file1 = open(r"C:\Users\Wu Jui Hsuan\Desktop\GCJ\proC.txt","r")
file = open(r"C:\Users\Wu Jui Hsuan\Desktop\GCJ\resultC.txt","w")

def mp():
    global file1
    return map(int,file1.readline().split())
def ip():
    global file1
    return file1.readline()
def it():
    global file1
    return int(file1.readline())
def lt():
    global file1
    return list(map(int,file1.readline().split()))
def ptlist(l):
    global file
    file.write(' '.join(map(str,l)))
#"Case #d: "
T = it()
for i in range(T):
    n = it()
    a = lt()
    for r in range(n):
        a[r] -= 1
    b = [[i for i in range(n) if a[i] == k] for k in range(n)]
    maxx = 0
    maxlen = []

    def backtracking():
        global L
        global a,b,maxx,maxlen
        k = L[-1]
        s = []
        for i in b[k]:
            if not i in L:
                s.append(i)
        if a[k] in L and len(s) == 0:
            if (a[L[0]] == L[1] or a[L[0]] == L[-1]) and (a[L[-1]] == L[0] or (len(L)>=2 and a[L[-1]] == L[-2])) and len(L) > maxx:
                maxlen = list(L)
                maxx = len(L)
        else:
            if len(L) <= 1 or L[-2] != a[k]:
                s = [a[k]]
            for t in s:
                L.append(t)
                backtracking()
                L.pop()
    for j in range(n):
        L = [j]
        backtracking()
    print("Case #%d: %d" % (i+1,maxx))
    file.write("Case #%d: %d\n" % (i+1,maxx))


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pylab import mpl
import seaborn as sns
import data

mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(facecolor='snow')
sns.set_style("darkgrid", {"font.sans-serif": ['simhei', 'Droid Sans Fallback','Times New Roman']})
font_size = 12
font_family = "SimHei"
font_weight = "bold"
plt.rc("font", size=font_size, family=font_family, weight=font_weight)
#  my_font = fm.FontProperties(fname="C:\\Windows\\Fonts\\simhei.ttf")

font2 = {'family' : 'Times New Roman',
'weight' : 'bold',
'size'   : 12,
}

# fig,ax=plt.subplots(figsize=(6.4,4.8), dpi=100)
fig,ax=plt.subplots(figsize=(6.4,4.8), dpi=100)

def drawLineStyle():
    #设置自变量的范围和个数
    x = ["BerNB", "MultiNB", "LogReg", "SVC" ,"LSVC", "NuSVC"]
    #画图
    ax.plot(x,data.bigram_accuracy_list, label='bigram', linestyle='-', marker='*',  markersize='10')
    ax.plot(x,data.bigram_words_accuracy_list, label='bigram_words', linestyle='--', marker='p', markersize='10')
    ax.plot(x,data.jieba_feature_accuracy_list, label='jieba_feature', linestyle='-.', marker='o', markersize='10')
    ax.plot(x,data.bag_of_words_accuracy_list, label='bag_of_words', linestyle=':', marker='x', markersize='10')
    #设置坐标轴
    #ax.set_xlim(0, 9.5)
    #ax.set_ylim(0, 1.4)
    ax.set_xlabel('Classifier', font2)
    ax.set_ylabel('Accuracy', font2)
    # ax.set_ylabel('F1-score', fontsize=15)
    #设置刻度
    ax.tick_params(axis='both', labelsize=12)
    #显示网格
    #ax.grid(True, linestyle='-.')
    ax.yaxis.grid(True, linestyle='-.')
    #添加图例
    legend = ax.legend(loc='best')

    plt.show()
    fig.savefig('res/pic/1.png',format='png', bbox_inches='tight', transparent=False, dpi=600)

def myPie():
    data = [1249,1462,1728,1771,978]
    labels = ['2015','2016','2017','2018','2019']
    explode = [0,0,0.3,0,0]
    colors = ['red','hotpink','purple','orange','yellow']
    plt.axes(aspect="equal") #保证正圆
    plt.xlim(0,8)
    plt.ylim(0,8)

    plt.gca().spines['right'].set_color('white')
    plt.gca().spines['top'].set_color('white')
    plt.gca().spines['left'].set_color('white')
    plt.gca().spines['bottom'].set_color('white')

    # 绘制饼图
    plt.pie(x=data,  # 绘制数据
            labels=labels,  # 添加编程语言标签
            explode=explode,  # 突出显示Python
            colors=colors,  # 设置自定义填充色
            autopct='%.2f%%',  # 设置百分比的格式,保留2位小数
            pctdistance=0.8,  # 设置百分比标签和圆心的距离
            labeldistance=1.37,  # 设置标签和圆心的距离
            startangle=160,  # 设置饼图的初始角度
            center=(4, 4),  # 设置饼图的圆心(相当于X轴和Y轴的范围)
            radius=2.6,  # 设置饼图的半径(相当于X轴和Y轴的范围)
            counterclock=False,  # 是否为逆时针方向,False表示顺时针方向
            wedgeprops={'linewidth': 1, 'edgecolor': 'pink'},  # 设置饼图内外边界的属性值
            # textprops={'fontsize': 19, 'color': 'black', 'fontproperties': my_font},  # 设置文本标签的属性值
            textprops={'fontsize': 10, 'color': 'black'},  # 设置文本标签的属性值
            frame=1)  # 是否显示饼图的圆圈,1为显示

    # 不显示X轴、Y轴的刻度值
    plt.xticks(())
    plt.yticks(())
    # 添加图形标题
    # plt.title('专利分布', fontproperties=my_font)
    # plt.title('distribution of Food')
    # 显示图形
    plt.show()
    fig.savefig('res/pic/4.png')

def axPie():
    fig, ax = plt.subplots(figsize=(8, 4), subplot_kw=dict(aspect="equal"))
    recipe  = ['2015y 1249',
               '2016y 1462',
               '2017y 1728',
               '2018y 1771',
               '2019y 978']
    data = [1249,1462,1728,1771,978]

    """
    参数wedgeprops以字典形式传递，设置饼图边界的相关属性，例如圆环宽度0.5
    饼状图默认从x轴正向沿逆时针绘图，参数startangle可指定新的角（例如负40度）度起画
    """
    wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)

    # 创建字典bbox_props，设置文本框的边框样式(boxstyle：方框，pad设置方框尺寸)、前景色(fc)为白色(w)、边框颜色(ec)为黑色(k)、线粗(lw)为0.72
    bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)

    """
    参数集kw以字典形式传递，包含一系列用于绘图标注的指定参数
    xycoords用于指定点xy的坐标环境，xycoords='data'表示沿用被注释的对象所采用的坐标系（默认设置）
    textcoords用于指定点xytext的坐标环境，textcoords='data'表示沿用被注释的对象所采用的坐标系（默认设置）
    参数arrowprops以字典形式传递，用于控制箭头的诸多属性，如箭头类型(arrowstyle)、箭头连接时的弯曲程度(connectionstyle)
    """
    kw = dict(xycoords='data', textcoords='data', arrowprops=dict(arrowstyle="-"),
              bbox=bbox_props, zorder=0, va="center")

    for i, p in enumerate(wedges):  # 遍历每一个扇形

        ang = (p.theta2 - p.theta1) / 2. + p.theta1  # 锁定扇形夹角的中间位置，对应的度数为ang

        # np.deg2rad(x)将度数x转为弧度(x*pi)/180
        y = np.sin(np.deg2rad(ang))  # np.sin()求正弦
        x = np.cos(np.deg2rad(ang))  # np.cos()求余弦

        """
        np.sign()符号函数：大于0返回1.0，小于0返回-1.0，等于0返回0.0
        参数horizontalalignment用于设置垂直对齐方式，可选参数：left、right、center
        当余弦值x大于0（即标签在饼图右侧时，按框左侧对齐）时，horizontalalignment="left"
        当余弦值x小于0（即标签在饼图左侧时，按框右侧对齐）时，horizontalalignment="right"
        """
        horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]

        connectionstyle = "angle,angleA=0,angleB={}".format(ang)  # 参数connectionstyle用于控制箭头连接时的弯曲程度
        kw["arrowprops"].update({"connectionstyle": connectionstyle})  # 将connectionstyle更新至参数集kw的参数arrowprops中

        """
        用一个箭头/横线指向要注释的地方，再写上一段话的行为，叫做annotate
        ax.annotate()用于对已绘制的图形做标注
        recipe[i]是第i个注释文本
        size设置字体大小
        xy=(x1, y1)表示在给定的xycoords中，被注释对象的坐标点
        xytext=(x2, y2)表示在给定的textcoords中，注释文本的坐标点
        """
        ax.annotate(recipe[i], size=15, xy=(x, y), xytext=(1.35 * np.sign(x), 1.4 * y),
                    horizontalalignment=horizontalalignment, **kw)

    ax.set_title("")
    plt.show()
    fig.savefig('res/pic/3.png')

from pyecharts import Line, Bar
# pip install pyecharts==0.1.9.4
def barDemo():
    list1 = data.bigram_F1Score_list #bigram
    list2 = data.bigram_words_F1Score_list #bigram_words
    list3 = data.jieba_feature_F1Score_list #jieba_feature
    list4 = data.bag_of_words_F1Score_list #bag_of_words
    # labes1 = ["bigram","bigram_words","jieba_feature","bag_of_words"]
    labes1 = ["BerNB", "MultiNB", "LogReg", "SVC" ,"LSVC", "NuSVC"]
    line = Line()
    line.add("bigram",labes1,list1,is_label_show=True)
    line.add("bigram_words",labes1,list2,is_label_show=True)
    line.add("jieba_feature",labes1,list3,is_label_show=True)
    line.add("bag_of_words",labes1,list4,is_label_show=True)
    line.render()

    bar = Bar()
    bar.add("bigram",labes1,list1)
    bar.add("bigram_words",labes1,list2)
    bar.add("jieba_feature",labes1,list3)
    bar.add("bag_of_words",labes1,list4)
    bar.render("res/2.html")

