from __future__ import absolute_import
from __future__ import unicode_literals

import json
import jwt
import datetime
import requests
import time
import urllib3
import re

__all__ = [
    "ERROR",
    "Warning",
    "InterfaceERROR",
    "DatabaseERROR",
    "InternalERROR",
    "OperationalERROR",
    "ProgrammingERROR",
    "DataERROR",
    "NotSupportedERROR",
]

class ERROR(Exception):
    pass

class Warning(Exception):
    pass

class InterfaceERROR(ERROR):
    pass

class DatabaseERROR(ERROR):
    pass

class InternalERROR(DatabaseERROR):
    pass

class OperationalERROR(DatabaseERROR):
    pass

class ProgrammingERROR(DatabaseERROR):
    pass

class IntegrityERROR(DatabaseERROR):
    pass

class DataERROR(DatabaseERROR):
    pass

class NotSupportedERROR(DatabaseERROR):
    pass

class uptycs_rest_call(object):
    def __init__(
        self,
        url=None,
        customer_id=None,
        key=None,
        secret=None,
        verify_ssl=False,
        api=None,
        method=None,
        post_data=None,
        media_type=None,
        download_location=None,
        threat_source_name=None,
        threat_source_description=None,
        threat_data_csv=None,
        **kwargs
    ):

        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        self.baseurl = url
        self.customer_id = customer_id
        self.final_url = "%s/public/api/customers/%s%s" % (url, customer_id, api)
        self.api = api
        self.osquery_list_url = "%s/public/api/osqueryPackages" % (url)
        self.key = key
        self.secret = secret
        self.method = method
        self.verify_ssl = verify_ssl
        self.post_data = post_data
        self.media_type = media_type
        self.download_location = download_location
        self.threat_data_csv = threat_data_csv
        self.threat_source_name = threat_source_name
        self.threat_source_description = threat_source_description

        self.header = {}
        utcnow = datetime.datetime.utcnow()
        date = utcnow.strftime("%a, %d %b %Y %H:%M:%S GMT")
        authVar = jwt.encode({"iss": self.key, 'exp': time.time() + 60}, self.secret, algorithm="HS256")
        authorization = "Bearer %s" % (authVar)
        self.header["date"] = date
        self.header["Authorization"] = authorization

        self._is_response_json = False
        self._error = None
        self._response_content = None

    @property
    def is_response_json(self):
        return self._is_response_json

    @property
    def response_content(self):
        return self._response_content

    @property
    def errir(self):
        return self._error

    def filename_in_content_disposition(self, contnt_disp):
        """
            Get filename from content-disposition
            """
        if not contnt_disp:
            return None
        fname = re.findall("filename=(.+)", contnt_disp)
        if len(fname) == 0:
            return None
        filename = fname[0]
        if (filename.startswith('"') and filename.endswith('"')) or (
            filename.startswith("'") and filename.endswith("'")
        ):
            filename = filename[1:-1]
        if self.download_location:
            filename = self.download_location + "/" + filename
        return filename

    def rest_api_call(self):

        if (
            self.method.lower() == "get"
            and not self.api.startswith("/packageDownloads")
            and self.api != "/osqueryPackages"
        ):
            try:
                response = requests.get(
                    url=self.final_url, headers=self.header, verify=self.verify_ssl
                )
                if response and response.status_code in [
                    requests.codes.ok,
                    requests.codes.bad,
                ]:
                    self._is_response_json = True
                    self._response_content = response.content.decode("utf-8")
                else:
                    self._is_response_json = False
                    self._response_content = response.content

            except requests.exceptions.RequestException as e:
                self._error = "ERROR: {}".format(e)
                raise OperationalERROR(self._error)

        elif (self.method.lower() == "get") and self.api.startswith(
            "/packageDownloads"
        ):
            try:
                response = requests.get(
                    url=self.final_url,
                    headers=self.header,
                    verify=self.verify_ssl,
                    allow_redirects=True,
                )
                if response and response.status_code in [
                    requests.codes.ok,
                    requests.codes.bad,
                ]:
                    self._is_response_json = True
                    filename = self.filename_in_content_disposition(
                        response.headers.get("content-disposition")
                    )
                    open(filename, "wb").write(response.content)

                    temp_response_content = {
                        "status": response.status_code,
                        "filename": filename,
                    }
                    self._response_content = json.dumps(temp_response_content).decode(
                        "utf-8"
                    )
                else:
                    self._is_response_json = False
                    self._response_content = response.content

            except requests.exceptions.RequestException as e:
                self._error = "ERROR: {}".format(e)
                raise OperationalERROR(self._error)

        elif self.method.lower() == "get" and self.api == "/osqueryPackages":
            try:
                response = requests.get(
                    url=self.osquery_list_url,
                    headers=self.header,
                    verify=self.verify_ssl,
                )
                if response and response.status_code in [
                    requests.codes.ok,
                    requests.codes.bad,
                ]:
                    self._is_response_json = True
                    self._response_content = response.content.decode("utf-8")
                else:
                    self._is_response_json = False
                    self._response_content = response.content

            except requests.exceptions.RequestException as e:
                self._error = "ERROR: {}".format(e)
                raise OperationalERROR(self._error)

        elif self.method.lower() == "post" and self.api == "/threatSources":
            if (
                self.threat_source_name
                and self.threat_source_description
                and self.threat_data_csv
            ):
                try:
                    files = {"file": open(self.threat_data_csv, "rb")}

                    payload = {
                        "name": self.threat_source_name,
                        "description": self.threat_source_description,
                    }
                    response = requests.post(
                        headers=self.header,
                        url=self.final_url,
                        files=files,
                        data=payload,
                        verify=self.verify_ssl,
                        timeout=None,
                    )
                    if response and response.status_code in [
                        requests.codes.ok,
                        requests.codes.bad,
                    ]:
                        self._is_response_json = True
                    self._response_content = response.content.decode("utf-8")
                except requests.exceptions.RequestException as e:
                    self._error = "ERROR: {}".format(e)
                    raise OperationalERROR(self._error)

            else:
                raise OperationalERROR(
                    "ERROR: with post method. " "please pass post data json"
                )

        elif self.method.lower() == "post":
            if self.post_data:
                try:
                    response = requests.post(
                        url=self.final_url,
                        headers=self.header,
                        json=self.post_data,
                        verify=self.verify_ssl,
                        timeout=None,
                    )
                    if response and response.status_code in [
                        requests.codes.ok,
                        requests.codes.bad,
                    ]:
                        self._is_response_json = True
                    self._response_content = response.content.decode("utf-8")
                except requests.exceptions.RequestException as e:
                    self._error = "ERROR: {}".format(e)
                    raise OperationalERROR(self._error)

            else:
                raise OperationalERROR(
                    "ERROR: with post method. " "please pass post data json"
                )

        elif self.method.lower() == "put":
            if self.post_data:
                try:
                    response = requests.put(
                        url=self.final_url,
                        headers=self.header,
                        json=self.post_data,
                        verify=self.verify_ssl,
                        timeout=None,
                    )
                    if response and response.status_code in [
                        requests.codes.ok,
                        requests.codes.bad,
                    ]:
                        self._is_response_json = True
                    self._response_content = response.content.decode("utf-8")
                except requests.exceptions.RequestException as e:
                    self._error = "ERROR: {}".format(e)
                    raise OperationalERROR(self._error)

            else:
                raise OperationalERROR(
                    "ERROR: with put method. " "please pass post data json"
                )

        elif self.method.lower() == "delete":
            try:
                response = requests.delete(
                    url=self.final_url,
                    headers=self.header,
                    verify=self.verify_ssl,
                    timeout=None,
                )
                if response and response.status_code in [
                    requests.codes.ok,
                    requests.codes.bad,
                ]:
                    self._is_response_json = False
                self._response_content = response.content.decode("utf-8")
            except requests.exceptions.RequestException as e:
                self._error = "ERROR: {}".format(e)
                raise OperationalERROR(self._error)
        else:
            raise OperationalERROR("ERROR: Unknown request")


import json
import logging
from collections import defaultdict

from mmcv.utils import get_logger

def get_root_logger(log_file=None, log_level=logging.INFO):
    """Get root logger.

    Args:
        log_file (str, optional): File path of log. Defaults to None.
        log_level (int, optional): The level of logger.
            Defaults to :obj:`logging.INFO`.

    Returns:
        :obj:`logging.Logger`: The obtained logger
    """
    return get_logger('mmcls', log_file, log_level)

def load_json_log(json_log):
    """load and convert json_logs to log_dicts.

    Args:
        json_log (str): The path of the json log file.

    Returns:
        dict[int, dict[str, list]]:
            Key is the epoch, value is a sub dict. The keys in each sub dict
            are different metrics, e.g. memory, bbox_mAP, and the value is a
            list of corresponding values in all iterations in this epoch.

            .. code-block:: python

                # An example output
                {
                    1: {'iter': [100, 200, 300], 'loss': [6.94, 6.73, 6.53]},
                    2: {'iter': [100, 200, 300], 'loss': [6.33, 6.20, 6.07]},
                    ...
                }
    """
    log_dict = dict()
    with open(json_log, 'r') as log_file:
        for line in log_file:
            log = json.loads(line.strip())
            # skip lines without `epoch` field
            if 'epoch' not in log:
                continue
            epoch = log.pop('epoch')
            if epoch not in log_dict:
                log_dict[epoch] = defaultdict(list)
            for k, v in log.items():
                log_dict[epoch][k].append(v)
    return log_dict


"""Tests for bocs."""
from vizier._src.algorithms.designers import harmonica
from vizier._src.algorithms.testing import test_runners
from vizier._src.benchmarks.experimenters import combo_experimenter

from absl.testing import absltest

class HarmonicaTest(absltest.TestCase):

  def test_make_suggestions(self):
    experimenter = combo_experimenter.IsingExperimenter(lamda=0.01)
    designer = harmonica.HarmonicaDesigner(
        experimenter.problem_statement(), num_init_samples=1)

    num_trials = 10
    trials = test_runners.run_with_random_metrics(
        designer,
        experimenter.problem_statement(),
        iters=num_trials,
        batch_size=1,
        verbose=1,
        validate_parameters=True)
    self.assertLen(trials, num_trials)

if __name__ == '__main__':
  absltest.main()


# -*- coding: utf-8 -*-
import urllib
import urllib2
import re
import sys
import json

class ObjectConstructor(object):

    def __init__(self, index, queryword):
        with open('./info/' + str(index) + '.txt', 'r') as f:
            self.data = json.load(f)
            self.key_words = list(queryword)

    def get_title(self):
        title = ''
        for char in self.data['title']:
            if char in self.key_words:
                char = '' + char + ''
            title += char
        return title

    def get_text(self):
        string = self.data['text']
        cur = string.find(self.key_words[0])
        i = max(0, cur - 40)
        j = cur + 90
        origin = string[i:j]
        returnString = ''
        for char in origin:
            if char in self.key_words:
                char = '' + char + ''
            returnString += char
        return returnString

    def get_url_ori(self):
        return self.data['url']


