Python operator.pos() Examples

The following are 30 code examples of operator.pos(). 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: cparser.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def p_unary_operator(p):
    '''unary_operator : '&'
                      | '*'
                      | '+'
                      | '-'
                      | '~'
                      | '!'
    '''
    # reduces to (op, op_str)
    p[0] = ({
        '+': operator.pos,
        '-': operator.neg,
        '~': operator.inv,
        '!': operator.not_,
        '&': 'AddressOfUnaryOperator',
        '*': 'DereferenceUnaryOperator'}[p[1]], p[1]) 
Example #3
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 #4
Source File: CONGO.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_edge(G, edge, h):
    """
    Given a graph G and one of its edges in tuple form, checks if the deletion
    splits the graph.
    """


    tup = G.es[edge].tuple

    # logging.info("Deleted: %s", tup)

    neighborhood = get_neighborhood_edge(G, tup, h)
    # subtracts local betweennesses in the region, as discussed
    # in the paper
    do_local_betweenness(G, neighborhood, h, operator.neg)
    G.delete_edges(edge)
    fix_betweennesses(G)
    # adds back in local betweennesses after the deletion
    do_local_betweenness(G, neighborhood, h, operator.pos)
    return check_for_split(G, tup) 
Example #5
Source File: CONGO.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def split_vertex(G, vToSplit, instr, h):
    """
    Splits the vertex v into two new vertices, each with
    edges depending on s. Returns True if the split
    divided the graph, else False.
    """
    neighborhood = get_neighborhood_vertex(G, vToSplit, h)
    do_local_betweenness(G, neighborhood, h, operator.neg)
    new_index = G.vcount()
    G.add_vertex()
    G.vs[new_index]['CONGA_orig'] = G.vs[vToSplit]['CONGA_orig']
    G.vs[new_index]['pb'] = {uw : 0 for uw in itertools.combinations(G.neighbors(vToSplit), 2)}

    # adding all relevant edges to new vertex, deleting from old one.
    toAdd = list(zip(itertools.repeat(new_index), instr[0]))
    toDelete = list(zip(itertools.repeat(vToSplit), instr[0]))
    G.add_edges(toAdd)
    G.delete_edges(toDelete)
    neighborhood.append(new_index)
    fix_betweennesses(G)
    # logging.info("split: %d, %s", vToSplit, instr)
    do_local_betweenness(G, neighborhood, h, operator.pos)
    # check if the two new vertices are disconnected.
    return check_for_split(G, (vToSplit, new_index)) 
Example #6
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 #7
Source File: CONGO.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def do_local_betweenness(G, neighborhood, h, op=operator.pos):
    """
    Given a neighborhood and depth h, recalculates all betweennesses
    confined to the neighborhood. If op is operator.neg, it subtracts these
    betweennesses from the current ones. Otherwise, it adds them.
    """
    all_pairs_shortest_paths = []
    pathCounts = Counter()
    for i, v in enumerate(neighborhood):
        s_s_shortest_paths = G.get_all_shortest_paths(v, to=neighborhood)#[i+1:])
        all_pairs_shortest_paths += s_s_shortest_paths
    neighSet = set(neighborhood)
    neighSize = len(neighborhood)
    apsp = []
    for path in all_pairs_shortest_paths:
        # path does not go out of region
        if len(neighSet | set(path)) == neighSize:
            pathCounts[(path[0], path[-1])] += 1 # can improve
            apsp.append(path)
    for path in apsp:
        if len(path) <= h + 1:
            update_betweenness(G, path, pathCounts[(path[0], path[-1])], op) 
Example #8
Source File: test_mixins.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda 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 #9
Source File: test_operator.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pos(self):
        self.assertRaises(TypeError, operator.pos)
        self.assertRaises(TypeError, operator.pos, None)
        self.assertTrue(operator.pos(5) == 5)
        self.assertTrue(operator.pos(-5) == -5)
        self.assertTrue(operator.pos(0) == 0)
        self.assertTrue(operator.pos(-0) == 0) 
Example #10
Source File: test_number.py    From hpy with MIT License 5 votes vote down vote up
def test_unary(self):
        import pytest
        import operator
        for c_name, op in [
                ('Negative', operator.neg),
                ('Positive', operator.pos),
                ('Absolute', abs),
                ('Invert', operator.invert),
                ('Index', operator.index),
                ('Long', int),
                ('Float', float),
                ]:
            mod = self.make_module("""
                HPyDef_METH(f, "f", f_impl, HPyFunc_O)
                static HPy f_impl(HPyContext ctx, HPy self, HPy arg)
                {
                    return HPy_%s(ctx, arg);
                }
                @EXPORT(f)
                @INIT
            """ % (c_name,), name='number_'+c_name)
            assert mod.f(-5) == op(-5)
            assert mod.f(6) == op(6)
            try:
                res = op(4.75)
            except Exception as e:
                with pytest.raises(e.__class__):
                    mod.f(4.75)
            else:
                assert mod.f(4.75) == res 
Example #11
Source File: expr.py    From owasp-pysec with Apache License 2.0 5 votes vote down vote up
def __pos__(self):
        return Expression(self, operator.pos) 
Example #12
Source File: transform.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __pos__(self): return type(self)(self, operator.pos)

    # Binary operators 
Example #13
Source File: test_util.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __pos__(self):
    return NonStandardInteger(operator.pos(self.val)) 
