'''
Descripttion:
version:
Author: Catop
Date: 2021-02-10 07:47:09
LastEditTime: 2021-02-18 07:40:13
'''
#coding:utf-8

from flask import Flask,request,jsonify
import json
import requests
import dbconn
import goapi
import time
import os
import compress
import urllib.parse
import random
import ocrplus
import inputFilter
import json

app = Flask(__name__)
@app.route('/', methods=['POST'])
def getEvent():
    data = request.json
    post_type = data.get('post_type')
    if(post_type == 'message'):
        message_type = data.get('message_type')
        #print(data)
        message = data.get('message')
        user_id = str(data.get('user_id'))
        if(message_type=='private' and (dbconn.check_register(user_id)==1 or '注册' in message)):
            #仅接收注册用户的消息和注册消息
            print(f"--------------------\n接收消息@{user_id}:{message[:20]}")
            readMsg(user_id,message)
    elif(post_type == 'request'):
        request_type = data.get('request_type')
        if(request_type=='friend'):
            user_id = str(data.get('user_id'))
            comment = str(data.get('comment'))
            flag = str(data.get('flag'))
            print(f"--------------------\n接收加好友请求@{user_id}:{comment[:20]}")
            time.sleep(random.randint(5,10))
            goapi.add_request(flag)
            time.sleep(random.randint(5,10))
            goapi.sendMsg(user_id,"欢迎！\n请先注册，例如'注册@小明@智科20-2'\n 班级请严格按格式输入，否则可能统计不上哦,另外特别注意'-'是减号不是破折号，也不要加空格")
    else:
        #暂不处理其他类型上报，为防止go-cq报错而设置
        pass

    return data

def readMsg(user_id,message):
    #处理消息核心
    user_id = str(user_id)
    #管理员列表
    admin_list = show_admin()

    if('image' in message):
        if(dbconn.check_register(user_id)):
            #用户已注册
            get_img(user_id,message)
        else:
            #用户未注册
            goapi.sendMsg(user_id,'您还没注册呢，请输入例如"注册@小明@智科20-2"\n 班级请严格按格式输入，否则可能统计不上哦,另外特别注意'-'是减号不是破折号，也不要加空格')
        return
    if('注册' in message):
        try:
            user_name = message.split('@')[1]
            user_class = message.split('@')[2]
            #简单过滤用户输入
            if not(inputFilter.is_Chinese(user_name) and inputFilter.check_length(user_name)):
                goapi.sendMsg(user_id,'输入好像有点问题呢')
                return
            if not(inputFilter.is_valid(user_class) and inputFilter.check_length(user_class)):
                goapi.sendMsg(user_id,'输入好像有点问题呢')
                return

        except:
            goapi.sendMsg(user_id,'输入好像有点问题呢')
        else:
            if(dbconn.check_register(user_id)):
                goapi.sendMsg(user_id,'您已注册过啦~')
                re_register_user(user_id,user_name,user_class)
            else:
                    register_user(user_id,user_name,user_class)
        return
    if('/admin' in message):
        user_class = dbconn.get_user(user_id)['user_class']
        upload_date = time.strftime("%Y-%m-%d", time.localtime())
        print(user_id)
        if(user_id in admin_list.keys()):
            group_id = admin_list[user_id]
            if('群提醒' in message):
                send_alert(group_id,dbconn.get_user(user_id)['user_class'],'group')
            elif('提醒'in message):
                send_alert(user_id,dbconn.get_user(user_id)['user_class'],'private')
                upload_date = time.strftime("%Y-%m-%d", time.localtime())
                time.sleep(1)
                #ocr_err_upload(user_id,user_class,upload_date)
                ocr_err_upload(user_id,user_class,upload_date)
                time.sleep(2)
                send_images_info(user_id,user_class)
            elif('打包'in message):
                cmp_ret = compress.zip_file(upload_date,dbconn.get_user(user_id)['user_class'])
                goapi.sendMsg(user_id,f"---打包完毕---\n共处理:{cmp_ret['file_num']}张照片")
                goapi.sendMsg(user_id,'下载地址:'+urllib.parse.quote(cmp_ret['file_name']))
            elif('成员'in message):
                list_class_menbers(user_id,user_class)
            elif('核对'in message):
                goapi.sendMsg(user_id,'get')
                err_imgid = message.split('@')[1]
                ocr_times = message.split('@')[2]
                ocr_scores = message.split('@')[3]
                if(dbconn.err_check):
                    err_code = dbconn.err_check(err_imgid)
                    if(err_code):
                        dbconn.manual_update(ocr_times,ocr_scores,err_imgid)
                        goapi.sendMsg(user_id,f"人工校对完成:{dbconn.get_user_by_migid(err_imgid)}\n参赛次数:{ocr_times}\n积分:{ocr_scores}")
                elif(err_code == 0):
                    goapi.sendMsg(user_id,'该图片无需校对，请重新检查输入的id')
                elif(err_code == -1):goapi.sendMsg(user_id,f"已经人工校对过了，覆盖校对:\n{dbconn.get_user_by_migid(imgid)}\n参赛次数:{ocr_times}\n积分:{ocr_scores}")

            else:
                goapi.sendMsg(user_id,"目前支持以下管理指令呢：\n群提醒\n提醒\n打包\n成员\n")
        else:

            goapi.sendMsg(user_id,"无管理权限")

    if('/sudo' in message and (user_id=='601179193' or user_id=="29242764" or user_id=="1476821890" or user_id=="3439911708")):
        #try:

        if('增加管理员' in message):
            admin_id = message.split('@')[1]
            group_id = message.split('@')[2]
            goapi.sendMsg(user_id,str(add_admin(admin_id,group_id)))
        elif('删除管理员' in message):
            admin_id = message.split('@')[1]
            goapi.sendMsg(user_id,str(del_admin(admin_id)))
        elif('展示管理员' in message):
            goapi.sendMsg(user_id,str(show_admin()))
        else:
            goapi.sendMsg(user_id,'增加管理员\n删除管理员\n展示管理员')
        #except:
            #goapi.sendMsg(user_id,'增加管理员\n删除管理员\n展示管理员')
        #else:
            #pass

    return

def get_img(user_id,message):
    #从message中解析到图片下载地址，并保存数据库，下载文件
    try:
        img_url = message.split('url=')[1][0:-1]
        user_name = dbconn.get_user(user_id)['user_name']
        user_class = dbconn.get_user(user_id)['user_class']
        upload_date = time.strftime("%Y-%m-%d", time.localtime())
        upload_time = time.strftime("%H:%M:%S", time.localtime())

        #修改文件名格式(注意只保存文件名和数据库中显示的file_name改变，目录等名称不变)
        file_date = time.strftime("%Y%m%d", time.localtime())

        #安全过滤
        if not(img_url[0:24] == 'http://c2cpicdw.qpic.cn/'):
            goapi.sendMsg(user_id,'图片url解析错误')
            return

        #判断文件目录是否存在
        if not(os.path.exists(f"images/{upload_date}")):
            os.mkdir(f"images/{upload_date}")
        if not(os.path.exists(f"images/{upload_date}/{user_class}")):
            os.mkdir(f"images/{upload_date}/{user_class}")

        file_name = f"/{upload_date}/{user_class}/{user_class}班-{user_name}-{file_date}.jpg"
        if(dbconn.check_today_upload(user_id,upload_date)):
            goapi.sendMsg(user_id,'您今天已经上传过照片啦，已覆盖之前的图片~')

        download_img(img_url,file_name)
        #print(img_url)
    except Exception as err:
        goapi.sendMsg(user_id,'图片下载出错了！')
        print(err)
    else:
        print("成功处理图片:"+file_name)
        goapi.sendMsg(user_id,"成功处理图片，正在识别...\n"+f"{user_class}班-{user_name}-{file_date}.jpg")

        """图片识别部分"""
        try:
            print(file_name)
            ocr_ret = ocrplus.ocr_img("images"+file_name)
            ocr_err_code = ocr_ret['err_code']
            if(ocr_err_code == 0):
                goapi.sendMsg(user_id,f"参赛次数:{ocr_ret['个人参赛次数']}\n个人积分:{ocr_ret['个人积分']}")
                ocr_times = ocr_ret['个人参赛次数']
                ocr_scores = ocr_ret['个人积分']
            else:
                print("图片无法识别:"+ocr_ret)
                #图片识别接口返回无法识别
                goapi.sendMsg(user_id,f"OCR无法识别，团支书将人工复核~")
                dbconn.insert_img(user_id,file_name,upload_date,upload_time,'1','0','0')
                return
        except:
            #图片识别接口出错
            print("OCR接口出错:")
            goapi.sendMsg(user_id,f"qwq图片识别出错了！可能是字体原因，请尝试更换字体后重试")
            dbconn.insert_img(user_id,file_name,upload_date,upload_time,'1','0','0')
        else:
            dbconn.insert_img(user_id,file_name,upload_date,upload_time,ocr_err_code,ocr_times,ocr_scores)

    return

def download_img(img_url,file_name):
    res = requests.get(img_url, stream=True)
    if res.status_code == 200:
        open('images/'+file_name, 'wb').write(res.content)
        #print("image"+file_name+"saved successfully.")

def register_user(user_id,user_name,user_class):
    if(dbconn.register_user(user_id,user_name,user_class) == 1):
        goapi.sendMsg(user_id,'注册成功，现在可以开始上传图片了~')
    else:
        goapi.sendMsg(user_id,'注册失败'+f"user_id={user_id},user_name={user_name},user_class={user_class}")

def re_register_user(user_id,user_name,user_class):
    if(dbconn.re_register_user(user_id,user_name,user_class) == 1):
        goapi.sendMsg(user_id,'已更新字段')
    else:
        goapi.sendMsg(user_id,'更新字段失败:'+f"user_id={user_id},user_name={user_name},user_class={user_class}")

def send_alert(group_id,user_class,type='private'):
    group_menbers = dbconn.get_class_members(user_class)
    current_date = time.strftime("%Y-%m-%d", time.localtime())
    alert_users = {}
    #user_id:last_date
    for user_id in group_menbers:
        #print(user_id)
        try:
            last_date = dbconn.check_status(user_id)
        except TypeError:
            #还没发过照片
            alert_users[user_id] = '无记录'
        else:
            if(str(last_date)!=str(current_date)):
                alert_users[user_id] = str(last_date)[5:]

    #print(alert_users)
    msg = f"今天还有{len(alert_users)}位小可爱未完成哦\n"

    if(type=='private'):
        for user_id in alert_users.keys():
            last_date = alert_users[user_id]
            msg += f"{dbconn.get_user(user_id)['user_name']}({alert_users[user_id]})\n"
        msg+=f"{user_class} {current_date}\n完成情况:{len(group_menbers)-len(alert_users)}/{len(group_menbers)}"
        goapi.sendMsg(group_id,msg)
    elif(type=='group'):
        for user_id in alert_users.keys():
            last_date = alert_users[user_id]
            msg += f"[CQ:at,qq={user_id}]({alert_users[user_id]})\n"
        msg += f"{user_class} {current_date}\n完成情况:{len(group_menbers)-len(alert_users)}/{len(group_menbers)}"
        goapi.sendGroupMsg(group_id,msg)

def list_class_menbers(user_id,user_class):
    msg = f"{user_class}成员情况：\n"
    ret = dbconn.get_class_members(user_class)
    for i in range(0,len(ret)):
        msg += f"{ret[i]} {dbconn.get_user(str(ret[i]))['user_name']}\n"
    msg += f"共计{str(len(ret))}人"

    goapi.sendMsg(user_id,msg)

def ocr_err_upload(user_id,user_class,upload_date):
    """为管理员上报ocr错误的图片"""
    msg = "OCR无法识别以下图片:\n"
    err_list = []
    err_imgid = []
    class_menbers = dbconn.get_class_members(user_class)
    for i in range(0,len(class_menbers)):
        img_date = dbconn.check_status(class_menbers[i])
        if(str(img_date) == str(upload_date)):
            img_info = dbconn.get_latest_img_info(class_menbers[i],upload_date)[0]
            #print(img_info)
            if(img_info['ocr_err_code'] == 1):
                print(img_info)
                err_list.append(img_info['file_name'])
                err_imgid.append(img_info['imgid'])

    for i in range(0,len(err_list)):
        cqCode = f"[CQ:image,file=file:{os.getcwd()}/images{err_list[i]}]"
        msg += f"id:{err_imgid[i]}\n"
        msg += f"{cqCode}\n"
    msg += f"数量:{len(err_list)}/{len(class_menbers)}\n"
    msg += "可人工核对，操作格式: /admin 核对@id@次数@分数，例如：\n核对id为233，次数66，分数99则输入：/admin 核对@233@66@99"
    goapi.sendMsg(user_id,msg)
    return msg

