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

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

项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __SkipRubish(self, aFilePathList):
        """
        Edit this method to select the private file that will not be backed up.
        """

        myFilteredList = []

        for myFilePath in aFilePathList:
            myLowerFilePath = string.lower(string.strip(myFilePath))

            if myLowerFilePath[-4:]=='.obj':
                continue

            if myLowerFilePath[-5:]=='.class':
                continue

            if myLowerFilePath[-1:]=='~':
                continue

            myFilteredList.append(myFilePath)

        return myFilteredList
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_RPL_NAMREPLY(self,prefix,params):
        """
        RPL_NAMREPLY
        >> NAMES #bnl
        << :Arlington.VA.US.Undernet.Org 353 z3p = #bnl :pSwede Dan-- SkOyg AG
        """
        group=string.lower(params[2][1:])
        users=string.split(params[3])
        for ui in range(len(users)):
            while users[ui][0] in ["@","+"]: # channel modes
                users[ui]=users[ui][1:]
        if not self._namreplies.has_key(group):
            self._namreplies[group]=[]
        self._namreplies[group].extend(users)
        for nickname in users:
                try:
                    self._ingroups[nickname].append(group)
                except:
                    self._ingroups[nickname]=[group]
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def connectionMade(self):
        def func(f,path,names):
            names.sort(lambda x,y:cmp(string.lower(x),string.lower(y)))
            for n in names:
                name=os.path.join(path,n)
                lt=time.localtime(os.path.getmtime(name))
                size=os.path.getsize(name)
                f[1]=f[1]+size
                f.append("%02d/%02d/%4d %02d:%02d %8d %s" %
                             (lt[1],lt[2],lt[0],lt[3],lt[4],size,name[f[0]:]))
        f=[len(self.dir)+1,0]
        os.path.walk(self.dir,func,f)
        size=f[1]
        self.listing=string.join(f[2:],"\r\n")+"\r\n"
        open("\\listing.txt","w").write(self.listing)
        hdr=["OFT2",256,0x1108,self.cookie,0,0,len(f)-2,len(f)-2,1,1,size,
             len(self.listing),os.path.getmtime(self.dir),
             checksum(self.listing),0,0,0,0,0,0,"OFT_Windows ICBMFT V1.1 32",
             "\002",chr(0x1a),chr(0x10),"","",0,0,""]
        self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
项目:polichombr    作者:ANSSI-FR    | 项目源码 | 文件源码
def filter_coms_blacklist(cmt):
        """
            These are standards coms, we don't want them in the DB
        """
        if cmt is None:
            g_logger.error("No comment provided to filter_coms")
            return True
        black_list = [
            "size_t", "int", "LPSTR", "char", "char *", "lpString",
            "dw", "lp", "Str", "Dest", "Src", "cch", "Dst", "jumptable",
            "switch ", "unsigned int", "void *", "Size",
            "indirect table for switch statement", "this", "jump table for",
            "switch jump", "nSize", "hInternet", "hObject",
            "SEH", "Exception handler", "Source", "Size", "Val", "Time",
            "struct", "unsigned __int", "__int32", "void (", "Memory",
            "HINSTANCE", "jumptable"
        ]
        for elem in black_list:
            if cmt.lower().startswith(elem.lower()):
                g_logger.debug("Comment %s has been blacklisted", cmt)
                return True
        return False
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def test(serverName):
    if string.lower(serverName)==string.lower(win32api.GetComputerName()):
        print "You must specify a remote server name, not the local machine!"
        return

    # Hack to overcome a DCOM limitation.  As the Python.Interpreter object
    # is probably installed locally as an InProc object, DCOM seems to ignore
    # all settings, and use the local object.
    clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER
    ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx)
    ob.Exec("import win32api")
    actualName = ob.Eval("win32api.GetComputerName()")
    if string.lower(serverName) != string.lower(actualName):
        print "Error: The object created on server '%s' reported its name as '%s'" % (serverName, actualName)
    else:
        print "Object created and tested OK on server '%s'" % serverName
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def test(serverName):
    if string.lower(serverName)==string.lower(win32api.GetComputerName()):
        print "You must specify a remote server name, not the local machine!"
        return

    # Hack to overcome a DCOM limitation.  As the Python.Interpreter object
    # is probably installed locally as an InProc object, DCOM seems to ignore
    # all settings, and use the local object.
    clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER
    ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx)
    ob.Exec("import win32api")
    actualName = ob.Eval("win32api.GetComputerName()")
    if string.lower(serverName) != string.lower(actualName):
        print "Error: The object created on server '%s' reported its name as '%s'" % (serverName, actualName)
    else:
        print "Object created and tested OK on server '%s'" % serverName
