Get organization activity, handle pagination
359348
def _fetch_activities(self):
        
        activities = []
        # Prepare url of the first page
        url = '{0}/organizations/{1}/activity/'.format(
            self.url, self.organization)
        while url:
            # Fetch one page of activities
            try:
                log.debug('Fetching activity data: {0}'.format(url))
                response = requests.get(url, headers=self.headers)
                if not response.ok:
                    log.error(response.text)
                    raise ReportError('Failed to fetch Sentry activities.')
                data = response.json()
                log.data("Response headers:\n{0}".format(
                    pretty(response.headers)))
                log.debug("Fetched {0}.".format(listed(len(data), 'activity')))
                log.data(pretty(data))
                for activity in [Activity(item) for item in data]:
                    # We've reached the last page, older records not relevant
                    if activity.created < self.stats.options.since.date:
                        return activities
                    # Store only relevant activites (before until date)
                    if activity.created < self.stats.options.until.date:
                        log.details("Activity: {0}".format(activity))
                        activities.append(activity)
            except requests.RequestException as error:
                log.debug(error)
                raise ReportError(
                    'Failed to fetch Sentry activities from {0}'.format(url))
            # Check for possible next page
            try:
                url = NEXT_PAGE.search(response.headers['Link']).groups()[0]
            except AttributeError:
                url = None
        return activities
984736
def paginate(self, request, collection):
        
        p = Paginator(request, self, collection)
        return p.paginator and p or UpdatedList(collection)
1191192
def query_all_pageview(current_page_num=1):
        '''
        
        '''
        return TabLog.select().distinct(TabLog.current_url).order_by(TabLog.current_url).paginate(
            current_page_num, CMS_CFG['list_num']
        )
1099185
function pagedGet ({source, method, skip = 0, aggregatedResponse = null, query = null}) {
  const fullQuery = Object.assign({},
    {
      skip: skip,
      limit: pageLimit,
      order: 'sys.createdAt,sys.id'
    },
    query
  )

  return source[method](fullQuery)
    .then((response) => {
      if (!aggregatedResponse) {
        aggregatedResponse = response
      } else {
        aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
      }
      const page = Math.ceil(skip / pageLimit) + 1
      const pages = Math.ceil(response.total / pageLimit)
      logEmitter.emit('info', `Fetched ${aggregatedResponse.items.length} of ${response.total} items (Page ${page}/${pages})`)
      if (skip + pageLimit <= response.total) {
        return pagedGet({source, method, skip: skip + pageLimit, aggregatedResponse, query})
      }
      return aggregatedResponse
    })
}
712472
def get_events(params = nil, paging = nil)
      response = @client.get(construct_url(paging), params)
      extract_paging(response)
      response
    end
266541
public function listAction()
    {
        $params     = $this->params();
        $request    = $this->getRequest();
        $bodyOnly   = $request->isXmlHttpRequest();
        $page       = $params->fromRoute( 'page',
            $request->getPost( 'page',
                $request->getQuery( 'page', 1 )
            )
        );

        $view = new ViewModel( array(
            'paginator' => $this->getPaginator(),
            'page'      => ( (int) $page ) ?: 1,
            'format'    => $bodyOnly,
        ) );

        if ( $bodyOnly )
        {
            $view->setTerminal( true );
        }

        return $view;
    }
999337
def _entity_paginator(namespace, workspace, etype, page_size=500,
                            filter_terms=None, sort_direction="asc"):
    

    page = 1
    all_entities = []
    # Make initial request
    r = fapi.get_entities_query(namespace, workspace, etype, page=page,
                           page_size=page_size, sort_direction=sort_direction,
                           filter_terms=filter_terms)
    fapi._check_response_code(r, 200)

    response_body = r.json()
    # Get the total number of pages
    total_pages = response_body['resultMetadata']['filteredPageCount']

    # append the first set of results
    entities = response_body['results']
    all_entities.extend(entities)
    # Now iterate over remaining pages to retrieve all the results
    page = 2
    while page <= total_pages:
        r = fapi.get_entities_query(namespace, workspace, etype, page=page,
                               page_size=page_size, sort_direction=sort_direction,
                               filter_terms=filter_terms)
        fapi._check_response_code(r, 200)
        entities = r.json()['results']
        all_entities.extend(entities)
        page += 1

    return all_entities
