Python types 模块,NoneType() 实例源码

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

项目:clusterdock    作者:cloudera    | 项目源码 | 文件源码
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in 'encoding'.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    elif not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return ' '.join([smart_str(arg, encoding, strings_only,
                        errors) for arg in s])
            return unicode(s).encode(encoding, errors)
    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self):
        """SecurityOptions()
        Initialize.
        """
        # I don't believe any of these types can ever pose a security hazard,
        # except perhaps "reference"...
        self.allowedTypes = {"None": 1,
                             "bool": 1,
                             "boolean": 1,
                             "string": 1,
                             "str": 1,
                             "int": 1,
                             "float": 1,
                             "datetime": 1,
                             "time": 1,
                             "date": 1,
                             "timedelta": 1,
                             "NoneType": 1}
        if hasattr(types, 'UnicodeType'):
            self.allowedTypes['unicode'] = 1
        self.allowedModules = {}
        self.allowedClasses = {}
项目:pc-ble-driver-py    作者:NordicSemiconductor    | 项目源码 | 文件源码
def ble_gap_sec_params_reply(self, conn_handle, sec_status, sec_params, own_keys, peer_keys):
        assert isinstance(sec_status, BLEGapSecStatus),             'Invalid argument type'
        assert isinstance(sec_params, (BLEGapSecParams, NoneType)), 'Invalid argument type'
        assert isinstance(own_keys,   NoneType),                    'NOT IMPLEMENTED'
        assert isinstance(peer_keys,  NoneType),                    'NOT IMPLEMENTED'

        keyset                      = driver.ble_gap_sec_keyset_t()

        keyset.keys_own.p_enc_key   = driver.ble_gap_enc_key_t()
        keyset.keys_own.p_id_key    = driver.ble_gap_id_key_t()
        keyset.keys_own.p_sign_key  = driver.ble_gap_sign_info_t()
        keyset.keys_own.p_pk        = driver.ble_gap_lesc_p256_pk_t()

        keyset.keys_peer.p_enc_key  = driver.ble_gap_enc_key_t()
        keyset.keys_peer.p_id_key   = driver.ble_gap_id_key_t()
        keyset.keys_peer.p_sign_key = driver.ble_gap_sign_info_t()
        keyset.keys_peer.p_pk       = driver.ble_gap_lesc_p256_pk_t()

        self.__keyset = keyset

        return driver.sd_ble_gap_sec_params_reply(self.rpc_adapter,
                                                  conn_handle,
                                                  sec_status.value,
                                                  sec_params.to_c() if sec_params else None,
                                                  self.__keyset)
项目:odooalipay    作者:Primary-Traxex    | 项目源码 | 文件源码
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):  
    if strings_only and isinstance(s, (types.NoneType, int)):  
        return s  
    if not isinstance(s, basestring):  
        try:  
            return str(s)  
        except UnicodeEncodeError:  
            if isinstance(s, Exception):  
                return ' '.join([smart_str(arg, encoding, strings_only,  
                        errors) for arg in s])  
            return unicode(s).encode(encoding, errors)  
    elif isinstance(s, unicode):  
        return s.encode(encoding, errors)  
    elif s and encoding != 'utf-8':  
        return s.decode('utf-8', errors).encode(encoding, errors)  
    else:  
        return s
