import os
import pathlib
import shutil
import sys
import zipfile
from PyQt5.QtWidgets import QMainWindow, QFileDialog

from check_db import *
from GUI.des import *
from GUI.archive import *

class Interface(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.reg)
        self.ui.pushButton_2.clicked.connect(self.auth)
        self.ui.pushButton_2.clicked.connect(self.show_main_window)
        self.ui.pushButton_2.clicked.connect(self.close)

        self.base_line_edit = [self.ui.lineEdit, self.ui.lineEdit_2]

        self.check_db = CheckThread()
        self.check_db.mysignal.connect(self.signal_handler)

    def show_main_window(self):
        self.w2 = MainWindow()
        self.w2.show()

    # Перевірка правильності введення
    def check_input(funct):
        def wrapper(self):
            for line_edit in self.base_line_edit:
                if len(line_edit.text()) == 0:
                    return
            funct(self)
        return wrapper

    # Обробник сигналів
    def signal_handler(self, value):
        QtWidgets.QMessageBox.about(self, 'Оповіщення', value)

    @check_input
    def auth(self):
        name = self.ui.lineEdit.text()
        passw = self.ui.lineEdit_2.text()
        self.check_db.thr_login(name, passw)

    @check_input
    def reg(self):
        name = self.ui.lineEdit.text()
        passw = self.ui.lineEdit_2.text()
        self.check_db.thr_register(name, passw)

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.show_main)
        self.ui.pushButton.clicked.connect(self.close)

        self.ui.toolButton.clicked.connect(self.addFiles)
        self.ui.pushButton_3.clicked.connect(self.openFile)

        self.ui.pushButton_2.clicked.connect(self.saveFile)

    def openFile(self):
        if os.path.exists("directory.zip"):
            os.remove("directory.zip")

        zipname, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.zip')

        with zipfile.ZipFile(zipname) as z:
            z.extractall("openZIP")

        for root, dirs, files in os.walk("openZIP"):
            for filename in files:
                self.ui.listWidget.addItem(filename)

    def show_main(self):
        self.w = Interface()
        self.w.show()

    def addFiles(self):
        if os.path.exists("directory.zip"):
            os.remove("directory.zip")

        fname=QFileDialog.getOpenFileName(self, 'Open file', 'D:\codefirst.io\PyQt5 tutorials\Browse Files', 'All (*.*)')
        shutil.copy(fname[0], "openZIP")
        self.ui.listWidget.addItem(fname[0])

    def saveFile(self):
        directory = pathlib.Path("openZIP/")
        with zipfile.ZipFile("directory.zip", mode="w") as archive:
            for file_path in directory.iterdir():
                archive.write(file_path, arcname=file_path.name)

        for f in os.listdir("openZIP"):
            os.remove(os.path.join("openZIP", f))
        self.ui.listWidget.clear()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    app.setWindowIcon(QtGui.QIcon('archiverIcon.png'))
    mywin = Interface()
    mywin.show()
    sys.exit(app.exec_())


import requests
from bs4 import BeautifulSoup
import json

