Python string.uppercase() Examples

The following are code examples for showing how to use string.uppercase(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: texi2html.py    GNU Lesser General Public License v3.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 2
Project: Spyce   Author: imec-myhdl   File: netlist.py    GNU Lesser General Public License v2.1 6 votes vote down vote up
def isidentifier(ident):
    """Determines if string is valid Python identifier."""

    if not isinstance(ident, (str, unicode)):
        raise TypeError("expected str, but got {!r}".format(type(ident)))

    if not ident:
        return False

    if keyword.iskeyword(ident):
        return False

    first = '_' + string.lowercase + string.uppercase
    if ident[0] not in first:
        return False

    other = first + string.digits
    for ch in ident[1:]:
        if ch not in other:
            return False

    return True 
Example 3
Project: Ossian   Author: candlewill   File: naive_util.py    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 4
Project: smbproxy   Author: Seekscale   File: utils.py    GNU General Public License v2.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 5
Project: oss-ftp   Author: aliyun   File: texi2html.py    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 6
Project: OffSec   Author: ducatinat   File: pattern.py    GNU General Public License v3.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 7
Project: CityEnergyAnalyst   Author: architecture-building-systems   File: dashboard.py    MIT License 6 votes vote down vote up
def get_drives():
    """Get a list of valid drive letters on windows:

       In [12]: get_drives()
       Out[12]: ['C:', 'I:', 'K:', 'S:', 'Y:', 'Z:']

    On on-windows systems, returns None
    """
    if sys.platform == 'win32':
        import string
        from ctypes import windll
        drives = []
        bitmask = windll.kernel32.GetLogicalDrives()
        for letter in string.uppercase:
            if bitmask & 1:
                drives.append(letter + ':')
            bitmask >>= 1

        return drives
    else:
        return None 
Example 8
Project: genpass   Author: ssrathi   File: genpass_cli.py    The Unlicense 6 votes vote down vote up
def gen_passwd(length=DEFAULT_LENGTH, capitals=True, numerals=True, symbols=True):
    """
    Generate a random password of specified length

    :param length: Length of generated password
    :param capitals: Include CAPITAL letters in the password
    :param numerals: Include NUMERALS in the password
    :param symbols: Include SYMBOLS in the password
    """

    chars = string.lowercase
    if capitals:
        chars += string.uppercase
    if numerals:
        chars += string.digits
    if symbols:
        chars += "@#$%^&?*():;-="

    password = []
    for i in xrange(length):
        index = random.SystemRandom().randrange(len(chars))
        password.append(chars[index])
    return "".join(password) 
Example 9
Project: xunfeng   Author: caterqiu   File: utils.py    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
Project: security-scripts   Author: Und3rf10w   File: pattern.py    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 11
Project: JovianDSS-Cinder   Author: open-e   File: iscsi.py    Apache License 2.0 6 votes vote down vote up
def _get_provider_auth(self):
        """Get provider authentication for the volume.

        :return: string of auth method and credentials
        """
        if not self.jovian_chap_auth:
            return None

        field = string.lowercase + string.uppercase + string.digits
        chap_password = ''.join(random.sample(field,
                                              int(self.jovian_chap_pass_len)))

        if self.jovian_chap_username is not None:
            return '%(auth)s %(user)s %(pass)s' % {
                'auth': 'CHAP',
                'user': self.jovian_chap_username,
                'pass': chap_password
            }

        return None 
Example 12
Project: Ossian   Author: CSTR-Edinburgh   File: naive_util.py    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 13
Project: addon   Author: alfa-addon   File: utils.py    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 14
Project: pwning-tools   Author: peternguyen93   File: Pwn.py    GNU General Public License v3.0 6 votes vote down vote up
def cyclic(self, length = None, n = 4):
		charset = []
		charset += ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"] # string.uppercase
		charset += ["abcdefghijklmnopqrstuvwxyz"] # string.lowercase
		charset += ["0123456789"] # string.digits
		charset[1] = "%$-;" + re.sub("[sn]", "", charset[1])
		charset[2] = "sn()" + charset[2]
		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

		pattern = self.de_bruijn(mixed_charset, 3, length)
		return pattern 
Example 15
Project: ribolands   Author: bad-ants-fleet   File: cofold_kinetics.py    MIT License 6 votes vote down vote up
def get_species(fullseq, homophobic):
    ''' Split a sequence of multiple molecules ('&') into a list:
    :param: homophobic Choose whether to return homo-dimers or not

    :return: [(name, seq), (name&name, seq&seq), ...]
    '''
    subseqs = c.OrderedDict.fromkeys(fullseq.split('&'))
    species = list(string.uppercase[:len(subseqs)])
    monomers = zip(species, subseqs)

    dim = len(monomers)
    dimers = []
    for x in range(dim):
        for y in range(x, dim):
            if (homophobic and x == y):
                continue
            (speX, seqX) = monomers[x]
            (speY, seqY) = monomers[y]
            dimers.append((speX + '&' + speY, seqX + '&' + seqY))
    return monomers + dimers 
Example 16
Project: libvirt-test-API   Author: libvirt   File: dir_vol_download.py    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 17
Project: pacu   Author: RhinoSecurityLabs   File: main.py    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 18
Project: eye-keyboard   Author: emanuelvianna   File: control.py    GNU General Public License v2.0 6 votes vote down vote up
def _execute_choice(self):
        if self.col_num == -1:
            self.col_num = 0
        else:
            cell = self.table.cells[self.row_num].get(self.col_num)
            if cell.label in uppercase:
                self.phrase.text += cell.label
            if cell.label == Table.SPACE:
                self.phrase.add_space()
            elif cell.label == Table.CLEAN:
                self.phrase.erase_all()
            elif cell.label == Table.ERASE:
                self.phrase.erase_one()
            elif cell.label == Table.ALERT:
                self._play_alert_sound()
            elif cell.label == Table.READ:
                self.phrase.read()
            elif cell.label == Table.QUIT:
                exit(0)
            self.row_num = 0
            self.col_num = -1
        self.press_enter = False 
Example 19
Project: cardciphers   Author: atoponce   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def _create_iv(n):
    """ Create a random initialization vector.

    Prepend a plaintext message with 5 random characters in the same ciphertext
    character base as the rest of the ciphertext.

    Args:
        n (int): The number of random characters to generate.

    Returns:
        str: An initialization vector string.

    """

    r = random.SystemRandom()
    return "".join(r.choice(string.uppercase) for i in xrange(n)) 
Example 20
Project: cardciphers   Author: atoponce   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def _create_iv(n):
    """ Create a random initialization vector.

    Prepend a plaintext message with 5 random characters in the same ciphertext
    character base as the rest of the ciphertext.

    Args:
        n (int): The number of random characters to generate

    Returns:
        str: An initialization vector string.

    """

    r = random.SystemRandom()
    return "".join(r.choice(string.uppercase) for i in xrange(n)) 
Example 21
Project: cardciphers   Author: atoponce   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def _create_iv(n, base):
    """ Create a random initialization vector.

    Prepend a plaintext message with 5 random characters in the same ciphertext
    character base as the rest of the ciphertext.

    Args:
        n (int): The number of random characters to generate.
        base (int): The input/output base of the plaintext/ciphertext.

    Returns:
        str: An initialization vector string.

    """

    r = random.SystemRandom()
    if base is 26:
        return "".join(r.choice(string.uppercase) for i in xrange(n))
    else:
        return "".join(r.choice(string.ascii_letters) for i in xrange(n)) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_string.py    GNU Lesser General Public License v3.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 23
Project: xia2   Author: xia2   File: to_shelx.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_compound(compound):
    result = {}
    element = ""
    number = ""
    compound += "X"
    for c in compound:
        if c in string.uppercase:
            if not element:
                element += c
                continue
            if number == "":
                count = 1
            else:
                count = int(number)
            if element not in result:
                result[element] = 0
            result[element] += count
            element = "" + c
            number = ""
            if c == "X":
                break
        elif c in string.ascii_lowercase:
            element += c
        elif c in string.digits:
            number += c
    return result 
Example 24
Project: Miscellaneous   Author: Shinpachi8   File: common.py    Apache License 2.0 5 votes vote down vote up
def random_str(length=8):
    s = string.lowercase + string.uppercase + string.digits
    return "".join(random.sample(s, length)) 
Example 25
Project: HEG_ESP32   Author: moothyknight   File: hegmovie.py    MIT License 5 votes vote down vote up
def OpenDisc(self, evt=None):
        if sys.platform == 'win32':
            import string
            from ctypes import windll

            #driveTypes = ['DRIVE_UNKNOWN', 'DRIVE_NO_ROOT_DIR', 'DRIVE_REMOVABLE', 
            #              'DRIVE_FIXED', 'DRIVE_REMOTE', 'DRIVE_CDROM', 'DRIVE_RAMDISK']
            drives = []
            bitmask = windll.kernel32.GetLogicalDrives()
            for letter in string.uppercase:
                if bitmask & 1:
                    try:
                        typeIndex = windll.kernel32.GetDriveTypeW(u"%s:\\"%letter)
                        if typeIndex == 5: # 'DRIVE_CDROM'
                            drives.append(letter + ':')
                    except: pass
                bitmask >>= 1
                
            if not drives:
                 return error("No DVD drives could be found.")
        elif sys.platform == 'darwin':
            return error("This feature has not yet been implemented for Mac OS X.")
        else:
            return error("This feature has not yet been implemented for whatever operating system you're using.")
        
        dlg = wx.SingleChoiceDialog(self, message="Message", caption='Caption', choices=drives)
        res = dlg.ShowModal()
        if res == wx.ID_OK:
            drive = drives[dlg.GetSelection()]
            self.LoadVideo('dvd://' + drive + '\\')
            #print "I would now open drive %s" % drive 
Example 26
Project: CVE-2017-7494   Author: joxeankoret   File: nmb.py    GNU General Public License v3.0 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 27
Project: ironpython2   Author: IronLanguages   File: makegwenum.py    Apache License 2.0 5 votes vote down vote up
def is_interface_enum(enumtype):
  return not (enumtype[0] in string.uppercase and enumtype[2] in string.uppercase) 
Example 28
Project: ironpython2   Author: IronLanguages   File: test_string.py    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 29
Project: Ossian   Author: candlewill   File: naive_util.py    Apache License 2.0 5 votes vote down vote up
def unicode_character_to_safetext(char):
    """
    每一个unicode字符,用唯一的一个英文字符串替换表示,称为safetext
    work one out. The substitute
    should be safe to use with applications of interest (e.g. in HTK modelnames), and
    a perhaps over-cautious subset of ASCII is used for this (uppercase A-Z).

    TODO: [make this explanation complete]

     To enable
    reverse mapping, multicharacter safetexts are delimited with _.
    :param char: unicode字符
    :return: 英文字符串
    """
    ## Replacements to make greedily within unicode name:
    name_reps = {" ": "",
                 "-": "",
                 "0": "ZERO",
                 "1": "ONE",
                 "2": "TWO",
                 "3": "THREE",
                 "4": "FOUR",
                 "5": "FIVE",
                 "6": "SIX",
                 "7": "SEVEN",
                 "8": "EIGHT",
                 "9": "NINE"}
    if char in list("abcdefghijklmnopqrstuvwxyz"):
        substitute = char
    else:
        try:
            substitute = unicodedata.name(char)
        except ValueError:  ## got ValueError: no such name
            substitute = "PROBLEM_CHARACTER"
        for key in name_reps.keys():
            substitute = substitute.replace(key, name_reps[key])
        substitute = "_" + substitute + "_"
    return substitute


##-------- config processing ------- 
Example 30
Project: open-recipe   Author: dspray95   File: makegwenum.py    The Unlicense 5 votes vote down vote up
def is_interface_enum(enumtype):
  return not (enumtype[0] in string.uppercase and enumtype[2] in string.uppercase) 
Example 31
Project: BCN3DSigma-Profile-Generator   Author: BCN3D   File: ProgenSettings.py    GNU General Public License v3.0 5 votes vote down vote up
def init():
    # Generic
    global progenVersionNumber
    progenVersionNumber = '2.0.2'
    global progenBuildNumber
    progenBuildNumber = time.strftime("%d")+string.uppercase[int(time.strftime("%m"))]+string.uppercase[int(time.strftime("%y")[-1])]+time.strftime("%H")+time.strftime("%M")
    global profilesData
    profilesData = readProfilesData()
    global loggedData
    loggedData = ["LFilament;RFilament;Extruder;Quality;LNozzle;RNozzle;InfillExt;PrimaryExt;SupportExt;LFlow;RFlow;Layers/Infill;DefaultSpeed;FirstLayerUnderspeed;OutLineUnderspeed;SupportUnderspeed;FirstLayerHeightPercentage;LTemp;RTemp;BTemp;\n"]

    # Cura 2
    global cura2id
    cura2id = 'bcn3dsigma'
    global cura2Name
    cura2Name = 'Sigma'
    global cura2Manufacturer
    cura2Manufacturer = 'BCN3D Technologies'
    global cura2Category
    cura2Category = 'BCN3D Technologies'
    global cura2Author
    cura2Author = 'Guillem'
    global cura2PostProcessingPluginName
    cura2PostProcessingPluginName = 'Sigma Vitamins'
    global machineSettingsPluginName
    machineSettingsPluginName = 'SigmaSettingsAction' 
Example 32
Project: oss-ftp   Author: aliyun   File: test_string.py    MIT 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 33
Project: OffSec   Author: ducatinat   File: pattern.py    GNU General Public License v3.0 5 votes vote down vote up
def pattern_search(search_pattern):
    """
    Search for search_pattern in pattern. Convert from hex if given as such.
    """
    needle = search_pattern
    if len(needle) == 10 or len(needle) == 8:
        try:
            # (EIP = 0x41326641) Value can be given as either 0x41326641 or 41326641
            if needle.startswith('0x'):
                # Strip off '0x', convert to ASCII and reverse
                needle = needle[2:].decode('hex')
                needle = needle[::-1]
            else:
                needle = needle.decode('hex')
                needle = needle[::-1]
        except TypeError as e:
            print 'Unable to convert hex input:', e
            sys.exit(1)

    haystack = ''
    for upper in uppercase:
        for lower in lowercase:
            for digit in digits:
                haystack += upper+lower+digit
                found_at = haystack.find(needle)
                if found_at > -1:
                    print('Pattern %s first occurrence at position %d in pattern.' %
                          (search_pattern, found_at))
                    return

    print ('Couldn\'t find %s (%s) anywhere in the pattern.' %
           (search_pattern, needle)) 
Example 34
Project: cracke-dit   Author: eth0izzle   File: nmb.py    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 35
Project: tornado-ssdb-project   Author: ego008   File: helper.py    MIT License 5 votes vote down vote up
def random_str(n=8):
    allow = list(string.uppercase + string.digits)
    r = []
    for i in range(n):
        r.append(random.choice(allow))
    return ''.join(r)
    # return ''.join(random.sample(allow, n))


# 处理ssdb_008.py 接口返回的较原始的数据 
Example 36
Project: hask   Author: billpmurphy   File: syntax.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __getattr__(self, value):
        if not value[0] in string.uppercase:
            raise SyntaxError("Type constructor name must be capitalized")
        return __new_tcon_enum__(value) 
Example 37
Project: hask   Author: billpmurphy   File: syntax.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __getattr__(self, value):
        if not value[0] in string.uppercase:
            raise SyntaxError("Data constructor name must be capitalized")
        return __new_dcon_enum__(value) 
Example 38
Project: tvalacarta   Author: tvalacarta   File: nmb.py    GNU General Public License v3.0 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 39
Project: eve-metrics   Author: ccpgames   File: tools.py    MIT License 5 votes vote down vote up
def random_password(self):
        import string
        import random
        password = ''
        specials = r'!#$*'
        for i in range(0, 3):
            password += random.choice(string.lowercase)
            password += random.choice(string.uppercase)
            password += random.choice(string.digits)
            password += random.choice(specials)
        return ''.join(random.sample(password, len(password))) 
Example 40
Project: MoAL   Author: christabor   File: restful_eve.py    Apache License 2.0 5 votes vote down vote up
def _random_robot():
    return {'model': '{}{}-{}'.format(choice(uc), choice(uc), rr(0, 9999))} 
Example 41
Project: script-languages   Author: exasol   File: script_import.py    MIT License 5 votes vote down vote up
def test_import_is_semi_case_sensitive(self):
        def check(name, classname, n):
            self.query(udf.fixindent('''
                CREATE OR REPLACE java SCALAR SCRIPT
                foo()
                RETURNS INT AS
                %%import %s;
                class FOO {
                    static int run(ExaMetadata exa, ExaIterator ctx) throws Exception {
                        return %s.f();
                    }
                }
                /''' % (name, classname)))
            self.assertRowsEqual([(n,)],
                self.query('SELECT foo() FROM DUAL'))

        for name in 'bar', 'Bar', 'BAR':
            self.query(udf.fixindent('''
                CREATE java SCALAR SCRIPT
                "%s"()
                RETURNS INT AS
                class %s {
                    static int f() {
                            return %d;
                    }
                }
                /''' % (name, name, sum(x in string.uppercase for x in name))
                ))

        check("bar", "BAR", 3)
        check("Bar", "BAR", 3)
        check("\"Bar\"", "Bar", 1)
        check("\"bar\"", "bar", 0) 
Example 42
Project: script-languages   Author: exasol   File: script_import.py    MIT License 5 votes vote down vote up
def test_import_is_semi_case_sensitive(self):
        def check(name, n):
            self.query(udf.fixindent('''
                CREATE OR REPLACE EXTERNAL SCALAR SCRIPT
                foo()
                RETURNS INT AS
                # redirector @@redirector_url@@

                def run(ctx):
                    m = exa.import_script(%s)
                    return m.f()
                /''' % name))
            self.assertRowsEqual([(n,)],
                self.query('SELECT foo() FROM DUAL'))

        for name in 'bar', 'Bar', 'BAR':
            self.query(udf.fixindent('''
                CREATE EXTERNAL SCALAR SCRIPT
                "%s"()
                RETURNS INT AS
                # redirector @@redirector_url@@

                def f():
                    return %d
                /''' % (name, sum(x in string.uppercase for x in name))
                ))

        check("'bar'", 3)
        check("'Bar'", 3)
        check("'Bar'", 3)
        check("'\"Bar\"'", 1)
        check("'\"bar\"'", 0) 
Example 43
Project: script-languages   Author: exasol   File: script_import.py    MIT License 5 votes vote down vote up
def test_import_is_semi_case_sensitive(self):
        def check(name, n):
            self.query(udf.fixindent('''
                CREATE OR REPLACE python SCALAR SCRIPT
                foo()
                RETURNS INT AS

                def run(ctx):
                    m = exa.import_script(%s)
                    return m.f()
                /''' % name))
            self.assertRowsEqual([(n,)],
                self.query('SELECT foo() FROM DUAL'))

        for name in 'bar', 'Bar', 'BAR':
            self.query(udf.fixindent('''
                CREATE python SCALAR SCRIPT
                "%s"()
                RETURNS INT AS

                def f():
                    return %d
                /''' % (name, sum(x in string.uppercase for x in name))
                ))

        check("'bar'", 3)
        check("'Bar'", 3)
        check("'Bar'", 3)
        check("'\"Bar\"'", 1)
        check("'\"bar\"'", 0) 
Example 44
Project: script-languages   Author: exasol   File: script_import.py    MIT License 5 votes vote down vote up
def test_import_is_semi_case_sensitive(self):
        def check(name, n):
            self.query(udf.fixindent('''
                CREATE OR REPLACE r SCALAR SCRIPT
                foo()
                RETURNS INT AS

                run <- function(ctx) {
                    m <- exa$import_script(%s)
                    m$f()
                }
                /''' % name))
            self.assertRowsEqual([(n,)],
                self.query('SELECT foo() FROM DUAL'))

        for name in 'bar', 'Bar', 'BAR':
            self.query(udf.fixindent('''
                CREATE r SCALAR SCRIPT
                "%s"()
                RETURNS INT AS

                f <- function() {
                    %d
                }
                /''' % (name, sum(x in string.uppercase for x in name))
                ))

        check("'bar'", 3)
        check("'Bar'", 3)
        check("'Bar'", 3)
        check("'\"Bar\"'", 1)
        check("'\"bar\"'", 0) 
Example 45
Project: script-languages   Author: exasol   File: script_import.py    MIT License 5 votes vote down vote up
def test_import_is_semi_case_sensitive(self):
        def check(name, n):
            self.query(udf.fixindent('''
                CREATE OR REPLACE lua SCALAR SCRIPT
                foo()
                RETURNS DOUBLE AS

                function run(ctx)
                    exa.import(%s, 'm')
                    return m.f()
                end
                /''' % name))
            self.assertRowsEqual([(n,)],
                self.query('SELECT foo() FROM DUAL'))

        for name in 'bar', 'Bar', 'BAR':
            self.query(udf.fixindent('''
                CREATE lua SCALAR SCRIPT
                "%s"()
                RETURNS DOUBLE AS

                function f()
                    return %d
                end
                /''' % (name, sum(x in string.uppercase for x in name))
                ))

        check("'bar'", 3)
        check("'Bar'", 3)
        check("'Bar'", 3)
        check("'\"Bar\"'", 1)
        check("'\"bar\"'", 0) 
Example 46
Project: script-languages   Author: exasol   File: script_import.py    MIT License 5 votes vote down vote up
def test_import_is_semi_case_sensitive(self):
        def check(name, n):
            self.query(udf.fixindent('''
                CREATE OR REPLACE python3 SCALAR SCRIPT
                foo()
                RETURNS INT AS

                def run(ctx):
                    m = exa.import_script(%s)
                    return m.f()
                /''' % name))
            self.assertRowsEqual([(n,)],
                self.query('SELECT foo() FROM DUAL'))

        for name in 'bar', 'Bar', 'BAR':
            self.query(udf.fixindent('''
                CREATE python3 SCALAR SCRIPT
                "%s"()
                RETURNS INT AS

                def f():
                    return %d
                /''' % (name, sum(x in string.uppercase for x in name))
                ))

        check("'bar'", 3)
        check("'Bar'", 3)
        check("'Bar'", 3)
        check("'\"Bar\"'", 1)
        check("'\"bar\"'", 0) 
Example 47
Project: hws   Author: nash-x   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_random_passwd(**kwargs):
    """
    generate random password, include eight letters(upper + lower), eight
    digits.

    upper_num: the number of upper cases. must lower than 27
    lower_num: the number of lower cases. must lower than 27
    digit_num: the number of digits. must lower than 11
    special_num: the number of special cases. must lower than 33

    :return: password as string
    """
    password_list = []
    special_words = ['`', '~', '!', '@', '#', '$', '%', '^', '&', '*',
                     '(', ')', '-', '_', '+', '=', '\\', '|', '[', ']', '{',
                     '}', ':', ';', '\'', '"', ',', '<', '>', '.', '/','?']

    if "upper_num" in kwargs:
        password_list.extend(random.sample(string.uppercase,
                                           int(kwargs['upper_num'])))
    if "lower_num" in kwargs:
        password_list.extend(random.sample(string.lowercase,
                                           int(kwargs['lower_num'])))
    if "digit_num" in kwargs:
        password_list.extend(random.sample(string.digits,
                                           int(kwargs['digit_num'])))
    if "special_num" in kwargs:
        password_list.extend(random.sample(special_words,
                                           int(kwargs['special_num'])))

    # random places
    random.shuffle(password_list)
    return ''.join(password_list) 
Example 48
Project: security-scripts   Author: Und3rf10w   File: pattern.py    GNU General Public License v2.0 5 votes vote down vote up
def pattern_search(search_pattern):
    """
    Search for search_pattern in pattern. Convert from hex if given as such.
    """
    needle = search_pattern
    if len(needle) == 10 or len(needle) == 8:
        try:
            # (EIP = 0x41326641) Value can be given as either 0x41326641 or 41326641
            if needle.startswith('0x'):
                # Strip off '0x', convert to ASCII and reverse
                needle = needle[2:].decode('hex')
                needle = needle[::-1]
            else:
                needle = needle.decode('hex')
                needle = needle[::-1]
        except TypeError as e:
            print 'Unable to convert hex input:', e
            sys.exit(1)

    haystack = ''
    for upper in uppercase:
        for lower in lowercase:
            for digit in digits:
                haystack += upper+lower+digit
                found_at = haystack.find(needle)
                if found_at > -1:
                    print('Pattern %s first occurrence at position %d in pattern.' %
                          (search_pattern, found_at))
                    return

    print ('Couldn\'t find %s (%s) anywhere in the pattern.' %
           (search_pattern, needle)) 
Example 49
Project: Ossian   Author: CSTR-Edinburgh   File: naive_util.py    Apache License 2.0 5 votes vote down vote up
def unicode_character_to_safetext(char):
    '''
    work one out. The substitute 
    should be safe to use with applications of interest (e.g. in HTK modelnames), and
    a perhaps over-cautious subset of ASCII is used for this (uppercase A-Z).
    
    TODO: [make this explanation complete]
    
     To enable 
    reverse mapping, multicharacter safetexts are delimited with _. 
    '''
    ## Replacements to make greedily within unicode name:
    name_reps = {" ": "",
                 "-": "",
                 "0": "ZERO",
                 "1": "ONE",
                 "2": "TWO",
                 "3": "THREE",
                 "4": "FOUR",
                 "5": "FIVE",
                 "6": "SIX",
                 "7": "SEVEN",
                 "8": "EIGHT",
                 "9": "NINE"     }
    if char in list("abcdefghijklmnopqrstuvwxyz"):
        substitute = char
    else:          
        try:
            substitute = unicodedata.name(char)
        except ValueError:   ## got ValueError: no such name
            substitute = "PROBLEM_CHARACTER"
        for key in name_reps.keys():
            substitute = substitute.replace(key, name_reps[key])
        substitute = "_" + substitute + "_"    
    return substitute



##-------- config processing ------- 
Example 50
Project: phixlib   Author: mwielgoszewski   File: generators.py    ISC License 5 votes vote down vote up
def generate_Symbol(tag, **kwargs):
    return ''.join([random.choice(string.uppercase) for _ in xrange(random.randrange(1,5))]) 
Example 51
Project: openwrt-remote-manager   Author: jumpscale7   File: users_test.py    MIT License 5 votes vote down vote up
def test_changing_and_checking_passwords():
    test_user = 'daemon'

    # Generate a random password
    password = ''.join(random.choice(string.lowercase + string.uppercase + string.digits) for _ in range(10))

    assert not manager.users.check_password(test_user, password)

    manager.users.change_password(test_user, password)

    assert manager.users.check_password(test_user, password) 
Example 52
Project: obsolete.webrtc-gyp   Author: openpeer   File: gyptest-generator-output-different-drive.py    BSD 3-Clause "New" or "Revised" License 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 53
Project: phystricks   Author: LaurentClaessens   File: SudokuGridGraph.py    GNU General Public License v3.0 5 votes vote down vote up
def action_on_pspict(self,pspict):
        import string

        vlines=[]
        hlines=[]
        content=[]
        numbering=[]

        # Numbering (1,2,3, ... and A,B,C ...)
        for i in range(0,9):
            A=Point(  (i+1)*self.length-self.length/2,self.length/2  )
            A.parameters.symbol=""
            A.put_mark(0,0,string.uppercase[i],pspict=pspict)
            B=Point(-self.length/2,-i*self.length-self.length/2)
            B.parameters.symbol=""
            B.put_mark(0,0,string.digits[i+1],pspict=pspict)
            numbering.append(A)
            numbering.append(B)

        # Grid
        for i in range(0,10):
            v=Segment(Point(i*self.length,0),Point(i*self.length,-9*self.length))
            h=Segment(Point(0,-i*self.length),Point(9*self.length,-i*self.length))
            # for the subgrid
            if i%3==0 :
                v.parameters.linewidth=2
                h.parameters.linewidth=2
            vlines.append(v)
            hlines.append(h)
        # Content of the cells
        lines = self.question.split("\n")
        for i,li in enumerate(lines):
            for j,c in enumerate(li.split(",")):
                A=Point(j*self.length+self.length/2,-i*self.length-self.length/2)
                A.parameters.symbol=""
                if c=="i":
                    A.put_mark(3*self.length/9,text="\ldots",pspict=pspict,position="N")
                if c in [  str(k) for k in range(-9,10)  ] :
                    A.put_mark(0,0,c,pspict=pspict)
                content.append(A)
        pspict.DrawGraphs(vlines,hlines,content,numbering) 
Example 54
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 55
Project: Hot   Author: dsolimando   File: test_string.py    GNU General Public License v3.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 56
Project: WAScan   Author: m4ll0k   File: rand.py    GNU General Public License v3.0 5 votes vote down vote up
def r_string(n):
	""" random strings """
	return "".join([choice(uppercase+lowercase) for _ in xrange(0,int(n))]) 
Example 57
Project: snaps-kubernetes   Author: cablelabs   File: validation_utils.py    Apache License 2.0 5 votes vote down vote up
def validate_multus_network_macvlan_params(config):
    """
    Checks the presence of Macvlan parameters also check Macvlan
    network name format and validations of "type"
    """
    logger.info("checking Macvlan params")
    macvlan_nets = config_utils.get_multus_cni_macvlan_cfgs(config)
    if len(macvlan_nets) == 0:
        raise ValidationException('At least one macvlan network required')

    for macvlan_net in macvlan_nets:
        macvlan_conf = macvlan_net[consts.MACVLAN_NET_DTLS_KEY]
        validate_dict_data(macvlan_conf, consts.MACVLAN_PARENT_INTF_KEY)
        validate_dict_data(macvlan_conf, consts.HOSTNAME_KEY)
        validate_dict_data(macvlan_conf, consts.IP_KEY)
        validate_dict_data(macvlan_conf, consts.NODE_TYPE_MASTER)
        validate_dict_data(macvlan_conf, consts.TYPE_KEY)
        validate_dict_data(macvlan_conf, consts.NETWORK_NAME_KEY)

        net_name = macvlan_conf[consts.NETWORK_NAME_KEY]
        to_find = "_"
        count = net_name.find(to_find)
        count2 = len(filter(lambda x: x in string.uppercase, net_name))

        if not (count < 1 and count2 < 1):
            raise ValidationException("Network_name value format is wrong ")

        if macvlan_conf[consts.TYPE_KEY] == consts.NET_TYPE_LOCAL_TYPE:
            validate_dict_data(macvlan_conf, consts.RANGE_END_KEY)
            validate_dict_data(macvlan_conf, consts.RANGE_START_KEY)
            validate_dict_data(macvlan_conf, consts.ROUTES_DST_KEY)
            validate_dict_data(macvlan_conf, consts.SUBNET_KEY)
            validate_dict_data(macvlan_conf, consts.GATEWAY_KEY) 
Example 58
Project: registrasion   Author: chrisjrn   File: util.py    Apache License 2.0 5 votes vote down vote up
def generate_access_code():
    ''' Generates an access code for users' payments as well as their
    fulfilment code for check-in.
    The access code will 4 characters long, which allows for 1,500,625
    unique codes, which really should be enough for anyone. '''

    length = 6
    # all upper-case letters + digits 1-9 (no 0 vs O confusion)
    chars = string.uppercase + string.digits[1:]
    # 6 chars => 35 ** 6 = 1838265625 (should be enough for anyone)
    return get_random_string(length=length, allowed_chars=chars) 
Example 59
Project: libvirt-test-API   Author: libvirt   File: logical_vol_download.py    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 %sM data into file %s" % (capacity, path))
    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(capacity / 64)
    data = ''.join(repeat * datastr)
    f.write(data)
    f.close() 
Example 60
Project: libvirt-test-API   Author: libvirt   File: logical_vol_upload.py    GNU General Public License v2.0 5 votes vote down vote up
def write_file(path):
    """write 1M test data to file
    """
    logger.info("write 1M data into file %s" % path)
    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')
    data = ''.join(16384 * datastr)
    f.write(data)
    f.close() 
Example 61
Project: libvirt-test-API   Author: libvirt   File: dir_vol_upload.py    GNU General Public License v2.0 5 votes vote down vote up
def write_file(path):
    """write 1M test data to file
    """
    logger.info("write data into file %s" % path)
    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')
    data = ''.join(16384 * datastr)
    f.write(data)
    f.close() 
Example 62
Project: libvirt-test-API   Author: libvirt   File: dir_vol_wipe_pattern.py    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() 
Example 63
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 64
Project: opsbro   Author: naparuba   File: winstats.py    MIT License 5 votes vote down vote up
def get_drives():
    ''' Return a list of current drive letters.
        Recipe:
            http://stackoverflow.com/a/827398/450917
    '''
    drives = []
    bitmask = kernel32.GetLogicalDrives()
    for letter in string.uppercase:
        if bitmask & 1:
            drives.append(letter)
        bitmask >>= 1
    
    return drives 
Example 65
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 66
Project: scrimmage-scoreboard   Author: ShySec   File: tools.py    GNU General Public License v2.0 5 votes vote down vote up
def random_password(self):
        import string
        import random
        password = ''
        specials = r'!#$*'
        for i in range(0, 3):
            password += random.choice(string.lowercase)
            password += random.choice(string.uppercase)
            password += random.choice(string.digits)
            password += random.choice(specials)
        return ''.join(random.sample(password, len(password))) 
Example 67
Project: python   Author: CospanDesign   File: utils.py    MIT License 5 votes vote down vote up
def get_window_drives():
    """
    Returns a list of drives for a windows box

    Args:
        Nothing

    Return:
        Returns a list of drives in a list
    """
    if os.name != "nt":
        raise ConfigurationError("Not a windows box")

    import string
    from ctypes import windll

    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()
    for letter in string.uppercase:
        #For every letter of the alphabet (string.uppercase)
        if bitmask & 1:
            #if the associated bit for that letter is set
            drives.append(letter)
        bitmask >>= 1

    return drives 
Example 68
Project: GdbPlugins   Author: gatieme   File: utils.py    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 69
Project: BruteforceHTTP   Author: dmknght   File: passgen.py    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 70
Project: arkScript   Author: akbchris   File: makegwenum.py    MIT License 5 votes vote down vote up
def is_interface_enum(enumtype):
  return not (enumtype[0] in string.uppercase and enumtype[2] in string.uppercase) 
Example 71
Project: addrest   Author: JBrVJxsc   File: tools.py    MIT License 5 votes vote down vote up
def random_password(self):
        import string
        import random
        password = ''
        specials = r'!#$*'
        for i in range(0, 3):
            password += random.choice(string.lowercase)
            password += random.choice(string.uppercase)
            password += random.choice(string.digits)
            password += random.choice(specials)
        return ''.join(random.sample(password, len(password))) 
Example 72
Project: TER_Project   Author: rtbn   File: poodle.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, host, port):
        self.proxy_host = host
        self.proxy_port = port
        self.cookie = ''.join(random.SystemRandom().choice(string.uppercase + string.digits + string.lowercase) for _ in xrange(15))
        print draw("Sending request : ", bold=True, fg_yellow=True)
        print draw("GET / HTTP/1.1\r\nCookie: " + self.cookie + "\r\n\r\n",  bold=True, fg_yellow=True) 
