from odoo import models, fields, api

from odoo.exceptions import UserError

import logging
_logger = logging.getLogger(__name__)

class LinkPickingPurchase(models.TransientModel):
	_name = 'link.picking.purchase'

	def _default_picking(self):
		return self.env['stock.picking'].browse(self._context.get('active_id'))

	picking_id = fields.Many2one('stock.picking', string='Picking', default=_default_picking)
	purchase_ids = fields.Many2many('purchase.order', string='Purchase')

	# @api.multi
	def apply(self):
		# self.purchase_id.invoice_ids |= self.invoice_ids
		# return {}

		if not self.purchase_ids:
			raise UserError("You must select at least one purchase to link to this purchase order.")

		for purchase in self.purchase_ids:

			if purchase.partner_id != self.picking_id.partner_id:
				raise UserError("Picking and purchase vendor must be the same.")

			for purchase_lines in purchase.order_line:
				for move_lines in self.picking_id.move_lines:
					# Check if line items match
					if purchase_lines.product_id == move_lines.product_id and purchase_lines.product_uom == move_lines.product_uom:
						move_lines.write({'purchase_line_id': purchase_lines.id})


from forex_python.converter import CurrencyRates
import requests

def convert_brl_btc(amount):
    c = CurrencyRates()

    bitcoin_api_url = 'https://api.coinbase.com/v2/prices/spot?currency=USD'
    response = requests.get(bitcoin_api_url)
    response_json = response.json()

    usd_blr = c.get_rate('USD', 'BRL')
    btc_usd = float(response_json['data']['amount'])
    btc_brl = ((amount - 20) / (usd_blr * btc_usd))

    return round(btc_brl, 5)

if __name__ == '__main__':
    print(convert_brl_btc(1000))


while True:
	try:
		p1 = input()
		p2 = input()
		m1 = len(p1)
		m2 = len(p2)
		resposta = 0
		for posP1 in range(m1):
			for posP2 in range(m2):

				if(p1[posP1] == p2[posP2]):
					r = 0
					h = 0
					while (posP1 + h < m1 and posP2 + h < m2):
						if(p1[posP1 + h] != p2[posP2 + h]):
							break
						h = h + 1
						r = r + 1
					if (r > resposta):
						resposta = r
		print(resposta)
	except :
		break


from typing import List

# assume all rows are of equal length
# and feature scale each column to be in the range 0 - 1
def normalize_by_feature_scaling(dataset: List[List[float]]) -> None:
    for col_num in range(len(dataset[0])):
        column: List[float] = [row[col_num] for row in dataset]
        maximum = max(column)
        minimum = min(column)
        for row_num in range(len(dataset)):
            dataset[row_num][col_num] = (dataset[row_num][col_num] - minimum) / (maximum - minimum)


from tkinter import *
import tkinter.font as font

root = Tk()
# root.attributes("-fullscreen",True) # For Full Screen Window without Option (i.e. Close, Restore, & Minimize)

monitor_width = root.winfo_screenwidth()
monitor_height = root.winfo_screenheight()
root.geometry("%dx%d" % (monitor_width, monitor_height))

myFont = font.Font(family="Courier",size=20,weight="bold")

fontsize = font.Font(size = 20)     # Just for Some good Visuals :))

labelfont = font.Font(family = "Arial", size = 15, weight = "bold")

buttonfont = font.Font(family = "Courier", size = 15, weight = "bold")

root.title("Chess")

frame = Frame(root)

moveInput = Frame(root)

container1 = Frame(moveInput)
container2 = Frame(moveInput)

board = [
    [' ','a','b','c','d','e','f','g','h'],
    [8,'♜','♞','♝','♚','♛','♝','♞','♜'],
    [7,'♟','♟','♟','♟','♟','♟','♟','♟'],
    [6,'   ','   ','   ','   ','   ','   ','   ','   '],
    [5,'   ','   ','   ','   ','   ','   ','   ','   '],
    [4,'   ','   ','   ','   ','   ','   ','   ','   '],
    [3,'   ','   ','   ','   ','   ','   ','   ','   '],
    [2,'♙','♙','♙','♙','♙','♙','♙','♙'],
    [1,'♖','♘','♗','♔','♕','♗','♘','♖']
]

# Logic behind Creating the Chess Board using the above list
def Create_Board():
    global fontsize, frame, board
    temp = label = Label(frame)
    r = c = 0
    for r in range(9):
        for c in range(9):
            if r > 0 and c > 0:
                temp = Label(frame, text = board[r][c], font = fontsize)
                temp.grid(row = r,column = c,ipadx = 30,ipady = 20)
                if r % 2 != 0:
                    if c % 2 != 0:
                        temp.config(bg = '#a6a')
                    else:
                        temp.config(bg = 'white')
                else:
                    if c % 2 != 0:
                        temp.config(bg = 'white')
                    else:
                        temp.config(bg = '#a6a')
            else:
                temp = Label(frame, text = board[r][c], font = fontsize)
                temp.grid(row = r,column = c,ipadx = 25,ipady = 20)

Create_Board()  # Creating the Chess Board

Label(moveInput, text = "Enter the Row and Column Below to Make a Move", font = myFont, fg = '#4169e1').pack(side = TOP, expand = True, pady = 30)

# For Row Input
Label(container1, text = "Initial Row Index:", font = labelfont, fg = '#007bff').pack(side = 'left', expand = True, padx = 10, pady = 20)
initialrowInput = Entry(container1, font = labelfont, fg = '#28a745')
initialrowInput.pack(side = LEFT, expand = True, padx = 10, pady = 20)

finalrowInput = Entry(container1, font = labelfont, fg = '#28a745')
finalrowInput.pack(side = RIGHT, expand = True, padx = 10, pady = 20)
Label(container1, text = "Final Row Index:", font = labelfont, fg = '#007bff').pack(side = RIGHT, expand = True, padx = 10, pady = 10)

# For Column Input
Label(container2, text = "Initial Column Letter:", font = labelfont, fg = '#007bff').pack(side = 'left', expand = True, padx = 10, pady = 10)
initialcolumnInput = Entry(container2, font = labelfont, fg = '#28a745')
initialcolumnInput.pack(side = LEFT, expand = True, padx = 10, pady = 10)

finalcolumnInput = Entry(container2, font = labelfont, fg = '#28a745')
finalcolumnInput.pack(side = RIGHT, expand = True, padx = 10, pady = 10)
Label(container2, text = "Final Column Letter:", font = labelfont, fg = '#007bff').pack(side = RIGHT, expand = True, padx = 10, pady = 10)

# Submit Move via Button
submitMove = Button(moveInput, text = 'Submit', font = buttonfont, fg = '#800080', bg = '#ffc107', borderwidth = 0)
submitMove.pack(side = BOTTOM, expand = True, ipadx = 5, ipady = 5, pady = 5)

frame.pack(expand=True) # Making the Positioning of the Board onto the Center of the window generated.
moveInput.pack(expand = True, side = 'bottom')
container1.pack(expand = True, side = 'bottom', pady = 10, fill = X)
container2.pack(expand = True, side = 'bottom', pady = 10, fill = X)

root.mainloop()


from typing import List

class Solution:
    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
        graph = [[] for _ in range(n)]
        low = [0 for _ in range(n)]
        visited = [False for _ in range(n)]
        for x, y in connections:
            graph[x].append(y)
            graph[y].append(x)

        self.answer = []

        def dfs(rank, cur, prev):
            low[cur] = rank
            visited[cur] = True
            for nxt in graph[cur]:
                if nxt == prev:
                    continue
                if not visited[nxt]:
                    dfs(rank + 1, nxt, cur)
                low[cur] = min(low[cur], low[nxt])
                if low[nxt] >= rank + 1:
                    self.answer.append([cur, nxt])

        dfs(1, 0, -1)
        return self.answer


import numpy as np
from collections import Counter
import operator
import os
from sklearn.neighbors import KNeighborsClassifier as knn
train_digits='./digits/trainingDigits'
test_digits='./digits/testDigits'

def classify0(inx,dataset,labels,k):
    dist=np.sum((inx-dataset)**2,axis=1)**0.5

    k_labels=[labels[i] for i in dist.argsort()[:k]]
    label_dict={}
    for i in k_labels:
        label_dict[i]=label_dict.get(i,0)+1
    label_list=sorted(label_dict.items(),key=operator.itemgetter(1),reverse=True)

    return label_list[0][0]

# def classify0(inx,dataset,labels,k):
#     #计算距离
#     dist=np.sum((inx-dataset)**2,axis=1)**0.5
#
#     #找到距离最近的前k个label
#     k_labels=[labels[i] for i in dist.argsort()[:k]]
#
#     #归类 counter返回类型list,内部元素为tuple
#     label=Counter(k_labels).most_common(1)[0][0]
#     return label

def img2vector(filename):
    with open(filename,'r+') as f:
        returnVec=list(map(int,f.read().replace('\n','')))
    return returnVec

def handwritingClassTest():
    #获取训练特征
    train_mat=[]
    train_labels=[]
    for sub in os.listdir(train_digits):
        label=sub.split('_')[0]
        train_labels.append(label)

        vector=img2vector(os.path.join(train_digits,sub))
        train_mat.append(vector)
    train_mat=np.array(train_mat)

    #进行测试
    error=0.0
    total=0.0
    for sub in os.listdir(test_digits):
        total+=1
        label=sub.split('_')[0]
        vector=img2vector(os.path.join(test_digits,sub))

        pred_label=classify0(vector,train_mat,train_labels,3)
        if pred_label!=label:
            error+=1

    print('错误率为{}/{}'.format(error,total))

def sklearn_handwritingTest():
    #获取训练特征
    train_mat=[]
    train_labels=[]
    for sub in os.listdir(train_digits):
        label=sub.split('_')[0]
        train_labels.append(label)

        vector=img2vector(os.path.join(train_digits,sub))
        train_mat.append(vector)
    train_mat=np.array(train_mat)

    neigh=knn(n_neighbors=3)
    neigh.fit(train_mat,train_labels)

    #进行测试
    error=0.0
    total=0.0
    for sub in os.listdir(test_digits):
        total+=1
        label=sub.split('_')[0]
        vector=img2vector(os.path.join(test_digits,sub))

        vector=np.array(vector).reshape(1,-1)# 1d->2d
        pred_label=neigh.predict(vector)
        if pred_label!=label:
            error+=1

    print('错误率为{}/{}'.format(error, total))

if __name__ == '__main__':
    handwritingClassTest()
    sklearn_handwritingTest()


array = [5, 7, 9, 0, 3, 1, 6, 2, 4, 8]

def quick(start, end):
    if start+1 >= end:
        return
    pivot = start
    stateStart = 0
    stateEnd = 0
    firstStart = start - 1
    firstEnd = end
    while end >= start:
        if array[start] < array[pivot]:
            start += 1
        else:
            stateStart = 1
        if array[end] > array[pivot]:
            end -= 1
        else:
            stateEnd = 1
        if stateStart == 1 and stateEnd == 1:
            array[end], array[start] = array[start], array[end]
            stateStart, stateEnd = 0, 0
    array[end], array[pivot] = array[pivot], array[end]
    pivot = end
    quick(firstStart, pivot-1)
    quick(pivot + 1, firstEnd)

quick(0, len(array)-1)
print(array)


import collections
import os.path
import subprocess

import numpy as np

from . import utils

UCHAR = 'B'
DOUBLE = '>d'
INT = '>i'

