Python string 模块,lowercase() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.lowercase()

项目:pogom-linux    作者:PokeHunterProject    | 项目源码 | 文件源码
def read_config(scan_config):
    config_path = os.path.join(
        os.path.dirname(os.path.realpath(sys.argv[0])), "config.json")

    if os.path.isfile(config_path):
        config['CONFIG_PATH'] = config_path

    try:
        with open(config_path, "r") as f:
            c = json.loads(f.read())
    except:
        c = {}

    config['LOCALE'] = c.get('LOCALE', 'en')
    config['GOOGLEMAPS_KEY'] = c.get('GOOGLEMAPS_KEY', None)
    config['CONFIG_PASSWORD'] = c.get('CONFIG_PASSWORD', None)
    config['ACCOUNTS'] = c.get('ACCOUNTS', [])
    scan_config.update_scan_locations(c.get('SCAN_LOCATIONS', {}))

    if config.get('CONFIG_PASSWORD', None):
        config['AUTH_KEY'] = ''.join(random.choice(string.lowercase) for _ in range(32))
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def ex3(argv):

    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)]

    return ''.join(random.sample(password,len(password)))
项目:cpyparsing    作者:evhub    | 项目源码 | 文件源码
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
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def ssl_authenticator():
    try:
        import pupy_credentials
        keystr=pupy_credentials.SSL_BIND_KEY
        certstr=pupy_credentials.SSL_BIND_CERT
    except:
        keystr=DEFAULT_SSL_BIND_KEY
        certstr=DEFAULT_SSL_BIND_CERT
    key_path=None
    cert_path=None
    if os.path.isfile("pupy.conf"):
        config = configparser.ConfigParser()
        config.read("pupy.conf")
        key_path=config.get("pupyd","keyfile").replace("\\",os.sep).replace("/",os.sep)
        cert_path=config.get("pupyd","certfile").replace("\\",os.sep).replace("/",os.sep)
    else:
        tmpdir=tempfile.gettempdir()
        cert_path=os.path.join(tmpdir, ''.join(random.choice(string.lowercase+string.digits) for _ in range(random.randint(5,8))))
        key_path=os.path.join(tmpdir,''.join(random.choice(string.lowercase+string.digits) for _ in range(random.randint(5,8))))
        with open(cert_path,'wb') as f:
            f.write(certstr.strip())
        with open(key_path,'wb') as f:
            f.write(keystr.strip())
    return SSLAuthenticator(key_path, cert_path, ciphers="SHA256+AES256:SHA1+AES256:@STRENGTH")
项目:lc-all-solutions    作者:csujedihy    | 项目源码 | 文件源码
def detectCapitalUse(self, word):
        """
        :type word: str
        :rtype: bool
        """
        ud = set(string.uppercase)
        ld = set(string.lowercase)
        n = len(word)
        cap = 0
        for c in word:
            if c in ud:
                cap += 1
        if cap == n:
            return True
        if cap == 1 and word[0] in ud:
            return True
        return False if cap > 0 else True
项目:imgpedia    作者:scferrada    | 项目源码 | 文件源码
def compute(self, image):
        directory = ''.join(random.choice(string.lowercase) for _ in range(8))
        if not os.path.exists(directory):
            os.makedirs(directory)
        image = cv2.resize(image, self.size)
        patches = []
        patches.append(image)
        patches.append(image[:self.patch_size, :self.patch_size])
        patches.append(image[32:,32:])
        patches.append(image[32:, :self.patch_size])
        patches.append(image[:self.patch_size, 32:])
        patches.append(image[16:-16, 16:-16])
        patches.append(image[16:-16, 32:])
        patches.append(image[16:-16, :self.patch_size])
        patches.append(image[32:, 16:-16])
        patches.append(image[:self.patch_size, 16:-16])

        descriptor = np.zeros((1,4096))
        for i in range(len(patches)):
            filepath = os.path.join(directory, ("%d.jpg" % i))
            cv2.imwrite(filepath, patches[i])
            descriptor = descriptor + self.compute_oversample(filepath)
        shutil.rmtree(directory)
        return descriptor/len(patches)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def ssl_authenticator():
    try:
        import pupy_credentials
        keystr=pupy_credentials.SSL_BIND_KEY
        certstr=pupy_credentials.SSL_BIND_CERT
    except:
        keystr=DEFAULT_SSL_BIND_KEY
        certstr=DEFAULT_SSL_BIND_CERT
    key_path=None
    cert_path=None
    if os.path.isfile("pupy.conf"):
        config = configparser.ConfigParser()
        config.read("pupy.conf")
        key_path=config.get("pupyd","keyfile").replace("\\",os.sep).replace("/",os.sep)
        cert_path=config.get("pupyd","certfile").replace("\\",os.sep).replace("/",os.sep)
    else:
        tmpdir=tempfile.gettempdir()
        cert_path=os.path.join(tmpdir, ''.join(random.choice(string.lowercase+string.digits) for _ in range(random.randint(5,8))))
        key_path=os.path.join(tmpdir,''.join(random.choice(string.lowercase+string.digits) for _ in range(random.randint(5,8))))
        with open(cert_path,'wb') as f:
            f.write(certstr.strip())
        with open(key_path,'wb') as f:
            f.write(keystr.strip())
    return SSLAuthenticator(key_path, cert_path, ciphers="SHA256+AES256:SHA1+AES256:@STRENGTH")