######################################################################
# def manual_identify(user_id,user_class,upload_date):
#     """管理员手动识别ocr错误的图片"""
#     msg="OCR无法识别以下图片"
#     goapi.sendMsg(user_id,msg)
#     err_list = []
#     user_info = []
#     class_menbers = dbconn.get_class_members(user_class)
#     for i in range(0,len(class_menbers)):
#         img_date = dbconn.check_status(class_menbers[i])
#         if(str(img_date) == str(upload_date)):
#             img_info = dbconn.get_latest_img_info(class_menbers[i],upload_date)[0]
#             #print(img_info)
#             if(img_info['ocr_err_code'] == 1):
#                 print(img_info)
#                 err_list.append(img_info['file_name'])
#     i = 0
#     while i < len(err_list):
#         cqCode = f"[CQ:image,file=file:{os.getcwd()}/images{err_list[i]}]"
#         msg = f"{cqCode}\n"
#         msg += f"请人工核对，格式：核对@答题次数@答题分数，例如:核对@43@505"
#         goapi.sendMsg(user_id,msg)
#         if ("核对" in message )
#             ocr_times = message.split('@')[1]
#             ocr_scores = message.split('@')[2]

######################################################################

def send_images_info(user_id,user_class):
    """上报班级图片情况（次数和成绩）"""
    class_menbers = dbconn.get_class_members(user_class)
    today_upload_count = 0
    upload_date = time.strftime("%Y-%m-%d", time.localtime())
    msg = f"{user_class} {upload_date}情况:\n"
    for i in range(0,len(class_menbers)):
        if(str(dbconn.check_status(class_menbers[i])) == str(upload_date)):
            today_upload_count += 1
            img_info = dbconn.get_latest_img_info(class_menbers[i],upload_date)[0]
            if(img_info['ocr_err_code'] == 0):
                msg += f"·{dbconn.get_user(class_menbers[i])['user_name']} 次数{img_info['ocr_times']} 分数{img_info['ocr_scores']}\n"
            else:
                msg += f"·{dbconn.get_user(class_menbers[i])['user_name']} 未识别到\n"

    msg += f"共计{today_upload_count}张照片"

    goapi.sendMsg(user_id,msg)
    return msg

def add_admin(user_id,class_id):
    admin_list = show_admin()
    admin_list[str(user_id)] = str(class_id)
    with open("admin_list.txt","w") as f:
        json.dump(admin_list,f)
    return admin_list

def del_admin(user_id):
    admin_list = show_admin()
    del admin_list[str(user_id)]
    with open("admin_list.txt","w") as f:
        json.dump(admin_list,f)
    return admin_list

    return admin_list

def show_admin():
    with open("admin_list.txt","r") as f:
        admin_list = json.load(f)
    return admin_list

if __name__ == '__main__':
    app.run(host='127.0.0.1',port='5000',debug=False)
    #send_alert('1038368144','信安20-2','group')
    #goapi.sendMsg('29242764','[CQ:image,file=file:/Users/catop/Desktop/ChangZhengBot/go-cq/res1.png]')
    #print(ocr_err_upload('29242764','信安20-2','2021-02-13'))
    #goapi.sendMsg('29242764','[CQ:image,file=file:/Users/catop/Desktop/ChangZhengBot/images/2021-02-13/信安20-2/信安20-2班-张宏远-20210213.jpg]')
    #ocr_err_upload('601179193','信安20-2','2021-02-13')
    #print(send_images_info('29242764','信安20-2'))
    #print(show_admin())
    #print(del_admin('1234567890'))


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

# définition d'une fonction à l'aide de lambda
s = lambda x : 0 if x < 0 else x
print(s(12));

def f(x):
    return x**2;

carre = lambda x : x**2
print (carre(6));

R = map(carre, range(10));
print(list(R));

# fonction --->  lambda y : 0 if y < 0 else y
#itérateur ---> [-1, 20, 3, 6, 11, -4, 8, 4]
R2 = map(lambda y : 0 if y < 0 else y*-1, [-1, 20, 3, 6, 11, -4, 8, 4])
print(list(R2))


import numpy as np
import pylab as plt
import h5py
import mne

from scipy.signal import welch, hilbert
from pynfb.postprocessing.utils import get_info, add_data_simple, get_colors, fft_filter, dc_blocker, load_rejections
from collections import OrderedDict
from IPython.display import clear_output

# load raw
from json import loads

from pynfb.widgets.helpers import ch_names_to_2d_pos

settings_file = 'D:\\vnd_spbu\\pilot\\mu5days\\vnd_spbu_5days.json'
with open(settings_file, 'r', encoding="utf-8") as f:
    settings = loads(f.read())

dir_ = settings['dir']
subj = 0
day = 0

def preproc(x, fs, rej=None):
    x = dc_blocker(x)
    x = fft_filter(x, fs, band=(3, 45))
    if rej is not None:
        x = np.dot(x, rej)
    return x

from pynfb.protocols.ssd.topomap_selector_ica import ICADialog
from PyQt5 import QtGui, QtWidgets

a = QtWidgets.QApplication([])

fig1, axes1 = plt.subplots(ncols=3)

for subj in range(3,4):
    for day in range(2,5):
        experiments = settings['subjects'][subj]
        experiment = experiments[day]
        reject = True
        with h5py.File('{}\\{}\\{}'.format(settings['dir'], experiment, 'experiment_data.h5')) as f:
            fs, channels, p_names = get_info(f, settings['drop_channels'])
            rejection, alpha, ica = load_rejections(f, reject_alpha=False)
            raw_before = OrderedDict()
            raw_after = OrderedDict()
            for j, name in enumerate(p_names):
                if j < 3:
                    x = preproc(f['protocol{}/raw_data'.format(j + 1)][:], fs, rejection if reject else None)
                    raw_before = add_data_simple(raw_before, name, x)
                elif j > len(p_names) - 3:
                    x = preproc(f['protocol{}/raw_data'.format(j + 1)][:], fs, rejection if reject else None)
                    print(x.shape)
                    raw_after = add_data_simple(raw_after, name, x)

        xx = np.concatenate([raw_before['Opened'], raw_before['Baseline'], raw_after['Baseline'], raw_before['Left'], raw_before['Right'],  raw_after['Left'], raw_after['Right'], ])
        #xx[:, channels.index('C3')] = xx[:, channels.index('C3')]
        rejection, spatial, topography, unmixing_matrix, bandpass, _ = ICADialog.get_rejection(xx, channels, fs, mode='csp', states=None)
        from mne.viz import plot_topomap
        print(spatial)
        fig, axes = plt.subplots(ncols=rejection.topographies.shape[1])
        if not isinstance(axes, type(axes1)) :
            axes = [axes]
        for ax, top in zip(axes, rejection.topographies.T):
            plot_topomap(top, ch_names_to_2d_pos(channels), axes=ax, show=False)
        fig.savefig('csp_S{}_D{}.png'.format(subj, day+1))
        fig.show()


import ShapeGr as gr
import turtle as t

class DGraphics(gr.Point):

    SLIST = ["ryba", "circle","point","rect","str"]

    def __init__(self, shape, x=0, y=0, size=10, inColor="black", outColor="black"):

        while True:
            if(shape.lower() in self.SLIST):
                self.__shape__ = shape
                break
            else:
                print("INVALID SHAPE INPUT")
                shape = str(input("\nInput shape: "))

        self.x = x
        self.y = y
        self.inColor = inColor
        self.outColor = outColor
        self.size = size

        self.track = False

        self.transX = 0
        self.transY = 0

        self.matrixPointX = 0
        self.matrixPointY = 0

    def draw(self):
        t.down() if self.track else t.up()
        t.color(self.inColor,self.outColor)
        t.down()

        t.begin_fill()
        t.left(60)
        for i in range(4):
            t.forward(10*self.size)
            t.right(100)
        t.end_fill()

    def move(self,x,y):
        self.x = x
        self.y = y

        t.up()
        t.setpos(self.transX + x, self.transY + y)
        print("newPos {}:{}".format(self.transX + x, self.transY + y))

    def screenSize(self,pos=-1):
        width = t.Screen().window_width()
        height = t.Screen().window_height()

        if(pos == -1):
            return(width,height)
        elif(pos == 0):
            return(width)
        elif(pos == 1):
            return(height)

    def translate(self, x, y):
        self.transX = x
        self.transY = y
        print("translated {}:{}".format(x, y))

    def pushMatrix(self):
        self.matrixPointX = self.transX
        self.matrixPointY = self.transY
        print("pushMatrix {}:{}".format(self.matrixPointX, self.matrixPointY))

    def popMatrix(self):
        self.transX = self.matrixPointX
        self.transY = self.matrixPointY
        print("popMatrix {}:{}".format(self.transX, self.transY))

if __name__ == "__main__":
    d = DGraphics(shape="ryba", size = 50,inColor = "red", outColor="blue")
    d.draw()


t = int(input())

if(0<t<1001):
    for i in range(0, t):
        n = int(input())
        first = n
        last = n % 10
        while(first >= 10):
            first = first // 10
        s = first + last
        print(s)

First and Last Digit/sum_first_and_last.py


# 데이터 구조
# 데이터를 저장 다양하게 조작, 활용(crud)

# 문제를 더 효율적으로 풀기 위한 도구가 된다.

# 딕셔너리가 해쉬

# 순서가 아닌 형태로 접근

# 스택은 후입선출 오래된 늠은 썩고 새놈은 바로 사용
# 리스트 팝 어펜드 list[-1] top # 뒤로가기

# 괄호매칭

# 왼쪽괄호 입력수
n = int(input())
a_list = list(range(1,n + 1))
a2_list = []
while True :
    a2_list.append(a_list.pop(0))
    if len(a_list) == 0 :
        break
    a_list.append(a_list.pop(0))

print(*a2_list)


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

"""
序列化是将数据结构或对象转换为一系列位的过程，以便它可以存储在文件或内存缓冲区中，或通过网络连接链路传输，以便稍后在同一个或另一个计算机环境中重建。

设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串，并且可以将该字符串反序列化为最初的二叉搜索树。

编码的字符串应尽可能紧凑。

示例 1：

输入：root = [2,1,3]
输出：[2,1,3]

示例 2：

输入：root = []
输出：[]

提示：

树中节点数范围是 [0, 104]
0 <= Node.val <= 104
题目数据 保证 输入的树是一棵二叉搜索树。

注意：不要使用类成员/全局/静态变量来存储状态。 你的序列化和反序列化算法应该是无状态的。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/serialize-and-deserialize-bst
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

"""

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

import json

class Codec:
    def serialize(self, root: TreeNode) -> str:
        """Encodes a tree to a single string.
        """
        self.preorder = []
        self.inorder = []
        self.pre_dfs(root)
        self.in_dfs(root)
        return json.dumps({"preorder": self.preorder, "inorder": self.inorder})

    def deserialize(self, data: str) -> TreeNode:
        """Decodes your encoded data to tree.
        """
        print(data)
        data_map = json.loads(data)
        preorder = data_map["preorder"]
        inorder = data_map["inorder"]
        inorder_map = {i: v for v, i in enumerate(inorder)}
        print(inorder_map)
        root = self.create(preorder, inorder, inorder_map, 0, len(inorder))
        return root

    def pre_dfs(self, root):
        if root is None:
            return
        self.preorder.append(root.val)
        self.pre_dfs(root.left)
        self.pre_dfs(root.right)

    def in_dfs(self, root):
        if root is None:
            return
        self.in_dfs(root.left)
        self.inorder.append(root.val)
        self.in_dfs(root.right)

    def create(self, preorder, inorder, inorder_map, in_left, in_right):
        if not preorder or in_left > in_right:
            return None

        val = preorder.pop(0)
        mid = inorder_map[val]
        root = TreeNode(val)
        # 这里需要注意的是，这里其实是引用级别的策略，不是这种其他的逻辑修改。
        root.left = self.create(preorder, inorder, inorder_map, in_left, mid - 1)
        root.right = self.create(preorder, inorder, inorder_map, mid + 1, in_right)
        return root

