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 
Example 51
Project: webssh   Author: huashengdun   File: utils.py    MIT License 5 votes vote down vote up
def to_bytes(ustr, encoding='utf-8'):
    if isinstance(ustr, UnicodeType):
        return ustr.encode(encoding)
    return ustr 
Example 52
Project: catalog-service   Author: sassoftware   File: parse.py    Apache License 2.0 5 votes vote down vote up
def ResolveHREF(self, uri, tc, **keywords):
        r = getattr(tc, 'resolver', self.resolver)
        if not r:
            raise EvaluateException('No resolver for "' + uri + '"')
        try:
            if type(uri) == types.UnicodeType: uri = str(uri)
            retval = r(uri, tc, self, **keywords)
        except Exception, e:
            raise EvaluateException('''Can't resolve "''' + uri + '" (' + \
                str(e.__class__) + "): " + str(e)) 
Example 53
Project: eden   Author: facebookexperimental   File: polib.py    GNU General Public License v2.0 5 votes vote down vote up
def __unicode__(self):
        """
        Returns the unicode representation of the file.
        """
        ret = []
        entries = [self.metadata_as_entry()] + [e for e in self if not e.obsolete]
        for entry in entries:
            ret.append(entry.__unicode__(self.wrapwidth))
        for entry in self.obsolete_entries():
            ret.append(entry.__unicode__(self.wrapwidth))
        ret = "\n".join(ret)

        if type(ret) != types.UnicodeType:
            return unicode(ret, self.encoding)  # noqa
        return ret 
Example 54
Project: eden   Author: facebookexperimental   File: polib.py    GNU General Public License v2.0 5 votes vote down vote up
def save(self, fpath=None, repr_method="__str__"):
        """
        Saves the po file to ``fpath``.
        If it is an existing file and no ``fpath`` is provided, then the
        existing file is rewritten with the modified data.

        Keyword arguments:

        ``fpath``
            string, full or relative path to the file.

        ``repr_method``
            string, the method to use for output.
        """
        if self.fpath is None and fpath is None:
            raise IOError("You must provide a file path to save() method")
        contents = getattr(self, repr_method)()
        if fpath is None:
            fpath = self.fpath
        if repr_method == "to_binary":
            fhandle = open(fpath, "wb")
        else:
            fhandle = codecs.open(fpath, "w", self.encoding)
            if type(contents) != types.UnicodeType:
                contents = contents.decode(self.encoding)
        fhandle.write(contents)
        fhandle.close()
        # set the file path if not set
        if self.fpath is None and fpath:
            self.fpath = fpath 
Example 55
Project: eden   Author: facebookexperimental   File: polib.py    GNU General Public License v2.0 5 votes vote down vote up
def _encode(self, mixed):
        """
        Encodes the given ``mixed`` argument with the file encoding if and
        only if it's an unicode string and returns the encoded string.
        """
        if type(mixed) == types.UnicodeType:
            return mixed.encode(self.encoding)
        return mixed


# }}}
# class POFile {{{ 
Example 56
Project: eden   Author: facebookexperimental   File: polib.py    GNU General Public License v2.0 5 votes vote down vote up
def __unicode__(self):
        """
        Returns the unicode representation of the po file.
        """
        ret, headers = "", self.header.split("\n")
        for header in headers:
            if header[:1] in [",", ":"]:
                ret += "#%s\n" % header
            else:
                ret += "# %s\n" % header

        if type(ret) != types.UnicodeType:
            ret = unicode(ret, self.encoding)  # noqa

        return ret + _BaseFile.__unicode__(self) 
