Пример #1
0
def test_lshift(int_proxy: MagicProxy, str_proxy: MagicProxy):
    assert not int_proxy._hasError
    assert not str_proxy._hasError
    with pytest.raises(TypeError):
        operator.lshift(int_proxy, str_proxy)
    assert int_proxy._hasError
    assert str_proxy._hasError
Пример #2
0
 def eval(self, p4_state):
     # z3 does not like to shift operators of different size
     # but casting both values could lead to missing an overflow
     # so after the operation cast the lvalue down to its original size
     lval_expr = p4_state.resolve_expr(self.lval)
     rval_expr = p4_state.resolve_expr(self.rval)
     if isinstance(lval_expr, int):
         # if lval_expr is an int we might get a signed value
         # the only size adjustment is to make the rval expr large enough
         # for some reason a small rval leads to erroneous shifts...
         return op.lshift(lval_expr, rval_expr)
     if isinstance(rval_expr, int):
         # shift is larger than width, all zero
         if lval_expr.size() <= rval_expr:
             return z3.BitVecVal(0, lval_expr.size())
     # align the bitvectors to allow operations
     lval_is_bitvec = isinstance(lval_expr, z3.BitVecRef)
     rval_is_bitvec = isinstance(rval_expr, z3.BitVecRef)
     orig_lval_size = lval_expr.size()
     if lval_is_bitvec and rval_is_bitvec:
         # shift is larger than width, all zero
         if lval_expr.size() <= rval_expr.size():
             lval_expr = z3_cast(lval_expr, rval_expr.size())
         if lval_expr.size() > rval_expr.size():
             rval_expr = z3_cast(rval_expr, lval_expr.size())
     return z3_cast(op.lshift(lval_expr, rval_expr), orig_lval_size)
Пример #3
0
    def test_lshift_trace(self):
        trace = self.sdk.current_trace
        span = trace.span()

        operator.lshift(span, trace)
        self.assertNotIn(span, trace.spans)
        self.assertNotIn(span.span_id, trace.span_ids)
Пример #4
0
 def __ilshift__(self, other):
     """
     :see: `__lshift__`
     :rtype: Span
     """
     operator.lshift(self, other)
     return self
Пример #5
0
 def test_lshift(self):
     #operator = self.module
     self.assertRaises(TypeError, operator.lshift)
     self.assertRaises(TypeError, operator.lshift, None, 42)
     self.assertTrue(operator.lshift(5, 1) == 10)
     self.assertTrue(operator.lshift(5, 0) == 5)
     self.assertRaises(ValueError, operator.lshift, 2, -1)
Пример #6
0
    def test_shifts_with_some_values(self, i: PythonValue,
                                     j: Optional[int]) -> None:
        TypeCheckLogger.clean_sing()

        new_val1 = i.lshift(pv.int(j))
        new_val2 = i.rshift(pv.int(j))

        assert not i.is_top()
        assert isinstance(i.val, AbstractValue)
        assert isinstance(new_val1.val, AbstractValue)
        assert isinstance(new_val2.val, AbstractValue)

        if i.val.is_top() or j is None:
            assert new_val1.val.is_top()
            assert new_val2.val.is_top()
            assert len(TypeCheckLogger().warnings) == 0
            return

        if new_val1.val.is_top():
            with raises(ValueError):
                ops.lshift(i.val.val, j)  # type: ignore
            assert len(TypeCheckLogger().warnings) > 0
            assert valueError.match(TypeCheckLogger().warnings[0][1])
        else:
            assert ops.lshift(i.val.val, j) == new_val1.val.val  # type: ignore

        if new_val2.val.is_top():
            with raises(ValueError):
                ops.rshift(i.val.val, j)  # type: ignore
            assert len(TypeCheckLogger().warnings) > 0
            assert valueError.match(TypeCheckLogger().warnings[-1][1])
        else:
            assert ops.rshift(i.val.val, j) == new_val2.val.val  # type: ignore