class BibarchReader:

    def __init__(self, filename):
        self.chapter_readers = {
            'VERSION': self._ch_version,
            'TITRE': self._ch_title,
            'GLOBAL': self._ch_global,
            'THERMODYNAMIQUE': self._ch_thermo,
            'ESPECES': self._ch_specie,
            'DOMUTIL': self._ch_dom,
            'STRUCTURE': self._ch_structure,
            'NUMEROTATION': self._ch_numbering,
            'CONNEXION': self._ch_connection,
            'VARIABLES': self._ch_variable,
            'MAILLAGE': self._ch_mesh,
            'GRAVITE CELLULE': self._ch_cell_g,
            'GRAVITE FACE': self._ch_face_g,
            'CELLULES': self._ch_cells,
            'SURFACE': self._ch_surface,
            'VALEUR VOLUMIQUE': self._ch_sca_vol,
            'VALEUR SURFACIQUE': self._ch_sca_surf,
            'VECTEUR SURFACIQUE': self._ch_vec_surf,
            'VECTEUR VOLUMIQUE': self._ch_vec_vol,
            'TENSEUR VOLUMIQUE': self._ch_tens_vol,
        }

        self._data = collections.defaultdict(
            lambda: collections.defaultdict(
                lambda: collections.defaultdict(
                    lambda: np.array([])
                )
            )
        )

        self._filename = filename
        self._ff = self._nff = self._save_nff = None

        self.nblocks = int(subprocess.check_output(['grep', '-c', 'VARIABLES', self._filename]))
        self._i_variable = -1
        self._count = utils.Counter(self.nblocks, 'Merging')

        self._done = False

    def _ch_version(self):
        self._read_val(UCHAR)  # version

    def _ch_title(self):
        self._read_str()  # title
        self._read_str()  # date
        self._read_str()  # arch
        self._read_val(DOUBLE)  # t0
        self._read_val(DOUBLE)  # eps

    def _ch_global(self):
        self._read_str()  # solver
        self._read_val(UCHAR)  # dim

    def _ch_thermo(self):
        flag = self._read_val(INT)  # flag thermodynamic values
        self._read_str()  # filename
        if flag == 0:
            ge = self._read_val(INT)  # ge
            gr = self._read_val(INT)  # gr
            e = self._read_val(INT)  # e
            r = self._read_val(INT)  # r
            self._read_val(INT, n=ge)
            self._read_val(INT, n=gr)
            self._read_val(INT, n=e)
            self._read_val(DOUBLE, n=r)

    def _ch_specie(self):
        self._read_val(INT)  # mix number
        self._read_str()  # mix name
        n_elem = self._read_val(INT)  # n elements
        self._read_str(n=n_elem)  # elements names

    def _ch_dom(self):
        self._read_val(INT)  # idom
        self._read_str()  # name

    def _ch_structure(self):
        self._read_val(INT)  # i_dom abs
        self._read_val(INT)  # i_dom user
        self._read_str()  # dom name
        self._read_val(UCHAR)  # mesh type
        self._read_val(UCHAR)  # values location (0: nodes, 1: centers)
        self._read_val(INT)  # dom spicies mix
        self._read_val(INT)  # dom scalars

    def _ch_numbering(self):
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        n_v = self._read_val(INT)  # n vertices
        n_f = self._read_val(INT)  # n faces
        n_bf = self._read_val(INT)  # n boundary faces
        n_of = self._read_val(INT)  # n overlap faces
        n_c = self._read_val(INT)  # n cells
        self._read_val(INT, n=n_v)  # i vertices
        self._read_val(INT, n=n_f)  # i faces
        self._read_val(INT, n=n_c + n_bf + n_of)  # i cells

    def _ch_connection(self):
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(INT)  # f_min
        nfaces = self._read_val(INT)  # n faces
        self._read_val(INT, n=2 * nfaces)  # cell numbers
        nbpoints = self._read_val(UCHAR, n=nfaces)  # number of vertices
        self._read_val(INT, n=sum(nbpoints))  # vertice numbers

    def _ch_variable(self):
        self._i_variable += 1

        self._read_val(INT)  # idom
        nvar = self._read_val(INT)  # n variables
        names = self._read_str(n=nvar)  # variable names
        group = self._read_str()  # group
        category = self._read_str()  # category
        self._read_val(UCHAR)  # global
        self._read_val(INT)  # elem min
        nelem = self._read_val(INT)  # n elem
        values = self._read_bloc_real(nvar * nelem).reshape((nvar, nelem))

        for i in range(nvar):
            # foo = self._offset[category][group][names[i]]
            # if len(self[category, group, names[i]]) < foo + nelem:
            #     if names[0] == 'Temps':
            #         print(2 * len(self[category, group, names[i]]) + nelem)
            #     buffer = np.zeros(2 * len(self[category, group, names[i]]) + nelem)
            #     buffer[:len(self[category, group, names[i]])] = self[category, group, names[i]]
            #     self[category, group, names[i]] = buffer

            # self[category, group, names[i]][foo:foo + nvar] = values[i]
            # self._offset[category][group][names[i]] = foo + nvar
            self[category, group, names[i]] = np.concatenate((self[category, group, names[i]], values[i]))

    def _ch_mesh(self):
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(INT)  # v_min
        n_v = self._read_val(INT)  # n vertices
        self._read_bloc_real(n_v)  # x
        self._read_bloc_real(n_v)  # y
        self._read_bloc_real(n_v)  # z

    def _ch_cell_g(self):
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(INT)  # c_min
        n_c = self._read_val(INT)  # n cells
        self._read_bloc_real(n_c)  # x
        self._read_bloc_real(n_c)  # y
        self._read_bloc_real(n_c)  # z

    def _ch_face_g(self):
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(INT)  # f_min
        n_f = self._read_val(INT)  # n faces
        self._read_bloc_real(n_f)  # x
        self._read_bloc_real(n_f)  # y
        self._read_bloc_real(n_f)  # z

    def _ch_cells(self):
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(INT)  # f_min
        n_c = self._read_val(INT)  # n cells
        self._read_val(UCHAR, n=n_c)  # cell types

    def _ch_surface(self):
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(INT)  # s_min
        self._read_str()  # name
        self._read_val(UCHAR)  # type
        self._read_val(INT)  # elem min
        nelem = self._read_val(INT)  # n elem
        self._read_val(INT, n=nelem)  # n face
        self._read_val(UCHAR, n=nelem)  # type face

    def _ch_sca_vol(self):
        self._read_val(UCHAR)  # moyen
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(DOUBLE)  # dt
        self._read_val(UCHAR)  # class
        self._read_str()  # name
        self._read_val(INT)  # elem min
        nelem = self._read_val(INT)  # n elem
        self._read_bloc_real(nelem)  # scalar

    def _ch_sca_surf(self):
        self._read_val(UCHAR)  # moyen
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(DOUBLE)  # dt
        self._read_val(UCHAR)  # class
        self._read_str()  # name
        self._read_val(INT)  # surface
        self._read_val(INT)  # elem min
        nelem = self._read_val(INT)  # n elem
        self._read_bloc_real(nelem)  # scalar

    def _ch_vec_vol(self):
        self._read_val(UCHAR)  # moyen
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(DOUBLE)  # dt
        self._read_val(UCHAR)  # class
        self._read_str()  # name
        self._read_val(INT)  # elem min
        nelem = self._read_val(INT)  # n elem
        self._read_bloc_real(nelem)  # v_x
        self._read_bloc_real(nelem)  # v_y
        self._read_bloc_real(nelem)  # v_z

    def _ch_vec_surf(self):
        self._read_val(UCHAR)  # moyen
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(DOUBLE)  # dt
        self._read_val(UCHAR)  # class
        self._read_str()  # name
        self._read_val(INT)  # surface
        self._read_val(INT)  # elem min
        nelem = self._read_val(INT)  # n elem
        self._read_bloc_real(nelem)  # v_x
        self._read_bloc_real(nelem)  # v_y
        self._read_bloc_real(nelem)  # v_z

    def _ch_tens_vol(self):
        self._read_val(UCHAR)  # moyen
        self._read_val(INT)  # idom
        self._read_val(DOUBLE)  # time
        self._read_val(DOUBLE)  # dt
        self._read_val(UCHAR)  # class
        self._read_str()  # name
        self._read_val(INT)  # elem min
        nelem = self._read_val(INT)  # n elem
        self._read_bloc_real(nelem)  # t_xx
        self._read_bloc_real(nelem)  # t_yx
        self._read_bloc_real(nelem)  # t_zx
        self._read_bloc_real(nelem)  # t_xy
        self._read_bloc_real(nelem)  # t_yy
        self._read_bloc_real(nelem)  # t_zy
        self._read_bloc_real(nelem)  # t_xz
        self._read_bloc_real(nelem)  # t_yz
        self._read_bloc_real(nelem)  # t_zz

    def read(self, verbose=False):
        self._ff = open(self._filename, 'rb')
        while True:
            chapter = self._read_str()
            if verbose:
                print(chapter)
            if chapter == 'FIN_DU_FICHIER':
                break
            elif chapter == '':
                break
            self.chapter_readers[chapter]()
        self._ff.close()
        self._done = True

    def read_and_merge_variable(self, verbose=False):
        self._ff = open(self._filename, 'rb')
        self._nff = self._save_nff = open(self._filename + '.TMP', 'wb')
        while True:
            chapter = self._read_str()
            if verbose:
                print(chapter)
            else:
                self._count(self._i_variable)
            if chapter == 'VARIABLES':
                self._nff = None
            elif self._nff is None:
                self._nff = self._save_nff
                first = True
                name = ''
                for category in self:
                    for group in self[category]:
                        if first:
                            first = False
                        else:
                            self._nff.write(b'VARIABLES\x00')
                        self._nff.write(np.array([0], dtype=INT).tobytes())  # idom
                        self._nff.write(np.array([len(self[category, group])], dtype=INT).tobytes())  # n variables
                        for name in self[category][group]:
                            self._nff.write(name.encode() + b'\x00')  # variable names
                        self._nff.write(group.encode() + b'\x00')  # group
                        self._nff.write(category.encode() + b'\x00')  # group
                        self._nff.write(np.array([0], dtype=UCHAR).tobytes())  # global
                        self._nff.write(np.array([0], dtype=INT).tobytes())  # elem min
                        self._nff.write(np.array(len(self[category, group, name]), dtype=INT).tobytes())  # n elem
                        self._nff.write(np.array([0], dtype=UCHAR).tobytes())  # compression
                        for name in self[category, group]:
                            # noinspection PyUnresolvedReferences
                            self._nff.write(self[category, group, name].astype(DOUBLE).tobytes())
                self._nff.write(chapter.encode() + b'\x00')
            if chapter == 'FIN_DU_FICHIER' or chapter == '':
                break
            self.chapter_readers[chapter]()
        self._nff.write(b'FINFINFIN\x00')
        self._nff.close()
        self._ff.close()
        subprocess.run(['mv', self._filename + '.TMP', self._filename])
        self._done = True

    def _read_bloc_real(self, n):
        compression = self._read_val(UCHAR)
        if compression == 4:  # Constant
            return self._read_val(DOUBLE) * np.ones((n,))
        elif compression == 1:  # None
            v_min = self._read_val(DOUBLE)
            v_max = self._read_val(DOUBLE)
            return v_min + self._read_val('>I', n=n) * (v_max - v_min) / np.iinfo('>I').max
        elif compression == 0:  # None
            return self._read_val(DOUBLE, n=n)
        else:
            raise ValueError("Compression mode not implemented yet: {0}".format(compression))

    def _read_val(self, dtype, n=1):
        data = self._ff.read(n * np.dtype(dtype).itemsize)
        if self._nff:
            self._nff.write(data)
        if n == 1:
            return np.frombuffer(data, dtype=dtype)[0]
        return np.frombuffer(data, dtype=dtype, count=n)

    def _read_str(self, n=0):
        buffer = b''
        while True:
            b = self._ff.read(1)
            if b == b'' or b == b'\x00':
                break
            buffer += b
        if self._nff:
            self._nff.write(buffer + b)
        if n == 0:
            return buffer.decode()
        elif n == 1:
            return [buffer.decode()]
        else:
            return [buffer.decode(), *self._read_str(n=n - 1)]

    def __getitem__(self, items):
        def _pop(_out, _items):
            if not _items:
                return _out
            if isinstance(_items[0], (list, tuple)):
                for _item in _items[0]:
                    if self._done and _item not in _out:
                        self.inspect_data()
                        raise KeyError(_item)
                return sum(_pop(_out[_item], _items[1:]) for _item in _items[0])
            if self._done and _items[0] not in _out:
                self.inspect_data()
                raise KeyError(_items[0])
            return _pop(_out[_items[0]], _items[1:])

        return _pop(self._data, items if isinstance(items, (list, tuple)) else [items])

    def __setitem__(self, items, value):
        items = items if isinstance(items, (list, tuple)) else [items]
        out = self._data
        for item in items[:-1]:
            out = out[item]
        out[items[-1]] = value

    def __iter__(self):
        return self._data.__iter__()

    def inspect_data(self, tab='    '):
        if not self._done:
            raise RuntimeError("The file has not been parsed yet!")

        for i in self:
            print(i)
            for j in self[i]:
                print(tab, j)
                print(tab, tab, *[repr(k) for k in self[i, j]])

