Python operator 模块,xor() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.xor()

项目:fdxread    作者:lkarsten    | 项目源码 | 文件源码
def checksum(self, samples):
        if samples is None:
            return None

        completed = []
        for sentence in samples:
            assert sentence[0] == "$"
            cksum = reduce(xor, (ord(s) for s in sentence[1:]))
            completed.append("%s*%02X" % (sentence, cksum))

        if len(completed) == 0:
            return None

        # NMEA0183 uses \r\n as line separator even on Unix systems.
        s = ""
        for line in completed:
            s = s + line + "\r\n"
        return s
项目:litesdcard    作者:lambdaconcept    | 项目源码 | 文件源码
def __init__(self, n_out, n_state=31, taps=[27, 30]):
        self.o = Signal(n_out)

        # # #

        state = Signal(n_state)
        curval = [state[i] for i in range(n_state)]
        curval += [0]*(n_out - n_state)
        for i in range(n_out):
            nv = ~reduce(xor, [curval[tap] for tap in taps])
            curval.insert(0, nv)
            curval.pop()

        self.sync += [
            state.eq(Cat(*curval[:n_state])),
            self.o.eq(Cat(*curval))
        ]
项目:segno    作者:heuer    | 项目源码 | 文件源码
def calc_structured_append_parity(content):
    """\
    Calculates the parity data for the Structured Append mode.

    :param str content: The content.
    :rtype: int
    """
    if not isinstance(content, str_type):
        content = str(content)
    try:
        data = content.encode('iso-8859-1')
    except UnicodeError:
        try:
            data = content.encode('shift-jis')
        except (LookupError, UnicodeError):
            data = content.encode('utf-8')
    if _PY2:
        data = (ord(c) for c in data)
    return reduce(xor, data)
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`.  It iterates `iterations` time and produces a
    key of `keylen` bytes.  By default SHA-1 is used as hash function,
    a different hashlib `hashfunc` can be provided.
    """
    hashfunc = hashfunc or hashlib.sha1
    mac = hmac.new(data, None, hashfunc)
    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(x)
        return map(ord, h.digest())
    buf = []
    for block in xrange(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(salt + _pack_int(block))
        for i in xrange(iterations - 1):
            u = _pseudorandom(''.join(map(chr, u)))
            rv = starmap(xor, izip(rv, u))
        buf.extend(rv)
    return ''.join(map(chr, buf))[:keylen]
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`.  It iterates `iterations` time and produces a
    key of `keylen` bytes.  By default SHA-1 is used as hash function,
    a different hashlib `hashfunc` can be provided.
    """
    hashfunc = hashfunc or hashlib.sha1
    mac = hmac.new(data, None, hashfunc)
    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(x)
        return map(ord, h.digest())
    buf = []
    for block in xrange(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(salt + _pack_int(block))
        for i in xrange(iterations - 1):
            u = _pseudorandom(''.join(map(chr, u)))
            rv = starmap(xor, izip(rv, u))
        buf.extend(rv)
    return ''.join(map(chr, buf))[:keylen]
项目:grove    作者:rigetticomputing    | 项目源码 | 文件源码
def binary_back_substitute(W, s):
    """
    Perform back substitution on a binary system of equations, i.e. it performs Gauss elimination
    over the field :math:`GF(2)`. It finds an :math:`\\mathbf{x}` such that
    :math:`\\mathbf{\\mathit{W}}\\mathbf{x}=\\mathbf{s}`, where all arithmetic is taken bitwise
    and modulo 2.

    :param 2darray W: A square :math:`n\\times n` matrix of 0s and 1s,
              in row-echelon (upper-triangle) form
    :param 1darray s: An :math:`n\\times 1` vector of 0s and 1s
    :return: The :math:`n\\times 1` vector of 0s and 1s that solves the above
             system of equations.
    :rtype: 1darray
    """
    # iterate backwards, starting from second to last row for back-substitution
    m = np.copy(s)
    n = len(s)
    for row_num in range(n - 2, -1, -1):
        row = W[row_num]
        for col_num in range(row_num + 1, n):
            if row[col_num] == 1:
                m[row_num] = xor(s[row_num], s[col_num])

    return m[::-1]
项目:lampost_lib    作者:genzgd    | 项目源码 | 文件源码
def pbkdf2_bin(data, salt, iterations=1000, key_len=24, hash_func=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`.  It iterates `iterations` time and produces a
    key of `key_len` bytes.  By default SHA-1 is used as hash function,
    a different hashlib `hash_func` can be provided.
    """
    hash_func = hash_func or hashlib.sha1
    mac = hmac.new(data, None, hash_func)
    def _pseudo_random(x):
        h = mac.copy()
        h.update(x)
        return h.digest()
    buf = bytearray()
    for block in range(1, -(-key_len // mac.digest_size) + 1):
        rv = u = _pseudo_random(salt + _pack_int(block))
        for i in range(iterations - 1):
            u = _pseudo_random(u)
            rv = starmap(xor, zip(rv, u))
        buf.extend(rv)
    return bytes(buf[:key_len])
项目:drtio_transceiver_test    作者:m-labs    | 项目源码 | 文件源码
def __init__(self, n_out, n_state=23, taps=[17, 22]):
        self.o = Signal(n_out)

        # # #

        state = Signal(n_state, reset=1)
        curval = [state[i] for i in range(n_state)]
        curval += [0]*(n_out - n_state)
        for i in range(n_out):
            nv = reduce(xor, [curval[tap] for tap in taps])
            curval.insert(0, nv)
            curval.pop()

        self.sync += [
            state.eq(Cat(*curval[:n_state])),
            self.o.eq(Cat(*curval))
        ]
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def __init__(self, code, objects=None):
        self._OPERATORS = [
            ('|', operator.or_),
            ('^', operator.xor),
            ('&', operator.and_),
            ('>>', operator.rshift),
            ('<<', operator.lshift),
            ('-', operator.sub),
            ('+', operator.add),
            ('%', operator.mod),
            ('/', operator.truediv),
            ('*', operator.mul),
        ]
        self._ASSIGN_OPERATORS = [(op + '=', opfunc)
                                  for op, opfunc in self._OPERATORS]
        self._ASSIGN_OPERATORS.append(('=', lambda cur, right: right))
        self._VARNAME_PATTERN = r'[a-zA-Z_$][a-zA-Z_$0-9]*'

        if objects is None:
            objects = {}
        self.code = code
        self._functions = {}
        self._objects = objects
项目:Networking    作者:JoaoChervinski    | 项目源码 | 文件源码
def encrypt():
    ciphertext = ''
    with open(args.filename, 'r') as arq:
        content = arq.readlines()
        for index in range(len(content)):
            content[index] = content[index].rstrip('\n')
    try:
        for line in content:
            for index in range(len(line)):
                bin_text = format(int(line[index]), '#06b')
                bin_secret = format(int(args.secret[index]), '#06b')
                for item in range(len(bin_text)):
                    if item < 2:
                        ciphertext += bin_text[item]
                    else:
                        ciphertext += str(xor(int(bin_text[item]), int(bin_secret[item])))
    except IndexError:
        print '[*] WARNING: The key and the text must be of the same size.'
        quit()
    return ciphertext
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
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))
项目:NMEA-Tools    作者:slott56    | 项目源码 | 文件源码
def validate(sentence_bytes):
        """Validate an NMEA sentence, returning either a tuple of substrings or an 
        :exc:`AssertionError`.

        :param sentence_bytes: A bytes object with the raw sentence.
        :returns: tuple with individual fields, suitable for use with a
            :class:`Sentence_Factory` isntance.
        :raises AssertionError: If the sentence is incomplete in some way.
        """
        assert sentence_bytes.startswith(b'$'), "Sentence fragment"
        content, _, checksum_txt = sentence_bytes[1:].partition(b"*")
        if checksum_txt:
            checksum_exp = int(checksum_txt, 16)
            checksum_act = reduce(xor, content)
            assert checksum_exp == checksum_act, "Invalid checksum"
        return tuple(content.split(b','))
