Python string.ascii_uppercase() Examples

The following are 30 code examples for showing how to use string.ascii_uppercase(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: hydrus   Author: HTTP-APIs   File: test_app.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 2
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 3
Project: hydrus   Author: HTTP-APIs   File: test_cli.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 4
Project: aws-batch-example   Author: dejonghe   File: lambda_function.py    License: MIT License 6 votes vote down vote up
def lambda_handler(event,context):
    # Grab data from environment
    jobqueue = os.environ['JobQueue']
    jobdef = os.environ['JobDefinition']

    # Create unique name for the job (this does not need to be unique)
    job1Name = 'job1' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))

    # Set up a batch client 
    session = boto3.session.Session()
    client = session.client('batch')

    # Submit the job
    job1 = client.submit_job(
        jobName=job1Name,
        jobQueue=jobqueue,
        jobDefinition=jobdef
    )
    print("Started Job: {}".format(job1['jobName'])) 
Example 5
Project: ICDAR-2019-SROIE   Author: zzzDavid   File: my_utils.py    License: MIT License 6 votes vote down vote up
def random_string(n):
    if n == 0:
        return ""

    x = random.random()
    if x > 0.5:
        pad = " " * n
    elif x > 0.3:
        pad = "".join(random.choices(digits + " \t\n", k=n))
    elif x > 0.2:
        pad = "".join(random.choices(ascii_uppercase + " \t\n", k=n))
    elif x > 0.1:
        pad = "".join(random.choices(ascii_uppercase + digits + " \t\n", k=n))
    else:
        pad = "".join(
            random.choices(ascii_uppercase + digits + punctuation + " \t\n", k=n)
        )

    return pad 
Example 6
Project: instavpn   Author: sockeye44   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def setup_passwords():
    try:
        char_set = string.ascii_lowercase + string.ascii_uppercase + string.digits
        f = open('/etc/ppp/chap-secrets', 'w')
        pw1 = gen_random_text(12)
        pw2 = gen_random_text(12)
        f.write("username1 l2tpd {} *\n".format(pw1))
        f.write("username2 l2tpd {} *".format(pw2))
        f.close()
        f = open('/etc/ipsec.secrets', 'w')
        f.write('1.2.3.4 %any: PSK "{}"'.format(gen_random_text(16)))
        f.close()
    except:
        logger.exception("Exception creating passwords:")
        return False

    return True 