Пример #7
0
 def test_lshift(self):
     #operator = self.module
     self.assertRaises(TypeError, operator.lshift)
     self.assertRaises(TypeError, operator.lshift, None, 42)
     self.assertTrue(operator.lshift(5, 1) == 10)
     self.assertTrue(operator.lshift(5, 0) == 5)
     self.assertRaises(ValueError, operator.lshift, 2, -1)
Пример #8
0
    def test_lshift_span(self):
        span_id = Span.new_span_id()
        span_a = Span.new(self.trace, span_id)

        new_span_id = Span.new_span_id()
        span_b = Span.new(self.trace, new_span_id)

        operator.lshift(span_b, span_a)
        self.assertIs(span_a.parent_span, span_b)
Пример #9
0
def max_common_dicision2(a, b):
    if (a % 2 == 0) and (b % 2 == 0):
        a = operator.lshift(a, 1)
        b = operator.lshift(b, 1)
    elif (a % 2 == 0) and (b % 2 != 0):
        a = operator.lshift(a, 1)
    elif (a % 2 != 0) and (b % 2 == 0):
        b = operator.lshift(b, 1)
    elif (a % 2 != 0) and (b % 2 != 0):
        a, b = b, a - b
    if a == b:
        return a
    else:
        max_common_dicision2(a, b)
Пример #10
0
 def test_idiv(self):
     for i in range(0, NUM_TESTS):
         a = random.randint(MIN_TEST, MAX_TEST)
         d = random.randint(MIN_TEST, MAX_TEST)
         b = 0
         while (b == 0):  # Divisor can't be zero.
             b = random.randint(MIN_TEST, MAX_TEST)
         correct_quotient = (opfunc.lshift(d, REGISTER_SIZE) + a) // b
         correct_remainder = (opfunc.lshift(d, REGISTER_SIZE) + a) % b
         vmachine.registers["EAX"] = a
         vmachine.registers["EDX"] = d
         vmachine.registers["EBX"] = b
         assemble("idiv ebx", vmachine)
         self.assertEqual(vmachine.registers["EAX"], correct_quotient)
         self.assertEqual(vmachine.registers["EBX"], correct_remainder)
Пример #11
0
 def test_lui(self):
     for _ in range(0, NUM_TESTS):
         a = random.randint(0, 1048576)
         hex_string = hex(a).upper()
         correct = check_overflow(opfunc.lshift(a, 12), riscv_machine)
         assemble("40000 LUI X10, " + hex_string, riscv_machine)
         self.assertEqual(riscv_machine.registers["X10"], correct)
Пример #12
0
 def fhook(self, ops, vm):
     check_num_args(self.name, ops, 3)
     check_reg_only(self.name, ops)
     fixed_op2 = ops[2].get_val() % 32
     ops[0].set_val(
         check_overflow(opfunc.lshift(ops[1].get_val(), fixed_op2), vm))
     vm.changes.add(ops[0].get_nm())
Пример #13
0
def main():
    a = -1
    b = 5.0
    c = 2
    d = 6

    for k, v in {"a": a, "b": b, "c": c, "d": d}.items():
        print(k + " =", v)

    print("\nPositive/Negative:")
    print("abs(a);", operator.abs(a))
    print("neg(a);", operator.neg(a))
    print("neg(b);", operator.neg(b))
    print("pos(a);", operator.pos(a))
    print("pos(b);", operator.pos(b))

    print("\nArithmetic:")
    print("add(a, b)     :", operator.add(a, b))
    print("floordiv(a, b):", operator.floordiv(a, b))
    print("floordiv(d, c):", operator.floordiv(d, c))
    print("mod(a, b)     :", operator.mod(a, b))
    print("mul(a, b)     :", operator.mul(a, b))
    print("pow(c, d)     :", operator.pow(c, d))
    print("sub(b, a)     :", operator.sub(b, a))
    print("truediv(a, b) :", operator.truediv(a, b))
    print("truediv(d, c) :", operator.truediv(d, c))

    print("\nBitwise:")
    print("and_(c, d)  :", operator.and_(c, d))
    print("invert(c)   :", operator.invert(c))
    print("lshift(c, d):", operator.lshift(c, d))
    print("or_(c, d)   :", operator.or_(c, d))
    print("rshift(d, c):", operator.rshift(d, c))
    print("xor(c, d)   :", operator.xor(c, d))
