Enable client-side caching for the current request
323848
def enable_cache(self):
        
        self.set_header('Cache-Control', 'max-age=%d, public' % self.CACHE_TIME)

        now = datetime.datetime.now()
        expires = now + datetime.timedelta(seconds=self.CACHE_TIME)
        self.set_header('Expires', expires.strftime('%a, %d %b %Y %H:%M:%S'))

        self.set_header('access-control-max-age', self.CACHE_TIME)
440968
function _cacheGetHandleByUrl( sUrl )
{
	let oRet;
	let arrResult;

	if ( 'string' !== typeof sUrl || 0 === sUrl.length )
	{
		return null;
	}

	//	...
	oRet		= null;
	sUrl		= sUrl.trim().toLowerCase();
	arrResult	= m_arrCacheOutboundPeers.filter( oSocket => oSocket.peer === sUrl );
	if ( Array.isArray( arrResult ) && 1 === arrResult.length )
	{
		oRet = arrResult[ 0 ];
	}

	return oRet;
}
771853
private void requestCacheUpdate() {
        log.debug("Cache update requested");
        if (updateRequested) {
            log.debug("Cache update, redundant request ignored.");
            return;
        }

        updateRequested = true;

        if (!updating) {
            updateCache();
        }
    }
204168
def cache_key(self, request, method=None):
        

        if method is None:
            method = request.method
        return "bettercache_page:%s:%s" %(request.build_absolute_uri(), method)
367499
function fetch(request, maxCacheAge) {
    if (maxCacheAge === void 0) { maxCacheAge = 60 * 60 * 1000; }
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var promise;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!(!cache.has(request) || cache.get(request)[1].getTime() + maxCacheAge - new Date().getTime() < 0)) return [3 /*break*/, 2];
                    promise = window.fetch(request).then(function(res){return res.json()}).catch(function(err){return window.fetch(`https://lergin.de/api/cors/${request}`).then(function(res){return res.json()})});
                    cache.set(request, [promise, new Date()]);
                    return [4 /*yield*/, promise];
                case 1: return [2 /*return*/, _a.sent()];
                case 2: return [4 /*yield*/, cache.get(request)[0]];
                case 3: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
362785
function getAndCache (url) {
  var xhr = new XMLHttpRequest(); // eslint-disable-line

  if (cache[url]) {
    return cache[url]
  }

  xhr.open('GET', url, false);
  xhr.send();
  var script = xhr.responseText;
  cache[url] = evalJS(script);
  return cache[url]
}
752290
def cache_data(self, request, data, key='params'):
        
        request.session['%s:%s' % (constants.SESSION_KEY, key)] = data
506567
function ( params, cache ) {
            var sp = ( this._path.indexOf('?') < 0 )? '?' : '&',
                url = ( cache )? this._path : this._path + sp + 'requestTime=' + new Date().getTime();
    
            //URI encode
            if ( params ) {
                var datas = params.split( '&' ),
                    paramNum = datas.length,
                    dataSet, i;
    
                params = '';
                for ( i = 0; i < paramNum; ++i ) {
                    dataSet = datas[i].split( '=' );
                    params += dataSet[0] + '=' + encodeURIComponent( dataSet[1] );
                    if ( i < paramNum - 1 ) params += '&';
                }
            }
    
            this.xhr.onreadystatechange = this._handler;
    
            //GET
            if ( /get/i.test(this._method) ) {
                if ( params && params != '' ) url += '&' + params;
                this.xhr.open( 'GET', url, true );
                this.xhr.send( null );
                //POST
            } else {
                this.xhr.open( 'POST', url, true );
                this.xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded; charset=' + this._charset );
                this.xhr.send( params );
            }
            return this;
        }
138311
function _disableCache() {
        var result = new $.Deferred();

        if (brackets.inBrowser) {
            result.resolve();
        } else {
            var port = brackets.app.getRemoteDebuggingPort ? brackets.app.getRemoteDebuggingPort() : 9234;
            Inspector.getDebuggableWindows("127.0.0.1", port)
                .fail(result.reject)
                .done(function (response) {
                    var page = response[0];
                    if (!page || !page.webSocketDebuggerUrl) {
                        result.reject();
                        return;
                    }
                    var _socket = new WebSocket(page.webSocketDebuggerUrl);
                    // Disable the cache
                    _socket.onopen = function _onConnect() {
                        _socket.send(JSON.stringify({ id: 1, method: "Network.setCacheDisabled", params: { "cacheDisabled": true } }));
                    };
                    // The first message will be the confirmation => disconnected to allow remote debugging of Brackets
                    _socket.onmessage = function _onMessage(e) {
                        _socket.close();
                        result.resolve();
                    };
                    // In case of an error
                    _socket.onerror = result.reject;
                });
        }

        return result.promise();
    }