def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{:.2f}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, -7),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom',rotation=45)    # 'vertical'

def barDemo_notHtml():
    x = np.arange(3,21,3)
    width = 0.6
    axes_width = 3  # 刻度线宽度
    axes_length = 6  # 刻度线长度
    spines_width = 3  # 坐标轴的宽度
    fig, ax = plt.subplots(figsize=(6.4,4.8), dpi=500)
    labels = ["BerNB", "MultiNB", "LogReg", "SVC" ,"LSVC", "NuSVC"]
    rects1 = ax.bar(x - width*1.5, data.bigram_F1Score_list, width, color='#FF7F0E', alpha=0.6,label='bigram')  # 画第一批数据
    rects2 = ax.bar(x - width/2, data.jieba_feature_F1Score_list, width, color='#1F77B4', alpha=1,label='jieba')  # 画第二批数据
    rects3 = ax.bar(x + width/2, data.bag_of_words_F1Score_list, width, color='r', alpha=0.6,label='bag')  # 画第一批数据
    rects4 = ax.bar(x + width *1.5 , data.bigram_words_F1Score_list, width, color='c', alpha=1,label='bigram_words')  # 画第二批数据

    # Add some text for labels, title and custom x-axis tick labels, etc.
    ax.set_ylabel('F1-Scores', fontsize="large", weight=font_weight, family = "Arial")
    # ax.set_title('Scores by group and gender', fontsize="large", weight=font_weight, family="Arial")
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    # Left border is always shown
    # ax.spines["left"].set_linewidth(spines_width)
    for key in ("top", "bottom", "right","left"):
    # axes.spines[key].set_visible(False)
        ax.spines[key].set_linewidth(spines_width)

    ax.tick_params(axis="y", width=axes_width, length = axes_length)  # 刻度线
    ax.tick_params(axis="x", width=axes_width, length = axes_length)
    # plt.grid(axis='y') # 网格线 x,y,both  ,有点问题
    autolabel(rects1)   # 添加 标注
    autolabel(rects2)
    autolabel(rects3)   # 添加 标注
    autolabel(rects4)
    fig.tight_layout()

    # patches = [ mpatches.Patch(color=color[i], label="{:s}".format(labels[i]) ) for i in range(len(color)) ]
    ax=plt.gca()
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width , box.height])
    #下面一行中bbox_to_anchor指定了legend的位置
    # ax.legend(handles=patches, bbox_to_anchor=(0.95,1.12), ncol=4) #生成legend

    legend = ax.legend(edgecolor="w",bbox_to_anchor=(0.85,1.1), ncol=4)
    frame = legend.get_frame()
    frame.set_alpha(1)
    frame.set_facecolor('none') # 设置图例legend背景透明
    plt.show()
    # 保存为透明背景的图片
    fig.savefig('res/pic/4.png', format='png', bbox_inches='tight', transparent=True, dpi=600)

if __name__ == "__main__":
    drawLineStyle()
    # histDemo()
    # myPie()
    # barDemo()
    # barDemo_notHtml()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestZigZag(self, root: Optional[TreeNode]) -> int:

        def dfs(node, right, total):
            if not node:
                return total

            l = dfs(node.left, False, total + 1 if right else 1)
            r = dfs(node.right, True, total + 1 if not right else 1)

            return max(l, r)

        ans = dfs(root, None, 0)
        return ans - 1


from torch.utils.data import Dataset
import glob
import numpy as np
import SimpleITK as sitk
import torch
import albumentations as A

transformer = A.Compose([
    A.RandomCrop(height=160, width=160, always_apply=True),
    A.Resize(height=224, width=224)
])

class LGE_TrainSet(Dataset):
    def __init__(self, dir, sample_num, train):
        self.imgdir = dir + '/LGE/'

        if train:
            self.imgsname = glob.glob(self.imgdir + 'LGE_Test/*LGE.nii*')
        else:
            self.imgsname = glob.glob(self.imgdir + 'LGE_Vali/*LGE.nii*')

        imgs = np.zeros((1, 192, 192))
        labs = np.zeros((1, 192, 192))
        for img_num in range(sample_num):
            itkimg = sitk.ReadImage(self.imgsname[img_num])
            npimg = sitk.GetArrayFromImage(itkimg)  # Z,Y,X,220*240*1

            imgs = np.concatenate((imgs, npimg), axis=0)

            labname = self.imgsname[img_num].replace('.nii', '_manual.nii')
            itklab = sitk.ReadImage(labname)
            nplab = sitk.GetArrayFromImage(itklab)
            nplab = (nplab == 200) * 1 + (nplab == 500) * 2 + (nplab == 600) * 3

            labs = np.concatenate((labs, nplab), axis=0)

        self.imgs = imgs[1:, :, :]
        self.labs = labs[1:, :, :]
        self.imgs.astype(np.float32)
        self.labs.astype(np.float32)

    def __getitem__(self, item):
        npimg = self.imgs[item]
        nplab = self.labs[item]

        transformed = transformer(image=npimg, mask=nplab)
        npimg = transformed['image']
        nplab = transformed['mask']

        return torch.from_numpy(npimg).unsqueeze(0).type(dtype=torch.FloatTensor), \
               torch.from_numpy(nplab).type(dtype=torch.LongTensor)

    def __len__(self):
        return self.imgs.shape[0]

class C0_TrainSet(Dataset):
    def __init__(self, dir, sample_num):
        self.imgdir = dir + '/C0/'

        self.imgsname = glob.glob(self.imgdir + '*C0.nii*')

        imgs = np.zeros((1, 192, 192))
        labs = np.zeros((1, 192, 192))
        for img_num in range(sample_num):
            itkimg = sitk.ReadImage(self.imgsname[img_num])
            npimg = sitk.GetArrayFromImage(itkimg)  # Z,Y,X,220*240*1

            imgs = np.concatenate((imgs, npimg), axis=0)

            labname = self.imgsname[img_num].replace('.nii', '_manual.nii')
            itklab = sitk.ReadImage(labname)
            nplab = sitk.GetArrayFromImage(itklab)
            nplab = (nplab == 200) * 1 + (nplab == 500) * 2 + (nplab == 600) * 3

            labs = np.concatenate((labs, nplab), axis=0)

        self.imgs = imgs[1:, :, :]
        self.labs = labs[1:, :, :]
        self.imgs.astype(np.float32)
        self.labs.astype(np.float32)

    def __getitem__(self, item):
        npimg = self.imgs[item]
        nplab = self.labs[item]

        transformed = transformer(image=npimg, mask=nplab)
        npimg = transformed['image']
        nplab = transformed['mask']

        return torch.from_numpy(npimg).unsqueeze(0).type(dtype=torch.FloatTensor), \
               torch.from_numpy(nplab).type(dtype=torch.LongTensor)

    def __len__(self):
        return self.imgs.shape[0]

class Train_Dataset(Dataset):
    def __init__(self, dir, train):
        # dir = '/data02/imucs_data/machine58_img/wangxiaoming/dataset/MMWHS/Patch192'
        self.C0_dataset = C0_TrainSet(dir, 35)
        self.LGE_dataset = LGE_TrainSet(dir, 40, train)

        self.len_C0_dataset = self.C0_dataset.__len__()
        self.len_LGE_dataset = self.LGE_dataset.__len__()

        # print(self.len_C0_dataset)
        # print(self.len_LGE_dataset)

    def __len__(self):
        return self.len_C0_dataset if self.len_C0_dataset > self.len_LGE_dataset else self.len_LGE_dataset

    def __getitem__(self, item):
        source_image, source_label = self.C0_dataset.__getitem__(np.random.randint(low=0, high=self.len_C0_dataset))
        target_image, target_label = self.LGE_dataset.__getitem__(item)

        return source_image, source_label, target_image, target_label

if __name__ == '__main__':
    import os

    os.environ["CUDA_VISIBLE_DEVICES"] = '5'
    from torch.utils.data import Dataset, DataLoader

    path = '/data02/imucs_data/machine58_img/wangxiaoming/dataset/MMWHS/Patch192'
    train = False

    SourceData = LGE_TrainSet(path, 5, train)
    # SourceData = Train_Dataset(path, train)
    SourceData_loader = DataLoader(SourceData, batch_size=12, shuffle=True, num_workers=2, pin_memory=True,
                                   drop_last=True)
    print(SourceData.__len__())
    # for i in SourceData_loader:
    #     img, label = i
    #     print(img.shape)  # 12x1x160x160
    #     print(label.shape)  # 12x160x160

    '''
    数据读取一大缺陷：2D、没有增强

    数量：
    C0：35
    LGE,vali:5
    LGE,test:40

    预训练：C0数据用作预训练
    训练：C0与LGE的image组成对来进行训练，与C0的标签进行比较
    验证：LGE的image与label进行比较
    测试：LGE的test数据集中image与label进行比较
    '''

    # 数据集的分配可能有点问题，训练集少于验证集


# coding: utf-8

