Helper for constructing simple decorators around Lookup.results.

    func is a function which takes a request as the first parameter. If func
    returns an HttpReponse it is returned otherwise the original Lookup.results
    is returned.
179110
def results_decorator(func):
    
    # Wrap function to maintian the original doc string, etc
    @wraps(func)
    def decorator(lookup_cls):
        # Construct a class decorator from the original function
        original = lookup_cls.results
        def inner(self, request):
            # Wrap lookup_cls.results by first calling func and checking the result
            result = func(request)
            if isinstance(result, HttpResponse):
                return result
            return original(self, request)
        # Replace original lookup_cls.results with wrapped version
        lookup_cls.results = inner
        return lookup_cls
    # Return the constructed decorator
    return decorator
457656
def decorate(func, caller):
    
    evaldict = dict(_call_=caller, _func_=func)
    fun = FunctionMaker.create(
        func, "return _call_(_func_, %(shortsignature)s)",
        evaldict, __wrapped__=func)
    if hasattr(func, '__qualname__'):
        fun.__qualname__ = func.__qualname__
    return fun
378816
def _lookup(self, skip_cache, fun, *args, **kwargs):
        
        if args not in self.cache or skip_cache:
            self.cache[args] = fun(*args, **kwargs)
        return self.cache[args]
903265
def relicResult(relicFunc, resultType, *args):
    
    result = None

    # If there is a return type, it becomes the first parameter.
    if resultType is not None:
        result = resultType()
        args = (result,) + args

    # Pass all parameters byref
    params = [byref(x) for x in list(args)]

    # Call the function and return our result.
    relicFunc(*params)
    return result
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
350325
def any(cls, result_key, func):
        
        def scanner(self, obj):
            current_value = getattr(self, result_key, None)
            setattr(self, result_key, current_value or func(obj))

        cls._scan(result_key, scanner)
808778
function func(ast) {
  var params = list(ast["params"])
  var id = ast["id"] ? to_s(ast["id"]) : ""
  return "function " + id + "(" + params + ") " + to_s(ast["body"])
}
704765
def etag(func):
    
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        """Call the view function and generate an ETag value, checking the
        headers to determine what response to send."""
        # only for HEAD and GET requests
        assert request.method in ['HEAD', 'GET'],\
            '@etag is only supported for GET requests'
        response = func(*args, **kwargs)
        response = make_response(response)
        etag_value = '"' + hashlib.md5(response.get_data()).hexdigest() + '"'
        response.headers['ETag'] = etag_value
        if_match = request.headers.get('If-Match')
        if_none_match = request.headers.get('If-None-Match')
        if if_match:
            etag_list = [tag.strip() for tag in if_match.split(',')]
            if etag_value not in etag_list and '*' not in etag_list:
                response = precondition_failed()
        elif if_none_match:
            etag_list = [tag.strip() for tag in if_none_match.split(',')]
            if etag_value in etag_list or '*' in etag_list:
                response = not_modified()
        return response
    return wrapped
1208392
def collect(cls, result_key, func):
        
        def scanner(self, obj):
            if not getattr(self, result_key, None):
                setattr(self, result_key, [])
            rv = func(obj)
            if rv:
                getattr(self, result_key).append(rv)

        cls._scan(result_key, scanner)
864196
def find(self, func):
        
        self.ftmp = None

        def test(value, index, list):
            if func(value, index, list) is True:
                self.ftmp = value
                return True
        self._clean.any(test)
        return self._wrap(self.ftmp)
919202
def decorator(caller, func=None):
    
    if func is None: # returns a decorator
        fun = FunctionMaker(caller)
        first_arg = inspect.getargspec(caller)[0][0]
        src = 'def %s(%s): return _call_(caller, %s)' % (
            caller.__name__, first_arg, first_arg)
        return fun.make(src, dict(caller=caller, _call_=decorator),
                        undecorated=caller)
    else: # returns a decorated function
        fun = FunctionMaker(func)
        src = """def %(name)s(%(signature)s):
    return _call_(_func_, %(signature)s)"""
        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
1040043
function resultToEither(result) {
  if(isFunction(result)) {
    return function(x) {
      const m = result(x)

      if(!isSameType(Result, m)) {
        throw new TypeError('resultToEither: Result returning function required')
      }

      return applyTransform(m)
    }
  }

  if(isSameType(Result, result)) {
    return applyTransform(result)
  }

  throw new TypeError('resultToEither: Result or Result returning function required')
}
1371232
def find(self, func: Callable[[T], bool]) -> TOption[T]:
        
        for x in self:
            if func(x):
                return TOption(x)
        return TOption(None)
1189192
def get_result(self, decorated_function, *args, **kwargs):
		
		try:
			return self._storage[decorated_function]
		except KeyError as e:
			raise WCacheStorage.CacheMissedException('No cache record found') from e
974819
def _request(self, func, url, version=1, *args, **kwargs):
        
        return_json = kwargs.pop('return_json', False)
        url = self.api_url[version] + url
        response = func(url, *args, **kwargs)

        if 'proxies' not in kwargs:
            kwargs['proxies'] = self.proxydict

        # Check for error, raising an exception if appropriate.
        response.raise_for_status()

        try:
            json_response = response.json()
        except ValueError:
            json_response = None
        if isinstance(json_response, dict):
            error = json_response.get('error')
            if error:
                raise BitstampError(error)
            elif json_response.get('status') == "error":
                raise BitstampError(json_response.get('reason'))

        if return_json:
            if json_response is None:
                raise BitstampError(
                    "Could not decode json for: " + response.text)
            return json_response

        return response
440092
def callback(func):
    
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        result = func(*args, **kwargs)
        if inspect.iscoroutine(result):
            aio_loop.create_task(result)

    return wrapped
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