984626
def cached_request(self, request):
        
        cache_url = self.cache_url(request.url)
        logger.debug('Looking up "%s" in the cache', cache_url)
        cc = self.parse_cache_control(request.headers)

        # Bail out if the request insists on fresh data
        if "no-cache" in cc:
            logger.debug('Request header has "no-cache", cache bypassed')
            return False

        if "max-age" in cc and cc["max-age"] == 0:
            logger.debug('Request header has "max_age" as 0, cache bypassed')
            return False

        # Request allows serving from the cache, let's see if we find something
        cache_data = self.cache.get(cache_url)
        if cache_data is None:
            logger.debug("No cache entry available")
            return False

        # Check whether it can be deserialized
        resp = self.serializer.loads(request, cache_data)
        if not resp:
            logger.warning("Cache entry deserialization failed, entry ignored")
            return False

        # If we have a cached 301, return it immediately. We don't
        # need to test our response for other headers b/c it is
        # intrinsically "cacheable" as it is Permanent.
        # See:
        #   https://tools.ietf.org/html/rfc7231#section-6.4.2
        #
        # Client can try to refresh the value by repeating the request
        # with cache busting headers as usual (ie no-cache).
        if resp.status == 301:
            msg = (
                'Returning cached "301 Moved Permanently" response '
                "(ignoring date and etag information)"
            )
            logger.debug(msg)
            return resp

        headers = CaseInsensitiveDict(resp.headers)
        if not headers or "date" not in headers:
            if "etag" not in headers:
                # Without date or etag, the cached response can never be used
                # and should be deleted.
                logger.debug("Purging cached response: no date or etag")
                self.cache.delete(cache_url)
            logger.debug("Ignoring cached response: no date")
            return False

        now = time.time()
        date = calendar.timegm(parsedate_tz(headers["date"]))
        current_age = max(0, now - date)
        logger.debug("Current age based on date: %i", current_age)

        # TODO: There is an assumption that the result will be a
        #       urllib3 response object. This may not be best since we
        #       could probably avoid instantiating or constructing the
        #       response until we know we need it.
        resp_cc = self.parse_cache_control(headers)

        # determine freshness
        freshness_lifetime = 0

        # Check the max-age pragma in the cache control header
        if "max-age" in resp_cc:
            freshness_lifetime = resp_cc["max-age"]
            logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime)

        # If there isn't a max-age, check for an expires header
        elif "expires" in headers:
            expires = parsedate_tz(headers["expires"])
            if expires is not None:
                expire_time = calendar.timegm(expires) - date
                freshness_lifetime = max(0, expire_time)
                logger.debug("Freshness lifetime from expires: %i", freshness_lifetime)

        # Determine if we are setting freshness limit in the
        # request. Note, this overrides what was in the response.
        if "max-age" in cc:
            freshness_lifetime = cc["max-age"]
            logger.debug(
                "Freshness lifetime from request max-age: %i", freshness_lifetime
            )

        if "min-fresh" in cc:
            min_fresh = cc["min-fresh"]
            # adjust our current age by our min fresh
            current_age += min_fresh
            logger.debug("Adjusted current age from min-fresh: %i", current_age)

        # Return entry if it is fresh enough
        if freshness_lifetime > current_age:
            logger.debug('The response is "fresh", returning cached response')
            logger.debug("%i > %i", freshness_lifetime, current_age)
            return resp

        # we're not fresh. If we don't have an Etag, clear it out
        if "etag" not in headers:
            logger.debug('The cached response is "stale" with no etag, purging')
            self.cache.delete(cache_url)

        # return the original handler
        return False
895350
function(oRequest, oResponse) {
    var aCache = this._aCache;
    if(!aCache) {
        return;
    }

    // If the cache is full, make room by removing stalest element (index=0)
    while(aCache.length >= this.maxCacheEntries) {
        aCache.shift();
    }

    // Add to cache in the newest position, at the end of the array
    var oCacheElem = {request:oRequest,response:oResponse};
    aCache[aCache.length] = oCacheElem;
    this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
}
1254078
def execute(self, cacheable=False):
        """"""

        if self.network.is_caching_enabled() and cacheable:
            response = self._get_cached_response()
        else:
            response = self._download_response()

        return minidom.parseString(_string(response).replace("opensearch:", ""))