项目:ecel    作者:ARL-UTEP-OC    | 项目源码 | 文件源码
def _recolorTree(widget, oldpalette, newcolors):
    # Change the colors in a widget and its descendants.

    # Change the colors in <widget> and all of its descendants,
    # according to the <newcolors> dictionary.  It only modifies
    # colors that have their default values as specified by the
    # <oldpalette> variable.  The keys of the <newcolors> dictionary
    # are named after widget configuration options and the values are
    # the new value for that option.

    for dbOption in newcolors.keys():
        option = string.lower(dbOption)
        try:
            value = str(widget.cget(option))
        except:
            continue
        if oldpalette is None or value == oldpalette[dbOption]:
            apply(widget.configure, (), {option : newcolors[dbOption]})

    for child in widget.winfo_children():
       _recolorTree(child, oldpalette, newcolors)
项目:electron-cassette-io    作者:stardot    | 项目源码 | 文件源码
def chunk_number(self, name):
        """
        Returns the relevant chunk number for the name given.
        """

        # Use a convention for determining the chunk number to be used:
        # Certain names are converted to chunk numbers. These are listed
        # in the encode_as dictionary.

        encode_as = {'creator': 0x0, 'originator': 0x0, 'instructions': 0x1, 'manual': 0x1,
                 'credits': 0x2, 'inlay': 0x3, 'target': 0x5, 'machine': 0x5,
                 'multi': 0x6, 'multiplexing': 0x6, 'palette': 0x7,
                 'tone': 0x110, 'dummy': 0x111, 'gap': 0x112, 'baud': 0x113,
                 'position': 0x120,
                 'discinfo': 0x200, 'discside': 0x201, 'rom': 0x300,
                 '6502': 0x400, 'ula': 0x401, 'wd1770': 0x402, 'memory': 0x410,
                 'emulator': 0xff00}

        # Attempt to convert name into a chunk number
        try:
            return encode_as[string.lower(name)]

        except KeyError:
            raise UEFfile_error, "Couldn't find suitable chunk number for %s" % name
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def irc_RPL_NAMREPLY(self,prefix,params):
        """
        RPL_NAMREPLY
        >> NAMES #bnl
        << :Arlington.VA.US.Undernet.Org 353 z3p = #bnl :pSwede Dan-- SkOyg AG
        """
        group=string.lower(params[2][1:])
        users=string.split(params[3])
        for ui in range(len(users)):
            while users[ui][0] in ["@","+"]: # channel modes
                users[ui]=users[ui][1:]
        if not self._namreplies.has_key(group):
            self._namreplies[group]=[]
        self._namreplies[group].extend(users)
        for nickname in users:
                try:
                    self._ingroups[nickname].append(group)
                except:
                    self._ingroups[nickname]=[group]
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def connectionMade(self):
        def func(f,path,names):
            names.sort(lambda x,y:cmp(string.lower(x),string.lower(y)))
            for n in names:
                name=os.path.join(path,n)
                lt=time.localtime(os.path.getmtime(name))
                size=os.path.getsize(name)
                f[1]=f[1]+size
                f.append("%02d/%02d/%4d %02d:%02d %8d %s" %
                             (lt[1],lt[2],lt[0],lt[3],lt[4],size,name[f[0]:]))
        f=[len(self.dir)+1,0]
        os.path.walk(self.dir,func,f)
        size=f[1]
        self.listing=string.join(f[2:],"\r\n")+"\r\n"
        open("\\listing.txt","w").write(self.listing)
        hdr=["OFT2",256,0x1108,self.cookie,0,0,len(f)-2,len(f)-2,1,1,size,
             len(self.listing),os.path.getmtime(self.dir),
             checksum(self.listing),0,0,0,0,0,0,"OFT_Windows ICBMFT V1.1 32",
             "\002",chr(0x1a),chr(0x10),"","",0,0,""]
        self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
