Auto cached queryset and generate results.
188554
def cached_query(qs, timeout=None):
    
    cache_key = generate_cache_key(qs)
    return get_cached(cache_key, list, args=(qs,), timeout=None)
1040839
def cache_results(&block)
        return yield unless template_cache_configured? && defined?(@_cache_key)

        if cache_read_on_render?
          fetch_result_from_cache(cache_key, @_cache_options, &block)
        else
          write_result_to_cache(cache_key, @_cache_options, &block)
        end
      end
703355
private void updateCache(int index, QueryParameters params) {
        if (generatedCacheMap.containsKey(index) == true) {
            this.generatedCacheMap.put(index, params);
        } else {
            this.resultSetCacheMap.put(index, params);
        }
    }
548422
def generate_cache(self, resources=None, underlined=None,
                       task_handle=taskhandle.NullTaskHandle()):
        
        if resources is None:
            resources = self.project.get_python_files()
        job_set = task_handle.create_jobset(
            'Generatig autoimport cache', len(resources))
        for file in resources:
            job_set.started_job('Working on <%s>' % file.path)
            self.update_resource(file, underlined)
            job_set.finished_job()
434409
def _build_cache():
    """"""
    sets = current_oaiserver.sets
    if sets is None:
        # build sets cache
        sets = current_oaiserver.sets = [
            oaiset.spec for oaiset in OAISet.query.filter(
                OAISet.search_pattern.is_(None)).all()]
    return sets
196313
def _prepare_results(self, results):
        
        if self._instances:
            results = self._to_instances(results)
        else:
            results = list(results)

        # cache the len for future use
        self._len = len(results)

        return results
338954
def cache_all(self):
        """"""

        respond = input(
              'By default, cppman fetches pages on-the-fly if corresponding '
              'page is not found in the cache. The "cache-all" option is only '
              'useful if you want to view man pages offline. '
              'Caching all contents will take several minutes, '
              'do you want to continue [y/N]? ')
        if not (respond and 'yes'.startswith(respond.lower())):
            raise KeyboardInterrupt

        try:
            os.makedirs(environ.cache_dir)
        except:
            pass

        self.success_count = 0
        self.failure_count = 0

        if not os.path.exists(environ.index_db):
            raise RuntimeError("can't find index.db")

        conn = sqlite3.connect(environ.index_db)
        cursor = conn.cursor()

        source = environ.config.source
        print('Caching manpages from %s ...' % source)
        data = cursor.execute('SELECT * FROM "%s"' % source).fetchall()

        for name, url, _ in data:
            print('Caching %s ...' % name)
            retries = 3
            while retries > 0:
                try:
                    self.cache_man_page(source, url, name)
                except Exception:
                    print('Retrying ...')
                    retries -= 1
                else:
                    self.success_count += 1
                    break
            else:
                print('Error caching %s ...' % name)
                self.failure_count += 1

        conn.close()

        print('\n%d manual pages cached successfully.' % self.success_count)
        print('%d manual pages failed to cache.' % self.failure_count)
        self.update_mandb(False)
494980
def items(self, query=None, **kwargs):
        
        # Cut this, we don't need no empty query
        if not query:
            self.__final_queryset = self.get_model().objects.none()
            return self.serialize(self.__final_queryset)
        # Query is too short, no item
        if len(query) < self.get_query_size_min():
            self.__final_queryset = self.get_model().objects.none()
            return self.serialize(self.__final_queryset)

        if self.requires_authentication:
            if not self.user:
                raise AuthenticationRequiredAgnocompleteException(
                    "Authentication is required to use this autocomplete"
                )
            if not self.user.is_authenticated:
                raise AuthenticationRequiredAgnocompleteException(
                    "Authentication is required to use this autocomplete"
                )

        qs = self.build_filtered_queryset(query, **kwargs)
        # The final queryset is the paginated queryset
        self.__final_queryset = qs
        return self.serialize(qs)
