import numpy as np
from sklearn.model_selection import train_test_split,StratifiedKFold
from catboost import CatBoostRegressor, CatBoostClassifier, Pool
from xgboost import XGBRegressor, XGBClassifier
from lightgbm import LGBMRegressor, LGBMClassifier
import sys
import os

sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))

from _models import rmse, RMSELoss

class KfoldWrapper :

    def __init__(self,args, wrapper_model_class , kfold_num):

        self.kfold_num = kfold_num
        self.my_class = wrapper_model_class
        self.model_name = args.MODEL
        self.cur_model_collect = {}

        skf = StratifiedKFold(n_splits = kfold_num, shuffle=True, random_state=42)
        folds = []

        for train_idx, valid_idx in skf.split( wrapper_model_class.data['train'].drop(['rating'], axis=1),
                                               wrapper_model_class.data['train']['rating']):
            folds.append((train_idx,valid_idx))

        self.folds = folds

    def train(self):
        for fold in range( self.kfold_num  ):
            print(f'==================================== {fold+1} ============================================')
            train_idx, valid_idx = self.folds[fold]
            X_train = self.my_class.data['train'].drop(['rating'],axis=1).iloc[train_idx]
            X_valid = self.my_class.data['train'].drop(['rating'],axis=1).iloc[valid_idx]
            y_train = self.my_class.data['train']['rating'][train_idx]
            y_valid = self.my_class.data['train']['rating'][valid_idx]

            target_model = CatBoostRegressor

            if( "LightGBMRegressor" == self.model_name  ):
                target_model = LGBMRegressor
            elif( "XGBRegressor" == self.model_name  ):
                target_model = XGBRegressor
            elif( "CatBoostRegressor"== self.model_name ):
                target_model = CatBoostRegressor

            cur_predict_model = target_model( **self.my_class.best_params)

            if( "CatBoostRegressor"== self.model_name ):
                cur_predict_model.fit(X_train,y_train, eval_set=(X_valid, y_valid))
            else:
                cur_predict_model.fit(X_train,y_train)

            preds = cur_predict_model.predict(X_valid)
            print(f'{fold} : RMSE : ', rmse(y_valid, preds))
            self.cur_model_collect[fold] = cur_predict_model
            print(f'================================================================================\n\n')

    def predict(self):
        preds =np.zeros(self.my_class.data['test'].shape[0])
        for fold in range(self.kfold_num):
            simple_pred = self.cur_model_collect[fold].predict(self.my_class.data['test'])
            preds += simple_pred.squeeze(1) if 'Classifier' in self.model_name else simple_pred
        return ( preds / self.kfold_num ).transpose()


"""
locations.regex_flow
-------------------
A flow for generating the regex model.
Note that the model is so simple that this flow is basically pointless.
    python regex_flow.py run
"""
from regex_utils import save_model
from metaflow import FlowSpec, Parameter, step

class RegexFlow(FlowSpec):
    outcode_regex = Parameter(
        "ouctode_regex",
        help="The postcode area regex parameter for this model",
        default="[A-Z]{1,2}[0-9][0-9A-Z]?\s?",
    )
    boilerplate_text = Parameter(
        "boilerplate_text",
        help="The cleaning regex parameter for this model",
        default="[^\w\s]",
    )

    @step
    def start(self):
        """
        Starts the flow, you could do some prep steps here
        """
        self.next(self.train_model)

    @step
    def train_model(self):
        """
        This isn't needed for this model, because it's so easy
        """
        self.next(self.save_model)

    @step
    def save_model(self):
        """
        Pickle the model, or save model config
        """
        save_model(
            outcode_regex=self.outcode_regex, boilerplate_text=self.boilerplate_text
        )
        self.next(self.end)

    @step
    def end(self):
        """
        Do any cleanup that's required
        """
        pass

if __name__ == "__main__":
    RegexFlow()


import unittest
from exchanges import loader

api_keys = {
    'key': '',
    'secret': ''
}

class PoloniexTestCast(unittest.TestCase):
    def setUp(self):
        self.poloniex = loader.get_exchange_by_name('poloniex')
        self.poloniex.connect_to_api(api_keys)

    @unittest.skip("testing skipping")
    def test_get_coin_info(self):
        coins = ['btc', 'eth']

        info = self.poloniex.get_general_coin_info(coins)

        self.assertTrue(info, 'coin info failing')

    @unittest.skip("testing skipping")
    def test_get_balance(self):
        coin = None
        balances = self.poloniex.get_balance(coin)

        self.assertTrue(balances, 'coin balance failing')

    @unittest.skip("testing skipping")
    def test_get_open_orders(self):
        coins = None
        open_orders = self.poloniex.get_open_orders(coins)

        self.assertTrue(open_orders, 'open orders failing')

    @unittest.skip("testing skipping")
    def test_get_order_history(self):
        coins = ['btc', 'eth']
        order_history = self.poloniex.get_order_history(coins)

        self.assertTrue(order_history, 'order history failing')

    @unittest.skip("testing skipping")
    def test_get_trade_history(self):
        coins = ['btc', 'eth']
        start_date = '8/10/2017'

        trade_history = self.poloniex.get_trade_history(coins, start_date)

        self.assertTrue(trade_history, 'trade history failing')

    @unittest.skip("testing skipping")
    def test_get_chart_info(self):
        coins = ['btc', 'eth']
        start_date = '8/10/2017'

        chart_info = self.poloniex.get_chart_info(coins, start_date)

        self.assertTrue(chart_info, 'chart info failing')

    @unittest.skip("testing skipping")
    def test_buy(self):
        coins = ['btc', 'sc']
        quantity = 200
        price = 0.00000060

        result = self.poloniex.buy(coins, quantity, price)
        print(result['orderNumber'])

        self.assertTrue(result['orderNumber'], 'buying coins failing')

    @unittest.skip("testing skipping")
    def test_sell(self):
        coins = ['btc', 'sc']
        quantity = 199.5
        price = 0.00000060

        result = self.poloniex.sell(coins, quantity, price)
        print(result['orderNumber'])

        self.assertTrue(result['orderNumber'], 'selling coins failing')

    @unittest.skip("testing skipping")
    def test_cancel_order(self):
        order_number = 15009693432

        result = self.poloniex.cancel_order(order_number)

        self.assertTrue(result['success'], 'cancel order failing')

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


import typing as t

import torch
import torch.nn as nn
from torch.utils.data import DataLoader

from matplotlib import pyplot as plt

torch.manual_seed(0)

def create_discriminator() -> nn.Module:
  # creates discriminator network
  return nn.Sequential(
      nn.Linear(2, 256),
      nn.ReLU(),
      nn.Dropout(0.2),

      nn.Linear(256, 128),
      nn.ReLU(),
      nn.Dropout(0.2),

      nn.Linear(128, 64),
      nn.ReLU(),
      nn.Dropout(0.2),

      nn.Linear(64, 1),
      nn.Sigmoid()
  )

def create_generator() -> nn.Module:
  # creates generator network
  return nn.Sequential(
      nn.Linear(2, 16),
      nn.ReLU(),

      nn.Linear(16, 32),
      nn.ReLU(),

      nn.Linear(32, 2)
  )

def select_device() -> str:
  return 'cuda' if torch.cuda.is_available() else 'cpu'

# TRAIN DISCRIMINATOR
def train_dis_on_real_batch(
    model: nn.Module,
    opt: torch.optim.Optimizer,
    loss_fn: t.Callable,
    real_batch: torch.tensor,
    device: str
  ) -> float:
  # trains discriminator given only real data from <real_batch>

  batch_size = real_batch.shape[0]
  real_samples = real_batch.to(device)
  opt.zero_grad()

  output = model(real_samples)
  true_labels = torch.ones((batch_size, 1), device=device)
  loss = loss_fn(output, true_labels)
  loss.backward()

  loss_value = loss.detach().cpu().item()

  opt.step()
  return loss_value

def train_dis_on_fake_batch(
    model: nn.Module,
    fake_creator: nn.Module,
    opt: torch.optim.Optimizer,
    loss_fn: t.Callable,
    batch_size: int,
    device: str
) -> float:
  # trains discriminator given only fake data from <fake_creator> ~ generator.

  noize = torch.rand((batch_size, 2))
  noize = noize.to(device)
  fake_output = fake_creator(noize)

  opt.zero_grad()

  output = model(fake_output)
  true_labels = torch.zeros((batch_size, 1), device=device)
  loss = loss_fn(output, true_labels)
  loss.backward()

  loss_value = loss.detach().cpu().item()

  opt.step()
  return loss_value

# TRAIN GENERATOR
def train_gen(
    model: nn.Module,
    dis: nn.Module,
    opt: torch.optim.Optimizer,
    loss_fn: t.Callable,
    batch_size: int,
    device: str
) -> float:
  # trains generator on discriminator fake detections

  noize = torch.rand((batch_size, 2))
  noize = noize.to(device)
  opt.zero_grad()

  fake_output = model(noize)
  dis_detections = dis(fake_output)
  true_labels = torch.ones((batch_size, 1), device=device)
  loss = loss_fn(dis_detections, true_labels)
  loss.backward()

  loss_value = loss.detach().cpu().item()

  opt.step()
  return loss_value

# USING GENERATOR
def generate(model: nn.Module, batch_size: int, device: str) -> torch.tensor:
  # generate fake data by generator in inference mode.
  with torch.no_grad():
    noize = torch.rand((batch_size, 2))
    noize = noize.to(device)
    gen_output = model(noize)
    gen_output = gen_output.detach().cpu()
  return gen_output

def train_epoch(
    dis: nn.Module,
    gen: nn.Module,
    loader: DataLoader,
    loss_fn: t.Callable,
    dis_opt: torch.optim.Optimizer,
    gen_opt: torch.optim.Optimizer,
    device: str
) -> t.Tuple[float, float]:
  # trains one epoch for discrimiator and generator

  dis_epoch_loss = 0
  gen_epoch_loss = 0

  for batch in loader:
    dis_true_loss = train_dis_on_real_batch(
        model=dis,
        opt=dis_opt,
        loss_fn=loss_fn,
        real_batch=batch,
        device=device
    )
    dis_fake_loss = train_dis_on_fake_batch(
        model=dis,
        fake_creator=gen,
        opt=dis_opt,
        loss_fn=loss_fn,
        batch_size=batch.shape[0],
        device=device
    )
    gen_loss = train_gen(
        model=gen,
        dis=dis,
        opt=gen_opt,
        loss_fn=loss_fn,
        batch_size=batch.shape[0],
        device=device
    )

    dis_epoch_loss += (dis_true_loss + gen_epoch_loss) / 2
    gen_epoch_loss += gen_loss

  dis_epoch_loss = dis_epoch_loss / len(loader)
  gen_epoch_loss = gen_epoch_loss / len(loader)

  return dis_epoch_loss, gen_epoch_loss

def get_observed_data(n_dots: int, start: float, end: float) -> torch.tesnor:
  observed_data = torch.zeros((n_dots, 2))
  observed_data[:, 0] = torch.arange(start, end, step=(end - start) / n_dots)
  observed_data[:, 1] = torch.sin(observed_data[:, 0])
  return observed_data

if __name__ == '__main__':

  N_DOTS = 2000
  START_V, END_V = 0., 10.

  observed_data = get_observed_data(N_DOTS, START_V, END_V)

  loader = DataLoader(observed_data, batch_size=128, shuffle=True)
  device = select_device()
  loss_function = nn.BCELoss().to(device)
  gen = create_generator().to(device)
  dis = create_discriminator().to(device)

  gen_optimizer = torch.optim.Adam(gen.parameters(), lr=0.001)
  dis_optimizer = torch.optim.Adam(dis.parameters(), lr=0.001)

  dis_losses = []
  gen_losses = []

  # training loop with every 100 epoch visialization
  for e in range(2_000):

    dis_epoch_loss, gen_epoch_loss = train_epoch(
        dis=dis,
        gen=gen,
        loader=loader,
        loss_fn=loss_function,
        dis_opt=dis_optimizer,
        gen_opt=gen_optimizer,
        device=device
    )

    dis_losses.append(dis_epoch_loss)
    gen_losses.append(gen_epoch_loss)

    if e % 100 == 0:
      print('Dis loss', dis_epoch_loss, '\t', 'Gen loss', gen_epoch_loss)
      generated_data = generate(model=gen, batch_size=100, device=device)
      generated_data = generated_data.numpy()

      fig, axes = plt.subplots(1, 2, figsize=(10, 3))
      axes[0].scatter(observed_data[:, 0], observed_data[:, 1], label='Obs')
      axes[0].scatter(generated_data[:, 0], generated_data[:, 1], label='Gen')
      axes[0].grid(True)
      axes[0].legend()

      plot_x = list(range(e + 1))
      axes[1].plot(plot_x, dis_losses, label='Dis losses')
      axes[1].plot(plot_x, gen_losses, label='Gen losses')
      axes[1].grid(True)
      axes[1].legend()

      plt.show()

  # saving model into traced-models
  dis_traced = torch.jit.trace(func=dis, example_inputs=torch.rand((2, 2)))
  gen_traced = torch.jit.trace(func=gen, example_inputs=torch.rand((2, 2)))

  dis_traced.save('discriminator_traced.pt')
  gen_traced.save('generator_traced.pt')

  # ready to use for generation
  gen_traced = torch.jit.load('generator_traced.pt', map_location=device)
  generated_data = generate(model=gen_traced, batch_size=1000, device=device)
  generated_data = generated_data.numpy()