Example 57
Project: eden   Author: facebookexperimental   File: polib.py    GNU General Public License v2.0 5 votes vote down vote up
def __unicode__(self, wrapwidth=78):
        """
        Returns the unicode representation of the entry.
        """
        if self.obsolete:
            delflag = "#~ "
        else:
            delflag = ""
        ret = []
        # write the msgctxt if any
        if self.msgctxt is not None:
            ret += self._str_field("msgctxt", delflag, "", self.msgctxt, wrapwidth)
        # write the msgid
        ret += self._str_field("msgid", delflag, "", self.msgid, wrapwidth)
        # write the msgid_plural if any
        if self.msgid_plural:
            ret += self._str_field(
                "msgid_plural", delflag, "", self.msgid_plural, wrapwidth
            )
        if self.msgstr_plural:
            # write the msgstr_plural if any
            msgstrs = self.msgstr_plural
            keys = list(msgstrs)
            keys.sort()
            for index in keys:
                msgstr = msgstrs[index]
                plural_index = "[%s]" % index
                ret += self._str_field(
                    "msgstr", delflag, plural_index, msgstr, wrapwidth
                )
        else:
            # otherwise write the msgstr
            ret += self._str_field("msgstr", delflag, "", self.msgstr, wrapwidth)
        ret.append("")
        ret = "\n".join(ret)

        if type(ret) != types.UnicodeType:
            return unicode(ret, self.encoding)  # noqa
        return ret 
Example 58
Project: pykit   Author: bsc-s2   File: strutil.py    MIT License 5 votes vote down vote up
def filter_invisible_chars(data):
    if type(data) not in (types.StringType, types.UnicodeType):
        return data

    return invisible_chars_re.sub('', data) 
Example 59
Project: hacker-scripts   Author: restran   File: optparse.py    MIT License 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 60
Project: hacker-scripts   Author: restran   File: optparse.py    MIT License 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 61
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 62
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 63
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 64
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 65
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 66
Project: core   Author: lifemapper   File: lmobj.py    GNU General Public License v3.0 4 votes vote down vote up
def _setBBox(self, bbox):
        """
        @summary Sets the bounding box
        @param bbox : geographic boundary in one of 2 formats:
                          - a list or tuple in the format [minX, minY, maxX, maxY]
                          - a string in the format 'minX, minY, maxX, maxY'
        @exception LMError: Thrown when the bounding box has values that are 
                                  out of legal range
        """
        if bbox is None:
            self._bbox = bbox
            
        else:
            try:
                if (isinstance(bbox, (StringType, UnicodeType))):
                    bbox = tuple([float(b) for b in bbox.split(',')])
                elif isinstance(bbox, ListType):
                    bbox = tuple(bbox)
                    
                if (isinstance(bbox, TupleType) and len(bbox) == 4):
                    for v in bbox:
                        if not(isinstance(v, FloatType) or isinstance(v, IntType)):
                            raise LMError('Invalid bounding box type(s) {}'.format(bbox))
                        
                    if LMSpatialObject._checkBounds(bbox):
                        self._bbox = bbox
                    else:
                        # TODO: replace with LMError as soon as bad bboxes are cleared out
                        print('Invalid bounding box boundaries {}'.format(bbox))
                        self._bbox = None
                else:
                    raise LMError('Invalid BBox: require 4-tuple in format (minX, minY, maxX, maxY)')
            except LMError, e:
                print('Invalid bounding box boundaries {}'.format(bbox))
                self._bbox = None
            except Exception, e:
                print('Invalid bounding box boundaries {}'.format(bbox))
                self._bbox = None


# ..............................................................................
    ## Tuple representation of bounding box, i.e. (minX, minY, maxX, maxY) 
