Generates a cache key for the *args and **kwargs
762032
def generate_cache_key(value):
    
    if is_bytes(value):
        return hashlib.md5(value).hexdigest()
    elif is_text(value):
        return generate_cache_key(to_bytes(text=value))
    elif is_boolean(value) or is_null(value) or is_number(value):
        return generate_cache_key(repr(value))
    elif is_dict(value):
        return generate_cache_key((
            (key, value[key])
            for key
            in sorted(value.keys())
        ))
    elif is_list_like(value) or isinstance(value, collections.abc.Generator):
        return generate_cache_key("".join((
            generate_cache_key(item)
            for item
            in value
        )))
    else:
        raise TypeError("Cannot generate cache key for value {0} of type {1}".format(
            value,
            type(value),
        ))
184794
def _memoize_cache_key(args, kwargs):
    
    cache_key_list = []

    # hack to get around the unhashability of lists,
    # add a special case to convert them to tuples
    for arg in args:
        if type(arg) is list:
            cache_key_list.append(tuple(arg))
        else:
            cache_key_list.append(arg)
    for (k, v) in sorted(kwargs.items()):
        if type(v) is list:
            cache_key_list.append((k, tuple(v)))
        else:
            cache_key_list.append((k, v))
    return tuple(cache_key_list)
595789
def get_kwargs(args, exp_keys, exp_elems):
    """"""
    arg_dict = {}    # For arguments that have values
    for key, val in args.items():
        if exp_keys is not None and key in exp_keys and val:
            if isinstance(val, str):
                val = val.strip()
            arg_dict[key] = val
        elif exp_elems is not None and key in exp_elems and val:
            arg_dict[key] = True
    return arg_dict
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)
649541
def memoize(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """ wrap it up and store info in a cache """
        cache = args[0].memoized
        refresh = args[0].refresh_interval
        use_cache = args[0].use_cache

        # short circuit if not using cache
        if use_cache is False:
            return func(*args, **kwargs)

        if func.__name__ not in cache:
            cache[func.__name__] = dict()
            if "defaults" not in cache:
                cache["defaults"] = dict()
            cache["defaults"][func.__name__] = parse_all_arguments(func)
        # build a key; should also consist of the default values
        defaults = cache["defaults"][func.__name__].copy()
        for key, val in kwargs.items():
            defaults[key] = val
        tmp = list()
        tmp.extend(args[1:])
        for k in sorted(defaults.keys()):
            tmp.append("({0}: {1})".format(k, defaults[k]))

        # handle possible unicode characters
        if sys.version_info < (3, 0):
            tmp = [unicode(x) for x in tmp]
        key = " - ".join(tmp)

        # set the value in the cache if missing or needs to be refreshed
        if key not in cache[func.__name__]:
            cache[func.__name__][key] = (time.time(), func(*args, **kwargs))
        else:
            tmp = cache[func.__name__][key]
            # determine if we need to refresh the data...
            if refresh is not None and time.time() - tmp[0] > refresh:
                cache[func.__name__][key] = (time.time(), func(*args, **kwargs))
        return cache[func.__name__][key][1]

    return wrapper
789879
def memoize(f):
    """"""
    def _c(*args, **kwargs):
        if not hasattr(f, 'cache'):
            f.cache = dict()
        key = (args, tuple(kwargs))
        if key not in f.cache:
            f.cache[key] = f(*args, **kwargs)
        return f.cache[key]
    return wraps(f)(_c)
339246
String computeCacheKey(Class cls, String methodName, String argpart) {
		String cachekey = keyMaker.getMd5(cls.getName() + "." + methodName);
		if (!argpart.isEmpty()) {
			cachekey += "_" + keyMaker.getMd5(argpart);
		}
		logger.debug("CACHEID : {}.{}_{} = {}", cls.getName(), methodName, argpart, cachekey);
		return cachekey;
	}
366647
def get_cached_value(self, *args, **kwargs):
        
        key = self.get_cache_key(*args, **kwargs)
        logger.debug(key)
        return self.cache.get(key, default=Ellipsis)
487072
public Serializable cached(String key, Object... args) {
        if (conf().cacheDisabled()) return null;
        ICacheService cacheService = _cacheService;
        if (args.length > 0) {
            StringBuilder sb = new StringBuilder(key);
            for (Object arg : args) {
                sb.append("-").append(arg);
            }
            key = sb.toString();
        }
        return cacheService.get(key);
    }
386564
def cached(key, timeout=3600):
    

    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            cache = get_cache()
            # Check if key is a function
            if callable(key):
                cache_key = key(*args, **kwargs)
            else:
                cache_key = key
            # Try to get the value from cache
            cached_val = cache.get(cache_key)
            if cached_val is None:
                # Call the original function and cache the result
                cached_val = f(*args, **kwargs)
                cache.set(cache_key, cached_val, timeout)
            return cached_val

        return wrapped

    return decorator
365779
def _get_cache_key(self, obj):
        """"""
        if obj is not None:
            # Make sure that key is REALLY unique.
            return '{}-{}'.format(id(self), obj.pk)

        return "{}-None".format(id(self))
1147866
def get_func_result_cachekey(func_, args_=tuple(), kwargs_={}):
    
    import utool as ut
    # Rectify partials and whatnot
    true_args = args_
    true_kwargs = kwargs_
    true_func = func_
    if isinstance(func_, partial):
        true_func = func_.func
        if func_.args is not None:
            true_args = tuple(list(func_.args) + list(args_))
        if func_.keywords is not None:
            true_kwargs.update(func_.keywords)

    if ut.is_method(true_func):
        method = true_func
        true_func = method.im_func
        self = method.im_self
        true_args = tuple([self] + list(true_args))

    # Build up cachekey
    funcname = ut.get_funcname(true_func)
    kwdefaults = ut.get_kwdefaults(true_func, parse_source=False)
    #kwdefaults = ut.get_kwdefaults(true_func, parse_source=True)
    argnames   = ut.get_argnames(true_func)
    key_argx = None
    key_kwds = None
    func = true_func  # NOQA
    args = true_args  # NOQA
    kwargs = true_kwargs  # NOQA
    args_key = ut.get_cfgstr_from_args(true_func, true_args, true_kwargs,
                                       key_argx, key_kwds, kwdefaults,
                                       argnames)
    cachekey = funcname + '(' + args_key + ')'
    return cachekey
891560
def generate_key(self):
        
        sql = self.sql()
        key, created = self.get_or_create_model_key()
        if created:
            db_table = self.model._meta.db_table
            logger.debug('created new key {0} for model {1}'.format(key, db_table))
            model_cache_info = ModelCacheInfo(db_table, key)
            model_cache_backend.share_model_cache_info(model_cache_info)
        query_key = u'{model_key}{qs}{db}'.format(model_key=key,
                                                  qs=sql,
                                                  db=self.db)
        key = hashlib.md5(query_key.encode('utf-8')).hexdigest()
        return key
418129
def _execute_callback(self, *args):
        ""
        self._validate_key(args)      # Validate input key

        # Additional validation needed to ensure kwargs don't clash
        kdims = [kdim.name for kdim in self.kdims]
        kwarg_items = [s.contents.items() for s in self.streams]
        hash_items = tuple(tuple(sorted(s.hashkey.items())) for s in self.streams)+args
        flattened = [(k,v) for kws in kwarg_items for (k,v) in kws
                     if k not in kdims]

        if self._posarg_keys:
            kwargs = dict(flattened, **dict(zip(self._posarg_keys, args)))
            args = ()
        else:
            kwargs = dict(flattened)
        if not isinstance(self.callback, Generator):
            kwargs['_memoization_hash_'] = hash_items

        with dynamicmap_memoization(self.callback, self.streams):
            retval = self.callback(*args, **kwargs)
        return self._style(retval)
1278569
def method_args(self, context, **kwargs):
        
        try:
            _args = self.conf[context].copy()
        except KeyError:
            _args = kwargs
        else:
            _args.update(kwargs)
        return _args
1283161
def get_cache_key(content, **kwargs):
    ''''''
    cache_key = ''
    for key in sorted(kwargs.keys()):
        cache_key = '{cache_key}.{key}:{value}'.format(
            cache_key=cache_key,
            key=key,
            value=kwargs[key],
        )

    cache_key = '{content}{cache_key}'.format(
        content=content,
        cache_key=cache_key,
    )

    # fix for non ascii symbols, ensure encoding, python3 hashlib fix
    cache_key = cache_key.encode('utf-8', 'ignore')
    cache_key = md5(cache_key).hexdigest()

    cache_key = '{prefix}.{version}.{language}.{cache_key}'.format(
        prefix=settings.ACTIVE_URL_CACHE_PREFIX,
        version=__version__,
        language=get_language(),
        cache_key=cache_key
    )

    return cache_key
505297
def get_kwargs(kwargs):
    
    return {
        key: value for key, value in six.iteritems(kwargs)
        if key != 'self'
    }