Parse a format string.  Factory function for the Format class.

        :param format: The format string to parse.

        :returns: An instance of class Format.
184939
def parse(cls, format):
        

        fmt = cls()

        # Return an empty Format if format is empty
        if not format:
            return fmt

        # Initialize the state for parsing
        state = ParseState(fmt, format)

        # Loop through the format string with a state-based parser
        for idx, char in enumerate(format):
            # Some characters get ignored
            if state.check_ignore():
                continue

            if state == 'string':
                if char == '%':
                    # Handle '%%'
                    if format[idx:idx + 2] == '%%':
                        # Add one % to the string context
                        state.add_text(idx + 1, idx + 2)
                        state.set_ignore(1)
                    else:
                        state.add_text(idx)
                        state.conversion(idx)
                elif char == '\\':
                    state.add_text(idx)
                    state.escape(idx)
            elif state == 'escape':
                state.add_escape(idx + 1, char)
                state.pop_state(idx + 1)
            elif state == 'param':
                if char == '}':
                    state.set_param(idx)
                    state.pop_state()
            elif state == 'conv':
                if char == ')':
                    state.set_conversion(idx)
                    state.pop_state()  # now in 'conversion'
                    state.pop_state(idx + 1)  # now in 'string'
            else:  # state == 'conversion'
                if char in '<>':
                    # Allowed for Apache compatibility, but ignored
                    continue
                elif char == '!':
                    state.set_reject()
                    continue
                elif char == ',' and state.code_last:
                    # Syntactically allowed ','
                    continue
                elif char.isdigit():
                    # True if the code is valid
                    if state.set_code(idx):
                        continue
                elif char == '{' and state.param_begin is None:
                    state.param(idx + 1)
                    continue
                elif char == '(' and state.conv_begin is None:
                    state.conv(idx + 1)
                    continue

                # OK, we have a complete conversion
                state.set_conversion(idx)
                state.pop_state(idx + 1)

        # Finish the parse and return the completed format
        return state.end_state()
1011977
def configure_formatter(self, config):
        """"""
        if '()' in config:
            factory = config['()'] # for use in exception handler
            try:
                result = self.configure_custom(config)
            except TypeError, te:
                if "'format'" not in str(te):
                    raise
                #Name of parameter changed from fmt to format.
                #Retry with old name.
                #This is so that code can be used with older Python versions
                #(e.g. by Django)
                config['fmt'] = config.pop('format')
                config['()'] = factory
                result = self.configure_custom(config)
        else:
            fmt = config.get('format', None)
            dfmt = config.get('datefmt', None)
            result = logging.Formatter(fmt, dfmt)
        return result
362292
def parser(format_name, ext_names=None):
    

    def decorator(cls):
        format_name_lower = format_name.lower()
        if ext_names is None:
            _ext_format_mapping[format_name_lower] = format_name_lower
        else:
            for ext in to_list(ext_names):
                _ext_format_mapping[ext.lower()] = format_name_lower
        _format_parser_mapping[format_name_lower] = cls()
        return cls

    return decorator
160471
def _inject_format_spec(self, value, format_spec):
        
        t = type(value)
        return value[:-1] + t(u':') + format_spec + t(u'}')
909315
def parse_format_specifier(specification):
    
    m = _parse_format_specifier_regex.match(specification)
    if m is None:
        raise ValueError(
            "Invalid format specifier: {!r}".format(specification))
    format_dict = m.groupdict('')

    # Convert zero-padding into fill and alignment.
    zeropad = format_dict.pop('zeropad')
    if zeropad:
        # If zero padding is requested, fill and align fields should be absent.
        if format_dict['align']:
            raise ValueError(
                "Invalid format specifier: {!r}".format(specification))
        # Impossible to have 'fill' without 'align'.
        assert not format_dict['fill']
        format_dict['align'] = '='
        format_dict['fill'] = '0'

    # Default alignment is right-aligned.
    if not format_dict['align']:
        format_dict['align'] = '>'

    # Default fill character is space.
    if not format_dict['fill']:
        format_dict['fill'] = ' '

    # Default sign is '-'.
    if not format_dict['sign']:
        format_dict['sign'] = '-'

    # Convert minimum width to an int; default is zero.
    format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')

    # Convert precision to an int, or `None` if no precision given.
    if format_dict['precision']:
        format_dict['precision'] = int(format_dict['precision'][1:])
    else:
        format_dict['precision'] = None

    # If no rounding mode is given, assume 'N'.
    if not format_dict['rounding']:
        format_dict['rounding'] = 'N'

    return format_dict
105556
public ResourceFormatGenerator getGeneratorForFormat(final String format) throws UnsupportedFormatException {
        try {
            return providerOfType(format);
        } catch (ExecutionServiceException e) {
            throw new UnsupportedFormatException("No provider available to parse format: " + format, e);
        }
    }
