Python types.UnicodeType() Examples

The following are code examples for showing how to use types.UnicodeType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_StringIO.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_unicode(self):

        if not test_support.have_unicode: return

        # The StringIO module also supports concatenating Unicode
        # snippets to larger Unicode strings. This is tested by this
        # method. Note that cStringIO does not support this extension.

        f = self.MODULE.StringIO()
        f.write(self._line[:6])
        f.seek(3)
        f.write(unicode(self._line[20:26]))
        f.write(unicode(self._line[52]))
        s = f.getvalue()
        self.assertEqual(s, unicode('abcuvwxyz!'))
        self.assertEqual(type(s), types.UnicodeType) 
Example 2
Project: pyblish-win   Author: pyblish   File: PyShell.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def runsource(self, source):
        "Extend base class method: Stuff the source in the line cache first"
        filename = self.stuffsource(source)
        self.more = 0
        self.save_warnings_filters = warnings.filters[:]
        warnings.filterwarnings(action="error", category=SyntaxWarning)
        if isinstance(source, types.UnicodeType):
            from idlelib import IOBinding
            try:
                source = source.encode(IOBinding.encoding)
            except UnicodeError:
                self.tkconsole.resetoutput()
                self.write("Unsupported characters in input\n")
                return
        try:
            # InteractiveInterpreter.runsource() calls its runcode() method,
            # which is overridden (see below)
            return InteractiveInterpreter.runsource(self, source, filename)
        finally:
            if self.save_warnings_filters is not None:
                warnings.filters[:] = self.save_warnings_filters
                self.save_warnings_filters = None 
Example 3
Project: core   Author: lifemapper   File: lmobj.py    GNU General Public License v3.0 6 votes vote down vote up
def _setEPSG(self, epsg=None):
        if epsg == None:
            self._epsg = None
        else:
            if isinstance(epsg, (StringType, UnicodeType)): 
                try:
                    epsg = int(epsg)
                    self._epsg = epsg
                except:
                    raise LMError('Invalid epsg code {}'.format(epsg))
            elif isinstance(epsg, IntType):
                self._epsg = epsg
            elif isinstance(epsg, ListType) or isinstance(epsg, TupleType):
                epsgcodes = set(epsg).discard(None)
                if len(epsgcodes) == 1:
                    self._epsg = epsgcodes[0]
                else:
                    raise LMError('LMSpatialObject may only contain a single EPSG code'
                                      .format(epsgcodes))
            else:
                raise LMError('Invalid EPSG code {} type {}'.format(epsg, type(epsg))) 
Example 4
Project: jawfish   Author: war-and-code   File: urllib2.py    MIT License 6 votes vote down vote up
def open(self, fullurl, data=None):
        # accept a URL or a Request object
        if isinstance(fullurl, (types.StringType, types.UnicodeType)):
            req = Request(fullurl, data)
        else:
            req = fullurl
            if data is not None:
                req.add_data(data)
        assert isinstance(req, Request) # really only care about interface

        result = self._call_chain(self.handle_open, 'default',
                                  'default_open', req)
        if result:
            return result

        type_ = req.get_type()
        result = self._call_chain(self.handle_open, type_, type_ + \
                                  '_open', req)
        if result:
            return result

        return self._call_chain(self.handle_open, 'unknown',
                                'unknown_open', req) 
Example 5
Project: pyomni   Author: taxpon   File: VersionHandler.py    MIT License 6 votes vote down vote up
def revertToVersion(self, oldVersion):
        """
        Revert this VCR to the given version.
        Beware: All versions succeeding the given version are made unavailable.
        
        @param oldVersion: URL-path of a previous version of this VCR.
        """
        ## send an update request
        assert isinstance(oldVersion, types.StringType) or isinstance(oldVersion, types.UnicodeType)
        response = self.connection._request(Constants.METHOD_UPDATE, self.path,
                        _createUpdateBody(oldVersion), {})
        return response


    # the following is not needed when using auto-versioning
    
    # warning: not tested yet 
