def generic_type_name(v):
"""Return a descriptive type name that isn't Python specific. For example,
an int value will return 'integer' rather than 'int'."""
if isinstance(v, numbers.Integral):
# Must come before real numbers check since integrals are reals too
return 'integer'
elif isinstance(v, numbers.Real):
return 'float'
elif isinstance(v, (tuple, list)):
return 'list'
elif isinstance(v, six.string_types):
return 'string'
elif v is None:
return 'null'
else:
return type(v).__name__
python类Real()的实例源码
def validate(self, val):
if not isinstance(val, numbers.Real):
raise ValidationError('expected real number, got %s' %
generic_type_name(val))
if not isinstance(val, float):
# This checks for the case where a number is passed in with a
# magnitude larger than supported by float64.
try:
val = float(val)
except OverflowError:
raise ValidationError('too large for float')
if math.isnan(val) or math.isinf(val):
raise ValidationError('%f values are not supported' % val)
if self.minimum is not None and val < self.minimum:
raise ValidationError('%f is not greater than %f' %
(val, self.minimum))
if self.maximum is not None and val > self.maximum:
raise ValidationError('%f is not less than %f' %
(val, self.maximum))
return val
def generic_type_name(v):
"""Return a descriptive type name that isn't Python specific. For example,
an int value will return 'integer' rather than 'int'."""
if isinstance(v, numbers.Integral):
# Must come before real numbers check since integrals are reals too
return 'integer'
elif isinstance(v, numbers.Real):
return 'float'
elif isinstance(v, (tuple, list)):
return 'list'
elif isinstance(v, six.string_types):
return 'string'
elif v is None:
return 'null'
else:
return type(v).__name__
def validate(self, val):
if not isinstance(val, numbers.Real):
raise ValidationError('expected real number, got %s' %
generic_type_name(val))
if not isinstance(val, float):
# This checks for the case where a number is passed in with a
# magnitude larger than supported by float64.
try:
val = float(val)
except OverflowError:
raise ValidationError('too large for float')
if math.isnan(val) or math.isinf(val):
raise ValidationError('%f values are not supported' % val)
if self.minimum is not None and val < self.minimum:
raise ValidationError('%f is not greater than %f' %
(val, self.minimum))
if self.maximum is not None and val > self.maximum:
raise ValidationError('%f is not less than %f' %
(val, self.maximum))
return val
def __setitem__(self, key, value):
# Overridden to make sure dict is normalized.
if not isinstance(value, Real) or value < 0 or value > 1:
raise ValueError("Value must be a number between 0 and 1, unlike " +
str(i))
try:
r = (self[key] - value)/(1 - self[key])
# r is the fraction of the remaining probability mass that
# we're going to give up (take).
for k in filter(key.__ne__, self):
dict.__setitem__(self, k, self[k] * (1 + r))
value = value if len(self) != 1 else 1
if value:
dict.__setitem__(self, key, value)
else:
# This is the purging stage!
dict.__delitem__(self, key)
except ZeroDivisionError:
# self[key] = 1, so key has all the probability mass. We'll leave it
# as is, since there's no sensible way of reducing it.
pass
def handle(self, conf):
if type(self).strategy == StartupBot.strategy:
yield _StartupBot.handle(self, conf)
return
import warnings
warnings.warn(
"Implementing custom startup bot relaunch strategies by implementing " +
"strategy() has been deprecated.",
DeprecationWarning
)
for value in self.strategy(conf):
if isinstance(value, numbers.Real):
yield idiokit.sleep(value)
else:
yield self.launch(value)
def fill(self, datum, weight=1.0):
self._checkForCrossReferences()
if weight > 0.0:
q = self.quantity(datum)
if not isinstance(q, numbers.Real):
raise TypeError("function return value ({0}) must be boolean or number".format(q))
if self.nan(q):
self.nanflow.fill(datum, weight)
else:
b = self.bin(q)
if b not in self.bins:
self.bins[b] = self.value.copy()
self.bins[b].fill(datum, weight)
# no possibility of exception from here on out (for rollback)
self.entries += weight
def is_float(x):
"""Determine whether some object ``x`` is a
float type (float, np.float, etc).
Parameters
----------
x : object
The item to assess
Returns
-------
bool
True if ``x`` is a float type
"""
return isinstance(x, (float, np.float)) or \
(not isinstance(x, (bool, np.bool)) and isinstance(x, numbers.Real))
def make_train_test(Y, ntest, seed = None):
if type(Y) not in [sp.sparse.coo.coo_matrix, sp.sparse.csr.csr_matrix, sp.sparse.csc.csc_matrix]:
raise ValueError("Unsupported Y type: %s" + type(Y))
if not isinstance(ntest, numbers.Real) or ntest < 0:
raise ValueError("ntest has to be a non-negative number (number or ratio of test samples).")
Y = Y.tocoo(copy = False)
if ntest < 1:
ntest = Y.nnz * ntest
if seed is not None:
np.random.seed(seed)
ntest = int(round(ntest))
rperm = np.random.permutation(Y.nnz)
train = rperm[ntest:]
test = rperm[0:ntest]
Ytrain = sp.sparse.coo_matrix( (Y.data[train], (Y.row[train], Y.col[train])), shape=Y.shape )
Ytest = sp.sparse.coo_matrix( (Y.data[test], (Y.row[test], Y.col[test])), shape=Y.shape )
return Ytrain, Ytest
def make_train_test(Y, ntest, seed = None):
if type(Y) not in [sp.sparse.coo.coo_matrix, sp.sparse.csr.csr_matrix, sp.sparse.csc.csc_matrix]:
raise ValueError("Unsupported Y type: %s" + type(Y))
if not isinstance(ntest, numbers.Real) or ntest < 0:
raise ValueError("ntest has to be a non-negative number (number or ratio of test samples).")
Y = Y.tocoo(copy = False)
if ntest < 1:
ntest = Y.nnz * ntest
if seed is not None:
np.random.seed(seed)
ntest = int(round(ntest))
rperm = np.random.permutation(Y.nnz)
train = rperm[ntest:]
test = rperm[0:ntest]
Ytrain = sp.sparse.coo_matrix( (Y.data[train], (Y.row[train], Y.col[train])), shape=Y.shape )
Ytest = sp.sparse.coo_matrix( (Y.data[test], (Y.row[test], Y.col[test])), shape=Y.shape )
return Ytrain, Ytest
def make_train_test(Y, ntest, seed = None):
if type(Y) not in [sp.sparse.coo.coo_matrix, sp.sparse.csr.csr_matrix, sp.sparse.csc.csc_matrix]:
raise ValueError("Unsupported Y type: %s" + type(Y))
if not isinstance(ntest, numbers.Real) or ntest < 0:
raise ValueError("ntest has to be a non-negative number (number or ratio of test samples).")
Y = Y.tocoo(copy = False)
if ntest < 1:
ntest = Y.nnz * ntest
if seed is not None:
np.random.seed(seed)
ntest = int(round(ntest))
rperm = np.random.permutation(Y.nnz)
train = rperm[ntest:]
test = rperm[0:ntest]
Ytrain = sp.sparse.coo_matrix( (Y.data[train], (Y.row[train], Y.col[train])), shape=Y.shape )
Ytest = sp.sparse.coo_matrix( (Y.data[test], (Y.row[test], Y.col[test])), shape=Y.shape )
return Ytrain, Ytest
def make_train_test(Y, ntest, seed = None):
if type(Y) not in [sp.sparse.coo.coo_matrix, sp.sparse.csr.csr_matrix, sp.sparse.csc.csc_matrix]:
raise ValueError("Unsupported Y type: %s" + type(Y))
if not isinstance(ntest, numbers.Real) or ntest < 0:
raise ValueError("ntest has to be a non-negative number (number or ratio of test samples).")
Y = Y.tocoo(copy = False)
if ntest < 1:
ntest = Y.nnz * ntest
if seed is not None:
np.random.seed(seed)
ntest = int(round(ntest))
rperm = np.random.permutation(Y.nnz)
train = rperm[ntest:]
test = rperm[0:ntest]
Ytrain = sp.sparse.coo_matrix( (Y.data[train], (Y.row[train], Y.col[train])), shape=Y.shape )
Ytest = sp.sparse.coo_matrix( (Y.data[test], (Y.row[test], Y.col[test])), shape=Y.shape )
return Ytrain, Ytest
def get_learning_rate_policy_callback(lr_params):
if isinstance(lr_params, numbers.Real):
# If argument is real number, set policy to fixed and use given value as base_lr
lr_params = {'name': 'fixed', 'base_lr': lr_params}
# Check if lr_params contains all required parameters for selected policy.
if lr_params['name'] not in lrp.lr_policies:
raise NotImplementedError("Learning rate policy {lr_name} not supported."
"\nSupported policies are: {policies}".format(
lr_name=lr_params['name'],
policies=lrp.lr_policies.keys())
)
elif all([x in lr_params.keys() for x in lrp.lr_policies[lr_params['name']]['args']]):
return lrp.lr_policies[lr_params['name']]['obj'](lr_params)
else:
raise ValueError("Too few arguments provided to create policy {lr_name}."
"\nGiven: {lr_params}"
"\nExpected: {lr_args}".format(
lr_name=lr_params['name'],
lr_params=lr_params.keys(),
lr_args=lrp.lr_policies[lr_params['name']])
)
def __init__(self, amount=None, currency=DEFAULT_CURRENCY,
amount_raw=None):
if not (amount is None) ^ (amount_raw is None):
raise ValueError("You must specify an amount or a raw amount")
if not isinstance(currency, Currency):
raise TypeError("You must specify a valid Currency")
if amount is not None:
if not isinstance(amount, numbers.Real):
raise TypeError("Amount must be an integer or float")
amount_raw = int(amount * 10**currency.precision)
if not isinstance(amount_raw, numbers.Integral):
raise TypeError("Amount must be an integer or float")
self.amount_raw = amount_raw
self.currency = currency
def __init__(self, amount=None, currency=DEFAULT_CURRENCY,
amount_raw=None):
if not (amount is None) ^ (amount_raw is None):
raise ValueError("You must specify an amount or a raw amount")
if not isinstance(currency, Currency):
raise TypeError("You must specify a valid Currency")
if amount is not None:
if not isinstance(amount, numbers.Real):
raise TypeError("Amount must be an integer or float")
amount_raw = int(amount * 10**currency.precision)
if not isinstance(amount_raw, numbers.Integral):
raise TypeError("Amount must be an integer or float")
self.amount_raw = amount_raw
self.currency = currency
def __init__(self, amount=None, currency=DEFAULT_CURRENCY,
amount_raw=None):
if not (amount is None) ^ (amount_raw is None):
raise ValueError("You must specify an amount or a raw amount")
if not isinstance(currency, Currency):
raise TypeError("You must specify a valid Currency")
if amount is not None:
if not isinstance(amount, numbers.Real):
raise TypeError("Amount must be an integer or float")
amount_raw = int(amount * 10**currency.precision)
if not isinstance(amount_raw, numbers.Integral):
raise TypeError("Amount must be an integer or float")
self.amount_raw = amount_raw
self.currency = currency
def test_get_types(self):
tc = testClass('mnop')
tc2 = testClass2('qrst')
tc3 = testClass3()
self.assertEqual(get_types(testfunc),
(Tuple[int, Real, str], Tuple[int, Real]))
self.assertEqual(get_types(testfunc2),
(Tuple[int, Real, testClass], Tuple[int, float]))
self.assertEqual(get_types(testfunc4), (Any, Any))
self.assertEqual(get_types(tc2.testmeth), (Tuple[int, Real], str))
self.assertEqual(get_types(testClass2.testmeth), (Tuple[int, Real], str))
self.assertEqual(get_types(tc3.testmeth), (Any, Any))
self.assertEqual(get_types(testClass3Base.testmeth),
(Tuple[int, Real], Union[str, int]))
self.assertEqual(get_types(tc.testmeth2), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_class), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_class2), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_static), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_static2), (Tuple[int, Real], str))
self.assertEqual(get_types(testfunc),
(Tuple[int, Real, str], Tuple[int, Real]))
def test_get_types_py3(self):
tc = py3.testClass('mnop')
tc2 = py3.testClass2('qrst')
tc3 = py3.testClass3()
self.assertEqual(get_types(py3.testfunc),
(Tuple[int, Real, str], Tuple[int, Real]))
self.assertEqual(get_types(py3.testfunc2),
(Tuple[int, Real, py3.testClass], Tuple[int, float]))
self.assertEqual(get_types(tc2.testmeth), (Tuple[int, Real], str))
self.assertEqual(get_types(py3.testClass2.testmeth), (Tuple[int, Real], str))
self.assertEqual(get_types(tc3.testmeth), (Any, Any))
self.assertEqual(get_types(py3.testClass3Base.testmeth),
(Tuple[int, Real], Union[str, int]))
self.assertEqual(get_types(tc.testmeth2), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_class), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_class2), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_static), (Tuple[int, Real], str))
self.assertEqual(get_types(tc.testmeth_static2), (Tuple[int, Real], str))
self.assertEqual(get_types(py3.testfunc),
(Tuple[int, Real, str], Tuple[int, Real]))
def __init__(self, min_value=None, max_value=None):
"""
A more restrictive minimum or maximum value can be specified than the
range inherent to the defined type.
"""
if min_value is not None:
assert isinstance(min_value, numbers.Real), \
'min_value must be a real number'
if not isinstance(min_value, float):
try:
min_value = float(min_value)
except OverflowError:
raise AssertionError('min_value is too small for a float')
if self.minimum is not None and min_value < self.minimum:
raise AssertionError('min_value cannot be less than the '
'minimum value for this type (%f < %f)' %
(min_value, self.minimum))
self.minimum = min_value
if max_value is not None:
assert isinstance(max_value, numbers.Real), \
'max_value must be a real number'
if not isinstance(max_value, float):
try:
max_value = float(max_value)
except OverflowError:
raise AssertionError('max_value is too large for a float')
if self.maximum is not None and max_value > self.maximum:
raise AssertionError('max_value cannot be greater than the '
'maximum value for this type (%f < %f)' %
(max_value, self.maximum))
self.maximum = max_value
def assert_trade_protocol(event):
"""Assert that an event meets the protocol for datasource TRADE outputs."""
assert_datasource_protocol(event)
assert event.type == DATASOURCE_TYPE.TRADE
assert isinstance(event.price, numbers.Real)
assert isinstance(event.volume, numbers.Integral)
assert isinstance(event.dt, datetime)
def _timedelta_to_seconds(td):
"""Convert a datetime.timedelta object into a seconds interval for
rotating file ouput.
:param td: datetime.timedelta
:return: time in seconds
:rtype: int
"""
if isinstance(td, numbers.Real):
td = datetime.timedelta(seconds=td)
return td.total_seconds()
def __mul__(self, other):
"""Multiply a Point with a constant.
>>> 2 * Point(1,2)
(2.000,4.000)
>>> Point(1,2) * Point(1,2) #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
"""
if not isinstance(other, numbers.Real):
return NotImplemented
return Point(self.x * other, self.y * other)
def __init__(self, arg):
if isinstance(arg, numbers.Real):
# We precompute sin and cos for rotations
self.angle = arg
self.cos = math.cos(self.angle)
self.sin = math.sin(self.angle)
elif isinstance(arg, Point):
# Point angle is the trigonometric angle of the vector
# [origin, Point]
pt = arg
try:
self.cos = pt.x / pt.length()
self.sin = pt.y / pt.length()
except ZeroDivisionError:
self.cos = 1
self.sin = 0
self.angle = math.acos(self.cos)
if self.sin < 0:
self.angle = -self.angle
else:
raise TypeError("Angle is defined by a number or a Point")
def __init__(self, min_value=None, max_value=None):
"""
A more restrictive minimum or maximum value can be specified than the
range inherent to the defined type.
"""
if min_value is not None:
assert isinstance(min_value, numbers.Real), \
'min_value must be a real number'
if not isinstance(min_value, float):
try:
min_value = float(min_value)
except OverflowError:
raise AssertionError('min_value is too small for a float')
if self.minimum is not None and min_value < self.minimum:
raise AssertionError('min_value cannot be less than the '
'minimum value for this type (%f < %f)' %
(min_value, self.minimum))
self.minimum = min_value
if max_value is not None:
assert isinstance(max_value, numbers.Real), \
'max_value must be a real number'
if not isinstance(max_value, float):
try:
max_value = float(max_value)
except OverflowError:
raise AssertionError('max_value is too large for a float')
if self.maximum is not None and max_value > self.maximum:
raise AssertionError('max_value cannot be greater than the '
'maximum value for this type (%f < %f)' %
(max_value, self.maximum))
self.maximum = max_value
def __init__(self, items = None):
"""Create a dictionary from iters.
If items can't be fed to a dictionary, it will be interpreted as a
collection of keys, and each value will default to value 1/n. Otherwise,
the values are normalized to sum to one. Raises ValueError if
some values are not numbers or are negative.
Arguments:
- `items`: argument with which to make dictionary
"""
if items is None: return dict.__init__(self)
try:
# can fail if items is not iterable or not full of size 2 items:
dict.__init__(self, items)
except TypeError:
try:
# Let's assume items is a finite iterable full of keys
vals = [1/len(items)] * len(items)
except TypeError:
# Apparently items has no length -- let's take it as the only
# key and put all the probability on it.
dict.__init__(self, (items, 1))
else:
# if items has a length, it can be iterated through with zip
dict.__init__(self, zip(items, vals))
else:
# we've successfully made dic from key, value pairs in items, now let's
# normalize the dictionary, and check the values
for v in self.values():
if not isinstance(v, Real):
raise TypeError("Values must be nonnegative real numbers so I " +
"can properly normalize them. " + str(v) + " is not.")
elif v < 0:
raise ValueError("Values must be nonnegative, unlike " + str(v))
tot = sum(self.values())
for k, v in self.items(): self[k] = v/tot
def add_timeout(self, deadline, callback, *args, **kwargs):
# This method could be simplified (since tornado 4.0) by
# overriding call_at instead of add_timeout, but we leave it
# for now as a test of backwards-compatibility.
if isinstance(deadline, numbers.Real):
delay = max(deadline - self.time(), 0)
elif isinstance(deadline, datetime.timedelta):
delay = timedelta_to_seconds(deadline)
else:
raise TypeError("Unsupported deadline %r")
return self.reactor.callLater(
delay, self._run_callback,
functools.partial(wrap(callback), *args, **kwargs))
def format_timestamp(ts):
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
"""
if isinstance(ts, numbers.Real):
pass
elif isinstance(ts, (tuple, time.struct_time)):
ts = calendar.timegm(ts)
elif isinstance(ts, datetime.datetime):
ts = calendar.timegm(ts.utctimetuple())
else:
raise TypeError("unknown timestamp type: %r" % ts)
return email.utils.formatdate(ts, usegmt=True)
def add_timeout(self, deadline, callback, *args, **kwargs):
"""Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current time. Since Tornado 4.0, `call_later` is a more
convenient alternative for the relative case since it does not
require a timedelta object.
Note that it is not safe to call `add_timeout` from other threads.
Instead, you must use `add_callback` to transfer control to the
`IOLoop`'s thread, and then call `add_timeout` from there.
Subclasses of IOLoop must implement either `add_timeout` or
`call_at`; the default implementations of each will call
the other. `call_at` is usually easier to implement, but
subclasses that wish to maintain compatibility with Tornado
versions prior to 4.0 must use `add_timeout` instead.
.. versionchanged:: 4.0
Now passes through ``*args`` and ``**kwargs`` to the callback.
"""
if isinstance(deadline, numbers.Real):
return self.call_at(deadline, callback, *args, **kwargs)
elif isinstance(deadline, datetime.timedelta):
return self.call_at(self.time() + timedelta_to_seconds(deadline),
callback, *args, **kwargs)
else:
raise TypeError("Unsupported deadline %r" % deadline)
def __init__(self, deadline, callback, io_loop):
if not isinstance(deadline, numbers.Real):
raise TypeError("Unsupported deadline %r" % deadline)
self.deadline = deadline
self.callback = callback
self.tiebreaker = next(io_loop._timeout_counter)
# Comparison methods to sort by deadline, with object id as a tiebreaker
# to guarantee a consistent ordering. The heapq module uses __le__
# in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
# use __lt__).
def add_timeout(self, deadline, callback, *args, **kwargs):
# This method could be simplified (since tornado 4.0) by
# overriding call_at instead of add_timeout, but we leave it
# for now as a test of backwards-compatibility.
if isinstance(deadline, numbers.Real):
delay = max(deadline - self.time(), 0)
elif isinstance(deadline, datetime.timedelta):
delay = timedelta_to_seconds(deadline)
else:
raise TypeError("Unsupported deadline %r")
return self.reactor.callLater(
delay, self._run_callback,
functools.partial(wrap(callback), *args, **kwargs))