Return a format string for printing an `expr_type`
        ket/bra/ketbra/braket
830
def _braket_fmt(self, expr_type):
        """"""
        if self._settings['unicode_sub_super']:
            sub_sup_fmt = SubSupFmt
        else:
            sub_sup_fmt = SubSupFmtNoUni
        mapping = {
            'bra': {
                True: sub_sup_fmt('⟨{label}|', sup='({space})'),
                'subscript': sub_sup_fmt('⟨{label}|', sub='({space})'),
                False:  sub_sup_fmt('⟨{label}|')},
            'ket': {
                True: sub_sup_fmt('|{label}⟩', sup='({space})'),
                'subscript': sub_sup_fmt('|{label}⟩', sub='({space})'),
                False:  sub_sup_fmt('|{label}⟩')},
            'ketbra': {
                True: sub_sup_fmt('|{label_i}⟩⟨{label_j}|', sup='({space})'),
                'subscript': sub_sup_fmt(
                    '|{label_i}⟩⟨{label_j}|', sub='({space})'),
                False:  sub_sup_fmt('|{label_i}⟩⟨{label_j}|')},
            'braket': {
                True: sub_sup_fmt('⟨{label_i}|{label_j}⟩', sup='({space})'),
                'subscript': sub_sup_fmt(
                    '⟨{label_i}|{label_j}⟩', sub='({space})'),
                False:  sub_sup_fmt('⟨{label_i}|{label_j}⟩')},
        }
        hs_setting = bool(self._settings['show_hs_label'])
        if self._settings['show_hs_label'] == 'subscript':
            hs_setting = 'subscript'
        return mapping[expr_type][hs_setting]
1190733
def format_arg(value):
    
    translator = repr if isinstance(value, six.string_types) else six.text_type
    return translator(value)
1212783
def default_value(cls, type_, expr):  # TODO: This function must be moved to api.xx
        
        assert isinstance(type_, symbols.TYPE)
        assert type_.is_basic
        assert check.is_static(expr)

        if isinstance(expr, (symbols.CONST, symbols.VAR)):  # a constant expression like @label + 1
            if type_ in (cls.TYPE(TYPE.float_), cls.TYPE(TYPE.string)):
                syntax_error(expr.lineno, "Can't convert non-numeric value to {0} at compile time".format(type_.name))
                return ['<ERROR>']

            val = Translator.traverse_const(expr)
            if type_.size == 1:  # U/byte
                if expr.type_.size != 1:
                    return ['#({0}) & 0xFF'.format(val)]
                else:
                    return ['#{0}'.format(val)]

            if type_.size == 2:  # U/integer
                if expr.type_.size != 2:
                    return ['##({0}) & 0xFFFF'.format(val)]
                else:
                    return ['##{0}'.format(val)]

            if type_ == cls.TYPE(TYPE.fixed):
                return ['0000', '##({0}) & 0xFFFF'.format(val)]

            # U/Long
            return ['##({0}) & 0xFFFF'.format(val), '##(({0}) >> 16) & 0xFFFF'.format(val)]

        if type_ == cls.TYPE(TYPE.float_):
            C, DE, HL = _float(expr.value)
            C = C[:-1]  # Remove 'h' suffix
            if len(C) > 2:
                C = C[-2:]

            DE = DE[:-1]  # Remove 'h' suffix
            if len(DE) > 4:
                DE = DE[-4:]
            elif len(DE) < 3:
                DE = '00' + DE

            HL = HL[:-1]  # Remove 'h' suffix
            if len(HL) > 4:
                HL = HL[-4:]
            elif len(HL) < 3:
                HL = '00' + HL

            return [C, DE[-2:], DE[:-2], HL[-2:], HL[:-2]]

        if type_ == cls.TYPE(TYPE.fixed):
            value = 0xFFFFFFFF & int(expr.value * 2 ** 16)
        else:
            value = int(expr.value)

        result = [value, value >> 8, value >> 16, value >> 24]
        result = ['%02X' % (v & 0xFF) for v in result]
        return result[:type_.size]