Example 6
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 6 votes vote down vote up
def addResource(self, name, content=None, properties=None, lockToken=None):
        """
        Create a new empty WebDAV resource contained in this collection with the given
        properties.
        
        @param name: leaf name of the new resource    
        @param content: None or initial binary content of resource
        @param properties: name/value-map containing properties
        @param lockToken: None or token returned by last lock operation
        @type  lockToken: L{LockToken}
        """
        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        if self.validateResourceNames:
            validateResourceName(name) # check for invalid characters        
        resource_ = ResourceStorer(self.url + name, self.connection, self.validateResourceNames)
        resource_.uploadContent(content, lockToken)
        if properties:
            resource_.writeProperties(properties, lockToken)
        return resource_ 
Example 7
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 6 votes vote down vote up
def deleteResource(self, name, lockToken=None):
        """
        Delete a collection which is contained within this collection
        
        @param name: leaf name of a contained collection resource
        @param lockToken: None or token returned by last lock operation
        @type  lockToken: L{LockToken}
        """
        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        header = {}
        if lockToken:
            header = lockToken.toHeader()
        if self.validateResourceNames:
            validateResourceName(name)
        response = self.connection.delete(self.path + name, header)
        if response.status == Constants.CODE_MULTISTATUS and response.msr.errorCount > 0:
            raise WebdavError("Request failed: %s" % response.msr.reason, response.msr.code) 
Example 8
Project: ironpython2   Author: IronLanguages   File: test_StringIO.py    Apache License 2.0 6 votes vote down vote up
def test_unicode(self):

        if not test_support.have_unicode: return

        # The StringIO module also supports concatenating Unicode
        # snippets to larger Unicode strings. This is tested by this
        # method. Note that cStringIO does not support this extension.

        f = self.MODULE.StringIO()
        f.write(self._line[:6])
        f.seek(3)
        f.write(unicode(self._line[20:26]))
        f.write(unicode(self._line[52]))
        s = f.getvalue()
        self.assertEqual(s, unicode('abcuvwxyz!'))
        self.assertEqual(type(s), types.UnicodeType) 
Example 9
Project: appsdk-python   Author: elves-project   File: log4py.py    Apache License 2.0 6 votes vote down vote up
def fmtstr(self, *fmt):  
        str = ''  
        encoding = 'utf8'#缺省utf8编码  
        for i in fmt:  
            if not type(i) in [types.UnicodeType, types.StringTypes, types.StringType]:  
                s= repr(i)  
            else:  
                s = i  
            if type(s) == type(u''):  
                str += s.encode(encoding)  
            else:  
                str += s  
            str += '.'  
        #str += '/n'  
        #print 'fmtstr:'+str  
        return str 
Example 10
Project: xuemc   Author: skycucumber   File: Utility.py    GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, sw, message=None):
        '''Initialize.
           sw -- SoapWriter
        '''
        self._indx = 0
        MessageInterface.__init__(self, sw)
        Base.__init__(self)
        self._dom = DOM
        self.node = None
        if type(message) in (types.StringType, types.UnicodeType):
            self.loadFromString(message)
        elif isinstance(message, ElementProxy):
            self.node = message._getNode()
        else:
            self.node = message
        self.processorNss = self.standard_ns.copy()
        self.processorNss.update(self.reserved_ns) 
Example 11
Project: oss-ftp   Author: aliyun   File: test_StringIO.py    MIT License 6 votes vote down vote up
def test_unicode(self):

        if not test_support.have_unicode: return

        # The StringIO module also supports concatenating Unicode
        # snippets to larger Unicode strings. This is tested by this
        # method. Note that cStringIO does not support this extension.

        f = self.MODULE.StringIO()
        f.write(self._line[:6])
        f.seek(3)
        f.write(unicode(self._line[20:26]))
        f.write(unicode(self._line[52]))
        s = f.getvalue()
        self.assertEqual(s, unicode('abcuvwxyz!'))
        self.assertEqual(type(s), types.UnicodeType) 