Пример #14
0
def guarded_lshift(a, b):
    if not (isinstance(a, int) and isinstance(b, int)):
        raise CalcError("non-integer shift values")
    elif b.bit_length() > 64:
        # Only need to check how much the number is being shifted by
        raise CalcError("would take too long to calculate")
    return op.lshift(a, b)
Пример #15
0
 def operator_lshift(size):
     a = Array(size, 'int32')
     b = Array(size, 'int32')
     for i in range(size):
         a[i] = nb_types.int32(i)
         b[i] = nb_types.int32(size-i-1)
     return operator.lshift(a, b)
Пример #16
0
 def fhook(self, ops, vm):
     val_one, val_two = get_stack_operands(vm)
     val_two = val_two % 32  # only for i32
     result = opfunc.lshift(val_one, val_two)
     check_overflow(result, vm)
     vm.stack[hex(vm.get_sp()).split('x')[-1].upper()] = result
     vm.inc_sp()
Пример #17
0
def parse_data(*, debug=False):
    prob_num = __file__[-5:-3]
    filename = int(prob_num)
    if debug:
        filename = f'{prob_num}.test'

    def to_int_maybe(v):
        try:
            return int(v)
        except:
            return v

    funcs = dict(AND=lambda a, b: and_(a, b) & 0xFFFF,
                 OR=lambda a, b: or_(a, b) & 0xFFFF,
                 LSHIFT=lambda a, b: lshift(a, b) & 0xFFFF,
                 RSHIFT=lambda a, b: rshift(a, b) & 0xFFFF)

    def invert(v):
        return inv(v) & 0xFFFF

    def _get_circuit(l):
        left, right = l.split(' -> ')
        match left.split():
            case ('NOT', x):
                left = invert, to_int_maybe(x)
            case x, cmd, y:
                left = funcs[cmd], to_int_maybe(x), to_int_maybe(y)
            case (x, ):
                left = to_int_maybe(x)
            case _:
                raise Exception('wth')
        return left, to_int_maybe(right)

    return [_get_circuit(l) for l in read_file(filename, 2015)]
Пример #18
0
def dechiffre_image(image):
    """
    Permet de récupérer le texte caché dans l'image
    Le texte est caché à partir de la ligne 2
    Il faut tout d'abord récupérer la taille du texte caché
            recup_taille_image(image)
    """
    taille = recup_taille_texte(
        image)  #récupère la taille du texte sous forme d'entier décimal
    liste_recup = []
    print("taille = :", taille)
    cpt = 0
    for y in range(1, 512):
        for x in range(0, 512):
            #print(x,y)
            if cpt == taille * 2:
                break
            r, g, b = image.getpixel((x, y))
            liste_recup.append(operator.and_(0b00001111, r))
            cpt += 1
    print(liste_recup)

    Lf = []
    for i in range(0, len(liste_recup), 2):
        print(i)
        temp = operator.lshift(liste_recup[i], 4) + liste_recup[i + 1]
        Lf.append(temp)
    print(Lf)
    Chaine = []
    for i in Lf:
        Chaine.append(chr(i))
    return "".join(Chaine)
Пример #19
0
 def fhook(self, ops, vm):
     (op1, op2) = get_two_op_imm(self.get_nm(), ops)
     if op2.get_val() > 1048576:
         raise IncorrectImmLength(op2.get_val())
     # print(op2.get_val())
     op1.set_val(check_overflow(opfunc.lshift(op2.get_val(), 12), vm))
     # print(op1.get_val())
     vm.changes.add(op1.get_nm())