#! Python3

import datetime

# URL how to download from a file URL http://sgeek.org/download-file-using-python-over-http/
# Initialize Date and Time for today's date

now = datetime.datetime.now()

#Initialize urls
nyturl = 'http://www.nytimes.com/svc/crosswords/v2/puzzle/'
laturl = 'http://www.cruciverb.com/download.php?f='

def monthname():
	#datenames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
	#return datenames[(now.month-1)]
	if len(str(now.month)) == 2:
		return str(now.month)
	else:
		return "0" + str(now.month)

def dayname():
	if len(str(now.day)) == 2:
		return str(now.day)
	else:
		return "0" + str(now.day)

def yearname():
	return str(now.year)[2:]

def nytpuz():
	filename = 'daily-' + str(now.year) + '-'
	filename += monthname() + '-'
	filename += dayname() + '.puz'
	return filename

def latpuz():
	return 'lat' + yearname() + monthname() + dayname() + '.puz'

#Printing out to the screen for debugging purposes

print (monthname() + " " + dayname() + " " + yearname())
print('Today\'s NYT file: ' + nytpuz())
print('Today\'s LAX file: ' + latpuz())
print('NYT URL: ' + nyturl + nytpuz())
print('LAT URL: ' + laturl + latpuz())

nyturl = nyturl + nytpuz()
laturl = laturl + latpuz()

print(nyturl)
print(laturl)


# Purpose: Rename nested keys in a dictionary object
# -----------------------------------------------------------------------------
# History: MM/DD/YYYY (developer) - description
#   03/20/2023 (htu) - initial coding
#   03/29/2023 (htu) -
#     1. added 2nd test case
#     2. added code to check if it is a list
#
#

import json
import re
# from io import StringIO
import sys
from ruamel.yaml import YAML

def rename_keys(d, regex:str=" ", replacement:str = "_", mapping=None):
    """
    Rename keys in a dictionary object recursively
    :param d: the input dictionary object
    :param mapping: a dictionary containing the old key names as keys and the new key names as values
    :param regex: a regular expression pattern to match against key names
    :param replacement: the character to replace the matched pattern with
    :return: the modified dictionary object
    """
    if mapping is None:
        mapping = {}
    # if isinstance(d, dict):
    #     for k1, v1 in list(d.items()):
    #         if k1 in mapping:
    #             k2 = mapping[k1]
    #         elif re.search(regex, k1):
    #             k2 = re.sub(regex, replacement, k1)
    #             # k2 = re.sub(re2,replacement,k2)
    #         else:
    #             k2 = k1
    #         d[k2] = d.pop(k1)
    #         if isinstance(v1, dict):
    #             d[k2] = rename_keys(v1, regex, replacement, mapping)
    #         elif isinstance(v1, list):
    #             for i, item in enumerate(v1):
    #                 v1[i] = rename_keys(item,  regex, replacement, mapping)
    if isinstance(d, list):
        for item in d:
            rename_keys(item, regex, replacement, mapping)
    elif isinstance(d, dict):
        for key, value in list(d.items()):
            # if key in mapping:
            #     new_key = mapping[key]
            # else:
            new_key = key.replace(regex, replacement)
            # print(f"Key: {key}; New Key: {new_key}")
            if new_key != key:
                d[new_key] = d.pop(key)
                if hasattr(d, 'lc') and hasattr(d, 'ca'):
                    d.lc.move(new_key, key)
                    d.ca.items[new_key] = d.ca.items.pop(key)
            rename_keys(value, regex, replacement, mapping)
    return d

# Test cases
if __name__ == "__main__":
    # Test Case 01: convert _ to " "
    d = {'a_1': 1, 'b__1': {'c': 2, 'd___1': 3, 'e-1': {'f-1': 4, 'g__1': 5}}}
    m = {}
    d = rename_keys(d, "_", " ", m)
    print(d)
    # Output: {'a 1': 1, 'b  1': {'c': 2, 'd   1': 3, 'e 1': {'f 1': 4, 'g  1': 5}}}

    # Test Case 02: Convert " " to "_"
    b = {'a 1': 1, 'b  1': {'c': 2, 'd   1': 3, 'e 1': {'f 1': 4, 'g  1': 5}}}

    d = rename_keys(b, " ", "_", m)
    print(d)

    # Test Case 03: Convert keys in YAML string to JSON
    y = YAML()
    y.indent(mapping=2, sequence=4, offset=2)
    y.preserve_quotes = True
    y_str = """\
# example 1
person:
  - full name: Smith Alice
    # details
    first name: John  # very common
    last name: Smith  # last name - Smith
    # Age is numerical
    age: 18  # Age is 18
    hobbies:
        1st hobby: car
        2nd hobby: garden
  - full name: Tom Evans
    first name: Tom
    last name: Evans
    age: 20
"""

    from ruamel.yaml.comments import CommentedMap

    def convert_spaces_to_underscores(obj, a: str=" ", b: str="_"):
        if isinstance(obj, list):
            for item in obj:
                convert_spaces_to_underscores(item)
        elif isinstance(obj, CommentedMap):
            for key, value in list(obj.items()):
                new_key = key.replace(a, b)
                if new_key != key:
                    obj[new_key] = obj.pop(key)
                    if hasattr(obj, 'ca'):
                        obj.ca.items[new_key] = obj.ca.items.get(key)
                        if key in obj.ca.items:
                            del obj.ca.items[key]
                convert_spaces_to_underscores(value)

    # Load the YAML string
    d1 = y.load(y_str)

    # Add the comment for Tom
    d1['person'][1].yaml_add_eol_comment(
        "This is a comment for Tom", 'first name')

    # Dump the modified YAML content back to a string
    y.dump(d1, sys.stdout)

    # rename the keys
    m = {"first name":"1st name", "last name":"family name"}
    # rename_keys(d1, " ", "_")
    convert_spaces_to_underscores(d1)
    # convert_spaces_to_underscores(d1)

    # Convert the data to a JSON string
    json_str = json.dumps(d1, indent=2)

    # Print the JSON string to the screen
    print(json_str)

    y.dump(d1, sys.stdout)


# -*- coding: utf-8 -*-
# @Time    : 2022/4/20 16:08
# @Author  : zhaoxiaoyu
# @File    : heat2D_voronoiunet.py
import torch
import torch.nn.functional as F
import logging
import os
import sys
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
from sklearn.decomposition import PCA
import h5py
import numpy as np
from sklearn import linear_model
from sklearn.kernel_ridge import KernelRidge
from sklearn.model_selection import GridSearchCV, PredefinedSplit
from tqdm import tqdm

filename = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
sys.path.append(filename)

from model.cnn import UNet
from data.dataset import HeatLayout
from utils.misc import save_model, prep_experiment, save_model2
from utils.options import parses
from utils.visualization import plot3x1
from utils.utils import cre

# Configure the arguments
args = parses()
args.exp = 'voronoicnn_heatlayout2_100'
args.epochs = 30
args.batch_size = 16
print(args)
torch.cuda.set_device(args.gpu_id)
cudnn.benchmark = True

class PODHeat:
    def __init__(self, n_components, positions, pod_index):
        self.positions = positions
        # Loading data
        f = h5py.File('/mnt/jfs/zhaoxiaoyu/Gappy_POD/heat_layout.h5', 'r')
        pca_data = f['u'][pod_index, :, :, :] - 298.0
        self.n_components = n_components

        self.n_components = n_components
        self.pca = PCA(n_components=n_components)
        X_t = self.pca.fit_transform(pca_data.reshape(len(pod_index), -1))
        self.max_coeff, self.min_coeff = np.max(X_t, axis=0).reshape(1, -1), np.min(X_t, axis=0).reshape(1, -1)
        self.size = pca_data.shape[-3:]

        self.train_data_coff = (X_t - self.min_coeff) / (self.max_coeff - self.min_coeff + 1e-10)

    def prepare_data(self, data_index, data_pre, flag=False):
        # Loading data
        f = h5py.File('/mnt/jfs/zhaoxiaoyu/Gappy_POD/heat_layout.h5', 'r')
        data = f['u'][data_index, :, :, :] - 298.0
        f.close()
        data_pre = data_pre[data_index, :, :, :]

        # Normalize the coefficients
        data_coff = self.pca.transform(data.reshape(len(data_index), -1))
        data_coff = (data_coff - self.min_coeff) / (self.max_coeff - self.min_coeff)

        sparse_data = []
        for i in range(self.positions.shape[0]):
            sparse_data.append(data_pre[:, 0, self.positions[i, 0], :][:, self.positions[i, 1]].reshape(-1, 1))
        observe = np.concatenate(sparse_data, axis=-1)
        return observe, data_coff, data

    def inverse_transform(self, coff):
        inverse_coff = coff * (self.max_coeff - self.min_coeff) + self.min_coeff
        return self.pca.inverse_transform(inverse_coff).reshape(coff.shape[0], self.size[0], self.size[1], self.size[2])

    def sample(self, numbers=1000):
        # Loading data
        data_index = (np.random.rand(numbers) * 500).tolist()
        data_index = [int(i) for i in data_index]
        f = h5py.File('/mnt/jfs/zhaoxiaoyu/Gappy_POD/heat_layout.h5', 'r')
        data = f['u'][:][data_index, :, :, :] - 298.0
        f.close()

        # Normalize the coefficients
        data_coff = self.pca.transform(data.reshape(len(data_index), -1))
        data_coff = (data_coff - self.min_coeff) / (self.max_coeff - self.min_coeff)

        sparse_data = []
        for i in range(self.positions.shape[0]):
            sparse_data.append(data[:, 0, self.positions[i, 0], :][:, self.positions[i, 1]].reshape(-1, 1))
        observe = np.concatenate(sparse_data, axis=-1)
        observe = observe + (np.random.randn(numbers, self.positions.shape[0]) - 0.5) * 0.1
        return observe, data_coff

    # def sample(self, n=1000):
    # data_coff = np.random.rand(n, self.n_components)
    # inverse_coff = data_coff * (self.max_coeff - self.min_coeff) + self.min_coeff
    # observe = []
    # for i in tqdm(range(int(n / 100.0))):
    #     data = self.pca.inverse_transform(inverse_coff[i * 100:i * 100 + 100]).reshape(100, 1, 200, 200)
    #     data = data + 0.3 * np.random.randn(100, 1, 200, 200)
    #     sparse_data = []
    #     for j in range(self.positions.shape[0]):
    #         sparse_data.append(data[:, 0, self.positions[j, 0], :][:, self.positions[j, 1]].reshape(-1, 1))
    #     sparse_data = np.concatenate(sparse_data, axis=-1)
    #     observe.append(sparse_data)
    # observe = np.concatenate(observe, axis=0)
    # return observe, data_coff

# Gaussian Process Regression
def ridge_regression(train_inputs, train_outputs, val_inputs, val_outputs):
    X = np.concatenate([train_inputs, val_inputs], axis=0)
    y = np.concatenate([train_outputs, val_outputs], axis=0)
    ps = PredefinedSplit(
        test_fold=np.concatenate([-1 * np.ones((train_inputs.shape[0], 1)), np.zeros((val_inputs.shape[0], 1))],
                                 axis=0)
    )
    tuned_parameter = [{'alpha': [0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 0.2, 0.25, 0.30, 0.5, 1.0, 10.0]}]
    ridge = linear_model.Ridge()
    gpr_c = GridSearchCV(estimator=ridge, param_grid=tuned_parameter, cv=ps, n_jobs=4)
    gpr_c.fit(X, y)
    alpha = gpr_c.best_params_['alpha']
    print('The optimal parameters are: \n alpha:', alpha)

    ridge = linear_model.Ridge(alpha=alpha)
    ridge.fit(train_inputs, train_outputs)
    return ridge

