def beautify(uglypath, table, delchars='', stringfunc=None):
"""Make three changes to a name in an ugly path.
The changes are (1) apply a string function, (2) translate
characters, and (3) delete characters.
>>> table = string.maketrans('', '')
>>> beautify('/foo/bar/a"b)c]d e.txt', table, UGLYCHARS)
'/foo/bar/abcde.txt'
>>> beautify("03 - Blue 'n' Boogie.mp3", table, UGLYCHARS)
'03-BluenBoogie.mp3'
>>> beautify("My Document #3 - (2005)[1].txt", table, UGLYCHARS)
'MyDocument3-20051.txt'
>>> beautify('a_b-c', table, UGLYCHARS, string.upper)
'A_B-C'
"""
dirname, ugly2pretty, ext = split_dir_base_ext(uglypath)
if stringfunc is not None:
ugly2pretty = stringfunc(ugly2pretty)
# Translate FROMCHARS to TOCHARS and delete DELCHARS
ugly2pretty = ugly2pretty.translate(table, delchars)
return os.path.join(dirname, ugly2pretty+ext)
python类upper()的实例源码
def parsePhrase(self, phrase):
"""Decode the phrase, and return a 64bit OTP
I will raise Unauthorized if the parity is wrong
TODO: Add support for hex (MUST) and the '2nd scheme'(SHOULD)"""
words = string.split(phrase)
for i in xrange(len(words)):
words[i] = string.upper(words[i])
b = 0L
for i in xrange(0,5):
b = b | ((long(dict.index(words[i])) << ((4-i)*11L+9L)))
tmp = dict.index(words[5])
b = b | (tmp & 0x7FC ) >> 2
if (tmp & 3) <> self.calculateParity(b):
raise Unauthorized("Parity error")
digest = longToString(b)
return digest
def __init__(self, write, iterable, memoryBufferSize=None):
"""
Create a _IteratorBuffer.
@param write: A one-argument callable which will be invoked with a list
of strings which have been buffered.
@param iterable: The source of input strings as any iterable.
@param memoryBufferSize: The upper limit on buffered string length,
beyond which the buffer will be flushed to the writer.
"""
self.lines = []
self.write = write
self.iterator = iter(iterable)
if memoryBufferSize is None:
memoryBufferSize = 2 ** 16
self.memoryBufferSize = memoryBufferSize
def do_AUTH(self, args=None):
if not getattr(self.factory, 'challengers', None):
self.failResponse("AUTH extension unsupported")
return
if args is None:
self.successResponse("Supported authentication methods:")
for a in self.factory.challengers:
self.sendLine(a.upper())
self.sendLine(".")
return
auth = self.factory.challengers.get(args.strip().upper())
if not self.portal or not auth:
self.failResponse("Unsupported SASL selected")
return
self._auth = auth()
chal = self._auth.getChallenge()
self.sendLine('+ ' + base64.encodestring(chal).rstrip('\n'))
self.state = 'AUTH'
def complete_get(self, text, line, begidx, endidx, include = 1):
# include means
# 1 just files
# 2 just directories
items = []
if include == 1:
mask = 0
else:
mask = FILE_ATTR_I30_INDEX_PRESENT
for i in self.completion:
if i[1] == mask:
items.append(i[0])
if text:
return [
item for item in items
if item.upper().startswith(text.upper())
]
else:
return items
def name_query_request(self, nbname, destaddr = None, qtype = TYPE_SERVER, scope = None, timeout = 1):
netbios_name = nbname.upper()
qn_label = encode_name(netbios_name, qtype, scope)
p = NAME_QUERY_REQUEST()
p['NAME_TRN_ID'] = randint(1, 32000)
p['QUESTION_NAME'] = qn_label[:-1]
p['FLAGS'] = NM_FLAGS_RD
if not destaddr:
p['FLAGS'] |= NM_FLAGS_BROADCAST
destaddr = self.__broadcastaddr
req = p.getData()
res = self.send(p, destaddr, timeout)
return NBPositiveNameQueryResponse(res['ANSWERS'])
def node_status_request(self, nbname, destaddr, type, scope, timeout):
netbios_name = string.upper(nbname)
qn_label = encode_name(netbios_name, type, scope)
p = NODE_STATUS_REQUEST()
p['NAME_TRN_ID'] = randint(1, 32000)
p['QUESTION_NAME'] = qn_label[:-1]
if not destaddr:
p['FLAGS'] = NM_FLAGS_BROADCAST
destaddr = self.__broadcastaddr
res = self.send(p, destaddr, timeout)
answ = NBNodeStatusResponse(res['ANSWERS'])
self.mac = answ.get_mac()
return answ.entries
################################################################################
# 4.2 SESSION SERVICE PACKETS
################################################################################
def __connect_tree(self, path, service, password, timeout = None):
if password:
# Password is only encrypted if the server passed us an "encryption" during protocol dialect
# negotiation and mxCrypto's DES module is loaded.
if self.__enc_key and DES:
password = self.__deshash(password)
self.__send_smb_packet(SMB.SMB_COM_TREE_CONNECT_ANDX, 0, 0x08, 0, 0, 0, pack('<BBHHH', 0xff, 0, 0, 0, len(password)), password + string.upper(path) + '\0' + service + '\0')
else:
self.__send_smb_packet(SMB.SMB_COM_TREE_CONNECT_ANDX, 0, 0x08, 0, 0, 0, pack('<BBHHH', 0xff, 0, 0, 0, 1), '\0' + string.upper(path) + '\0' + service + '\0')
while 1:
data = self.__sess.recv_packet(timeout)
if data:
cmd, err_class, err_code, flags1, flags2, tid, _, mid, params, d = self.__decode_smb(data)
if cmd == SMB.SMB_COM_TREE_CONNECT_ANDX:
if err_class == 0x00 and err_code == 0x00:
return tid
else:
raise SessionError, ( "Cannot connect tree. (ErrClass: %d and ErrCode: %d)" % ( err_class, err_code ), err_class, err_code )
def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
super(Keyword,self).__init__()
self.match = matchString
self.matchLen = len(matchString)
try:
self.firstMatchChar = matchString[0]
except IndexError:
warnings.warn("null string passed to Keyword; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.name = '"%s"' % self.match
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = False
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.caseless = caseless
if caseless:
self.caselessmatch = matchString.upper()
identChars = identChars.upper()
self.identChars = _str2dict(identChars)
def parseImpl( self, instring, loc, doActions=True ):
if self.caseless:
if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
(loc == 0 or instring[loc-1].upper() not in self.identChars) ):
return loc+self.matchLen, self.match
else:
if (instring[loc] == self.firstMatchChar and
(self.matchLen==1 or instring.startswith(self.match,loc)) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
(loc == 0 or instring[loc-1] not in self.identChars) ):
return loc+self.matchLen, self.match
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
def __call__( self, block ):
if not block: return block
if len(block.components) < 2:
return
cpglist = list_cpg_restricted( \
string.upper(block.components[0].text), \
string.upper(block.components[1].text) )
# now we have a fast list of CpG columns, iterate/mask
self.masked += len(cpglist)
self.total += len(block.components[0].text)
for component in block.components:
component.text = mask_columns( cpglist, component.text, self.mask )
return block
# Inclusive. Mask out all sites that are not non-CpG sites.
def __call__( self, block ):
if not block: return block
if len(block.components) < 2:
return
cpglist = list_cpg( \
string.upper(block.components[0].text), \
string.upper(block.components[1].text) )
self.masked += len( cpglist )
self.total += len( block.components[0].text )
for component in block.components:
component.text = mask_columns( cpglist, component.text, self.mask)
return block
#Mak nonCpG sites
def volume_type(user_input=''):
try:
volume = user_input.split(':', 1)
if len(volume) != 2:
raise ValueError
_volume_type = string.upper(volume[0])
volume_size = int(volume[1])
if _volume_type != 'SSD' and _volume_type != 'SATA':
raise ValueError
return dict(type=_volume_type, size=volume_size)
except ValueError:
msg = _("%s is not a valid volume format") % user_input
raise argparse.ArgumentTypeError(msg)
# noinspection PyTypeChecker
def match(self, pattern, that, topic):
"""Return the template which is the closest match to pattern. The
'that' parameter contains the bot's previous response. The 'topic'
parameter contains the current topic of conversation.
Returns None if no template is found.
"""
if len(pattern) == 0:
return None
# Mutilate the input. Remove all punctuation and convert the
# text to all caps.
input = string.upper(pattern)
input = re.sub(self._puncStripRE, " ", input)
if that.strip() == u"": that = u"ULTRABOGUSDUMMYTHAT" # 'that' must never be empty
thatInput = string.upper(that)
thatInput = re.sub(self._puncStripRE, " ", thatInput)
thatInput = re.sub(self._whitespaceRE, " ", thatInput)
if topic.strip() == u"": topic = u"ULTRABOGUSDUMMYTOPIC" # 'topic' must never be empty
topicInput = string.upper(topic)
topicInput = re.sub(self._puncStripRE, " ", topicInput)
# Pass the input off to the recursive call
patMatch, template = self._match(input.split(), thatInput.split(), topicInput.split(), self._root)
return template
entry-with-shared-variable.py 文件源码
项目:python2-tracer
作者: extremecoders-re
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.entrythingy = Entry(self)
self.entrythingy.pack()
self.button = Button(self, text="Uppercase The Entry",
command=self.upper)
self.button.pack()
# here we have the text in the entry widget tied to a variable.
# changes in the variable are echoed in the widget and vice versa.
# Very handy.
# there are other Variable types. See Tkinter.py for all
# the other variable types that can be shadowed
self.contents = StringVar()
self.contents.set("this is a variable")
self.entrythingy.config(textvariable=self.contents)
# and here we get a callback when the user hits return. we could
# make the key that triggers the callback anything we wanted to.
# other typical options might be <Key-Tab> or <Key> (for anything)
self.entrythingy.bind('<Key-Return>', self.print_contents)
def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
super(Keyword,self).__init__()
self.match = matchString
self.matchLen = len(matchString)
try:
self.firstMatchChar = matchString[0]
except IndexError:
warnings.warn("null string passed to Keyword; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.name = '"%s"' % self.match
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = False
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.caseless = caseless
if caseless:
self.caselessmatch = matchString.upper()
identChars = identChars.upper()
self.identChars = _str2dict(identChars)
def parseImpl( self, instring, loc, doActions=True ):
if self.caseless:
if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
(loc == 0 or instring[loc-1].upper() not in self.identChars) ):
return loc+self.matchLen, self.match
else:
if (instring[loc] == self.firstMatchChar and
(self.matchLen==1 or instring.startswith(self.match,loc)) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
(loc == 0 or instring[loc-1] not in self.identChars) ):
return loc+self.matchLen, self.match
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
def name_registration_request(self, nbname, destaddr, qtype, scope, nb_flags=0, nb_address='0.0.0.0'):
netbios_name = nbname.upper()
qn_label = encode_name(netbios_name, qtype, scope)
p = NAME_REGISTRATION_REQUEST()
p['NAME_TRN_ID'] = randint(1, 32000)
p['QUESTION_NAME'] = qn_label[:-1]
p['RR_NAME'] = qn_label[:-1]
p['TTL'] = 0xffff
p['NB_FLAGS'] = nb_flags
p['NB_ADDRESS'] = socket.inet_aton(nb_address)
if not destaddr:
p['FLAGS'] |= NM_FLAGS_BROADCAST
destaddr = self.__broadcastaddr
req = p.getData()
res = self.send(p, destaddr, 1)
return res
def name_query_request(self, nbname, destaddr = None, qtype = TYPE_SERVER, scope = None, timeout = 1):
netbios_name = nbname.upper()
qn_label = encode_name(netbios_name, qtype, scope)
p = NAME_QUERY_REQUEST()
p['NAME_TRN_ID'] = randint(1, 32000)
p['QUESTION_NAME'] = qn_label[:-1]
p['FLAGS'] = NM_FLAGS_RD
if not destaddr:
p['FLAGS'] |= NM_FLAGS_BROADCAST
destaddr = self.__broadcastaddr
req = p.getData()
res = self.send(p, destaddr, timeout)
return NBPositiveNameQueryResponse(res['ANSWERS'])
def node_status_request(self, nbname, destaddr, type, scope, timeout):
netbios_name = string.upper(nbname)
qn_label = encode_name(netbios_name, type, scope)
p = NODE_STATUS_REQUEST()
p['NAME_TRN_ID'] = randint(1, 32000)
p['QUESTION_NAME'] = qn_label[:-1]
if not destaddr:
p['FLAGS'] = NM_FLAGS_BROADCAST
destaddr = self.__broadcastaddr
res = self.send(p, destaddr, timeout)
answ = NBNodeStatusResponse(res['ANSWERS'])
self.mac = answ.get_mac()
return answ.entries
################################################################################
# 4.2 SESSION SERVICE PACKETS
################################################################################
def parsePhrase(self, phrase):
"""Decode the phrase, and return a 64bit OTP
I will raise Unauthorized if the parity is wrong
TODO: Add support for hex (MUST) and the '2nd scheme'(SHOULD)"""
words = string.split(phrase)
for i in xrange(len(words)):
words[i] = string.upper(words[i])
b = 0L
for i in xrange(0,5):
b = b | ((long(dict.index(words[i])) << ((4-i)*11L+9L)))
tmp = dict.index(words[5])
b = b | (tmp & 0x7FC ) >> 2
if (tmp & 3) <> self.calculateParity(b):
raise Unauthorized("Parity error")
digest = longToString(b)
return digest
def __init__(self, write, iterable, memoryBufferSize=None):
"""
Create a _IteratorBuffer.
@param write: A one-argument callable which will be invoked with a list
of strings which have been buffered.
@param iterable: The source of input strings as any iterable.
@param memoryBufferSize: The upper limit on buffered string length,
beyond which the buffer will be flushed to the writer.
"""
self.lines = []
self.write = write
self.iterator = iter(iterable)
if memoryBufferSize is None:
memoryBufferSize = 2 ** 16
self.memoryBufferSize = memoryBufferSize
def do_AUTH(self, args=None):
if not getattr(self.factory, 'challengers', None):
self.failResponse("AUTH extension unsupported")
return
if args is None:
self.successResponse("Supported authentication methods:")
for a in self.factory.challengers:
self.sendLine(a.upper())
self.sendLine(".")
return
auth = self.factory.challengers.get(args.strip().upper())
if not self.portal or not auth:
self.failResponse("Unsupported SASL selected")
return
self._auth = auth()
chal = self._auth.getChallenge()
self.sendLine('+ ' + base64.encodestring(chal).rstrip('\n'))
self.state = 'AUTH'
def join_holecards(self, player, asList=False):
holeNo = Card.games[self.gametype['category']][5][0][1]
hcs = [u'0x'] * holeNo
for street in self.holeStreets:
if player in self.holecards[street].keys():
if len(self.holecards[street][player][1])==1: continue
for i in 0,1:
hcs[i] = self.holecards[street][player][1][i]
hcs[i] = upper(hcs[i][0:1])+hcs[i][1:2]
try:
for i in xrange(2, holeNo):
hcs[i] = self.holecards[street][player][1][i]
hcs[i] = upper(hcs[i][0:1])+hcs[i][1:2]
except IndexError:
log.debug("Why did we get an indexerror?")
if asList:
return hcs
else:
return " ".join(hcs)
def formatMS(self,fmt):
'''format like MS date using the notation
{YY} --> 2 digit year
{YYYY} --> 4 digit year
{M} --> month as digit
{MM} --> 2 digit month
{MMM} --> abbreviated month name
{MMMM} --> monthname
{MMMMM} --> first character of monthname
{D} --> day of month as digit
{DD} --> 2 digit day of month
{DDD} --> abrreviated weekday name
{DDDD} --> weekday name
'''
r = fmt[:]
f = 0
while 1:
m = _fmtPat.search(r,f)
if m:
y = getattr(self,'_fmt'+string.upper(m.group()[1:-1]))()
i, j = m.span()
r = (r[0:i] + y) + r[j:]
f = i + len(y)
else:
return r
def __connect_tree(self, path, service, password, timeout = None):
if password:
# Password is only encrypted if the server passed us an "encryption" during protocol dialect
# negotiation and mxCrypto's DES module is loaded.
if self.__enc_key and DES:
password = self.__deshash(password)
self.__send_smb_packet(SMB.SMB_COM_TREE_CONNECT_ANDX, 0, 0x08, 0, 0, 0, pack('<BBHHH', 0xff, 0, 0, 0, len(password)), password + string.upper(path) + '\0' + service + '\0')
else:
self.__send_smb_packet(SMB.SMB_COM_TREE_CONNECT_ANDX, 0, 0x08, 0, 0, 0, pack('<BBHHH', 0xff, 0, 0, 0, 1), '\0' + string.upper(path) + '\0' + service + '\0')
while 1:
data = self.__sess.recv_packet(timeout)
if data:
cmd, err_class, err_code, flags1, flags2, tid, _, mid, params, d = self.__decode_smb(data)
if cmd == SMB.SMB_COM_TREE_CONNECT_ANDX:
if err_class == 0x00 and err_code == 0x00:
return tid
else:
raise SessionError, ( "Cannot connect tree. (ErrClass: %d and ErrCode: %d)" % ( err_class, err_code ), err_class, err_code )
def _process_subject(self, input, output, indent=0):
# trace = sys.stdout
while not input.eof():
tag = input.peek()
if tag[1] == ASN1.TypePrimitive:
tag, value = input.read()
if tag[0] == ASN1.PrintableString:
value = string.upper(value)
output.write(value, tag[0], tag[1], tag[2])
elif tag[1] == ASN1.TypeConstructed:
input.enter()
output.enter(tag[0], tag[2])
self._process_subject(input, output, indent+2)
output.leave()
input.leave()
# ======================================================================================================================
# IOS TrustStore.sqlite3 handling
# ======================================================================================================================
def get_config_settings(config_file=None, type='defaults'):
# Current types: defaults, workflow_invocation, workflows
if config_file is None:
config_file = CONFIG_FILE
d = {}
config_parser = ConfigParser()
config_parser.read(config_file)
for key, value in config_parser.items(type):
if type == 'defaults':
d[string.upper(key)] = value
log_file_dir = d.get('ANALYSIS_PREP_LOG_FILE_DIR', os.getcwd())
d['ANALYSIS_PREP_LOG_FILE'] = os.path.join(log_file_dir, ANALYSIS_PREP_LOG_FILE_NAME)
elif type == 'len_files':
d[key] = value
elif type == 'workflow_invocation':
d[string.upper(key)] = listify(value)
elif type == 'workflows':
d[string.upper(key)] = value
return d
def copy(self):
"Copy raster data"
self.load()
im = self.im.copy()
return self._new(im)
##
# Returns a rectangular region from this image. The box is a
# 4-tuple defining the left, upper, right, and lower pixel
# coordinate.
# <p>
# This is a lazy operation. Changes to the source image may or
# may not be reflected in the cropped image. To break the
# connection, call the {@link #Image.load} method on the cropped
# copy.
#
# @param The crop rectangle, as a (left, upper, right, lower)-tuple.
# @return An Image object.
def _initializePOSTables():
global _POSNormalizationTable, _POStoDictionaryTable
_POSNormalizationTable = {}
_POStoDictionaryTable = {}
for pos, abbreviations in (
(NOUN, "noun n n."),
(VERB, "verb v v."),
(ADJECTIVE, "adjective adj adj. a s"),
(ADVERB, "adverb adv adv. r")):
tokens = string.split(abbreviations)
for token in tokens:
_POSNormalizationTable[token] = pos
_POSNormalizationTable[string.upper(token)] = pos
for dict in Dictionaries:
_POSNormalizationTable[dict] = dict.pos
_POStoDictionaryTable[dict.pos] = dict