Returns generator that iterates over frames in a traceback
439297
def _frames(traceback):
    '''
    
    '''
    frame = traceback
    while frame.tb_next:
      frame = frame.tb_next
      yield frame.tb_frame
    return
623659
def _trace_full (frame, event, arg):
    """"""
    if event == "line":
        _trace_line(frame, event, arg)
    else:
        _trace(frame, event, arg)
    return _trace_full
7303
def iter_sources(self):
        """"""
        for src_id in xrange(self.get_source_count()):
            yield src_id, self.get_source_name(src_id)
1162321
def start_trace(
        full=False, frame=None, below=0, under=None, server=None, port=None
):
    """"""
    wdb = Wdb.get(server=server, port=port)
    if not wdb.stepping:
        wdb.start_trace(full, frame or sys._getframe().f_back, below, under)
    return wdb
1105330
def _trace(self, frame, event, arg_unused):
        
        cur_time = time.time()

        lineno = frame.f_lineno
        depth = self.depth

        filename = inspect.getfile(frame)

        if self.last_exc_back:
            if frame == self.last_exc_back:
                self.data['time_spent'] += (cur_time - self.start_time)
                self.depth -= 1

                self.data = self.data_stack.pop()

            self.last_exc_back = None

        if event == 'call':
            # Update our state
            self.depth += 1

            if self.log:
                print >> sys.stdout, '%s >> %s:%s' % (' ' * (depth - 1), filename, frame.f_code.co_name)

            # origin line number (where it was called from)
            o_lineno = frame.f_back.f_lineno

            if self.pause_until is not None:
                if depth == self.pause_until:
                    self.pause_until = None
                else:
                    return self._trace

            if o_lineno not in self.data['lines']:
                self.pause_until = depth

                return self._trace

            # Append it to the stack
            self.data_stack.append(self.data)

            call_sig = '%s:%s' % (inspect.getfile(frame), frame.f_code.co_name)

            if call_sig not in self.data['children']:
                self.data['children'][o_lineno][call_sig] = self._get_struct(frame, event)

            self.data = self.data['children'][o_lineno][call_sig]

            self.data['num_calls'] += 1

        elif event == 'line':
            # Record an executed line.
            if self.pause_until is None and lineno in self.data['lines']:
                self.data['lines'][lineno]['num_calls'] += 1
                self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time)

            if self.log:
                print >> sys.stdout, '%s -- %s:%s executing line %d' % (' ' * (depth - 1), filename, frame.f_code.co_name, lineno)

        elif event == 'return':
            timing = (cur_time - self.start_time)

            # Leaving this function, pop the filename stack.
            if self.pause_until is None:
                self.data['time_spent'] += timing
                self.data = self.data_stack.pop()
                self.data['time_spent'] += timing
                # self.data['lines'][lineno]['num_calls'] += 1
                # self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time)

            if self.log:
                print >> sys.stdout, '%s << %s:%s %.3fs' % (' ' * (depth - 1), filename, frame.f_code.co_name, timing)

            self.depth -= 1

        elif event == 'exception':
            self.last_exc_back = frame.f_back
            self.last_exc_firstlineno = frame.f_code.co_firstlineno

        return self._trace
1092936
def get_trace(self, frame, tb):
        """"""
        import linecache
        frames = []
        stack, _ = self.get_stack(frame, tb)
        current = 0

        for i, (stack_frame, lno) in enumerate(stack):
            code = stack_frame.f_code
            filename = code.co_filename or '<unspecified>'
            line = None
            if filename[0] == '<' and filename[-1] == '>':
                line = get_source_from_byte_code(code)
                fn = filename
            else:
                fn = os.path.abspath(filename)
            if not line:
                linecache.checkcache(filename)
                line = linecache.getline(filename, lno, stack_frame.f_globals)
                if not line:
                    line = self.compile_cache.get(id(code), '')
                line = to_unicode_string(line, filename)
                line = line and line.strip()
            startlnos = dis.findlinestarts(code)
            lastlineno = list(startlnos)[-1][1]
            if frame == stack_frame:
                current = i
            frames.append({
                'file': fn,
                'function': code.co_name,
                'flno': code.co_firstlineno,
                'llno': lastlineno,
                'lno': lno,
                'code': line,
                'level': i,
                'current': frame == stack_frame
            })

        # While in exception always put the context to the top
        return stack, frames, current
