我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用builtins.float()。
def _set_array_types(): ibytes = [1, 2, 4, 8, 16, 32, 64] fbytes = [2, 4, 8, 10, 12, 16, 32, 64] for bytes in ibytes: bits = 8*bytes _add_array_type('int', bits) _add_array_type('uint', bits) for bytes in fbytes: bits = 8*bytes _add_array_type('float', bits) _add_array_type('complex', 2*bits) _gi = dtype('p') if _gi.type not in sctypes['int']: indx = 0 sz = _gi.itemsize _lst = sctypes['int'] while (indx < len(_lst) and sz >= _lst[indx](0).itemsize): indx += 1 sctypes['int'].insert(indx, _gi.type) sctypes['uint'].insert(indx, dtype('P').type)
def _get_default_gfa_tag_datatype(obj): """Default GFA tag datatype for a given object Parameters: obj : an object of any Python class Returns: str : the identifier of a datatype (one of the keys of FIELD_MODULE) to be used for a tag with obj as value, if a datatype has not been specified by the user """ if getattr(obj, "_default_gfa_tag_datatype",None): return obj._default_gfa_tag_datatype() else: if isinstance(obj, list) and\ (all([isinstance(v, builtins.int) for v in obj]) or all([isinstance(v, builtins.float) for v in obj])): return "B" for k,v in gfapy.Field._default_tag_datatypes: if isinstance(obj, k): return v return "J"
def validate_type_declaration(type_decl): """ Check if a type delaration is valid A type declaration can either declare a primitive value (e.g. int, float, string etc.), a custom type value (Enum or Named Hash) or a typed array containing a value of either a primitive type or a custom type (e.g. array<int>, array<{CustomType}>, ...) Args: type_decl (str): The type declaration to validate Returns: bool: True if valid, False if not """ if validate_primitive_type_name(type_decl): return True if validate_custom_type_name(type_decl): return True if validate_typed_array_declaration(type_decl): return True return False
def assert_bounded(val, lower=None, upper=None, msg=None): """Assert that ``lower <= val <= upper``. :arg val: The value to check. :arg lower: The lower bound. If ``None``, it defaults to ``-inf``. :arg upper: The upper bound. If ``None``, it defaults to ``inf``. :returns: ``True`` on success. :raises reframe.core.exceptions.SanityError: if assertion fails. """ if lower is None: lower = builtins.float('-inf') if upper is None: upper = builtins.float('inf') if val >= lower and val <= upper: return True error_msg = msg or 'value {0} not within bounds {1}..{2}' raise SanityError(_format(error_msg, val, lower, upper))
def issubclass_(arg1, arg2): """ Determine if a class is a subclass of a second class. `issubclass_` is equivalent to the Python built-in ``issubclass``, except that it returns False instead of raising a TypeError if one of the arguments is not a class. Parameters ---------- arg1 : class Input class. True is returned if `arg1` is a subclass of `arg2`. arg2 : class or tuple of classes. Input class. If a tuple of classes, True is returned if `arg1` is a subclass of any of the tuple elements. Returns ------- out : bool Whether `arg1` is a subclass of `arg2` or not. See Also -------- issubsctype, issubdtype, issctype Examples -------- >>> np.issubclass_(np.int32, np.int) True >>> np.issubclass_(np.int32, np.float) False """ try: return issubclass(arg1, arg2) except TypeError: return False
def issubsctype(arg1, arg2): """ Determine if the first argument is a subclass of the second argument. Parameters ---------- arg1, arg2 : dtype or dtype specifier Data-types. Returns ------- out : bool The result. See Also -------- issctype, issubdtype,obj2sctype Examples -------- >>> np.issubsctype('S8', str) True >>> np.issubsctype(np.array([1]), np.int) True >>> np.issubsctype(np.array([1]), np.float) False """ return issubclass(obj2sctype(arg1), obj2sctype(arg2))
def flatten_dtype(ndtype, flatten_base=False): """ Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : {False, True}, optional Whether to transform a field with a shape into several fields or not. Examples -------- >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ... ('block', int, (2, 3))]) >>> np.lib._iotools.flatten_dtype(dt) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')] >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32')] """ names = ndtype.names if names is None: if flatten_base: return [ndtype.base] * int(np.prod(ndtype.shape)) return [ndtype.base] else: types = [] for field in names: info = ndtype.fields[field] flat_dt = flatten_dtype(info[0], flatten_base) types.extend(flat_dt) return types
def json2py(json_type): mapping = {'bool': 'bool', 'int': 'int', 'float': 'float', 'string': 'str', 'array': 'list', 'hash': 'dict', 'base64': 'str'} if json_type not in mapping: return None return mapping[json_type]
def __init__(self): """ Constructor """ self.functions = [] self.functions_dict = {} self.custom_types = [] self.custom_types_dict = {} self.description = { 'name': '', 'description': '', 'version': '', 'custom_fields': {} } self.builtins = {} self.builtins['__describe_service'] = self.describe_service self.builtins['__describe_functions'] = self.describe_functions self.builtins['__describe_custom_types'] = self.describe_custom_types self.named_hash_validation = True self.json2py = {'bool': 'bool', 'int': 'int', 'float': 'float', 'string': 'str', 'array': 'list', 'hash': 'dict', 'base64': 'str'} self.py2json = {'bool': 'bool', 'int': 'int', 'float': 'float', 'str': 'string', 'list': 'array', 'dict': 'hash'}
def div(a, b): return float(a) / float(b)
def test_type_checks(self): rpc = RpcProcessor() echo_func = RpcFunction(echo, 'echo', 'Returns what it was given', 'string', 'Same value as the first parameter') echo_func.add_param('string', 'message', 'Message to send back') rpc.add_function(echo_func) add_func = RpcFunction(add, 'add', 'Returns the sum of the two parameters', 'int', 'Sum of a and b') add_func.add_param('int', 'a', 'First int to add') add_func.add_param('int', 'b', 'Second int to add') rpc.add_function(add_func) reply = rpc.process_request('{"method": "echo", "params": [42], "id": 1}') self.assertEqual(reply['result'], None) self.assertEqual(reply['error'], {'name': 'TypeError', 'message':'echo: Expected value of type \'string\' for parameter \'message\' but got value of type \'int\''}) reply = rpc.process_request('{"method": "echo", "params": [[]], "id": 2}') self.assertEqual(reply['result'], None) self.assertEqual(reply['error'], {'name': 'TypeError', 'message':'echo: Expected value of type \'string\' for parameter \'message\' but got value of type \'array\''}) reply = rpc.process_request('{"method": "add", "params": [4, 8.9], "id": 3}') self.assertEqual(reply['result'], None) self.assertEqual(reply['error'], {'name': 'TypeError', 'message':'add: Expected value of type \'int\' for parameter \'b\' but got value of type \'float\''}) reply = rpc.process_request('{"method": "add", "params": [4, {"test": 8}], "id": 3}') self.assertEqual(reply['result'], None) self.assertEqual(reply['error'], {'name': 'TypeError', 'message':'add: Expected value of type \'int\' for parameter \'b\' but got value of type \'hash\''})
def test_type_checks_for_fields_of_named_hashes(self): rpc = RpcProcessor() custom_type = JsonHashType('CustomHash', 'Dummy named hash for testing') custom_type.add_field('boolfield', 'bool', 'Some bool') custom_type.add_field('stringfield', 'string', 'Some string') custom_type.add_field('intfield', 'int', 'Some integer') custom_type.add_field('floatfield', 'float', 'Some float') custom_type.add_field('arrayfield', 'array', 'City') custom_type.add_field('hashfield', 'hash', 'City') rpc.add_custom_type(custom_type) rpc.enable_named_hash_validation() echo_hash_func = RpcFunction(echo_hash, 'echo_hash', 'Returns what it was given', 'hash', 'Same value as the first parameter') echo_hash_func.add_param('CustomHash', 'custom_hash', 'Some custom hash instance') rpc.add_function(echo_hash_func) # Call with an empty hash should get us an error mentioning the first missing field reply = rpc.process_request('{"method": "echo_hash", "params": [{}], "id": 1}') self.assertEqual(reply['result'], None) self.assertEqual(reply['error'], {'name': 'TypeError', 'message': "echo_hash: Named hash parameter 'custom_hash' of type 'CustomHash': Missing field 'boolfield'" }) # Call with an invalid field should return the corresponding error reply = rpc.process_request('{"method": "echo_hash", "params": [{"boolfield": true, "stringfield": 5, "intfield": 5, "floatfield": 5.5, "arrayfield": [], "hashfield": {}}], "id": 2}') self.assertEqual(reply['result'], None) self.assertEqual(reply['error'], {'name': 'TypeError', 'message': "echo_hash: Expected value of type 'string' for parameter 'custom_hash.stringfield' but got value of type 'int'"}) # Call with a valid hash should return the same hash without error reply = rpc.process_request('{"method": "echo_hash", "params": [{"boolfield": true, "stringfield": "test", "intfield": 5, "floatfield": 5.5, "arrayfield": [], "hashfield": {}}], "id": 3}') self.assertEqual(reply['error'], None) self.assertEqual(reply['result'], {"boolfield": True, "stringfield": "test", "intfield": 5, "floatfield": 5.5, "arrayfield": [], "hashfield": {}})
def _set_up_aliases(): type_pairs = [('complex_', 'cdouble'), ('int0', 'intp'), ('uint0', 'uintp'), ('single', 'float'), ('csingle', 'cfloat'), ('singlecomplex', 'cfloat'), ('float_', 'double'), ('intc', 'int'), ('uintc', 'uint'), ('int_', 'long'), ('uint', 'ulong'), ('cfloat', 'cdouble'), ('longfloat', 'longdouble'), ('clongfloat', 'clongdouble'), ('longcomplex', 'clongdouble'), ('bool_', 'bool'), ('unicode_', 'unicode'), ('object_', 'object')] if sys.version_info[0] >= 3: type_pairs.extend([('bytes_', 'string'), ('str_', 'unicode'), ('string_', 'string')]) else: type_pairs.extend([('str_', 'string'), ('string_', 'string'), ('bytes_', 'string')]) for alias, t in type_pairs: allTypes[alias] = allTypes[t] sctypeDict[alias] = sctypeDict[t] # Remove aliases overriding python types and modules to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float', 'complex', 'bool', 'string', 'datetime', 'timedelta'] if sys.version_info[0] >= 3: # Py3K to_remove.append('bytes') to_remove.append('str') to_remove.remove('unicode') to_remove.remove('long') for t in to_remove: try: del allTypes[t] del sctypeDict[t] except KeyError: pass
def sctype2char(sctype): """ Return the string representation of a scalar dtype. Parameters ---------- sctype : scalar dtype or object If a scalar dtype, the corresponding string character is returned. If an object, `sctype2char` tries to infer its scalar type and then return the corresponding string character. Returns ------- typechar : str The string character corresponding to the scalar type. Raises ------ ValueError If `sctype` is an object for which the type can not be inferred. See Also -------- obj2sctype, issctype, issubsctype, mintypecode Examples -------- >>> for sctype in [np.int32, np.float, np.complex, np.string_, np.ndarray]: ... print(np.sctype2char(sctype)) l d D S O >>> x = np.array([1., 2-1.j]) >>> np.sctype2char(x) 'D' >>> np.sctype2char(list) 'O' """ sctype = obj2sctype(sctype) if sctype is None: raise ValueError("unrecognized type") return _sctype2char_dict[sctype] # Create dictionary of casting functions that wrap sequences # indexed by type or type character
def sctype2char(sctype): """ Return the string representation of a scalar dtype. Parameters ---------- sctype : scalar dtype or object If a scalar dtype, the corresponding string character is returned. If an object, `sctype2char` tries to infer its scalar type and then return the corresponding string character. Returns ------- typechar : str The string character corresponding to the scalar type. Raises ------ ValueError If `sctype` is an object for which the type can not be inferred. See Also -------- obj2sctype, issctype, issubsctype, mintypecode Examples -------- >>> for sctype in [np.int32, np.float, np.complex, np.string_, np.ndarray]: ... print np.sctype2char(sctype) l d D S O >>> x = np.array([1., 2-1.j]) >>> np.sctype2char(x) 'D' >>> np.sctype2char(list) 'O' """ sctype = obj2sctype(sctype) if sctype is None: raise ValueError("unrecognized type") return _sctype2char_dict[sctype] # Create dictionary of casting functions that wrap sequences # indexed by type or type character
def test_valid_types_in_constructor(self): try: RpcFunction(dummy_function, 'dummy', 'Dummy function', 'int', 'Return value') except: self.fail("Constructor of RpcFunction raised unexpected exception!") try: RpcFunction(dummy_function, 'dummy', 'Dummy function', 'bool', 'Return value') except: self.fail("Constructor of RpcFunction raised unexpected exception!") try: RpcFunction(dummy_function, 'dummy', 'Dummy function', 'float', 'Return value') except: self.fail("Constructor of RpcFunction raised unexpected exception!") try: RpcFunction(dummy_function, 'dummy', 'Dummy function', 'string', 'Return value') except: self.fail("Constructor of RpcFunction raised unexpected exception!") try: RpcFunction(dummy_function, 'dummy', 'Dummy function', 'array', 'Return value') except: self.fail("Constructor of RpcFunction raised unexpected exception!") try: RpcFunction(dummy_function, 'dummy', 'Dummy function', 'hash', 'Return value') except: self.fail("Constructor of RpcFunction raised unexpected exception!") try: RpcFunction(dummy_function, 'dummy', 'Dummy function', 'base64', 'Return value') except: self.fail("Constructor of RpcFunction raised unexpected exception!")