Given a traceback object, it will iterate over all
    frames that do not contain the ``__traceback_hide__``
    local variable.
765181
def iter_traceback_frames(tb):
    
    # Some versions of celery have hacked traceback objects that might
    # miss tb_frame.
    while tb and hasattr(tb, 'tb_frame'):
        # support for __traceback_hide__ which is used by a few libraries
        # to hide internal frames.
        f_locals = getattr(tb.tb_frame, 'f_locals', {})
        if not _getitem_from_frame(f_locals, '__traceback_hide__'):
            yield tb.tb_frame, getattr(tb, 'tb_lineno', None)
        tb = tb.tb_next
312448
def _trace(self, frame, event, arg):
        

        # Return if this is not a function call
        if event != 'call':
            return

        # Filter calling and called functions by module names
        src_mod = current_module_name(frame.f_back)
        dst_mod = current_module_name(frame)

        # Avoid tracing the tracer (specifically, call from
        # ContextCallTracer.__exit__ to CallTracer.stop)
        if src_mod == __modulename__ or dst_mod == __modulename__:
            return

        # Apply source and destination module filters
        if not self.srcmodflt.match(src_mod):
            return
        if not self.dstmodflt.match(dst_mod):
            return

        # Get calling and called functions
        src_func = current_function(frame.f_back)
        dst_func = current_function(frame)

        # Filter calling and called functions by qnames
        if not self.srcqnmflt.match(function_qname(src_func)):
            return
        if not self.dstqnmflt.match(function_qname(dst_func)):
            return

        # Get calling and called function full names
        src_name = function_fqname(src_func)
        dst_name = function_fqname(dst_func)

        # Modify full function names if necessary
        if self.fnmsub is not None:
            src_name = re.sub(self.fnmsub[0], self.fnmsub[1], src_name)
            dst_name = re.sub(self.fnmsub[0], self.fnmsub[1], dst_name)

        # Update calling function count
        if src_func is not None:
            if src_name in self.fncts:
                self.fncts[src_name][0] += 1
            else:
                self.fncts[src_name] = [1, 0]

        # Update called function count
        if dst_func is not None and src_func is not None:
            if dst_name in self.fncts:
                self.fncts[dst_name][1] += 1
            else:
                self.fncts[dst_name] = [0, 1]

        # Update caller/calling pair count
        if dst_func is not None and src_func is not None:
            key = (src_name, dst_name)
            if key in self.calls:
                self.calls[key] += 1
            else:
                self.calls[key] = 1
364666
def tracer(object):
    

    @functools.wraps(object)
    @functools.partial(validate_tracer, object)
    def tracer_wrapper(*args, **kwargs):
        """
        Traces execution.

        :param \*args: Arguments.
        :type \*args: \*
        :param \*\*kwargs: Keywords arguments.
        :type \*\*kwargs: \*\*
        :return: Object.
        :rtype: object
        """

        code = object.func_code
        args_count = code.co_argcount
        args_names = code.co_varnames[:args_count]
        function_defaults = object.func_defaults or list()
        args_defaults = dict(zip(args_names[-len(function_defaults):], function_defaults))

        positional_args = map(format_argument, zip(args_names, args))
        defaulted_args = [format_argument((name, args_defaults[name]))
                          for name in args_names[len(args):] if name not in kwargs]
        nameless_args = map(repr, args[args_count:])
        keyword_args = map(format_argument, kwargs.items())
        sys.stdout.write("{0}({1})\n".format(get_trace_name(object),
                                             ", ".join(itertools.chain(positional_args,
                                                                       defaulted_args,
                                                                       nameless_args,
                                                                       keyword_args))))
        return object(*args, **kwargs)

    return tracer_wrapper
236801
def search_stack_for_var(varname, verbose=util_arg.NOT_QUIET):
    
    curr_frame = inspect.currentframe()
    if verbose:
        print(' * Searching parent frames for: ' + six.text_type(varname))
    frame_no = 0
    while curr_frame.f_back is not None:
        if varname in curr_frame.f_locals.keys():
            if verbose:
                print(' * Found local in frame: ' + six.text_type(frame_no))
            return curr_frame.f_locals[varname]
        if varname in curr_frame.f_globals.keys():
            if verbose:
                print(' * Found global in frame: ' + six.text_type(frame_no))
            return curr_frame.f_globals[varname]
        frame_no += 1
        curr_frame = curr_frame.f_back
    if verbose:
        print('... Found nothing in all ' + six.text_type(frame_no) + ' frames.')
    return None
