Called to query Mongo for documents in a time range.
346073
def search(self, start_ts, end_ts):
        
        for meta_collection_name in self._meta_collections():
            meta_coll = self.meta_database[meta_collection_name]
            for ts_ns_doc in meta_coll.find(
                {"_ts": {"$lte": end_ts, "$gte": start_ts}}
            ):
                yield ts_ns_doc
104350
def from_mongo(cls, data, expired=False, **kw):
		""""""
		
		value = super(Expires, cls).from_mongo(data, **kw)
		
		if not expired and value.is_expired:
			return None
		
		return value
562781
def _set_item_querytime(self, item, type_check=True):
        
        if isinstance(item, Versionable):
            item._querytime = self.querytime
        elif isinstance(item, VersionedQuerySet):
            item.querytime = self.querytime
        else:
            if type_check:
                raise TypeError(
                    "This item is not a Versionable, it's a " + str(
                        type(item)))
        return item
654799
function querySearch (query) {
      var results = query ? self.states.filter(createFilterFor(query)) : self.states,
          deferred;
      if (self.simulateQuery) {
        deferred = $q.defer();
        $timeout(function () { deferred.resolve(results); }, Math.random() * 1000, false);
        return deferred.promise;
      } else {
        return results;
      }
    }
1171404
def query_recent(num=8, **kwargs):
        '''
        
        '''
        order_by_create = kwargs.get('order_by_create', False)
        kind = kwargs.get('kind', None)
        if order_by_create:
            if kind:
                recent_recs = TabPost.select().where(
                    (TabPost.kind == kind) & (TabPost.valid == 1)
                ).order_by(
                    TabPost.time_create.desc()
                ).limit(num)
            else:
                recent_recs = TabPost.select().where(
                    TabPost.valid == 1
                ).order_by(
                    TabPost.time_create.desc()
                ).limit(num)
        else:
            if kind:
                recent_recs = TabPost.select().where(
                    (TabPost.kind == kind) & (TabPost.valid == 1)
                ).order_by(
                    TabPost.time_update.desc()
                ).limit(num)
            else:
                recent_recs = TabPost.select().where(
                    TabPost.valid == 1
                ).order_by(
                    TabPost.time_update.desc()
                ).limit(num)
        return recent_recs
261290
def find_one(self, query):
        
        mongo_response = yield self.collection.find_one(query)
        raise Return(self._obj_cursor_to_dictionary(mongo_response))
1173593
def query(options, collection_name, num_to_skip, num_to_return,
          query, field_selector, opts, check_keys=False, ctx=None):
    """"""
    if ctx:
        return _query_compressed(options, collection_name, num_to_skip,
                                 num_to_return, query, field_selector,
                                 opts, check_keys, ctx)
    return _query_uncompressed(options, collection_name, num_to_skip,
                               num_to_return, query, field_selector, opts,
                               check_keys)
1032754
def _stream_search(self, query):
        """"""
        for doc in self.solr.search(query, rows=100000000):
            if self.unique_key != "_id":
                doc["_id"] = doc.pop(self.unique_key)
            yield doc
765311
def _query(options, collection_name, num_to_skip,
           num_to_return, query, field_selector, opts, check_keys):
    """"""
    encoded = _dict_to_bson(query, check_keys, opts)
    if field_selector:
        efs = _dict_to_bson(field_selector, False, opts)
    else:
        efs = b""
    max_bson_size = max(len(encoded), len(efs))
    return b"".join([
        _pack_int(options),
        _make_c_string(collection_name),
        _pack_int(num_to_skip),
        _pack_int(num_to_return),
        encoded,
        efs]), max_bson_size
530782
def query(self, **options):
        ''''''
        if not self._query_path:
            raise AttributeError('query is not available for %s' % self._item_name)
        last_item = 0
        offset = 0
        current_item = None
        limit = options.get('limit', 25)
        options['limit'] = limit
        target = self._query_path
        while True:
            options['offset'] = offset
            # go get the data with the given offset
            json_data = self._redmine.get(target, options)
            # Try and read the json
            try:
                data = json.loads(json_data)
            except:
                raise RedmineError(json_data)

            # The data is enclosed in the _query_container item
            # That is, {'issues':{(issue1),(issue2)...}, 'total_count':##}
            data_container = data[self._query_container]
            for item_data in data_container:
                yield(self._objectify(data=item_data))

            # If the container was empty, we requested past the end, just exit
            if not data_container:
                break
            try:
                if int(data['total_count']) > ( offset + len(data_container) ):
                    # moar data!
                    offset += limit
                else:
                    break
            except:
                # If we don't even have a 'total_count', we're done.
                break
