Python operator.eq() Examples

The following are 30 code examples of operator.eq(). 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: imshow_result.py    From SlowFast-Network-pytorch with MIT License 6 votes vote down vote up
def make_multi_lable(self,dic):
        for key in dic:
            pre=None
            #print("before:",dic[key])
            temp=[]
            for info in dic[key]:
                if pre==None:
                    pre=info
                    temp.append(info)
                elif operator.eq(info.bbox.tolist(),pre.bbox.tolist()):
                        temp[-1].img_class.append(info.img_class[0])
                        temp[-1].prob.append(info.prob[0])
                        #这是个陷坑
                        #dic[key].remove(info)
                else:
                    pre=info
                    temp.append(info)
            dic[key]=temp 
Example #2
Source File: test_operators.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_compare_frame(self):
        # GH#24282 check that Categorical.__cmp__(DataFrame) defers to frame
        data = ["a", "b", 2, "a"]
        cat = Categorical(data)

        df = DataFrame(cat)

        for op in [operator.eq, operator.ne, operator.ge,
                   operator.gt, operator.le, operator.lt]:
            with pytest.raises(ValueError):
                # alignment raises unless we transpose
                op(cat, df)

        result = cat == df.T
        expected = DataFrame([[True, True, True, True]])
        tm.assert_frame_equal(result, expected)

        result = cat[::-1] != df.T
        expected = DataFrame([[False, True, True, False]])
        tm.assert_frame_equal(result, expected) 
Example #3
Source File: __init__.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def get_op(cls, op):
        ops = {
            symbol.test: cls.test,
            symbol.and_test: cls.and_test,
            symbol.atom: cls.atom,
            symbol.comparison: cls.comparison,
            'not in': lambda x, y: x not in y,
            'in': lambda x, y: x in y,
            '==': operator.eq,
            '!=': operator.ne,
            '<':  operator.lt,
            '>':  operator.gt,
            '<=': operator.le,
            '>=': operator.ge,
        }
        if hasattr(symbol, 'or_test'):
            ops[symbol.or_test] = cls.test
        return ops[op] 
Example #4
Source File: AVA_video_v1.py    From SlowFast-Network-pytorch with MIT License 6 votes vote down vote up
def make_multi_lable(self,dic):
        for key in dic:
            pre=None
            #print("before:",dic[key])
            temp=[]
            for info in dic[key]:
                if pre==None:
                    pre=info
                    temp.append(info)
                elif operator.eq(info.bbox.tolist(),pre.bbox.tolist()):
                        temp[-1].img_class.append(info.img_class[0])
                        #这是个陷坑
                        #dic[key].remove(info)
                else:
                    pre=info
                    temp.append(info)
            dic[key]=temp
        #print("dic:",dic) 
Example #5
Source File: __init__.py    From jbox with MIT License 6 votes vote down vote up
def get_op(cls, op):
        ops = {
            symbol.test: cls.test,
            symbol.and_test: cls.and_test,
            symbol.atom: cls.atom,
            symbol.comparison: cls.comparison,
            'not in': lambda x, y: x not in y,
            'in': lambda x, y: x in y,
            '==': operator.eq,
            '!=': operator.ne,
            '<':  operator.lt,
            '>':  operator.gt,
            '<=': operator.le,
            '>=': operator.ge,
        }
        if hasattr(symbol, 'or_test'):
            ops[symbol.or_test] = cls.test
        return ops[op] 
Example #6
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_values(self):
        # check all operators and all comparison results
        self.checkvalue("lt", 0, 0, False)
        self.checkvalue("le", 0, 0, True )
        self.checkvalue("eq", 0, 0, True )
        self.checkvalue("ne", 0, 0, False)
        self.checkvalue("gt", 0, 0, False)
        self.checkvalue("ge", 0, 0, True )

        self.checkvalue("lt", 0, 1, True )
        self.checkvalue("le", 0, 1, True )
        self.checkvalue("eq", 0, 1, False)
        self.checkvalue("ne", 0, 1, True )
        self.checkvalue("gt", 0, 1, False)
        self.checkvalue("ge", 0, 1, False)

        self.checkvalue("lt", 1, 0, False)
        self.checkvalue("le", 1, 0, False)
        self.checkvalue("eq", 1, 0, False)
        self.checkvalue("ne", 1, 0, True )
        self.checkvalue("gt", 1, 0, True )
        self.checkvalue("ge", 1, 0, True ) 
