import datetime
import json
import os
import random
import string
import sys
import time
import urllib.request

os.system("title WARP-PLUS-CLOUDFLARE By Tran Thai Tuan Anh")
os.system('cls' if os.name == 'nt' else 'clear')
print ("[+] About script: With this script, you can getting unlimited GB on Warp+")
print ("[+] This script coded by Tran Thai Tuan Anh")
print ("----------")
referrer = input("[#] Enter your WARP+ ID:")
def genString(stringLength):
	try:
		letters = string.ascii_letters + string.digits
		return ''.join(random.choice(letters) for i in range(stringLength))
	except Exception as error:
		print(error)
def digitString(stringLength):
	try:
		digit = string.digits
		return ''.join((random.choice(digit) for i in range(stringLength)))
	except Exception as error:
		print(error)
url = f'https://api.cloudflareclient.com/v0a{digitString(3)}/reg'
def run():
	try:
		install_id = genString(22)
		body = {"key": "{}=".format(genString(43)),
				"install_id": install_id,
				"fcm_token": "{}:APA91b{}".format(install_id, genString(134)),
				"referrer": referrer,
				"warp_enabled": False,
				"tos": datetime.datetime.now().isoformat()[:-3] + "+02:00",
				"type": "Android",
				"locale": "es_ES"}
		data = json.dumps(body).encode('utf8')
		headers = {'Content-Type': 'application/json; charset=UTF-8',
					'Host': 'api.cloudflareclient.com',
					'Connection': 'Keep-Alive',
					'Accept-Encoding': 'gzip',
					'User-Agent': 'okhttp/3.12.1'
					}
		req         = urllib.request.Request(url, data, headers)
		response    = urllib.request.urlopen(req)
		status_code = response.getcode()
		return status_code
	except Exception as error:
		print(error)