from flask import Flask, render_template, request
import numpy as np
import pandas as pd

from sklearn.preprocessing import StandardScaler
from src.pipeline.predict_pipeline import CustomData, PredictPipeline

import warnings
warnings.filterwarnings('ignore')

application = Flask(__name__)

app = application

# @app.route('/')
# def index():
#     return render_template('index.html')

@app.route('/', methods=['GET', 'POST'])
def predict_data():
    if request.method=="GET":
        return render_template('home.html')

    else:
        data = CustomData(
            Age = request.form.get('age'),
            Sex = request.form.get('sex'),
            ChestPainType = request.form.get('chestpaintype'),
            RestingBP = request.form.get('resting_bp'),
            Cholesterol = request.form.get('cholesterol'),
            FastingBS = request.form.get('fasting_bs'),
            RestingECG = request.form.get('resting_ecg'),
            MaxHR = request.form.get('max_hr'),
            ExerciseAngina = request.form.get('exercise_angina'),
            Oldpeak = request.form.get('oldpeak'),
            ST_Slope = request.form.get('st_slope'),
        )

        pred_df = data.get_data_as_data_frame()
        print(pred_df)
        print("Before Prediction")

        predict_pipeline = PredictPipeline()
        print("Mid Prediction")

        result = predict_pipeline.predict(pred_df)
        results = int(result[0])
        print("After Prediction")

        if results == 1:
            predicted_text = "Heart Disease Predicted"
        else:
            predicted_text = "Heart Disease Not Predicted"

        print(predicted_text)

        return render_template('home.html', predicted_text=predicted_text)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True, port=5000)


# from pudb import set_trace; set_trace()
from typing import List

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        """LeetCode 503

        The same stack solution as in the easier version of this problem. The
        only trick is that we need to run the same algorithm twice to count for
        looping around.

        O(N), 228 ms, 61% ranking.
        """
        stack, N = [], len(nums)
        res = [-1] * N

        def find_next_greater(end_idx: int) -> None:
            for i in range(end_idx + 1):
                while stack and stack[-1][1] < nums[i]:
                    idx, _ = stack.pop()
                    if res[idx] < 0:
                        res[idx] = nums[i]
                stack.append((i, nums[i]))

        find_next_greater(N - 1)  # first round
        find_next_greater(N - 2)  # second round
        return res

sol = Solution()
tests = [
    ([1, 2, 1], [2, -1, 2]),
    ([1, 2, 3, 4, 3], [2, 3, 4, -1, 4]),
]

for i, (nums, ans) in enumerate(tests):
    res = sol.nextGreaterElements(nums)
    if res == ans:
        print(f'Test {i}: PASS')
    else:
        print(f'Test {i}; Fail. Ans: {ans}, Res: {res}')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pyquery import PyQuery

def get_exchange_rate():
    html = PyQuery('https://rate.bot.com.tw/xrt?Lang=zh-TW')
    currency_names = html('div.hidden-phone').text().split()
    bid_filter = 'td.rate-content-cash[data-table="本行現金買入"]'
    offer_filer = 'td.rate-content-cash[data-table="本行現金賣出"]'
    currency_bids = html(bid_filter).text().split()
    currency_offers = html(offer_filer).text().split()
    currency = {}

    price_idx = 0
    for idx, name in enumerate(currency_names):

        if idx % 2 == 0:

            # EX: "美金": { "bids": "30.00", "offers": "30.50" }
            currency[name] = {
                "bids": currency_bids[price_idx],
                "offers": currency_offers[price_idx]
            }

            price_idx += 1
    # {"美元":{"bids": 30,"offers": 30},""}
    return currency


import argparse
import os
import parser
from functools import partial

import dataset
import evaluate
import longrange
import lovely_tensors as lt
import matplotlib.pyplot as plt
import numpy as np
import torch
import util
import wandb
from tqdm import tqdm
from tqdm.auto import tqdm

lt.monkey_patch()

def train_transformer(ds, net, n_batches=10, batch_size=32, seq_len=100, lr=1e-3, device='cpu', wandb=None, tqdm=None):
    net.to(device).train()
    opt = torch.optim.Adam(net.parameters(), lr=lr)

    pbar = dataset.get_seq_batches(ds, n_batches, batch_size, n_seqs=1, seq_len=seq_len, min_dist=0, max_dist=1, unbind=True)
    pbar = pbar if tqdm is None else tqdm(pbar, total=n_batches)
    for (batch1,), (batch1fchar,) in pbar:
        batch1 = batch1.to(device).long()

        loss = longrange.loss_fn(net, batch1)
        opt.zero_grad()
        loss.backward()
        opt.step()

        grad_main = torch.cat([p.grad.flatten() for p in net.blocks_main.parameters()]).norm().item()

        data = dict(loss=loss.item(), grad_main=grad_main)
        if tqdm is not None:
            pbar.set_postfix({k: v for k, v in data.items() if isinstance(v, float)})
        if wandb is not None:
            wandb.log(data)

def train_longrange(net, ds, n_batches, batch_size,
                    n_seqs, seq_len, min_dist, max_dist,
                    lr=1e-3, device='cpu', wandb=None, tqdm=None):
    net.to(device).train()
    opt = torch.optim.Adam(net.parameters(), lr=lr)
    # scheduler = torch.optim.MultiStepLR(opt, milestones=[1000], gamma=0.1)

    pbar = dataset.get_seq_batches(ds, n_batches, batch_size, n_seqs, seq_len,
                                   min_dist, max_dist, unbind=False, device=device)
    pbar = pbar if tqdm is None else tqdm(pbar, total=n_batches)
    for ids, fbins in pbar:
        # ids: (bs, n_seqs, seq_len), fbins: (bs, n_seqs, seq_len)
        losses = longrange.loss_fn_longrange(net, ids) #: (bs, n_seqs, seq_len-1)
        loss = losses.mean()

        opt.zero_grad()
        loss.backward()
        opt.step()

        grad_main = torch.cat([p.grad.flatten() for p in net.blocks_main.parameters()]).norm()

        data = dict(ppl=loss.exp().item())
        data.update({f'ppl_seq_{seq_i}': losses_seq_i.mean().exp().item()
                     for seq_i, losses_seq_i in enumerate(losses.unbind(dim=-2))})
        data.update(grad_main=grad_main.item())
        if net.config['use_memory']:
            grad_mc = torch.cat([p.grad.flatten() for p in net.blocks_memory_creator.parameters()]).norm()
            grad_mr = torch.cat([p.grad.flatten() for p in net.blocks_memory_retriever.parameters()]).norm()
            data.update(grad_mc=grad_mc.item(), grad_mr=grad_mr.item())

        if tqdm is not None:
            pbar.set_postfix({k: v for k, v in data.items() if isinstance(v, float)})
        if wandb is not None:
            wandb.log(data)

# def log_network_stats(akl, net):
#     grad_mag = [block.attn.out_proj.weight.grad.norm().item() for block in net.blocks_main]
#     akl.put(grad_blocks_main=grad_mag)
#     grad_mag = [block.attn.out_proj.weight.grad.norm().item() for block in net.blocks_memory_retriever]
#     akl.put(grad_blocks_retriever=grad_mag)
#     grad_mag = [block.attn.out_proj.weight.grad.norm().item() for block in net.blocks_memory_creator]
#     akl.put(grad_blocks_creator=grad_mag)
#     if akl.ts%20==0:
#         for name, module in net.named_modules():
#             if isinstance(module, longrange.Block):
#                 key = f'attn_mat_{name}'
#                 akl.put(**{key: module.attn_weights.detach().cpu().numpy()})

# def print_network_gradient_stats(net):
#     print('Main blocks gradient mag:')
#     for block in net.blocks_main:
#         gradmag = block.attn.out_proj.weight.grad.norm().item()
#         print(f'{gradmag: .3e}', end=' ')
#     print()
#     print('Memory Retrieval blocks gradient mag:')
#     for block in net.blocks_memory_retriever:
#         gradmag = block.attn.out_proj.weight.grad.norm().item()
#         print(f'{gradmag: .3e}', end=' ')
#     print()
#     print('Memory Creator blocks gradient mag:')
#     for block in net.blocks_memory_creator:
#         gradmag = block.attn.out_proj.weight.grad.norm().item()
#         print(f'{gradmag: .3e}', end=' ')
#     print()

def main(args):
    print(f'Starting training with args: {args}')
    print('Loading dataset...')
    ds_train, ds_test = dataset.load_dataset(tqdm=tqdm)
    print('Done!')
    np.random.seed(args.seed); torch.manual_seed(args.seed)
    config_net = longrange.get_config(args.model, max_context_length=args.seq_len)
    net = longrange.LongRangeGPT(**config_net)
    print(f'Model: {args.model}')
    print(f'Model config: {config_net}')
    print(f'Model # of parameters: {util.count_params(net)}')

    config = vars(args)
    config['config_net'] = config_net

    if args.track:
        run = wandb.init(config=config, name=args.name, save_code=True)

    n_seqs_train = 2 if net.config['use_memory'] else 1
    n_seqs_test = 4 if net.config['use_memory'] else 1
    train_longrange(net=net, ds=ds_train, n_batches=args.n_batches_train, batch_size=args.batch_size,
                    n_seqs=n_seqs_train, seq_len=args.seq_len, min_dist=args.min_dist, max_dist=args.max_dist,
                    lr=args.lr, device=args.device, wandb=wandb if args.track else None, tqdm=tqdm)
    loss_mean, loss_count = evaluate.evaluate_longrange(net=net, ds=ds_test, n_batches=args.n_batches_test, batch_size=args.batch_size,
                                                        n_seqs=n_seqs_test, seq_len=args.seq_len, min_dist=0, max_dist=1,
                                                        device=args.device, wandb=wandb if args.track else None, tqdm=tqdm)

    if args.track:
        for i_seq in range(len(loss_mean)):
            fig = evaluate.viz_losses(loss_mean[i_seq], loss_count[i_seq])
            plt.suptitle(f'Losses for sequence {i_seq}')
            wandb.log({f'viz loss': fig})

        net.eval().cpu()

        # make the log directory recursively
        os.makedirs(f'./results/{run.name}', exist_ok=True)
        torch.save(net, f'./results/{run.name}/model.pt')
        torch.save((loss_mean, loss_count), f'./results/{run.name}/losses.pt')

        run.finish()
        plt.close('all')

parser = argparse.ArgumentParser(description='Train a model.')

parser.add_argument('--model', type=str, default='longrange')
parser.add_argument('--n_batches_train', type=int, default=5000)
parser.add_argument('--n_batches_test', type=int, default=5000)
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--seq_len', type=int, default=8)
parser.add_argument('--min_dist', type=int, default=0)
parser.add_argument('--max_dist', type=int, default=1)
parser.add_argument('--n_latent_tokens', type=int, default=None)

parser.add_argument('--lr', type=float, default=1e-3)

parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--device', type=str, default='cpu')
parser.add_argument('--track', action=argparse.BooleanOptionalAction, default=False)
parser.add_argument('--name', type=str, default=None)

if __name__ == '__main__':
    args = parser.parse_args()
    main(args)