1029971
def get_real_last_traceback(exception):
    
    traceback_blocks = []
    _n, _n, exc_traceback = sys.exc_info()
    tb_list = get_all_tracebacks(exc_traceback)[1:]

    # Remove already captured tracebacks
    # TODO(jmv): This must be a better way of doing this. Need to revisit.
    tb_list = [tb for tb in tb_list if tb not in CAPTURED_TRACEBACKS]
    CAPTURED_TRACEBACKS.extend(tb_list)

    for traceback in tb_list:
        lines, path, line_num = get_source_from_frame(traceback.tb_frame)
        traceback_lines = get_numbered_source(lines, traceback.tb_lineno,
                                              line_num)

        traceback_lines.insert(0, '  - {0}'.format(path))
        traceback_lines.insert(1, '  ------------------')
        traceback_lines.append('  ------------------')
        traceback_blocks.append(traceback_lines)

    traced_lines = ['Error Traceback:']
    traced_lines.extend(itertools.chain.from_iterable(traceback_blocks))
    traced_lines.append('  - Error | {0}: {1}'.format(
        type(exception).__name__, exception))

    return traced_lines
1093415
def tracebacks_from_file(fileobj, reverse=False):
    

    if reverse:
        lines = deque()

        for line in BackwardsReader(fileobj):
            lines.appendleft(line)
            if tb_head in line:
                yield next(tracebacks_from_lines(lines))
                lines.clear()
    else:
        for traceback in tracebacks_from_lines(fileobj):
            yield traceback
1145500
def _next_trace_frames(
        self,
        session: Session,
        trace_frame: TraceFrameQueryResult,
        visited_ids: Set[int],
        backwards: bool = False,
    ) -> List[TraceFrameQueryResult]:
        
        query = (
            session.query(
                TraceFrame.id,
                TraceFrame.caller_id,
                CallerText.contents.label("caller"),
                TraceFrame.caller_port,
                TraceFrame.callee_id,
                CalleeText.contents.label("callee"),
                TraceFrame.callee_port,
                TraceFrame.callee_location,
                TraceFrame.kind,
                FilenameText.contents.label("filename"),
                TraceFrameLeafAssoc.trace_length,
            )
            .filter(TraceFrame.run_id == self.current_run_id)
            .filter(TraceFrame.kind == trace_frame.kind)
            .join(CallerText, CallerText.id == TraceFrame.caller_id)
            .join(CalleeText, CalleeText.id == TraceFrame.callee_id)
            .join(FilenameText, FilenameText.id == TraceFrame.filename_id)
            .filter(
                TraceFrame.caller_id != TraceFrame.callee_id
            )  # skip recursive calls for now
        )
        if backwards:
            query = query.filter(TraceFrame.callee_id == trace_frame.caller_id).filter(
                TraceFrame.callee_port == trace_frame.caller_port
            )
        else:
            query = query.filter(TraceFrame.caller_id == trace_frame.callee_id).filter(
                TraceFrame.caller_port == trace_frame.callee_port
            )

        results = (
            query.join(
                TraceFrameLeafAssoc, TraceFrameLeafAssoc.trace_frame_id == TraceFrame.id
            )
            .group_by(TraceFrame.id)
            .order_by(TraceFrameLeafAssoc.trace_length, TraceFrame.callee_location)
        )
        filter_leaves = (
            self.sources if trace_frame.kind == TraceKind.POSTCONDITION else self.sinks
        )

        filtered_results = []
        for frame in results:
            if int(frame.id) not in visited_ids and filter_leaves.intersection(
                set(
                    self._get_leaves_trace_frame(
                        session,
                        int(frame.id),
                        self._trace_kind_to_shared_text_kind(frame.kind),
                    )
                )
            ):
                filtered_results.append(frame)

        return filtered_results
629017
def trace():
    
    import traceback, inspect, sys
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    filename = inspect.getfile(inspect.currentframe())
    # script name + line number
    line = tbinfo.split(", ")[1]
    # Get Python syntax error
    #
    synerror = traceback.format_exc().splitlines()[-1]
    return line, filename, synerror
1333343
def render_summary(self, app, include_title=True):
        """"""
        title = ''
        frames = []
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = text_('Syntax Error')
            else:
                title = text_('Traceback <small>(most recent call last)'
                              '</small>')

        for frame in self.frames:
            txt = frame.info
            if not txt:
                txt = text_(' title="%s"' % escape(frame.info))
            if not txt:
                txt = text_('')
            frames.append(
                text_('<li%s>%s') % (txt, frame.render()))

        if self.is_syntax_error:
            description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
        else:
            description_wrapper = text_('<blockquote>%s</blockquote>')
        vars = {
            'classes': text_(' '.join(classes)),
            'title': title and text_('<h3 class="traceback">%s</h3>'
                                     % title) or text_(''),
            'frames': text_('\n'.join(frames)),
            'description': description_wrapper % escape(self.exception),
        }
        return render('exception_summary.jinja2', app, vars)
188856
def tracing(pattern=None, out=None):
    """"""
    _trace = partial(trace_line, pattern)

    if out is None:
        out = sys.stdout

    with redirect_stdout(out):
        sys.settrace(_trace)
        try:
            yield
        finally:
            sys.settrace(None)
