Call a remote method and update the local cache with the result
		if it already existed.

		:param str method: The name of the remote procedure to execute.
		:return: The return value from the remote function.
355397
def cache_call_refresh(self, method, *options):
		
		options_hash = self.encode(options)
		if len(options_hash) > 20:
			options_hash = hashlib.new('sha1', options).digest()
		options_hash = sqlite3.Binary(options_hash)

		with self.cache_lock:
			cursor = self.cache_db.cursor()
			cursor.execute('DELETE FROM cache WHERE method = ? AND options_hash = ?', (method, options_hash))
		return_value = self.call(method, *options)
		store_return_value = sqlite3.Binary(self.encode(return_value))
		with self.cache_lock:
			cursor = self.cache_db.cursor()
			cursor.execute('INSERT INTO cache (method, options_hash, return_value) VALUES (?, ?, ?)', (method, options_hash, store_return_value))
			self.cache_db.commit()
		return return_value
635917
def memoize_method(method):
    """"""
    cache = {}

    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        """Caching wrapper."""
        key = (args, tuple(sorted(kwargs.items())))
        if key in cache:
            return cache[key]
        else:
            result = method(self, *args, **kwargs)
            cache[key] = result
            return result

    return wrapper
55447
def method_for_cached(object, key, fetch_method=:fetch, method_name=nil)
      method_name = ("cached_" + (method_name || key)).gsub(/[^\w\!\?]/, '_')
      method_body = <<-END
        def #{method_name}(*args, &block)
          opts = args.empty? ? {} : args.first

          proxy = AridCache::CacheProxy.new(self, #{key.inspect}, opts, &block)
          if opts[:clear] == true
            proxy.clear_cached
          else
            proxy.#{fetch_method.to_s}
          end
        end
      END
      # Get the correct object
      object = (class << object; self; end) if object.is_a?(Class)
      object.class_eval(method_body, __FILE__, __LINE__)
    end
1219067
def remote_eval(self, func, *args, **kwargs):
        
        return eval(self.remote(func, *args, **kwargs))
335774
def exec(method, options = {}, &code)
    Manager.connection.exec(method, options, &code)
  end
278445
function cacheCall(method, key) {
    return methodCache.call(method, key)
        .catch((err) => {
        log_1.logger.error(`[${method}] Error:`, err);
        throw err; // throw after log to stop async chain
    })
        .then((result) => {
        (result)
            ? log_1.logger.debug(`[${method}] Success: ${JSON.stringify(result)}`)
            : log_1.logger.debug(`[${method}] Success`);
        return result;
    });
}
815303
def method_cache(by='value',method='run'):
    """"""

    def decorate_(func):
        def decorate(*args, **kwargs):
            model = args[0] # Assumed to be self.
            assert hasattr(model,method), "Model must have a '%s' method."%method
            if func.__name__ == method: # Run itself.
                method_args = kwargs
            else: # Any other method.
                method_args = kwargs[method] if method in kwargs else {}
            if not hasattr(model.__class__,'cached_runs'): # If there is no run cache.
                model.__class__.cached_runs = {} # Create the method cache.
            cache = model.__class__.cached_runs
            if by == 'value':
                model_dict = {key:value for key,value in list(model.__dict__.items()) \
                              if key[0]!='_'}
                method_signature = SciUnit.dict_hash({'attrs':model_dict,'args':method_args}) # Hash key.
            elif by == 'instance':
                method_signature = SciUnit.dict_hash({'id':id(model),'args':method_args}) # Hash key.
            else:
                raise ValueError("Cache type must be 'value' or 'instance'")
            if method_signature not in cache:
                print("Method with this signature not found in the cache. Running...")
                f = getattr(model,method)
                f(**method_args)
                cache[method_signature] = (datetime.now(),model.__dict__.copy())
            else:
                print("Method with this signature found in the cache. Restoring...")
                _,attrs = cache[method_signature]
                model.__dict__.update(attrs)
            return func(*args, **kwargs)
        return decorate
    return decorate_
673726
def call_remote(method, args)
      # Blank out username and password
      safe_args = args.inject([]) {|memo, v| memo << ((memo.last == :username or memo.last == :password) ? "" : v) }
      key = "#{method}(#{safe_args.join(':')})"
      
      if @recording
        response = super(method, args)
        
        unless @recorded_responses[key]
          # track this { key => request } to avoid duplication in the YAML
          @recorded_responses[key] = true
          
          YAML.dump({ key => response }, @recording_source)
        end
      else
        response = @recorded_responses[key]
        raise ASFRecordingBindingError.new(@logger, "Unable to find matching response for recorded request '#{key}'") unless response
      end
      
      response
    end
125706
def memoize(method):
    

    cache = method.cache = collections.OrderedDict()

    # Put these two methods in the local space (faster)
    _get = cache.get
    _popitem = cache.popitem

    @functools.wraps(method)
    def memoizer(instance, x, *args, **kwargs):

        if not _WITH_MEMOIZATION or isinstance(x, u.Quantity):

            # Memoization is not active or using units, do not use memoization

            return method(instance, x, *args, **kwargs)

        # Create a tuple because a tuple is hashable

        unique_id = tuple(float(yy.value) for yy in instance.parameters.values()) + (x.size, x.min(), x.max())

        # Create a unique identifier for this combination of inputs

        key = hash(unique_id)

        # Let's do it this way so we only look into the dictionary once

        result = _get(key)

        if result is not None:

            return result

        else:

            result = method(instance, x, *args, **kwargs)

            cache[key] = result

            if len(cache) > _CACHE_SIZE:
                # Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) )
                [_popitem(False) for i in range(max(_CACHE_SIZE // 2, 1))]

            return result

    # Add the function as a "attribute" so we can access it
    memoizer.input_object = method

    return memoizer
100614
def client_call(method, *args)
      key = cache_key(method, args)
      cached = dalli.get(key)
      return cached if cached
      response = client.send(method, *args)
      dalli.set(key, response)
      response
    end
1081058
def _exec_method(self, method, request, data, *args, **kw):
        
        if self._is_data_method(request):
            return method(data, request, *args, **kw)
        else:
            return method(request, *args, **kw)
1149446
def map(self, method: str, *args, _threaded: bool = True, **kwargs
           ) -> "AttrIndexedDict":
        ""

        work = lambda item: getattr(item, method)(*args, **kwargs)

        if _threaded:
            pool = ThreadPool(int(config.CFG["GENERAL"]["parallel_requests"]))

            try:
                pool.map(work, self.data.values())
            except KeyboardInterrupt:
                LOG.warning("CTRL-C caught, finishing current tasks...")
                pool.terminate()
            else:
                pool.close()

            pool.join()
            return self

        for item in self.data.values():
            work(item)
        return self
154362
def request_method(self, method: str,
                       **method_kwargs: Union[str, int]) -> dict:
        
        response = self.session.send_method_request(method, method_kwargs)
        self.check_for_errors(method, method_kwargs, response)
        return response
36468
def api_call(method, path, params ={}, &proc)
      if cache = caching? && (@cache[cache_key(path, params)])
        return cache
      else
        if @logging
          Calculated::Logging.log_calculated_api(method, path, params) do
            api_call_without_logging(method, path, params, &proc)
          end
        else
          api_call_without_logging(method, path, params, &proc)
        end
      end
    end
630678
def _call_method(self, method_name, *args, **kwargs):
        
        if self.use_redfish_only:
            if method_name in SUPPORTED_REDFISH_METHODS:
                the_operation_object = self.redfish
            else:
                raise NotImplementedError()
        else:
            the_operation_object = self.ribcl
            if 'Gen10' in self.model:
                if method_name in SUPPORTED_REDFISH_METHODS:
                    the_operation_object = self.redfish
                else:
                    if (self.is_ribcl_enabled is not None
                            and not self.is_ribcl_enabled):
                        raise NotImplementedError()
            elif ('Gen9' in self.model) and (method_name in
                                             SUPPORTED_RIS_METHODS):
                the_operation_object = self.ris

        method = getattr(the_operation_object, method_name)

        LOG.debug(self._("Using %(class)s for method %(method)s."),
                  {'class': type(the_operation_object).__name__,
                   'method': method_name})

        return method(*args, **kwargs)
902954
def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
        
        if self.loop.is_running():
            raise RuntimeError("Event loop is already running.")

        if not self.is_connected:
            self.loop.run_until_complete(self.connect())

        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)
        result = self.loop.run_until_complete(task)

        self.loop.run_until_complete(self.quit())

        return result
534517
def rpc(method):
    
    @wraps(method)
    def rpc_wrapper(*args, **kwargs):
        controller_instance = args[0]

        if not isinstance(controller_instance, RemoteControllerDeamon):
            raise Exception("'rpc' decorator must use in a RemoteControllerDeamon (-derived) class method!")

        # Decide the call origin: if the current pid is the daemon pid, this is server side,
        # so call registered method. If not, start a jsonrpc request.
        call_from_server = os.getpid() == controller_instance.get_pid()

        logger.debug("Initiate RPC method '%s' in '%s'", method.__name__, 'daemon' if call_from_server else 'cli')

        if call_from_server:
            return method(*args, **kwargs)
        else:
            url = "http://{}:{}/jsonrpc".format(controller_instance.host, controller_instance.port)
            headers = {'content-type': 'application/json'}

            payload = {
                "method": method.__name__,
                "params": kwargs,
                "jsonrpc": "2.0",
                "id": 0,
            }
            try:
                response = requests.post(url, data=json.dumps(payload), headers=headers).json()
                if 'result' in response:
                    return response['result']
                else:
                    logger.error("There is an error during rpc call. Response:\n%s", json.dumps(response, indent=4))
                    return "Error: {}. (see logs for details)".format(response['error']['message'])
            except requests.exceptions.ConnectionError as e:
                logger.error("Command server not runnning (%s), args: %s, kwargs: %s", e, args, kwargs)
                return None

    rpc_wrapper.registered_for_rpc = method
    return rpc_wrapper