1312642
function loadUncached () {
    // execute original query
    return this.query.executeQuery()
    // cache result
    .then(results => {
        // cache results if there are any
        if (results.length > 0) {
            // cache results - do not wait to complete
            this.cacheResults(results)
        }
        // resolve with results
        return results
    })
}
1278847
def process(self, data):
        
        for res in data:
            try:
                cache.dbapi().save(res)
            except Exception:
                LOG.exception('failed to cache result: %s', res.status)
359705
def cached_get(timeout, *params):
    """"""

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(view_or_request, *args, **kwargs):

            # The type of the request gets muddled when using a function based
            # decorator. We must use a function based decorator so it can be
            # used in urls.py.
            request = getattr(view_or_request, "request", view_or_request)

            if not hasattr(_thread_locals, "ultracache_request"):
                setattr(_thread_locals, "ultracache_request", request)

            # If request not GET or HEAD never cache
            if request.method.lower() not in ("get", "head"):
                return view_func(view_or_request, *args, **kwargs)

            # If request contains messages never cache
            l = 0
            try:
                l = len(request._messages)
            except (AttributeError, TypeError):
                pass
            if l:
                return view_func(view_or_request, *args, **kwargs)

            # Compute a cache key
            li = [str(view_or_request.__class__), view_func.__name__]

            # request.get_full_path is implicitly added it no other request
            # path is provided. get_full_path includes the querystring and is
            # the more conservative approach but makes it trivially easy for a
            # request to bust through the cache.
            if not set(params).intersection(set((
                "request.get_full_path()", "request.path", "request.path_info"
            ))):
                li.append(request.get_full_path())

            if "django.contrib.sites" in settings.INSTALLED_APPS:
                li.append(get_current_site_pk(request))

            # Pre-sort kwargs
            keys = list(kwargs.keys())
            keys.sort()
            for key in keys:
                li.append("%s,%s" % (key, kwargs[key]))

            # Extend cache key with custom variables
            for param in params:
                if not isinstance(param, str):
                    param = str(param)
                li.append(eval(param))

            s = ":".join([str(l) for l in li])
            hashed = hashlib.md5(s.encode("utf-8")).hexdigest()
            cache_key = "ucache-get-%s" % hashed
            cached = cache.get(cache_key, None)
            if cached is None:
                # The get view as outermost caller may bluntly set _ultracache
                request._ultracache = []
                response = view_func(view_or_request, *args, **kwargs)
                content = None
                if isinstance(response, TemplateResponse):
                    content = response.render().rendered_content
                elif isinstance(response, HttpResponse):
                    content = response.content
                if content is not None:
                    headers = getattr(response, "_headers", {})
                    cache.set(
                        cache_key,
                        {"content": content, "headers": headers},
                        timeout
                    )
                    cache_meta(request, cache_key)
            else:
                response = HttpResponse(cached["content"])
                # Headers has a non-obvious format
                for k, v in cached["headers"].items():
                    response[v[0]] = v[1]

            return response

        return _wrapped_view
    return decorator
600672
def put_cache_results(self, key, func_akw, set_cache_cb):
        """"""
        args, kwargs = func_akw

        # get function results
        func_results = self.func(*args, **kwargs)

        # optionally add results to cache
        if set_cache_cb(func_results):
            self[key] = func_results
        return func_results
1179902
def queryset(self, request):
        """"""
        query_set = self.model._default_manager.all_with_deleted()
        ordering = self.ordering or ()
        if ordering:
            query_set = query_set.order_by(*ordering)
        return query_set
