Retrieves the limit of historical revisions to store for any single
        document in the current remote database.

        :returns: Revision limit value for the current remote database
547366
def get_revision_limit(self):
        
        url = '/'.join((self.database_url, '_revs_limit'))
        resp = self.r_session.get(url)
        resp.raise_for_status()

        try:
            ret = int(resp.text)
        except ValueError:
            raise CloudantDatabaseException(400, response_to_json_dict(resp))

        return ret
187802
def recheck_limits(self):
        

        limit_data = self.control_daemon.get_limits()

        try:
            # Get the new checksum and list of limits
            new_sum, new_limits = limit_data.get_limits(self.limit_sum)

            # Convert the limits list into a list of objects
            lims = database.limits_hydrate(self.db, new_limits)

            # Save the new data
            self.limits = lims
            self.limit_map = dict((lim.uuid, lim) for lim in lims)
            self.limit_sum = new_sum
        except control.NoChangeException:
            # No changes to process; just keep going...
            return
        except Exception:
            # Log an error
            LOG.exception("Could not load limits")

            # Get our error set and publish channel
            control_args = self.conf['control']
            error_key = control_args.get('errors_key', 'errors')
            error_channel = control_args.get('errors_channel', 'errors')

            # Get an informative message
            msg = "Failed to load limits: " + traceback.format_exc()

            # Store the message into the error set.  We use a set
            # here because it's likely that more than one node
            # will generate the same message if there is an error,
            # and this avoids an explosion in the size of the set.
            with utils.ignore_except():
                self.db.sadd(error_key, msg)

            # Publish the message to a channel
            with utils.ignore_except():
                self.db.publish(error_channel, msg)
1001324
def ratelimit_remaining(self):
        
        json = self._json(self._get(self._github_url + '/rate_limit'), 200)
        core = json.get('resources', {}).get('core', {})
        self._remaining = core.get('remaining', 0)
        return self._remaining
437241
def update(self):
        

        with self.lock:
            # Increment revision and commit it.
            self.revision += 1
            self.server.commit(self.revision + 1)

            # Unblock all waiting clients.
            self.next_revision_available.set()
            self.next_revision_available.clear()

            # Check sessions to see which revision can be removed.
            if self.sessions:
                lowest_revision = min(
                    session.revision for session in self.sessions.itervalues())

                # Remove all old revision history
                if lowest_revision == self.revision:
                    self.server.clean(lowest_revision)

        # Invoke hooks
        invoke_hooks(self.hooks, "updated", self.revision)
530534
def list(self, toa=None, show_history=False):
        
        if not toa:
            toa = time.mktime(datetime.datetime.now().timetuple())

        query = {
            "$query": {
                "master_id": self.master_id,
                "processed": show_history,
                "toa" : {"$lte" : toa}
            },
            "$orderby": {
                "toa": 1
            }
        }

        revisions = yield self.revisions.find(query)

        raise Return(revisions)
231010
def fetch_all_data(self, limit=50000):
        
        # Query text
        query = text(
            """
            SELECT domain, entity_id, state, last_changed
            FROM states
            WHERE
                state NOT IN ('unknown', 'unavailable')
            ORDER BY last_changed DESC
            LIMIT :limit
            """
        )

        try:
            print("Querying the database, this could take a while")
            response = self.perform_query(query, limit=limit)
            master_df = pd.DataFrame(response.fetchall())
            print("master_df created successfully.")
            self._master_df = master_df.copy()
            self.parse_all_data()
        except:
            raise ValueError("Error querying the database.")
282676
def _retrieve_revisions(self):
        """"""
        response = self._swimlane.request(
            'get',
            'history',
            params={
                'type': 'Records',
                'id': self._record.id
            }
        )

        raw_revisions = response.json()

        return [Revision(self._record, raw) for raw in raw_revisions]
123832
def get_rate_limits(self):
        
        resp, body = self.method_get("/limits")
        rate_limits = body.get("limits", {}).get("rate")
        ret = []
        for rate_limit in rate_limits:
            limits = rate_limit["limit"]
            uri_limits = {"uri": rate_limit["uri"],
                    "limits": limits}
            ret.append(uri_limits)
        return ret
997415
def current_revision(self, r_stmts):
        
        cur = max([[int(p) for p in r.arg.split("-")] for r in r_stmts])
        return "%4d-%02d-%02d" % tuple(cur)
1327338
def restore_revision!(id, revision_number)
      record = restore_revision(id, revision_number)
      if record
        record.store_revision do
          save_restorable_associations(record, revisionable_associations)
        end
      end
      return record
    end
56235
def recheck_limits(self):
        

        limit_data = self.control_daemon.get_limits()

        try:
            # Get the new checksum and list of limits
            new_sum, new_limits = limit_data.get_limits(self.limit_sum)

            # Convert the limits list into a list of objects
            lims = database.limits_hydrate(self.db, new_limits)

            # Build a new mapper
            mapper = routes.Mapper(register=False)
            for lim in lims:
                lim._route(mapper)

            # Save the new data
            self.limits = lims
            self.limit_sum = new_sum
            self.mapper = mapper
        except control.NoChangeException:
            # No changes to process; just keep going...
            return
        except Exception:
            # Log an error
            LOG.exception("Could not load limits")

            # Get our error set and publish channel
            control_args = self.conf['control']
            error_key = control_args.get('errors_key', 'errors')
            error_channel = control_args.get('errors_channel', 'errors')

            # Get an informative message
            msg = "Failed to load limits: " + traceback.format_exc()

            # Store the message into the error set.  We use a set
            # here because it's likely that more than one node
            # will generate the same message if there is an error,
            # and this avoids an explosion in the size of the set.
            with utils.ignore_except():
                self.db.sadd(error_key, msg)

            # Publish the message to a channel
            with utils.ignore_except():
                self.db.publish(error_channel, msg)