Example 73
Project: TER_Project   Author: rtbn   File: BEAST.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, host, port, cbc):
        self.proxy_host = host
        self.proxy_port = port
        self.cbc = cbc
        self.cookie = ''.join(random.SystemRandom().choice(string.uppercase + string.digits + string.lowercase) for _ in xrange(15))
        print draw("Sending request : ", bold=True, fg_yellow=True)
        print draw("the secret is " + self.cookie +"\n\n",  bold=True, fg_yellow=True) 
Example 74
Project: xd   Author: century-arcade   File: httpxd.py    MIT License 4 votes vote down vote up
def find(self, grid="", xd=""):
        xdobj = self.corpus.get(xd) or httpxd.xd_from_grid(grid)
        gridstr = "".join([x for x in "".join(xdobj.grid).upper() if x in string.uppercase])
        if len(gridstr) < 15:  # one row, wouldn't really consider less than this a match anyway
            return self.error('please specify a more specific grid than "%s".  Example: <br/>%s' % (gridstr, self.example_grid))

        index_list = []
        dups = findsimilar.find_similar_to(xdobj, list(self.corpus.values()))
        for pct, needle, other, same_answers in sorted(dups):
            pct *= 100
            if xd:
                parms = {"left": xdfile.get_base_filename(other.filename), "right": xd}
            else:
                parms = {"left": xdfile.get_base_filename(other.filename), "right": grid}
            index_line = '%d%% <a href="/diff/?%s">%s</a> %s' % (pct, urllib.parse.urlencode(parms), xdfile.get_base_filename(other.filename), other.get_header("Author") or "")

            index_list.append((pct, index_line))

        r = mkwww.html_header.format(title="Crossword Search Results")
        r += "<ul>"

        fmt = '<li>%s</li>'
        sorted_list = sorted(index_list, reverse=True)
        matches = '\n'.join(fmt % L for pct, L in sorted_list if pct > 80)
        partial = '\n'.join(fmt % L for pct, L in sorted_list if 50 < pct <= 80)
        theme = '\n'.join(fmt % L for pct, L in sorted_list if 25 < pct <= 50)
        unlikely = '\n'.join(fmt % L for pct, L in sorted_list if pct <= 25)

        if matches:
            r += '\n<h3>Very similar</h3>\n' + matches

        if partial:
            r += '\n<h3>Partially similar</h3>\n' + partial

        if theme:
            r += '\n<h3>Possibly similar</h3>\n' + theme

        if not matches and not partial and not theme:
            r += "\n<h3>Nothing matched, but here's some dregs</h3>\n" + unlikely[:10]

        r += '</ul>'

        r += '<a href="/">search again</a>'
        r += mkwww.html_footer

        return r 