356162
def get_writer_factory_for(self, name, *, format=None):
        
        return self.get_factory_for(WRITER, name, format=format)
344637
def format_manager(cls):
        
        if cls._instance is None:
            # Discover the formats and register them with a new singleton.
            cls._instance = cls().register_entrypoints()
        return cls._instance
1034717
def get_format(**kwargs):
    

    settings = foundations.data_structures.Structure(**{"format": QTextCharFormat(),
                                                        "background_color": None,
                                                        "color": None,
                                                        "font_weight": None,
                                                        "font_point_size": None,
                                                        "italic": False})
    settings.update(kwargs)

    format = QTextCharFormat(settings.format)

    settings.background_color and format.setBackground(settings.background_color)
    settings.color and format.setForeground(settings.color)
    settings.font_weight and format.setFontWeight(settings.font_weight)
    settings.font_point_size and format.setFontPointSize(settings.font_point_size)
    settings.italic and format.setFontItalic(True)

    return format
770838
public String format(String format)
    {
        Matcher m = REF.matcher(format);
        StringBuffer sb = new StringBuffer();
        while (m.find())
        {
            Object ob = get(m.group(1));
            if (ob != null)
            {
                m.appendReplacement(sb, ob.toString());
            }
            else
            {
                m.appendReplacement(sb, m.group());
            }
        }
        m.appendTail(sb);
        return sb.toString();
    }
1204143
public ResourceFormatParser getParserForFormat(final String format) throws UnsupportedFormatException {
        try {
            return providerOfType(format);
        } catch (ExecutionServiceException e) {
            throw new UnsupportedFormatException("No provider available to parse format: " + format,e);
        }
    }
1225717
def _parse_format(cls, fmt):
        
        fields = []
        if not fmt:
            raise ValueError('empty format')
        for code, length in fmt:
            if length == 0:
                raise ValueError('zero-length field (bug_compat mismatch?)')
            if ((code in ('u', 'i') and length in (8, 16, 32, 64)) or
                    (code == 'f' and length in (32, 64))):
                fields.append('>' + code + str(length // 8))
            elif code == 'b' and length == 8:
                fields.append('?')
            elif code == 'c' and length == 8:
                fields.append('S1')
            else:
                if code not in ['u', 'i', 'b']:
                    raise ValueError('illegal format ({}, {})'.format(code, length))
                fields.append('O')
        return _np.dtype(','.join(fields))
120711
def format_dict(dic, format_list, separator=',', default_value=str):
    

    dic = collections.defaultdict(default_value, dic)

    str_format = separator.join(["{" + "{}".format(head) + "}" for head in format_list])

    return str_format.format(**dic)
955804
def extract_format(format, extra_types):
    '''
    '''
    fill = align = None
    if format[0] in '<>=^':
        align = format[0]
        format = format[1:]
    elif len(format) > 1 and format[1] in '<>=^':
        fill = format[0]
        align = format[1]
        format = format[2:]

    zero = False
    if format and format[0] == '0':
        zero = True
        format = format[1:]

    width = ''
    while format:
        if not format[0].isdigit():
            break
        width += format[0]
        format = format[1:]

    if format.startswith('.'):
        # Precision isn't needed but we need to capture it so that
        # the ValueError isn't raised.
        format = format[1:]  # drop the '.'
        precision = ''
        while format:
            if not format[0].isdigit():
                break
            precision += format[0]
            format = format[1:]

    # the rest is the type, if present
    type = format
    if type and type not in ALLOWED_TYPES and type not in extra_types:
        raise ValueError('format spec %r not recognised' % type)

    return locals()
1285324
def format(self, format_spec='f'):
        
        """
        if format_spec == '' or format_spec == 'f':
            cpf = CPF.clean(self._cpf)
            return '{0}.{1}.{2}-{3}'.format(cpf[0:3], cpf[3:6], cpf[6:9], cpf[9:11])
        if format_spec == 'r':
            return self._cpf
        raise ValueError(
            "Unknown format code '{0}' for object of type '{1}'".format(format_spec, CPF.__name__))
542088
def get_pairs(self, format_string):
        
        for token in self.get_tokens(format_string):
            match = self.name_pattern.search(token)
            name = match.group(1) if match else None
            yield FormatStringToken(name=name, text=token)
1178401
def from_format(
    string,  # type: str
    fmt,  # type: str
    tz=UTC,  # type: Union[str, _Timezone]
    locale=None,  # type: Union[str, None]
):  # type: (...) -> DateTime
    
    parts = _formatter.parse(string, fmt, now(), locale=locale)
    if parts["tz"] is None:
        parts["tz"] = tz

    return datetime(**parts)