good = 0
bad = 0
while True:
	result = run()
	if result == 200:
		good += 1
		os.system('cls' if os.name == 'nt' else 'clear')
		print("WARP-PLUS-CLOUDFLARE (script) by Tran Thai Tuan Anh")
		print("")
		animation = ["10%","20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]
		for i in range(len(animation)):
			time.sleep(0.5)
			sys.stdout.write("\rprocessing..." + animation[i % len(animation)])
			sys.stdout.flush()
		os.system('cls' if os.name == 'nt' else 'clear')
		print("WARP-PLUS-CLOUDFLARE (script) by Tran Thai Tuan Anh")
		print(f"\n[-] ID: {referrer}")
		print(f"[-] {good} GB has been successfully added to your account.")
		print(f"[-] Total: {good} Good {bad} Bad")
		print("[-] After 18 seconds, a new request will be sent.")
		time.sleep(18)
	else:
		bad += 1
		os.system('cls' if os.name == 'nt' else 'clear')
		print("WARP-PLUS-CLOUDFLARE (script) by Tran Thai Tuan Anh")
		print("")
		print("[-] Error when connecting to server.")
		print(f"[-] Total: {good} Good {bad} Bad")
		print("[-] After 18 seconds, a new request will be sent.")
		time.sleep(18)


from flask import Flask, request

app = Flask(__name__)

@app.route('/02-server')
def server01_views():
    return "This is my first response by Ajax"

@app.route('/03-server')
def server03_views():
    uname = request.args['uname']
    return "欢迎" + uname

if __name__ == '__main__':
    app.run(debug=True)


from selenium import webdriver
from time import sleep

from selenium.webdriver import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

chrome_options = Options()
chrome_options.add_argument("--headless")  # Chạy trình duyệt ẩn danh
browser = webdriver.Chrome()
browser.get("https://services.ca.judiciary.gov.ph/recentdecisions/")
sleep(3)
select50 = browser.find_element(By.XPATH, "/html/body/center/div[3]/form/div/div[3]/select/option[4]")
select50.click()
sleep(1)
viewPDF = browser.find_element(By.XPATH,"/html/body/center/div[3]/form/div/div[2]/table/tbody/tr[1]/td[4]")
viewPDF.click()
sleep(2)
browser.find_element(By.XPATH,'/html/body').send_keys(Keys.CONTROL, 's')
page_content = browser.page_source

# Lưu nội dung vào tệp tin
with open('1.pdf', 'w', encoding='utf-8') as file:
    file.write(page_content)
sleep(10)
browser.quit()


#Import Libs
import time
import click
import mouse
import keyboard
import pyautogui

def inicialize():

    print('''
    =========================================================================
    ||  Configure according to screen size:                                ||
    ||  Configurar de acordo com o tamanho da tela:                        ||
    ||                                                                     ||
    ||    => Remember to configure the positions in the functions          ||
    ||    => Lembre-se de configurar as posições nas funções               ||
    ||    variable [position xloc] and [position yloc]                     ||
    ||                                                                     ||
    ||  Make sure the browser is open before running the script            ||
    ||  Verfique se o navegador está aberto antes de executar o script     ||
    ||                                                                     ||
    ||  Screen size     ==  1365x767                                       ||
    ||  Tamanho da tela ==  1365x767                                       ||
    ||                                                                     ||
    ||    ===> Press CTRL + C to kill the bot.                             ||
    ||    ===> Pressione CTRL + C para encerrar o bot.                     ||
    =========================================================================

>>-----> Initializing Application <-----<<
''')

def selectBrowser():

    xloc = 142
    yloc = 12

    print(">>-----> Selecting browser....")
    print(">>-----> Leave the browser open !!!")

    # mouse.move(xloc, yloc, absolute=True, duration=0.1)
    # mouse.click('left')
    time.sleep(5)

def clickHome():

    xloc = 243
    yloc = 124

    # mouse.move(xloc, yloc, absolute=True, duration=0.1)
    # mouse.click('left')
    time.sleep(5)

    print("<-----<< Returning to home....")

def login():
    # Developing function
    pass

def selectHeroes():

    xloc = 1089
    yloc = 630

    print(">>-----> Selecting heroes....")

    # mouse.move(xloc, yloc, absolute=True, duration=0.1)
    # mouse.click('left')
    time.sleep(5)

def loadAllHeroes():

    xloc = 600
    yloc = 273

    print(">>-----> Putting the heroes to work....")

    # mouse.move(xloc, yloc, absolute=True, duration=0.1)
    # mouse.click('left')
    # time.sleep(5)
    # #comando para fechar a tela
    # mouse.move(731,225,absolute=True, duration=0.1)
    # mouse.click('left')
    print('>>-----> Close screen....')
    time.sleep(5)

def goTogame():

    xloc = 691
    yloc = 407

    print(">>-----> Starting mining!....")

    # mouse.move(xloc, yloc, absolute=True, duration=0.1)
    # mouse.click('left')
    time.sleep(5)

def countDown(num_of_secs):

    while num_of_secs:
        m, s = divmod(num_of_secs, 60)
        min_sec_format = '{:02d}:{:02d}'.format(m,s)
        print(">>-----> Waiting time : " + min_sec_format, end='\r')
        time.sleep(1)
        num_of_secs -=1
    print("\n<-----<< Restarting routine!!\n")

def closeApp():

    print(">>-----> ## Closing Application ## <-----<<")
    exit()

def main():

    inicialize()

    try:
        while True:
            selectBrowser()
            clickHome()
            selectHeroes()
            loadAllHeroes()
            goTogame()
            countDown(5) #real 600
    except:
        print(">>-----> Command CTRL + C detected")
        print(">>-----> ## Closing Application ## <-----<<")
        exit()

if __name__=='__main__':
    main()


import serial
import numpy as np
import matplotlib.pyplot as plt

# シリアルポートの設定（必要に応じて変更）
ser = serial.Serial('/dev/ttyACM0', 115200)

# グラフの初期化
fig, ax = plt.subplots()
x_data, y_data = [], []
line, = ax.plot(x_data, y_data, 'o', markersize=6)

# 3秒間のデータを保持するためのリングバッファ
max_data_points = 300  # 1秒あたり100データ点 × 3秒
x_ring_buffer = [0] * max_data_points
y_ring_buffer = [0] * max_data_points
current_index = 0

def update_plot(x, y):
    # データをプロット
    x_data.append(x)
    y_data.append(y)
    line.set_data(x_data, y_data)

    # データが3秒分を超えた場合、古いデータを削除
    if len(x_data) > max_data_points:
        x_data.pop(0)
        y_data.pop(0)

    # グラフを更新
    plt.pause(0.01)

while True:
    data = ser.readline().decode().strip()
    if data.startswith("(") and data.endswith(")"):
        data = data[1:-1]
        x, y, _ = map(int, data.split(", "))

        # リアルタイムプロットを更新
        update_plot(x, y)


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

# In[1]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pickle

# In[2]:

train=pd.read_csv('sales_train.csv')
items=pd.read_csv('items.csv')
shops=pd.read_csv('shops.csv')
cats=pd.read_csv('item_categories.csv')

# In[3]:

sns.boxplot(train.item_cnt_day)

# In[4]:

train = train[train.item_cnt_day < 1000]

# In[5]:

sns.boxplot(train.item_price)

# In[6]:

train = train[train.item_price < 300000]

# In[7]:

train = train[train.item_price > 0].reset_index(drop = True)
train.loc[train.item_cnt_day < 1, "item_cnt_day"] = 0

# In[8]:

train.loc[train.shop_id == 0, 'shop_id'] = 57
train.loc[train.shop_id == 1, 'shop_id'] = 58
train.loc[train.shop_id == 10, 'shop_id'] = 11
train.loc[train.shop_id == 40, 'shop_id'] = 39

# In[9]:

shops.loc[ shops.shop_name == 'Сергиев Посад ТЦ "7Я"',"shop_name" ] = 'СергиевПосад ТЦ "7Я"'
shops["city"] = shops.shop_name.str.split(" ").map( lambda x: x[0] )
shops["category"] = shops.shop_name.str.split(" ").map( lambda x: x[1] )
shops.loc[shops.city == "!Якутск", "city"] = "Якутск"

# In[10]:

category = []
for cat in shops.category.unique():
    if len(shops[shops.category == cat]) >= 5:
        category.append(cat)
shops.category = shops.category.apply( lambda x: x if (x in category) else "other" )

# In[11]:

from sklearn.preprocessing import LabelEncoder
shops["shop_category"] = LabelEncoder().fit_transform( shops.category )
shops["shop_city"] = LabelEncoder().fit_transform( shops.city )
shops = shops[["shop_id", "shop_category", "shop_city"]]
shops=shops.drop([0,1,10,40]).reset_index(drop=True)

# In[12]:

cats["type_code"] = cats.item_category_name.apply( lambda x: x.split(" ")[0] ).astype(str)
cats.loc[ (cats.type_code == "Игровые")| (cats.type_code == "Аксессуары"), "category" ] = "Игры"

# In[13]:

category = []
for cat in cats.type_code.unique():
    if len(cats[cats.type_code == cat]) >= 5:
        category.append( cat )
cats.type_code = cats.type_code.apply(lambda x: x if (x in category) else "etc")

# In[14]:

cats.type_code = LabelEncoder().fit_transform(cats.type_code)
cats["split"] = cats.item_category_name.apply(lambda x: x.split("-"))
cats["subtype"] = cats.split.apply(lambda x: x[1].strip() if len(x) > 1 else x[0].strip())
cats["subtype_code"] = LabelEncoder().fit_transform( cats["subtype"] )
cats = cats[["item_category_id", "subtype_code", "type_code"]]

# In[15]:

import re
def name_correction(x):
    x = x.lower() # all letters lower case
    x = x.partition('[')[0] # partition by square brackets
    x = x.partition('(')[0] # partition by curly brackets
    x = re.sub('[^A-Za-z0-9А-Яа-я]+', ' ', x) # remove special characters
    x = x.replace('  ', ' ') # replace double spaces with single spaces
    x = x.strip() # remove leading and trailing white space
    return x

# In[16]:

items["name1"], items["name2"] = items.item_name.str.split("[", 1).str
items["name1"], items["name3"] = items.item_name.str.split("(", 1).str

items["name2"] = items.name2.str.replace('[^A-Za-z0-9А-Яа-я]+', " ").str.lower()
items["name3"] = items.name3.str.replace('[^A-Za-z0-9А-Яа-я]+', " ").str.lower()

items = items.fillna('0')

items["item_name"] = items["item_name"].apply(lambda x: name_correction(x))

items.name2 = items.name2.apply( lambda x: x[:-1] if x !="0" else "0")

# In[17]:

items["type"] = items.name2.apply(lambda x: x[0:8] if x.split(" ")[0] == "xbox" else x.split(" ")[0] )
items.loc[(items.type == "x360") | (items.type == "xbox360") | (items.type == "xbox 360") ,"type"] = "xbox 360"
items.loc[ items.type == "", "type"] = "mac"
items.type = items.type.apply( lambda x: x.replace(" ", "") )
items.loc[ (items.type == 'pc' )| (items.type == 'pс') | (items.type == "pc"), "type" ] = "pc"
items.loc[ items.type == 'рs3' , "type"] = "ps3"

# In[18]:

group_sum = items.groupby(["type"]).agg({"item_id": "count"})
group_sum = group_sum.reset_index()
drop_cols = []
for cat in group_sum.type.unique():
    if group_sum.loc[(group_sum.type == cat), "item_id"].values[0] <40:
        drop_cols.append(cat)
items.name2 = items.name2.apply( lambda x: "other" if (x in drop_cols) else x )
items = items.drop(["type"], axis = 1)

# In[19]:

items.name2 = LabelEncoder().fit_transform(items.name2)
items.name3 = LabelEncoder().fit_transform(items.name3)

items.drop(["item_name", "name1"],axis = 1, inplace= True)

# In[20]:

price=train[['item_id','item_price']]
price=price.groupby(['item_id']).mean()
price=price.reset_index()

items=pd.merge(items,price,on=['item_id'],how='inner')
items=pd.merge(items,cats,on=['item_category_id'],how='inner')

# In[21]:

train=train.drop('date',axis=1)
train=train.groupby(['date_block_num', 'shop_id', 'item_id']).sum()
train.drop('item_price',axis=1,inplace=True)
train=train.reset_index()
train=train.rename(columns = {'item_cnt_day' : 'item_cnt_month'})

# In[22]:

from itertools import product
matrix = []
cols  = ["date_block_num", "shop_id", "item_id"]
for i in range(34):
    sales = train[train.date_block_num == i]
    matrix.append( np.array(list( product( [i], sales.shop_id.unique(), sales.item_id.unique() ) ), dtype = np.int16) )

matrix = pd.DataFrame( np.vstack(matrix), columns = cols )
matrix["date_block_num"] = matrix["date_block_num"].astype(np.int8)
matrix["shop_id"] = matrix["shop_id"].astype(np.int8)
matrix["item_id"] = matrix["item_id"].astype(np.int16)
matrix.sort_values( cols, inplace = True )

train=pd.merge(matrix,train,on=["date_block_num", "shop_id", "item_id"],how='left')
train=train.fillna(0)
train=pd.merge(train,items,on=['item_id'],how='inner')
train=pd.merge(train,shops,on=['shop_id'],how='inner')
train.sort_values(["date_block_num", "shop_id", "item_id"], inplace = True )
train=train.reset_index(drop=True)

# In[23]:

train["month"] = train["date_block_num"] % 12
days = pd.Series([31,28,31,30,31,30,31,31,30,31,30,31])
train["days"] = train["month"].map(days).astype(np.int8)
train["year"] = 2013+(train["date_block_num"]/12).astype(np.int16)
train['month']=train['month']+1

# In[24]:

train=train[['date_block_num', 'shop_id', 'item_id', 'shop_category', 'shop_city',
       'item_category_id', 'name2', 'name3', 'subtype_code', 'type_code', 'days', 'month', 'year',
       'item_price', 'item_cnt_month']]

items.to_csv('items_data.csv')
shops.to_csv('shops_data.csv')

# In[25]:

X_train = train[train.date_block_num < 33].drop(['item_cnt_month'], axis=1)
Y_train = train[train.date_block_num < 33]['item_cnt_month']
X_valid = train[train.date_block_num == 33].drop(['item_cnt_month'], axis=1)
Y_valid = train[train.date_block_num == 33]['item_cnt_month']

# In[26]:

Y_train = Y_train.clip(0, 20)
Y_valid = Y_valid.clip(0, 20)

# In[27]:

from xgboost import XGBRegressor
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 12, 4

# In[28]:

model = XGBRegressor(
    max_depth=10,
    n_estimators=1000,
    min_child_weight=0.5,
    colsample_bytree=0.8,
    subsample=0.8,
    eta=0.1,
#     tree_method='gpu_hist',
    seed=42)

model.fit(
    X_train,
    Y_train,
    eval_metric="rmse",
    eval_set=[(X_train, Y_train), (X_valid, Y_valid)],
    verbose=True,
    early_stopping_rounds = 20)

pickle.dump(model,open('model.pkl','wb'))

model=pickle.load(open('model.pkl','rb'))


from pathlib import Path
import numpy as np
from collections import Counter
from itertools import product

DIRECTIONS = ("up", "down", "left", "right")
ROTATIONS = (0, 90, 180, 270)

def get_tile_borders(tile, dir="all"):
    borders = []
    border = None
    for d in DIRECTIONS:
        if dir in [d, "all"]:
            id = tile_to_id(tile, d, False)
            id_flip = tile_to_id(tile, d, True)
            border = min(id, id_flip)
            borders.append(border)
    if dir != "all":
        return border
    return borders

def tile_to_id(tile, dir, reverse=False):

    step = 1
    if reverse:
        step = -1
    if dir == "up":
        return border_to_id(tile[0, ::step])
    if dir == "down":
        return border_to_id(tile[-1, ::step])
    if dir == "left":
        return border_to_id(tile[::step, 0])
    if dir == "right":
        return border_to_id(tile[::step, -1])

def border_to_id(border):
    return int("".join([str(el) for el in border.astype(int)]), 2)

def rotate(tile, deg, flip_hor=False):
    if deg not in [0, 90, 180, 270]:
        raise RuntimeError("Invalid degrees")
    arr = np.copy(tile)
    if flip_hor:
        arr = arr[:, ::-1]

    if deg == 90:
        return arr[::-1, :].T
    elif deg == 180:
        return arr[::-1, ::-1]
    elif deg == 270:
        return arr[:, ::-1].T
    return arr

class Image:
    def __init__(self, data, pattern):

        self.tiles = dict()
        self.borders = dict()
        self.n_tiles = 0
        self.tile_dim = None
        self.corners = set()
        self.edges = set()
        self.interiors = set()
        self.border_counter = None
        self.corner_prod = None

        i = 0
        lines = data.split("\n")
        while i < len(lines):
            if lines[i].startswith("Tile"):
                id = int(lines[i][5:-1])
                i += 1
            tile = []
            while (i < len(lines)) and lines[i]:
                tile.append([int(l == "#") for l in lines[i]])
                i += 1
            if self.tile_dim is None:
                self.tile_dim = len(tile)
            tile = np.array(tile, dtype=np.uint8)
            self.tiles[id] = tile
            self.borders[id] = get_tile_borders(tile)
            self.n_tiles += 1
            i += 1
        for id in self.tiles:
            assert self.tiles[id].shape[0] == self.tile_dim
            assert self.tiles[id].shape[1] == self.tile_dim
        self.puzzle_dim = int(np.round(np.sqrt(self.n_tiles)))
        assert self.puzzle_dim ** 2 == self.n_tiles

        self.solution = np.zeros(
            (self.puzzle_dim, self.puzzle_dim), dtype=int
        )
        self._solve()

        lines = pattern.split("\n")
        self.pattern = []
        for line in lines:
            self.pattern.append([l == "#" for l in line])
        self.pattern = np.array(self.pattern, dtype=bool)

        im_size = self.puzzle_dim * (self.tile_dim - 2)
        self.image = np.zeros((im_size, im_size), dtype=np.uint8)
        self._assemble_image()
        self.n_monsters = self._mark_sea_monsters()

    def _check_direction_unique(self, tile, direction):
        id = get_tile_borders(tile, direction)
        return self.border_counter[id] == 1

    def _solve(self):
        borders = []
        for id in self.borders:
            borders.extend(self.borders[id])
        self.border_counter = Counter(borders)

        max_edge_count = 0
        for id in self.borders:
            n_unique = 0
            for border in self.borders[id]:
                c = self.border_counter[border]
                n_unique += c == 1
                if c > max_edge_count:
                    max_edge_count = c
            if n_unique == 2:
                self.corners.add(id)
            elif n_unique == 1:
                self.edges.add(id)
            elif n_unique == 0:
                self.interiors.add(id)
        assert max_edge_count == 2

        self.corner_prod = self.find_corner_product()

        dim_range = range(self.puzzle_dim)
        for col, row in product(dim_range, dim_range):
            self._solve_coord(row, col)

    def _solve_coord(self, row, col):
        unique_edges = (
            (row == 0)
            + (col == 0)
            + (row == self.puzzle_dim - 1)
            + (col == self.puzzle_dim - 1)
        )
        pieces = None
        if unique_edges == 0:
            pieces = self.interiors
        elif unique_edges == 1:
            pieces = self.edges
        if unique_edges == 2:
            pieces = self.corners

        orientations = list(product(ROTATIONS, [True, False]))
        cand = None
        tile = None
        for cand in pieces:
            valid = False
            for rot, flip in orientations:
                tile = rotate(self.tiles[cand], rot, flip)
                valid = True
                if row == 0:
                    valid &= self._check_direction_unique(tile, "up")
                else:
                    up = self.tiles[self.solution[row - 1, col]]
                    valid &= tile_to_id(tile, "up") == tile_to_id(
                        up, "down"
                    )

                if col == 0:
                    valid &= self._check_direction_unique(tile, "left")
                else:
                    left = self.tiles[self.solution[row, col - 1]]
                    valid &= tile_to_id(tile, "left") == tile_to_id(
                        left, "right"
                    )

                if row == self.puzzle_dim - 1:
                    valid &= self._check_direction_unique(tile, "down")
                if col == self.puzzle_dim - 1:
                    valid &= self._check_direction_unique(tile, "right")

                if valid:
                    break

            if valid:
                break
        self.solution[row, col] = cand
        pieces.remove(cand)
        self.tiles[cand] = tile

    def _assemble_image(self):
        im_col = 0
        for col in range(self.puzzle_dim):
            im_row = 0
            for row in range(self.puzzle_dim):
                tile = np.copy(self.tiles[self.solution[row, col]])[
                    1:-1, 1:-1
                ]
                self.image[
                    im_row : im_row + tile.shape[0],
                    im_col : im_col + tile.shape[1],
                ] = tile
                im_row += tile.shape[0]
            im_col += tile.shape[1]

    def _mark_sea_monsters(self):
        orientations = list(product(ROTATIONS, [True, False]))
        n_monsters = 0
        image = np.copy(self.image)
        for rot, flip in orientations:
            found_pattern = False
            image = rotate(self.image, rot, flip)
            n_monsters = 0
            for row in range(image.shape[0] - self.pattern.shape[0] + 1):
                for col in range(
                    image.shape[1] - self.pattern.shape[1] + 1
                ):
                    part = image[
                        row : row + self.pattern.shape[0],
                        col : col + self.pattern.shape[1],
                    ]
                    if part[self.pattern].all():
                        part[self.pattern] = 2
                        n_monsters += 1
                        found_pattern = True
            if found_pattern:
                break
        self.image = image
        return n_monsters

    def print_image(self, image):
        line = []
        char = {1: "#", 0: ".", 2: "O"}
        for row in range(image.shape[0]):
            s = ""
            for col in range(image.shape[1]):
                s += char[image[row, col]]
            line.append(s)
        line.append("")
        output = "\n".join(line)
        print(output)

    def find_corner_product(self):
        corner_prod = 1
        for corner in self.corners:
            corner_prod *= corner
        return corner_prod

    def find_habitat_roughness(self):
        return np.sum(self.image == 1)

def main():
    data_folder = Path(__file__).parent.resolve()
    data = data_folder.joinpath("input.txt").read_text()
    pattern = data_folder.joinpath("seamonster.txt").read_text()
    t = Image(data, pattern)
    print("Part 1")
    print("The product of the IDs of the four corner ")
    print(f"tiles is {t.corner_prod}")
    print()

    print("Part 2")
    print(f"The habitat's roughness is {t.find_habitat_roughness()}")
    print()

    print(f"Final image with {t.n_monsters} marked sea monsters:")
    t.print_image(t.image)

if __name__ == "__main__":
    main()


def min_max():
    print("Ingresa los numeros que quieras, cuando termines escribe 'fin'")
    lista = []
    while True:
        numero = input("Ingresa un numero: ")
        if numero == "fin":
            break
        else:
            lista.append(int(numero))
    print("valores introducidos")
    print(lista)
    print("El numero maximo es: ", max(lista))
    print("El numero minimo es: ", min(lista))


# This defines the model
import torch.nn as nn

from torchvision import models

import torch.nn as nn
import torch

class MyEnsemble(nn.Module):

    def __init__(self, modelA, modelB, input):
        super(MyEnsemble, self).__init__()
        self.modelA = modelA
        self.modelB = modelB
        self.fc1 = nn.Linear(input, 2)

    def forward(self, x):
        out1 = self.modelA(x)
        out2 = self.modelB(x)
        out = out1 + out2
        x = self.fc1(out)
        return torch.softmax(x, dim=1)

"""
def build_model( num_classes=2):
    model1 = models.resnet101(pretrained=True)
    num_ftrs1 = model1.fc.in_features
    model1.fc = nn.Linear(num_ftrs1, num_classes)

    model2 = models.resnet152(pretrained=True)
    num_ftrs2 = model2.fc.in_features
    model2.fc = nn.Linear(num_ftrs2, num_classes)

    model = MyEnsemble(model1, model2,num_classes)

    return model

"""
def build_model(pretrained=True, fine_tune=True, num_classes=10):
    model=models.resnet152(pretrained=True)
    num_ftrs1 = model.fc.in_features
    model.fc = nn.Linear(num_ftrs1, num_classes)
    return model


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

n = int(input())
emails = set()

for i in range(n):
	email = input()
	user, provider = email.split('@')

	if('+' in user):
		user, dump = email.split('+')

	user = user.replace('.', '')
	email = user + '@' + provider

	emails.add(email)

print(len(emails))

problems/solutions/Brazilian Summer School/Summer School 2019/Dia 1/D.py


from django.shortcuts import render

from .models import AreaOfExpertise, Expert

def browser(request):
    aoe = AreaOfExpertise.objects.all().order_by('field')

    experts = Expert.objects.all()

    institutes = set()
    for expert in experts:
        institutes.add(expert.institute) if expert.institute is not None else None

    name = request.GET.get('name')
    institute = request.GET.get('institute')
    expertise = request.GET.get('expertise')

    if name:
        experts = experts.filter(name__contains=request.GET.get('name'))

    if institute:
        experts = experts.filter(institute=request.GET.get('institute'))

    if expertise:
        experts = experts.filter(expertise=AreaOfExpertise.objects.filter(field=expertise)).distinct()

    return render(request, 'expertBrowser.html', {'experts': experts, 'institutes': institutes, 'aoe': aoe, 'name': name, 'institute': institute, 'expertise': expertise})

def viewer(request, id):
    expert = Expert.objects.get(id=id)
    return render(request, 'expertViewer.html', {'expert': expert})


import math

print("Enter the time of year you were born")
year_time = input(">>> ")
print("Enter x")
x = int(input(">>> "))
year_time = year_time.lower()
if year_time == "winter":
    y = ((math.sin(x) + 23 * x) ** 4) / (math.sqrt(abs(x) ** x - 3))
    y = round(y, 2)
    print(y)
elif year_time == "spring":
    y = (2 * math.cos(x) * math.sqrt((888 * (x**4) ** 5))) / math.cos(math.pi)
    y = round(y, 2)
    print(y)
elif year_time == "summer":
    y = ((x**2) ** math.sqrt(abs(x))) / (math.sin(x) + math.cos(math.pi))
    y = round(y, 2)
    print(y)
elif year_time == "autumn":
    y = (math.cos(123 * x) + math.sqrt(4 * abs(x))) / (abs(math.sin(2**x) + math.pi))
    y = round(y, 2)
else:
    print("Sorry, but there is no such time of year")


ms="the quick brown fox over lazy dog.the dog slept over a varandah"
ss="over"
i=0
k=" "
s=ms.split()
while i<len(s):
    if s[i]==ss:
        k=k+" on"
    else:
        k=k+" "+s[i]
    i+=1
print(k)


import math
import pytest
from datatable import f, dt, update
from tests import assert_equals

stypes_int = dt.ltype.int.stypes
stypes_float = dt.ltype.real.stypes
stypes_str = dt.ltype.str.stypes
stypes_all = [dt.bool8, dt.obj64] + stypes_int + stypes_float + stypes_str

#-------------------------------------------------------------------------------
# Assign None
#-------------------------------------------------------------------------------

def test_assign_none_single():
    DT = dt.Frame(A=range(5))
    DT[:, f.A] = None
    assert_equals(DT, dt.Frame(A=[None]*5, stype=dt.int32))

def test_assign_none_new():
    DT = dt.Frame(A=range(5))
    DT[:, "B"] = None
    assert_equals(DT, dt.Frame(A=range(5), B=[None]*5,
                               stypes={"A": dt.int32, "B": dt.bool8}))

def test_assign_none_all():
    DT = dt.Frame([[True, False], [1, 5], [999, -12], [34.2, math.inf],
                   [0.001, 1e-100], ['foo', 'bar'], ['buzz', '?']],
                  names=list("ABCDEFG"),
                  stypes=['bool', 'int8', 'int64', 'float32', 'float64',
                          'str32', 'str64'])
    DT[:, :] = None
    assert_equals(DT, dt.Frame([[None, None]] * 7,
                               names=tuple("ABCDEFG"),
                               stypes=(dt.bool8, dt.int8, dt.int64, dt.float32,
                                       dt.float64, dt.str32, dt.str64)))

#-------------------------------------------------------------------------------
# Assign boolean values
#-------------------------------------------------------------------------------

def test_assign_boolean():
    DT = dt.Frame(A=[None])
    DT[:, "A"] = True
    assert_equals(DT, dt.Frame(A=[True]))

def test_assign_boolean2():
    DT = dt.Frame(A=[True, False, True])
    DT[:, "A"] = False
    assert_equals(DT, dt.Frame(A=[False] * 3))

@pytest.mark.parametrize("stype", stypes_int + stypes_float + stypes_str)
def test_assign_boolean_to_different_type(stype):
    DT = dt.Frame(A=[5, 7], stype=stype)
    assert DT.stype == stype
    DT[:, "A"] = False
    assert_equals(DT, dt.Frame(A=[False, False], stype=bool))

def test_assign_boolean_partial():
    DT = dt.Frame(A=range(5))
    DT[2, "B"] = False
    assert_equals(DT, dt.Frame(A=range(5), B=[None, None, False, None, None]))

#-------------------------------------------------------------------------------
# Assign integer values
#-------------------------------------------------------------------------------

def test_assign_integer_out_of_range():
    DT = dt.Frame(A=[1, 2, 3], stype=dt.int8)
    assert DT.stype == dt.int8
    DT[:, "A"] = 5000000
    assert_equals(DT, dt.Frame(A=[5000000] * 3, stype=dt.int32))

def test_assign_integer_out_of_range_to_subset():
    DT = dt.Frame(A=range(10), stype=dt.int8)
    assert DT.stype == dt.int8
    DT[:3, "A"] = 999
    assert_equals(DT, dt.Frame(A=[999, 999, 999, 3, 4, 5, 6, 7, 8, 9],
                               stype=dt.int16))
    DT[-1, "A"] = 10**10
    assert_equals(DT, dt.Frame(A=[999, 999, 999, 3, 4, 5, 6, 7, 8, 10**10],
                               stype=dt.int64))

def test_assign_int_overflow():
    # When integer overflows, it becomes a float64 value
    DT = dt.Frame(A=range(5), B=[0.0]*5)
    DT[:, "A"] = 10**100
    DT[:, "B"] = 10**100
    assert_equals(DT, dt.Frame(A=[1.0e100]*5, B=[1.0e100]*5))

@pytest.mark.parametrize("stype", [dt.bool8] + stypes_str)
def test_assign_integer_to_different_type(stype):
    DT = dt.Frame(A=[5], stype=stype)
    assert DT.stype == stype
    DT[:, "A"] = 777
    assert_equals(DT, dt.Frame(A=[777], stype=dt.int32))

#-------------------------------------------------------------------------------
# Assign float values
#-------------------------------------------------------------------------------

def test_assign_to_newcolumn_subset():
    DT = dt.Frame(A=range(5))
    DT[[1, 4], "B"] = 3.7
    assert_equals(DT, dt.Frame(A=range(5), B=[None, 3.7, None, None, 3.7]))

def test_assign_float_upcast():
    # When float32 overflows, it is converted to float64
    DT = dt.Frame(A=[1.3, 2.7], stype=dt.float32)
    DT[:, "A"] = 1.5e+100
    assert_equals(DT, dt.Frame(A=[1.5e100, 1.5e100]))

def test_assign_to_float32_column():
    DT = dt.Frame(A=range(5), stype=dt.float32)
    DT[:, "A"] = 3.14159
    assert_equals(DT, dt.Frame(A=[3.14159] * 5, stype=dt.float32))

@pytest.mark.parametrize("stype", [dt.bool8] + stypes_int + stypes_str)
def test_assign_float_to_different_type(stype):
    DT = dt.Frame(A=[5], stype=stype)
    assert DT.stype == stype
    DT[:, "A"] = 3.14159265
    assert_equals(DT, dt.Frame(A=[3.14159265]))

#-------------------------------------------------------------------------------
# Assign string values
#-------------------------------------------------------------------------------

def test_assign_string_to_str64():
    DT = dt.Frame(A=["wonder", None, "ful", None], stype=dt.str64)
    DT[:, "A"] = "beep"
    assert_equals(DT, dt.Frame(A=["beep"] * 4, stype=dt.str64))

@pytest.mark.parametrize("stype", [dt.bool8] + stypes_int + stypes_float)
def test_assign_string_to_different_type(stype):
    DT = dt.Frame(A=[5], stype=stype)
    assert DT.stype == stype
    DT[:, "A"] = 'what?'
    assert_equals(DT, dt.Frame(A=['what?']))

def test_assign_str_to_empty_frame():
    # See issue #2043, the assignment used to deadlock
    DT = dt.Frame(W=[], stype=dt.str32)
    DT[f.W == '', f.W] = 'yay!'
    assert_equals(DT, dt.Frame(W=[], stype=dt.str32))

#-------------------------------------------------------------------------------
# Assign types
#-------------------------------------------------------------------------------

def test_assign_type_simple():
    DT = dt.Frame(A=range(5))
    DT["A"] = dt.float64
    assert_equals(DT, dt.Frame(A=range(5), stype=dt.float64))

def test_assign_type_to_many_columns():
    DT = dt.Frame(A=[True, False], B=[3, 7], C=[2.4, 9.9])
    DT[:, :] = dt.int64
    assert_equals(DT, dt.Frame(A=[1, 0], B=[3, 7], C=[2, 9], stype=dt.int64))

def test_assign_type_to_some_columns():
    DT = dt.Frame(A=['bii', 'doo'], B=[3, 5], C=[4, 4])
    DT[:, int] = float
    assert_equals(DT, dt.Frame(A=['bii', 'doo'], B=[3.0, 5.0], C=[4.0, 4.0]))

@pytest.mark.parametrize("st", stypes_all)
def test_assign_stypes(st):
    DT = dt.Frame(A=[1])
    DT["A"] = st
    assert DT.stype == st

@pytest.mark.parametrize("pt", [bool, int, float, str, object])
def test_assign_python_type(pt):
    DT = dt.Frame(A=[7])
    DT["A"] = pt
    if pt is object:
        assert DT.stype == dt.obj64
    else:
        assert type(DT[0, 0]) is pt

@pytest.mark.parametrize("lt", [dt.ltype.bool, dt.ltype.int, dt.ltype.real,
                                dt.ltype.str, dt.ltype.obj])
def test_assign_ltype(lt):
    DT = dt.Frame(A=[7])
    DT["A"] = lt
    assert DT.ltypes[0] == lt

def test_assign_type_without_stype_change():
    # Verify that if a column already has same ltype, then that ltype will
    # not change upon the assignment
    DT = dt.Frame([[0], [1], [2], [3], [4], [5]],
                  stypes=[dt.bool8, dt.int8, dt.int16, dt.int32, dt.int64,
                          dt.float32])
    DT[:, "C0":"C5"] = int
    assert_equals(DT, dt.Frame([[0], [1], [2], [3], [4], [5]],
                               stypes=[dt.int32, dt.int8, dt.int16, dt.int32,
                                       dt.int64, dt.int32]))

def test_assign_stype_to_new_column():
    DT = dt.Frame(S=range(5))
    DT["N"] = dt.float64
    DT["M"] = dt.float32
    assert_equals(DT, dt.Frame(S=range(5), N=[None]*5, M=[None]*5,
                               stypes=dict(N=dt.float64, M=dt.float32)))

def test_assign_bad_type():
    DT = dt.Frame(A=range(5))
    with pytest.raises(ValueError, match="Unknown type <class 'type'> used in "
                                         "the replacement expression"):
        DT["A"] = type

def test_assign_different_types():
    DT = dt.Frame(A=range(5), B=list("ABCDE"))
    assert DT.stypes == (dt.int32, dt.str32)
    DT[:, update(A=dt.float32, B=dt.str64)]
    assert_equals(DT, dt.Frame(A=range(5), B=list("ABCDE"),
                               stypes=dict(A=dt.float32, B=dt.str64)))

def test_assign_types_partial():
    DT = dt.Frame(A=range(5))
    with pytest.raises(ValueError, match="Partial reassignment of Column's "
                                         "type is not possible"):
        DT[:2, "A"] = str

#-------------------------------------------------------------------------------
# Assign range
#-------------------------------------------------------------------------------

def test_assign_range():
    DT = dt.Frame(A=[3, 4, 0])
    DT["B"] = range(3)
    assert_equals(DT, dt.Frame(A=[3, 4, 0], B=[0, 1, 2]))

def test_assign_range2():
    DT = dt.Frame(A=[7]*7, stype=dt.float32)
    DT["A"] = range(3, 10)
    assert_equals(DT, dt.Frame(A=range(3, 10)))

def test_assign_range_subframe():
    DT = dt.Frame(A=range(20))
    DT[10:, "A"] = range(10)
    assert_equals(DT, dt.Frame(A=list(range(10))*2))

def test_assign_range_compute():
    DT = dt.Frame(A=[5, 10, 100])
    DT["B"] = f.A * range(3)
    assert_equals(DT, dt.Frame(A=[5, 10, 100], B=[0, 10, 200]))


"""
Created on 03.12.2020

:author: Ilya Krasnokutskiy
converting codewords to Newick format

:functions:
    add_brackets
    add_commas
    codewords_conversion
"""

def add_brackets(code_words: list, code_chars: list) -> str:
    '''
    Перевод кодовых слов в скобочную последовательность (The Newick format).
    Должно выполнятся равенство: len(code_words) = len(code_chars)

    :param code_words: Отсортированный (во возрастанию) список кодовых слов (str).
    :type code_words:  list

    :param code_chars: Список соответствующих кодовым словам символов (str).
    :type code_chars:  list

    :return: Строка скобочной последовательности.
    :rtype:  str
    '''

    #((.  c - 00,(.  a - 011)),((.  f - 101),((.  d - 1100),(.  e - 1110,(((.  b - 1111110)))))));

    # Проверка на совпадение длин списков
    if(len(code_words) != len(code_chars)):
        print('Длины списков не совпадают!')
        return 'er'

    code_words = list(reversed(code_words))
    code_chars = list(reversed(code_chars))

    max_word = code_words[0]
    dif_w1 = 0
    dif_w2 = 0

    # Инициализация строки
    back_brackets = len(max_word) - 1
    result = '.  ' + code_chars[0] + ' - ' + max_word + ')'*back_brackets

    # Наполнение строки
    for k in range(len(code_words) - 1):
        w1 = code_words[k]
        w2 = code_words[k + 1]

        for ind in range(len(w2)):
            if(w2[ind] != w1[ind]):
                dif_w1 = len(w1) - ind - 1
                dif_w2 = len(w2) - ind - 1

                result = '.  ' + code_chars[k + 1] + ' - ' + w2 + ')'*dif_w2 + '('*dif_w1 + result
                break

    brackets = 0
    for i in result:
        if i == ')':
            brackets += 1
        elif i == '(':
            brackets -= 1

    result ='('*abs(brackets) + result

    return result

def add_commas(brackets_line: str) -> str:
    '''
    Добавление запятых в скобочную последовательность.

    :param brackets_line: Строка скобочной последовательности.
    :type brackets_line:  str

    :return: Строка скобочной последовательности в формате Ньюика.
    :rtype:  str
    '''

    commas = []

    for i in range(len(brackets_line) - 1):
        first_sim = brackets_line[i]
        second_sim = brackets_line[i + 1]
        if ((first_sim not in [',', '('] or first_sim == ')') and second_sim == '('):
            commas.append(i + 1)
        if ((first_sim not in ['(']) and second_sim == '.'):
            commas.append(i + 1)

    commas = list(reversed(commas))

    for i in commas:
        brackets_line = brackets_line[0:i] + ',' + brackets_line[i:]

    brackets_line = '(' + brackets_line + ');'

    return brackets_line

def codewords_conversion(code_words: list, code_chars: list) -> str:
    '''
    Перевод кодовых слов в формат Ньюика (The Newick format).
    Длина списка code_words должна быть равна длине списка code_chars !!!

    :param code_words: Отсортированный (во возрастанию) список кодовых слов (str).
    :type code_words:  list

    :param code_chars: Список соответствующих кодовым словам символов (str).
    :type code_chars:  list

    :return: Строка скобочной последовательности в формате Ньюика.
    :rtype:  str
    '''

    # Запасная сортировка
    code_words = sorted(code_words)

    if(len(code_words) != len(code_chars)):
        print('Длины списков не совпадают!')
        return 'er'

    brackets_line = add_brackets(code_words, code_chars)
    result = add_commas(brackets_line)
    #print(result)
    return result


#=================================================================================================
#   Assignment: 1 Long assignment 2
#       Author: Feiran Yang
#
#       Course:  CSc 120
#   Instructor:  Saumya Debray
#
#  Description:  This program will read two user input as grid size and random number seed. the
#				 program will then create an N * N lower-case letters grid randomly with the
#				 random number seed and print the grid out.
#=================================================================================================
import random

def main():
	size = init()
	grid = make_grid(size)
	print_grid(grid)

#=================================================================================================
# Function Name:    init()
#       Purpose:    read the user input as size and seed_gen, use seed_gen as seed to initialize
#					random number. return size in the end.
#    Parameters:    N/A
#       Returns:    size
#=================================================================================================
def init():
	size = input()
	seed_gen = input()
	random_number = random.seed(seed_gen)

	return size

#=================================================================================================
# Function Name:    make_grid(size)
#       Purpose:    take size from main as parameter. creat an size * size list of list with
#					generated random letter. return that list of list in the end.
#    Parameters:    size
#       Returns:    gird
#=================================================================================================
def make_grid(size):
	size = int(size)
	grid = [0] * size
	for i in range(0,size):
		grid[i] = [0] * size
		for j in range(0, size):
			# random number using seed and transfer number ASCII characters
			new_chr = random.randint(97,122)
			grid[i][j] = chr(new_chr)
	return grid

#=================================================================================================
# Function Name:    init()
#       Purpose:    take grid as parameter. print that grid out so it looks like a grid.
#    Parameters:    grid
#       Returns:    N/A
#=================================================================================================
def print_grid(grid):
	for i in range(0, len(grid)):
		for j in range(0, len(grid)-1):
			print(grid[i][j]+',',end ='')
		print(grid[i][j+1])

main()


# -*- coding: utf-8 -*-
import requests
import os

# 6000 is a large number to make sure we get all the components of a collection. Please do note that RISE also has a pagination feature,
# which can be implemented by clients if they wish.
per_page = 6000

# getting the list of collections that the user has access to:
collections_response = requests.get(f'https://rise.mpiwg-berlin.mpg.de/api/collections?per_page={per_page}')

collections = collections_response.json()
# each accessible collections has a name, a uuid, and a number of resources.
# print(collections)
idx = 1
for collection in collections:
      print(f'collection at index: {idx}')
      idx += 1
      print(collection)

# picking a collection by its index
# collection_index = 1
# collection = collections[collection_index]

results = list(filter(lambda collection: collection['name'] == 'MPIWG - 哈佛燕京圖書館藏珍稀方志', collections))
collection = results[0]
print(collection['uuid'])
collection_uuid = collection['uuid']

# we grab all resources for this collection
resources_response = requests.get(f'https://rise.mpiwg-berlin.mpg.de/api/collections/{collection_uuid}/resources?per_page={per_page}')

corpus_path = './corpus'
if not os.path.exists(corpus_path):
      os.makedirs(corpus_path)

for resource in resources_response.json():
      uuid = resource['uuid']
      resource_name = resource['name']
      print(resource_name)

      if not os.path.exists(corpus_path + "/" + resource_name):
            os.makedirs(corpus_path + "/" + resource_name)
      sections = requests.get("https://rise.mpiwg-berlin.mpg.de/api/resources/"+ resource['uuid'] +"/sections")

      for section in sections.json():
            print(section)
            print(section['uuid'])
            section_name = section['name']
            section_path = corpus_path + "/" + resource_name + "/" + section_name
            file = open(section_path +".txt", "w")
            content_units = requests.get("https://rise.mpiwg-berlin.mpg.de/api/sections/"+ section['uuid'] +"/content_units?per_page=6000")
            for content_unit in content_units.json():
                  print(content_unit)
                  file.write(content_unit['content'])
            file.close()


# import cv2
# import glob
# import numpy as np

def bbox_for_deepsort(*x1y1x2y2):
    '''
    return bbox info for deep_sort
    :param x1y1x2y2: (tensor(), tensor(), tensor(), tensor())
    :return: (center_x, center_y, bbox_width, bbox_height)
    '''
    x1, y1, x2, y2 = \
        x1y1x2y2[0].item(), x1y1x2y2[1].item(), x1y1x2y2[2].item(), x1y1x2y2[3].item()
    bbox_left = min(x1, x2)
    bbox_top = min(y1, y2)
    bbox_width = abs(x1 - x2)
    bbox_height = abs(y1 - y2)
    center_x = bbox_left + bbox_width / 2
    center_y = bbox_top + bbox_height / 2
    return center_x, center_y, bbox_width, bbox_height

def id_rgb(idx):
    '''
    return unique rgb corresponding to id
    :param idx: integer
    :return: rgb
    '''
    chs = (pow(2, 10) + 1, pow(2, 15) + 1, pow(2, 20) + 1)
    rgb = tuple(ch * (pow(idx + 10, 10) + 1) % 255 for ch in chs)
    return rgb

def im_trim(img, x, y, w, h):
    img_trim = img[y:y+h, x:x+w]
    return img_trim

def bbox_trim(img, bboxes, ids=None, store=False):
    '''
    trim bbox(es) on img (frame)
    :param img:
    :param bboxes:
    :param ids:
    '''
    import time

    result = {}
    for i, bbox in enumerate(bboxes):
        x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]

        id_ = int(ids[i]) if ids is not None else 0
        min_x, min_y = x1 if x1 < x2 else x2, y1 if y1 < y2 else y2
        width, height = int(abs(x1-x2)), int(abs(y1-y2))

        if width < 32 or height < 32: # contest condition.
            continue

        img_trim = img[min_y: min_y + height, min_x: min_x + width]

        if store: # for debug
            pass
            # caption = '{:d}'.format(id_)
            # text_size, _ = cv2.getTextSize(text=caption, fontFace=cv2.FONT_HERSHEY_PLAIN,
            #                                fontScale=2, thickness=2)
            # cv2.putText(img=img_trim, text=caption,
            #             org=(0, 0 + text_size[1] + 4), fontFace=cv2.FONT_HERSHEY_PLAIN,
            #             fontScale=2, color=(255, 255, 255), thickness=2)
            # cv2.imwrite('chanchanchan/{}-{}.jpg'.format(time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()), id_), img_trim)

        result[id_] = img_trim
        # show_img2(img_trim)

    return result

