Python string.ascii_letters() Examples

The following are 30 code examples of string.ascii_letters(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: Encryption.py    From vault with MIT License 8 votes vote down vote up
def gen_salt(self, set_=True):
        """
            Generate a random salt
        """

        min_char = 8
        max_char = 12
        allchar = string.ascii_letters + string.punctuation + string.digits
        salt = "".join(choice(allchar)
                       for x in range(randint(min_char, max_char))).encode()

        # Set the salt in the same instance if required
        if set_:
            self.set_salt(salt)

        return salt 
Example #2
Source File: ssh.py    From aegea with Apache License 2.0 8 votes vote down vote up
def scp(args):
    """
    Transfer files to or from EC2 instance.
    """
    scp_opts, host_opts = extract_passthrough_opts(args, "scp"), []
    user_or_hostname_chars = string.ascii_letters + string.digits
    ssm_init_complete = False
    for i, arg in enumerate(args.scp_args):
        if arg[0] in user_or_hostname_chars and ":" in arg:
            hostname, colon, path = arg.partition(":")
            username, at, hostname = hostname.rpartition("@")
            if args.use_ssm and not ssm_init_complete:
                scp_opts += init_ssm(get_instance(hostname).id)
                ssm_init_complete = True
            host_opts, hostname = prepare_ssh_host_opts(username=username, hostname=hostname,
                                                        bless_config_filename=args.bless_config,
                                                        use_kms_auth=args.use_kms_auth, use_ssm=args.use_ssm)
            args.scp_args[i] = hostname + colon + path
    os.execvp("scp", ["scp"] + scp_opts + host_opts + args.scp_args) 
Example #3
Source File: DNS.py    From XFLTReaT with MIT License 8 votes vote down vote up
def cmh_autotune(self, module, message, additional_data, cm):
		message = message[len(self.CONTROL_AUTOTUNE)+2:]
		# get tune type, requested record type, length and encoding for crafting the answer
		(query_type, RRtype, length, encode_class) = struct.unpack("<BHHH", message[0:7])
		if self.DNS_proto.get_RR_type(RRtype)[0] == None:
			return True
		
		# extra parameters added to be able to response in the proper way
		additional_data = additional_data + (True, self.download_encoding_list[encode_class], self.DNS_proto.get_RR_type(RRtype)[0])		
		if (query_type == 0) or (query_type == 3):
			# record && downstream length discovery
			message = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
		if query_type == 1:
			# A record name length discovery
			message = struct.pack("<i", binascii.crc32(message[7:]))
		if query_type == 2:
			# checking download encoding, echoing back request payload
			message = message[7:]

		module.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_AUTOTUNE_CLIENT+message, additional_data)
		return True

	# tune control message handler
	# client sets the record type and encodings by calling this
	# server side 
Example #4
Source File: test_models.py    From qutebrowser with GNU General Public License v3.0 8 votes vote down vote up
def test_tab_completion_not_sorted(qtmodeltester, fake_web_tab, win_registry,
                                   tabbed_browser_stubs):
    """Ensure that the completion row order is the same as tab index order.

    Would be violated for more than 9 tabs if the completion was being
    alphabetically sorted on the first column, or the others.
    """
    expected = []
    for idx in range(1, 11):
        url = "".join(random.sample(string.ascii_letters, 12))
        title = "".join(random.sample(string.ascii_letters, 12))
        expected.append(("0/{}".format(idx), url, title))

    tabbed_browser_stubs[0].widget.tabs = [
        fake_web_tab(QUrl(tab[1]), tab[2], idx)
        for idx, tab in enumerate(expected)
    ]
    model = miscmodels.buffer()
    model.set_pattern('')
    qtmodeltester.check(model)

    _check_completions(model, {
        '0': expected,
        '1': [],
    }) 
Example #5
Source File: items.py    From tomlkit with MIT License 7 votes vote down vote up
def __init__(
        self, k, t=None, sep=None, dotted=False
    ):  # type: (str, Optional[KeyType], Optional[str], bool) -> None
        if t is None:
            if any(
                [c not in string.ascii_letters + string.digits + "-" + "_" for c in k]
            ):
                t = KeyType.Basic
            else:
                t = KeyType.Bare

        self.t = t
        if sep is None:
            sep = " = "

        self.sep = sep
        self.key = k
        self._dotted = dotted 