# ridge
def ridge_regression2(train_inputs, train_outputs, val_inputs, val_outputs):
    alphas = []
    for i in range(train_outputs.shape[1]):
        X = np.concatenate([train_inputs / 50, val_inputs / 50], axis=0)
        y = np.concatenate([train_outputs[:, i:i + 1], val_outputs[:, i:i + 1]], axis=0)
        ps = PredefinedSplit(
            test_fold=np.concatenate([-1 * np.ones((train_inputs.shape[0], 1)), np.zeros((val_inputs.shape[0], 1))],
                                     axis=0)
        )
        tuned_parameter = [{'alpha': [0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0]}]
        ridge = linear_model.Ridge()
        gpr_c = GridSearchCV(estimator=ridge, param_grid=tuned_parameter, cv=ps, n_jobs=4)
        gpr_c.fit(X, y)
        alpha = gpr_c.best_params_['alpha']
        print('The optimal parameters are: \n alpha:', alpha)
        alphas.append(alpha)
    print(alphas)
    ridge = linear_model.Ridge(alpha=np.array(alpha))
    ridge.fit(train_inputs / 50.0, train_outputs)
    return ridge

def train():
    # Prepare the experiment environment
    tb_writer = prep_experiment(args)
    # Create figure dir
    args.fig_path = args.exp_path + '/figure'
    os.makedirs(args.fig_path, exist_ok=True)
    args.best_record = {'epoch': -1, 'loss': 1e10, 'epoch2': -1, 'loss2': 1e10}

    # Build neural network
    net = UNet(in_channels=1, out_channels=1).cuda()

    # Build data loader
    train_dataset = HeatLayout(index=[i for i in range(100)], expand=80)
    train_loader = DataLoader(train_dataset, batch_size=args.batch_size, num_workers=4, shuffle=True)
    val_dataset = HeatLayout(index=[i for i in range(0, 200)])
    val_loader = DataLoader(val_dataset, batch_size=12, num_workers=4)
    n_components = 100
    positions = np.array([[int(200 * np.random.rand(1)), int(200 * np.random.rand(1))] for i in range(1600)])
    pod_index = [i for i in range(100)]
    train_index = [i for i in range(100)]
    val_index = [i for i in range(100, 200)]
    pod_cylinder = PODHeat(n_components, positions, pod_index)

    # Build optimizer
    optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)
    scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.80)

    for epoch in range(args.epochs):
        # Training procedure
        train_loss, train_num = 0., 0.
        for i, (inputs, outputs) in tqdm(enumerate(train_loader)):
            inputs, outputs = inputs.cuda(), outputs.cuda()
            pre = net(inputs)
            loss = F.l1_loss(outputs, pre)

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

            # Record results by tensorboard
            tb_writer.add_scalar('train_loss', loss, i + epoch * len(train_loader))
            train_loss += loss.item() * inputs.shape[0]
            train_num += inputs.shape[0]

        train_loss = train_loss / train_num
        logging.info("Epoch: {}, Avg_loss: {}".format(epoch, train_loss))
        scheduler.step()

        # Validation procedure
        if epoch % args.val_interval == 0:
            net.eval()
            pres, output_list = [], []
            for i, (inputs, outputs) in tqdm(enumerate(val_loader)):
                inputs, outputs = inputs.cuda(), outputs.cuda()
                with torch.no_grad():
                    pre = net(inputs)
                    pres.append(pre)
                    output_list.append(outputs)
            pres = torch.cat(pres, dim=0).detach().cpu().numpy() * 50
            output_list = torch.cat(output_list, dim=0).detach().cpu().numpy() * 50

            val_loss2 = np.mean(np.abs(pres - output_list)[val_index, :, :, :])
            if val_loss2 < args.best_record['loss2']:
                save_model2(args, epoch, val_loss2, net)

            train_inputs, train_outputs, _ = pod_cylinder.prepare_data(train_index, pres)
            val_inputs, val_outputs, _ = pod_cylinder.prepare_data(val_index, pres)
            model = ridge_regression(train_inputs, train_outputs, val_inputs, val_outputs)
            test_inputs, test_outputs, test_data = pod_cylinder.prepare_data(val_index, pres)
            test_pres = model.predict(test_inputs)
            test_maps = pod_cylinder.inverse_transform(coff=test_pres)

            val_loss = np.mean(np.abs(test_maps - output_list[val_index, :, :, :]))

            # Record results by tensorboard
            tb_writer.add_scalar('val_loss', val_loss, epoch)
            logging.info("Epoch: {}, Val_loss: {}".format(epoch, val_loss))
            if val_loss < args.best_record['loss']:
                save_model(args, epoch, val_loss, net)
            net.train()

            # Plotting
            if epoch % args.plot_freq == 0:
                plot3x1(outputs[-1, 0, :, :].cpu().numpy(), pre[-1, 0, :, :].cpu().numpy(),
                        file_name=args.fig_path + f'/epoch{epoch}.png')

def test(index):
    # Path of trained network
    args.snapshot = '/mnt/jfs/zhaoxiaoyu/Gappy_POD/heat2D/logs/ckpt/voronoicnn_heatlayout2/best_epoch_29_loss_0.01949539.pth'

    # Define data loader
    test_dataset = HeatLayout(index=index)
    test_loader = DataLoader(test_dataset, batch_size=args.batch_size, num_workers=0)
    n_components = 15
    positions = np.array([[int(i*2), int(j*2)] for i in range(100) for j in range(100)])
    pod_index = [i for i in range(500)]
    train_index = [i for i in range(0, 2000)]
    val_index = [i for i in range(2000, 3000)]
    pod_cylinder = PODHeat(n_components, positions, pod_index)

    # Load trained network
    net = UNet(in_channels=1, out_channels=1).cuda()
    net.load_state_dict(torch.load(args.snapshot)['state_dict'])
    print('load models: ' + args.snapshot)

    # Test procedure
    net.eval()
    test_mae, test_rmse, test_num = 0.0, 0.0, 0.0
    test_max_ae = 0
    pres, output_list = [], []
    for i, (inputs, outputs) in enumerate(test_loader):
        N, _, _, _ = inputs.shape
        inputs, outputs = inputs.cuda(), outputs.cuda()
        with torch.no_grad():
            pre = net(inputs)

            # coff = pod_cylinder.pca.transform(pre.cpu().numpy().reshape(outputs.shape[0], -1) * 50)
            # pre2 = pod_cylinder.pca.inverse_transform(coff)
            # pre = torch.from_numpy(pre2).reshape(pre2.shape[0], 1, 200, 200)

            pres.append(pre)
            output_list.append(outputs)
    pres = torch.cat(pres, dim=0).detach().cpu().numpy() * 50
    output_list = torch.cat(output_list, dim=0).detach().cpu().numpy() * 50
    train_inputs, train_outputs, _ = pod_cylinder.prepare_data(train_index, pres, flag=False)
    # aug_inputs, aug_outputs = pod_cylinder.sample(1000)
    # train_inputs = np.concatenate([train_inputs, aug_inputs], axis=0)
    # train_outputs = np.concatenate([train_outputs, aug_outputs], axis=0)

    val_inputs, val_outputs, _ = pod_cylinder.prepare_data(val_index, pres)
    model = ridge_regression2(train_inputs, train_outputs, val_inputs, val_outputs)
    test_inputs, test_outputs, test_data = pod_cylinder.prepare_data(val_index, pres)
    test_pres = model.predict(test_inputs / 50.0)
    pre = pod_cylinder.inverse_transform(coff=test_pres)
    test_num += pre.shape[0]
    pre = torch.from_numpy(pre)
    output_list = torch.from_numpy(output_list[val_index])

    pre = torch.from_numpy(pres[val_index, :, :, :])

    test_mae += F.l1_loss(output_list, pre).item() * test_num
    test_rmse += torch.sum(cre(output_list, pre, 2))
    test_max_ae += torch.sum(torch.max(torch.abs(output_list - pre).flatten(1), dim=1)[0]).item()
    print('test mae:', test_mae / test_num)
    print('test rmse:', test_rmse / test_num)
    print('test max_ae:', test_max_ae / test_num)

    # pre_data, u_data = torch.cat(pre_data, dim=0).cpu().numpy(), torch.cat(u_data, dim=0).cpu().numpy()
    #
    # f = h5py.File('heat_test.h5', 'w')
    # f['pre'] = pre_data
    # f['u'] = u_data
    # f.close()

    # plot3x1(outputs[-1, 0, :, :].cpu().numpy(), pre[-1, 0, :, :].cpu().numpy(), './test.png')

if __name__ == '__main__':
    # train()
    test(index=[i for i in range(0, 3000)])
    # test(index=[i for i in range(4000, 5000)])
    # test(index=[i for i in range(1800, 1940)])


import csv
import json
from datetime import datetime, timezone
from enum import Enum
from typing import List

from django.contrib import messages
from django.http import HttpResponse, Http404, HttpRequest
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
from django_otp.decorators import otp_required
from django.urls import reverse
from requests import RequestException
from two_factor.views.utils import class_view_decorator

from octopoes.connector import RemoteException
from octopoes.models import Reference
from octopoes.models.exception import ObjectNotFoundException
from octopoes.models.ooi.findings import Finding, FindingType
from octopoes.models.types import get_collapsed_types, type_by_name
from rocky.exceptions import IndemnificationNotPresentException, ClearanceLevelTooLowException
from rocky.views.ooi_view import BaseOOIListView
from tools.forms.ooi import SelectOOIForm
from tools.models import Indemnification
from tools.models import SCAN_LEVEL

class PageActions(Enum):
    DELETE = "delete"
    UPDATE_SCAN_PROFILE = "update-scan-profile"

@class_view_decorator(otp_required)
class OOIListView(BaseOOIListView):
    breadcrumbs = [{"url": reverse_lazy("ooi_list"), "text": _("Objects")}]
    template_name = "oois/ooi_list.html"
    ooi_types = get_collapsed_types().difference({Finding, FindingType})

    def setup(self, request, *args, **kwargs):
        super().setup(request, *args, **kwargs)
        self.filtered_ooi_types = self.get_filtered_ooi_types()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context["types_display"] = self.get_ooi_types_display()
        context["object_type_filters"] = self.get_ooi_type_filters()
        context["select_oois_form"] = SelectOOIForm(
            context.get("ooi_list", []), organization_code=self.organization.code
        )
        context["member"] = self.organization_member
        context["scan_levels"] = [alias for level, alias in SCAN_LEVEL.choices]
        context["organization_indemnification"] = self.get_organization_indemnification
        context["breadcrumbs"] = [
            {"url": reverse("ooi_list", kwargs={"organization_code": self.organization.code}), "text": _("Objects")},
        ]

        return context

    def get(self, request: HttpRequest, status=200, *args, **kwargs) -> HttpResponse:
        """Override the response status in case submitting a form returns an error message"""
        response = super().get(request, *args, **kwargs)
        response.status_code = status

        return response

    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
        """Perform bulk action on selected oois."""
        selected_oois = request.POST.getlist("ooi")
        if not selected_oois:
            messages.add_message(request, messages.ERROR, _("No OOIs selected."))
            return self.get(request, status=422, *args, **kwargs)

        action = request.POST.get("action")

        if action == PageActions.DELETE.value:
            return self._delete_oois(selected_oois, request, *args, **kwargs)

        if action == PageActions.UPDATE_SCAN_PROFILE.value:

            return self._set_scan_profiles(selected_oois, request, *args, **kwargs)

        messages.add_message(request, messages.ERROR, _("Unknown action."))
        return self.get(request, status=404, *args, **kwargs)

    def _set_scan_profiles(self, selected_oois: List[Reference], request: HttpRequest, *args, **kwargs) -> HttpResponse:
        scan_profile = request.POST.get("scan-profile")

        level = SCAN_LEVEL[scan_profile]

        try:
            self.verify_raise_clearance_level(level.value)
        except IndemnificationNotPresentException:
            messages.add_message(
                self.request,
                messages.ERROR,
                _(
                    "Could not raise clearance level to L%s. \
                    Indemnification not present at organization %s."
                )
                % (
                    level,
                    self.organization.name,
                ),
            )
            return self.get(request, status=403, *args, **kwargs)
        except ClearanceLevelTooLowException:
            messages.add_message(
                self.request,
                messages.ERROR,
                _(
                    "Could not raise clearance level to L%s. \
                    You acknowledged a clearance level of %s."
                )
                % (
                    level,
                    self.organization_member.acknowledged_clearance_level,
                ),
            )
            return self.get(request, status=403, *args, **kwargs)

        for ooi_reference in selected_oois:
            try:
                self.raise_clearance_level(Reference.from_str(ooi_reference), level.value)
            except (RequestException, RemoteException, ConnectionError):
                messages.add_message(
                    request, messages.ERROR, _("An error occurred while saving clearance level for %s.") % ooi_reference
                )
                return self.get(request, status=500, *args, **kwargs)
            except ObjectNotFoundException:
                messages.add_message(
                    request,
                    messages.ERROR,
                    _("An error occurred while saving clearance level for %s.") % ooi_reference
                    + _("OOI doesn't exist"),
                )
                return self.get(request, status=404, *args, **kwargs)

        messages.add_message(
            request,
            messages.SUCCESS,
            _("Successfully set scan profile to %s for %d oois.") % (level.name, len(selected_oois)),
        )
        return self.get(request, *args, **kwargs)

    def _delete_oois(self, selected_oois: List[Reference], request: HttpRequest, *args, **kwargs) -> HttpResponse:
        connector = self.octopoes_api_connector

        for ooi in selected_oois:
            try:
                connector.delete(ooi, valid_time=datetime.now(timezone.utc))
            except (RequestException, RemoteException, ConnectionError):
                messages.add_message(request, messages.ERROR, _("An error occurred deleting %s.") % ooi)
                return self.get(request, status=500, *args, **kwargs)
            except ObjectNotFoundException:
                messages.add_message(
                    request, messages.ERROR, _("An error occurred deleting %s.") % ooi + _("OOI doesn't exist")
                )
                return self.get(request, status=404, *args, **kwargs)

        messages.add_message(
            request,
            messages.SUCCESS,
            _("Successfully deleted %d ooi(s). Note: Bits can recreate objects automatically.") % len(selected_oois),
        )

        return self.get(request, *args, **kwargs)

    def get_organization_indemnification(self):
        return Indemnification.objects.filter(organization=self.organization).exists()