# def bbox_draw(img, bboxes, ids=None):
#     '''
#     draw bbox(es) on img (frame)
#     :param img:
#     :param bboxes:
#     :param ids:
#     '''
#     for i, bbox in enumerate(bboxes):
#         x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]
#
#         id_ = int(ids[i]) if ids is not None else 0
#         label = ''
#         # caption (eg) label='person', id=1 → caption='person1'
#         caption = '{}{:d}'.format(label, id_)
#         text_size, _ = cv2.getTextSize(text=caption, fontFace=cv2.FONT_HERSHEY_PLAIN,
#                                        fontScale=2, thickness=2)
#         color = id_rgb(id_)
#         # draw a bounding box(bbox)
#         cv2.rectangle(img=img, pt1=(x1, y1), pt2=(x2, y2),
#                       color=color, thickness=3)
#         # draw a caption bar and put caption on it
#         cv2.rectangle(img=img, pt1=(x1, y1),
#                       pt2=(x1 + text_size[0] + 3, y1 + text_size[1] + 4),
#                       color=color, thickness=-1)
#         cv2.putText(img=img, text=caption,
#                     org=(x1, y1 + text_size[1] + 4), fontFace=cv2.FONT_HERSHEY_PLAIN,
#                     fontScale=2, color=(255, 255, 255), thickness=2)
#     return img
#
#
# def img_to_video(img_dir, img_type='jpg', vid_type='mp4'):
#     imgs = []
#     img_files_list = glob.glob('{}/*.{}'.format(img_dir, img_type))
#     img_files_list.sort()
#
#     for filename in img_files_list:
#         img = cv2.imread(filename)
#         height, width, layers = img.shape
#         size = (width, height)
#         imgs.append(img)
#
#     out = cv2.VideoWriter('result.{}'.format(vid_type), cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
#
#     for img in imgs:
#         out.write(img)
#     out.release()