项目:py_menu    作者:BillWang139967    | 项目源码 | 文件源码
def __init__(self, screen, buttonlist, compact = 0):
        self.list = []
        self.hotkeys = {}
        self.item = 0
        Grid.__init__(self, len(buttonlist), 1)
        for blist in buttonlist:
            if (type(blist) == types.StringType):
                title = blist
                value = string.lower(blist)
            elif len(blist) == 2:
                (title, value) = blist
            else:
                (title, value, hotkey) = blist
                self.hotkeys[hotkey] = value

            if compact:
                b = CompactButton(title)
            else:
                b = Button(title)
            self.list.append((b, value))
            self.setField(b, self.item, 0, (1, 0, 1, 0))
            self.item = self.item + 1
项目:gram    作者:pgfoster    | 项目源码 | 文件源码
def _setTextFamily(self, newVal):
        gm = ['GramTikzStyle._setTextFamily()']
        assert isinstance(newVal, basestring)
        lowVal = string.lower(newVal)
        goodVals = self.goodTextFamilies
        if lowVal not in goodVals:
            gm.append("You can only set property 'textFamily' to one of")
            gm.append("%s" % goodVals)
            gm.append("Got attempt to set to '%s'" % newVal)
            raise GramError(gm)
        if self.font == 'helvetica':
            # if lowVal != 'sffamily':
            #     print gm[0]
            #     print "  Ignoring request to set textFamily to '%s' -- it does not work with helvetica" % newVal
            #     print "does this work?"  # does not work with ttfamily
            self._textFamily = lowVal
        else:
            self._textFamily = lowVal
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args ):
    if module:
        keep = module.__name__
        keep = keep and (built_nodes.get(module) is None)
        if keep and hasattr(module, '__file__'):
            keep = string.lower(os.path.splitext(module.__file__)[1]) not in [".pyd", ".dll"]
#               keep = keep and module.__name__=='__main__'
    if module and keep:
#        print "keeping", module.__name__
        node = ModuleTreeNode(module)
        built_nodes[module] = node
        realNode = create_node_fn(*(node,)+create_node_args)
        node.realNode = realNode

        # Split into parent nodes.
        parts = string.split(module.__name__, '.')
        if parts[-1][:8]=='__init__': parts = parts[:-1]
        parent = string.join(parts[:-1], '.')
        parentNode = rootNode
        if parent:
            parentModule = sys.modules[parent]
            BuildModule(parentModule, built_nodes, rootNode, create_node_fn, create_node_args)
            if parentModule in built_nodes:
                parentNode = built_nodes[parentModule].realNode
        node.Attach(parentNode)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def test(serverName):
    if string.lower(serverName)==string.lower(win32api.GetComputerName()):
        print "You must specify a remote server name, not the local machine!"
        return

    # Hack to overcome a DCOM limitation.  As the Python.Interpreter object
    # is probably installed locally as an InProc object, DCOM seems to ignore
    # all settings, and use the local object.
    clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER
    ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx)
    ob.Exec("import win32api")
    actualName = ob.Eval("win32api.GetComputerName()")
    if string.lower(serverName) != string.lower(actualName):
        print "Error: The object created on server '%s' reported its name as '%s'" % (serverName, actualName)
    else:
        print "Object created and tested OK on server '%s'" % serverName
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args ):
    if module:
        keep = module.__name__
        keep = keep and (built_nodes.get(module) is None)
        if keep and hasattr(module, '__file__'):
            keep = string.lower(os.path.splitext(module.__file__)[1]) not in [".pyd", ".dll"]
#               keep = keep and module.__name__=='__main__'
    if module and keep:
