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
python类NoneType()的实例源码
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 = {}
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)
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
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
# ???????????????????
# ????????
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)
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 = {}
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
# ???????????????????
# ????????
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
# ??
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))
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
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)
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)
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])
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
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)
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]
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)))
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]
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,
})
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
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
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)
)
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
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
def __init__(self, table):
assert isinstance(table, (dict, NoneType))
self.table = table
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)
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)
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)
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)