我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.neg()。
def mk_seconds(mg, **kwargs): rv = 0.0 secday = 86400 grps = mg.groupdict() if 'd' in grps and mg.group('d'): rv += float(mg.group('d'))*secday if 'h' in grps and mg.group('h'): rv += float(mg.group('h'))*3600.0 if 'm' in grps and mg.group('m'): rv += float(mg.group('m'))*60.0 if 's' in grps and mg.group('s'): rv += float(mg.group('s')) if 'offset' in grps and mg.group('offset'): rv += (int(mg.group('offset')) + (math.floor(float(kwargs.get('start', 0))/secday))) * secday if 'neg' in grps and mg.group('neg'): rv *= -1 return rv
def test_map(self): self.assertEqual(list(map(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) def tupleize(*args): return args self.assertEqual(list(map(tupleize, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(map(tupleize, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,map(tupleize, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(map(operator.pow, [])), []) self.assertRaises(TypeError, map) self.assertRaises(TypeError, list, map(None, range(3), range(3))) self.assertRaises(TypeError, map, operator.neg) self.assertRaises(TypeError, next, map(10, range(5))) self.assertRaises(ValueError, next, map(errfunc, [4], [5])) self.assertRaises(TypeError, next, map(onearg, [4], [5]))
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 _count_to_pvalue(island_enriched_threshold, average_window_readcount, df): # type: (int, float, pd.DataFrame) -> pd.DataFrame df = df.loc[df["ChIP"] >= island_enriched_threshold] scores = df["ChIP"].apply( lambda count: _poisson(count, average_window_readcount) + 0.000001) df.insert(len(df.columns), "Score", scores) pd.options.mode.chained_assignment = None df["Score"] = df["Score"].apply(log) df["Score"] = df["Score"].apply(minus) pd.options.mode.chained_assignment = "warn" return df
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 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 sort_metrics(cls, desc, metrics): """Order data series""" metas = desc['series'].get('metas') or [] if metas: key_builder = [] for meta in metas: if meta.startswith('-'): key_builder.append(compose( operator.neg, operator.itemgetter(meta[1:]) )) else: key_builder.append(operator.itemgetter(meta)) def _key_builder_func(metric): return [ getter(metric['metas']) for getter in key_builder ] metrics.sort(key=_key_builder_func) return metrics
def __neg__(self): return self.apply_op1(operator.neg)
def __neg__(self): return Vector(self._unaryOp(operator.neg), keep=True)
def __neg__(self): return self.__class__(operator.neg(self._magnitude), self._units)
def test_quantity_abs_round(self): x = self.Q_(-4.2, 'meter') y = self.Q_(4.2, 'meter') # In Python 3+ round of x is delegated to x.__round__, instead of round(x.__float__) # and therefore it can be properly implemented by Pint for fun in (abs, op.pos, op.neg) + (round, ) if PYTHON3 else (): zx = self.Q_(fun(x.magnitude), 'meter') zy = self.Q_(fun(y.magnitude), 'meter') rx = fun(x) ry = fun(y) self.assertEqual(rx, zx, 'while testing {0}'.format(fun)) self.assertEqual(ry, zy, 'while testing {0}'.format(fun)) self.assertIsNot(rx, zx, 'while testing {0}'.format(fun)) self.assertIsNot(ry, zy, 'while testing {0}'.format(fun))
def test_unary_minus_operator_deprecation(self): array = np.array([True]) generic = np.bool_(True) # Unary minus/negative ufunc: self.assert_deprecated(operator.neg, args=(array,)) self.assert_deprecated(operator.neg, args=(generic,))
def test_neg_array(self, xp, dtype): a = testing.shaped_arange((2, 3), xp, dtype) return operator.neg(a)
def test_neg_zerodim(self, xp, dtype): a = xp.array(-2, dtype) return operator.neg(a)
def test_neg(self): self.assertRaises(TypeError, operator.neg) self.assertRaises(TypeError, operator.neg, None) self.assertEqual(operator.neg(5), -5) self.assertEqual(operator.neg(-5), 5) self.assertEqual(operator.neg(0), 0) self.assertEqual(operator.neg(-0), 0)
def test_max(self): self.assertEqual(max('123123'), '3') self.assertEqual(max(1, 2, 3), 3) self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) self.assertEqual(max(1, 2, 3.0), 3.0) self.assertEqual(max(1, 2.0, 3), 3) self.assertEqual(max(1.0, 2, 3), 3) for stmt in ( "max(key=int)", # no args "max(1, key=int)", # single arg not iterable "max(1, 2, keystone=int)", # wrong keyword "max(1, 2, key=int, abc=int)", # two many keywords "max(1, 2, key=1)", # keyfunc is not callable ): try: exec(stmt, globals()) except TypeError: pass else: self.fail(stmt) self.assertEqual(max((1,), key=neg), 1) # one elem iterable self.assertEqual(max((1,2), key=neg), 1) # two elem iterable self.assertEqual(max(1, 2, key=neg), 1) # two elems data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(max(data, key=f), sorted(reversed(data), key=f)[-1])
def test_min(self): self.assertEqual(min('123123'), '1') self.assertEqual(min(1, 2, 3), 1) self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) self.assertEqual(min(1, 2, 3.0), 1) self.assertEqual(min(1, 2.0, 3), 1) self.assertEqual(min(1.0, 2, 3), 1.0) self.assertRaises(TypeError, min) self.assertRaises(TypeError, min, 42) self.assertRaises(ValueError, min, ()) class BadSeq: def __getitem__(self, index): raise ValueError self.assertRaises(ValueError, min, BadSeq()) for stmt in ( "min(key=int)", # no args "min(1, key=int)", # single arg not iterable "min(1, 2, keystone=int)", # wrong keyword "min(1, 2, key=int, abc=int)", # two many keywords "min(1, 2, key=1)", # keyfunc is not callable ): try: exec(stmt, globals()) except TypeError: pass else: self.fail(stmt) self.assertEqual(min((1,), key=neg), 1) # one elem iterable self.assertEqual(min((1,2), key=neg), 2) # two elem iterable self.assertEqual(min(1, 2, key=neg), 2) # two elems data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(min(data, key=f), sorted(data, key=f)[0])
def __neg__(self): return NonStandardInteger(operator.neg(self.val))
def test_registry_association(): ds = fake_random_ds(64, nprocs=1, length_unit=10) a = ds.quan(3, 'cm') b = YTQuantity(4, 'm') c = ds.quan(6, '') d = 5 assert_equal(id(a.units.registry), id(ds.unit_registry)) def binary_op_registry_comparison(op): e = op(a, b) f = op(b, a) g = op(c, d) h = op(d, c) assert_equal(id(e.units.registry), id(ds.unit_registry)) assert_equal(id(f.units.registry), id(b.units.registry)) assert_equal(id(g.units.registry), id(h.units.registry)) assert_equal(id(g.units.registry), id(ds.unit_registry)) def unary_op_registry_comparison(op): c = op(a) d = op(b) assert_equal(id(c.units.registry), id(ds.unit_registry)) assert_equal(id(d.units.registry), id(b.units.registry)) binary_ops = [operator.add, operator.sub, operator.mul, operator.truediv] if hasattr(operator, "div"): binary_ops.append(operator.div) for op in binary_ops: binary_op_registry_comparison(op) for op in [operator.abs, operator.neg, operator.pos]: unary_op_registry_comparison(op)
def test_neg(self): self.assertRaises(TypeError, operator.neg) self.assertRaises(TypeError, operator.neg, None) self.assertTrue(operator.neg(5) == -5) self.assertTrue(operator.neg(-5) == 5) self.assertTrue(operator.neg(0) == 0) self.assertTrue(operator.neg(-0) == 0)
def test_imap(self): self.assertEqual(list(imap(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) self.assertEqual(list(imap(None, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(imap(None, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,imap(None, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(imap(operator.pow, [])), []) self.assertRaises(TypeError, imap) self.assertRaises(TypeError, imap, operator.neg) self.assertRaises(TypeError, imap(10, range(5)).next) self.assertRaises(ValueError, imap(errfunc, [4], [5]).next) self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
def test_max(self): self.assertEqual(max('123123'), '3') self.assertEqual(max(1, 2, 3), 3) self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) self.assertEqual(max(1, 2L, 3.0), 3.0) self.assertEqual(max(1L, 2.0, 3), 3) self.assertEqual(max(1.0, 2, 3L), 3L) for stmt in ( "max(key=int)", # no args "max(1, key=int)", # single arg not iterable "max(1, 2, keystone=int)", # wrong keyword "max(1, 2, key=int, abc=int)", # two many keywords "max(1, 2, key=1)", # keyfunc is not callable ): try: exec(stmt) in globals() except TypeError: pass else: self.fail(stmt) self.assertEqual(max((1,), key=neg), 1) # one elem iterable self.assertEqual(max((1,2), key=neg), 1) # two elem iterable self.assertEqual(max(1, 2, key=neg), 1) # two elems data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(max(data, key=f), sorted(reversed(data), key=f)[-1])
def test_max(self): self.assertEqual(max('123123'), '3') self.assertEqual(max(1, 2, 3), 3) self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) self.assertEqual(max(1, 2, 3.0), 3.0) self.assertEqual(max(1, 2.0, 3), 3) self.assertEqual(max(1.0, 2, 3), 3) for stmt in ( "max(key=int)", # no args "max(1, key=int)", # single arg not iterable "max(1, 2, keystone=int)", # wrong keyword "max(1, 2, key=int, abc=int)", # two many keywords "max(1, 2, key=1)", # keyfunc is not callable ): try: exec_(stmt, globals()) except TypeError: pass else: self.fail(stmt) self.assertEqual(max((1,), key=neg), 1) # one elem iterable self.assertEqual(max((1,2), key=neg), 1) # two elem iterable self.assertEqual(max(1, 2, key=neg), 1) # two elems data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(max(data, key=f), sorted(reversed(data), key=f)[-1])
def test_min(self): self.assertEqual(min('123123'), '1') self.assertEqual(min(1, 2, 3), 1) self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) self.assertEqual(min(1, 2, 3.0), 1) self.assertEqual(min(1, 2.0, 3), 1) self.assertEqual(min(1.0, 2, 3), 1.0) self.assertRaises(TypeError, min) self.assertRaises(TypeError, min, 42) self.assertRaises(ValueError, min, ()) class BadSeq: def __getitem__(self, index): raise ValueError self.assertRaises(ValueError, min, BadSeq()) for stmt in ( "min(key=int)", # no args "min(1, key=int)", # single arg not iterable "min(1, 2, keystone=int)", # wrong keyword "min(1, 2, key=int, abc=int)", # two many keywords "min(1, 2, key=1)", # keyfunc is not callable ): try: exec_(stmt, globals()) except TypeError: pass else: self.fail(stmt) self.assertEqual(min((1,), key=neg), 1) # one elem iterable self.assertEqual(min((1,2), key=neg), 2) # two elem iterable self.assertEqual(min(1, 2, key=neg), 2) # two elems data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(min(data, key=f), sorted(data, key=f)[0])
def test_max(self): self.assertEqual(max('123123'), '3') self.assertEqual(max(1, 2, 3), 3) self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) self.assertEqual(max(1, 2, 3.0), 3.0) self.assertEqual(max(1, 2.0, 3), 3) self.assertEqual(max(1.0, 2, 3), 3) for stmt in ( "max(key=int)", # no args "max(1, key=int)", # single arg not iterable "max(1, 2, keystone=int)", # wrong keyword "max(1, 2, key=int, abc=int)", # two many keywords "max(1, 2, key=1)", # keyfunc is not callable ): try: exec(stmt) in globals() except TypeError: pass else: self.fail(stmt) self.assertEqual(max((1,), key=neg), 1) # one elem iterable self.assertEqual(max((1,2), key=neg), 1) # two elem iterable self.assertEqual(max(1, 2, key=neg), 1) # two elems data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(max(data, key=f), sorted(reversed(data), key=f)[-1])
def __neg__(self): return op.neg(self)
def test_neg_array(self): self.check_array_op(operator.neg)
def test_neg_zerodim(self): self.check_zerodim_op(operator.neg)
def setUp(self): super(CoreUnaryOpsTest, self).setUp() self.ops = [ ('abs', operator.abs, tf.abs, core.abs_function), ('neg', operator.neg, tf.neg, core.neg), # TODO(shoyer): add unary + to core TensorFlow ('pos', None, None, None), ('sign', None, tf.sign, core.sign), ('reciprocal', None, tf.reciprocal, core.reciprocal), ('square', None, tf.square, core.square), ('round', None, tf.round, core.round_function), ('sqrt', None, tf.sqrt, core.sqrt), ('rsqrt', None, tf.rsqrt, core.rsqrt), ('log', None, tf.log, core.log), ('exp', None, tf.exp, core.exp), ('log', None, tf.log, core.log), ('ceil', None, tf.ceil, core.ceil), ('floor', None, tf.floor, core.floor), ('cos', None, tf.cos, core.cos), ('sin', None, tf.sin, core.sin), ('tan', None, tf.tan, core.tan), ('acos', None, tf.acos, core.acos), ('asin', None, tf.asin, core.asin), ('atan', None, tf.atan, core.atan), ('lgamma', None, tf.lgamma, core.lgamma), ('digamma', None, tf.digamma, core.digamma), ('erf', None, tf.erf, core.erf), ('erfc', None, tf.erfc, core.erfc), ('lgamma', None, tf.lgamma, core.lgamma), ] total_size = np.prod([v.size for v in self.original_lt.axes.values()]) self.test_lt = core.LabeledTensor( tf.cast(self.original_lt, tf.float32) / total_size, self.original_lt.axes)
def test_map(self): self.assertEqual(list(map(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) self.assertEqual(list(map(tupleize, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(map(tupleize, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,map(tupleize, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(map(operator.pow, [])), []) self.assertRaises(TypeError, map) self.assertRaises(TypeError, list, map(None, range(3), range(3))) self.assertRaises(TypeError, map, operator.neg) self.assertRaises(TypeError, next, map(10, range(5))) self.assertRaises(ValueError, next, map(errfunc, [4], [5])) self.assertRaises(TypeError, next, map(onearg, [4], [5])) # check copy, deepcopy, pickle ans = [('a',0),('b',1),('c',2)] c = map(tupleize, 'abc', count()) self.assertEqual(list(copy.copy(c)), ans) c = map(tupleize, 'abc', count()) self.assertEqual(list(copy.deepcopy(c)), ans) c = map(tupleize, 'abc', count()) self.pickletest(c)
def __neg__(self): return Vec2d(operator.neg(self.x), operator.neg(self.y))
def __neg__(self): values = _values_from_object(self) if values.dtype == np.bool_: arr = operator.inv(values) else: arr = operator.neg(values) return self.__array_wrap__(arr)
def take(self, indices, axis=0, convert=True, is_copy=True): """ Analogous to ndarray.take Parameters ---------- indices : list / array of ints axis : int, default 0 convert : translate neg to pos indices (default) is_copy : mark the returned frame as a copy Returns ------- taken : type of caller """ self._consolidate_inplace() new_data = self._data.take(indices, axis=self._get_block_manager_axis(axis), convert=True, verify=True) result = self._constructor(new_data).__finalize__(self) # maybe set copy if we didn't actually change the index if is_copy: if not result._get_axis(axis).equals(self._get_axis(axis)): result._set_is_copy(self) return result
def negative(x): """ Like -x, except that a zero dimensional numpy array input results in a numpy array return value. This works on garrays, numpy arrays, and numbers, preserving type (though all numbers become floats). """ return _elementwise__base(x, operator.neg, operator.neg)
def all_fields(self, **kwargs): return [ self.build_help_field(), { 'type': 'unicode', 'required': True, 'key': 'operation', 'choices': 'add|Add,sub|Subtract,mul|Multiply,div|Divide,neg|Make Negative', 'help_text': 'The math operation to perform.' }, self.build_list_input_field() ]
def __neg__(self): return _op1(self, operator.neg)
def test_map(self): self.assertEqual(list(map(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) self.assertEqual(list(map(tupleize, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(map(tupleize, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,map(tupleize, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(map(operator.pow, [])), []) self.assertRaises(TypeError, map) self.assertRaises(TypeError, list, map(None, range(3), range(3))) self.assertRaises(TypeError, map, operator.neg) self.assertRaises(TypeError, next, map(10, range(5))) self.assertRaises(ValueError, next, map(errfunc, [4], [5])) self.assertRaises(TypeError, next, map(onearg, [4], [5])) # check copy, deepcopy, pickle ans = [('a',0),('b',1),('c',2)] c = map(tupleize, 'abc', count()) self.assertEqual(list(copy.copy(c)), ans) c = map(tupleize, 'abc', count()) self.assertEqual(list(copy.deepcopy(c)), ans) for proto in range(pickle.HIGHEST_PROTOCOL + 1): c = map(tupleize, 'abc', count()) self.pickletest(proto, c)