#        print "keeping", module.__name__
        node = ModuleTreeNode(module)
        built_nodes[module] = node
        realNode = create_node_fn(*(node,)+create_node_args)
        node.realNode = realNode

        # Split into parent nodes.
        parts = string.split(module.__name__, '.')
        if parts[-1][:8]=='__init__': parts = parts[:-1]
        parent = string.join(parts[:-1], '.')
        parentNode = rootNode
        if parent:
            parentModule = sys.modules[parent]
            BuildModule(parentModule, built_nodes, rootNode, create_node_fn, create_node_args)
            if parentModule in built_nodes:
                parentNode = built_nodes[parentModule].realNode
        node.Attach(parentNode)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def test(serverName):
    if string.lower(serverName)==string.lower(win32api.GetComputerName()):
        print("You must specify a remote server name, not the local machine!")
        return

    # Hack to overcome a DCOM limitation.  As the Python.Interpreter object
    # is probably installed locally as an InProc object, DCOM seems to ignore
    # all settings, and use the local object.
    clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER
    ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx)
    ob.Exec("import win32api")
    actualName = ob.Eval("win32api.GetComputerName()")
    if string.lower(serverName) != string.lower(actualName):
        print("Error: The object created on server '%s' reported its name as '%s'" % (serverName, actualName))
    else:
        print("Object created and tested OK on server '%s'" % serverName)
项目:vmmenu    作者:piggyking    | 项目源码 | 文件源码
def __init__(self, screen, buttonlist, compact = 0):
        self.list = []
        self.hotkeys = {}
        self.item = 0
        Grid.__init__(self, len(buttonlist), 1)
        for blist in buttonlist:
            if (type(blist) == types.StringType):
                title = blist
                value = string.lower(blist)
            elif len(blist) == 2:
                (title, value) = blist
            else:
                (title, value, hotkey) = blist
                self.hotkeys[hotkey] = value

            if compact:
                b = CompactButton(title)
            else:
                b = Button(title)
            self.list.append((b, value))
            self.setField(b, self.item, 0, (1, 0, 1, 0))
            self.item = self.item + 1
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def registerService(self, info, ttl=_DNS_TTL):
        """Registers service information to the network with a default TTL
        of 60 seconds.  Zeroconf will then respond to requests for
        information for that service.  The name of the service may be
        changed if needed to make it unique on the network."""
        self.checkService(info)
        self.services[info.name.lower()] = info
        now = currentTimeMillis()
        nextTime = now
        i = 0
        while i < 3:
            if now < nextTime:
                self.wait(nextTime - now)
                now = currentTimeMillis()
                continue
            out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
            out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, ttl, info.name), 0)
            out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, ttl, info.priority, info.weight, info.port, info.server), 0)
            out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0)
            if info.address:
                out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, ttl, info.address), 0)
            self.send(out)
            i += 1
            nextTime += _REGISTER_TIME
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def unregisterService(self, info):
        """Unregister a service."""
        try:
            del(self.services[info.name.lower()])
        except Exception:
            pass
        now = currentTimeMillis()
        nextTime = now
        i = 0
        while i < 3:
            if now < nextTime:
                self.wait(nextTime - now)
                now = currentTimeMillis()
                continue
            out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
            out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)
            out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, info.priority, info.weight, info.port, info.name), 0)
            out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
            if info.address:
                out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, info.address), 0)
            self.send(out)
            i += 1
            nextTime += _UNREGISTER_TIME
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:IMAPmailbox    作者:IMAPMailbox    | 项目源码 | 文件源码
def readOptlist(self, optlist):
      for o, a in optlist:
        o = o[2:] # strip the leading --

        if o in configOptions:
          val = getattr(self, o)
          # check to see if the current/default value is a boolean. If so,
          # then the value is true if specified as a flag; otherwise, convert
          # the option value to a bool.
          if val.__class__ == bool:
            if (a == None or len(a) == 0) :
              val = True
            else:
              val = (a.strip().lower() == "true")
          else: 
            val = a
          setattr(self, o, val)

    # ---------------------
        # usage text for help
    # ---------------------