Example 12
Project: oss-ftp   Author: aliyun   File: PyShell.py    MIT License 6 votes vote down vote up
def runsource(self, source):
        "Extend base class method: Stuff the source in the line cache first"
        filename = self.stuffsource(source)
        self.more = 0
        self.save_warnings_filters = warnings.filters[:]
        warnings.filterwarnings(action="error", category=SyntaxWarning)
        if isinstance(source, types.UnicodeType):
            from idlelib import IOBinding
            try:
                source = source.encode(IOBinding.encoding)
            except UnicodeError:
                self.tkconsole.resetoutput()
                self.write("Unsupported characters in input\n")
                return
        try:
            # InteractiveInterpreter.runsource() calls its runcode() method,
            # which is overridden (see below)
            return InteractiveInterpreter.runsource(self, source, filename)
        finally:
            if self.save_warnings_filters is not None:
                warnings.filters[:] = self.save_warnings_filters
                self.save_warnings_filters = None 
Example 13
Project: ndb-py   Author: node-db   File: node_script.py    Apache License 2.0 6 votes vote down vote up
def run(self, node, script):
        if type(node) == types.StringType:
            node = ndb.read(node)
        
        query_list = []
        if type(script) == types.StringType or type(script) == types.UnicodeType:
            try:
                query_list = [line for line in open(script, 'r').readlines()]
            except:
                pass
        if type(script) == types.ListType:
            query_list = script
            
        for query in query_list:
            node = ndb.execute(node, query)
            
        return node 
Example 14
Project: Safejumper-for-Desktop   Author: proxysh   File: microdom.py    GNU General Public License v2.0 6 votes vote down vote up
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
                 nsprefixes={}, namespace=''):
        if self.raw:
            val = self.nodeValue
            if not isinstance(val, StringTypes):
                val = str(self.nodeValue)
        else:
            v = self.nodeValue
            if not isinstance(v, StringTypes):
                v = str(v)
            if strip:
                v = ' '.join(v.split())
            val = escape(v)
        if isinstance(val, UnicodeType):
            val = val.encode('utf8')
        stream.write(val) 
Example 15
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 16
Project: pyblish-win   Author: pyblish   File: test_optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def assertHelpEquals(self, expected_output):
        if type(expected_output) is types.UnicodeType:
            encoding = self.parser._get_encoding(sys.stdout)
            expected_output = expected_output.encode(encoding, "replace")

        save_argv = sys.argv[:]
        try:
            # Make optparse believe bar.py is being executed.
            sys.argv[0] = os.path.join("foo", "bar.py")
            self.assertOutput(["-h"], expected_output)
        finally:
            sys.argv[:] = save_argv 
Example 17
Project: core   Author: lifemapper   File: datalocator.py    GNU General Public License v3.0 5 votes vote down vote up
def _getGETQuery(self, urlprefix, paramTpls):
        """
        Method to construct a GET query from a URL endpoint and a list of  
        of key-value tuples. URL endpoint concludes in either a '?' or a key/value 
        pair (i.e. id=25)
        @note: using list of tuples to ensure that the order of the parameters
               is always the same so we can string compare GET Queries
        """
        kvSep = '&'
        paramsSep = '?'
         
        pairs = []
        for key, val in paramTpls:
            if isinstance(val, (StringType, UnicodeType)):
                val = val.replace(' ', '%20')
            pairs.append('%s=%s' % (key, val))
         
        # Don't end in key/value pair separator
        if urlprefix.endswith(paramsSep) or urlprefix.endswith('&') :
            raise LMError(['Improperly formatted URL prefix %s' % urlprefix])
        # If url/key-value-pair separator isn't present, append it
        elif urlprefix.find(paramsSep) == -1:
            urlprefix = urlprefix + '?'
        # > one key/value pair on the urlprefix, add separator before more pairs
        elif not urlprefix.endswith('?') and pairs:
            urlprefix = urlprefix + kvSep
         
        return urlprefix + kvSep.join(pairs)

    # ............................................... 
Example 18
Project: core   Author: lifemapper   File: jsonTree.py    GNU General Public License v3.0 5 votes vote down vote up
def addValue(self, name, value):
      """
      @summary: Adds a name value pair to an object
      @param name: The attribute name
      @param value: The attribute value
      """
      if not isinstance(value, UnicodeType):
         value = unicode(value, ENCODING, errors='ignore')
      self.values.append((name, value.encode(ENCODING)))
      
   # .................................. 