# Python Project 1: Sudoku Solver
# Started 8/8/2021
# Finished 8/11/2021
# Status: Completed
# -----------------------------------------------------
# Purpose of Project/Learning Goals:
#   -Understand Recursion
#   -Understand Backtracking
#   -Python Syntax (transitioning from C++)
# -----------------------------------------------------

def printGrid():  # print Grid
    print("\n")
    print(*grid, sep="\n")

def findEmpty(i, j):
    # Start from last 0
    for x in range(i,9):
        for y in range (j,9):
            if grid[x][y] == 0:
                print("Reset Empty: " + str(x) + ", " + str(y))
                return x, y
    # Starts from beginning
    for x in range(0,9):
        for y in range (0,9):
            if grid[x][y] == 0:
                print("Reset Empty: " + str(x) + ", " + str(y))
                return x, y
    print("No Empty: " + str(x)+ "," + str(y))
    return -1,-1

def isSafe(fillNum,i,j): # check if number is safe
    if checkBox(fillNum, i,j) and checkCol(fillNum, j) and checkRow(fillNum,i):
        return True
    else:
        return False

def checkRow(rowFill, i):
    for y in range(9):
        if grid[i][y] == rowFill:
            return False
    return True
def checkCol(colFill, j):
    for x in range(9):
        if grid[x][j] == colFill:
            return False
    return True