url = "https://www.melon.com/chart/index.htm"
headers = {
    'Referer': 'https://www.melon.com/',
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
html = requests.get(url, headers = headers).text
soup = BeautifulSoup(html, 'html.parser')

urlj = "https://www.melon.com/commonlike/getSongLike.json"
parameter = []

rank_50 = soup.select("table > tbody #lst50")
rank_100 = soup.select("table > tbody #lst100")

for i in rank_50:
    a = i.attrs['data-song-no']
    parameter.append(a)

for j in rank_100:
    b = j.attrs['data-song-no']
    parameter.append(b)

param_ = ",".join(parameter)

params = {
    "contsIds" : str(param_)
}

headersj = {
    "Referer": "https://www.melon.com/chart/index.htm",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
}

htmlj = requests.get(urlj, params = params, headers = headersj).text
jsonData = json.loads(htmlj, encoding='utf-8')

def melon(rank):

    trs = rank
    song_info = {}
    for tr in trs:
        t = tr.select('div.ellipsis.rank01 a')
        t1 = t[0].text
        songno = tr.get('data-song-no')
        s = tr.select('div.ellipsis.rank02 span a')
        s1 = s[0].text
        if len(s) >= 2:
                s1 = []
                for j in s:
                    s1.append(j.text)
                s1 = ",".join(s1)
        aaaa = {"song_id" : songno, "title" : t1, "singer" :s1}
        song_info[songno] = aaaa

    song_id = []
    for j in jsonData['contsLike']:
        song_id = str(j['CONTSID'])
        x = song_info.get(song_id)
        if x == None:
            continue
        x['LIKE'] = j['SUMMCNT']
        print(x)

melon(rank_50)
melon(rank_100)


from flask import Flask, request, jsonify
from flask_cors import CORS
from process import main

app = Flask(__name__)

CORS(app)

@app.route('/api', methods=["POST"])
def process_data():
    data = request.json
    fresult = process_function(data)
    return jsonify(fresult)

def process_function(fdata):
    result = main(fdata)
    formattedresult = {'identified_disease': result}

    return formattedresult

if __name__ == '__main__':
    app.run(port=5000)


import numpy as np
import matplotlib.pyplot as plt
def drawMoons(names, xpositions, xlim=[-500,500], labels=False, color=False):
    '''
    Draw a plot of the positions of moons relative to Jupiter.

    This function requires two input arguments. They should
    both be lists, and they should be the same size as each
    other. They are:

        moons -- a 1-dimensional list of moon names
        xpositions -- a 1-dimensional list of moon positions (in arcsec)

    For example:

        %matplotlib inline
        names = ['Io', 'Europa', 'Ganymede', 'Callisto']
        xpositions = [-20, 40, 80, -160]
        drawMoons(names, xpositions)

        (should display a plot of the moon positions)

    Options keyword arguments

        xlim = [-500,500]
            (set this to some other 2-element list to change
                the range over which the plot stretchs)
        labels = False
            (set this to True to provide text labels)
        color = False
            (set this to True to provide different colors for each moon)

    '''

    # since we're plotting only 1D positions, we make up y-values
    ypositions = np.zeros_like(xpositions)

    # we create a new figure, and set its size
    plt.figure(figsize=(10,.25))

    # if color output, set colors
    if color:
        colors=['orange','blue','magenta','green']
    else:
        colors=['black']*len(xpositions)

    # we plot the moons in their positions
    for i in range(len(xpositions)):
        plt.plot(xpositions[i], ypositions[i],
                    marker = '.',
                    linewidth=0,
                    color=colors[i])

    # if desired, we add text labels to all the moons
    if labels:
        for x, y, n in zip(xpositions, ypositions, names):
            plt.text(x, y+0.1, n, ha='center', va='bottom')

    # plot Jupiter in the center
    plt.plot(0,0, marker='o', markersize=10, color='black')

    # set the x and y limits of the plot
    plt.xlim(*xlim)
    plt.ylim(-1,1)

    # turn off all axis labels (and the box around the plot)
    plt.axis('off')

    # make sure the plot shows to the screen
    plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 28 14:41:23 2019

@author: shaun
"""

def centroid(region, img):
    """ Takes input in terms of coordinates of region
    and returns its centroid"""
    x_centre = 0
    y_centre = 0
    elements = 0
    for i in region:
        x_centre += i[0]*img[i[0], i[1]]
        y_centre += i[1]*img[i[0], i[1]]
        elements += 1*img[i[0], i[1]]
    return [x_centre/elements, y_centre/elements]

def getRegion(j, i, region, img):
    """Recursively adds all pixels above threshold to the array named region
    Takes starting point coordinates as input"""
    #checks if current seed is edge one or not
    edge = j==img.shape[0] or i==img.shape[1] or j==-1*img.shape[0] or i==-1*img.shape[1]
    if(len(region) > 150 or edge):
        return
    if(img[j, i] <= thresh):
        return region
    else:
        img[j, i] = 0 #setting it to 0 so it is not counted again
        region.append([j, i])
        if edge:
            return region
        else:
            getRegion(j, i-1, region, img)
            getRegion(j, i+1, region, img)
            getRegion(j+1, i, region, img)
            getRegion(j-1, i, region, img)

def rga(j, i, img, img1):
    """This implements the region growing algorithm"""
    region = []
    getRegion(j, i, region, img) #once whole region is identified, it is assigned
    if(len(region) > 149):
        return
    return centroid(region, img1)

import cv2
import numpy as np
import matplotlib.pyplot as plt
import time
import math

n = 3 #Every nth pixel is checked
centroids = []
# Reading the images as arrays
img = np.array(cv2.imread("Image 1.jpg", 0))
img1 = img.copy()
thresh = 45 #arbitrarily set threshold value for intensity value

start = time.time()
xlen = img.shape[1] #length of image in x
ylen = img.shape[0] #length of image in y
for i in range(xlen//n):
    for j in range(ylen//n):
        if img[n*j,n*i] > thresh: #checking for seeds in every nth pixel
            centroids.append(rga(n*j, n*i, img, img1))

end = time.time()
centroids = np.array(centroids) #converting into numpy array so it can be plotted
#print("Total time taken = " +str((end-start)*1000)+" ms")
#print("Number of stars = " +str(centroids.shape[0]))
centroids = np.array(sorted(centroids, key = lambda x:x[0])) #sorting by first element

#This part is solely done to get a pictorial representation of the data obtained
plt.rcParams['axes.facecolor'] = 'black'
#plt.xlim(0,640)
#plt.ylim(0,480)
#plt.axis('off');
x = []
y = []
for i in centroids:
    x.append(i[1])
    y.append((-1)*i[0]+480)
#plt.plot(x, y, 'w.', )

#Done for making image of centroids
image = np.zeros(img.shape, dtype = np.uint8)
for m in centroids:
    image[math.floor(m[0]), math.floor(m[1])] = 255
cv2.imwrite('gen4_result.jpg', image)
cv2.waitKey(0)
cv2.destroyAllWindows()


import torch

def getRotationAngle(R):
    return torch.arccos((torch.trace(R) - 1 - 1e-5) / 2)

def hat(v, device):
    v = v.flatten()
    R = torch.tensor([
        [0, -v[2], v[1]],
        [v[2], 0, -v[0]],
        [-v[1], v[0], 0]]).to(device)
    return R

def matExp(omega, device):
    I = torch.eye(3).to(device)

    angle = torch.linalg.norm(omega)
    # Near angle==0, use first order Taylor expansion
    if angle < 1e-10:
        return I + hat(omega, device)

    axis = omega / angle
    s = torch.sin(angle)
    c = torch.cos(angle)
    return c * I + (1 - c) * torch.outer(axis, axis) + s * hat(axis, device)


# -*- coding: utf-8 -*-
import base64
import logging
import base64
import xlwt
from io import BytesIO
try:
    from BytesIO import BytesIO
except ImportError:
    from io import BytesIO
import zipfile
from datetime import datetime
from odoo import http, exceptions
from odoo.http import request
from odoo.http import content_disposition
import ast
_logger = logging.getLogger(__name__)
import time
# 获取时间戳
def t_stamp():
    t = time.time()
    t_stamp = int(t)
    print('当前时间戳:', t_stamp)
    return t_stamp

class Binary(http.Controller):

    @http.route('/web/attachment/download_document', type='http', auth="public")
    def download_document(self, att_ids, **kw):
        new_tab = ast.literal_eval(att_ids)
        attachment_ids = request.env['ir.attachment'].sudo().search([('id', 'in', tuple(new_tab))])
        file_dict = {}
        for attachment_id in attachment_ids:
            file_store = attachment_id.store_fname
            if file_store:
                file_name = attachment_id.name
                file_path = attachment_id._full_path(file_store)
                file_dict["%s:%s" % (file_store, file_name)] = dict(path=file_path, name=file_name)
        print ('---------file_dict',file_dict)
        zip_filename = datetime.now()
        zip_filename = "%s.zip" % zip_filename
        bitIO = BytesIO()
        zip_file = zipfile.ZipFile(bitIO, "w", zipfile.ZIP_DEFLATED)
        for file_info in file_dict.values():
            zip_file.write(file_info["path"], file_info["name"])
        print ('zip_file----',zip_file)
        zip_file.close()
        return request.make_response(bitIO.getvalue(),
                                     headers=[('Content-Type', 'application/x-zip-compressed'),
                                              ('Content-Disposition', content_disposition(zip_filename))])

    def generate_excel(self, task_ids):
        workbook = xlwt.Workbook(encoding='utf-8')
        worksheet = workbook.add_sheet('任务清单')
        style = xlwt.XFStyle()  # 初始化样式
        font = xlwt.Font()  # 为样式创建字体
        font.name = '宋体'  # 字体
        font.bold = True  # 加粗
        font.height = 20 * 10  # 字体大小
        style.font = font  # 为样式设置字体

        # 添加列的标题
        header = ['姓名', '性别', '年龄']
        for col in range(len(header)):
            worksheet.write(0, col, header[col], style)
        row = 1
        for line in task_ids:
            worksheet.write(row, 0, line.name if line.name else '')
            worksheet.write(row, 1, line.sex if line.sex else '')
            worksheet.write(row, 2, line.age if line.age else '')
            row = row + 1
            # 保存
        buffer = BytesIO()
        workbook.save(buffer)
        return base64.encodebytes(buffer.getvalue())

    @http.route('/web/excel/download', type='http', auth="public",csrf=False)
    def download_excel(self, task_ids, **kw):
        file_dict = {}
        task_ids = ast.literal_eval(task_ids)
        task_ids=request.env['demo.user'].browse(task_ids)
        stream = BytesIO()
        try:
            with zipfile.ZipFile(stream, 'w') as doc_zip:
                i=1
                for task in task_ids:
                   doc_zip.writestr('test_%s.xls'%str(i), base64.b64decode(self.generate_excel(task)),
                                     compress_type=zipfile.ZIP_DEFLATED)
                   i+=1
        except zipfile.BadZipfile:
            _logger.exception("BadZipfile exception")
        content = stream.getvalue()
        headers = [
            ('Content-Type', 'zip'),
            ('X-Content-Type-Options', 'nosniff'),
            ('Content-Length', len(content)),
            ('Content-Disposition', content_disposition('Demo—20220608.zip'))
        ]
        return request.make_response(content, headers)


import pygame
import random

class Button:
    global mass
    def __init__(self, path, text, x, y):
        self.im = pygame.image.load(path)
        self.path = path
        self.text = text
        self.x = x
        self.y = y
        ger1 = self.im.get_rect(
        bottomright=(x, y))
        screen.blit(self.im, ger1)

class Button1(Button):
    def izobr(self):
        self.im = pygame.image.load(self.path)
        ger1 = self.im.get_rect(
        bottomright=(self.x, self.y))
        screen.blit(self.im, ger1)
    def delete(self):
        self.im = pygame.image.load("pr1.png")
        self.path = "pr1.png"
        ger1 = self.im.get_rect(
        bottomright=(self.x, self.y))
        screen.blit(self.im, ger1)

def igra(screen, s, n):
    global r, r1, r2, r3
    k = []
    k1 = []
    for i in range(37):
        k1.append(list(s[i]))
    for i in range(1, 36):
        for j in range(1, 36):
            x1 = []
            x1.append(s[i][j - 1])
            x1.append(s[i - 1][j])
            x1.append(s[i + 1][j])
            x1.append(s[i][j + 1])
            x1.append(s[i - 1][j + 1])
            x1.append(s[i + 1][j + 1])
            x1.append(s[i - 1][j - 1])
            x1.append(s[i + 1][j - 1])
            d = x1.count(n)
            d1 = x1.count(0)
            if (d1 == 5 or d1 == 6) and s[i][j] == n:
                k.append([i - 1, j - 1])
                k1[i][j] = n
            elif d >= 3 and s[i][j] != n:
                i1, j1 = i - 1, j - 1
                if s[i][j] == 1:
                    del r[r.index([i1, j1])]
                if s[i][j] == 2:
                    del r1[r1.index([i1, j1])]
                if s[i][j] == 3:
                    del r2[r2.index([i1, j1])]
                if s[i][j] == 4:
                    del r3[r3.index([i1, j1])]
                k.append([i - 1, j - 1])
                k1[i][j] = n
            elif s[i][j] == n:
                k1[i][j] = 0
    return k, k1

class Board:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.board = [[0] * width for _ in range(height)]
        self.left = 10
        self.k = 1
        self.top = 10
        self.s2 = []
        for i in range(height):
            self.s2.append([])
            for j in range(width):
                self.s2[i].append([])
        self.cell_size = 30

    def set_view(self, left, top, cell_size):
        self.left = left
        self.top = top
        self.cell_size = cell_size

    def render(self, screen):
        s = self.left
        s1 = self.top
        m = self.cell_size
        y = self.width
        y1 = self.height
        for i in range(y1):
            for j in range(y):
                pygame.draw.rect(screen, (255, 255, 255), (s, s1, m, m), 1)
                if self.k == 1:
                    self.s2[i][j] = [s, s1]
                s = s + m
            s = self.left
            s1 = s1 + m
        self.k = 0

    def click(self, screen, x):
        m = self.cell_size
        for i in range(self.height):
            for j in range(self.width):
                a = self.s2[i][j][0]
                a1 = self.s2[i][j][0] + m
                b = self.s2[i][j][1]
                b1 = self.s2[i][j][1] + m
                if x[0] > a and x[0] < a1 and x[1] > b and \
                   x[1] < b1:
                       return i, j

class Life(Board):
    def life(self, screen, r, r1, r2, r3):
        for i in range(len(r)):
            m = self.cell_size
            s = r[i][1] * m + 1
            s1 = r[i][0] * m + 1
            pygame.draw.rect(screen, (0, 255, 0), (s, s1, m - 2, m - 2))
        for i in range(len(r1)):
            m = self.cell_size
            s = r1[i][1] * m + 1
            s1 = r1[i][0] * m + 1
            pygame.draw.rect(screen, (0, 255, 255), (s, s1, m - 2, m - 2))
        for i in range(len(r2)):
            m = self.cell_size
            s = r2[i][1] * m + 1
            s1 = r2[i][0] * m + 1
            pygame.draw.rect(screen, (255, 255, 0), (s, s1, m - 2, m - 2))
        for i in range(len(r3)):
            m = self.cell_size
            s = r3[i][1] * m + 1
            s1 = r3[i][0] * m + 1
            pygame.draw.rect(screen, (255, 0, 0), (s, s1, m - 2, m - 2))

    def start(self, screen, s, n):
        k, k1 = igra(screen, s, n)
        return k, k1

pygame.init()
pygame.display.set_caption('Жизнь')
size = width, height = 940, 800
screen = pygame.display.set_mode(size)
board = Life(35, 35)
board.set_view(0, 0, 20)
k = 0
font = pygame.font.Font(None, 30)
font1 = pygame.font.Font(None, 60)
k1 = 0
clock = pygame.time.Clock()
s = [[0] * 37 for _ in range(37)]
running = True
r = []
dd = 0
hh = 0
fps = 500
t = 1
dd1 = []
t1 = 1
r1 = []
r2 = []
mass = []
r3 = []
pomoch = 0
koef = 0
ggg = 0
spisok = [1, 2, 3, 4]
pygame.display.flip()
vyhod = 0
colser = 0
ss = "Начните игру"
stav1 = 0
pobeda = 0
stav2 = 0
cpec = 0
ser = [1, 1, 1, -1, -1, -1]
i21 = Button1('pr2.png', '', 820, 680)
i22 = Button1('pr2.png', '', 860, 680)
i23 = Button1('pr2.png', '', 900, 680)
i11 = Button1('pr.png', '', 820, 150)
i12 = Button1('pr.png', '', 860, 150)
i13 = Button1('pr.png', '', 900, 150)
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and k1 == 0:
            k = 1
            if (event.pos[0] < 900) and (event.pos[1] < 60) and (event.pos[0] + 171 > 900) and (event.pos[1] + 47 > 60) and ggg == 0 and pomoch != 1:
                ss = "Начните игру"
                pob = -1
                posx1 = random.randint(1, 31)
                posy1 = random.randint(1, 31)
                pov1 = random.randint(1, 2)
                posx2 = posx1
                posy2 = posy1
                while ((posx2 > posx1 - 4) and (posx2 < posx1 + 4)) or ((posy2 > posy1 - 4) and (posy2 < posy1 + 4)):
                    posx2 = random.randint(1, 31)
                    posy2 = random.randint(1, 31)
                pov2 = random.randint(1, 2)
                posx3 = posx1
                posy3 = posy1
                while ((posx3 > posx1 - 4) and (posx3 < posx1 + 4)) or ((posy3 > posy1 - 4) and (posy3 < posy1 + 4)) or \
                      ((posx3 > posx2 - 4) and (posx3 < posx2 + 4)) or ((posy3 > posy2 - 4) and (posy3 < posy2 + 4)):
                    posx3 = random.randint(1, 31)
                    posy3 = random.randint(1, 31)
                pov3 = random.randint(1, 2)
                posx4 = posx1
                posy4 = posy1
                while ((posx4 > posx1 - 4) and (posx4 < posx1 + 4)) or ((posy4 > posy1 - 4) and (posy4 < posy1 + 4)) or \
                      ((posx4 > posx2 - 4) and (posx4 < posx2 + 4)) or ((posy4 > posy2 - 4) and (posy4 < posy2 + 4)) or \
                      ((posx4 > posx3 - 4) and (posx4 < posx3 + 4)) or ((posy4 > posy3 - 4) and (posy4 < posy3 + 4)):
                    posx4 = random.randint(1, 31)
                    posy4 = random.randint(1, 31)
                pov4 = random.randint(1, 2)
                aa = (posx1, posy1)
                r.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 1
                if pov1 == 1:
                    for i in range(1, 4):
                        aa = (posx1 + i, posy1)
                        r.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 1
                else:
                    for i in range(1, 4):
                        aa = (posx1, posy1 + i)
                        r.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 1
                aa = (posx2, posy2)
                r1.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 2
                if pov2 == 1:
                    for i in range(1, 4):
                        aa = (posx2 + i, posy2)
                        r1.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 2
                else:
                    for i in range(1, 4):
                        aa = (posx2, posy2 + i)
                        r1.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 2
                aa = (posx3, posy3)
                r2.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 3
                if pov3 == 1:
                    for i in range(1, 4):
                        aa = (posx3 + i, posy3)
                        r2.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 3
                else:
                    for i in range(1, 4):
                        aa = (posx3, posy3 + i)
                        r2.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 3
                aa = (posx4, posy4)
                r3.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 4
                if pov4 == 1:
                    for i in range(1, 4):
                        aa = (posx4 + i, posy4)
                        r3.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 4
                else:
                    for i in range(1, 4):
                        aa = (posx4, posy4 + i)
                        r3.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 4
                ggg = 1
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and ggg == 1:
            if (event.pos[0] < 750) and (event.pos[1] < 250) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 250) and (stav1 == 0) and (pomoch != 1):
                stav1 = 1
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 250)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 250)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 250)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 250)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 250)
            if (event.pos[0] < 750) and (event.pos[1] < 350) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 350) and (stav1 == 0) and (pomoch != 1):
                stav1 = 2
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 350)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 350)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 350)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 350)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 350)
            if (event.pos[0] < 750) and (event.pos[1] < 450) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 450) and (stav1 == 0) and (pomoch != 1):
                stav1 = 3
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 450)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 450)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 450)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 450)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 450)
            if (event.pos[0] < 750) and (event.pos[1] < 550) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 550) and (stav1 == 0) and (pomoch != 1):
                stav1 = 4
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 550)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 550)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 550)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 550)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 550)
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if (event.pos[0] < 370) and (event.pos[1] < 760) and (event.pos[0] + 171 > 370) and (event.pos[1] + 47 > 760) and pomoch != 1:
                vyhod = 1
            if (event.pos[0] < 180) and (event.pos[1] < 760) and (event.pos[0] + 171 > 180) and (event.pos[1] + 47 > 760):
                pomoch = 1
            if (event.pos[0] < 900) and (event.pos[1] < 760) and (event.pos[0] + 171 > 900) and (event.pos[1] + 47 > 760) and pomoch == 1:
                pomoch = 0
            if (event.pos[0] < 900) and (event.pos[1] < 760) and (event.pos[0] + 171 > 900) and (event.pos[1] + 47 > 760) and pobeda != 0:
                cpec = 0
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3 and k1 == 0 and k == 1:
            k1 += 1
        if event.type == pygame.KEYDOWN and k == 1 and k1 == 0:
            if event.key == pygame.K_SPACE and stav2 != 0:
                k1 += 1
                ss = "Идет игра..."
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 4 and k1 == 1:
            koef += 50
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 5 and k1 == 1:
            koef -= 50
    if pomoch != 1:
        screen.fill((10, 0, 0))
    if vyhod == 1:
        break
    if cpec == 0 and pobeda != 0:
        k1 = 0
        clock = pygame.time.Clock()
        s = [[0] * 37 for _ in range(37)]
        running = True
        r = []
        dd = 0
        hh = 0
        fps = 500
        t = 1
        dd1 = []
        t1 = 1
        r1 = []
        r2 = []
        mass = []
        r3 = []
        pomoch = 0
        koef = 0
        ggg = 0
        spisok = [1, 2, 3, 4]
        pygame.display.flip()
        vyhod = 0
        colser = 0
        ss = "Начните игру"
        stav1 = 0
        pobeda = 3
        stav2 = 0
        ser = [1, 1, 1, -1, -1, -1]
        i21 = Button1('pr2.png', '', 820, 680)
        i22 = Button1('pr2.png', '', 860, 680)
        i23 = Button1('pr2.png', '', 900, 680)
        i11 = Button1('pr.png', '', 820, 150)
        i12 = Button1('pr.png', '', 860, 150)
        i13 = Button1('pr.png', '', 900, 150)
        pobeda = 0
    if pobeda == 3 and cpec == 1:
        screen.fill((10, 0, 0))
        text = font1.render("Вы победили!", True, (255, 255, 255))
        screen.blit(text, [340, 380])
        i8 = Button('vyh.png', '', 900, 760)
        pygame.display.flip()
        continue
    if pobeda == 2 and cpec == 1:
        screen.fill((10, 0, 0))
        text = font1.render("Победа ИИ!", True, (255, 255, 255))
        screen.blit(text, [340, 380])
        i8 = Button('vyh.png', '', 900, 760)
        pygame.display.flip()
        continue
    if pomoch == 1:
        screen.fill((10, 0, 0))
        text = font.render("Правила игры", True, (255, 255, 255))
        text2 = font.render("Вы играете против ИИ. Сначала нажмите на кнопку random. Вам выпадет последователь-", True, (255, 255, 255))
        text3 = font.render("ность в которой вы должны будете выбрать цвет. За один цвет ставится одна жизнь.", True, (255, 255, 255))
        text4 = font.render("Нажмите на квадратик с цветом чтобы поставить (отменить нельзя) жизнь. После ход", True, (255, 255, 255))
        text5 = font.render("ИИ. Он ставит на любой другой цвет свою жизнь. Тот кто побеждает забирает жизни со-", True, (255, 255, 255))
        text6 = font.render("перника. Всего жизней три на каждого. Победит тот кто заберет все жизни себе.", True, (255, 255, 255))
        text7 = font.render("Если же никто из вас не победил, то жизни уходят обратно к вам. Мы уверяем вас в", True, (255, 255, 255))
        text8 = font.render("нашей честности, поэтому ИИ будет выбирать абсолютно рандомно, не зная до этого кто", True, (255, 255, 255))
        text9 = font.render("победит. Сердечки рядом с персонажем - это жизни. Нажмите на пробел чтобы начать", True, (255, 255, 255))
        text10 = font.render("Ваш персонаж - сверху, персонаж ИИ снизу. Желаем вам приятной игры!", True, (255, 255, 255))
        text11 = font.render("Просто стишок, для хорошего настроения ;)", True, (255, 255, 255))
        text12 = font.render("Если плох как математик,", True, (255, 255, 255))
        text13 = font.render("Это в общем не беда,", True, (255, 255, 255))
        text14 = font.render("Ведь хороший может физик", True, (255, 255, 255))
        text15 = font.render("Получиться из тебя!", True, (255, 255, 255))
        text16 = font.render("Если физик получился,", True, (255, 255, 255))
        text17 = font.render("Скажем прямо, неказист,", True, (255, 255, 255))
        text18 = font.render("Позже может получиться", True, (255, 255, 255))
        text19 = font.render("Очень классный программист!", True, (255, 255, 255))
        text20 = font.render("Программист хреновый вышел,", True, (255, 255, 255))
        text21 = font.render("Но остался шанс один,", True, (255, 255, 255))
        text22 = font.render("Что в конце концов отличный", True, (255, 255, 255))
        text23 = font.render("Из вас выйдет сисадмин!", True, (255, 255, 255))
        screen.blit(text, [10, 10])
        screen.blit(text2, [10, 40])
        screen.blit(text3, [10, 70])
        screen.blit(text4, [10, 100])
        screen.blit(text5, [10, 130])
        screen.blit(text6, [10, 160])
        screen.blit(text7, [10, 190])
        screen.blit(text8, [10, 220])
        screen.blit(text9, [10, 250])
        screen.blit(text10, [10, 280])
        screen.blit(text11, [10, 320])
        screen.blit(text12, [10, 350])
        screen.blit(text13, [10, 380])
        screen.blit(text14, [10, 410])
        screen.blit(text15, [10, 440])
        screen.blit(text16, [10, 480])
        screen.blit(text17, [10, 510])
        screen.blit(text18, [10, 540])
        screen.blit(text19, [10, 570])
        screen.blit(text20, [10, 610])
        screen.blit(text21, [10, 640])
        screen.blit(text22, [10, 670])
        screen.blit(text23, [10, 700])
        i8 = Button('vyh.png', '', 900, 760)
        pygame.display.flip()
        continue
    board.render(screen)
    Button('knop.png', '', 900, 60)
    i1 = Button('cv1.png', '', 750, 250)
    i2 = Button('cv2.png', '', 750, 350)
    i3 = Button('cv3.png', '', 750, 450)
    i4 = Button('cv4.png', '', 750, 550)
    Button('pom.png', '', 180, 760)
    Button('vyh.png', '', 370, 760)
    Button('12.png', '', 790, 200)
    i11.izobr()
    i12.izobr()
    i13.izobr()
    Button('mil.png', '', 770, 700)
    i21.izobr()
    i22.izobr()
    i23.izobr()
    if k == 1:
        board.life(screen, r, r1, r2, r3)
        if k1 == 1:
            random.shuffle(spisok)
            for i in spisok:
                if i == 1:
                    r, s = board.start(screen, s, 1)
                if i == 2:
                    r1, s = board.start(screen, s, 2)
                if i == 3:
                    r2, s = board.start(screen, s, 3)
                if i == 4:
                    r3, s = board.start(screen, s, 4)
            pygame.time.delay(fps + koef)
            if (r == []) and ('r' not in dd1):
                dd += 1
                dd1.append('r')
            if (r1 == []) and ('r1' not in dd1):
                dd += 1
                dd1.append('r1')
            if (r2 == []) and ('r2' not in dd1):
                dd += 1
                dd1.append('r2')
            if (r3 == []) and ('r3' not in dd1):
                dd += 1
                dd1.append('r3')
            if dd > 2:
                k1 = 3
        elif k1 == 2:
            k = 1
            koef = 0
            k1 = 0
            r1 = []
            dd = 0
            r = []
            k1 = 0
            ggg = 0
            r2 = []
            dd1 = []
            s = [[0] * 37 for _ in range(37)]
            r3 = []
            if pob == stav2:
                if ser.count(1) == 3:
                    ser[2] = -1
                    i23 = Button1('pr2.png', '', 900, 680)
                    i13 = Button1('pr.png', '', 900, 730)
                elif ser.count(1) == 2:
                    ser[1] = -1
                    i12 = Button1('pr.png', '', 860, 730)
                    i13 = Button1('pr.png', '', 900, 730)
                elif ser.count(1) == 1:
                    pobeda = 2
                    cpec = 1
                elif ser.count(1) == 4:
                    ser[3] = -1
                    i23 = Button1('pr2.png', '', 900, 680)
                    i22 = Button1('pr2.png', '', 860, 680)
                elif ser.count(1) == 5:
                    ser[4] = -1
                    i22 = Button1('pr2.png', '', 860, 680)
                    i21 = Button1('pr2.png', '', 820, 680)
            elif pob == stav1:
                if ser.count(1) == 3:
                    ser[3] = 1
                    i13 = Button1('pr.png', '', 900, 150)
                    i23 = Button1('pr2.png', '', 900, 200)
                elif ser.count(1) == 2:
                    ser[2] = 1
                    i12 = Button1('pr.png', '', 860, 150)
                    i13 = Button1('pr.png', '', 900, 150)
                elif ser.count(1) == 1:
                    ser[1] = 1
                    i11 = Button1('pr.png', '', 820, 150)
                    i12 = Button1('pr.png', '', 860, 150)
                elif ser.count(1) == 4:
                    ser[4] = 1
                    i23 = Button1('pr2.png', '', 900, 200)
                    i22 = Button1('pr2.png', '', 860, 200)
                elif ser.count(1) == 5:
                    pobeda = 3
                    cpec = 1
            else:
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 900, 150)
                    i23 = Button1('pr2.png', '', 900, 680)
                if ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 860, 150)
                    i13 = Button1('pr.png', '', 900, 730)
                if ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 150)
                    i12 = Button1('pr.png', '', 860, 730)
                if ser.count(1) == 4:
                    i22 = Button1('pr2.png', '', 860, 680)
                    i23 = Button1('pr2.png', '', 900, 200)
                if ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 860, 200)
                    i21 = Button1('pr2.png', '', 820, 680)
            stav1 = 0
            stav2 = 0
        elif k1 == 3:
            if 'r' not in dd1:
                pob = 4
                ss = 'Победили зеленые'
            if 'r1' not in dd1:
                pob = 2
                ss = 'Победили голубые'
            if 'r2' not in dd1:
                pob = 3
                ss = 'Победили желтые'
            if 'r3' not in dd1:
                pob = 1
                ss = 'Победили красные'
            k1 = 2
        if stav1 != 0 and stav2 == 0:
            ran = [1, 2, 3, 4]
            del ran[ran.index(stav1)]
            random.shuffle(ran)
            stav2 = ran[0]
            if stav2 == 1:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 250)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 250)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 250)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 250)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 250)
            if stav2 == 2:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 350)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 350)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 350)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 350)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 350)
            if stav2 == 3:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 450)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 450)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 450)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 450)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 450)
            if stav2 == 4:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 550)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 550)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 550)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 550)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 550)
    text23 = font.render(ss, True, (255, 255, 255))
    screen.blit(text23, [600, 730])
    clock.tick(fps)
    pygame.display.flip()


import numpy as np
import pandas as pd

def create_samples(data, ph, hist, day_len):
    """
    Create samples consisting in glucose, insulin and CHO (+ mets, heartrate, steps, CPB, AOB, IOB if needed)
    histories (past hist-length values)
    :param data: dataframe
    :param ph: prediction horizon in minutes in sampling frequency scale
    :param hist: history length in sampling frequency scale
    :param day_len: length of day in sampling frequency scale
    :return: dataframe of samples
    """
    n_samples = data.shape[0] - ph - hist + 1
    y = data.loc[ph + hist - 1:, "glucose"].values.reshape(-1, 1)
    d = pd.DatetimeIndex(data.loc[ph + hist - 1:, "datetime"].values)
    t = np.concatenate([np.arange(day_len) for _ in range(len(data) // day_len)], axis=0)[ph + hist - 1:].reshape(-1, 1)
    x = {}

    for feature in list(data.columns):
        if feature != "datetime":
            x[feature] = np.array([data.loc[i:i + n_samples - 1, feature] for i in range(hist)]).transpose()

    new_col_features = np.concatenate([[ele + "_" + str(i) for i in range(hist)] for ele in list(x.keys())], axis=None)
    new_columns = np.r_[["time"], new_col_features, ["y"]]

    data_features = np.c_[tuple(x.values())]
    data_full = np.c_[t, data_features, y]
    new_data = pd.DataFrame(data=np.c_[data_full], columns=new_columns)
    new_data["datetime"] = d
    new_data = new_data.loc[:, np.r_[["datetime"], new_columns]]  # reorder the columns, with datetime first

    return new_data

# hist_2 = hist //2
# m = np.array([data.loc[i + hist_2:i + hist_2 + n_samples - 1, "mets"] for i in range(hist_2)]).transpose()
# cal = np.array([data.loc[i + hist_2:i + hist_2 + n_samples - 1, "calories"] for i in range(hist_2)]).transpose()
# h = np.array([data.loc[i + hist_2:i + hist_2 + n_samples - 1, "heartrate"] for i in range(hist_2)]).transpose()
# new_columns = np.r_[["time"], ["glucose_" + str(i) for i in range(hist)], ["CHO_" + str(i) for i in range(hist)],
# ["insulin_" + str(i) for i in range(hist)], ["mets_" + str(i) for i in range(hist_2)],
# ["calories_" + str(i) for i in range(hist_2)], ["heartrate_" + str(i) for i in range(hist_2)], ["y"]]


"""Mixins for (API) views in the whole project."""

from bleach import clean
from rest_framework import generics, status
from rest_framework.response import Response

class CleanMixin():
    """Model mixin class which cleans inputs."""

    # Define a map of fields avaialble for import
    SAFE_FIELDS = {}

    def create(self, request, *args, **kwargs):
        """Override to clean data before processing it."""
        serializer = self.get_serializer(data=self.clean_data(request.data))
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        """Override to clean data before processing it."""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=self.clean_data(request.data), partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)

    def clean_data(self, data: dict) -> dict:
        """Clean / sanitize data.

        This uses mozillas bleach under the hood to disable certain html tags by
        encoding them - this leads to script tags etc. to not work.
        The results can be longer then the input; might make some character combinations
        `ugly`. Prevents XSS on the server-level.

        Args:
            data (dict): Data that should be sanatized.

        Returns:
            dict: Profided data sanatized; still in the same order.
        """
        clean_data = {}
        for k, v in data.items():
            if isinstance(v, str):
                ret = clean(v)
            elif isinstance(v, dict):
                ret = self.clean_data(v)
            else:
                ret = v
            clean_data[k] = ret
        return clean_data

class ListAPI(generics.ListAPIView):
    """View for list API."""

class ListCreateAPI(CleanMixin, generics.ListCreateAPIView):
    """View for list and create API."""

class CreateAPI(CleanMixin, generics.CreateAPIView):
    """View for create API."""

class RetrieveAPI(generics.RetrieveAPIView):
    """View for retreive API."""
    pass

class RetrieveUpdateAPI(CleanMixin, generics.RetrieveUpdateAPIView):
    """View for retrieve and update API."""
    pass

class RetrieveUpdateDestroyAPI(CleanMixin, generics.RetrieveUpdateDestroyAPIView):
    """View for retrieve, update and destroy API."""

class UpdateAPI(CleanMixin, generics.UpdateAPIView):
    """View for update API."""


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

from detectron2.config import CfgNode as CN

def add_swint_config(cfg):
    # SwinT backbone
    cfg.MODEL.SWINT = CN()
    cfg.MODEL.SWINT.EMBED_DIM = 192
    cfg.MODEL.SWINT.OUT_FEATURES = ["stage2", "stage3", "stage4", "stage5"]
    cfg.MODEL.SWINT.DEPTHS = [ 2, 2, 18, 2 ]
    cfg.MODEL.SWINT.NUM_HEADS = [ 6, 12, 24, 48 ]
    cfg.MODEL.SWINT.WINDOW_SIZE = 12
    cfg.MODEL.SWINT.MLP_RATIO = 4
    cfg.MODEL.SWINT.DROP_PATH_RATE = 0.2
    cfg.MODEL.SWINT.APE = False
    cfg.MODEL.BACKBONE.FREEZE_AT = -1

    # addation
    cfg.MODEL.FPN.TOP_LEVELS = 2
    cfg.SOLVER.OPTIMIZER = "AdamW"

    # RCNN
    cfg.DATASETS.TRAIN = (f"sartorius_train",)
    cfg.DATASETS.TEST = (f"sartorius_val",)
    cfg.INPUT.MIN_SIZE_TRAIN = (440, 480, 520, 560, 580, 620)
    cfg.MODEL.RPN.BATCH_SIZE_PER_IMAGE = 320
    cfg.MODEL.ROI_HEADS.NUM_CLASSES = 3
    cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
    cfg.TEST.DETECTIONS_PER_IMAGE = 1000
    cfg.INPUT.MASK_FORMAT='bitmask'

    cfg.MODEL.RPN.POST_NMS_TOPK_TRAIN = 3000
    cfg.MODEL.RPN.POST_NMS_TOPK_TEST = 3000

    cfg.MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS = [128,128,128]
    cfg.MODEL.ANCHOR_GENERATOR.SIZES = [13.235,13.235,13.235]

    cfg.DATALOADER.NUM_WORKERS = 2
    cfg.SOLVER.IMS_PER_BATCH = 2


from typing import List
import torch
from torch import nn
import numpy as np
from torchvision.models import resnet18

def get_resnet_18():
    model = resnet18()
    model.fc = nn.Linear(in_features=512,out_features=10,bias=True)
    return model

class EarlyStopping:
    def __init__(self, tolerance=5, min_delta=0):

        self.tolerance = tolerance
        self.min_delta = min_delta
        self.counter = 0
        self.early_stop = False

    def __call__(self, train_loss, validation_loss):
        if (validation_loss - train_loss) > self.min_delta:
            self.counter +=1
            if self.counter >= self.tolerance:
                self.early_stop = True

assignment/D22CS051 Lab Assignment 8/models.py


from tkinter import *
from tkinter import ttk
import tkinter.font as font

root = Tk()
root.title('Palindrome Generator')

f = font.Font(family='Roboto Condensed', size=18, weight='bold')
f2 = font.Font(family='Varela Round', size=15, weight='bold')

frame = LabelFrame(root, text='Frame Title', pady=30, padx=30)
frame.grid(row=0, column=0, padx=30, pady=30)

e = Entry(frame, width=30, bg='#f2f2f2', borderwidth=2, font=f)
e.grid(row=0, column=0)
e.get()
e.delete(0, END)

def palindrome():
    global label
    txt1 = e.get()
    txt2 = txt1[-2::-1]
    join_txt = f'{txt1}{txt2}'
    result.config(text=join_txt)
    e.delete(0, END)

result = Label(frame, text='', font=f, fg='red')
result.grid(row=1, column=0, columnspan=2, pady=10)

submit = Button(frame, text='Submit', font=f2, width=10, fg='#F6FF73', bg='#203140',
state=NORMAL, command=palindrome, relief='raise')
submit.grid(row=0, column=1)

root.mainloop()


"""
Pushes new music library data up into the cloud (i.e. the AppEngine
data store).  This causes the newly-added tracks to appear in the DJ
database and other chirpradio apps.

TODO(trow): Some of this is a bit hacky; it was put together quickly
to do the initial import.  It needs cleaning up before it can be put
into general use.
"""

import datetime
import re
import sys
import time
import urllib2

from chirp.common.printing import cprint
from chirp.common import timestamp
from chirp.common import conf
from chirp.library import album
from chirp.library import constants
from chirp.library import database
from chirp.library import order
from chirp.library import titles

from chirp.common import chirpradio
from google.appengine.ext import db
from djdb import models
from djdb import search

START_TIMESTAMP = 0
start_at_flag = "--start-at="
for arg in sys.argv:
    if arg.startswith(start_at_flag):
        arg = arg[len(start_at_flag):]
        START_TIMESTAMP = timestamp.parse_human_readable(arg)
        break

# TODO(trow): Is this optimal?
_NUM_ALBUMS_PER_FLUSH = 3

_DISC_NUM_RE = re.compile("disc\s+(\d+)", re.IGNORECASE)

_artist_cache = {}

DRY_RUN = False

class UnknownArtistError(Exception):
    pass

def get_artist_by_name(name):
    global _artist_cache
    if name in _artist_cache:
        return _artist_cache[name]
    while True:
        try:
            art = models.Artist.fetch_by_name(name)
            if art is None:
                raise UnknownArtistError("Unknown artist: %s" % name)
            _artist_cache[name] = art
            return art
        except urllib2.URLError:
            cprint("Retrying fetch_by_name for '%s'" % name)

def seen_album(album_id):
    while True:
        try:
            for alb in models.Album.all().filter("album_id =", album_id):
                if not alb.revoked:
                    return True
            return False
        except urllib2.URLError:
            cprint("Retrying fetch of album_id=%s" % album_id)

def process_one_album(idx, alb):
    # Build up an Album entity.
    kwargs = {}
    kwargs["parent"] = idx.transaction
    kwargs["title"] = alb.title()
    kwargs["album_id"] = alb.album_id
    kwargs["import_timestamp"] = datetime.datetime.utcfromtimestamp(
        alb.import_timestamp())
    kwargs["num_tracks"] = len(alb.all_au_files)
    kwargs["import_tags"] = alb.tags()

    if alb.is_compilation():
        kwargs["is_compilation"] = True
    else:
        kwargs["is_compilation"] = False
        kwargs["album_artist"] = get_artist_by_name(alb.artist_name())

    for key, val in sorted(kwargs.iteritems()):
        cprint("%s: %s" % (key, val))
    if seen_album(alb.album_id):
        cprint("   Skipping")
        return

    album = models.Album(**kwargs)

    # Look for a disc number in the tags.
    for tag in kwargs["import_tags"]:
        m = _DISC_NUM_RE.search(tag)
        if m:
            album.disc_number = int(m.group(1))
            break

    idx.add_album(album)

    for au_file in alb.all_au_files:
        track_title, import_tags = titles.split_tags(au_file.tit2())
        track_num, _ = order.decode(unicode(au_file.mutagen_id3["TRCK"]))
        kwargs = {}
        if alb.is_compilation():
            kwargs["track_artist"] = get_artist_by_name(au_file.tpe1())
        track = models.Track(
            parent=idx.transaction,
            ufid=au_file.ufid(),
            album=album,
            title=track_title,
            import_tags=import_tags,
            track_num=track_num,
            sampling_rate_hz=au_file.mp3_header.sampling_rate_hz,
            bit_rate_kbps=int(au_file.mp3_header.bit_rate_kbps),
            channels=au_file.mp3_header.channels_str,
            duration_ms=au_file.duration_ms,
            **kwargs)
        idx.add_track(track)

def flush(list_of_pending_albums):
    if not list_of_pending_albums:
        return
    if DRY_RUN:
        cprint("Dry run -- skipped flush")
        return
    idx = search.Indexer()
    for alb in list_of_pending_albums:
        process_one_album(idx, alb)
    # This runs as a batch job, so set a very long deadline.
    while True:
        try:
            rpc = db.create_rpc(deadline=120)
            idx.save(rpc=rpc)
            return
        except urllib2.URLError:
            cprint("Retrying indexer flush")

def maybe_flush(list_of_pending_albums):
    if len(list_of_pending_albums) < _NUM_ALBUMS_PER_FLUSH:
        return list_of_pending_albums
    flush(list_of_pending_albums)
    return []

def main():
    for _ in main_generator(START_TIMESTAMP):
        pass

def main_generator(start_timestamp):
    #chirpradio.connect("10.0.1.98:8000")
    chirpradio.connect()

    sql_db = database.Database(conf.LIBRARY_DB)
    pending_albums = []
    this_album = []
    # TODO(trow): Select the albums to import in a saner way.
    for vol, import_timestamp in sql_db.get_all_imports():
        if start_timestamp is not None and import_timestamp < start_timestamp:
            continue
        cprint("***")
        cprint("*** import_timestamp = %s" % timestamp.get_human_readable(
            import_timestamp))
        cprint("***")
        for au_file in sql_db.get_by_import(vol, import_timestamp):
            if this_album and this_album[0].album_id != au_file.album_id:
                alb = album.Album(this_album)
                pending_albums.append(alb)
                cprint('Adding "%s"' % alb.title())
                pending_albums = maybe_flush(pending_albums)
                this_album = []
            this_album.append(au_file)
            yield

    # Add the last album to the list of pending albums, then do the
    # final flush.
    if this_album:
        alb = album.Album(this_album)
        cprint('Adding "%s"' % alb.title())
        pending_albums.append(alb)
        this_album = []
    flush(pending_albums)

if __name__ == "__main__":
    main()


import copy

from django.db.models import Q

from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied, ValidationError

from oarndb.models import Family, AdultFamilyRelationship, ChildFamilyRelationship
from oarndb.models import Adult, Child, Person, Organization
from oarndb.models import RefAdultFamilyRelationshipType, RefChildFamilyRelationshipType
from oarndb.models import OrganizationFamilyLink, OrganizationPersonRole
from oarndb.models import FamilyEnrollment, PersonEnrollment, ServiceLevelEnrollment
from oarndb.models import RefRole, RefServiceLevel, RefProgram

class FilteredPersonSerializer(serializers.ListSerializer):
    """
    This is used in the NestedPersonSerializer, overriding the 'to-many' functionality
    of that serializer to be certain that no person the user lacks read access to
    are returned.
    """

    def to_representation(self, data):

        request = self.context.get('request', None)
        if request:
            data = data.filter(
                person__organization__in=Organization.objects.get_read_orgs(request.user)
            )
            return super(FilteredPersonSerializer, self).to_representation(data)
        else:
            raise ValidationError(detail="No request context was provided.")

class FilteredChildFamilyRelationshipSerializer(serializers.ListSerializer):
    """
    The FamilyListSerializer uses NestedChildFamilyRelationshipSerializer to describe
    the children linked to the family. It's necessary to override the 'to-many' functionality
    of that serializer to be certain that no children the user lacks read access to
    are returned.
    """

    def to_representation(self, data):

        request = self.context.get('request', None)
        if request:
            data = data.filter(
                child__person__organization__in=Organization.objects.get_read_orgs(request.user)
            )
            return super(FilteredChildFamilyRelationshipSerializer, self).to_representation(data)
        else:
            raise ValidationError(detail="No request context was provided.")

class FilteredAdultFamilyRelationshipSerializer(serializers.ListSerializer):
    """
    The FamilyListSerializer uses NestedAdultFamilyRelationshipSerializer to describe
    the adults linked to the family. It's necessary to override the 'to-many' functionality
    of that serializer to be certain that no adults the user lacks read access to
    are returned.
    """

    def to_representation(self, data):

        request = self.context.get('request', None)
        if request:
            data = data.filter(
                adult__person__organization__in=Organization.objects.get_read_orgs(request.user)
            )
            return super(FilteredAdultFamilyRelationshipSerializer, self).to_representation(data)
        else:
            raise ValidationError(detail="No request context was provided.")

class FilteredOrganizationSerializer(serializers.ListSerializer):
    """
    The FamilyListSerializer uses NestedOrganizationSerializer to describe the organizations
    the family is linked to. It's necessary to override the 'to-many' functionality of that
    serializer to be certain that no organizations the user lacks read access to are returned.
    """

    def to_representation(self, data):

        request = self.context.get('request', None)
        if request:
            data = data.filter(
                organization_id__in=Organization.objects.get_read_orgs(request.user)
            )
            return super(FilteredAdultFamilyRelationshipSerializer, self).to_representation(data)
        else:
            raise ValidationError(detail="No request context was provided.")

class FilteredAdultOrChildSerializer(serializers.ListSerializer):

    def to_representation(self, data):

        request = self.context.get('request', None)
        if request:
            data = data.filter(
                person__organization__in=Organization.objects.get_read_orgs(request.user)
            )
            return super(FilteredAdultFamilyRelationshipSerializer, self).to_representation(data)
        else:
            raise ValidationError(detail="No request context was provided.")

class FilteredRefRoleSerializer(serializers.ListSerializer):

    def to_representation(self, data):
        request = self.context.get('request', None)
        if request:
            data = data.filter(
                Q(universal=True) |
                Q(organization__in=Organization.objects.get_read_orgs(request.user))
            )
            return super(FilteredRefRoleSerializer, self).to_representation(data)
        else:
            raise ValidationError(detail="No request context was provided.")

class NestedRefRoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = RefRole

        list_serializer_class = FilteredRefRoleSerializer

        fields = (
            'ref_role_id',
            'description',
            'code',
            'sort_order'
        )

class NestedPersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person

        fields = (
            'person_id',
            'first_name',
            'last_name',
        )

class NestedChildSerializer(serializers.ModelSerializer):
    person = NestedPersonSerializer()

    class Meta:
        model = Child

        list_serializer_class = FilteredAdultOrChildSerializer

        fields = (
            'person',
        )

class NestedAdultSerializer(serializers.ModelSerializer):
    person = NestedPersonSerializer()

    class Meta:
        model = Adult

        list_serializer_class = FilteredAdultOrChildSerializer

        fields = (
            'person',
        )

class NestedChildFamilyRelationshipSerializer(serializers.ModelSerializer):
    """
    Allows the family views to present more information about linked children.
    Not used for updating.
    """

    child = NestedChildSerializer()

    class Meta:
        model = ChildFamilyRelationship

        list_serializer_class = FilteredChildFamilyRelationshipSerializer

        fields = (
            'child_family_relationship_id',
            'child',
            'family',
            'ref_child_family_relationship_type',
            'relationship_begin_date',
            'relationship_end_date',
            'notes'
        )

class NestedAdultFamilyRelationshipSerializer(serializers.ModelSerializer):
    """
    Allows the family views to present more information about linked adults.
    Not used for updating.
    """

    adult = NestedAdultSerializer()

    class Meta:
        model = AdultFamilyRelationship

        list_serializer_class = FilteredAdultFamilyRelationshipSerializer

        fields = (
            'adult_family_relationship_id',
            'adult',
            'family',
            'ref_adult_family_relationship_type',
            'primary_adult',
            'relationship_begin_date',
            'relationship_end_date',
            'notes'
        )

class NestedOrganizationSerializer(serializers.ModelSerializer):
    """
    Allows the family views to present more information about linked organizations.
    Not used for updating.
    """
    class Meta:
        model = Organization

        fields = (
            'organization_id',
            'name',
            'short_name'
        )

class NestedOrganizationPersonRoleSerializer(serializers.ModelSerializer):
    """
    The link between a Person and an Organization, defined by a Role.
    This nested version lacks a `person` FK, since that will be supplied by the
    parent Person serializer.
    """

    ref_role = NestedRefRoleSerializer()

    class Meta:
        model = OrganizationPersonRole

        fields = (
            'organization_person_role_id',
            'organization',
            'ref_role',
            'entry_date',
            'exit_date',
            'created_by',
            'created_at',
            'modified_at',
            'modified_by'
        )

class NestedPersonEnrollmentSerializer(serializers.ModelSerializer):

    person = NestedPersonSerializer()

    class Meta:
        model = PersonEnrollment

        fields = (
            'person_enrollment_id',
            'person',
            'family_enrollment',
            'open_date',
            'close_date'
        )

class NestedRefProgramSerializer(serializers.ModelSerializer):

    class Meta:
        model = RefProgram

        fields = (
            'ref_program_id',
            'code',
            'description',
            'sort_order',
            'universal',
            'organization',
            'definition',
            'is_oarn_program'
        )

class NestedRefServiceLevelSerializer(serializers.ModelSerializer):

    ref_program = NestedRefProgramSerializer()

    class Meta:
        model = RefServiceLevel

        fields = (
            'ref_service_level_id',
            'ref_program',
            'code',
            'description',
            'sort_order',
            'definition'
        )

class NestedServiceLevelEnrollmentSerializer(serializers.ModelSerializer):

    ref_service_level = NestedRefServiceLevelSerializer()

    class Meta:
        model = ServiceLevelEnrollment

        fields = (
            'service_level_enrollment_id',
            'family_enrollment',
            'ref_service_level',
            'open_date',
            'close_date'
        )


# 12
# x1,y1,z1,i1 - координаты точек начала и конца вектора №1 (аналогично для второго вектора)

import math

class Vector:
	# ИНИЦИАЛИЗАЦИЯ ПЕРВОГО ВЕКТОРА
	def plus(self, x1,y1,z1,i1,x2,y2,z2,i2):
		self.X1 = z1 - x1
		self.Y1 = i1 - y1
		self.X2 = z2 - x2
		self.Y2 = i2 - y2

		print("Результирующий вектор:", '{', self.X1 + self.X2, self.Y1 + self.Y2, '}')

	def umnozhenie_na_chislo(self,x1,y1,z1,i1, k):
		self.X1 = z1 - x1
		self.Y1 = i1 - y1
		print('Вектор после умножения на число:','{',self.X1 * k, self.Y1 *k, '}')

	def dlina(self, x1,y1,z1,i1):
		self.X1 = z1 - x1
		self.Y1 = i1 - y1
		print('Длина вектора:', math.sqrt(self.X1 ^ 2 + self.Y1 ^ 2))

	def skalyarnoe_p(self, x1,y1,z1,i1,x2,y2,z2,i2):
		self.X1 = z1 - x1
		self.Y1 = i1 - y1
		self.X2 = z2 - x2
		self.Y2 = i2 - y2
		print('Скалярное произведение векторов:', self.X1*self.X2 + self.Y1*self.Y2)

	def print(self, x1,y1,z1,i1):
		self.X1 = z1 - x1
		self.Y1 = i1 - y1
		print('Координаты вектора:', self.X1, self.Y1)

vector = Vector()

vector.plus(1,2,3,4,1,3,4,5)
vector.umnozhenie_na_chislo(1,2,3,4,10)
vector.dlina(1,2,3,4)
vector.skalyarnoe_p(1,2,3,4,1,3,4,5)

vector.print(1,2,3,4)


# Advent of Code day 12, part 2, Hot Springs.
# https://adventofcode.com/2023/day/12

from icecream import ic
import functools

# From, https://medium.com/@nkhaja/memoization-and-decorators-with-python-32f607439f84
def memoize(func):
    cache = func.cache = {}
    @functools.wraps(func)
    def memoized_func(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = func(*args, **kwargs)
        return cache[key]
    return memoized_func

@memoize
def solution(condition_records: list, groups: list, banked_springs: int) -> int:

    # Success!
    if len(condition_records) == 0 and len(groups) == 0 and banked_springs == 0:
        return 1

    # Basic failure.
    if len(condition_records) == 0:
        return 0

    new_condition_records = condition_records.copy()
    front_condition = new_condition_records.pop(0)

    if front_condition == '#':
        return solution(new_condition_records, groups, banked_springs + 1)

    if front_condition == '.':
        if banked_springs == 0:         # One of a line of consecutive dots, so skip.
            return solution(new_condition_records, groups, banked_springs)

        if len(groups) == 0:
            return 0

        new_groups = groups.copy()
        front_group = new_groups.pop(0)

        # Failure: the group we are about to close has incorrect number of springs in it.
        if banked_springs != front_group:
            return 0

        return solution(new_condition_records, new_groups, 0)   # Start a new group.

    else:                           # Must be a question mark.
        new_condition_records2 = new_condition_records.copy()

        new_condition_records.insert(0, '.')
        new_condition_records2.insert(0, '#')

        return (solution(new_condition_records, groups, banked_springs)
                + solution(new_condition_records2, groups, banked_springs))

def process(line: str) -> int:
    condition_records_str, groups_str = line.split(' ')

    condition_record = [each for each in condition_records_str]
    groups = [int(group) for group in groups_str.split(',')]

    unfolded_condition_record = []
    for i in range(4):
        unfolded_condition_record += condition_record
        unfolded_condition_record.append('?')
    unfolded_condition_record += condition_record
    unfolded_condition_record.append('.')

    unfolded_groups = groups * 5
    return solution(unfolded_condition_record, unfolded_groups, 0)

with open('input.txt', 'r') as file:
    conditions = file.read()

total, line_no = 0, 0
for line in conditions.split('\n'):
    line_no += 1

    arrangements = process(line)
    ic(line_no, line, arrangements)
    total += arrangements

ic(total)


#   File: RandomWalker.py
#   Author: Nawaf Abdullah
#   Creation Date: 19/Mar/2018
#   Description: Modeling of the random walker problem in 1D, 2D and 3D
#   Reference: Computational Physics by Nichholas J. Giordano & Hisao Nakanishi (2nd Ed)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random

class Walker:
    n_points = 0
    x = [0]
    y = [0]
    z = [0]
    z_switch = False

    def __init__(self, N):
        self.n_points = N
        for i in range(N-1):
            self.x.append(0)
            self.y.append(0)
            self.z.append(0)

    def init_npoints(self, N):
        del self.x[:]
        del self.y[:]
        del self.z[:]
        self.__init__(N)

    def one_dimension(self):
        for i in range(self.n_points-1):
            r = random.randint(0, 100)
            if r > 50:
                self.x[i] = self.x[i] + 1
            else:
                self.x[i] = self.x[i] - 1
            self.y[i+1] = self.y[i] + 1
        self.z_switch = False
        return self.x, self.y

    def two_dimension(self):
        for i in range(self.n_points-1):
            if i == 0:
                continue
            r = random.randint(0, 100)
            if r <= 25:
                self.x[i+1] = self.x[i] + 1
                self.y[i+1] = self.y[i]
            elif 25 < r <= 50:
                self.x[i+1] = self.x[i] - 1
                self.y[i+1] = self.y[i]
            elif 50 < r <= 75:
                self.y[i+1] = self.y[i] + 1
                self.x[i+1] = self.x[i]
            else:
                self.y[i+1] = self.y[i] - 1
                self.x[i+1] = self.x[i]
        self.z_switch = False
        return self.x, self.y

    def three_dimension(self):
        for i in range(self.n_points-1):
            if i == 0:
                continue
            r = random.randint(0, 100)
            if r <= 16.66:
                self.x[i+1] = self.x[i] + 1
                self.y[i+1] = self.y[i]
                self.z[i+1] = self.z[i]
            elif 16.66 < r <= 33.32:
                self.x[i+1] = self.x[i] - 1
                self.y[i+1] = self.y[i]
                self.z[i+1] = self.z[i]
            elif 33.32 < r <= 49.98:
                self.y[i+1] = self.y[i] + 1
                self.x[i+1] = self.x[i]
                self.z[i+1] = self.z[i]
            elif 49.98 < r <= 66.64:
                self.y[i+1] = self.y[i] - 1
                self.x[i+1] = self.x[i]
                self.z[i+1] = self.z[i]
            elif 66.64 < r < 83.33:
                self.z[i+1] = self.z[i] + 1
                self.x[i+1] = self.x[i]
                self.y[i+1] = self.y[i]
            else:
                self.z[i+1] = self.z[i] - 1
                self.x[i+1] = self.x[i]
                self.y[i+1] = self.y[i]
        self.z_switch = True
        return self.x, self.y, self.z

    def plot_walker(self):
        if self.z_switch is True:
            ax = plt.axes(projection='3d')
            ax.plot3D(self.x, self.y, self.z, 'gray')
            plt.show()
        else:
            fig1 = plt.figure(1)
            fig1.suptitle("Walker Path")
            plt.xlabel("x-position")
            plt.ylabel("y-position")
            plt.plot(self.x, self.y)
            plt.show()


#!/usr/bin/python3

from PIL import Image
import os
import array
import time
import sys
import argparse
from ctypes import *
import numpy

numpy.set_printoptions(threshold=numpy.nan)
numpy.set_printoptions(linewidth=2000)

colorScheme = numpy.array([(0x00, 0x00, 0x8F), \
                           (0x00, 0x0F, 0xFF), \
                           (0x00, 0x8F, 0xFF), \
                           (0x00, 0xCF, 0xFF), \
                           (0x0F, 0xFF, 0xEF), \
                           (0x4F, 0xFF, 0xAF), \
                           (0x8F, 0xFF, 0x6F), \
                           (0xCF, 0xFF, 0x2F), \
                           (0xFF, 0xEF, 0x00), \
                           (0xFF, 0xAF, 0x00), \
                           (0xFF, 0x9F, 0x00), \
                           (0xFF, 0x6F, 0x00), \
                           (0xFF, 0x2F, 0x00), \
                           (0xEF, 0x00, 0x00), \
                           (0xAF, 0x00, 0x00), \
                           (0x7F, 0x00, 0x00)])

#fDisp = open('cDisp.txt', 'r')

disp = numpy.loadtxt('cDisp.txt', dtype='int')
[dispH, dispW] = disp.shape

sad = numpy.loadtxt('cSadVals_7x7.txt', dtype='int')
[sadH, sadW] = sad.shape

'''for i in range(282): #280
    for j in range(363): #361
        if (disp[i][j] > 15):
            disp[i][j] = 15'''

# create disparity image
im = Image.new("RGB", (dispW, dispH), "white")

for i in range(dispW):
    for j in range(dispH):
        if (sad[j][i] < 4096):
            im.putpixel((i,j), (colorScheme[disp[j][i]][0], colorScheme[disp[j][i]][1], colorScheme[disp[j][i]][2]))
        else:
            im.putpixel((i,j), (0x00, 0x00, 0x00))
            print("sad[%d][%d]", i, j)

im.save("tsukuba_largeVal_7x7.png")
im.show()

#fDisp.close()


import RCxxSerial

def chk(filename):
  print(filename,RCxxSerial.CheckFilename(filename))

chk("HELLO")
chk("HI.THERE")
chk("")
chk("AAA.ZZZ")
chk("TOOLONGFILE.txt")
chk("aaa.zzz")
chk("text.")
chk(".fal")
chk("ZZZZZZZZ.ZZZ")
chk("A.A")
chk("TEST.001")
chk("1456.789")
chk(" ")
chk("   .   ")
chk("dot.dot.dot")
chk("help.tx")
chk("TEST.t@T")
chk("File!.TXT")


a=[]
res=[]
idx=0
num=int(input())
for i in range(num):
    n=int(input())
    a.append(n)
while idx<num:
    if(idx==num-1):
        res.append(idx+1)
    elif(a[idx]>=a[idx+1]):
        res.append(idx+1)
        while(idx!=num-1):
            if(a[idx]>a[idx+1]):
                idx+=1
            else:
                break
    idx=idx+1
for j in res:
    print(j)


data = {
 'file_state'         :
{
 'file_path'        : '/home/chang/programs/ysyx-workbench/projects/encoder83/vsrc/seg.v'
,'last_modify_time' : 1649343114
}
,'code_inf_list'      :
[
{
 'logic_line_range'       : [0, -1]
,'real_line_range'        : [0, -1]
,'file_path'              : '/home/chang/programs/ysyx-workbench/projects/encoder83/vsrc/seg.v'
,'real_code_line_boundry' :
[]
}
]
,'module_inf_list'    :
[
{
 'module_name_sr'    :
{
 'str'   : 'seg'
,'range' : (2,7,2,9)
}
,'module_line_range' : (2,47)
,'inst_inf_list'     :
[]
,'parm_inf_list'     :
[
{
 'str'   : 'CLK_NUM'
,'range' : (25,10,25,16)
}
]
,'io_inf_list'       :
[
{
 'name_sr' :
{
 'str'   : 'clk'
,'range' : (3,8,3,10)
}
,'type'    : 1
}
,
{
 'name_sr' :
{
 'str'   : 'rst'
,'range' : (4,8,4,10)
}
,'type'    : 1
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg0'
,'range' : (5,15,5,20)
}
,'type'    : 2
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg1'
,'range' : (6,15,6,20)
}
,'type'    : 2
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg2'
,'range' : (7,15,7,20)
}
,'type'    : 2
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg3'
,'range' : (8,15,8,20)
}
,'type'    : 2
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg4'
,'range' : (9,15,9,20)
}
,'type'    : 2
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg5'
,'range' : (10,15,10,20)
}
,'type'    : 2
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg6'
,'range' : (11,15,11,20)
}
,'type'    : 2
}
,
{
 'name_sr' :
{
 'str'   : 'o_seg7'
,'range' : (12,15,12,20)
}
,'type'    : 2
}
]
,'code_inf_list'     :
[
{
 'logic_line_range'       : [2, 47]
,'real_line_range'        : [2, 47]
,'file_path'              : '/home/chang/programs/ysyx-workbench/projects/encoder83/vsrc/seg.v'
,'real_code_line_boundry' :
[
[2, 12, 1]
,
[30, 2, 2]
,
[35, 4, 1]
]
}
]
}
]
,'macro_inf_list'     :
[]
,'wild_inst_inf_list' :
[]
}


import requests
from pathlib import Path

class WeatherForecast:
    """
    {
        "state": "晴れ",
        "max": "13℃",
        "min": "5℃",
        "max_diff": "[-5]",
        "min_diff": "[0]",
        "icon": "https://s.yimg.jp/images/weather/general/next/size150/100_night.png",
        "rainy-percent": [
            "---",
            "---",
            "---",
            "0%"
        ]
    }
    """
    def __init__(self, api_url):
        self.TIME_OUT = (3, 6)
        self.USER_AGENT = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'}
        self.api_url = api_url

    def fetch_weather_forecast(self):
        forecast_dict = {}
        try:
            res = requests.get(self.api_url, headers=self.USER_AGENT, timeout=self.TIME_OUT)
            if res.status_code == 200:
                forecast = res.json()['forecasts'][0]

                forecast_dict['state'] = forecast['telop']
                forecast_dict['max'] = forecast['temperature']['max']['celsius']
                forecast_dict['max_diff'] = ''
                forecast_dict['min'] = forecast['temperature']['min']['celsius']
                forecast_dict['min_diff'] = ''
                forecast_dict['icon'] = forecast['image']['url']
                forecast_dict['rainy_percent'] = [percent for percent in forecast['chanceOfRain'].values()]
            else:
                forecast_dict['error'] = 'Status Code:{} From:{}'.format(res.status_code, self.api_url)
        except Exception as e:
            forecast_dict['error'] = str(e)

        return forecast_dict

    def fetch_forecast_icon(self, root_dir, src_url):
        file_name = src_url.split('/')[-1]
        image_dir = Path(root_dir.parent).joinpath('public/images')
        image_file_path = Path(image_dir).joinpath(file_name)
        try:
            res = requests.get(src_url, headers=self.USER_AGENT, timeout=self.TIME_OUT)
            image = res.content
            # imagesフォルダなかったら作成
            if not image_dir.is_dir(): Path.mkdir(image_dir)
            # 画像保存
            with open(image_file_path, 'wb') as f:
                f.write(image)

            # 画像ファイルのフルパスを返す
            if Path(image_file_path).exists():
                return str(image_file_path)
            else:
                return False
        except Exception as e:
            return str(e)


for t in range(1, 11):
    N = int(input())
    buildings = list(map(int, input().split()))
    ans = 0

    for i in range(2, N-2):
        home = buildings[i]
        tmp = buildings[i-2 : i] + buildings[i+1 : i+3]

        maximum = 0
        for height in tmp:
            if maximum < height:
                maximum = height
        if maximum < home:
            ans += (home - maximum)

    print(f'#{t} {ans}')


#! /usr/bin/python3
# This is the Python script for Class Exercise 26

# returns the number of times a character occurs in a string
def character_count(string, char):
    count = 0
    for ch in string:
        if ch == char:
            count += 1
    return count

# returns a string that is the reverse of a string given
def string_reverse(string):
    new_string = ""
    for ch in string:
        new_string = ch + new_string
    return new_string

# turns an integer into a string with digits represented by words
def digits_to_words(number):
    new_string = ""
    number_string = str(number)
    for digit in number_string:
        digit = int(digit)
        new_string += digits[digit] + " "
    return new_string

# returns the first name from a full name
def first_name(full_name):
    return full_name[:full_name.index(' ')]

# returns the last name from a full name
def last_name(full_name):
    return full_name[full_name.index(' ') + 1:]

print("character_count('Mississippi', 'i'):", character_count('Mississippi', 'i'))
print("character_count('Mississippi', 'p'):", character_count('Mississippi', 'p'))
print("character_count('Mississippi', 's'):", character_count('Mississippi', 's'))
print()
print("string_reverse('Mississippi'):      ", string_reverse('Mississippi'))
print("string_reverse('radar'):            ", string_reverse('radar'))
print()
digits = ["zero", "one", "two", "three", "four"]
digits += ["five", "six", "seven", "eight", "nine"]
print("digits:", digits)
for i in range(len(digits)):
    print(str(i) + ":\t" + digits[i])
print("digits_to_words(512)", digits_to_words(512))
print("digits_to_words(10428)", digits_to_words(10428))
print()
print("first_name('Glenn Hoffman'):", first_name('Glenn Hoffman'))
print("last_name('Glenn Hoffman'): ", last_name('Glenn Hoffman'))