Return the hook function (called when the response is received.)

    This allows us to intercept the response and do any necessary
    macaroon discharge before returning.
199572
def _prepare_discharge_hook(req, client):
    ''' 
    '''
    class Retry:
        # Define a local class so that we can use its class variable as
        # mutable state accessed by the closures below.
        count = 0

    def hook(response, *args, **kwargs):
        ''' Requests hooks system, this is the hook for the response.
        '''
        status_code = response.status_code

        if status_code != 407 and status_code != 401:
            return response
        if (status_code == 401 and response.headers.get('WWW-Authenticate') !=
                'Macaroon'):
            return response

        if response.headers.get('Content-Type') != 'application/json':
            return response
        errorJSON = response.json()
        if errorJSON.get('Code') != ERR_DISCHARGE_REQUIRED:
            return response
        error = Error.from_dict(errorJSON)
        Retry.count += 1
        if Retry.count >= MAX_DISCHARGE_RETRIES:
            raise BakeryException('too many ({}) discharge requests'.format(
                Retry.count)
            )
        client.handle_error(error, req.url)
        req.headers.pop('Cookie', None)
        req.prepare_cookies(client.cookies)
        req.headers[BAKERY_PROTOCOL_HEADER] = \
            str(bakery.LATEST_VERSION)
        with requests.Session() as s:
            return s.send(req)
    return hook
1123161
def handle_return(self, frame, return_value):
        """"""
        self.obj_cache[id(return_value)] = return_value
        self.extra_vars['__return__'] = return_value
        fun = frame.f_code.co_name
        log.info('Returning from %r with value: %r' % (fun, return_value))

        init = 'Echo|%s' % dump({
            'for': '__return__',
            'val': self.safe_better_repr(return_value)
        })
        self.interaction(
            frame,
            init=init,
            exception_description='Returning from %s with value %s' %
            (fun, return_value)
        )
1355340
def hook(name=None, *args, **kwargs):
    
    def decorator(f):
        if not hasattr(f, "hooks"):
            f.hooks = []
        f.hooks.append((name or f.__name__, args, kwargs))
        return f
    return decorator
512472
def add_hook(self, name, function):
        
        if not callable(function):
            return ValueError('Hook function should be callable')
        if name not in self.hooks:
            self.hooks[name] = []
        self.hooks[name].append(function)
        return self
569771
def _handle_func_call(self, node, scope, ctxt, stream):
        
        self._dlog("handling function call to '{}'".format(node.name.name))
        if node.args is None:
            func_args = []
        else:
            func_args = self._handle_node(node.args, scope, ctxt, stream)
        func = self._handle_node(node.name, scope, ctxt, stream)
        return func.call(func_args, ctxt, scope, stream, self, node.coord)
1065295
function functionWrapperFunction () {
        // call original function - catching errors for logging
        try {
            var res = functionObj.apply(this, arguments)
        }
        catch (error) {
            var err = error
        }
        // if log client then do logging
        if (options.logClient) {
            // get number of arguments
            var argsLength = arguments.length
            // copy of arguments
            var args = []
            // create copy of arguments
            for (var i=0; i < argsLength; i++) {
                args[i] = arguments[i]
            }
            // log call
            options.logClient.log('functionCall', {
                functionName: functionName,
                args: args,
                res: err || res,
                isError: (err ? true : false),
                moduleCallId: (this ? this.moduleCallId : undefined),
                requestId: (this ? this.requestId : undefined),
            })
        }
        // if result was an error then throw original error
        if (err) {
            throw err
        }
        // otherwise return original result
        else {
            return res
        }
    }
1173079
def _hook_decorator(self, addr, length=0, kwargs=None):
        

        def hook_decorator(func):
            self.hook(addr, func, length=length, kwargs=kwargs)
            return func

        return hook_decorator