525429
private static void traceBack(int[] pre, int currafp0, int twist, FatCatParameters params, AFPChain afpChain,Atom[] ca1, Atom[]ca2)
	{

		afpChain.setConn(0d);
		afpChain.setDVar(0d);

		int minLen = afpChain.getMinLen();
		List<AFP> afpSet = afpChain.getAfpSet();

		int afpChainLen = 0;

		//trace-back from currafp (maxsco)
		int[]     afpchain    = new int[minLen];
		int[]     afptwibin   = new int[minLen];
		double[]  afptwilist  = new double[minLen];
		int       currafp = currafp0;
		int       s = 0;

		afptwibin[s] = 0;
		afpchain[s ++] = currafp;

		boolean isConnected = false;
		int     prevafp;
		// int     alnlen = afpSet.get(afpchain[s]).getFragLen();

		//Double  conn = new Double(0) ;
		//Double dvar =  new Double(0);

		while((prevafp = pre[currafp]) != -1)   {

			isConnected = afpPairConn(prevafp, currafp, params,afpChain);

			if ( isConnected )
				afptwibin[s - 1] = 1;
			else
				afptwibin[s - 1] = 0;
			Double dvar = afpChain.getDVar();
			afptwilist[s - 1] = dvar;
			//note s - 1: the transformation of prevafp-currafp is recorded in currafp
			currafp = prevafp;
			// alnlen += afpSet.get(currafp).getFragLen();
			afpchain[s ++] = currafp;
		}

		afpChainLen = s;
		afpChain.setAfpChainLen(afpChainLen);

		//first afp without transformation
		if ( isConnected)
			afptwibin[s - 1] = 1;
		else
			afptwibin[s - 1] = 0;

		//if(debug)
		//   System.out.println(String.format("including %d AFPs, %d residues\n", afpChainLen, alnlen));

		//record the optimal alignment in afpChainList (afpChainLen)

		int[] afpChainList = afpChain.getAfpChainList();
		double[] afpChainTwiBin = afpChain.getAfpChainTwiBin();
		double[] afpChainTwiList = afpChain.getAfpChainTwiList();

		if(afpChainList == null)        {
			afpChainList   = new int[s];
			afpChain.setAfpChainList(afpChainList);
			afpChainTwiBin     = new double[s];
			afpChain.setAfpChainTwiBin(afpChainTwiBin);
			afpChainTwiList = new double[s];
			afpChain.setAfpChainTwiList(afpChainTwiList);
		}

		int afpChainTwiNum = afpChain.getAfpChainTwiNum();

		int     i;
		for(i = 0; i < s; i ++) {
			afpChainList[i]     = afpchain[s - 1 - i];
			afpChainTwiBin[i]   = afptwibin[s - 1 - i];
			afpChainTwiList[i]  = afptwilist[s - 1 - i];
			afpChainTwiNum      += afptwibin[s - 1 - i];
		}

		if(afpChainTwiNum != twist)     {
			System.err.println(String.format("AFPChainer Warning: the twists number is not consistent %d %d\n", afpChainTwiNum, twist));
		}

		double alignScore = afpChain.getAlignScore();

		double  checkscore = afpSet.get(afpChainList[0]).getScore();
		for(i = 1; i < afpChainLen; i ++)       {
			isConnected = afpPairConn(afpChainList[i - 1], afpChainList[i], params,afpChain);
			checkscore = checkscore + afpSet.get(afpChainList[i]).getScore() + afpChain.getConn();
		}
		if(Math.abs(checkscore - alignScore) > 1e-4)        {
			System.err.println(String.format("AFPChainer Warning: fail in alignment score checking %.4f %.4f\n", alignScore, checkscore));
		}

		if ( debug )
			System.out.println("traceBack:" + afpChainLen + " " + afpChainList.length);
		double  rmsd = calAfpRmsd(afpChainLen, afpChainList,0, afpChain,ca1,ca2);
		afpChain.setChainRmsd(rmsd);
		if (debug )
			System.out.println("Chain RMSD: " + rmsd);
		int     b1 = 0;
		int     bk = 0;
		int     a, b;
		afpChain.setChainLen( 0);
		int chainLen       = afpChain.getChainLen();
		int[] block2Afp = afpChain.getBlock2Afp();


		double[] blockRmsd = afpChain.getBlockRmsd();
		int[] blockSize = afpChain.getBlockSize();

		block2Afp[0] = 0;
		for(i = 0; i < afpChainLen; i ++)       {
			a = afpChainList[i];
			chainLen += afpSet.get(a).getFragLen();
			if(i > 0)       {
				b = afpChainList[i - 1];
				int misLen = afpChain.getMisLen();
				misLen += calcMismatch(afpSet.get(a),afpSet.get(b));
				afpChain.setMisLen(misLen);
				int gapLen = afpChain.getGapLen();
				gapLen += calcGap(afpSet.get(a),afpSet.get(b));
				afpChain.setGapLen(gapLen);

			}

			if(afpChainTwiBin[i] == 1)   {
				if (debug)
					System.out.println(" ** calAfpTmsd : afpChainWtiBin == 1 : i: "+i+" i-b1: " + (i-b1) + " b1: " + b1 + " afpChainList.len: " + afpChainList.length);

				//int len = afpChainList.length - b1 +1;
				//int[] fakeList = new int[len];
				//int pos = -1;
				//for ( int fPos = b1 ; fPos< afpChainList.length ; fPos++){
				//   pos++;
				//   fakeList[pos] = afpChainList[fPos];
				//}
				if (debug )
					System.err.println("calculation calAfpRmsd " + i + " " + b1 + " " );


				rmsd = calAfpRmsd(i - b1, afpChainList,b1, afpChain, ca1, ca2);


				blockRmsd[bk] = rmsd;
				blockSize[bk] = i - b1;
				b1 = i;

				//System.out.println("block2Afp.length:"+ block2Afp.length + " " + bk + " " + i + " " + afpChain.getMaxTra() );
				block2Afp[++bk] = i; //next-block
			}
		}
		afpChain.setBlock2Afp(block2Afp);
		afpChain.setChainLen(chainLen);

		if (debug)
			System.out.println("after loop over all afpChainList " + (i-b1) + " " + b1);

		rmsd = calAfpRmsd(i - b1, afpChainList, b1, afpChain,ca1,ca2);
		if (debug)
			System.out.println("*** i:" + i + " b1: " + b1 + " i-b1 " + (i-b1));



		// argh this is the block RMSD, not the chain RMSD!
		//afpChain.setChainRmsd(rmsd);
		//rmsd = calAfpRmsd(i - b1, afpChainList[b1]);
		blockSize[bk] = i - b1;
		blockRmsd[bk] = rmsd;

		afpChain.setBlockSize(blockSize);
		afpChain.setBlockRmsd(blockRmsd);
		int blockNum = afpChain.getBlockNum();
		blockNum = ++bk;
		if ( debug)
			System.err.println("AFPChainser setBlockNUm:" + blockNum);
		afpChain.setBlockNum(blockNum);
		afpChain.setAfpChainList(afpChainList);
		afpChain.setAfpChainTwiList(afpChainTwiList);

	}
