text:
<?php

namespace ApplicationCoreAclTest\Service;

use ApplicationCoreAcl\Service\AclFactory;
use BusinessLogicDomainUsers\Entity\UserEntityInterface;
use Zend\Permissions\Acl\Acl;

class AclFactoryTest extends \PHPUnit_Framework_TestCase
{
    const MODULE_A = 'ModuleA',
        MODULE_B = 'ModuleB\\subB',
        MODULE_C = 'ModuleC\\subC\\subc',
        MODULE_D = 'ModuleD';

    const PRIVILEGE_A = 'ControllerA',
        PRIVILEGE_B = 'ControllerB:actionb',
        PRIVILEGE_C = 'controllerc:actionc';

    /**
     * @var AclFactory
     */
    private $testedObject;

    public function setUp()
    {
        $this->testedObject = new AclFactory($this->getModules(), $this->getAclConfig());
    }

    public function testCreate()
    {
        $result = $this->testedObject->create();

        $this->assertInstanceOf(Acl::class, $result);
        $this->assertCount(count(array_keys($this->getModules())), $result->getResources());
        $this->assertCount(count(array_keys($this->getAclConfig())), $result->getRoles());
    }

    private function getModules()
    {
        return [
            self::MODULE_A,
            self::MODULE_B,
            self::MODULE_C,
            self::MODULE_D
        ];
    }

    private function getAclConfig()
    {
        return [
            UserEntityInterface::ROLE_GUEST => [
                'parents' => [],
                'allow' => [
                    self::MODULE_A => [],
                    self::MODULE_B => [
                        self::PRIVILEGE_B,
                        self::PRIVILEGE_C
                    ],
                    self::MODULE_D => []
                ],
                'deny' => []
            ],
            UserEntityInterface::ROLE_ADMIN => [
                'parents' => ['guest'],
                'allow' => [
                    self::MODULE_B => [
                        self::PRIVILEGE_A
                    ],
                    self::MODULE_C => [
                        self::PRIVILEGE_A,
                        self::PRIVILEGE_B,
                    ]
                ],
                'deny' => [
                    self::MODULE_B => [
                        self::PRIVILEGE_C,
                    ],
                    self::MODULE_D => []
                ]
            ]
        ];
    }

    /**
     * @dataProvider dataProviderForTestCreatedAclIsAllowedTo
     *
     * @param bool   $expectedResult
     * @param string $role
     * @param string $resource
     * @param string $privilege
     */
    public function testCreatedAclIsAllowedTo($expectedResult, $role, $resource, $privilege)
    {
        $acl = $this->testedObject->create();

        $result = $acl->isAllowed(strtolower($role), strtolower($resource), strtolower($privilege));

        $this->assertSame($expectedResult, $result);
    }

