Пример #1
0
def move_right(data):  # 反转====反转回来
    """
    2048整体向右移动
    源数据:
        [2 0 2 0]
        [0 0 0 0]
        [0 0 0 0]
        [0 0 0 0]


    反转
        [0 2 0 2]
        [0 0 0 0]
        [0 0 0 0]
        [0 0 0 0]

    向左移动
        [4 0 0 0]
        [0 0 0 0]
        [0 0 0 0]
        [0 0 0 0]


    反转:
        [0 0 0 4]
        [0 0 0 0]
        [0 0 0 0]
        [0 0 0 0]

    """
    invertData = invert(data)
    return invert(move_left(invertData))
def find_endpoint_bounds(positive_example, tolerance_a, tolerance_b,
                         param_boundaries):
    """
    Find upper and lower bounds for where the endpoints of the boundary can be

    Returns a tuple of 4 coordinates: (left_upper_bound, right_upper_bound,
    left_lower_bound, right_lower_bound)
    positive_example should be some boundary.
    tolerance_a and tolerance_b should be floats.
    param_boundaries should be a list of lists giving lower and upper bounds for
    the possible parameter values. Specifically, it should be a list of the form
    [[lower_bound_x, upper_bound_x], [lower_bound_y, upper_bound_y]]
    """
    print("In find_endpoint_bounds.")

    # use helper function to find upper bounds
    upper_bounds = find_upper_endpoint_bounds(positive_example, tolerance_a,
                                              tolerance_b, param_boundaries,
                                              False)
    # negate the example, find upper bounds of the negated thing, then negate
    # that to find lower bounds
    # but instead of negating, you want to take the limits minus the example,
    # so that you remain within the same parameter boundaries
    inv_pos_example = utils.invert(positive_example, param_boundaries)
    # print("in find_endpoint_bounds, the positive example is",
    #        positive_example)
    # print("in find_endpoint_bounds, inv_pos_example is", inv_pos_example)
    inv_upper_bounds = find_upper_endpoint_bounds(inv_pos_example, tolerance_a,
                                                  tolerance_b,
                                                  param_boundaries, True)
    lower_bounds = utils.invert(inv_upper_bounds, param_boundaries)
    return (upper_bounds[0], upper_bounds[1], lower_bounds[0], lower_bounds[1])
Пример #3
0
def verify(sig, e, pub, g, n):
    r, s = sig
    w = utils.invert(s, n)
    u1 = e * w % n
    u2 = r * w % n
    x, y = point_add(point_mult(g, u1), point_mult(pub, u2))
    return r == x
def label(boundary, should_invert=False, param_boundaries=[[0.0, 20.0],
                                                           [0, 1.0]],
          epsilon=0.01, num_points=200, lipschitz_param=0.05):
    """
    Takes a boundary, and returns its proper label, which is True or False.

    Correct implementation will depend on context, and in the extreme case will
    require computation done by the human.
    """
    # TODO: add type assertions
    if should_invert:
        my_boundary = utils.invert(boundary, param_boundaries)
    else:
        my_boundary = boundary
    # print("endpoints of labelled boundary:", [my_boundary[0], my_boundary[-1]])
    utils.plot(my_boundary, 'tab:orange', param_boundaries)
    print("in the label function")
    
    # print("in the label function, should_invert is", should_invert)
    # print("boundary that label is synthesising", my_boundary)
    # print(num_points)
    
    xs = [z3.Real('x%d' % i) for i in range(num_points)]
    us = [z3.Real('u%d' % i) for i in range(num_points)]

    def make_phi(xs, us):
        # this basically makes a formula encoding dynamics of a system xs
        # controlled by us
        formula = True
        for i in range(num_points - 1):
            formula = z3.And(formula, xs[i+1] == xs[i] + us[i],
                             # xs[i+1] - xs[i] <= lipschitz_param,
                             # xs[i] - xs[i+1] <= lipschitz_param,
                             xs[i] >= 0, xs[i+1] >= 0, xs[i] <= 1, xs[i+1] <= 1)
        return formula

    trace = bt.trace(my_boundary, epsilon, num_points, xs,
                     param_boundaries[0][1], make_phi(xs, us))

    # print("trace that is being labelled is", trace)
    utils.plot(trace, 'b-', param_boundaries)

    # in this labelling function, we demand that the trace's velocity be below
    # the lines connecting the points (0,1), (8, 0.9), (14, 0.6), (20, 0.2),
    # i.e. those points should be the polygon that the boundary has to be below
    
    below_top = True
    
    for point in trace:
        if point[0] <= 8:
            below_top = below_top and (point[1] <= point[0]/(-80.0) + 1.0)
        if point[0] <= 14 and point[0] >= 8:
            below_top = below_top and (point[1] <= point[0]/(-20.0) + 13.0/10)
        if point[0] >= 14:
            below_top = below_top and (point[1] <= point[0]/(-15.0) + 23.0/15)

    # print("below top?", below_top)
            
    return below_top
