Show source code around the current trace frame location.

        Parameters:
            context: int    number of lines to show above and below trace location
                            (default: 5)
174942
def list_source_code(self, context: int = 5) -> None:
        
        self._verify_entrypoint_selected()

        current_trace_frame = self.trace_tuples[
            self.current_trace_frame_index
        ].trace_frame

        filename = os.path.join(self.repository_directory, current_trace_frame.filename)
        file_lines: List[str] = []

        try:
            # Use readlines instead of enumerate(file) because mock_open
            # doesn't support __iter__ until python 3.7.1.
            with open(filename, "r") as file:
                file_lines = file.readlines()
        except FileNotFoundError:
            self.warning(f"Couldn't open {filename}.")
            return

        self._output_file_lines(current_trace_frame, file_lines, context)
469291
def debug(text):
    
    frame = inspect.currentframe().f_back
    module = frame.f_globals['__name__']
    func = frame.f_code.co_name
    msg = "%s.%s: %s" % (module, func, text)
    _LOGGER.debug(msg)
672599
def view_context(self):
        
        url = self.get_selected_item().get('context')
        if url:
            self.selected_page = self.open_submission_page(url)
474818
def _format_trace(trace):
    
    lines = []
    for fname, lineno, func, src, _ in trace:
        if src:
            for line in src:
                lines.append('    '+line.strip()+'\n')
        lines.append('  %s:%4d in %s\n' % (fname, lineno, func))
    return ''.join(lines)
965710
def default_should_trace_hook(frame, filename):
    '''
    
    '''
    # First, check whether this code object has a cached value
    ignored_lines = _filename_to_ignored_lines.get(filename)
    if ignored_lines is None:
        # Now, look up that line of code and check for a @DontTrace
        # preceding or on the same line as the method.
        # E.g.:
        # #@DontTrace
        # def test():
        #     pass
        #  ... or ...
        # def test(): #@DontTrace
        #     pass
        ignored_lines = {}
        lines = linecache.getlines(filename)
        for i_line, line in enumerate(lines):
            j = line.find('#')
            if j >= 0:
                comment = line[j:]
                if DONT_TRACE_TAG in comment:
                    ignored_lines[i_line] = 1
                    
                    #Note: when it's found in the comment, mark it up and down for the decorator lines found.
                    k = i_line - 1
                    while k >= 0:
                        if RE_DECORATOR.match(lines[k]):
                            ignored_lines[k] = 1
                            k -= 1
                        else:
                            break
                        
                    k = i_line + 1
                    while k <= len(lines):
                        if RE_DECORATOR.match(lines[k]):
                            ignored_lines[k] = 1
                            k += 1
                        else:
                            break
                        

        _filename_to_ignored_lines[filename] = ignored_lines

    func_line = frame.f_code.co_firstlineno - 1 # co_firstlineno is 1-based, so -1 is needed
    return not (
        func_line - 1 in ignored_lines or #-1 to get line before method 
        func_line in ignored_lines)
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
693608
def from_traceback(cls, tb):
        
        while tb.tb_next:
            tb = tb.tb_next
        return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)
187273
def create_context_location(source_input,
                                document: nil,
                                pointer_segments: [])
      source = if !document
                 Openapi3Parser::Document.new(source_input).root_source
               else
                 Openapi3Parser::Source.new(
                   source_input,
                   document,
                   Openapi3Parser::Document::ReferenceRegister.new
                 )
               end

      Openapi3Parser::Context::Location.new(source, pointer_segments)
    end
870548
def commented_out_code_lines(source):
    
    line_numbers = []
    try:
        for t in generate_tokens(source):
            token_type = t[0]
            token_string = t[1]
            start_row = t[2][0]
            line = t[4]

            # Ignore inline comments.
            if not line.lstrip().startswith('#'):
                continue

            if token_type == tokenize.COMMENT:
                stripped_line = token_string.lstrip('#').strip()
                if (
                    ' ' in stripped_line and
                    '#' not in stripped_line and
                    check_syntax(stripped_line)
                ):
                    line_numbers.append(start_row)
    except (SyntaxError, tokenize.TokenError):
        pass

    return line_numbers