Example 7
Project: maubot   Author: maubot   File: client_auth.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def login(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, _, username, password, _ = info
    device_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    try:
        return web.json_response(await api.request(Method.POST, Path.login, content={
            "type": "m.login.password",
            "identifier": {
                "type": "m.id.user",
                "user": username,
            },
            "password": password,
            "device_id": f"maubot_{device_id}",
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
        }, status=e.http_status) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_repr_info.py    License: Apache License 2.0 6 votes vote down vote up
def test_info_memory_usage_bug_on_multiindex(self):
        # GH 14308
        # memory usage introspection should not materialize .values

        from string import ascii_uppercase as uppercase

        def memory_usage(f):
            return f.memory_usage(deep=True).sum()

        N = 100
        M = len(uppercase)
        index = pd.MultiIndex.from_product([list(uppercase),
                                            pd.date_range('20160101',
                                                          periods=N)],
                                           names=['id', 'date'])
        df = DataFrame({'value': np.random.randn(N * M)}, index=index)

        unstacked = df.unstack('id')
        assert df.values.nbytes == unstacked.values.nbytes
        assert memory_usage(df) > memory_usage(unstacked)

        # high upper bound
        assert memory_usage(unstacked) - memory_usage(df) < 2000 
Example 9
Project: dsub   Author: DataBiosphere   File: job_model.py    License: Apache License 2.0 6 votes vote down vote up
def convert_to_label_chars(s):
  """Turn the specified name and value into a valid Google label."""

  # We want the results to be user-friendly, not just functional.
  # So we can't base-64 encode it.
  #   * If upper-case: lower-case it
  #   * If the char is not a standard letter or digit. make it a dash

  # March 2019 note: underscores are now allowed in labels.
  # However, removing the conversion of underscores to dashes here would
  # create inconsistencies between old jobs and new jobs.
  # With existing code, $USER "jane_doe" has a user-id label of "jane-doe".
  # If we remove the conversion, the user-id label for new jobs is "jane_doe".
  # This makes looking up old jobs more complicated.

  accepted_characters = string.ascii_lowercase + string.digits + '-'

  def label_char_transform(char):
    if char in accepted_characters:
      return char
    if char in string.ascii_uppercase:
      return char.lower()
    return '-'

  return ''.join(label_char_transform(c) for c in s) 
Example 10
Project: assaytools   Author: choderalab   File: experiments.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def generate_uuid(size=6, chars=(string.ascii_uppercase + string.digits)):
    """
    Generate convenient universally unique id (UUID)

    Parameters
    ----------
    size : int, optional, default=6
       Number of alphanumeric characters to generate.
    chars : list of chars, optional, default is all uppercase characters and digits
       Characters to use for generating UUIDs

    NOTE
    ----
    This is not really universally unique, but it is convenient.

    """
    return ''.join(random.choice(chars) for _ in range(size)) 
Example 11
Project: ReolinkCameraAPI   Author: Benehiko   File: recording.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_snap(self, timeout: int = 3) -> Image or None:
        """
        Gets a "snap" of the current camera video data and returns a Pillow Image or None
        :param timeout: Request timeout to camera in seconds
        :return: Image or None
        """
        randomstr = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
        snap = self.url + "?cmd=Snap&channel=0&rs=" \
               + randomstr \
               + "&user=" + self.username \
               + "&password=" + self.password
        try:
            req = request.Request(snap)
            req.set_proxy(Request.proxies, 'http')
            reader = request.urlopen(req, timeout)
            if reader.status == 200:
                b = bytearray(reader.read())
                return Image.open(io.BytesIO(b))
            print("Could not retrieve data from camera successfully. Status:", reader.status)
            return None

        except Exception as e:
            print("Could not get Image data\n", e)
            raise 
Example 12
Project: tempest-lib   Author: openstack   File: data_utils.py    License: Apache License 2.0 6 votes vote down vote up
def rand_password(length=15):
    """Generate a random password

    :param int length: The length of password that you expect to set
                       (If it's smaller than 3, it's same as 3.)
    :return: a random password. The format is
             '<random upper letter>-<random number>-<random special character>
              -<random ascii letters or digit characters or special symbols>'
             (e.g. 'G2*ac8&lKFFgh%2')
    :rtype: string
    """
    upper = random.choice(string.ascii_uppercase)
    ascii_char = string.ascii_letters
    digits = string.digits
    digit = random.choice(string.digits)
    puncs = '~!@#$%^&*_=+'
    punc = random.choice(puncs)
    seed = ascii_char + digits + puncs
    pre = upper + digit + punc
    password = pre + ''.join(random.choice(seed) for x in range(length - 3))
    return password 
Example 13
Project: mlbv   Author: kmac   File: mlbsession.py    License: GNU General Public License v3.0 5 votes vote down vote up
def gen_random_string(n):
    return ''.join(
        random.choice(
            string.ascii_uppercase + string.digits
        ) for _ in range(n)
    ) 
Example 14
Project: aegea   Author: kislyuk   File: iam.py    License: Apache License 2.0 5 votes vote down vote up
def generate_password(length=16):
    while True:
        password = [random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length)]
        password.insert(8, "-")
        if not any(c in string.ascii_uppercase for c in password):
            continue
        if not any(c in string.ascii_lowercase for c in password):
            continue
        if not any(c in string.digits for c in password):
            continue
        return ''.join(password) 
Example 15
Project: pythonjobs.ie   Author: kimeraapp   File: services.py    License: GNU General Public License v2.0 5 votes vote down vote up
def generate_token(length=60):
    chars = string.ascii_uppercase + string.digits
    return ''.join(random.choice(chars) for _ in range(length)) 
Example 16
Project: ToonRooter   Author: martenjacobs   File: rooter.py    License: MIT License 5 votes vote down vote up
def patch_toon(self):
        (port, clean_up, reboot) = (
            self._port, self._cleanup_payload, self._reboot_after)
        log.info("Patching Toon")
        log.debug(port.read_until("/ # "))
        password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
        port.write("sh payload/patch_toon.sh \"{}\"\n".format(password))
        try:
            while True:
                line = read_until(port, ["/ # ", "\n"])
                if line == "/ # ":
                    break
                if line.startswith(">>>"):
                    log.info(line.strip())
                else:
                    log.debug(line.strip())
        except:
            log.exception("Script failed")
            sleep(5)
        if clean_up:
            log.info("Cleaning up")
            port.write("rm -r payload\n")
            log.debug(port.read_until("/ # "))
        if reboot:
            log.info("Rebooting")
            port.write("/etc/init.d/reboot\n") 
Example 17
def test_recordio_pack_label():
    frec = tempfile.mktemp()
    N = 255

    for i in range(1, N):
        for j in range(N):
            content = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(j))
            content = content.encode('utf-8')
            label = np.random.uniform(size=i).astype(np.float32)
            header = (0, label, 0, 0)
            s = mx.recordio.pack(header, content)
            rheader, rcontent = mx.recordio.unpack(s)
            assert (label == rheader.label).all()
            assert content == rcontent 