def checkBox(boxFill,x,y):
    startRow = x - x % 3
    startCol = y - y % 3
    for r in range(3):
        for c in range(3):
            if grid[startRow+r][startCol+c] == boxFill:
                return False
    return True

def sudokuSolver(grid, i=0, j=0):
    i,j = findEmpty(i,j)
    if i == -1:
        print("\n Solved!")
        return True
    for x in range(9):
        if isSafe(x+1,i,j):
            grid[i][j] = x+1
            printGrid()
            if sudokuSolver(grid,i,j):
                return True
            print("BEFORE RESET 0")
            printGrid()
            grid[i][j] = 0
            print("AFTER RESET 0")
            printGrid()
    print("FALSE SOLUTION")
    return False

if __name__ == '__main__':
    grid = [[0 for x in range(9)] for y in range(9)]
    grid = [[3, 0, 6, 5, 0, 8, 4, 0, 0],
            [5, 2, 0, 0, 0, 0, 0, 0, 0],
            [0, 8, 0, 0, 0, 0, 0, 3, 1],
            [0, 0, 3, 0, 1, 0, 0, 8, 0],
            [9, 0, 0, 8, 0, 3, 0, 0, 5],
            [0, 5, 0, 0, 9, 0, 6, 0, 0],
            [1, 3, 0, 0, 0, 0, 2, 5, 0],
            [0, 0, 0, 0, 0, 0, 0, 7, 4],
            [0, 0, 5, 2, 0, 6, 3, 0, 0]]

    printGrid()
    sudokuSolver(grid)
    print("FINISHED")
    printGrid()