    public function dataProviderForTestCreatedAclIsAllowedTo()
    {
        return [
            // module A

            'guest should have access to ANY privilege (A) in module A' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_A,
                self::PRIVILEGE_A
            ],
            'guest should have access to ANY privilege (B) in module A' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_A,
                self::PRIVILEGE_B
            ],
            'guest should have access to ANY privilege (C) in module A' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_A,
                self::PRIVILEGE_C
            ],
            'admin should have access to ANY privilege (A) in module A' => [
                true,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_A,
                self::PRIVILEGE_A
            ],
            'admin should have access to ANY privilege (B) in module A' => [
                true,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_A,
                self::PRIVILEGE_B
            ],
            'admin should have access to ANY privilege (C) in module A' => [
                true,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_A,
                self::PRIVILEGE_C
            ],
            // module B

            'guest should have access to privilege B in module B' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_B,
                self::PRIVILEGE_B
            ],
            'guest should have access to privilege C in module B' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_B,
                self::PRIVILEGE_C
            ],
            'admin should have access to privilege A in module B' => [
                true,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_B,
                self::PRIVILEGE_A
            ],
            'admin should have access to privilege B in module B' => [
                true,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_B,
                self::PRIVILEGE_B
            ],
            'admin shouldn\'t have access to privilege C in module B' => [
                false,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_B,
                self::PRIVILEGE_C
            ],
            // module C

            'guest shouldn\'t have access to ANY privilege (A) in module C' => [
                false,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_C,
                self::PRIVILEGE_A
            ],
            'guest shouldn\'t have access to ANY privilege (B) in module C' => [
                false,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_C,
                self::PRIVILEGE_B
            ],
            'guest shouldn\'t have access to ANY privilege (C) in module C' => [
                false,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_C,
                self::PRIVILEGE_C
            ],
            'admin should have access to privilege A in module C' => [
                true,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_C,
                self::PRIVILEGE_A
            ],
            'admin should have access to privilege B in module C' => [
                true,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_C,
                self::PRIVILEGE_B
            ],
            'admin shouldn\'t have access to privilege C in module C' => [
                false,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_C,
                self::PRIVILEGE_C
            ],
            // Module D
            'guest should have access to ANY privilege (A) in module D' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_D,
                self::PRIVILEGE_A
            ],
            'guest should have access to ANY privilege (B) in module D' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_D,
                self::PRIVILEGE_B
            ],
            'guest should have access to ANY privilege (C) in module D' => [
                true,
                UserEntityInterface::ROLE_GUEST,
                self::MODULE_D,
                self::PRIVILEGE_C
            ],
            'admin shouldn\'t have access to privilege A in module D' => [
                false,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_D,
                self::PRIVILEGE_A
            ],
            'admin shouldn\'t have access to privilege B in module D' => [
                false,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_D,
                self::PRIVILEGE_B
            ],
            'admin shouldn\'t have access to privilege C in module D' => [
                false,
                UserEntityInterface::ROLE_ADMIN,
                self::MODULE_D,
                self::PRIVILEGE_C
            ],
        ];
    }

}


text:
from __future__ import division
from ryu import cfg
from ryu.base import app_manager
from ryu.base.app_manager import lookup_service_brick
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib import hub
from ryu.topology.switches import Switches
from ryu.topology.switches import LLDPPacket
import networkx as nx
import time
import setting
import sql

CONF = cfg.CONF
GPATH = '/home/mini/tempmessage/switchinfo.db'