Пример #5
0
	def __init__(self, n):
		self.n = n
		self.acceptable = set(string.uppercase)
		self.e_table = dict(zip(self.acceptable, utils.nLetterGenerator(self.acceptable, self.n)))
		self.e_transform = utils.mkTransform(self.e_table)
		self.d_table = utils.invert(self.e_table)
		self.d_transform = utils.mkTransform(self.d_table)
		self.key = json.dumps(self.e_table)
Пример #6
0
def sign(e, g, n, d):
    while True:
        k = utils.randomnumber(n-1)
        x, y = point_mult(g, k)
        if x % n != 0:
            break
    r = x
    s = utils.invert(k, n) * (e + r * d) % n
    return r, s
Пример #7
0
def key_gen(p, q):
    if utils.nonrec_gcd(p, q) != 1:
        # non-distinct
        exit(1)
    n = p * q
    g = n + 1
    lmdba = (p - 1) * (q - 1)
    mu = utils.invert(lmdba, n)
    return (n, g), (n, p, q, g, lmdba, mu)
Пример #8
0
	def __init__(self):
		# self.lower=u"aąbcćdeęfghijklłmnńoóprsśtuwyzźż"
		self.upper=u"AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUWYZŹŻ"
		self.acceptable = set(self.upper)
		bigrams = utils.nLetterGenerator(string.uppercase, 2)
		self.e_table = dict(zip(self.acceptable, bigrams))
		self.e_transform = utils.mkTransform(self.e_table)
		self.d_table = utils.invert(self.e_table)
		self.d_transform = utils.mkTransform(self.d_table)
		self.key = json.dumps(self.e_table)
Пример #9
0
def verify(m, sig, y, p=P, q=Q, g=G):
    r, s = sig
    w = utils.invert(s, q)
    u1 = m * w % q
    u2 = r * w % q
    r1 = gmpy2.powmod(g, u1, p)
    r2 = gmpy2.powmod(y, u2, p)
    r3 = r1 * r2 % p
    v = r3 % q
    return v == r
Пример #10
0
def run(sources, destination):
    """
    sources: list of mve scene folders (name:path)
    destination: target folder
    """

    Path(destination).mkdir(exist_ok=True)

    for source in sources:
        i = source.index(':')
        setname = source[0:i]
        path = source[i + 1:]
        dst = Path(destination) / setname
        dst.mkdir(exist_ok=True)
        children = sorted((Path(path) / "output" / "views").iterdir())
        for child in children:
            metafile = child / "meta.ini"
            meta = ConfigParser()
            meta.read(metafile)
            if 'view' not in meta or 'camera' not in meta or float(
                    meta['camera']['focal_length']) <= 0:
                continue
            name = meta['view']['name']

            orgfile = child / "original.jpg"
            colorfile = child / "undistorted.png"
            maskfile = child / "mask.png"
            depthfile = child / "mask-depth.png"
            if not metafile.exists() or not (orgfile.exists()
                                             or colorfile.exists()):
                continue

            dstinput = dst / (name + '.png')
            dstmask = dst / (name + '.mask')
            dstweight = dst / (name + '.weight')

            if colorfile.exists() and not dstinput.exists():
                logger.info(dstinput)
                os.symlink(colorfile.resolve(), dstinput)
            elif orgfile.exists() and not dstinput.exists():
                logger.info(dstinput)
                os.symlink(orgfile.resolve(), dstinput)
            if not dstmask.exists() and maskfile.exists():
                logger.info(dstmask)
                mask = binarymask(
                    normalize(cv2.imread(str(maskfile), cv2.IMREAD_ANYDEPTH)),
                    0.1, 5, 5, 10)
                cv2.imwrite(str(dstmask) + '.png', tobytes(mask))
                (dst / (name + '.mask.png')).replace(dstmask)
            if not dstweight.exists() and depthfile.exists():
                logger.info(dstweight)
                weight = invert(
                    normalize(cv2.imread(str(depthfile), cv2.IMREAD_ANYDEPTH)))
                cv2.imwrite(str(dstweight) + '.png', tobytes(weight))
                (dst / (name + '.weight.png')).replace(dstweight)