746890
def filename(self):
        
        filename = self.key

        if self.has_revision_file() and self.history.current_revision:
            filename += "-"
            filename += self.history.current_revision.revision_id

        filename += ".zip"

        return filename
90589
def __get_pending_revisions(self):
        
        dttime = time.mktime(datetime.datetime.now().timetuple())
        changes = yield self.revisions.find({
            "toa" : {
                "$lt" : dttime,
            },
            "processed": False,
            "inProcess": None
        })
        if len(changes) > 0:
            yield self.set_all_revisions_to_in_process([change.get("id") for change in changes])

        raise Return(changes)
1314918
def content(self):
    '''
    
    '''

    if not getattr(self, '_content', False):
      query_params = {
        'prop': 'extracts|revisions',
        'explaintext': '',
        'rvprop': 'ids'
      }
      if not getattr(self, 'title', None) is None:
         query_params['titles'] = self.title
      else:
         query_params['pageids'] = self.pageid
      request = _wiki_request(query_params)
      self._content     = request['query']['pages'][self.pageid]['extract']
      self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid']
      self._parent_id   = request['query']['pages'][self.pageid]['revisions'][0]['parentid']

    return self._content
590168
def get_current_revision(
        database_url: str,
        version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
    
    engine = create_engine(database_url)
    conn = engine.connect()
    opts = {'version_table': version_table}
    mig_context = MigrationContext.configure(conn, opts=opts)
    return mig_context.get_current_revision()
1135717
@InterfaceAudience.Private
    public void pullRemoteRevision(final RevisionInternal rev) {

        Log.d(TAG, "%s: pullRemoteRevision with rev: %s", this, rev);

        ++httpConnectionCount;

        // Construct a query. We want the revision history, and the bodies of attachments that have
        // been added since the latest revisions we have locally.
        // See: http://wiki.apache.org/couchdb/HTTP_Document_API#Getting_Attachments_With_a_Document
        StringBuilder path = new StringBuilder(encodeDocumentId(rev.getDocID()));
        path.append("?rev=").append(URIUtils.encode(rev.getRevID()));
        path.append("&revs=true");

        // TODO: CBL Java does not have implementation of _settings yet. Till then, attachments always true
        boolean attachments = true;
        if (attachments)
            path.append("&attachments=true");

        // Include atts_since with a list of possible ancestor revisions of rev. If getting attachments,
        // this allows the server to skip the bodies of attachments that have not changed since the
        // local ancestor. The server can also trim the revision history it returns, to not extend past
        // the local ancestor (not implemented yet in SG but will be soon.)
        AtomicBoolean haveBodies = new AtomicBoolean(false);
        List<String> possibleAncestors = null;
        possibleAncestors = db.getPossibleAncestorRevisionIDs(rev,
                PullerInternal.MAX_NUMBER_OF_ATTS_SINCE, attachments ? haveBodies : null, true);
        if (possibleAncestors != null) {
            path.append(haveBodies.get() ? "&atts_since=" : "&revs_from=");
            path.append(joinQuotedEscaped(possibleAncestors));
        } else {
            int maxRevTreeDepth = getLocalDatabase().getMaxRevTreeDepth();
            if (rev.getGeneration() > maxRevTreeDepth) {
                path.append("&revs_limit=");
                path.append(maxRevTreeDepth);
            }
        }

        //create a final version of this variable for the log statement inside
        //FIXME find a way to avoid this
        final String pathInside = path.toString();
        CustomFuture future = sendAsyncMultipartDownloaderRequest("GET", pathInside,
                null, db, new RemoteRequestCompletion() {

                    @Override
                    public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
                        if (e != null) {
                            Log.w(TAG, "Error pulling remote revision: %s", e, this);
                            if (Utils.isDocumentError(e)) {
                                // Revision is missing or not accessible:
                                revisionFailed(rev, e);
                            } else {
                                // Request failed:
                                setError(e);
                            }
                        } else {

                            Map<String, Object> properties = (Map<String, Object>) result;
                            long size = 0;
                            if (httpResponse != null && httpResponse.body() != null)
                                size = httpResponse.body().contentLength();
                            PulledRevision gotRev = new PulledRevision(properties, size);
                            gotRev.setSequence(rev.getSequence());

                            Log.d(TAG, "%s: pullRemoteRevision add rev: %s to batcher: %s",
                                    PullerInternal.this, gotRev, downloadsToInsert);

                            // NOTE: should not/not necessary to call Body.compact()
                            // new PulledRevision(Map<string, Object>) creates Body instance only
                            // with `object`. Serializing object to json causes two unnecessary
                            // JSON serializations.

                            if (gotRev.getBody() != null)
                                queuedMemorySize.addAndGet(gotRev.getBody().getSize());

                            // Add to batcher ... eventually it will be fed to -insertRevisions:.
                            downloadsToInsert.queueObject(gotRev);

                            // if queue memory size is more than maximum, force flush the queue.
                            if (queuedMemorySize.get() > MAX_QUEUE_MEMORY_SIZE) {
                                Log.d(TAG, "Flushing  queued memory size at: " + queuedMemorySize);
                                downloadsToInsert.flushAllAndWait();
                            }
                        }

                        // Note that we've finished this task:
                        --httpConnectionCount;

                        // Start another task if there are still revisions waiting to be pulled:
                        pullRemoteRevisions();
                    }
                });
        future.setQueue(pendingFutures);
        pendingFutures.add(future);
    }
628211
def limit(self, limit: int) -> "QuerySet":
        
        queryset = self._clone()
        queryset._limit = limit
        return queryset