1200834
def frame_generator(self):
        """"""
        if self.input_rate == self.RATE_PROCESS:
            while True:
                yield self.read()
        else:
            while True:
                yield self.read_resampled()
709326
def threads_bt(self):
        """"""
        import threading
        import traceback

        threads = {}
        for thread in threading.enumerate():
            frames = sys._current_frames().get(thread.ident)
            if frames:
                stack = traceback.format_stack(frames)
            else:
                stack = []
            threads[thread] = "".join(stack)
        return flask.render_template("gourde/threads.html", threads=threads)
1229423
def get_frames(self):
        ""
        nb_frames = self.input_totalframes // self.output_blocksize

        if self.input_totalframes % self.output_blocksize == 0:
            nb_frames -= 1  # Last frame must send eod=True

        for index in xrange(0,
                            nb_frames * self.output_blocksize,
                            self.output_blocksize):
            yield (self.samples[index:index + self.output_blocksize], False)

        yield (self.samples[nb_frames * self.output_blocksize:], True)
211917
def _BacktraceFromFramePtr(self, frame_ptr):
    """"""
    # expects frame_ptr to be a gdb.Value
    frame_objs = [PyFrameObjectPtr(frame) for frame
                  in self._IterateChainedList(frame_ptr, 'f_back')]

    # We want to output tracebacks in the same format python uses, so we have to
    # reverse the stack
    frame_objs.reverse()
    tb_strings = ['Traceback (most recent call last):']
    for frame in frame_objs:
      line_string = ('  File "%s", line %s, in %s' %
                     (frame.filename(),
                      str(frame.current_line_num()),
                      frame.co_name.proxyval(set())))
      tb_strings.append(line_string)
      line_string = '    %s' % frame.current_line().strip()
      tb_strings.append(line_string)
    return '\n'.join(tb_strings)
111745
def build_exception_info_response(dbg, thread_id, request_seq, set_additional_thread_info, iter_visible_frames_info, max_frames):
    '''
    
    '''
    thread = pydevd_find_thread_by_id(thread_id)
    additional_info = set_additional_thread_info(thread)
    topmost_frame = additional_info.get_topmost_frame(thread)

    frames = []
    exc_type = None
    exc_desc = None
    if topmost_frame is not None:
        frame_id_to_lineno = {}
        try:
            trace_obj = None
            frame = topmost_frame
            while frame is not None:
                if frame.f_code.co_name == 'do_wait_suspend' and frame.f_code.co_filename.endswith('pydevd.py'):
                    arg = frame.f_locals.get('arg', None)
                    if arg is not None:
                        exc_type, exc_desc, trace_obj = arg
                        break
                frame = frame.f_back

            while trace_obj.tb_next is not None:
                trace_obj = trace_obj.tb_next

            info = dbg.suspended_frames_manager.get_topmost_frame_and_frame_id_to_line(thread_id)
            if info is not None:
                topmost_frame, frame_id_to_lineno = info

            if trace_obj is not None:
                for frame_id, frame, method_name, original_filename, filename_in_utf8, lineno in iter_visible_frames_info(
                        dbg, trace_obj.tb_frame, frame_id_to_lineno):

                    line_text = linecache.getline(original_filename, lineno)

                    # Never filter out plugin frames!
                    if not getattr(frame, 'IS_PLUGIN_FRAME', False):
                        if dbg.is_files_filter_enabled and dbg.apply_files_filter(frame, original_filename, False):
                            continue
                    frames.append((filename_in_utf8, lineno, method_name, line_text))
        finally:
            topmost_frame = None

    name = 'exception: type unknown'
    if exc_type is not None:
        try:
            name = exc_type.__qualname__
        except:
            try:
                name = exc_type.__name__
            except:
                try:
                    name = str(exc_type)
                except:
                    pass

    description = 'exception: no description'
    if exc_desc is not None:
        try:
            description = str(exc_desc)
        except:
            pass

    stack_str = ''.join(traceback.format_list(frames[-max_frames:]))

    # This is an extra bit of data used by Visual Studio
    source_path = frames[0][0] if frames else ''

    if thread.stop_reason == CMD_STEP_CAUGHT_EXCEPTION:
        break_mode = pydevd_schema.ExceptionBreakMode.ALWAYS
    else:
        break_mode = pydevd_schema.ExceptionBreakMode.UNHANDLED

    response = pydevd_schema.ExceptionInfoResponse(
        request_seq=request_seq,
        success=True,
        command='exceptionInfo',
        body=pydevd_schema.ExceptionInfoResponseBody(
            exceptionId=name,
            description=description,
            breakMode=break_mode,
            details=pydevd_schema.ExceptionDetails(
                message=description,
                typeName=name,
                stackTrace=stack_str,
                source=source_path
            )
        )
    )
    return response