Signal handler to print a stack trace and some interesting values.
357188
def print_stack(sig, frame):
    """"""
    if _debug: print_stack._debug("print_stack %r %r", sig, frame)
    global running, deferredFns, sleeptime

    sys.stderr.write("==== USR1 Signal, %s\n" % time.strftime("%d-%b-%Y %H:%M:%S"))

    sys.stderr.write("---------- globals\n")
    sys.stderr.write("    running: %r\n" % (running,))
    sys.stderr.write("    deferredFns: %r\n" % (deferredFns,))
    sys.stderr.write("    sleeptime: %r\n" % (sleeptime,))

    sys.stderr.write("---------- stack\n")
    traceback.print_stack(frame)

    # make a list of interesting frames
    flist = []
    f = frame
    while f.f_back:
        flist.append(f)
        f = f.f_back

    # reverse the list so it is in the same order as print_stack
    flist.reverse()
    for f in flist:
        sys.stderr.write("---------- frame: %s\n" % (f,))
        for k, v in f.f_locals.items():
            sys.stderr.write("    %s: %r\n" % (k, v))

    sys.stderr.flush()
162509
def print_stack_events(self):
        '''
        
        '''
        first_token = '7be7981bd6287dd8112305e8f3822a6f'
        keep_going = True
        next_token = first_token
        current_request_token = None
        rows = []
        try:
            while keep_going and next_token:
                if next_token == first_token:
                    response = self._cf_client.describe_stack_events(
                        StackName=self._stack_name
                    )
                else:
                    response = self._cf_client.describe_stack_events(
                        StackName=self._stack_name,
                        NextToken=next_token
                    )

                next_token = response.get('NextToken', None)
                for event in response['StackEvents']:
                    row = []
                    event_time = event.get('Timestamp')
                    request_token = event.get('ClientRequestToken', 'unknown')
                    if current_request_token is None:
                        current_request_token = request_token
                    elif current_request_token != request_token:
                        keep_going = False
                        break

                    row.append(event_time.strftime('%x %X'))
                    row.append(event.get('LogicalResourceId'))
                    row.append(event.get('ResourceStatus'))
                    row.append(event.get('ResourceStatusReason', ''))
                    rows.append(row)

            if len(rows) > 0:
                print('\nEvents for the current upsert:')
                print(tabulate(rows, headers=['Time', 'Logical ID', 'Status', 'Message']))
                return True
            else:
                print('\nNo stack events found\n')
        except Exception as wtf:
            print(wtf)

        return False
45347
def cli_main(pid, include_greenlet, debugger, verbose):
    '''
    '''
    try:
        print_stack(pid, include_greenlet, debugger, verbose)
    except DebuggerNotFound as e:
        click.echo('DebuggerNotFound: %s' % e.args[0], err=True)
        click.get_current_context().exit(1)
918344
def msg(cls, error=None, debug=True, trace=True):
        
        if debug and error is not None:
            print(error)
        # TODO: BUG: trace should only be printed if debug is true
        if trace:
            print(traceback.format_exc())
201141
private static String stackTraceToString(List<StackTraceElement> stack) {
		return StringPrinter.buildString(printer -> {
			for (StackTraceElement element : stack) {
				printer.print("at ");
				printer.print(element.getClassName());
				printer.print(".");
				printer.print(element.getMethodName());
				printer.print("(");
				printer.print(element.getFileName());
				printer.print(":");
				printer.print(Integer.toString(element.getLineNumber()));
				printer.println(")");
			}
		});
	}
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))
902632
function printStack(err) {
  if (err && err.stack) {
    console.error(err.stack);
  }
  else {
    console.log(err);
  }
}
75106
def debug_print(*message):
    """"""
    warnings.warn("debug_print is deprecated; use the logging module instead.")
    if get_debug_level():
        ss = STDOUT
        if PY3:
            # This is needed after restarting and using debug_print
            for m in message:
                ss.buffer.write(str(m).encode('utf-8'))
            print('', file=ss)
        else:
            print(*message, file=ss)
