Generate custom code using ascii uppercase and random integers.

        :param mask: Mask of code.
        :param char: Placeholder for characters.
        :param digit: Placeholder for digits.
        :return: Custom code.
774797
def custom_code(self, mask: str = '@###',
                    char: str = '@', digit: str = '#') -> str:
        
        char_code = ord(char)
        digit_code = ord(digit)
        code = bytearray(len(mask))

        def random_int(a: int, b: int) -> int:
            b = b - a
            return int(self.random() * b) + a

        _mask = mask.encode()
        for i, p in enumerate(_mask):
            if p == char_code:
                a = random_int(65, 91)  # A-Z
            elif p == digit_code:
                a = random_int(48, 58)  # 0-9
            else:
                a = p
            code[i] = a
        return code.decode()
1080974
def _make_one_char_uppercase(string: str) -> str:
        """"""
        if not isinstance(string, str):
            raise TypeError('string must be a string')

        if Aux.lowercase_count(string) > 0:
            while True:
                cindex = randbelow(len(string))
                if string[cindex].islower():
                    aux = list(string)
                    aux[cindex] = aux[cindex].upper()
                    string = ''.join(aux)
                    break

        return string
614860
public static String mask(final String mask, final String value)
    {
        return maskFormat(mask).format(value);
    }
261136
def get_submask(self, *args, **kwargs) -> masktools.CustomMask:
        
        if args or kwargs:
            masks = self.availablemasks
            mask = masktools.CustomMask(numpy.full(self.shape, False))
            for arg in args:
                mask = mask + self._prepare_mask(arg, masks)
            for key, value in kwargs.items():
                mask = mask + self._prepare_mask(key, masks, **value)
            if mask not in self.mask:
                raise ValueError(
                    f'Based on the arguments `{args}` and `{kwargs}` '
                    f'the mask `{repr(mask)}` has been determined, '
                    f'which is not a submask of `{repr(self.mask)}`.')
        else:
            mask = self.mask
        return mask
984621
def _conform_mask(in_mask, in_reference):
    """"""
    from pathlib import Path
    import nibabel as nb
    from nipype.utils.filemanip import fname_presuffix

    ref = nb.load(in_reference)
    nii = nb.load(in_mask)
    hdr = nii.header.copy()
    hdr.set_data_dtype('int16')
    hdr.set_slope_inter(1, 0)

    qform, qcode = ref.header.get_qform(coded=True)
    if qcode is not None:
        hdr.set_qform(qform, int(qcode))

    sform, scode = ref.header.get_sform(coded=True)
    if scode is not None:
        hdr.set_sform(sform, int(scode))

    if '_maths' in in_mask:  # Cut the name at first _maths occurrence
        ext = ''.join(Path(in_mask).suffixes)
        basename = Path(in_mask).name
        in_mask = basename.split('_maths')[0] + ext

    out_file = fname_presuffix(in_mask, suffix='_mask',
                               newpath=str(Path()))
    nii.__class__(nii.get_data().astype('int16'), ref.affine,
                  hdr).to_filename(out_file)
    return out_file
295142
function getMaskTemplate(mask) {
                if (opts.numericInput) {
                    mask = mask.split('').reverse().join('');
                }
                var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat;
                if (repeat == "*") greedy = false;
                //if (greedy == true && opts.placeholder == "") opts.placeholder = " ";
                if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
                var singleMask = $.map(mask.split(""), function (element, index) {
                    var outElem = [];
                    if (element == opts.escapeChar) {
                        escaped = true;
                    }
                    else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
                        var maskdef = opts.definitions[element];
                        if (maskdef && !escaped) {
                            for (var i = 0; i < maskdef.cardinality; i++) {
                                outElem.push(opts.placeholder.charAt((outCount + i) % opts.placeholder.length));
                            }
                        } else {
                            outElem.push(element);
                            escaped = false;
                        }
                        outCount += outElem.length;
                        return outElem;
                    }
                });

                //allocate repetitions
                var repeatedMask = singleMask.slice();
                for (var i = 1; i < repeat && greedy; i++) {
                    repeatedMask = repeatedMask.concat(singleMask.slice());
                }

                return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy };
            }
297640
def _build_regexes():
    
    # Define a regex that matches ASCII text.
    encoding_regexes = {'ascii': re.compile('^[\x00-\x7f]*$')}

    for encoding in CHARMAP_ENCODINGS:
        # Make a sequence of characters that bytes \x80 to \xFF decode to
        # in each encoding, as well as byte \x1A, which is used to represent
        # the replacement character � in the sloppy-* encodings.
        byte_range = bytes(list(range(0x80, 0x100)) + [0x1a])
        charlist = byte_range.decode(encoding)

        # The rest of the ASCII bytes -- bytes \x00 to \x19 and \x1B
        # to \x7F -- will decode as those ASCII characters in any encoding we
        # support, so we can just include them as ranges. This also lets us
        # not worry about escaping regex special characters, because all of
        # them are in the \x1B to \x7F range.
        regex = '^[\x00-\x19\x1b-\x7f{0}]*$'.format(charlist)
        encoding_regexes[encoding] = re.compile(regex)
    return encoding_regexes