"""
# Test

python train.py --model transformer --n_batches_train 0100 --n_batches_test 0100 --batch_size 64 --seq_len 8 --seed 0 --lr 1e-3 --device cuda:0 --track --name testing
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 1e-3 --device cuda:0 --track --name testing

# Learning Rate Sweep
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 3e-3 --device cuda:0 --track --name lr_3e-3 &
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 1e-3 --device cuda:0 --track --name lr_1e-3 &
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 6e-4 --device cuda:1 --track --name lr_6e-4 &
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:1 --track --name lr_3e-4 &
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 1e-4 --device cuda:2 --track --name lr_1e-4 &
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 6e-5 --device cuda:2 --track --name lr_6e-5 &
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 3e-5 --device cuda:3 --track --name lr_3e-5 &
python train.py --model transformer --batch_size 64 --seq_len 8 --seed 0 --lr 1e-5 --device cuda:3 --track --name lr_1e-5 &
wait

# Transformer Model Size Sweep
python train.py --model  transformer_small --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:0 --track --name transformer__small &
python train.py --model transformer_medium --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:1 --track --name transformer_medium &
python train.py --model  transformer_large --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:2 --track --name transformer__large &
python train.py --model transformer_xlarge --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:3 --track --name transformer_xlarge &
wait

# Longrange Model Size Sweep
python train.py --model  longrange_small --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:0 --track --name longrange__small &
python train.py --model longrange_medium --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:1 --track --name longrange_medium &
python train.py --model  longrange_large --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:2 --track --name longrange__large &
python train.py --model longrange_xlarge --batch_size 64 --seq_len 8 --seed 0 --lr 3e-4 --device cuda:3 --track --name longrange_xlarge &
wait

# Transformer Seq Length Sweep
python train.py --model transformer --batch_size 64 --seq_len 002 --seed 0 --lr 3e-4 --device cuda:0 --track --name transformer_002 &
python train.py --model transformer --batch_size 64 --seq_len 004 --seed 0 --lr 3e-4 --device cuda:1 --track --name transformer_004 &
python train.py --model transformer --batch_size 64 --seq_len 008 --seed 0 --lr 3e-4 --device cuda:2 --track --name transformer_008 &
python train.py --model transformer --batch_size 64 --seq_len 016 --seed 0 --lr 3e-4 --device cuda:3 --track --name transformer_016 &
python train.py --model transformer --batch_size 64 --seq_len 032 --seed 0 --lr 3e-4 --device cuda:4 --track --name transformer_032 &
python train.py --model transformer --batch_size 64 --seq_len 064 --seed 0 --lr 3e-4 --device cuda:0 --track --name transformer_064 &
wait

# Longrange Seq Length Sweep
python train.py --model longrange --batch_size 64 --seq_len 002 --seed 0 --lr 3e-4 --device cuda:0 --track --name longrange_002 &
python train.py --model longrange --batch_size 64 --seq_len 004 --seed 0 --lr 3e-4 --device cuda:1 --track --name longrange_004 &
python train.py --model longrange --batch_size 64 --seq_len 008 --seed 0 --lr 3e-4 --device cuda:2 --track --name longrange_008 &
python train.py --model longrange --batch_size 64 --seq_len 016 --seed 0 --lr 3e-4 --device cuda:3 --track --name longrange_016 &
python train.py --model longrange --batch_size 64 --seq_len 032 --seed 0 --lr 3e-4 --device cuda:4 --track --name longrange_032 &
python train.py --model longrange --batch_size 64 --seq_len 064 --seed 0 --lr 3e-4 --device cuda:0 --track --name longrange_064 &
wait

python train.py --device cuda:0 --model transformer --seq_len 64 --seed 0

python train.py --device cuda:1 --model perceiver --seq_len 128 --seed 0
python train.py --device cuda:2 --model perceiver --seq_len 256 --seed 0
python train.py --device cuda:0 --model perceiver --seq_len 512 --seed 0

python train.py --device cuda:3 --model longrange1 --seq_len 64 --batch_size 64 --seed 0

python main.py --device cuda:0 --model transformer --seq_len 002 --track --name transformer-002
python main.py --device cuda:0 --model transformer --seq_len 004 --track --name transformer-004
python main.py --device cuda:0 --model transformer --seq_len 008 --track --name transformer-008
python main.py --device cuda:0 --model transformer --seq_len 016 --track --name transformer-016

python main.py --device cuda:1 --model transformer --seq_len 032 --track --name transformer-032
python main.py --device cuda:1 --model transformer --seq_len 064 --track --name transformer-064

python main.py --device cuda:2 --model  longrange1 --seq_len 002 --track --name  longrange1-002
python main.py --device cuda:2 --model  longrange1 --seq_len 004 --track --name  longrange1-004
python main.py --device cuda:2 --model  longrange1 --seq_len 008 --track --name  longrange1-008
python main.py --device cuda:2 --model  longrange1 --seq_len 016 --track --name  longrange1-016

python main.py --device cuda:3 --model  longrange1 --seq_len 032 --track --name  longrange1-032
python main.py --device cuda:3 --model  longrange1 --seq_len 064 --track --name  longrange1-064

"""


import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import numpy as np

from datetime import datetime, timedelta
from matplotlib.dates import date2num
from floodsystem.analysis import polyfit

def plot_water_levels(station, dates, levels):
    """
    Function that plots a graph of the water level over time for a station.
    """

    if len(levels) == 0:
        #plt.text(0,0.1,"NO DATA",fontsize=12,backgroundcolor="red")
        raise IndexError("Missing data")

    plt.plot(dates, levels)

    # check to see if the station has typical low and high levels
    if station.typical_range:
        low, high = station.typical_range
        # plot low and high levels
        plt.axhline(low, color='r', linestyle='--')
        plt.axhline(high, color='r', linestyle='--')

    #dont plot if missing data

    #formatting
    plt.xlabel('date')
    plt.ylabel('water level (m)')
    plt.title(station.name)
    plt.tight_layout()

    plt.show()

def plot_water_level_with_fit(station, dates, levels, p):
    """Plots the water level data and the best-fit polynomial for given station."""

    #get least-square fit of a polynomial of degree P for level history
    poly, d0 = polyfit(dates, levels, p)

    #plot history
    plt.plot(dates, levels)

    #plot typical range
    if station.typical_range:
        low, high = station.typical_range
        plt.axhline(low, color='r', linestyle='--')
        plt.axhline(high, color='r', linestyle='--')

    #plot best fit curve
    x = date2num(dates)
    plt.plot(x, poly(x - d0), color='m')

    #labels
    plt.xlabel('date')
    plt.ylabel('water level (m)')
    plt.title(station.name)
    plt.tight_layout()
    plt.show()


import json, os
from myVars import myCurrentMat

class materialsFile:
    """
    More abstract object for the current materials file.

    Methods:
    get(): Gets and interprets the materials file.  Returns a list of material() objects.
    getraw(): Gets and de-serializes the object, but that's it.  List is in this form:
        [Number of material entries, [[mat1 name, mat1 density, ...], [mat2...]]]
    set(materials): Takes a list in the get() output style and saves it to file.
    """

    FILENAME = "materials.json"

    def __init__(self):  # This must work okay because the files work fine.
        """ Open (or create) the materials data file. """
        if os.path.exists(self.FILENAME):
            self.fileObject = open(self.FILENAME, "r+")
        else:
            tempfile = open(self.FILENAME, 'x')
            tempfile.close()

    def getraw(self):  # Works fine.
        """Get and de-serialize the material data"""
        self.fileObject.seek(0,0)  # Make sure we seek to the beginning of the file.
        try:
            out = json.load(self.fileObject)  # Decode the file.
        except json.JSONDecodeError as err:  # This is the only exception we should have here.
            print("[DEBUG] JSON decode: {}".format(err.msg))  # Complain to the output.
            return(-1)  # Use -1 as an error value, to catch later.
        return(out)

    def get(self):  # This works fine.
        """Get, de-serialize, and interperet the material data."""

        data = self.getraw()    # Get the data
        if data == -1:  # Catch our error value from getraw()
            return(-1)  # Pass it along the line.
        numberOfEntries = data[0]  # The first element of the data list is the number of entires to facilitate error checking.
        materials = []
        for iter1 in range(numberOfEntries):
            materials.append(myCurrentMat.material())  # Instantiate the class here
            cmat = data[1][iter1]   # Shortcut to save typing
            # Assign all of the file's list contents to the right material attribute:
            materials[iter1].name = cmat[0]
            materials[iter1].longName = cmat[1]
            materials[iter1].diameter = cmat[2]
            materials[iter1].density = cmat[3]
            materials[iter1].pricePerKilo = cmat[4]
            materials[iter1].matFlatHandling = cmat[5]
            materials[iter1].matPricePerHr = cmat[6]
        assert len(materials) == numberOfEntries    # This ensures we have the proper number of entries, and that there were no encoding errors.
        return (materials) # Materials is now an array of material objects.

    def set(self, materials):   # So far, this is the one thing that doesn't work right.  I will fix it when I figure out a good way to.
        """
        Serialize and write the provided data to file.

        Arguments:
        materials ([] of material objects) :
        """
        self.fileObject.seek(0,0)   # Make sure we're looking at the beginning of the file.
        output = []
        output.append(len(materials))  # That error checking number.
        output.append([])  # Make sure that's a list so we can append to it.
        for iter2 in materials:
            tempList = []  # A temporary list to save trouble.  This statement clears it for every material in the list.
            # Turn the class variables into a list.
            tempList.append(iter2.name)
            tempList.append(iter2.longName)
            tempList.append(iter2.diameter)
            tempList.append(iter2.density)
            tempList.append(iter2.pricePerKilo)
            tempList.append(iter2.matFlatHandling)
            tempList.append(iter2.matPricePerHr)
            output[1].append(tempList)
        json.dump(output, self.fileObject)  # Dump the list to file.

    def __del__(self):  # I don't know if this really works, and I don't know that it matters a whole lot.
        while fileObject.closed == False:
            fileObject.close()


from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends
from fastapi_pagination import Page

from db.database import get_db
from api.employee import services
from api.employee.schemas import (
    Employee as SchemaEmloyee,
    PostEmployee as SchemaPostEmployee,
    PatchEmployee as SchemaPatchEmployee,
    EmployeeNotFound404,
    EmployeeEmptyJson
)

router = APIRouter(
    prefix="/employee",
    tags=["employee"]
)

@router.get("/", response_model=Page[SchemaEmloyee])
async def list_employee(db: AsyncSession = Depends(get_db)):
    list_employee = await services.list_employee(db)
    return list_employee

@router.get(
    "/{uid}",
    response_model=SchemaEmloyee,
    responses={
        404: {
            "model": EmployeeNotFound404,
            "description": "This endpoint is called if not found Employee"
        }
    }
)
async def get_employee(uid: UUID, db: AsyncSession = Depends(get_db)):
    employee = await services.get_employee(uid, db)
    return employee

@router.post("/", response_model=SchemaEmloyee)
async def create_employee(employee: SchemaPostEmployee, session: AsyncSession = Depends(get_db)):
    db_employee = await services.create_employee(employee, session)
    return db_employee

