Python string.upper() Examples

The following are 30 code examples of string.upper(). 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 .
Example #1
Source File: NodeProcessors.py    From Ossian with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: nmb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: wordnet.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: nmb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
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']) 
Example #5
Source File: nmb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
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
################################################################################ 
Example #6
Source File: wordnet.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: SConsOptions.py    From pivy with ISC License 6 votes vote down vote up
def format_option_strings(self, option):
        """Return a comma-separated list of option strings & metavariables."""
        if option.takes_value():
            metavar = option.metavar or string.upper(option.dest)
            short_opts = []
            for sopt in option._short_opts:
                short_opts.append(self._short_opt_fmt % (sopt, metavar))
            long_opts = []
            for lopt in option._long_opts:
                long_opts.append(self._long_opt_fmt % (lopt, metavar))
        else:
            short_opts = option._short_opts
            long_opts = option._long_opts

        if self.short_first:
            opts = short_opts + long_opts
        else:
            opts = long_opts + short_opts

        return string.join(opts, ", ") 
Example #8
Source File: _scons_optparse.py    From pivy with ISC License 6 votes vote down vote up
def format_option_strings(self, option):
        """Return a comma-separated list of option strings & metavariables."""
        if option.takes_value():
            metavar = option.metavar or string.upper(option.dest)
            short_opts = []
            for sopt in option._short_opts:
                short_opts.append(self._short_opt_fmt % (sopt, metavar))
            long_opts = []
            for lopt in option._long_opts:
                long_opts.append(self._long_opt_fmt % (lopt, metavar))
        else:
            short_opts = option._short_opts
            long_opts = option._long_opts

        if self.short_first:
            opts = short_opts + long_opts
        else:
            opts = long_opts + short_opts

        return string.join(opts, ", ") 
Example #9
Source File: msvs.py    From pivy with ISC License 6 votes vote down vote up
def _generateGUID(slnfile, name):
    """This generates a dummy GUID for the sln file to use.  It is
    based on the MD5 signatures of the sln filename plus the name of
    the project.  It basically just needs to be unique, and not
    change with each invocation."""
    m = hashlib.md5()
    # Normalize the slnfile path to a Windows path (\ separators) so
    # the generated file has a consistent GUID even if we generate
    # it on a non-Windows platform.
    m.update(ntpath.normpath(str(slnfile)) + str(name))
    # TODO(1.5)
    #solution = m.hexdigest().upper()
    solution = string.upper(_hexdigest(m.digest()))
    # convert most of the signature to GUID form (discard the rest)
    solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
    return solution 
Example #10
Source File: ntlm.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def create_LM_hashed_password_v1(passwd):
    "setup LanManager password"
    "create LanManager hashed password"
    # if the passwd provided is already a hash, we just return the first half
    if re.match(r'^[\w]{32}:[\w]{32}$',passwd):
        return binascii.unhexlify(passwd.split(':')[0])

    # fix the password length to 14 bytes
    passwd = string.upper(passwd)
    lm_pw = passwd + '\0' * (14 - len(passwd))
    lm_pw = passwd[0:14]

    # do hash
    magic_str = "KGS!@#$%" # page 57 in [MS-NLMP]

    res = ''
    dobj = des.DES(lm_pw[0:7])
    res = res + dobj.encrypt(magic_str)

    dobj = des.DES(lm_pw[7:14])
    res = res + dobj.encrypt(magic_str)

    return res 
Example #11
Source File: nmb.py    From cracke-dit with MIT License 6 votes vote down vote up
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 
Example #12
Source File: nmb.py    From cracke-dit with MIT License 6 votes vote down vote up
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']) 
Example #13
Source File: nmb.py    From cracke-dit with MIT License 6 votes vote down vote up
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
################################################################################ 
Example #14
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def heathcheck_exist(cls, healthcheck_type, id_evironment_vip):

        health_type_upper = healthcheck_type.upper()

        env_query = Ambiente.objects.filter(
            Q(vlan__networkipv4__ambient_vip__id=id_evironment_vip) |
            Q(vlan__networkipv6__ambient_vip__id=id_evironment_vip)
        )

        environment = env_query and env_query.uniqueResult() or None

        options_pool_environment = environment.opcaopoolambiente_set.all()

        for option_pool_env in options_pool_environment:
            if option_pool_env.opcao_pool.description.upper() == health_type_upper:
                return True

        return False 
Example #15
Source File: smb.py    From tvalacarta with GNU General Public License v3.0 6 votes vote down vote up
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 ) 
Example #16
Source File: normalDate.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #17
Source File: Image.py    From mxnet-lambda with Apache License 2.0 6 votes vote down vote up
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. 
Example #18
Source File: __init__.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def determine_netbios_name(hostname):
    """Determine a netbios name from a hostname."""
    # remove forbidden chars and force the length to be <16
    netbiosname = "".join([x for x in hostname if is_valid_netbios_char(x)])
    return netbiosname[:MAX_NETBIOS_NAME_LEN].upper() 
Example #19
Source File: pildriver.py    From ImageFusion with MIT License 5 votes vote down vote up
def do_crop(self):
        """usage: crop <int:left> <int:upper> <int:right> <int:lower> <image:pic1>

        Crop and push a rectangular region from the current image.
        """
        left = int(self.do_pop())
        upper = int(self.do_pop())
        right = int(self.do_pop())
        lower = int(self.do_pop())
        image = self.do_pop()
        self.push(image.crop((left, upper, right, lower))) 