Example 75
Project: yamtbx   Author: keitaroyam   File: exclude_resolution_range.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(mtz, mtz_out, ranges):
    # Open mtz
    mtz_file = iotbx.mtz.object(mtz)
    miller_arrays = mtz_file.as_miller_arrays()
    print "Opening", mtz

    mtz_dataset = None
    labels = ["H", "K", "L"]

    for i, ar in enumerate(miller_arrays):
        d_spacings = ar.d_spacings().data()
        sel = flex.bool(d_spacings.size(), True)
        for d1, d2 in ranges:
            dmax, dmin = max(d1,d2), min(d1,d2)
            tmp = d_spacings > dmax
            tmp |= dmin > d_spacings
            sel &= tmp

        print "%d reflections removed from %s" % (sum(~sel), ar.info().label_string())
        fake_label = 2 * string.uppercase[i]
        for lab in guess_array_output_labels(ar):
            labels.append(lab)
        array_types = get_original_array_types(mtz_file, ar.info().labels)
        default_types = iotbx.mtz.default_column_types(ar)
        if len(default_types) == len(array_types):
            column_types = array_types
        else:
            column_types = None

        mtz_dataset = add_array_to_mtz_dataset(mtz_dataset, ar.select(sel), fake_label,
                                               column_types)


    # Decide labels and write mtz file
    mtz_object = mtz_dataset.mtz_object()
    invalid_chars = re.compile("[^A-Za-z0-9_\-+\(\)]")

    used = dict([ (label, 0) for label in labels ])

    for i, column in enumerate(mtz_object.columns()):
        if column.label() != labels[i] :
            label = labels[i]
            original_label = label

            assert used[label] == 0

            try:
                column.set_label(label)
            except RuntimeError, e:
                if ("new_label is used already" in str(e)) :
                    col_names = [ col.label() for col in mtz_object.columns() ]
                    raise RuntimeError(("Duplicate column label '%s': current labels "+
                                        "are %s; user-specified output labels are %s.") %
                                       (label, " ".join(col_names), " ".join(labels)))
            else:
                used[original_label] += 1 
