我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.truediv()。
def test_division_with_scalar(self, input_tuple, expected): self.ureg.default_as_delta = False in1, in2 = input_tuple if type(in1) is tuple: in1, in2 = self.Q_(*in1), in2 else: in1, in2 = in1, self.Q_(*in2) input_tuple = in1, in2 # update input_tuple for better tracebacks expected_copy = expected[:] for i, mode in enumerate([False, True]): self.ureg.autoconvert_offset_to_baseunit = mode if expected_copy[i] == 'error': self.assertRaises(OffsetUnitCalculusError, op.truediv, in1, in2) else: expected = self.Q_(*expected_copy[i]) self.assertEqual(op.truediv(in1, in2).units, expected.units) self.assertQuantityAlmostEqual(op.truediv(in1, in2), expected)
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 operate(self, left, right, operation): """ Do operation on colors args: left (str): left side right (str): right side operation (str): Operation returns: str """ operation = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv }.get(operation) return operation(left, right)
def post(self, request): if not request.user.is_authenticated(): return self.json_error({ 'message': _('Authentication required'), }, status=401) request.user.avatar.delete() return self.json_response({ 'micro_avatar': request.user.micro_avatar, 'small_avatar': request.user.small_avatar, 'normal_avatar': request.user.normal_avatar, 'profile_avatar_html': self.render_to_string('users/profile_avatar.html', { 'profile_user': request.user, 'aspect': truediv(*request.user.avatar.variations.normal.size), 'min_dimensions': 'x'.join(request.user.avatar.variations.normal.size), }) })
def format_aspects(value, variations): """ ?????????????? ???????? """ result = [] aspects = value if isinstance(value, tuple) else (value,) for aspect in aspects: try: aspect = float(aspect) except (TypeError, ValueError): if aspect not in variations: continue size = variations[aspect]['size'] if all(d > 0 for d in size): aspect = operator.truediv(*size) else: continue result.append(str(round(aspect, 4))) return tuple(result)
def test_division(self): t = timedelta(hours=1, minutes=24, seconds=19) second = timedelta(seconds=1) self.assertEqual(t / second, 5059.0) self.assertEqual(t // second, 5059) t = timedelta(minutes=2, seconds=30) minute = timedelta(minutes=1) self.assertEqual(t / minute, 2.5) self.assertEqual(t // minute, 2) zerotd = timedelta(0) self.assertRaises(ZeroDivisionError, truediv, t, zerotd) self.assertRaises(ZeroDivisionError, floordiv, t, zerotd) # self.assertRaises(TypeError, truediv, t, 2) # note: floor division of a timedelta by an integer *is* # currently permitted.
def normalize(timeSeries,nfFactor) : if isinstance(timeSeries[0],(int,float)) == True : nFeatures = 1 else : nFeatures = len(timeSeries[0]) assert len(nfFactor) == nFeatures nSamples = len(timeSeries) normalizedTimeSeries = [] for i in xrange(0,nFeatures) : if nfFactor[i] == 0.0 : nfFactor[i] = 1.0 for i in xrange(0,nSamples): if isinstance(timeSeries[0],(int,float)) == True : normalizedTimeSeries.append(float(timeSeries[i])/float(nfFactor[0])) else : normalizedTimeSeries.append(map(truediv,timeSeries[i],nfFactor)) return np.array(normalizedTimeSeries)
def __init__(self, code, objects=None): self._OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] self._ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in self._OPERATORS] self._ASSIGN_OPERATORS.append(('=', lambda cur, right: right)) self._VARNAME_PATTERN = r'[a-zA-Z_$][a-zA-Z_$0-9]*' if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects
def number_of_args(fn): """Return the number of positional arguments for a function, or None if the number is variable. Looks inside any decorated functions.""" try: if hasattr(fn, '__wrapped__'): return number_of_args(fn.__wrapped__) if any(p.kind == p.VAR_POSITIONAL for p in signature(fn).parameters.values()): return None else: return sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in signature(fn).parameters.values()) except ValueError: # signatures don't work for built-in operators, so check for a few explicitly UNARY_OPS = [len, op.not_, op.truth, op.abs, op.index, op.inv, op.invert, op.neg, op.pos] BINARY_OPS = [op.lt, op.le, op.gt, op.ge, op.eq, op.ne, op.is_, op.is_not, op.add, op.and_, op.floordiv, op.lshift, op.mod, op.mul, op.or_, op.pow, op.rshift, op.sub, op.truediv, op.xor, op.concat, op.contains, op.countOf, op.delitem, op.getitem, op.indexOf] TERNARY_OPS = [op.setitem] if fn in UNARY_OPS: return 1 elif fn in BINARY_OPS: return 2 elif fn in TERNARY_OPS: return 3 else: raise NotImplementedError("Bult-in operator {} not supported".format(fn))
def __call__(self, env): """Recursively evaluate an expression in Python space. Parameters ---------- env : Scope Returns ------- object The result of an evaluated expression. """ # handle truediv if self.op == '/' and env.scope['truediv']: self.func = op.truediv # recurse over the left/right nodes left = self.lhs(env) right = self.rhs(env) return self.func(left, right)
def test_binops(self): ops = [operator.add, operator.sub, operator.mul, operator.floordiv, operator.truediv, pow] scalars = [-1, 1, 2] idxs = [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2), RangeIndex(-10, 10, 2), RangeIndex(5, -5, -1)] for op in ops: for a, b in combinations(idxs, 2): result = op(a, b) expected = op(Int64Index(a), Int64Index(b)) tm.assert_index_equal(result, expected) for idx in idxs: for scalar in scalars: result = op(idx, scalar) expected = op(Int64Index(idx), scalar) tm.assert_index_equal(result, expected)
def test_arith(self): self._test_op(self.panel, operator.add) self._test_op(self.panel, operator.sub) self._test_op(self.panel, operator.mul) self._test_op(self.panel, operator.truediv) self._test_op(self.panel, operator.floordiv) self._test_op(self.panel, operator.pow) self._test_op(self.panel, lambda x, y: y + x) self._test_op(self.panel, lambda x, y: y - x) self._test_op(self.panel, lambda x, y: y * x) self._test_op(self.panel, lambda x, y: y / x) self._test_op(self.panel, lambda x, y: y ** x) self._test_op(self.panel, lambda x, y: x + y) # panel + 1 self._test_op(self.panel, lambda x, y: x - y) # panel - 1 self._test_op(self.panel, lambda x, y: x * y) # panel * 1 self._test_op(self.panel, lambda x, y: x / y) # panel / 1 self._test_op(self.panel, lambda x, y: x ** y) # panel ** 1 self.assertRaises(Exception, self.panel.__add__, self.panel['ItemA'])
def test_arith_flex_panel(self): ops = ['add', 'sub', 'mul', 'div', 'truediv', 'pow', 'floordiv', 'mod'] if not compat.PY3: aliases = {} else: aliases = {'div': 'truediv'} self.panel = self.panel.to_panel() for n in [np.random.randint(-50, -1), np.random.randint(1, 50), 0]: for op in ops: alias = aliases.get(op, op) f = getattr(operator, alias) exp = f(self.panel, n) result = getattr(self.panel, op)(n) assert_panel_equal(result, exp, check_panel_type=True) # rops r_f = lambda x, y: f(y, x) exp = r_f(self.panel, n) result = getattr(self.panel, 'r' + op)(n) assert_panel_equal(result, exp)
def test_operators_none_as_na(self): df = DataFrame({"col1": [2, 5.0, 123, None], "col2": [1, 2, 3, 4]}, dtype=object) ops = [operator.add, operator.sub, operator.mul, operator.truediv] # since filling converts dtypes from object, changed expected to be # object for op in ops: filled = df.fillna(np.nan) result = op(df, 3) expected = op(filled, 3).astype(object) expected[com.isnull(expected)] = None assert_frame_equal(result, expected) result = op(df, df) expected = op(filled, filled).astype(object) expected[com.isnull(expected)] = None assert_frame_equal(result, expected) result = op(df, df.fillna(7)) assert_frame_equal(result, expected) result = op(df.fillna(7), df) assert_frame_equal(result, expected, check_dtype=False)
def test_arith_getitem_commute(self): df = DataFrame({'A': [1.1, 3.3], 'B': [2.5, -3.9]}) self._test_op(df, operator.add) self._test_op(df, operator.sub) self._test_op(df, operator.mul) self._test_op(df, operator.truediv) self._test_op(df, operator.floordiv) self._test_op(df, operator.pow) self._test_op(df, lambda x, y: y + x) self._test_op(df, lambda x, y: y - x) self._test_op(df, lambda x, y: y * x) self._test_op(df, lambda x, y: y / x) self._test_op(df, lambda x, y: y ** x) self._test_op(df, lambda x, y: x + y) self._test_op(df, lambda x, y: x - y) self._test_op(df, lambda x, y: x * y) self._test_op(df, lambda x, y: x / y) self._test_op(df, lambda x, y: x ** y)
def test_binary_operators(self): # skipping for now ##### raise nose.SkipTest("skipping sparse binary operators test") def _check_inplace_op(iop, op): tmp = self.bseries.copy() expected = op(tmp, self.bseries) iop(tmp, self.bseries) assert_sp_series_equal(tmp, expected) inplace_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'pow'] for op in inplace_ops: _check_inplace_op(getattr(operator, "i%s" % op), getattr(operator, op))
def get_default_operators(): """ generate a mapping of default operators allowed for evaluation """ return { 'u-': Func(1, operator.neg), # unary negation 'u%': Func(1, lambda a: a / Decimal(100)), # unary percentage '&': Func(2, operator.concat), '^': Func(2, operator.pow), '+': Func(2, op_add), '-': Func(2, operator.sub), '/': Func(2, operator.truediv), '*': Func(2, operator.mul), '=': Func(2, operator.eq), '<>': Func(2, lambda a, b: not operator.eq(a, b)), '>': Func(2, operator.gt), '<': Func(2, operator.lt), '>=': Func(2, operator.ge), '<=': Func(2, operator.le), }
def divide(dividend, divisor): """Divide two numbers. Args: dividend (int/float): The first number in a division. divisor (int/float): The second number in a division. Returns: int/float: Returns the quotient. Example: >>> divide(20, 5) 4.0 >>> divide(1.5, 3) 0.5 >>> divide(None, None) 1.0 >>> divide(5, None) 5.0 .. versionadded:: 4.0.0 """ return call_math_operator(dividend, divisor, operator.truediv, 1)
def eval_expr(expr): import ast import operator as op op = { ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor, ast.USub: op.neg, } def eval_(node): if isinstance(node, ast.Num): return fractions.Fraction(node.n) elif isinstance(node, ast.BinOp): return op[type(node.op)](eval_(node.left), eval_(node.right)) elif isinstance(node, ast.UnaryOp): return op[type(node.op)](eval_(node.operand)) raise TypeError(node) return eval_(ast.parse(str(expr), mode='eval').body)
def divide(lhs, rhs): """ Perform element-wise divide Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, NDArray._div, operator.truediv, NDArray._div_scalar, NDArray._rdiv_scalar) # pylint: enable= no-member, protected-access
def test_walk_up(): raw = Stream() a_translation = FromEventStream(raw, 'start', ('time',)) b_translation = FromEventStream(raw, 'event', ('data', 'pe1_image')) d = b_translation.zip_latest(a_translation) dd = d.map(op.truediv) e = ToEventStream(dd, ('data',)) g = nx.DiGraph() walk_up(e, g) att = [] for node, attrs in g.node.items(): att.append(attrs['stream']) s = {a_translation, b_translation, d, dd, e} assert s == set(att) assert {hash(k) for k in s} == set(g.nodes)
def divide(lhs, rhs): """ Perform element-wise divide Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._div, operator.truediv, _internal._div_scalar, _internal._rdiv_scalar) # pylint: enable= no-member, protected-access
def __truediv__(self, trc): return self.apply_op2(trc, operator.truediv)
def __itruediv__(self, other): if not isinstance(self._magnitude, ndarray): return self._mul_div(other, operator.truediv) else: return self._imul_div(other, operator.itruediv)
def __truediv__(self, other): return self._mul_div(other, operator.truediv)
def test_unitcontainer_arithmetic(self): x = UnitsContainer(meter=1) y = UnitsContainer(second=1) z = UnitsContainer(meter=1, second=-2) self._test_not_inplace(op.mul, x, y, UnitsContainer(meter=1, second=1)) self._test_not_inplace(op.truediv, x, y, UnitsContainer(meter=1, second=-1)) self._test_not_inplace(op.pow, z, 2, UnitsContainer(meter=2, second=-4)) self._test_not_inplace(op.pow, z, -2, UnitsContainer(meter=-2, second=4)) self._test_inplace(op.imul, x, y, UnitsContainer(meter=1, second=1)) self._test_inplace(op.itruediv, x, y, UnitsContainer(meter=1, second=-1)) self._test_inplace(op.ipow, z, 2, UnitsContainer(meter=2, second=-4)) self._test_inplace(op.ipow, z, -2, UnitsContainer(meter=-2, second=4))
def test_issue52(self): u1 = UnitRegistry() u2 = UnitRegistry() q1 = 1*u1.meter q2 = 1*u2.meter import operator as op for fun in (op.add, op.iadd, op.sub, op.isub, op.mul, op.imul, op.floordiv, op.ifloordiv, op.truediv, op.itruediv): self.assertRaises(ValueError, fun, q1, q2)
def _test_quantity_mul_div(self, unit, func): func(op.mul, unit * 10.0, '4.2*meter', '42*meter', unit) func(op.mul, '4.2*meter', unit * 10.0, '42*meter', unit) func(op.mul, '4.2*meter', '10*inch', '42*meter*inch', unit) func(op.truediv, unit * 42, '4.2*meter', '10/meter', unit) func(op.truediv, '4.2*meter', unit * 10.0, '0.42*meter', unit) func(op.truediv, '4.2*meter', '10*inch', '0.42*meter/inch', unit)
def test_truedivision(self, input_tuple, expected): self.ureg.autoconvert_offset_to_baseunit = False qin1, qin2 = input_tuple q1, q2 = self.Q_(*qin1), self.Q_(*qin2) input_tuple = q1, q2 if expected == 'error': self.assertRaises(OffsetUnitCalculusError, op.truediv, q1, q2) else: expected = self.Q_(*expected) self.assertEqual(op.truediv(q1, q2).units, expected.units) self.assertQuantityAlmostEqual(op.truediv(q1, q2), expected, atol=0.01)
def __truediv__(self, other): fieldop = FieldOp(operator.truediv, self, other) return R(fieldop)
def test_truediv_scalar(self): with testing.NumpyError(divide='ignore'): self.check_array_scalar_op(operator.truediv)
def test_rtruediv_scalar(self): with testing.NumpyError(divide='ignore'): self.check_array_scalar_op(operator.truediv, swap=True)
def test_truediv_array(self): with testing.NumpyError(divide='ignore'): self.check_array_array_op(operator.truediv)
def test_broadcasted_truediv(self): with testing.NumpyError(divide='ignore'): self.check_array_broadcasted_op(operator.truediv)
def test_doubly_broadcasted_truediv(self): with testing.NumpyError(divide='ignore', invalid='ignore'): self.check_array_doubly_broadcasted_op(operator.truediv)
def operate(self, vala, valb, oper): """Perform operation args: vala (mixed): 1st value valb (mixed): 2nd value oper (str): operation returns: mixed """ operation = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, '=': operator.eq, '>': operator.gt, '<': operator.lt, '>=': operator.ge, '=<': operator.le, }.get(oper) if operation is None: raise SyntaxError("Unknown operation %s" % oper) ret = operation(vala, valb) if oper in '+-*/' and int(ret) == ret: ret = int(ret) return ret
def __truediv__(self, other): return operator.truediv(self.__wrapped__, other)
def __rtruediv__(self, other): return operator.truediv(other, self.__wrapped__)
def evaluate(t): # Evaluate a expression tree oper = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv} left = t.get_left() right = t.get_right() if left and right: return oper[t.get_root()](evaluate(left),evaluate(right)) else: return t.get_root()