Example 67
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 68
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 69
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 70
Project: centreon-discovery   Author: Centreon-Community   File: cursors.py    GNU General Public License v2.0 4 votes vote down vote up
def callproc(self, procname, args=()):

        """Execute stored procedure procname with args
        
        procname -- string, name of procedure to execute on server

        args -- Sequence of parameters to use with procedure

        Returns the original args.

        Compatibility warning: PEP-249 specifies that any modified
        parameters must be returned. This is currently impossible
        as they are only available by storing them in a server
        variable and then retrieved by a query. Since stored
        procedures return zero or more result sets, there is no
        reliable way to get at OUT or INOUT parameters via callproc.
        The server variables are named @_procname_n, where procname
        is the parameter above and n is the position of the parameter
        (from zero). Once all result sets generated by the procedure
        have been fetched, you can issue a SELECT @_procname_0, ...
        query using .execute() to get any OUT or INOUT values.

        Compatibility warning: The act of calling a stored procedure
        itself creates an empty result set. This appears after any
        result sets generated by the procedure. This is non-standard
        behavior with respect to the DB-API. Be sure to use nextset()
        to advance through all result sets; otherwise you may get
        disconnected.
        """

        db = self._get_db()
        charset = db.character_set_name()
        for index, arg in enumerate(args):
            q = "SET @_%s_%d=%s" % (procname, index,
                                         db.literal(arg))
            if isinstance(q, unicode):
                q = q.encode(charset)
            self._query(q)
            self.nextset()
            
        q = "CALL %s(%s)" % (procname,
                             ','.join(['@_%s_%d' % (procname, i)
                                       for i in range(len(args))]))
        if type(q) is UnicodeType:
            q = q.encode(charset)
        self._query(q)
        self._executed = q
        if not self._defer_warnings: self._warning_check()
        return args 
Example 71
Project: oa_qian   Author: sunqb   File: kvform.py    Apache License 2.0 4 votes vote down vote up
def seqToKV(seq, strict=False):
    """Represent a sequence of pairs of strings as newline-terminated
    key:value pairs. The pairs are generated in the order given.

    @param seq: The pairs
    @type seq: [(str, (unicode|str))]

    @return: A string representation of the sequence
    @rtype: str
    """
    def err(msg):
        formatted = 'seqToKV warning: %s: %r' % (msg, seq)
        if strict:
            raise KVFormError(formatted)
        else:
            oidutil.log(formatted)

    lines = []
    for k, v in seq:
        if isinstance(k, types.StringType):
            k = k.decode('UTF8')
        elif not isinstance(k, types.UnicodeType):
            err('Converting key to string: %r' % k)
            k = str(k)

        if '\n' in k:
            raise KVFormError(
                'Invalid input for seqToKV: key contains newline: %r' % (k,))

        if ':' in k:
            raise KVFormError(
                'Invalid input for seqToKV: key contains colon: %r' % (k,))

        if k.strip() != k:
            err('Key has whitespace at beginning or end: %r' % (k,))

        if isinstance(v, types.StringType):
            v = v.decode('UTF8')
        elif not isinstance(v, types.UnicodeType):
            err('Converting value to string: %r' % (v,))
            v = str(v)

        if '\n' in v:
            raise KVFormError(
                'Invalid input for seqToKV: value contains newline: %r' % (v,))

        if v.strip() != v:
            err('Value has whitespace at beginning or end: %r' % (v,))

        lines.append(k + ':' + v + '\n')

    return ''.join(lines).encode('UTF8') 
Example 72
Project: ironpython2   Author: IronLanguages   File: win32clipboardDemo.py    Apache License 2.0 4 votes vote down vote up
def TestText():
    OpenClipboard()
    try:
        text = "Hello from Python"
        text_bytes = str2bytes(text)
        SetClipboardText(text)
        got = GetClipboardData(win32con.CF_TEXT)
        # CF_TEXT always gives us 'bytes' back .
        assert  got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)
    finally:
        CloseClipboard()

    OpenClipboard()
    try:
        # CF_UNICODE text always gives unicode objects back.
        got = GetClipboardData(win32con.CF_UNICODETEXT)
        assert  got == text, "Didnt get the correct result back - '%r'." % (got,)
        assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,)

        # CF_OEMTEXT is a bytes-based format.
        got = GetClipboardData(win32con.CF_OEMTEXT)
        assert  got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)

        # Unicode tests
        EmptyClipboard()
        text = u"Hello from Python unicode"
        text_bytes = str2bytes(text)
        # Now set the Unicode value
        SetClipboardData(win32con.CF_UNICODETEXT, text)
        # Get it in Unicode.
        got = GetClipboardData(win32con.CF_UNICODETEXT)
        assert  got == text, "Didnt get the correct result back - '%r'." % (got,)
        assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,)

        # Close and open the clipboard to ensure auto-conversions take place.
    finally:
        CloseClipboard()

    OpenClipboard()
    try:

        # Make sure I can still get the text as bytes
        got = GetClipboardData(win32con.CF_TEXT)
        assert  got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)
        # Make sure we get back the correct types.
        got = GetClipboardData(win32con.CF_UNICODETEXT)
        assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,)
        got = GetClipboardData(win32con.CF_OEMTEXT)
        assert  got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)
        print "Clipboard text tests worked correctly"
    finally:
        CloseClipboard() 