Example 76
Project: yamtbx   Author: keitaroyam   File: apply_b_factor.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(mtz, bs):
    # Open mtz
    mtz_file = iotbx.mtz.object(mtz)
    miller_arrays = mtz_file.as_miller_arrays()
    print "Opening", mtz

    for b in bs:
        mtz_out = os.path.splitext(os.path.basename(args[1]))[0] + "_b%.2f.mtz" % b
        mtz_dataset = None
        labels = ["H", "K", "L"]
        
        for i, ar in enumerate(miller_arrays):
            fake_label = 2 * string.uppercase[i]
            for lab in guess_array_output_labels(ar):
                labels.append(lab)
            array_types = get_original_array_types(mtz_file, ar.info().labels)
            default_types = iotbx.mtz.default_column_types(ar)
            if len(default_types) == len(array_types):
                column_types = array_types
            else:
                column_types = None

            if ar.is_xray_data_array() or ar.is_complex_array():
                fac = 2. if ar.is_xray_intensity_array() else 1.
                print "Applying B=%.2f to %s" % (b*fac, ar.info())
                k = flex.exp(-ar.d_star_sq().data() * b*fac)
                ar = ar.customized_copy(data=ar.data()*k, sigmas=ar.sigmas()*k if ar.sigmas() else None)

            mtz_dataset = add_array_to_mtz_dataset(mtz_dataset, ar, fake_label,
                                                   column_types)

        # Decide labels and write mtz file
        mtz_object = mtz_dataset.mtz_object()
        invalid_chars = re.compile("[^A-Za-z0-9_\-+\(\)]")

        used = dict([ (label, 0) for label in labels ])

        for i, column in enumerate(mtz_object.columns()):
            if column.label() != labels[i] :
                label = labels[i]
                original_label = label

                assert used[label] == 0

                try:
                    column.set_label(label)
                except RuntimeError, e:
                    if ("new_label is used already" in str(e)) :
                        col_names = [ col.label() for col in mtz_object.columns() ]
                        raise RuntimeError(("Duplicate column label '%s': current labels "+
                                            "are %s; user-specified output labels are %s.") %
                                           (label, " ".join(col_names), " ".join(labels)))
                else:
                    used[original_label] += 1

        mtz_object.write(file_name=mtz_out)

        print
        print "Writing:", mtz_out
        print