class OOIListExportView(OOIListView):
    def get(self, request, *args, **kwargs):
        super().get(request, *args, **kwargs)

        file_type = request.GET.get("file_type")
        observed_at = self.get_observed_at()
        filters = self.get_ooi_types_display()

        ooi_types = self.ooi_types
        if self.filtered_ooi_types:
            ooi_types = {type_by_name(t) for t in self.filtered_ooi_types}

        ooi_list = self.octopoes_api_connector.list(ooi_types, observed_at).items
        exports = [
            {
                "observed_at": str(observed_at),
                "filters": str(filters),
            }
        ]

        for ooi in ooi_list:
            exports.append(
                {
                    "key": ooi.primary_key,
                    "name": ooi.human_readable,
                    "ooi_type": ooi.ooi_type,
                }
            )

        if file_type == "json":

            response = HttpResponse(
                json.dumps(exports),
                content_type="application/json",
                headers={"Content-Disposition": "attachment; filename=ooi_list_" + str(observed_at) + ".json"},
            )

            return response

        elif file_type == "csv":

            response = HttpResponse(
                content_type="text/csv",
                headers={"Content-Disposition": "attachment; filename=ooi_list_" + str(observed_at) + ".csv"},
            )

            writer = csv.writer(response)
            writer.writerow(["observed_at", "filters"])
            writer.writerow([str(observed_at), str(filters)])
            writer.writerow(["key", "name", "ooi_type"])
            for ooi in ooi_list:
                writer.writerow(
                    [
                        ooi.primary_key,
                        ooi.human_readable,
                        ooi.ooi_type,
                    ]
                )

            return response

        else:

            raise Http404("Export type not found")


""" from https://github.com/keithito/tacotron """

'''
Cleaners are transformations that run over the input text at both training and eval time.

Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
  1. "english_cleaners" for English text
  2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
     the Unidecode library (https://pypi.python.org/pypi/Unidecode)
  3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
     the symbols in symbols.py to match your data).
'''

import re
from unidecode import unidecode
# from phonemizer import phonemize
import phonemizer
global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True,  with_stress=True)
from indic_transliteration import sanscript

# Regular expression matching whitespace:
_whitespace_re = re.compile(r'\s+')

# List of (regular expression, replacement) pairs for abbreviations:
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
  ('mrs', 'misess'),
  ('mr', 'mister'),
  ('dr', 'doctor'),
  ('st', 'saint'),
  ('co', 'company'),
  ('jr', 'junior'),
  ('maj', 'major'),
  ('gen', 'general'),
  ('drs', 'doctors'),
  ('rev', 'reverend'),
  ('lt', 'lieutenant'),
  ('hon', 'honorable'),
  ('sgt', 'sergeant'),
  ('capt', 'captain'),
  ('esq', 'esquire'),
  ('ltd', 'limited'),
  ('col', 'colonel'),
  ('ft', 'fort'),
]]

# List of (iast, ipa) pairs:
_iast_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
    ('a', 'ə'),
    ('ā', 'aː'),
    ('ī', 'iː'),
    ('ū', 'uː'),
    ('ṛ', 'ɹ`'),
    ('ṝ', 'ɹ`ː'),
    ('ḷ', 'l`'),
    ('ḹ', 'l`ː'),
    ('e', 'eː'),
    ('o', 'oː'),
    ('k', 'k⁼'),
    ('k⁼h', 'kʰ'),
    ('g', 'g⁼'),
    ('g⁼h', 'gʰ'),
    ('ṅ', 'ŋ'),
    ('c', 'ʧ⁼'),
    ('ʧ⁼h', 'ʧʰ'),
    ('j', 'ʥ⁼'),
    ('ʥ⁼h', 'ʥʰ'),
    ('ñ', 'n^'),
    ('ṭ', 't`⁼'),
    ('t`⁼h', 't`ʰ'),
    ('ḍ', 'd`⁼'),
    ('d`⁼h', 'd`ʰ'),
    ('ṇ', 'n`'),
    ('t', 't⁼'),
    ('t⁼h', 'tʰ'),
    ('d', 'd⁼'),
    ('d⁼h', 'dʰ'),
    ('p', 'p⁼'),
    ('p⁼h', 'pʰ'),
    ('b', 'b⁼'),
    ('b⁼h', 'bʰ'),
    ('y', 'j'),
    ('ś', 'ʃ'),
    ('ṣ', 's`'),
    ('r', 'ɾ'),
    ('l̤', 'l`'),
    ('h', 'ɦ'),
    ("'", ''),
    ('~', '^'),
    ('ṃ', '^')
]]

def devanagari_to_ipa(text):
    text = text.replace('ॐ', 'ओम्')
    text = re.sub(r'\s*।\s*$', '.', text)
    text = re.sub(r'\s*।\s*', ', ', text)
    text = re.sub(r'\s*॥', '.', text)
    text = sanscript.transliterate(text, sanscript.DEVANAGARI, sanscript.IAST)
    for regex, replacement in _iast_to_ipa:
        text = re.sub(regex, replacement, text)
    text = re.sub('(.)[`ː]*ḥ', lambda x: x.group(0)
                  [:-1]+'h'+x.group(1)+'*', text)
    return text

def expand_abbreviations(text):
  for regex, replacement in _abbreviations:
    text = re.sub(regex, replacement, text)
  return text

def expand_numbers(text):
  return normalize_numbers(text)

def lowercase(text):
  return text.lower()

def collapse_whitespace(text):
  return re.sub(_whitespace_re, ' ', text)

def convert_to_ascii(text):
  return unidecode(text)