项目:pureftp    作者:SRELabs    | 项目源码 | 文件源码
def smart_str(self, s, encoding='utf-8', strings_only=False, errors='strict'):
        if strings_only and isinstance(s, (types.NoneType, int)):
            return s
        if not isinstance(s, basestring):
            try:
                return str(s)
            except UnicodeEncodeError:
                if isinstance(s, Exception):
                    return ' '.join([self.smart_str(arg, encoding, strings_only, errors) for arg in s])
                return unicode(s).encode(encoding, errors)
        elif isinstance(s, unicode):
            return s.encode(encoding, errors)
        elif s and encoding != 'utf-8':
            return s.decode('utf-8', errors).encode(encoding, errors)
        else:
            return s

    # ???????????????????
    # ????????
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def coerce_session_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string "
         "referring to a directory."),
        ('lock_dir', (str, types.NoneType), "lock_dir must be a string referring to a "
         "directory."),
        ('type', (str, types.NoneType), "Session type must be a string."),
        ('cookie_expires', (bool, datetime, timedelta), "Cookie expires was "
         "not a boolean, datetime, or timedelta instance."),
        ('cookie_domain', (str, types.NoneType), "Cookie domain must be a "
         "string."),
        ('id', (str,), "Session id must be a string."),
        ('key', (str,), "Session key must be a string."),
        ('secret', (str, types.NoneType), "Session secret must be a string."),
        ('validate_key', (str, types.NoneType), "Session encrypt_key must be "
         "a string."),
        ('encrypt_key', (str, types.NoneType), "Session validate_key must be "
         "a string."),
        ('secure', (bool, types.NoneType), "Session secure must be a boolean."),
        ('timeout', (int, types.NoneType), "Session timeout must be an "
         "integer."),
        ('auto', (bool, types.NoneType), "Session is created if accessed."),
    ]
    return verify_rules(params, rules)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self):
        """SecurityOptions()
        Initialize.
        """
        # I don't believe any of these types can ever pose a security hazard,
        # except perhaps "reference"...
        self.allowedTypes = {"None": 1,
                             "bool": 1,
                             "boolean": 1,
                             "string": 1,
                             "str": 1,
                             "int": 1,
                             "float": 1,
                             "datetime": 1,
                             "time": 1,
                             "date": 1,
                             "timedelta": 1,
                             "NoneType": 1}
        if hasattr(types, 'UnicodeType'):
            self.allowedTypes['unicode'] = 1
        self.allowedModules = {}
        self.allowedClasses = {}
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def smart_str(self, s, encoding='utf-8', strings_only=False, errors='strict'):
        if strings_only and isinstance(s, (types.NoneType, int)):
            return s
        if not isinstance(s, basestring):
            try:
                return str(s)
            except UnicodeEncodeError:
                if isinstance(s, Exception):
                    return ' '.join([self.smart_str(arg, encoding, strings_only, errors) for arg in s])
                return unicode(s).encode(encoding, errors)
        elif isinstance(s, unicode):
            return s.encode(encoding, errors)
        elif s and encoding != 'utf-8':
            return s.decode('utf-8', errors).encode(encoding, errors)
        else:
            return s

    # ???????????????????
    # ????????
项目:cetusshop    作者:icetusorg    | 项目源码 | 文件源码
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    if not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                return ' '.join([smart_str(arg, encoding, strings_only,errors) for arg in s])
            return unicode(s).encode(encoding, errors)
    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s

# ??
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def to_string(x, quote_string=True):
    """Format value so it can be used for task log detail"""
    if isinstance(x, string_types):
        if quote_string:
            return "'%s'" % x
        else:
            return '%s' % x
    elif isinstance(x, bool):
        return str(x).lower()
    elif isinstance(x, (int, float)):
        return str(x)
    elif isinstance(x, NoneType):
        return 'null'
    elif isinstance(x, dict):
        return to_string(','.join('%s:%s' % (to_string(k, quote_string=False), to_string(v, quote_string=False))
                                  for k, v in iteritems(x)))
    elif isinstance(x, (list, tuple)):
        return to_string(','.join(to_string(i, quote_string=False) for i in x))
    return to_string(str(x))
项目:fluiddb    作者:fluidinfo    | 项目源码 | 文件源码
def checkPayloadFieldType(value, field, strCountsAsUnicode=False):
    if field.mayBeNone and value is None:
        return True
    ft = field.type
    vt = type(value)
    if ft in (bool, int, float, types.NoneType):
        return vt is ft
    elif ft is unicode:
        return (vt is unicode or
                (strCountsAsUnicode and vt is str) or
                (value is None and field.mayBeNone))
    elif ft is list:
        if vt is not list:
            return False
        if field.listType is unicode and strCountsAsUnicode:
            return all([isinstance(x, basestring) for x in value])
        else:
            return all([type(x) is field.listType for x in value])
    return False