Example #7
Source File: test_regression.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_richcompare_crash(self):
        # gh-4613
        import operator as op

        # dummy class where __array__ throws exception
        class Foo(object):
            __array_priority__ = 1002

            def __array__(self, *args, **kwargs):
                raise Exception()

        rhs = Foo()
        lhs = np.array(1)
        for f in [op.lt, op.le, op.gt, op.ge]:
            if sys.version_info[0] >= 3:
                assert_raises(TypeError, f, lhs, rhs)
            elif not sys.py3kwarning:
                # With -3 switch in python 2, DeprecationWarning is raised
                # which we are not interested in
                f(lhs, rhs)
        assert_(not op.eq(lhs, rhs))
        assert_(op.ne(lhs, rhs)) 
Example #8
Source File: persistence.py    From jbox with MIT License 6 votes vote down vote up
def _validate_query_state(self):
        for attr, methname, notset, op in (
            ('_limit', 'limit()', None, operator.is_),
            ('_offset', 'offset()', None, operator.is_),
            ('_order_by', 'order_by()', False, operator.is_),
            ('_group_by', 'group_by()', False, operator.is_),
            ('_distinct', 'distinct()', False, operator.is_),
            (
                '_from_obj',
                'join(), outerjoin(), select_from(), or from_self()',
                (), operator.eq)
        ):
            if not op(getattr(self.query, attr), notset):
                raise sa_exc.InvalidRequestError(
                    "Can't call Query.update() or Query.delete() "
                    "when %s has been called" %
                    (methname, )
                ) 
Example #9
Source File: neighbourhoodblock_test.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dedup_with_blocking_vs_sortedneighbourhood(self, window):
        indexers = [
            NeighbourhoodBlock(
                ['var_arange', 'var_block10'],
                max_nulls=1,
                windows=[window, 1]),
            NeighbourhoodBlock(
                left_on=['var_arange', 'var_block10'],
                right_on=['var_arange', 'var_block10'],
                max_nulls=1,
                windows=[window, 1]),
            SortedNeighbourhood(
                'var_arange', block_on='var_block10', window=window),
        ]
        self.assert_index_comparisons(eq, indexers, self.a)
        self.assert_index_comparisons(gt, indexers[-2:], self.incomplete_a) 
Example #10
Source File: base.py    From jbox with MIT License 6 votes vote down vote up
def visit_binary(self, binary, **kwargs):
        """Move bind parameters to the right-hand side of an operator, where
        possible.

        """
        if (
            isinstance(binary.left, expression.BindParameter)
            and binary.operator == operator.eq
            and not isinstance(binary.right, expression.BindParameter)
        ):
            return self.process(
                expression.BinaryExpression(binary.right,
                                            binary.left,
                                            binary.operator),
                **kwargs)
        return super(MSSQLCompiler, self).visit_binary(binary, **kwargs) 
Example #11
Source File: neighbourhoodblock_test.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_link_with_blocking_vs_sortedneighbourhood(self, window):
        indexers = [
            NeighbourhoodBlock(
                ['var_arange', 'var_block10'],
                max_nulls=1,
                windows=[window, 1]),
            NeighbourhoodBlock(
                left_on=['var_arange', 'var_block10'],
                right_on=['var_arange', 'var_block10'],
                max_nulls=1,
                windows=[window, 1]),
            SortedNeighbourhood(
                'var_arange', block_on='var_block10', window=window),
        ]
        self.assert_index_comparisons(eq, indexers, self.a, self.b)
        self.assert_index_comparisons(gt, indexers[-2:], self.incomplete_a,
                                      self.incomplete_b) 