Example 19
Project: core   Author: lifemapper   File: jsonTree.py    GNU General Public License v3.0 5 votes vote down vote up
def addValue(self, value):
      """
      @summary: Adds a value to the array
      """
      if not isinstance(value, UnicodeType):
         value = unicode(value, ENCODING, errors='ignore')
      self.values.append(value.encode(ENCODING))
      
   # .................................. 
Example 20
Project: core   Author: lifemapper   File: createshape.py    GNU General Public License v3.0 5 votes vote down vote up
def _handleSpecialFields(self, feat, recDict):
        try:
            # Find or assign a (dataset) unique id for each point
            if self.idField is not None:
                try:
                    ptid = recDict[self.idField]
                except:
                    # Set LM added id field
                    ptid = self._currRecum 
                    feat.SetField(self.idField, ptid)

            # If data has a Url link field
            if self.linkField is not None:
                try:
                    searchid = recDict[self.linkField]
                except:
                    pass
                else:
                    pturl = '{}{}'.format(self.linkUrl, str(searchid))
                    feat.SetField(self.linkField, pturl)
                            
            # If data has a provider field and value to be resolved
            if self.computedProviderField is not None:
                prov = ''
                try:
                    prov = recDict[self.providerKeyField]
                except:
                    pass
                if not (isinstance(prov, StringType) or isinstance(prov, UnicodeType)):
                    prov = ''
                feat.SetField(self.computedProviderField, prov)

        except Exception, e:
            print('Failed to set optional field in rec {}, e = {}'.format(str(recDict), e))
            raise e

    # ............................................... 
Example 21
Project: tintri-python-sdk   Author: Tintri   File: common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _process_result(self, method, url, response, request_class, response_class, query_params, path_params):
        cls = response_class and response_class or request_class
        if cls in [types.StringType, types.UnicodeType]: # if we expect string type result, no need for further processing
            return response.text
        else:
            # prepare context to hold url and data along with method to navigate pages
            context = { 'method': method, 'url': url, 'query_params': query_params, 'response_class': response_class, 'func': self._get_all, 'request_class': request_class, 'path_params': path_params, 'response_data': response.text }
            return self._json_object_to_object(json.loads(response.text), cls, context=context) # first load JSON to a Python list or dict 
Example 22
Project: jawfish   Author: war-and-code   File: urllib2.py    MIT License 5 votes vote down vote up
def add_password(self, realm, uri, user, passwd):
        # uri could be a single URI or a sequence
        if isinstance(uri, (types.StringType, types.UnicodeType)):
            uri = [uri]
        uri = tuple(map(self.reduce_uri, uri))
        if not self.passwd.has_key(realm):
            self.passwd[realm] = {}
        self.passwd[realm][uri] = (user, passwd) 
Example 23
Project: group-contribution   Author: bdu91   File: molecule.py    MIT License 5 votes vote down vote up
def GetAtomicNum(elem):
        if type(elem) == types.UnicodeType:
            elem = str(elem)
        return Molecule._obElements.GetAtomicNum(elem) 
Example 24
Project: pyomni   Author: taxpon   File: Connection.py    MIT License 5 votes vote down vote up
def _toUtf8(body):
    if not body is None:
        if type(body) == types.UnicodeType:
            body = body.encode('utf-8')
    return body 
Example 25
Project: pyomni   Author: taxpon   File: Connection.py    MIT License 5 votes vote down vote up
def _urlEncode(url):
    if type(url) == types.UnicodeType:
        url = url.encode('utf-8')
    return urllib.quote(url) 
Example 26
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 5 votes vote down vote up
def uploadContent(self, content, lockToken=None, extra_hdrs={}):
        """
        Write binary data to permanent storage.
        
        @param content: containing binary data
        @param lockToken: None or lock token from last lock request
        @type  lockToken: L{LockToken}
        """
        assert not content or isinstance(content, types.UnicodeType) or\
                isinstance(content, types.StringType), "Content is not a string: " + content.__class__.__name__
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        header = {}
        if lockToken:
            header = lockToken.toHeader()
        response = None
        if not content is None:
            header["Content-length"] = str(len(content))
        else:
            header["Content-length"] = "0"
        header.update(extra_hdrs)
        try: 
            response = self.connection.put(self.path, content, extra_hdrs=header)
        finally:
            if response:        
                self.connection.logger.debug(response.read())
                response.close() 