Example #6
Source File: casm.py    From stream with MIT License 7 votes vote down vote up
def s_ctype(s, t):
  CTYPE0 = string.ascii_letters + "_.!:"
  CTYPE1 = string.ascii_letters + string.digits + "_."

  token = ""
  if s.peek() not in CTYPE0:
    return False

  token = s.get()

  try:
    while s.peek() in CTYPE1:
      token += s.get()
  except StreamException:
    pass

  t.append(token)  # TODO: maybe add more info on type

  return True 
Example #7
Source File: casm.py    From stream with MIT License 7 votes vote down vote up
def s_cname(s, t):
  CNAME0 = string.ascii_letters + "_.!:"
  CNAME1 = string.ascii_letters + string.digits + "_."

  token = ""
  if s.peek() not in CNAME0:
    return False

  token = s.get()

  try:
    while s.peek() in CNAME1:
      token += s.get()
  except StreamException:
    pass

  t.append((TokenTypes.IDENTIFIER, token))  # TODO: maybe add more info on type

  return True 
Example #8
Source File: test_url_building.py    From sanic with MIT License 7 votes vote down vote up
def test_fails_url_build_if_param_not_passed(app):
    url = "/"

    for letter in string.ascii_letters:
        url += f"<{letter}>/"

    @app.route(url)
    def fail(request):
        return text("this should fail")

    fail_args = list(string.ascii_letters)
    fail_args.pop()

    fail_kwargs = {l: l for l in fail_args}

    with pytest.raises(URLBuildError) as e:
        app.url_for("fail", **fail_kwargs)

    assert "Required parameter `Z` was not passed to url_for" in str(e.value) 
Example #9
Source File: test_pySmartDL.py    From pySmartDL with The Unlicense 7 votes vote down vote up
def setUp(self):
        warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*<ssl.SSLSocket.*>")
        self.dl_dir = os.path.join(tempfile.gettempdir(), "".join([random.choice(string.ascii_letters+string.digits) for i in range(8)]), '')
        while os.path.exists(self.dl_dir):
            self.dl_dir = os.path.join(tempfile.gettempdir(), "".join([random.choice(string.ascii_letters+string.digits) for i in range(8)]), '')
            
        self.res_7za920_mirrors = [
            "https://github.com/iTaybb/pySmartDL/raw/master/test/7za920.zip",
            "https://sourceforge.mirrorservice.org/s/se/sevenzip/7-Zip/9.20/7za920.zip",
            "http://www.bevc.net/dl/7za920.zip",
            "http://ftp.psu.ru/tools/7-zip/stable/7za920.zip",
            "http://www.mirrorservice.org/sites/downloads.sourceforge.net/s/se/sevenzip/7-Zip/9.20/7za920.zip"
        ]
        self.res_7za920_hash = '2a3afe19c180f8373fa02ff00254d5394fec0349f5804e0ad2f6067854ff28ac'
        self.res_testfile_1gb = 'http://www.ovh.net/files/1Gio.dat'
        self.res_testfile_100mb = 'http://www.ovh.net/files/100Mio.dat'
        self.enable_logging = "-vvv" in sys.argv 
Example #10
Source File: base.py    From wanggeService with MIT License 6 votes vote down vote up
def getRandomStr(types='letter', length=8):
        """ 随机产生length长度的字符串

        :param types: 随机字符串的类型
        types in ['letter', 'ascii'] 返回包含字母的字符串
        types in ['digit', 'num']: 返回包含数字的字符串
        其他:返回混合字母和数字的字符串

        :param length: 返回字符串的长度
        :return: 长度为length,类型为types的字符串

        todo string.punctuation

        """
        import random
        import string
        if types in ['letter', 'ascii']:
            return ''.join(random.sample(string.ascii_letters, length))
        if types in ['digit', 'num']:
            return ''.join(random.sample(string.digits, length))
        else:
            return ''.join(random.sample(string.ascii_letters + string.digits, length)) 