# run() 
Example 77
Project: yamtbx   Author: keitaroyam   File: aniso_cutoff.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(mtzin, rescut, mtzout):
    # Open mtz
    mtz_file = iotbx.mtz.object(mtzin)
    miller_arrays = mtz_file.as_miller_arrays()
    print "Opening", mtzin

    mtz_dataset = None
    labels = ["H", "K", "L"]

    for i, ar in enumerate(miller_arrays):
        d_spacings = ar.d_spacings().data()
        sel = aniso_res_cut_selection(ar, *rescut)

        print "%d reflections removed from %s" % (sum(~sel), ar.info().label_string())
        fake_label = 2 * string.uppercase[i]
        for lab in guess_array_output_labels(ar):
            labels.append(lab)
        array_types = get_original_array_types(mtz_file, ar.info().labels)
        default_types = iotbx.mtz.default_column_types(ar)
        if len(default_types) == len(array_types):
            column_types = array_types
        else:
            column_types = None

        mtz_dataset = add_array_to_mtz_dataset(mtz_dataset, ar.select(sel), fake_label,
                                               column_types)


    # Decide labels and write mtz file
    mtz_object = mtz_dataset.mtz_object()
    invalid_chars = re.compile("[^A-Za-z0-9_\-+\(\)]")

    used = dict([ (label, 0) for label in labels ])

    for i, column in enumerate(mtz_object.columns()):
        if column.label() != labels[i] :
            label = labels[i]
            original_label = label

            assert used[label] == 0

            try:
                column.set_label(label)
            except RuntimeError, e:
                if ("new_label is used already" in str(e)) :
                    col_names = [ col.label() for col in mtz_object.columns() ]
                    raise RuntimeError(("Duplicate column label '%s': current labels "+
                                        "are %s; user-specified output labels are %s.") %
                                       (label, " ".join(col_names), " ".join(labels)))
            else:
                used[original_label] += 1 