1044689
def to_mongo(self, range_obj):
        
        if isinstance(range_obj, (pd.DatetimeIndex, tuple)):
            range_obj = DateRange(range_obj[0], range_obj[-1])
        if range_obj.start and range_obj.end:
            return {'$and': [{START: {'$lte': range_obj.end}}, {END: {'$gte': range_obj.start}}]}
        elif range_obj.start:
            return {END: {'$gte': range_obj.start}}
        elif range_obj.end:
            return {START: {'$lte': range_obj.end}}
        else:
            return {}
369328
def filter_by_moys(self, moys):
        
        _filt_values, _filt_datetimes = self._filter_by_moys_slow(moys)
        collection = HourlyDiscontinuousCollection(
            self.header.duplicate(), _filt_values, _filt_datetimes)
        collection._validated_a_period = self._validated_a_period
        return collection
190484
def query_dated(num=10, kind='1'):
        '''
        
        '''
        return TabWiki.select().where(
            TabWiki.kind == kind
        ).order_by(
            TabWiki.time_update.desc()
        ).limit(num)
1148054
def run_query(self, query):
        
        cursor = self.ds.filter(COLLECTION_UNIT_OF_WORK, query)
        return [UnitOfWork.from_json(document) for document in cursor]
290192
def query_by_assignment(self, assignment_id, end_time=None, start_time=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - assignment_id
        """ID"""
        path["assignment_id"] = assignment_id

        # OPTIONAL - start_time
        """The beginning of the time range from which you want events."""
        if start_time is not None:
            params["start_time"] = start_time

        # OPTIONAL - end_time
        """The end of the time range from which you want events."""
        if end_time is not None:
            params["end_time"] = end_time

        self.logger.debug("GET /api/v1/audit/grade_change/assignments/{assignment_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/audit/grade_change/assignments/{assignment_id}".format(**path), data=data, params=params, all_pages=True)
111182
function (clt_name, onSuccess, onFail, query_obj) {

	// error check
	var collection = l_getCollection(clt_name, onFail);
	if (collection === undefined) {
		return;
	}

	var is_empty = (query_obj === undefined ||
					l_isEmpty(query_obj));
	var query = {};

	// check if there's a specific query
	if (query_obj !== undefined) {
		query = query_obj;
	}

	// if not in cache, get data from DB and cache in memory
	//LOG.sys('data caching from [' + clt_name + '], query: ' + query + '...', 'SR.DB');

	try {

		// load all documents from the DB
		collection.findOne(query,
			function (err, data)
			{
				if (err) {
					return l_notifyError(clt_name, 'cacheData', err, onFail);
				}

				// something returned but is empty
				if (data === undefined ||
					data === null ||
					data === '') {

					LOG.warn('data not found for [' + clt_name + '] query: ' + JSON.stringify(query), 'SR.DB');
					return UTIL.safeCall(onSuccess, null);
				}

				// store all if is_empty, or store single object
				if (is_empty) {
					collection.cache = data;
					//LOG.sys('caching all objects...', 'SR.DB');
				} else {
					collection.cache[data._id] = data;
					//LOG.sys('caching single object, query: ' + query_obj, 'SR.DB');
				}

				//LOG.sys('returning data for id: ' + data._id, 'SR.DB');
				UTIL.safeCall(onSuccess, data);
			}
		);
	} catch (err) {
		l_notifyError(clt_name, 'cacheData.exception', err, onFail, true);
	}
}
515572
def search(self, pattern, start=None, limit=None, include_category=None):
        ''''''

        params = dict()

        if start is None:
            start = datetime.timedelta(days=30)

        if isinstance(start, datetime.timedelta):
            params['start'] = int(time.mktime((datetime.datetime.utcnow() - start).timetuple()) * 1000)
        elif isinstance(start, datetime.datetime):
            params['start'] = int(time.mktime(start.timetuple()) * 1000)
        else:
            raise Investigate.SEARCH_ERR

        if limit is not None and isinstance(limit, int):
            params['limit'] = limit
        if include_category is not None and isinstance(include_category, bool):
            params['includeCategory'] = str(include_category).lower()

        uri = self._uris['search'].format(quote_plus(pattern))

        return self.get_parse(uri, params)