604434
def decorate_method(cls, func):
        
        func_args = [arg for arg in function_arguments(func) if arg != 'self']
        method_return_types = \
            Endpoint._parse_function_return_types_from_doc(func.__doc__)
        name = '%s.%s' % (cls.path, func.__name__)

        @wraps(func)
        def method_decorator(self, *args, **kwargs):
            for i in range(len(args)):
                kwargs[func_args[i]] = args[i]

            api_call = self.connection._pre_process_call(
                name, endpoint_params=kwargs)
            try:
                data = func(**kwargs)
            except RestException as e:
                api_call.error = e
                raise e

            except Exception as e:
                call_queue = self.connection._call_queue.get(
                    self.connection._get_thread_id(), [])
                if api_call in call_queue:
                    call_queue.remove(api_call)
                e = RestException(original_error=e,
                                  stack=traceback.format_exc())
                log.error('ApiCall Exception: %s' % e, exc_info=True)
                raise e
            return self.connection._post_process_call(
                api_call, data, method_return_types)

        method_decorator.rest_method = True
        return method_decorator
19127
function wrapReturn(trace, clientState, hooks, rules){
  if (util.isFunction(trace.ret) && !trace.ret.__concurix_blacklisted) {
    wrapFunctions(trace.moduleName, trace.ret, -1, hooks, clientState, rules );
    trace.ret = wrap(trace.ret)
          .before(hooks.beforeHook)
          .after(hooks.afterHook)
          .state(clientState)
          .nameIfNeeded(trace.moduleName)
          .module(trace.moduleName)
          .getProxy();
  } else {
    wrapFunctions(trace.moduleName, trace.ret, -1, hooks, clientState, rules );
  }
}
1295741
def hook(self, name):
        
        def decorator(func):
            self.add_hook(name, func)
            return func
        return decorator
410999
async def hook(self, *args, **kwargs):
        

        return await self._makeApiCall(self.funcinfo["hook"], *args, **kwargs)
1189609
function(funcName, contextObject, _extraArgs) {
		var ctx = this._makeHookContext(contextObject),
			fn = this[funcName],
			args = Array.prototype.slice.call(arguments, 2);
		if(!$.isFunction(fn)){
			$.error("_callHook('" + funcName + "') is not a function");
		}
		args.unshift(ctx);
//		this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
		return fn.apply(this, args);
	}
77262
def api(func=None, timeout=API_TIMEOUT):  # incoming
    
    if func is None:
        return partial(api, timeout=timeout)
    else:
        wrapper = _get_api_decorator(func=func, timeout=timeout)
        return wrapper
1299970
function wrapRequestHandler(func) {
  return function handler(req, res, next) {
    try {
      const result = func(req, res, next)
      if (result && result.catch) result.catch(e => next(e))
    } catch(e) {
      next(e)
    }
  }
}
502090
@Override
    public ActionResponse hookBefore(final ActionRuntime runtime) { // application may override
        return viewHelper.getActionHook().hookBefore(runtime, r -> super.hookBefore(r));
    }
315334
def ReceiveRaw(self, **kw):
        '''
        '''
        if self.data: return self.data
        trace = self.trace
        while 1:
            response = self.h.getresponse()
            self.reply_code, self.reply_msg, self.reply_headers, self.data = \
                response.status, response.reason, response.msg, response.read()
            if trace:
                print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
                for i in (self.reply_code, self.reply_msg,):
                    print >>trace, str(i)
                print >>trace, "-------"
                print >>trace, str(self.reply_headers)
                print >>trace, self.data
            saved = None
            for d in response.msg.getallmatchingheaders('set-cookie'):
                if d[0] in [ ' ', '\t' ]:
                    saved += d.strip()
                else:
                    if saved: self.cookies.load(saved)
                    saved = d.strip()
            if saved: self.cookies.load(saved)
            if response.status == 401:
                if not callable(self.http_callbacks.get(response.status,None)):
                    raise RuntimeError, 'HTTP Digest Authorization Failed'
                self.http_callbacks[response.status](response)
                continue
            if response.status != 100: break

            # The httplib doesn't understand the HTTP continuation header.
            # Horrible internals hack to patch things up.
            self.h._HTTPConnection__state = httplib._CS_REQ_SENT
            self.h._HTTPConnection__response = None
        return self.data
640954
def trigger_hook(self, __name, *args, **kwargs):
        '''  '''
        return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]