Example #11
Source File: test_pyeclib_api.py    From pyeclib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_verify_fragment_inline_chksum_succeed(self):
        pyeclib_drivers = self.get_pyeclib_testspec("inline_crc32")

        filesize = 1024 * 1024 * 3
        file_str = ''.join(random.choice(ascii_letters)
                           for i in range(filesize))
        file_bytes = file_str.encode('utf-8')

        for pyeclib_driver in pyeclib_drivers:
            fragments = pyeclib_driver.encode(file_bytes)

            fragment_metadata_list = []

            for fragment in fragments:
                fragment_metadata_list.append(
                    pyeclib_driver.get_metadata(fragment))

            expected_ret_value = {"status": 0}

            self.assertTrue(pyeclib_driver.verify_stripe_metadata(
                fragment_metadata_list) == expected_ret_value) 
Example #12
Source File: test_pyeclib_api.py    From pyeclib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _create_tmp_files(self):
        """
        Create the temporary files needed for testing.  Use the tempfile
        package so that the files will be automatically removed during
        garbage collection.
        """
        for size_str in self.file_sizes:
            # Determine the size of the file to create
            size_desc = size_str.split("-")
            size = int(size_desc[0])
            if size_desc[1] == 'M':
                size *= 1000000
            elif size_desc[1] == 'K':
                size *= 1000

            # Create the dictionary of files to test with
            buf = ''.join(random.choice(ascii_letters) for i in range(size))
            if sys.version_info >= (3,):
                buf = buf.encode('ascii')
            tmp_file = tempfile.NamedTemporaryFile()
            tmp_file.write(buf)
            self.files[size_str] = tmp_file 
Example #13
Source File: test_pyeclib_c.py    From pyeclib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _create_tmp_files(self):
        """
        Create the temporary files needed for testing.  Use the tempfile
        package so that the files will be automatically removed during
        garbage collection.
        """
        for size_str in self.sizes:
            # Determine the size of the file to create
            size_desc = size_str.split("-")
            size = int(size_desc[0])
            if size_desc[1] == 'M':
                size *= 1000000
            elif size_desc[1] == 'K':
                size *= 1000

            # Create the dictionary of files to test with
            buf = ''.join(random.choice(ascii_letters) for i in range(size))
            if sys.version_info >= (3,):
                buf = buf.encode('ascii')
            tmp_file = tempfile.NamedTemporaryFile('w+b')
            tmp_file.write(buf)
            self.files[size_str] = tmp_file 
Example #14
Source File: test_frame.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_plot_scatter(self):
        df = DataFrame(randn(6, 4),
                       index=list(string.ascii_letters[:6]),
                       columns=['x', 'y', 'z', 'four'])

        _check_plot_works(df.plot.scatter, x='x', y='y')
        _check_plot_works(df.plot.scatter, x=1, y=2)

        with pytest.raises(TypeError):
            df.plot.scatter(x='x')
        with pytest.raises(TypeError):
            df.plot.scatter(y='y')

        # GH 6951
        axes = df.plot(x='x', y='y', kind='scatter', subplots=True)
        self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) 
Example #15
Source File: test_frame.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_boxplot_return_type(self):
        df = DataFrame(randn(6, 4),
                       index=list(string.ascii_letters[:6]),
                       columns=['one', 'two', 'three', 'four'])
        with pytest.raises(ValueError):
            df.plot.box(return_type='NOTATYPE')

        result = df.plot.box(return_type='dict')
        self._check_box_return_type(result, 'dict')

        result = df.plot.box(return_type='axes')
        self._check_box_return_type(result, 'axes')

        result = df.plot.box()  # default axes
        self._check_box_return_type(result, 'axes')

        result = df.plot.box(return_type='both')
        self._check_box_return_type(result, 'both') 