Example 27
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 5 votes vote down vote up
def getResourceStorer(self, name):
        """
        Return a ResourceStorer instance for a child resource (member) of this Collection.
        
        @param name: leaf name of child resource
        @return: L{ResourceStorer} instance
        """
        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
        return ResourceStorer(self.url + name, self.connection, self.validateResourceNames) 
Example 28
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 5 votes vote down vote up
def lockAll(self, owner):
        """
        Locks this collection resource for exclusive write access. This means that for 
        succeeding write operations the returned lock token has to be passed.
        The operation is applied recursively to all contained resources.
        If the methode does not throw an exception then the lock has been granted.
        
        @param owner: describes the lock holder
        @return: Lock token string (automatically generated).
        @rtype: L{LockToken}
        """
        assert isinstance(owner, types.StringType) or isinstance(owner, types.UnicodeType)
        response = self.connection.lock(self.path, owner, depth=Constants.HTTP_HEADER_DEPTH_INFINITY)
        return LockToken(self.url, response.locktoken) 
Example 29
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 5 votes vote down vote up
def __init__(self, url, token):
        assert isinstance(url, types.StringType) or isinstance(url, types.UnicodeType), \
            "Invalid url argument %s" % type(url)
        assert isinstance(token, types.StringType) or isinstance(token, types.UnicodeType), \
            "Invalid lockToken argument %s" % type(token)
        self.url = url
        self.token = token 
Example 30
Project: bilibiliupload   Author: ForgQi   File: compact.py    MIT License 5 votes vote down vote up
def compact_isstr(s):
        return isinstance(s, types.UnicodeType) or isinstance(s, str) 
Example 31
Project: ems   Author: mtils   File: applicationdescriber.py    MIT License 5 votes vote down vote up
def getFriendlyName(identifier,value):
        if isinstance(identifier, types.StringType) or isinstance(identifier, types.UnicodeType):
            stringIdentifier = identifier
        else:
            stringIdentifier = "%s.%s" % (type(identifier).__module__,type(identifier).__name__)
        
        if stringIdentifier == 'application.ui.settings.Connection.Connection':
            if value == 'databasefile':
                return 'Datenbankdatei'
            if value == 'database':
                return 'Datenbank'
            if value == 'driverbackend':
                return 'Treibertyp'
            if value == 'hostname':
                return 'Serveradresse'
            if value == 'authtype':
                return 'Authentifizierung'
            if value == 'username':
                return 'Benutzername'
            if value == 'password':
                return 'Passwort'
            if value == 'odbc-msqlserver':
                return 'SQL Server (ODBC)'
            if value == 'odbc-msqlclient':
                return 'SQL Native CLient (ODBC)'
            if value == 'ntauth':
                return 'NT Authentifizierung'
            if value == 'sql':
                return 'SQL Authentifizierung'
            
        if stringIdentifier == 'db.adapter.backend':
            if value == 'mssql':
                return 'Microsoft SQL Server'
            if value == 'sqlite':
                return 'SQLITE Datenbank'
        return value 
Example 32
Project: hackerdroid   Author: CreatorB   File: androconf.py    MIT License 5 votes vote down vote up
def str2long(s):
    """Convert a string to a long integer."""
    if type(s) not in (types.StringType, types.UnicodeType):
        raise ValueError, 'the input must be a string'

    l = 0L
    for i in s:
        l <<= 8
        l |= ord(i)

    return l 