项目:dbf    作者:wenzhihong2003    | 项目源码 | 文件源码
def retrieve_logical(bytes, fielddef, *ignore):
    """
    Returns True if bytes is 't', 'T', 'y', or 'Y'
    None if '?'
    False otherwise
    """
    cls = fielddef[CLASS]
    empty = fielddef[EMPTY]
    bytes = bytes.tostring()
    if bytes in 'tTyY':
        return cls(True)
    elif bytes in 'fFnN':
        return cls(False)
    elif bytes in '? ':
        if empty is NoneType:
            return None
        return empty()
    elif LOGICAL_BAD_IS_NONE:
        return None
    else:
        raise BadDataError('Logical field contained %r' % bytes)
    return typ(bytes)
项目:dbf    作者:wenzhihong2003    | 项目源码 | 文件源码
def retrieve_vfp_datetime(bytes, fielddef, *ignore):
    """
    returns the date/time stored in bytes; dates <= 01/01/1981 00:00:00
    may not be accurate;  BC dates are nulled.
    """
    # two four-byte integers store the date and time.
    # millesecords are discarded from time
    if bytes == array('c', '\x00' * 8):
        cls = fielddef[EMPTY]
        if cls is NoneType:
            return None
        return cls()
    cls = fielddef[CLASS]
    time = unpack_long_int(bytes[4:])
    microseconds = (time % 1000) * 1000
    time = time // 1000                      # int(round(time, -3)) // 1000 discard milliseconds
    hours = time // 3600
    mins = time % 3600 // 60
    secs = time % 3600 % 60
    time = datetime.time(hours, mins, secs, microseconds)
    possible = unpack_long_int(bytes[:4])
    possible -= VFPTIME
    possible = max(0, possible)
    date = datetime.date.fromordinal(possible)
    return cls(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond)
项目:dbf    作者:wenzhihong2003    | 项目源码 | 文件源码
def retrieve_vfp_memo(bytes, fielddef, memo, decoder):
    """
    Returns the block of data from a memo file
    """
    if memo is None:
        block = 0
    else:
        block = struct.unpack('<i', bytes)[0]
    if not block:
        cls =  fielddef[EMPTY]
        if cls is NoneType:
            return None
        return cls()
    data = memo.get_memo(block)
    if fielddef[FLAGS] & BINARY:
        return data
    return fielddef[CLASS](decoder(data)[0])
项目:de-visualization-wizard    作者:deleidos    | 项目源码 | 文件源码
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in 'encoding'.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int, float)):
        return s
    if not isinstance(s, six.string_types):
        if six.PY3:
            if isinstance(s, bytes):
                s = six.text_type(s, encoding, errors)
            else:
                s = six.text_type(s)
        else:
            s = six.text_type(bytes(s), encoding, errors)
    return s
项目:amonone    作者:amonapp    | 项目源码 | 文件源码
def smart_str(s, encoding='utf-8', errors='strict', from_encoding='utf-8'):
    if type(s) in (int, long, float, types.NoneType):
        return str(s)
    elif type(s) is str:
        if encoding != from_encoding:
            return s.decode(from_encoding, errors).encode(encoding, errors)
        else:
            return s
    elif type(s) is unicode:
        return s.encode(encoding, errors)
    elif hasattr(s, '__str__'):
        return smart_str(str(s), encoding, errors, from_encoding)
    elif hasattr(s, '__unicode__'):
        return smart_str(unicode(s), encoding, errors, from_encoding)
    else:
        return smart_str(str(s), encoding, errors, from_encoding)