Пример #20
0
def bits(*args):
    if len(args) == 2 and all(type(x)==int for x in args):
        rng = sorted(args)
        rng = range(rng[0], rng[1]+1)
    else:
        rng = args[0]

    return reduce(or_, map(lambda x: lshift(1, x), rng))
Пример #21
0
    def test_lshift():
        """Test Number - correct initilization"""
        value = 42
        num_a = param.Number(value=value)
        assert num_a.value == value

        new_value = operator.lshift(value, 1)
        num_a.value <<= 1
        assert num_a.value == new_value
Пример #22
0
    def test_lshift():
        """Test Parameter - correct initilization"""
        value = 42
        num_a = param.Parameter(value=value)
        assert num_a.value == value

        new_value = operator.lshift(value, 1)
        num_a.value = num_a.__lshift__(1)
        assert num_a.value == new_value
Пример #23
0
    def test_lshift():
        """Test Integer - correct operation"""
        value = 42
        num_a = param.Integer(value=value)
        assert num_a.value == value

        new_value = operator.lshift(value, 1)
        num_a.value <<= 1
        assert num_a.value == new_value
Пример #24
0
def limited_lshift(a, b):
    if is_too_long(b):
        # Neaten the error message
        raise OverflowError("result is too long to be printed")

    if not isinstance(a, int) or not isinstance(b, int):
        # floats are handled more gracefully
        pass
    elif b.bit_length() > 64:
        # Only need to check how much the number is being shifted by
        raise OverflowError("{} << {} would take too long to calculate".format(a, b))
    return op.lshift(a, b)
Пример #25
0
def recup_taille_texte(image):
    N = 8
    masque = 0b00001111
    taille = 0  # nombre qui donne la taille du texte
    rec = []
    for i in range(N):
        r, g, b = image.getpixel((i, 0))
        rec.append(operator.and_(r, 0b00001111))
    nb_final = 0
    for i, v in enumerate(rec):
        nb_final += operator.lshift(v, 4 * (N - 1 - i))
    return nb_final  # recupération de la valeur finale (taille du texte)
Пример #26
0
 def fhook(self, ops, vm):
     check_num_args(self.name, ops, 2)
     check_reg_only(self.name, ops)
     result = ops[0].get_val() * ops[1].get_val()
     if result > 2**32 - 1:
         vm.registers['LO'] = opfunc.lshift(result, 32)
         vm.registers['HI'] = opfunc.rshift(result, 32)
     else:
         vm.registers['LO'] = result
         vm.registers['HI'] = 0
     vm.changes.add('LO')
     vm.changes.add('HI')
     return ''
Пример #27
0
def apply_operator_to_expressions(expression_operator, numerical_expressions):
    if expression_operator == "AND":
        return numerical_expressions[0] & numerical_expressions[1]
    elif expression_operator == "NOT":
        return ~numerical_expressions[0]
    elif expression_operator == "OR":
        return numerical_expressions[0] | numerical_expressions[1]
    elif expression_operator == "LSHIFT":
        return operator.lshift(numerical_expressions[0], numerical_expressions[1])
    elif expression_operator == "RSHIFT":
        return operator.rshift(numerical_expressions[0], numerical_expressions[1])

    return None