项目:WebScraping    作者:liinnux    | 项目源码 | 文件源码
def main():
    template_url = 'http://example.webscraping.com/ajax/search.json?page={}&page_size=10&search_term={}'
    countries = set()
    download = downloader.Downloader(mongo_cache.MongoCache())

    for letter in string.lowercase:
        page = 0
        while True:
            html = download(template_url.format(page, letter))
            try:
                ajax = json.loads(html)
            except ValueError as e:
                print e
                ajax = None
            else:
                for record in ajax['records']:
                    countries.add(record['country'])
            page += 1
            if ajax is None or page >= ajax['num_pages']:
                break

    open('countries.txt', 'w').write('\n'.join(sorted(countries)))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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
项目:pwndemo    作者:zh-explorer    | 项目源码 | 文件源码
def randoms(count, alphabet = string.lowercase):
    """randoms(count, alphabet = string.lowercase) -> str

    Returns a random string of a given length using only the specified alphabet.

    Arguments:
      count (int): The length of the desired string.
      alphabet: The alphabet of allowed characters. Defaults to all lowercase characters.

    Returns:
      A random string.

    Example:

      >>> randoms(10) #doctest: +SKIP
      'evafjilupm'
"""

    return ''.join(random.choice(alphabet) for _ in xrange(count))
项目:sflearn    作者:GeorgeArgyros    | 项目源码 | 文件源码
def main():
    parser = _create_argument_parser()
    args = parser.parse_args()

    # Alphabet for the experiments
    I = [ord(x) for x in string.punctuation + string.lowercase]

    enc_learn = EncoderLearner(I)
    print '[+] Learning HTML Encoder: ',
    sanitizer = enc_learn.learn_mealy_machine()
    print 'OK'

    print '[+] Saving transducer model in file {}.txt: '.format(args.outfile),
    sanitizer.save(args.outfile + '.txt')
    print 'OK'

    if args.save_bek:
        print '[+] Saving BEK program in file {}.bek: '.format(args.outfile),
        bek = BekProgram()
        bek.create_from_transducer(sanitizer)
        bek.save(args.outfile + '.bek')
        print 'OK'
项目:HackerRank    作者:xkal36    | 项目源码 | 文件源码
def get_num_ops(s):
    if s == s[::-1]:
        return 0
    else:
        list_s = list(s)
        alph = string.lowercase
        len_s = len(s) 
        index = 0
        num_ops = 0
        while index < len_s:
            if s[index] != s[(len_s - 1) - index]:
                if s[(len_s - 1) - index] > s[index]:
                    list_s[(len_s - 1) - index] = list_s[index]
                else:
                    list_s[index] = list_s[(len_s - 1) - index]
                num_ops += abs(alph.find(s[(len_s - 1) - index]) - alph.find(s[index]))
            index += 1
        return num_ops / 2
项目:MCMC-Metropolis-Hastings-Decryption    作者:jhell96    | 项目源码 | 文件源码
def create_mapping_from_cipher(cipher):
    """
    Creates the mapping between the alphabet string and the cipher string

    Inputs
    ------
    cipher : a string, in which order matters, that is mapped to from the alphabet in the 
             encrypted document i.e. abcdefg.. -> udhjenk...

    Returns
    -------
    a dictionary in which each key is a letter of the alphabet, and each value is
    the corresponding letter in the cipher
    """
    charset = list(string.lowercase)
    return {charset.pop(0):elem for elem in cipher}