项目:jsondata    作者:ArnoCan    | 项目源码 | 文件源码
def __call__(self, j, x=None):
        """Evaluates the related task for the provided index.

        Args:
            x: Task index.

            j: JSON data the task has to be 
                applied on.

        Returns:
            Returns a tuple of:
                0: len of the job list
                1: list of the execution status for 
                    the tasks

        Raises:
            JSONPatchException:
        """
        if type(x) is NoneType:
            return self.apply(j)
        if self.patch[x](j):
            return 1,[]
        return 1,[0]
项目:pwtools    作者:elcorto    | 项目源码 | 文件源码
def find_sqltype(val):
    """
    Find sqlite data type which matches the type of `val`.

    Parameters
    ----------
    val : any python type

    Returns
    -------
    sqltype : str
        String with sql type which can be used to set up a sqlile table
    """        
    mapping = {\
        types.NoneType:    'NULL',
        types.IntType:     'INTEGER',
        types.LongType:    'INTEGER',
        types.FloatType:   'REAL',  # 'FLOAT' also works
        types.StringTypes: 'TEXT',  # StringType + UnicodeType
        types.BufferType:  'BLOB'}
    for typ in mapping.keys():
        if isinstance(val, typ):
            return mapping[typ]
    raise StandardError("type '%s' unknown, cannot find mapping "
        "to sqlite3 type" %str(type(val)))
项目:hermes    作者:xutaoding    | 项目源码 | 文件源码
def query(self, q_kw=None, fields=None, sort_by=None, use_iterators=True, *args, **kwargs):
        """ Find a set of document with condition
            Sometimes because of memory, cause `MemoryError` exception
         """
        if not isinstance(sort_by, (tuple, types.NoneType)):
            raise TypeError('meth: query, `sort_by` keyword type error')

        if not isinstance(fields, dict):
            raise TypeError('meth: query, `fields` keyword type error')

        self.__connect()

        skip = kwargs.pop('skip', 0)
        limit = kwargs.pop('limit', 0)  # 0 hint to get overall document

        args = (q_kw, ) + args
        kwargs['projection'] = fields
        sort_by = sort_by or [('_id', pymongo.DESCENDING)]

        cursor = self.__collection.find(*args, **kwargs).sort(sort_by)

        if use_iterators:
            return cursor.skip(skip).limit(limit)
        return [doc for doc in cursor]
