Prettifies a scope stack for use in error messages.

        :param list(str) stack: List of scopes.
        :param str current: The current scope. If specified, will be appended
            onto the stack before formatting.
        :returns: str
493418
def _format_stack(self, stack, current=None):
        
        if current is not None:
            stack = stack + [current]
        if len(stack) > 1:
            prefix = os.path.commonprefix(stack)
            if prefix.endswith('/'):
                prefix = prefix[:-1]
            stack = [scope[len(prefix):] for scope in stack]
        return ' => '.join(stack)
1250615
def refresh_stack(self):
        
        self.stack, _ = self.compute_stack(self.fullstack)
        # find the current frame in the new stack
        for i, (frame, _) in enumerate(self.stack):
            if frame is self.curframe:
                self.curindex = i
                break
        else:
            self.curindex = len(self.stack)-1
            self.curframe = self.stack[-1][0]
            self.print_current_stack_entry()
926143
def dump_stacks(self):
        '''
        
        '''

        dump = []

        # threads
        threads = dict([(th.ident, th.name)
                            for th in threading.enumerate()])

        for thread, frame in sys._current_frames().items():
            if thread not in threads: continue
            dump.append('Thread 0x%x (%s)\n' % (thread, threads[thread]))
            dump.append(''.join(traceback.format_stack(frame)))
            dump.append('\n')

        return ''.join(dump)
1037632
def catch(ignore=[],
          was_doing="something important",
          helpfull_tips="you should use a debugger",
          gbc=None):
    
    exc_cls, exc, tb=sys.exc_info()
    if exc_cls in ignore:
        msg='exception in ignorelist'
        gbc.say('ignoring caught:'+str(exc_cls))
        return 'exception in ignorelist'
        

    ex_message = traceback.format_exception_only(exc_cls, exc)[-1]
    ex_message = ex_message.strip()
    
    # TODO: print(ex_message)

    error_frame = tb
    while error_frame.tb_next is not None:
        error_frame = error_frame.tb_next

    file = error_frame.tb_frame.f_code.co_filename
    line = error_frame.tb_lineno
    stack = traceback.extract_tb(tb)

    formated_stack = []
    for summary in stack:
        formated_stack.append({
            'file': summary[0],
            'line': summary[1],
            'func': summary[2],
            'text': summary[3]
        })

    event = {
        'was_doing':was_doing,
        'message': ex_message,
        'errorLocation': {
            'file': file,
            'line': line,
            'full': file + ' -> ' + str(line)
        },
        'stack': formated_stack
        #,
        #'time': time.time()
    }

    try:
        #logging.info('caught:'+pformat(event))
        gbc.cry('caught:'+pformat(event))
        print('Bubble3: written error to log')
        print('Bubble3: tips for fixing this:')
        print(helpfull_tips)

    except Exception as e:
        print('Bubble3: cant log error cause of %s' % e)
194717
def _build_stack(self) -> List[Callable]:
        

        stack = []

        for m in self.manager.middlewares:
            try:
                stack.append(getattr(m(self), self.name))
            except AttributeError:
                pass

        return stack
1164109
def list_stacks(stack_ref: List[str], all: bool, remote: str, region: str,
                watch: int, output: str):
    """"""
    lizzy = setup_lizzy_client(remote)
    stack_references = parse_stack_refs(stack_ref)

    while True:
        rows = []
        for stack in lizzy.get_stacks(stack_references, region=region):
            creation_time = dateutil.parser.parse(stack['creation_time'])
            rows.append({'stack_name': stack['stack_name'],
                         'version': stack['version'],
                         'status': stack['status'],
                         'creation_time': creation_time.timestamp(),
                         'description': stack['description']})

        rows.sort(key=lambda x: (x['stack_name'], x['version']))
        with OutputFormat(output):
            print_table(
                'stack_name version status creation_time description'.split(),
                rows, styles=STYLES, titles=TITLES)

        if watch:  # pragma: no cover
            time.sleep(watch)
            click.clear()
        else:
            break