Example 78
Project: Beginners-Python-Examples   Author: AsciiKay   File: caesars_cipher_encryption.py    GNU General Public License v3.0 4 votes vote down vote up
def caesars_cipher_encoding(s, k, lowercase = True, uppercase = False):
	
	# To encrypt plain text in either 
	# uppercase letters or lowercase letters
	if lowercase:
		alphas = list(string.lowercase)
	elif uppercase:
		alphas = list(string.uppercase)

	encrypted = ""
	# List characters in orignal string
	char_s = list(s)

	# Shifting of each single 
	# character in orignal string
	# using given key
	for char in char_s:

		# avoid encryption of spaces
		if char == " ":
			encrypted += " "
		
		else:  
			# n_index or new index is
			# the index of encrypted character
			n_index = k + alphas.index(char)
			
			# if encrypted character is greater than
			# length of english alphabets
			if n_index > 25:

				# Read explaination on line 59
				while not n_index <= 25:
					n_index = n_index - 26
				encrypted += alphas[n_index]
			
			# simple shift
			else:
				encrypted += alphas[n_index]
				
	return encrypted

# Explaination of key bigger than 26:
# say we have key 54, 
# we add index of char(say 'a') to key, i.e. key = 54 + 1 = 55
# so after first iteration over array of length(26), 
# i.e. 55(total iterations to perform) - 26(iterations completed) = 29(iterations left)
# but, 29 is still a big index i.e. 29 > length of array(26)
# so we continue to subtract more 26(iterations), 
# i.e. 29(iterations to perform) - (26 iterations done) = 3(remaining)
# so 3 is smaller than length of array and can be used as key, 
# i.e. 3 < 26(length of array)
# thus, we reached at index of 3 after 54 iterations over an array of length 26
# bit complicated but read it twice, you'll master it!