算法分析和归类/树/序列化和反序列化二叉搜索树.py

序列化和反序列化二叉搜索树.py


from rich.console import Console

from org.metadatacenter.model.PlanTask import PlanTask
from org.metadatacenter.model.PrePostType import PrePostType
from org.metadatacenter.model.PreReleaseBranchType import PreReleaseBranchType
from org.metadatacenter.model.TaskType import TaskType
from org.metadatacenter.operator.Operator import Operator
from org.metadatacenter.taskfactory.BuildShellTaskFactory import BuildShellTaskFactory
from org.metadatacenter.taskfactory.ReleaseCleanupShellTaskFactory import ReleaseCleanupShellTaskFactory

console = Console()

class ReleaseCleanupOperator(Operator):

    def __init__(self):
        super().__init__()

    @staticmethod
    def expand(task: PlanTask):
        ReleaseCleanupOperator.expand_for_release(task)

    @classmethod
    def expand_for_release(cls, task):
        repo_list = [task.repo]

        for repo in repo_list:
            if repo.pre_post_type == PrePostType.SUB:
                not_handled = PlanTask("Skip sub repo", TaskType.NOOP, repo)
                not_handled.add_task_as_task(BuildShellTaskFactory.noop(repo))
                task.add_task_as_task(not_handled)
            elif repo.pre_post_type == PrePostType.NONE or repo.pre_post_type == PrePostType.PRE:
                shell_wrapper = PlanTask("Clean up repo", TaskType.SHELL_WRAPPER, repo)
                shell_wrapper.add_task_as_task(ReleaseCleanupShellTaskFactory.cleanup_generic(repo))
                task.add_task_as_task(shell_wrapper)


import os
import nmap3
from json2html import json2html

class Scanner:
    def __init__(self):
        self.nm = nmap3.Nmap()
        self._open_ports = []
        self._http_ports = []
        self._output = {}
        self.nm_type = ""
        self._hostname = ""
        self.path = "report_nmap"

    def create(self):
        parent_dir = str(os.getcwd())
        is_exist = os.path.exists(self.path)
        if is_exist is False:
            res = os.path.join(parent_dir, self.path)
            os.makedirs(res)

    def nmap_scan_file(self, hostname, ip):
        output_file = f"{hostname}.html"
        output = self.nm.nmap_version_detection(ip, args="-Pn")
        self._output = output
        html = json2html.convert(json=output)
        try:
            with open('report_nmap/' + str(output_file), 'w') as o:
                o.write(html)
                print("Ho stampato il report")
        except FileNotFoundError:
            print("The 'report' directory does not exist")
        self._hostname = hostname

    def parse_info(self, ip):
        data = self._output
        spec_data = data[ip]["ports"]
        ports = []
        http_ports = []
        for i in range(0, len(spec_data)):
            spec = spec_data[i]
            ports.append(spec["portid"])
            if spec["service"]["name"] == ("http" or "https"):
                http_ports.append(spec["portid"])
        self._open_ports = ports
        self._http_ports = http_ports

    def get_open_ports(self):
        return self._open_ports

    def get_hostname(self):
        return self._hostname

    def get_http_ports(self):
        return self._http_ports


# Built-in modules
import argparse
import os
import gzip
import random
import shutil
from pathlib import Path
from datetime import datetime, timedelta

# Basics of Python data handling and visualization
import numpy as np
import pandas as pd
import geopandas as gpd
import tqdm
#from shapely import wkt

from lib.utils import _get_point
from configs.utils import load_config
from lib.train_utils import get_data, load_pickle, save_pickle
from algorithms.ensemble import Ensemble

def preprocess(config, update=False):
    if not os.path.isfile(config["cache_path"]) or update:
        data, gts, target_size = get_data(
            indir, outdir, label, aoi, config["feature_keys"], update=update)
        save_pickle((data, gts, target_size), config["cache_path"])
    else:
        (data, gts, target_size) = load_pickle(config["cache_path"])

    # Dataset
    dataset = {"X": [],
               "Y": [],
               "gt": [],
               "native_Y": [],
               "target_Y": [],
               "lat": [],
               "lon": [],
               "coords": [],
               "date": []}
    grid = np.zeros(target_size)
    bbox = data['data'][0]["s5p" if label == "NO2" else "cams"].bbox
    for date, lat, lon, gt in tqdm.tqdm(gts[["Date", "SITE_LATIT", "SITE_LONGI", "AirQuality"]].values):
        y_ind, x_ind = _get_point(lat, lon, grid, bbox)
        try:
            day_ind = data["date"].index(int(date))

            ind = data['date'].index(date)
            native = data['feat_dicts'][ind]['no2_native' if label ==
                                             'NO2' else 'pm25_native']
            target = data['feat_dicts'][ind]['no2_target' if label ==
                                             'NO2' else 'pm25_target']

            if np.isnan(native[y_ind, x_ind]):
                continue

            dataset["X"].append(data['feats'][day_ind][y_ind, x_ind])
            dataset["native_Y"].append(native[y_ind, x_ind])
            dataset["target_Y"].append(target[y_ind, x_ind])
            dataset["gt"].append(gt)
            dataset["lat"].append(lat)
            dataset["lon"].append(lon)
            dataset["coords"].append((lat, lon))
            dataset["date"].append(date)

        except:
            pass
            #print("Error on date:", date)

    dataset = {k: np.array(v) for k, v in dataset.items()}
    # -------------------

    gt, native_Y = dataset["gt"], dataset["native_Y"]
    # Filter any very off GT

    if label == "NO2":
        dataset["Y"] = gt / (6.02214 * 1e4 * 1.9125) - native_Y
        v1 = gt
        v2 = native_Y * 6.02214 * 1e4 * 1.9125
        m = np.min([v2, v1], axis=0)
        r = (v1 / v2)
        if "Africa" in aoi:
            mask = (r < 3.5) & (r > 0.7)
        elif "California" == aoi:
            mask = (r < 4.5) & (r > 0.7)
        elif "Italy" == aoi:
            mask = (r < 2.5) & (r > 0.85)

    else:
        dataset["Y"] = gt - native_Y
        v1 = gt
        v2 = native_Y
        if "Africa" in aoi:
            m = np.min([v2, v1], axis=0)
            mask = ~((abs(v2 - v1) > (m * 3)) & ((v2 > 1) | (v1 > 1)))
        elif aoi == "Italy":
            mask = ~((abs(v2 - v1) > v2 * 0.9) & ((v2 > 5) | (v1 > 5)))
        elif aoi == "California":
            mask = ~((abs(v2 - v1) > v2 * 0.535) & ((v2 > 5) | (v1 > 5)))

    print('Rate of kept samples from filter:', mask.mean())
    print('Correlation between native measure and ground truth',
          np.corrcoef(gt[mask], native_Y[mask]))

    X = dataset["X"][mask]
    Y = dataset["Y"][mask]
    coords = dataset["coords"][mask]
    return X, Y, coords, data