"""
    ExtremeCloud IQ API

    ExtremeCloud IQ RESTful API for external and internal applications.  # noqa: E501

    The version of the OpenAPI document: 23.6.0.46
    Contact: support@extremenetworks.com
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from extremecloudiq.configuration import Configuration

class XiqValidDuringDateSettings(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'start_date_time': 'XiqDateTimeType',
        'end_date_time': 'XiqDateTimeType',
        'time_zone': 'str'
    }

    attribute_map = {
        'start_date_time': 'start_date_time',
        'end_date_time': 'end_date_time',
        'time_zone': 'time_zone'
    }

    def __init__(self, start_date_time=None, end_date_time=None, time_zone=None, local_vars_configuration=None):  # noqa: E501
        """XiqValidDuringDateSettings - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._start_date_time = None
        self._end_date_time = None
        self._time_zone = None
        self.discriminator = None

        self.start_date_time = start_date_time
        self.end_date_time = end_date_time
        self.time_zone = time_zone

    @property
    def start_date_time(self):
        """Gets the start_date_time of this XiqValidDuringDateSettings.  # noqa: E501

        :return: The start_date_time of this XiqValidDuringDateSettings.  # noqa: E501
        :rtype: XiqDateTimeType
        """
        return self._start_date_time

    @start_date_time.setter
    def start_date_time(self, start_date_time):
        """Sets the start_date_time of this XiqValidDuringDateSettings.

        :param start_date_time: The start_date_time of this XiqValidDuringDateSettings.  # noqa: E501
        :type: XiqDateTimeType
        """
        if self.local_vars_configuration.client_side_validation and start_date_time is None:  # noqa: E501
            raise ValueError("Invalid value for `start_date_time`, must not be `None`")  # noqa: E501

        self._start_date_time = start_date_time

    @property
    def end_date_time(self):
        """Gets the end_date_time of this XiqValidDuringDateSettings.  # noqa: E501

        :return: The end_date_time of this XiqValidDuringDateSettings.  # noqa: E501
        :rtype: XiqDateTimeType
        """
        return self._end_date_time

    @end_date_time.setter
    def end_date_time(self, end_date_time):
        """Sets the end_date_time of this XiqValidDuringDateSettings.

        :param end_date_time: The end_date_time of this XiqValidDuringDateSettings.  # noqa: E501
        :type: XiqDateTimeType
        """
        if self.local_vars_configuration.client_side_validation and end_date_time is None:  # noqa: E501
            raise ValueError("Invalid value for `end_date_time`, must not be `None`")  # noqa: E501

        self._end_date_time = end_date_time

    @property
    def time_zone(self):
        """Gets the time_zone of this XiqValidDuringDateSettings.  # noqa: E501

        The date/time timezone  # noqa: E501

        :return: The time_zone of this XiqValidDuringDateSettings.  # noqa: E501
        :rtype: str
        """
        return self._time_zone

    @time_zone.setter
    def time_zone(self, time_zone):
        """Sets the time_zone of this XiqValidDuringDateSettings.

        The date/time timezone  # noqa: E501

        :param time_zone: The time_zone of this XiqValidDuringDateSettings.  # noqa: E501
        :type: str
        """
        if self.local_vars_configuration.client_side_validation and time_zone is None:  # noqa: E501
            raise ValueError("Invalid value for `time_zone`, must not be `None`")  # noqa: E501

        self._time_zone = time_zone

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, XiqValidDuringDateSettings):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, XiqValidDuringDateSettings):
            return True

        return self.to_dict() != other.to_dict()


import sys
input = sys.stdin.readline

grundy = [-1] * 2001
grundy[0] = 0
grundy[1] = 0
grundy[2] = 1

def mex(l):
    l = sorted(l)
    for i in range(len(l)):
        if i != l[i]:
            return i
    return len(l)

n = int(input().rstrip())
arr = list(map(int, input().rstrip().split()))