项目:deb-python-cassandra-driver    作者:openstack    | 项目源码 | 文件源码
def __init__(self):
        self.mapping = {
            float: self.cql_encode_float,
            bytearray: self.cql_encode_bytes,
            str: self.cql_encode_str,
            int: self.cql_encode_object,
            UUID: self.cql_encode_object,
            datetime.datetime: self.cql_encode_datetime,
            datetime.date: self.cql_encode_date,
            datetime.time: self.cql_encode_time,
            Date: self.cql_encode_date_ext,
            Time: self.cql_encode_time,
            dict: self.cql_encode_map_collection,
            OrderedDict: self.cql_encode_map_collection,
            OrderedMap: self.cql_encode_map_collection,
            OrderedMapSerializedKey: self.cql_encode_map_collection,
            list: self.cql_encode_list_collection,
            tuple: self.cql_encode_list_collection,  # TODO: change to tuple in next major
            set: self.cql_encode_set_collection,
            sortedset: self.cql_encode_set_collection,
            frozenset: self.cql_encode_set_collection,
            types.GeneratorType: self.cql_encode_list_collection,
            ValueSequence: self.cql_encode_sequence
        }

        if six.PY2:
            self.mapping.update({
                unicode: self.cql_encode_unicode,
                buffer: self.cql_encode_bytes,
                long: self.cql_encode_object,
                types.NoneType: self.cql_encode_none,
            })
        else:
            self.mapping.update({
                memoryview: self.cql_encode_bytes,
                bytes: self.cql_encode_bytes,
                type(None): self.cql_encode_none,
            })
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def makeObjInsertStrings( obj, tplObjects = None, blnUseParens=True, blnGetAllAttrib=True ):
    # Returns a 3 val tuple, the first two of which are strings which can be dropped into a MySQL Insert statement for (1) column names and (2) values

    if not tplObjects:
        return None, None, None
    if isinstance( obj, tplObjects ):    #find out what got passed - valid objects must be included in tuple tplObjects
        strDblQuote = '"'
        lstCols = list()
        lstVals = list()
        lstExcludedAttrib = list()
        dctObj = vars( obj )
        lstObjVarNames = dctObj.keys()
        if blnGetAllAttrib:
            tplValidTypes = ( types.BooleanType, types.FloatType, types.IntType, types.LongType, types.StringType, types.StringTypes, types.NoneType )
            for varName in lstObjVarNames:
                val = dctObj[ varName ]
                if isinstance( val, tplValidTypes ):
                    lstCols.append( varName )
                    if val or val == 0:
                        lstVals.append( dctObj[ varName ] )
                    else:
                        lstVals.append('')
                else:
                    lstExcludedAttrib.append( varName )
        if blnUseParens:
            strCols = joinListItems( lstCols )
            strVals = joinListItems( lstVals )
        else:
            strCols = joinListItems( lstCols, blnUseParens=False )
            strCols = joinListItems( lstVals, blnUseParens=False )
        strCols = strCols.replace('"', '')
        return strCols, strVals, lstExcludedAttrib
    else:
        print 'No object passed.'
        return None, None, None
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def IsInternetExplorer(name):
    import re
    from types import NoneType
    if type(re.search(r'iexplore.exe$',name)) != NoneType:
        return True
    else:
        return False

# Lets create an instance of ShellWindows Interface
项目:v2ex-tornado-2    作者:coderyy    | 项目源码 | 文件源码
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        types.NoneType,
        int, long,
        datetime.datetime, datetime.date, datetime.time,
        float, Decimal)
    )
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def __init__(self, port,authkey=None,socket=None,alt_keys={},interval=None,
        home=None, proc_name=None, logging=False):
        if (not socket) and (type(port) != int or port < 1):
            raise Exception('client port must be integer >= 1')
        # authkey is used in hmac computation, which doesn't understand unicode
        if authkey and type (authkey) != str:
            raise Exception('authkey must be a regular string')
        Process.__init__(self, self.run, (), logging, proc_name)
        self.socket  = socket
        self.port    = port        # listening port for all connections
        self.fds     = {}
        if type(authkey) not in [str, types.NoneType]:
            raise Exception('authkey must be a regular string or None')
        self.keys = {0: authkey}   # primary authentication key (may be None)
        if alt_keys:
            if type(alt_keys) != dict:
                raise Exception('alt_keys must be a dictionary')
            for k in alt_keys:
                if type(alt_keys[k]) not in [str, types.NoneType]:
                    raise Exception('alt keys must be regular strings or None')
                self.keys[k] = alt_keys[k]
        if type(interval) not in [int, float, types.NoneType]:
            raise Exception(
                'the interval (seconds) must be expressed as in integer, a '
                'float, or None'
            )
        if not home:
            home = ave.config.load_etc()['home']
        self.home           = home
        self.interval       = to_milliseconds(interval)
        self.unpend         = []    # fd's to ignore in pending events handling
        self.rejecting      = False
        self.accepting      = []    # connections
        self.authenticating = {}    # connection -> salt
        self.established    = {}    # connection -> authkey or None
        self.keepwatching   = {}
        self.listener       = None
        self.outgoing       = {}    # connection -> message
        self.buf_sizes      = (1024*16, 1024*16) # setsockopt() parameters
        self.deferred_joins = None
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def __init__(self, port,authkey=None,socket=None,alt_keys={},interval=None,
        home=None, proc_name=None, logging=False):
        if (not socket) and (type(port) != int or port < 1):
            raise Exception('client port must be integer >= 1')
        # authkey is used in hmac computation, which doesn't understand unicode
        if authkey and type (authkey) != str:
            raise Exception('authkey must be a regular string')
        Process.__init__(self, self.run, (), logging, proc_name)
        self.socket  = socket
        self.port    = port        # listening port for all connections
        self.fds     = {}
        if type(authkey) not in [str, types.NoneType]:
            raise Exception('authkey must be a regular string or None')
        self.keys = {0: authkey}   # primary authentication key (may be None)
        if alt_keys:
            if type(alt_keys) != dict:
                raise Exception('alt_keys must be a dictionary')
            for k in alt_keys:
                if type(alt_keys[k]) not in [str, types.NoneType]:
                    raise Exception('alt keys must be regular strings or None')
                self.keys[k] = alt_keys[k]
        if type(interval) not in [int, float, types.NoneType]:
            raise Exception(
                'the interval (seconds) must be expressed as in integer, a '
                'float, or None'
            )
        if not home:
            home = ave.config.load_etc()['home']
        self.home           = home
        self.interval       = to_milliseconds(interval)
        self.unpend         = []    # fd's to ignore in pending events handling
        self.rejecting      = False
        self.accepting      = []    # connections
        self.authenticating = {}    # connection -> salt
        self.established    = {}    # connection -> authkey or None
        self.keepwatching   = {}
        self.listener       = None
        self.outgoing       = {}    # connection -> message
        self.buf_sizes      = (1024*16, 1024*16) # setsockopt() parameters
        self.deferred_joins = None