Example 18
Project: comport   Author: codeforamerica   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def random_string(N):
    return ''.join(choice(string.ascii_uppercase + string.digits + '     ') for _ in range(N)) 
Example 19
Project: fine-lm   Author: akzaidi   File: text_encoder_test.py    License: MIT License 5 votes vote down vote up
def test_long_tokens(self):
    """Subword tokenization should still run efficiently with long tokens.

    To make it run efficiently, we need to use the `max_subtoken_length`
    argument when calling SubwordTextEncoder.build_to_target_size.
    """
    token_length = 4000
    num_tokens = 50
    target_vocab_size = 600
    max_subtoken_length = 10  # Set this to `None` to get problems.
    max_count = 500

    # Generate some long random strings.
    random.seed(0)
    long_tokens = []
    for _ in range(num_tokens):
      long_token = "".join([random.choice(string.ascii_uppercase)
                            for _ in range(token_length)])
      long_tokens.append(long_token)

    corpus = " ".join(long_tokens)
    token_counts = collections.Counter(corpus.split(" "))
    alphabet = set(corpus) - {" "}

    encoder = text_encoder.SubwordTextEncoder.build_to_target_size(
        target_vocab_size, token_counts, 1, max_count, num_iterations=1,
        max_subtoken_length=max_subtoken_length)

    # All vocabulary elements are in the alphabet and subtoken strings even
    # if we requested a smaller vocabulary to assure all expected strings
    # are encodable.
    self.assertTrue(alphabet.issubset(encoder._alphabet))
    for a in alphabet:
      self.assertIn(a, encoder.all_subtoken_strings) 
Example 20
Project: aws-batch-example   Author: dejonghe   File: schedule.py    License: MIT License 5 votes vote down vote up
def random_four():
    """Returns a random 4 charactors"""
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=4)) 
Example 21
Project: certidude   Author: laurivosandi   File: tokens.py    License: MIT License 5 votes vote down vote up
def issue(self, issuer, subject, subject_mail=None):
        # Expand variables
        subject_username = subject.name
        if not subject_mail:
            subject_mail = subject.mail

        # Generate token
        token = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(32))
        token_created = datetime.utcnow()
        token_expires = token_created + config.TOKEN_LIFETIME

        self.sql_execute("token_issue.sql",
            token_created, token_expires, token,
            issuer.name if issuer else None,
            subject_username, subject_mail, "rw")

        # Token lifetime in local time, to select timezone: dpkg-reconfigure tzdata
        try:
            with open("/etc/timezone") as fh:
                token_timezone = fh.read().strip()
        except EnvironmentError:
            token_timezone = None

        router = sorted([j[0] for j in authority.list_signed(
                    common_name=config.SERVICE_ROUTERS)])[0]
        protocols = ",".join(config.SERVICE_PROTOCOLS)
        url = config.TOKEN_URL % locals()

        context = globals()
        context.update(locals())

        mailer.send("token.md", to=subject_mail, **context)
        return token 