def process_line(filename):
    with open(filename, 'r') as f:
        lines = f.read().splitlines()
        for line in lines:
            words = line.split(' ')
            wire_name = CircuitBookletReader.give_wire(line)
            gate, index = CircuitBookletReader.give_gate(line)
            if gate == '':
                wire_signals[wire_name] = CircuitBookletReader.Signal(words[0])
            if gate == 'NOT':
                if wire_name in list(wire_signals.keys()):
                    wire_signals[wire_name].value = ~wire_signals[words[1]]
                else:
                    wire_signals[wire_name] = CircuitBookletReader.Signal(~wire_signals[words[1]])
            if gate == 'OR':
                if wire_name in list(wire_signals.keys()):
                    wire_signals[wire_name].value = wire_signals[words[0]] | wire_signals[words[2]]
                else:
                    wire_signals[wire_name] = CircuitBookletReader.Signal(wire_signals[words[0]] | wire_signals[words[2]])
            if gate == 'AND':
                if wire_name in list(wire_signals.keys()):
                    wire_signals[wire_name].value = wire_signals[words[0]] & wire_signals[words[2]]
                else:
                    wire_signals[wire_name] = CircuitBookletReader.Signal(wire_signals[words[0]] & wire_signals[words[2]])
            if gate == 'lshift':
                if wire_name in list(wire_signals.keys()):
                    wire_signals[wire_name].value = operator.lshift(wire_signals[words[0]], int(words[2]))
                else:
                    wire_signals[wire_name] = CircuitBookletReader.Signal(operator.lshift(wire_signals[words[0]], int(words[2])))
            if gate == 'RSHIFT':
                if wire_name in list(wire_signals.keys()):
                    wire_signals[wire_name].value = operator.rshift(wire_signals[words[0]], int(words[2]))
                else:
                    wire_signals[wire_name] = CircuitBookletReader.Signal(operator.rshift(wire_signals[words[0]], int(words[2])))

        pprint.pprint(wire_signals,indent=4)
Пример #29
0
 def test_mult(self):
     for i in range(0, NUM_TESTS):
         a = random.randint(MIN_MUL, MAX_MUL)
         b = random.randint(MIN_MUL, MAX_MUL)
         correct = opfunc.mul(a, b)
         mips_machine.registers["R8"] = a
         mips_machine.registers["R9"] = b
         low_correct, high_correct = 0, 0
         assemble("40000 MULT R8, R9", mips_machine)
         if correct > 2**32 - 1:
             low_correct = opfunc.lshift(correct, 32)
             high_correct = opfunc.rshift(correct, 32)
         else:
             low_correct = correct
             high_correct = 0
         self.assertEqual(mips_machine.registers["HI"], high_correct)
         self.assertEqual(mips_machine.registers["LO"], low_correct)
Пример #30
0
def ecrire_taille_texte(im, texte):
    """
    image est une image du style image=Image.open('fichier.png')
    im : est une image sur laquelle on va aplliquer les changement
    im : résulte de Image.open('lena.png')
    texte : contient la chaine à cacher dans l'image
    """
    N = 8  # nb de quartets réservés
    #taille=len(texte)
    # mise à zero des 8 premiers quartets rouges (R)
    im1 = lire_image(chemin, fichier)
    im2 = lire_image(chemin, fichier)

    ######### mise à zero des 8 premiers quartets R
    msq = 0b11110000
    for i in range(N):
        r, g, b = im2.getpixel((i, 0))
        im2.putpixel((i, 0), (operator.and_(r, msq), g, b))

    ######### écriture de la longeur de la chaine dans les 8 premiers quartets R
    # longueur de la chaine dans la variable long
    long = len(texte)
    #long=3561
    n_bits_long_chaine = len(bin(long)) - 2
    # n_R représente le nombre de R utiles pour écrire la taille du texte
    # exemple si n_bits_long_chaine vaut 15, il faut 3 4 4 4 donc
    # R7 = xxxx 4 bits poids fort
    # R6 = xxxx 4 bits suivants
    # R5 = xxxx 4 bits suivants
    # R4 = xxxx x3 derniers bits
    nb_R = n_bits_long_chaine // 4 + 1  # nb quartets utiles
    # on commence par le R7 et on redescend vers R0 si besoin
    for i in range(N - 1, N - 1 - nb_R, -1):
        r, g, b = im2.getpixel((i, 0))
        masque = operator.lshift(0b1111, 4 * (N - 1 - i))
        nb = operator.and_(long, masque)
        nb = operator.rshift(
            nb,
            4 * (N - 1 -
                 i))  # on décale d'un multiple de 4 bits pour chaque valeur
        r = operator.or_(r, nb)
        im2.putpixel((i, 0), (r, g, b))
    return im2