794093
def _trace (frame, event, arg):
    """"""
    if event in ('call', 'c_call'):
        _trace_line(frame, event, arg)
    elif event in ('return', 'c_return'):
        _trace_line(frame, event, arg)
        print("  return:", arg)
    #elif event in ('exception', 'c_exception'):
    #    _trace_line(frame, event, arg)
    return _trace
63699
def get_ref_free_exc_info():
    ""
    type, val, tb = sys.exc_info()
    traceback.clear_frames(tb)
    return (type, val, tb)
1057236
def translate_exception(exc_info, initial_skip=0):
    
    tb = exc_info[2]
    frames = []

    # skip some internal frames if wanted
    for x in range(initial_skip):
        if tb is not None:
            tb = tb.tb_next
    initial_tb = tb

    while tb is not None:
        # skip frames decorated with @internalcode.  These are internal
        # calls we can't avoid and that are useless in template debugging
        # output.
        if tb.tb_frame.f_code in internal_code:
            tb = tb.tb_next
            continue

        # save a reference to the next frame if we override the current
        # one with a faked one.
        next = tb.tb_next

        # fake template exceptions
        template = tb.tb_frame.f_globals.get('__TK_template_info__')
        if template is not None:
            lineno = template.get_corresponding_lineno(tb.tb_lineno)
            tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
                               lineno)[2]

        frames.append(make_frame_proxy(tb))
        tb = next

    # if we don't have any exceptions in the frames left, we have to reraise it unchanged. XXX: can we backup here?  when could this happen?
    if not frames:
        reraise(exc_info[0], exc_info[1], exc_info[2])

    return ProcessedTraceback(exc_info[0], exc_info[1], frames)
