Python operator.neg() Examples

The following are 30 code examples of operator.neg(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module operator , or try the search function .
Example #1
Source File: base.py    From recruit with Apache License 2.0 7 votes vote down vote up
def _add_numeric_methods_unary(cls):
        """
        Add in numeric unary methods.
        """
        def _make_evaluate_unary(op, opstr):

            def _evaluate_numeric_unary(self):

                self._validate_for_numeric_unaryop(op, opstr)
                attrs = self._get_attributes_dict()
                attrs = self._maybe_update_attributes(attrs)
                return Index(op(self.values), **attrs)

            _evaluate_numeric_unary.__name__ = opstr
            return _evaluate_numeric_unary

        cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__')
        cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__')
        cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__')
        cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__') 
Example #2
Source File: base.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _add_numeric_methods_unary(cls):
        """
        Add in numeric unary methods.
        """
        def _make_evaluate_unary(op, opstr):

            def _evaluate_numeric_unary(self):

                self._validate_for_numeric_unaryop(op, opstr)
                attrs = self._get_attributes_dict()
                attrs = self._maybe_update_attributes(attrs)
                return Index(op(self.values), **attrs)

            _evaluate_numeric_unary.__name__ = opstr
            return _evaluate_numeric_unary

        cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__')
        cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__')
        cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__')
        cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__') 
Example #3
Source File: base.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _add_numeric_methods_unary(cls):
        """ add in numeric unary methods """

        def _make_evaluate_unary(op, opstr):

            def _evaluate_numeric_unary(self):

                self._validate_for_numeric_unaryop(op, opstr)
                attrs = self._get_attributes_dict()
                attrs = self._maybe_update_attributes(attrs)
                return Index(op(self.values), **attrs)

            return _evaluate_numeric_unary

        cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__')
        cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__')
        cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__')
        cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__') 
Example #4
Source File: test_scalarmath.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_exceptions(self):
        a = np.ones((), dtype=np.bool_)[()]
        assert_raises(TypeError, operator.neg, a) 
Example #5
Source File: test_scalarmath.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_result(self):
        types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning)
            for dt in types:
                a = np.ones((), dtype=dt)[()]
                assert_equal(operator.neg(a) + a, 0) 
Example #6
Source File: test_scalarmath.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_result(self):
        types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning)
            for dt in types:
                a = np.ones((), dtype=dt)[()]
                assert_equal(operator.neg(a) + a, 0) 
Example #7
Source File: vec2d.py    From omnitool with MIT License 5 votes vote down vote up
def __neg__(self):
        return Vec2d(operator.neg(self.x), operator.neg(self.y)) 
Example #8
Source File: test_scalarmath.py    From pySINDy with MIT License 5 votes vote down vote up
def test_exceptions(self):
        a = np.ones((), dtype=np.bool_)[()]
        assert_raises(TypeError, operator.neg, a) 
Example #9
Source File: test_quantity.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
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)) 
Example #10
Source File: gnumpy.py    From DeepNeuralNet-QSAR with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #11
Source File: test_util.py    From go2mapillary with GNU General Public License v3.0 5 votes vote down vote up
def __neg__(self):
    return NonStandardInteger(operator.neg(self.val)) 
Example #12
Source File: recipe-52275.py    From code with MIT License 5 votes vote down vote up
def __neg__(self):
		return sparse(zip(self.keys(), map(operator.neg, self.values()))) 
Example #13
Source File: test_itertools.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #14
Source File: test_util.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __neg__(self):
    return NonStandardInteger(operator.neg(self.val)) 
Example #15
Source File: myhdlpeek.py    From myhdlpeek with MIT License 5 votes vote down vote up
def __neg__(self):
        return self.apply_op1(operator.neg) 
Example #16
Source File: test_scalarmath.py    From pySINDy with MIT License 5 votes vote down vote up
def test_result(self):
        types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning)
            for dt in types:
                a = np.ones((), dtype=dt)[()]
                assert_equal(operator.neg(a) + a, 0) 
Example #17
Source File: test_scalarmath.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_exceptions(self):
        a = np.ones((), dtype=np.bool_)[()]
        assert_raises(TypeError, operator.neg, a) 
Example #18
Source File: test_mixins.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_unary_methods(self):
        array = np.array([-1, 0, 1, 2])
        array_like = ArrayLike(array)
        for op in [operator.neg,
                   operator.pos,
                   abs,
                   operator.invert]:
            _assert_equal_type_and_value(op(array_like), ArrayLike(op(array))) 
Example #19
Source File: test_builtins.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
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]) 
Example #20
Source File: test_builtins.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
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]) 
Example #21
Source File: test_builtins.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
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]) 
Example #22
Source File: UserLong.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __neg__(self):
        return self._uop(operator.neg) 
Example #23
Source File: UserInt.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __neg__(self):
        return self._uop(operator.neg) 
Example #24
Source File: UserFloat.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __neg__(self):
        return self._uop(operator.neg) 
Example #25
Source File: dataset.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __neg__(self):
        return self._un_op(operator.neg) 
Example #26
Source File: test_expr.py    From altair with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unary_operations():
    OP_MAP = {"-": operator.neg, "+": operator.pos}
    for op, func in OP_MAP.items():
        z = func(datum.xxx)
        assert repr(z) == "({}datum.xxx)".format(op) 
Example #27
Source File: test_scalarmath.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_result(self):
        types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning)
            for dt in types:
                a = np.ones((), dtype=dt)[()]
                assert_equal(operator.neg(a) + a, 0) 
Example #28
Source File: test_Signal.py    From myhdl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def testNeg(self):
        self.unaryCheck(operator.neg) 
Example #29
Source File: test_mixins.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_unary_methods(self):
        array = np.array([-1, 0, 1, 2])
        array_like = ArrayLike(array)
        for op in [operator.neg,
                   operator.pos,
                   abs,
                   operator.invert]:
            _assert_equal_type_and_value(op(array_like), ArrayLike(op(array))) 
Example #30
Source File: window.py    From ibis with Apache License 2.0 5 votes vote down vote up
def execute_series_lead_lag(op, data, offset, default, **kwargs):
    func = toolz.identity if isinstance(op, ops.Lag) else operator.neg
    result = data.shift(func(1 if offset is None else offset))
    return post_lead_lag(result, default)