项目:IMAPmailbox    作者:IMAPMailbox    | 项目源码 | 文件源码
def readOptlist(self, optlist):
      for o, a in optlist:
        o = o[2:] # strip the leading --

        if o in configOptions:
          val = getattr(self, o)
          # check to see if the current/default value is a boolean. If so,
          # then the value is true if specified as a flag; otherwise, convert
          # the option value to a bool.
          if val.__class__ == bool:
            if (a == None or len(a) == 0) :
              val = True
            else:
              val = (a.strip().lower() == "true")
          else: 
            val = a
          setattr(self, o, val)

    # ---------------------
        # usage text for help
    # ---------------------
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:maestro    作者:InWorldz    | 项目源码 | 文件源码
def execute(self):
        # ReconfigureTasklet
        # {
        #    "target": "All", "AllRegions", "Region", "Services"
        #    "regionId": "[uuid of region]"
        # }
        target = string.lower(self.args['target'])

        host = self.session.api.RegionHost.get_all()[0]

        regions = self.session.api.RegionHost.get_Regions(host)

        if target == "all" or target == "services":
            self.session.api.RegionHost.ReconfigureGridServices(host)

        if target == "all" or target == "allregions":
            for region in regions:
                self.session.api.Region.Reconfigure(region)

        elif target == "region":
            region = self.args['regionId']
            self.session.api.Region.Reconfigure(region)