216406
def vector_str(p, decimal_places=2, print_zero=True):
    ''''''
    style = '{0:.' + str(decimal_places) + 'f}'
    return '[{0}]'.format(", ".join([' ' if not print_zero and a == 0 else style.format(a) for a in p]))
699050
def _format_ret(self, full_ret):
        '''
        
        '''
        ret = {}
        out = ''
        retcode = 0
        for key, data in six.iteritems(full_ret):
            ret[key] = data['ret']
            if 'out' in data:
                out = data['out']
            ret_retcode = self._get_retcode(data)
            if ret_retcode > retcode:
                retcode = ret_retcode
        return ret, out, retcode
226846
def PythonPercentFormat(format_str):
  """"""

  if format_str.startswith('printf '):
    fmt = format_str[len('printf '):]
    return lambda value: fmt % value
  else:
    return None
1131526
def string_format(data, out, opts=None, **kwargs):
    '''
    
    '''
    raw_output = try_printout(data, out, opts, **kwargs)
    ansi_escape = re.compile(r'\x1b[^m]*m')
    return ansi_escape.sub('', raw_output)
1054187
def get_value_format(value_format: Union[Callable, str] = str) -> Callable[[float], str]:
    
    if value_format is None:
        value_format = ""
    if isinstance(value_format, str):
        format_str = "{0:" + value_format + "}"

        def value_format(x): return format_str.format(x)

    return value_format
1120402
def fmt_text(text):
    
    PRINTABLE_CHAR = set(
        list(range(ord(' '), ord('~') + 1)) + [ord('\r'), ord('\n')])
    newtext = ("\\x{:02X}".format(
        c) if c not in PRINTABLE_CHAR else chr(c) for c in text)
    textlines = "\r\n".join(l.strip('\r')
                            for l in "".join(newtext).split('\n'))
    return textlines
723995
def format(self, obj, **kwargs):
        """"""
        sio = StringIO()
        self.fprint(obj, stream=sio, **kwargs)
        return sio.getvalue()
344457
def format_return_text(self, data, function, **kwargs):  # pylint: disable=unused-argument
        '''
        
        '''
        # emulate the yaml_out output formatter. It relies on a global __opts__ object which
        # we can't obviously pass in
        try:
            try:
                outputter = data[next(iter(data))].get('out')
            except (StopIteration, AttributeError):
                outputter = None
            return salt.output.string_format(
                {x: y['return'] for x, y in six.iteritems(data)},
                out=outputter,
                opts=__opts__,
            )
        except Exception as exc:
            import pprint
            log.exception(
                'Exception encountered when trying to serialize %s',
                pprint.pformat(data)
            )
            return 'Got an error trying to serialze/clean up the response'
968835
def format_kinds(raw):
    """"""
    output = ' '.join('{} {}'.format(*kind) for kind in raw if kind)
    return output
733099
def __type2str(type_, buf, _, tbl):
    
    del buf[:]
    if type_ in tbl:
        buf.extend(tbl[type_].encode('ascii'))
    else:
        buf.extend('0x{0:x}'.format(type_).encode('ascii'))
    return buf