# Test, Playing UI 
Example 79
Project: Beginners-Python-Examples   Author: AsciiKay   File: caesars_cipher_encryption.py    GNU General Public License v3.0 4 votes vote down vote up
def caesars_cipher_encoding(s, k, lowercase = True, uppercase = False):
	
	# To encrypt plain text in either 
	# uppercase letters or lowercase letters
	if lowercase:
		alphas = list(string.lowercase)
	elif uppercase:
		alphas = list(string.uppercase)

	encrypted = ""
	# List characters in orignal string
	char_s = list(s)

	# Shifting of each single 
	# character in orignal string
	# using given key
	for char in char_s:

		# avoid encryption of spaces
		if char == " ":
			encrypted += " "
		
		else:  
			# n_index or new index is
			# the index of encrypted character
			n_index = k + alphas.index(char)
			
			# if encrypted character is greater than
			# length of english alphabets
			if n_index > 25:

				# Read explaination on line 59
				while not n_index <= 25:
					n_index = n_index - 26
				encrypted += alphas[n_index]
			
			# simple shift
			else:
				encrypted += alphas[n_index]
				
	return encrypted

# Explaination of key bigger than 26:
# say we have key 54, 
# we add index of char(say 'a') to key, i.e. key = 54 + 1 = 55
# so after first iteration over array of length(26), 
# i.e. 55(total iterations to perform) - 26(iterations completed) = 29(iterations left)
# but, 29 is still a big index i.e. 29 > length of array(26)
# so we continue to subtract more 26(iterations), 
# i.e. 29(iterations to perform) - (26 iterations done) = 3(remaining)
# so 3 is smaller than length of array and can be used as key, 
# i.e. 3 < 26(length of array)
# thus, we reached at index of 3 after 54 iterations over an array of length 26
# bit complicated but read it twice, you'll master it!