项目:maestro    作者:InWorldz    | 项目源码 | 文件源码
def execute(self):
        # BackupTasklet
        # {
        #    "type": "full" or "singleRegion"
        #    "regionId": "[region uuid]"
        # }

        host = self.session.api.RegionHost.get_all()[0]
        regions = self.session.api.RegionHost.get_Regions(host)

        if string.lower(self.args['type']) == 'full':
            #perform a backup on all regions that are running
            for region in regions:
                self.backupRegion(region)
        else:
            self.backupRegion(self.args['regionId'])
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def strtobool (val):
    """Convert a string representation of truth to true (1) or false (0).

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = string.lower(val)
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError, "invalid truth value %r" % (val,)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def getinnerframes(tb, context=1):
    """Get a list of records for a traceback's frame and all lower frames.

    Each record contains a frame object, filename, line number, function
    name, a list of lines of context, and index within the context."""
    framelist = []
    while tb:
        framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
        tb = tb.tb_next
    return framelist
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def interact(self):
        self.output.write('\n')
        while True:
            try:
                request = self.getline('help> ')
                if not request: break
            except (KeyboardInterrupt, EOFError):
                break
            request = strip(replace(request, '"', '', "'", ''))
            if lower(request) in ('q', 'quit'): break
            self.help(request)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def run(self, callback, key=None, completer=None, onerror=None):
        if key: key = lower(key)
        self.quit = False
        seen = {}

        for modname in sys.builtin_module_names:
            if modname != '__main__':
                seen[modname] = 1
                if key is None:
                    callback(None, modname, '')
                else:
                    desc = split(__import__(modname).__doc__ or '', '\n')[0]
                    if find(lower(modname + ' - ' + desc), key) >= 0:
                        callback(None, modname, desc)

        for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
            if self.quit:
                break
            if key is None:
                callback(None, modname, '')
            else:
                loader = importer.find_module(modname)
                if hasattr(loader,'get_source'):
                    import StringIO
                    desc = source_synopsis(
                        StringIO.StringIO(loader.get_source(modname))
                    ) or ''
                    if hasattr(loader,'get_filename'):
                        path = loader.get_filename(modname)
                    else:
                        path = None
                else:
                    module = loader.load_module(modname)
                    desc = (module.__doc__ or '').splitlines()[0]
                    path = getattr(module,'__file__',None)
                if find(lower(modname + ' - ' + desc), key) >= 0:
                    callback(path, modname, desc)

        if completer:
            completer()
项目: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 __GetLocalViews(self):
        """
        Return a list with all local view.
        """

        import socket

        myClearCaseCommand = 'cleartool lsview'
        myHostName = string.lower(socket.gethostname())

        myListLocalView = []

        (mystdIn, myStdOut) = popen2.popen2(myClearCaseCommand)
        for myLine in mystdIn:
            myLowerLine = string.lower(myLine)
            myStartHostName = string.find(myLowerLine, myHostName)

            if myStartHostName != -1:
                myLocalView = myLine[2:myStartHostName-2]
                myListLocalView.append(string.strip(myLocalView))

        self.__StartViews(myListLocalView)

        return myListLocalView

        return
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def main():

    # if parameters are wrong, exit with error
    if len(sys.argv) < 5:

        print '\nUsage:'
        print 'python regexplace.py dirname files-regexp search-regexp replace-string'

        sys.exit(1)

    # ask user for simulated execution or real substitution
    print '\nyou are replacing %s with %s in %s' %(sys.argv[3], sys.argv[4], sys.argv[2])
    question1 = raw_input('continue with real substitution (y/N) ? ')
    question1 = string.lower(question1)

    # if user selected real substitution, ask user if execution must be step by step
    if question1=='y':
        question2 = raw_input('\nsubstitute step by step (Y/n) ? ')
        question2 = string.lower(question2)

    # make the file list
    fileslist = make_files_list(sys.argv[1], sys.argv[2])

    # if real substitution
    if question1=='y':

        # if step by step
        if question2!='n':
            replace_in_files(fileslist, sys.argv[3], sys.argv[4], 0, 1)

        # if not step by step
        else:
            replace_in_files(fileslist, sys.argv[3], sys.argv[4], 0, 0)        

    # if simulated execution
    else:
        replace_in_files(fileslist, sys.argv[3], sys.argv[4], 1, 0)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def generateOTP(self, seed, passwd, sequence):
        """Return a 64 bit OTP based on inputs
        Run through makeReadable to get a 6 word pass-phrase"""
        seed = string.lower(seed)
        otp = self.hashUpdate(seed + passwd)
        for a in xrange(sequence):
            otp = self.hashUpdate(otp)
        return otp
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def getGroupConversation(self, name, hide=0):
        name=string.lower(name)
        return self.chat.getGroupConversation(self.chat.getGroup(name, self),
                                              stayHidden=hide)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_RPL_ENDOFNAMES(self,prefix,params):
        group=params[1][1:]
        self.getGroupConversation(group).setGroupMembers(self._namreplies[string.lower(group)])
        del self._namreplies[string.lower(group)]
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_JOIN(self,prefix,params):
        nickname=string.split(prefix,"!")[0]
        group=string.lower(params[0][1:])
        if nickname!=self.nickname:
            try:
                self._ingroups[nickname].append(group)
            except:
                self._ingroups[nickname]=[group]
            self.getGroupConversation(group).memberJoined(nickname)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def tabComplete(self, word):
        """InputOutputWindow calls me when tab is pressed."""
        if not word:
            return []
        potentialMatches = []
        for nick in self.members:
            if string.lower(nick[:len(word)]) == string.lower(word):
                potentialMatches.append(nick + ": ") #colon is a nick-specific thing
        return potentialMatches

    # Internal
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def refreshMemberList(self):
        pl = self.xml.get_widget("ParticipantList")
        pl.freeze()
        pl.clear()
        self.members.sort(lambda x,y: cmp(string.lower(x), string.lower(y)))
        for member in self.members:
            pl.append([member])
        pl.thaw()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_KICK(self, prefix, params):
        """Kicked?  Who?  Not me, I hope.
        """
        kicker = string.split(prefix,'!')[0]
        channel = params[0]
        kicked = params[1]
        message = params[-1]
        if string.lower(kicked) == string.lower(self.nickname):
            # Yikes!
            self.kickedFrom(channel, kicker, message)
        else:
            self.userKicked(kicked, channel, kicker, message)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def unroast(pw):
    roaststring="Tic/Toc"
    pw=string.lower(pw[2:])
    r=""
    count=0
    hex=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
    while pw:
        st,pw=pw[:2],pw[2:]
        value=(16*hex.index(st[0]))+hex.index(st[1])
        xor=ord(roaststring[count])
        count=(count+1)%len(roaststring)
        r=r+chr(value^xor)
    return r
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def roast(pw):
    # contributed by jemfinch on #python
    key="Tic/Toc"
    ro="0x"
    i=0
    ascii=map(ord,pw)
    for c in ascii:
        ro=ro+'%02x'%(c^ord(key[i%len(key)]))
        i=i+1
    return string.lower(ro)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _handleHeader(self, key, value):
        self.numHeaders = self.numHeaders + 1
        self.assertEquals(self.expectedHeaders[string.lower(key)], value)