Example #12
Source File: AVA_video_v2.py    From SlowFast-Network-pytorch with MIT License 6 votes vote down vote up
def make_multi_lable(self,dic):
        for key in dic:
            pre=None
            #print("before:",dic[key])
            temp=[]
            for info in dic[key]:
                if pre==None:
                    pre=info
                    temp.append(info)
                elif operator.eq(info.bbox.tolist(),pre.bbox.tolist()):
                        temp[-1].img_class.append(info.img_class[0])
                        #这是个陷坑
                        #dic[key].remove(info)
                else:
                    pre=info
                    temp.append(info)
            dic[key]=temp
        #print("dic:",dic)



    #把dic的信息转换成一一对应的list信息(bboxes,labels,detector_bboxes_list,width,height,ratio,image_position) 
Example #13
Source File: collections.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __eq__(self, other):
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
        while comparison to a regular mapping is order-insensitive.

        '''
        if isinstance(other, OrderedDict):
            return dict.__eq__(self, other) and all(_imap(_eq, self, other))
        return dict.__eq__(self, other) 
Example #14
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_recursion(self):
        # Check that comparison for recursive objects fails gracefully
        from UserList import UserList
        a = UserList()
        b = UserList()
        a.append(b)
        b.append(a)
        self.assertRaises(RuntimeError, operator.eq, a, b)
        self.assertRaises(RuntimeError, operator.ne, a, b)
        self.assertRaises(RuntimeError, operator.lt, a, b)
        self.assertRaises(RuntimeError, operator.le, a, b)
        self.assertRaises(RuntimeError, operator.gt, a, b)
        self.assertRaises(RuntimeError, operator.ge, a, b)

        b.append(17)
        # Even recursive lists of different lengths are different,
        # but they cannot be ordered
        self.assertTrue(not (a == b))
        self.assertTrue(a != b)
        self.assertRaises(RuntimeError, operator.lt, a, b)
        self.assertRaises(RuntimeError, operator.le, a, b)
        self.assertRaises(RuntimeError, operator.gt, a, b)
        self.assertRaises(RuntimeError, operator.ge, a, b)
        a.append(17)
        self.assertRaises(RuntimeError, operator.eq, a, b)
        self.assertRaises(RuntimeError, operator.ne, a, b)
        a.insert(0, 11)
        b.insert(0, 12)
        self.assertTrue(not (a == b))
        self.assertTrue(a != b)
        self.assertTrue(a < b) 
Example #15
Source File: elements.py    From jbox with MIT License 5 votes vote down vote up
def __bool__(self):
        if self.operator in (operator.eq, operator.ne):
            return self.operator(hash(self._orig[0]), hash(self._orig[1]))
        else:
            raise TypeError("Boolean value of this clause is not defined") 
Example #16
Source File: test_fractions.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __eq__(self, other): return self._richcmp(other, operator.eq) 
Example #17
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_mixed(self):
        # check that comparisons involving Vector objects
        # which return rich results (i.e. Vectors with itemwise
        # comparison results) work
        a = Vector(range(2))
        b = Vector(range(3))
        # all comparisons should fail for different length
        for opname in opmap:
            self.checkfail(ValueError, opname, a, b)

        a = range(5)
        b = 5 * [2]
        # try mixed arguments (but not (a, b) as that won't return a bool vector)
        args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
        for (a, b) in args:
            self.checkequal("lt", a, b, [True,  True,  False, False, False])
            self.checkequal("le", a, b, [True,  True,  True,  False, False])
            self.checkequal("eq", a, b, [False, False, True,  False, False])
            self.checkequal("ne", a, b, [True,  True,  False, True,  True ])
            self.checkequal("gt", a, b, [False, False, False, True,  True ])
            self.checkequal("ge", a, b, [False, False, True,  True,  True ])

            for ops in opmap.itervalues():
                for op in ops:
                    # calls __nonzero__, which should fail
                    self.assertRaises(TypeError, bool, op(a, b)) 
Example #18
Source File: test_deprecations.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_normal_types(self):
        for op in (operator.eq, operator.ne):
            # Broadcasting errors:
            self.assert_deprecated(op, args=(np.zeros(3), []))
            a = np.zeros(3, dtype='i,i')
            # (warning is issued a couple of times here)
            self.assert_deprecated(op, args=(a, a[:-1]), num=None)

            # Element comparison error (numpy array can't be compared).
            a = np.array([1, np.array([1,2,3])], dtype=object)
            b = np.array([1, np.array([1,2,3])], dtype=object)
            self.assert_deprecated(op, args=(a, b), num=None) 
Example #19
Source File: test_deprecations.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_none_comparison(self):
        # Test comparison of None, which should result in element-wise
        # comparison in the future. [1, 2] == None should be [False, False].
        with warnings.catch_warnings():
            warnings.filterwarnings('always', '', FutureWarning)
            assert_warns(FutureWarning, operator.eq, np.arange(3), None)
            assert_warns(FutureWarning, operator.ne, np.arange(3), None)

        with warnings.catch_warnings():
            warnings.filterwarnings('error', '', FutureWarning)
            assert_raises(FutureWarning, operator.eq, np.arange(3), None)
            assert_raises(FutureWarning, operator.ne, np.arange(3), None) 
Example #20
Source File: test_util.py    From lambda-packs with MIT License 5 votes vote down vote up
def __eq__(self, y):
    return operator.eq(self.val, y) 
Example #21
Source File: test_operators.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_comparisons(self):
        df1 = tm.makeTimeDataFrame()
        df2 = tm.makeTimeDataFrame()

        row = self.simple.xs('a')
        ndim_5 = np.ones(df1.shape + (1, 1, 1))

        def test_comp(func):
            result = func(df1, df2)
            tm.assert_numpy_array_equal(result.values,
                                        func(df1.values, df2.values))

            with pytest.raises(ValueError, match='dim must be <= 2'):
                func(df1, ndim_5)

            result2 = func(self.simple, row)
            tm.assert_numpy_array_equal(result2.values,
                                        func(self.simple.values, row.values))

            result3 = func(self.frame, 0)
            tm.assert_numpy_array_equal(result3.values,
                                        func(self.frame.values, 0))

            msg = 'Can only compare identically-labeled DataFrame'
            with pytest.raises(ValueError, match=msg):
                func(self.simple, self.simple[:2])

        test_comp(operator.eq)
        test_comp(operator.ne)
        test_comp(operator.lt)
        test_comp(operator.gt)
        test_comp(operator.ge)
        test_comp(operator.le) 
Example #22
Source File: result.py    From jbox with MIT License 5 votes vote down vote up
def __eq__(self, other):
        return self._op(other, operator.eq) 
Example #23
Source File: streaming_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def test_zerocopy_streaming_no_replication(self):
        self._test_streaming(op_zerocopy=operator.eq, op_partial=operator.eq, num_zerocopy=0, num_partial=0, rf=1,
                             num_nodes=3) 
Example #24
Source File: streaming_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def test_zerocopy_streaming(self):
        self._test_streaming(op_zerocopy=operator.gt, op_partial=operator.eq, num_zerocopy=1, num_partial=0,
                             num_nodes=2, rf=2) 
Example #25
Source File: base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _add_comparison_methods(cls):
        """
        Add in comparison methods.
        """
        cls.__eq__ = _make_comparison_op(operator.eq, cls)
        cls.__ne__ = _make_comparison_op(operator.ne, cls)
        cls.__lt__ = _make_comparison_op(operator.lt, cls)
        cls.__gt__ = _make_comparison_op(operator.gt, cls)
        cls.__le__ = _make_comparison_op(operator.le, cls)
        cls.__ge__ = _make_comparison_op(operator.ge, cls) 
Example #26
Source File: base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _add_comparison_ops(cls):
        cls.__eq__ = cls._create_comparison_method(operator.eq)
        cls.__ne__ = cls._create_comparison_method(operator.ne)
        cls.__lt__ = cls._create_comparison_method(operator.lt)
        cls.__gt__ = cls._create_comparison_method(operator.gt)
        cls.__le__ = cls._create_comparison_method(operator.le)
        cls.__ge__ = cls._create_comparison_method(operator.ge) 
Example #27
Source File: test_query_eval.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_str_list_query_method(self, parser, engine):
        df = DataFrame(np.random.randn(10, 1), columns=['b'])
        df['strings'] = Series(list('aabbccddee'))
        expect = df[df.strings.isin(['a', 'b'])]

        if parser != 'pandas':
            col = 'strings'
            lst = '["a", "b"]'

            lhs = [col] * 2 + [lst] * 2
            rhs = lhs[::-1]

            eq, ne = '==', '!='
            ops = 2 * ([eq] + [ne])

            for lhs, op, rhs in zip(lhs, ops, rhs):
                ex = '{lhs} {op} {rhs}'.format(lhs=lhs, op=op, rhs=rhs)
                with pytest.raises(NotImplementedError):
                    df.query(ex, engine=engine, parser=parser)
        else:
            res = df.query('strings == ["a", "b"]', engine=engine,
                           parser=parser)
            assert_frame_equal(res, expect)

            res = df.query('["a", "b"] == strings', engine=engine,
                           parser=parser)
            assert_frame_equal(res, expect)

            expect = df[~df.strings.isin(['a', 'b'])]

            res = df.query('strings != ["a", "b"]', engine=engine,
                           parser=parser)
            assert_frame_equal(res, expect)

            res = df.query('["a", "b"] != strings', engine=engine,
                           parser=parser)
            assert_frame_equal(res, expect) 
Example #28
Source File: test_query_eval.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_str_query_method(self, parser, engine):
        df = DataFrame(np.random.randn(10, 1), columns=['b'])
        df['strings'] = Series(list('aabbccddee'))
        expect = df[df.strings == 'a']

        if parser != 'pandas':
            col = 'strings'
            lst = '"a"'

            lhs = [col] * 2 + [lst] * 2
            rhs = lhs[::-1]

            eq, ne = '==', '!='
            ops = 2 * ([eq] + [ne])

            for lhs, op, rhs in zip(lhs, ops, rhs):
                ex = '{lhs} {op} {rhs}'.format(lhs=lhs, op=op, rhs=rhs)
                pytest.raises(NotImplementedError, df.query, ex,
                              engine=engine, parser=parser,
                              local_dict={'strings': df.strings})
        else:
            res = df.query('"a" == strings', engine=engine, parser=parser)
            assert_frame_equal(res, expect)

            res = df.query('strings == "a"', engine=engine, parser=parser)
            assert_frame_equal(res, expect)
            assert_frame_equal(res, df[df.strings.isin(['a'])])

            expect = df[df.strings != 'a']
            res = df.query('strings != "a"', engine=engine, parser=parser)
            assert_frame_equal(res, expect)

            res = df.query('"a" != strings', engine=engine, parser=parser)
            assert_frame_equal(res, expect)
            assert_frame_equal(res, df[~df.strings.isin(['a'])]) 
Example #29
Source File: inspector.py    From goodtables-py with MIT License 5 votes vote down vote up
def _filter_checks(checks, type=None, context=None, inverse=False):
    result = []
    comparator = operator.eq if inverse else operator.ne
    for check in checks:
        if type and comparator(check['type'], type):
            continue
        if context and comparator(check['context'], context):
            continue
        result.append(check)
    return result 
Example #30
Source File: test_query_eval.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_inf(self):
        n = 10
        df = DataFrame({'a': np.random.rand(n), 'b': np.random.rand(n)})
        df.loc[::2, 0] = np.inf
        ops = '==', '!='
        d = dict(zip(ops, (operator.eq, operator.ne)))
        for op, f in d.items():
            q = 'a %s inf' % op
            expected = df[f(df.a, np.inf)]
            result = df.query(q, engine=self.engine, parser=self.parser)
            assert_frame_equal(result, expected)