def main(config, update=False):
    X, Y, coords, data = preprocess(config, update=update)

    ensemble = Ensemble(config, indir, outdir)
    print("models:", ensemble.models)

    mu = np.nanmean(data["feats"], axis=(0, 1, 2))
    sigma = np.nanstd(data["feats"], axis=(0, 1, 2))

    ensemble.train(X, Y, coords=coords, mu=mu, sigma=sigma)
    ensemble.save()
    print("Done.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', required=True)
    parser.add_argument('--update', action="store_true")
    args = parser.parse_args()

    random.seed(0)

    config = load_config(args.config)
    aoi = config["aoi"]
    label = config["label"]
    indir = Path("./data/train") / config["aoi"]
    outdir = Path("./wdir") / config["aoi"]

    main(config, args.update)


#!/usr/bin/python3
import sys
import zenoh
from zenoh import Zenoh, Value
import time
from datetime import datetime
import rospy
from sensor_msgs.msg import JointState

# Data pushed by a robot
storage_path = '/mystorage'

def callback_joint_states(joint_states, args):
    global sample_id
    position = joint_states.position
    position = [round(pos, 4) for pos in position]
    x1, x2, y1, y2, z1, z2 = position
    # Zenoh data format
    value = { 'x1': str(x1), 'y1': str(y1), 'z1': str(z1),
              'x2': str(x2), 'y2': str(y2), 'z2': str(z2) }

    now = datetime.now()
    minute_id = str(now.minute)
    second_id = str(now.second)

    # Zenoh path
    sample_path = minute_id + '/' + second_id + '/' + str(sample_id)
    workspace.put(sample_path, value)
    sample_id = sample_id + 1

if __name__=="__main__":
    if len(sys.argv) < 3:
        print("Usage <address of zenohd router> <rostopic> <rostopic hz>")
    address = sys.argv[1]
    rostopic = sys.argv[2]
    sample_id = 0

    conf = {
      'mode': 'client',
      'peer': '{}'.format(address),
    }

    print("Opening Zenoh session...")
    zenoh = Zenoh(conf)

    # Create a new storage called my-storage
    path = '/@/router/local/plugin/storages/backend/memory/storage/my-storage'

    # Workspace creation
    print("New Zenoh workspace...")
    storage = zenoh.workspace()

    # Clearing the router
    print("Clearing the router first..")
    try:
        storage.delete(storage_path)
        print("Clear router")
    except Exception:
        print("Router is good")
        pass

    # Storage creation
    print("Creating storage...")
    value = {"path_expr": storage_path + '/**'}
    storage.put(path, value)
    workspace = zenoh.workspace(storage_path)
    now = datetime.now()
    print("Robot data acquisition started at:", now)

    # Setting up ROS publisher node
    rospy.init_node('zenoh_subscriber', disable_signals=True)
    sub = rospy.Subscriber(rostopic, JointState, callback_joint_states,
                           (zenoh, workspace, sample_id))

    rospy.spin()
    zenoh.close()
    now = datetime.now()
    print("Robot data acquisition stopped at:", now)
    print("Number of samples acquired:", sample_id - 1)


import torch
from torch_geometric.nn.conv import GENConv
from torch_geometric.nn import Linear, global_add_pool, DeepGCNLayer
import torch.nn.functional as F
from torch.nn import BatchNorm1d, Dropout, SELU, LayerNorm, ReLU
from torch_geometric.utils import add_self_loops, scatter
from utils.pooling import GlobalAddPooling
from utils.sigmoid import Sigmoid

class GCN2Regressor(torch.nn.Module):
    """
    Graph Neural Network for regression
    a customizable number of The GENeralized Graph Convolution (GENConv) layer from <https://arxiv.org/pdf/2006.07739.pdf>
    max graph pool layer followed by a two-layer fully-connected prediction networks
    """

    def __init__(
        self,
        node_feature_dim,
        edge_feature_dim,
        hidden_channels,
        pool_dim,
        fully_connected_channels,
        output_channels,
    ):
        """
        Args:
            node_feature_dim (int): Size of node featrues
            edge_feature_dim (int): Size of edge features
            hidden_channels (tuple or list): output size of each GEN layer
            pool_dim (int): size of the pooling layer
            fully_connected_channels (tuple or list): dimension for fully-connected prediction layers
        """
        super(GCN2Regressor, self).__init__()

        self.layers = torch.nn.ModuleList()
        self.lin = torch.nn.ModuleList()
        self.node_encoder = torch.nn.ModuleList()
        self.edge_encoder = torch.nn.ModuleList()

        for i in range(len(hidden_channels)):
            conv = GENConv(
                hidden_channels[i],
                pool_dim,
                edge_dim=hidden_channels[i],
                msg_norm=True,
                learn_msg_scale=True,
            )
            norm = LayerNorm(pool_dim)
            act = ReLU(inplace=True)
            layer = DeepGCNLayer(conv, norm, act, block="plain", dropout=0.47)
            self.layers.append(layer)

            self.lin.append(Linear(hidden_channels[i], pool_dim))

            self.node_encoder.append(Linear(node_feature_dim, hidden_channels[i]))
            self.edge_encoder.append(Linear(edge_feature_dim, hidden_channels[i]))

        self.regressor = torch.nn.Sequential(
            torch.nn.Linear(pool_dim, fully_connected_channels[0]),
            torch.nn.ReLU(),
            torch.nn.BatchNorm1d(fully_connected_channels[0]),
            torch.nn.Dropout(p=0.47),
            torch.nn.Linear(fully_connected_channels[0], fully_connected_channels[1]),
            torch.nn.ReLU(),
            torch.nn.BatchNorm1d(fully_connected_channels[1]),
            torch.nn.Dropout(p=0.47),
            torch.nn.Linear(fully_connected_channels[1], output_channels),
        )

        self.pool = GlobalAddPooling()

    def forward(self, atom_feat, edge_index, edge_attr, batch):
        """
        update nodes using atom feature, edge feature, and edge index information for every batch
        """
        # 1. Obtain node embeddings
        readout = 0

        for layer, lin, node_encoder, edge_encoder in zip(
            self.layers, self.lin, self.node_encoder, self.edge_encoder
        ):
            data = node_encoder(atom_feat)
            data_edge_attr = edge_encoder(edge_attr)
            layer_read = layer(data, edge_index, data_edge_attr)
            readout += F.softmax(layer_read, dim=-1)

        # 2. Readout layer
        x = self.pool(readout, batch)  # [batch_size, hidden_channels]

        # 3. Fully Connected Neural Net
        x = self.regressor(x)

        return x


from collections import deque

input_cups = '364297581'
cups = list(map(int, input_cups))

class Node:
    def __init__(self, value, next):
        self.value = value
        self.next = next

    def pop_next_n(self, n):
        next_n = []

        curr = self.next
        for _ in range(n):
            next_n.append(curr)
            curr = curr.next

        self.next = curr

        return next_n

    def insert_after(self, nodes):
        prev = self
        prev_next = self.next
        for node in nodes:
            prev.next = node
            prev = node
        prev.next = prev_next

    def values(self):
        values = [self.value]
        curr = self.next
        while curr != self:
            values.append(curr.value)
            curr = curr.next
        return values

    def __repr__(self):
        return " ".join(map(str, self.values()))

def decrement_and_wrap(num, min, max):
    return (num - 1 - min) % max + min

def move(cups, n):
    max_cup = max(cups)
    min_cup = min(cups)

    cup_map = {}
    prev = None
    last = None
    for cup in reversed(cups):
        node = Node(cup, prev)
        cup_map[cup] = node
        if not last:
            last = node
        prev = node
    head = prev
    last.next = head

    current_cup = head

    for _ in range(n):
        pick_up = current_cup.pop_next_n(3)
        pick_up_values = {node.value for node in pick_up}

        destination_cup_value = decrement_and_wrap(current_cup.value, min_cup, max_cup)
        while destination_cup_value in pick_up_values:
            destination_cup_value = decrement_and_wrap(destination_cup_value, min_cup, max_cup)

        destination_cup = cup_map[destination_cup_value]
        destination_cup.insert_after(pick_up)

        current_cup = current_cup.next

    return head.values(), cup_map

final_order, _ = move(cups, 100)
print(final_order)

max_cup = max(cups)
more_cups = cups + [cup for cup in range(max_cup + 1, 1_000_000 + 1)]

_, cup_map = move(more_cups, 10_000_000)

cup_1 = cup_map[1]
print(cup_1.next.value * cup_1.next.next.value)


# -*- mode: python -*-

block_cipher = None

a = Analysis(['manage.py'],
             pathex=['C:\\Users\\Trouble\\Desktop\\Pack_Test'],
             binaries=[],
             datas=[(r'C:\Users\Trouble\Desktop\Pack_Test\static_root',r'.\static_root'), (r'C:\Users\Trouble\Desktop\Pack_Test\templates', r'.\templates')],
             hiddenimports=['django.contrib.admin',
                            'django.contrib.auth',
                            'django.contrib.contenttypes',
                            'django.contrib.sessions',
                            'django.contrib.messages',
                            'django.contrib.staticfiles',
                            'Zawarudo',
                            'django.middleware.security.SecurityMiddleware',
                            'django.contrib.sessions.middleware.SessionMiddleware',
                            'django.middleware.common.CommonMiddleware',
                            'django.middleware.csrf.CsrfViewMiddleware',
                            'django.contrib.auth.middleware.AuthenticationMiddleware',
                            'django.contrib.messages.middleware.MessageMiddleware',
                            'django.middleware.clickjacking.XFrameOptionsMiddleware',
                            'django.template.context_processors.debug',
                            'django.template.context_processors.request',
                            'django.contrib.auth.context_processors.auth',
                            'django.contrib.messages.context_processors.messages',
                            'Zawarudo.urls',
                            ],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='manage',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='manage')


from abc import ABC, abstractmethod
from typing import Protocol

from src.schedule.demand_schedule_strategy import DemandScheduleStrategy
from src.schedule.random_schedule_strategy import RandomScheduleStrategy
from src.schedule.regular_schedule_strategy import RegularScheduleStrategy
from src.schedule.schedule_configuration import ScheduleConfiguration
from src.schedule.schedule_strategy import ScheduleStrategy
from src.wrapper.train_builder import TrainBuilder

class SpawnerProtocol(Protocol):
    """Protocol for the Spawner"""

    train_spawner: TrainBuilder

class Schedule(ABC):
    """An abstract schedule for spawning SUMO vehicles."""

    id: str
    _blocked: bool
    _seconds_to_be_spawned: list[int]
    strategy: ScheduleStrategy

    STRATEGY_CLASSES: dict[str, type] = {
        "RegularScheduleStrategy": RegularScheduleStrategy,
        "RandomScheduleStrategy": RandomScheduleStrategy,
        "DemandScheduleStrategy": DemandScheduleStrategy,
    }

    @classmethod
    def strategy_from_schedule_configuration(
        cls, schedule_configuration: ScheduleConfiguration
    ) -> ScheduleStrategy:
        """Dynamically cosntructs a ScheduleStrategy from a ScheduleConfiguration

        :param schedule_configuration: The Schedule configuration
        :return: A ScheduleStrategy
        """
        strategy_type = schedule_configuration.strategy_type
        strategy_class = cls.STRATEGY_CLASSES[strategy_type]
        assert issubclass(strategy_class, ScheduleStrategy)
        return strategy_class.from_schedule_configuration(schedule_configuration)

    def __init__(self, strategy: ScheduleStrategy, id_: str):
        """Constructs a Schedule."""
        self._blocked = False
        self._seconds_to_be_spawned = []
        self.strategy = strategy
        self.id = id_  # pylint: disable=invalid-name

    @abstractmethod
    def _spawn(self, spawner: SpawnerProtocol, seconds: int) -> bool:
        """Spawns a vehicle.

        :param spawner: The calling Spawner.
        :param seconds: The elapsed seconds
        """
        raise NotImplementedError()

    def maybe_spawn(self, seconds: int, spawner: SpawnerProtocol):
        """Spawns a vehicle if the schedule strategy allows it.

        :param seconds: The elapsed seconds
        :param spawner: The calling spawner.
        """
        if not self._blocked and self.strategy.should_spawn(seconds):
            self._seconds_to_be_spawned.append(seconds)

        if len(self._seconds_to_be_spawned) > 0:
            if self._spawn(spawner, self._seconds_to_be_spawned[-1]):
                self._seconds_to_be_spawned.pop()

    def block(self):
        """Blocks the schedule.

        :raises RuntimeError: when the schedule is already blocked
        """
        if self._blocked:
            raise RuntimeError(f"Schedule {self.id} is already blocked")
        self._blocked = True

    def unblock(self):
        """Unblocks the schedule.

        :raises RuntimeError: when the schedule is already unblocked
        """
        if not self._blocked:
            raise RuntimeError(f"Schedule {self.id} is already unblocked")
        self._blocked = False


import sqlite3

sq_baglanti = sqlite3.connect("Kütüphane.db")

imlec = sq_baglanti.cursor()

def tablo_olustur():
    imlec.execute("CREATE TABLE IF NOT EXISTS kitaplik (isim TEXT, yazar TEXT, Yayınevi TEXT, Sayfa_sayısı INT)")
    sq_baglanti.commit()
tablo_olustur()

def veri_ekle():
    imlec.execute("Insert into kitaplik Values('İstanbul Hatırası','Ahmet Ümit','Everest',561)")
    sq_baglanti.commit()
# veri_ekle()

def veri_ekle2(isim,yazar,yayinevi,sayfa):
    imlec.execute(f"Insert into kitaplik Values('{isim}','{yazar}','{yayinevi}',{sayfa})")
    sq_baglanti.commit()

isim = input("Kitap İsmini Giriniz: ")
yazar = input("Yazar İsmini Giriniz: ")
yayinevi = input("Yayınevi İsmini Giriniz: ")
sayfa = int(input("Sayfa Sayısını Giriniz: "))

if input("Girdiğiniz bilgileri eklemek istiyor musunuz ?\n(y \ n) ") == "y":
    veri_ekle2(isim, yazar, yayinevi, sayfa)
    print("Bilgiler Eklendi")
else:
    print("Ekleme Yapılmadı")

sq_baglanti.close()


"""
    -*- coding: utf-8 -*-
    @Author: yaofanghao
    @Date: 2023/7/24 10:42
    @Filename: test.py
    @Software: PyCharm
"""

# -*- coding: utf-8 -*-

import os
import cv2
import numpy as np

def readimg(image_path, output_path):
    image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
    # image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    output_image_name = image_path.rsplit("\\", 1)[-1]
    output_path_all = output_path+output_image_name

    # 处理模块，在这里进行修改
    _, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

    cv2.imencode('.jpg', binary_image)[1].tofile(output_path_all)

    print("111")
    # cv2.imshow('Binary Image', binary_image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    return 1

# image_path="C:\\Users\\Rainy\\Desktop\\test_camera\\img\\210.jpg"
# output_path="C:\\Users\\Rainy\\Desktop\\test_camera\\img_out\\"
# readimg(image_path=image_path, output_path=output_path)


nome = str(input('Digite seu nome completo: ')).strip()
# Todas letras maiusculas
print(nome.upper())

# Todas Letras Minusculas
print(nome.lower())

# Total de letras sem considerar espaços
caracteres = len(nome)
espacos = int(nome.count(' '))
letras = caracteres - espacos
print('Existem {} letras ao total.'.format(letras))

# Total de letras do primeiro nome
divido = nome.split()
fname = divido[0]
print('Primeiro nome possui {} letras.'.format(len(fname)))


# Largely adapted from https://github.com/altair-viz/altair/blob/master/setup.py, BSD licensed

import io
import os
import re

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

# ==============================================================================
# Utilities
# ==============================================================================

def read(path, encoding="utf-8"):
    path = os.path.join(os.path.dirname(__file__), path)
    with io.open(path, encoding=encoding) as fp:
        return fp.read()

def get_req(path):
    content = read(path)
    return [req for req in content.split("\n") if req != "" and not req.startswith("#")]

def version(path):
    """Obtain the packge version from a python file e.g. pkg/__init__.py

    See <https://packaging.python.org/en/latest/single_source_version.html>.
    """
    version_file = read(path)
    version_match = re.search(
        r"""^__version__ = ['"]([^'"]*)['"]""", version_file, re.M
    )
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

HERE = os.path.abspath(os.path.dirname(__file__))

# From https://github.com/jupyterlab/jupyterlab/blob/master/setupbase.py, BSD licensed
def find_packages(top=HERE):
    """
    Find all of the packages.
    """
    packages = []
    for d, dirs, _ in os.walk(top, followlinks=True):
        if os.path.exists(os.path.join(d, "__init__.py")):
            packages.append(os.path.relpath(d, top).replace(os.path.sep, "."))
        elif d != top:
            # Do not look for packages in subfolders if current is not a package
            dirs[:] = []
    return packages

# ==============================================================================
# Setup
# ==============================================================================

setup(
    name="customlibrary",
    version=version("./customlibrary/__init__.py"),
    description=""""Project Name" needs a short and sweet description here.""",
    long_description=read("README.md"),
    long_description_content_type="text/markdown",
    author="Author Name",
    author_email="author.email@email.com",
    url="https://github.com/author/this-repository",
    download_url="https://github.com/author/this-repository",
    packages=find_packages(),
    include_package_data=True,
    install_requires=get_req("requirements.txt"),
    extras_require={
        "dev": get_req("requirements_dev.txt"),
        "test": get_req("requirements_test.txt"),
    },
    classifiers=[
        "Development Status :: 1 - Planning",  # 1 - Planning, 2 - Pre-Alpha, 3 - Alpha, 4 - Beta, 5 - Production/Stable, 6 - Mature, 7 - Inactive
        "Environment :: Console",
        "Intended Audience :: Science/Research",
        "License :: MIT License",
        "Natural Language :: English",
        "Programming Language :: Python :: 3.0",
        "Programming Language :: Python :: 3.1",
        "Programming Language :: Python :: 3.2",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.0",
    project_urls={
        "Bug Reports": "https://github.com/author/this-repository/issues",
        "Source": "https://github.com/author/this-repository/",
    },
)


# 739. Daily Temperatures
class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        '''
        Monotonic stack
        Store the index of the previous temperatures in a stack, when seeing
        a new temperature t, if last temperature < t, pop stack and mark that
        previous index using the current distance.

        Time: O(n) where n is len(T)
        Space: O(n)
        '''
        prev_temp_idx = []
        ans = [0] * len(T)
        for i, t in enumerate(T):
            while prev_temp_idx and T[prev_temp_idx[-1]] < t:
                prev_i = prev_temp_idx.pop()
                ans[prev_i] = i - prev_i
            prev_temp_idx.append(i)
        return ans


import os
from datetime import date
from maya import cmds

today = date.today()
ws = cmds.workspace( q=True, rootDirectory=True )
current_date = today.strftime("%Y%m%d")
file_path_abs = cmds.file(q=True, sn=True)
file_path_rlt = file_path_abs.replace(ws, "")
asset_name = file_path_rlt.split("/")[-1].split("_")[1]
print(asset_name)
full_path = "/".join([ws, "images", "dailyScreenShot", asset_name, current_date])
print(full_path)
if not os.path.exists(full_path):
    os.makedirs(full_path)

class ImgName():
    i = 0
    def __call__(self, name):
        self.i += 1
        return '{:02}_{}'.format(self.i, name)
In = ImgName()

def take_screenShot(name, width=1920, height=1080):
    img_path = "/".join([full_path, name + ".jpg"])
    cmds.playblast(fr=0, v=False, fmt="image", c="jpg", orn=False, cf=img_path, wh=[width,height], p=100)

def switch_light(on=True):
    currentPanel = cmds.getPanel(withFocus=True)

    if cmds.getPanel(to=currentPanel) == "modelPanel":
        if on:
            cmds.modelEditor(currentPanel, e=True, dl="default")
        else:
            cmds.modelEditor(currentPanel, e=True, dl="none")

def zoom(v):
    currentPanel = cmds.getPanel(withFocus=True)

    if cmds.getPanel(to=currentPanel) == "modelPanel":
        curCamera=cmds.modelEditor(currentPanel,q=1,av=1,cam=1)
        cmds.xform(curCamera, rt=[0, 0, v], r=True, os=True)

def fit():
    if cmds.ls("GEO"):
        cmds.select(cmds.ls("GEO"), r=True)
    else:
        cmds.select(cmds.listRelatives(cmds.ls(geometry=True), p=True, path=True), r=True)
    cmds.viewFit()
    cmds.select(cl=True)

def isolateSelected(state):
    viewport = cmds.getPanel( withFocus = True)
    if cmds.ls("GEO"):
        cmds.select(cmds.ls("GEO"), r=True)
    else:
        cmds.select(cmds.listRelatives(cmds.ls(geometry=True), p=True, path=True), r=True)
    if 'modelPanel' in viewport:
        if state:
            cmds.isolateSelect( viewport, addSelected=True )
            cmds.isolateSelect( viewport, s=True )
            cmds.isolateSelect( viewport, addSelected=True )
            cmds.isolateSelect( viewport, s=True )
        else:
            cmds.isolateSelect( viewport, s=False )
    cmds.select(cl=True)

def wireframe_switcher(state=None):
    viewport = cmds.getPanel( withFocus = True)
    if 'modelPanel' in viewport:

        currentState = cmds.modelEditor( viewport, q = True, wireframeOnShaded = True) if state == None else not state
        if currentState:
            cmds.modelEditor( viewport, edit = True, wireframeOnShaded = False)
        else:
            cmds.modelEditor( viewport, edit = True, wireframeOnShaded = True)

old_sl = cmds.ls(sl=True)
current_view = cmds.lookThru(q=True)
cmds.lookThru('persp')
isolateSelected(True)

# fit()
# zoom(-20)
wireframe_switcher(False)
switch_light(True)

take_screenShot(In("default"))

switch_light(False)
take_screenShot(In("shadow"))
switch_light(True)

wireframe_switcher(True)
take_screenShot(In("wireframe"))
wireframe_switcher(False)

# zoom(20)

cmds.lookThru('front')
fit()
# cmds.dolly( 'front', os=0.6666 )
take_screenShot(In("front"))
# cmds.dolly( 'front', os=1.5 )
cmds.hotkey( 'z', query=True, alt=True )

cmds.lookThru('side')
fit()

# cmds.dolly( 'side', os=0.6666 )
take_screenShot(In("side"))
cmds.hotkey( 'z', query=True, alt=True )

# cmds.dolly( 'side', os=1.5 )
cmds.lookThru(current_view)
cmds.select(old_sl)
isolateSelected(False)


list = [5,4,6]
'''
Словарь-структура данных доступ к информации у которой * по ключу
Множество-структура данных для хранения уникальных значений
'''
dict()
d = {'dict': 1, 'dictionary': 2}
print(d['dict'])
set()
a= set([3,1,7,7])
{}
print(a)
names = set()
name = input()
visitors = dict()
while name != '0':
    names.add(name)
    if visitors.get(name) != None:
        visitors[name] +=1
    else:
        visitors[name] = 1
    name = input()
print(names)
print(visitors)


from slackclient import SlackClient
from kubernetes import client, config,watch
import argparse
import json
from datetime import date, datetime, timezone

slack_token = "YOUR TOKEN"
sc = SlackClient(slack_token)

gbl_channel=""

def build_arg_parser():
    """
    Builds a standard argument parser with arguments for talking to vCenter
    -s service_host_name_or_ip
    -o optional_port_number
    -u required_user
    -p optional_password
    """
    parser = argparse.ArgumentParser(
        description='Standard Arguments for talking to k8s')

    parser.add_argument('-k', '--ctxt',
                        required=True,
                        action='store',
                        help='Set context kubernetes')

    parser.add_argument('-e', '--only_error',
                        required=False,
                        action='store_true',
                        help='Enable error check')

    parser.add_argument('-c', '--channel',
                        required=True,
                        action='store',
                        help='Channel name to use when sending to slack')

    return parser

def get_args():
    """
    Supports the command-line arguments needed to form a connection to vSphere.
    """
    parser = build_arg_parser()

    args = parser.parse_args()

    return (args)

def sc_call():
    sc.api_call(
      "chat.postMessage",
      channel="#kubedev_chan",
      text="Hello from Python! :tada:"
    )

def send_slack_msg(chan,ico,text):

    sc.api_call("chat.postMessage",
    channel=chan,
    icon_emoji =ico,
    as_user=False,
    attachments= text)

def create_field(my_list, title, value, short=True):
    if value != None:
        if (  isinstance(value, dict)):
            dictstr = '\n'.join('{} : {}'.format(key, value) for key, value in value.items())
            my_list.append( { "title" :title, "value" :dictstr, "short" : short})
        elif ( isinstance(value, datetime) ):
           my_list.append( { "title" :title, "value" :value.isoformat(), "short" : short})
        else:
            my_list.append( { "title" :title, "value" :value, "short" : short})

def extract_event_info(ctxt, event, mode='good'):
    global gbl_channel
    my_list=[]

    create_field(my_list, "namespaces", event.metadata.namespace)
    create_field(my_list, "name", event.metadata.name)
    create_field(my_list, "labels", event.metadata.labels)
    create_field(my_list, "status.message", str(event.status.container_statuses[0].state))
    create_field(my_list, "status.start_time", event.status.start_time)
    create_field(my_list, "status.phase", event.status.phase)
    c = datetime.now(timezone.utc) - event.status.start_time
    create_field(my_list, "Runing since", str(c))
    text=[
    {

      "color" : mode,
      "pretext" : "Just from information from k8s" + ctxt ,
      "fields" : my_list
    }
    ]

    send_slack_msg(gbl_channel, ":k8s:", text)

def main():
    global gbl_channel
    args = get_args()
    gbl_channel=args.channel
    contexts, active_context = config.list_kube_config_contexts()
    if not contexts:
        print("Cannot find any context in kube-config file.")
        return

    client1 = client.CoreV1Api(
        api_client=config.new_client_from_config(context=args.ctxt))

    only_error = args.only_error

    for event in client1.list_pod_for_all_namespaces(watch=False).items:
        if only_error == True :
            for i in event.status.container_statuses :
                if(i.ready == False and i.restart_count != 0):
                    extract_event_info(args.ctxt, event, "danger")
            #if (event.status.phase != "Running" and event.status.phase != "Succeeded"):
            #    extract_event_info(args.ctxt, event, "danger")
        else:
            extract_event_info(args.ctxt, event )

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
"""
Handy utility to reformat some data for use in a d3js chart.
  read input xls data file
  find final averages sheet
  allow for different years
  find the rows we want
  write intermediate per-year csv files??
  get maxaverages, do scaling
  write the yearly jsons
"""

__author__ = "Richard Leir"
__copyright__ = "Copyright 2018, Richard Leir"
__credits__ = ["Kathy Conlan", "Mike Bostock"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Richard Leir"
__email__ = "rleir at leirtech ddot com"
__status__ = "Production"

import csv
import json
from xlrd import open_workbook # type: ignore
from importdata import chart_by_mapsite
from typing import Dict, List

# The input spreadsheet might contain more species than we want to display.
# Here is the way to indicate which species we want to display:
featured_species = {} # type: Dict[ str, str]

all_years = [ ] # type: List[ str]

# Site name keys below match the column headers in the input xlsx
site_keys = [] # type: List[ str]

species_keys = []

all_data   = {} # type: Dict
max_average   = {} # type: Dict

def initData() -> None:
    global all_years
    with open("data/allyears.json") as json_file:
        all_years= json.load( json_file)

    global featured_species
    global species_keys
    with open("data/featured_species.json") as json_file:
        featured_species = json.load( json_file)
    species_keys = list(featured_species.keys())

    positions = [ ] # type: List[ Dict[ str,str]]
    with open("data/positions.json") as json_file:
        positions= json.load( json_file)
    for position in positions:
        site_keys.append(position['placeName'])

    for year in all_years:
        all_data[year] = {}

        for site_key in site_keys:
            all_data[year][site_key] = []
            all_data[year][site_key].append({})
            all_data[year][site_key][0]["data"   ]={}
            all_data[year][site_key][0]["average"]={}
            for species in species_keys:
                abbr = featured_species[species]
                all_data[year][site_key][0]["data"][abbr]=0
                all_data[year][site_key][0]["average"][abbr]=-10

def readFiles() -> None:
        # read xls, find avg sheet
        path = "data/SpeciesCounts.xlsx"
        wb = open_workbook(path)
        final_av_s_found = 0
        for sheet in wb.sheets():
            shname = sheet.name
            if shname.endswith("ave"):
                final_av_s_found = 1
                coltoyear=[] # type: List[ str]
                maxcol = 0
                for row in range(sheet.nrows):
                    if row == 0:
                        for col in range(sheet.ncols):
                            if "MAX" == sheet.cell(row,col).value:
                                maxcol = col
                    elif row == 1:
                        coltoyear = readheader(sheet,row)
                    else:
                        for col in range(sheet.ncols):
                            if col == 0:
                                species = sheet.cell(row,col).value
                                if species not in featured_species:
                                    continue
                                else:
                                    abbr = featured_species[species]
                                    for datacol in range(sheet.ncols):
                                        colval = coltoyear[datacol]
                                        if maxcol == datacol:
                                            max_average[abbr]= sheet.cell(row,datacol).value

                                        if colval == "MAXAVG":
                                            max_average[abbr]= sheet.cell(row,datacol).value

                                        elif datacol > 0 and colval != "not ave col":
                                            year = coltoyear[datacol][-4:]
                                            site = coltoyear[datacol][:-4]
                                            all_data[year][site][0]["average"][abbr] = sheet.cell(row,datacol).value
        if final_av_s_found == 0 :
            print("final averages sheet not found in " + path)

def scaleData() -> None:
    running_count = {}
    check_max_average   = {}

    for species_key in species_keys:
        abbr = featured_species[species_key]
        check_max_average  [abbr] = 0
        running_count[abbr] = 0

    # find the max average for each species
    for year in all_years:
        for site_key in site_keys:
            for species_key in species_keys:
                abbr = featured_species[species_key]
                replicates_average = all_data[year][site_key][0]["average"][abbr]
                if  check_max_average[ abbr] < replicates_average :
                    check_max_average[  abbr] = replicates_average
                    running_count[abbr] += 1

    for species_key in species_keys:
        abbr = featured_species[species_key]
        if check_max_average[abbr] <= 0 :
            print("error, running count 0 " + abbr)
        if running_count[abbr] <= 0 :
            print("error, running count 0 " + abbr)

    # scale all the data in the range 0 to 100 where 100 represents the max average
    for year in all_years:
        for site_key in site_keys:
            for species_key in species_keys:
                abbr = featured_species[species_key]
                replicates_average = all_data[year][site_key][0]["average"][abbr]

                if max_average[  abbr] != check_max_average[  abbr]:
                    print("max_avg="+ str(max_average[  abbr]) + " check_max=" + str(check_max_average[  abbr]) + " species=" + abbr)
                max_avg = check_max_average[  abbr]

                display = -10.0 # should be 0, but -10 is a flag saying 'no data'
                #display = 1.0 # should be 0, but 1 avoids a bug in the tweening
                if replicates_average > -10 :
                    #display = replicates_average*100 / (max_avg+0.00001)
                    display = replicates_average*100 / max_avg
                all_data[year][site_key][0]["data"][abbr] = display

def writeFiles() -> None:
    for year in all_years:
        # write output
        output_file = "data/all_sites_" + str(year) + ".csv"

        with open(output_file, 'w', newline='') as csvfile:
            fieldnames = ["organism","abbr"] + site_keys
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            for species_key in species_keys:
                abbr = featured_species[ species_key]
                row_data = {'organism': species_key, 'abbr': abbr}
                for site_key in site_keys:
                    row_data[site_key] =        all_data[year][site_key][0]["data"][abbr]
                writer.writerow(row_data)

def readheader(sheet,row) -> List[str]:
    coltoyear=[]
    for col in range(sheet.ncols):
        colheader = sheet.cell(row,col).value
        if colheader == "MAX":
            coltoyear.append("MAXAVG")
        elif not colheader.endswith("-ave"):
            coltoyear.append("not ave col")

        else:
                siten =  colheader[:-6]
                year = colheader[-6:-4]
                if int(year) > 80:
                    year = "19"+year
                else:
                    year = "20"+year
                coltoyear.append(siten+year)
    return coltoyear

if __name__ == "__main__":
    # execute only if run as a script

    initData()
    readFiles()
    scaleData()
    writeFiles()

    for year in all_years:
        chart_by_mapsite(year)


S = lambda: map(int, input().split())
L = lambda: list(S())

def solve():
    n = int(input())
    l = L()
    l.extend(l)
    l1 = l.copy()
    l.reverse()
    l2 = l.copy()
    incs, decs = 0, 0
    incst, decst = 2*n-1, 2*n-1
    ans1, ans2 = -1, -1
    for i in range(2*n-2, -1, -1):
        if l1[i] < l1[i+1]:
            incs = 0
            decs += 1
            incst = i
        elif l1[i] > l1[i+1]:
            incs += 1
            decs = 0
            decst = i
        else:
            incs += 1
            decs += 1
        if decs == n-1:
            ans1 = 2*n-1-decst
            break
        if incs == n-1:
            ans1 = 2*n-incst
            break

    incs, decs = 0, 0
    incst, decst = 2*n-1, 2*n-1
    for i in range(2*n-2, -1, -1):
        if l2[i] < l2[i+1]:
            incs = 0
            decs += 1
            incst = i
        elif l2[i] > l2[i+1]:
            incs += 1
            decs = 0
            decst = i
        else:
            incs += 1
            decs += 1
        if decs == n-1:
            ans2 = 2*n-decst
            break
        if incs == n-1:
            ans2 = 2*n+1-incst
            break
    if n == 1:
        print(0)
    else:
        print(min(ans1, ans2))
    return

if __name__ == "__main__":
    for test in range(int(input())):
        solve()


class Solution:
    def maximumGap(self, nums: List[int]) -> int:
        if len(nums) < 2:
            return 0
        hi, lo, ans = max(nums), min(nums), 0
        bsize = (hi - lo) // (len(nums) - 1) or 1
        buckets = [[] for _ in range(((hi - lo) // bsize) + 1)]
        for n in nums:
            buckets[(n - lo) // bsize].append(n)
        currhi = 0
        for b in buckets:
            if not len(b): continue
            prevhi, currlo = currhi or b[0], b[0]
            for n in b:
                currhi, currlo = max(currhi, n), min(currlo, n)
            ans = max(ans, currlo - prevhi)
        return ans


TANK = 1
PLATFORM = 1 << 1
BULLET = 1 << 2
EXPLOSION = 1 << 3
POWERUP = 1 << 4
TANK_DEF = ("player_input", "floor_collision", "body", "tank_graphic")
PLATFORM_DEF = ("collision", "sprite")
BULLET_DEF = ("body", "collision", "sprite")
EXPLOSION_DEF = ("body", "collision", "timer", "sprite")
WIDTH = 480*2
HEIGHT = 320*2
VWIDTH = 480
VHEIGHT = 320
TANK_SPEED = 64.
SIZE = 16.
G = VHEIGHT
MAX_FALLING_SPEED = G/2.
MAX_ASCENDING_SPEED = G/2.


#!/usr/bin/env python
import time, math
import numpy as np

import christine_hwi_ext

import pdb

#
# Drive circle of given radius
#
#   can be used to check steering servo
#
class Controller:

    def __init__(self, vel_cps, R):
        self.vel_cps = vel_cps
        self.R = R      # Radius of circle
        self.L = 0.27   # Distance between front and rear wheels

    def get(self): return self.vel_cps, np.arctan2(self.L, self.R)

    def alpha_to_servo(self, _a): return 1.508*_a

    # 0.75 -> 1.520
    # 1.25 -> 1.535
    # 2.   -> 1.523

def drive(bbbl, vel_cps, R, d_psi=np.pi):
    ctl = Controller(vel_cps, R)
    while True:
        vel_cps, alpha = ctl.get()
        srv = ctl.alpha_to_servo(alpha)
        print('alpha {:.2f} deg servo {:.1f} %'.format(np.rad2deg(alpha), srv*100.))
        bbbl.send(srv, vel_cps)
        time.sleep(0.02)

def main():
    bbbl = christine_hwi_ext.BBBLink()
    bbbl.init()
    drive(bbbl, vel_cps=60, R=0.75)

if __name__ == '__main__':
    main()


from . import cross_val2
if __name__ == "__main__":
    df = pd.read_csv("../../input/kaggle_cat_data/cat-in-the-dat-ii/train.csv")
    cv = cross_validation.CrossValidation(df, shuffle=True, target_cols=["attribute_ids"],
        problem_type="multilabel_classification", multilabel_delimiter=" ")

    df_split = cv.split()
    print(df_split.head())
    print(df_split.kfold.value_counts())


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

# In[1]:

import pandas as pd
import numpy as np
import csv
import json
import urllib.parse
from statistics import mean
import networkx as nx

# In[2]:

i=1
reader=open("paths_finished.tsv")
paths = csv.reader(reader, delimiter="\t")
paths_finished=[]
for row in paths:
    if(i>16):
        l=row[3].split(';')
        s=urllib.parse.unquote(l[0])
        d=urllib.parse.unquote(l[-1])
        paths_finished.append([s,d])
    i+=1
#paths_finished

# In[3]:

with open("articleAllCategory.json", "r") as f:
    artAllCat = json.load(f)
#artAllCat

# In[4]:

with open("human_path_len.json", "r") as f:
    total_len = json.load(f)
#total_len

# In[5]:

with open("short_path.json", "r") as f:
    short_path = json.load(f)
#short_path

# In[6]:

with open("back_clicks.json", "r") as f:
    back_clicks = json.load(f)
#back_clicks

# In[7]:

finish_cat_pair={}
x=1
for ele in paths_finished:
    s_cat=artAllCat[ele[0]]
    d_cat=artAllCat[ele[1]]
    human_path=total_len[str(x)]-2*back_clicks[str(x)]
    ratio=human_path/short_path[str(x)]
    x+=1
    all_permutation=[[i,j] for i in s_cat for j in d_cat]
    for per in all_permutation:
        finish_cat_pair[tuple(per)]=finish_cat_pair.get(tuple(per),[])
        finish_cat_pair[tuple(per)].append(ratio)
#finish_cat_pair

# In[8]:

finish_list=[]
for (key,val) in finish_cat_pair.items():
    avg=mean(val)
    finish_list.append([key[0],key[1],avg])
#finish_list

# In[9]:

finish_list.sort()

# In[10]:

df=pd.DataFrame(finish_list,columns=['From_Category','To_Category','Ratio_of_human_to_shortest'])

# In[11]:

df.to_csv("category-ratios.csv",index=False)

# In[ ]:


class user:
    def __init__(self,  name):
        self.balance = 0
        self.name = name

    def make_deposite(self, amount):
        self.balance += amount

    def make_withdrawal(self, amount):
        self.balance -= amount

    def display_user_balance(self):
        pass

user1 = user("Qamar")
user1.make_deposite(500)
user1.make_deposite(100)
user1.make_deposite(200)
user1.make_withdrawal(300)
print(user1.name)
print("User's name is {} and has {} balance".format(user1.name,user1.balance))

user2 = user("Asmaa")
user2.make_deposite(500)
user2.make_deposite(100)
user2.make_withdrawal(200)
user2.make_withdrawal(300)
print(user2.name)
print("User's name is {} and has {} balance".format(user2.name,user2.balance))

user3 = user("Denise")
user3.make_deposite(500)
user3.make_withdrawal(100)
user3.make_withdrawal(100)
user3.make_withdrawal(200)
print(user3.name)
print("User's name is {} and has {} balance".format(user3.name,user3.balance))


"""Style transfer reimplementation

- Get a pre-trained encoder
- Get a style image
- Get a content image
- Get a gaussian noise image
- Define style loss and content loss
- Optimize the noise image to lower that loss
"""
from collections import namedtuple

import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models

class VGG16(nn.Module):
    def __init__(self):
        super(VGG16, self).__init__()
        self.pretrained = models.vgg16(pretrained=True).features
        self.pool_indices = [4, 9, 16, 23, 30]
        self.output = namedtuple(
            "Outputs", ["slice{}".format(idx) for idx in range(len(self.pool_indices))]
        )

    def forward(self, input_x):
        outputs = []
        h = input_x
        last_idx = 0
        for pool_idx in self.pool_indices:
            h = self.pretrained[last_idx:pool_idx](h)
            outputs.append(h)
            last_idx = pool_idx

        return self.output(*outputs)

def prepare_image(np_image):
    image = torch.FloatTensor(np_image) / 255
    image = image.permute(2, 0, 1).unsqueeze(0)
    mean = image.new_tensor([0.485, 0.456, 0.406]).view(-1, 1, 1)
    std = image.new_tensor([0.229, 0.224, 0.225]).view(-1, 1, 1)
    return (image - mean) / std

def get_npimage(image):
    mean = image.new_tensor([0.485, 0.456, 0.406]).view(-1, 1, 1)
    std = image.new_tensor([0.229, 0.224, 0.225]).view(-1, 1, 1)
    np_image = (image * std + mean) * 255.0
    np_image = np_image.clamp(0.0, 255.0)
    np_image = np_image.squeeze().permute(1, 2, 0).cpu().data.numpy()
    return np_image.astype(np.uint8)

def gram_matrix(features):
    """Construct the gram matrix for a feature map"""
    batch, channels, height, width = features.shape
    features = features.view(batch, channels, height * width)
    inner_prod = torch.bmm(features, features.transpose(1, 2))
    return inner_prod / (channels * height * width)

if __name__ == "__main__":

    content_weight = 1e3
    style_weight = 1e8

    # get encoder
    encoder = VGG16()
    encoder.eval()
    for each_param in encoder.parameters():
        each_param.requires_grad = False

    # get content & style images
    content_image = cv2.cvtColor(cv2.imread('datasets/content.jpg'), cv2.COLOR_BGR2RGB)
    content_image = prepare_image(content_image)
    style_image = cv2.cvtColor(cv2.imread('datasets/style_picasso.jpg'), cv2.COLOR_BGR2RGB)
    style_image = prepare_image(style_image)

    # random image to optimize
    image = torch.randn(*content_image.shape)
    criterion = nn.MSELoss()

    # use gpu
    encoder = encoder.cuda()
    content_image, style_image = content_image.cuda(), style_image.cuda()
    image = image.cuda()

    # optimization
    image = image.requires_grad_()
    optimizer = optim.Adam([image], lr=1e-3)

    style_output = encoder(style_image)
    style_grams = [gram_matrix(each) for each in style_output[:-2]]
    content_output = encoder(content_image)

    for idx in range(30001):
        output = encoder(image)

        grams = [gram_matrix(each) for each in output[:-2]]
        style_loss = 0
        for style1, style2 in zip(grams, style_grams):
            style_loss += criterion(style1, style2)

        content_loss = criterion(output[2], content_output[2])
        loss = content_weight * content_loss + style_weight * style_loss

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if idx % 1000 == 0:
            print(idx, loss.item(), style_loss.item(), content_loss.item())
            im = get_npimage(image)
            cv2.imwrite(f'logs/{idx}.png', cv2.cvtColor(im, cv2.COLOR_RGB2BGR))


import game_gui
import pygame
import random
import sys

DIAMOND_ASSETPATH = {
    "red": "./assets/red_diamond.png",
    "green": "./assets/green_diamond.png",
    "blue": "./assets/blue_diamond.png",
    "yellow": "./assets/yellow_diamond.png",
    "tan": "./assets/tan_diamond.png",
    "grey": "./assets/grey_diamond.png",
    "teal": "./assets/teal_diamond.png"
}
HEXAGON_ASSETPATH = {
    "red": "./assets/red_hexagon.png",
    "green": "./assets/green_hexagon.png",
    "blue": "./assets/blue_hexagon.png",
    "yellow": "./assets/yellow_hexagon.png",
    "tan": "./assets/tan_hexagon.png",
    "grey": "./assets/grey_hexagon.png",
    "teal": "./assets/teal_hexagon.png"
}
OCTAGON_ASSETPATH = {
    "red": "./assets/red_octagon.png",
    "green": "./assets/green_octagon.png",
    "blue": "./assets/blue_octagon.png",
    "yellow": "./assets/yellow_octagon.png",
    "tan": "./assets/tan_octagon.png",
    "grey": "./assets/grey_octagon.png",
    "teal": "./assets/teal_octagon.png"
}
SQUARE_ASSETPATH = {
    "red": "./assets/red_square.png",
    "green": "./assets/green_square.png",
    "blue": "./assets/blue_square.png",
    "yellow": "./assets/yellow_square.png",
    "tan": "./assets/tan_square.png",
    "grey": "./assets/grey_square.png",
    "teal": "./assets/teal_square.png"
}
TRIANGLE_ASSETPATH = {
    "red": "./assets/red_triangle.png",
    "green": "./assets/green_triangle.png",
    "blue": "./assets/blue_triangle.png",
    "yellow": "./assets/yellow_triangle.png",
    "tan": "./assets/tan_triangle.png",
    "grey": "./assets/grey_triangle.png",
    "teal": "./assets/teal_triangle.png"
}
"""Coding global variables"""
global FPS_CLOCK, DISPLAYSURF
FPS = 100  # frames per second, the general speed of the program
WINDOWWIDTH = 1000  # size of window's width in pixels
WINDOWHEIGHT = 700  # size of windows' height in pixels
REVEALSPEED = 10  # speed boxes' sliding reveals and covers
BOXSIZE = 50  # size of box height & width in pixels
GAPSIZE = 10  # size of gap between boxes in pixels
BOARDWIDTH = 4  # number of columns of icons
BOARDHEIGHT = 3  # number of rows of icons
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)
GAME_SCORE = 0
GAME_LEVEL = 1
GAME_PAUSED = False

#            R    G    B
GRAY = (100, 100, 100)
ROYALBLUE = (0, 35, 102)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)

BGCOLOR = ROYALBLUE
LIGHTBGCOLOR = GRAY
BOXCOLOR = WHITE
HIGHLIGHTCOLOR = BLUE

TIMER_PAUSED = False
TIMER_RUNNING = True

SQUARE = 'square'
DIAMOND = 'diamond'
HEXAGON = 'hexagon'
OCTAGON = 'octagon'
TRIANGLE = 'triangle'

SPRITE_RED = "red"
SPRITE_GREEN = "green"
SPRITE_BLUE = "blue"
SPRITE_YELLOW = "yellow"
SPRITE_TAN = "tan"
SPRITE_GREY = "grey"
SPRITE_TEAL = "teal"

ALLCOLORS = (SPRITE_RED, SPRITE_GREEN, SPRITE_BLUE, SPRITE_YELLOW, SPRITE_TAN, SPRITE_GREY, SPRITE_TEAL)
ALLSHAPES = (DIAMOND, HEXAGON, OCTAGON, SQUARE, TRIANGLE)

def level_up():
    """This function add one row and one column everytime user reach next level in order to increase difficulty"""
    global BOARDWIDTH, BOARDHEIGHT
    BOARDWIDTH += 1
    BOARDHEIGHT += 1

def background_music():
    """Adding background music"""
    pygame.mixer.init()
    pygame.mixer.music.load('background_music.mp3')
    pygame.mixer.music.play(loops=-1)
    pygame.mixer.music.set_volume(0.05)

def draw_diamond_sprite(color, left, top, width, height):
    """This function instantiate a gem object using asset path and passing colours.
     It also scale the image to match the height and width of the rectangle in game window.
     By using draw function, it draws the shape in game display window"""
    diamond_image = DIAMOND_ASSETPATH[color] or None
    diamond_image = pygame.transform.scale(pygame.image.load(diamond_image).convert_alpha(), (width, height))
    diamond = Gem((left, top), diamond_image)
    diamond.draw(DISPLAYSURF)

def draw_hexagon_sprite(color, left, top, width, height):
    hexagon_image = HEXAGON_ASSETPATH[color] or None
    hexagon_image = pygame.transform.scale(pygame.image.load(hexagon_image).convert_alpha(), (width, height))
    hexagon = Gem((left, top), hexagon_image)
    hexagon.draw(DISPLAYSURF)

def draw_octagon_sprite(color, left, top, width, height):
    octagon_image = OCTAGON_ASSETPATH[color] or None
    octagon_image = pygame.transform.scale(pygame.image.load(octagon_image).convert_alpha(), (width, height))
    octagon = Gem((left, top), octagon_image)
    octagon.draw(DISPLAYSURF)

def draw_square_sprite(color, left, top, width, height):
    square_image = SQUARE_ASSETPATH[color] or None
    square_image = pygame.transform.scale(pygame.image.load(square_image).convert_alpha(), (width, height))
    square = Gem((left, top), square_image)
    square.draw(DISPLAYSURF)

def draw_triangle_sprite(color, left, top, width, height):
    triangle_image = TRIANGLE_ASSETPATH[color] or None
    triangle_image = pygame.transform.scale(pygame.image.load(triangle_image).convert_alpha(), (width, height))
    triangle = Gem((left, top), triangle_image)
    triangle.draw(DISPLAYSURF)

class Gem(pygame.sprite.Sprite):
    """It is a python sprite class which takes position and image as argument,
    it takes the image and place it in right position"""
    def __init__(self, pos, image):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect(center=pos)

    def draw(self, screen):
        """it uses blit method in order to draw object in game window
        screen argument is represented by DISPLAYSURF which is pygame main window"""
        screen.blit(self.image, self.rect)

def text_objects(text, font):
    """ Font.render()  is used to create an image (Surface) of the text, then blit this image onto the Surface"""
    text_surface = font.render(text, True, (0, 0, 0))
    return text_surface, text_surface.get_rect()

def button(msg, x, y, w, h, ic, ac, action=None):
    """msg = str(text for the button), w=width, h=height,ic=inactive_colour,
    ac=active colour, action will execute if the button is clicked  """
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    print(click)
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(DISPLAYSURF, ac, (x, y, w, h))
        if click[0] == 1 and action is not None:
            action()
    else:
        pygame.draw.rect(DISPLAYSURF, ic, (x, y, w, h))

    small_text = pygame.font.SysFont("comicsansms", 20)
    text_surf, text_rect = text_objects(msg, small_text)
    text_rect.center = ((x + (w / 2)), (y + (h / 2)))
    DISPLAYSURF.blit(text_surf, text_rect)

def unpause():
    """It setting the game as unpause by setting GAME_PAUSED variable false"""
    global GAME_PAUSED
    GAME_PAUSED = False

def quit_game():
    """It quits pygame before exiting python"""
    pygame.quit()
    sys.exit()

def pause():
    """It checks if GAME_PAUSED variable is set to true.
    If it is true, it shows a pause menu onto the main window with the 'Resume' and 'Quit' button.
    if resume button is clicked then un_paused method is called, and if the quit button is clicked
    the game will automatically quit and then screen will be updated"""
    font = pygame.font.SysFont("Consolas", 32)
    while GAME_PAUSED:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pause_text = font.render("Game Paused", True, (255, 255, 255))
        pause_rect = pause_text.get_rect(center=(WINDOWWIDTH / 2, WINDOWHEIGHT / 2 - 210))
        print(pause_text.get_size())
        pause_surface = pygame.Surface((210, 145))
        pause_surface.fill((0, 0, 0))
        pause_surface.blit(pause_text, (0, 0))
        DISPLAYSURF.blit(pause_surface, pause_rect)
        button("Resume", WINDOWWIDTH / 2 - 35, WINDOWHEIGHT / 2 - 140, 100, 50, ROYALBLUE, GRAY, unpause)
        button("Quit", WINDOWWIDTH / 2 - 35, WINDOWHEIGHT / 2 - 190, 100, 50, ROYALBLUE, GRAY, quit_game)
        pygame.display.update()
        FPS_CLOCK.tick(FPS)

def game_events(mouse_clicked, mousex, mousey):
    """This function is called to get all the events.
    If quit event occurs the game quit and if escape key is pressed the game pause menu will appear"""
    global GAME_PAUSED
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            game_gui.main()
            sys.exit()
        if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:  # to display pause menu
            GAME_PAUSED = True
        elif event.type == pygame.MOUSEMOTION:
            mousex, mousey = event.pos
        elif event.type == pygame.MOUSEBUTTONUP:
            mousex, mousey = event.pos
            mouse_clicked = True
        pause()
    return mouse_clicked, mousex, mousey

def generate_revealed_boxes_data(val):
    """It takes a boolean val as argument and return a array of boolean values
    where true value indicates reveal box to show sprite under it and false value indicates cover up each box"""
    return [[val] * BOARDHEIGHT for _ in range(BOARDWIDTH)]

def get_randomized_board():
    """This function get all possible shapes in every possible colours in a list called icons and
    ir randomly shuffles the list items and makes two copy of each item of the list and shuffles again.
    Then two for loop is used to append all the items of icons list in the 2d list called board"""
    icons = []
    for color in ALLCOLORS:
        for shape in ALLSHAPES:
            icons.append((shape, color))
    random.shuffle(icons)
    num_icons_used = int(BOARDWIDTH * BOARDHEIGHT / 2)
    icons = icons[:num_icons_used] * 2
    random.shuffle(icons)

    board = []
    for _ in range(BOARDWIDTH):
        column = []
        for _ in range(BOARDHEIGHT):
            column.append(icons[0])
            del icons[0]
        board.append(column)
    # transposeBoard = [*zip(*board)] // might need later on
    return board

def split_into_groups_of(group_size, the_list):
    """It split the game board into a group of boxes
    (ex: it split 16 boxes into a four by four group of boxes and return the result as a list)"""
    return [the_list[i:i + group_size] for i in range(0, len(the_list), group_size)]

def left_top_coords_of_box(boxx, boxy):
    """It transform box coordinate into pixel coordinate to identify which box the user clicks at the time of playing"""
    left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
    top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
    return left, top

def get_box_at_pixel(x, y):
    """It takes in x and y which is pixel values and goes through boxx and boxy.
    It uses collidepoint function which return True if x and y coordinates are within the bounds of the rectangle.
    It return x and y coordinates of the box"""
    for boxx in range(BOARDWIDTH):
        for boxy in range(BOARDHEIGHT):
            left, top = left_top_coords_of_box(boxx, boxy)
            box_rect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)
            if box_rect.collidepoint(x, y):
                return boxx, boxy
    return None, None

def main():  # sourcery no-metrics skip: none-compare
    """All main functions are called to run the game"""
    global FPS_CLOCK, DISPLAYSURF, GAME_SCORE, GAME_LEVEL, GAME_PAUSED
    pygame.init()         # to initialize pygame
    background_music()    # to run background music
    FPS_CLOCK = pygame.time.Clock()   # in order to set general time for the game
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))    # to set the main window
    mousex = 0
    mousey = 0
    pygame.display.set_caption('Memory Game                                           Press Esc to se pause/exit menu')

    main_board = get_randomized_board()   # it randomize all the objects in the board
    revealed_boxes = generate_revealed_boxes_data(False)

    first_selection = None

    DISPLAYSURF.fill(BGCOLOR)
    start_game_animation(main_board)
    pygame.time.get_ticks()

    while True:
        mouse_clicked = False

        DISPLAYSURF.fill(BGCOLOR)
        draw_board(main_board, revealed_boxes)
        font = pygame.font.SysFont("", 32)

        game_score_string = "Score: " + str(GAME_SCORE) + "     Level: " + str(GAME_LEVEL)
        game_score_text = font.render(game_score_string, True, (255, 255, 255))
        game_score_rect = game_score_text.get_rect(center=(120, 10))

        mouse_clicked, mousex, mousey = game_events(mouse_clicked, mousex, mousey)
        DISPLAYSURF.fill((0, 0, 0), (0, 0, 250, 30))
        DISPLAYSURF.blit(game_score_text, game_score_rect)

        boxx, boxy = get_box_at_pixel(mousex, mousey)
        if boxx is not None and boxy is not None:
            if not revealed_boxes[boxx][boxy]:
                draw_highlight_box(boxx, boxy)
            if not revealed_boxes[boxx][boxy] and mouse_clicked:
                reveal_boxes_animation(main_board, [(boxx, boxy)])
                revealed_boxes[boxx][boxy] = [True]
                if first_selection is None:
                    first_selection = (boxx, boxy)
                else:
                    icon1shape, icon1color = get_shape_and_color(main_board, first_selection[0], first_selection[1])
                    icon2shape, icon2color = get_shape_and_color(main_board, boxx, boxy)
                    if icon1shape != icon2shape or icon1color != icon2color:
                        pygame.time.wait(1000)
                        cover_boxes_animation(main_board, [(first_selection[0], first_selection[1]), (boxx, boxy)])
                        revealed_boxes[first_selection[0]][first_selection[1]] = False
                        revealed_boxes[boxx][boxy] = False
                    elif has_won(revealed_boxes):
                        game_won_animation(main_board)
                        pygame.time.wait(2000)
                        level_up()
                        GAME_LEVEL += 1
                        main_board = get_randomized_board()
                        revealed_boxes = generate_revealed_boxes_data(False)

                        draw_board(main_board, revealed_boxes)

                        pygame.display.update()
                        pygame.time.wait(1000)
                        start_game_animation(main_board)

                    first_selection = None

        pygame.display.update()

        FPS_CLOCK.tick(FPS)

def draw_icon(shape, color, boxx, boxy):
    """This function is used to draw sprite that will displayed on gameboard.
     It takes four parameters to draw appropriate shapes with appropriate colours."""
    # quarter = int(BOXSIZE * 0.25) // Might need later on
    half = int(BOXSIZE * 0.5)

    left, top = left_top_coords_of_box(boxx, boxy)
    if shape == DIAMOND:
        draw_diamond_sprite(color, left + half, top + half, BOXSIZE, BOXSIZE)
    elif shape == HEXAGON:
        draw_hexagon_sprite(color, left + half, top + half, BOXSIZE, BOXSIZE)
    elif shape == OCTAGON:
        draw_octagon_sprite(color, left + half, top + half, BOXSIZE, BOXSIZE)
    elif shape == SQUARE:
        draw_square_sprite(color, left + half, top + half, BOXSIZE, BOXSIZE)
    elif shape == TRIANGLE:
        draw_triangle_sprite(color, left + half, top + half, BOXSIZE, BOXSIZE)

def get_shape_and_color(board, boxx, boxy):
    """It is used to identify shape and colour of a given box position using x and y coordinates of the box position"""
    return board[boxx][boxy][0], board[boxx][boxy][1]

def draw_box_covers(board, boxes, coverage):
    """This function is a frame drawing function for the board.
    It is called repeatedly and with each call all the boxes are given a different coverage amount
    which starts with a positive value and eventually getting to zero value and negative value"""
    # pauseDisplay = False //Might use later on
    for box in boxes:
        left, top = left_top_coords_of_box(box[0], box[1])
        pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE))
        shape, color = get_shape_and_color(board, box[0], box[1])
        draw_icon(shape, color, box[0], box[1])
        if coverage > 0:
            pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, coverage, BOXSIZE))
    pygame.display.update()
    FPS_CLOCK.tick(FPS)