Пример #11
0
def sign(m, p, q, g, x):
    k = utils.randomnumber(q - 1, inf=2)
    while True:
        r = utils.powmod(g, k, p) % q
        if r == 0:
            k = utils.randomnumber(q, inf=2)
            continue
        break
    inv = utils.invert(k, q)
    h = m + x * r
    s = inv * h % q
    return r, s
def label(boundary, should_invert=False, param_boundaries=[[0.0, 20.0],
                                                           [0,1.0]],
          epsilon=0.01, num_points=200, lipschitz_param=0.05):
    """
    Takes a boundary, and returns its proper label, which is True or False.

    Correct implementation will depend on context, and in the extreme case will
    require computation done by the human.
    """
    # TODO: add type assertions
    if should_invert:
        my_boundary = utils.invert(boundary, param_boundaries)
    else:
        my_boundary = boundary
    utils.plot(my_boundary, 'tab:orange', param_boundaries)
    print("in the label function")
    
    # print("in the label function, should_invert is", should_invert)
    # print("boundary that label is synthesising", my_boundary)
    # print(num_points)
    
    xs = [z3.Real('x%d' % i) for i in range(num_points)]
    us = [z3.Real('u%d' % i) for i in range(num_points)]

    def make_phi(xs, us):
        # this basically makes a formula encoding dynamics of a system xs
        # controlled by us
        formula = True
        for i in range(num_points - 1):
            formula = z3.And(formula, xs[i+1] == xs[i] + us[i],
                             # xs[i+1] - xs[i] <= lipschitz_param,
                             # xs[i] - xs[i+1] <= lipschitz_param,
                             xs[i] >= 0, xs[i+1] >= 0, xs[i] <= 1, xs[i+1] <= 1)
        return formula

    trace = bt.trace(my_boundary, epsilon, num_points, xs,
                     param_boundaries[0][1], make_phi(xs, us))

    # print("trace that is being labelled is", trace)
    # utils.plot(trace)
    class_val = True
    
    for point in trace:
        if point[0] >= 10:
            class_val = class_val and (point[1] <= (-0.08)*point[0] + 1.8)

    return class_val
Пример #13
0
def bob_round_2(pi, m, alpha, zeta, r, k2, x2, r2, y1, y2, ka_pub, kb_pub, zkp):
    n, g = ka_pub
    n2 = n * n

    rq = r[0] % ecdsa.n
    if rq == 0:
        print("signature failed, retry")
        exit(1)

    z2 = utils.invert(k2, ecdsa.n)
    x2z2 = (x2 * z2) % ecdsa.n
    x3 = utils.randomnumber(pow(ecdsa.n, 5)-1, inf=1)

    if not eczkp.pi_verify(pi, r, ecdsa.G, r2, y1, alpha, zeta, zkp, ka_pub):
        print "Error: zkp failed"
        exit(1)

    mu1 = paillier.mult(alpha, m * z2, n2)
    mu2 = paillier.mult(zeta, rq * x2z2, n2)
    mu3, rnumb = paillier.encrypt(x3 * ecdsa.n, ka_pub)
    mu = paillier.add(paillier.add(mu1, mu2, n2), mu3, n2)

    muprim, rmuprim = paillier.encrypt(z2, kb_pub)

    c = r2
    d = ecdsa.G
    w1 = ecdsa.G
    w2 = y2
    m1 = muprim # ENCRYPTED Z2
    m2 = mu # ENCRYPTED RESULT
    m3 = alpha # ENCRYPTED Z1
    m4 = zeta # ENCRYPTED X1Z1
    r1 = rmuprim
    r2 = rnumb
    x1 = z2
    x2 = x2z2
    x4 = m
    x5 = rq

    pi2 = eczkp.pi2(c, d, w1, w2, m1, m2, m3, m4, r1, r2, x1, x2, x3, x4, x5, zkp, ka_pub, kb_pub)
    if not pi2:
        print "Error: zkp failed"
        exit(1)

    return mu, muprim, pi2