项目:rekall-agent-server    作者:rekall-innovations    | 项目源码 | 文件源码
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`.  It iterates `iterations` time and produces a
    key of `keylen` bytes.  By default SHA-1 is used as hash function,
    a different hashlib `hashfunc` can be provided.
    """
    hashfunc = hashfunc or hashlib.sha1
    mac = hmac.new(data, None, hashfunc)
    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(x)
        return map(ord, h.digest())
    buf = []
    for block in xrange(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(salt + _pack_int(block))
        for i in xrange(iterations - 1):
            u = _pseudorandom(''.join(map(chr, u)))
            rv = starmap(xor, izip(rv, u))
        buf.extend(rv)
    return ''.join(map(chr, buf))[:keylen]
项目:EvilOSX    作者:Marten4n6    | 项目源码 | 文件源码
def pbkdf2_bin(hash_fxn, password, salt, iterations, keylen=16):
    # https://github.com/mitsuhiko/python-pbkdf2
    _pack_int = struct.Struct('>I').pack
    hashfunc = sha1
    mac = hmac.new(password, None, hashfunc)

    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(x)
        return map(ord, h.digest())
    buf = []
    for block in xrange(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(salt + _pack_int(block))
        for i in xrange(iterations - 1):
            u = _pseudorandom("".join(map(chr, u)))
            rv = itertools.starmap(operator.xor, itertools.izip(rv, u))
        buf.extend(rv)
    return "".join(map(chr, buf))[:keylen]
项目:diy_driverless_car_ROS    作者:wilselby    | 项目源码 | 文件源码
def get_arguments():
    ap = argparse.ArgumentParser()
    ap.add_argument('-f', '--filter', required=True,
                    help='Range filter. RGB or HSV')
    ap.add_argument('-i', '--image', required=False,
                    help='Path to the image')
    ap.add_argument('-w', '--webcam', required=False,
                    help='Use webcam', action='store_true')
    ap.add_argument('-p', '--preview', required=False,
                    help='Show a preview of the image after applying the mask',
                    action='store_true')
    args = vars(ap.parse_args())

    if not xor(bool(args['image']), bool(args['webcam'])):
        ap.error("Please specify only one image source")

    if not args['filter'].upper() in ['RGB', 'HSV']:
        ap.error("Please speciy a correct filter.")

    return args
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
def get_config(data):
    config_list = []
    config_string = data.split(split_string)
    for x in range(1, len(config_string)):
        try:
            output = ""
            hex_pairs = [config_string[x][i:i+2] for i in range(0, len(config_string[x]), 2)]
            for i in range(0,len(config_string[x])/2):
                data_slice = int(hex_pairs[i], 16)#get next hex value

                key_slice = ord(enc_key[i+1])#get next Char For Key
                output += chr(xor(data_slice,key_slice)) # xor Hex and Key Char
            print output
        except:
            output = "DecodeError"
        config_list.append(output)
    return config_list

# returns pretty config
项目:bubblesub    作者:rr-    | 项目源码 | 文件源码
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)
项目:myhdlpeek    作者:xesscorp    | 项目源码 | 文件源码
def __xor__(self, trc):
        return self.apply_op2(trc, operator.xor)
项目:pycreateuserpkg    作者:gregneagle    | 项目源码 | 文件源码
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`.  It iterates `iterations` time and produces a
    key of `keylen` bytes.  By default SHA-1 is used as hash function,
    a different hashlib `hashfunc` can be provided.
    """
    hashfunc = hashfunc or hashlib.sha1
    mac = hmac.new(data, None, hashfunc)
    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(x)
        return map(ord, h.digest())
    buf = []
    for block in xrange(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(salt + _pack_int(block))
        for i in xrange(iterations - 1):
            u = _pseudorandom(''.join(map(chr, u)))
            rv = starmap(xor, izip(rv, u))
        buf.extend(rv)
    return ''.join(map(chr, buf))[:keylen]
项目:Fluent-Python    作者:Ehco1996    | 项目源码 | 文件源码
def __hash__(self):
        # ????????????????????
        hashes = (hash(x) for x in self)
        # ???operator?xor?? ???????? ?????0????
        return functools.reduce(operator.xor, hashes, 0)
项目:Fluent-Python    作者:Ehco1996    | 项目源码 | 文件源码
def __hash__(self):
        # ????????????????????
        hashes = (hash(x) for x in self)
        # ???operator?xor?? ???????? ?????0????
        return functools.reduce(operator.xor, hashes, 0)
项目:PicoSim    作者:Vadman97    | 项目源码 | 文件源码
def exec(self, proc: Processor):
        self.proc = proc
        self.args = map(self.expand, self.o_args)  # load register values
        val = reduce(self.operator, self.args)  # apply operator
        if operator is addc or operator is subc:
            val += int(self.proc.external.carry)
        proc.memory.set_register(self.register, val)  # set result
        if operator is operator.and_ or operator is operator.or_ or operator is operator.xor:
            self.proc.set_carry(False)

        # increment pc
        self.proc.manager.next()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def lineReceived(self, line):
        if not line.startswith('$'):
            if self.ignore_invalid_sentence:
                return
            raise InvalidSentence("%r does not begin with $" % (line,))
        # message is everything between $ and *, checksum is xor of all ASCII values of the message
        strmessage, checksum = line[1:].strip().split('*')
        message = strmessage.split(',')
        sentencetype, message = message[0], message[1:]
        dispatch = self.dispatch.get(sentencetype, None)
        if (not dispatch) and (not self.ignore_unknown_sentencetypes):
            raise InvalidSentence("sentencetype %r" % (sentencetype,))
        if not self.ignore_checksum_mismatch:
            checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, map(ord, strmessage))
            if checksum != calculated_checksum:
                raise InvalidChecksum("Given 0x%02X != 0x%02X" % (checksum, calculated_checksum))
        handler = getattr(self, "handle_%s" % dispatch, None)
        decoder = getattr(self, "decode_%s" % dispatch, None)
        if not (dispatch and handler and decoder):
            # missing dispatch, handler, or decoder
            return
        # return handler(*decoder(*message))
        try:
            decoded = decoder(*message)
        except Exception, e:
            raise InvalidSentence("%r is not a valid %s (%s) sentence" % (line, sentencetype, dispatch))
        return handler(*decoded)
项目:whatsapp-rest-webservice    作者:svub    | 项目源码 | 文件源码
def pbkdf2( password, salt, itercount, keylen, hashfn = hashlib.sha1 ):
        def pbkdf2_F( h, salt, itercount, blocknum ):
            def prf( h, data ):
                hm = h.copy()
                try:
                    hm.update(bytearray(data))
                except TypeError: #python 3 support
                    hm.update(bytes(data))

                d = hm.digest()
                return bytearray(d)

            U = prf( h, salt + pack('>i',blocknum ) )
            T = U

            for i in range(2, itercount + 1):
                U = prf( h, U )
                T = starmap(xor, zip(T, U))
            return T

        digest_size = hashfn().digest_size
        l = int(keylen / digest_size)
        if keylen % digest_size != 0:
            l += 1

        h = hmac.new(bytes(password), None, hashfn )

        T = bytearray()
        for i in range(1, l+1):
            tmp = pbkdf2_F( h, salt, itercount, i )
            T.extend(tmp)

        return T[0: keylen]
项目:PyWaves    作者:PyWaves    | 项目源码 | 文件源码
def keccak_f(state):
    def round(A, RC):
        W, H = state.W, state.H
        rangeW, rangeH = state.rangeW, state.rangeH
        lanew = state.lanew
        zero = state.zero

        # theta
        C = [functools.reduce(xor, A[x]) for x in rangeW]
        D = [0] * W
        for x in rangeW:
            D[x] = C[(x - 1) % W] ^ rol(C[(x + 1) % W], 1, lanew)
            for y in rangeH:
                A[x][y] ^= D[x]

        # rho and pi
        B = zero()
        for x in rangeW:
            for y in rangeH:
                B[y % W][(2 * x + 3 * y) % H] = rol(A[x][y], RotationConstants[y][x], lanew)

        # chi
        for x in rangeW:
            for y in rangeH:
                A[x][y] = B[x][y] ^ ((~ B[(x + 1) % W][y]) & B[(x + 2) % W][y])

        # iota
        A[0][0] ^= RC

    l = int(log(state.lanew, 2))
    nr = 12 + 2 * l

    for ir in range(nr):
        round(state.s, RoundConstants[ir])
项目:pyTeliumManager    作者:Ousret    | 项目源码 | 文件源码
def lrc(data):
        """
        Calc. LRC from data. Checksum
        :param bytes|str data: Data from which LRC checksum should be computed
        :return: 0x00 < Result < 0xFF
        :rtype: int
        """
        if isinstance(data, str):
            data = data.encode(TERMINAL_DATA_ENCODING)
        elif not isinstance(data, bytes):
            raise TypeError("Cannot compute LRC of type {0}. Expect string or bytes.".format(str(type(data))))
        return reduce(xor, [c for c in data]) if six.PY3 else reduce(xor, [ord(c) for c in data])
项目:mopidy-deezer    作者:rusty-dev    | 项目源码 | 文件源码
def get_track_cipher(self, track_id):
        """ Get track-specific cipher from `track_id` """
        track_md5 = get_md5(str(track_id).lstrip('-'))
        key_parts = map(lambda v: array('B', v), ('g4el58wc0zvf9na1', track_md5[:16], track_md5[16:]))
        blowfish_key = b''.join(chr(reduce(xor, x)) for x in zip(*key_parts))
        IV = pack('B' * 8, *range(8))

        def track_cipher():
            return Blowfish.new(blowfish_key, mode=Blowfish.MODE_CBC, IV=IV)

        return track_cipher
项目:cupy    作者:cupy    | 项目源码 | 文件源码
def test_xor_scalar(self):
        self.check_array_scalar_op(operator.xor)
项目:cupy    作者:cupy    | 项目源码 | 文件源码
def test_rxor_scalar(self):
        self.check_array_scalar_op(operator.xor, swap=True)
项目:cupy    作者:cupy    | 项目源码 | 文件源码
def test_xor_scalarzero(self):
        self.check_array_scalarzero_op(operator.xor)
项目:cupy    作者:cupy    | 项目源码 | 文件源码
def test_rxor_scalarzero(self):
        self.check_array_scalarzero_op(operator.xor, swap=True)
项目:cupy    作者:cupy    | 项目源码 | 文件源码
def test_xor_array(self):
        self.check_array_array_op(operator.xor)
项目:cupy    作者:cupy    | 项目源码 | 文件源码
def test_doubly_broadcasted_xor(self):
        self.check_array_doubly_broadcasted_op(operator.xor)
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def pbkdf2_bin(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,
               keylen=None, hashfunc=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`. It iterates `iterations` time and produces a
    key of `keylen` bytes. By default SHA-1 is used as hash function,
    a different hashlib `hashfunc` can be provided.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function or a function
                     from the hashlib module.  Defaults to sha1.
    """
    if isinstance(hashfunc, string_types):
        hashfunc = _hash_funcs[hashfunc]
    elif not hashfunc:
        hashfunc = hashlib.sha1
    salt = to_bytes(salt)
    mac = hmac.HMAC(to_bytes(data), None, hashfunc)
    if not keylen:
        keylen = mac.digest_size
    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(x)
        return bytearray(h.digest())
    buf = bytearray()
    for block in range_type(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(salt + _pack_int(block))
        for i in range_type(iterations - 1):
            u = _pseudorandom(bytes(u))
            rv = bytearray(starmap(xor, izip(rv, u)))
        buf.extend(rv)
    return bytes(buf[:keylen])
项目:notebooks    作者:fluentpython    | 项目源码 | 文件源码
def __hash__(self):
        hashes = (hash(x) for x in self)
        return functools.reduce(operator.xor, hashes, 0)
项目:notebooks    作者:fluentpython    | 项目源码 | 文件源码
def __hash__(self):
        hashes = (hash(x) for x in self)
        return functools.reduce(operator.xor, hashes, 0)
项目:notebooks    作者:fluentpython    | 项目源码 | 文件源码
def __hash__(self):
        hashes = (hash(x) for x in self)
        return functools.reduce(operator.xor, hashes, 0)

# BEGIN VECTOR_V6_UNARY
项目:notebooks    作者:fluentpython    | 项目源码 | 文件源码
def __hash__(self):
        hashes = (hash(x) for x in self)
        return functools.reduce(operator.xor, hashes, 0)
项目:notebooks    作者:fluentpython    | 项目源码 | 文件源码
def __hash__(self):
        hashes = (hash(x) for x in self)
        return functools.reduce(operator.xor, hashes, 0)
项目:baya    作者:counsyl    | 项目源码 | 文件源码
def test_coercion(self):
        """Throw a TypeError when trying to combine nodes with non-nodes."""
        for op in [and_, or_, xor]:
            self.assertRaises(TypeError, op, g('A'), 'b')
            self.assertRaises(TypeError, op, 'b', g('A'))
            self.assertRaises(TypeError, op, g('A'), 1234)
            self.assertRaises(TypeError, op, 1234, g('A'))
项目:baya    作者:counsyl    | 项目源码 | 文件源码
def test_coercion(self):
        """Throw a TypeError when trying to combine nodes with non-nodes."""
        for op in [and_, or_, xor]:
            self.assertRaises(TypeError, op, g('A'), 'b')
            self.assertRaises(TypeError, op, 'b', g('A'))
            self.assertRaises(TypeError, op, g('A'), 1234)
            self.assertRaises(TypeError, op, 1234, g('A'))
项目:grove    作者:rigetticomputing    | 项目源码 | 文件源码
def bitwise_xor(bs0, bs1):
    """
    A helper to calculate the bitwise XOR of two bit string

    :param String bs0: String of 0's and 1's representing a number in binary representations
    :param String bs1: String of 0's and 1's representing a number in binary representations
    :return: String of 0's and 1's representing the XOR between bs0 and bs1
    :rtype: String
    """
    if len(bs0) != len(bs1):
        raise ValueError("Bit strings are not of equal length")
    n_bits = len(bs0)
    return PADDED_BINARY_BIT_STRING.format(xor(int(bs0, 2), int(bs1, 2)), n_bits)
项目:grove    作者:rigetticomputing    | 项目源码 | 文件源码
def _add_to_dict_of_indep_bit_vectors(self, z):
        """
        This method adds a bit-vector z to the dictionary of independent vectors. It checks the
        provenance (most significant bit) of the vector and only adds it to the dictionary if the
        provenance is not yet found in the dictionary. This guarantees that we can write up a
        resulting matrix in upper-triangular form which by virtue of its form is invertible

        :param z: array containing the bit-vector
        :return: None
        :rtype: NoneType
        """
        if all(np.asarray(z) == 0) or all(np.asarray(z) == 1):
            return None
        msb_z = utils.most_significant_bit(z)

        # try to add bitstring z to samples dictionary directly
        if msb_z not in self._dict_of_linearly_indep_bit_vectors.keys():
            self._dict_of_linearly_indep_bit_vectors[msb_z] = z
        # if we have a conflict with the provenance of a sample try to create
        # bit-wise XOR vector (guaranteed to be orthogonal to the conflict) and add
        # that to the samples.
        # Bail if this doesn't work and continue sampling.
        else:
            conflict_z = self._dict_of_linearly_indep_bit_vectors[msb_z]
            not_z = [xor(conflict_z[idx], z[idx]) for idx in range(len(z))]
            if all(np.asarray(not_z) == 0):
                return None
            msb_not_z = utils.most_significant_bit(not_z)
            if msb_not_z not in self._dict_of_linearly_indep_bit_vectors.keys():
                self._dict_of_linearly_indep_bit_vectors[msb_not_z] = not_z
项目:grove    作者:rigetticomputing    | 项目源码 | 文件源码
def bitwise_xor(bs0, bs1):
    """
    A helper to calculate the bitwise XOR of two bit string

    :param bs0: String of 0's and 1's representing a number in binary representations
    :param bs1: String of 0's and 1's representing a number in binary representations
    :return: String of 0's and 1's representing the XOR between bs0 and bs1
    :rtype: str
    """
    if len(bs0) != len(bs1):
        raise ValueError("Bit strings are not of equal length")
    n_bits = len(bs0)
    return PADDED_BINARY_BIT_STRING.format(xor(int(bs0, 2), int(bs1, 2)), n_bits)
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def strxor(a, b):
        return ''.join(chr(xor(ord(x), ord(y))) for x,y in  izip(a, b))
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def pbkdf2_bin(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,
               keylen=None, hashfunc=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`. It iterates `iterations` time and produces a
    key of `keylen` bytes. By default SHA-1 is used as hash function,
    a different hashlib `hashfunc` can be provided.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function or a function
                     from the hashlib module.  Defaults to sha1.
    """
    if isinstance(hashfunc, string_types):
        hashfunc = _hash_funcs[hashfunc]
    elif not hashfunc:
        hashfunc = hashlib.sha1
    salt = to_bytes(salt)
    mac = hmac.HMAC(to_bytes(data), None, hashfunc)
    if not keylen:
        keylen = mac.digest_size
    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(x)
        return bytearray(h.digest())
    buf = bytearray()
    for block in range_type(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(salt + _pack_int(block))
        for i in range_type(iterations - 1):
            u = _pseudorandom(bytes(u))
            rv = bytearray(starmap(xor, izip(rv, u)))
        buf.extend(rv)
    return bytes(buf[:keylen])
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def strxor(a, b):
        return ''.join(chr(xor(ord(x), ord(y))) for x,y in  izip(a, b))
项目:pythonic-api    作者:fluentpython    | 项目源码 | 文件源码
def __hash__(self):
        hashes = (hash(x) for x in self)
        return functools.reduce(operator.xor, hashes, 0)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_bitwise_xor(self):
        self.assertRaises(TypeError, operator.xor)
        self.assertRaises(TypeError, operator.xor, None, None)
        self.assertTrue(operator.xor(0xb, 0xc) == 0x7)
项目:Vector-Tiles-Reader-QGIS-Plugin    作者:geometalab    | 项目源码 | 文件源码
def __xor__(self, y):
    return NonStandardInteger(operator.xor(self.val, y))