项目:gcp-census    作者:ocadotechnology    | 项目源码 | 文件源码
def __init__(self, table):
        assert isinstance(table, (dict, NoneType))
        self.table = table
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
def __set__(self, inst, value):
        Target = self.get_target()
        if isinstance(value, dict):
            value = Target(*value)
        elif isinstance(value, (int, long)):
            value = Target(value)
        assert isinstance(value, (Target, NoneType))
        Field.__set__(self, inst, value)
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
def __set__(self, inst, value):
        from ..model import Model
        if not isinstance(value, (Model, NoneType)):
            if isinstance(value, basestring):
                target, value = value.split(',')
            else:
                target, value = value
            Target = Pool().get(target)
            if isinstance(value, dict):
                value = Target(**value)
            else:
                value = Target(value)
        super(Reference, self).__set__(inst, value)
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
def __set__(self, inst, value):
        Target = self.get_target()
        if isinstance(value, dict):
            value = Target(**value)
        elif isinstance(value, (int, long)):
            value = Target(value)
        assert isinstance(value, (Target, NoneType))
        super(Many2One, self).__set__(inst, value)
项目:clyde    作者:laurakah    | 项目源码 | 文件源码
def testExpandMap_appendsThirdDimensionHorizontally_Bug(self):
        horizontal = 1
        vertical = 0
        mObj = gameMap.GameMap()
        mObj.expandMap(1, 1, True, True)
        mObj.expandMap(horizontal, vertical, True, True)
        self.assertEqual(True, type(mObj.getLocation(2, 1)) is types.NoneType)
项目:pc-ble-driver-py    作者:NordicSemiconductor    | 项目源码 | 文件源码
def __init__(self, vs_uuid_base=None, uuid_type=None):
        assert isinstance(vs_uuid_base, (list, NoneType)), 'Invalid argument type'
        assert isinstance(uuid_type, (int, long, NoneType)), 'Invalid argument type'
        if (vs_uuid_base is None) and uuid_type is None:
            self.base   = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
                           0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB]
            self.type   = driver.BLE_UUID_TYPE_BLE

        else:
            self.base   = vs_uuid_base
            self.type   = uuid_type