Example 73
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 74
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 75
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 76
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 77
Project: xuemc   Author: skycucumber   File: kvform.py    GNU General Public License v2.0 4 votes vote down vote up
def seqToKV(seq, strict=False):
    """Represent a sequence of pairs of strings as newline-terminated
    key:value pairs. The pairs are generated in the order given.

    @param seq: The pairs
    @type seq: [(str, (unicode|str))]

    @return: A string representation of the sequence
    @rtype: str
    """
    def err(msg):
        formatted = 'seqToKV warning: %s: %r' % (msg, seq)
        if strict:
            raise KVFormError(formatted)
        else:
            oidutil.log(formatted)

    lines = []
    for k, v in seq:
        if isinstance(k, types.StringType):
            k = k.decode('UTF8')
        elif not isinstance(k, types.UnicodeType):
            err('Converting key to string: %r' % k)
            k = str(k)

        if '\n' in k:
            raise KVFormError(
                'Invalid input for seqToKV: key contains newline: %r' % (k,))

        if ':' in k:
            raise KVFormError(
                'Invalid input for seqToKV: key contains colon: %r' % (k,))

        if k.strip() != k:
            err('Key has whitespace at beginning or end: %r' % (k,))

        if isinstance(v, types.StringType):
            v = v.decode('UTF8')
        elif not isinstance(v, types.UnicodeType):
            err('Converting value to string: %r' % (v,))
            v = str(v)

        if '\n' in v:
            raise KVFormError(
                'Invalid input for seqToKV: value contains newline: %r' % (v,))

        if v.strip() != v:
            err('Value has whitespace at beginning or end: %r' % (v,))

        lines.append(k + ':' + v + '\n')

    return ''.join(lines).encode('UTF8') 
Example 78
Project: chihu   Author: yelongyu   File: cursors.py    GNU General Public License v3.0 4 votes vote down vote up
def callproc(self, procname, args=()):

        """Execute stored procedure procname with args
        
        procname -- string, name of procedure to execute on server

        args -- Sequence of parameters to use with procedure

        Returns the original args.

        Compatibility warning: PEP-249 specifies that any modified
        parameters must be returned. This is currently impossible
        as they are only available by storing them in a server
        variable and then retrieved by a query. Since stored
        procedures return zero or more result sets, there is no
        reliable way to get at OUT or INOUT parameters via callproc.
        The server variables are named @_procname_n, where procname
        is the parameter above and n is the position of the parameter
        (from zero). Once all result sets generated by the procedure
        have been fetched, you can issue a SELECT @_procname_0, ...
        query using .execute() to get any OUT or INOUT values.

        Compatibility warning: The act of calling a stored procedure
        itself creates an empty result set. This appears after any
        result sets generated by the procedure. This is non-standard
        behavior with respect to the DB-API. Be sure to use nextset()
        to advance through all result sets; otherwise you may get
        disconnected.
        """

        db = self._get_db()
        for index, arg in enumerate(args):
            q = "SET @_%s_%d=%s" % (procname, index,
                                         db.literal(arg))
            if isinstance(q, unicode):
                q = q.encode(db.unicode_literal.charset)
            self._query(q)
            self.nextset()
            
        q = "CALL %s(%s)" % (procname,
                             ','.join(['@_%s_%d' % (procname, i)
                                       for i in range(len(args))]))
        if type(q) is UnicodeType:
            q = q.encode(db.unicode_literal.charset)
        self._query(q)
        self._executed = q
        if not self._defer_warnings: self._warning_check()
        return args 