def read_histo(runs, category, group, name, use_time=False):
    """
    Read a set of "Explore's historique" files and return the expected data

    :param str, list[str] runs: path to the files, may be remote
    :param category:
    :param group:
    :param name:
    :param bool use_time:
    :return: the x and y data, and the restart indices
    """
    x_data = np.array([])
    y_data = np.array([])
    restarts = []
    g_x, n_x = ('DATES', 'Temps') if use_time else ('CYCLES', 'Ncycle')
    runs = runs if isinstance(runs, (list, tuple)) else [runs]

    for r in runs:
        f, = utils.fetch_file(os.path.join(r, 'histo_CHARME.0'))
        bibarch_reader = BibarchReader(f)
        if bibarch_reader.nblocks > 100:
            bibarch_reader.read_and_merge_variable()
        else:
            bibarch_reader.read()
        x_data = np.concatenate((x_data, bibarch_reader['HORLOGE', g_x, n_x]))
        y_data = np.concatenate((y_data, bibarch_reader[category, group, name]))
        restarts.append(len(x_data))
    return x_data, y_data, restarts[:-1]

class HistoPlotter:

    def __init__(self, axis, tags, mode='ITER', root='', plot_restarts=True):
        """

        :param matplotlib.axis._axis.Axis axis:
        :param str mode: 'ITER', 'TIME' or 'WALL'
        :param str root: path to prepend to case files
        :param tuple(str, str, str) tags:
        :param bool plot_restarts: if True, plot a marker at restarts
        """

        self._tags = tags
        self._mode = mode
        self._root = root

        self._ax = axis
        self._ax.set_xlabel({'ITER': 'Iteration number', 'TIME': 'Simulation time', 'WALL': 'Wall time'}[self._mode])
        self._ax.set_title(r'$\qquad$'
                           .join([' + '.join(tag) if isinstance(tag, (list, tuple)) else tag for tag in self._tags]))

        self._offset = 0
        self._plot_restarts = plot_restarts

    def get_wall_time(self, name):
        file, = utils.fetch_file(os.path.join(os.path.join(self._root, name), 'suivi.1'))
        t = utils.fetch_suivi_stats(file)
        if t is None:
            file, = utils.fetch_file(os.path.join(os.path.join(self._root, name), 'slurm.*.out'))
            t = utils.fetch_slurm_stats(file)[0]
        return t

    def get(self, names):
        names = names if isinstance(names, (list, tuple)) else [names]
        x_data, y_data, restarts = read_histo([os.path.join(self._root, name) for name in names], *self._tags,
                                              use_time=self._mode == 'TIME')
        if self._mode == 'WALL':
            lengths = [0, *restarts, len(x_data)]
            offset = self._offset
            for i in range(len(names)):
                t = self.get_wall_time(names[i])
                x = x_data[lengths[i]:lengths[i + 1]]
                x_data[lengths[i]:lengths[i + 1]] = t * (x + x[1] - 2 * x[0]) / (x[-1] + x[1] - 2 * x[0]) + offset
                offset = x_data[lengths[i + 1] - 1]
        return x_data, y_data, restarts

    def reset_offset(self, names):
        if self._mode != 'WALL':
            return
        names = names if isinstance(names, (list, tuple)) else [names]
        self._offset = sum(self.get_wall_time(name) for name in names)

    def plot(self, case, *args, **kwargs):
        x, y, restarts = self.get(case)
        self._ax.plot(x, y, *args, **kwargs)
        if self._plot_restarts:
            self._ax.plot(x[restarts], y[restarts], 'k|', ms=10, mew=3)

    def change_root(self, new_root):
        self._root = new_root


import json
import requests

key = "AIzaSyA-"
cx = ""

def getimage(query):
    url = f"https://www.googleapis.com/customsearch/v1?q={query}_logo&num=1&cx={cx}&alt=json&key={key}&searchType=image"
    response = requests.get(url)
    text = response.text
    data = json.loads(text)
    image_link = data['items'][0]['link']
    print(image_link)
    return image_link
    response.close()

def getLargerImage(query):
    url = f"https://www.googleapis.com/customsearch/v1?q={query}&num=1&cx={cx}&alt=json&key={key}&searchType=image"
    response = requests.get(url)
    text = response.text
    data = json.loads(text)
    image_link = data['items'][0]['link']
    return image_link
    response.close()

def getCovidData(state):
    url = f"https://api.covidtracking.com/v1/states/{state}/current.json"
    response = requests.get(url)
    text = response.text
    data = json.loads(text)
    response.close()
    return data

def getHistoricData(state):
    url = f"https://api.covidtracking.com/v1/states/{state}/daily.json"
    response = requests.get(url)
    text = response.text
    data = json.loads(text)
    result = []
    counter = 0
    for api_data in data:
        r = []
        r.append(counter)
        counter += 1
        if api_data["hospitalizedCurrently"] is None:
            r.append(0)
        else:
            r.append(api_data["hospitalizedCurrently"])
        if api_data["positiveIncrease"] is None:
            r.append(0)
        else:
            r.append(api_data["positiveIncrease"])
        if api_data["deathIncrease"] is None:
            r.append(0)
        else:
            r.append(api_data["deathIncrease"])
        result.append(r)
    response.close()
    return result


import time
import cv2

SCREEN_REZ = (2560, 1440)
if __name__ == '__main__':
    url = "https://ch-fra-n9.livespotting.com/vpu/ggazg0ll/taelb29k_1080.m3u8"
    cap = cv2.VideoCapture(url)
    cap.set(cv2.CAP_PROP_BUFFERSIZE, 100)

    lastImage = cap.read()[1]
    lastRead = time.perf_counter()

    while True:

        if time.perf_counter() - lastRead >= 1.0/20:
            lastRead = time.perf_counter()
            lastImage = cap.read()[1]
            #lastImage = cv2.resize(lastImage, SCREEN_REZ)

        cv2.imshow("Pjaca", lastImage)

        char = cv2.waitKey(1)
        if char == ord('q'):
            break


from celery import Celery
import subprocess

celery_app = Celery('tasks', broker='redis://localhost:6379/0',
                    backend='redis://localhost:6379/0')