"""Control module for the Vapourtec R4 heater."""
from __future__ import annotations

from collections import namedtuple
from collections.abc import Iterable

import aioserial
import pint
from loguru import logger

from flowchem import ureg
from flowchem.components.device_info import DeviceInfo
from flowchem.components.technical.temperature import TempRange
from flowchem.devices.flowchem_device import FlowchemDevice
from flowchem.devices.vapourtec.r4_heater_channel_control import R4HeaterChannelControl
from flowchem.utils.exceptions import InvalidConfigurationError
from flowchem.utils.people import dario, jakob, wei_hsin

try:
    # noinspection PyUnresolvedReferences
    from flowchem_vapourtec import VapourtecR4Commands

    HAS_VAPOURTEC_COMMANDS = True
except ImportError:
    HAS_VAPOURTEC_COMMANDS = False

class R4Heater(FlowchemDevice):
    """R4 reactor heater control class."""

    DEFAULT_CONFIG = {
        "timeout": 0.1,
        "baudrate": 19200,
        "parity": aioserial.PARITY_NONE,
        "stopbits": aioserial.STOPBITS_ONE,
        "bytesize": aioserial.EIGHTBITS,
    }

    ChannelStatus = namedtuple("ChannelStatus", "state, temperature")

    def __init__(
        self,
        name: str = "",
        min_temp: float | list[float] = -100,
        max_temp: float | list[float] = 250,
        **config,
    ) -> None:
        super().__init__(name)
        # Set min and max temp for all 4 channels
        if not isinstance(min_temp, Iterable):
            min_temp = [min_temp] * 4
        if not isinstance(max_temp, Iterable):
            max_temp = [max_temp] * 4
        assert len(min_temp) == len(max_temp) == 4
        self._min_t = min_temp * ureg.degreeC
        self._max_t = max_temp * ureg.degreeC

        if not HAS_VAPOURTEC_COMMANDS:
            msg = (
                "You tried to use a Vapourtec device but the relevant commands are missing!"
                "Unfortunately, we cannot publish those as they were provided under NDA."
                "Contact Vapourtec for further assistance."
            )
            raise InvalidConfigurationError(
                msg,
            )

        self.cmd = VapourtecR4Commands()

        # Merge default settings, including serial, with provided ones.
        configuration = R4Heater.DEFAULT_CONFIG | config
        try:
            self._serial = aioserial.AioSerial(**configuration)
        except aioserial.SerialException as ex:
            msg = f"Cannot connect to the R4Heater on the port <{config.get('port')}>"
            raise InvalidConfigurationError(
                msg,
            ) from ex

        self.device_info = DeviceInfo(
            authors=[dario, jakob, wei_hsin],
            manufacturer="Vapourtec",
            model="R4 reactor module",
        )

    async def initialize(self):
        """Ensure connection."""
        self.device_info.version = await self.version()
        logger.info(f"Connected with R4Heater version {self.device_info.version}")
        temp_limits = {
            ch_num: TempRange(
                min=ureg.Quantity(f"{t[0]} °C"),
                max=ureg.Quantity(f"{t[1]} °C"),
            )
            for ch_num, t in enumerate(zip(self._min_t, self._max_t, strict=True))
        }
        reactor_positions = [
            R4HeaterChannelControl(f"reactor{n+1}", self, n, temp_limits[n])
            for n in range(4)
        ]
        self.components.extend(reactor_positions)

    async def _write(self, command: str):
        """Write a command to the pump."""
        cmd = command + "\r\n"
        await self._serial.write_async(cmd.encode("ascii"))
        logger.debug(f"Sent command: {command!r}")

    async def _read_reply(self) -> str:
        """Read the pump reply from serial communication."""
        reply_string = await self._serial.readline_async()
        logger.debug(f"Reply received: {reply_string.decode('ascii').rstrip()}")
        return reply_string.decode("ascii")

    async def write_and_read_reply(self, command: str) -> str:
        """Send a command to the pump, read the replies and return it, optionally parsed."""
        self._serial.reset_input_buffer()
        await self._write(command)
        logger.debug(f"Command {command} sent to R4!")
        response = await self._read_reply()

        if not response:
            msg = "No response received from heating module!"
            raise InvalidConfigurationError(msg)

        logger.debug(f"Reply received: {response}")
        return response.rstrip()

    async def version(self):
        """Get firmware version."""
        return await self.write_and_read_reply(self.cmd.VERSION)

    async def set_temperature(self, channel, temperature: pint.Quantity):
        """Set temperature to channel."""
        cmd = self.cmd.SET_TEMPERATURE.format(
            channel=channel,
            temperature_in_C=round(temperature.m_as("°C")),
        )
        await self.write_and_read_reply(cmd)
        # Set temperature implies channel on
        await self.power_on(channel)
        # Verify it is not unplugged
        status = await self.get_status(channel)
        if status.state == "U":
            logger.error(
                f"TARGET CHANNEL {channel} UNPLUGGED! (Note: numbering starts at 0)",
            )

    async def get_status(self, channel) -> ChannelStatus:
        """Get status from channel."""
        # This command is a bit fragile for unknown reasons.
        failure = 0
        while True:
            try:
                raw_status = await self.write_and_read_reply(
                    self.cmd.GET_STATUS.format(channel=channel),
                )
                return R4Heater.ChannelStatus(raw_status[:1], raw_status[1:])
            except InvalidConfigurationError as ex:
                failure += 1
                # Allows 3 failures cause the R4 is choosy at times...
                if failure > 3:
                    raise ex
                else:
                    continue

    async def get_temperature(self, channel):
        """Get temperature (in Celsius) from channel."""
        state = await self.get_status(channel)
        return None if state.temperature == "281.2" else state.temperature

    async def power_on(self, channel):
        """Turn on channel."""
        await self.write_and_read_reply(self.cmd.POWER_ON.format(channel=channel))

    async def power_off(self, channel):
        """Turn off channel."""
        await self.write_and_read_reply(self.cmd.POWER_OFF.format(channel=channel))

if __name__ == "__main__":
    import asyncio

    r4_device = R4Heater(port="COM1")

    async def main(heat):
        """Test function."""
        await heat.initialize()
        # Get reactors
        r1, r2, r3, r4 = heat.components()

        await r1.set_temperature("30 °C")
        print(f"Temperature is {await r1.get_temperature()}")

    asyncio.run(main(r4_device))


from os import name
from django.urls import path
#from .views import HomePageView
from . import views
urlpatterns = [
	path('',views.teacher_index,name='teacher'),  # Homepag

    path('<slug:teacher_id>/<int:choice>/Classes/', views.teacher_home, name="teacher_home"), #Student Batches
    path('<slug:classid>/Students', views.view_teacher_students, name='teacher_stud'),
    path('info/<slug:student>/', views.each_student_info, name='each_student_info'),
    path('<slug:stud>/<slug:course>/<slug:teach>/', views.view_student_attendence, name='student_attendence'),

    # Assignment Routes

    path('<slug:class_id>/<slug:course>/', views.view_assignments_page, name='view_assignments_page'),
    path('/add/<slug:class_id>/<slug:course>/added/',views.add_assigment,name='add_assigment'),

    # get_assigment is used to view teacter's submitted Assignments and Delete is for to Delete Their Assignments
    path('get_assignments_data/', views.get_submitted_assignments, name='view_assignments'),
    path('delete_assignmet/<slug:ta>/deleted', views.delete_assignments, name='delete_assignments'),

    path('view_own_attendance',views.view_attendance,name='view_attendance'),

    path('promote/', views.promote_students, name='promote_students'),
    path('msgfromhod/',views.messages_from_hod, name='messages_from_hod'),
    # Marks Routes
    path('marks/<slug:stud>/<slug:course>/<slug:teach>/', views.teacher_view_marks, name='teacher_view_marks'),
    path('<slug:stud>/<slug:course>/<slug:teach>/take', views.take_marks, name='take_marks'),

    path('profile', views.teacher_profile, name='teacher_profiles'),

    path('profile/<slug:teacher>/update', views.update_profile, name='update_profile'),
    # path('teacher/<int:id>/teacher_view_students/',views.teacher_view_students, name='teacher_view_students'),
    path('logout/',views.logOut, name='logOut'),

]