Example #14
Source File: CONGO.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update_betweenness(G, path, count, op):
    """
    Given a shortest path in G, along with a count of paths
    that length, to determine weight, updates the edge and
    pair betweenness dicts with the path's new information.
    """
    weight = op(1./count)
    pos = 0
    while pos < len(path) - 2:
        G.vs[path[pos + 1]]['pb'][order_tuple((path[pos], path[pos + 2]))] += weight
        G.es[G.get_eid(path[pos], path[pos + 1])]['eb'] += weight
        pos += 1
    if pos < len(path) - 1:
        G.es[G.get_eid(path[pos], path[pos + 1])]['eb'] += weight 
Example #15
Source File: pspace_test.py    From odl with Mozilla Public License 2.0 5 votes vote down vote up
def test_unary_ops():
    # Verify that the unary operators (`+x` and `-x`) work as expected

    space = odl.rn(3)
    pspace = odl.ProductSpace(space, 2)

    for op in [operator.pos, operator.neg]:
        x_arr, x = noise_elements(pspace)

        y_arr = op(x_arr)
        y = op(x)

        assert all_almost_equal([x, y], [x_arr, y_arr]) 
Example #16
Source File: tensors_test.py    From odl with Mozilla Public License 2.0 5 votes vote down vote up
def test_unary_ops(tspace):
    """Verify that the unary operators (`+x` and `-x`) work as expected."""
    for op in [operator.pos, operator.neg]:
        x_arr, x = noise_elements(tspace)

        y_arr = op(x_arr)
        y = op(x)

        assert all_almost_equal([x, y], [x_arr, y_arr]) 
Example #17
Source File: nodes.py    From hyper-engine with Apache License 2.0 5 votes vote down vote up
def __pos__(self):  return _op1(self, operator.pos) 
Example #18
Source File: test_operator.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_pos(self):
        self.failUnlessRaises(TypeError, operator.pos)
        self.failUnlessRaises(TypeError, operator.pos, None)
        self.failUnless(operator.pos(5) == 5)
        self.failUnless(operator.pos(-5) == -5)
        self.failUnless(operator.pos(0) == 0)
        self.failUnless(operator.pos(-0) == 0) 
Example #19
Source File: test_mixins.py    From twitter-stock-recommendation 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 #20
Source File: test_util.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __pos__(self):
    return NonStandardInteger(operator.pos(self.val)) 
Example #21
Source File: test_util.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __pos__(self):
    return NonStandardInteger(operator.pos(self.val)) 
Example #22
Source File: vec2d.py    From code-for-blog with The Unlicense 5 votes vote down vote up
def __pos__(self):
        return vec2d(operator.pos(self.x), operator.pos(self.y)) 
Example #23
Source File: test_util.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __pos__(self):
    return NonStandardInteger(operator.pos(self.val)) 
Example #24
Source File: test_util.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __pos__(self):
    return NonStandardInteger(operator.pos(self.val)) 
Example #25
Source File: core.py    From pythonflow with Apache License 2.0 5 votes vote down vote up
def __pos__(self):
        return pos(self, graph=self.graph) 
Example #26
Source File: preprocessor.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def token(self):
        if self.pos < len(self.tokens):
            t = self.tokens[self.pos]
            self.pos += 1
            return t
        else:
            return None 
Example #27
Source File: preprocessor.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, tokens):
        self.tokens = tokens
        self.pos = 0 
Example #28
Source File: cparser.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def token(self):
        while self.pos < len(self.tokens):
            t = self.tokens[self.pos]
            self.pos += 1

            if not t:
                break

            # PP events
            if t.type == 'PP_DEFINE':
                name, value = t.value
                self.cparser.handle_define(
                    name, value, t.filename, t.lineno)
                continue
            elif t.type == 'PP_DEFINE_CONSTANT':
                name, value = t.value
                self.cparser.handle_define_constant(
                    name, value, t.filename, t.lineno)
                continue
            elif t.type == 'PP_IFNDEF':
                self.cparser.handle_ifndef(t.value, t.filename, t.lineno)
                continue
            # TODO: other PP tokens

            # Transform PP tokens into C tokens
            if t.type == 'LPAREN':
                t.type = '('
            elif t.type == 'PP_NUMBER':
                t.type = 'CONSTANT'
            elif t.type == 'IDENTIFIER' and t.value in keywords:
                t.type = t.value.upper()
            elif t.type == 'IDENTIFIER' and t.value in self.type_names:
                t.type = 'TYPE_NAME'
            t.lexer = self
            return t
        return None
        
# --------------------------------------------------------------------------
# Parser
# -------------------------------------------------------------------------- 
Example #29
Source File: cparser.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def input(self, tokens):
        self.tokens = tokens
        self.pos = 0 
Example #30
Source File: test_unyt_array.py    From unyt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registry_association():
    reg = UnitRegistry()
    a = unyt_quantity(3, "cm", registry=reg)
    b = unyt_quantity(4, "m")
    c = unyt_quantity(6, "", registry=reg)
    d = 5

    assert_equal(id(a.units.registry), id(reg))

    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(reg))
        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(reg))

    def unary_op_registry_comparison(op):
        c = op(a)
        d = op(b)

        assert_equal(id(c.units.registry), id(reg))
        assert_equal(id(d.units.registry), id(b.units.registry))

    binary_ops = [operator.add, operator.sub, operator.mul, operator.truediv]
    for op in binary_ops:
        binary_op_registry_comparison(op)

    for op in [operator.abs, operator.neg, operator.pos]:
        unary_op_registry_comparison(op)