Example list pagination.
429806
def list_example():
    
    from uuid import uuid4
    from redis import StrictRedis
    from zato.redis_paginator import ListPaginator
    
    conn = StrictRedis()
    key = 'paginator:{}'.format(uuid4().hex)
    
    for x in range(1, 18):
        conn.rpush(key, x)
        
    p = ListPaginator(conn, key, 6)
    
    print(p.count)      # 17
    print(p.num_pages)  # 3
    print(p.page_range) # [1, 2, 3]
    
    page = p.page(3)
    print(page)             # <Page 3 of 3>
    print(page.object_list) # ['13', '14', '15', '16', '17']
        
    conn.delete(key)
1019400
def items_iter(self, limit):
        '''
        '''

        pages = (page.get() for page in self._pages())
        items = itertools.chain.from_iterable(
            (p[self.ITEM_KEY] for p in pages)
        )
        if limit is not None:
            items = itertools.islice(items, limit)
        return items
963638
def listEverything(matching=False):
    
    pages=pageNames()
    if matching:
        pages=[x for x in pages if matching in x]
    for i,page in enumerate(pages):
        pages[i]="%s%s (%s)"%(pageFolder(page),page,getPageType(page))
    print("\n".join(sorted(pages)))
9274
def search_list(kb, from_=None, match_type=None,
                    page=None, per_page=None, unique=False):
        """"""
        # init
        page = page or 1
        per_page = per_page or 10

        if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']:
            # get the base query
            query = api.query_kb_mappings(
                kbid=kb.id,
                key=from_ or '',
                match_type=match_type or 's'
            ).with_entities(models.KnwKBRVAL.m_key)
            # if you want a 'unique' list
            if unique:
                query = query.distinct()
            # run query and paginate
            return [item.m_key for item in
                    pagination.RestfulSQLAlchemyPagination(
                        query, page=page or 1,
                        per_page=per_page or 10
                    ).items]
        return []
726406
def next(self, error_out=False):
        """"""
        assert self.query is not None, 'a query object is required ' \
                                       'for this method to work'
        return self.query.paginate(self.page + 1, self.per_page, error_out)
851101
def paginate(self, page=1, perpage=10, category=None):
        """"""
        q = db.select(self.table).fields('title', 'slug', 'description', 'html', 'css', 'js',
                                         'category', 'status', 'comments', 'author', 'created', 'pid')
        if category:
            q.condition('category', category)
        results = (q.limit(perpage).offset((page - 1) * perpage)
                    .order_by('created', 'DESC').execute())
        return [self.load(data, self.model) for data in results]
525343
def admin_docker_list_view(context, request):
    """"""
    return {
        'paginator': Page(
            context.all,
            url_maker=lambda p: request.path_url + "?page=%s" % p,
            page=int(request.params.get('page', 1)),
            items_per_page=6
        )
    }
577263
def list(self,header,choices):
        ""

        if not self.__list_window:
            (y,x)=self.__main.getmaxyx()
            self.__list_window = self.__main.subwin(35,x,0,0)
            
        _lw=self.__list_window


        _lw.keypad(1)
        (y_max,x_max)=_lw.getmaxyx()
        (y_0, x_0)=_lw.getbegyx()
        x_start=1+x_0
        _lw.box()
        ## Number of list items allowed.
        ### first entry in the list appears at page_top
        page_top=y_0+2
        ### the last entry display will be at page_bottom
        page_bottom = y_max-2

        ### break the list into chunks.
        max_items_per_page = page_bottom-page_top

        ### start at the top of the list
        top_item=0
        f=open('log.msg','w')
        first_item=page_top
        current_item=0
        item_list=[]
        while 1:
            _lw.erase()
            _lw.box()
            _lw.addstr(page_top-1,x_start,header)
            if top_item > len(choices):
                top_item=0
            for i in range(max_items_per_page):
                item=i+top_item
                if not item in range(len(choices)):
                    break
                _lw.addstr(i+page_top,x_start,choices[item])
            ### provide a hint that there is more info in the list
            ### setup where we are in the list
            last_item=item
            if top_item > 0 :
                _lw.addstr(page_bottom,x_start,"P(revious)")
            if last_item < len(choices):
                _lw.addstr(page_bottom,x_max-8,"N(ext)")
            while 1:
                c=_lw.getch(current_item-top_item+page_top,x_start)
                if c==curses.KEY_UP:
                    current_item=current_item-1
                elif c==curses.KEY_DOWN:
                    current_item=current_item+1
                elif c==ord(' '):
                    if current_item in item_list:
                        _lw.addstr(choices[current_item])
                        item_list.remove(current_item)
                    else:
                        _lw.addstr(choices[current_item],curses.A_REVERSE)
                        item_list.append(current_item)
                elif c==ord('P'):
                    top_item=top_item-max_items_per_page
                    current_item=top_item
                    break
                elif c==ord('N'):
                    top_item=top_item + max_items_per_page
                    current_item=top_item
                    break
                elif c==10:
                    return(item_list)
                elif c==ord('q'):
                    _lw.erase()
                    return(None)
		elif c==ord('x'):
		    choices[current_item]=choices[current_item][:4]+" "+choices[current_item][5:]
                    _lw.addstr(choices[current_item])
		else:
		    choices[current_item]=choices[current_item][:7]+chr(c).capitalize()+choices[current_item][8:]
                    _lw.addstr(choices[current_item])

                if current_item > last_item-1:
                    if last_item < len(choices):
                        top_item = top_item+1
                        break
                    else:
                        current_item=current_item-1
                if current_item < top_item :
                    if top_item > 0:
                        top_item = top_item-1
                        break
                    else:
                        current_item=current_item+1