535857
def CaptureFrameLocals(self, frame):
    
    # Capture all local variables (including method arguments).
    variables = {n: self.CaptureNamedVariable(n, v, 1,
                                              self.default_capture_limits)
                 for n, v in six.viewitems(frame.f_locals)}

    # Split between locals and arguments (keeping arguments in the right order).
    nargs = frame.f_code.co_argcount
    if frame.f_code.co_flags & inspect.CO_VARARGS: nargs += 1
    if frame.f_code.co_flags & inspect.CO_VARKEYWORDS: nargs += 1

    frame_arguments = []
    for argname in frame.f_code.co_varnames[:nargs]:
      if argname in variables: frame_arguments.append(variables.pop(argname))

    return (frame_arguments, list(six.viewvalues(variables)))
32084
def _populate_trace(self, graph: TraceGraph, trace_frame_ids: List[int]) -> None:
        
        while len(trace_frame_ids) > 0:
            trace_frame_id = trace_frame_ids.pop()
            if trace_frame_id in self._visited_trace_frame_ids:
                continue

            trace_frame = graph._trace_frames[trace_frame_id]
            self._add_trace_frame(graph, trace_frame)
            self._visited_trace_frame_ids.add(trace_frame_id)

            key = (trace_frame.callee_id.local_id, trace_frame.callee_port)
            trace_frame_ids.extend(
                [
                    trace_frame_id
                    for trace_frame_id in graph._trace_frames_map[key]
                    if trace_frame_id not in self._visited_trace_frame_ids
                    and graph._trace_frames[trace_frame_id].kind == trace_frame.kind
                ]
            )
1070579
def _group_trace_frames(
        self, trace_frames: Iterable[TraceFrameQueryResult], limit: int
    ) -> Dict[Tuple[str, str], List[TraceFrameQueryResult]]:
        
        # pyre-fixme[9]: caller_buckets has type `DefaultDict[Tuple[str, str], List[T...
        caller_buckets: DefaultDict[
            Tuple[str, str], List[TraceFrameQueryResult]
        ] = defaultdict(list)
        for trace_frame in itertools.islice(trace_frames, limit):
            caller_buckets[(trace_frame.caller, trace_frame.caller_port)].append(
                trace_frame
            )
        return caller_buckets
1081753
def _populate_issues_from_affected_trace_frames(self, graph: TraceGraph) -> None:
        

        initial_trace_frames = [
            trace_frame
            for trace_frame in graph._trace_frames.values()
            if self._is_filename_prefixed_with(
                graph.get_text(trace_frame.filename_id), self._affected_files
            )
        ]

        self._populate_issues_from_affected_conditions(
            initial_trace_frames,
            graph,
            lambda trace_frame_id: (
                graph._trace_frame_issue_instance_assoc[trace_frame_id]
            ),
            lambda trace_frame: (
                [
                    graph._trace_frames[trace_frame_id]
                    for trace_frame_id in graph._trace_frames_rev_map[
                        (trace_frame.caller_id.local_id, trace_frame.caller_port)
                    ]
                    if graph._trace_frames[trace_frame_id].kind == trace_frame.kind
                ]
            ),
            lambda instance_id: (self._get_leaf_names(graph, instance_id)),
            lambda trace_frame_id: (
                self._get_leaf_names_from_pairs(
                    graph, graph._trace_frame_leaf_assoc[trace_frame_id]
                )
            ),
            lambda instance, trace_frame: (
                self.add_issue_instance_trace_frame_assoc(instance, trace_frame)
            ),
            lambda trace_frame_id: (
                self._add_trace_frame(graph, graph._trace_frames[trace_frame_id])
            ),
            lambda initial_trace_frame_ids: (
                self._populate_trace(graph, initial_trace_frame_ids)
            ),
        )