项目:pc-ble-driver-py    作者:NordicSemiconductor    | 项目源码 | 文件源码
def ble_gap_conn_param_update(self, conn_handle, conn_params):
        assert isinstance(conn_params, (BLEGapConnParams, NoneType)), 'Invalid argument type'
        if conn_params:
            conn_params=conn_params.to_c()
        return driver.sd_ble_gap_conn_param_update(self.rpc_adapter, conn_handle, conn_params)
项目:pc-ble-driver-py    作者:NordicSemiconductor    | 项目源码 | 文件源码
def ble_gap_authenticate(self, conn_handle, sec_params):
        assert isinstance(sec_params, (BLEGapSecParams, NoneType)), 'Invalid argument type'
        return driver.sd_ble_gap_authenticate(self.rpc_adapter,
                                              conn_handle,
                                              sec_params.to_c() if sec_params else None)
项目:pc-ble-driver-py    作者:NordicSemiconductor    | 项目源码 | 文件源码
def ble_gattc_prim_srvc_disc(self, conn_handle, srvc_uuid, start_handle):
        assert isinstance(srvc_uuid, (BLEUUID, NoneType)), 'Invalid argument type'
        return driver.sd_ble_gattc_primary_services_discover(self.rpc_adapter,
                                                             conn_handle,
                                                             start_handle,
                                                             srvc_uuid.to_c() if srvc_uuid else None)
项目:xiaodi    作者:shenaishiren    | 项目源码 | 文件源码
def write_success(self, data=None, finish=True):
        assert isinstance(data, (types.NoneType, dict)), 'data must be NoneType or dict'
        self._async_write(dict((data or {}), **{'status': 'success'}), finish=finish)
项目:py2cpp    作者:mugwort-rc    | 项目源码 | 文件源码
def create(field, node, parent=None):
        item = ASTAttrTreeItem(field, node, parent)
        if isinstance(node, list):
            for child in node:
                item.children.append(ASTTreeItem.create(child, parent=item))
        elif not isinstance(node, (str, int, float, types.NoneType)):
            item.children.append(ASTTreeItem.create(node, parent=item))
        return item
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    )
项目:MusicML    作者:tonyhong272    | 项目源码 | 文件源码
def save_sqlite(track_info):
    [track, trackInfoEchoNest, trackInfoLastFM] = track_info
    convert_type_dict = {float:'REAL', unicode:'TEXT', int:'INTEGER', str:'TEXT'}

    EN_key_list = trackInfoEchoNest.keys()
    LF_key_list = trackInfoLastFM.keys()

    table_columns = []
    column_names = []
    question_mark_sign = []
    for key in EN_key_list:
        if type(trackInfoEchoNest[key]) != types.NoneType:
            column_names.append('EN_' + key)
            table_columns1 = ' '.join(['EN_' + key, convert_type_dict[type(trackInfoEchoNest[key])]])
            table_columns.append(table_columns1)
            question_mark_sign.append('?')
        else:
            trackInfoEchoNest.pop(key)

    for key in LF_key_list:
        if type(trackInfoLastFM[key]) != types.NoneType:
            column_names.append('LF_' + key)
            table_columns1 = ' '.join(['LF_' + key, convert_type_dict[type(trackInfoLastFM[key])]])
            table_columns.append(table_columns1)
            question_mark_sign.append('?')
        else:
            trackInfoLastFM.pop(key)

    con = lite.connect('musicdata.db')
    with con:
        cur = con.cursor()
        #cur.execute("DROP TABLE IF EXISTS BoardEntries")
        cur.execute("SELECT ROWID FROM TrackEntries WHERE EN_title = ? and EN_artist_name = ?", (trackInfoEchoNest['title'],trackInfoEchoNest['artist_name']))
        existingEntry=cur.fetchone()
        if existingEntry is None:
            print('saving into database %s, %s'%(trackInfoEchoNest['title'], trackInfoEchoNest['artist_name']))
            single_entry = tuple([str(time.strftime("%Y-%m-%d %H:%M:%S")), track['title'], track['artist']] + trackInfoEchoNest.values() + trackInfoLastFM.values())
            cur.execute('INSERT OR IGNORE INTO TrackEntries(ID, EntryDate, SearchTitle, SearchArtist, ' + ', '.join(column_names) + ') VALUES (NULL, ?,?,?, ' + ', '.join(question_mark_sign)+')', single_entry)
        else:
            print('found in database %s, %s'%(trackInfoEchoNest['title'], trackInfoEchoNest['artist_name']))
    con.close()
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    )
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_unsubclassable_types(self):
        with self.assertRaises(TypeError):
            class X(types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(object, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, object):
                pass
        class O(object):
            pass
        with self.assertRaises(TypeError):
            class X(O, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, O):
                pass

        class X(object):
            pass
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType,
        with self.assertRaises(TypeError):
            X.__bases__ = object, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, object
        with self.assertRaises(TypeError):
            X.__bases__ = O, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, O
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_unsubclassable_types(self):
        with self.assertRaises(TypeError):
            class X(types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(object, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, object):
                pass
        class O(object):
            pass
        with self.assertRaises(TypeError):
            class X(O, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, O):
                pass

        class X(object):
            pass
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType,
        with self.assertRaises(TypeError):
            X.__bases__ = object, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, object
        with self.assertRaises(TypeError):
            X.__bases__ = O, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, O
项目:opc-rest-api    作者:matzpersson    | 项目源码 | 文件源码
def properties(self, tags, id=None):
      """Return list of property tuples (id, name, value) for the specified tag(s) """

      if type(tags) not in (types.ListType, types.TupleType) and type(id) not in (types.NoneType, types.ListType, types.TupleType):
         single = True
      else:
         single = False

      props = self.iproperties(tags, id)

      if single:
         return list(props)[0]
      else:
         return list(props)
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def coerce_cache_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string "
         "referring to a directory."),
        ('lock_dir', (str, types.NoneType), "lock_dir must be a string referring to a "
         "directory."),
        ('type', (str,), "Cache type must be a string."),
        ('enabled', (bool, types.NoneType), "enabled must be true/false "
         "if present."),
        ('expire', (int, types.NoneType), "expire must be an integer representing "
         "how many seconds the cache is valid for"),
        ('regions', (list, tuple, types.NoneType), "Regions must be a "
         "comma seperated list of valid regions")
    ]
    return verify_rules(params, rules)