def draw_board(board, revealed):
    """It takes in game board and revealed (a boolean) as parameter, where false means
    the box should be covered and true means the box should be revealed"""
    for boxx in range(BOARDWIDTH):
        for boxy in range(BOARDHEIGHT):
            left, top = left_top_coords_of_box(boxx, boxy)
            if not revealed[boxx][boxy]:
                pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))
            else:
                shape, color = get_shape_and_color(board, boxx, boxy)
                draw_icon(shape, color, boxx, boxy)

def draw_highlight_box(boxx, boxy):
    """This function is used to highlight the boxes by blue background
     to make the application more responsive for users"""
    left, top = left_top_coords_of_box(boxx, boxy)
    pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left - 5, top - 5, BOXSIZE + 10, BOXSIZE + 10), 4)

def reveal_boxes_animation(board, boxes_to_reveal):
    """It takes game board and list of boxes as parameter and in order to do reveal boxes animation,
    it repeatedly call draw_box_cover function.
    Here the positive coverage value indicates that the box should be fully or partially covered
    and A negative or zero value indicates  the box should be revealed"""
    for coverage in range(BOXSIZE, (-REVEALSPEED) - 1, -REVEALSPEED):
        print(coverage)
        if coverage < 0:
            pygame.time.wait(1000)
        draw_box_covers(board, boxes_to_reveal, coverage)