class NetworkDelayDetector(app_manager.RyuApp):
    """
        NetworkDelayDetector is a Ryu app for collecting link delay.
    """

    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(NetworkDelayDetector, self).__init__(*args, **kwargs)
        self.name = 'delaydetector'
        self.sending_echo_request_interval = 0.05
        # Get the active object of swicthes and awareness module.
        # So that this module can use their data.
        self.sw_module = lookup_service_brick('switches')
        self.awareness = lookup_service_brick('awareness')

        self.datapaths = {}
        self.echo_latency = {}
        self.measure_thread = hub.spawn(self._detector)

        self.conn = sql.get_conn(GPATH)

    @set_ev_cls(ofp_event.EventOFPStateChange,
                [MAIN_DISPATCHER, DEAD_DISPATCHER])
    def _state_change_handler(self, ev):
        datapath = ev.datapath
        if ev.state == MAIN_DISPATCHER:
            if not datapath.id in self.datapaths:
                self.logger.debug('Register datapath: %016x', datapath.id)
                self.datapaths[datapath.id] = datapath
        elif ev.state == DEAD_DISPATCHER:
            if datapath.id in self.datapaths:
                self.logger.debug('Unregister datapath: %016x', datapath.id)
                del self.datapaths[datapath.id]

    def _detector(self):
        """
            Delay detecting functon.
            Send echo request and calculate link delay periodically
        """
        #while CONF.weight == 'delay':
        while True:
            self._send_echo_request()
            self.create_link_delay()
            try:
                self.awareness.shortest_paths = {}
                self.logger.debug("Refresh the shortest_paths")
            except:
                self.awareness = lookup_service_brick('awareness')

            self.show_delay_statis()
            hub.sleep(setting.DELAY_DETECTING_PERIOD)

    def _send_echo_request(self):
        """
            Seng echo request msg to datapath.
        """
        for datapath in self.datapaths.values():
            parser = datapath.ofproto_parser
            echo_req = parser.OFPEchoRequest(datapath,
                                             data="%.12f" % time.time())
            datapath.send_msg(echo_req)
            # Important! Don't send echo request together, Because it will
            # generate a lot of echo reply almost in the same time.
            # which will generate a lot of delay of waiting in queue
            # when processing echo reply in echo_reply_handler.

            hub.sleep(self.sending_echo_request_interval)

    @set_ev_cls(ofp_event.EventOFPEchoReply, MAIN_DISPATCHER)
    def echo_reply_handler(self, ev):
        """
            Handle the echo reply msg, and get the latency of link.
        """
        now_timestamp = time.time()
        try:
            latency = now_timestamp - eval(ev.msg.data)
            self.echo_latency[ev.msg.datapath.id] = latency
        except:
            return

    def get_delay(self, src, dst):
        """
            Get link delay.
                        Controller
                        |        |
        src echo latency|        |dst echo latency
                        |        |
                   SwitchA-------SwitchB

                    fwd_delay--->
                        <----reply_delay
            delay = (forward delay + reply delay - src datapath's echo latency
        """
        try:
            fwd_delay = self.awareness.graph[src][dst]['lldpdelay']
            re_delay = self.awareness.graph[dst][src]['lldpdelay']
            src_latency = self.echo_latency[src]
            dst_latency = self.echo_latency[dst]

            delay = (fwd_delay + re_delay - src_latency - dst_latency)/2 *1000
            return max(delay, 0)
        except:
            return float('inf')

    def _save_lldp_delay(self, src=0, dst=0, lldpdelay=0):
        try:
            self.awareness.graph[src][dst]['lldpdelay'] = lldpdelay
        except:
            if self.awareness is None:
                self.awareness = lookup_service_brick('awareness')
            return
    def saving_delay(self ,src , dst ,delay):
        """
            saving the delay info to the sqlite
        """
        saving_sql = 'UPDATE switch SET delay = ? WHERE sw1 = ? AND sw2 = ?'
        data = [(str(delay) , str(src) , str(dst))]
        sql.update(self.conn , saving_sql , data)

    def create_link_delay(self):
        """
            Create link delay data, and save it into graph object.
        """
        try:
            for src in self.awareness.graph:
                for dst in self.awareness.graph[src]:
                    if src == dst:
                        self.awareness.graph[src][dst]['delay'] = 0
                        continue
                    delay = self.get_delay(src, dst)
                    self.awareness.graph[src][dst]['delay'] = delay
                    self.saving_delay(src ,dst ,delay)
        except:
            if self.awareness is None:
                self.awareness = lookup_service_brick('awareness')
            return

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def packet_in_handler(self, ev):
        """
            Parsing LLDP packet and get the delay of link.
        """
        msg = ev.msg
        try:
            src_dpid, src_port_no = LLDPPacket.lldp_parse(msg.data)
            dpid = msg.datapath.id
            if self.sw_module is None:
                self.sw_module = lookup_service_brick('switches')

            for port in self.sw_module.ports.keys():
                if src_dpid == port.dpid and src_port_no == port.port_no:
                    delay = self.sw_module.ports[port].delay
                    self._save_lldp_delay(src=src_dpid, dst=dpid,
                                          lldpdelay=delay)
        except LLDPPacket.LLDPUnknownFormat as e:
            return

    def show_delay_statis(self):
        if setting.TOSHOW and self.awareness is not None:
            self.logger.info("\nsrc   dst      delay")
            self.logger.info("---------------------------")
            for src in self.awareness.graph:
                for dst in self.awareness.graph[src]:
                    delay = self.awareness.graph[src][dst]['delay']
                    self.logger.info("%s<-->%s : %s" % (src, dst, delay))

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace vierbergenlars\Xml;