项目:crypto    作者:erose1337    | 项目源码 | 文件源码
def crack_monoalphabetic_substitution_cipher(ciphertext, dictionary):
    lowercase_ascii = string.lowercase
    ciphertext_words = sorted(ciphertext.split(), key=len)    
    sorted_dictionary = sorted(dictionary, key=len)

    biggest_word_size = len(ciphertext_words[-1])
    key = {}
    searching = True                                       
    for ciphertext_word in (bytearray(word) for word in reversed(sorted_dictionary)):
        word_size = len(ciphertext_word)
        for branch, dictionary_word in enumerate((bytearray(word) for word in 
                                                  reversed(sorted_dictionary) if 
                                                  len(word) == word_size)):
            for index, letter in enumerate(dictionary_word):
                try:
                    key[branch][letter] = ciphertext_word[index]
                except KeyError:
                    _key = bytearray(26)
                    _key[letter] = ciphertext_word[index]
                    key[branch] = _key
项目:pogom    作者:favll    | 项目源码 | 文件源码
def read_config(scan_config):
    config_path = os.path.join(
        os.path.dirname(os.path.realpath(sys.argv[0])), "config.json")

    if os.path.isfile(config_path):
        config['CONFIG_PATH'] = config_path

    try:
        with open(config_path, "r") as f:
            c = json.loads(f.read())
    except:
        c = {}

    config['LOCALE'] = c.get('LOCALE', 'en')
    config['GOOGLEMAPS_KEY'] = c.get('GOOGLEMAPS_KEY', None)
    config['CONFIG_PASSWORD'] = c.get('CONFIG_PASSWORD', None)
    config['ACCOUNTS'] = c.get('ACCOUNTS', [])
    scan_config.update_scan_locations(c.get('SCAN_LOCATIONS', {}))

    if config.get('CONFIG_PASSWORD', None):
        config['AUTH_KEY'] = ''.join(random.choice(string.lowercase) for _ in range(32))
项目:one-time-mail    作者:dividuum    | 项目源码 | 文件源码
def index():
    nonce = ''.join(random.sample(
        string.lowercase+string.digits, 16
    ))
    r = Response(render_template("otm.jinja",
        nonce=nonce
    ))
    r.headers['Content-Security-Policy'] = ';'.join((
        "default-src 'none'",
        "style-src 'nonce-%s'" % nonce,
        "script-src 'nonce-%s'" % nonce,
        "connect-src %s://%s/ws" % (
            "wss" if request.is_secure else "ws",
            request.host,
        ),
    ))
    r.headers['X-Frame-Options'] = 'DENY'
    return r
项目:MegaQC    作者:ewels    | 项目源码 | 文件源码
def store_report_data(user, report_data, uploaded_file):
    file_name = ''.join([random.choice(string.lowercase) for i in xrange(10)])
    if report_data:
        with open(os.path.join(current_app.config['UPLOAD_FOLDER'], file_name),"w") as fh:
            fh.write(report_data)
    else:
        uploaded_file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], file_name))

    upload_row = Upload(
                        upload_id=Upload.get_next_id(),
                        status="NOT TREATED",
                        path=os.path.join(current_app.config['UPLOAD_FOLDER'], file_name),
                        message="File has been created, loading in MegaQC is queued.",
                        user_id=user.user_id
                )
    upload_row.save()
    return (True, 'Data upload queued successfully')
项目:ooniprobe-debian    作者:TheTorProject    | 项目源码 | 文件源码
def get_random_url_safe_string(self, length):
        """
        Returns a random url-safe string of specified length, where
        0 < length <= 256. The returned string will always start with
        an alphabetic character.
        """
        if length <= 0:
            length = 1
        elif length > 256:
            length = 256

        random_string = ''
        while length > 0:
            random_string += random.choice(string.lowercase)
            length -= 1

        return random_string
项目:JovianDSS-Cinder    作者:open-e    | 项目源码 | 文件源码
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
项目:CAPTCHA_Identifier    作者:AlphaLFC    | 项目源码 | 文件源码
def __init__(self, image_set, devkit_path):
        imdb.__init__(self, image_set)
        self._image_set = image_set
        self._devkit_path = devkit_path
        self._data_path = self._devkit_path  # yeah!
        self._classes = tuple(['__background__'] +  # always index 0
                              list(string.digits + string.lowercase +
                                   string.uppercase))
        self._class_to_idx = dict(zip(self.classes,
                                      xrange(self.num_classes)))
        self._image_ext = ['.jpg', '.png']
        self._image_index = self._load_image_set_index()
        self._salt = str(uuid.uuid4())
        self._comp_id = 'comp4'

        self.config = {'cleanup': True,
                       'use_salt': True,
                       'top_k': 2000,
                       'use_diff': False,
                       'rpn_file': None}
        assert os.path.exists(self._devkit_path), \
            'Devkit path does not exist: {}'.format(self._devkit_path)
        assert os.path.exists(self._data_path), \
            'Path does not exist: {}'.format(self._data_path)