845128
def _strip_scope(msg):
    '''
    
    '''
    ret = []
    for line in msg.splitlines():
        if not line.endswith('.scope'):
            ret.append(line)
    return '\n'.join(ret).strip()
889876
def eval(lisp):
    '''
    
    '''
    macro_values = []
    if not isinstance(lisp, list):
        raise EvalError('eval root element must be a list')
    for item in lisp:
        if not isinstance(item, list):
            raise EvalError('must evaluate list of list')
        if not all(isinstance(i, str) for i in item):
            raise EvalError(
                'must evaluate list of list of strings. not a list of strings: {}'
                .format(item))
        name = item[0]
        args = item[1:]
        try:
            macro = state['macros'][name]
        except KeyError:
            raise MacroNotFoundError("macro {} not found".format(repr(name)))
        try:
            res = macro(*args)
        except Exception as exc:
            if os.getenv('PLASH_DEBUG', '').lower() in ('1', 'yes', 'true'):
                raise
            if isinstance(exc, MacroError):
                # only raise that one time and don't have multiple wrapped MacroError
                raise
            raise MacroError(macro, name, sys.exc_info())
        if not isinstance(res, str) and res is not None:
            raise EvalError(
                'eval macro must return string or None ({} returned {})'.
                format(name, type(res)))
        if res is not None:
            macro_values.append(res)
    return '\n'.join(macro_values)
868595
def scopes(self, scopes):
        
        validate_scopes(scopes)
        self._scopes = " ".join(set(scopes)) if scopes else ""
828127
def dump_stacktraces():
    
    lines = []
    for thread_id, stack in sys._current_frames().items():  # pylint: disable=W0212
        lines.append("\n######### ProcessID=%s, ThreadID=%s #########" % (
            os.getpid(), thread_id
        ))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            lines.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                lines.append("  %s" % (line.strip()))
    lines.append("#############################################\n\n")

    print('\n'.join(lines), file=sys.stderr if _MANHOLE.redirect_stderr else sys.stdout)
776788
def scope(self, scope):
        
        if scope is None:
            raise ValueError("Invalid value for `scope`, must not be `None`")  # noqa: E501
        allowed_values = ["CLUSTER", "CUSTOMER", "USER"]  # noqa: E501
        if scope not in allowed_values:
            raise ValueError(
                "Invalid value for `scope` ({0}), must be one of {1}"  # noqa: E501
                .format(scope, allowed_values)
            )

        self._scope = scope
1201248
def update_stack_list!
      if updater.nil? || !updater.alive?
        self.updater = Thread.new {
          loop do
            begin
              fetch_stacks
              sleep(stack_list_interval)
            rescue => e
              logger.error "Failure encountered on stack fetch: #{e.class} - #{e}"
            end
          end
        }
        true
      else
        false
      end
    end
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(")");
			}
		});
	}
1093975
private Context currentContext()
   {
      LinkedList<Context> stack = threadContexts.get();

      if (stack != null && !stack.isEmpty())
      {
         return stack.getLast();
      }

      return null;
   }
1288095
def current_scope(klass = nil)
      if klass && Thread.current[CURRENT_SCOPE_KEY].respond_to?(:keys)
        Thread.current[CURRENT_SCOPE_KEY][
            Thread.current[CURRENT_SCOPE_KEY].keys.find { |k| k <= klass }
        ]
      else
        Thread.current[CURRENT_SCOPE_KEY]
      end
    end
169304
def is_in_scope(cls, want_scope: str, have_scopes: List[Scope]) -> bool:
        
        if not want_scope:
            return True
        if want_scope in have_scopes or want_scope.split(':')[0] in have_scopes:
            return True
        elif want_scope.startswith('read'):
            return cls.is_in_scope(want_scope.replace('read', 'write'), have_scopes)
        elif want_scope.startswith('write'):
            return cls.is_in_scope(want_scope.replace('write', 'admin'), have_scopes)
        else:
            return False
502913
def stackToList(stack):
    
    if isinstance(stack, types.TracebackType):
        while stack.tb_next:
            stack = stack.tb_next
        stack = stack.tb_frame
    out = []
    while stack:
        out.append(stack)
        stack = stack.f_back
    return out