Takes a callback function and name, and captures a stack trace, returning a new callback that restores the stack frame This function adds a single function call overhead during callback registration vs. inlining it in wrapRegistationFunction
197002
function makeWrappedCallback(callback, frameLocation) {
        // add a fake stack frame. we can't get a real one since we aren't inside the original function
        var traceError = new Error();
        traceError.__location = frameLocation;
        traceError.__previous = currentTraceError;
        return function() {
            // if (currentTraceError) {
            //     FIXME: This shouldn't normally happen, but it often does. Do we actually need a stack instead?
            //     console.warn("(long-stack-traces) Internal Error: currentTrace already set.");
            // }
            // restore the trace
            currentTraceError = traceError;
            try {
                return callback.apply(this, arguments);
            } catch (e) {
                console.error("Uncaught " + e.stack);
                if (LST.rethrow)
                    throw ""; // TODO: throw the original error, or undefined?
            } finally {
                // clear the trace so we can check that none is set above.
                // TODO: could we remove this for slightly better performace?
                currentTraceError = null;
            }
        }
    }
327529
def register_function(self, name: Optional[str]=None):
        
        def wrap(function: Callable)->Any:
            nonlocal name
            if name is None:
                name = function.__name__
            self.funcs[name] = function
            return function
        return wrap
1001549
def recorded(function, custom_id=None, reentrant=True):
    ''''''
    canonical = reflect.class_canonical_name(3)
    annotate.injectClassCallback("recorded", 4,
                                 "_register_recorded_call",
                                 function, custom_id=custom_id,
                                 class_canonical_name=canonical)

    def wrapper(self, *args, **kwargs):
        recorder = IRecorder(self)
        return recorder.call(function, args, kwargs, reentrant=reentrant)

    return wrapper
30716
function(callback) {
    // capture current error location
    var trace_error = new Error();
    trace_error.id = ERROR_ID++;
    trace_error.__previous__ = current_trace_error;
    trace_error.__trace_count__ = current_trace_error ? current_trace_error.__trace_count__ + 1 : 1;
    limit_frames(trace_error);
    var new_callback = function() {
        current_trace_error = trace_error;
        trace_error = null;
        var res = callback.apply(this, arguments);
        current_trace_error = null;
        return res;
    };
    new_callback.__original_callback__ = callback;
    return new_callback;
}
590479
def _methodInTraceback(self, name, traceback):
    '''
    
    '''
    foundMethod = False
    for frame in self._frames(traceback):
      this = frame.f_locals.get('self')
      if this is self and frame.f_code.co_name == name:
        foundMethod = True
        break
    return foundMethod
460904
def _get_stack_info_for_trace(
        self,
        frames,
        library_frame_context_lines=None,
        in_app_frame_context_lines=None,
        with_locals=True,
        locals_processor_func=None,
    ):
        """"""
        return stacks.get_stack_info(
            frames,
            library_frame_context_lines=library_frame_context_lines,
            in_app_frame_context_lines=in_app_frame_context_lines,
            with_locals=with_locals,
            include_paths_re=self.include_paths_re,
            exclude_paths_re=self.exclude_paths_re,
            locals_processor_func=locals_processor_func,
        )
771649
def _record_call(func):
    

    @wraps(func)
    def wrapper(*args, **kwargs):
        global global_error_context

        # log a call as about to take place
        if global_error_context is not None:
            key = CallLogKey(name=func.__name__,
                             args=[serialize_object_for_logging(arg) for arg in args],
                             kwargs={k: serialize_object_for_logging(v) for k, v in kwargs.items()})

            pre_entry = CallLogValue(timestamp_in=datetime.utcnow(),
                                     timestamp_out=None,
                                     return_value=None)
            global_error_context.log[key] = pre_entry

        val = func(*args, **kwargs)

        # poke the return value of that call in
        if global_error_context is not None:
            post_entry = CallLogValue(timestamp_in=pre_entry.timestamp_in,
                                      timestamp_out=datetime.utcnow(),
                                      return_value=serialize_object_for_logging(val))
            global_error_context.log[key] = post_entry

        return val

    return wrapper
1142550
function wrap(fn, callback) {
  var invoked

  return wrapped

  function wrapped() {
    var params = slice.call(arguments, 0)
    var callback = fn.length > params.length
    var result

    if (callback) {
      params.push(done)
    }

    try {
      result = fn.apply(null, params)
    } catch (err) {
      /* Well, this is quite the pickle.  `fn` received
       * a callback and invoked it (thus continuing the
       * pipeline), but later also threw an error.
       * We’re not about to restart the pipeline again,
       * so the only thing left to do is to throw the
       * thing instea. */
      if (callback && invoked) {
        throw err
      }

      return done(err)
    }

    if (!callback) {
      if (result && typeof result.then === 'function') {
        result.then(then, done)
      } else if (result instanceof Error) {
        done(result)
      } else {
        then(result)
      }
    }
  }

  /* Invoke `next`, only once. */
  function done() {
    if (!invoked) {
      invoked = true

      callback.apply(null, arguments)
    }
  }

  /* Invoke `done` with one value.
   * Tracks if an error is passed, too. */
  function then(value) {
    done(null, value)
  }
}
1306421
def stack_trace(depth=None):
    
    frames = inspect.stack()[2:]
    if depth:
        frames = frames[:depth]
        
    result = StringIO()
    result.write("----------------------------------------------------\n")
    for (frame, file, line, context, code, status) in frames:
        result.write("In %s from %s\n%s %s" % (context, file, line, "\n".join(code)))
        result.write("----------------------------------------------------\n")        
    return result.getvalue()