import tensorflow as tf

# Softmax Regression Model
# Multilayer Convolutional Network
# batch_size=128
def convolutional(image_holder):
    def variable_with_weight_loss(shape, stddev):
        var = tf.Variable(tf.truncated_normal(shape, stddev=stddev))
        return var

    weight1 = variable_with_weight_loss(shape=[5, 5, 3, 64], stddev=5e-2
                                        )  # 设置wl为零，是因为第一层神经网路不需要做正则化处理，5x5的卷积核，RGB通道，64个卷积核
    kernel1 = tf.nn.conv2d(image_holder, weight1, [1, 1, 1, 1], padding='SAME')  # 1，1代表每次选取1x1的
    bias1 = tf.Variable(tf.constant(0.0, shape=[64]))
    conv1 = tf.nn.relu(tf.nn.bias_add(kernel1, bias1))
    pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],
                           padding='SAME')
    #lrn层
    norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)

    weight2 = variable_with_weight_loss(shape=[5, 5, 64, 64], stddev=5e-2)
    kernel2 = tf.nn.conv2d(norm1, weight2, [1, 1, 1, 1], padding='SAME')
    bias2 = tf.Variable(tf.constant(0.1, shape=[64]))
    conv2 = tf.nn.relu(tf.nn.bias_add(kernel2, bias2))
    #lrn层
    norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
    pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],
                           padding='SAME')
    # print('pool2',pool2.shape)
    reshape = tf.reshape(pool2, [-1, 3072])
    # print(reshape.shape)
    # dim = reshape.get_shape()[1].value
    # dim=3072
    weight3 = variable_with_weight_loss(shape=[3072, 384], stddev=0.04)
    bias3 = tf.Variable(tf.constant(0.1, shape=[384]))
    local3 = tf.nn.relu(tf.matmul(reshape, weight3) + bias3)

    weight4 = variable_with_weight_loss(shape=[384, 192], stddev=0.04)
    bias4 = tf.Variable(tf.constant(0.1, shape=[192]))
    local4 = tf.nn.relu(tf.matmul(local3, weight4) + bias4) #128x192
    # print(local4)
    weight5 = variable_with_weight_loss(shape=[192,2], stddev=1 / 192.0)
    bias5 = tf.Variable(tf.constant(0.0, shape=[2]))
    logits = tf.add(tf.matmul(local4, weight5), bias5)
    y = logits
    variables = [weight1, bias1, weight2, bias2, weight3, bias3, weight4, bias4,weight5,bias5]
    return y,variables


from fastapi import HTTPException, status
from odmantic.bson import ObjectId
from typing import List

# Import helpers
from helpers.database import db

# Import Models
from models.currency import Currency

async def currency_exists(cid: ObjectId, loc=None):
    if loc is None:
        loc = []
    loc = ['body'] + loc + ['currency']

    currency = await db.find_one(Currency, Currency.id == cid)
    if currency is None:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=[
                dict(
                    loc=loc,
                    msg='not exists',
                    type='value_error.not.exists'
                )
            ]
        )

    return currency

async def currencies_exists(cids: List[ObjectId], loc=None):
    if loc is None:
        loc = []
    loc = ['body'] + loc

    errors = list()
    if isinstance(cids, List):
        for i, cid in enumerate(cids):
            country = await db.find_one(Currency, Currency.id == cid)
            if country is None:
                errors.append(
                    dict(
                        loc=loc + [i, 'currency'],
                        msg='not exists',
                        type='value_error.not.exists'
                    )
                )

    if len(errors) > 0:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=errors
        )


from os import path
from tIGAr.timeIntegration import *
from PENGoLINS.occ_preprocessing import *
from PENGoLINS.nonmatching_coupling import *

parameters["std_out_all_processes"] = False

SAVE_PATH = "./"

class SplineBC(object):
    """
    Setting Dirichlet boundary condition to tIGAr spline generator.
    """
    def __init__(self, directions=[0,1], sides=[[0,1],[0,1]],
                 fields=[[[0,1,2],[0,1,2]],[[0,1,2],[0,1,2]]],
                 n_layers=[[1,1],[1,1]]):
        self.fields = fields
        self.directions = directions
        self.sides = sides
        self.n_layers = n_layers

    def set_bc(self, spline_generator):
        for direction in self.directions:
            for side in self.sides[direction]:
                for field in self.fields[direction][side]:
                    scalar_spline = spline_generator.getScalarSpline(field)
                    side_dofs = scalar_spline.getSideDofs(direction,
                                side, nLayers=self.n_layers[direction][side])
                    spline_generator.addZeroDofs(field, side_dofs)

def OCCBSpline2tIGArSpline(surface, num_field=3, quad_deg_const=4,
                           spline_bc=None, zero_domain=None,
                           fields=[0,1,2], index=0):
    """
    Convert igakit NURBS to ExtractedBSpline.
    """
    # DIR = SAVE_PATH+"spline_data/extraction_"+str(index)
    quad_deg = surface.UDegree()*quad_deg_const
    spline_mesh = NURBSControlMesh4OCC(surface, useRect=False)
    spline_generator = EqualOrderSpline(worldcomm, num_field, spline_mesh)
    if spline_bc is not None:
        spline_bc.set_bc(spline_generator)
    if zero_domain is not None:
        for i in fields:
            spline_generator.addZeroDofsByLocation(zero_domain(), i)
    # spline_generator.writeExtraction(DIR)
    spline = ExtractedSpline(spline_generator, quad_deg)
    return spline

# Define material and geometric parameters
h_th = Constant(0.04)  # Thickness
E = Constant(1e7)
nu = Constant(0.4)
penalty_coefficient = 1.0e3

print("Importing geometry...")
filename_igs = "./nonmatching_bicuspid.igs"
igs_shapes = read_igs_file(filename_igs, as_compound=False)

bicuspid_leaflets = [topoface2surface(face, BSpline=True)
                     for face in igs_shapes]
num_surfs = len(bicuspid_leaflets)
if mpirank == 0:
    print("Number of surfaces:", num_surfs)

# Geometry preprocessing and surface-surface intersections computation
preprocessor = OCCPreprocessing(bicuspid_leaflets,
                                reparametrize=False, refine=False)
print("Computing intersections...")
preprocessor.compute_intersections(rtol=1e-1, mortar_refine=3)
num_interfaces = preprocessor.num_intersections_all

if mpirank == 0:
    print("Total DoFs:", preprocessor.total_DoFs)
    print("Number of intersections:", num_interfaces)

# display, _, _, _ = init_display()
# preprocessor.display_intersections(display, show_triedron=True)
# preprocessor.display_surfaces(display)

if mpirank == 0:
    print("Creating splines...")
# Create tIGAr extracted spline instances
splines = []
spline_bc0 = SplineBC(directions=[0,1], sides=[[0,1], [0]],
                      n_layers=[[1,1],[2]])
bcs_list = [spline_bc0,]*3 + [None,]*4

for i in range(num_surfs):
    splines += [OCCBSpline2tIGArSpline(bicuspid_leaflets[i],
                                       spline_bc=bcs_list[i], index=i),]

# Create non-matching problem
problem = NonMatchingCoupling(splines, E, h_th, nu, comm=worldcomm)
problem.create_mortar_meshes(preprocessor.mortar_nels)

if mpirank == 0:
    print("Setting up mortar meshes...")

problem.mortar_meshes_setup(preprocessor.mapping_list,
                            preprocessor.intersections_para_coords,
                            penalty_coefficient)

# Create time integrators
rho_inf = Constant(0.5)
delta_t = Constant(1e-4)
n_steps = 100
dens = Constant(1.)

y_old_hom_list = []
ydot_old_hom_list = []
yddot_old_hom_list = []
time_integrator_list = []
y_alpha_list = []
ydot_alpha_list = []
yddot_alpha_list = []
for i in range(num_surfs):
    y_old_hom_list += [Function(problem.splines[i].V)]
    ydot_old_hom_list += [Function(problem.splines[i].V)]
    yddot_old_hom_list += [Function(problem.splines[i].V)]
    time_integrator_list += [GeneralizedAlphaIntegrator(rho_inf, delta_t,
        problem.spline_funcs[i], (y_old_hom_list[i], ydot_old_hom_list[i],
        yddot_old_hom_list[i])),]
    y_alpha_list += [problem.splines[i].rationalize(time_integrator_list[i].x_alpha())]
    ydot_alpha_list += [problem.splines[i].rationalize(time_integrator_list[i].xdot_alpha())]
    yddot_alpha_list += [problem.splines[i].rationalize(time_integrator_list[i].xddot_alpha())]
    time_integrator_list[i].xdot_old.interpolate(Expression(("-1.0","0.0","0.0"),degree=1))

# Create SVK residuals
pressure = Constant(5e3)
source_terms = []
res_list = []
dMass_list = []
residuals = []

# Follower pressure
for i in range(len(splines)):
    A0,A1,A2,dA2,A,B = surfaceGeometry(problem.splines[i],
                                       problem.splines[i].F)
    a0,a1,a2,da2,a,b = surfaceGeometry(problem.splines[i],
                       problem.splines[i].F+problem.spline_funcs[i])
    source_terms += [(pressure)*sqrt(det(a)/det(A))\
                 *inner(a2,problem.splines[i].rationalize(
                  problem.spline_test_funcs[i]))*problem.splines[i].dx,]
    res_list += [Constant(1./time_integrator_list[i].ALPHA_F)\
                 *SVK_residual(problem.splines[i], problem.spline_funcs[i],
                 problem.spline_test_funcs[i], E, nu, h_th, source_terms[i])]
    dMass_list += [dens*h_th*inner(yddot_alpha_list[i],
                   problem.spline_test_funcs[i])*problem.splines[i].dx,]
    residuals += [res_list[i]+dMass_list[i]]

problem.set_residuals(residuals)