项目:Flask-NvRay-Blog    作者:rui7157    | 项目源码 | 文件源码
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    )
项目:Flask-NvRay-Blog    作者:rui7157    | 项目源码 | 文件源码
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    )
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def _is_protected_type(obj):
    """
    True if the object is a native data type that does not need to be serialized further.
    """
    return isinstance(obj, six.string_types + six.integer_types + (
        types.NoneType,
        datetime.datetime, datetime.date, datetime.time,
        float, Decimal,
    ))
项目:zignal    作者:ronnyandersson    | 项目源码 | 文件源码
def comment(self, comment=None):
        """Modify or return a string comment."""
        assert isinstance(comment, (basestring, types.NoneType)), "A comment is a string"

        if comment is not None:
            self._comment = comment

        return self._comment
项目:crime-analysis-toolbox    作者:Esri    | 项目源码 | 文件源码
def X(self, value):
        """sets the X coordinate"""
        if isinstance(value, (int, float,
                              long, types.NoneType)):
            self._x = value
    #----------------------------------------------------------------------
项目:crime-analysis-toolbox    作者:Esri    | 项目源码 | 文件源码
def Y(self, value):
        """ sets the Y coordinate """
        if isinstance(value, (int, float,
                              long, types.NoneType)):
            self._y = value
    #----------------------------------------------------------------------
项目:crime-analysis-toolbox    作者:Esri    | 项目源码 | 文件源码
def Z(self, value):
        """ sets the Z coordinate """
        if isinstance(value, (int, float,
                              long, types.NoneType)):
            self._z = value
    #----------------------------------------------------------------------