Make a cache key from optionally typed positional and keyword arguments
540833
def _make_key(func,
              args,
              kwds,
              typed,
              kwd_mark=(object(), ),
              fasttypes={int, str, frozenset, type(None)},
              sorted=sorted,
              tuple=tuple,
              type=type,
              len=len):
    ''
    key = args
    key += kwd_mark
    key += ('__func__', func)
    if kwds:
        sorted_items = sorted(kwds.items())
        for item in sorted_items:
            key += item
    if typed:
        key += tuple(type(v) for v in args)
        if kwds:
            key += tuple(type(v) for k, v in sorted_items)
    elif len(key) == 1 and type(key[0]) in fasttypes:
        return key[0]
    return _HashedSeq(key)
3227
def save_cache(dpath, fname, cfgstr, data, ext='.cPkl', verbose=None):
    
    fpath = _args2_fpath(dpath, fname, cfgstr, ext)
    util_io.save_data(fpath, data, verbose=verbose)
    return fpath
610023
def _get_key(args, kwargs, remove_callback):
    """"""
    # Use tuples, because lists are not hashable.
    weak_args = tuple(_try_weakref(arg, remove_callback) for arg in args)
    # Use a tuple of (key, values) pairs, because dict is not hashable.
    # Sort it, so that we don't depend on the order of keys.
    weak_kwargs = tuple(sorted(
        (key, _try_weakref(value, remove_callback))
        for (key, value) in kwargs.items()))
    return weak_args, weak_kwargs
1205897
def cache_page(key_params, timeout='default'):
    
    def decorator_fn(fn):
        d = CachePageDecorator()
        return d.decorate(key_params, timeout, fn)

    return decorator_fn
683395
def cached(cache, key=keys.hashkey, lock=None):
    
    def decorator(func):
        if cache is None:
            def wrapper(*args, **kwargs):
                return func(*args, **kwargs)
        elif lock is None:
            def wrapper(*args, **kwargs):
                k = key(*args, **kwargs)
                try:
                    return cache[k]
                except KeyError:
                    pass  # key not found
                v = func(*args, **kwargs)
                try:
                    cache[k] = v
                except ValueError:
                    pass  # value too large
                return v
        else:
            def wrapper(*args, **kwargs):
                k = key(*args, **kwargs)
                try:
                    with lock:
                        return cache[k]
                except KeyError:
                    pass  # key not found
                v = func(*args, **kwargs)
                try:
                    with lock:
                        cache[k] = v
                except ValueError:
                    pass  # value too large
                return v
        return _update_wrapper(wrapper, func)
    return decorator
754259
def write_cache_decorator(self, node_or_pagetag, name,
                                    args, buffered, identifiers,
                                    inline=False, toplevel=False):
        """"""

        self.printer.writeline("__M_%s = %s" % (name, name))
        cachekey = node_or_pagetag.parsed_attributes.get('cache_key',
                                                         repr(name))

        cache_args = {}
        if self.compiler.pagetag is not None:
            cache_args.update(
                (
                    pa[6:],
                    self.compiler.pagetag.parsed_attributes[pa]
                )
                for pa in self.compiler.pagetag.parsed_attributes
                if pa.startswith('cache_') and pa != 'cache_key'
            )
        cache_args.update(
            (
                pa[6:],
                node_or_pagetag.parsed_attributes[pa]
            ) for pa in node_or_pagetag.parsed_attributes
            if pa.startswith('cache_') and pa != 'cache_key'
        )
        if 'timeout' in cache_args:
            cache_args['timeout'] = int(eval(cache_args['timeout']))

        self.printer.writeline("def %s(%s):" % (name, ','.join(args)))

        # form "arg1, arg2, arg3=arg3, arg4=arg4", etc.
        pass_args = [
                        "%s=%s" % ((a.split('=')[0],) * 2) if '=' in a else a
                        for a in args
                    ]

        self.write_variable_declares(
                            identifiers,
                            toplevel=toplevel,
                            limit=node_or_pagetag.undeclared_identifiers()
                        )
        if buffered:
            s = "context.get('local')."\
                "cache._ctx_get_or_create("\
                "%s, lambda:__M_%s(%s),  context, %s__M_defname=%r)" % (
                                cachekey, name, ','.join(pass_args),
                                ''.join(["%s=%s, " % (k, v)
                                for k, v in cache_args.items()]),
                                name
                            )
            # apply buffer_filters
            s = self.create_filter_callable(self.compiler.buffer_filters, s,
                                            False)
            self.printer.writelines("return " + s, None)
        else:
            self.printer.writelines(
                    "__M_writer(context.get('local')."
                    "cache._ctx_get_or_create("
                    "%s, lambda:__M_%s(%s), context, %s__M_defname=%r))" %
                    (
                        cachekey, name, ','.join(pass_args),
                        ''.join(["%s=%s, " % (k, v)
                        for k, v in cache_args.items()]),
                        name,
                    ),
                    "return ''",
                None
            )
