Python string.uppercase() Examples

The following are 30 code examples of string.uppercase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: strings.py    From yaql with Apache License 2.0 6 votes vote down vote up
def to_upper(string):
    """:yaql:toUpper

    Returns a string with all case-based characters uppercase.

    :signature: string.toUpper()
    :receiverArg string: value to uppercase
    :argType string: string
    :returnType: string

    .. code::

        yaql> "aB1c".toUpper()
        "AB1C"
    """
    return string.upper() 
Example #2
Source File: recipe-578396.py    From code with MIT License 6 votes vote down vote up
def main(argv):

	if (len(sys.argv) != 5):
		sys.exit('Usage: simple_pass.py <upper_case> <lower_case> <digit> <special_characters>')
    
	password = ''
	
	for i in range(len(argv)):
		for j in range(int(argv[i])):
			if i == 0:
				password += string.uppercase[random.randint(0,len(string.uppercase)-1)]
			elif i == 1:
				password += string.lowercase[random.randint(0,len(string.lowercase)-1)]
			elif i == 2:
				password += string.digits[random.randint(0,len(string.digits)-1)]
			elif i == 3:
				password += string.punctuation[random.randint(0,len(string.punctuation)-1)]
	
	print 'You new password is: ' + ''.join(random.sample(password,len(password))) 
Example #3
Source File: utils.py    From pelisalacarta-ce with GNU General Public License v3.0 6 votes vote down vote up
def encode_name(name, type, scope = None):
    """
    Perform first and second level encoding of name as specified in RFC 1001 (Section 4)
    """
    if name == '*':
        name = name + '\0' * 15
    elif len(name) > 15:
        name = name[:15] + chr(type)
    else:
        name = string.ljust(name, 15) + chr(type)

    def _do_first_level_encoding(m):
        s = ord(m.group(0))
        return string.uppercase[s >> 4] + string.uppercase[s & 0x0f]

    encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name)
    if scope:
        encoded_scope = ''
        for s in string.split(scope, '.'):
            encoded_scope = encoded_scope + chr(len(s)) + s
        return encoded_name + encoded_scope + '\0'
    else:
        return encoded_name + '\0' 
Example #4
Source File: pattern.py    From security-scripts with GNU General Public License v2.0 6 votes vote down vote up
def pattern_gen(length):
    """
    Generate a pattern of a given length up to a maximum
    of 20280 - after this the pattern would repeat
    """
    if length >= MAX_PATTERN_LENGTH:
        print 'ERROR: Pattern length exceeds maximum of %d' % MAX_PATTERN_LENGTH
        sys.exit(1)

    pattern = ''
    for upper in uppercase:
        for lower in lowercase:
            for digit in digits:
                if len(pattern) < length:
                    pattern += upper+lower+digit
                else:
                    out = pattern[:length]
                    print out
                    return 
Example #5
Source File: naive_util.py    From Ossian with Apache License 2.0 6 votes vote down vote up
def int_to_alphabetic(number): 
    """Convert non-negative integer to base 26 representation using uppercase A-Z
    as symbols. Can use this instead of numbers in feature delimiters because:
        -- gives shorter full context model names (esp. with many features)
        -- trivially, split-context-balanced.py expects delimiters to contain no digits        
    """    
    assert number >= 0,"Function not intended to handle negative input values"    
    if number == 0:
        return string.uppercase[0]    
    alphabetic = ""
    current = number
    while current!=0:
        remainder = current % 26
        remainder_string = string.uppercase[remainder]        
        alphabetic = remainder_string + alphabetic
        current = current / 26
    return alphabetic 
Example #6
Source File: utils.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def encode_name(name, type, scope = None):
    """
    Perform first and second level encoding of name as specified in RFC 1001 (Section 4)
    """
    if name == '*':
        name = name + '\0' * 15
    elif len(name) > 15:
        name = name[:15] + chr(type)
    else:
        name = string.ljust(name, 15) + chr(type)

    def _do_first_level_encoding(m):
        s = ord(m.group(0))
        return string.uppercase[s >> 4] + string.uppercase[s & 0x0f]

    encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name)
    if scope:
        encoded_scope = ''
        for s in string.split(scope, '.'):
            encoded_scope = encoded_scope + chr(len(s)) + s
        return encoded_name + encoded_scope + '\0'
    else:
        return encoded_name + '\0' 