375066
public void printStackTrace(java.io.PrintWriter s) {
        synchronized (s) {
            s.print(prefix);
            ex.printStackTrace(s);
        }
    }
387412
def debug(self, msg, *args, **kwargs):
        
        kwargs.setdefault('inc_stackinfo', True)
        self.log(DEBUG, msg, args, **kwargs)
1360325
def signal_catcher(callback):
    """"""
    def _catch_exit_signal(sig_num, _frame):
        print('Received signal {:d} invoking callback...'.format(sig_num))
        callback()

    signal.signal(signal.SIGINT, _catch_exit_signal)
    signal.signal(signal.SIGQUIT, _catch_exit_signal)
    signal.signal(signal.SIGTERM, _catch_exit_signal)
    yield
463688
def trace_dispatch(self, frame, event, arg):
    """"""
    if hasattr(self, 'vimpdb'):
        return self.vimpdb.trace_dispatch(frame, event, arg)
    else:
        return self._orig_trace_dispatch(frame, event, arg)
1060296
private final static void printStackTrace(Throwable t, PrintWriter p) {
        if (t == null) {
            p.println("none");
            return;
        }

        // Capture any exceptions while printing stack so we return what we have
        // so far
        try {
            // Print the stack trace of the Throwable.
            t.printStackTrace(p);
        } catch (Throwable e) {
            // Do not throw exception, add a message to PrintWriter and return
            // what we have so far.
            p.println("<Encountered exception while printing stack trace>");
            p.println(e.getClass().getName() + ": " + e.getMessage());
            return;
        }

        // Handle the degenerate case of a TraceException which contains an
        // array of Throwables.
//        if (t instanceof TraceException) {
//            TraceException te = (TraceException) t;
//            Throwable subexs[] = te.getSubexceptions();
//            if (subexs == null)
//                return;
//            for (int i = 0; i < subexs.length; i++) {
//                p.println("----- Begin backtrace for subexception[" + i + "]");
//                printStackTrace(subexs[i], p);
//            }
//            return;
//        }

        // Normal Throwables may contain a single nested Throwable. So this
        // Throwable could be the
        // start of a chain of Throwables. We want to obtain the stack traces of
        // all Throwables in
        // the chain so we can see the entire history, execution path and root
        // exception.
        // Some Throwables that support nesting provide support for
        // automatically walking the chain
        // by providing the appropriate printStackTrace() overrides. Others do
        // not, which means we
        // need to manually walk the chain if we want to obtain all the stack
        // traces.
        // If printStackTrace is called on a Throwable chain that contains
        // Throwables that have
        // overriden printStackTrace, the recursion will end after printing out
        // the stack trace of
        // the first Throwable that does not provide an override. If
        // printStackTrace is called on
        // a chain where the base Throwable does not provide the override, then
        // only the stack trace
        // of the base Throwable will have been printed. Therefore, to obtain
        // the next Throwable that
        // needs its stack trace printed, simply walk the chain starting at the
        // base, find the first
        // Throwable that does not provide an override, then start with that
        // guys nested Throwable.

        // updated to support J2SE1.4's nested Throwables.

        boolean autoRecursion = true;
        Throwable tNext = null;

        // Capture any exceptions while calculating nexted exception so we return what we have
        // so far
        try {
            // Compute tNext - the first Throwable in the stack that doesn't recurse
            // properly
            while (autoRecursion) {

                // all known throwables printStackTrace methods recurse properly
                // when cause is set.
                tNext = t.getCause();
                if (tNext != null) {
                    t = tNext;
                } else {
                    tNext = getNestedThrowable(t);
                    if (tNext == null) {
                        // no cause or nested Throwable - done
                        return;
                    }

                    // some of the known throwables with custom nesting don't
                    // recurse properly
                    if (pstRecursesOnNested(t)) {
                        t = tNext;
                    } else {
                        autoRecursion = false;
                    }
                }

            }
        } catch (Throwable e) {
            // Do not throw exception, add a message to PrintWriter and return
            // what we have so far.
            p.println("<Encountered exception while calculating a nested throwable>");
            p.println(e.getClass().getName() + ": " + e.getMessage());
            try {
                // Try to convert that exception into a stack trace.
                e.printStackTrace(p);
            } catch (Throwable e2) {
                p.println("<Caught exception while printing stack trace from failed nested calculation>");
                p.println(e2.getClass().getName() + ": " + e2.getMessage());
            }
            return;
        }

        // tNext will not be null at this point

        // Have found the first Throwable that doesn't include nested throwable
        // in printStackTrace
        // Obtain the nested Throwable and keep going.
        p.println("---- Begin backtrace for Nested Throwables");
        printStackTrace(tNext, p);

        /*
         * while (pstRecurses(t)) { t = getNestedThrowable(t); if (t == null)
         * return; }
         *
         * // Have found the first Throwable that doesn't override
         * printStackTrace. // Obtain the nested Throwable and keep going. t =
         * getNestedThrowable(t); if (t == null) return;
         * p.println("---- Begin backtrace for Nested Throwables");
         * printStackTrace(t, p);
         */
    }