/**
 * Interface for an xml element
 */
interface XmlElementInterface
{
    /**
     * Get the name of the element
     * @return string
     */
    public function getName();
    /**
     * Get the text contained in the element
     * @return string
     */
    public function text();

    /**
     * Set the text contained in the element
     * @param string $text
     * @return XmlElementInterface Fluent interface
     */
    public function setText($text);
    /**
     * Gets the value of an attribute
     * @param string $name The name of the attribute to get
     * @return string
     */
    public function attr($name);

    /**
     * Gets all attributes of the element
     * @return XmlAttributesInterface
     */
    public function attributes();

    /**
     * Adds a new element as a child of the current element
     * @param XmlElementInterface|string $name Name of the new element, or a description of the element
     * @param XmlElementInterface|string|null $value Copies all properties from the given element, or sets its string value (only if $name is a string)
     * @return XmlElementInterface The added element
     */
    public function addChild($name, $value = null);
    /**
     * Gets the child with the specified name at the specified position
     * @param string $name The name of the children to get
     * @param array $filter Filter the children of the element on their attributes
     * @param int $pos The position of the child to get from the collection
     * @return XmlElementInterface
     */
    public function child($name = null, $filter = array(), $pos = 0);
    /**
     * Gets all children with the specified name
     * @param string $name The name of the children to get
     * @return XmlCollectionInterface
     */
    public function children($name = null);
    /**
     * Filter the children of the element on their attributes
     * @param array $attributes
     * @return XmlCollectionInterface
     */
    public function find($attributes = array());

    /**
     *
     * @param \SimpleXMLElement $elem
     * @internal
     */
    public function _swapoutInternal(\SimpleXMLElement $elem);
}


text:
// Package app implements a server that runs a set of active
// components.  This includes replication controllers, service endpoints and
// nodes.
//
package app

import (
	"fmt"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/kubernetes/pkg/controller/cronjob"
	"k8s.io/kubernetes/pkg/controller/job"
)

func startJobController(ctx ControllerContext) (bool, error) {
	if !ctx.AvailableResources[schema.GroupVersionResource{Group: "batch", Version: "v1", Resource: "jobs"}] {
		return false, nil
	}
	go job.NewJobController(
		ctx.InformerFactory.Core().V1().Pods(),
		ctx.InformerFactory.Batch().V1().Jobs(),
		ctx.ClientBuilder.ClientOrDie("job-controller"),
	).Run(int(ctx.Options.ConcurrentJobSyncs), ctx.Stop)
	return true, nil
}

func startCronJobController(ctx ControllerContext) (bool, error) {
	if !ctx.AvailableResources[schema.GroupVersionResource{Group: "batch", Version: "v1beta1", Resource: "cronjobs"}] {
		return false, nil
	}
	cjc, err := cronjob.NewCronJobController(
		ctx.ClientBuilder.ClientOrDie("cronjob-controller"),
	)
	if err != nil {
		return true, fmt.Errorf("error creating CronJob controller: %v", err)
	}
	go cjc.Run(ctx.Stop)
	return true, nil
}


text:
from snapboard.management import sampledata
from snapboard.management import notices


text:
These demos showcase networking and/or multiplayer features.

Languages: All have GDScript, WebRTC uses some GDNative

Renderer: All are GLES 2


text:
import datetime
import decimal
import functools
import re
import unicodedata
from importlib import import_module

from django.conf import settings
from django.utils import dateformat, numberformat
from django.utils.functional import lazy
from django.utils.translation import (
    check_for_language, get_language, to_locale,
)

# format_cache is a mapping from (format_type, lang) to the format string.
# By using the cache, it is possible to avoid running get_format_modules
# repeatedly.
_format_cache = {}
_format_modules_cache = {}