781654
def get_current_orga(request, hproject, availableOrga):
    """"""

    # If nothing available return 404
    if len(availableOrga) == 0:
        raise Http404

    # Find the current orga
    currentOrgaId = request.session.get('plugit-orgapk-' + str(hproject.pk), None)

    # If we don't have a current one select the first available
    if currentOrgaId is None:
        (tmpOrga, _) = availableOrga[0]
        currentOrgaId = tmpOrga.pk
    else:
        # If the current Orga is not among the available ones reset to the first one
        availableOrgaIds = [o.pk for (o, r) in availableOrga]
        if currentOrgaId not in availableOrgaIds:
            (tmpOrga, _) = availableOrga[0]
            currentOrgaId = tmpOrga.pk

    from organizations.models import Organization

    realCurrentOrga = get_object_or_404(Organization, pk=currentOrgaId)

    return realCurrentOrga
800667
public function get(Pagination $pagination = null, $resource_id = null, $event = null)
    {
        $params = [];

        if (!is_null($resource_id)) {
            $params['resourceId'] = $resource_id;
        }

        if (!is_null($event)) {
            $params['event'] = $event;
        }

        return $this->getByPath($this->generateListPath($pagination, null, $params));
    }
837155
def get_user_paginator(
        cls,
        instance,
        page=1,
        item_count=None,
        items_per_page=50,
        user_ids=None,
        GET_params=None,
    ):
        
        if not GET_params:
            GET_params = {}
        GET_params.pop("page", None)
        query = instance.users_dynamic
        if user_ids:
            query = query.filter(cls.models_proxy.UserGroup.user_id.in_(user_ids))
        return SqlalchemyOrmPage(
            query,
            page=page,
            item_count=item_count,
            items_per_page=items_per_page,
            **GET_params
        )
763301
def paginate(self):
        """"""

        project_dir = self.project_dir
        raw_dir = self.raw_dir
        batch_dir = self.batch_dir

        if project_dir is None:
            raise UnderDefined("no project directory defined")
        if raw_dir is None:
            raise UnderDefined("no raw directory defined")
        if batch_dir is None:
            raise UnderDefined("no batcb directory defined")

        # create the folders
        if not os.path.isdir(project_dir):
            os.mkdir(project_dir)
            logging.info(f"created folder {project_dir}")
        if not os.path.isdir(batch_dir):
            os.mkdir(batch_dir)
            logging.info(f"created folder {batch_dir}")
        if not os.path.isdir(raw_dir):
            os.mkdir(raw_dir)
            logging.info(f"created folder {raw_dir}")

        return project_dir, batch_dir, raw_dir
1002339
def paginate(self, request, offset=0, limit=None):
        """"""
        return self.collection.offset(offset).limit(limit), self.collection.count()
432702
def activities_list(self, since=None, **kwargs):
        ""
        api_path = "/api/v2/activities.json"
        api_query = {}
        if "query" in kwargs.keys():
            api_query.update(kwargs["query"])
            del kwargs["query"]
        if since:
            api_query.update({
                "since": since,
            })
        return self.call(api_path, query=api_query, **kwargs)
529001
def __get_activities(self, search):
        """"""

        query = """
                   SELECT a.name AS name, b.name AS category
                     FROM activities a
                LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id
                LEFT JOIN facts f ON a.id = f.activity_id
                    WHERE deleted IS NULL
                      AND a.search_name LIKE ? ESCAPE '\\'
                 GROUP BY a.id
                 ORDER BY max(f.start_time) DESC, lower(a.name)
                    LIMIT 50
        """
        search = search.lower()
        search = search.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
        activities = self.fetchall(query, ('%s%%' % search, ))

        return activities
1254589
def pagination_for(context, current_page, page_var="page", exclude_vars=""):
    
    querystring = context["request"].GET.copy()
    exclude_vars = [v for v in exclude_vars.split(",") if v] + [page_var]
    for exclude_var in exclude_vars:
        if exclude_var in querystring:
            del querystring[exclude_var]
    querystring = querystring.urlencode()
    return {
        "current_page": current_page,
        "querystring": querystring,
        "page_var": page_var,
    }
1157595
def get_iterator(self, query, **options):
        """"""
        return EventsPageIterator(self.client, '/events', query, options).items()
767539
def get_organization(self, **kwargs):
        
        resp = self._get(self._u(self._ORGANIZATION_ENDPOINT_SUFFIX),
                         **kwargs)
        resp.raise_for_status()
        return resp.json()