项目:black_zone    作者:zh-explorer    | 项目源码 | 文件源码
def randoms(count, alphabet = string.lowercase):
    """randoms(count, alphabet = string.lowercase) -> str

    Returns a random string of a given length using only the specified alphabet.

    Arguments:
      count (int): The length of the desired string.
      alphabet: The alphabet of allowed characters. Defaults to all lowercase characters.

    Returns:
      A random string.

    Example:

      >>> randoms(10) #doctest: +SKIP
      'evafjilupm'
"""

    return ''.join(random.choice(alphabet) for _ in xrange(count))
项目:pwning-tools    作者:peternguyen93    | 项目源码 | 文件源码
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
项目:cyris    作者:crond-jaist    | 项目源码 | 文件源码
def setEntryPoint(self, instance_id, port, host_id):
        for clone_guest in self.getCloneGuestList():
            #if clone_guest.getGuestId() == "desktop" and clone_guest.getIndex() == 1:
            if clone_guest.getIsEntryPoint() == True and clone_guest.getIndex() == 1:
                self.entry_point.setAddr(clone_guest.getNicAddrDict()["eth0"])
        self.entry_point.setPort(port) 
        # Generate random account and passwd for entry point.
        s = string.lowercase+string.digits
        # OLD VERSION: Random suffix of 5 digits
        #account = "trainee{0}".format(''.join(random.sample(s,5)))
        # NEW VERSION: Use instance id as suffix (add 1 so as to start from 1)
        # Use leading zeros (up to 2 digits) to match current Moodle settings
        account = "trainee{number:02d}".format(number=(instance_id+1))
        passwd = ''.join(random.sample(s,10))
        self.entry_point.setAccount(account)
        self.entry_point.setPasswd(passwd)
        self.entry_point.setHostId(host_id)
项目:pogom-updated    作者:PokeHunterProject    | 项目源码 | 文件源码
def read_config(scan_config):
    config_path = os.path.join(
        os.path.dirname(os.path.realpath(sys.argv[0])), "config.json")

    if os.path.isfile(config_path):
        config['CONFIG_PATH'] = config_path

    try:
        with open(config_path, "r") as f:
            c = json.loads(f.read())
    except:
        c = {}

    config['LOCALE'] = c.get('LOCALE', 'en')
    config['GOOGLEMAPS_KEY'] = c.get('GOOGLEMAPS_KEY', None)
    config['CONFIG_PASSWORD'] = c.get('CONFIG_PASSWORD', None)
    config['ACCOUNTS'] = c.get('ACCOUNTS', [])
    scan_config.update_scan_locations(c.get('SCAN_LOCATIONS', {}))

    if config.get('CONFIG_PASSWORD', None):
        config['AUTH_KEY'] = ''.join(random.choice(string.lowercase) for _ in range(32))
项目:deviation-manual    作者:DeviationTX    | 项目源码 | 文件源码
def setPageCounter(counter=None, style=None):

    global _counter, _counterStyle

    if counter is not None:
        _counter = counter
    if style is not None:
        _counterStyle = style

    if _counterStyle=='lowerroman':
        ptext=toRoman(_counter).lower()
    elif _counterStyle=='roman':
        ptext=toRoman(_counter).upper()
    elif _counterStyle=='alpha':
        ptext=string.uppercase[_counter%26]
    elif _counterStyle=='loweralpha':
        ptext=string.lowercase[_counter%26]
    else:
        ptext=unicode(_counter)
    return ptext
项目:CTF-chal-code    作者:zwhubuntu    | 项目源码 | 文件源码
def foo():
    s='vbkq{ukCkS_vrduztucCVQXVuvzuckrvtZDUBTGYSkvcktv}'
    '''
    '''
    a=string.lowercase
    b=""
    for i in xrange(len(a)):
        if i%2==0:
            if i<19:
                b+=a[i+7]
            else:
                b+=a[i-19]
        else:
            if i>=7:
                b+=a[i-7]
            else:
                b+=a[i+19]

    table=string.maketrans(a,b)
    print string.translate(s,table)