# Create pvd files
FILE_FOLDER = "results/"
u_file_names = []
u_files = []
F_file_names = []
F_files = []
for i in range(num_surfs):
    u_file_names += [[],]
    u_files += [[],]
    F_file_names += [[],]
    F_files += [[],]
    for j in range(3):
        # print("J:", j)
        u_file_names[i] += [SAVE_PATH+FILE_FOLDER+"u"
                            +str(i)+"_"+str(j)+"_file.pvd",]
        u_files[i] += [File(u_file_names[i][j]),]
        F_file_names[i] += [SAVE_PATH+FILE_FOLDER+"F"
                            +str(i)+"_"+str(j)+"_file.pvd",]
        F_files[i] += [File(F_file_names[i][j]),]
        if j == 2:
            F_file_names[i] += [SAVE_PATH+FILE_FOLDER+"F"
                                +str(i)+"_3_file.pvd",]
            F_files[i] += [File(F_file_names[i][3]),]

for time_iter in range(n_steps):
    # Save initial zero solution
    if time_iter == 0:
        for i in range(num_surfs):
            soln_split = problem.spline_funcs[i].split()
            for j in range(3):
                soln_split[j].rename("u"+str(i)+"_"+str(j),
                                     "u"+str(i)+"_"+str(j))
                u_files[i][j] << soln_split[j]
                problem.splines[i].cpFuncs[j].rename("F"+str(i)+"_"+str(j),
                                                     "F"+str(i)+"_"+str(j))
                F_files[i][j] << problem.splines[i].cpFuncs[j]
                if j == 2:
                    problem.splines[i].cpFuncs[3].rename("F"+str(i)+"_3",
                                                         "F"+str(i)+"_3")
                    F_files[i][3] << problem.splines[i].cpFuncs[3]

    # Solve nonlinear problem
    print("--- Step:", time_iter, ", time:", time_integrator_list[i].t, "---")
    soln = problem.solve_nonlinear_nonmatching_problem(rtol=1e-4, max_it=30,
                                                       zero_mortar_funcs=False)

    # Save results and move forward
    for i in range(problem.num_splines):
        soln_split = problem.spline_funcs[i].split()
        for j in range(3):
            soln_split[j].rename("u"+str(i)+"_"+str(j), "u"+str(i)+"_"+str(j))
            u_files[i][j] << soln_split[j]
            problem.splines[i].cpFuncs[j].rename("F"+str(i)+"_"+str(j),
                                                 "F"+str(i)+"_"+str(j))
            F_files[i][j] << problem.splines[i].cpFuncs[j]
            if j == 2:
                problem.splines[i].cpFuncs[3].rename("F"+str(i)+"_3",
                                                     "F"+str(i)+"_3")
                F_files[i][3] << problem.splines[i].cpFuncs[3]
        time_integrator_list[i].advance()


from typing import List
from PyQt5 import QtGui
import networkx as nx
from commandbar.api import cmdutils
from commandbar.commands.cmdexc import PrerequisitesError
from commandbar.utils import objreg
from mainwindow.graph_view import GraphView
from mainwindow.mainwindow import MainWindow
from tree_covers.pygraph.metric_spaces import tree_cover_bad_pairs, tree_cover_embedding_distortion

@cmdutils.register(name='calc-stretch', instance='main-window', scope='window', maxsplit=0)
def calculate_stretch(self: MainWindow):
    """
    calculate the stretch of the first graph in the window with respect to the cover
    that is induced by all other graphs in the window
    """
    if len(self.canvases) <= 1:
        raise PrerequisitesError("Number of graph view must be more then 1 to calculate stretch")
    V = set(self.canvases[0].G.nodes)
    if not all(V.issubset(gv.G.nodes) for gv in self.canvases[1:]):
        raise PrerequisitesError("the set of verticies of the first graph must"
                                 "be a subset of the vertices of tje other graphs")
    sc = StretchCalculator(self.canvases)
    objreg.register('stretch-calculator', sc, scope='window', window=self.win_id)

class StretchCalculator:
    def __init__(self, graph_views: List[GraphView]) -> None:
        self.graph_views = graph_views
        self.bad_pairs = self.calc_and_display_strecth_cb()
        # for gv in self.graph_views:
        #     gv.G.register_on_edge_add_callback(self.calc_and_display_strecth_cb)
        #     gv.G.register_on_edge_remove_callback(self.calc_and_display_strecth_cb)
        self.last_bad_pair = None

    def calc_and_display_strecth_cb(self, *args):
        dist = tree_cover_embedding_distortion(self.graph_views[0].G, [gv.G for gv in self.graph_views[1:]])
        print(dist)
        self.bad_pairs = tree_cover_bad_pairs(self.graph_views[0].G, [gv.G for gv in self.graph_views[1:]], 1.1)
        self.bad_pairs = list(self.bad_pairs)
        print(self.bad_pairs)
        self.bad_pairs = iter(self.bad_pairs)
        return self.bad_pairs

    @cmdutils.register(instance='stretch-calculator', name='next-stetch-pair', scope='window')
    def next_pair(self):
        """
        displays the next pair that has high stretch
        and its respective paths in each graph view
        """
        if self.last_bad_pair:
            u, v = self.last_bad_pair
            for gv in self.graph_views:
                p = nx.shortest_path(gv.G, u, v)
                gv.draw_edges(zip(p, p[1:]))
                gv.draw_vertices(p)
        try:
            u, v = next(self.bad_pairs)
            self.last_bad_pair = u, v
            for gv in self.graph_views:
                p = nx.shortest_path(gv.G, u, v)
                red_pen = QtGui.QPen(QtGui.QColor('red'))
                gv.draw_edges(zip(p, p[1:]), red_pen, None)
                gv.draw_vertices(p, red_pen)
        except StopIteration:
            raise PrerequisitesError("Out of bad pairs")


#!/usr/bin/env python
# vim: set expandtab tabstop=4 shiftwidth=4:

import struct
from ftexplorer.data import Data

data = Data('BL2')

#bpd = data.get_struct_by_full_object('GD_ButtStallion_Proto.Character.AIDef_ButtStallion_Proto:AIBehaviorProviderDefinition_1')
bpd = data.get_struct_by_full_object('gd_slotmachine.SlotMachine:BehaviorProviderDefinition_0')
behavior_linkids = {}
for idx, cold in enumerate(bpd['BehaviorSequences'][1]['ConsolidatedOutputLinkData']):
    compliment = int(cold['LinkIdAndLinkedBehavior'])
    # Use big-endian just for clarity's sake
    packed = struct.pack('>i', compliment)
    #print('{:08b} {:08b} {:08b} {:08b}'.format(packed[0], packed[1], packed[2], packed[3]))
    #linkid = compliment >> 16
    #linkid = compliment >> 24
    linkid = packed[0]
    behavior = compliment & 0xFF
    if behavior not in behavior_linkids:
        behavior_linkids[behavior] = {}
    if linkid not in behavior_linkids[behavior]:
        behavior_linkids[behavior][linkid] = 1
    else:
        behavior_linkids[behavior][linkid] += 1
    print('[{:3d}] {:9d} ({:08b} {:08b} {:08b} {:08b}): {}, {}'.format(idx, compliment, packed[0], packed[1], packed[2], packed[3], linkid, behavior))

print('')
for behavior, linkids in behavior_linkids.items():

    show_behavior = False
    if len(linkids) == 1:
        for val in linkids.values():
            if val > 1:
                show_behavior = True
                break
    else:
        show_behavior = True

    if show_behavior:
        print('{}: {}'.format(behavior, linkids))


import citations as cit
import json
from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

years = [ 2015, 2016, 2017, 2018, 2019 ]

class_names = [
    "-",
    "A",
    "B",
    "C",
    "D",
    "E",
]

sectors = [
  "MAT01",
  "MAT02",
  "MAT03",
  "MAT05",
  "MAT06",
  "MAT07",
  "MAT08"
]

classifications = {
   "mcq": {
     "db": "scopus",
     "folder": "MCQ-SCOPUS",
     "sheet": "article_MCQ"
   },

   "sjr": {
     "db": "scopus",
     "folder": "SJR-SNIP",
     "sheet": "article_SJR"
   },

   "snip": {
     "db": "scopus",
     "folder": "SJR-SNIP",
     "sheet": "article_SNIP"
   },

   "mcq-wos": {
     "db": "wos",
     "folder": "MCQ-WOS",
     "sheet": "article_MCQ"
   }
}

sectors_db = {}

for sector in sectors:
  sectors_db[sector] = {}

  for (cl, classification) in classifications.items():
    print("Loading %s / %s ..." % (sector, cl), end = '')
    sectors_db[sector][cl] = { year: db for (year, db) in zip(
        years,
        map(lambda x : cit.get_journals_classification(x, classification["db"], sector, classification["folder"], classification["sheet"]), years)
    ) }
    print(" done.")

# We also build a set with all Journal names
print("Building index of Journal names ... ", end = '')
journal_names = set()
for sector in sectors:
  for classification in classifications:
    for year in years:
      for name in sectors_db[sector][classification][year].keys():
        journal_names.add(name)
print(" done.")

@app.route("/")
def index():
  return "Hello"

@app.route("/api/v1/search-journal", methods = [ "POST" ])
def search_journal():
  d = json.loads(request.data)
  name = d["journal"].lower()

  print("Searching %s" % name)
  print(journal_names)

  matching_j = list(filter(lambda x : d["journal"].lower() in x, journal_names))

  return json.dumps(matching_j)

@app.route("/api/v1/journals", methods = [ "GET" ])
def journals():
  return json.dumps(list(journal_names))

@app.route("/api/v1/classify", methods = [ "POST" ])
def classify():
  d = json.loads(request.data)

  journal = d["journal"].lower()
  scopus_citations = d["scopus-citations"]
  wos_citations = d["wos-citations"]
  year = int(d["year"])
  sector = d["sector"].replace("/", "")

  cl_mcq = cit.get_classification(journal, scopus_citations, sectors_db[sector]["mcq"][year])
  cl_sjr = cit.get_classification(journal, scopus_citations, sectors_db[sector]["sjr"][year])
  cl_snip = cit.get_classification(journal, scopus_citations, sectors_db[sector]["snip"][year])
  cl_wos = cit.get_classification(journal, wos_citations, sectors_db[sector]["mcq-wos"][year])

  return json.dumps({
    "mcq": class_names[cl_mcq+1],
    "sjr": class_names[cl_sjr+1],
    "snip": class_names[cl_snip+1],
    "mcq-wos": class_names[cl_wos+1]
  })