enable tracing of hook calls and return an undo function.
329374
def enable_tracing(self):
        
        hooktrace = self.hook._trace

        def before(hook_name, methods, kwargs):
            hooktrace.root.indent += 1
            hooktrace(hook_name, kwargs)

        def after(outcome, hook_name, methods, kwargs):
            if outcome.excinfo is None:
                hooktrace("finish", hook_name, "-->", outcome.get_result())
            hooktrace.root.indent -= 1

        return self.add_hookcall_monitoring(before, after)
1317571
def handle_hooks(self, hooks, hook_type, *args):
        '''
        
        '''
        if hook_type not in ['before', 'on_route']:
            hooks = reversed(hooks)

        for hook in hooks:
            result = getattr(hook, hook_type)(*args)
            # on_error hooks can choose to return a Response, which will
            # be used instead of the standard error pages.
            if hook_type == 'on_error' and isinstance(result, WebObResponse):
                return result
992510
def trace(line):
    """"""
    args = line.split()
    enable = args[0] in {'enable', 'on'}

    if not enable:
        sys.settrace(None)
        sys.stdout = _ORIGINAL_STDOUT
        return

    pattern = args[1] if len(args) > 1 else None
    sys.stdout = open(args[2], 'a') if len(args) > 2 else sys.stdout
    sys.settrace(partial(trace_line, pattern))
1236286
def _unwrap_func(cls, decorated_func):
        '''
        
        '''
        if click is not None:
            # Workaround for click.command() decorator not setting
            # __wrapped__
            if isinstance(decorated_func, click.Command):
                return cls._unwrap_func(decorated_func.callback)

        if hasattr(decorated_func, '__wrapped__'):
            # Recursion: unwrap more if needed
            return cls._unwrap_func(decorated_func.__wrapped__)
        else:
            # decorated_func isn't actually decorated, no more
            # unwrapping to do
            return decorated_func
42541
def hook_wrapper(prompt):
    '''
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, str):
            raise TypeError, u'readline must return a string.'
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = u''
    except:
        print >>sys.stderr, u'Readline internal error'
        traceback.print_exc()
        res = u'\n'
    # we have to make a copy because the caller expects to free the result
    p = _strdup(res)
    return p
1333022
def trace():
        """"""
        def fget(self):
            return self._options.get('trace', None)

        def fset(self, value):
            self._options['trace'] = value

        return locals()
667240
def excepthook(cls, error, trace):
    
    global _excepthooks
    new_hooks = []

    for hook_ref in _excepthooks:
        hook = hook_ref()
        if hook:
            hook(cls, error, trace)
            new_hooks.append(hook_ref)

    _excepthook = new_hooks
    sys.__excepthook__(cls, error, trace)
390834
def enable_tracing(self):
        
        _logger.x_debug("entering enable_tracing()")
        # uncomment next line to get debugger tracing info
        #self.dump_tracing_state("before enable_tracing()")
        
        if not self.tracing_enabled and self.execution_started:
            # Restore or set trace function on all existing frames appart from 
            # debugger
            threading.settrace(self._tracer)  # then enable on all threads to come
            for thr in threading.enumerate():
                if thr.ident != self.debugger_thread_ident:  # skip debugger thread
                    a_frame = sys._current_frames()[thr.ident]
                    while a_frame:
                        a_frame.f_trace = self._tracer
                        a_frame = a_frame.f_back
            iksettrace3._set_trace_on(self._tracer, self.debugger_thread_ident)
            self.tracing_enabled = True
        
        #self.dump_tracing_state("after enable_tracing()")
        return self.tracing_enabled
538356
def on_finish(func, handler, args, kwargs):
    
    tracing = handler.settings.get('opentracing_tracing')
    tracing._finish_tracing(handler)

    return func(*args, **kwargs)
1199805
function listenBefore(hook) {
      return history.listenBefore(function (location, callback) {
        _runTransitionHook2['default'](hook, addQuery(location), callback);
      });
    }
1203598
def undecorate(func):
    """"""
    orig_call_wrapper = lambda x: x
    for call_wrapper, unwrap in SUPPORTED_DECORATOR.items():
        if isinstance(func, call_wrapper):
            func = unwrap(func)
            orig_call_wrapper = call_wrapper
            break
    return orig_call_wrapper, func
611976
def register_postloop_hook(self, func: Callable[[None], None]) -> None:
        """"""
        self._validate_prepostloop_callable(func)
        self._postloop_hooks.append(func)
382922
def hook_output (module:nn.Module, detach:bool=True, grad:bool=False)->Hook:
    ""
    return Hook(module, _hook_inner, detach=detach, is_forward=not grad)
895477
public function restoreGlobalFunctions(): void
    {
        foreach (self::$hooks as $key => $data) {
            self::$hooks[$key]['callback'] = null;
        }
    }
640954
def trigger_hook(self, __name, *args, **kwargs):
        '''  '''
        return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
1309041
def trace(self, func):
        """"""

        def wrapper(*args, **kwargs):
            # Print out the call to the function with its arguments.
            s = self.Stanza(self.indent)
            s.add([self.GREEN, func.__name__, self.NORMAL, '('])
            s.indent += 4
            sep = ''
            for arg in args:
                s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep)
                sep = ', '
            for name, value in sorted(kwargs.items()):
                s.add([name + '=', self.CYAN, self.safe_repr(value),
                       self.NORMAL], sep)
                sep = ', '
            s.add(')', wrap=False)
            self.writer.write(s.chunks)

            # Call the function.
            self.indent += 2
            try:
                result = func(*args, **kwargs)
            except:
                # Display an exception.
                self.indent -= 2
                etype, evalue, etb = self.sys.exc_info()
                info = self.inspect.getframeinfo(etb.tb_next, context=3)
                s = self.Stanza(self.indent)
                s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL])
                s.add(['at ', info.filename, ':', info.lineno], ' ')
                lines = self.unindent(info.code_context)
                firstlineno = info.lineno - info.index
                fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd'
                for i, line in enumerate(lines):
                    s.newline()
                    s.add([
                        i == info.index and self.MAGENTA or '',
                        fmt % (i + firstlineno),
                        i == info.index and '> ' or ': ', line, self.NORMAL])
                self.writer.write(s.chunks)
                raise

            # Display the return value.
            self.indent -= 2
            s = self.Stanza(self.indent)
            s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result),
                   self.NORMAL])
            self.writer.write(s.chunks)
            return result
        return self.functools.update_wrapper(wrapper, func)
93995
def with_current_context(self, func):
        """"""

        caller_context = self.snapshot()

        def call_with_current_context(*args, **kwargs):
            try:
                backup_context = self.snapshot()
                self.apply(caller_context)
                return func(*args, **kwargs)
            finally:
                self.apply(backup_context)

        return call_with_current_context