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))
python类lowercase()的实例源码
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)))
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
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")
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
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)
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")
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)))
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
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
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))
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'
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
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}
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
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))
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
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')
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
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
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)
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))
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
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)
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))
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
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)
def random_word(length):
return ''.join(random.choice(string.lowercase+string.uppercase+string.digits) for i in range(length))
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
def get_random_str(length):
return ''.join(random.choice(string.lowercase) for i in range(length))