Example #7
Source File: common.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def computeSize(self, *args):
        barWidth = self.barWidth
        oa, oA = ord('a') - 1, ord('A') - 1

        w = 0.0

        for c in self.decomposed:
            oc = ord(c)
            if c in string.lowercase:
                w = w + barWidth * (oc - oa)
            elif c in string.uppercase:
                w = w + barWidth * (oc - oA)

        if self.barHeight is None:
            self.barHeight = w * 0.15
            self.barHeight = max(0.25 * inch, self.barHeight)

        if self.quiet:
            w += self.lquiet + self.rquiet

        self._height = self.barHeight
        self._width = w 
Example #8
Source File: utils.py    From xunfengES with GNU General Public License v3.0 6 votes vote down vote up
def encode_name(name, type, scope = None):
    """
    Perform first and second level encoding of name as specified in RFC 1001 (Section 4)
    """
    if name == '*':
        name = name + '\0' * 15
    elif len(name) > 15:
        name = name[:15] + chr(type)
    else:
        name = string.ljust(name, 15) + chr(type)

    def _do_first_level_encoding(m):
        s = ord(m.group(0))
        return string.uppercase[s >> 4] + string.uppercase[s & 0x0f]

    encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name)
    if scope:
        encoded_scope = ''
        for s in string.split(scope, '.'):
            encoded_scope = encoded_scope + chr(len(s)) + s
        return encoded_name + encoded_scope + '\0'
    else:
        return encoded_name + '\0' 
Example #9
Source File: utils.py    From xunfengES with GNU General Public License v3.0 6 votes vote down vote up
def encode_name(name, type, scope = None):
    """
    Perform first and second level encoding of name as specified in RFC 1001 (Section 4)
    """
    if name == '*':
        name = name + '\0' * 15
    elif len(name) > 15:
        name = name[:15] + chr(type)
    else:
        name = string.ljust(name, 15) + chr(type)

    def _do_first_level_encoding(m):
        s = ord(m.group(0))
        return string.uppercase[s >> 4] + string.uppercase[s & 0x0f]

    encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name)
    if scope:
        encoded_scope = ''
        for s in string.split(scope, '.'):
            encoded_scope = encoded_scope + chr(len(s)) + s
        return encoded_name + encoded_scope + '\0'
    else:
        return encoded_name + '\0' 
Example #10
Source File: ChainSeparator.py    From biskit with GNU General Public License v3.0 6 votes vote down vote up
def _assign_seg_ids(self):
        """
        Assign new segment id to each chain.
        """
        counter = self.chainIdOffset
        for chain in self.chains:

            ## Assemble segid from pdb code + one letter out of A to Z
            chain.segment_id = self.pdbname()[:3] + string.uppercase[counter]
            counter = counter + 1
            try:                        # report changed segement ids
                chain_id = chain.chain_id
                self.log.add("changed segment ID of chain "+chain_id+\
                             " to "+chain.segment_id)
            except:
                T.errWriteln("_assign_seg_ids(): logerror") 
Example #11
Source File: texi2html.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def increment(s):
    if not s:
        return '1'
    for sequence in string.digits, string.lowercase, string.uppercase:
        lastc = s[-1]
        if lastc in sequence:
            i = sequence.index(lastc) + 1
            if i >= len(sequence):
                if len(s) == 1:
                    s = sequence[0]*2
                    if s == '00':
                        s = '10'
                else:
                    s = increment(s[:-1]) + sequence[0]
            else:
                s = s[:-1] + sequence[i]
            return s
    return s # Don't increment 