@router.patch(
    "/{uid}",
    response_model=SchemaPatchEmployee,
    responses={
        404: {
            "model": EmployeeNotFound404,
            "description": "This endpoint is called if not found Employee."
        },
        411: {
            "model": EmployeeEmptyJson,
            "description": "This endpoint is called if send empty Json."
        }
    }
)
async def patch_employee(uid: UUID, employee: SchemaPatchEmployee, session: AsyncSession = Depends(get_db)):
    db_employee = await services.patch_employee(uid, employee, session)
    return db_employee


"""Core game engine logic."""
import ctypes
import enum
import logging
import operator
import textwrap
import importlib.resources
from typing import Iterator
from typing import Literal
from typing import MutableMapping
from typing import Optional
from typing import Tuple
from typing import Union
from PIL import Image, ImageDraw
import sdl2
import sdl2.ext
import sdl2.sdlttf
import sdl2.surface
import itertools
from sdl2 import endian
from pathlib import Path
from animearena.animation import JoinAnimation, SplitAnimation
from animearena.text_formatter import get_lines, get_font_height
def get_image_from_path(file_name: str) -> Image:
    with importlib.resources.path('animearena.resources', file_name) as path:
        return Image.open(path)

RESOURCES = Path(__file__).parent.parent.parent / "resources"
WHITE = sdl2.SDL_Color(255, 255, 255)

def sat_subtract(subtractor: int, subtractee: int) -> int:
    subtractee -= subtractor
    if subtractee < 0:
        subtractee = 0
    return subtractee

def get_mouse_position() -> Tuple[int, int]:
    x, y = ctypes.c_int(0), ctypes.c_int(0)
    sdl2.mouse.SDL_GetMouseState(ctypes.byref(x), ctypes.byref(y))
    return (x.value, y.value)

class Scene:
    """Scene assets, draw regions, and associated game state."""
    surfaces: MutableMapping[str, sdl2.SDL_Surface]
    region: "Region"
    sprite_factory: sdl2.ext.SpriteFactory
    ui_factory: sdl2.ext.UIFactory
    triggered_event: bool
    font: None
    animations: list
    animation_lock: list
    animation_locked: bool
    skipping_animations: bool

    def __init__(self, sprite_type: Union[Literal[0], Literal[1]]):
        self.animations = []
        self.animation_lock = []
        self.skipping_animations = False
        self.animation_locked = False
        self.region = Region()
        self.animation_region = Region()
        self.sprite_factory = sdl2.ext.SpriteFactory(sprite_type, free=True)
        self.ui_factory = sdl2.ext.UIFactory(self.sprite_factory, free=True)
        self.surfaces = dict()
        self.window_closing = False
        self.window_up = False
        self.triggered_event = False

    def add_animation(self, animation):
        self.animations.append(animation)
        if animation.lock:
            self.animation_locked = True
            self.animation_lock.append(animation)

    def remove_animation(self, animation):
        self.animations.remove(animation)

    def check_animation_lock(self, animation):
        self.animation_lock.remove(animation)

    def end_animations(self):
        logging.debug("Calling end animations")
        end_funcs = list()
        for animation in self.animations:
            for func in animation.end_funcs:
                end_funcs.append(func)
        self.animations.clear()
        self.animation_lock.clear()
        self.animation_locked = False
        self.animation_region.clear()
        for func in end_funcs:
            func[0](*func[1])

    def progress_animations(self):
        self.animation_region.clear()
        for animation in self.animations:

            animation.progress_frame_timer()
            if animation.display:
                self.animation_region.add_sprite(animation.current_sprite, animation.display_x, animation.display_y)

    def check_animations(self):
        for animation in self.animations:
            if animation.has_ended:
                animation.end()

        if not self.animation_lock:
            self.animation_locked = False

    def load_assets(self, **kwargs: str):
        log = logging.getLogger(__name__)
        for (k, v) in kwargs.items():
            self.surfaces[k] = get_image_from_path(v)

    def renderables(self) -> Iterator[sdl2.ext.Sprite]:
        for it in [iter(self.region), iter(self.animation_region)]:
            for element in it:
                yield element

    def eventables(self) -> Iterator[sdl2.ext.Sprite]:
        return self.region.eventables()

    def render_text(self, font, text, color, target, x, y, flow = False, target_width = 0, fontsize = 0):
        if not flow:
            text_surface = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(text), color)
            sdl2.surface.SDL_BlitSurface(text_surface, None, target.surface, sdl2.SDL_Rect(x, y))
            sdl2.SDL_FreeSurface(text_surface)
        else:
            lines = get_lines(text, target_width, fontsize)
            line_height = get_font_height(fontsize)
            for i, line in enumerate(lines):
                text_surface = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(line), color)
                sdl2.surface.SDL_BlitSurface(text_surface, None, target.surface, sdl2.SDL_Rect(x, y + (i * line_height)))
                sdl2.SDL_FreeSurface(text_surface)
        return target

    def render_bordered_text(self, font, text, color, border_color, target, x, y, thickness, flow = False, target_width = 0, fontsize = 0):
        if not flow:
            text_surf = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(text), border_color)
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x-thickness, y-thickness))
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x,           y-thickness))
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x+thickness, y-thickness))
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x-thickness, y))
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x+thickness, y))
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x-thickness, y+thickness))
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x,           y+thickness))
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x+thickness, y+thickness))
            sdl2.SDL_FreeSurface(text_surf)

            text_surf = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(text), color)
            sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x, y))
            sdl2.SDL_FreeSurface(text_surf)
        else:
            lines = get_lines(text, target_width, fontsize)
            line_height = get_font_height(fontsize)
            for i, line in enumerate(lines):
                mod_y = y + (i * line_height)
                text_surf = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(line), border_color)
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x-thickness, mod_y-thickness))
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x,           mod_y-thickness))
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x+thickness, mod_y-thickness))
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x-thickness, mod_y))
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x+thickness, mod_y))
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x-thickness, mod_y+thickness))
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x,           mod_y+thickness))
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x+thickness, mod_y+thickness))
                sdl2.SDL_FreeSurface(text_surf)

                text_surf = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(line), color)
                sdl2.surface.SDL_BlitSurface(text_surf, None, target.surface, sdl2.SDL_Rect(x, mod_y))
                sdl2.SDL_FreeSurface(text_surf)

        return target

    def border_image(self, image, thickness):
        new = image.copy()
        w, h = image.size

        brush = ImageDraw.Draw(new)
        brush.rectangle([(0, 0), (w, thickness)], fill="black", outline = "black")
        brush.rectangle([(0, 0), (thickness, h)], fill="black", outline = "black")
        brush.rectangle([(w - 2, 0), (w, h)], fill="black", outline = "black")
        brush.rectangle([(0, h - 2), (w, h)], fill="black", outline = "black")

        return new

    def border_sprite(self, sprite, color, thickness):

        target_surface = sprite.surface
        height = target_surface.h
        width = target_surface.w
        horizontal_border = self.sprite_factory.from_color(color, (width, thickness))
        vertical_border = self.sprite_factory.from_color(color, (thickness, height))

        sdl2.surface.SDL_BlitSurface(horizontal_border.surface, None, sprite.surface, sdl2.SDL_Rect(0, 0))
        sdl2.surface.SDL_BlitSurface(horizontal_border.surface, None, sprite.surface, sdl2.SDL_Rect(0, height - thickness))
        sdl2.surface.SDL_BlitSurface(vertical_border.surface, None, sprite.surface, sdl2.SDL_Rect(0, 0))
        sdl2.surface.SDL_BlitSurface(vertical_border.surface, None, sprite.surface, sdl2.SDL_Rect(width - thickness, 0))

        return sprite

    def blit_surface(self, target, surface, dest):

        sdl2.surface.SDL_BlitSurface(surface, None, target.surface, sdl2.SDL_Rect(*dest))

        return target

    def add_horizontal_line(self, sprite, color, thickness, length, destination):

        line = self.sprite_factory.from_color(color, (length, thickness))
        sdl2.surface.SDL_BlitSurface(line.surface, None, sprite.surface, sdl2.SDL_Rect(*destination))

        return sprite

    def get_scaled_surface(self, img, width: int = 0, height: int = 0, flipped=False) -> sdl2.SDL_Surface:
        image = img
        if width != 0 or height != 0:
            image = image.resize((width, height))
        else:
            width, height = (image.size)
        mode = image.mode
        if flipped:
            image = image.transpose(Image.FLIP_LEFT_RIGHT)
        rmask = gmask = bmask = amask = 0
        if mode in ("1", "L", "P"):
            # 1 = B/W, 1 bit per byte
            # "L" = greyscale, 8-bit
            # "P" = palette-based, 8-bit
            pitch = width
            depth = 8
        elif mode == "RGB":
            # 3x8-bit, 24bpp

            if endian.SDL_BYTEORDER == endian.SDL_LIL_ENDIAN:
                rmask = 0x0000FF
                gmask = 0x00FF00
                bmask = 0xFF0000
            else:
                rmask = 0xFF0000
                gmask = 0x00FF00
                bmask = 0x0000FF
            depth = 24
            pitch = width * 3
        elif mode in ("RGBA", "RGBX"):
            # RGBX: 4x8-bit, no alpha
            # RGBA: 4x8-bit, alpha

            if endian.SDL_BYTEORDER == endian.SDL_LIL_ENDIAN:
                rmask = 0x000000FF
                gmask = 0x0000FF00
                bmask = 0x00FF0000
                if mode == "RGBA":
                    amask = 0xFF000000
            else:
                rmask = 0xFF000000
                gmask = 0x00FF0000
                bmask = 0x0000FF00
                if mode == "RGBA":
                    amask = 0x000000FF
            depth = 32
            pitch = width * 4
        else:
            # We do not support CMYK or YCbCr for now
            raise TypeError("unsupported image format")
        pxbuf = image.tobytes()

        imgsurface = sdl2.ext.surface.SDL_CreateRGBSurfaceFrom(pxbuf, width, height, depth, pitch, rmask, gmask, bmask, amask)
        imgsurface = imgsurface.contents
        imgsurface._pxbuf = pxbuf
        return imgsurface

    def create_selected_version(self, surface: sdl2.SDL_Surface,
                                filter_type: "FilterType") -> sdl2.ext.SoftwareSprite:
        new_sprite = self.ui_factory.from_surface(sdl2.ext.BUTTON, clone_surface(surface))

        filter_string = filter_type.name.lower()

        sdl2.surface.SDL_BlitSurface(self.get_scaled_surface(self.surfaces[filter_string]), None, new_sprite.surface,
                                     sdl2.SDL_Rect(0, 0, 0, 0))
        return new_sprite

    def add_sprite_with_border(self, region: "Region", sprite: sdl2.ext.Sprite, border_sprite, x:int, y:int, depth: int=0):
        region.add_sprite(border_sprite, x - 2, y - 2, depth=depth)
        region.add_sprite(sprite, x, y, depth)

    def add_bordered_sprite(self, region: "Region", sprite: sdl2.ext.Sprite, color: sdl2.SDL_Color, x:int, y:int, depth: int=0):
        width, height = sprite.size
        border_sprite = self.sprite_factory.from_color(color, (width+4, height+4))
        region.add_sprite(border_sprite, x - 2, y - 2, depth=depth)
        region.add_sprite(sprite, x, y, depth)

    def update_text_display(self, font, text, text_color, display, blotter, x, y):
        max_width = display.size[0] - (x * 2)
        char_width = 7.3
        chars_per_line = max_width // char_width

        lines = textwrap.wrap(text, chars_per_line)
        sdl2.surface.SDL_BlitSurface(self.get_scaled_surface(blotter), sdl2.SDL_Rect(0, 0, blotter.size[0], blotter.size[1]), display.surface, sdl2.SDL_Rect(0, 0, 0, 0))
        for row, line in enumerate(lines):
            sdl2.surface.SDL_BlitSurface(sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(line), text_color), None, display.surface,
                                         sdl2.SDL_Rect(x, y + (row * 15), 0, 0))

    def create_text_display(  # pylint: disable=too-many-arguments
            self,
            font: sdl2.sdlttf.TTF_Font,
            text: str,
            text_color: sdl2.ext.Color,
            background_color: sdl2.ext.Color,
            x: int,
            y: int,
            width: int,
            height: Optional[int] = None) -> sdl2.ext.Sprite:

        # create fake tiny lowercase constants to appease the overlord
        horizontal_margin = x
        max_width = width - (horizontal_margin * 2)
        y_offset = 15
        vertical_margin = 15
        char_width = 7.3
        chars_per_line = max_width // char_width

        # get list of lines from full string based on box width
        # lines = textwrap.wrap(text, chars_per_line)
        lines = get_lines(text, max_width, 16)

        # if height is on auto, then set it to a function of the margin plus
        # the space required for all lines
        if height is None:
            true_height = vertical_margin + (13 * len(lines))
        else:
            true_height = vertical_margin + height

        # create rectangular button using parameter-supplied color as background
        # and specified dimensions
        new_sprite = self.ui_factory.from_color(sdl2.ext.BUTTON,
                                                background_color,
                                                size=(width, true_height))
        # for each line in the list of lines, render that line on the sprite's surface
        for row, line in enumerate(lines):
            text_surface = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(line), text_color)
            sdl2.surface.SDL_BlitSurface(text_surface, None, new_sprite.surface,
                                         sdl2.SDL_Rect(x, y + (row * y_offset), 0, 0))
            sdl2.SDL_FreeSurface(text_surface)

        return new_sprite

    def create_bordered_font_text_display(  # pylint: disable=too-many-arguments
            self,
            font: sdl2.sdlttf.TTF_Font,
            text: str,
            text_color: sdl2.ext.Color,
            background_color: sdl2.ext.Color,
            x: int,
            y: int,
            width: int,
            height: Optional[int] = None) -> sdl2.ext.Sprite:

        # create fake tiny lowercase constants to appease the overlord
        horizontal_margin = x
        max_width = width - (horizontal_margin * 2)
        y_offset = 15
        vertical_margin = 15
        char_width = 7.3
        chars_per_line = max_width // char_width

        # get list of lines from full string based on box width
        # lines = textwrap.wrap(text, chars_per_line)
        lines = get_lines(text, max_width, 16)

        # if height is on auto, then set it to a function of the margin plus
        # the space required for all lines
        if height is None:
            true_height = vertical_margin + (13 * len(lines))
        else:
            true_height = vertical_margin + height

        # create rectangular button using parameter-supplied color as background
        # and specified dimensions
        new_sprite = self.ui_factory.from_color(sdl2.ext.BUTTON,
                                                background_color,
                                                size=(width, true_height))
        # for each line in the list of lines, render that line on the sprite's surface
        for row, line in enumerate(lines):
            border_text_surface = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(line), text_color)
            text_surface = sdl2.sdlttf.TTF_RenderText_Blended(font, str.encode(line), WHITE)
            sdl2.surface.SDL_BlitSurface(border_text_surface, None, new_sprite.surface,
                                        sdl2.SDL_Rect(x - 1, y + (row * y_offset) - 1, 0, 0))
            sdl2.surface.SDL_BlitSurface(border_text_surface, None, new_sprite.surface,
                                        sdl2.SDL_Rect(x - 1, y + (row * y_offset) + 1, 0, 0))
            sdl2.surface.SDL_BlitSurface(border_text_surface, None, new_sprite.surface,
                                        sdl2.SDL_Rect(x + 1, y + (row * y_offset) - 1, 0, 0))
            sdl2.surface.SDL_BlitSurface(border_text_surface, None, new_sprite.surface,
                                        sdl2.SDL_Rect(x + 1, y + (row * y_offset) + 1, 0, 0))

            sdl2.surface.SDL_BlitSurface(text_surface, None, new_sprite.surface,
                                         sdl2.SDL_Rect(x, y + (row * y_offset), 0, 0))
            sdl2.SDL_FreeSurface(text_surface)

        return new_sprite