def cover_boxes_animation(board, boxes_to_cover):
    """It is the inverse of reveal_boxes_animation where coverage
    starts with a positive number and goes toward a negative number"""
    for coverage in range(0, BOXSIZE + REVEALSPEED, REVEALSPEED):
        draw_box_covers(board, boxes_to_cover, coverage)

def start_game_animation(board):
    """This function generate a list of boxes, shuffles them and split them into a group of boxes
    and hold it into box_group variable. Next it call draw_board function to draw the board and for box_group,
    reveal_boxes_animation and cover_boxes_animation functions are called to reveal the boxes for one second"""
    covered_boxes = generate_revealed_boxes_data(False)
    boxes = []
    for x in range(BOARDWIDTH):
        for y in range(BOARDHEIGHT):
            boxes.append((x, y))
    random.shuffle(boxes)
    box_groups = split_into_groups_of(BOARDWIDTH * BOARDHEIGHT, boxes)

    draw_board(board, covered_boxes)
    for boxGroup in box_groups:
        reveal_boxes_animation(board, boxGroup)
        cover_boxes_animation(board, boxGroup)

def game_won_animation(board):
    """This function is called in main function when it is detected that the game has a winning condition.
    A for loop is used to create end game animation, draw a new game board a level higher, updates window and
    wait 300 milli_seconds before exiting the function"""
    covered_boxes = generate_revealed_boxes_data(True)
    color1 = LIGHTBGCOLOR
    color2 = BGCOLOR

    for _ in range(13):
        color1, color2 = color2, color1
        DISPLAYSURF.fill(color1)
        draw_board(board, covered_boxes)
        pygame.display.update()
        pygame.time.wait(300)