Example #16
Source File: test_boxplot_method.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_boxplot_legacy1(self):
        df = DataFrame(np.random.randn(6, 4),
                       index=list(string.ascii_letters[:6]),
                       columns=['one', 'two', 'three', 'four'])
        df['indic'] = ['foo', 'bar'] * 3
        df['indic2'] = ['foo', 'bar', 'foo'] * 2

        _check_plot_works(df.boxplot, return_type='dict')
        _check_plot_works(df.boxplot, column=[
                          'one', 'two'], return_type='dict')
        # _check_plot_works adds an ax so catch warning. see GH #13188
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(df.boxplot, column=['one', 'two'],
                              by='indic')
        _check_plot_works(df.boxplot, column='one', by=['indic', 'indic2'])
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(df.boxplot, by='indic')
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(df.boxplot, by=['indic', 'indic2'])
        _check_plot_works(plotting._core.boxplot, data=df['one'],
                          return_type='dict')
        _check_plot_works(df.boxplot, notch=1, return_type='dict')
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(df.boxplot, by='indic', notch=1) 
Example #17
Source File: test_boxplot_method.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_boxplot_return_type_legacy(self):
        # API change in https://github.com/pandas-dev/pandas/pull/7096
        import matplotlib as mpl  # noqa

        df = DataFrame(np.random.randn(6, 4),
                       index=list(string.ascii_letters[:6]),
                       columns=['one', 'two', 'three', 'four'])
        with pytest.raises(ValueError):
            df.boxplot(return_type='NOTATYPE')

        result = df.boxplot()
        self._check_box_return_type(result, 'axes')

        with tm.assert_produces_warning(False):
            result = df.boxplot(return_type='dict')
        self._check_box_return_type(result, 'dict')

        with tm.assert_produces_warning(False):
            result = df.boxplot(return_type='axes')
        self._check_box_return_type(result, 'axes')

        with tm.assert_produces_warning(False):
            result = df.boxplot(return_type='both')
        self._check_box_return_type(result, 'both') 
Example #18
Source File: test_frame.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_plot_bar(self):
        df = DataFrame(randn(6, 4),
                       index=list(string.ascii_letters[:6]),
                       columns=['one', 'two', 'three', 'four'])

        _check_plot_works(df.plot.bar)
        _check_plot_works(df.plot.bar, legend=False)
        # _check_plot_works adds an ax so catch warning. see GH #13188
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(df.plot.bar, subplots=True)
        _check_plot_works(df.plot.bar, stacked=True)

        df = DataFrame(randn(10, 15),
                       index=list(string.ascii_letters[:10]),
                       columns=lrange(15))
        _check_plot_works(df.plot.bar)

        df = DataFrame({'a': [0, 1], 'b': [1, 0]})
        ax = _check_plot_works(df.plot.bar)
        self._check_ticks_props(ax, xrot=90)

        ax = df.plot.bar(rot=35, fontsize=10)
        self._check_ticks_props(ax, xrot=35, xlabelsize=10, ylabelsize=10)

        ax = _check_plot_works(df.plot.barh)
        self._check_ticks_props(ax, yrot=0)

        ax = df.plot.barh(rot=55, fontsize=11)
        self._check_ticks_props(ax, yrot=55, ylabelsize=11, xlabelsize=11) 
Example #19
Source File: test_boxplot_method.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_boxplot_legacy3(self):
        tuples = lzip(string.ascii_letters[:10], range(10))
        df = DataFrame(np.random.rand(10, 3),
                       index=MultiIndex.from_tuples(tuples))
        grouped = df.unstack(level=1).groupby(level=0, axis=1)
        with tm.assert_produces_warning(UserWarning):
            axes = _check_plot_works(grouped.boxplot, return_type='axes')
        self._check_axes_shape(list(axes.values), axes_num=3, layout=(2, 2))
        axes = _check_plot_works(grouped.boxplot, subplots=False,
                                 return_type='axes')
        self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) 
Example #20
Source File: authentication.py    From WebGPIO with GNU General Public License v3.0 5 votes vote down vote up
def randomString(length):
    return ''.join(random.choice(string.ascii_letters + string.digits) for m in range(length)) 
Example #21
Source File: test_boxplot_method.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_boxplot_legacy2(self):
        tuples = lzip(string.ascii_letters[:10], range(10))
        df = DataFrame(np.random.rand(10, 3),
                       index=MultiIndex.from_tuples(tuples))
        grouped = df.groupby(level=1)
        with tm.assert_produces_warning(UserWarning):
            axes = _check_plot_works(grouped.boxplot, return_type='axes')
        self._check_axes_shape(list(axes.values), axes_num=10, layout=(4, 3))

        axes = _check_plot_works(grouped.boxplot, subplots=False,
                                 return_type='axes')
        self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) 
Example #22
Source File: update_repo_handler.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def dump_solv(name, baseurl):
    pool = solv.Pool()
    pool.setarch()

    repo = pool.add_repo(''.join(random.choice(string.ascii_letters) for _ in range(5)))
    if not parse_repomd(repo, baseurl) and not parse_susetags(repo, baseurl):
        raise Exception('neither repomd nor susetags exists in ' + baseurl)

    repo.create_stubs()

    ofh = solv.xfopen(name, 'w')
    repo.write(ofh)
    ofh.flush()

    return name 