758946
def _build_requested_prefetches(
        self,
        prefetches,
        requirements,
        model,
        fields,
        filters
    ):
        """"""

        for name, field in six.iteritems(fields):
            original_field = field
            if isinstance(field, DynamicRelationField):
                field = field.serializer
            if isinstance(field, serializers.ListSerializer):
                field = field.child
            if not isinstance(field, serializers.ModelSerializer):
                continue

            source = field.source or name
            if '.' in source:
                raise ValidationError(
                    'nested relationship values '
                    'are not supported'
                )

            if source in prefetches:
                # ignore duplicated sources
                continue

            is_remote = is_field_remote(model, source)
            is_id_only = getattr(field, 'id_only', lambda: False)()
            if is_id_only and not is_remote:
                continue

            related_queryset = getattr(original_field, 'queryset', None)

            if callable(related_queryset):
                related_queryset = related_queryset(field)

            source = field.source or name
            # Popping the source here (during explicit prefetch construction)
            # guarantees that implicitly required prefetches that follow will
            # not conflict.
            required = requirements.pop(source, None)

            prefetch_queryset = self._build_queryset(
                serializer=field,
                filters=filters.get(name, {}),
                queryset=related_queryset,
                requirements=required
            )

            # Note: There can only be one prefetch per source, even
            #       though there can be multiple fields pointing to
            #       the same source. This could break in some cases,
            #       but is mostly an issue on writes when we use all
            #       fields by default.
            prefetches[source] = self._create_prefetch(
                source,
                prefetch_queryset
            )

        return prefetches
544353
def collect(self):
        """"""
        for func in self._caches:
            cache = {}
            for key in self._caches[func]:
                if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
                    cache[key] = self._caches[func][key]
            self._caches[func] = cache
914528
def get_queryset(self, request):
        """"""
        qs = super(TaskAdmin, self).get_queryset(request)
        return qs.filter(success=True)
241302
def get_prefetch_queryset(self, instances, queryset=None):
        
        if queryset is None:
            queryset = self.get_queryset()
        queryset._add_hints(instance=instances[0])

        # CleanerVersion change 1: force the querytime to be the same as the
        # prefetched-for instance.
        # This is necessary to have reliable results and avoid extra queries
        # for cache misses when accessing the child objects from their
        # parents (e.g. choice.poll).
        instance_querytime = instances[0]._querytime
        if instance_querytime.active:
            if queryset.querytime.active and \
                            queryset.querytime.time != instance_querytime.time:
                raise ValueError(
                    "A Prefetch queryset that specifies an as_of time must "
                    "match the as_of of the base queryset.")
            else:
                queryset.querytime = instance_querytime

        # CleanerVersion change 2: make rel_obj_attr return a tuple with
        # the object's identity.
        # rel_obj_attr = self.field.get_foreign_related_value
        def versioned_fk_rel_obj_attr(versioned_rel_obj):
            return versioned_rel_obj.identity,

        rel_obj_attr = versioned_fk_rel_obj_attr
        instance_attr = self.field.get_local_related_value
        instances_dict = {instance_attr(inst): inst for inst in instances}
        # CleanerVersion change 3: fake the related field so that it provides
        # a name of 'identity'.
        # related_field = self.field.foreign_related_fields[0]
        related_field = namedtuple('VersionedRelatedFieldTuple', 'name')(
            'identity')

        # FIXME: This will need to be revisited when we introduce support for
        # composite fields. In the meantime we take this practical approach to
        # solve a regression on 1.6 when the reverse manager in hidden
        # (related_name ends with a '+'). Refs #21410.
        # The check for len(...) == 1 is a special case that allows the query
        # to be join-less and smaller. Refs #21760.
        if self.field.remote_field.is_hidden() or len(
                self.field.foreign_related_fields) == 1:
            query = {'%s__in' % related_field.name: set(
                instance_attr(inst)[0] for inst in instances)}
        else:
            query = {'%s__in' % self.field.related_query_name(): instances}
        queryset = queryset.filter(**query)

        # Since we're going to assign directly in the cache,
        # we must manage the reverse relation cache manually.
        if not self.field.remote_field.multiple:
            rel_obj_cache_name = self.field.remote_field.get_cache_name()
            for rel_obj in queryset:
                instance = instances_dict[rel_obj_attr(rel_obj)]
                setattr(rel_obj, rel_obj_cache_name, instance)

        if VERSION[:1] < (2,):
            return (queryset, rel_obj_attr, instance_attr, True,
                    self.field.get_cache_name())
        else:
            return (queryset, rel_obj_attr, instance_attr, True,
                    self.field.get_cache_name(), False)