Пример #14
0
def bob_round_2(pi, m, alpha, zeta, r, k2, x2, r2, y1, y2, ka_pub, kb_pub,
                zkpa, zkpb):
    n, g = ka_pub
    n2 = n * n
    rq = r % dsa.Q
    N, h1, h2 = zkpa
    if rq == 0:
        print("signature failed, retry")
    z2 = utils.invert(k2, dsa.Q)
    x2z2 = (x2 * z2) % dsa.Q
    c = x3 = utils.randomnumber(pow(dsa.Q, 5) - 1, inf=1)

    if not zkp.pi_verify(pi, r, dsa.G, r2, y1, alpha, zeta, N, h1, h2, ka_pub):
        return False

    mu1 = paillier.mult(alpha, (m * z2) % dsa.Q, n2)
    mu2 = paillier.mult(zeta, (rq * x2z2) % dsa.Q, n2)
    mu3, rnumb = paillier.encrypt(c * dsa.Q, ka_pub)
    mu = paillier.add(paillier.add(mu1, mu2, n2), mu3, n2)

    muprim, rmuprim = paillier.encrypt((m * z2) % dsa.Q, kb_pub)

    c = r2
    d = dsa.G
    w2 = y2
    m1 = muprim
    m2 = mu
    m3 = alpha
    m4 = zeta
    r1 = rmuprim
    r2 = rnumb
    x1 = z2
    x2 = (rq * x2z2) % dsa.Q
    w1 = dsa.G

    pi2 = zkp.pi2(m, c, d, w1, w2, m1, m2, m3, m4, r1, r2, x1, x2, x3, zkpb,
                  ka_pub, kb_pub)

    return mu, muprim, pi2