Example #12
Source File: models.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def validate_username(cls, username):
        """ Returns None if the username is valid and does not exist. """
        un = username.lower()

        if (un in Config['blocked_usernames']
                or any(fragment in un for fragment in Config['blocked_username_fragments'])
                or any(fragment in un for fragment in Config['autoflag_words'])):
            return "Sorry, this username is not allowed."

        if len(un) < 3:
            return "Username must be 3 or more characters."

        if len(un) > 16:
            return "Username must be 16 characters or less."

        alphabet = string.lowercase + string.uppercase + string.digits + '_'
        if not all(char in alphabet for char in username):
            return "Usernames can only contain letters, digits and underscores."
        if User.objects.filter(username__iexact=username):
            return "This username is taken :(" 
Example #13
Source File: models.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def validate_username(cls, username, skip_uniqueness_check=False):
        """ Returns None if the username is valid and does not exist. """
        un = username.lower()

        if (un in Config['blocked_usernames']
                or any(fragment in un for fragment in Config['blocked_username_fragments'])
                or any(fragment in un for fragment in Config['autoflag_words'])):
            return "Sorry, this username is not allowed."

        if not un:
            return "Please enter a username."
        elif len(un) < 3:
            return "Username must be 3 or more characters."
        elif len(un) > 16:
            return "Username must be 16 characters or less."

        alphabet = string.lowercase + string.uppercase + string.digits + '_'
        if not all(char in alphabet for char in username):
            return "Usernames can only contain letters, digits and underscores."

        if not skip_uniqueness_check:
            if cls.objects.filter(username__iexact=username):
                return "Sorry! This username is taken. Please pick a different username." 
Example #14
Source File: targets.py    From chordrec with MIT License 6 votes vote down vote up
def _targets_to_annotations(self, targets):
        natural = zip([0, 2, 3, 5, 7, 8, 10], string.uppercase[:7])
        sharp = map(lambda v: ((v[0] + 1) % 12, v[1] + '#'), natural)

        semitone_to_label = dict(sharp + natural + [(12, 'N')])
        spf = 1. / self.fps
        labels = [(i * spf, semitone_to_label[p])
                  for i, p in enumerate(targets)]

        # join same consequtive predictions
        prev_label = (None, None)
        uniq_labels = []

        for label in labels:
            if label[1] != prev_label[1]:
                uniq_labels.append(label)
                prev_label = label

        # end time of last label is one frame duration after
        # the last prediction time
        start_times, chord_labels = zip(*uniq_labels)
        end_times = start_times[1:] + (labels[-1][0] + spf,)

        return zip(start_times, end_times, chord_labels) 
Example #15
Source File: dir_vol_download.py    From libvirt-test-API with GNU General Public License v2.0 6 votes vote down vote up
def write_file(path, capacity):
    """write test data to file
    """
    logger.info("write %s data into file %s" % (capacity, path))
    out = utils.get_capacity_suffix_size(capacity)
    f = open(path, 'w')
    if sys.version_info[0] < 3:
        datastr = ''.join(string.lowercase + string.uppercase +
                          string.digits + '.' + '\n')
    else:
        datastr = ''.join(string.ascii_lowercase + string.ascii_uppercase +
                          string.digits + '.' + '\n')
    repeat = int(out['capacity_byte'] / 64)
    data = ''.join(repeat * datastr)
    f.write(data)
    f.close() 
Example #16
Source File: texi2html.py    From datafari with Apache License 2.0 6 votes vote down vote up
def increment(s):
    if not s:
        return '1'
    for sequence in string.digits, string.lowercase, string.uppercase:
        lastc = s[-1]
        if lastc in sequence:
            i = sequence.index(lastc) + 1
            if i >= len(sequence):
                if len(s) == 1:
                    s = sequence[0]*2
                    if s == '00':
                        s = '10'
                else:
                    s = increment(s[:-1]) + sequence[0]
            else:
                s = s[:-1] + sequence[i]
            return s
    return s # Don't increment 
Example #17
Source File: texi2html.py    From oss-ftp with MIT License 6 votes vote down vote up
def increment(s):
    if not s:
        return '1'
    for sequence in string.digits, string.lowercase, string.uppercase:
        lastc = s[-1]
        if lastc in sequence:
            i = sequence.index(lastc) + 1
            if i >= len(sequence):
                if len(s) == 1:
                    s = sequence[0]*2
                    if s == '00':
                        s = '10'
                else:
                    s = increment(s[:-1]) + sequence[0]
            else:
                s = s[:-1] + sequence[i]
            return s
    return s # Don't increment 