@celery_app.task
def take_thumbnail(video_input_path: str, img_output_path: str) -> None:
    try:
        proc = subprocess.Popen(['ffmpeg', '-i', video_input_path, '-ss', '00:00:00.000', '-vframes', '1', img_output_path],
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        proc.wait()
        (stdout, stderr) = proc.communicate()
    except subprocess.CalledProcessError as err:
        raise Exception(f'take_thumbnail: failed {str(err)}')

@celery_app.task
def video_manipulation_done(*args, **kwargs):
    # check for next video manipulation in db
    # next_video_manipulation.apply_async('arg1', 'arg2', link=done.s())
    print('ok')


import time
import datetime

from ffpyplayer.player import MediaPlayer
import numpy as np
import torch
import pandas as pd
import cv2

video_urls = {
    "Pjaca": "https://ch-fra-n12.livespotting.com/vpu/ggazg0ll/g98s254r_720.m3u8",
    "Burkovo": "https://ch-fra-n9.livespotting.com/vpu/ggazg0ll/taelb29k_1080.m3u8",
    "Vrtic1": "https://cdn-004.whatsupcams.com/hls/hr_jelsa01.m3u8",
    "Vrtic2": "https://cdn-002.whatsupcams.com/hls/hr_jelsa04.m3u8",
    "CentarOkretna": "https://cdn-004.whatsupcams.com/hls/hr_jelsa06.m3u8",
    "VelaGospa": "https://cdn-002.whatsupcams.com/hls/hr_jelsa07.m3u8",
}

def get_data(model):
    print("Getting detections..")
    images = []
    for name in video_urls:
        print(f"Getting image from {name}")
        player = None

        while player is None:
            try:
                #player = MediaPlayer(video_urls[name])
                player = cv2.VideoCapture(video_urls[name])
            except Exception as e:
                print("Failed to create player")
                print(e)
                time.sleep(1)
            if player is None or not player.isOpened():
                player  = None
                print("Failed opening player")
                time.sleep(1)

        time.sleep(1)

        img = None
        while img is None:
            try:
                ret, img = player.read()
            except Exception as e:
                print("Failed getting image")
                print(e)
                time.sleep(1)

        #img, t = img
        #h,w = img.shape[:2]
        #img = np.asarray(img.to_bytearray()[0]).reshape(h,w,3)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        images.append(img)
        player.release()

    results = model(images, size=640)
    print("Got detections")
    return results.pandas().xyxy

def write_data(detections):
    data = {
        "Name":[],
        "Class":[],
        "Detections":[],
        "Timestamp":[]
    }
    for name, d in zip(video_urls.keys(), detections):
        values = d.name.value_counts()
        for cls, count in values.items():
            data["Name"].append(name)
            data["Class"].append(cls)
            data["Detections"].append(count)
            data["Timestamp"].append(datetime.datetime.now())
    new_df = pd.DataFrame(data)
    print(new_df)

    df = pd.read_csv('logged_data.csv')
    df = pd.concat([df, new_df])
    df.to_csv('logged_data.csv', index=False)

if __name__ == "__main__":
    print(f"Setup complete. Using torch {torch.__version__} ({torch.cuda.get_device_properties(0).name if torch.cuda.is_available() else 'CPU'})")
    print("Loading model..")
    model = torch.hub.load('ultralytics/yolov5', 'yolov5m')
    print("Model loaded.")

    while True:
        detections = get_data(model)
        write_data(detections)
        time.sleep(300)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import logging
import sys
import traceback
import os
import importlib
import yaml

from . import defaults

logger = logging.getLogger(__name__)
project_path = os.path.dirname(os.path.dirname(__file__))

def update_recursively(d, ud, overwrite=True):
    for key, value in ud.items():
        if key not in d:
            d[key] = value
        elif isinstance(value,dict):
            update_recursively(d[key], value)
        else:
            if key in d and not overwrite:
                return
            d[key] = value

class Settings(object):

    """
    Contains all relevant global settings:

    * Commands
    * Analyzers
    * Aggregators
    * Plugins
    * Language patterns
    * Models

    The global settings should not be confused with the project-specific
    settings, which contain e.g. specific configuration options for the
    individual analyzers.
    """

    def __init__(self,
                 commands=None,
                 analyzers=None,
                 aggregators=None,
                 plugins=None,
                 models=None,
                 hooks=None,
                 language_patterns=None):

        self.plugins = plugins if plugins is not None else defaults.plugins.copy()
        self.hooks = hooks if hooks is not None else defaults.hooks.copy()
        self.commands = commands if commands is not None else defaults.commands.copy()
        self.analyzers = analyzers if analyzers is not None else defaults.analyzers.copy()
        self.aggregators = aggregators if aggregators is not None else defaults.aggregators.copy()
        self.models = models if models is not None else defaults.models.copy()
        self.language_patterns = language_patterns if language_patterns is not None else defaults.language_patterns.copy()

    def initialize(self):
        logger.debug("Initializing checkmate settings...")
        self.load_plugins()

    def call_hooks(self, name,*args,**kwargs):
        if name in self.hooks:
            for hook in self.hooks[name]:
                hook(self, *args, **kwargs)

    def load_plugin(self, module,name = None):
        logger.info("Loading plugin: %s" % name)
        if hasattr(module,'analyzers'):
            self.analyzers.update(module.analyzers)
        if hasattr(module,'commands'):
            if name is None:
                raise AttributeError("You must specify a name for your plugin if you defined new commands!")
            self.commands.update({name : module.commands})
        if hasattr(module,'hooks'):
            for key,value in module.hooks.items():
                self.hooks[key].append(value)
        if hasattr(module,'models'):
            self.models.update(module.models)
        if hasattr(module,'top_level_commands'):
            self.commands.update(module.top_level_commands)

    def load_plugins(self, abort_on_error=False,verbose=True):
        for name,module_name in self.plugins.items():
            try:
                module = importlib.import_module(module_name+'.setup')
                self.load_plugin(module,name)
            except BaseException as e:
                logger.error("Cannot import plugin %s (module %s)" % (name,module_name))
                if verbose:
                    logger.error(traceback.format_exc())
                if abort_on_error:
                    raise

    def update(self, settings):
        if settings is None:
            return
        for key in ('plugins',
                    'analyzers',
                    'aggregators',
                    'language_patterns',
                    'commands',
                    'models'):
            if key in settings:
                update_recursively(getattr(self,key), settings[key])

    def load(self, project_path=None):
        home = os.path.expanduser('~')
        possible_config_paths = [home,os.path.join(os.getcwd())]
        if project_path is not None:
            possible_config_paths.append(project_path)
        d = {}
        for possible_config_path in possible_config_paths:
            print(possible_config_path)
            possible_config_filename = os.path.join(possible_config_path,'.checkmate.yml')
            if os.path.exists(possible_config_filename) and os.path.isfile(possible_config_filename):
                with open(possible_config_filename,'r') as config_file:
                    update_recursively(d,yaml.load(config_file.read()))
        return d


import charm_gems as gems
from .ProbabilisticAtlas import ProbabilisticAtlas
from .SamsegUtility import undoLogTransformAndBiasField, writeImage, maskOutBackground, logTransform, readCroppedImages
from .GMM import GMM
import numpy as np
import nibabel as nib
import gc
from simnibs.segmentation._cat_c_utils import cat_vbdist
from simnibs.segmentation.samseg.utilities import requireNumpyArray

def writeBiasCorrectedImagesAndSegmentation(output_names_bias,
                                            output_name_segmentation,
                                            parameters_and_inputs,
                                            tissue_settings,
                                            csf_factor,
                                            cat_structure_options=None,
                                            cat_images=None):

    # We need an init of the probabilistic segmentation class
    # to call instance methods
    probabilisticAtlas = ProbabilisticAtlas()
    # Bias correct images
    biasFields = parameters_and_inputs['biasFields']
    imageBuffers = parameters_and_inputs['imageBuffers']
    mask = parameters_and_inputs['mask']

    # Write these out
    exampleImageFileName = parameters_and_inputs['imageFileNames']
    exampleImage = gems.KvlImage(exampleImageFileName[0])
    cropping = parameters_and_inputs['cropping']
    expImageBuffers, expBiasFields = undoLogTransformAndBiasField(
                                        imageBuffers,
                                        biasFields,
                                        mask)
    expImageBuffers[~mask] = 0
    for contrastNumber, out_name in enumerate(output_names_bias):
        # Bias field correct and write
        writeImage(out_name,  expImageBuffers[..., contrastNumber],
                   cropping, exampleImage)

    # Next do the segmentation, first read in the mesh
    modelSpecifications = parameters_and_inputs['modelSpecifications']
    transform_matrix = parameters_and_inputs['transform']
    transform = gems.KvlTransform(requireNumpyArray(transform_matrix))
    deformation = parameters_and_inputs['deformation']
    deformationAtlasFileName = parameters_and_inputs['deformationAtlas']

    mesh = probabilisticAtlas.getMesh(
            modelSpecifications.atlasFileName,
            transform=transform,
            K=modelSpecifications.K,
            initialDeformation=deformation,
            initialDeformationMeshCollectionFileName=deformationAtlasFileName)

    fractionsTable = parameters_and_inputs['fractionsTable']
    GMMparameters = parameters_and_inputs['GMMParameters']
    numberOfGaussiansPerClass = parameters_and_inputs['gaussiansPerClass']
    means = GMMparameters['means']
    variances = GMMparameters['variances']
    mixtureWeights = GMMparameters['mixtureWeights']
    names = parameters_and_inputs['names']
    bg_label = names.index("Background")
    FreeSurferLabels = np.array(modelSpecifications.FreeSurferLabels,
                                dtype=np.uint16)
    segmentation_tissues = tissue_settings['segmentation_tissues']
    csf_tissues = segmentation_tissues['CSF']
    if cat_structure_options is not None:
        segmentation, cat_norm_scan_masks = _calculateSegmentationLoop(
                                            imageBuffers - biasFields,
                                            mask, fractionsTable, mesh,
                                            numberOfGaussiansPerClass,
                                            means, variances, mixtureWeights,
                                            FreeSurferLabels, bg_label,
                                            csf_tissues, csf_factor,
                                            cat_opts=cat_structure_options)
    else:
        segmentation = _calculateSegmentationLoop(
                        imageBuffers - biasFields,
                        mask, fractionsTable, mesh,
                        numberOfGaussiansPerClass,
                        means, variances, mixtureWeights,
                        FreeSurferLabels, bg_label,
                        csf_tissues, csf_factor)

    writeImage(output_name_segmentation,
               segmentation, cropping, exampleImage)

    if cat_structure_options is not None and cat_images is not None:
        for inds, name in enumerate(cat_images):
            writeImage(name, cat_norm_scan_masks[inds], cropping, exampleImage)

def segmentUpsampled(input_bias_corrected, tissue_settings,
                     parameters_and_inputs, transformedTemplateFileName,
                     affine_atlas, csf_factor):

    # We need an init of the probabilistic segmentation class
    # to call instance methods
    probabilisticAtlas = ProbabilisticAtlas()

    # Read the input images doing the necessary cropping
    imageBuffersUpsampled, transformUpsampled, voxelSpacingUpsampled, croppingUpsampled = readCroppedImages(
                                                                                input_bias_corrected,
                                                                                transformedTemplateFileName)
    # Redo background masking now with the upsampled scans, note this only rasterizes
    # a single class so should be decent memory-wise
    modelSpecifications = parameters_and_inputs['modelSpecifications']
    imageBuffersUpsampled, maskUpsampled = maskOutBackground(
            imageBuffersUpsampled,
            modelSpecifications.atlasFileName,
            transformUpsampled,
            modelSpecifications.brainMaskingSmoothingSigma,
            modelSpecifications.brainMaskingThreshold,
            probabilisticAtlas)

    # Log-transform the intensities, note the scans are already
    # bias corrected so no need to remove the bias contribution

    imageBuffersUpsampled = logTransform(imageBuffersUpsampled,
                                         maskUpsampled)

    # Calculate the posteriors.
    # NOTE: the method for calculating the posteriors
    # in the gmm class rasterizes all classes in the atlas at once.
    # This is very memory-heavy if we have many classes
    # and the input resolution is high. Here we do it instead in
    # a loop to save memory.
    deformation = parameters_and_inputs['deformation']
    deformationAtlasFileName = parameters_and_inputs['deformationAtlas']
    meshUpsampled = probabilisticAtlas.getMesh(
                modelSpecifications.atlasFileName,
                transformUpsampled,
                initialDeformation=deformation,
                initialDeformationMeshCollectionFileName=deformationAtlasFileName)
    del deformation
    fractionsTable = parameters_and_inputs['fractionsTable']
    GMMparameters = parameters_and_inputs['GMMParameters']
    numberOfGaussiansPerClass = parameters_and_inputs['gaussiansPerClass']
    means = GMMparameters['means']
    variances = GMMparameters['variances']
    mixtureWeights = GMMparameters['mixtureWeights']
    names = parameters_and_inputs['names']
    bg_label = names.index("Background")
    FreeSurferLabels = np.array(modelSpecifications.FreeSurferLabels,
                                dtype=np.uint16)
    simnibs_tissues = tissue_settings['simnibs_tissues']
    segmentation_tissues = tissue_settings['segmentation_tissues']
    csf_tissues = segmentation_tissues['CSF']
    segmentation = _calculateSegmentationLoop(
                imageBuffersUpsampled,
                maskUpsampled, fractionsTable, meshUpsampled,
                numberOfGaussiansPerClass,
                means, variances, mixtureWeights, FreeSurferLabels,
                bg_label, csf_tissues, csf_factor)

    del meshUpsampled
    del imageBuffersUpsampled

    tissue_labeling = np.zeros_like(segmentation)
    for t, label in simnibs_tissues.items():
        tissue_labeling[np.isin(segmentation,
                                FreeSurferLabels[segmentation_tissues[t]])] = label

    example_image = gems.KvlImage(input_bias_corrected[0])
    uncropped_tissue_labeling = np.zeros(
            example_image.getImageBuffer().shape, dtype=np.uint16, order='F')
    uncropped_tissue_labeling[croppingUpsampled] = tissue_labeling

    #Create a head mask for post-processing
    affine_upsampled= probabilisticAtlas.getMesh(
                      affine_atlas,
                      transformUpsampled)

    upper_part = np.zeros(example_image.getImageBuffer().shape, bool, order='F')
    upper_part_cropped = affine_upsampled.rasterize(maskUpsampled.shape, 1)
    upper_part[croppingUpsampled] = (65535 - upper_part_cropped) > 32768
    del affine_upsampled
    del maskUpsampled
    del upper_part_cropped
    gc.collect()
    return uncropped_tissue_labeling, upper_part

def saveWarpField(template_name, warp_to_mni,
                  warp_from_mni, parameters_and_inputs):
    # Save warp field two ways: the subject space world coordinates
    # in template space, i.e., the iamge voxel coordinates in
    # physical space for every voxel in the template.
    # And the other way around, i.e., the template voxel coordinates
    # in physical space for every voxel in the image.

    # We need an init of the probabilistic segmentation class
    # to call instance methods
    probabilisticAtlas = ProbabilisticAtlas()

    # First write image -> template.
    # Get the node positions in image voxels
    modelSpecifications = parameters_and_inputs['modelSpecifications']
    transform_matrix = parameters_and_inputs['transform']
    transform = gems.KvlTransform(requireNumpyArray(transform_matrix))

    deformation = parameters_and_inputs['deformation']
    deformationAtlasFileName = parameters_and_inputs['deformationAtlas']
    nodePositions = probabilisticAtlas.getMesh(
             modelSpecifications.atlasFileName,
             transform,
             K=modelSpecifications.K,
             initialDeformation=deformation,
             initialDeformationMeshCollectionFileName=deformationAtlasFileName
         ).points

    # The image is cropped as well so the voxel coordinates
    # do not exactly match with the original image,
    # i.e., there's a shift. Let's undo that.
    cropping = parameters_and_inputs['cropping']
    nodePositions += [slc.start for slc in cropping]

    # Get mapping from voxels to world space of the image.
    imageFileNames = parameters_and_inputs['imageFileNames']
    image = nib.load(imageFileNames[0])
    imageToWorldTransformMatrix = image.affine
    image_buffer = image.get_fdata()
    # Transform the node positions
    nodePositionsInWorldSpace = (imageToWorldTransformMatrix @
                                 np.pad(nodePositions,
                                        ((0, 0), (0, 1)),
                                        'constant', constant_values=1).T).T
    nodePositionsInWorldSpace = nodePositionsInWorldSpace[:, 0:3]
    template = gems.KvlImage(template_name)
    templateToWorldTransformMatrix = template.transform_matrix.as_numpy_array
    template_buffer = template.getImageBuffer()

    # Rasterize the final node coordinates (in image space)
    # using the initial template mesh
    mesh = probabilisticAtlas.getMesh(
                modelSpecifications.atlasFileName,
                K=modelSpecifications.K)

    # Get node positions in template voxel space
    nodePositionsTemplate = mesh.points

    # Rasterize the coordinate values
    coordmapTemplate = mesh.rasterize_values(template_buffer.shape,
                                             nodePositionsInWorldSpace)
    # Write the warp file
    temp_header = nib.load(template_name)
    warp_image = nib.Nifti1Image(coordmapTemplate, temp_header.affine)
                                 #templateToWorldTransformMatrix)
    nib.save(warp_image, warp_to_mni)

    # Now do it the other way, i.e., template->image
    nodePositionsTemplateWorldSpace = (temp_header.affine @
                                       np.pad(nodePositionsTemplate,
                                              ((0, 0), (0, 1)),
                                              'constant', constant_values=1).T).T
    nodePositionsTemplateWorldSpace = nodePositionsTemplateWorldSpace[:, 0:3]
    # Okay get the mesh in image space
    mesh = probabilisticAtlas.getMesh(
             modelSpecifications.atlasFileName,
             transform,
             initialDeformation=deformation,
             initialDeformationMeshCollectionFileName=deformationAtlasFileName)

    imageBuffers = parameters_and_inputs['imageBuffers']
    coordmapImage = mesh.rasterize_values(imageBuffers.shape[0:-1],
                                          nodePositionsTemplateWorldSpace)
    # The image buffer is cropped so need to set
    # everything to the correct place
    uncroppedWarp = np.zeros(image_buffer.shape+(3,),
                             dtype=np.float32, order='F')

    for c in range(coordmapImage.shape[-1]):
        uncroppedMap = np.zeros(image_buffer.shape,
                                dtype=np.float32, order='F')
        uncroppedMap[cropping] = np.squeeze(coordmapImage[:, :, :, c])
        uncroppedWarp[:, :, :, c] = uncroppedMap

    # Write the warp
    warp_image = nib.Nifti1Image(uncroppedWarp,
                                 imageToWorldTransformMatrix)
    nib.save(warp_image, warp_from_mni)

def _calculateSegmentationLoop(biasCorrectedImageBuffers,
                               mask, fractionsTable, mesh,
                               numberOfGaussiansPerClass,
                               means, variances,
                               mixtureWeights, FreeSurferLabels,
                               bg_label,
                               csf_tissues,
                               csf_factor,
                               cat_opts=None):

    data = biasCorrectedImageBuffers[mask, :]
    channels = data.shape[1]
    numberOfVoxels = data.shape[0]
    numberOfStructures = fractionsTable.shape[1]

    # We need an init of the GMM class
    # to call instance methods
    gmm = GMM(numberOfGaussiansPerClass, data.shape[1], True,
              means, variances, mixtureWeights)

    # These will store the max values and indices
    maxValues = np.zeros(biasCorrectedImageBuffers.shape[0:3],
                         dtype=np.float32)
    maxIndices = np.empty(biasCorrectedImageBuffers.shape[0:3],
                          dtype=np.uint16)

    maxIndices[:] = FreeSurferLabels[bg_label]
    print('done')

    # We need the normalizer if we are writing out the normalized images
    # for CAT
    if cat_opts is not None:
        cat_tissue_dict = cat_opts['cat_tissues']
        cat_mask_dict = cat_opts['cat_masks']
        wm_probs = np.zeros(biasCorrectedImageBuffers.shape[0:3],
                            dtype=np.float32)
        gm_probs = np.zeros(biasCorrectedImageBuffers.shape[0:3],
                            dtype=np.float32)
        csf_probs = np.zeros(biasCorrectedImageBuffers.shape[0:3],
                             dtype=np.float32)
        normalizer = np.zeros(biasCorrectedImageBuffers.shape[0:3],
                              dtype=np.float32)

    # The different structures can share their mixtures between classes
    # E.g., thalamus can be half wm and half gm. This needs to be accounted
    # for when looping. We'll first loop over the structures, i.e.,
    # everything that's in the segmentation, so that we also
    # include the correct fractions for each class (if any)
    # NOTE: this function ONLY calculates the labeling and
    # returns the normalizer (if specified). I.e., we don't
    # need to normalize to find the label with highest probability.
    # But we're not going to compute the posteriors here.
    # We're also filling zero values (outside the mask) from the prior
    print('Segmenting, can take a while...')
    for structureNumber in range(numberOfStructures):
        # Rasterize the current structure from the atlas
        # and cast to float from uint16
        nonNormalized = mesh.rasterize(mask.shape, structureNumber)/65535.0
        prior = nonNormalized[mask]

        # Find which classes we need to look at
        # to get the fractions correct
        print('Segmented ' + str(structureNumber +1 ) +' out of ' + str(numberOfStructures) + ' structures.')
        classesToLoop = [i for i, val in enumerate(fractionsTable[:, structureNumber] > 1e-10) if val]
        likelihoods = np.zeros(numberOfVoxels, dtype=np.float32)
        for classNumber in classesToLoop:
            # Compute likelihood for this class
            numberOfComponents = numberOfGaussiansPerClass[classNumber]
            fraction = fractionsTable[classNumber, structureNumber]
            for componentNumber in range(numberOfComponents):
                gaussianNumber = sum(numberOfGaussiansPerClass[:classNumber]) + componentNumber
                mean = np.expand_dims(means[gaussianNumber, :], 1)
                variance = variances[gaussianNumber, :, :]
                mixtureWeight = mixtureWeights[gaussianNumber]

                gaussianLikelihood = gmm.getGaussianLikelihoods(data,
                                                                mean,
                                                                variance)
                likelihoods += gaussianLikelihood * mixtureWeight * fraction

        # Now compute the non-normalized posterior

        if (channels > 1) and (structureNumber in csf_tissues):
            nonNormalized[mask] = csf_factor * likelihoods * prior
        else:
            nonNormalized[mask] = likelihoods * prior

        if cat_opts is not None:
            normalizer += nonNormalized
            if structureNumber in cat_tissue_dict['WM']:
                wm_probs += nonNormalized
            elif structureNumber in cat_tissue_dict['GM']:
                gm_probs += nonNormalized
            elif structureNumber in cat_tissue_dict['CSF']:
                csf_probs += nonNormalized

        if structureNumber == 0:
            # In the first iteration just save the non-normalized values
            # Indices are initialized to zero anyway
            maxValues = nonNormalized
        else:
            # Check whether we have higher values and save indices
            higher_values = nonNormalized > maxValues
            maxValues[higher_values] = nonNormalized[higher_values]
            maxIndices[higher_values] = FreeSurferLabels[structureNumber]

    if cat_opts is not None:
        cat_scan_and_masks = _prep_scans_and_masks([wm_probs, gm_probs,
                                                    csf_probs],
                                                   normalizer,
                                                   maxIndices,
                                                   FreeSurferLabels,
                                                   cat_mask_dict)

    if cat_opts is not None:
        return maxIndices, cat_scan_and_masks
    else:
        return maxIndices

def _prep_scans_and_masks(tissue_prob_list, normalizer, maxInds,
                          FreeSurferLabels, mask_dict):

    # Create normalized image
    eps = np.finfo(float).eps
    normalized_scan = np.zeros_like(normalizer)
    normalized_scan += tissue_prob_list[0]/(normalizer + eps)
    normalized_scan += (2.0*tissue_prob_list[1])/(3.0*(normalizer + eps))
    normalized_scan += tissue_prob_list[2]/(3.0*(normalizer + eps))

    normalized_scan = 3.0*normalized_scan
    # Create cerebrum mask
    mask_cereb = np.zeros_like(normalizer)
    for left, right in zip(mask_dict['Left_Cerebrum'], mask_dict['Right_Cerebrum']):
        mask_cereb += 1*(maxInds == FreeSurferLabels[left])
        mask_cereb += 2*(maxInds == FreeSurferLabels[right])

    for left, right in zip(mask_dict['Left_Cerebellum'], mask_dict['Right_Cerebellum']):
        mask_cereb += 3*(maxInds == FreeSurferLabels[left])
        mask_cereb += 4*(maxInds == FreeSurferLabels[right])

    mask_cereb = mask_cereb.astype(np.uint8)
    # Create subcortical mask
    mask_subcortical = np.zeros_like(normalizer)
    for struct in mask_dict['Sub_cortical']:
        mask_subcortical += 1*(maxInds == FreeSurferLabels[struct])

    # Make boolean
    mask_subcortical = mask_subcortical > 0

    # # Create parahippo mask
    # mask_parahippo = np.zeros_like(normalizer)
    # for struct in mask_dict['Parahippo']:
    #     mask_parahippo += 1*(maxInds == FreeSurferLabels[struct])

    # # Make boolean
    # mask_parahippo = mask_parahippo > 0

    # Create left/right mask by interpolating the cereb mask into the background
    mask = 2*(mask_cereb == 1) + 2*(mask_cereb == 3) + 1*(mask_cereb == 2) + 1*(mask_cereb == 4)
    # cat_vbdist takes in a voxel size as well, need to probably use that too
    _, _, mask_hemi = cat_vbdist(mask)
    mask_hemi = mask_hemi > 1
    mask_hemi = mask_hemi.astype(np.uint8)

    # return [normalized_scan, mask_cereb, mask_subcortical,
    #         mask_parahippo, mask_hemi]
    return [normalized_scan, mask_cereb, mask_subcortical, mask_hemi]


from djangobackend.settings.base import *

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '47(6^lv2h6lo*2cfr#v02021$8p(wvwgivq9+=3f3r5=hbsu'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["backend"]


import sys
n=int(sys.stdin.readline())
li=[]
cnt={}
avg=0
for _ in range(n):
    num=int(sys.stdin.readline())
    avg+=num
    li.append(num)
    if num not in cnt:
        cnt[num]=1
    else:
        cnt[num]+=1

many=max(list(cnt.values()))
many_li=[key for key in cnt if cnt[key]==many]
li.sort()
many_li.sort()

print(round(avg/n))
print(li[(n-1)//2])
if len(many_li)==1:
    print(many_li[0])
else:
    print(many_li[1])
print(li[-1]-li[0])


def replace_vowels(chars):
    """Given list of chars, return a new copy, but with vowels replaced by '*'."""

    vowels = set(['a','e','i','o','u'])

    new_list = []

    for char in chars:
        if char in vowels:
            char = '*'
        new_list.append(char)

    return new_list


from django.apps import apps
import json

class Metadata:
    """

    """
    def __init__(self, parent, metadata=None):
        self.parent = parent
        self.metadata = json.loads(metadata) if metadata else {}

    def get_metadata(self, metadata_type, names=None):
        metadata_model = apps.get_model("vb_django", metadata_type)
        if names:
            metadata = []
            for n in names:
                m = metadata_model.objects.filter(base_id=self.parent, name=n).values()
                if len(m) > 0:
                    metadata.append(m[0])
        else:
            metadata = metadata_model.objects.filter(base_id=self.parent).values()
        meta = {}
        for m in metadata:
            meta[m['name']] = m['value']
        return meta

    def set_metadata(self, metadata_type):
        metadata_model = apps.get_model("vb_django", metadata_type)
        for k, v in self.metadata.items():
            if type(v) == object:
                v = json.dumps(v)
            elif type(v) != str:
                v = str(v)
            current_metadata = metadata_model.objects.filter(base_id=self.parent, name=k)
            if len(current_metadata) == 0:
                meta = metadata_model.objects.create(base_id=self.parent, name=k, value=v)
                meta.save()
            else:
                current_metadata[0].value = v
                current_metadata[0].save()
        meta = self.get_metadata(metadata_type)
        return meta

    def delete_metadata(self, metadata_type, names=None):
        metadata_model = apps.get_model("vb_django", metadata_type)
        if names:
            metadata = []
            for n in names:
                metadata.append(metadata_model.objects.filter(base_id=self.parent, name=n))
        else:
            metadata = metadata_model.objects.filter(base_id=self.parent)
        for m in metadata:
            m.delete()


from design_baselines.data import StaticGraphTask
from design_baselines.logger import Logger
from design_baselines.utils import spearman
from design_baselines.utils import soft_noise, cont_noise, disc_noise
from design_baselines.safeweight_latent.trainers import Trainer
from design_baselines.safeweight_latent.nets import DoubleheadModel, SingleheadModel, NemoModel
from collections import defaultdict
import tensorflow as tf
import numpy as np
from tensorflow_probability import distributions as tfpd

from design_baselines.cbas.nets import Encoder
from design_baselines.cbas.nets import DiscreteDecoder
from design_baselines.cbas.nets import ContinuousDecoder
from design_baselines.cbas.trainers import WeightedVAE
import os

def normalize_dataset(x, y, normalize_xs, normalize_ys, is_discrete):
    if normalize_ys:
        # compute normalization statistics for the score
        mu_y = np.mean(y, axis=0, keepdims=True).astype(np.float32)
        y = y - mu_y
        st_y = np.std(y, axis=0, keepdims=True).astype(np.float32).clip(1e-6, 1e9)
        y = y / st_y

    else:
        # compute normalization statistics for the score
        mu_y = np.zeros_like(y[:1])
        st_y = np.ones_like(y[:1])

    if normalize_xs:
        # compute normalization statistics for the data vectors
        mu_x = np.mean(x, axis=0, keepdims=True).astype(np.float32)
        x = x - mu_x
        st_x = np.std(x, axis=0, keepdims=True).astype(np.float32).clip(1e-6, 1e9)
        st_x = np.where(np.equal(st_x, 0), 1, st_x)
        x = x / st_x

    else:
        # compute normalization statistics for the score
        mu_x = np.zeros_like(x[:1])
        st_x = np.ones_like(x[:1])

    return (x, mu_x, st_x), (y, mu_y, st_y)

def safeweight_latent(config):
    # create the training task and logger
    logger = Logger(config["logging_dir"])
    task = StaticGraphTask(config["task"], **config["task_kwargs"])

    task_x = task.x
    task_y = task.y

    (task_x, mu_x, st_x), (task_y, mu_y, st_y) = normalize_dataset(
        x=task_x,
        y=task_y,
        normalize_xs=config["normalize_xs"],
        normalize_ys=config["normalize_ys"],
        is_discrete=config["is_discrete"]
    )

    # record the inputs shape of the forward model
    input_shape = list(task.input_shape)

    max_y = np.amax(task_y)
    indices = tf.math.top_k(task_y[:, 0], k=config["sol_x_samples"])[1]

    sol_x =  tf.gather(task_x, indices, axis=0)
    sol_y = tf.gather(task_y, indices, axis=0)

    ### Warmup
    train_data, validate_data = task.build(
        x=task_x, y=task_y, batch_size=config["batch_size"], val_size=config["val_size"]
    )

    sol_x_opt = tf.keras.optimizers.Adam(learning_rate=config["sol_x_lr"])
    perturb_fn = lambda x: cont_noise(x, noise_std=config["continuous_noise_std"])

    model_class = {
        "doublehead": DoubleheadModel,
        "singlehead": SingleheadModel,
        "nemo": NemoModel,
    }.get(config["model_class"])

    model = model_class(
        input_shape=[32],
        hidden=config["hidden_size"],
    )
    temp_model = model_class(
        input_shape=[32],
        hidden=config["hidden_size"],
    )

    decoder = DiscreteDecoder \
        if config['is_discrete'] else ContinuousDecoder

    # build the encoder and decoder distribution and the p model
    p_encoder = Encoder(task.input_shape,
                        config['latent_size'],
                        hidden=256)
    p_decoder = decoder(task.input_shape,
                        config['latent_size'],
                        hidden=256)
    p_vae = WeightedVAE(p_encoder,
                        p_decoder,
                        vae_optim=tf.keras.optimizers.Adam,
                        vae_lr=config['vae_lr'],
                        vae_beta=config['vae_beta'])

    # create a manager for saving algorithms state to the disk
    p_manager = tf.train.CheckpointManager(
        tf.train.Checkpoint(**p_vae.get_saveables()),
        os.path.join(config['logging_dir'], 'p_vae'), 1)

    # train the initial vae fit to the original data distribution
    p_manager.restore_or_initialize()
    p_vae.launch(train_data,
                 validate_data,
                 logger,
                 config['offline_epochs'])

    max_y = np.amax(task_y)
    indices = tf.math.top_k(task_y[:, 0], k=config["sol_x_samples"])[1]

    sol_x_opt = tf.keras.optimizers.Adam(learning_rate=config["sol_x_lr"])
    perturb_fn = lambda x: cont_noise(x, noise_std=config["continuous_noise_std"])

    #model_opt = tfa.optimizers.AdamW(learning_rate=config["model_lr"], weight_decay=config["wd"])
    model_opt = tf.keras.optimizers.Adam(learning_rate=config["model_lr"])

    task_d = p_encoder.get_distribution(task_x, training=False)
    task_x = task_d.sample().numpy()
    task_y = task.y

    for _ in range(9):
        np.append(task_x, task_d.sample().numpy())
        np.append(task_y, task.y)

    # renormalize
    (task_x, mu_x, st_x), (task_y, mu_y, st_y) = normalize_dataset(
        x=task_x,
        y=task_y,
        normalize_xs=True,
        normalize_ys=True,
        is_discrete=config["is_discrete"]
    )

    train_data, validate_data = task.build(
        x=task_x, y=task_y, batch_size=config["batch_size"], val_size=config["val_size"]
    )

    sol_x =  tf.gather(task_x, indices, axis=0)
    sol_y = tf.gather(task_y, indices, axis=0)

    trainer = Trainer(
        model=model,
        model_opt=model_opt,
        perturb_fn=perturb_fn,
        is_discrete=config["is_discrete"],
        sol_x=sol_x,
        sol_y=sol_y,
        sol_x_opt=sol_x_opt,
        coef_pessimism=config["coef_pessimism"],
        coef_stddev=config["coef_stddev"],
        temp_model=temp_model,
        steps_per_update=config["steps_per_update"],
        encoder=p_encoder,
        inner_lr=config["inner_lr"],
        region=config["region"],
        max_y=max_y,
        lr=config["sol_x_lr"],
        alpha=config["alpha"]
        )

    for epoch in range(config["warmup_epochs"]):
        statistics = defaultdict(list)
        for x, y in train_data:
            for name, tsr in trainer.train_step(x, y).items():
                statistics[f"warmup/train/{name}"].append(tsr)

        for x, y in validate_data:
            for name, tsr in trainer.validate_step(x, y).items():
                statistics[f"warmup/validate/{name}"].append(tsr)

        for name, tsrs in statistics.items():
            logger.record(name, tf.reduce_mean(tf.concat(tsrs, axis=0)), epoch)

    model.save('./model/')
    ### Main training
    step = 0
    update = 0
    while update < config["updates"]:
        trainer.init_step()
        train_statistics = defaultdict(list)
        statistics = trainer.fix_step()
        for name, tsr in statistics.items():
            logger.record(f"fix/{name}", tsr, update)

        statistics = trainer.update_step()
        for name, tsr in statistics.items():
            logger.record(f"update/{name}", tsr, update)

        if (update + 1) % config["score_freq"] == 0:
            sol_z = trainer.get_sol_x()
            d = p_decoder.get_distribution(sol_z * st_x + mu_x, training=False)

            logits = d.logits
            maxlogit = tf.math.argmax(logits, axis=-1)
            maxlogit = tf.one_hot(maxlogit, input_shape[-1], axis=-1)
            score = task.score(maxlogit)

            logger.record(f"update/score", score, update, percentile=True,
                molecule=(config["task"]=="MoleculeActivity-v0"))

            sample_score = task.score(d.sample())
            logger.record(f"update/sample_score", sample_score, update, percentile=True)

        update += 1
        if update + 1 > config["updates"]:
            break


# -*- coding: utf-8 -*-
"""
language.py
Author: Gilson, K.
"""

from typing import Any

from .mixin import JSONableMixin

class Language(JSONableMixin):
    """Language: inherit from 'JSONableMixin'.

    Attributes:
        name (str): language name.
        irl_scale (str, optional): IRL Scale level of competence. Defaults to None.
        cefr_level (str, optional): CEFR Level of competence. Defaults to None.
    """

    def __init__(
        self, name: str, irl_scale: str = None, cefr_level: str = None
    ) -> None:
        """Initialize the Language class instance.

        Args:
            name (str): language name.
            irl_scale (str, optional): IRL Scale level of competence. Defaults to None.
            cefr_level (str, optional): CEFR Level of competence. Defaults to None.
        """
        self.name = name
        self.irl_scale = irl_scale
        self.cefr_level = cefr_level

    def __setattr__(self, name: str, value: Any) -> None:
        """Validate the attributes of the Language class.

        Args:
            name (str): name of the attribute.
            value (Any): value of the attribute.

        Raises:
            TypeError: if a value is not a str.
            AttributeError: if the irl_scale value is unknown.
            AttributeError: if the cefr_level value is unknown.
        """
        # Validation
        if value is not None and not isinstance(value, str):
            raise TypeError(f"'{name}' expect a str.")

        if name == "irl_scale" and value is not None:
            irl_list = [
                "No Proficiency",
                "Elementary Proficiency",
                "Limited Working Proficiency",
                "Professional Working Proficiency",
                "Full Professional Proficiency",
                "Bilingual",
                "Native",
            ]
            if value.title() not in irl_list:
                raise AttributeError(
                    f"IRL Scale '{value}' unknown.\nShould be part of list:\n{irl_list}"
                )
        elif name == "cefr_level" and value is not None:
            cefr_list = [
                "A1",
                "A2",
                "B1",
                "B2",
                "C1",
                "C2",
            ]
            if value.upper() not in cefr_list:
                raise AttributeError(
                    f"CEFR Level '{value}' unknown.\nShould be part of list:\n{cefr_list}"
                )

        # Set
        if value is None:
            self.__dict__[name] = value
        else:
            if name == "irl_scale":
                self.__dict__[name] = value.title()
            elif name == "cefr_level":
                self.__dict__[name] = value.upper()
            else:
                self.__dict__[name] = value


input = open('input.txt').read()
test = '''1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581'''
t = open('test.txt').read()

def parse_input(inp: str) -> list[list[int]]:
    return list(map(lambda l: list(map(lambda r: int(r), list(l))), inp.split('\n')))

def scale_y(caves: list[list[int]]) -> list[list[int]]:
    c = caves
    le = len(caves)
    new = [*c]
    for _ in range(4):
        for o in range(le):
            r = c[o]
            t = [n+1 if n + 1 <= 9 else abs(9 - (n+1)) for n in r]
            c[o] = t

        new.extend(c)

    caves = new

    return caves

def scale_x(caves: list[list[int]]) -> list[list[int]]:
    for i in range(len(caves)):
        r = caves[i]
        l = []
        for p in range(5):
            l.extend([n+p if n + p <= 9 else abs(9 - (n+p)) for n in r])

        caves[i] = l

    return caves

def get_adjacent(point: tuple, i_max: int, j_max: int) -> list[tuple]:
    adj: list[tuple] = []
    i, j = point

    if j < j_max - 1:
        adj.append((i, j+1))
    if j > 0:
        adj.append((i, j-1))
    if i < i_max - 1:
        adj.append((i+1, j))
    if i > 0:
        adj.append((i-1, j))

    return adj

def find_path(caves: list[list[int]]):
    paths: dict[tuple, int] = {(0,0):0}
    final_map: dict[tuple, int] = {(0,0):0}
    end = (len(caves)-1, len(caves[0])-1)

    while(len(paths) > 0 ):
        point = min(paths.keys(), key=(lambda k: paths[k]))
        paths.pop(point)

        for p in get_adjacent(point, len(caves), len(caves[0])):
            if p not in final_map:
                i, j = p
                risk = final_map[point] + caves[i][j]
                final_map[p] = risk

                if p == end:
                    break

                paths[p] = risk

    print(final_map[end])

def sollution_1():
    caves = parse_input(input)
    find_path(caves)

def sollution_2():
    caves = parse_input(input)
    new_caves = scale_x(caves)
    new_caves = scale_y(new_caves)
    find_path(new_caves)

if __name__ == "__main__":
    sollution_1()
    sollution_2()


from nsk import *
from cable_operators import *
from ip_operators import *
import  subprocess

subprocess.Popen(['python3', 'nsk.py'])
subprocess.Popen(['python3', 'cable_operators.py'])
subprocess.Popen(['python3', 'ip_operators.py'])

lines =  (('{}\n'*len(nsk)).format(*nsk)),(('{}\n'*len(cab)).format(*cab)),(('{}\n'*len(ip)).format(*ip))
with open(r"metric", "w") as file:
    for  line in lines:
        file.write(line)

with open("metric", 'r+') as f:
    text = ''.join([line.replace(")", "}")  for line in f.readlines()])
    f.seek(0)
    f.write(text)

with open("metric", 'r+') as f:
    text = ''.join([line.replace("(", "{")  for line in f.readlines()])
    f.seek(0)
    f.write(text)


"""
There is some tool which sends request to the switch/router.
When device take this request it sends the file (e.g. configuration) to the TFTP as a response.
Server is needed to confirm and to prove vulnerability.

"""
import logging
import socket
import os
import select
import time
from threading import Event, Lock

from os.path import isfile

log = logging.getLogger('aucote.tftp')

class TFTPError(Exception):
    """
    Base class for TFTP server related exceptions
    """
    def __init__(self, *args, **kwargs):
        super(TFTPError, self).__init__(*args, **kwargs)

class TFTPTimeoutError(TFTPError):
    def __init__(self, address, *args, **kwargs):
        self.address = address
        self.msg = 'Timeout Error while waiting for file from {}'.format(address)
        super(TFTPError, self).__init__(self.msg, *args, **kwargs)

class TFTPAlreadyExists(TFTPError):
    def __init__(self, address, *args, **kwargs):
        self.address = address
        self.msg = 'Already listening on file from {}. Try again later'.format(address)
        super(TFTPError, self).__init__(self.msg, *args, **kwargs)

class TFTPNotFound(TFTPError):
    def __init__(self, address, *args, **kwargs):
        self.address = address
        self.msg = 'Cannot find request for {}. Make sure anything is waiting on it'.format(address)
        super(TFTPError, self).__init__(self.msg, *args, **kwargs)

class TFTPMaxSizeExceeded(TFTPError):
    def __init__(self, address, *args, **kwargs):
        self.address = address
        self.msg = 'Maximum file size exceeded for {}'.format(address)
        super(TFTPError, self).__init__(self.msg, *args, **kwargs)

class TFTP:
    """
    Simple TFTP server for obtaining vulnerable data by scripts with TFTP protocol (RFC 1350)

    Server processes only request from whitelisted addresses.
    An address can be whitelisted by `register_address` function.
    Address can be registered only once till the file is obtained or TimeoutError occurs

    If file was sent from specific address, it can be obtain by `get_file`.
    The file should be removed by consumer
    """

    GET_BYTE = 1
    PUT_BYTE = 2

    MAX_BLKSIZE = 0x10000
    MAX_FILE_SIZE = 0x100000  # Max file size in bytes

    OPCODE_LEN = BLOCK_NUMBER_LEN = 2
    PREFIX_LEN = OPCODE_LEN + BLOCK_NUMBER_LEN

    DEF_BLKSIZE = 512  # size of data block in TFTP-packet

    def __init__(self, ip, port, timeout, data_dir, min_port, max_port):
        self.ip = ip
        self.port = port
        self._timeout = timeout
        self._dir = data_dir
        self._socket = None
        self._min_port = min_port
        self._max_port = max_port
        self._current_receive_port = self._min_port
        self._epoll = select.epoll()
        self._receivers = {}
        self._files = {}
        self._stop = False
        self._lock = Lock()

    def register_address(self, address, filename, timeout=120):
        """
        Ask server to listen for file from given address. Raises Exception if any script is already waiting on file.

        To get path of received file, using of get_file is required

        """
        event = Event()

        with self._lock:
            if address in self._files:
                raise TFTPAlreadyExists(address)

            self._files[address] = {
                'event': event,
                'time': int(time.time()) + timeout,
                'exception': None,
                'size': 0,
                'filename': filename,
                'path': '{}/{}'.format(self._dir, filename)
            }

            log.debug('Add %s to the TFTP server', address)

        return event

    def get_file(self, address):
        """
        Get file from specific address if available. If file wasn't downloaded within timeout given to `add_file`
        the TimeoutError is raise

        """
        with self._lock:
            if address not in self._files:
                raise TFTPNotFound(address)

        self._lock.acquire()

        event = self._files[address]['event']

        while not event.is_set():
            self._lock.release()
            time.sleep(1)
            self._lock.acquire()

        return_value = self._files[address].get('path')
        self._lock.release()

        with self._lock:
            try:
                if self._files[address]['exception'] is not None:
                    raise self._files[address]['exception']
                return return_value
            finally:
                del self._files[address]

    @property
    def next_receive_port(self):
        """
        Get port number to obtain data from server

        """
        self._current_receive_port += 1
        if self._current_receive_port > self._max_port:
            self._current_receive_port = self._min_port

        return self._current_receive_port

    def start(self):
        """
        Start socket

        """
        self._socket = self._open_port(self.ip, self.port)

        os.makedirs(self._dir, exist_ok=True)

    def listen(self):
        """
        Listen for requests using epoll

        """
        self._epoll.register(self._socket, select.EPOLLIN)

        while True:
            events = self._epoll.poll(1)

            for fd, event in events:
                if self._socket.fileno() == fd:
                    if event & select.EPOLLIN:
                        self.handle_new_client()
                else:
                    self.receive_file(fd)

            self.check_timeouts()

            if self._stop:
                self._epoll.close()
                break

    def handle_new_client(self):
        """
        Handle connection on main port

        """
        try:
            buffer, (address, port) = self._socket.recvfrom(self.MAX_BLKSIZE)
        except OSError:
            # Dont do anything in case of socket timeout/error
            log.warning("Error while obtaining data by TFTP server")
            return

        with self._lock:
            if address not in self._files:
                # Unexpected packet, do nothing
                log.warning("TFTP server got packet from unexpected address: %s", address)
                return

        log.debug('Connection from %s:%s', address, port)

        message_type = buffer[1]

        if message_type == self.GET_BYTE:
            # Reading files is unsupported
            return
        elif message_type == self.PUT_BYTE:
            ss = buffer[self.OPCODE_LEN:].split(b'\0')
            filename = ss[0].decode('utf-8')

            receiver = self._open_port('', self.next_receive_port)

            # Send ACK
            response = b'\x00\x04\x00\x00'

            receiver.sendto(response, (address, port))
            self._epoll.register(receiver.fileno())
            with self._lock:
                self._files[address]['receiver'] = receiver
            self._receivers[receiver.fileno()] = receiver
        else:
            # Ignore request
            return

    def receive_file(self, fd):
        """
        Receive data on given fd. Append it to configured file
        """
        receiver = self._receivers[fd]
        buffer, (remote_address, remote_port) = receiver.recvfrom(self.MAX_BLKSIZE)

        with self._lock:
            path = self._files[remote_address]['path']

            log.debug("Receiving data from %s", remote_address)

            self._files[remote_address]['size'] += len(buffer[self.PREFIX_LEN:])

            if self._files[remote_address]['size'] > self.MAX_FILE_SIZE:
                # Too big file from client, close connection
                self._files[remote_address]['exception'] = TFTPMaxSizeExceeded(remote_address)
                self._close_receiver(fd, remote_address)
                os.remove(path)
                return

        with open(path, 'ba') as f:
            f.write(buffer[self.PREFIX_LEN:])

            # send ACK
            response = b'\x00\x04' + buffer[self.OPCODE_LEN:self.PREFIX_LEN]
            receiver.sendto(response, (remote_address, remote_port))

            if len(buffer[self.PREFIX_LEN:]) < self.DEF_BLKSIZE:
                self._close_receiver(fd, remote_address)

    def _close_receiver(self, fd, remote_address):
        """
        Close receiver basing on fd and remote_address

        """
        log.debug('Closing receiver')
        self._epoll.unregister(fd)
        self._receivers[fd].close()
        del self._receivers[fd]
        with self._lock:
            self._files[remote_address]['event'].set()

    def check_timeouts(self):
        """
        Check timeouts and clean obsolete data (used for process requests and save file)
        """
        current_time = time.time()

        with self._lock:
            for address, details in self._files.items():
                if details['event'].is_set():
                    continue

                if details['time'] > current_time:
                    continue

                if 'receiver' in details:
                    del self._receivers[details['receiver'].fileno()]
                    details['receiver'].close()

                try:
                    os.remove(details['path'])
                except:
                    pass

                details['exception'] = TFTPTimeoutError(address)
                details['event'].set()

    def stop(self):
        """
        Close and unregister all connections
        """
        for receiver in self._receivers.values():
            self._epoll.unregister(receiver.fileno())
            receiver.close()

        if self._socket is not None:
            self._epoll.unregister(self._socket.fileno())
            self._socket.close()

        self._stop = True

    def _open_port(self, host, port):
        log.warning('Opening port (%s, %s)', host, port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(self._timeout)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((host, port))
        return sock

    def monitor_filesystem(self):
        """
        Monitor for filesystem in case when external TFTP server is used
        """
        while not self._stop:
            with self._lock:
                for address, details in self._files.items():
                    try:
                        if isfile(details['path']):
                            details['event'].set()
                    finally:
                        pass

            self.check_timeouts()
            time.sleep(1)


from django.db import models
import uuid

from django.db.models.deletion import DO_NOTHING
from django.db.models.fields import DateTimeField, DecimalField
from users.models import User
from cloudinary.models import CloudinaryField
# Create your models here.
class Account_type(models.Model):
    id = models.UUIDField(
        primary_key=True,
        editable=False,
        default=uuid.uuid4
    )
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Icon(models.Model):
    id = models.UUIDField(
        primary_key=True,
        editable=False,
        default=uuid.uuid4
    )
    name = models.CharField(max_length=200)
    image = CloudinaryField('iamge')

    def __str__(self):
        return self.name

class Account(models.Model):
    id = models.UUIDField(
        primary_key=True,
        editable=False,
        default=uuid.uuid4
    )
    name = models.CharField(max_length=200)
    amount = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    account_type = models.ForeignKey(
        Account_type,
        on_delete=DO_NOTHING,
        related_name="accounts"
    )
    user = models.ForeignKey(
        User,
        on_delete=DO_NOTHING,
        related_name="accounts"
    )
    color = models.CharField(max_length=200)
    icon = models.ForeignKey(
        Icon,
        on_delete=DO_NOTHING,
        related_name='accounts'
    )

    def serialize(self):
        return {
            "id" : self.id,
            "name": self.name,
            "amount" : self.amount,
            "account_type" : {
                "name" : self.account_type.name
            },
            "color": self.color,
            "icon": str(self.icon.image.url)
        }

    def __str__(self):
        return self.name

class Transaction_type(models.Model):
    id = models.UUIDField(
        primary_key=True,
        editable=False,
        default=uuid.uuid4
    )
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Transaction(models.Model):
    id = models.UUIDField(
        primary_key=True,
        editable=False,
        default=uuid.uuid4
    )
    name = models.CharField(max_length=200)
    account = models.ForeignKey(
        Account,
        on_delete=DO_NOTHING,
        related_name="transactions"
    )
    transaction_type = models.ForeignKey(
        Transaction_type,
        on_delete=DO_NOTHING,
        related_name="transactions"
    )
    amount = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    date_time = models.DateTimeField(auto_now=False, auto_now_add=False)

    def serialize(self):
        return {
            "id" : self.id,
            "name": self.name,
            "amount" : self.amount,
            "transaction_type" : {
                "name" : self.transaction_type.name
            },
            "account" : {
                "name" : self.account.name
            },
            'date_time' : self.date_time
        }


from django.shortcuts import render
from polls.models import Poll, Alert
from django.db.models import Q

def index(request):
    if not request.user.is_authenticated:
        return render(request, "welcome.html")

    query = request.GET.get("q")
    polls = Poll.objects.all()
    alerts = Alert.objects.filter(is_active=True)

    if query:
        polls = polls.filter(
            Q(title__icontains=query) |
            Q(explanation__icontains=query)
        ).distinct()

    context = {
        "polls": polls,
        "alerts": alerts,
    }

    return render(request, "index.html", context=context)


import requests
import json

def test_insecure_plugin_design(base_url, api_key, plugin_endpoint):
    # Lista de payloads que podrían explotar un diseño inseguro en plugins
    malicious_payloads = [
        "<script>alert('XSS')</script>",
        "'; DROP TABLE users;--",
        "admin' OR '1'='1",
        "| ls -al",
        "eval('malicious code')"
    ]

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    for payload in malicious_payloads:
        # Configurar la petición para el modelo de lenguaje y el plugin
        plugin_data = json.dumps({
            "plugin_input": payload,
        })

        response = requests.post(
            f"{base_url}/{plugin_endpoint}",
            headers=headers,
            data=plugin_data
        )

        # Revisar la respuesta del plugin
        if response.status_code == 200:
            content = json.loads(response.content)
            output = content.get("plugin_output", "")
            if output:
                print(f"Payload: {payload}")
                print(f"Plugin Output: {output}\n")
        else:
            print(f"Received non-200 status code: {response.status_code} for payload: {payload}")

# Ejemplo de uso
# base_url = "https://api.example.com/v1"
# api_key = "your_api_key_here"
# plugin_endpoint = "insecure_plugin"
# test_insecure_plugin_design(base_url, api_key, plugin_endpoint)


#
# @lc app=leetcode id=1 lang=python3
#
# [1] Two Sum
#

# @lc code=start
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map= {}

        for i,n in enumerate(nums):
            if n in map:
                return [i,map.get(n)]
            map[target-n]=i
        return

# @lc code=end


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from urllib.parse import quote
import time
import os
from urllib.request import urlretrieve

url = 'https://mp.weixin.qq.com/mp/homepage?__biz=MzI0MTA2MDk3MA==&hid=28&sn=a9d5bea6dc313eee96a1dd79ab9d5f10&scene=18&devicetype=android-29&version=27000f3d&lang=zh_CN&nettype=WIFI&ascene=7&session_us=gh_f2631d699e12&pass_ticket=4grhxozRhAev9IGqdIFiuiTbY8jJbL4C9zQQ20RQLsW%2BeKOlhG1fjP4%2BE7OcYMoQ&wx_header=1'

opt = Options()
opt.add_argument('--no-sandbox')                # 解决DevToolsActivePort文件不存在的报错
opt.add_argument('--disable-gpu')               # 谷歌文档提到需要加上这个属性来规避bug
opt.add_argument('blink-settings=imagesEnabled=false')      # 不加载图片，提升运行速度
opt.add_argument('--headless')                  # 浏览器不提供可视化界面。Linux下如果系统不支持可视化不加这条会启动失败

browser = webdriver.Chrome(options=opt)
sub_browser = webdriver.Chrome(options=opt)
img_browser = webdriver.Chrome(options=opt)

def get_gage(url):
    try:
        browser.get(url)
        # 获取页面初始高度
        js = "return action=document.body.scrollHeight"
        height = browser.execute_script(js)
        # 将滚动条调整至页面底部
        browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
        #定义初始时间戳（秒）
        t1 = int(time.time())
        # 重试次数
        num=0

        while True:
	        # 获取当前时间戳（秒）
            t2 = int(time.time())
            # 判断时间初始时间戳和当前时间戳相差是否大于2秒，小于2秒则下拉滚动条
            if t2-t1 < 2:
                new_height = browser.execute_script(js)
                if new_height > height :
                    browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
                    # 重置初始页面高度
                    height = new_height
                    # 重置初始时间戳，重新计时
                    t1 = int(time.time())
            elif num < 3:                        # 当超过2秒页面高度仍然没有更新时，进入重试逻辑，重试3次，每次等待2秒
                num = num+1
            else:    # 超时并超过重试次数，程序结束跳出循环，并认为页面已经加载完毕！
                print("滚动条已经处于页面最下方！")
                break

        # 获取路径和标题
        links = browser.find_elements_by_class_name('js_post')
        titles = browser.find_elements_by_class_name('js_title')

        for i in range(len(links)):
            sub_url = links[i].get_attribute('href')
            title = titles[i].text
            title = title_pre(title)
            # 创建文件夹
            if not os.path.exists('./图片集/'+title):
                os.mkdir('./图片集/'+title)
            get_sub_page(sub_url, title)

        print("图片下载完成！")
    except Exception as e:
        print(e)

def get_sub_page(url, title):
    try:
        sub_browser.get(url)
        tables = sub_browser.find_elements_by_xpath('//td/a')
        tables_2 = sub_browser.find_elements_by_xpath('//td/p/a')
        for link in tables:
            sub_url = link.get_attribute('href')
            get_imgs(sub_url, title)
        for link in tables_2:
            sub_url = link.get_attribute('href')
            get_imgs(sub_url, title)
    except Exception as e:
        print(e)

def get_imgs(url, title):
    try:
        img_browser.get(url)
        sub_title = img_browser.find_element_by_id('activity-name').text
        print('正在下载：'+ sub_title)
        sub_title = title_pre(sub_title)
        # 创建子文件夹
        if not os.path.exists('./图片集/'+title+'/'+sub_title):
            os.mkdir('./图片集/'+title+'/'+sub_title)
            # 匹配图片
            imgs = img_browser.find_elements_by_xpath('//td/p/img')
            imgs_2 = img_browser.find_elements_by_xpath('//td/img')
            index = 0
            for i in range(len(imgs)):
                # 获取图片路径
                img_url = imgs[i].get_attribute('data-src')
                img_url += '&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1'
                # 保存到本地
                urlretrieve(img_url, './图片集/'+title+'/'+sub_title+'/'+str(index)+'.png')
                index += 1
            for i in range(len(imgs_2)):
                # 获取图片路径
                img_url = imgs_2[i].get_attribute('data-src')
                img_url += '&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1'
                # 保存到本地
                urlretrieve(img_url, './图片集/'+title+'/'+sub_title+'/'+str(index)+'.png')
                index += 1
        else:
            return
    except Exception as e:
        print(e)

# 替换文件名中不能出现的字符
def title_pre(title):
    ng_word = ['\\', '/', ':', '：', '*', '?', '？', '\"', '“', '”', '<', '>', '|',]
    for word in ng_word:
        title = title.replace(word, ' ')
    title = title.rstrip()
    return title

get_gage(url)


class Solution(object):
    def minDominoRotations(self, tops, bottoms):
        """
        :type tops: List[int]
        :type bottoms: List[int]
        """

        if len(tops) != len(bottoms): return -1
        if len(tops) == 0: return 0

        for cand in set([tops[0], bottoms[0]]):  # Candidates.
            count_top = count_bottom = 0

            for i in range(len(tops)):
                if cand not in (tops[i], bottoms[i]):
                    break

                count_top += int(cand != bottoms[i])
                count_bottom += int(cand != tops[i])

            else:
                return min(count_top, count_bottom)

        return -1


from discord.ext import commands

class Owner(commands.Cog):
    "Just for Djarrah's eyes"

    def __init__(self, bot):
        self.bot = bot

    @commands.command(help="unloads a cog", hidden=True, aliases=["unload"])
    @commands.is_owner()
    async def unload_cog(self, ctx, cogname: str):
        try:
            cog = "cogs." + cogname
            self.bot.unload_extension(cog)
            await ctx.send(f"{cogname} commands disabled")
            print(f"{cogname} commands disabled")
        except Exception as e:
            await ctx.send(f"**`ERROR:`** {type(e).__name__} - {e}")

    @commands.command(help="loads a cog", hidden=True, aliases=["load"])
    @commands.is_owner()
    async def load_cog(self, ctx, cogname: str):
        try:
            cog = "cogs." + cogname
            self.bot.load_extension(cog)
            await ctx.send(f"{cogname} commands enabled")
            print(f"{cogname} commands enabled")
        except Exception as e:
            await ctx.send(f"**`ERROR:`** {type(e).__name__} - {e}")

    @commands.command(help="reloads a cog", hidden=True, aliases=["reload"])
    @commands.is_owner()
    async def reload_cog(self, ctx, cogname: str):
        try:
            cog = "cogs." + cogname
            self.bot.unload_extension(cog)
            self.bot.load_extension(cog)
            await ctx.send(f"{cogname} commands reloaded")
            print(f"{cogname} commands reloaded")
        except Exception as e:
            await ctx.send(f"**`ERROR:`** {type(e).__name__} - {e}")

def setup(bot):
    bot.add_cog(Owner(bot))