Example 22
Project: pymsl   Author: truedread   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_esn(prefix):
    """
    generate_esn()

    @param prefix: Prefix of ESN to append generated device ID onto

    @return: ESN to use with MSL API
    """

    return prefix + ''.join(random.choice(
        string.ascii_uppercase + string.digits
    ) for _ in range(30)) 
Example 23
Project: Jtyoui   Author: jtyoui   File: methods.py    License: MIT License 5 votes vote down vote up
def random_upper_char(number=1):
    """随机选择大写字母

    :param number: 生成个数
    """
    ls = random.choices(string.ascii_uppercase, k=number)
    return ''.join(ls)


# 随机选择数字: 
Example 24
Project: plugin.video.kmediatorrent   Author: jmarth   File: eztv.py    License: GNU General Public License v3.0 5 votes vote down vote up
def eztv_index():
    import string
    for letter in ["0-9"] + list(string.ascii_uppercase):
        yield {
            "label": letter,
            "path": plugin.url_for("eztv_shows_by_letter", letter=letter),
            "is_playable": False,
        } 
Example 25
Project: Python_Master_Courses   Author: makelove   File: caesarCipher.py    License: GNU General Public License v3.0 5 votes vote down vote up
def encode(s, key='H'):
    rt = []
    for c in s.upper():  # 大写
        if c in string.ascii_uppercase:
            n = ord(c) + ord(key)
            if n > 90:
                n = n - 26
            c = chr(n)
        rt.append(c)
    return ''.join(rt) 
Example 26
Project: Python_Master_Courses   Author: makelove   File: caesarCipher.py    License: GNU General Public License v3.0 5 votes vote down vote up
def decode(s, key='H'):
    rt = []
    for c in s.upper():
        if c in string.ascii_uppercase:
            n = ord(c) - ord(key)
            if n < 65:
                n = n + 26
            c = chr(n)
        rt.append(c)
    return ''.join(rt) 
Example 27
Project: gitlab-tools   Author: Salamek   File: crypto.py    License: GNU General Public License v3.0 5 votes vote down vote up
def random_password() -> str:
    """
    Generates random password with fixed len of 64 characters
    :return: 64 len string
    """
    return hashlib.sha256('{}_{}_{}'.format(
        random.randint(0, sys.maxsize),
        round(time.time() * 1000),
        ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(20))
    ).encode('UTF-8')).hexdigest() 
Example 28
Project: Data_Analytics_with_Hadoop   Author: oreillymedia   File: impression_tracker.py    License: MIT License 5 votes vote down vote up
def generate_skus(num):
    skus = []
    for i in xrange(num):
        sku = '%s%d-%d' % (random.choice(string.ascii_uppercase), random.randint(1000, 9999), random.randint(0, 9))
        skus.append(sku)
    return skus 
Example 29
Project: snowflake-connector-python   Author: snowflakedb   File: test_put_get_medium.py    License: Apache License 2.0 5 votes vote down vote up
def _generate_huge_value_json(tmpdir, n=1, value_size=1):
    fname = str(tmpdir.join('test_put_get_huge_json'))
    f = gzip.open(fname, 'wb')
    for i in range(n):
        logger.debug("adding a value in {}".format(i))
        f.write('{{"k":"{}"}}'.format(
            ''.join(
                random.choice(string.ascii_uppercase + string.digits) for _ in
                range(value_size))))
    f.close()
    return fname 
Example 30
Project: snowflake-connector-python   Author: snowflakedb   File: test_put_get_medium.py    License: Apache License 2.0 5 votes vote down vote up
def _generate_huge_value_json(tmpdir, n=1, value_size=1):
    fname = str(tmpdir.join('test_put_get_huge_json'))
    f = gzip.open(fname, 'wb')
    for i in range(n):
        logger.debug("adding a value in {}".format(i))
        f.write('{{"k":"{}"}}'.format(
            ''.join(
                random.choice(string.ascii_uppercase + string.digits) for _ in
                range(value_size))))
    f.close()
    return fname