665909
def _escape_char(c):
    ""
    if isinstance(c, int):
        c = _unichr(c)
    return c if c in LEGAL_CHARS else ESCAPE_FMT % ord(c)
416826
def _generate_identifier():
    
    bit_length = 64
    byte_length = int(bit_length / 8)
    identifier = os.urandom(byte_length)
    return hexlify(identifier).decode('ascii')
977342
def code(_, s, from_fenced_block = None, **kw):
        
        lang = kw.get('lang')

        raw_code = s
        if have_pygments:
            s = style_ansi(raw_code, lang=lang)


        # outest hir is 2, use it for fenced:
        ind = ' ' * kw.get('hir', 2)
        #if from_fenced_block: ... WE treat equal.

        # shift to the far left, no matter the indent (screenspace matters):
        firstl = s.split('\n')[0]
        del_spaces = ' ' * (len(firstl) - len(firstl.lstrip()))
        s = ('\n' + s).replace('\n%s' % del_spaces, '\n')[1:]

        # we want an indent of one and low vis prefix. this does it:
        code_lines = ('\n' + s).splitlines()
        prefix = ('\n%s%s %s' % (ind, low(code_pref), col('', C, no_reset=1)))
        code = prefix.join(code_lines)
        return code + '\n' + reset_col
712854
def createMask(input=None, static_sig=4.0, group=None, editpars=False, configObj=None, **inputDict):
    

    if input is not None:
        inputDict["static_sig"]=static_sig
        inputDict["group"]=group
        inputDict["updatewcs"]=False
        inputDict["input"]=input
    else:
        print >> sys.stderr, "Please supply an input image\n"
        raise ValueError

    #this accounts for a user-called init where config is not defined yet
    configObj = util.getDefaultConfigObj(__taskname__,configObj,inputDict,loadOnly=(not editpars))
    if configObj is None:
        return

    if not editpars:
        run(configObj)
69313
private String toCidrNotation(String addr, String mask) {
        return addr + "/" + pop(toInteger(mask));
    }
331271
def random(length, chars=None):
    
    if chars is None:
        chars = string.ascii_letters + string.digits
    else:
        ensure_string(chars)
        if not chars:
            raise ValueError("character set must not be empty")

    if is_pair(length):
        length = randint(*length)
    elif isinstance(length, Integral):
        if not length > 0:
            raise ValueError(
                "random string length must be positive (got %r)" % (length,))
    else:
        raise TypeError("random string length must be an integer; "
                        "got '%s'" % type(length).__name__)

    return join(chars.__class__(), (choice(chars) for _ in xrange(length)))
1233932
def draw_mask(im, mask, alpha=0.5, color=None):
    
    if color is None:
        color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]
    im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2),
                  im * (1 - alpha) + color * alpha, im)
    im = im.astype('uint8')
    return im
789787
def do_kpl_set_on_mask(self, args):
        
        params = args.split()
        address = None
        group = None
        mask_string = None
        mask = None

        try:
            address = params[0]
            group = int(params[1])
            mask_string = params[2]
            if mask_string[0:2].lower() == '0x':
                mask = binascii.unhexlify(mask_string[2:])
            else:
                mask = int(mask_string)
        except IndexError:
            _LOGGING.error("Address, group and mask are regquired")
            self.do_help('kpl_status')
        except TypeError:
            _LOGGING.error("Group must be an integer")
            self.do_help('kpl_status')

        if address and group and mask:
            self.tools.kpl_set_on_mask(address, group, mask)
897557
def set_digit_raw(self, pos, bitmask):
        """"""
        if pos < 0 or pos > 3:
            # Ignore out of bounds digits.
            return
        # Jump past the colon at position 2 by adding a conditional offset.
        offset = 0 if pos < 2 else 1

        # Calculate the correct position depending on orientation
        if self.invert:
            pos = 4-(pos+offset)
        else:
            pos = pos+offset

        # Set the digit bitmask value at the appropriate position.
        self.buffer[pos*2] = bitmask & 0xFF
721702
def set_digit_raw(self, pos, bitmask):
        """"""
        if pos < 0 or pos > 3:
            # Ignore out of bounds digits.
            return
        # Set the digit bitmask value at the appropriate position.
        # Also set bit 7 (decimal point) if decimal is True.
        self.buffer[pos*2]   = bitmask & 0xFF
        self.buffer[pos*2+1] = (bitmask >> 8) & 0xFF