1262976
def _debug_current_process(sig, current_frame):
    
    # Import modules only if necessary, readline is for shell history support.
    import code, traceback, readline, threading  # @UnresolvedImport @UnusedImport

    d={'_frame':current_frame}         # Allow access to frame object.
    d.update(current_frame.f_globals)  # Unless shadowed by global
    d.update(current_frame.f_locals)

    i = code.InteractiveConsole(d)
    message  = "Signal received : entering python shell.\n"

    threads = dict((thread.ident, thread) for thread in threading.enumerate())
    current_thread = threading.current_thread()
    for thread_id, frame in sys._current_frames().items():
        if current_thread.ident != thread_id:
            message += "\nTraceback of thread {}:\n".format(threads[thread_id])
            message += ''.join(traceback.format_stack(frame))
    message += "\nTraceback of current thread {}:\n".format(current_thread)
    message += ''.join(traceback.format_stack(current_frame))
    i.interact(message)
1018639
def _signal(self, sig, pid=None):
        
        log = self._params.get('log', self._discard)
        if pid is None:
            pids = self.get_pids()
        else:
            pids = [pid]
        for pid in pids:
            try:
                os.kill(pid, sig)
                log.debug("Signalled '%s' pid %d with %s", self._name, pid, utils.signame(sig))
            except Exception as e:
                log.warning("Failed to signal '%s' pid %d with %s -- %s", self._name, pid, utils.signame(sig), e)
1076319
def print_detailed_traceback(self, space=None, file=None):
        """"""
        if file is None:
            file = sys.stderr
        f = io.StringIO()
        for i in range(len(self.debug_excs)-1, -1, -1):
            print >> f, "Traceback (interpreter-level):"
            traceback.print_tb(self.debug_excs[i][2], file=f)
        f.seek(0)
        debug_print(''.join(['|| ' + line for line in f.readlines()]), file)
        if self.debug_excs:
            from pypy.tool import tb_server
            tb_server.publish_exc(self.debug_excs[-1])
        self.print_app_tb_only(file)
        print >> file, '(application-level)', self.errorstr(space)
        if AUTO_DEBUG:
            debug.fire(self)
1131681
public static void printStackTrace(Throwable e, PrintWriter out)
  {
    StackTraceElement lastHead = null;

    ClassLoader loader = SimpleLoader.create(WorkDir.getLocalWorkDir());
    
    while (true) {
      if (e.getMessage() != null)
        out.println(e.getClass().getName() + ": " + e.getMessage());
      else
        out.println(e.getClass().getName());

      StackTraceElement []trace = e.getStackTrace();
      StackTraceElement nextHead = trace.length > 0 ? trace[0] : null;

      for (int i = 0; i < trace.length; i++) {
        if (trace[i].equals(lastHead))
          break;

        out.print("\tat ");

        printStackTraceElement(trace[i], out, loader);
      }

      lastHead = nextHead;

      Throwable cause = e.getCause();

      if (cause != null) {
        out.print("Caused by: ");
        e = cause;
      }
      else
        break;
    }
  }