1256327
def context(src):
    
    try:
        yield
    except Exception:
        etype, err, tb = sys.exc_info()
        msg = 'An error occurred with source id=%s. Error: %s'
        msg %= (src.source_id, err)
        raise_(etype, msg, tb)
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)
230039
def find_source_lines(self):
        """"""
        strs = trace.find_strings(self.filename)
        lines = trace.find_lines_from_code(self.fn.__code__, strs)
        self.firstcodelineno = sys.maxint
        for lineno in lines:
            self.firstcodelineno = min(self.firstcodelineno, lineno)
            self.sourcelines.setdefault(lineno, 0)
        if self.firstcodelineno == sys.maxint:
            self.firstcodelineno = self.firstlineno
123192
public static void ensureScopeUsesRequestContext(Tracing tracing) {
        final PingPongExtra extra = new PingPongExtra();
        // trace contexts are not recorded until Tracer.toSpan, so this won't end up as junk data
        final TraceContext dummyContext = TraceContext.newBuilder().traceId(1).spanId(1)
                                                      .extra(Collections.singletonList(extra)).build();
        final boolean scopeUsesRequestContext;
        try (Scope scope = tracing.currentTraceContext().newScope(dummyContext)) {
            scopeUsesRequestContext = extra.isPong();
        }
        if (!scopeUsesRequestContext) {
            throw new IllegalStateException(
                    "Tracing.currentTraceContext is not a " + RequestContextCurrentTraceContext.class
                            .getSimpleName() + " scope. " +
                    "Please call Tracing.Builder.currentTraceContext(" + RequestContextCurrentTraceContext.class
                            .getSimpleName() + ".INSTANCE).");
        }
    }
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()
1106053
def _initialize_context(self, trace_header):
        
        sampled = None
        if not global_sdk_config.sdk_enabled():
            # Force subsequent subsegments to be disabled and turned into DummySegments.
            sampled = False
        elif trace_header.sampled == 0:
            sampled = False
        elif trace_header.sampled == 1:
            sampled = True

        segment = FacadeSegment(
            name='facade',
            traceid=trace_header.root,
            entityid=trace_header.parent,
            sampled=sampled,
        )
        setattr(self._local, 'segment', segment)
        setattr(self._local, 'entities', [])
1212171
def _short_traceback(skip=3):
  """"""
  counter, res = 0, []
  # Skipping 3 lines by default: the top (useless) and self-call.
  lines = traceback.format_exc().splitlines()[skip:]
  for l in lines:
    res.append(_shorten_file_path(l))
    if counter % 2 == 1:
      res.append('')
    counter += 1
    # If we see a LayerError, the traceback has already been processed.
    if l.startswith('LayerError'):
      # Skip 4 back except last as these are internal base-layer calls.
      res = res[:-4] + [res[-1]]
      res += lines[counter:]
      break
  return '\n'.join(res)
907950
def get_traceback_frames(self):
        """"""
        frames = []
        tb = self.tb
        while tb is not None:
            # Support for __traceback_hide__ which is used by a few libraries
            # to hide internal frames.
            if tb.tb_frame.f_locals.get('__traceback_hide__'):
                tb = tb.tb_next
                continue
            filename = tb.tb_frame.f_code.co_filename
            function = tb.tb_frame.f_code.co_name
            lineno = tb.tb_lineno - 1
            loader = tb.tb_frame.f_globals.get('__loader__')
            module_name = tb.tb_frame.f_globals.get('__name__') or ''
            pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file(
                filename, lineno, 7, loader, module_name,
            )
            if pre_context_lineno is not None:
                frames.append({
                    'tb': tb,
                    'type': 'django' if module_name.startswith('django.') else 'user',
                    'filename': filename,
                    'function': function,
                    'lineno': lineno + 1,
                    'vars': list(six.iteritems(tb.tb_frame.f_locals)),
                    'id': id(tb),
                    'pre_context': pre_context,
                    'context_line': context_line,
                    'post_context': post_context,
                    'pre_context_lineno': pre_context_lineno + 1,
                })
            tb = tb.tb_next

        return frames