本文整理汇总了Python中string.ascii_uppercase方法的典型用法代码示例。如果您正苦于以下问题:Python string.ascii_uppercase方法的具体用法?Python string.ascii_uppercase怎么用?Python string.ascii_uppercase使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块string的用法示例。
在下文中一共展示了string.ascii_uppercase方法的27个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: gen_dummy_object
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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_
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:23,
示例2: lambda_handler
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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']))
开发者ID:dejonghe,项目名称:aws-batch-example,代码行数:21,
示例3: random_string
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:zzzDavid,项目名称:ICDAR-2019-SROIE,代码行数:21,
示例4: setup_passwords
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:sockeye44,项目名称:instavpn,代码行数:19,
示例5: login
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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)
开发者ID:maubot,项目名称:maubot,代码行数:23,
示例6: test_info_memory_usage_bug_on_multiindex
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:Frank-qlu,项目名称:recruit,代码行数:25,
示例7: convert_to_label_chars
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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)
开发者ID:DataBiosphere,项目名称:dsub,代码行数:27,
示例8: generate_uuid
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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))
开发者ID:choderalab,项目名称:assaytools,代码行数:19,
示例9: get_snap
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:Benehiko,项目名称:ReolinkCameraAPI,代码行数:26,
示例10: rand_password
点赞 6
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
'--
-'
(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
开发者ID:openstack,项目名称:tempest-lib,代码行数:23,
示例11: gen_random_string
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
def gen_random_string(n):
return ''.join(
random.choice(
string.ascii_uppercase + string.digits
) for _ in range(n)
)
开发者ID:kmac,项目名称:mlbv,代码行数:8,
示例12: generate_password
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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)
开发者ID:kislyuk,项目名称:aegea,代码行数:13,
示例13: generate_token
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
def generate_token(length=60):
chars = string.ascii_uppercase + string.digits
return ''.join(random.choice(chars) for _ in range(length))
开发者ID:kimeraapp,项目名称:pythonjobs.ie,代码行数:5,
示例14: patch_toon
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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")
开发者ID:martenjacobs,项目名称:ToonRooter,代码行数:28,
示例15: test_recordio_pack_label
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:16,
示例16: random_string
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
def random_string(N):
return ''.join(choice(string.ascii_uppercase + string.digits + ' ') for _ in range(N))
开发者ID:codeforamerica,项目名称:comport,代码行数:4,
示例17: test_long_tokens
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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)
开发者ID:akzaidi,项目名称:fine-lm,代码行数:36,
示例18: random_four
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
def random_four():
"""Returns a random 4 charactors"""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
开发者ID:dejonghe,项目名称:aws-batch-example,代码行数:5,
示例19: issue
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:laurivosandi,项目名称:certidude,代码行数:35,
示例20: generate_esn
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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))
开发者ID:truedread,项目名称:pymsl,代码行数:14,
示例21: random_upper_char
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
def random_upper_char(number=1):
"""随机选择大写字母
:param number: 生成个数
"""
ls = random.choices(string.ascii_uppercase, k=number)
return ''.join(ls)
# 随机选择数字:
开发者ID:jtyoui,项目名称:Jtyoui,代码行数:12,
示例22: eztv_index
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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,
}
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:10,
示例23: encode
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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)
开发者ID:makelove,项目名称:Python_Master_Courses,代码行数:12,
示例24: decode
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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)
开发者ID:makelove,项目名称:Python_Master_Courses,代码行数:12,
示例25: random_password
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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()
开发者ID:Salamek,项目名称:gitlab-tools,代码行数:12,
示例26: generate_skus
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:oreillymedia,项目名称:Data_Analytics_with_Hadoop,代码行数:8,
示例27: _generate_huge_value_json
点赞 5
# 需要导入模块: import string [as 别名]
# 或者: from string import ascii_uppercase [as 别名]
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
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:13,
注:本文中的string.ascii_uppercase方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。