Example 33
Project: Alexa-Ecovacs   Author: EtienneMD   File: tostring.py    MIT License 5 votes vote down vote up
def escape(text, use_cdata=False):
    """Convert special characters in XML to escape sequences.

    :param string text: The XML text to convert.
    :rtype: Unicode string
    """
    if sys.version_info < (3, 0):
        if type(text) != types.UnicodeType:
            text = unicode(text, 'utf-8', 'ignore')

    escapes = {'&': '&amp;',
               '<': '&lt;',
               '>': '&gt;',
               "'": '&apos;',
               '"': '&quot;'}

    if not use_cdata:
        text = list(text)
        for i, c in enumerate(text):
            text[i] = escapes.get(c, c)
        return ''.join(text)
    else:
        escape_needed = False
        for c in text:
            if c in escapes:
                escape_needed = True
                break
        if escape_needed:
            escaped = map(lambda x : "<![CDATA[%s]]>" % x, text.split("]]>"))
            return "<![CDATA[]]]><![CDATA[]>]]>".join(escaped)
        return text 
Example 34
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: c_spec.py    GNU General Public License v3.0 5 votes vote down vote up
def init_info(self):
        common_base_converter.init_info(self)
        self.type_name = 'unicode'
        self.check_func = 'PyUnicode_Check'
        # This isn't supported by gcc 2.95.3 -- MSVC works fine with it.
        # self.c_type = 'std::wstring'
        # self.to_c_return = "std::wstring(PyUnicode_AS_UNICODE(py_obj))"
        self.c_type = 'Py_UNICODE*'
        self.return_type = self.c_type
        self.to_c_return = "PyUnicode_AS_UNICODE(py_obj)"
        self.matching_types = [types.UnicodeType]
        # self.headers.append('<string>') 
Example 35
Project: TESTGIT   Author: B-ROY   File: androconf.py    Apache License 2.0 5 votes vote down vote up
def str2long(s):
    """Convert a string to a long integer."""
    if type(s) not in (types.StringType, types.UnicodeType):
        raise ValueError, 'the input must be a string'

    l = 0L
    for i in s:
        l <<= 8
        l |= ord(i)

    return l 
Example 36
Project: ironpython2   Author: IronLanguages   File: optparse.py    Apache License 2.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 37
Project: ironpython2   Author: IronLanguages   File: test_optparse.py    Apache License 2.0 5 votes vote down vote up
def assertHelpEquals(self, expected_output):
        if type(expected_output) is types.UnicodeType:
            encoding = self.parser._get_encoding(sys.stdout)
            expected_output = expected_output.encode(encoding, "replace")

        save_argv = sys.argv[:]
        try:
            # Make optparse believe bar.py is being executed.
            sys.argv[0] = os.path.join("foo", "bar.py")
            self.assertOutput(["-h"], expected_output)
        finally:
            sys.argv[:] = save_argv 
Example 38
Project: Android-Malware-Detection   Author: aup8497   File: androconf.py    MIT License 5 votes vote down vote up
def str2long(s):
    """Convert a string to a long integer."""
    if type(s) not in (types.StringType, types.UnicodeType):
        raise ValueError, 'the input must be a string'

    l = 0L
    for i in s:
        l <<= 8
        l |= ord(i)

    return l 
Example 39
Project: IronHydra   Author: microdee   File: optparse.py    MIT License 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 40
Project: Computable   Author: ktraunmueller   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        common_base_converter.init_info(self)
        self.type_name = 'unicode'
        self.check_func = 'PyUnicode_Check'
        # This isn't supported by gcc 2.95.3 -- MSVC works fine with it.
        # self.c_type = 'std::wstring'
        # self.to_c_return = "std::wstring(PyUnicode_AS_UNICODE(py_obj))"
        self.c_type = 'Py_UNICODE*'
        self.return_type = self.c_type
        self.to_c_return = "PyUnicode_AS_UNICODE(py_obj)"
        self.matching_types = [types.UnicodeType]
        # self.headers.append('<string>') 
Example 41
Project: Computable   Author: ktraunmueller   File: optparse.py    MIT License 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 42
Project: oss-ftp   Author: aliyun   File: optparse.py    MIT License 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 43
Project: oss-ftp   Author: aliyun   File: test_optparse.py    MIT License 5 votes vote down vote up
def assertHelpEquals(self, expected_output):
        if type(expected_output) is types.UnicodeType:
            encoding = self.parser._get_encoding(sys.stdout)
            expected_output = expected_output.encode(encoding, "replace")

        save_argv = sys.argv[:]
        try:
            # Make optparse believe bar.py is being executed.
            sys.argv[0] = os.path.join("foo", "bar.py")
            self.assertOutput(["-h"], expected_output)
        finally:
            sys.argv[:] = save_argv 