Example #23
Source File: test_printing.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_repr_binary_type():
    import string
    letters = string.ascii_letters
    btype = compat.binary_type
    try:
        raw = btype(letters, encoding=cf.get_option('display.encoding'))
    except TypeError:
        raw = btype(letters)
    b = compat.text_type(compat.bytes_to_str(raw))
    res = printing.pprint_thing(b, quote_strings=True)
    assert res == repr(b)
    res = printing.pprint_thing(b, quote_strings=False)
    assert res == b 
Example #24
Source File: macphish.py    From macphish with MIT License 5 votes vote down vote up
def random_name():
  rnd = ''.join(choice(ascii_letters) for i in range(12))
  return rnd 
Example #25
Source File: checker.py    From linter-pylama with MIT License 5 votes vote down vote up
def check_capitalized(self, function, docstring):
        """D403: First word of the first line should be properly capitalized.

        The [first line of a] docstring is a phrase ending in a period.

        """
        if docstring:
            first_word = ast.literal_eval(docstring).split()[0]
            if first_word == first_word.upper():
                return
            for char in first_word:
                if char not in string.ascii_letters and char != "'":
                    return
            if first_word != first_word.capitalize():
                return violations.D403(first_word.capitalize(), first_word) 
Example #26
Source File: test_pyeclib_api.py    From pyeclib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_verify_fragment_inline_chksum_fail(self):
        pyeclib_drivers = self.get_pyeclib_testspec("inline_crc32")
        filesize = 1024 * 1024 * 3
        file_str = ''.join(random.choice(ascii_letters)
                           for i in range(filesize))
        file_bytes = file_str.encode('utf-8')

        for pyeclib_driver in pyeclib_drivers:
            fragments = pyeclib_driver.encode(file_bytes)

            fragment_metadata_list = []

            first_fragment_to_corrupt = random.randint(0, len(fragments))
            num_to_corrupt = 2
            fragments_to_corrupt = [
                (first_fragment_to_corrupt + i) % len(fragments)
                for i in range(num_to_corrupt + 1)]
            fragments_to_corrupt.sort()

            i = 0
            for fragment in fragments:
                if i in fragments_to_corrupt:
                    corrupted_fragment = fragment[:100] +\
                        (str(chr((b2i(fragment[100]) + 0x1)
                                 % 128))).encode('utf-8') + fragment[101:]
                    fragment_metadata_list.append(
                        pyeclib_driver.get_metadata(corrupted_fragment))
                else:
                    fragment_metadata_list.append(
                        pyeclib_driver.get_metadata(fragment))
                i += 1

            expected_ret_value = {"status": -206,
                                  "reason": "Bad checksum",
                                  "bad_fragments": fragments_to_corrupt}
            self.assertEqual(
                pyeclib_driver.verify_stripe_metadata(fragment_metadata_list),
                expected_ret_value) 
Example #27
Source File: test_dataintegrity.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_VARCHAR(conn_cnx):
    def generator(row, col):
        import string
        rstr = ''.join(
            [random.choice(string.ascii_letters + string.digits) for n in
             range(50)])
        return rstr

    check_data_integrity(conn_cnx, ('col2 VARCHAR',), 'VARCHAR', generator) 
Example #28
Source File: test_dataintegrity.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_STRING(conn_cnx):
    def generator(row, col):
        import string
        rstr = ''.join(
            [random.choice(string.ascii_letters + string.digits) for n in
             range(1024)])
        return rstr

    check_data_integrity(conn_cnx, ('col2 STRING',), 'STRING', generator) 
Example #29
Source File: test_dataintegrity.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_VARCHAR(conn_cnx):
    def generator(row, col):
        import string
        rstr = ''.join(
            [random.choice(string.ascii_letters + string.digits) for n in
             range(50)])
        return rstr

    check_data_integrity(conn_cnx, ('col2 VARCHAR',), 'VARCHAR', generator) 
Example #30
Source File: test_dataintegrity.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_STRING(conn_cnx):
    def generator(row, col):
        import string
        rstr = ''.join(
            [random.choice(string.ascii_letters + string.digits) for n in
             range(1024)])
        return rstr

    check_data_integrity(conn_cnx, ('col2 STRING',), 'STRING', generator)