コード例 #1
0
def main():
    frequency_table = find_frequency(
        "https://www.gutenberg.org/files/1342/1342-h/1342-h.htm")
    print(frequency_table)
    encoded_ciphertext = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
    ciphertext = hex_to_bytes(encoded_ciphertext)
    for k in sorted(decode(ciphertext, frequency_table)):
        print(k[1])
コード例 #2
0
ファイル: client.py プロジェクト: CatDevz/PyChat
def handleMessages(interface: Interface, client: Client):
    while True:
        message = decode(client.socket)

        msg_type = message["type"]
        msg_data = message["data"]

        if msg_type == "message":
            client.message_history.append(msg_data)

        interface.refresh()
コード例 #3
0
    def run(self):
        while not self.running_queue.empty():
            try:
                received_data = self.client_socket.recv(1024)
                if received_data:
                    received_data = received_data.decode('UTF-8').split("$")
                    if _debug:
                        print("Server received raw data: " +
                              str(received_data))
                    for data in received_data:
                        if data:
                            msg = decode(data)
                            if msg.msg_type == MessageType.sendMessage:
                                for s in self.server.senders:
                                    if msg.receiver == "ALL" or msg.receiver == s.username:
                                        s.messages_to_receive.put(msg)

                            elif msg.msg_type == MessageType.addUsername:
                                contains = False
                                for s in self.server.senders:
                                    if msg.sender == s.username:
                                        contains = True
                                if contains:
                                    if _debug:
                                        print("Server didn't accept user: "******"Server accepted user: "******"default":
                                            s.messages_to_receive.put(msg)
                                            self.queue_to_fill.put(
                                                Message(
                                                    MessageType.addUsername,
                                                    s.username))

                else:
                    self.running_queue.get()
                    self.server.clean_client(self.client_socket)
                    if _debug: print("IF clause: {0}".format(received_data))
                    break

            except Exception as e:
                self.server.clean_client(self.client_socket)
                self.running_queue.get()
                if _debug: print("EXCEPT clasue: {0}".format(e))
                break
コード例 #4
0
def handleConnection(server: Server, client: Client):
    # This function will be responsible for handling connections
    # once they have actually been aquired
    global running

    while running:
        # Attempt to get a message from the connection
        try:
            message = decode(client.connection)

            msg_type = message.get("type", None)
            msg_data = message.get("data", None)
            if msg_type == None or msg_data == None:
                raise MalformedPacketException(
                    "Malformed packet receved from client")

            if not msg_type in server.handlers:
                print("Could not find handler for packet type of {}".format(
                    msg_type))
                continue

            handler = server.handlers.get(msg_type)
            handler(server, client, msg_data)
        except MalformedPacketException:
            print("Client with identity {} sent a malformed packet".format(
                client.identity))
            client.send(
                encode({
                    "type": "error",
                    "data": {
                        "body": "A Malformed Packet was sent"
                    }
                }))
        except Exception:
            # Removing the client from the list of clients
            server.clients.remove(client)
            print("Lost client with identity {}".format(client.identity))
            return
コード例 #5
0
def main():
    encoded_ciphertext = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
    ciphertext = bytes.fromhex(encoded_ciphertext)
    for k in sorted(decode(ciphertext, frequency), reverse=True):
        print(k[1])
コード例 #6
0
    def __getitem__(self, idx):
        if self.target_network is None:
            self.target_network = get_model(self.target_network_name,
                                            gpus=[0],
                                            num_classes=self.dataset.num_class,
                                            train_aug=self.target_aug).eval()

        img_orig, lb = self.dataset[idx]
        n_img, n_lb, n_losses, n_corrects = [], [], [], []
        for _ in range(self.num_sample):
            tta_rotate_default = random.choice(
                self.transform_r) if random.random() < self.d_tta_prob else 0.0
            tta_zoom_default = random.choice(
                self.transform_zs
            ) if random.random() < self.d_tta_prob else 1.0
            tta_bright_default = random.choice(
                self.transform_b) if random.random() < self.d_tta_prob else 1.0

            for t_flip in self.transform_flip:
                img_new = img_orig.copy()

                corrupt_name = corrupt_op = corrupt_lv = None
                if self.do_random_corrupt and random.random(
                ) < self.d_tta_prob:  # TODO
                    corrupt_op = random.choice(corruption_tuple)
                    corrupt_lv = random.choice([1, 2, 3, 4, 5])
                elif isinstance(self.corrupt_list, list) and random.random(
                ) < self.d_tta_prob:  # TODO : Partial Corruptions
                    corrupt_name = random.choice(self.corrupt_list)
                    corrupt_op = corruption_dict[corrupt_name]
                    corrupt_lv = random.choice([1, 2, 3, 4, 5])
                    # corrupt_lv = random.choice([3, 4, 5])

                if corrupt_op is not None:
                    img_np = corrupt_op(img_new, severity=corrupt_lv)
                    if isinstance(img_np, np.ndarray):
                        img_np = img_np.astype(np.uint8)
                        img_new = Image.fromarray(img_np)
                    elif isinstance(img_np, PIL.Image.Image):
                        img_new = img_np
                    else:
                        raise Exception(type(img_np))

                if t_flip:
                    img_new = torchvision.transforms.functional.hflip(img_new)
                mirror_expansion_factor = 3
                try:
                    img_mirror = mirror_expansion(img_new)
                except Exception as e:
                    print(corrupt_op, corrupt_lv)
                    print(e)
                    print(type(img_new))
                    print(img_new.size)
                    raise e
                img_new = img_mirror.copy()

                if tta_rotate_default != 0:
                    img_new = torchvision.transforms.functional.rotate(
                        img_new,
                        tta_rotate_default,
                        expand=False,
                        resample=PIL.Image.BICUBIC)
                assert tta_bright_default > 0
                if tta_bright_default != 1.0:
                    img_new = torchvision.transforms.functional.adjust_brightness(
                        img_new, tta_bright_default)
                new_resize = int((self.target_size + self.padding) *
                                 mirror_expansion_factor * tta_zoom_default)
                assert 0.5 < tta_zoom_default < 1.5
                if tta_zoom_default != 1.0:
                    img_new = torchvision.transforms.functional.resize(
                        img_new, new_resize, interpolation=PIL.Image.BICUBIC)

                imgs_pil = []
                for tta_action in tta_actions:
                    tta_rotate, tta_brightness, tta_zoom, tta_contrast, tta_color, tta_blur, tta_att, _ = decode(
                        tta_action)
                    if tta_rotate != 0:
                        img_rotate = torchvision.transforms.functional.rotate(
                            img_new,
                            tta_rotate,
                            expand=False,
                            resample=PIL.Image.BICUBIC)
                    else:
                        img_rotate = img_new.copy()
                    if tta_brightness != 1.0:
                        img_bright = torchvision.transforms.functional.adjust_brightness(
                            img_rotate, tta_brightness)
                    else:
                        img_bright = img_rotate.copy()
                    if tta_zoom != 1.0:
                        resize = int(new_resize * tta_zoom)
                        img_zoom = torchvision.transforms.functional.resize(
                            img_bright,
                            resize,
                            interpolation=PIL.Image.BICUBIC)
                        assert img_zoom.width > 32, (img_zoom.size,
                                                     img_bright.size)
                    else:
                        img_zoom = img_bright.copy()

                    if tta_contrast > 0.0:
                        img_zoom = PIL.ImageOps.autocontrast(img_zoom)
                    assert img_zoom.width > 32, ('autocont', img_zoom.size,
                                                 img_bright.size, img_new.size)
                    if tta_color != 1.0:
                        img_zoom = PIL.ImageEnhance.Color(img_zoom).enhance(
                            tta_color)
                    assert img_zoom.width > 32, ('color', img_zoom.size,
                                                 img_bright.size, img_new.size)
                    if tta_blur != 1.0:
                        img_zoom = ImageEnhance.Sharpness(img_zoom).enhance(
                            tta_blur)
                    assert img_zoom.width > 32, ('blur', img_zoom.size,
                                                 img_bright.size, img_new.size)

                    w, h = img_zoom.size
                    att_padding = self.padding if self.padding else 0
                    pw, ph = max(0, self.target_size + att_padding - w), max(
                        0, self.target_size + att_padding - h)
                    pw1, ph1 = pw // 2, ph // 2
                    pw2, ph2 = pw - pw1, ph - ph1
                    if pw1 > 0 or ph1 > 0 or pw2 > 0 or ph2 > 0:
                        img_pad = torchvision.transforms.functional.pad(
                            img_zoom, (pw1, ph1, pw2, ph2),
                            random.randint(0, 255), 'reflect')
                    else:
                        img_pad = img_zoom
                    # img = torchvision.transforms.functional.center_crop(img_zoom, (self.target_size, self.target_size))

                    crop_width = crop_height = self.target_size
                    # print(tta_action, 'orig.size=', img_orig.size, 'zoom.size=', img_zoom.size, 'img_pad.size', img_pad.size, 'target_size=', self.target_size, 'padding=', self.padding)
                    if tta_att == 0:
                        img = pil_center_crop(img_pad, self.target_size)
                    elif tta_att == 1:
                        img_pad = pil_center_crop(
                            img_pad, int(self.target_size + att_padding))
                        img = img_pad.crop((0, 0, crop_width, crop_height))
                    elif tta_att == 2:
                        img_pad = pil_center_crop(
                            img_pad, int(self.target_size + att_padding))
                        image_width, image_height = img_pad.size
                        img = img_pad.crop((image_width - crop_width, 0,
                                            image_width, crop_height))
                    elif tta_att == 3:
                        img_pad = pil_center_crop(
                            img_pad, int(self.target_size + att_padding))
                        image_width, image_height = img_pad.size
                        img = img_pad.crop((0, image_height - crop_height,
                                            crop_width, image_height))
                    elif tta_att == 4:
                        img_pad = pil_center_crop(
                            img_pad, int(self.target_size + att_padding))
                        image_width, image_height = img_pad.size
                        img = img_pad.crop((image_width - crop_width,
                                            image_height - crop_height,
                                            image_width, image_height))
                    else:
                        raise Exception

                    imgs_pil.append(img)
                    self.img_pils = imgs_pil

                imgs = []
                for img in imgs_pil:
                    img = torchvision.transforms.functional.to_tensor(img)
                    img = torchvision.transforms.functional.normalize(
                        img,
                        mean=[0.485, 0.456, 0.406],
                        std=[0.229, 0.224, 0.225])
                    imgs.append(img)
                imgs = torch.stack(imgs).cuda()
                assert len(imgs) == tta_num

                with torch.no_grad():
                    preds = self.target_network(imgs)
                corrects = (torch.argmax(
                    preds,
                    dim=1).squeeze() == lb).detach().cpu().int().float()
                lbs = torch.tensor([lb] * tta_num).squeeze().cuda()
                # taus = torch.FloatTensor(tta_taus).detach()
                losses = torch.nn.functional.cross_entropy(
                    preds, lbs, reduction='none').detach().cpu()
                del preds
                if self.target_size > 32:  # TODO
                    torch.cuda.empty_cache()

                w, h = img_new.size
                pw, ph = max(0, self.target_size + self.padding - w), max(
                    0, self.target_size + self.padding - h)
                pw1, ph1 = pw // 2, ph // 2
                pw2, ph2 = pw - pw1, ph - ph1
                if pw1 > 0 or ph1 > 0 or pw2 > 0 or ph2 > 0:
                    img_new = torchvision.transforms.functional.pad(
                        img_new, (pw1, ph1, pw2, ph2), random.randint(0, 255),
                        'reflect')
                if img_new.size[0] >= self.target_size or img_new.size[
                        1] >= self.target_size:
                    # img_new = torchvision.transforms.functional.center_crop(img_new, self.target_size)
                    img_new = pil_center_crop(img_new, self.target_size)
                self.orig_img_pil = img_new

                img_new = cutout(img_new,
                                 cutsize=self.cutout * mirror_expansion_factor)

                if self.is_test:
                    return img_mirror, imgs_pil, img_new, losses, corrects

                img_new = torchvision.transforms.functional.resize(
                    img_new, self.l2t_size,
                    interpolation=PIL.Image.BICUBIC)  # TODO
                img_new = torchvision.transforms.functional.to_tensor(img_new)
                img_new = torchvision.transforms.functional.normalize(
                    img_new,
                    mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225]).cpu()

                n_img.append(img_new)
                n_lb.append(lb)
                n_losses.append(losses)
                n_corrects.append(corrects)
        return torch.stack(n_img), torch.Tensor(n_lb), torch.stack(
            n_losses), torch.stack(n_corrects)