for i in range(3, max(arr)+1):
    s = []
    for k in range(1, i):
        first = k if (i // k) % 2 == 1 else 0
        second = i % k
        s.append((first, second))

    sr = set()
    for ss in s:
        sr.add(grundy[ss[0]] ^ grundy[ss[1]])

    grundy[i] = mex(sr)

result = 0
for a in arr:
    result ^= grundy[a]
if result == 0: print('Second')
else: print('First')


import uuid
from datetime import datetime
from decimal import Decimal

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from pytz import utc

from users.models import Base

ONSITE = 'OnSite'
OFFSITE = 'OffSite'
BOTH = 'Both'

ITEM_GROUP_TYPE_CHOICES = (
    (OFFSITE, OFFSITE),
    (ONSITE, ONSITE),
    (BOTH, BOTH),
)

class EventItem(Base):
    uuid = models.UUIDField(default=uuid.uuid4, db_index=True)
    item_master = models.ForeignKey('items.ItemMaster', on_delete=models.CASCADE)
    group = models.ForeignKey('events.EventItemGroup', on_delete=models.CASCADE)
    event = models.ForeignKey('events.Event', on_delete=models.CASCADE)
    event_registration_type = models.ForeignKey('events.EventRegistrationType', on_delete=models.CASCADE)
    group_type = models.CharField(max_length=10, choices=ITEM_GROUP_TYPE_CHOICES)
    item_capacity = models.PositiveIntegerField(validators=[MinValueValidator(int(1))])
    items_booked = models.PositiveIntegerField(default=0)
    item_sharing_count = models.PositiveIntegerField(validators=[MinValueValidator(int(1))])
    discount_before_early_bird = models.DecimalField(max_digits=5, decimal_places=2,
                                                     validators=[MinValueValidator(Decimal('0.00')),
                                                                 MaxValueValidator(Decimal('100.00'))])  # percentage
    discount_after_early_bird = models.DecimalField(max_digits=5, decimal_places=2,
                                                    validators=[MinValueValidator(Decimal('0.00')),
                                                                MaxValueValidator(Decimal('100.00'))])  # percentage
    is_day_pass_item = models.BooleanField()
    senior_citizen_discount_applicable = models.BooleanField(default=False)
    # start of fields applicable only for transportation items
    ask_for_arrival_datetime = models.BooleanField(default=False)
    ask_for_departure_datetime = models.BooleanField(default=False)
    ask_for_pickup_location = models.BooleanField(default=False)
    transportation_pickup_locations = models.ManyToManyField('events.TransportationPickupLocation', blank=True)
    # this is only for accommodation items
    accommodation_rooms = models.ManyToManyField('events.AccommodationRoom', blank=True)

    #  end of fields appliacable for only transportation items

    def __str__(self):
        return '{}'.format(self.item_master.name)

    def __repr__(self):
        return '{}'.format(self.item_master.name)

    class Meta:
        unique_together = ('item_master', 'event_registration_type', 'event', 'group_type')
        ordering = ('-created_at',)

    def get_early_bird_rate(self):
        return Decimal(self.item_master.item_rate) - (self.discount_before_early_bird / 100 * Decimal(
            self.item_master.item_rate))

    def get_late_bird_rate(self):
        return Decimal(self.item_master.item_rate) - (self.discount_after_early_bird / 100 * Decimal(
            self.item_master.item_rate))

    def get_current_rate(self):
        current_datetime = datetime.utcnow()
        if current_datetime.replace(tzinfo=utc) < self.event.early_bird_date.replace(tzinfo=utc):
            return self.get_early_bird_rate()
        else:
            return self.get_late_bird_rate()

# following statement to get the value of event items in csv from already existing database
# \copy (SELECT item_master_id,group_id,event_id,event_registration_type_id,group_type,item_capacity,
# items_booked,item_sharing_count,discount_before_early_bird,discount_after_early_bird,is_day_pass_item
# FROM events_eventitem) to 'eventitem_backup.csv' with csv;


from django.conf import settings
from django.db import models

from bleach import clean

from .utils import get_bleach_default_options

class BleachField(models.TextField):
    def __init__(self, allowed_tags=None, allowed_attributes=None,
                 allowed_styles=None, strip_tags=None, strip_comments=None,
                 *args, **kwargs):

        super(BleachField, self).__init__(*args, **kwargs)

        self.bleach_kwargs = get_bleach_default_options()

        if allowed_tags:
            self.bleach_kwargs['tags'] = allowed_tags
        if allowed_attributes:
            self.bleach_kwargs['attributes'] = allowed_attributes
        if allowed_styles:
            self.bleach_kwargs['styles'] = allowed_styles
        if strip_tags:
            self.bleach_kwargs['strip'] = strip_tags
        if strip_comments:
            self.bleach_kwargs['strip_comments'] = strip_comments

    def pre_save(self, model_instance, add):
        return clean(
            getattr(model_instance, self.attname),
            **self.bleach_kwargs
        )

if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules
    # Bleach attributes don't influence on data representation so we use
    # default introspection rules of TextField
    add_introspection_rules([], ['^django_bleach\.models\.BleachField'])


import os.path as osp
import torch
from torch import nn
import torch.nn.functional as F
from torch_geometric.nn import GraphUNet
from examples.core.base_model import BaseModel

class GraphUNetModel(BaseModel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.save_hyperparameters()

        assert kwargs["num_layers"] >= 2

        self.unet = GraphUNet(
            kwargs["num_features"],
            kwargs["hidden_channels"],
            kwargs["num_classes"],
            depth=kwargs["num_layers"],
            pool_ratios=kwargs["pool_ratios"],
        )

    def forward(self, batch):
        x = self.unet(batch.x, batch.edge_index[0])
        return x, 0


rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

#input from user
user_input = input("Type either 'rock', 'paper' or scissors :\n").lower()

print("User Choose:")
print(user_input)
#putting it in a list for the computer
result = [rock,paper, scissors]

#Generate random result for the Computer
import random
computer = result[random.randint(1,3)-1]
print(computer)

#Who WON, Who Lose?
if user_input == "rock":
    if computer == rock:
        print("It's a draw. Nobody Wins, repeat!")
    elif computer == paper:
        print("Paper cover up the whole rock and therefore is greater.\n You Lose")
    elif computer == scissors:
         print("One hit with the rock, destroys the scissors.\nYou win!")
elif user_input == "paper":
  if computer == rock:
    print("Paper is greater than the rock and eats the rock. You win!")
  elif computer == paper:
    print("It's a draw! Try again!")
  elif computer == scissors:
    print("Ohnoo, scissors cut the paper. You lose!")

elif user_input == "scissors":
  if computer == rock:
    print("Ohnoo! One hit by the rock breaks the scissors in two pieces. You lose!")
  elif computer == paper:
    print("Scissors cut the paper. You win!")
  elif computer == scissors:
    print("It's a draw. Try again!")

else:
  print("I don't understand your input...\nDo you chose either rock, paper or scissors?\n")

Python_Projects-main/Rock, Paper and Scissor.py


from typing import List
class Solution:
    def pancakeSort(self, arr: List[int]) -> List[int]:
        n = len(arr) -1
        output = []

        def flip(start,end):
            while start < end:
                arr[start],arr[end] = arr[end],arr[start]
                start += 1
                end -= 1
        for i in range(n,-1,-1):
            maxVIndex = i
            for j in range(0,i):
                if arr[j] > arr[maxVIndex]:
                    maxVIndex = j

            if maxVIndex != i:
                flip(0,maxVIndex) # bring the maximum element to index 0
                output.append(maxVIndex+1)
                flip(0,i)               #flip it to the last index of the array
                output.append(i+1)

        return output

s = Solution()
print(s.pancakeSort([3,2,4,1]))


import cv2

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

genislik = cap.get(3)  # get(3) ile genislik degeri 4 ile de yukseklik degeri float olarak bulundu
yukseklik = cap.get(4)

print(genislik)
print(yukseklik)

cap.set(3, genislik*2)  # set ile istenilen aralik yeniden boyutlandirildi
cap.set(4, yukseklik*2)

genislik = cap.get(3)
yukseklik = cap.get(4)

print(genislik)
print(yukseklik)

while True:
    ret, frame = cap.read()

    if ret == 0:
        break

    frame = cv2.flip(frame, 1)

    cv2.imshow("frame", frame)

    if cv2.waitKey(5) & 0xFF == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()


#!/usr/bin/env python

import numpy as np
from scipy.spatial import ConvexHull

def PolyArea2D(pts):
    lines = np.hstack([pts,np.roll(pts,-1,axis=0)])
    area = 0.5*abs(sum(x1*y2-x2*y1 for x1,y1,x2,y2 in lines))
    return area

isQuitTrue = False
pointList = []

print("Program to Calculate Convex Hull Area")

while(isQuitTrue==False):
    myInput = input("Press 'c' To Enter Coordinates or Press 'q' To Exit: ")

    if(myInput=="q" or myInput=="Q"):
        isQuitTrue = True
        break

    elif(myInput=="c" or myInput=="C"):
        xCoordinate = int(input("Enter x coordinate: "))
        yCoordinate = int(input("Enter y coordinate: "))
        pointList.append([xCoordinate,yCoordinate])

        continueInput = input("To continue adding points precc 'c', to calculate area press 'a': ")
        if(continueInput=="c" or continueInput =="C"):
            continue
        elif(myInput=="a" or myInput=="A"):
            isQuitTrue = True
    else:
        print("Invalid input try again\n")

print("Your list of points: ",pointList)
print("Area: ", PolyArea2D(pointList))

points = np.array([(1, 2), (3, 4), (3, 6), (2, 4.5), (2.5, 5)])
hull = ConvexHull(pointList)

np.random.seed(1)
random_points = np.random.uniform(0, 6, (100, 2))
#print("randpoints: ",random_points)

# get array of boolean values indicating in hull if True
in_hull = np.all(np.add(np.dot(random_points, hull.equations[:,:-1].T),
                        hull.equations[:,-1]) <= 0.5, axis=1)

random_points_in_hull = random_points[in_hull]

#print(random_points_in_hull)

howManyNumInHull = 0

for i in range(len(random_points_in_hull)):
    howManyNumInHull+=1
print("What percent is in this area: ",howManyNumInHull/100)


""" pete's version """
def merge(arr1, arr2):
    output = []
    start_length_arr1 = len(arr1)
    start_length_arr2 = len(arr2)
    target_output_length = start_length_arr1 + start_length_arr2

    # OR:
    # while len(arr1) > 0 or len(arr2) > 0
    while len(output) < target_output_length:
        print('-----')
        print('arr1', arr1)
        print('arr2', arr2)
        print('output', output)

        if len(arr1) == 0:
            output += arr2
            arr2 = []
        elif len(arr2) == 0:
            output += arr1
            arr1 = []
        elif arr1[0] < arr2[0]:
            output.append(arr1[0])
            arr1 = arr1[1:]
        else:
            output.append(arr2[0])
            arr2 = arr2[1:]

    return output

# helper split function
def split(arr):
    print('splitting: ', arr)
    midpoint = len(arr) // 2
    arr1 = arr[:midpoint]
    arr2 = arr[midpoint:]

    if len(arr1) <= 1 and len(arr2) <= 1:
        # fire base case
        return merge(arr1, arr2)

    split_arr1 = split(arr1)
    split_arr2 = split(arr2)
    return merge(split_arr1, split_arr2)

print(split([4,5,7,8,2,1]))

# print(merge([2], [4]))
# print(merge([1, 3], [2, 4]))

# def merge(a, b):
#     merged_list = []
#     i = 0
#     j = 0
#     while i < len(a) and j < len(b):
#         if a[i] < b[j]:
#             merged_list.append(a[i])
#             i += 1
#         else:
#             # append whichever is smaller on to merged_list
#             merged_list(b[j])
#             j += 1
#     if len(a) > i:
#         merged_list = merged_list + a
#     elif len(b) > j:
#         merged_list = merged_list + b
#     return merged_list

# def merge_sort(n):
#     if len(n) <= 1:
#         return n

#     split_point = int(len(n) / 2)
#     left = merge_sort(n[:split_point])
#     right = merge_sort(n[split_point:])

#     return merge(left, right)

# print(merge_sort([2,6,9,3,5,7,2,7,0,2]))


'''
Our game will use words of 5 letters - any you will find in this list, including plurals like books and verbs in past
like bowed.

Input data contains a number N of word pairs to process.
Next N lines contain two words each.
Answer should contain minimum length of the path between words for each pair - i.e. the total count of words in the
chain, including starting and ending ones.

Example:

input data:
2
girls women
mayor clown

answer:
9 14

Here the following paths are possible:

women woken token tokes tikes tiles tills gills girls

mayor manor minor miner mines miles moles molts moots boots blots blows blown clown
'''
from sys import stdin

def ladder_len(start_word, end_word, dictionary):
    curr, next, explored = [start_word], [], set(start_word,)
    length = 1
    while curr:
        for word in curr:
            if word == end_word:
                return length
            for i in range(len(word)):
                for char in 'abcdefghijklmnopqrstuvwxyz':
                    next_word = word[:i] + char + word[i + 1:]
                    if next_word not in explored and next_word in dictionary:
                        next.append(next_word)
                        explored.add(next_word)
        length += 1
        curr = next
        next = []
    return 0

with open('words.txt', 'r') as f:
    dictionary = set([line.rstrip() for line in f.readlines()])
    # print(ladder_len('mayor', 'clown', dictionary))
    print(*[ladder_len(*line.rstrip().split(), dictionary) for i, line in enumerate(stdin) if i > 0])


from systems.stage import SystemStage
from copy import copy

from syscore.objects import resolve_function

class RawData(SystemStage):

    """
        A SystemStage that does some fairly common calculations before we do
        forecasting and which gives access to some widely used methods.

            This is optional; forecasts can go straight to system.data
            The advantages of using RawData are:
                   - preliminary calculations that are reused can be cached, to
                     save time (eg volatility)
                   - preliminary calculations are available for inspection when
                     diagnosing what is going on

    KEY INPUTS: system.data.get_daily_prices(instrument_code)
               found in self.get_daily_prices

    KEY OUTPUTS: system.rawdata.... several

    Name: rawdata
    """

    def __init__(self):
        """
        Create a new stage: raw data object

        """

        setattr(self, "name", "rawdata")
        setattr(self, "description", "")

    def _system_init(self, system):
        # method called once we have a system
        setattr(self, "parent", system)

    def get_daily_prices(self, instrument_code):
        """
        Gets daily prices

        :param instrument_code: Instrument to get prices for
        :type trading_rules: str

        :returns: Tx1 pd.DataFrame

        KEY OUTPUT
        """
        def _daily_prices(system, instrument_code, this_stage):
            this_stage.log.msg(
                "Calculating daily prices for %s" %
                instrument_code,
                instrument_code=instrument_code)
            dailyprice = system.data.daily_prices(instrument_code)
            return dailyprice

        dailyprice = self.parent.calc_or_cache(
            "daily_price", instrument_code, _daily_prices, self)

        return dailyprice

    def daily_denominator_price(self, instrument_code):
        """
        Gets daily prices for use with % volatility
        This won't always be the same as the normal 'price' which is normally a cumulated total return series

        :param instrument_code: Instrument to get prices for
        :type trading_rules: str

        :returns: Tx1 pd.DataFrame

        KEY OUTPUT

        >>> from systems.tests.testdata import get_test_object
        >>> from systems.basesystem import System
        >>>
        >>> (rawdata, data, config)=get_test_object()

        >>> system=System([rawdata], data)
        >>> system.rawdata.daily_denominator_price("EDOLLAR").head(2)
                        price
        1983-09-26  71.241192
        1983-09-27  71.131192
        """
        def _daily_denominator_returns(system, instrument_code, this_stage):

            dem_returns = this_stage.get_daily_prices(instrument_code)
            return dem_returns

        dem_returns = self.parent.calc_or_cache(
            "daily_denominator_price", instrument_code, _daily_denominator_returns, self)

        return dem_returns

    def daily_returns(self, instrument_code):
        """
        Gets daily returns (not % returns)

        :param instrument_code: Instrument to get prices for
        :type trading_rules: str

        :returns: Tx1 pd.DataFrame

        KEY OUTPUT

        >>> from systems.tests.testdata import get_test_object
        >>> from systems.basesystem import System
        >>>
        >>> (rawdata, data, config)=get_test_object()
        >>> system=System([rawdata], data)
        >>> system.rawdata.daily_returns("EDOLLAR").tail(2)
                     price
        2015-12-10 -0.0650
        2015-12-11  0.1075
        """
        def _daily_returns(system, instrument_code, this_stage):
            instrdailyprice = this_stage.get_daily_prices(instrument_code)
            dailyreturns = instrdailyprice.diff()
            return dailyreturns

        dailyreturns = self.parent.calc_or_cache(
            "daily_returns", instrument_code, _daily_returns, self)

        return dailyreturns

    def daily_returns_volatility(self, instrument_code):
        """
        Gets volatility of daily returns (not % returns)

        This is done using a user defined function

        We get this from:
          the configuration object
          or if not found, system.defaults.py

        The dict must contain func key; anything else is optional

        KEY OUTPUT

        :param instrument_code: Instrument to get prices for
        :type trading_rules: str

        :returns: Tx1 pd.DataFrame

        >>> from systems.tests.testdata import get_test_object
        >>> from systems.basesystem import System
        >>>
        >>> (rawdata, data, config)=get_test_object()
        >>> system=System([rawdata], data)
        >>> ## uses defaults
        >>> system.rawdata.daily_returns_volatility("EDOLLAR").tail(2)
                         vol
        2015-12-10  0.054145
        2015-12-11  0.058522
        >>>
        >>> from sysdata.configdata import Config
        >>> config=Config("systems.provided.example.exampleconfig.yaml")
        >>> system=System([rawdata], data, config)
        >>> system.rawdata.daily_returns_volatility("EDOLLAR").tail(2)
                         vol
        2015-12-10  0.054145
        2015-12-11  0.058522
        >>>
        >>> config=Config(dict(volatility_calculation=dict(func="syscore.algos.robust_vol_calc", days=200)))
        >>> system2=System([rawdata], data, config)
        >>> system2.rawdata.daily_returns_volatility("EDOLLAR").tail(2)
                         vol
        2015-12-10  0.057946
        2015-12-11  0.058626

        """
        def _daily_returns_volatility(system, instrument_code, this_stage):
            this_stage.log.msg(
                "Calculating daily volatility for %s" %
                instrument_code,
                instrument_code=instrument_code)

            dailyreturns = this_stage.daily_returns(instrument_code)

            volconfig = copy(system.config.volatility_calculation)

            # volconfig contains 'func' and some other arguments
            # we turn func which could be a string into a function, and then
            # call it with the other ags
            volfunction = resolve_function(volconfig.pop('func'))
            vol = volfunction(dailyreturns, **volconfig)

            return vol

        vol = self.parent.calc_or_cache(
            "daily_returns_volatility", instrument_code, _daily_returns_volatility, self)

        return vol

    def get_daily_percentage_volatility(self, instrument_code):
        """
        Get percentage returns normalised by recent vol

        Useful statistic, also used for some trading rules

        This is an optional subsystem; forecasts can go straight to system.data
        :param instrument_code: Instrument to get prices for
        :type trading_rules: str

        :returns: Tx1 pd.DataFrame

        >>> from systems.tests.testdata import get_test_object
        >>> from systems.basesystem import System
        >>>
        >>> (rawdata, data, config)=get_test_object()
        >>> system=System([rawdata], data)
        >>> system.rawdata.get_daily_percentage_volatility("EDOLLAR").tail(2)
                         vol
        2015-12-10  0.055281
        2015-12-11  0.059789
        """
        def _get_daily_percentage_volatility(
                system, instrument_code, this_stage):
            denom_price = this_stage.daily_denominator_price(instrument_code)
            return_vol = this_stage.daily_returns_volatility(instrument_code)
            (denom_price, return_vol) = denom_price.align(
                return_vol, join="right")
            perc_vol = 100.0 * \
                (return_vol / denom_price.shift(1))

            return perc_vol

        perc_vol = self.parent.calc_or_cache(
            "daily_percentage_volatility", instrument_code, _get_daily_percentage_volatility, self)
        return perc_vol

    def norm_returns(self, instrument_code):
        """
        Get returns normalised by recent vol

        Useful statistic, also used for some trading rules

        This is an optional subsystem; forecasts can go straight to system.data
        :param instrument_code: Instrument to get prices for
        :type trading_rules: str

        :returns: Tx1 pd.DataFrame

        >>> from systems.tests.testdata import get_test_object
        >>> from systems.basesystem import System
        >>>
        >>> (rawdata, data, config)=get_test_object()
        >>> system=System([rawdata], data)
        >>> system.rawdata.norm_returns("EDOLLAR").tail(2)
                    norm_return
        2015-12-10    -1.219510
        2015-12-11     1.985413
        """
        def _norm_returns(system, instrument_code, this_stage):
            this_stage.log.msg(
                "Calculating normalised prices for %s" %
                instrument_code,
                instrument_code=instrument_code)

            returnvol = this_stage.daily_returns_volatility(
                instrument_code).shift(1)
            dailyreturns = this_stage.daily_returns(instrument_code)
            norm_return = dailyreturns / returnvol
            return norm_return

        norm_returns = self.parent.calc_or_cache(
            "_norm_return_dict", instrument_code, _norm_returns, self)

        return norm_returns

if __name__ == '__main__':
    import doctest
    doctest.testmod()


"""
# Runtime - 139 ms
# Beats 27.94%

# Memory - 13.9 MB
# Beats 58.55%

# Time Complexity - O(log(n))
# Space Complexity - O(1)
"""

def isPalindrome(x):
    if x < 0:
        return False

    n = 0
    y = 0

    # Finding the number of digits in `x`
    while x // (10 ** n) != 0:
        n += 1

    # Deriving the reverse of `x`
    for i in range(n):
        d = (x // (10 ** i)) % 10
        m = 10 ** (n - i - 1)
        y += d * m

    return x == y


import json

class Question:
    def __init__(self, text: str, answers: list, right_answer: int):
        self.right_answer = right_answer
        self.answers = answers
        self.text = text

    def to_json(self):
        return json.dumps(self,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def from_json(json_str: str):
        loaded_json = json.loads(json_str)
        text = loaded_json['text']
        answers = loaded_json['answers']
        right_answer = loaded_json['right_answer']

        question = Question(text, answers, right_answer)
        return question

if __name__ == '__main__':
    json_str = '{"text": "asd", "answers": [1, 2, 3], "right_answer": 1}'
    a = Question.from_json(json_str)


# # Importing the necessary libraries:

import re
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.svm import NuSVC
from sklearn.metrics import classification_report
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import pandas as pd
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

# # Loading the 20 Newsgroups dataset for the specified classes:

categories = ['comp.graphics', 'misc.forsale', 'rec.sport.baseball', 'soc.religion.christian', 'talk.politics.guns']
newsgroups_data = fetch_20newsgroups(categories=categories, subset='all', remove=('headers', 'footers', 'quotes'))

newsgroups_data.filenames.shape

# # Get the category labels

labels = newsgroups_data.target

# #  Prepocessing the texts :
# * Transorm to LowerCase
# * Remove Punctuation
# * Remove dates
# * Tokenize
# * Remove StopWords

preprocessed_texts = []
for text in newsgroups_data.data:
    # Lowercase the text
    text = text.lower()
    # Remove punctuations, quotations, and dates
    text = re.sub(r'[^\w\s]', '', text)
    text = re.sub(r'\d+', '', text)
    # Tokenize the text
    tokens = word_tokenize(text)
    # Remove stopwords
    tokens = [word for word in tokens if word not in stopwords.words('english')]

    # Append the preprocessed text to the list
    preprocessed_texts.append(' '.join(tokens))

# ## Create a DataFrame with labels and preprocessed texts:

data = pd.DataFrame({'labels': labels, 'preprocessed_texts': preprocessed_texts})
data

# # Feature Extraction Based On TF-IDF :

# ## Initialize the TF-IDF vectorizer

vectorizer = TfidfVectorizer()

# ## Fit the vectorizer on the preprocessed texts to learn the vocabulary and IDF values

vectorizer.fit(preprocessed_texts)

# ## Transform the preprocessed texts into TF-IDF feature vectors

features = vectorizer.transform(preprocessed_texts)

print(features.shape)
print(labels.shape)

# # Classification using SVM :

# ## Splitting into Train-Test

X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, shuffle=True, random_state=42)

# ## Initialize the Nu-SVC classifier with the specified maximum value of nu (0.5 in this case)

svm = NuSVC(nu=0.5)

# ## Train the SVM classifier

svm.fit(X_train, y_train)

# ## Make predictions on the testing data

y_pred = svm.predict(X_test)

# ## Calculate precision

precision = precision_score(y_test, y_pred, average='weighted')
print(f"Precision: {precision:.4f}")

# ## Calculate recall

recall = recall_score(y_test, y_pred, average='weighted')
print(f"Recall: {recall:.4f}")

# ## Calculate F1-score

f1 = f1_score(y_test, y_pred, average='weighted')
print(f"F1-score: {f1:.4f}")

# ## Calculate the classification report

report = classification_report(y_test, y_pred)

print(report)


import os
import logging
from huggingface_deploy.nlp.token_classification_demo.classifier import TokenClassifer

logger = logging.getLogger(__name__)

class HuaziExtract():
    def __init__(self, file_name=None, **kwargs):
        super(HuaziExtract, self).__init__(file_name, **kwargs)
        tokenizer_dir = file_name
        model_path = os.path.join(file_name, kwargs.get("onnx_name", "best.onnx"))
        model="bert"
        label_list = kwargs.get("label_list", [])
        self.classifier = TokenClassifer(tokenizer_dir, model_path, model, label_list)

    def convert_input(self, data):
        """
        转换输入数据的格式

        Parameters
        ----------
        data : list[dict]
            输入的数据
        data[*].raw_str : str
            原始的字符串

        Returns
        -------
        classifier_input : dict
            输入的数据
        classifier_input.tokens : list[str]
            输入的句子列表
        """
        classifier_input = {"tokens": []}
        for item in data:
            classifier_input["tokens"].append(item["raw_str"])
        return classifier_input

    def predict(self, data, **kwargs):
        """
        通过tokenizer处理输入的字符串，并通过onnx对token进行分类

        Parameters
        ----------
        data : list[dict]
            输入的数据
        data[*].raw_str : str
            原始的字符串

        Returns
        -------
            即self.classifier的输出
        """
        classifier_input = self.convert_input(data)
        results = self.classifier.predict(classifier_input, **kwargs)
        return results

if __name__ == "__main__":
    model_path = ""
    kwargs = {
        "onnx_name": "best.onnx",
        "label_list": ["O", "B-MAIN", "I-MAIN"]
    }

    model = HuaziExtract(file_name=model_path, **kwargs)

    data = [
        {"raw_str": "这瓶雅诗兰黛面霜效果非常好，能让脸润润的，有光泽"}
    ]

    result = model.predict(data)
    logger.fatal("result:{}".format(result))
    print("result:{}".format(result))


# To start, command line
# > hug -f api.py

import hug
import base64

from SkillsComparer import SkillsComparer

@hug.response_middleware()
def process_data(request, response, resource):
    response.set_header('Access-Control-Allow-Origin', '*')

@hug.get('/home')
def root():
    return 'Welcome home!'

@hug.get('/add', examples='/add?first_num=6&second_num=8')
def do_add(first_num: hug.types.number, second_num: hug.types.number):
    return {'Final Result:': first_num + second_num}

@hug.get('/send')
def receive_data(firstName: hug.types.text, lastName: hug.types.text, position: hug.types.text, link: hug.types.text, skills: hug.types.text, resume: hug.types.text):

    #debug
    values = {'firstname': firstName, 'lastName': lastName, 'position': position, 'link': link,
               'resume': resume, 'skills': base64.b64decode(skills)}

    skills_class = SkillsComparer()

    api_firstName = firstName
    api_lastName = lastName
    api_position = position
    api_link = link
    #list of skills is array
    api_skills = base64.b64decode(skills).decode('utf-8').split("|")
    api_skills.pop(0)

    #Strip duplicates
    api_skills = list(set(api_skills))
    if api_skills[0] == '':
        api_skills.pop(0)
    print("SKILLS FROM SKILLS LIST: " + str(api_skills))

    # get all the resume stuff, remove duplicates
    api_resume = resume.strip()
    api_resume = list(set(api_resume.split()))
    print("SKILLS FROM RESUME: " + str(api_resume))
    api_resume = skills_class.returnTechTerms(api_resume)
    print("SKILLS FROM RESUME IN SKILLS LIST: " + str(api_resume))

    print("Extending resume to skills list")
    api_skills.extend(api_resume)

    print("FINAL SKILLS LIST: " + str(api_skills))

    scrape_method = skills_class.scrape_link
    scrape_method(api_link)

    extra_skill_call = skills_class.getExtraJobSkills
    extraJobSkills = extra_skill_call(api_skills)
    print("SKILLS FROM Job NOT IN SKILLS_LIST: " + str(extraJobSkills))
    extra_skill_list_call_call = skills_class.getExtraSkillsListSkills
    extraSkillsListSkills = extra_skill_list_call_call(api_skills)
    print("SKILLS FROM SKILLS_LIST NOT IN JOB: " + str(extraSkillsListSkills))

    notInSkillsInJob = "|".join(list(set(extraJobSkills)))
    if notInSkillsInJob != "" and "|" in notInSkillsInJob:
        notInSkillsInJob = notInSkillsInJob[1:]
    notInJobInSkills = "|".join(extraSkillsListSkills)
    if notInJobInSkills != "" and "|" in notInJobInSkills:
        notInJobInSkills = notInJobInSkills[1:]
    inSkillsinJob = skills_class.getSimilarSkills(api_skills)
    inSkillsinJob = "|".join(list(set(inSkillsinJob)))
    if inSkillsinJob != "" and "|" in inSkillsinJob:
        inSkillsinJob = inSkillsinJob[1:]
    print("SKILLS IN JOB AND LIST:" + inSkillsinJob)
    return {'1':inSkillsinJob,'2': notInSkillsInJob, '3': notInJobInSkills}
    #return {'1':'abc|def','2':'yuuu2','3':'skillsboi|a|b'}

def buildCoverLetter():
    pass

def getExtraSkills():
    pass

print("Running API!")


#!/usr/bin/env python
import rospy
import numpy as np
import math
from geometry_msgs.msg import Twist
from simulation_control.msg import InputValues

TIMESTEP = 0.05

def get_jacobian_and_wheel_speed(robot_data):

    if(robot_data.robot_type == 1):

        l_diff = robot_data.width/2

        diff_J_1 = np.array([[1,0,l_diff],
                             [1,0,-l_diff],
                             [0,1,0]])

        diff_J_2 = np.array([[robot_data.wheels[0].radius*robot_data.wheels[0].angular_velocity],
                             [robot_data.wheels[1].radius*robot_data.wheels[1].angular_velocity],
                             [0]])

        return diff_J_1, diff_J_2
    elif(robot_data.robot_type == 2):

        l_mecanum = math.sqrt((robot_data.width/2)**2 + (robot_data.length/2)**2)
        alpha_1 = math.atan(robot_data.width/robot_data.length)

        mecanum_J_1 = np.array([[math.sqrt(2)/2, -math.sqrt(2)/2, -l_mecanum*math.cos((math.pi/4)-alpha_1)],
                                [math.sqrt(2)/2, math.sqrt(2)/2, -l_mecanum*math.cos((3*math.pi/4)+alpha_1)],
                                [math.sqrt(2)/2, math.sqrt(2)/2, -l_mecanum*math.cos((-math.pi/4)+alpha_1)],
                                [math.sqrt(2)/2, -math.sqrt(2)/2, -l_mecanum*math.cos((-3*math.pi/4)-alpha_1)]])

        mecanum_J_2 = np.array([[robot_data.wheels[0].radius*robot_data.wheels[0].angular_velocity*math.cos(-math.pi/4)],
                                [robot_data.wheels[1].radius*robot_data.wheels[1].angular_velocity*math.cos(math.pi/4)],
                                [robot_data.wheels[2].radius*robot_data.wheels[2].angular_velocity*math.cos(math.pi/4)],
                                [robot_data.wheels[3].radius*robot_data.wheels[3].angular_velocity*math.cos(-math.pi/4)]])

        return mecanum_J_1, mecanum_J_2
    elif(robot_data.robot_type == 3):

        l_omni = robot_data.width/2

        omni_J_1 = np.array([[math.sin(math.pi/3),-0.5,-l_omni],
                             [0,1,-l_omni],
                             [-math.sin(math.pi/3),-0.5,-l_omni]])

        omni_J_2 = np.array([[robot_data.wheels[0].radius*robot_data.wheels[0].angular_velocity],
                             [robot_data.wheels[1].radius*robot_data.wheels[1].angular_velocity],
                             [robot_data.wheels[2].radius*robot_data.wheels[2].angular_velocity]])

        return omni_J_1, omni_J_2
    else:
        rospy.loginfo('%d is not a valid Robot Type!\nRobot Types:\n1 = Differential Drive Mobile Robot\n2 = Omnidirectional Drive Mobile Robot\n3 = Tricycle Drive Mobile Robot', robot_data.robot_type)

def calculate_odom_values(robot_type, jacobian, wheel_speed):
    values = Twist()

    values.linear.z = 0
    values.angular.x = 0
    values.angular.y = 0

    if(robot_type == 2):
        j_1p = np.dot(np.linalg.inv(np.dot(np.transpose(jacobian),jacobian)),np.transpose(jacobian))
        temp_values = np.dot(j_1p,wheel_speed)
    else:
        temp_values = np.dot(np.linalg.inv(jacobian),wheel_speed)

    values.linear.x = temp_values[0]
    values.linear.y = temp_values[1]
    values.angular.z = temp_values[2]

    return values

def callback(data):

    control_data = Twist()

    j_1, j_2 = get_jacobian_and_wheel_speed(data)
    control_data = calculate_odom_values(data.robot_type,j_1,j_2)

    odom_pub.publish(control_data)
    rospy.sleep(rospy.Duration(TIMESTEP))

if __name__ == '__main__':

    rospy.init_node("odometry_sim", anonymous=True)
    rospy.Subscriber("vmr_input_data",InputValues,callback, queue_size=1)
    odom_pub = rospy.Publisher("cmd_vel",Twist,queue_size=1)
    rospy.spin()


import cv2
import matplotlib.pyplot as plt
import glob, os
from random import randint

def drawRects(path, im, color):
    with open(path) as f:
        rectFile = f.readlines()

    while len(rectFile) > 0:
        verticies = []
        for i in range(4):
            line = rectFile[i].rstrip("\n\r").split(" ")
            verticies.append((int(float(line[0])), int(float(line[1]))))

        cv2.line(im, verticies[0], verticies[1], color, 1)
        cv2.line(im, verticies[1], verticies[2], color, 2)
        cv2.line(im, verticies[2], verticies[3], color, 1)
        cv2.line(im, verticies[3], verticies[0], color, 2)

        rectFile = rectFile[4:]

imagePaths = glob.glob("./cornell/*.png")

for dispImages in range(5):
    randIndex = randint(0, len(imagePaths))
    imPath = imagePaths[randIndex]
    posPath = imPath[0:-5] + "cpos.txt"
    negPath = imPath[0:-5] + "cneg.txt"

    im = cv2.imread(imPath)

    drawRects(posPath, im, (100, 255, 100))
    #drawRects(negPath, im, (0, 0, 255))

    cv2.imshow('Test image',im)
    cv2.waitKey(0)

cv2.destroyAllWindows()


import numpy as np
import matplotlib.pyplot as plt
import exoplanet as xo
from scipy.interpolate import interp1d
from matplotlib.widgets import Slider, Button

def test_DW_per_epoch(x_detrended, y_detrended, yerr_detrended, mask_detrended, mask_fitted_planet_detrended, period, t0s, duration):
    from scipy.special import erfcinv

    #break up the epochs...
    x_split, y_split, yerr_split, mask_split, mask_fitted_planet_split = \
    split_around_transits(x_detrended, y_detrended, yerr_detrended,
                          mask_detrended, mask_fitted_planet_detrended,
                          t0s, float(6*duration/(24.))/period, period)

    #if len(x_split) != len(DWs):
    #    print('error mismatching number of epochs with DW array length')

    sigmas = []
    for ii in range(0, len(x_split)):
        x = x_split[ii]
        y = y_split[ii]
        yerr = yerr_split[ii]
        mask = mask_split[ii]
        mask_fitted_planet = mask_fitted_planet_split[ii]
        #DWdetrend = DWs[ii]

        ###determine native DW for a single epoch and a single detrended LC
        in_transit = False
        out_transit = True

        no_pre_transit = False
        no_post_transit = False
        for index in range(0, len(mask_fitted_planet)):
            mask_val = mask_fitted_planet[index]

            if out_transit:
                if mask_val:
                    in_transit_index = index

                    in_transit = True
                    out_transit = False

            if in_transit:
                if not mask_val:
                    out_transit_index = index

                    in_transit = False
                    out_transit = True

        if in_transit_index == 0:
            no_pre_transit = True

        if out_transit_index == len(x):
            no_post_transit = True

        if no_pre_transit:
            DWstat_pre_transit = 2.

        else:
            residuals_pre_transit = y[0:in_transit_index]
            if np.all(np.isnan(residuals_pre_transit)):
                DWstat_pre_transit = 2.
            else:
                DWstat_pre_transit = DurbinWatson(residuals_pre_transit)

        if no_post_transit:
            DWstat_post_transit = 2.
        else:
            residuals_post_transit = y[out_transit_index:len(y)]
            if np.all(np.isnan(residuals_post_transit)):
                DWstat_post_transit = 2.
            else:
                DWstat_post_transit = DurbinWatson(residuals_post_transit)

        DWdetrend = np.sqrt((DWstat_pre_transit-2.)**2. + (DWstat_post_transit-2.)**2.)

        ###create 10,000 white noise profiles and determine DW for epoch
        ###then count the number of these that have greater DW than detrended DW
        n_DWfake_greater_than_DWdetrend = 0
        for jj in range(0, 10000):

            if no_pre_transit:
                DWstat_fake_pre_transit = 2.
            else:
                fake_residuals_pre_transit = np.random.normal(loc=0.0,
                                                              scale=yerr[0:in_transit_index],
                                                              size=np.shape(yerr[0:in_transit_index]))
                DWstat_fake_pre_transit = DurbinWatson(fake_residuals_pre_transit)

            if no_post_transit:
                DWstat_fake_post_transit = 2.
            else:
                fake_residuals_post_transit = np.random.normal(loc=0.0,
                                                               scale=yerr[out_transit_index:len(yerr)],
                                                               size=np.shape(yerr[out_transit_index:len(yerr)]))
                DWstat_fake_post_transit = DurbinWatson(fake_residuals_post_transit)

            #determine DW for white noise data
            DWfake = np.sqrt((DWstat_fake_pre_transit-2.)**2. + (DWstat_fake_post_transit-2.)**2.)

            if DWfake > DWdetrend:
                n_DWfake_greater_than_DWdetrend += 1

        #calculate and save sigma value for each epoch
        sigma = np.sqrt(2.) * erfcinv(n_DWfake_greater_than_DWdetrend/10000.)
        sigmas.append(sigma)

    return sigmas

def reject_epochs_by_DW(x_detrended, y_detrended, yerr_detrended, mask_detrended, mask_fitted_planet_detrended, sigma_values, t0s):
    #break up the epochs...
    x_split, y_split, yerr_split, mask_split, mask_fitted_planet_split = \
    split_around_transits(x_detrended, y_detrended, yerr_detrended,
                          mask_detrended, mask_fitted_planet_detrended,
                          t0s, float(6*duration/(24.))/period, period)

    if len(x_split) == len(sigma_values):
        epochs = len(sigma_values)
    else:
        print("mistmatched array lengths!")
        print(len(x_split))
        print(len(sigma_values))
        return(None)

    y_detrended_out = []
    for ii in range(0, epochs):
        sigma = sigma_values[ii]
        if sigma > 2.:
            nan_array = np.empty(np.shape(y_split[ii]))
            y_split[ii][:] = np.nan

        y_detrended_out.extend(y_split[ii])

    return(np.array(y_detrended_out))


#! /usr/bin/env python3

import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from FeatureExtractor_ResNet50 import FeatureExtractor
from math import floor
from sklearn.metrics import confusion_matrix
import tensorflow as tf
'''config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config)'''

#os.environ['CUDA_VISIBLE_DEVICES'] = '0'
#CUDA_VISIBLE_DEVICES=""
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

class SVCClassificator:

    def __init__(self, ds_selection = "", kernel= ""):
        self.ds_selection = ds_selection
        self.kernel = kernel

    def execute(self):

        #device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        #device = torch.device('cpu')
        #print('Using device:' , device)
        #gpus = tf.config.experimental.list_physical_devices('CPU')

        '''gpus = tf.config.experimental.list_physical_devices('GPU')
        for device in gpus:
                tf.config.experimental.set_memory_growth(device, True)
        if gpus:
        # Restrict TensorFlow to only allocate 2GB of memory on the first GPU
            try:
                tf.config.experimental.set_virtual_device_configuration(
                    gpus[0],
                    [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=3800)])
                logical_gpus = tf.config.experimental.list_logical_devices('GPU')
                print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
            except RuntimeError as e:
                # Virtual devices must be set before GPUs have been initialized
                print(e)
        else:
            print('no gpus')'''

        # Confusion matrix lists
        Ccm_list = []
        Fcm_list = []
        Mcm_list = []

        for i in range(30):
                gpus = tf.config.list_physical_devices('CPU')
                print('CICLE: ' + str(i))
                '''gc.collect()
                torch.cuda.empty_cache()
                gpus = tf.config.list_physical_devices('GPU')
                if gpus:
                # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
                        try:
                                tf.config.set_logical_device_configuration(
                                gpus[0],
                                [tf.config.LogicalDeviceConfiguration(memory_limit=3000)])
                                logical_gpus = tf.config.list_logical_devices('GPU')
                                print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
                        except RuntimeError as e:
                # Virtual devices must be set before GPUs have been initialized
                                print(e)
                else:
                        print('Using CPU')'''
                ############################################################
                ############### READ DATA ##################################
                itd = FeatureExtractor(self.ds_selection)

                CX = itd.CX
                CXT = itd.CXT
                CY = itd.CY
                CYT = itd.CYT

                FX = itd.FX
                FXT = itd.FXT
                FY = itd.FY
                FYT = itd.FYT

                MX = itd.MX
                MXT = itd.MXT
                MY = itd.MY
                MYT = itd.MYT

                #####################################################################
                ################### MODEL SELECTION (HYPERPARAMETER TUNING)##########
                #device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
                #print('Using device:' , device)
                points = 80
                print('MODEL SELECTION AND TUNING')
                if self.kernel == 'rbf':
                    logspaceC = np.logspace(-2,2.5,points)
                    logspaceGamma = np.logspace(-2,2.5,points)
                if self.kernel == 'linear':
                    logspaceC = np.logspace(-2,2.5,points)
                    logspaceGamma = np.logspace(-2,2.5,points)
                grid = {'C':        logspaceC,
                        'kernel':   [self.kernel],
                        'gamma':    logspaceGamma}
                MS = GridSearchCV(estimator = SVC(),
                                param_grid = grid,
                                scoring = 'balanced_accuracy',
                                cv = 10,
                                verbose = 0)

                if self.ds_selection == "chinese":
                    H = MS.fit(CX,CY)
                if self.ds_selection == "french":
                    H = MS.fit(FX,FY)
                if self.ds_selection == "mix":
                    H = MS.fit(MX,MY)

                print('CLASSIFICATION')
                print('C best param')
                print(H.best_params_['C'])
                print('gamma best param')
                print(H.best_params_['gamma'])

                M = SVC(C = H.best_params_['C'],
                        kernel = H.best_params_['kernel'],
                        gamma = H.best_params_['gamma'])

                if self.ds_selection == "chinese":
                    M = MS.fit(CX,CY)
                if self.ds_selection == "french":
                    M = MS.fit(FX,FY)
                if self.ds_selection == "mix":
                    M = MS.fit(MX,MY)

                ####################################################
                ################## TESTING #########################

                print('PREDICTING CHINESE TEST SET')
                CYF = M.predict(CXT)
                cm = confusion_matrix(CYT,CYF)
                print(cm)
                Ccm_list.append(cm)
                print('Predicting FRENCH TEST SET')
                CFYF = M.predict(FXT)
                cm = confusion_matrix(FYT,CFYF)
                print(cm)
                Fcm_list.append(cm)
                print('PREDICTING MIX TEST SET')
                MYF = M.predict(MXT)
                cm = confusion_matrix(MYT,MYF)
                print(cm)
                Mcm_list.append(cm)
                #device = torch.device('cpu')

        ######################################################
        ###################### RESULTS #######################
        print('RESULTS')
        def calculate_percentage_confusion_matrix(confusion_matrix_list, tot):
                pcms = []
                for i in confusion_matrix_list:
                        true_negative = (i[0,0]/tot)*100
                        false_negative = (i[1,0]/tot)*100
                        true_positive = (i[1,1]/tot)*100
                        false_positive = (i[0,1]/tot)*100
                        pcm = np.array([[true_negative , false_positive],[false_negative, true_positive]])
                        pcms.append(pcm)
                return pcms

        def return_tot_elements(cm):
                tot = cm[0,0] + cm[0,1] + cm[1,0] + cm[1,1]
                return tot

        def return_statistics_pcm(pcms):
                max_true_negative = 0
                max_false_negative = 0
                max_true_positive = 0
                max_false_positive = 0
                min_true_negative = 100
                min_false_negative = 100
                min_true_positive = 100
                min_false_positive = 100
                count_true_negative = 0
                count_false_negative = 0
                count_true_positive = 0
                count_false_positive = 0
                for i in pcms:
                        true_negative = i[0,0]
                        false_negative = i[1,0]
                        true_positive = i[1,1]
                        false_positive = i[0,1]

                        count_true_negative += true_negative
                        count_false_negative += false_negative
                        count_false_positive += false_positive
                        count_true_positive += true_positive

                        if true_negative > max_true_negative:
                                max_true_negative = true_negative
                        if false_negative > max_false_negative:
                                max_false_negative = false_negative
                        if true_positive > max_true_positive:
                                max_true_positive = true_positive
                        if false_positive > max_false_positive:
                                max_false_positive = false_positive

                        if true_negative < min_true_negative:
                                min_true_negative = true_negative
                        if false_negative < min_false_negative:
                                min_false_negative = false_negative
                        if true_positive < min_true_positive:
                                min_true_positive = true_positive
                        if false_positive < min_false_positive:
                                min_false_positive = false_positive

                mean_true_negative = count_true_negative/len(pcms)
                mean_false_negative = count_false_negative/len(pcms)
                mean_true_positive = count_true_positive/len(pcms)
                mean_false_positive = count_false_positive/len(pcms)

                mean_matrix = np.array([[mean_true_negative, mean_false_positive],[mean_false_negative, mean_true_positive]])
                max_matrix = np.array([[max_true_negative, max_false_positive],[max_false_negative, max_true_positive]])
                min_matrix = np.array([[min_true_negative, min_false_positive],[min_false_negative, min_true_positive]])

                matrix = []
                matrix.append(mean_matrix)
                matrix.append(max_matrix)
                matrix.append(min_matrix)
                return matrix

        Ctot = return_tot_elements(Ccm_list[0])
        Ccm_list = calculate_percentage_confusion_matrix(Ccm_list, Ctot)

        Ftot = return_tot_elements(Fcm_list[0])
        Fcm_list = calculate_percentage_confusion_matrix(Fcm_list, Ftot)

        Mtot = return_tot_elements(Mcm_list[0])
        Mcm_list = calculate_percentage_confusion_matrix(Mcm_list, Mtot)

        statistic_C = return_statistics_pcm(Ccm_list)
        statistic_F = return_statistics_pcm(Fcm_list)
        statistic_M = return_statistics_pcm(Mcm_list)

        print('CHINESE')
        for i in statistic_C:
                print(i)
        #print(statistic_C)
        print('FRENCH')
        for i in statistic_F:
                print(i)
        #print(statistic_F)
        print('MIX')
        for i in statistic_M:
                print(i)
        #print(statistic_M)

        ###################################################################
        ################## PRINT RESULTS ##################################
        accuracy_C = statistic_C[0][0][0] + statistic_C[0][1][1]
        accuracy_F = statistic_F[0][0][0] + statistic_F[0][1][1]
        accuracy_M = statistic_M[0][0][0] + statistic_M[0][1][1]
        print('Chinese Accuracy Out 0 ', accuracy_C, '%')
        print('French Accuracy Out 0 ', accuracy_F, '%')
        print('Mixed Accuracy Out 0 ', accuracy_M, '%')

        ####################################################################
        ###################### PLOT IMAGE ##################################
        print('PLOT IMAGE')
        plt.figure()
        plt.imshow(np.reshape(CX[30], (itd.size,itd.size)))
        plt.show()


import math
import torch
import torch.nn as nn

BN_MOMENTUM = 0.1

def get_deconv_net(layers, num_classes, downsample):
    RESNET = {18: (BasicBlock, [2, 2, 2, 2]),
                    50: (Bottleneck, [3, 4, 6, 3]),
                    101: (Bottleneck, [3, 4, 23, 3]),
                    152: (Bottleneck, [3, 8, 36, 3])
                }
    block, layers = RESNET[layers]
    model = ResnetDeconv(1, num_classes, block, layers, downsample=downsample)
    return model

class ResnetDeconv(nn.Module):
    def __init__(self, inchannels, outchannels, block, layers=[2, 2, 2, 2], downsample=1):
        '''
        :params inchannels: input image channels, for depth image, inplanes=1
        :params outchannels: output channels, aks joint nums
        :params block: basic building block of resnet
        :params layers: num of blocks in each component of resnet
        :params downsample: downsample rate, indicating the downsample rate from input to output, i.e., input size 128 and output size 64, downsample=2

        '''
        super(ResnetDeconv, self).__init__()

        self.pre = nn.Sequential(
            nn.Conv2d(inchannels, 64, kernel_size=5, stride=1, padding=2, bias=False),
            nn.BatchNorm2d(64, momentum=BN_MOMENTUM),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        )

        self.inplanes = 64
        self.layer1 = self._make_layer(block, 64, layers[0])

        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)

        deconv_num = 4 - int(math.log(downsample, 2))
        deconv_kernel = [4] * deconv_num
        deconv_planes = [256] * deconv_num
        self.deconv_with_bias = False
        self.deconv_layers = self._make_deconv_layer(deconv_num, deconv_kernel, deconv_planes)

        # self.final1 = nn.Conv2d(in_channels=256, out_channels=outchannels*2, kernel_size=1, stride=1, padding=0)
        self.final1 = nn.Conv2d(in_channels=256, out_channels=outchannels*3, kernel_size=1, stride=1, padding=0)
        self.final2 = nn.Conv2d(in_channels=256, out_channels=outchannels, kernel_size=1, stride=1, padding=0)
        self.init_weights()

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def _make_deconv_layer(self, num_layers, kernels, planes):

        layers = []
        for i in range(num_layers):
            kernel, padding, output_padding = kernels[i], 1, 0
            layers.append(
                nn.ConvTranspose2d(
                    in_channels=self.inplanes,
                    out_channels=planes[i],
                    kernel_size=kernel,
                    stride=2,
                    padding=padding,
                    output_padding=output_padding,
                    bias=self.deconv_with_bias))
            layers.append(nn.BatchNorm2d(planes[i], momentum=BN_MOMENTUM))
            layers.append(nn.ReLU(inplace=True))
            self.inplanes = planes[i]

        return nn.Sequential(*layers)

    def init_weights(self):
        for name, m in self.named_modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.weight.data.normal_(0, 0.001)
            elif isinstance(m, nn.ConvTranspose2d):
                nn.init.normal_(m.weight, std=0.001)
                if self.deconv_with_bias:
                    nn.init.constant_(m.bias, 0)

        for m in self.final1.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.normal_(m.weight, std=0.001)
                nn.init.constant_(m.bias, 0)
        for m in self.final2.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.normal_(m.weight, std=0.001)
                nn.init.constant_(m.bias, 0)

    def forward(self, x):
        c = self.pre(x)
        # print('pre size: ', x.size())

        c1 = self.layer1(c)
        # print('enc1 size: ', c1.size())
        c2 = self.layer2(c1)
        # print('enc2 size: ', c2.size())
        c3 = self.layer3(c2)
        # print('enc3 size: ', c3.size())
        c4 = self.layer4(c3)
        # print('enc4 size: ', c4.size())

        out = self.deconv_layers(c4)
        # print('deconv size: ', x.size())
        vec = self.final1(out)
        ht = self.final2(out)

        return torch.cat([vec, ht], dim=1)

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
                               bias=False)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion,
                                  momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

if __name__ == '__main__':
    from ptflops import get_model_complexity_info
    import os

    os.environ["CUDA_VISIBLE_DEVICES"] = '3'

    img = torch.randn(1, 1, 128, 128).cuda()
    model = get_deconv_net(18, 14, 2).cuda()
    print(model)
    out = model(img)
    print(out.size())
    macs, params = get_model_complexity_info(model, (1,128,128),as_strings=True,print_per_layer_stat=False)
    print(macs)
    print(params)


from sourpea.primitives import *
from sourpea.util import *
import pandas as pd
import os
_dir=os.path.dirname(__file__)
 ### DERIVED FACTORS
ihlv = Factor("ihlv", ["dfuu","aramdr","yadl","vekpr","vvhj"])
ngheks = Factor("ngheks", ["sctvll","qjpsrm","anz","zsmnya","ifcx","xbcj","ganxoa"])
def oyf(ihlv, ngheks):
    return ihlv == "yadl" and ngheks == "ganxoa"
def kdv(ihlv,ngheks):
    return not (ihlv == "yadl") or ngheks != "ganxoa"
csxav = Factor("yxyzr", [DerivedLevel("psyro", WithinTrial(oyf, [ihlv, ngheks])), DerivedLevel("igmf", WithinTrial(kdv, [ihlv, ngheks]))])
### EXPERIMENT
design=[ihlv,ngheks,csxav]
crossing=[csxav]
### APPENDIX
block=Block(design,crossing,[])
sequence_code_1=trials_from_csv(os.path.join(_dir,"out_code_1/2_2_3_0.csv"))
nr_input_factors=2
nr_output_levels=2
test_code_1=block.test(sequence_code_1)
try:
	sequence_code_2=trials_from_csv(os.path.join(_dir,"out_code_2/2_2_3_0.csv"))
	test_code_2=block.test(sequence_code_2)
except:
	test_code_2={"pValue":0}
df=pd.read_csv(os.path.join(_dir,"result_sour_c1.csv"))
df.loc[len(df.index)] = [test_code_1["pValue"], test_code_2["pValue"], test_code_1["levels"], test_code_2["levels"], nr_input_factors, nr_output_levels]
df.to_csv(os.path.join(_dir,"result_sour_c1.csv"), index=False)


import matplotlib.pyplot as plt
from mydataset import load_data, DataSetType
from torch.utils.data import DataLoader
import math
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")

dataset = load_data("CLEVR", DataSetType.Train)

print("Number of images = %r" % len(dataset))

print("Shape = ", dataset[-1].shape)

def multiplot(figures, cols: int=3):
    rows = math.ceil(len(figures)/cols)
    fig, ax = plt.subplots(rows, cols)
    c = 0
    r = 0
    for f in figures:
        ax[r,c].imshow(f.permute(1,2,0))
        c += 1
        if c==cols:
            r += 1
            c = 0
    plt.show()

figs = [dataset[i] for i in range(0,9)]
multiplot(figs)


import random

my_int = random.randint(0, 10)
my_float = random.random()

# One way to make random floats over 1.0... but always ends up being a factor of 10
print(str(my_int) + str(my_float))

# better way to make random floats (This will make a float between 0 and 10:
print(my_float * 10)