Example 79
Project: ndb-py   Author: node-db   File: node_writer.py    Apache License 2.0 4 votes vote down vote up
def __print_node(self, indent, node_name, node, indent_flag):
        '''
        #将节点数据内容输出为ndb格式的字符串
        
        @param indent: 缩进量
        @param node_name: 根节点名称
        @param node: 节点数据
        @param indent_flag: 缩进标识符, 默认\t 
        
        @return: 节点数据字符串
        '''
        if type(node) != types.DictionaryType:
            raise 'Node is NOT DictionaryType'
        
        result = []
        
        next_indent = indent + 1;
        
        if node_name != None and node_name != '':
            result.append(indent_flag * indent + node_name + '{\n')
        else:
            next_indent = indent
            
        for key in node.keys():
            value = node[key]
            if type(value) == types.ListType and len(value) != 0:
                for item in value:
                    if type(item) == types.DictionaryType:
                        result.append(self.__print_node(next_indent, key, item, indent_flag))
                    if type(item) == types.StringType:
                        result.append(indent_flag * next_indent + '{0}:{1}\n'.format(key, item))
                        
            if type(value) == types.DictionaryType and len(value.keys()) != 0:
                result.append(self.__print_node(next_indent, str(key), value, indent_flag))
                
            if (type(value) == types.StringType or type(value) == types.UnicodeType) and value != '':
                result.append(indent_flag * next_indent + '{0}:{1}\n'.format(key, value))
                
            if type(value) == types.IntType or type(value) == types.LongType or type(value) == types.BooleanType:
                result.append(indent_flag * next_indent + '{0}:{1}\n'.format(key, str(value)))
        
        if node_name != None and node_name != '':
            result.append(indent_flag * indent + indent_flag * indent + '}\n')
            
        return ''.join(result) 
Example 80
Project: ndb-py   Author: node-db   File: node_writer.py    Apache License 2.0 4 votes vote down vote up
def __print_xml(self, indent, node_name, node, indent_flag):
        '''
        #将节点数据内容输出为XML格式的字符串
        
        @param node_name: 根节点名称
        @param node: 节点数据
        
        @return: 节点数据XML字符串
        '''
        result = []
    
        next_indent = indent + 1;
        
        if node_name != None:
            node_name = str(node_name).split()
            
        if node_name != None and node_name != '':
            result.append(indent_flag * indent + '<{0}>\n'.format(node_name))
        else:
            next_indent = indent
            
        for key in node.keys():
            value = node[key]
            if type(value) == types.ListType and len(value) != 0:
                for item in value:
                    if type(item) == types.DictionaryType:
                        result.append(self.__print_xml(next_indent, key, item, indent_flag))
                    if type(item) == types.StringType:
                        result.append(indent_flag * next_indent + '<{0}>{1}</{0}>\n'.format(key, item))
                        
            if type(value) == types.DictionaryType and len(value.keys()) != 0:
                result.append(self.__print_xml(next_indent, key, value, indent_flag))
                
            if (type(value) == types.StringType or type(value) == types.UnicodeType) and value != '':
                result.append(indent_flag * next_indent + '<{0}>{1}</{0}>\n'.format(key, value))
                
            if type(value) == types.IntType or type(value) == types.LongType or type(value) == types.BooleanType:
                result.append(indent_flag * next_indent + '<{0}>{1}</{0}>\n'.format(key, str(value)))
                
        if node_name != None and node_name != '':   
            result.append('<{0}>\n'.format(node_name))
        
        return ''.join(result)