我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numbers.Number()。
def build_binary_op(self, op, other): """ Compute new expression strings and a new inputs tuple for combining self and other with a binary operator. """ if isinstance(other, NumericalExpression): self_expr, other_expr, new_inputs = self._merge_expressions(other) elif isinstance(other, Term): self_expr = self._expr new_inputs, other_idx = _ensure_element(self.inputs, other) other_expr = "x_%d" % other_idx elif isinstance(other, Number): self_expr = self._expr other_expr = str(other) new_inputs = self.inputs else: raise BadBinaryOperator(op, other) return self_expr, other_expr, new_inputs
def coerce_numbers_to_my_dtype(f): """ A decorator for methods whose signature is f(self, other) that coerces ``other`` to ``self.dtype``. This is used to make comparison operations between numbers and `Factor` instances work independently of whether the user supplies a float or integer literal. For example, if I write:: my_filter = my_factor > 3 my_factor probably has dtype float64, but 3 is an int, so we want to coerce to float64 before doing the comparison. """ @wraps(f) def method(self, other): if isinstance(other, Number): other = coerce_to_dtype(self.dtype, other) return f(self, other) return method
def quantiles(self, bins, mask=NotSpecified): """ Construct a Classifier computing quantiles of the output of ``self``. Every non-NaN data point the output is labelled with an integer value from 0 to (bins - 1). NaNs are labelled with -1. If ``mask`` is supplied, ignore data points in locations for which ``mask`` produces False, and emit a label of -1 at those locations. Parameters ---------- bins : int Number of bins labels to compute. mask : zipline.pipeline.Filter, optional Mask of values to ignore when computing quantiles. Returns ------- quantiles : zipline.pipeline.classifiers.Quantiles A Classifier producing integer labels ranging from 0 to (bins - 1). """ if mask is NotSpecified: mask = self.mask return Quantiles(inputs=(self,), bins=bins, mask=mask)
def bottom(self, N, mask=NotSpecified): """ Construct a Filter matching the bottom N asset values of self each day. Parameters ---------- N : int Number of assets passing the returned filter each day. mask : zipline.pipeline.Filter, optional A Filter representing assets to consider when computing ranks. If mask is supplied, bottom values are computed ignoring any asset/date pairs for which `mask` produces a value of False. Returns ------- filter : zipline.pipeline.Filter """ return self.rank(ascending=True, mask=mask) <= N
def version_range(version): """\ Returns the version range for the provided version. This applies to QR Code versions, only. :param int version: The QR Code version (1 .. 40) :rtype: int """ # ISO/IEC 18004:2015(E) # Table 3 — Number of bits in character count indicator for QR Code (page 23) if 0 < version < 10: return consts.VERSION_RANGE_01_09 elif 9 < version < 27: return consts.VERSION_RANGE_10_26 elif 26 < version < 41: return consts.VERSION_RANGE_27_40 raise VersionError('Unknown version "{0}"'.format(version))
def _getink(self, ink, fill=None): if ink is None and fill is None: if self.fill: fill = self.ink else: ink = self.ink else: if ink is not None: if isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not isinstance(ink, numbers.Number): ink = self.palette.getcolor(ink) ink = self.draw.draw_ink(ink, self.mode) if fill is not None: if isStringType(fill): fill = ImageColor.getcolor(fill, self.mode) if self.palette and not isinstance(fill, numbers.Number): fill = self.palette.getcolor(fill) fill = self.draw.draw_ink(fill, self.mode) return ink, fill ## # Draw an arc.
def _getscaleoffset(expr): stub = ["stub"] data = expr(_E(stub)).data try: (a, b, c) = data # simplified syntax if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)): return c, 0.0 if a is stub and b == "__add__" and isinstance(c, numbers.Number): return 1.0, c except TypeError: pass try: ((a, b, c), d, e) = data # full syntax if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and d == "__add__" and isinstance(e, numbers.Number)): return c, e except TypeError: pass raise ValueError("illegal expression") # -------------------------------------------------------------------- # Implementation wrapper
def __imul__(self, other): """ >>> g = GlyphCoordinates([(1,2)]) >>> g *= (2,.5) >>> g *= 2 >>> g GlyphCoordinates([(4.0, 2.0)]) >>> g = GlyphCoordinates([(1,2)]) >>> g *= 2 >>> g GlyphCoordinates([(2, 4)]) """ if isinstance(other, Number): other = (other, other) if isinstance(other, tuple): if other == (1,1): return self assert len(other) == 2 self.scale(other) return self return NotImplemented
def __itruediv__(self, other): """ >>> g = GlyphCoordinates([(1,3)]) >>> g /= (.5,1.5) >>> g /= 2 >>> g GlyphCoordinates([(1.0, 1.0)]) """ if isinstance(other, Number): other = (other, other) if isinstance(other, tuple): if other == (1,1): return self assert len(other) == 2 self.scale((1./other[0],1./other[1])) return self return NotImplemented
def _getink(self, ink, fill=None): if ink is None and fill is None: if self.fill: fill = self.ink else: ink = self.ink else: if ink is not None: if isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not isinstance(ink, numbers.Number): ink = self.palette.getcolor(ink) ink = self.draw.draw_ink(ink, self.mode) if fill is not None: if isStringType(fill): fill = ImageColor.getcolor(fill, self.mode) if self.palette and not isinstance(fill, numbers.Number): fill = self.palette.getcolor(fill) fill = self.draw.draw_ink(fill, self.mode) return ink, fill
def __mul__(self, mult): """Multiply the point by a scalar. Parameters ---------- mult : float The number by which to multiply the Point. Returns ------- :obj:`Point3D` A 3D point created by the multiplication. Raises ------ ValueError If mult is not a scalar value. """ if isinstance(mult, numbers.Number): return Point(mult * self._data, self._frame) raise ValueError('Type %s not supported. Only scalar multiplication is supported' %(type(mult)))
def __div__(self, div): """Divide the point by a scalar. Parameters ---------- div : float The number by which to divide the Point. Returns ------- :obj:`Point3D` A 3D point created by the division. Raises ------ ValueError If div is not a scalar value. """ if not isinstance(div, numbers.Number): raise ValueError('Type %s not supported. Only scalar division is supported' %(type(div))) return self.__mul__(1.0 / div)
def __mul__(self, mult): """Multiply each point in the cloud by a scalar. Parameters ---------- mult : float The number by which to multiply the PointCloud. Returns ------- :obj:`PointCloud` A PointCloud created by the multiplication. Raises ------ ValueError If mult is not a scalar value. """ if isinstance(mult, numbers.Number): return PointCloud(mult * self._data, self._frame) raise ValueError('Type %s not supported. Only scalar multiplication is supported' %(type(mult)))
def __div__(self, div): """Divide each point in the cloud by a scalar. Parameters ---------- div : float The number by which to divide the PointCloud. Returns ------- :obj:`PointCloud` A PointCloud created by the division. Raises ------ ValueError If div is not a scalar value. """ if not isinstance(div, numbers.Number): raise ValueError('Type %s not supported. Only scalar division is supported' %(type(div))) return self.__mul__(1.0 / div)
def _render_node(self, node): """ Renders a node. Recursive callee for node rendering. :param node: the representation of a node (dependent of rendered data structure) :return: node id of created node """ if isinstance(node, (str, numbers.Number)) or node is None: node_id = uuid() else: node_id = id(node) node_id = str(node_id) if node_id not in self._rendered: self._rendered.add(node_id) if isinstance(node, dict): self._render_dict(node, node_id) elif isinstance(node, list): self._render_list(node, node_id) else: self._graph.node(node_id, label=self._escape_label(self._shorten_label(repr(node)))) return node_id
def set_ibasset(self, ibasset): """Set interbank assets. Interbank assets are represented as a sequence of 2-tuples whose first element is a `Bank` object (the borrower) and whose second element is the face value of the interbank asset. Parameters: ibasset (sequence of tuples (`Bank`, float)): interbank assets. """ if not isinstance(ibasset, (list, tuple)): raise TypeError for item in ibasset: if not isinstance(item, (list, tuple)): raise TypeError else: if (not isinstance(item[0], Bank)) or (not isinstance(item[1], numbers.Number)): raise TypeError self.ibasset = ibasset self.equity = self.get_naiveequity()
def rescale_exchange(exc, value, remove_uncertainty=True): """Dummy function to rescale exchange amount and uncertainty. This depends on some code being separated from Ocelot, which will take a bit of time. * ``exc`` is an exchange dataset. * ``value`` is a number, to be multiplied by the existing amount. * ``remove_uncertainty``: Remove (unscaled) uncertainty data, default is ``True``. Returns the modified exchange.""" assert isinstance(exc, dict), "Must pass exchange dictionary" assert isinstance(value, Number), "Constant factor ``value`` must be a number" exc['amount'] *= value FIELDS = ('shape', 'size', 'minimum', 'maximum') if remove_uncertainty: exc['uncertainty type'] = 0 exc['loc'] = exc['amount'] for field in FIELDS: if field in exc: del exc[field] return exc
def logfmt_key(self, k): if isinstance(k, bytes): k = k.decode('utf8') if isinstance(k, str): k = k.replace(' ', '_').replace('.', '_').replace('=', '_') k = self.safe_string(k, self.MAX_KEY_SIZE, self.TRUNCATED_KEY) # TODO: look at measuring perf of this # ' ' and = are replaced because they're are not valid logfmt # . is replaced because elasticsearch can't do keys with . in elif isinstance(k, bool): # need to do this here, as bool are also numbers return None elif isinstance(k, numbers.Number): k = str(k) else: return None return k
def sync(self, method): self.setHorizontalHeaderLabels(self.HEADERS) method = bw.Method(method) data = method.load() self.setRowCount(len(data)) for row, obj in enumerate(data): key, amount = obj[:2] flow = bw.get_activity(key) if isinstance(amount, numbers.Number): uncertain = "False" else: uncertain = "True" amount = amount['amount'] self.setItem(row, 0, ABTableItem(flow['name'], key=key)) self.setItem(row, 1, ABTableItem("{:.6g}".format(amount), key=key)) self.setItem(row, 2, ABTableItem(flow.get('unit', 'Unknown'), key=key)) self.setItem(row, 3, ABTableItem(str(uncertain), key=key))
def __init__(self, name, type=None, required=False, min=None, max=None, regex=None, logic=None, default=None): """ :param name ????????????? :param required ???True????????? :param min ?????????????????(???????)? ?????(numbers.Number??)??????????(???????) :param max ?? :param regex ???? :param type ??????????????? :param logic ?????????????????????????????????? ?????????True?False???????????????????? ?????????????None :param default ?????? """ pass
def _query_len(self): """influxdb only counts non-null values, so we return the count of the field with maximum non-null values""" q = u'SELECT COUNT(*) FROM "{}" {} {}'.format( self.measurement_name, self._where_expression(), self._groupby_expression() ).strip() self.container.client.switch_database(self.db_name) logger.info('Querying InfluxDB: {}'.format(q)) rs = self.container.client.query(q) interval_list = list(rs.get_points()) if request and request.args.get('aggregate'): max_count = len(interval_list) else: max_count = max(val for val in rs.get_points().next().values() if isinstance(val, numbers.Number)) self._influxdb_len = max_count return max_count
def add(self, output, target): if torch.is_tensor(output): output = output.cpu().squeeze().numpy() if torch.is_tensor(target): target = target.cpu().squeeze().numpy() elif isinstance(target, numbers.Number): target = np.asarray([target]) assert np.ndim(output) == 1, \ 'wrong output size (1D expected)' assert np.ndim(target) == 1, \ 'wrong target size (1D expected)' assert output.shape[0] == target.shape[0], \ 'number of outputs and targets does not match' assert np.all(np.add(np.equal(target, 1), np.equal(target, 0))), \ 'targets should be binary (0, 1)' self.scores = np.append(self.scores, output) self.targets = np.append(self.targets, target)
def __init__(self, target): self.error_dict = {} self._data = {} for field in self.fields: self._data[field] = target.get(field) for field in self.defaults: if not target.get(field): self._data[field] = self.defaults[field] for field in self.required_fields: if not self._data.get(field) and not isinstance(self._data.get(field), Number): self.error_dict[field] = ['This field is required'] self.validate()
def _validate_X_predict( self, X: np.ndarray, check_input: bool) -> np.ndarray: if check_input: X = check_array(X, dtype=DTYPE, accept_sparse="csr") if issparse(X) and (X.indices.dtype != np.intc or X.indptr.dtype != np.intc): raise ValueError( "No support for np.int64 index based sparse matrices") n_features = X.shape[1] if self.n_features_ != n_features: raise ValueError( "Number of features of the model must match the input." " Model n_features is %s and input n_features is %s " % (self.n_features_, n_features)) return X
def check_truediv(Poly): # true division is valid only if the denominator is a Number and # not a python bool. p1 = Poly([1,2,3]) p2 = p1 * 5 for stype in np.ScalarType: if not issubclass(stype, Number) or issubclass(stype, bool): continue s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for stype in (int, long, float): s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for stype in [complex]: s = stype(5, 0) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for s in [tuple(), list(), dict(), bool(), np.array([1])]: assert_raises(TypeError, op.truediv, p2, s) assert_raises(TypeError, op.truediv, s, p2) for ptype in classes: assert_raises(TypeError, op.truediv, p2, ptype(1))
def _format_stats(self, stats): postfix = OrderedDict(stats) # Preprocess stats according to datatype for key in postfix.keys(): # Number: limit the length of the string if isinstance(postfix[key], Number): postfix[key] = '{:g}'.format(postfix[key]) # Meter: display both current and average value elif isinstance(postfix[key], AverageMeter): postfix[key] = '{:.2f} ({:.2f})'.format( postfix[key].val, postfix[key].avg) # Else for any other type, try to get the string conversion elif not isinstance(postfix[key], str): postfix[key] = str(postfix[key]) # Else if it's a string, don't need to preprocess anything return postfix
def _document(self, section, value, comments, path, shape): """ :param section: The section to add the docs to. :param value: The input / output values representing the parameters that are included in the example. :param comments: The dictionary containing all the comments to be applied to the example. :param path: A list describing where the documenter is in traversing the parameters. This is used to find the equivalent location in the comments dictionary. """ if isinstance(value, dict): self._document_dict(section, value, comments, path, shape) elif isinstance(value, list): self._document_list(section, value, comments, path, shape) elif isinstance(value, numbers.Number): self._document_number(section, value, path) elif shape and shape.type_name == 'timestamp': self._document_datetime(section, value, path) else: self._document_str(section, value, path)
def transform_pt_obj_to_grid(self, x_sdf, direction = False): """ Converts a point in sdf coords to the grid basis. If direction then don't translate. Parameters ---------- x_sdf : numpy 3xN ndarray or numeric scalar points to transform from sdf basis in meters to grid basis Returns ------- x_grid : numpy 3xN ndarray or scalar points in grid basis """ if isinstance(x_sdf, Number): return self.T_world_grid_.scale * x_sdf if direction: points_sdf = NormalCloud(x_sdf.astype(np.float32), frame='world') else: points_sdf = PointCloud(x_sdf.astype(np.float32), frame='world') x_grid = self.T_world_grid_ * points_sdf return x_grid.data
def transform_pt_grid_to_obj(self, x_grid, direction = False): """ Converts a point in grid coords to the world basis. If direction then don't translate. Parameters ---------- x_grid : numpy 3xN ndarray or numeric scalar points to transform from grid basis to sdf basis in meters Returns ------- x_sdf : numpy 3xN ndarray points in sdf basis (meters) """ if isinstance(x_grid, Number): return self.T_grid_world_.scale * x_grid if direction: points_grid = NormalCloud(x_grid.astype(np.float32), frame='grid') else: points_grid = PointCloud(x_grid.astype(np.float32), frame='grid') x_sdf = self.T_grid_world_ * points_grid return x_sdf.data
def __init__(self, method, path, expected_code, actual_code): self.method = method self.path = path self.expected_code = expected_code self.actual_code = actual_code operation_name = self._OPERATIONS[method] self.reason = 'Failed to {operation_name} "{path}"'.format(**locals()) expected_codes = (expected_code,) if isinstance(expected_code, Number) else expected_code expected_codes_str = ", ".join('{0} {1}'.format(code, codestr(code)) for code in expected_codes) actual_code_str = codestr(actual_code) msg = '''\ {self.reason}. Operation : {method} {path} Expected code : {expected_codes_str} Actual code : {actual_code} {actual_code_str}'''.format(**locals()) super(OperationFailed, self).__init__(msg)
def __mul__(self, other): """ Scalar and Hamilton quaternion product. The multiplication with a scalar returns the quaternion with all elements multiplied by the scalar. The multiplication with a quaternion returns the Hamilton product. """ if isinstance(other, Quaternion): x = (self.w * other.x + self.x * other.w + self.y * other.z - self.z * other.y) y = (self.w * other.y - self.x * other.z + self.y * other.w + self.z * other.x) z = (self.w * other.z + self.x * other.y - self.y * other.x + self.z * other.w) w = (self.w * other.w - self.x * other.x - self.y * other.y - self.z * other.z) return Quaternion(x, y, z, w) elif isinstance(other, Number): q = self.q.copy() q_out = q * np.float64(other) return Quaternion(q=q_out) else: assert False, "Multiplication is only defined for scalars or quaternions."
def __truediv__(self, other): """ Quaternion division with either scalars or quaternions. The division with a scalar returns the quaternion with all elements divided by the scalar. The division with a quaternion returns q = q1 / q2 = q1 * q2^-1. """ if isinstance(other, Quaternion): return self * other.inverse() elif isinstance(other, Number): q = self.q.copy() q_out = q / np.float64(other) return Quaternion(q=q_out) else: assert False, "Division is only defined for scalars or quaternions."
def __mul__(self, other): """ Dual quaternion multiplication. The multiplication with a scalar returns the dual quaternion with all elements multiplied by the scalar. The multiplication of two dual quaternions dq1 and dq2 as: q1_rot * q2_rot + epsilon * (q1_rot * q2_trans + q1_trans * q2_rot), where dq1 and dq2 are defined as: dq1 = q1_rot + epsilon * q1_trans, dq2 = q2_rot + epsilon * q2_trans. """ if isinstance(other, DualQuaternion): rotational_part = self.q_rot * other.q_rot translational_part = (self.q_rot * other.q_dual + self.q_dual * other.q_rot) return DualQuaternion(rotational_part.copy(), translational_part.copy()) elif isinstance(other, Number): dq = self.dq.copy() dq_out = dq * np.float64(other) return DualQuaternion.from_vector(dq_out) else: assert False, ("Multiplication is only defined for scalars or dual " "quaternions.")
def __truediv__(self, other): """ Quaternion division with either scalars or quaternions. The division with a scalar returns the dual quaternion with all translational elements divided by the scalar. The division with a dual quaternion returns dq = dq1/dq2 = dq1 * dq2^-1, hence other divides on the right. """ # TODO(ff): Check if this is correct. print("WARNING: This might not be properly implemented.") if isinstance(other, DualQuaternion): return self * other.inverse() elif isinstance(other, Number): dq = self.dq.copy() dq_out = dq / np.float64(other) return DualQuaternion.from_vector(dq_out) else: assert False, "Division is only defined for scalars or dual quaternions."
def add(self, data): assert isinstance(data, numbers.Number) if self.last_update is None: self._avg = data self.last_update = time.time() self.last_data_decay = 1 else: now = time.time() delta = now - self.last_update if delta < 0: # Time is allowed to go a little backwards (NTP update, etc) logger.warn("Backwards delta value: {}".format(delta)) # Treat this entry as if it happened with 0 delta delta = 0 if delta != 0: self.last_data_decay = (1 - self.decay**delta) * 1/delta self._avg = self.decay**delta * self._avg + self.last_data_decay * data else: # Don't divide by zero; just reuse the last delta. Should stack well self._avg += self.last_data_decay * data self.last_update = now
def rotate(self, theta, point=None, axis=None): """Rotates the point theta radians around the axis defined by the given point and axis.""" if not isinstance(theta, Number): raise TypeError("theta must be scalar.") if point is None: center = np.zeros(self.dim) elif isinstance(point, Point): center = point._x else: raise TypeError("center of rotation must be Point.") if axis is not None: raise NotImplementedError("Rotation about axis besides [0 0 1] are" " not implemented.") # shift rotation center to origin self._x -= center # do rotation R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) self._x = np.dot(R, self._x) # shift rotation center back self._x += center
def __init__(self, callbacks={}, strict_parsing=False, max_size=float('inf')): super(QuerystringParser, self).__init__() self.state = STATE_BEFORE_FIELD self._found_sep = False self.callbacks = callbacks # Max-size stuff if not isinstance(max_size, Number) or max_size < 1: raise ValueError("max_size must be a positive number, not %r" % max_size) self.max_size = max_size self._current_size = 0 # Should parsing be strict? self.strict_parsing = strict_parsing
def __ne__(self, other): """ Construct a Filter returning True for asset/date pairs where the output of ``self`` matches ``other. """ if isinstance(other, Number) != (self.dtype == int64_dtype): raise InvalidClassifierComparison(self, other) if isinstance(other, Number): return NumExprFilter.create( "((x_0 != {other}) & (x_0 != {missing}))".format( other=int(other), missing=self.missing_value, ), binds=(self,), ) else: # Numexpr doesn't know how to use LabelArrays. return ArrayPredicate(term=self, op=operator.ne, opargs=(other,))
def quantiles(self, bins, mask=NotSpecified): """ Construct a Classifier computing quantiles of the output of ``self``. Every non-NaN data point the output is labelled with an integer value from 0 to (bins - 1). NaNs are labelled with -1. If ``mask`` is supplied, ignore data points in locations for which ``mask`` produces False, and emit a label of -1 at those locations. Parameters ---------- bins : int Number of bins labels to compute. mask : catalyst.pipeline.Filter, optional Mask of values to ignore when computing quantiles. Returns ------- quantiles : catalyst.pipeline.classifiers.Quantiles A Classifier producing integer labels ranging from 0 to (bins - 1). """ if mask is NotSpecified: mask = self.mask return Quantiles(inputs=(self,), bins=bins, mask=mask)
def top(self, N, mask=NotSpecified, groupby=NotSpecified): """ Construct a Filter matching the top N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the top N asset values for each group. Parameters ---------- N : int Number of assets passing the returned filter each day. mask : catalyst.pipeline.Filter, optional A Filter representing assets to consider when computing ranks. If mask is supplied, top values are computed ignoring any asset/date pairs for which `mask` produces a value of False. groupby : catalyst.pipeline.Classifier, optional A classifier defining partitions over which to perform ranking. Returns ------- filter : catalyst.pipeline.filters.Filter """ return self.rank(ascending=False, mask=mask, groupby=groupby) <= N