class Region:
    """Spatial region on the screen with relative coordinate offsets & spinning rims."""
    x: int
    y: int
    width: int
    height: int
    _regions: list["Region"]
    _sprites: list[sdl2.ext.Sprite]

    def __init__(self, x: int = 0, y: int = 0, width: int = 0, height: int = 0):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self._regions = []
        self._sprites = []

    def __iter__(self) -> Iterator[sdl2.ext.Sprite]:
        yield from self._sprites
        for subregion in self._regions:
            yield from subregion

    def subregion(self, x: int, y: int, width: int, height: int) -> "Region":
        subreg = Region(self.x + x, self.y + y, width, height)
        self._regions.append(subreg)
        return subreg

    def add_sprite(self, sprite: sdl2.ext.Sprite, x: int, y: int, depth: int = 0):
        sprite.x = self.x + x
        sprite.y = self.y + y
        sprite.depth = depth
        self._sprites.append(sprite)
        self._sprites.sort(key=operator.attrgetter('depth'))

    def add_sprite_vertical_center(self, sprite: sdl2.ext.Sprite, x: int, depth: int = 0):
        sprite.x = self.x + x
        sprite.depth = depth

        region_center = self.height // 2
        sprite_center = sprite.size[1] // 2

        sprite.y = self.y + region_center - sprite_center

        self._sprites.append(sprite)
        self._sprites.sort(key=operator.attrgetter('depth'))

    def size(self) -> Tuple[int, int]:
        return (self.width, self.height)

    def clear(self):
        """Removes all sprites from this region and all sub-regions"""
        self._sprites.clear()

        for subregion in self._regions:
            subregion.clear()

    def from_bottom(self, y: int) -> int:
        return self.height - y

    def from_right(self, x: int) -> int:
        return self.width - x

    def eventables(self) -> Iterator[sdl2.ext.Sprite]:
        for subregion in reversed(self._regions):
            yield from subregion.eventables()
        yield from filter(is_eventable, reversed(self._sprites))

def is_eventable(sprite: sdl2.ext.Sprite) -> bool:
    """"Determines whether a sprite is configured to be an event handler or not."""
    return (isinstance(sprite, sdl2.ext.Sprite) and hasattr(sprite, "events")
            and hasattr(sprite, "uitype"))

def clone_surface(surface: sdl2.SDL_Surface) -> sdl2.SDL_Surface:
    return sdl2.SDL_DuplicateSurface(surface).contents

@enum.unique
class FilterType(enum.IntEnum):
    """A component for denoting which transparent color filter to apply to surfaces"""
    SELECTED = 0
    ALLY = 1
    ENEMY = 2
    LOCKED = 3


import pygtk
pygtk.require('2.0')
import gtk

from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
from seatree.modules.hc.manipulate_hc import ManipulateXYData