758523
def cachedmethod(cache, key=keys.hashkey, lock=None):
    
    def decorator(method):
        if lock is None:
            def wrapper(self, *args, **kwargs):
                c = cache(self)
                if c is None:
                    return method(self, *args, **kwargs)
                k = key(*args, **kwargs)
                try:
                    return c[k]
                except KeyError:
                    pass  # key not found
                v = method(self, *args, **kwargs)
                try:
                    c[k] = v
                except ValueError:
                    pass  # value too large
                return v
        else:
            def wrapper(self, *args, **kwargs):
                c = cache(self)
                if c is None:
                    return method(self, *args, **kwargs)
                k = key(*args, **kwargs)
                try:
                    with lock(self):
                        return c[k]
                except KeyError:
                    pass  # key not found
                v = method(self, *args, **kwargs)
                try:
                    with lock(self):
                        c[k] = v
                except ValueError:
                    pass  # value too large
                return v
        return _update_wrapper(wrapper, method)
    return decorator
1356608
function(keysFunc, undefinedOnly) {
    return function(obj) {
      var length = arguments.length;
      if (length < 2 || obj === null) return obj;
      for (var index = 1; index < length; index++) {
        var source = arguments[index];
        var keys = keysFunc(source);
        var l = keys.length;

        for (var i = 0; i < l; i++) {
          var key = keys[i];
          if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
        }
      }

      return obj;
    };
  }
682945
def keys(self, namespace, prefix=None, limit=None, offset=None):
        """"""
        params = [namespace]
        query = 'SELECT key FROM gauged_keys WHERE namespace = %s'
        if prefix is not None:
            query += ' AND key LIKE %s'
            params.append(prefix + '%')
        if limit is not None:
            query += ' LIMIT %s'
            params.append(limit)
        if offset is not None:
            query += ' OFFSET %s'
            params.append(offset)
        cursor = self.cursor
        cursor.execute(query, params)
        return [key for key, in cursor]
1319093
def _memoize(f):
  """"""
  nothing = object()  # Unique "no value" sentinel object.
  cache = {}
  # Use a reentrant lock so that if f references the resulting wrapper we die
  # with recursion depth exceeded instead of deadlocking.
  lock = threading.RLock()
  @functools.wraps(f)
  def wrapper(arg):
    if cache.get(arg, nothing) is nothing:
      with lock:
        if cache.get(arg, nothing) is nothing:
          cache[arg] = f(arg)
    return cache[arg]
  return wrapper
129471
def cached_getter(func):
  """"""
  @wraps(func)
  def wrapper(self):
    attribute = f'_{func.__name__}'
    value = getattr(self, attribute, None)
    if value is None:
      value = func(self)
      setattr(self, attribute, value)
    return value
  return wrapper
479691
def Cache(fn):
   
   def fnCache(*args, **kwargs):
      """ Cache function """
      key = (args and tuple(args) or None,
             kwargs and frozenset(kwargs.items()) or None)
      if key not in fn.__cached__:
         fn.__cached__[key] = cache = fn(*args, **kwargs)
      else:
         cache = fn.__cached__[key]
      return cache

   def ResetCache():
      """ Reset cache """
      fn.__cached__ = {}

   setattr(fn, "__cached__", {})
   setattr(fn, "__resetcache__", ResetCache)
   fnCache.__name__ = fn.__name__
   fnCache.__doc__ = fn.__doc__
   fnCache.__dict__.update(fn.__dict__)
   return fnCache
