python类Number()的实例源码

Image.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
test_classes.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
progress_bar.py 文件源码 项目:ParlAI 作者: facebookresearch 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
sharedexample.py 文件源码 项目:aws-cfn-plex 作者: lordmuffin 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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)
sharedexample.py 文件源码 项目:AshsSDK 作者: thehappydinoa 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
sdf.py 文件源码 项目:meshpy 作者: BerkeleyAutomation 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
sdf.py 文件源码 项目:meshpy 作者: BerkeleyAutomation 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
easywebdav.py 文件源码 项目:Quantrade 作者: quant-trade 项目源码 文件源码 阅读 120 收藏 0 点赞 0 评论 0
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)
quaternion.py 文件源码 项目:hand_eye_calibration 作者: ethz-asl 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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."
quaternion.py 文件源码 项目:hand_eye_calibration 作者: ethz-asl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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."
dual_quaternion.py 文件源码 项目:hand_eye_calibration 作者: ethz-asl 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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.")
dual_quaternion.py 文件源码 项目:hand_eye_calibration 作者: ethz-asl 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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."
__init__.py 文件源码 项目:universe 作者: openai 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
geometry.py 文件源码 项目:xdesign 作者: tomography 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
multipart.py 文件源码 项目:jumpscale_portal 作者: jumpscale7 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
expression.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
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
classifier.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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,))
factor.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
factor.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
factor.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号