Пример #31
0
def run301_03():
    """
    arithmetic ops
    :return:
    """
    a = -1
    b = 5.0
    c = 2
    d = 6

    print('a =', a)
    print('b =', b)
    print('c =', c)
    print('d =', d)

    print('\nPositive/Negative:')
    print('abs(a):', abs(a))
    print('neg(a):', neg(a))
    print('neg(b):', neg(b))
    print('pos(a):', pos(a))
    print('pos(b):', pos(b))

    print('\nArithmetic:')
    print('add(a, b)     :', add(a, b))
    print('floordiv(a, b):', floordiv(a, b))  # for py2
    print('floordiv(d, c):', floordiv(d, c))  # for py2
    print('mod(a, b)     :', mod(a, b))
    print('mul(a, b)     :', mul(a, b))
    print('pow(c, d)     :', pow(c, d))
    print('sub(b, a)     :', sub(b, a))
    print('truediv(a, b) :', truediv(a, b))
    print('truediv(d, c) :', truediv(d, c))

    print('\nBitwise:')
    print('and_(c, d)  :', and_(c, d))
    print('invert(c)   :', invert(c))  # ~c
    print('lshift(c, d):', lshift(c, d))  # c << d
    print('or_(c, d)   :', or_(c, d))
    print('rshift(d, c):', rshift(d, c))  # d >> c
    print('xor(c, d)   :', xor(c, d))  # 不同得1 ^
Пример #32
0
 def __init__(self, environment=Environment(), input=None):
     self.environment = environment
     self.environment.defineVariable("console", Console())
     self.environment.defineVariable("Math", MathModule())
     self.environment.defineVariable("Object", ObjectModule())
     self.binaries = {
         '+': operator.add,
         '-': operator.sub,
         '*': operator.mul,
         '/': operator.truediv,
         '%': operator.mod,
         '<<': lambda x, y: float(operator.lshift(int(x), int(y))),
         '>>': lambda x, y: float(operator.rshift(int(x), int(y))),
         '>>>': lambda x, y: float((int(x) % 0x100000000) >> int(y)),
         '<': operator.lt,
         '>': operator.gt,
         '<=': operator.le,
         '>=': operator.ge,
         '==': operator.eq,
         '!=': operator.ne,
         '===': lambda x, y: type(x) == type(y) and x == y,
         '!==': lambda x, y: type(x) != type(y) or x != y,
         '||': lambda x, y: x or y,
         '&&': lambda x, y: x and y
     }
     self.unaries = {
         '-': operator.neg,
         '+': operator.pos,
         '~': lambda x: float(~int(x)),
         '!': operator.not_,
         '++': lambda x: x.__add__(1),
         '--': lambda x: x.__add__(-1)
     }
     self.assignment = {
         '=': lambda x, y: y,
         '+=': operator.iadd,
         '-=': operator.isub,
         '*=': operator.mul,
         '/=': operator.truediv
     }