740422
def paginate_announcements_list(request, context, items):
    

    # pagination
    if "start" in request.GET:
        try:
            start_num = int(request.GET.get("start"))
        except ValueError:
            start_num = 0
    else:
        start_num = 0

    display_num = 10
    end_num = start_num + display_num
    prev_page = start_num - display_num
    more_items = ((len(items) - start_num) > display_num)
    try:
        items_sorted = items[start_num:end_num]
    except (ValueError, AssertionError):
        items_sorted = items[:display_num]
    else:
        items = items_sorted

    context.update({
        "items": items,
        "start_num": start_num,
        "end_num": end_num,
        "prev_page": prev_page,
        "more_items": more_items,
    })

    return context, items
73142
def expand_pagination(pages):
    """"""
    # If there is no hyphen, it's a single page, and we're good to go
    parts = pages.split('-')
    if len(parts) == 1: # No hyphen, so no split
        return pages
    elif len(parts) == 2:
        start = parts[0]
        end = parts[1]
        # If the end is the same number of digits as the start, then we
        # don't change anything!
        if len(start) == len(end):
            return pages
        # Otherwise, replace the last digits of start with the digits of end
        num_end_digits = len(end)
        new_end = start[:-num_end_digits] + end
        return '%s-%s' % (start, new_end)
    else: # More than one hyphen, something weird happened
        logger.warning("Multiple hyphens in page number: %s" % pages)
        return pages
1139608
def rows(self):
        """"""

        return map(
            lambda o: self._meta.row_class(self, o),
            self.paginator.page(self._meta.page).object_list )
760088
def _paginate(url, topkey, *args, **kwargs):
    '''
    
    '''

    ret = salt.utils.http.query(url, **kwargs)
    if 'errors' in ret['dict']:
        return ret['dict']

    lim = int(ret['dict']['page']['limit'])
    total = int(ret['dict']['page']['total'])

    if total == 0:
        return {}

    numpages = (total / lim) + 1

    # If the count returned is less than the page size, just return the dict
    if numpages == 1:
        return ret['dict'][topkey]

    aggregate_ret = ret['dict'][topkey]
    url = args[0]
    for p in range(2, numpages):
        param_url = url + '?offset={0}'.format(lim * (p - 1))
        next_ret = salt.utils.http.query(param_url, kwargs)
        aggregate_ret[topkey].extend(next_ret['dict'][topkey])

    return aggregate_ret
468239
def list_containers(self, page_size=None):
        
        params = {}

        if page_size is not None:
            params['limit'] = page_size

        return pagination.Iterator(
            client=self._client,
            path='/mdb/{}/containers'.format(self._instance),
            params=params,
            response_class=mdb_pb2.ListContainersResponse,
            items_key='container',
            item_mapper=Container,
        )
307845
function createPagination(req) {
  return function createPagination(pages, page, liClass, anchorClass) {
    var params = qs.parse(url.parse(req.url).query);
    var str = '';

    params.page = 1;
    var clas = (page == 1 && 'active') || '';

    for (var p = 1; p <= pages; p++) {
      params.page = p;
      clas = (page == p && 'active') || '';

      var href = '?' + qs.stringify(params);

      str += `<li class="${liClass} ${clas}"><a class="${anchorClass}" href="${href}">${p}</a></li>`;
    }

    return str;
  };
}
227737
def items(self):
        
        if self._multipage:
            while True:
                # Pool for more torrents
                items = super(Paginated, self).items()
                # Stop if no more torrents
                first = next(items, None)
                if first is None:
                    raise StopIteration()
                # Yield them if not
                else:
                    yield first
                    for item in items:
                        yield item
                # Go to the next page
                self.next()
        else:
            for item in super(Paginated, self).items():
                yield item
453284
public static <T> List<T> subList(final List<T> list, int pageSize, int page) {

		if (pageSize <= 0 || page == 0) {

			return Collections.EMPTY_LIST;
		}

		int size        = list.size();

		int fromIndex   = page > 0
		     ? (page - 1) * pageSize
		     : size + (page * pageSize);

		int toIndex = fromIndex + pageSize;

		int finalFromIndex = Math.max(0, fromIndex);
		int finalToIndex   =  Math.min(size, Math.max(0, toIndex));

		// prevent fromIndex to be greater than toIndex
		if (finalFromIndex > finalToIndex) {
			finalFromIndex = finalToIndex;
		}

		try {
			return list.subList(finalFromIndex, finalToIndex);

		} catch (Throwable t) {

			logger.warn("Invalid range for sublist in paging, pageSize {}, page {}: {}", new Object[] {
				pageSize,
				page,
				t.getMessage()
			});
		}

		return Collections.EMPTY_LIST;

	}
69933
def paging
      page = 0
      results = []
      loop do
        page += 1
        current = yield(page)

        results += current

        break if (current || []).count < page_size # no more results
      end

      return results
    end