项目:openedoo    作者:openedoo    | 项目源码 | 文件源码
def random_word(length):
    return ''.join(random.choice(string.lowercase+string.uppercase+string.digits) for i in range(length))
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def lowerFirstCamelWord(word):
    """ puts the first word in a CamelCase Word in lowercase.

    I.e. CustomerID becomes customerID, XMLInfoTest becomes xmlInfoTest
    """
    newstr = ''
    swapped = word.swapcase()
    idx = 0

    # if it's all-caps, return an all-lowered version
    lowered = word.lower()

    if swapped == lowered:
        return lowered

    for c in swapped:
        if c in string.lowercase:
            newstr += c
            idx += 1
        else:
            break
    if idx < 2:
        newstr += word[idx:]
    else:
        newstr = newstr[:-1]+ word[idx-1:]

    return newstr
项目:SPF    作者:Exploit-install    | 项目源码 | 文件源码
def get_random_str(length):
        return ''.join(random.choice(string.lowercase) for i in range(length))
项目:kcli    作者:karmab    | 项目源码 | 文件源码
def setup_class(self):
        self.host = os.environ.get('KVIRT_HOST', '127.0.0.1')
        self.user = os.environ.get('KVIRT_USER', 'root')
        self.path = os.environ.get('KVIRT_PATH', '')
        self.virttype = os.environ.get('KVIRT_TYPE', 'kvm')
        self.libvirt_user = os.environ.get('KVIRT_LIBVIRT_USER', 'qemu')
        k = Kvirt(self.host)
        name = "test_%s" % ''.join(random.choice(string.lowercase) for i in range(5))
        self.name = name
        self.conn = k
项目:kcli    作者:karmab    | 项目源码 | 文件源码
def add_disk(self, name, size, pool=None, thin=True, template=None, shareable=False, existing=None):
        conn = self.conn
        # diskformat = 'qcow2'
        if size < 1:
            print("Incorrect size.Leaving...")
            return {'result': 'failure', 'reason': "Incorrect size"}
        # if not thin:
        #     diskformat = 'raw'
        try:
            vm = conn.find_machine(name)
        except:
            common.pprint("VM %s not found" % name, color='red')
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        disks = []
        for index, dev in enumerate(string.lowercase[:10]):
            try:
                vm.get_medium('SATA', index, 0)
                disks.append(0)
            except:
                continue
        index = len(disks)
        if existing is None:
            storagename = "%s_%d" % (name, index)
            diskpath = self.create_disk(name=storagename, size=size, pool=pool, thin=thin, template=template)
        else:
            disks = self.list_disks()
            if existing in disks:
                diskpath = disks[existing]['path']
            else:
                diskpath = existing
        session = Session()
        vm.lock_machine(session, library.LockType.write)
        machine = session.machine
        disk = conn.open_medium(diskpath, library.DeviceType.hard_disk, library.AccessMode.read_write, True)
        machine.attach_device("SATA", index, 0, library.DeviceType.hard_disk, disk)
        machine.save_settings()
        session.unlock_machine()
        return {'result': 'success'}
项目:dfly_edit    作者:Monospark    | 项目源码 | 文件源码
def letters(t):
    letter_map = {}
    for char in string.lowercase:
        letter_map[char] = (t(char), string.capitalize(char))
    return letter_map
项目:OpenPlanetMaps    作者:ajmas    | 项目源码 | 文件源码
def random_str(length=16):
    """ Generates a random string, defaulting to 16 characters in length """
    rand_str = lambda n: ''.join([random.choice(string.lowercase) for i in xrange(n)])
    return rand_str(length)
项目:MISP-IOC-Validator    作者:tom8941    | 项目源码 | 文件源码
def _is_snort_rule_invalid(rule):
    '''Check if the snort rule given is invalid by trying to compile it.

    rule -- Snort rule to test.
    '''
    filepath = '/tmp/tmp_' + ''.join(random.choice(string.lowercase) for i in range(8))
    f = open(filepath, "w")
    f.write(rule)
    f.close()

    if not rule.startswith('alert'):
        return 'Snort rule does not start with "alert"'

    if "threshold" in rule:
        return 'threshold in snort rule is deprecated'

    dp = dumbpig.RuleChecker()

    dp.set_rule_file(filepath)
    dp.test_rule_file()
    os.remove(filepath)

    result = json.dumps(dp.json_output()).encode('utf8').decode('string_escape')

    if (result == '"{}"'):
        return None
    else:
        return result