Example #18
Source File: httpServerLogParser.py    From phpsploit with GNU General Public License v3.0 6 votes vote down vote up
def getLogLineBNF():
    global logLineBNF
    
    if logLineBNF is None:
        integer = Word( nums )
        ipAddress = delimitedList( integer, ".", combine=True )
        
        timeZoneOffset = Word("+-",nums)
        month = Word(string.uppercase, string.lowercase, exact=3)
        serverDateTime = Group( Suppress("[") + 
                                Combine( integer + "/" + month + "/" + integer +
                                        ":" + integer + ":" + integer + ":" + integer ) +
                                timeZoneOffset + 
                                Suppress("]") )
                         
        logLineBNF = ( ipAddress.setResultsName("ipAddr") + 
                       Suppress("-") +
                       ("-" | Word( alphas+nums+"@._" )).setResultsName("auth") +
                       serverDateTime.setResultsName("timestamp") + 
                       dblQuotedString.setResultsName("cmd").setParseAction(getCmdFields) +
                       (integer | "-").setResultsName("statusCode") + 
                       (integer | "-").setResultsName("numBytesSent")  + 
                       dblQuotedString.setResultsName("referrer").setParseAction(removeQuotes) +
                       dblQuotedString.setResultsName("clientSfw").setParseAction(removeQuotes) )
    return logLineBNF 
Example #19
Source File: main.py    From pacu with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_valid_password(password_policy):
    symbols = '!@#$%^&*()_+=-\][{}|;:",./?><`~'
    password = ''.join(choice(string.ascii_lowercase) for _ in range(3))
    try:
        if password_policy['RequireNumbers'] is True:
            password += ''.join(choice(string.digits) for _ in range(3))
        if password_policy['RequireSymbols'] is True:
            password += ''.join(choice(symbols) for _ in range(3))
        if password_policy['RequireUppercaseCharacters'] is True:
            password += ''.join(choice(string.uppercase) for _ in range(3))
        if password_policy['MinimumPasswordLength'] > 0:
            while len(password) < password_policy['MinimumPasswordLength']:
                password += choice(string.digits)
    except:
        # Password policy couldn't be grabbed for some reason, make a max-length
        # password with all types of characters, so no matter what, it will be accepted.
        characters = string.ascii_lowercase + string.ascii_uppercase + string.digits + symbols
        password = ''.join(choice(characters) for _ in range(128))
    return password 
Example #20
Source File: nmb.py    From PiBunny with MIT License 5 votes vote down vote up
def _do_first_level_encoding(m):
    s = ord(m.group(0))
    return string.uppercase[s >> 4] + string.uppercase[s & 0x0f] 
Example #21
Source File: OL_OSX_decryptor.py    From malware-research with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def custom_b64decode(encoded_str):
    normal_abc = string.uppercase + string.lowercase + string.digits + "+/"
    custom_abc = GetManyBytes(CUSTOM_B64_ALPHA, 0x40)
    decode_abc = string.maketrans(custom_abc, normal_abc)
    try:
        decoded = b64decode(encoded_str.translate(decode_abc))
    except:
        decoded = ''
    return decoded 
Example #22
Source File: targets.py    From chordrec with MIT License 5 votes vote down vote up
def _targets_to_annotations(self, targets):
        natural = zip([0, 2, 3, 5, 7, 8, 10], string.uppercase[:7])
        sharp = map(lambda v: ((v[0] + 1) % 12, v[1] + '#'), natural)

        semitone_to_label = dict(sharp + natural)

        def pred_to_label(pred):
            if pred == 24:
                return 'N'
            return '{}:{}'.format(semitone_to_label[pred % 12],
                                  'maj' if pred < 12 else 'min')

        spf = 1. / self.fps
        labels = [(i * spf, pred_to_label(p)) for i, p in enumerate(targets)]

        # join same consequtive predictions
        prev_label = (None, None)
        uniq_labels = []

        for label in labels:
            if label[1] != prev_label[1]:
                uniq_labels.append(label)
                prev_label = label

        # end time of last label is one frame duration after
        # the last prediction time
        start_times, chord_labels = zip(*uniq_labels)
        end_times = start_times[1:] + (labels[-1][0] + spf,)

        return zip(start_times, end_times, chord_labels) 