Пример #15
0
def run(sources,
        threshold=1e-6,
        open_size=0,
        close_size=0,
        min_area=0,
        expand_size=0,
        preview=False):
    """
    sources: list of image folders
    """

    for source in sources:
        path = Path(source)
        if not (path / "items.json").exists():
            continue
        with io.open(path / "items.json") as f:
            for (filename, meta) in json.load(f).items():
                if not meta['active']:
                    continue

                srcimg = path / filename
                srcmask = srcimg.parent / (srcimg.stem + '.mask')
                if not srcmask.exists():
                    continue

                logger.info(srcmask)

                mask = normalize(cv2.imread(str(srcmask),
                                            cv2.IMREAD_GRAYSCALE))

                binarymask = 255 * np.ones(
                    mask.shape, dtype=np.uint8) * (mask >= threshold)

                if close_size > 0:
                    kernel = cv2.getStructuringElement(
                        cv2.MORPH_ELLIPSE, (close_size, close_size))
                    binarymask = cv2.dilate(binarymask, kernel)
                    binarymask = cv2.erode(binarymask, kernel)

                if open_size > 0:
                    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
                                                       (open_size, open_size))
                    binarymask = cv2.erode(binarymask, kernel)
                    binarymask = cv2.dilate(binarymask, kernel)

                contours_outline = np.zeros(binarymask.shape, np.uint8)
                if min_area > 0:
                    _, contours, hierarchy = cv2.findContours(
                        binarymask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
                    valid = list()
                    for contour in contours:
                        area = cv2.contourArea(contour)
                        if area >= min_area:
                            valid.append(contour)
                    binarymask = np.zeros(binarymask.shape, np.uint8)
                    cv2.drawContours(binarymask, valid, -1, 255, cv2.FILLED)
                    cv2.drawContours(contours_outline, valid, -1, 255, 2)

                if expand_size > 0:
                    kernel = cv2.getStructuringElement(
                        cv2.MORPH_ELLIPSE, (expand_size, expand_size))
                    binarymask = cv2.dilate(binarymask, kernel)

                binarymask = normalize(binarymask)
                contours_outline = normalize(contours_outline)

                if preview:
                    preview_before = cv2.cvtColor(resizemax(mask, 1600),
                                                  cv2.COLOR_GRAY2BGR)
                    preview_after = cv2.cvtColor(resizemax(binarymask, 1600),
                                                 cv2.COLOR_GRAY2BGR)
                    preview_contours = resizemax(contours_outline, 1600)
                    preview_after[:, :, 0] = preview_contours
                    preview_after[:, :, 1] *= invert(preview_contours)
                    preview_after[:, :, 2] = preview_before[:, :, 0] * invert(
                        preview_contours)

                    zeros1 = np.zeros([preview_before.shape[0], 10, 3],
                                      np.float32)
                    ones1 = np.ones([preview_before.shape[0], 10, 3],
                                    np.float32)
                    padded1 = np.concatenate([
                        zeros1, preview_before, zeros1, ones1, zeros1,
                        preview_after, zeros1
                    ],
                                             axis=1)
                    zeros2 = np.zeros([10, padded1.shape[1], 3], np.float32)
                    padded2 = np.concatenate([zeros2, padded1, zeros2], axis=0)
                    cv2.imshow('cv2: mask', padded2)

                    key = cv2.waitKey()
                    while key != ord('q') and key != ord('c'):
                        key = cv2.waitKey()
                    if key == ord('q'):
                        break
                else:
                    cv2.imwrite(str(srcmask) + '.png', tobytes(binarymask))
                    (srcimg.parent /
                     (srcimg.stem + '.mask.png')).replace(srcmask)
Пример #16
0
    def decode_packet(self, packet):

        raw = packet
        kw = {}

        if  (len(packet) < 56) or (len(packet) > 89):
            print "!invalid packet length: ", len(packet)
            #return


        nibbles = [int(utils.invert(s[::-1]),2) for s in utils.batch_gen(packet,4)]

        if len(nibbles) < 14:
            #~ logging.info("!invalid nibbles length: %s" % len(nibbles))
            return

        if len(nibbles) > 24:
            pass
#            print "!invalid nibbles length: ", len(nibbles)
        else:
            pass
#        	print "nibbles len=", len(nibbles)

        if nibbles[0] != 10:
#            print "!syncrobyte ", hex(nibbles[0]), " does not match 0xa"
            return

        sensor_type = ((nibbles[1] << 12)+(nibbles[2] << 8)+(nibbles[3] << 4) + nibbles[4])
        channel = nibbles[5]
        rolling_code = (nibbles[7] << 4) + nibbles[6]
        status = nibbles[8]

#        print "sensor type: ", hex(sensor_type)[2:], "code: ", hex(rolling_code)[2:], " channel: ", str(channel), "status: ", hex(status)[2:]

        if (sensor_type in self.SENSOR_BLOCKTYPE) :
            bt = self.SENSOR_BLOCKTYPE.get(sensor_type)
            bl = self.BLOCK_LEN.get(bt)
        else:
            bt = self.BLOCKTYPE_UNKN;
            bl = 0
            kw['error'] = "Unknown sensor type " + hex(sensor_type)[2:] + "! ";

        if (bl != 0) and (bl + 3 < len(nibbles)):
#            print "fix message len ", len(nibbles), " to ", bl
            del nibbles[bl + 3:]

        expected_checksum = sum(nibbles[:-4]) - 0xA
        checksum = nibbles[-3] * 16 + nibbles[-4]

        #~ print checksum, expected_checksum
        if checksum != expected_checksum:
		#   print "!invalid checksum: ", hex(checksum)[2:], " expected: ", hex(expected_checksum)[2:]
            return
        else:
#             print "checksum matched: ", hex(checksum)[2:]
            pass

        #TODO: !!! if sensor_type == 1d20 or 1d30 => only 3 channels (bitcoded) change channel 4 to channel 3

        kw['raw'] = raw
        kw['channel'] = str(channel)
        kw['type'] = hex(sensor_type)[2:]
        kw['code'] = hex(rolling_code)[2:]
        kw['lowbat'] = str(1 if (status & 0b0100) else 0)
        kw['forced'] = str(1 if (status & 0b1000) else 0)

        if bt == self.BLOCKTYPE_T:
            self.decode_temp(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_TH:
            self.decode_temp(nibbles, 9, kw)
            self.decode_humidity(nibbles, 13, kw)
        elif bt == self.BLOCKTYPE_UV:
            self.decode_UV(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_UV2:
            self.decode_UV(nibbles, 12, kw)
        elif bt == self.BLOCKTYPE_W:
            self.decode_wind(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_R:
            self.decode_rain(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_R2:
            self.decode_rain2(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_THB:
            self.decode_temp(nibbles, 9, kw)
            self.decode_humidity(nibbles, 13, kw)
        else:
             kw['UNKN'] = 'Ok'

        return kw
Пример #17
0
def create_windows(array_input, window_shape, step):
    """
    Creates windows in an array in a given shape (window_shape). The Overlap is defined by the parameter step.
    Returns a list of the offset points of the created windows that pass the threshold (Checkbox or Slice).
    In this function the step_size equals the checkbox_size.
    :type step: tuple or int
    :type window_shape: tuple or int
    :type array_input: ndarray
    """
    from utils import invert
    import numpy as np
    from skimage.util import view_as_windows

    """Check the binary image"""
    numberOfValues = np.unique(array_input, return_counts=True)

    if numberOfValues[1][1] > numberOfValues[1][0]:
        pass
    else:
        array_input = invert(array_input)

    """changes the values to 0 and 1 instead of 0 and 255"""
    array_input[array_input == 0] = 1
    array_input[array_input == 255] = 0

    listCoordinates = []

    new_array = view_as_windows(array_input, window_shape, step=step)

    """Check the dimensions of the array"""
    if array_input.ndim == 2:

        n = window_shape[0]
        m = window_shape[1]

        if type(step) == tuple:
            stepY = step[0]
            stepX = step[1]
        if type(step) == int:
            stepX = step
            stepY = step

        """Iterating over the windows of new_array"""
        for y in range(new_array.shape[0]):
            for x in range(new_array.shape[1]):
                window = new_array[y, x]

                """Creating the central slice of the window"""
                OffSetSliceY = np.uint8((n - stepY) / 2)
                OffSetSliceX = np.uint8((m - stepX) / 2)
                SliceOfWindow = window[OffSetSliceY:OffSetSliceY + stepY, OffSetSliceX:OffSetSliceX + stepX]

                """Threshold"""
                sumSlice = np.sum(SliceOfWindow, axis=(0, 1))
                if sumSlice >= min(SliceOfWindow.shape[0], SliceOfWindow.shape[1]):
                    listCoordinates.append((y * stepY, x * stepX))

    if array_input.ndim == 3:

        k = window_shape[0]
        n = window_shape[1]
        m = window_shape[2]

        if type(step) == tuple:
            stepZ = step[0]
            stepY = step[1]
            stepX = step[2]
        if type(step) == int:
            stepZ = step
            stepX = step
            stepY = step

        """Iterating over the windows of new_array"""
        for z in range(new_array.shape[0]):
            for y in range(new_array.shape[1]):
                for x in range(new_array.shape[2]):
                    window = new_array[z, y, x]

                    """Creating the central slice of the window"""
                    OffSetSliceZ = np.uint8((k - stepZ) / 2)
                    OffSetSliceY = np.uint8((n - stepY) / 2)
                    OffSetSliceX = np.uint8((m - stepX) / 2)
                    SliceOfWindow = window[OffSetSliceZ:OffSetSliceZ + stepZ, OffSetSliceY:OffSetSliceY + stepY,
                                    OffSetSliceX:OffSetSliceX + stepX]

                    """Threshold"""
                    sumSlice = np.sum(SliceOfWindow, axis=(0, 1, 2))
                    if sumSlice >= min(SliceOfWindow.shape[0], SliceOfWindow.shape[1], SliceOfWindow.shape[2]):
                        listCoordinates.append((z * stepZ, y * stepY, x * stepX))

        """Changing the values back to 0 and 255"""
        array_input[array_input == 0] = 255
        array_input[array_input == 1] = 0

    return listCoordinates
Пример #18
0
def create_windows_slice_nth(array_input, window_shape, step, checkbox_shape, nth):
    """
    Same as create_windows function, but the checkbox_shape does not depend on the step_size.
    :type checkbox_shape: tuple
    :type step: tuple or int
    :type window_shape: tuple or int
    :type array_input: ndarray
    """
    from utils import invert
    import numpy as np
    from skimage.util import view_as_windows

    """Check the binary image"""
    numberOfValues = np.unique(array_input, return_counts=True)

    if numberOfValues[1][1] > numberOfValues[1][0]:
        pass
    else:
        array_input = invert(array_input)

    """changes the values to 0 and 1 instead of 0 and 255"""
    array_input[array_input == 0] = 1
    array_input[array_input == 255] = 0

    listCoordinates = []

    new_array = view_as_windows(array_input, window_shape, step=step)

    """Check the dimensions of the array"""
    if array_input.ndim == 2:

        n = window_shape[0]
        m = window_shape[1]

        if type(step) == tuple:
            stepY = step[0]
            stepX = step[1]
        if type(step) == int:
            stepX = step
            stepY = step

        """Iterating over the windows of new_array"""
        for y in range(0, new_array.shape[0], nth):
            for x in range(0, new_array.shape[1], nth):
                window = new_array[y, x]

                """Creating the central slice of the window"""
                OffSetSliceY = np.uint8((n - checkbox_shape[0]) / 2)
                OffSetSliceX = np.uint8((m - checkbox_shape[1]) / 2)
                SliceOfWindow = window[OffSetSliceY:OffSetSliceY + checkbox_shape[0],
                                OffSetSliceX:OffSetSliceX + checkbox_shape[1]]

                """Threshold"""
                sumSlice = np.sum(SliceOfWindow, axis=(0, 1))
                if sumSlice >= min(SliceOfWindow.shape[0], SliceOfWindow.shape[1]):
                    listCoordinates.append((y * stepY, x * stepX))

    if array_input.ndim == 3:

        k = window_shape[0]
        n = window_shape[1]
        m = window_shape[2]

        if type(step) == tuple:
            stepZ = step[0]
            stepY = step[1]
            stepX = step[2]
        if type(step) == int:
            stepZ = step
            stepX = step
            stepY = step

        """Iterating over the windows of new_array"""
        for z in range(0, new_array.shape[0], nth):
            for y in range(0, new_array.shape[1], nth):
                for x in range(0, new_array.shape[2], nth):
                    window = new_array[z, y, x]

                    """Creating the central slice of the window"""
                    OffSetSliceZ = np.uint8((k - checkbox_shape[0]) / 2)
                    OffSetSliceY = np.uint8((n - checkbox_shape[1]) / 2)
                    OffSetSliceX = np.uint8((m - checkbox_shape[2]) / 2)
                    SliceOfWindow = window[OffSetSliceZ:OffSetSliceZ + checkbox_shape[0],
                                    OffSetSliceY:OffSetSliceY + checkbox_shape[1],
                                    OffSetSliceX:OffSetSliceX + checkbox_shape[2]]

                    """Threshold"""
                    sumSlice = np.sum(SliceOfWindow, axis=(0, 1, 2))
                    if sumSlice >= min(SliceOfWindow.shape[0], SliceOfWindow.shape[1], SliceOfWindow.shape[2]):
                        listCoordinates.append((z * stepZ, y * stepY, x * stepX))

    """Changing the values back to 0 and 255"""
    array_input[array_input == 0] = 255
    array_input[array_input == 1] = 0

    return listCoordinates
Пример #19
0
def alice_round_1(m, x1, y1, ka_pub, ka_priv):
    k1 = utils.randomnumber(dsa.Q - 1, inf=2)
    z1 = utils.invert(k1, dsa.Q)
    alpha, r1 = paillier.encrypt(z1, ka_pub)
    zeta, r2 = paillier.encrypt(x1 * z1 % dsa.Q, ka_pub)
    return k1, z1, alpha, zeta, r1, r2
Пример #20
0
    def decode_packet(self, packet):

        raw = packet
        kw = {}

        if (len(packet) < 56) or (len(packet) > 89):
            print "!invalid packet length: ", len(packet)
            #return

        nibbles = [
            int(utils.invert(s[::-1]), 2) for s in utils.batch_gen(packet, 4)
        ]

        if len(nibbles) < 14:
            #~ logging.info("!invalid nibbles length: %s" % len(nibbles))
            return

        if len(nibbles) > 24:
            pass
#            print "!invalid nibbles length: ", len(nibbles)
        else:
            pass


#        	print "nibbles len=", len(nibbles)

        if nibbles[0] != 10:
            #            print "!syncrobyte ", hex(nibbles[0]), " does not match 0xa"
            return

        sensor_type = ((nibbles[1] << 12) + (nibbles[2] << 8) +
                       (nibbles[3] << 4) + nibbles[4])
        channel = nibbles[5]
        rolling_code = (nibbles[7] << 4) + nibbles[6]
        status = nibbles[8]

        #        print "sensor type: ", hex(sensor_type)[2:], "code: ", hex(rolling_code)[2:], " channel: ", str(channel), "status: ", hex(status)[2:]

        if (sensor_type in self.SENSOR_BLOCKTYPE):
            bt = self.SENSOR_BLOCKTYPE.get(sensor_type)
            bl = self.BLOCK_LEN.get(bt)
        else:
            bt = self.BLOCKTYPE_UNKN
            bl = 0
            kw['error'] = "Unknown sensor type " + hex(sensor_type)[2:] + "! "

        if (bl != 0) and (bl + 3 < len(nibbles)):
            #            print "fix message len ", len(nibbles), " to ", bl
            del nibbles[bl + 3:]

        expected_checksum = sum(nibbles[:-4]) - 0xA
        checksum = nibbles[-3] * 16 + nibbles[-4]

        #~ print checksum, expected_checksum
        if checksum != expected_checksum:
            #   print "!invalid checksum: ", hex(checksum)[2:], " expected: ", hex(expected_checksum)[2:]
            return
        else:
            #             print "checksum matched: ", hex(checksum)[2:]
            pass

        #TODO: !!! if sensor_type == 1d20 or 1d30 => only 3 channels (bitcoded) change channel 4 to channel 3

        kw['raw'] = raw
        kw['channel'] = str(channel)
        kw['type'] = hex(sensor_type)[2:]
        kw['code'] = hex(rolling_code)[2:]
        kw['lowbat'] = str(1 if (status & 0b0100) else 0)
        kw['forced'] = str(1 if (status & 0b1000) else 0)

        if bt == self.BLOCKTYPE_T:
            self.decode_temp(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_TH:
            self.decode_temp(nibbles, 9, kw)
            self.decode_humidity(nibbles, 13, kw)
        elif bt == self.BLOCKTYPE_UV:
            self.decode_UV(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_UV2:
            self.decode_UV(nibbles, 12, kw)
        elif bt == self.BLOCKTYPE_W:
            self.decode_wind(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_R:
            self.decode_rain(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_R2:
            self.decode_rain2(nibbles, 9, kw)
        elif bt == self.BLOCKTYPE_THB:
            self.decode_temp(nibbles, 9, kw)
            self.decode_humidity(nibbles, 13, kw)
        else:
            kw['UNKN'] = 'Ok'

        return kw
Пример #21
0
	def loadKey(self, table):
		self.e_table = table
		self.e_transform = utils.mkTransform(self.e_table)
		self.d_table = utils.invert(self.e_table)
		self.d_transform = utils.mkTransform(self.d_table)
		self.key = json.dumps(self.e_table)
Пример #22
0
    h.update(message.encode("utf-8"))
    m = long(h.hexdigest(), 16)
    sig = sign(m, G, n, priv)
    print(sig)
    print(verify(sig, m, pub, G, n))
    h.update("an other one".encode("utf-8"))
    m = long(h.hexdigest(), 16)
    print(verify(sig, m, pub, G, n))

if __name__ == "__main__":
    print("ECDSA")
    # test()
    # run_ecdsa()

    k1 = utils.randomnumber(n-1, inf=1)
    z1 = utils.invert(k1, n)

    k2 = utils.randomnumber(n-1, inf=1)
    z2 = utils.invert(k2, n)

    r2 = point_mult(G, k2)
    r = point_mult(r2, k1)
    r1 = point_mult(r, z1)

    print r2
    print r
    print r1


    
Пример #23
0
	def __init__(self, table, preserveAll=False):
		self.preserveAll = preserveAll
		self.e_table = table
		self.e_transform = utils.mkTransform(table)
		self.d_table = utils.invert(table)
		self.d_transform = utils.mkTransform(self.d_table)