980028
def cache(key, options = {}, &block) # :doc:
        if cache_configured?
          cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
        else
          yield
        end
      end
41793
function getCache() {
      return new Promise(function(resolve, reject) {
        // create and fetch the cache key
        get(getKey(), function(err, data) {
          if (err) {
            return reject(err);
          }
          resolve(data);
        });
      });
    }
279626
private function _process() {

        // if caching is enabled but path doesn't exist, or is not writable
        if ($this->cache !== false && (!is_dir($this->cache['path']) || !is_writable($this->cache['path'])))

            // trigger an error and stop execution
            trigger_error('Cache path does not exists or is not writable', E_USER_ERROR);

        // iterate through the requests to process
        foreach ($this->_requests as $index => $request) {

            // if callback function is defined but it doesn't exists
            if ($request['callback'] != '' && !is_callable($request['callback']))

                // trigger an error and stop execution
                // the check is for when callback functions are defined as methods of a class
                trigger_error('Callback function "' . (is_array($request['callback']) ? array_pop($request['callback']) : $request['callback']) . '" does not exist', E_USER_ERROR);

            // if caching is enabled
            if ($this->cache !== false) {

                // get the name to be used for the cache file associated with the request
                $cache_file = $this->_get_cache_file_name($request);

                // if cache file exists and is not expired
                if (file_exists($cache_file) && filemtime($cache_file) + $this->cache['lifetime'] > time()) {

                    // if we have a callback
                    if ($request['callback'] != '') {

                        // prepare the arguments to pass to the callback function
                        $arguments = array_merge(

                            // made of the result from the cache file...
                            array(unserialize($this->cache['compress'] ? gzuncompress(file_get_contents($cache_file)) : file_get_contents($cache_file))),

                            // ...and any additional arguments (minus the first 2)
                            (array)$request['arguments']

                        );

                        // feed them as arguments to the callback function
                        call_user_func_array($request['callback'], $arguments);

                        // remove this request from the list so it doesn't get processed
                        unset($this->_requests[$index]);

                    }

                }

            }

        }

        // if there are any requests to process
        if (!empty($this->_requests)) {

            // initialize the multi handle
            // this will allow us to process multiple handles in parallel
            $this->_multi_handle = curl_multi_init();

            // queue the first batch of requests
            // (as many as defined by the "threads" property, or less if there aren't as many requests)
            $this->_queue_requests();

            // a flag telling the library if there are any requests currently processing
            $running = null;

            // loop
            do {

                // get status update
                while (($status = curl_multi_exec($this->_multi_handle, $running)) == CURLM_CALL_MULTI_PERFORM);

                // if no request has finished yet, keep looping
                if ($status != CURLM_OK) break;

                // if a request was just completed, we'll have to find out which one
                while ($info = curl_multi_info_read($this->_multi_handle)) {

                    // get handle of the completed request
                    $handle = $info['handle'];

                    // get content associated with the handle
                    $content = curl_multi_getcontent($handle);

                    // get the handle's ID
                    $resource_number = preg_replace('/Resource id #/', '', $handle);

                    // get the information associated with the request
                    $request = $this->_running['fh' . $resource_number];

                    // create a new object in which we will store all the data associated with the handle,
                    // as properties of this object
                    $result = new stdClass();

                    // get information about the request
                    $result->info = curl_getinfo($handle);

                    // extend the "info" property with the original URL
                    $result->info = array('original_url' => $request['url']) + $result->info;

                    // if request was a POST
                    if (isset($request['options'][CURLOPT_POSTFIELDS]) && $request['options'][CURLOPT_POSTFIELDS])

                        // put POST parameters in the response
                        $result->post = $request['options'][CURLOPT_POSTFIELDS];

                    // last request headers
                    $result->headers['last_request'] =

                        (

                            // if CURLINFO_HEADER_OUT is set
                            isset($request['options'][CURLINFO_HEADER_OUT]) &&

                            // if CURLINFO_HEADER_OUT is TRUE
                            $request['options'][CURLINFO_HEADER_OUT] == 1 &&

                            // if we actually have this information
                            isset($result->info['request_header'])

                        // extract request headers
                        ) ? $this->_parse_headers($result->info['request_header'], true) : '';

                    // remove request headers information from its previous location
                    unset($result->info['request_header']);

                    // get headers (unless we were explicitly told not to)
                    $result->headers['responses'] = (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1) ?

                        $this->_parse_headers(substr($content, 0, $result->info['header_size'])) :

                        '';

                    // get output (unless we were explicitly told not to)
                    $result->body = !isset($request['options'][CURLOPT_NOBODY]) || $request['options'][CURLOPT_NOBODY] == 0 ?

                        (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1 ?

                        substr($content, $result->info['header_size']) :

                        $content) :

                        '';

                    // if _htmlentities is set to TRUE, we're not doing a binary transfer and we have a body, run htmlentities() on it
                    if ($this->_htmlentities && !isset($request['options'][CURLOPT_BINARYTRANSFER]) && $result->body != '') {

                        // since PHP 5.3.0, htmlentities will return an empty string if the input string contains an
                        // invalid code unit sequence within the given encoding (utf-8 in our case)
                        // so take care of that
                        if (defined(ENT_IGNORE)) $result->body = htmlentities($result->body, ENT_IGNORE, 'utf-8');

                        // for PHP versions lower than 5.3.0
                        else htmlentities($result->body);

                    }

                    // get CURLs response code and associated message
                    $result->response = array($this->_response_messages[$info['result']], $info['result']);

                    // if we have a callback
                    if (isset($request['callback']) && $request['callback'] != '') {

                        // prepare the arguments to pass to the callback function
                        $arguments = array_merge(

                            // made of the "result" object...
                            array($result),

                            // ...and any additional arguments
                            $request['arguments']

                        );

                        // if downloaded a file
                        if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) {

                            // we make a dummy array with the first first 2 elements (which we also remove from the $arguments[0]->info array)
                            $tmp_array = array_splice($arguments[0]->info, 0, 2);

                            // make available the name we saved the file with
                            // (we need to merge the first 2 elements, our new array and the rest of the elements)
                            $arguments[0]->info = array_merge($tmp_array, array('downloaded_filename' => $this->_running['fh' . $resource_number]['file_name']), $arguments[0]->info);

                        }

                        // feed them as arguments to the callback function
                        // and save the callback's response, if any
                        $callback_response = call_user_func_array($request['callback'], $arguments);

                    // if no callback function, we assume the response is TRUE
                    } else $callback_response = true;

                    // if caching is enabled and the callback function did not return FALSE
                    if ($this->cache !== false && $callback_response !== false) {

                        // get the name of the cache file associated with the request
                        $cache_file = $this->_get_cache_file_name($request);

                        // cache the result
                        file_put_contents($cache_file, $this->cache['compress'] ? gzcompress(serialize($result)) : serialize($result));

                        // set rights on the file
                        chmod($cache_file, intval($this->cache['chmod'], 8));

                    }

                    // if there are more URLs to process and we're don't pause between batches of requests, queue the next one(s)
                    if (!empty($this->_requests) && !$this->pause_interval) $this->_queue_requests();

                    // remove the handle that we finished processing
                    // this needs to be done *after* we've already queued a new URL for processing
                    curl_multi_remove_handle($this->_multi_handle, $handle);

                    // make sure the handle gets closed
                    curl_close($handle);

                    // if we downloaded a file
                    if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER])

                        // close the associated file pointer
                        fclose($this->_running['fh' . $resource_number]['file_handler']);

                    // we don't need the information associated with this request anymore
                    unset($this->_running['fh' . $resource_number]);

                }

                // waits until curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM or until the timeout, whatever happens first
                // call usleep() if a select returns -1 - workaround for PHP bug: https://bugs.php.net/bug.php?id=61141
                if ($running && curl_multi_select($this->_multi_handle) === -1) usleep(100);

            // as long as there are threads running or requests waiting in the queue
            } while ($running || !empty($this->_running));

            // close the multi curl handle
            curl_multi_close($this->_multi_handle);

        }

    }
661654
protected void saveRequestedUrl(final C context, final List<Client> currentClients, AjaxRequestResolver ajaxRequestResolver) {
        if (ajaxRequestResolver == null || !ajaxRequestResolver.isAjax(context)) {
            savedRequestHandler.save(context);
        }
    }
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