Example #23
Source File: core.py    From VN_IME with GNU General Public License v3.0 5 votes vote down vote up
def _accepted_chars(rules):
    if sys.version_info[0] > 2:
        ascii_letters = \
            string.ascii_letters
    else:
        ascii_letters = \
            string.lowercase + \
            string.uppercase

    return set(ascii_letters + ''.join(rules.keys()) + utils.VOWELS + "đ") 
Example #24
Source File: test_string.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example #25
Source File: gyptest-generator-output-different-drive.py    From kawalpemilu2014 with GNU Affero General Public License v3.0 5 votes vote down vote up
def GetFirstFreeDriveLetter():
    """ Returns the first unused Windows drive letter in [A, Z] """
    all_letters = [c for c in string.uppercase]
    in_use = win32api.GetLogicalDriveStrings()
    free = list(set(all_letters) - set(in_use))
    return free[0] 
Example #26
Source File: passgen.py    From BruteforceHTTP with GNU General Public License v3.0 5 votes vote down vote up
def toggle_case(text):
	# https://stackoverflow.com/a/29184387
	# Generate dict; keys = lower characters and values = upper characters
	text, SUBSTITUTIONS = text.lower(), dict(zip(string.lowercase, string.uppercase))
	
	from itertools import product
	possibilities = [c + SUBSTITUTIONS.get(c, "") for c in text]
	for subbed in product(*possibilities):
		yield "".join(subbed) 
Example #27
Source File: common.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def draw(self):
        self._calculate()
        oa, oA = ord('a') - 1, ord('A') - 1
        barWidth = self.barWidth
        left = self.quiet and self.lquiet or 0

        for c in self.decomposed:
            oc = ord(c)
            if c in string.lowercase:
                left = left + (oc - oa) * barWidth
            elif c in string.uppercase:
                w = (oc - oA) * barWidth
                self.rect(left, 0, w, self.barHeight)
                left += w
        self.drawHumanReadable() 
Example #28
Source File: utils.py    From GdbPlugins with GNU General Public License v3.0 5 votes vote down vote up
def cyclic_pattern_charset(charset_type=None):
    """
    Generate charset for cyclic pattern

    Args:
        - charset_type: charset type
            0: basic (0-9A-za-z)
            1: extended (default)
            2: maximum (almost printable chars)

    Returns:
        - list of charset
    """

    charset = []
    charset += ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"] # string.uppercase
    charset += ["abcdefghijklmnopqrstuvwxyz"] # string.lowercase
    charset += ["0123456789"] # string.digits

    if not charset_type:
        charset_type = config.Option.get("pattern")

    if charset_type == 1: # extended type
        charset[1] = "%$-;" + re.sub("[sn]", "", charset[1])
        charset[2] = "sn()" + charset[2]

    if charset_type == 2: # maximum type
        charset += ['!"#$%&\()*+,-./:;<=>?@[]^_{|}~'] # string.punctuation

    mixed_charset = mixed = ''
    k = 0
    while True:
        for i in range(0, len(charset)): mixed += charset[i][k:k+1]
        if not mixed: break
        mixed_charset += mixed
        mixed = ''
        k+=1

    return mixed_charset 
Example #29
Source File: test_string.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example #30
Source File: dir_vol_wipe_pattern.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def write_file(path, capacity):
    """write test data to file
    """
    logger.info("write %s data into file %s" % (capacity, path))
    out = utils.get_capacity_suffix_size(capacity)
    f = open(path, 'w')
    datastr = ''.join(string.lowercase + string.uppercase +
                      string.digits + '.' + '\n')
    repeat = out['capacity_byte'] / 64
    data = ''.join(repeat * datastr)
    f.write(data)
    f.close()