def has_won(revealed_boxes):
    """It is called everytime a matching pair of boxes is found. It increase the game score by 10 everytime
    and goes through revealed_boxes list to check if there is a winning condition"""
    global GAME_SCORE
    GAME_SCORE += 10
    for i in revealed_boxes:
        return False not in i

if __name__ == '__main__':
    main()


number = int(input('Insira o numero que deseja converter: '))
opcao = int(input('------Escolha uma opção para conversao:----------\n 1. Para converter para Hexadecimal: \n 2. Para converter para Octal: \n 3. Para converter para Binário: \n '))

hexa = hex(number)
octa = oct(number)
bina = bin(number)

if opcao == 1:
    print(hexa)
elif opcao == 2:
    print (octa)
elif opcao == 3:
    print (bina)
else:
    print("Opção não reconhecida, favor escolher uma válida")


#t = [30,40,50,60]
#t = [73,74,75,71,69,72,76,73]
t = [30,60,90]
Output: [1,1,1,0]
def lis(t):
    l = []
    for i in range(0,len(t)-1):
        c = 0
        cond = False
        for j in range(i+1,len(t)):
            c+=1
            if t[j]>t[i]:
                l.append(c)
                cond = True
                break
        if not (cond):
            l.append(0)

    print(l)
lis(t)
def fun(temp):
    st = []
    res = [0]*len(temp)
    for i,t in enumerate(temp):
        while st and t>st[-1][1]:
            sti,stt = st.pop()
            res[sti] = i - sti
        st.append([i,t])
    return res