Пример #33
0
def operator_arithmetic():
    """
    arithmetic, math
    +, -, |a|
    +, -, *, //, /, %, pow
    &, |, ^, ~, <<, >>
    """
    a, b, c, d = -1, 5.0, 2, 6
    print('a =', a)
    print('b =', b)
    print('c =', c)
    print('d =', d)

    print('\nPositive/Negative:')
    print('abs(a):', operator.abs(a))
    print('neg(a):', operator.neg(a))
    print('neg(b):', operator.neg(b))
    print('pos(a):', operator.pos(a))
    print('pos(b):', operator.pos(b))

    print('\nArithmetic:')
    print('add(a, b)        :', operator.add(a, b))
    print('sub(b, a)        :', operator.sub(b, a))
    print('mul(a, b)        :', operator.mul(a, b))
    print('truediv(a, b)    :', operator.truediv(a, b))
    print('truediv(d, c)    :', operator.truediv(d, c))
    print('floordiv(a, b)   :', operator.floordiv(a, b))
    print('pow(c, d)        :', operator.pow(c, d))
    print('mod(a, b)        :', operator.mod(a, b))

    print('\nBitwise:')
    print('and_(c, d)       :', operator.and_(c, d))  # c & d
    print('or_(c, d)        :', operator.or_(c, d))  # c | d
    print('invert(c)        :',
          operator.invert(c))  # two's complement. ~c = -c - 1
    print('xor(c, d)        :', operator.xor(c, d))  # a ^ b
    print('lshift(c, d)     :', operator.lshift(c, d))  # d << c
    print('rshift(d, c)     :', operator.rshift(d, c))  # d >> c
 def __init__(self, environment = Environment(), input=None):
     self.environment = environment
     self.environment.defineVariable("console", Console())
     self.environment.defineVariable("Math", MathModule())
     self.environment.defineVariable("Object", ObjectModule())
     self.binaries = { '+': operator.add, '-': operator.sub,
                       '*': operator.mul, '/': operator.truediv,
                       '%': operator.mod,
                       '<<': lambda x, y: float(operator.lshift(int(x), int(y))),
                       '>>': lambda x, y: float(operator.rshift(int(x), int(y))),
                       '>>>': lambda x, y: float((int(x) % 0x100000000) >> int(y)),
                       '<': operator.lt, '>': operator.gt,
                       '<=': operator.le, '>=': operator.ge,
                       '==': operator.eq, '!=': operator.ne,
                       '===': lambda x, y: type(x) == type(y) and x == y,
                       '!==': lambda x, y: type(x) != type(y) or x != y,
                       '||': lambda x, y: x or y, '&&': lambda x, y: x and y }
     self.unaries = { '-': operator.neg, '+': operator.pos,
                      '~': lambda x: float(~int(x)), '!': operator.not_,
                      '++': lambda x: x.__add__(1), '--': lambda x: x.__add__(-1)}
     self.assignment = { '=': lambda x, y: y,
                         '+=': operator.iadd, '-=': operator.isub,
                         '*=': operator.mul, '/=': operator.truediv}
Пример #35
0
print operator.neg(-10)

#取反 相当于 ~a  
#~a = (-a)-1
#~10 = -11
#~(-10) = 9
print operator.inv(10)
print operator.inv(-10)
print operator.invert(10)
print operator.invert(-10)

#乘方 同a**b
print operator.pow(2,3)

#向左移位 同<< 相当于乘以2的相应次方
print operator.lshift(3,2)

#向右移位 同>> 相当于除以2的相应次方 取整
print operator.rshift(3,2)

#按位与 即 a&b
print operator.and_(1,8)
print operator.and_(1,1)

#按位或 即 a|b
print operator.or_(1,8)
print operator.or_(1,3)

#按位异或 即 a^b
print operator.xor(1,8)
print operator.xor(1,3)
Пример #36
0
 def test_lshift(self):
     self.failUnlessRaises(TypeError, operator.lshift)
     self.failUnlessRaises(TypeError, operator.lshift, None, 42)
     self.failUnless(operator.lshift(5, 1) == 10)
     self.failUnless(operator.lshift(5, 0) == 5)
     self.assertRaises(ValueError, operator.lshift, 2, -1)
Пример #37
0
b = 1
print operator.is_(a, b)
b = 2
print operator.is_(a, b)

a = -1
print id(a)




print operator.index(1)

print operator.inv(8)

print operator.lshift(4, 1)


print operator.or_(2,4)


print operator.pos(30)



print operator.pow(2,8)




Пример #38
0
import operator
Пример #39
0
print operator.div(5, 2)
print operator.div(2.2, 2)
print operator.div(-5.0, 2)

print operator.floordiv(10, 5)
print operator.floordiv(5, 2)
print operator.floordiv(2.2, 2)
print operator.floordiv(-5.0, 2)

# Not implemented
# print operator.index("hello")

