本文整理匯總了Python中operator.add方法的典型用法代碼示例。如果您正苦於以下問題:Python operator.add方法的具體用法?Python operator.add怎麽用?Python operator.add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類operator
的用法示例。
在下文中一共展示了operator.add方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: attach_grad
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def attach_grad(self, grad_req='write', stype=None):
"""Attach a gradient buffer to this NDArray, so that `backward`
can compute gradient with respect to it.
Parameters
----------
grad_req : {'write', 'add', 'null'}
How gradient will be accumulated.
- 'write': gradient will be overwritten on every backward.
- 'add': gradient will be added to existing value on every backward.
- 'null': do not compute gradient for this NDArray.
stype : str, optional
The storage type of the gradient array. Defaults to the same stype of this NDArray.
"""
from . import zeros as _zeros
if stype is not None:
grad = _zeros(self.shape, stype=stype)
else:
grad = op.zeros_like(self) # pylint: disable=undefined-variable
grad_req = _GRAD_REQ_MAP[grad_req]
check_call(_LIB.MXAutogradMarkVariables(
1, ctypes.pointer(self.handle),
ctypes.pointer(mx_uint(grad_req)),
ctypes.pointer(grad.handle)))
示例2: create_internal_feed
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def create_internal_feed(portfolio: 'Portfolio'):
base_symbol = portfolio.base_instrument.symbol
sources = []
for wallet in portfolio.wallets:
symbol = wallet.instrument.symbol
sources += [wallet.exchange]
sources += [create_wallet_source(wallet, include_worth=(symbol != base_symbol))]
worth_nodes = Condition(
lambda node: node.name.endswith(base_symbol + ":/total") or node.name.endswith("worth")
)(*sources)
net_worth = Reduce(func=operator.add)(worth_nodes).rename("net_worth")
sources += [net_worth]
feed = DataFeed(sources).attach(portfolio)
return feed
示例3: test_safe_binop
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def test_safe_binop():
# Test checked arithmetic routines
ops = [
(operator.add, 1),
(operator.sub, 2),
(operator.mul, 3)
]
with exc_iter(ops, INT64_VALUES, INT64_VALUES) as it:
for xop, a, b in it:
pyop, op = xop
c = pyop(a, b)
if not (INT64_MIN <= c <= INT64_MAX):
assert_raises(OverflowError, mt.extint_safe_binop, a, b, op)
else:
d = mt.extint_safe_binop(a, b, op)
if c != d:
# assert_equal is slow
assert_equal(d, c)
示例4: test_add
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def test_add(Poly):
# This checks commutation, not numerical correctness
c1 = list(random((4,)) + .5)
c2 = list(random((3,)) + .5)
p1 = Poly(c1)
p2 = Poly(c2)
p3 = p1 + p2
assert_poly_almost_equal(p2 + p1, p3)
assert_poly_almost_equal(p1 + c2, p3)
assert_poly_almost_equal(c2 + p1, p3)
assert_poly_almost_equal(p1 + tuple(c2), p3)
assert_poly_almost_equal(tuple(c2) + p1, p3)
assert_poly_almost_equal(p1 + np.array(c2), p3)
assert_poly_almost_equal(np.array(c2) + p1, p3)
assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1))
assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1))
if Poly is Polynomial:
assert_raises(TypeError, op.add, p1, Chebyshev([0]))
else:
assert_raises(TypeError, op.add, p1, Polynomial([0]))
示例5: apply_index
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def apply_index(self, i):
time = i.to_perioddelta('D')
# to_period rolls forward to next BDay; track and
# reduce n where it does when rolling forward
asper = i.to_period('B')
if not isinstance(asper._data, np.ndarray):
# unwrap PeriodIndex --> PeriodArray
asper = asper._data
if self.n > 0:
shifted = (i.to_perioddelta('B') - time).asi8 != 0
# Integer-array addition is deprecated, so we use
# _time_shift directly
roll = np.where(shifted, self.n - 1, self.n)
shifted = asper._addsub_int_array(roll, operator.add)
else:
# Integer addition is deprecated, so we use _time_shift directly
roll = self.n
shifted = asper._time_shift(roll)
result = shifted.to_timestamp() + time
return result
示例6: test_arith
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
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
pytest.raises(Exception, self.panel.__add__,
self.panel['ItemA'])
示例7: test_arith_flex_panel
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
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)
示例8: test_binary_operators
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def test_binary_operators(self):
# skipping for now #####
import pytest
pytest.skip("skipping sparse binary operators test")
def _check_inplace_op(iop, op):
tmp = self.bseries.copy()
expected = op(tmp, self.bseries)
iop(tmp, self.bseries)
tm.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))
示例9: __add__
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def __add__(self, other):
return add(self, other)
示例10: __add__
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def __add__(self, other):
"""x.__add__(y) <=> x+y <=> mx.nd.add(x, y) """
return add(self, other)
示例11: __iadd__
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def __iadd__(self, other):
"""x.__iadd__(y) <=> x+=y """
if not self.writable:
raise ValueError('trying to add to a readonly NDArray')
if isinstance(other, NDArray):
return op.broadcast_add(self, other, out=self)
elif isinstance(other, numeric_types):
return _internal._plus_scalar(self, float(other), out=self)
else:
raise TypeError('type %s not supported' % str(type(other)))
示例12: _transform_action_to_motor_command
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def _transform_action_to_motor_command(self, action):
"""Method to transform the one dimensional action to rotate bottom two legs.
Args:
action: A double between -1 and 1, where 0 means keep the legs parallel
to the body.
Returns:
actions: The angles for all motors.
Raises:
ValueError: The action dimension is not the same as the number of motors.
ValueError: The magnitude of actions is out of bounds.
"""
action = action[0]
# Scale the action from [-1 to 1] to [-range to +range] (angle in radians).
action *= RANGE_OF_LEG_MOTION
action_all_legs = [
math.pi, # Upper leg pointing up.
0,
0, # Bottom leg pointing down.
math.pi,
0, # Upper leg pointing up.
math.pi,
math.pi, # Bottom leg pointing down.
0
]
action_all_legs = [angle - 0.7 for angle in action_all_legs]
# Use the one dimensional action to rotate both bottom legs.
action_delta = [0, 0, -action, action, 0, 0, action, -action]
action_all_legs = map(add, action_all_legs, action_delta)
return action_all_legs
示例13: __init__
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def __init__(self, capacity):
super(SumSegmentTree, self).__init__(
capacity=capacity,
operation=operator.add,
neutral_element=0.0
)
示例14: __init__
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def __init__(self, operators=None, functions=None, names=None):
'''
Create the evaluator instance. Set up valid operators (+,-, etc)
functions (add, random, get_val, whatever) and names. '''
if not operators:
operators = DEFAULT_OPERATORS
if not functions:
functions = DEFAULT_FUNCTIONS
if not names:
names = DEFAULT_NAMES
self.operators = operators
self.functions = functions
self.names = names
示例15: ConcatToSizedBase
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import add [as 別名]
def ConcatToSizedBase(self, bases, extslist):
for base, basestr in zip(bases, self.bases):
for exts, extstr in zip(extslist, self.extslist):
bv = concat(base, *exts)
refstr = basestr + reduce(operator.add, extstr)
reflen = len(refstr)
ref = int(refstr, 2)
assert bv == ref
assert len(bv) == reflen