Example 44
Project: poker   Author: surgebiswas   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        common_base_converter.init_info(self)
        self.type_name = 'unicode'
        self.check_func = 'PyUnicode_Check'
        # This isn't supported by gcc 2.95.3 -- MSVC works fine with it.
        # self.c_type = 'std::wstring'
        # self.to_c_return = "std::wstring(PyUnicode_AS_UNICODE(py_obj))"
        self.c_type = 'Py_UNICODE*'
        self.return_type = self.c_type
        self.to_c_return = "PyUnicode_AS_UNICODE(py_obj)"
        self.matching_types = [types.UnicodeType]
        # self.headers.append('<string>') 
Example 45
Project: iOS-private-api-checker   Author: NetEaseGame   File: mysql_escape_warp.py    GNU General Public License v2.0 5 votes vote down vote up
def mysql_escape(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        newargs = []
        #先转义参数,再执行方法
        for arg in args:
            #字符串,包括中文
            if type(arg) is types.StringType or type(arg) is types.UnicodeType:
                newargs.append(MySQLdb.escape_string(arg))
            
            #字典    
            elif isinstance(arg, dict):
                newargs.append(MySQLdb.escape_dict(arg, {
                                                         types.StringType: _str_escape,
                                                         types.UnicodeType: _str_escape,
                                                         types.IntType: _no_escape,
                                                         types.FloatType: _no_escape
                                                         }))
            #其他类型不转义
            else:
                newargs.append(arg)
                
        newargs = tuple(newargs)
        
        func = f(*newargs, **kwargs)
        
        return func
    return decorated_function 
Example 46
Project: ndb-py   Author: node-db   File: node_update.py    Apache License 2.0 5 votes vote down vote up
def update(self, node, path, value, action):
        if type(value) == types.StringType or type(value) == types.UnicodeType:
            self.update_value = super(NodeUpdate, self)._convert_value_map(value)
        elif type(value) == types.DictionaryType:
            self.update_value = value
            
        self.action = action
        
        super(NodeUpdate, self).locate(node, path);
        
        return node_clean.NodeClean().clean(node) 
Example 47
Project: ndb-py   Author: node-db   File: node_insert.py    Apache License 2.0 5 votes vote down vote up
def insert(self, node, path, value, action):
        if type(value) == types.StringType or type(value) == types.UnicodeType:
            self.insert_value = super(NodeInsert, self)._convert_value_map(value)
        elif type(value) == types.DictionaryType:
            self.insert_value = value
        
        self.action = action
        
        super(NodeInsert, self).locate(node, path, True);
        
        return node_clean.NodeClean().clean(node) 
Example 48
Project: Safejumper-for-Desktop   Author: proxysh   File: microdom.py    GNU General Public License v2.0 5 votes vote down vote up
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
                 nsprefixes={}, namespace=''):
        val=self.data
        if isinstance(val, UnicodeType):
            val=val.encode('utf8')
        stream.write("<!--%s-->" % val) 
Example 49
Project: Safejumper-for-Desktop   Author: proxysh   File: microdom.py    GNU General Public License v2.0 5 votes vote down vote up
def parseString(st, *args, **kw):
    if isinstance(st, UnicodeType):
        # this isn't particularly ideal, but it does work.
        return parse(StringIO(st.encode('UTF-16')), *args, **kw)
    return parse(StringIO(st), *args, **kw) 
Example 50
Project: apk_sdk_analysis   Author: ybdesire   File: androconf.py    GNU General Public License v3.0 5 votes vote down vote up
def str2long(s):
    """Convert a string to a long integer."""
    if type(s) not in (types.StringType, types.UnicodeType):
        raise ValueError, 'the input must be a string'

    l = 0L
    for i in s:
        l <<= 8
        l |= ord(i)

    return l