Example #20
Source File: xmlext.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def strobj_to_utf8str(text, encoding):
    if string.upper(encoding) not in ["UTF-8", "ISO-8859-1", "LATIN-1"]:
        raise ValueError("Invalid encoding: %s" % encoding)
    encoder = codecs.lookup(encoding)[0]  # encode,decode,reader,writer
    if type(text) is not unicode:
        text = unicode(text, "utf-8")
    # FIXME
    return str(encoder(text)[0]) 
Example #21
Source File: usps.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def validate(self):
        self.valid = 1
        self.validated = ''
        for c in self.value:
            if c in string.whitespace:
                continue
            elif c in "abcdABCD":
                self.validated = self.validated + string.upper(c)
            else:
                self.valid = 0

        if len(self.validated) != 1:
            raise ValueError, "Input must be exactly one character"

        return self.validated 
Example #22
Source File: Image.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def register_extension(id, extension):
    EXTENSION[string.lower(extension)] = string.upper(id)


# --------------------------------------------------------------------
# Simple display support 
Example #23
Source File: Image.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def register_save(id, driver):
    SAVE[string.upper(id)] = driver

##
# Registers an image extension.  This function should not be
# used in application code.
#
# @param id An image format identifier.
# @param extension An extension used for this format. 
Example #24
Source File: Image.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def register_mime(id, mimetype):
    MIME[string.upper(id)] = mimetype

##
# Registers an image save function.  This function should not be
# used in application code.
#
# @param id An image format identifier.
# @param driver A function to save images in this format. 
Example #25
Source File: Image.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def getbands(self):
        "Get band names"

        return ImageMode.getmode(self.mode).bands

    ##
    # Calculates the bounding box of the non-zero regions in the
    # image.
    #
    # @return The bounding box is returned as a 4-tuple defining the
    #    left, upper, right, and lower pixel coordinate. If the image
    #    is completely empty, this method returns None. 
Example #26
Source File: ref_seq_gen.py    From CAMISIM with Apache License 2.0 5 votes vote down vote up
def getSeeds(inSortedFasta, outSeedsFasta):
    """
        @param inSortedFasta: DNA sequences sorted according to the sequence length in the descending order
        @param outSeedsFasta: a fasta file that contains all seeds
    """
    out = csv.OutFileBuffer(outSeedsFasta)
    seedList = []
    seqList = fasta.getSequencesToList(inSortedFasta)  # list of (sequenceName, sequence)

    for seqId, seq in seqList:
        seq = string.upper(seq)

        newSeed = True
        for seedSeq in seedList:

            if len(seedSeq) < len(seq):
                continue

            # if bool(re.search(seq, seedSeq, re.I)) or bool(re.search(str(Seq(seq).reverse_complement()), seedSeq, re.I)):
            if seq in seedSeq or str(Seq(seq).reverse_complement()) in seedSeq:
                newSeed = False
                break

        if newSeed:
            # print 'new seed:', seqId
            seedList.append(seq)
            out.writeText(str('>' + seqId + '\n' + seq + '\n'))
        # else:
        #    print 'no seed:', seqId

    out.close()

    print 'total', len(seqList)
    print 'seed count', len(seedList)
    print 'duplicate', (len(seqList) - len(seedList)) 
Example #27
Source File: code39.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def validate(self):
        vval = [].append
        self.valid = 1
        for c in self.value:
            if c in string.lowercase:
                c = string.upper(c)
            if c not in _stdchrs:
                self.valid = 0
                continue
            vval(c)
        self.validated = ''.join(vval.__self__)
        return self.validated 
Example #28
Source File: recipe-578281.py    From code with MIT License 5 votes vote down vote up
def upcase(s):
 return string.upper(s) 
Example #29
Source File: pildriver.py    From ImageFusion with MIT License 5 votes vote down vote up
def do_paste(self):
        """usage: paste <image:figure> <int:xoffset> <int:yoffset> <image:ground>

        Paste figure image into ground with upper left at given offsets.
        """
        figure = self.do_pop()
        xoff = int(self.do_pop())
        yoff = int(self.do_pop())
        ground = self.do_pop()
        if figure.mode == "RGBA":
            ground.paste(figure, (xoff, yoff), figure)
        else:
            ground.paste(figure, (xoff, yoff))
        self.push(ground) 
Example #30
Source File: Base.py    From mailin with MIT License 5 votes vote down vote up
def req(self,*name,**args):
        " needs a refactoring "
        self.argparse(name,args)
        #if not self.args:
        #    raise ArgumentError, 'reinitialize request before reuse'
        protocol = self.args['protocol']
        self.port = self.args['port']
        self.tid = random.randint(0,65535)
        self.timeout = self.args['timeout'];
        opcode = self.args['opcode']
        rd = self.args['rd']
        server=self.args['server']
        if type(self.args['qtype']) == types.StringType:
            try:
                qtype = getattr(Type, string.upper(self.args['qtype']))
            except AttributeError:
                raise ArgumentError, 'unknown query type'
        else:
            qtype=self.args['qtype']
        if not self.args.has_key('name'):
            print self.args
            raise ArgumentError, 'nothing to lookup'
        qname = self.args['name']
        if qtype == Type.AXFR and protocol != 'tcp':
            print 'Query type AXFR, protocol forced to TCP'
            protocol = 'tcp'
        #print 'QTYPE %d(%s)' % (qtype, Type.typestr(qtype))
        m = Lib.Mpacker()
        # jesus. keywords and default args would be good. TODO.
        m.addHeader(self.tid,
              0, opcode, 0, 0, rd, 0, 0, 0,
              1, 0, 0, 0)
        m.addQuestion(qname, qtype, Class.IN)
        self.request = m.getbuf()
        try:
            if protocol == 'udp':
                self.sendUDPRequest(server)
            else:
                self.sendTCPRequest(server)
        except socket.error, reason:
            raise SocketError, reason