563764
def _bind(self, args, kwargs, partial=False):
        """"""

        arguments = OrderedDict()

        parameters = iter(self.parameters.values())
        parameters_ex = ()
        arg_vals = iter(args)

        if partial:
            # Support for binding arguments to 'functools.partial' objects.
            # See 'functools.partial' case in 'signature()' implementation
            # for details.
            for param_name, param in self.parameters.items():
                if param._partial_kwarg and param_name not in kwargs:
                    # Simulating 'functools.partial' behavior
                    kwargs[param_name] = param.default

        while True:
            # Let's iterate through the positional arguments and corresponding
            # parameters
            try:
                arg_val = next(arg_vals)
            except StopIteration:
                # No more positional arguments
                try:
                    param = next(parameters)
                except StopIteration:
                    # No more parameters. That's it. Just need to check that
                    # we have no `kwargs` after this while loop
                    break
                else:
                    if param.kind == _VAR_POSITIONAL:
                        # That's OK, just empty *args.  Let's start parsing
                        # kwargs
                        break
                    elif param.name in kwargs:
                        if param.kind == _POSITIONAL_ONLY:
                            msg = (
                                "{arg!r} parameter is positional only, "
                                "but was passed as a keyword"
                            )
                            msg = msg.format(arg=param.name)
                            raise TypeError(msg)
                        parameters_ex = (param,)
                        break
                    elif param.kind == _VAR_KEYWORD or param.default is not _empty:
                        # That's fine too - we have a default value for this
                        # parameter.  So, lets start parsing `kwargs`, starting
                        # with the current parameter
                        parameters_ex = (param,)
                        break
                    else:
                        if partial:
                            parameters_ex = (param,)
                            break
                        else:
                            msg = "{arg!r} parameter lacking default value"
                            msg = msg.format(arg=param.name)
                            raise TypeError(msg)
            else:
                # We have a positional argument to process
                try:
                    param = next(parameters)
                except StopIteration:
                    raise TypeError("too many positional arguments")
                else:
                    if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
                        # Looks like we have no parameter for this positional
                        # argument
                        raise TypeError("too many positional arguments")

                    if param.kind == _VAR_POSITIONAL:
                        # We have an '*args'-like argument, let's fill it with
                        # all positional arguments we have left and move on to
                        # the next phase
                        values = [arg_val]
                        values.extend(arg_vals)
                        arguments[param.name] = tuple(values)
                        break

                    if param.name in kwargs:
                        raise TypeError(
                            "multiple values for argument "
                            "{arg!r}".format(arg=param.name)
                        )

                    arguments[param.name] = arg_val

        # Now, we iterate through the remaining parameters to process
        # keyword arguments
        kwargs_param = None
        for param in itertools.chain(parameters_ex, parameters):
            if param.kind == _POSITIONAL_ONLY:
                # This should never happen in case of a properly built
                # Signature object (but let's have this check here
                # to ensure correct behaviour just in case)
                raise TypeError(
                    "{arg!r} parameter is positional only, "
                    "but was passed as a keyword".format(arg=param.name)
                )

            if param.kind == _VAR_KEYWORD:
                # Memorize that we have a '**kwargs'-like parameter
                kwargs_param = param
                continue

            param_name = param.name
            try:
                arg_val = kwargs.pop(param_name)
            except KeyError:
                # We have no value for this parameter.  It's fine though,
                # if it has a default value, or it is an '*args'-like
                # parameter, left alone by the processing of positional
                # arguments.
                if (
                    not partial
                    and param.kind != _VAR_POSITIONAL
                    and param.default is _empty
                ):
                    raise TypeError(
                        "{arg!r} parameter lacking default value".format(arg=param_name)
                    )

            else:
                arguments[param_name] = arg_val

        if kwargs:
            if kwargs_param is not None:
                # Process our '**kwargs'-like parameter
                arguments[kwargs_param.name] = kwargs
            else:
                raise TypeError("too many keyword arguments")

        return self._bound_arguments_cls(self, arguments)
301094
def memoize(function):
    """"""
    _cache = {}
    @wraps(function)
    def wrapper(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in _cache:
            _cache[key] = function(*args, **kwargs)
        return _cache[key]
    return wrapper
105566
def cached(key = None, extradata = {}):
	'''  '''

	def decorator(f):

		@wraps(f)
		def wrapper(*args, **kwargs):

			uid = key
			if not uid:
				from hashlib import md5
				arguments = list(args) + [(a, kwargs[a]) for a in sorted(kwargs.keys())]
				uid = md5(str(arguments)).hexdigest()
			if exists(uid):
				debug('Item \'%s\' is cached (%s).' % (uid, cache))
				return get(uid)
			else:
				debug('Item \'%s\' is not cached (%s).' % (uid, cache))
				result = f(*args, **kwargs)
				debug('Caching result \'%s\' as \'%s\' (%s)...' % (result, uid, cache))
				debug('Extra data: ' + (str(extradata) or 'None'))
				put(uid, result, extradata)
				return result
		return wrapper
	return decorator
506413
def get_search_cache_key(prefix, *args):
    
    key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
    not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
    key = not_allowed.sub('', key)
    return key
563522
function decodeParams(cache, API_URL, params) {
  var obj = {}, v;
  for (var k in params) {
    if (!params.hasOwnProperty(k)) continue;
    obj[k] = decode(cache, API_URL, params[k]);
  }
  return obj;
}