temp = [73,74,75,71,69,72,76,73]
print(fun(temp))


import json
import boto3

#遍历所有EC2 Instance，返回instance_id
def ec2():
    ec2instance = boto3.resource('ec2').instances.all()
    ec2_list = []
    for i in ec2instance:
        ec2_list.append(i.instance_id)
    print ("There are " + str(len(ec2_list)) + " EC2 instances")
    return ec2_list

#遍历所有RDS Instance，返回DBInstanceIdentifier
def rds():
    rdsinstance = boto3.client("rds").describe_db_instances()
    print ("There are " + str(len(list(rdsinstance))-1) + " databases")
    for i in range (0, len(list(rdsinstance))):
        print ("DB instance " + str(i) , end=" ")
        if (list(rdsinstance)[i] == "DBInstances"):
            print ("is " + rdsinstance["DBInstances"][i]["Engine"] + ", " + rdsinstance["DBInstances"][i]["DBInstanceIdentifier"] + ", " + rdsinstance["DBInstances"][i]["DBInstanceArn"])
    return True


import numpy as np
import pytest
from cirq import Circuit, LineQubit, ops, testing

from qbraid.interface import circuits_allclose
from qbraid.transpiler.cirq_pytket.conversions import to_pytket
from qbraid.transpiler.exceptions import CircuitConversionError

def test_bell_state_to_pytket():
    """Tests Circuit --> pytket.circuit.Circuit --> Circuit
    with a Bell state circuit.
    """
    qreg = LineQubit.range(2)
    cirq_circuit = Circuit([ops.H.on(qreg[0]), ops.CNOT.on(qreg[0], qreg[1])])
    pytket_circuit = to_pytket(cirq_circuit)
    assert circuits_allclose(pytket_circuit, cirq_circuit, strict_gphase=True)

@pytest.mark.parametrize("num_qubits", [1, 2, 3, 4, 5])
def test_random_circuit_to_pytket(num_qubits):
    for i in range(10):
        cirq_circuit = testing.random_circuit(
            qubits=num_qubits,
            n_moments=np.random.randint(1, 6),
            op_density=1,
            random_state=np.random.randint(1, 10),
        )
        pytket_circuit = to_pytket(cirq_circuit)
        assert circuits_allclose(pytket_circuit, cirq_circuit, strict_gphase=True)

def test_raise_error():
    with pytest.raises(CircuitConversionError):
        probs = np.random.uniform(low=0, high=0.5)
        cirq_circuit = Circuit(ops.PhaseDampingChannel(probs).on(*LineQubit.range(1)))
        to_pytket(cirq_circuit)