Python string 模块,upper() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用string.upper()

项目:code    作者:ActiveState    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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'
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
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
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
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'])
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
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
################################################################################
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
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 )
项目:bx-python    作者:bxlab    | 项目源码 | 文件源码
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)
项目:bx-python    作者:bxlab    | 项目源码 | 文件源码
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
项目:bx-python    作者:bxlab    | 项目源码 | 文件源码
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.
项目:bx-python    作者:bxlab    | 项目源码 | 文件源码
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
项目:OpenStackClient_Workspace    作者:Huawei    | 项目源码 | 文件源码
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
项目:spqrel_tools    作者:LCAS    | 项目源码 | 文件源码
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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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)
项目:HomBlocks    作者:fenghen360    | 项目源码 | 文件源码
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)
项目:HomBlocks    作者:fenghen360    | 项目源码 | 文件源码
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
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
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
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
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'])
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
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
################################################################################
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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'
项目:bovada-hand-history-converter    作者:matt57225    | 项目源码 | 文件源码
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)
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
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
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
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 )
项目:needle    作者:mwrlabs    | 项目源码 | 文件源码
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
# ======================================================================================================================
项目:cegr-galaxy    作者:seqcode    | 项目源码 | 文件源码
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
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
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.
项目:rensapy    作者:RensaProject    | 项目源码 | 文件源码
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
项目:rensapy    作者:RensaProject    | 项目源码 | 文件源码
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
项目:Ossian    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
def enrich_nodes(node, function=string.upper,\
                     target_nodes="//Token", input_attribute="text", \
                     output_attribute="uppercase_text", overwrite=True, kwargs={}):
    """
    Apply function to elements of utt that mathc xpath target_nodes. Input to
    the function with be input_attribute, output will be put in output_attribute.  

    Using the defaults, this should make uppercase copies of tokens [TODO: test this].  
    """
    nodes = node.xpath(target_nodes)
    assert len(nodes) > 0
    for node in nodes:
        assert node.has_attribute(input_attribute)
        if not overwrite:
            assert not node.has_attribute(output_attribute),"Cannot overwrite existing '%s' in node "%(output_attribute)
        input_data = node.get(input_attribute)
        transformed_data = function(input_data, **kwargs)
        node.set(output_attribute, transformed_data)
项目:RePhraser    作者:MissLummie    | 项目源码 | 文件源码
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
项目:RePhraser    作者:MissLummie    | 项目源码 | 文件源码
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
项目:image-occlusion-enhanced    作者:glutanimate    | 项目源码 | 文件源码
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.
项目:HoneySMB    作者:r0hi7    | 项目源码 | 文件源码
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
项目:HoneySMB    作者:r0hi7    | 项目源码 | 文件源码
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'])
项目:HoneySMB    作者:r0hi7    | 项目源码 | 文件源码
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
################################################################################
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
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)
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
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
项目:InstagramPosting    作者:LeviParadis    | 项目源码 | 文件源码
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.
项目:Verideals    作者:Derrreks    | 项目源码 | 文件源码
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
项目:Verideals    作者:Derrreks    | 项目源码 | 文件源码
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
项目:crispr    作者:mbiokyle29    | 项目源码 | 文件源码
def __init__(self, sequence, **kwargs):
        SeqRecord.__init__(self, sequence, **kwargs)

        sequence = upper(sequence)
        g_count = sequence.count('G')
        c_count = sequence.count('C')

        # make GC content as a percent
        content = sum([g_count, c_count]) / float(len(sequence))
        content = content * 100
        self.gc_content = round(content, 0)

        # set the start stop in parent seq
        self.start = int(kwargs.get('id', -1))
        self.stop = self.start + len(sequence) - 1

        # set up score
        self.score = -1
        self.genes = []
项目:iOSSecAudit    作者:alibaba    | 项目源码 | 文件源码
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])
                #trace.write(' ' * indent)
                #trace.write('[%s] %s (value %s)' %
                #         (strclass(tag[2]), strid(tag[0]), repr(value)))
                #trace.write('\n')
            elif tag[1] == ASN1.TypeConstructed:
                #trace.write(' ' * indent)
                #trace.write('[%s] %s:\n' % (strclass(tag[2]), strid(tag[0])))
                input.enter()
                output.enter(tag[0], tag[2])
                self._process_subject(input, output, indent+2)
                output.leave()
                input.leave()

#----------------------------------------------------------------------
# IOS TrustStore.sqlite3 handling
#----------------------------------------------------------------------
项目:ngx_status    作者:YoYoAdorkable    | 项目源码 | 文件源码
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.
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def cmdln():
    """Setup command line parser.
    """
    cmdln = optparse.OptionParser(usage=USAGE, description=DESCR)
    cmdln.add_option('-r', dest='recurse', action='store_true',
                     help='Recurse into subdirs')
    cmdln.add_option('-s', dest='silent', action='store_true',
                     help='Silent mode')
    cmdln.add_option('-n', dest='dryrun', action='store_true',
                     help='dry run/No-op mode (don\'t actually rename)')
    cmdln.add_option('-L', dest='lower', action='store_true',
                     help='make Lower case (string.lower)')
    cmdln.add_option('-U', dest='upper', action='store_true',
                     help='make Upper case (string.upper)')
    cmdln.add_option('-C', dest='capwords', action='store_true',
                     help='Capitalize words (string.capwords)')
    cmdln.add_option('-f', dest='fromchars', default='',
                     help='translate From FROMCHARS characters (requires -t)')
    cmdln.add_option('-t', dest='tochars', default='',
                     help='translate To TOCHARS characters (requires -f)')
    cmdln.add_option('-d', dest='delchars', default='',
                     help='Delete DELCHARS characters from file names')
    cmdln.add_option('-l', dest='limitglob', default='*',
                     help='Limit file globbing to LIMITGLOB pattern')
    opts, args = cmdln.parse_args(sys.argv[1:])
    opts.stringfunc = lambda x: x
    if opts.capwords: opts.stringfunc = string.capwords
    if opts.upper:    opts.stringfunc = string.upper
    if opts.lower:    opts.stringfunc = string.lower
    error_checks(cmdln, args, opts)
    return opts, args[0]
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def upcase(s):
 return string.upper(s)