Python string.digits() Examples
The following are 30
code examples of string.digits().
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
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: Encryption.py From vault with MIT License | 8 votes |
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 |
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 |
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: casm.py From stream with MIT License | 7 votes |
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 #5
Source File: casm.py From stream with MIT License | 7 votes |
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 #6
Source File: items.py From tomlkit with MIT License | 7 votes |
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 #7
Source File: client_auth.py From maubot with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: test_cli.py From hydrus with MIT License | 6 votes |
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 #9
Source File: test_crud.py From hydrus with MIT License | 6 votes |
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 #10
Source File: configurator.py From friendly-telegram with GNU Affero General Public License v3.0 | 6 votes |
def api_config(): """Request API config from user and set""" code, hash_value = DIALOG.inputbox("Enter your API Hash") if code == DIALOG.OK: if len(hash_value) != 32 or any(it not in string.hexdigits for it in hash_value): DIALOG.msgbox("Invalid hash") return string1 = "HASH = \"" + hash_value + "\"" code, id_value = DIALOG.inputbox("Enter your API ID") if not id_value or any(it not in string.digits for it in id_value): DIALOG.msgbox("Invalid ID") return string2 = "ID = \"" + id_value + "\"" with open(os.path.join(utils.get_base_dir(), "api_token.py"), "w") as file: file.write(string1 + "\n" + string2 + "\n") DIALOG.msgbox("API Token and ID set.")
Example #11
Source File: test_app.py From hydrus with MIT License | 6 votes |
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 #12
Source File: base.py From wanggeService with MIT License | 6 votes |
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 #13
Source File: util.py From instavpn with Apache License 2.0 | 6 votes |
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 #14
Source File: lambda_function.py From aws-batch-example with MIT License | 6 votes |
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 #15
Source File: my_utils.py From ICDAR-2019-SROIE with MIT License | 6 votes |
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 #16
Source File: conanfile.py From conan-center-index with MIT License | 6 votes |
def _library_name(self): libname = "jemalloc" if self.settings.compiler == "Visual Studio": if self.options.shared: if self.settings.build_type == "Debug": libname += "d" else: toolset = msvs_toolset(self.settings) toolset_number = "".join(c for c in toolset if c in string.digits) libname += "-vc{}-{}".format(toolset_number, self._msvc_build_type) else: if self.settings.os == "Windows": if not self.options.shared: libname += "_s" else: if not self.options.shared and self.options.fPIC: libname += "_pic" return libname
Example #17
Source File: __init__.py From pyspelling with MIT License | 5 votes |
def random_name_gen(size=6): """Generate a random python attribute name.""" return ''.join( [random.choice(string.ascii_uppercase)] + [random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)] ) if size > 0 else ''
Example #18
Source File: test_all.py From cog with GNU Affero General Public License v3.0 | 5 votes |
def user(app): quill_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) token = jws.sign(quill_id, SECRET, algorithm='HS256') user = User(quill_id, 'alyssap@hacker.org', False) db.session.add(user) db.session.commit() app.set_cookie('localhost:8000', 'jwt', token) return user
Example #19
Source File: crackfortran.py From recruit with Apache License 2.0 | 5 votes |
def expr2name(a, block, args=[]): orig_a = a a_is_expr = not analyzeargs_re_1.match(a) if a_is_expr: # `a` is an expression implicitrules, attrrules = buildimplicitrules(block) at = determineexprtype(a, block['vars'], implicitrules) na = 'e_' for c in a: c = c.lower() if c not in string.ascii_lowercase + string.digits: c = '_' na = na + c if na[-1] == '_': na = na + 'e' else: na = na + '_e' a = na while a in block['vars'] or a in block['args']: a = a + 'r' if a in args: k = 1 while a + str(k) in args: k = k + 1 a = a + str(k) if a_is_expr: block['vars'][a] = at else: if a not in block['vars']: if orig_a in block['vars']: block['vars'][a] = block['vars'][orig_a] else: block['vars'][a] = {} if 'externals' in block and orig_a in block['externals'] + block['interfaced']: block['vars'][a] = setattrspec(block['vars'][a], 'external') return a
Example #20
Source File: casm.py From stream with MIT License | 5 votes |
def s_declit(s, t): lit = "" while not s.empty() and s.peek() in string.digits: lit += s.get() if not lit: return False t.append(int(lit)) return True
Example #21
Source File: test_dtypes.py From recruit with Apache License 2.0 | 5 votes |
def test_astype_unicode(self): # see gh-7758: A bit of magic is required to set # default encoding to utf-8 digits = string.digits test_series = [ Series([digits * 10, tm.rands(63), tm.rands(64), tm.rands(1000)]), Series([u('データーサイエンス、お前はもう死んでいる')]), ] former_encoding = None if not compat.PY3: # In Python, we can force the default encoding for this test former_encoding = sys.getdefaultencoding() reload(sys) # noqa sys.setdefaultencoding("utf-8") if sys.getdefaultencoding() == "utf-8": test_series.append(Series([u('野菜食べないとやばい') .encode("utf-8")])) for s in test_series: res = s.astype("unicode") expec = s.map(compat.text_type) tm.assert_series_equal(res, expec) # Restore the former encoding if former_encoding is not None and former_encoding != "utf-8": reload(sys) # noqa sys.setdefaultencoding(former_encoding)
Example #22
Source File: casm.py From stream with MIT License | 5 votes |
def s_declit(s, t): lit = "" while not s.empty() and s.peek() in string.digits: lit += s.get() if not lit: return False t.append((TokenTypes.LITERAL_INT, int(lit))) return True
Example #23
Source File: scp_api.py From single_cell_portal with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_boundary(self): ''' Creates a random string that is likely to not be in a MIME message. Used as a boundary between MIME parts. :return: String ''' base = string.ascii_lowercase + string.digits return("".join([random.choice(base) for i in range(c_BOUNDARY_LENGTH)])) # The expected header
Example #24
Source File: tgc_gui.py From TGC-Designer-Tools with Apache License 2.0 | 5 votes |
def validateCourseName(action_type, index, value, previous, new_text, validation_types, validation_type, widget_name): # We also can submit as long of a course name as we want, so remove this limit! #if len(value) > 32: # return False return True # Looks like they accept almost all characters, wow... '''allowed_chars = string.ascii_letters + string.digits + ' ' allowed_set = set(allowed_chars) valid = all(x in allowed_set for x in new_text) if not valid: return False course_name_var.set(previous) return True'''
Example #25
Source File: instruments.py From CalibrationNN with GNU General Public License v3.0 | 5 votes |
def format_price(p, digits = 2): format = '%%.%df' % digits return format % p
Example #26
Source File: crypto.py From gitlab-tools with GNU General Public License v3.0 | 5 votes |
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 #27
Source File: basekeyparser.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def _match_count(self, sequence: keyutils.KeySequence, dry_run: bool) -> bool: """Try to match a key as count.""" txt = str(sequence[-1]) # To account for sequences changed above. if (txt in string.digits and self._supports_count and not (not self._count and txt == '0')): self._debug_log("Trying match as count") assert len(txt) == 1, txt if not dry_run: self._count += txt self.keystring_updated.emit(self._count + str(self._sequence)) return True return False
Example #28
Source File: create.py From plugin.video.kmediatorrent with GNU General Public License v3.0 | 5 votes |
def validate_pluginid(value): '''Returns True if the provided value is a valid pluglin id''' valid = string.ascii_letters + string.digits + '.' return all(c in valid for c in value)
Example #29
Source File: methods.py From Jtyoui with MIT License | 5 votes |
def random_digits(number=1): """随机选择数字 :param number: 生成个数 """ ls = random.choices(string.digits, k=number) return ''.join(ls) # 随机选择特殊字符:
Example #30
Source File: test_put_get_medium.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
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