# Test, Playing UI 
Example 80
Project: chordrec   Author: fdlm   File: targets.py    MIT License 4 votes vote down vote up
def _annotations_to_targets(self, labels):
        """
        Maps chord annotations to 25 classes (12 major, 12 minor, 1 no chord)

        :param labels: chord labels
        :return: one-hot encoding of class id per annotation
        """
        # first, create chord/class mapping. root note 'A' has id 0, increasing
        # with each semitone. we have duplicate mappings for flat and sharp
        # notes, just to be sure.
        natural = zip(string.uppercase[:7], [0, 2, 3, 5, 7, 8, 10])
        sharp = map(lambda v: (v[0] + '#', (v[1] + 1) % 12), natural)
        flat = map(lambda v: (v[0] + 'b', (v[1] - 1) % 12), natural)

        # 'no chord' is coded as 'N'. The class ID of 'N' is 24, after all
        # major and minor chords. Sometimes there is also an 'X' annotation,
        # meaning that the chord cannot be properly determined on beat-lebel
        # (too much going on in the audio). We will treat this also as
        # 'no chord'
        root_note_map = dict(natural + sharp + flat + [('N', 24), ('X', 24)])

        # then, we load the annotations, map the chords to class ids, and
        # finally map class ids to a one-hot encoding. first, map the root
        # notes.
        chord_root_notes = [c.split(':')[0].split('/')[0] for c in labels]
        chord_root_note_ids = np.array([root_note_map[crn]
                                        for crn in chord_root_notes])

        # then, map the chords to major and minor. we assume chords with a
        # minor third as first interval are considered minor chords,
        # the rest are major chords, following MIREX, as stated in
        # Taemin Cho, Juan Bello: "On the relative importance of Individual
        # Components of Chord Recognition Systems"

        chord_type = [c.split(':')[1] if ':' in c else '' for c in labels]

        # we will shift the class ids for all minor notes by 12
        # (num major chords)
        chord_type_shift = np.array(
            map(lambda x: 12 if 'min' in x or 'dim' in x else 0, chord_type)
        )

        # now we can compute the final chord class id
        return one_hot(chord_root_note_ids + chord_type_shift,
                       self.num_classes)