719907
def visit_FunctionCall(self, node):
        """"""
        call = self.memory[node.identifier.name]._node
        args = [self.visit(parameter) for parameter in node.parameters]

        if isinstance(call, AST):
            current_scope = self.memory.stack.current.current
            memory_functions = {
                key: current_scope[key]
                for key in current_scope
                if isinstance(current_scope[key], Function)
            }

            self.memory.append_frame()
            for i, arg in enumerate(args):
                self.memory[i] = arg

            for function in memory_functions:
                self.memory[function] = memory_functions[function]

            function_result = self.visit(call)

            self.memory.pop_frame()
            return function_result
        else:
            return bind_type(call(*args))
1107716
private static CallFrame initFrameForNoSuchMethod(Context cx,
            CallFrame frame, int indexReg, Object[] stack, double[] sDbl,
            int stackTop, int op, Scriptable funThisObj, Scriptable calleeScope,
            NoSuchMethodShim noSuchMethodShim, InterpretedFunction ifun)
    {
        // create an args array from the stack
        Object[] argsArray = null;
        // exactly like getArgsArray except that the first argument
        // is the method name from the shim
        int shift = stackTop + 2;
        Object[] elements = new Object[indexReg];
        for (int i=0; i < indexReg; ++i, ++shift) {
            Object val = stack[shift];
            if (val == DOUBLE_MARK) {
                val = ScriptRuntime.wrapNumber(sDbl[shift]);
            }
            elements[i] = val;
        }
        argsArray = new Object[2];
        argsArray[0] = noSuchMethodShim.methodName;
        argsArray[1] = cx.newArray(calleeScope, elements);

        // exactly the same as if it's a regular InterpretedFunction
        CallFrame callParentFrame = frame;
        if (op == Icode_TAIL_CALL) {
            callParentFrame = frame.parentFrame;
            exitFrame(cx, frame, null);
        }
        // init the frame with the underlying method with the
        // adjusted args array and shim's function
        CallFrame calleeFrame = initFrame(cx, calleeScope, funThisObj, argsArray, null,
          0, 2, ifun, callParentFrame);
        if (op != Icode_TAIL_CALL) {
            frame.savedStackTop = stackTop;
            frame.savedCallOp = op;
        }
        return calleeFrame;
    }
372935
def capture(context, callable_, *args, **kwargs):
    

    if not compat.callable(callable_):
        raise exceptions.RuntimeException(
                        "capture() function expects a callable as "
                        "its argument (i.e. capture(func, *args, **kwargs))"
                        )
    context._push_buffer()
    try:
        callable_(*args, **kwargs)
    finally:
        buf = context._pop_buffer()
    return buf.getvalue()
1265810
def register(name, _callable=None):
    
    def wrapper(_callable):
        registered_checks[name] = _callable
        return _callable

    # If function or class is given, do the registeration
    if _callable:
        return wrapper(_callable)

    return wrapper
99088
def remove_stacktrace_locals(client, event):
    
    func = lambda frame: frame.pop("vars", None)
    return _process_stack_frames(event, func)
245555
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        callerfunc = get_init(caller)
        doc = 'decorator(%s) converts functions/generators into ' \
            'factories of %s objects' % (caller.__name__, caller.__name__)
        fun = getfullargspec(callerfunc).args[1]  # second arg
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        callerfunc = caller
        doc = caller.__doc__
        fun = getfullargspec(callerfunc).args[0]  # first arg
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        callerfunc = caller.__call__.__func__
        doc = caller.__call__.__doc__
        fun = getfullargspec(callerfunc).args[1]  # second arg
    evaldict = callerfunc.__globals__.copy()
    evaldict['_call_'] = caller
    evaldict['_decorate_'] = decorate
    return FunctionMaker.create(
        '%s(%s)' % (name, fun),
        'return _decorate_(%s, _call_)' % fun,
        evaldict, call=caller, doc=doc, module=caller.__module__,
        __wrapped__=caller)
548305
def _get_registerd_func(name_or_func):
    
    # get the function or register callable
    if callable(name_or_func):
        func = register_array_xcorr(name_or_func)
    else:
        func = XCOR_FUNCS[name_or_func or 'default']
    assert callable(func), 'func is not callable'
    # ensure func has the added methods
    if not hasattr(func, 'registered'):
        func = register_array_xcorr(func)
    return func
641127
def sanitize_stacktrace_locals(client, event):
    

    def func(frame):
        if "vars" in frame:
            frame["vars"] = varmap(_sanitize, frame["vars"])

    return _process_stack_frames(event, func)