def basic_cleaners(text):
  '''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
  text = lowercase(text)
  text = collapse_whitespace(text)
  return text

def transliteration_cleaners(text):
  '''Pipeline for non-English text that transliterates to ASCII.'''
  text = convert_to_ascii(text)
  text = lowercase(text)
  text = collapse_whitespace(text)
  return text

def english_cleaners(text):
  '''Pipeline for English text, including abbreviation expansion.'''
  text = convert_to_ascii(text)
  text = lowercase(text)
  text = expand_abbreviations(text)
  phonemes = phonemize(text, language='en-us', backend='espeak', strip=True)
  phonemes = collapse_whitespace(phonemes)
  return phonemes

def english_cleaners2(text):
  '''Pipeline for English text, including abbreviation expansion. + punctuation + stress'''
  text = convert_to_ascii(text)
  text = lowercase(text)
  text = expand_abbreviations(text)
  # phonemes = phonemize(text, language='en-us', backend='espeak', strip=True, preserve_punctuation=True, with_stress=True)
  phonemes = global_phonemizer.phonemize([text], strip=True, njobs=1)[0]
  phonemes = collapse_whitespace(phonemes)
  return phonemes

def hindi_cleaners2(text):
  '''Pipeline for English text, including abbreviation expansion. + punctuation + stress'''
  text = convert_to_ascii(text)
  text = lowercase(text)
  text = expand_abbreviations(text)
  # phonemes = phonemize(text, language='hi', backend='espeak', strip=True, preserve_punctuation=True, with_stress=True)
  phonemes = global_phonemizer.phonemize([text], strip=True, njobs=1)[0]
  phonemes = collapse_whitespace(phonemes)
  return phonemes

def he_cleaners(text):
    hindi_texts = re.findall(r'\[HI\].*?\[HI\]', text)
    english_texts = re.findall(r'\[EN\].*?\[EN\]', text)
    for hindi_text in hindi_texts:
        cleaned_text = devanagari_to_ipa(hindi_text[4:-4])
        text = text.replace(hindi_text, cleaned_text+' ', 1)
    for english_text in english_texts:
        cleaned_text = english_cleaners2(english_text[4:-4])
        text = text.replace(english_text, cleaned_text+' ', 1)
    text = text[:-1]
    if re.match(r'[^\.,!\?\-…~]', text[-1]):
        text += '.'
    return text


from collections import OrderedDict
from core.choices import PATIENT
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from wagtail.core.models import Collection
from wagtail.documents.models import get_document_model
from patient.api.serializers import PatientSerializer
from utils.file_upload import filename_to_title
from django.utils import timezone
from datetime import datetime
from ..models import Complaint, ChatOptionAnswer, ChatOpinionConversation
from booking.models import booking
from django.utils import timezone
from datetime import datetime

STATUSES = {
    'new': _('New'),
    'in-progress': _('In Progress'),
    'reply': _('Reply'),
    'closed': _('Closed')
}

class ComplaintSerializer(serializers.ModelSerializer):
    class Meta:
        model = Complaint
        exclude = ('created', 'modified')

    def validate(self, attrs):
        booking = attrs.get('booking', None)
        request = self.context['request']
        user = request.user
        attrs['user'] = user
        attrs['type'] = PATIENT
        errors = OrderedDict()
        if booking:
            if not booking.user == user:
                errors['booking'] = [_("Invalid booking id")]

        if errors:
            raise serializers.ValidationError(errors)
        return attrs

class ChatOptionAnswerSerializers(serializers.ModelSerializer):
    question_label = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ChatOptionAnswer
        fields = ('question_label', 'answer')

    def get_question_label(self, obj):
        return obj.question.label if obj.question else obj.question_label

class ConversationSerializer(serializers.ModelSerializer):
    booking_data = serializers.SerializerMethodField(read_only=True)
    patient_can_replay = serializers.ReadOnlyField()
    doctor_attachments = serializers.SerializerMethodField(read_only=True)
    patient_attachments = serializers.SerializerMethodField(read_only=True)
    files = serializers.ListField(required=False, write_only=True)

    class Meta:
        model = ChatOpinionConversation
        exclude = ('modified',)

        extra_kwargs = {
            'patient': {
                'error_messages': {
                    'required': _('Please select patient Profile')
                }
            }
        }

    def __init__(self, *args, **kwargs):
        super(ConversationSerializer, self).__init__(*args, **kwargs)
        self.fields['patient'].required = True
        self.fields['doctor'].required = True

    def get_booking_data(self, obj):
        request = self.context['request']
        from booking.api.serializers import bookingSerializer
        return bookingSerializer(instance=obj.booking,
                                     context={'request': request}).data

    def get_patient_attachments(self, obj):
        request = self.context['request']
        from booking.api.serializers import AttachmentSerializer
        qs = obj.patient_attachments.all()
        if qs.exists():
            return AttachmentSerializer(qs, many=True,
                                        context={'request': request}
                                        ).data
        return []

    def get_doctor_attachments(self, obj):
        request = self.context['request']
        from booking.api.serializers import AttachmentSerializer
        qs = obj.doctor_attachments.all()
        if qs.exists():
            return AttachmentSerializer(qs, many=True,
                                        context={'request': request}
                                        ).data
        return []

    def create(self, validated_data):
        booking = validated_data.get('booking')
        messages = ChatOpinionConversation.objects.filter(
            booking=booking,
            is_doctor_message=False
        )
        doctor_message = ChatOpinionConversation.objects.filter(
            booking=booking,
            is_doctor_message=True
        )
        if self.context.get('request', None):
            user = self.context.get('request').user
        if not messages.count() < 3 and not user.is_doctor:
            raise serializers.ValidationError({
                'message': [_('Maximum Replies limit is 3')]
            })

        files = validated_data.pop('files', None)
        if user.is_doctor and user.doctor == booking.doctor:
            validated_data['is_doctor_message'] = True
        instance = super(ConversationSerializer, self).create(validated_data)
        if files:
            self.save_files(files, instance)
        return instance

    def save_files(self, files, instance):
        from common.api.serializer import CustomBase64FileField

        request = self.context['request']
        DocumentModel = get_document_model()

        if request.user.is_authenticated:
            user_slug = request.user.slug
        else:
            user_slug = "guest"

        try:
            collection = Collection.objects.get(name=user_slug)
        except:
            collection = Collection(name=user_slug)
            root_collection = Collection.get_first_root_node()
            root_collection.add_child(instance=collection)

        for f in files:
            for key, value in f.items():
                data = CustomBase64FileField(value, file_name=key)
                _file = data.to_internal_value(value)

                name = _file.name
                if _file:
                    file = DocumentModel(
                        file=_file,
                        title=filename_to_title(name),
                        collection=collection
                    )
                    file.save()
                    if instance.is_doctor_message:
                        instance.doctor_attachments.add(file)
                    else:
                        instance.patient_attachments.add(file)

class ChatOpinionSerializer(serializers.ModelSerializer):
    status = serializers.SerializerMethodField(read_only=True)
    status_display = serializers.SerializerMethodField(read_only=True)
    patient = serializers.SerializerMethodField(read_only=True)
    doctor = serializers.SerializerMethodField(read_only=True)
    creation_time = serializers.SerializerMethodField(read_only=True)
    creation_date = serializers.SerializerMethodField(read_only=True)
    can_share_data = serializers.SerializerMethodField(read_only=True)
    questions_ans = ChatOptionAnswerSerializers(
        required=False, many=True, source='booking_Chat_opinion_answer'
    )
    attachments = serializers.SerializerMethodField(read_only=True)

    def __init__(self, *args, **kwargs):
        remove_fields = kwargs.pop('remove_fields', None)
        self.user = kwargs.pop('user', None)
        super(ChatOpinionSerializer, self).__init__(*args, **kwargs)

        if remove_fields:
            for field_name in remove_fields:
                self.fields.pop(field_name)

    class Meta:
        model = booking
        fields = ('id', 'status', 'status_display', 'patient', 'doctor', 'creation_time',
                  'creation_date', 'attachments', 'questions_ans', 'can_share_data')

    def get_attachments(self, obj):
        from booking.api.serializers import AttachmentSerializer
        return AttachmentSerializer(obj.attachments, many=True).data

    def get_doctor(self, obj):
        from doctor.api.serializers import DoctorSerializer
        return DoctorSerializer(obj.doctor, read_only=True, remove_fields=['hospital']).data

    def get_can_share_data(self, obj):
        if obj.can_share_data:
            return obj.can_share_data
        return False

    def get_status(self, obj):
        if obj.status:
            return obj.status
        return None

    def get_status_display(self, obj):
        if obj.status == 'completed' or obj.status == 'cancelled':
            return STATUSES.get('closed')
        if self.context.get('request', None):
            if self.context['request'].GET.get('status', None) == 'reply' and obj.status == 'in-progress':
                return STATUSES.get('reply')
            else:
                return STATUSES.get(obj.status)
        else:
            return STATUSES.get(obj.status)

    def get_patient(self, obj):
        if obj.can_share_data:
            serializer = PatientSerializer(obj.patient, read_only=True)
        else:
            serializer = PatientSerializer(
                obj.patient, read_only=True, remove_fields=["medical_details"])
        return serializer.data

    def get_creation_time(self, obj):
        creation_time = timezone.localtime(obj.created)
        return creation_time.strftime('%I:%M %p')

    def get_creation_date(self, obj):
        UTC_OFFSET_TIMEDELTA = datetime.now() - datetime.utcnow()
        correct_date = obj.created + UTC_OFFSET_TIMEDELTA
        return correct_date.strftime('%b %d, %Y')


import collections
import os

import pandas as pd
import numpy as np
from torch import is_inference_mode_enabled

from ..utils.builder import build_pipeline,PIPELINES

@PIPELINES.register_module()
class time_stamp_gen:
    def __init__(self,encoder_length,decoder_length,time_interval,):
        self.encoder_length = encoder_length
        self.decoder_length = decoder_length
        self.time_interval = time_interval

    def __call__(self,data):
        time_interval = self.time_interval * 1000
        start_time = data['start_time']
        end_time = start_time + (self.encoder_length + self.decoder_length) * 60 * time_interval
        time_stamp = np.arange(start_time + time_interval*0.5,end_time,
                                time_interval)
        data['time_stamp'] = time_stamp

        return data


INPUT_FILE = "input{}.txt".format("1")

if __name__=="__main__":
    with open(INPUT_FILE, "r") as input_file:
        totals = []
        total = 0
        for line in input_file.read().splitlines():
            if line:
                total += int(line)
            else:
                totals.append(total)
                total = 0
    totals.sort(reverse=True)
    print(sum(totals[:3]))


"""
dansfunctions - various useful functions in python
usage:
>>import dansfunctions
>>dansfunctions.fg  # module of general mathematical, vector and string format functions
>>dansfunctions.fp  # module of matplotlib shortcuts
>>dansfunctions.widgets  # module of tkinter shortcuts

Requirements: numpy
Optional requirements: matplotlib, tkinter
"""

from . import functions_general as fg

try:
    import matplotlib
    matplotlib.use('TkAgg')
    from . import functions_plotting as fp
except ImportError:
    fp = None
    print('Matplotlib may not be available')

try:
    from .tkgui import basic_widgets as widgets
except ImportError:
    widgets = None
    print('tkinter may not be available')

def version_info():
    return 'dansfunctions version %s (%s)' % (fg.__version__, fg.__date__)

def module_info():
    import sys
    out = 'Python version %s' % sys.version
    out += '\n%s' % version_info()
    # Modules
    out += '\n     numpy version: %s' % fg.np.__version__
    try:
        import matplotlib
        out += '\nmatplotlib version: %s' % matplotlib.__version__
    except ImportError:
        out += '\nmatplotlib version: None'
    try:
        import tkinter
        out += '\n   tkinter version: %s' % tkinter.TkVersion
    except ImportError:
        out += '\n   tkinter version: None'
    return out

def check_general_functions():
    print('dansfunctions/functions_general.py')
    print('Version: %s (%s)' % (fg.__version__, fg.__date__))
    print('Methods:')
    print(fg.list_methods(fg, False))

def check_plotting_functions():
    print('dansfunctions/functions_plotting.py')
    if fp is None:
        print('Matplotlib may not be available')
        return
    print('Version: %s (%s)' % (fp.__version__, fp.__date__))
    print('Methods:')
    print(fg.list_methods(fp, False))

def check_tkinter_functions():
    print('dansfunctions/tkgui/basic_widgets.py')
    if widgets is None:
        print('tkinter may not be available')
        return
    print('Version: %s (%s)' % (widgets.__version__, widgets.__date__))
    print('Methods:')
    print(fg.list_methods(widgets, False))


'''
YYYYY
SYSYS
YYYYY
YSYYS
YYYYY
'''

from itertools import combinations
from collections import deque

graph = []

for _ in range(5):
    graph.append(list(input()))

answers = []

def range_check(i, j):
    if 0 <= i < 5 and 0 <= j < 5: return True
    else: return False

gaps = [[1, 0], [0, 1], [-1, 0], [0, -1]]

def conv_loc(num):
    return (num // 5, num % 5)

def conv_num(i, j):
    return  i * 5 + j

target_list = combinations(range(25), 7)

answer = 0

def is_connected(target):
    node_num = 1
    q = deque()
    visited = [False] * 25

    q.append(conv_loc(target[0]))
    visited[target[0]] = True

    while q:
        cur_i, cur_j = q.popleft()
        for gap in gaps:
            next_i = cur_i + gap[0]
            next_j = cur_j + gap[1]
            if range_check(next_i, next_j):
                next_num = conv_num(next_i, next_j)
                if next_num in target and not visited[next_num]:
                    q.append((next_i, next_j))
                    visited[next_num] = True
                    node_num += 1

    if node_num == 7: return True
    else: return False

def solve(target):
    global answer
    y_num = 0
    for t in target:
        i, j = conv_loc(t)
        if graph[i][j] == 'Y': y_num += 1
    if y_num > 3: return
    if not is_connected(target): return
    answer += 1

for target in target_list:
    solve(target)

print(answer)


from sys import stdin
input = stdin.readline

count = 666
chk = 0

n = int(input())

while True:
    if '666' in str(count):
        chk+=1

    if chk == n:
        print(count)
        break

    count+=1


from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cstr, flt
from frappe.desk.form.linked_with import get_linked_doctypes, get_linked_docs
import erpnext
import json

########################## Section Rad++ ##########################
print_debug = False

@frappe.whitelist()
def reasign_batch(item_code, batch, stock_entry):
	doc_batch = frappe.get_doc("Batch",batch)

	if "Nouveau" in stock_entry:
		frappe.throw("l'entrée de marchandise doit être enregistrée avant de pouvoir utiliser cette fonction.")
		return

	linked_doctypes = get_linked_doctypes("Batch")
	if print_debug: frappe.errprint("linked_doctypes : " + cstr(linked_doctypes))
	if print_debug: frappe.errprint("stock_entry : " + cstr(stock_entry))

	linked_doc = get_linked_docs("Batch",batch,	linked_doctypes)

	if linked_doc:
		if print_debug: frappe.errprint("linked_doc : " + cstr(linked_doc))
		for key, value in linked_doc.items():
			if print_debug: frappe.errprint("key : " + cstr(key))
			if print_debug: frappe.errprint("value : " + cstr(value))
			if key != "Stock Entry" and key != "Purchase Receipt":
				frappe.throw(_("Le lot {0} est lié au document {1}. Veuillez supprimer tous les liens avec le lot {0} avant de continuer").format(batch,cstr(value)))
			if key == "Stock Entry":
				for link in value:
					stock_entry_split = stock_entry.split('-')
					if not stock_entry_split[1] in link.name:
						if print_debug: frappe.errprint("stock_entry : " + stock_entry)
						if print_debug: frappe.errprint("link.name : " + link.name)
						frappe.throw(_("Le lot {0} est lié au document {1}. Veuillez supprimer tous les liens avec le lot {0} avant de continuer").format(batch,link.name))
					for stock_entry_detail_name in frappe.get_all("Stock Entry Detail", {"batch_no":batch,"parent":link.name}, "name"):
						frappe.db.set_value("Stock Entry Detail", stock_entry_detail_name, "batch_no","")
			if key == "Purchase Receipt":
				for link in value:
					stock_entry_split = stock_entry.split('-')
					if not stock_entry_split[1] in link.name:
						if print_debug: frappe.errprint("stock_entry : " + stock_entry)
						if print_debug: frappe.errprint("link.name : " + link.name)
						frappe.throw(_("Le lot {0} est lié au document {1}. Veuillez supprimer tous les liens avec le lot {0} avant de continuer").format(batch,link.name))
					for doc_detail_name in frappe.get_all("Purchase Receipt Item", {"batch_no":batch,"parent":link.name}, "name"):
						frappe.db.set_value("Purchase Receipt Item", doc_detail_name, "batch_no","")

	frappe.db.set_value("Batch", batch, "item",item_code)

@frappe.whitelist()
def get_item_details_translated(args):

	from erpnext.stock.get_item_details import get_item_details
	out = get_item_details(args)

	args = process_args(args)

	lang = "fr"

	if args.get("customer"):
		if print_debug: frappe.logger().debug(" if args.customer : " + args.customer)
		if frappe.db.get_value("Customer", args.customer, "language"):
			if print_debug: frappe.logger().debug(" if Customer ")
			lang = frappe.db.get_value("Customer", args.customer, "language")

		if frappe.db.get_value("Lead", args.customer, "language"):
			if print_debug: frappe.logger().debug(" if Lead ")
			lang = frappe.db.get_value("Lead", args.customer, "language")

	if args.get("supplier"):
		lang = frappe.db.get_value("Supplier", args.supplier, "language")

	out.update({
			"description": frappe.db.get_value("Item Language", {"parent":args.item_code,"language":lang}, "description") or frappe.db.get_value("Item", args.item_code, "description")
		})

	if print_debug: frappe.logger().debug(out)

	return out

def process_args(args):
	if isinstance(args, basestring):
		args = json.loads(args)

	args = frappe._dict(args)

	return args


import numpy as np

MAX_COLOUR = 255.0

IMG_SIZE = 224

# Gabor / grating parameters; orientation in radians, phase in radians,
# spatial frequencies in cycles per image (assume 224 px <-> 6.4 deg)
PARAM_DICT = dict()
PARAM_DICT["orientations"] = np.linspace(0, 172.5, 10) * np.pi / 180
PARAM_DICT["spatial_frequencies"] = np.array([2.5, 3.5, 5, 7.1, 10, 14.1, 20, 28.3, 40, 56])
PARAM_DICT["phases"] = np.linspace(0, 2*np.pi, 10)

# Gabor patch parameters
GABOR_SIGMA = 35
GABOR_GAMMA = 1 # spatial aspect ratio (1 = isotropic)


def matching(graph):
    """
    Find maximum cardinality matching of a bipartite graph (U,V,E).
    The input format is a dictionary mapping members of U to lists
    of their neighbors in V.  The output is a triple (M,A,B) where M is a
    dictionary mapping members of V to their matches in U, A is the part
    of the maximum independent set in U, and B is the part of the MIS in V.
    The same object may occur in both U and V, and is treated as two
    distinct vertices if this happens.
    """

    # initialize greedy matching (redundant, but faster than full search)
    matching = {}
    for u in graph:
        for v in graph[u]:
            if v not in matching:
                matching[v] = u
                break

    while True:
        # structure residual graph into layers
        # pred[u] gives the neighbor in the previous layer for u in U
        # preds[v] gives a list of neighbors in the previous layer for v in V
        # unmatched gives a list of unmatched vertices in final layer of V,
        # and is also used as a flag value for pred[u] when u is in the first layer
        preds = {}
        unmatched = []
        pred = {u:unmatched for u in graph}
        for v in matching:
            del pred[matching[v]]
        layer = list(pred)

        # repeatedly extend layering structure by another pair of layers
        while layer and not unmatched:
            newLayer = {}
            for u in layer:
                for v in graph[u]:
                    if v not in preds:
                        newLayer.setdefault(v,[]).append(u)
            layer = []
            for v in newLayer:
                preds[v] = newLayer[v]
                if v in matching:
                    layer.append(matching[v])
                    pred[matching[v]] = v
                else:
                    unmatched.append(v)

        # did we finish layering without finding any alternating paths?
        if not unmatched:
            unlayered = {}
            for u in graph:
                for v in graph[u]:
                    if v not in preds:
                        unlayered[v] = None
            return (matching,list(pred),list(unlayered))

        # recursively search backward through layers to find alternating paths
        # recursion returns true if found path, false otherwise
        def recurse(v):
            if v in preds:
                L = preds[v]
                del preds[v]
                for u in L:
                    if u in pred:
                        pu = pred[u]
                        del pred[u]
                        if pu is unmatched or recurse(pu):
                            matching[v] = u
                            return True
            return False

        for v in unmatched: recurse(v)


import pytest

from logic_parser.evaluation import TruthTable

@pytest.mark.parametrize(
    "expr",
    [
        "~(p & q) = (~p | ~q)",  # DeMorgan
        "(p > q) = (~p | q)",  # Implication removal
        "(p & (p | q)) = p",  # Absorption
        "(p > q) = (~q > ~p)",  # Reverse implication
        "(~p & (q | p)) = ((~p & q) | (~p & p))",  # Distribution of & over |
        "(~p | (q & p)) = ((~p | q) & (~p | p))",  # Distribution of | over &
        "(p = q) = ((p > q) & (q > p))",
        "(p = q) = ((p & q) | (~p & ~q))",  # Equivalence removal
        "((p > q) & p) > q",  # Modus ponens
        "(p & q) > p",  # Conjunction removal
    ],
)
def test_truth_table_tautologies(expr, grammar):
    tree = TruthTable(expr, grammar)
    assert tree.is_tautology is True
    assert tree.is_contradiction is False
    assert tree.is_contingency is False

@pytest.mark.parametrize(
    "expr",
    ["p & ~p", "(p & q) & (~p & q)", "(p = q) & ~(q > p)", "~(~(p & q) = (~p | ~q))"],
)
def test_truth_table_contradictions(expr, grammar):
    tree = TruthTable(expr, grammar)
    assert tree.is_tautology is False
    assert tree.is_contradiction is True
    assert tree.is_contingency is False

def test_dimensions():
    assert True


import math
import random

#kör
class Kor:
    def __init__(self, r, kozeppont=(0,0)): #KONSTRUKTOR
        self.r = r
        self.kozeppont = kozeppont
    def terulet(self):
        return self.r*self.r*math.pi
    def kerulet(self):
        return 2*self.r*math.pi
    def info(self):
        print(f"A(z) {self.r}cm sugarú {self.kozeppont} középpontű körnek \n telülete {self.terulet():.2f}cm\n kerülete: {self.kerulet():.2f}cm")

#példány
kor01 = Kor(5,(2,6))
kor01.info()
print(isinstance(kor01,Kor)) #Azonos típus? -> True / False
print(type(kor01))

#metodus
print(f"{kor01.terulet():.2f}")

korok = []

for _ in range(5):
    kor = Kor(random.randint(0,10))
    korok.append(kor)

for x in korok:
    x.info()


# import scientific libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize, fsolve
from scipy.optimize import Bounds
from typing import List
from sklearn.metrics import r2_score
plt.close('all')

# import data and define the variables

from dataimport import *
from Identification import *
kd1 = kd[0]; kd2 = kd[1]
C_in  = float(T2["Cin"])
S1_in = float(T2["S1in"])
D     = 1/T1["HRT"]
S1   = T1["S1"]
XT   = T1["XT"]
C    = T1["C"]
q_C  = T1["q_C"]
q_M  = T1["q_CH4"]         # Experimental points for the regression and comparison

# create main function
def main():

    # define the bounds
    bd = Bounds([0,0],[20,20])

    # define the initial values
    gs = [1,50]

    # solve minimization problem
    minsol = minimize(rmse, gs, args = (D, S1, XT, q_M, C, C_in, S1_in, k_hyd), method = 'SLSQP', bounds = bd, tol = 1e-10)
    qCmodel = qCeval(D, S1, XT, q_M, C, C_in, S1_in, k_hyd, minsol.x[0], minsol.x[1])

    # print out results
    fprint(minsol.x, minsol.success, minsol.nit, minsol.fun, [q_C, qCmodel])

    # plot results
    regplot(1/D, [q_C, qCmodel], 'time [days]', 'q_C [mmol/L/d]', 'Carbon dioxide production regression', ['Experimental data', 'Model'], False)

    # plot function surface
    CCx = np.linspace(0, 4, 40)
    DDx = np.linspace(0, 10, 40)

    rmsez = np.empty([len(CCx), len(DDx)])
    for i in range(0,len(CCx)):
        for j in range(0,len(DDx)):
            rmsez[i][j] = rmse([CCx[i], DDx[j]], D, S1, XT, q_M, C, C_in,  S1_in, k_hyd)

    surfplot(CCx, DDx, rmsez, 'CC', 'DD', 'rmse', 'rmse over CC and DD values', False)

    k4x = np.linspace(0, 200, 20)
    k5x = np.linspace(0, 200, 20)

    rmsez = np.empty([len(k4x), len(k5x)])
    for i in range(0,len(k4x)):
        for j in range(0,len(k5x)):
            rmsez[i][j] = rmse([k4x[i]/k1, k5x[j]/k6], D, S1, XT, q_M, C, C_in, S1_in, k_hyd)

    surfplot(k4x, k5x, rmsez, 'k4', 'k5', 'rmse', 'rmse over k4 and k5 values', False)
    print(rmse([13.68/k1, 186.97/k6], D, S1, XT, q_M, C, C_in,  S1_in, k_hyd))
    return 0;

# define the function for RSE
def rmse(x, D, S1, XT, q_M, C, C_in, S1_in, k_hyd) -> float:
    qClist = []
    for i in range(0, len(D)):
         qClist.append(qCeval(D[i], S1[i], XT[i], q_M[i], C[i], C_in, S1_in, k_hyd, x[0], x[1]))

    return np.sqrt(np.mean(q_C-qClist)**2)

# define the function for the qC
def qCeval(D, S1, XT, q_M, C, C_in, S1_in, k_hyd, CC, DD) -> float:
    return D*(C_in-C) + CC*(D*(S1_in-S1) + k_hyd*XT) + DD*q_M

# utility function for printing and plotting
def fprint(sol, flag, itr, funcall, r2: List):
    print(f"\nSuccess: {flag}\n")
    print("==Results==")
    print(f"Solution: {sol}")
    print(f"k4: {sol[0]*k1}")
    print(f"k5: {sol[1]*k6}")
    print(f"RSE: {funcall}")
    print(f"Iterations: {itr}")
    print(f"R2 score: {r2_score(r2[0], r2[1])}")
    print("============")

def regplot(x, y: List, xlabel, ylabel, title, legend: List, showbool):
    plt.figure(figsize=(10,5))
    plt.plot(x, y[0], 'o', label = legend[0])
    plt.plot(x, y[1], '-', label = legend[1], linewidth=2)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.grid(True)
    plt.legend()
    plt.title(title)

    if showbool == True:
        plt.show()
    else:
        pass

def surfplot(x, y, z, xlabel, ylabel, zlabel, title, showbool):
    import mpl_toolkits.mplot3d.axes3d as axes3d
    from matplotlib import cm
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    X, Y = np.meshgrid(x, y)
    ax.plot_surface(X, Y, z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_zlabel(zlabel)
    ax.set_title(title)

    if showbool == True:
        plt.show()
    else:
        pass

if __name__ == "__main__":
    main()

AD-OCS/Old Versions/OLD Not sulfur/V2.0 Constants minimization/minimOpt_Second.py


from __future__ import unicode_literals

from shuup.notify.base import ScriptTemplate
from shuup.notify.models.script import Script

class BaseScriptTemplate(ScriptTemplate):
    """
    A base ScriptTemplate class which provides implementation for create and update the script.
    """

    def get_script_steps(self, form=None):
        """
        Returns a list of Steps to use in the script.

        :param django.forms.Form|None form: validated form to use or None

        :return: list of steps
        :rtype: list[shuup.notify.Step]
        """
        return []

    def create_script(self, shop, form=None):
        """ Creates the script based on the event and the steps """
        script = Script(event_identifier=self.event.identifier, name=self.name, enabled=True, shop=shop)
        script.set_steps(self.get_script_steps(form))
        script.save()
        return script

    def update_script(self, form):
        """ Change the steps and save the script """
        self.script_instance.set_steps(self.get_script_steps(form))
        self.script_instance.save()
        return self.script_instance


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

import urllib2, json, sys, time
import requests

gene_omim_file = 'genelist_with_omim.xls'
with open(gene_omim_file) as f:
    gene_names = [line.strip().split()[3] for line in f if not line.startswith('chromosome') ]

## do esearch with gene_name
gene_names = set(gene_names)
gene_varid = {}
for gene in gene_names:
    gene_search_url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=clinvar&term={gene}[gene]&retmax=100&retmode=json'.format(**locals() )
    gene_varid[gene] = json.loads(urllib2.urlopen(gene_search_url).read() )
    time.sleep(2)

with open('gene_varid.json','w') as f:
    json.dump(gene_varid, f, indent=2)
## do esummary with varid
with open('gene_varid.json','r') as f:
    gene_varid = json.loads(f.read() )

for gene in gene_varid:
    varid = ','.join(gene_varid[gene]['esearchresult']['idlist'][:20] )

    req = requests.post('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi',
    data={'db':'clinvar', 'id':varid,
    'retmode':'json', 'email':'cuij@newgenegle.com',
    'tool':'Link2Clinvar'} )
    gene_varid[gene]['esumresult'] = req.json()
    time.sleep(1)

with open('gene_varid_esummary.json', 'w') as f:
    json.dump(gene_varid, f, indent=2)

### add annote info from  gene_varid_esummary.json to genelist_with_omim.xls
with open('gene_varid_esummary.json') as f:
    gene_varid = json.loads(f.read() )

for gene, ssresult in gene_varid.iteritems():
    if ssresult['esearchresult']['count'] == '0': #some gene return none result
        continue
    gene_varid[gene]['trait_names'] = []
    for uid in ssresult['esumresult']['result']['uids']:
        if ssresult['esumresult']['result'][uid].has_key('error'):
        #some varid return error
            continue
        if len(ssresult['esumresult']['result'][uid]['genes'] ) == 1:
            trait_set = ssresult['esumresult']['result'][uid]['trait_set']
            if trait_set:
                gene_varid[gene]['trait_names'].append( trait_set[0]['trait_name'] )
        else:
            pass
    gene_varid[gene]['trait_names'] = [tn for tn in gene_varid[gene]['trait_names'] if tn != 'See cases']
    gene_varid[gene]['trait_names'] = ','.join( list( set(gene_varid[gene]['trait_names']) ) )

result = []
result.append('#OMIM date:2016-01-04\n#ClinVar date:2016-01-06\n')
result.append('chromosome\tregion_start\tregion_end\tgene_name\tlocation\tdisease_omim\tgene_function\tdisease_clinvar\n')
with open(gene_omim_file) as f:
    for line in f:
        if line.startswith('chromosome'):
            continue
        gene_name = line.strip().split()[3]
        if gene_name in gene_varid:
            trait = gene_varid[gene_name]['trait_names'] if gene_varid[gene_name].has_key('trait_names') else ''
            trait_line = '{0}\t{1}\n'.format(
            line.strip('\n'), trait )
        else:
            trait_line = line
        result.append(trait_line)

with open('clinvar_{gene_omim_file}'.format(**locals() ), 'w') as f:
    f.writelines(result)


import subprocess

def create_environment():

    # Define the name of the virtual environment
    venv_name = "app"  # Change this to your desired environment name

    # Create the virtual environment
    subprocess.run(["python3", "-m", "venv", venv_name])

    # Activate the virtual environment
    activate_script = f"./{venv_name}/bin/activate"
    subprocess.run(["source", activate_script], shell=True)

    # Install requirements from 'requirements.txt'
    subprocess.run(["pip", "install", "-r", "requirement.txt"])

    # Deactivate the virtual environment
    # subprocess.run(["deactivate"], shell=True)

    # print("Virtual environment created and requirements installed.")


#!usr/bin/env python3
# Sean Reid

def GCD(m,n):
	rem = m % n
	if rem == 0:
		return n
	elif rem == 1:
		return 1
	return GCD(n,rem)

def main():
	print("GCD calculator!")
	number1 = int(input("Enter a number:"))
	number2 = int(input("Enter another number:"))
	if number1 and number2 == 0:
		print("Error! Both numbers cannot be 0")
	else:
		print(GCD(number1,number2))

if __name__ == '__main__':
	main()


import yaml
import os
import copy
import argparse
import numpy as np
import pandas as pd

BASE_DIR = "../../Results/Count_Contact/Resnet50/Pruning_Parameters/"

summary_data = []

## 1) Iterate through all base models, Mask Training tasks
base_models = os.listdir(BASE_DIR)
for base_model in base_models:
    mask_training_tasks = os.listdir(os.path.join(BASE_DIR, base_model))
    for mask_task in mask_training_tasks:
        mask_configurations = os.listdir(os.path.join(BASE_DIR, base_model, mask_task))

        ## 2) Concatenate all masked models together within a base model + mask training task
        data = []
        for mask_configuration in mask_configurations:
            try:
                data.append(pd.read_csv(os.path.join(BASE_DIR, base_model, mask_task, mask_configuration, "results.csv")))
            except:
                print(base_model)
                print(mask_configuration)
        data = pd.concat(data)

        # Get just relevant rows
        data = data[(data["0_ablation"].isna()) & (data["1_task"] == int(mask_task)) & (data["0_train"] == 0)]

        ## Get the configuration with best test acc
        high_acc = np.max(data["2_test_acc"])
        best_masked_model = data[data["2_test_acc"] == high_acc].iloc[0].to_frame().T
        best_masked_model["Base Model"] = [base_model]
        summary_data.append(best_masked_model)

## 5) Save summary DF
summary_data = pd.concat(summary_data)
summary_data.to_csv(os.path.join(BASE_DIR, "summary.csv"))


import json
import time

from setup.setup import setup_class, teardown_class, url, session

class Test():
    @classmethod
    def setup_class(cls):
        setup_class()

    @classmethod
    def teardown_class(cls):
        teardown_class()

    #@pytest.mark.skip
    def test_check_notification(self):
        time.sleep(1)
        token = session.cookies.get("token")
        headers = {
            'token': token
        }
        responseN = {
            "data": {
                "new_notifications_available": False
            },
            "msg": "OK",
            "status": 200
        }
        response = session.get("{}/api/notifications".format(url), headers=headers)
        js = json.loads(response.text)
        assert js == responseN
        duration = response.elapsed.total_seconds()
        assert duration <= 0.5

    def test_fetch_notifications(self):
        time.sleep(1)
        expect = {
            "data": {
                "customer_notifications": []
            },
            "msg": "OK",
            "status": 200
        }
        token = session.cookies.get("token")
        response = session.post("{}/api/notifications".format(url))
        res=json.loads(response.text)
        assert res==expect
        duration = response.elapsed.total_seconds()
        assert duration <= 0.5

    # one more test and complete previos one
    # def test_push_notification(self):
    #     time.sleep(1)
    #     response=session.get("{}/api/push-notifications".format(url))
    #     print(response.text)


def quicksort(a,p,r):
    if p<r:
        q = partition(a,p,r)
        quicksort(a,p,q-1)
        quicksort(a,q+1,r)

def partition(a,p,r):
    x = a[r]
    i = p-1
    for j in range(p, r, 1):
        if a[j]<x:
            i +=1
            a[i], a[j] = a[j], a[i]
    a[i+1], a[r] = a[r], a[i+1]
    return i+1

f1 = open("input3.txt", "r")
f2 = open("output3.txt", "w")
inp = f1.read().split("\n")
f1.close()
n = int(inp[0])
arr = inp[1].split(" ")
arr = list(map(int, arr))
quicksort(arr,0,n-1)
arr = list(map(str, arr))
f2.write(" ".join(arr))
f2.close()


import string

# the "strings" utility written in Python

def get(filename, min=4):
    try:
        with open(filename, "rb") as f:
            result = ""
            for c in f.read():
                if c in string.printable:
                    result += c
                    continue
                if len(result) >= min:
                    yield result
                result = ""
            if len(result) >= min:
                yield result

    except Exception as e:
        print(e)


def main():
	n=int(input())
	ar=[int(i) for i in input().split()]
	if ar.count(ar[0])==n:
		return print(0, n*(n-1)//2)
	else:
		return print(max(ar)-min(ar), ar.count(max(ar))*ar.count(min(ar)))
	'''d=dict()
	ar.sort()
	for i in ar:
		d[i]=d.get(i,0)+1
	count=0
	ma=ar[-1]-ar[0]
	for i in ar:
		if i+ma in d:
			d[i]=d[i]-1
			count+=d[i+ma]'''
	print(ma, count)
	return 0

if __name__ == '__main__':
	main()


from itertools import zip_longest

INPUT_FILE = "input{}.txt".format("3")

if __name__=="__main__":
    with open(INPUT_FILE, "r") as input_file:
        scores = []
        lines = input_file.read().splitlines()
        for index in range(0, len(lines), 3):
            sepLines = list(lines[index:index + 3])
            print(sepLines)
            samesies = []
            for i in sepLines[0]:
                for j in sepLines[1]:
                    for k in sepLines[2]:
                        if i == j == k:
                            samesies.append(i)
            print(samesies)
            scores.append(samesies[0])

        print(sum([ord(i) - 96 if i.lower() == i else ord(i) - 38 for i in scores]))


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

###
#Examples - Not all of them are working
###

import numpy as np
import itertools
import theano
from theano import tensor

from blocks import initialization
from blocks.initialization import (
    Constant, IsotropicGaussian, Orthogonal, Identity, Uniform)
from blocks.bricks import Identity, Linear, Tanh
from blocks.bricks.recurrent import LSTM, SimpleRecurrent, GatedRecurrent,Bidirectional
from blocks.bricks.parallel import Fork

def example():
    """ Simple reccurent example. Taken from : https://github.com/mdda/pycon.sg-2015_deep-learning/blob/master/ipynb/blocks-recurrent-docs.ipynb """
    x = tensor.tensor3('x')

    rnn = SimpleRecurrent(dim=3, activation=Identity(), weights_init=initialization.Identity())
    rnn.initialize()
    h = rnn.apply(x)

    f = theano.function([x], h)
    print(f(np.ones((3, 1, 3), dtype=theano.config.floatX)))

    doubler = Linear(
                 input_dim=3, output_dim=3, weights_init=initialization.Identity(2),
                 biases_init=initialization.Constant(0))
    doubler.initialize()
    h_doubler = rnn.apply(doubler.apply(x))

    f = theano.function([x], h_doubler)
    print(f(np.ones((3, 1, 3), dtype=theano.config.floatX)))

    #Initial State
    h0 = tensor.matrix('h0')
    h = rnn.apply(inputs=x, states=h0)

    f = theano.function([x, h0], h)
    print(f(np.ones((3, 1, 3), dtype=theano.config.floatX),
            np.ones((1, 3), dtype=theano.config.floatX)))

#
# Questions
#

def example2():
    """GRU"""
    x = tensor.tensor3('x')
    dim = 3

    fork = Fork(input_dim=dim, output_dims=[dim, dim*2],name='fork',output_names=["linear","gates"], weights_init=initialization.Identity(),biases_init=Constant(0))
    gru = GatedRecurrent(dim=dim, weights_init=initialization.Identity(),biases_init=Constant(0))

    fork.initialize()
    gru.initialize()

    linear, gate_inputs = fork.apply(x)
    h = gru.apply(linear, gate_inputs)

    f = theano.function([x], h)
    print(f(np.ones((dim, 1, dim), dtype=theano.config.floatX)))

    doubler = Linear(
                 input_dim=dim, output_dim=dim, weights_init=initialization.Identity(2),
                 biases_init=initialization.Constant(0))
    doubler.initialize()

    lin, gate = fork.apply(doubler.apply(x))
    h_doubler = gru.apply(lin,gate)

    f = theano.function([x], h_doubler)
    print(f(np.ones((dim, 1, dim), dtype=theano.config.floatX)))

def example3():
    """GRU + SimpleReccurrent. nope"""
    pass

def example4():
    """LSTM -> Plante lors de l'initialisation du lstm."""

    x = tensor.tensor3('x')
    dim=3

#    gate_inputs = theano.function([x],x*4)
    gate_inputs = Linear(input_dim=dim,output_dim=dim*4, name="linear",weights_init=initialization.Identity(), biases_init=Constant(2))

    lstm = LSTM(dim=dim,activation=Tanh(), weights_init=IsotropicGaussian(), biases_init=Constant(0))

    gate_inputs.initialize()
    hg = gate_inputs.apply(x)

    #print(gate_inputs.parameters)
    #print(gate_inputs.parameters[1].get_value())

    lstm.initialize()
    h, cells = lstm.apply(hg)
    print(lstm.parameters)

    f = theano.function([x], h)
    print(f(np.ones((dim, 1, dim), dtype=theano.config.floatX)))
    print(f(np.ones((dim, 1, dim), dtype=theano.config.floatX)))
    print(f(4*np.ones((dim, 1, dim), dtype=theano.config.floatX)))

    print("Good Job!")

#    lstm_output =

    #Initial State
    h0 = tensor.matrix('h0')
    c =  tensor.matrix('cells')
    h,c1 = lstm.apply(inputs=x, states=h0, cells=c) # lstm.apply(states=h0,cells=cells,inputs=gate_inputs)

    f = theano.function([x, h0, c], h)
    print("a")
    print(f(np.ones((3, 1, 3), dtype=theano.config.floatX),
            np.ones((1, 3), dtype=theano.config.floatX),
            np.ones((1, 3), dtype=theano.config.floatX)))

def example5():
    """Bidir + simplereccurent. Adaptation from a unittest in blocks """

    bidir = Bidirectional(weights_init=Orthogonal(),
                               prototype=SimpleRecurrent(
                                   dim=3, activation=Tanh()))

    simple = SimpleRecurrent(dim=3, weights_init=Orthogonal(),
                                  activation=Tanh(), seed=1)

    bidir.allocate()
    simple.initialize()

    bidir.children[0].parameters[0].set_value(

        simple.parameters[0].get_value())

    bidir.children[1].parameters[0].set_value(
        simple.parameters[0].get_value())

    #Initialize theano variables and functions
    x = tensor.tensor3('x')
    mask = tensor.matrix('mask')

    calc_bidir = theano.function([x, mask],
                                 [bidir.apply(x, mask=mask)])
    calc_simple = theano.function([x, mask],
                                  [simple.apply(x, mask=mask)])

    #Testing time

    x_val = 0.1 * np.asarray(
        list(itertools.permutations(range(4))),
        dtype=theano.config.floatX)

    x_val = (np.ones((24, 4, 3), dtype=theano.config.floatX) *
                  x_val[..., None])

    mask_val = np.ones((24, 4), dtype=theano.config.floatX)
    mask_val[12:24, 3] = 0

    h_bidir = calc_bidir(x_val, mask_val)[0]
    h_simple = calc_simple(x_val, mask_val)[0]
    h_simple_rev = calc_simple(x_val[::-1], mask_val[::-1])[0]

    print(h_bidir)
    print(h_simple)
    print(h_simple_rev)

#Example 6. Taken from blocks rnn tutorial

from blocks.bricks.recurrent import BaseRecurrent, recurrent

class FeedbackRNN(BaseRecurrent):
    def __init__(self, dim, **kwargs):
        super(FeedbackRNN, self).__init__(**kwargs)
        self.dim = dim
        self.first_recurrent_layer = SimpleRecurrent(
            dim=self.dim, activation=Identity(), name='first_recurrent_layer',
            weights_init=initialization.Identity())
        self.second_recurrent_layer = SimpleRecurrent(
            dim=self.dim, activation=Identity(), name='second_recurrent_layer',
            weights_init=initialization.Identity())
        self.children = [self.first_recurrent_layer,
                         self.second_recurrent_layer]

    @recurrent(sequences=['inputs'], contexts=[],
               states=['first_states', 'second_states'],
               outputs=['first_states', 'second_states'])
    def apply(self, inputs, first_states=None, second_states=None):
        first_h = self.first_recurrent_layer.apply(
            inputs=inputs, states=first_states + second_states, iterate=False)
        second_h = self.second_recurrent_layer.apply(
            inputs=first_h, states=second_states, iterate=False)
        return first_h, second_h

    def get_dim(self, name):
        return (self.dim if name in ('inputs', 'first_states', 'second_states')
                else super(FeedbackRNN, self).get_dim(name))

def example6():
    """ http://blocks.readthedocs.org/en/latest/rnn.html """
    x = tensor.tensor3('x')

    feedback = FeedbackRNN(dim=3)
    feedback.initialize()
    first_h, second_h = feedback.apply(inputs=x)

    f = theano.function([x], [first_h, second_h])
    for states in f(np.ones((3, 1, 3), dtype=theano.config.floatX)):
        print(states)

#
# Experimentations
#

#Adaptation du code plus haut pour un nombre arbitraire de RNN
class FeedbackRNNStack(BaseRecurrent):
    depth = 3

    def __init__(self, dim, depth, **kwargs):
        super(FeedbackRNNStack, self).__init__(**kwargs)
        self.dim = dim
        self.depth = depth
        self.children = []
        FeedbackRNNStack.depth = depth

        for i in range(depth):
            self.children.append(SimpleRecurrent(
            dim=self.dim, activation=Identity(), name=str(i)+'th_recurrent_layer',
            weights_init=initialization.Identity()))

    @recurrent(sequences=['inputs'], contexts=[],
               states=[str(i)+'th_states' for i in range(depth)],
               outputs=[str(i)+'th_states' for i in range(depth)])
    def apply(self, inputs):

        hs = [self.children[0].apply(inputs=inputs, iterate=False)]

        for i in range(1,self.depth):

            hs.append(self.children[i].apply(
            inputs=hs[-1], iterate=False))

        return hs

    def get_dim(self, name):
        return (self.dim if name in ['inputs'] + [str(i)+'th_states' for i in range(self.depth)]
                else super(FeedbackRNNStack, self).get_dim(name))

def example7():
    """Not working """
    x = tensor.tensor3('x')

    s = FeedbackRNNStack(dim=3,depth=3)
    s.initialize()
    hiddens = s.apply(inputs=x)

    f = theano.function([x], hiddens)
    for states in f(np.ones((3, 1, 3), dtype=theano.config.floatX)):
        print(states)

def test_square():
    from blocks.bricks.cost import SquaredError
    x = tensor.tensor3()
    y = tensor.tensor3()

    c = SquaredError()
    o = c.apply(x,y)
    f = theano.function([x,y],o)
    print(f(np.ones((3,3,3),dtype=theano.config.floatX),5*np.ones((3,3,3),dtype=theano.config.floatX)))

#def dropout(X, p=0.):
#    if p > 0:
#        retain_prob = 1 - p
#        X *= srng.binomial(X.shape, p=retain_prob, dtype=theano.config.floatX)
#        X /= retain_prob
#    return X


import argparse
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))

import torch
import numpy as np
from volksdep.converters import torch2onnx

from vedastr.runners import InferenceRunner
from vedastr.utils import Config

def parse_args():
    parser = argparse.ArgumentParser(description='Inference')
    parser.add_argument('config', type=str, help='config file path')
    parser.add_argument('checkpoint', type=str, help='checkpoint file path')
    parser.add_argument('out', type=str, help='output model file name')
    parser.add_argument('--dummy_input_shape', type=str, default='3,32,100',
                        help='input shape (e.g. 3,32,100) in C,H,W format')
    parser.add_argument('--dynamic_shape', action='store_true',
                        help='whether to use dynamic shape')
    parser.add_argument('--opset_version', default=9, type=int,
                        help='onnx opset version')
    parser.add_argument('--do_constant_folding', action='store_true',
                        help='whether to apply constant-folding optimization')
    parser.add_argument('--verbose', action='store_true',
                        help='whether print convert info')
    args = parser.parse_args()

    return args

def main():
    args = parse_args()

    cfg_path = args.config
    cfg = Config.fromfile(cfg_path)

    deploy_cfg = cfg['deploy']
    common_cfg = cfg.get('common')
    if torch.cuda.is_available():
        device = torch.cuda.current_device()
        deploy_cfg['gpu_id'] = str(device)
    else:
        raise AssertionError('Please use gpu for benchmark.')

    runner = InferenceRunner(deploy_cfg, common_cfg)
    runner.load_checkpoint(args.checkpoint)

    C, H, W = [int(_.strip()) for _ in args.dummy_input_shape.split(',')]
    dummy_image = np.random.random_integers(0, 255, (H, W, C)).astype(np.uint8)

    aug = runner.transform(image=dummy_image, label='')
    image, label = aug['image'], aug['label']
    image = image.unsqueeze(0).cuda()
    dummy_input = (image, runner.converter.test_encode(['']))
    model = runner.model.cuda().eval()
    need_text = runner.need_text
    if not need_text:
        dummy_input = dummy_input[0]

    if args.dynamic_shape:
        print(
            f'Convert to Onnx with dynamic input shape and opset version'
            f'{args.opset_version}'
        )
    else:
        print(
            f'Convert to Onnx with constant input shape'
            f' {args.dummy_input_shape} and opset version '
            f'{args.opset_version}'
        )

    torch2onnx(
        model,
        dummy_input,
        args.out,
        verbose=args.verbose,
        dynamic_shape=args.dynamic_shape,
        opset_version=args.opset_version,
        do_constant_folding=args.do_constant_folding,
    )

    runner.logger.info(
        f'Convert successfully, saved onnx file: {os.path.abspath(args.out)}'
    )

if __name__ == '__main__':
    main()


from django.conf.urls import url
from django.contrib import admin

from .views import (
    PlaylistCreateAPIView,
    PlaylistDeleteAPIView,
    PlaylistDetailAPIView,
    PlaylistListAPIView,
    PlaylistUpdateAPIView,
    )

urlpatterns = [
    url(r'^$', PlaylistListAPIView.as_view(), name='list'),
    url(r'^create/$', PlaylistCreateAPIView.as_view(), name='create'),
    url(r'^(?P<slug>[\w-]+)/$', PlaylistDetailAPIView.as_view(), name='detail'),
    url(r'^(?P<slug>[\w-]+)/edit/$', PlaylistUpdateAPIView.as_view(), name='update'),
    url(r'^(?P<slug>[\w-]+)/delete/$', PlaylistDeleteAPIView.as_view(), name='delete'),
]


import os
import sys

files = os.listdir('./img/')
cwd = os.path.realpath('./img/')

for i in files:
    if "2021" in i:
        temp = i.split('_Wed_')[0] + i.split('2021')[1]
        oldpath = cwd + "/" + i
        newpath = cwd + "/" + temp
        os.rename(oldpath, newpath)


from common.aocdays import AOCDay, day

DEBUG = True

@day(17)
class Day17(AOCDay):
    test_input = """target area: x=20..30, y=-10..-5""".split("\n")

    target = None

    def test(self, input_data):
        p1 = self.part1(self.test_input).__next__()
        assert p1 == 45, f'{p1} != 45'

        p2 = self.part2(self.test_input).__next__()
        assert p2 == 112, f'{p2} != 112'

    def common(self, input_data):
        yield 0

    def part1(self, input_data):
        part = input_data[0].split(': ')[1]
        xvalues = part.split(', ')[0].lstrip('x=')
        yvalues = part.split(', ')[1].lstrip('y=')

        x0 = int(xvalues.split('..')[0])
        x1 = int(xvalues.split('..')[1])
        y0 = int(yvalues.split('..')[0])
        y1 = int(yvalues.split('..')[1])
        self.target = (x0 if x0 < x1 else x1, y0 if y0 < y1 else y1, x1 if x1 > x0 else x0, y1 if y1 > y0 else y0)

        successful_shots = []

        for x in range(150):
            for y in range(170):
                shot = self.shoot(x,y)
                if shot is not None:
                    successful_shots.append(shot)

        max_y = 0
        for t in successful_shots:
            for (_,y) in t:
                if y > max_y:
                    max_y = y

        yield max_y

    def part2(self, input_data):
        part = input_data[0].split(': ')[1]
        xvalues = part.split(', ')[0].lstrip('x=')
        yvalues = part.split(', ')[1].lstrip('y=')

        x0 = int(xvalues.split('..')[0])
        x1 = int(xvalues.split('..')[1])
        y0 = int(yvalues.split('..')[0])
        y1 = int(yvalues.split('..')[1])
        self.target = (x0 if x0 < x1 else x1, y0 if y0 < y1 else y1, x1 if x1 > x0 else x0, y1 if y1 > y0 else y0)

        successful_shots = []

        for x in range(150):
            for y in range(-170, 170):
                shot = self.shoot(x,y)
                if shot is not None:
                    successful_shots.append(shot)

        yield len(successful_shots)

    def shoot(self, x, y):
        trajectory = []
        pos = (0,0)
        trajectory.append(pos)

        miss = False
        hit = False
        while not miss and not hit:
            pos = (pos[0]+x, pos[1]+y)
            trajectory.append(pos)
            if x != 0:
                x = x-1 if x > 0 else x+1
            y -= 1

            if self.target[0] <= pos[0] <= self.target[2] and self.target[1] <= pos[1] <= self.target[3]:
                hit = True
            elif (x == 0 and (pos[0] < self.target[0] or pos[0] > self.target[2])) or (pos[1] < self.target[1]):
                miss = True

        if hit:
            return trajectory
        else:
            return None