ISO_INPUT_FORMATS = {
    'DATE_INPUT_FORMATS': ['%Y-%m-%d'],
    'TIME_INPUT_FORMATS': ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'],
    'DATETIME_INPUT_FORMATS': [
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m-%d %H:%M:%S.%f',
        '%Y-%m-%d %H:%M',
        '%Y-%m-%d'
    ],
}

FORMAT_SETTINGS = frozenset([
    'DECIMAL_SEPARATOR',
    'THOUSAND_SEPARATOR',
    'NUMBER_GROUPING',
    'FIRST_DAY_OF_WEEK',
    'MONTH_DAY_FORMAT',
    'TIME_FORMAT',
    'DATE_FORMAT',
    'DATETIME_FORMAT',
    'SHORT_DATE_FORMAT',
    'SHORT_DATETIME_FORMAT',
    'YEAR_MONTH_FORMAT',
    'DATE_INPUT_FORMATS',
    'TIME_INPUT_FORMATS',
    'DATETIME_INPUT_FORMATS',
])

def reset_format_cache():
    """Clear any cached formats.

    This method is provided primarily for testing purposes,
    so that the effects of cached formats can be removed.
    """
    global _format_cache, _format_modules_cache
    _format_cache = {}
    _format_modules_cache = {}

def iter_format_modules(lang, format_module_path=None):
    """Find format modules."""
    if not check_for_language(lang):
        return

    if format_module_path is None:
        format_module_path = settings.FORMAT_MODULE_PATH

    format_locations = []
    if format_module_path:
        if isinstance(format_module_path, str):
            format_module_path = [format_module_path]
        for path in format_module_path:
            format_locations.append(path + '.%s')
    format_locations.append('django.conf.locale.%s')
    locale = to_locale(lang)
    locales = [locale]
    if '_' in locale:
        locales.append(locale.split('_')[0])
    for location in format_locations:
        for loc in locales:
            try:
                yield import_module('%s.formats' % (location % loc))
            except ImportError:
                pass

def get_format_modules(lang=None):
    """Return a list of the format modules found."""
    if lang is None:
        lang = get_language()
    if lang not in _format_modules_cache:
        _format_modules_cache[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH))
    return _format_modules_cache[lang]

def get_format(format_type, lang=None, use_l10n=None):
    """
    For a specific format type, return the format for the current
    language (locale). Default to the format in the settings.
    format_type is the name of the format, e.g. 'DATE_FORMAT'.

    If use_l10n is provided and is not None, it forces the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    use_l10n = use_l10n or (use_l10n is None and settings.USE_L10N)
    if use_l10n and lang is None:
        lang = get_language()
    cache_key = (format_type, lang)
    try:
        return _format_cache[cache_key]
    except KeyError:
        pass

    # The requested format_type has not been cached yet. Try to find it in any
    # of the format_modules for the given lang if l10n is enabled. If it's not
    # there or if l10n is disabled, fall back to the project settings.
    val = None
    if use_l10n:
        for module in get_format_modules(lang):
            val = getattr(module, format_type, None)
            if val is not None:
                break
    if val is None:
        if format_type not in FORMAT_SETTINGS:
            return format_type
        val = getattr(settings, format_type)
    elif format_type in ISO_INPUT_FORMATS:
        # If a list of input formats from one of the format_modules was
        # retrieved, make sure the ISO_INPUT_FORMATS are in this list.
        val = list(val)
        for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
            if iso_input not in val:
                val.append(iso_input)
    _format_cache[cache_key] = val
    return val

get_format_lazy = lazy(get_format, str, list, tuple)

def date_format(value, format=None, use_l10n=None):
    """
    Format a datetime.date or datetime.datetime object using a
    localizable format.

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))