class XYDialog:

	def __init__(self, title, parent, filename, tmpn, type):
		# create matplotlib figure
		self.figure = Figure()
		self.canvas = FigureCanvas(self.figure)
		self.mp = ManipulateXYData(filename, type, self.figure, self, tmpn=tmpn)

		# create GTK dialog
		self.dialog = gtk.Dialog(title=title, parent=parent, flags= gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
		self.dialog.set_default_size(500,400)
		self.vBox = self.dialog.vbox

		# setup matplotlib events
		self.canvas.mpl_connect('button_press_event', self.mp.on_click)
		self.canvas.mpl_connect('button_release_event', self.mp.on_release)

		# create buttons
		self.buttonBox = gtk.HBox(homogeneous=True, spacing=5)
		self.saveButton = gtk.Button(label="Save and Use", stock=gtk.STOCK_SAVE)
		self.useButton = gtk.Button(label="Use")
		self.revertButton = gtk.Button(label="Revert")
		self.cancelButton = gtk.Button(label="Cancel")

		# pack buttons
		self.buttonBox.pack_start(self.saveButton, expand=False)
		self.buttonBox.pack_start(self.useButton, expand=False)
		self.buttonBox.pack_start(self.revertButton, expand=False)
		self.buttonBox.pack_end(self.cancelButton, expand=False)

		# connect buttons
		self.use = False
		self.save = False
		self.saveButton.connect("clicked", self.saveHandler)
		self.useButton.connect("clicked", self.useHandler)
		self.revertButton.connect("clicked", self.revertHandler)
		self.cancelButton.connect("clicked", self.cancelHandler)

		# pack and show dialog
		self.vBox.pack_start(self.canvas, expand=True)
		self.vBox.pack_start(gtk.HSeparator(), expand=False)
		self.vBox.pack_end(self.buttonBox, expand=False)
		self.dialog.show_all()

	def redraw(self):
		self.canvas.draw()

	def saveHandler(self, widget):
		self.mp.save_to_file()
		self.save = True
		self.exit()

	def useHandler(self, widget):
		self.mp.save_to_file()
		self.use = True
		self.save = False
		self.exit()

	def revertHandler(self, widget):
		self.mp.reset_data()

	def cancelHandler(self, widget):
		self.save = False
		self.use = False
		self.exit()

	def exit(self):
		self.dialog.hide()
		#self.dialog.response(0)


from decimal import Decimal
import unittest
import datetime

import rdflib  # needed for eval(repr(...)) below
from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind, _XSD_BOOLEAN
from rdflib.namespace import XSD

class TestLiteral(unittest.TestCase):
    def setUp(self):
        pass

    def test_repr_apostrophe(self):
        a = rdflib.Literal("'")
        b = eval(repr(a))
        self.assertEqual(a, b)

    def test_repr_quote(self):
        a = rdflib.Literal('"')
        b = eval(repr(a))
        self.assertEqual(a, b)

    def test_backslash(self):
        d = r"""
<rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:foo="http://example.org/foo#">
    <rdf:Description>
      <foo:bar>a\b</foo:bar>
    </rdf:Description>
</rdf:RDF>
"""
        g = rdflib.Graph()
        g.parse(data=d, format="xml")
        a = rdflib.Literal("a\\b")
        b = list(g.objects())[0]
        self.assertEqual(a, b)

    def test_literal_from_bool(self):
        l = rdflib.Literal(True)
        self.assertEqual(l.datatype, rdflib.XSD["boolean"])

class TestNew(unittest.TestCase):
    def testCantPassLangAndDatatype(self):
        self.assertRaises(
            TypeError, Literal, "foo", lang="en", datatype=URIRef("http://example.com/")
        )

    def testFromOtherLiteral(self):
        l = Literal(1)
        l2 = Literal(l)
        self.assertTrue(isinstance(l.value, int))
        self.assertTrue(isinstance(l2.value, int))

        # change datatype
        l = Literal("1")
        l2 = Literal(l, datatype=rdflib.XSD.integer)
        self.assertTrue(isinstance(l2.value, int))

    def testDatatypeGetsAutoURIRefConversion(self):
        # drewp disapproves of this behavior, but it should be
        # represented in the tests
        x = Literal("foo", datatype="http://example.com/")
        self.assertTrue(isinstance(x.datatype, URIRef))

        x = Literal("foo", datatype=Literal("pennies"))
        self.assertEqual(x.datatype, URIRef("pennies"))

class TestRepr(unittest.TestCase):
    def testOmitsMissingDatatypeAndLang(self):
        self.assertEqual(repr(Literal("foo")), "rdflib.term.Literal('foo')")

    def testOmitsMissingDatatype(self):
        self.assertEqual(
            repr(Literal("foo", lang="en")),
            "rdflib.term.Literal('foo', lang='en')",
        )

    def testOmitsMissingLang(self):
        self.assertEqual(
            repr(Literal("foo", datatype=URIRef("http://example.com/"))),
            "rdflib.term.Literal('foo', datatype=rdflib.term.URIRef('http://example.com/'))",
        )

    def testSubclassNameAppearsInRepr(self):
        class MyLiteral(Literal):
            pass

        x = MyLiteral("foo")
        self.assertEqual(repr(x), "MyLiteral('foo')")

class TestDoubleOutput(unittest.TestCase):
    def testNoDanglingPoint(self):
        """confirms the fix for https://github.com/RDFLib/rdflib/issues/237"""
        vv = Literal("0.88", datatype=_XSD_DOUBLE)
        out = vv._literal_n3(use_plain=True)
        self.assertTrue(out in ["8.8e-01", "0.88"], out)

class TestParseBoolean(unittest.TestCase):
    """confirms the fix for https://github.com/RDFLib/rdflib/issues/913"""

    def testTrueBoolean(self):
        test_value = Literal("tRue", datatype=_XSD_BOOLEAN)
        self.assertTrue(test_value.value)
        test_value = Literal("1", datatype=_XSD_BOOLEAN)
        self.assertTrue(test_value.value)

    def testFalseBoolean(self):
        test_value = Literal("falsE", datatype=_XSD_BOOLEAN)
        self.assertFalse(test_value.value)
        test_value = Literal("0", datatype=_XSD_BOOLEAN)
        self.assertFalse(test_value.value)

    def testNonFalseBoolean(self):
        test_value = Literal("abcd", datatype=_XSD_BOOLEAN)
        self.assertRaises(UserWarning)
        self.assertFalse(test_value.value)
        test_value = Literal("10", datatype=_XSD_BOOLEAN)
        self.assertRaises(UserWarning)
        self.assertFalse(test_value.value)

class TestBindings(unittest.TestCase):
    def testBinding(self):
        class a:
            def __init__(self, v):
                self.v = v[3:-3]

            def __str__(self):
                return "<<<%s>>>" % self.v

        dtA = rdflib.URIRef("urn:dt:a")
        bind(dtA, a)

        va = a("<<<2>>>")
        la = Literal(va, normalize=True)
        self.assertEqual(la.value, va)
        self.assertEqual(la.datatype, dtA)

        la2 = Literal("<<<2>>>", datatype=dtA)
        self.assertTrue(isinstance(la2.value, a))
        self.assertEqual(la2.value.v, va.v)

        class b:
            def __init__(self, v):
                self.v = v[3:-3]

            def __str__(self):
                return "B%s" % self.v

        dtB = rdflib.URIRef("urn:dt:b")
        bind(dtB, b, None, lambda x: "<<<%s>>>" % x)

        vb = b("<<<3>>>")
        lb = Literal(vb, normalize=True)
        self.assertEqual(lb.value, vb)
        self.assertEqual(lb.datatype, dtB)

    def testSpecificBinding(self):
        def lexify(s):
            return "--%s--" % s

        def unlexify(s):
            return s[2:-2]

        datatype = rdflib.URIRef("urn:dt:mystring")

        # Datatype-specific rule
        bind(datatype, str, unlexify, lexify, datatype_specific=True)

        s = "Hello"
        normal_l = Literal(s)
        self.assertEqual(str(normal_l), s)
        self.assertEqual(normal_l.toPython(), s)
        self.assertEqual(normal_l.datatype, None)

        specific_l = Literal("--%s--" % s, datatype=datatype)
        self.assertEqual(str(specific_l), lexify(s))
        self.assertEqual(specific_l.toPython(), s)
        self.assertEqual(specific_l.datatype, datatype)

class TestXsdLiterals(unittest.TestCase):
    def test_make_literals(self):
        """
        Tests literal construction.
        """
        inputs = [
            # these literals do not get converted to Python types
            ("ABCD", XSD.integer, None),
            ("ABCD", XSD.gYear, None),
            ("-10000", XSD.gYear, None),
            ("-1921-00", XSD.gYearMonth, None),
            ("1921-00", XSD.gMonthDay, None),
            ("1921-13", XSD.gMonthDay, None),
            ("-1921-00", XSD.gMonthDay, None),
            ("10", XSD.gDay, None),
            ("-1", XSD.gDay, None),
            ("0000", XSD.gYear, None),
            ("0000-00-00", XSD.date, None),
            ("NOT A VALID HEX STRING", XSD.hexBinary, None),
            ("NOT A VALID BASE64 STRING", XSD.base64Binary, None),
            # these literals get converted to python types
            ("1921-05-01", XSD.date, datetime.date),
            ("1921-05-01T00:00:00", XSD.dateTime, datetime.datetime),
            ("1921-05", XSD.gYearMonth, datetime.date),
            ("0001-01", XSD.gYearMonth, datetime.date),
            ("0001-12", XSD.gYearMonth, datetime.date),
            ("2002-01", XSD.gYearMonth, datetime.date),
            ("9999-01", XSD.gYearMonth, datetime.date),
            ("9999-12", XSD.gYearMonth, datetime.date),
            ("1921", XSD.gYear, datetime.date),
            ("2000", XSD.gYear, datetime.date),
            ("0001", XSD.gYear, datetime.date),
            ("9999", XSD.gYear, datetime.date),
            ("1982", XSD.gYear, datetime.date),
            ("2002", XSD.gYear, datetime.date),
            ("1921-05-01T00:00:00+00:30", XSD.dateTime, datetime.datetime),
            ("1921-05-01T00:00:00-00:30", XSD.dateTime, datetime.datetime),
            ("abcdef0123", XSD.hexBinary, bytes),
            ("", XSD.hexBinary, bytes),
            ("UkRGTGli", XSD.base64Binary, bytes),
            ("", XSD.base64Binary, bytes),
            ("0.0000000000000000000000000000001", XSD.decimal, Decimal),
            ("0.1", XSD.decimal, Decimal),
            ("1", XSD.integer, int),
        ]
        self.check_make_literals(inputs)

    @unittest.expectedFailure
    def test_make_literals_ki(self):
        """
        Known issues with literal construction.
        """
        inputs = [
            ("1921-01Z", XSD.gYearMonth, datetime.date),
            ("1921Z", XSD.gYear, datetime.date),
            ("1921-00", XSD.gYearMonth, datetime.date),
            ("1921-05-01Z", XSD.date, datetime.date),
            ("1921-05-01+00:30", XSD.date, datetime.date),
            ("1921-05-01+00:30", XSD.date, datetime.date),
            ("1921-05-01+00:00", XSD.date, datetime.date),
            ("1921-05-01+00:00", XSD.date, datetime.date),
            ("1921-05-01T00:00:00Z", XSD.dateTime, datetime.datetime),
            ("1e-31", XSD.decimal, None),  # This is not a valid decimal value
        ]
        self.check_make_literals(inputs)

    def check_make_literals(self, inputs):
        for literal_pair in inputs:
            (lexical, type, value_cls) = literal_pair
            with self.subTest(f"testing {literal_pair}"):
                literal = Literal(lexical, datatype=type)
                if value_cls is not None:
                    self.assertIsInstance(literal.value, value_cls)
                else:
                    self.assertIsNone(literal.value)
                self.assertEqual(lexical, f"{literal}")

if __name__ == "__main__":
    unittest.main()


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

import configparser
import os
import sys
base_path = os.getcwd()
sys.path.append(base_path)

class ReadIni():
    # def __init__(self, file_name=None, node=None):
    #     if file_name == None:
    #         file_name = base_path + '/config/LocalElement.ini'
    #     if self.node == None:
    #         self.node = 'RegisterElement'
    #     else:
    #         self.node = node
    #     self.cf = self.load_ini(file_name)

    def load_ini(self, file_name=None):
        if file_name == None:
            file_name = base_path + '/config/LocalElement.ini'
        cf = configparser.ConfigParser()
        cf.read(file_name)
        return cf

    def get_value(self, key, node=None):
        cf = self.load_ini()
        if node == None:
            node = 'RegisterElement'
        data = cf.get(node, key)
        return data

if __name__ == '__main__':
    reat_ini = ReadIni()
    print(reat_ini.get_value('code_error'))


import os
from django import forms
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.template.defaultfilters import filesizeformat
from magic import Magic
from .models import SasviewModel
from .models import ModelFile
from .models import Comment
from .models import Category

class ModelFileField(forms.FileField):
    def __init__(self, *args, **kwargs):
        self.mimetypes = kwargs.pop('mimetypes')
        self.max_size = kwargs.pop('max_size')
        self.file_extensions = kwargs.pop('file_extensions') if 'file_extensions' in kwargs else None
        super(ModelFileField, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        data = super(ModelFileField, self).clean(*args, **kwargs)
        if data is None:
            return data
        extension = os.path.splitext(data.name)[-1]
        try:
            f = Magic(mime=True)
            content_type = f.from_buffer(data.file.read())
        except Exception as e:
            content_type = data.content_type_extra
        data.seek(0)

        if self.mimetypes is not None and content_type not in self.mimetypes:
            raise ValidationError(
                f"Files of type {content_type} cannot be uploaded. Please select a file of type {self.mimetypes}.")
        if self.file_extensions is not None and extension not in self.file_extensions:
            raise ValidationError(
                f"Files of type {extension} cannot be uploaded. Please select a file of type {self.file_extensions}.")
        if self.max_size is not None and data.size > self.max_size:
            raise ValidationError(f"Files must be smaller than {filesizeformat(self.max_size)}.")
        return data

class ExampleDataField(ModelFileField):
    def clean(self, *args, **kwargs):
        data = super(ExampleDataField, self).clean(*args, **kwargs)
        if data is None:
            return data
        x = []
        y = []
        error = None
        for line in data:
            values = line.split()
            if values[0] in ['<X>', b'<X>']:
                continue # Header row
            if len(values) < 2 and len(values) != 0:
                try:
                    float(values[0])
                except:
                    raise ValidationError(
                        ("Error parsing float %(error_val)s"),
                        params = { 'error_val': values[0] }
                    )
                raise ValidationError(("x and y columns must be the same length"))
            try:
                x.append(float(values[0]))
            except:
                error = values[0]
                break
            try:
                y.append(float(values[1]))
            except:
                error = values[0]
                break
        if error is not None:
            raise ValidationError(
                ("Error parsing float %(error_val)s"),
                params = { 'error_val': error }
            )
        x = ",".join([str(x_i) for x_i in x])
        y = ",".join([str(y_i) for y_i in y])

        return (x, y)

class SasviewModelForm(ModelForm):
    category = forms.ModelChoiceField(queryset=Category.objects.all(), required=False)
    example_data = ExampleDataField(mimetypes=['text/plain'], max_size=15*2**10,
        required=False, help_text=("(Optional) Run your model in SasView, right click on the "
        "theory curve and select \"Save As\". Save the data as a "
        ".txt file and upload it here. The data will display as a graph on"
        " the model's page."))
    class Meta:
        model = SasviewModel
        fields = ("name", "category", "description", "example_data")
        help_texts = {
            'description': ("LaTeX formatting is supported. Use $...$ to"
                " denote inline maths, and $$...$$ or \\[...\\] to denote"
                " displayed maths.")
        }

class ModelFileForm(ModelForm):
    model_file = ModelFileField(
        allow_empty_file=False,
        mimetypes=["text/x-c", "text/x-csrc",  # C++ files (.c)
                   "text/x-python", "text/x-python-script",  # Python files (.py)
                   "text/plain"],  # Plain text files (.txt)
        file_extensions=['.c', '.py'],
        max_size=50*2**10)
    class Meta:
        model = ModelFile
        fields = ("model_file",)
        labels = { "model_file": "Upload a model file:" }

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ("content",)
        labels = { "content": "Add a comment:" }

class SignupForm(UserCreationForm):
    email = forms.EmailField(required=True)
    email.help_text = "Required."
    first_name = forms.CharField()
    last_name = forms.CharField()

    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email", "password1", "password2")

    def save(self, commit=True):
        user = super(SignupForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        if commit:
            user.save()
        return user


# python3
"""
File name: finding_exit_from_maze.py
Author: Sayuri Monarrez Yesaki
Date created: 04/06/2022
Date last modified: 04/06/2022
Python version: 3.9

A maze is a rectangular grid of cells with walls between some of adjacent cells. You would like to check whether
there is a path from a given cell to a given exit from a maze where an exit is also a cell that lies on the border of
the maze. For this, you represent the maze as an undirected graph: vertices of the graph are cells of the maze,
two vertices are connected by an undirected edge if they are adjacent and there is no wall between them. Then, to check
whether there is a path between two given cells in the maze, it suffices to check that there is a path between the
corresponding two vertices in the graph.

Task: Given an undirected graph and two distinct vertices u and v, check if there is a path between u and v.

Input: An undirected graph with n vertices and m edges. The next line contains two vertices u and v of the graph.

Constraints: 2 <= n <= 10^3; 1 <= m <= 10^3; 1 <= u, v <= n; u != n

Output: Output 1 if there is a path between u and v and 0 otherwise.

Time limit: 5 sec

Memory Limit: 512 MB
"""

import sys
from typing import List

def explore(adj: List[List[int]], x: int, visited: List[int]) -> None:
    """Recursively explore nodes reachable from x. Neighbors only marked as visited when
    explored.

    Parameters
    ----------
    adj: List[List[int]]
        Adjacency list representation of graph.
    x: int
        current vertex
    visited: List[int]
        list to keep track of visited vertices ---> 1- visited; 0- not visited
    """

    # mark neighbor vertex as visited
    visited[x] = 1
    # explore neighbors
    for neighbor in adj[x]:
        # if neighbor is 0 in visited list, it means it has not been visited yet.
        if visited[neighbor] == 0:
            explore(adj, neighbor, visited)

def reach(adj: List[List[int]], x: int, y: int) -> int:
    """Check if there is a path between vertices x and y of the adj undirected graph.

    Parameters
    ----------
    adj: List[List[int]]
        Adjacency list representation of an undirected graph.
    x: int
        starting vertex
    y: int
        end vertex

    Returns
    -------
    int
        0 if there is NO path between x and y, 1 otherwise.
    """

    # initialize list of all vertices in the adj graph - mark all as unvisited.
    visited = [0] * len(adj)
    # explore neighbor vertices reachable from x
    explore(adj, x, visited)
    return visited[y]

def run_find_exit_from_maze():
    """Main method to find if there is an exit from a maze. Reads input
    from the user - list of numbers separated by spaces representing an
    undirected graph with n vertices and m edges, and two vertices
    representing the start and end of the maze.

        Example: 3 2 1 2 1 3 2 3
         n - 3 vertices
         m - 2 edges

         list of edges:
         1 2
         1 3

         start maze: 2
         end maze: 3

    After reading the user's input, the graph is constructed using the
    adjacency list representation.
    Prints out 0 if there is NO path between start and end of the maze, 1 otherwise.
    """
    # read input from user
    input = sys.stdin.read()
    # convert input into a list of int
    data = list(map(int, input.split()))
    # get number of vertices n, and number of edges m
    n, m = data[0:2]
    # list of edges
    data = data[2:]
    # list of edges - list of tuples that represent edges
    edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
    # create graph - adjacency list representation
    x, y = data[2 * m:]
    adj = [[] for _ in range(n)]
    x, y = x - 1, y - 1
    for (a, b) in edges:
        adj[a - 1].append(b - 1)
        adj[b - 1].append(a - 1)
    print(reach(adj, x, y))

if __name__ == '__main__':
    run_find_exit_from_maze()


# -*- coding: utf-8 -*-
# pylint: disable=arguments-differ, abstract-method
from __future__ import absolute_import
import logging

import torch

LOGGER = logging.getLogger(__name__)

class CrossEntropyLabelSmooth(torch.nn.Module):
    def __init__(self, num_classes, epsilon, reduction='avg'):
        super(CrossEntropyLabelSmooth, self).__init__()
        self.num_classes = num_classes
        self.epsilon = epsilon
        self.reduction = reduction
        self.logsoftmax = torch.nn.LogSoftmax(dim=1)

    def forward(self, input, target):  # pylint: disable=redefined-builtin
        log_probs = self.logsoftmax(input)
        targets = torch.zeros_like(log_probs).scatter_(1, target.unsqueeze(1), 1)
        targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
        loss = (-targets * log_probs)

        if self.reduction == 'avg':
            loss = loss.mean(0).sum()
        elif self.reduction == 'sum':
            loss = loss.sum()
        return loss


from rest_framework import serializers
from .models import (Ecole, Classe, Eleve, Questionnaire, Commentaire)

# Ecole

class EcoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ecole
        fields = (
            'id',
            'enseignant',
            'titre',
            'latitude',
            'longitude'
        )

# Classe

class ClasseSerializer(serializers.ModelSerializer):
    ecole = serializers.SerializerMethodField()

    class Meta:
        model = Classe
        fields = (
            'id',
            'nom',
            'filliere',
            'ecole'
        )

    def get_ecole(self, obj):
        return EcoleSerializer(obj.ecole).data

# Questionnaire
class QuestionnaireSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questionnaire
        fields = (
            'id',
            'enregistreur',
            'Otites_fréquentes',
            'Angines_fréquentes'
        )

# Eleve

class EleveSerializer(serializers.ModelSerializer):
    classe = serializers.SerializerMethodField()
    questionnaire = serializers.SerializerMethodField()

    class Meta:
        model = Eleve
        fields = (
            'id',
            'nom',
            'prenom',
            'sexe',
            'avatar',
            'image_AN',
            'classe',
            'questionnaire'
        )

    def get_classe(self, obj):
        return ClasseSerializer(obj.classe).data

    def get_questionnaire(self, obj):
        return QuestionnaireSerializer(obj.questionnaire).data

# Commantaire

class CommentaireSerializer(serializers.ModelSerializer):
    questionnaire = serializers.ModelSerializer()

    class Meta:
        model = Commentaire
        fields = (
            'id',
            'auteur',
            'titre',
            'questionnaire'
        )

        def get_questionnaire(self, obj):
            return QuestionnaireSerializer(obj.questionnaire).data


import datetime

import pytest
from pydeequ.analyzers import Mean
from sqlmodel import Session

from thoth import repository, service_layer
from thoth.anomaly import AnomalyScoring, Score
from thoth.anomaly.models import SimpleModelFactory
from thoth.anomaly.optimization import AnomalyOptimization, MetricOptimization
from thoth.dataset import Dataset
from thoth.profiler import Granularity, Metric, ProfilingBuilder
from thoth.quality import LogHandler

def test__build_repo_error():
    # act and assert
    with pytest.raises(ValueError):
        service_layer._build_repo()

def test__build_repo_with_session(session):
    # act
    output = service_layer._build_repo(session=session)

    # assert
    isinstance(output, repository.SqlRepository)

def test_init_db():
    engine = service_layer.build_engine()
    output = service_layer.is_db_initialized(engine=engine)
    assert output is False

    service_layer.init_db(engine=engine)
    output2 = service_layer.is_db_initialized(engine=engine)
    assert output2 is True

def test_assess_quality():
    """Test assess_quality service fetching optimization and scoring from repo."""
    # arrange
    engine = service_layer.build_engine()
    ts = datetime.datetime(2022, 1, 1)
    dataset = "my-dataset"
    metric = Metric(entity="Column", instance="f1", name="Mean")
    optimization = AnomalyOptimization(
        dataset_uri=dataset,
        confidence=0.95,
        metric_optimizations=[
            MetricOptimization(
                metric=metric,
                best_model_name="SimpleModel",
                threshold=0.2,
                validation_results=[],
            )
        ],
    )
    scoring = AnomalyScoring(
        dataset_uri=dataset,
        ts=ts,
        scores=[Score(metric=metric, value=0.19, predicted=123)],
    )

    # act
    with Session(engine) as session:
        service_layer.init_db(engine=engine)
        repo = service_layer._build_repo(session=session)

        repo.add_optimization(optimization=optimization)
        repo.add_scoring(scoring=scoring)
        [output_scoring] = repo.select_scoring(dataset_uri="my-dataset")

        success = service_layer.assess_quality(
            dataset_uri=dataset,
            ts=ts,
            session=session,
        )

    # assert
    assert success is True
    assert output_scoring == scoring

def test_e2e_flow_with_anomaly(json_data, spark_session, caplog):
    # arrange
    caplog.set_level("INFO")

    series = [
        dict(ts=data_point.get("ts"), value=data_point.get("value") * 1.5)
        if data_point.get("ts") == "1981-12-31"
        else data_point
        for data_point in json_data[-15:]
    ]
    normal_history_df = spark_session.createDataFrame(
        [data_point for data_point in series if data_point.get("ts") < "1981-12-31"],
        schema="ts string, value float",
    )
    new_anomalous_point_df = spark_session.createDataFrame(
        [data_point for data_point in series if data_point.get("ts") == "1981-12-31"],
        schema="ts string, value float",
    )
    dataset_uri = "temperatures"

    model_factory = SimpleModelFactory()

    engine = service_layer.build_engine()

    # act
    with Session(engine) as session:
        service_layer.init_db(engine=engine, clear=True)
        _, _ = service_layer.profile_create_optimize(
            df=normal_history_df,
            dataset_uri=dataset_uri,
            ts_column="ts",
            profiling_builder=ProfilingBuilder(analyzers=[Mean(column="value")]),
            model_factory=model_factory,
            session=session,
            spark=spark_session,
        )
        dataset = service_layer.get_dataset(dataset_uri=dataset_uri, session=session)
        profiling = service_layer.select_profiling(
            dataset_uri=dataset_uri, session=session
        )
        optimization = service_layer.get_optimization(
            dataset_uri=dataset_uri, session=session
        )

        result = service_layer.assess_new_ts(
            df=new_anomalous_point_df,
            ts=datetime.datetime(year=1981, month=12, day=31),
            dataset_uri=dataset_uri,
            profiling_builder=ProfilingBuilder(analyzers=[Mean(column="value")]),
            model_factory=model_factory,
            session=session,
            spark=spark_session,
            notification_handlers=[LogHandler()],
        )
        scoring = service_layer.get_scoring(dataset_uri=dataset_uri, session=session)

        # assert
        assert dataset.uri == dataset_uri
        assert len(profiling) == 14
        assert len(optimization.metric_optimizations) == 1
        assert "Anomaly detected for ts=1981-12-31" in caplog.text
        assert result is False
        assert len(scoring) == 1

def test_score_exception():
    engine = service_layer.build_engine()
    with Session(engine) as session:
        service_layer.init_db(engine=engine)
        with pytest.raises(ValueError):
            service_layer.score(
                dataset_uri="my-dataset", ts=datetime.datetime.utcnow(), session=session
            )

def test_assess_quality_exception():
    engine = service_layer.build_engine()
    with Session(engine) as session:
        service_layer.init_db(engine=engine)
        with pytest.raises(ValueError):
            service_layer.assess_quality(
                dataset_uri="my-dataset", ts=datetime.datetime.utcnow(), session=session
            )

def test_assess_new_ts_exception():
    engine = service_layer.build_engine()
    with Session(engine) as session:
        service_layer.init_db(engine=engine)
        with pytest.raises(ValueError):
            service_layer.assess_new_ts(
                df=None,
                ts=datetime.datetime.utcnow(),
                dataset_uri="my-dataset",
                session=session,
            )

def test_profile_exception(session):
    # act and assert
    with pytest.raises(service_layer.ThothServiceError):
        service_layer.profile(df=None, dataset_uri="not-found", session=session)

def test_get_datasets(session):
    # arrange
    service_layer.add_dataset(
        dataset=Dataset(
            uri="dataset-b",
            ts_column="ts",
            columns=["f1"],
            granularity=Granularity.DAY,
            metrics=[Metric(entity="Column", instance="f1", name="Mean")],
        ),
        session=session,
    )
    service_layer.add_dataset(
        dataset=Dataset(
            uri="dataset-a",
            ts_column="ts",
            columns=["f1"],
            granularity=Granularity.DAY,
            metrics=[Metric(entity="Column", instance="f1", name="Mean")],
        ),
        session=session,
    )

    # act
    output = service_layer.get_datasets(session=session)

    # assert
    assert len(output) == 2
    assert output[0].uri == "dataset-a"


import numpy as np
import torch.nn as nn
import torch
from transformers import DistilBertTokenizerFast, DistilBertModel
from torch.utils.data import Dataset, DataLoader

class BertForRegression(nn.Module):
    def __init__(self):
        super().__init__()
        self.bert = DistilBertModel.from_pretrained('distilbert-base-uncased')
#         self.dropout = nn.Dropout(p=0.75)
        self.classifier = nn.Linear(768, 1024)
#         self.batchn = torch.nn.BatchNorm1d(1000)
        self.relu = torch.nn.LeakyReLU()
        self.classifier2 = nn.Linear(1024, 1024)
#         self.batchn2 = torch.nn.BatchNorm1d(100)
        self.relu2 = torch.nn.LeakyReLU()
        self.classifier3 = nn.Linear(1024, 256)
        self.relu3 = torch.nn.LeakyReLU()
        self.classifier4 = nn.Linear(256, 64)
        self.relu4 = torch.nn.LeakyReLU()
        self.classifier5 = nn.Linear(64, 1)

    def forward(self, tokens, token_type_ids=None):
        x = self.bert(tokens)
#         print(torch.mean(x[0], dim=1).shape)
#         x = self.dropout(torch.mean(x[0], dim=1))
        x = self.classifier(torch.mean(x[0], dim=1))
#         x = self.batchn(x)
        x = self.relu(x)
        x = self.classifier2(x)
#         x = self.batchn2(x)
        x = self.relu2(x)
        x = self.classifier3(x)
        x = self.relu3(x)
        x = self.classifier4(x)
        x = self.relu4(x)
        x = self.classifier5(x)
        return x

    def train_mode(self,):
        self.bert.eval()
        self.classifier.train()

    def train_mode2(self,):
        self.bert.train()
        self.classifier.train()

    def eval_mode(self,):
        self.bert.eval()
        self.classifier.eval()


# -*- coding: utf-8 -*-
import scrapy

class FinancespiderSpider(scrapy.Spider):
    name = 'financespider'
    allowed_domains = ['www.yellowpages.com.au']
    start_urls = ['https://www.yellowpages.com.au/search/listings?clue=financial+planners&locationClue=&lat=&lon=']

    def parse(self, response):
        items = response.xpath("//div[@class='search-contact-card call-to-actions-4 feedback-feature-on']")
        for item in items:
            email = item.xpath(".//a[contains(@href,'mailto')]/@data-email").get()
            business = item.xpath(".//a[@class='listing-name']/text()").get()
            yield {
                'Business Name':business,
                'Email': email,
                'User-Agent': response.request.headers['User-Agent']
            }

        next_page = response.xpath("//a[text()='Next »']/@href").get()
        if next_page:
            print("**********************",next_page)
            next_abs_url = response.urljoin(next_page)
            print("****", next_abs_url)
            yield response.follow(
                url= next_abs_url,
                callback= self.parse,
                headers= {
                    'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
                }
            )


"""
2. Написать программу сложения и умножения двух шестнадцатеричных чисел. При этом каждое число представляется как
массив, элементы которого — цифры числа.
Например, пользователь ввёл A2 и C4F. Нужно сохранить их как [‘A’,
‘2’] и [‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение - [‘7’, ‘C’, ‘9’, ‘F’,
‘E’].
Примечание: Если воспользоваться функциями hex() и/или int() для преобразования систем счисления,
задача решается в несколько строк. Для прокачки алгоритмического мышления такой вариант не подходит. Поэтому
использование встроенных функций для перевода из одной системы счисления в другую в данной задаче под запретом.
"""

from collections import deque

def sum_hex_d(x, y, p=0):  # функция сложения шестнадцатеричных цифр. x, y в символьном виде
    a = deque('0123456789ABCDEF')
    b = deque('0123456789ABCDEF0123456789ABCDEF')
    i = a.index(x) + a.index(y) + p
    if i > 15:
        return 1, b[i]
    else:
        return 0, b[i]

def sum_hex(x, y):  # функция сложения шестнадцатеричных чисел
    c = deque()
    # приводим исходные данные к представлению массива шестнадцатеричных цифр
    x = tuple(x)
    y = tuple(y)
    # более длинное число располагаем сверху в виртуальном сложении столбиком
    if len(x) < len(y):
        x, y = y, x
    # разворачиваем массивы для удобства
    x = x[::-1]
    y = y[::-1]

    p = 0
    for i, v in enumerate(x):  # основной цикл сложения столбиком
        if i > (len(y) - 1):
            if p:
                res = sum_hex_d(v, '1', 0)
                c.appendleft(res[1])
                p = res[0]
            else:
                c.appendleft(v)
        else:
            res = sum_hex_d(v, y[i], p)
            c.appendleft(res[1])
            p = res[0]
    if p:
        c.appendleft('1')  # если после цикла "в уме" осталась единичка, добавляем ее слева
    return list(c)

def multi_hex(x, y):  # функция умножения шестнадцатеричных чисел
    a = deque('0123456789ABCDEF')
    x = tuple(x)
    y = tuple(y)

    # нас интересует меньшее число
    if len(x) > len(y):
        x, y = y, x
    # разворачиваем меньшее число
    x = x[::-1]

    spam_r = []  # здесь будем собирать результат умножения большего числа, на каждую цифру меньшего
    for i, v in enumerate(x):  # основной цикл поэлементного умножения
        spam = y
        for _ in range(a.index(v)-1):
            spam = sum_hex(spam, y)
        for _ in range(i):
            spam.append('0')
        spam_r.append(spam)
    # print(f'spam = {spam}')
    # print(f'spam_r = {spam_r}')
    res = spam_r[0]
    for i in range(len(spam_r)-1):  # цикл сложения чисел, полученных в результате поэлементного умножения
        res = sum_hex(res, spam_r[i+1])
    return res

#  Tecт
h_x = 'A2'
h_y = 'C4F'
assert sum_hex(h_x, h_y) == ['C', 'F', '1']
assert multi_hex(h_x, h_y) == ['7', 'C', '9', 'F', 'E']
print('Тест пройден!')
print()
h_x = input('Введите первое шестнадцатеричное число: ').upper()
h_y = input('Введите второе шестнадцатеричное число: ').upper()
print('Сложение:')
print(f'"{h_x}" + "{h_y}" = "{"".join(sum_hex(h_x, h_y))}"')
print('Умножение')
print(f'"{h_x}" * "{h_y}" = "{"".join(multi_hex(h_x, h_y))}"')


import setuptools

def get_content(*filename):
    """ Gets the content of a file and returns it as a string
    Args:
        filename(str): Name of file to pull content from
    Returns:
        str: Content from file
    """
    content = ""
    for file in filename:
        with open(file, "r") as full_description:
            content += full_description.read()
    return content

setuptools.setup(
    name = "pyerewolf",
    version = "0.0.1",
    author = "Kieran Wood",
    author_email = "kieran@canadiancoding.ca",
    description = "A web version of the werewolf game implemented in python using Flask.",
    long_description = get_content("README.md", "CHANGELOG.md"),
    long_description_content_type = "text/markdown",
    project_urls = {
        "User Docs" :  "https://kieranwood.ca/pyerewolf",
        "Source" :     "https://github.com/Descent098/pyerewolf",
    },
    include_package_data = True,
    packages = setuptools.find_packages(),
    classifiers = [
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
        "Development Status :: 1 - Planning"
    ],
)