491603
def analyze_traceback(tb, inspection_level=None, limit=None):
    
    info = []
    tb_level = tb
    extracted_tb = traceback.extract_tb(tb, limit=limit)
    for ii, (filepath, line, module, code) in enumerate(extracted_tb):
        func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame)

        d = {"File": filepath,
             "Error Line Number": line,
             "Module": module,
             "Error Line": code,
             "Module Line Number": func_lineno,
             "Custom Inspection": {},
             "Source Code": ''}
        if inspection_level is None or len(extracted_tb) - ii <= inspection_level:
            # Perform advanced inspection on the last `inspection_level` tracebacks.
            d['Source Code'] = ''.join(func_source)
            d['Local Variables'] = get_local_references(tb_level)
            d['Object Variables'] = get_object_references(tb_level, d['Source Code'])
        tb_level = getattr(tb_level, 'tb_next', None)
        info.append(d)

    return info
983974
def set_trace(self, frame=None):
        
        if hasattr(local, '_pdbpp_completing'):
            # Handle set_trace being called during completion, e.g. with
            # fancycompleter's attr_matches.
            return
        if frame is None:
            frame = sys._getframe().f_back
        self._via_set_trace_frame = frame
        return super(Pdb, self).set_trace(frame)
348817
def format_frame_info(frame):
    
    # Same as in traceback.extract_stack
    line_no = frame.f_lineno
    code = frame.f_code
    filename = code.co_filename
    method_name = code.co_name
    linecache.checkcache(filename)

    try:
        # Try to get the type of the calling object
        instance = frame.f_locals["self"]
        method_name = "{0}::{1}".format(type(instance).__name__, method_name)
    except KeyError:
        # Not called from a bound method
        pass

    # File & line
    output_lines = [
        '  File "{0}", line {1}, in {2}'.format(filename, line_no, method_name)
    ]

    # Arguments
    if frame.f_locals:
        # Pypy keeps f_locals as an empty dictionary
        arg_info = inspect.getargvalues(frame)
        for name in arg_info.args:
            try:
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )
            except TypeError:
                # Happens in dict/list-comprehensions in Python 2.x
                name = name[0]
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )

        if arg_info.varargs:
            output_lines.append(
                "    - *{0:s} = {1}".format(
                    arg_info.varargs, frame.f_locals[arg_info.varargs]
                )
            )

        if arg_info.keywords:
            output_lines.append(
                "    - **{0:s} = {1}".format(
                    arg_info.keywords, frame.f_locals[arg_info.keywords]
                )
            )

    # Line block
    lines = _extract_lines(filename, frame.f_globals, line_no, 3)
    if lines:
        output_lines.append("")
        prefix = "      "
        output_lines.append(
            "{0}{1}".format(prefix, "\n{0}".format(prefix).join(lines))
        )
    return "\n".join(output_lines)
335178
def stop_trace(self, frame=None):
        """"""
        self.tracing = False
        self.full = False
        frame = frame or sys._getframe().f_back
        while frame:
            del frame.f_trace
            frame = frame.f_back
        sys.settrace(None)
        log.info('Stopping trace')
589588
def translate_exception(exc_info, initial_skip=0):
    
    tb = exc_info[2]
    frames = []

    # skip some internal frames if wanted
    for x in xrange(initial_skip):
        if tb is not None:
            tb = tb.tb_next
    initial_tb = tb

    while tb is not None:
        # skip frames decorated with @internalcode.  These are internal
        # calls we can't avoid and that are useless in template debugging
        # output.
        if tb.tb_frame.f_code in internal_code:
            tb = tb.tb_next
            continue

        # save a reference to the next frame if we override the current
        # one with a faked one.
        next = tb.tb_next

        # fake template exceptions
        template = tb.tb_frame.f_globals.get('__jinja_template__')
        if template is not None:
            lineno = template.get_corresponding_lineno(tb.tb_lineno)
            tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
                               lineno)[2]

        frames.append(TracebackFrameProxy(tb))
        tb = next

    # if we don't have any exceptions in the frames left, we have to
    # reraise it unchanged.
    # XXX: can we backup here?  when could this happen?
    if not frames:
        raise exc_info[0], exc_info[1], exc_info[2]

    traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames)
    if tb_set_next is not None:
        traceback.chain_frames()
    return traceback