############################################
######## Attribute Check Functions #########
############################################
项目:motif-classify    作者:macks22    | 项目源码 | 文件源码
def __init__(self, grammar):
        self.grammar = grammar
        self.sax = pysax.SAXModel(
            window=grammar.window_size,
            stride=1,
            nbins=grammar.paa_size,
            alphabet=string.lowercase[:grammar.alphabet_size])
项目:WebHackSHL    作者:SecHackLabs    | 项目源码 | 文件源码
def randomword(length = 8):
   return ''.join(random.choice(string.lowercase) for i in range(length))
项目:pentestly    作者:praetorian-inc    | 项目源码 | 文件源码
def get_random_str(self, length):
        return ''.join(random.choice(string.lowercase) for i in range(length))
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def mark_pod_as_deleted(pod_id):
    p = db.session.query(Pod).get(pod_id)
    if p is not None:
        p.name += \
            '__' + ''.join(random.sample(string.lowercase + string.digits, 8))
        p.status = 'deleted'
    db.session.commit()
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def generate(length=8):
    """
    Generates random lowercase+digits string
    :param length: int -> default string length
    :return: string -> random string
    """
    rest = ''.join(random.sample(lowercase + digits, length - 1))
    return random.choice(lowercase) + rest
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def _autogen_subdomain(pod, base_domain):
    """
    Generate Subdomain from Pod name or Pod Domain if Pod already has it

    :param pod: Pod instance
    :param base_domain: BaseDomain instance in which zone Subdomain should be
     placed
    :return: (pod_domain, sub_domain_part):
     pod_domain -- if Pod Domain already exists for specified pod, else None
     sub_domain_part -- autogenerated Subdomain part

    """
    pod_domain = PodDomain.query.filter_by(domain_id=base_domain.id,
                                           pod_id=pod.id).first()
    if pod_domain:
        return pod_domain, None

    pod_name = domainize(pod.name)
    if not pod_name:
        pod_name = randstr(symbols=string.lowercase + string.digits,
                           length=8)
    user = domainize(pod.owner.username)
    sub_domain_part = '{0}-{1}'.format(user, pod_name)
    sub_domain_part = _get_unique_domain_name(sub_domain_part, base_domain.id)
    if sub_domain_part is None:
        raise InternalAPIError('Failed to get unique pod domain name')

    return None, sub_domain_part
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def _get_unique_domain_name(basename, domain_id):
    """Returns unique domain name for given basename.
    If basename does not exists in DB with specified domain_id, then it will
    be returned as is.
    Otherwise will be returned basename with random suffix
    """
    pod_domain = PodDomain.query.filter_by(name=basename,
                                           domain_id=domain_id).first()
    if pod_domain is None:
        return basename

    res = None
    # try to get unique random domain name. If it fails for tries limit,
    # then something is going wrong, return None and it will be better to fail
    # in calling code
    tries_limit = 100
    random_suffix_length = 6
    for _ in xrange(tries_limit):
        suffix = randstr(
            symbols=string.lowercase + string.digits,
            length=random_suffix_length)
        new_name = '{0}{1}'.format(basename, suffix)
        pod_domain = PodDomain.query.filter_by(
            name=new_name, domain_id=domain_id).first()
        if pod_domain is None:
            res = new_name
            break
    return res
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def delete(self):
        self.name += '__' + ''.join(
            random.sample(string.lowercase + string.digits, 8))
        self.status = 'deleted'

    # Such name to distinguish from non-db Pod's get_config() method
项目:dati-ckan-docker    作者:italia    | 项目源码 | 文件源码
def _make_tag_list(n=26):
    '''Returns a list of tag dicts, starting with 'aa, bb, ..., zz', then
    'aaa, bbb, ..., zzz', etc. Tags must be at least 2 characters.'''
    lc = string.lowercase
    lc_len = len(lc)
    return [{'name': lc[i % lc_len] * int(math.ceil(i / lc_len) + 2)}
            for i in range(0, n)]
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
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)))
项目:Fabrik    作者:Cloud-CV    | 项目源码 | 文件源码
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length))
项目:Fabrik    作者:Cloud-CV    | 项目源码 | 文件源码
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length))
项目:Fabrik    作者:Cloud-CV    | 项目源码 | 文件源码
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length))
项目:Fabrik    作者:Cloud-CV    | 项目源码 | 文件源码
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length))
项目:texta    作者:texta-tk    | 项目源码 | 文件源码
def get_random_key(size=10):
        # Generates random sequence of chars
        key = ""
        for i in range(size):
            key += random.choice(string.lowercase)
        return key