575842
def get_format(self, c, i):
        """"""

        index = i.index
        field = ''
        value = []

        try:
            if c == '}':
                value.append((_util.FMT_FIELD, ''))
                value.append((_util.FMT_INDEX, -1))
            else:
                # Field
                if c in _LETTERS_UNDERSCORE:
                    # Handle name
                    value.append(c)
                    c = self.format_next(i)
                    while c in _WORD:
                        value.append(c)
                        c = self.format_next(i)
                elif c in _DIGIT:
                    # Handle group number
                    value.append(c)
                    c = self.format_next(i)
                    while c in _DIGIT:
                        value.append(c)
                        c = self.format_next(i)

                # Try and covert to integer index
                field = ''.join(value).strip()
                try:
                    value = [(_util.FMT_FIELD, str(int(field, 10)))]
                except ValueError:
                    value = [(_util.FMT_FIELD, field)]
                    pass

                # Attributes and indexes
                count = 0
                while c in ('[', '.'):
                    if c == '[':
                        findex = []
                        sindex = i.index - 1
                        c = self.format_next(i)
                        try:
                            while c != ']':
                                findex.append(c)
                                c = self.format_next(i)
                        except StopIteration:
                            raise SyntaxError("Unmatched '[' at %d" % (sindex - 1))
                        idx = self.parse_format_index(''.join(findex))
                        if isinstance(idx, int):
                            value.append((_util.FMT_INDEX, idx))
                        else:
                            value.append((_util.FMT_INDEX, idx))
                        c = self.format_next(i)
                    else:
                        if count == 0:
                            value.append((_util.FMT_INDEX, -1))
                        findex = []
                        c = self.format_next(i)
                        while c in _WORD:
                            findex.append(c)
                            c = self.format_next(i)
                        value.append((_util.FMT_ATTR, ''.join(findex)))
                    count += 1

                if count == 0:
                    value.append((_util.FMT_INDEX, -1))

                # Conversion
                if c == '!':
                    c = self.format_next(i)
                    if c not in _FMT_CONV_TYPE:
                        raise SyntaxError("Invalid conversion type at %d!" % (i.index - 1))
                    value.append((_util.FMT_CONV, c))
                    c = self.format_next(i)

                # Format spec
                if c == ':':
                    fill = None
                    width = []
                    align = None
                    convert = None
                    c = self.format_next(i)

                    if c in ('<', '>', '^'):
                        # Get fill and alignment
                        align = c
                        c = self.format_next(i)
                        if c in ('<', '>', '^'):
                            fill = align
                            align = c
                            c = self.format_next(i)
                    elif c in _DIGIT:
                        # Get Width
                        fill = c
                        c = self.format_next(i)
                        if c in ('<', '>', '^'):
                            align = c
                            c = self.format_next(i)
                        else:
                            width.append(fill)
                            fill = None
                    else:
                        fill = c
                        c = self.format_next(i)
                        if fill == 's' and c == '}':
                            convert = fill
                            fill = None
                        if fill is not None:
                            if c not in ('<', '>', '^'):
                                raise SyntaxError('Invalid format spec char at %d!' % (i.index - 1))
                            align = c
                            c = self.format_next(i)

                    while c in _DIGIT:
                        width.append(c)
                        c = self.format_next(i)

                    if not align and len(width) and width[0] == '0':
                        raise ValueError("'=' alignment is not supported!")
                    if align and not fill and len(width) and width[0] == '0':
                        fill = '0'

                    if c == 's':
                        convert = c
                        c = self.format_next(i)

                    if fill and self.is_bytes:
                        fill = fill.encode('latin-1')
                    elif not fill:
                        fill = b' ' if self.is_bytes else ' '

                    value.append((_util.FMT_SPEC, (fill, align, (int(''.join(width)) if width else 0), convert)))

            if c != '}':
                raise SyntaxError("Unmatched '{' at %d" % (index - 1))
        except StopIteration:
            raise SyntaxError("Unmatched '{' at %d!" % (index - 1))

        return field, value
1142915
def _x_format(self):
        """"""

        def timedelta_to_str(x):
            td = timedelta(seconds=x)
            return self.x_value_formatter(td)

        return timedelta_to_str
148608
def _pprint(params):
    """"""
    params_list = list()
    line_sep = ','
    for i, (k, v) in enumerate(sorted(params.iteritems())):
        if type(v) is float:
            # use str for representing floating point numbers
            # this way we get consistent representation across
            # architectures and versions.
            this_repr = '%s=%.10f' % (k, v)
        else:
            # use repr of the rest
            this_repr = '%s=%r' % (k, v)
        params_list.append(this_repr)

    lines = ','.join(params_list)
    return lines
311128
def _GetFormatter(self, format_str):
        
        formatter, args, func_type = self.formatters.LookupWithType(format_str)
        if formatter:
            return formatter, args, func_type
        else:
            raise BadFormatter('%r is not a valid formatter' % format_str)