# Not implemented
# print operator.invert("hello")

print operator.lshift(5, 2)
print operator.lshift(-5, 3)

print operator.mod(10, 5)
print operator.mod(10, 3)
print operator.mod(15, 4)

print operator.mul(2, 1)
print operator.mul(-2, 1)
print operator.mul(2, -1)
print operator.mul(10, 20)

print operator.neg(-5)
print operator.neg(5)
print operator.neg(True)
print operator.neg(False)
Пример #40
0
        factor = Forward()
        factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( pushFirst ) )

        term = factor + ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) )
        expr << term + ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) )
        bnf = expr
    return bnf

# map operator symbols to corresponding arithmetic operations
epsilon = 1e-12
opn = { "+" : operator.add,
        "-" : operator.sub,
        "*" : operator.mul,
        "/" : operator.truediv,
        ">>" : lambda x,y: operator.rshift(int(x),int(y)),
        "<<" : lambda x,y: operator.lshift(int(x),int(y)),
        "|" : lambda x,y: operator.or_(int(x),int(y)),
        "&" : lambda x,y: operator.and_(int(x),int(y)),
        "^" : operator.pow }
fn  = { "sin" : math.sin,
        "cos" : math.cos,
        "tan" : math.tan,
        "abs" : abs,
        "trunc" : lambda a: int(a),
        "round" : round,
        "sgn" : lambda a: abs(a)>epsilon and cmp(a,0) or 0}
def evaluateStack( s ):
    op = s.pop()
    if op == 'unary -':
        return -evaluateStack( s )
    if op in "+-*/^<<>>|&":
Пример #41
0
def lshift(x, y): return operator.lshift(x, y)
@binary('rshift', '>>')
Пример #42
0
def op_lshift(x,y): return _op.lshift(x,y)

@cutype("(a,a) -> a")
Пример #43
0
_BINOPS = (
    ('lt', operator.lt),
    ('le', operator.le),
    ('eq', operator.eq),
    ('ne', operator.ne),
    ('ge', operator.ge),
    ('gt', operator.gt),
    ('add', operator.add),
    ('radd', lambda a, b: operator.add(b, a)),
    ('and', operator.and_),
    ('rand', lambda a, b: operator.and_(b, a)),
    ('floordiv', operator.floordiv),
    ('rfloordiv', lambda a, b: operator.floordiv(b, a)),
    ('lshift', operator.lshift),
    ('rlshift', lambda a, b: operator.lshift(b, a)),
    ('mod', operator.mod),
    ('rmod', lambda a, b: operator.mod(b, a)),
    ('mul', operator.mul),
    ('rmul', lambda a, b: operator.mul(b, a)),
    ('or', operator.or_),
    ('ror', lambda a, b: operator.or_(b, a)),
    ('pow', operator.pow),
    ('rpow', lambda a, b: operator.pow(b, a)),
    ('rshift', operator.rshift),
    ('rrshift', lambda a, b: operator.rshift(b, a)),
    ('sub', operator.sub),
    ('rsub', lambda a, b: operator.sub(b, a)),
    ('truediv', operator.truediv),
    ('rtruediv', lambda a, b: operator.truediv(b, a)),
    ('xor', operator.xor),
Пример #44
0
 def setLED(self, index):
     index = operator.and_(index, 0xF)
     index = operator.lshift(1, index)
     return  ioctl_iow_int(self.device, GRPOCTL, CMDOCTLON, index)
Пример #45
0
 def __lshift__(self, y):
   return NonStandardInteger(operator.lshift(self.val, y))
Пример #46
0
 def bitshift_left_usecase(x, y):
     return operator.lshift(x, y)
Пример #47
0
 def __rlshift__(self, y):
   return NonStandardInteger(operator.lshift(y, self.val))
Пример #48
0
 def tstringint(self, a, b):
     return operator.or_(operator.lshift(ord(b), 8), ord(a))
Пример #49
0
def lshift(a, b):
    return operator.lshift(a, b)