def time_format(value, format=None, use_l10n=None):
    """
    Format a datetime.time object using a localizable format.

    If use_l10n is provided and is not None, it forces the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n))

def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
    """
    Format a numeric value using localization settings.

    If use_l10n is provided and is not None, it forces the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    use_l10n = use_l10n or (use_l10n is None and settings.USE_L10N)
    lang = get_language() if use_l10n else None
    return numberformat.format(
        value,
        get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n),
        decimal_pos,
        get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n),
        get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n),
        force_grouping=force_grouping,
        use_l10n=use_l10n,
    )

def localize(value, use_l10n=None):
    """
    Check if value is a localizable type (date, number...) and return it
    formatted as a string using current locale format.

    If use_l10n is provided and is not None, it forces the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    if isinstance(value, str):  # Handle strings first for performance reasons.
        return value
    elif isinstance(value, bool):  # Make sure booleans don't get treated as numbers
        return str(value)
    elif isinstance(value, (decimal.Decimal, float, int)):
        if use_l10n is False:
            return str(value)
        return number_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.datetime):
        return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
    elif isinstance(value, datetime.date):
        return date_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.time):
        return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
    return value

def localize_input(value, default=None):
    """
    Check if an input value is a localizable type and return it
    formatted with the appropriate formatting string of the current locale.
    """
    if isinstance(value, str):  # Handle strings first for performance reasons.
        return value
    elif isinstance(value, bool):  # Don't treat booleans as numbers.
        return str(value)
    elif isinstance(value, (decimal.Decimal, float, int)):
        return number_format(value)
    elif isinstance(value, datetime.datetime):
        format = default or get_format('DATETIME_INPUT_FORMATS')[0]
        format = sanitize_strftime_format(format)
        return value.strftime(format)
    elif isinstance(value, datetime.date):
        format = default or get_format('DATE_INPUT_FORMATS')[0]
        format = sanitize_strftime_format(format)
        return value.strftime(format)
    elif isinstance(value, datetime.time):
        format = default or get_format('TIME_INPUT_FORMATS')[0]
        return value.strftime(format)
    return value

@functools.lru_cache()
def sanitize_strftime_format(fmt):
    """
    Ensure that certain specifiers are correctly padded with leading zeros.

    For years < 1000 specifiers %C, %F, %G, and %Y don't work as expected for
    strftime provided by glibc on Linux as they don't pad the year or century
    with leading zeros. Support for specifying the padding explicitly is
    available, however, which can be used to fix this issue.

    FreeBSD, macOS, and Windows do not support explicitly specifying the
    padding, but return four digit years (with leading zeros) as expected.

    This function checks whether the %Y produces a correctly padded string and,
    if not, makes the following substitutions:

    - %C → %02C
    - %F → %010F
    - %G → %04G
    - %Y → %04Y

    See https://bugs.python.org/issue13305 for more details.
    """
    if datetime.date(1, 1, 1).strftime('%Y') == '0001':
        return fmt
    mapping = {'C': 2, 'F': 10, 'G': 4, 'Y': 4}
    return re.sub(
        r'((?:^|[^%])(?:%%)*)%([CFGY])',
        lambda m: r'%s%%0%s%s' % (m[1], mapping[m[2]], m[2]),
        fmt,
    )

def sanitize_separators(value):
    """
    Sanitize a value according to the current decimal and
    thousand separator setting. Used with form field input.
    """
    if isinstance(value, str):
        parts = []
        decimal_separator = get_format('DECIMAL_SEPARATOR')
        if decimal_separator in value:
            value, decimals = value.split(decimal_separator, 1)
            parts.append(decimals)
        if settings.USE_THOUSAND_SEPARATOR:
            thousand_sep = get_format('THOUSAND_SEPARATOR')
            if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3:
                # Special case where we suspect a dot meant decimal separator (see #22171)
                pass
            else:
                for replacement in {
                        thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}:
                    value = value.replace(replacement, '')
        parts.append(value)
        value = '.'.join(reversed(parts))
    return value