import pandas as pd
import random
from sklearn import metrics
# --------------
from transformers import BertTokenizer
from transformers.configuration_albert import AlbertConfig
from transformers.modeling_albert import AlbertForMaskedLM
from transformers.modeling_albert import load_tf_weights_in_albert
# --------------
from rdkit import Chem
from torch_geometric.data import DataLoader
from torch.nn.utils.rnn import pad_sequence
from torch_geometric.utils import to_dense_batch
import torch
from typing import Sequence, Tuple, List, Union

from ligand_graph_features import *
from data_tool_box_DRD import load_json

def sample_minibatch_maml(args,train_maml_pfam,train_maml):
    batch_data_maml = []
    batch_pfam_maml = np.random.choice(train_maml_pfam,args['task_num'])

    for task_pfam in batch_pfam_maml:
    # for task_pfam in train_maml_pfam:
        per_task ={}
        task_data = train_maml[task_pfam]
        for s in ['spt','qry']:
            df = pd.DataFrame()
            df= df.append(  task_data['pos'].sample(args['k_' +s], replace=True))
            df= df.append(  task_data['neg'].sample(args['k_'+s], replace=True))
            per_task[s]= df
        batch_data_maml.append(per_task)
    return batch_data_maml

def sample_minibatch_classic(args,train_classic):
    batch_pos = train_classic['pos'].sample(args['classic_batch_size'])
    batch_neg = train_classic['neg'].sample(args['classic_batch_size'])

    batch_classic = pd.concat([batch_pos, batch_neg])
    return batch_classic
def sample_minibatch_test(args,train_classic):
    batch_pos = train_classic['pos'].sample(args['test_batch_size_pos'])
    batch_neg = train_classic['neg'].sample(args['test_batch_size_neg'])

    batch_classic = pd.concat([batch_pos, batch_neg])
    return batch_classic
# =======================================================
#             model related
# =======================================================
def load_DISAE(cwd):
    all_config = load_json( 'DTI_config.json')
    albertconfig = AlbertConfig.from_pretrained(cwd+ all_config['DISAE']['albertconfig'])
    m = AlbertForMaskedLM(config=albertconfig)
    m = load_tf_weights_in_albert(m, albertconfig, cwd+all_config['DISAE']['albert_pretrained_checkpoint'])
    prot_descriptor = m.albert
    prot_tokenizer = BertTokenizer.from_pretrained(cwd+all_config['DISAE']['albertvocab'])
    return  prot_descriptor,prot_tokenizer
# =======================================================
#             maml
# =======================================================
def get_repr_DTI_MAML(batch_data_pertask,mode,prot_tokenizer,chem_dict,protein_dict,args):
    batch_chem_graphs_spt,batch_protein_tokenized_spt = get_repr_DTI(batch_data_pertask[mode],
                                                                    prot_tokenizer,
                                                                    chem_dict,protein_dict,
                                                                    'DISAE')
    batch_chem_graphs_spt = batch_chem_graphs_spt.to(args['device'])
    batch_protein_tokenized_spt = batch_protein_tokenized_spt.to(args['device'])

    y_spt = torch.LongTensor(list(batch_data_pertask[mode]['Activity'].values)).to(args['device'])
    return batch_chem_graphs_spt,batch_protein_tokenized_spt,y_spt

def core_batch_prediction_MAML(batch_data_pertask, args, tokenizer,mode,loss_fn,
                               chem_dict, protein_dict, model,detach=False):

    batch_chem_graphs_spt, batch_protein_tokenized_spt, y_spt = get_repr_DTI_MAML(batch_data_pertask,
                                                              mode,
                                                              tokenizer, chem_dict, protein_dict,
                                                              args)

    batch_logits = model(batch_protein_tokenized_spt, batch_chem_graphs_spt)
    loss = loss_fn(batch_logits,y_spt)
    if detach == True:
        batch_logits = batch_logits.detach().cpu()
        y_spt = y_spt.detach().cpu()

    return batch_logits, y_spt,loss
def get_repr_DTI_0shot(batch_data,tokenizer,chem_dict,protein_dict,args):
    #  . . . .  chemicals  . . . .
    chem_smiles = chem_dict[batch_data['InChIKey'].values.tolist()].values.tolist()
    chem_graph_list = []
    for smiles in chem_smiles:
        mol = Chem.MolFromSmiles(smiles)
        graph = mol_to_graph_data_obj_simple(mol)
        chem_graph_list.append(graph)
    chem_graphs_loader = DataLoader(chem_graph_list, batch_size=batch_data.shape[0],
                                    shuffle=False)
    for batch in chem_graphs_loader:
        chem_graphs = batch
    #  . . . .  proteins  . . . .
    # if prot_descriptor_choice =='DISAE':
    uniprot_list = batch_data['uniprot+pfam'].values.tolist()
    protein_tokenized = torch.tensor([tokenizer.encode(protein_dict[uni]) for uni in uniprot_list  ])
    #  . . . .  to return  . . . .
    chem_graphs = chem_graphs.to(args['device'])
    protein_tokenized = protein_tokenized.to(args['device'])
    label = torch.LongTensor(list(batch_data['Activity'].values)).to(args['device'])
    return chem_graphs, protein_tokenized,label

def core_batch_prediction_0shot(batch_data_pertask, args, tokenizer,loss_fn,
                               chem_dict, protein_dict, model,detach=True):
    batch_chem_graphs_spt, batch_protein_tokenized_spt, y_spt = get_repr_DTI_0shot(batch_data_pertask,
                                                              tokenizer, chem_dict, protein_dict,
                                                              args)

    batch_logits = model(batch_protein_tokenized_spt, batch_chem_graphs_spt)
    loss = loss_fn(batch_logits,y_spt)
    if detach == True:
        batch_logits = batch_logits.detach().cpu()
        y_spt = y_spt.detach().cpu()
    return batch_logits, y_spt,loss

def get_repr_DTI(batch_data,tokenizer,chem_dict,protein_dict,prot_descriptor_choice):
    #  . . . .  chemicals  . . . .
    chem_smiles = chem_dict[batch_data['InChIKey'].values.tolist()].values.tolist()
    chem_graph_list = []
    for smiles in chem_smiles:
        mol = Chem.MolFromSmiles(smiles)
        graph = mol_to_graph_data_obj_simple(mol)
        chem_graph_list.append(graph)
    chem_graphs_loader = DataLoader(chem_graph_list, batch_size=batch_data.shape[0],
                                    shuffle=False)
    for batch in chem_graphs_loader:
        chem_graphs = batch
    #  . . . .  proteins  . . . .
    if prot_descriptor_choice =='DISAE':
        uniprot_list = batch_data['uniprot+pfam'].values.tolist()
        protein_tokenized = torch.tensor([tokenizer.encode(protein_dict[uni]) for uni in uniprot_list  ])

    return chem_graphs, protein_tokenized

#------------------
#  read data
#------------------

def load_training_data(exp_path,debug_ratio):
    def load_data(exp_path,file,debug_ratio):
        dataset = pd.read_csv(exp_path +file)
        cut = int(dataset.shape[0] * debug_ratio)
        print(file[:-3] + ' size:', cut)
        return dataset.iloc[:cut,:]

    train = load_data(exp_path,'train.csv',debug_ratio)
    dev   = load_data(exp_path,'dev.csv',debug_ratio)
    test  = load_data(exp_path,'test.csv',debug_ratio)

    return train, dev, test

#------------------
#  evaluate
#------------------

def evaluate_binary_predictions(label, predprobs):
    probs = np.array(predprobs)
    predclass = np.argmax(probs, axis=1)
    # --------------------------by label---
    bothF1 = metrics.f1_score(label, predclass, average=None)
    bothprecision = metrics.precision_score(label, predclass, average=None)
    bothrecall = metrics.recall_score(label, predclass, average=None)
    class0 = [bothF1[0], bothprecision[0], bothrecall[0]]
    class1 = [bothF1[1], bothprecision[1], bothrecall[1]]
    # -------------------------overall---
    f1 = metrics.f1_score(label, predclass, average='weighted')
    fpr, tpr, thresholds = metrics.roc_curve(label, probs[:, 1], pos_label=1)
    auc = metrics.auc(fpr, tpr)
    prec, reca, thresholds = metrics.precision_recall_curve(label, probs[:, 1], pos_label=1)
    aupr = metrics.auc(reca, prec)

    overall = [f1,auc,aupr]
    return overall,class0,class1


"""AtomRhoOrbitalRadialSlater and AtomRhoOrbitalRadialSlaterL classes."""

from typing import NoReturn
import os
import os.path
import math
import numpy
import scipy
import scipy.optimize
from pycifstar import to_data

from cryspy.A_functions_base.function_1_objects import \
    form_items_by_dictionary

from cryspy.A_functions_base.orbital_functions import calc_jl

from cryspy.B_parent_classes.cl_1_item import ItemN
from cryspy.B_parent_classes.cl_2_loop import LoopN

from cryspy.C_item_loop_classes.cl_1_atom_type_scat import AtomTypeScat

class AtomRhoOrbitalRadialSlater(ItemN):
    """Description of radial Slater functions.

    These items are used when the radial dependence of the
    electron density, R(k(l), l, r), of the atom specified in
    _atom_rho_orbital_atom_label is expressed as a Slater-type
    function [Hansen & Coppens (1978), equation (3)]:

    Attributes
        - n0, zeta0 (mandatory)
        - "coeff_1s", "coeff_2s", "coeff_3s", "coeff_4s", "coeff_5s", "coeff_6s",
          "coeff_2p", "coeff_3p", "coeff_4p", "coeff_5p", "coeff_6p",
          "coeff_3d", "coeff_4d", "coeff_5d", "coeff_6d",
          "coeff_4f", "coeff_5f", "coeff_6f" (optional)
    """

    ATTR_MANDATORY_NAMES = ("n0", "zeta0")
    ATTR_MANDATORY_TYPES = (int, float)
    ATTR_MANDATORY_CIF = ("n0", "zeta0")

    ATTR_OPTIONAL_NAMES = (
        "coeff_1s", "coeff_2s", "coeff_3s", "coeff_4s", "coeff_5s", "coeff_6s",
        "coeff_2p", "coeff_3p", "coeff_4p", "coeff_5p", "coeff_6p",
        "coeff_3d", "coeff_4d", "coeff_5d", "coeff_6d",
        "coeff_4f", "coeff_5f", "coeff_6f")
    ATTR_OPTIONAL_TYPES = (
        float, float, float, float, float, float,
        float, float, float, float, float,
        float, float, float, float,
        float, float, float)
    ATTR_OPTIONAL_CIF = (
        "coeff_1s", "coeff_2s", "coeff_3s", "coeff_4s", "coeff_5s", "coeff_6s",
        "coeff_2p", "coeff_3p", "coeff_4p", "coeff_5p", "coeff_6p",
        "coeff_3d", "coeff_4d", "coeff_5d", "coeff_6d",
        "coeff_4f", "coeff_5f", "coeff_6f")

    ATTR_NAMES = ATTR_MANDATORY_NAMES + ATTR_OPTIONAL_NAMES
    ATTR_TYPES = ATTR_MANDATORY_TYPES + ATTR_OPTIONAL_TYPES
    ATTR_CIF = ATTR_MANDATORY_CIF + ATTR_OPTIONAL_CIF

    ATTR_INT_NAMES = ()
    ATTR_INT_PROTECTED_NAMES = ()

    # parameters considered are refined parameters
    ATTR_REF = ("zeta0",
        "coeff_1s", "coeff_2s", "coeff_3s", "coeff_4s", "coeff_5s", "coeff_6s",
        "coeff_2p", "coeff_3p", "coeff_4p", "coeff_5p", "coeff_6p",
        "coeff_3d", "coeff_4d", "coeff_5d", "coeff_6d",
        "coeff_4f", "coeff_5f", "coeff_6f")
    ATTR_SIGMA = tuple([f"{_h:}_sigma" for _h in ATTR_REF])
    ATTR_CONSTR_FLAG = tuple([f"{_h:}_constraint" for _h in ATTR_REF])
    ATTR_REF_FLAG = tuple([f"{_h:}_refinement" for _h in ATTR_REF])
    ATTR_CONSTR_MARK = tuple([f"{_h:}_mark" for _h in ATTR_REF])

    # constraints on the parameters
    D_CONSTRAINTS = {}

    # default values for the parameters
    D_DEFAULT = {}
    for key in ATTR_SIGMA:
        D_DEFAULT[key] = 0.
    for key in (ATTR_CONSTR_FLAG + ATTR_REF_FLAG):
        D_DEFAULT[key] = False
    for key in ATTR_CONSTR_MARK:
        D_DEFAULT[key] = ""

    PREFIX = "atom_rho_orbital_radial_slater"

    def __init__(self, **kwargs) -> NoReturn:
        super(AtomRhoOrbitalRadialSlater, self).__init__()

        # defined for any integer and float parameters
        D_MIN = {"n0": 0, "zeta0": 0.}

        # defined for ani integer and float parameters
        D_MAX = {}

        self.__dict__["D_MIN"] = D_MIN
        self.__dict__["D_MAX"] = D_MAX
        for key, attr in self.D_DEFAULT.items():
            setattr(self, key, attr)
        for key, attr in kwargs.items():
            setattr(self, key, attr)

    def calc_normalized_rho(self, radius: numpy.array, kappa: float = 1.) -> \
            numpy.array:
        """Give normalized Slatter type function.

        R = ((2*zeta0)**(n0+0.5)/((2*n0)!)**0.5)*r**(n0-1)*exp(-zeta0*r)
        (see Clementi_1974)

        Arguments
        ---------
            - radius is numpy 1D array of float numbers in Angstrem
            - kappa is describes contraction/extension of atomic orbital

        Output
        ------
            - normalized radial density given as numpy 1D array of floats

        Example
        -------
            >>> radius = numpy.linspace(0.,5,600)
            >>> rho = obj.calc_normalized_rho(radius)
        """
        # transformation from atomic units to inverse angstrems
        zeta0 = self.zeta0
        n0 = self.n0
        zeta_ang = kappa*zeta0/0.52918
        coeff_norm = ((2.*zeta_ang)**(float(n0)+0.5)) / \
            math.sqrt(math.factorial(2*n0))
        norm_density = coeff_norm*(radius**(n0-1))*numpy.exp(-zeta_ang*radius)
        return norm_density

    def calc_jl(self, sthovl: numpy.array, l_max: int, kappa: float = 1.) -> \
            numpy.array:
        """Calculate jl for l from 0 until l_max of atomic orbital."""
        zeta0 = self.zeta0
        n0 = self.n0
        jl = calc_jl(sthovl, [1.], [n0], [zeta0, ], kappa=kappa, l_max=l_max)
        return jl

class AtomRhoOrbitalRadialSlaterL(LoopN):
    """Description of radial Slater functions.

    These items are used when the radial dependence of the
    electron density, R(k(l), l, r), of the atom specified in
    _atom_rho_orbital_atom_label is expressed as a Slater-type
    function [Hansen & Coppens (1978), equation (3)]:
    """

    ITEM_CLASS = AtomRhoOrbitalRadialSlater
    ATTR_INDEX = None # "atom_label"

    def __init__(self, loop_name: str = None, **kwargs) -> NoReturn:
        super(AtomRhoOrbitalRadialSlaterL, self).__init__()
        self.__dict__["items"] = form_items_by_dictionary(self.ITEM_CLASS, kwargs)
        self.__dict__["loop_name"] = loop_name

    def calc_normalized_rho(self, radius: numpy.array, shell: str, kappa=1.,
                            *argv) -> numpy.array:
        """Calc normalized rho.

        Give normalized Slatter type function at given radius for given shell.

        $$
        R = sum_i coeff_i*((2*zeta0)**(n0+0.5)/(2*n0)!)*r**(n0-1)*exp(-zeta0*r)
        $$
        (see Clementi_1974)

        Arguments
        ---------
            - radius is numpy 1D array of float numbers in Angstrem
            - shell is it is orbital shell
            - kappa is describes contraction/extension of atomic orbital

        Output
        ------
            - normalized radial density given as numpy 1D array of floats

        Example
        -------
            >>> radius = numpy.linspace(0.,5,600)
            >>> rho = obj.calc_rho(radius, "3d")
            >>> rho = obj.calc_rho(radius, "3d", "2s")
        """
        # transformation from atomic units to inverse angstrems
        l_shell = [shell]
        l_shell.extend(argv)
        n_shell = len(l_shell)
        n_item = len(self.items)
        coeff = numpy.zeros((n_shell, n_item), dtype=float)

        norm_density = numpy.zeros((radius.size, n_shell), dtype=float)

        l_attr = [f"coeff_{_.strip():}" for _ in l_shell]
        for _i, _item in enumerate(self.items):
            normalized_rho = _item.calc_normalized_rho(radius, kappa=kappa)
            for _j, _attr in enumerate(l_attr):
                coeff[_j, _i] = float(getattr(_item, _attr))
            norm_density += normalized_rho[:, numpy.newaxis] * \
                (coeff[:, _i])[numpy.newaxis, :]
        return norm_density

    @classmethod
    def take_objects_for_atom_type(cls, atom_type: str) -> list:
        """Take objects for atom type."""
        l_arors = []
        f_dir = os.path.dirname(__file__)
        f_dir = os.path.join(os.path.dirname(f_dir), "A_functions_base")
        f_name = os.path.join(f_dir, "atom_rho_orbital_radial_slater.rcif")

        obj_rcif = to_data(f_name)
        s_atom_type = ("".join([_ for _ in atom_type if _.isalpha()])).lower()
        for loop in obj_rcif.loops:
            loop_rcif = cls.from_cif(str(loop))
            if loop_rcif is not None:
                s_loop_name = loop_rcif.loop_name
                s_atom_type_loop = (s_loop_name.split("_")[0]).lower()
                if s_atom_type_loop == s_atom_type:
                    l_arors.append(loop_rcif)
        return l_arors

    def calc_jl_by_radial_density(self, sthovl, lmax: int, shell: str,
                                  kappa=1.):
        """Calculate <j_l> for given sthovl, l and shell.

        $$
        <j_l> = sum_{n, dzeta} integral_{0}^{inf} R^{2}(n,dzeta,r) j_l(r*s) dr
        $$
        """
        n0 = numpy.array(self.n0, dtype=int)
        zeta0 = numpy.array(self.zeta0, dtype=float)
        coeff = numpy.array(getattr(self, f"coeff_{shell:}"), dtype=float)

        if any([_ is None for _ in coeff]):
            return None

        jl = calc_jl(sthovl, coeff, n0, zeta0, kappa=kappa, l_max = 3)

        return jl

    def refine_coefficients_by_jl(self, atom_type: str, shell: str,
                                  sthovl_min=0.0, sthovl_max=2.0, lande=2.,
                                  kappa=1., sthvl_num=100):
        """Refine coefficients by jl."""
        ats = AtomTypeScat.form_by_symbol(atom_type)

        sthovl = numpy.linspace(sthovl_min, sthovl_max, num=int(sthvl_num))
        ff = ats.calc_form_factor(sthovl, lande=lande, kappa=kappa)
        fitable = self.get_variables()

        def tempfunc(param):
            for _1, _2 in zip(fitable, param):
                _1.value = abs(_2)  # only positive coefficients
            j0 = self.calc_jl_by_radial_density(sthovl, 0, shell, kappa)[0]
            chi_sq = (numpy.square(ff - j0)).sum()
            return chi_sq

        param_0 = [_.value for _ in fitable]
        j0 = self.calc_jl_by_radial_density(sthovl, 0, shell, kappa)[0]

        res = scipy.optimize.basinhopping(tempfunc, param_0, niter=10,
                                          T=0.1, stepsize=0.1, interval=20,
                                          disp=True)
        for _1, _2 in zip(fitable, res.x):
            _1.value = abs(_2)  # only positive coefficients, found minima

        return res


import logging
import os
import shutil
import subprocess
import tempfile

import multiprocessing as mp
from autometa.common.exceptions import ExternalToolError

logger = logging.getLogger(__name__)

def sort(sam, bam, cpus=mp.cpu_count()):
    """
    Views then sorts sam file by leftmost coordinates and outputs to bam.

    Parameters
    ----------
    sam : str
        </path/to/alignment.sam>
    bam : str
        </path/to/output/alignment.bam>
    cpus : int, optional
        Number of processors to be used. By default uses all the processors of the system

    Raises
    ------
    TypeError
        cpus must be an integer greater than zero
    FileNotFoundError
        Specified path is incorrect or the file is empty
    ExternalToolError
        Samtools did not run successfully, returns subprocess traceback and command run
    """

    if not isinstance(cpus, int) or cpus <= 0:
        raise TypeError(f"cpus must be an integer greater than zero! Given: {cpus}")
    if not os.path.exists(sam) or not os.path.getsize(sam):
        raise FileNotFoundError(
            f"The specified path: {sam} is either incorrect or the file is empty"
        )
    samtools_out_dir = os.path.dirname(os.path.abspath(bam))
    err = os.path.join(samtools_out_dir, "samtools.err")
    out = os.path.join(samtools_out_dir, "samtools.out")
    with tempfile.TemporaryDirectory() as tempdir:  # this will delete the temporary files even if program stops in between
        temp_bam = os.path.join(tempdir, os.path.basename(bam))
        cmd = f"samtools view -@{cpus} -bS {sam} | samtools sort -@{cpus} -o {temp_bam}"
        logger.debug(f"cmd: {cmd}")
        with open(out, "w") as stdout, open(err, "w") as stderr:
            try:
                subprocess.run(
                    cmd, stdout=stdout, stderr=stderr, shell=True, check=True
                )
            except subprocess.CalledProcessError as err:
                raise ExternalToolError(cmd, err)
            shutil.move(temp_bam, bam)
        os.remove(err)
        os.remove(out)
    return bam

def main():
    import argparse
    import logging as logger

    logger.basicConfig(
        format="%(asctime)s : %(name)s : %(levelname)s : %(message)s",
        datefmt="%m/%d/%Y %I:%M:%S %p",
    )
    parser = argparse.ArgumentParser(
        description="Takes a sam file, sorts it and returns the output to a bam file"
    )
    parser.add_argument("sam", help="</path/to/alignment.sam>", type=str)
    parser.add_argument("bam", help="</path/to/output/alignment.bam>", type=str)
    parser.add_argument(
        "--cpus", help="Number of processors to use", default=mp.cpu_count(), type=int
    )
    args = parser.parse_args()
    sort(sam=args.sam, bam=args.bam, cpus=args.cpus)

if __name__ == "__main__":

    main()


import websocket
import json
import requests
from config import username, password, rooms, header, admin, avatar
from battle import Battle

current_battle = None
current_information = None
opp_pokemon = {
    "name": None,
    "hp": None
}

def parser(wsapp, message):
    #websocket.enableTrace(True) # for debugging purposes
    message = message.split("|")
    if message[1] == "challstr": # creates necessary string to log in
        if len(message[3]) != 0:
            challstr = message[2] + "|" + message[3]
            log_in(challstr)
    if message[1] == "pm":
        pm_parser(message[2], message[4])
    if message[-2] == "gametype":
        global current_battle
        current_battle = Battle()
    elif message[1] == "request":
        if current_battle.getTeam() == None:
            current_battle.organize_team(message[2])
        global current_information
        current_information = json.loads(message[2])
        if "forceSwitch" in current_information:
            global opp_pokemon
            battle(message[0], current_information, current_battle, opp_pokemon)
    elif message[-2] == "turn":
        for i in range(0, len(message)):
            if message[i][0:4] == "p1a:":
                if message[i][-2:] == r'\n':
                    opp_pokemon["name"] = message[i][5:-2]
                else:
                    opp_pokemon["name"] = message[i][5:]
                if message[i-1] == "switch":
                    opp_pokemon["hp"] = message[i+2][:-1]
                elif message[i-1] == "-damage":
                    opp_pokemon["hp"] = message[i+1]
        battle(message[0], current_information, current_battle, opp_pokemon)

def log_in(challstr):
    body = {
        "act": "login",
        "name": username,
        "pass": password,
        "challstr": challstr
    }
    # sends a post request to the server
    r = requests.post("https://play.pokemonshowdown.com/~~showdown/action.php", headers = header, data = body)
    assertion = r.text.partition('"assertion":"')[2]
    assertion = assertion[:-2]
    # finishes log-in process to the server
    wsapp.send("|/trn " + username + "," + avatar + "," + assertion)
    # joins rooms that are wanted
    if len(rooms) > 0:
        for i in rooms:
            wsapp.send("|/join " + i)
    wsapp.send("|/avatar " + avatar)

def pm_parser(sender, message):
    if message[0:10] == "/challenge":
        if message[11:] == "gen8randombattle":
            wsapp.send("|/utm null")
            wsapp.send("|/accept " + sender)
        else:
            wsapp.send("|/reject " + sender)
            wsapp.send("|/pm " + sender + ", I do not support battling in this format. Send .help for more info.")
    elif message == ".kill" and sender[1:] == admin:
        wsapp.close()
    elif message == ".help":
            wsapp.send("|/pm " + sender + ", Hi! I am a bot programmed by " + admin + ". If you want to battle me, I can battle in [Gen 8] Random Battle, though I am still in development and could stop working during a battle.")

def battle(battle_link, information, current_battle, opponent = None):
    currentMon = current_battle.currentPokemon(information)
    if "active" in information:
        wsapp.send("|/msgroom " + battle_link[1:-1] + ", " + current_battle.move_selection_priority(information, opponent))
    elif "forceSwitch" in information:
        current_battle.faint(currentMon)
        wsapp.send("|/msgroom " + battle_link[1:-1] + ", " + "/choose switch " + current_battle.switch(opponent, information))

# connects to websocket
wsapp = websocket.WebSocketApp("wss://sim3.psim.us/showdown/websocket", on_message=parser)
# makes it an endless connection
wsapp.run_forever()


#!/usr/bin/env python
"""Copy random files form source to the destination"""
import logging
import os

def parseArgs():
    """Parse arguments from command line"""
    from argparse import ArgumentParser
    from sys import exit

    parser = ArgumentParser(
        description='Copy random files from source to destination')

    parser.add_argument('source',
                        help='source directory')
    parser.add_argument('destination',
                        help='destination directory')
    parser.add_argument('-d', '--debug', action='store_true',
                        help='enable debug output')
    parser.add_argument('-e', '--extension', default='.mp3',
                        help='file extension filter (defaults to ".mp3")')
    parser.add_argument('-n', '--number', type=int,
                        help='limit the number of files to copy')
    parser.add_argument('-r', '--random', action='store_true',
                        help='insert random id on the destination file name')
    parser.add_argument('-s', '--size', type=int,
                        help='limit the total size (in MB) to copy')

    args = parser.parse_args()

    if not os.path.exists(args.source):
        exit('Invalid source: {}'.format(args.source))

    if not os.path.exists(args.destination):
        exit('Invalid destination: {}'.format(args.destination))

    if args.debug:
        logging.basicConfig(level=logging.DEBUG, format='%(message)s')
        logging.debug('Debugging enabled.')
    else:
        logging.basicConfig(level=logging.INFO, format='%(message)s')

    return args

def scan(directory, extension):
    """Scan directory and return a list of files with the desired extension"""
    files_list = []

    logging.info('Scanning source...')
    for (dir_path, dir_names, file_names) in os.walk(directory):
        if file_names:
            logging.debug('Scanning directory: {}'.format(dir_path))

        for file_name in file_names:
            if file_name.lower().endswith(extension):
                logging.debug('  Match, adding to list: {}'.format(file_name))
                files_list.append((dir_path, file_name))

    return files_list

def copy(files_list, destination, insert_rid=False, max_files=None, max_size=None):
    """Copy files from the list to the destination"""
    from random import SystemRandom
    from shutil import copy

    random = SystemRandom()
    total_files = 0
    total_size = 0

    logging.info('Copying files...')
    while True:
        source, file_name = random.choice(files_list)
        src_path = os.path.join(source, file_name)
        file_size = os.stat(src_path).st_size / 1024.0 / 1024.0

        if insert_rid:
            dst_path = os.path.join(destination,
                                    '{:03}_{}'.format(total_files, file_name))
        else:
            dst_path = os.path.join(destination, file_name)

        logging.debug('  {} ({:.2f} MB)'
                      .format(file_name, file_size))

        if max_size:
            if total_size + file_size > max_size:
                logging.debug('    Maximum size reached ({} MB).'
                              .format(max_size))
                break

        if max_files:
            if total_files == max_files:
                logging.debug('    Number of files reached ({} files).'
                              .format(max_files))
                break

        try:
            copy(src_path, dst_path)

        except IOError as e:
            # No space left
            logging.debug('    {}'.format(e.strerror))
            logging.debug('  Removing file: {}'.format(dst_path))
            os.unlink(dst_path)
            break

        except KeyboardInterrupt:
            # User interruption
            logging.debug('    Keyboard interruption.')
            logging.debug('  Removing file: {}'.format(dst_path))
            os.unlink(dst_path)
            break

        else:
            # Increment the number of copied files
            total_files += 1

            # Increment the total data size copied
            total_size += file_size

    logging.info('Copied {} files ({:.2f} MB)'.format(total_files, total_size))

def run():
    args = parseArgs()
    files_list = scan(args.source, args.extension)

    opts = {}
    if args.random:
        opts['insert_rid'] = True
    if args.number:
        opts['max_files'] = args.number
    if args.size:
        opts['max_size'] = args.size

    copy(files_list, args.destination, **opts)

if __name__ == '__main__':
    try:
        run()
    except (KeyboardInterrupt, SystemExit):
        pass


import os
import sys
import pandas as pd
import pytest
import shutil
from datetime import datetime
sys.path.append(os.path.abspath(os.path.dirname(__file__)+'/../..'))
from src import todos

@pytest.fixture(scope="function")
def tmp_dir(tmpdir_factory):
    my_tmpdir = tmpdir_factory.mktemp("pytestdata")
    todos.PATH_TO_DATA = my_tmpdir
    yield my_tmpdir
    shutil.rmtree(str(my_tmpdir))

@pytest.fixture(scope="function")
def new_row():
    return {
        "created": datetime.now().strftime("%Y-%m-%d %H-%M-%S"),
        "task": "cocinar",
        "summary": "Cocinar algo rico",
        "status": "todo",
        "owner": "Andre",
    }

@pytest.fixture(scope="function")
def df_full(new_row):
    return pd.DataFrame(
        [new_row], columns=["created", "task", "summary", "status", "owner"]
    )

n1 = {
        "created": datetime.now().strftime("%Y-%m-%d %H-%M-%S"),
        "task": "cocinar",
        "summary": "Cocinar algo rico",
        "status": "todo",
        "owner": "Andre",
    }

n2 = {
        "created": datetime.now().strftime("%Y-%m-%d %H-%M-%S"),
        "task": "Programar",
        "summary": "Tarea python",
        "status": "todo",
        "owner": "Rodrigo",
    }

def obtener_datos_test_integration():
    return [(False, n1,
            'my_todo_list_1', pd.DataFrame(columns=["created", "task",
"summary", "status", "owner"])),
            (False, n2,
            'my_todo_list_2', pd.DataFrame(columns=["create", "task",
"summary", "status", "owner"]))]

@pytest.mark.parametrize('Bool, nr, tl, dataframe',
                         obtener_datos_test_integration())
def test_add_to_list(Bool, nr, tl, dataframe, df_full, tmp_dir):

    todos.create_list(tl)
    df0 = todos.load_list(tl)
    d0 = (pd.concat([df0, dataframe], axis=1).columns.unique().shape[0] == 5)

    todos.add_to_list(tl, nr)
    df1 = todos.load_list(tl)
    d1 = (df_full.append(df1).drop_duplicates().shape[0] > 1)

    assert (d0 and d1) == Bool


from tkinter import *
from tkhtmlview import HTMLLabel
import sys

def open_about(parent):
    window = Toplevel(parent)
    window.title("About")

# Set Geometry
    window.geometry("400x400")

# Add label
    my_label = HTMLLabel(window, html="""

ABOUT

            This project has been realized by a group of four student : Fissore Davide, Schmied Margaux, Venturelli Antoine, three students of the University of Côte d'Azur of Nice
            and Federica Galbiati, an Erasmus student coming from the University Bicocca of Milan.

            """)
    my_label.pack(pady=20, padx=20)
    window.mainloop()


from bs4 import BeautifulSoup as bs
from urllib.request import urlopen as uReq
import requests
import logging
from flask import Flask, render_template, request

logging.basicConfig(filename="scrapper.log" , level=logging.INFO)

app = Flask(__name__)
@app.route("/review" , methods = ['POST' , 'GET'])
def index():
    if request.method == 'POST':
        try:
            searchString = request.form['content'].replace(" ","")
            flipkart_url = "https://www.flipkart.com/search?q=" + searchString
            uClient = uReq(flipkart_url)
            flipkartPage = uClient.read()
            uClient.close()
            filename = searchString + ".csv"
            fw = open(filename, "w")
            headers = "Product, Customer Name, Rating, Heading, Comment \n"
            fw.write(headers)

            flipkart_html = bs(flipkartPage, "html.parser")
            x = flipkart_html.findAll("div", {"class": "_1AtVbE col-12-12"})
            del x[0:3]
            cnt = 0
            for i in x:
                productLink = "https://www.flipkart.com" + x.div.div.div.a['href']
                prodRes = requests.get(productLink)
                prod_html = bs(prodRes.text, "html.parser")
                commentboxes = prod_html.find_all('div', {'class': "_16PBlm"})
                reviews = []
                for commentbox in commentboxes:
                    try:
                        name = commentbox.div.div.find_all('p', {'class': '_2sc7ZR _2V5EHH'})[0].text
                    except:
                        logging.info("name")

                    try:
                        rating = commentbox.div.div.div.div.text
                    except:
                        rating = 'No Rating'
                        logging.info("rating")

                    try:
                        commentHead = commentbox.div.div.div.p.text
                    except:
                        commentHead = 'No Comment Heading'
                        logging.info(commentHead)

                    try:
                        comtag = commentbox.div.div.find_all('div', {'class': ''})
                        custComment = comtag[0].div.text
                    except Exception as e:
                        custComment = "no Comment content"
                        logging.info(custComment)

                    cnt = cnt + 1
                    mydict = {"S.no": cnt, "Product": "searchString", "Name": name, "Rating": rating, "CommentHead": commentHead, "Comment": custComment}
                    reviews.append(mydict)

            for data in reviews:
                fw.writerow(data)
            return render_template('result.html', reviews=reviews[0:(len(reviews)-1)])

        except Exception as e:
            logging.info(e)
            return 'something is wrong'

    else:
        return render_template('index.html')


from django.shortcuts import render
from django.conf import settings
from django.core.mail import send_mail
# Create your views here.

def index(request):
    return render(request,'email/index.html',context=None)

def send_email(request):
    subject='Django mail'
    message='trying to send mail'
    from_email=settings.EMAIL_HOST_USER
    to_list=['subham.mishra14@gmail.com']

    send_mail(subject,message,from_email,to_list,fail_silently=False)

    return render(request,'email/send_email.html',context=None)


import os
import argparse
from model import ConvBlock, Wav2Letter
import torch
import time

import numpy as np
import torch
import torchaudio
import torch.nn as nn
from torch.nn.utils.rnn import *
from torch.utils.data import DataLoader, Dataset
from utils.transcript_utils import *

import os
import sys
import numpy as np
import pandas as pd
import torch
import timeit
import torch.nn as nn
import onnxruntime as rt
from torch.autograd import Variable
from ctcdecode import CTCBeamDecoder

from data.dataloader import *
from hyperparameters import get_hyperparameters
from utils.transcript_utils import *
from utils.train_utils import *
from utils.metric_utils import *
from model import Wav2Letter

parser = argparse.ArgumentParser(description='Script to evaluate a pytorch model on HW4 data')
parser.add_argument('--model', type=str, help='path to the model file')
parser.add_argument('--beamwidth', type=int, default=20, help='beamwidth for the CTCBeamDecoder')
parser.add_argument('--outvocab', type=int, default=35, help='Out vocab for the model')
parser.add_argument('--batchsize', type=int, default=1, help='Batch size to evaluate the model')
parser.add_argument('--datadir', type=str, default='data',
                    help='data directory where train.npy, dev.npy, train_transcripts.npy, and dev_transcripts.npy are present')
parser.add_argument('--device', type=str, default='cuda',
                    help='cuda or cpu are valid options')
parser.add_argument('--quantized', action='store_true', default=False)

# Evaluate the model
@torch.no_grad()
def evaluate_model(val_loader, model, criterion, batchsize=32, beamwidth=20, device=None, quantized=False):
    predictions = []
    actuals = []
    val_loss = 0

    # distances = []
    input_name = ""
    # Set model in validation mode
    if not quantized:
        model.eval()
    else:
        input_name = model.get_inputs()[0].name

    stime = time.time()

    for i, (inputs, targets, input_lengths, target_lengths, input_len_ratio) in enumerate(val_loader):
        inputs = inputs.transpose(0, 1).transpose(1, 2).reshape((batchsize, 40, -1)).to(device)
        input_lengths = input_lengths.to(device)
        targets = targets.to(device)
        target_lengths = target_lengths.to(device)

        # evaluate the model on the validation set
        if not quantized:
            out = model(inputs.float())
        else:
            out = torch.tensor(model.run(None, {input_name: inputs.numpy().astype(np.float32)})[0])

        out = out.permute(2, 1, 0)

        seq_length = out.size(0)
        out_lengths = Variable(input_len_ratio.mul_(int(seq_length)).int(), requires_grad=False)

        # Calculate validation loss
        loss = criterion(out, targets, out_lengths, target_lengths)

        actual = targets.cpu().numpy()
        actual_lengths = target_lengths.cpu().numpy()

        decoder = CTCBeamDecoder(LETTER_LIST + ["&"], beam_width=beamwidth, log_probs_input=True, blank_id=len(LETTER_LIST))
        out, _, _, out_lengths = decoder.decode(out.transpose(0, 1), out_lengths)

        # reshape for stacking
        actual = unpad_beam1(actual, actual_lengths)
        out = unpad(torch.squeeze(out, 1).cpu().numpy(), torch.squeeze(out_lengths, 1).cpu().numpy())

        # store
        predictions.append(out)
        actuals.append(actual)

        if i%50==0:
            print(f"\tBatch: {i}/{len(val_loader)}\t Loss: {loss.item():3.3f}\ttime-elapsed: {time.time()-stime:3.3f} Secs")

        del out
        del out_lengths
        del targets
        del target_lengths
        del inputs
        del input_lengths
        del input_len_ratio

        torch.cuda.empty_cache()
        val_loss += loss.item()

    p = generate_all_outputs(predictions)
    a = generate_all_outputs(actuals)

    # Calculate Validation Levenshtein distance
    if len(p) != len(a):
        print("ERROR")

    dist = calc_levenshtein_dist(a, p)
    val_loss /= len(val_loader)
    print(f"Evaluation done in {time.time()-stime: 3.3f} Secs")
    print(f"\rAverage Loss: {val_loss:3.3f} and Average Edit Distance: {dist:3.3f}")
    return dist, val_loss

if __name__=="__main__":
    LETTER_LIST = ['<', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
                   'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '-', "'", '.', '_', '+', ' ', '>']

    letter2index, index2letter = create_dictionaries(LETTER_LIST)
    num_workers = get_num_workers()
    hparams = get_hyperparameters()
    hparams["num_workers"] = num_workers

    args = parser.parse_args()
    print(args)
    print(f"Loading model: {args.model}")

    DATA_PATH = args.datadir
    DEVICE = torch.device(args.device)

    model = Wav2Letter(args.outvocab)

    quantized = args.quantized
    if quantized and args.device=='cuda':
      print("Please note quantized models are not supported on GPU yet, so changing the backend to CPU")
      DEVICE = torch.device('cpu')

    if not quantized:
        mdl = torch.load(args.model, map_location=DEVICE)
        model.load_state_dict(mdl.state_dict())
        model.to(DEVICE)
    else:
        model = rt.InferenceSession(args.model)

    # Filepaths
    dev_filename = os.path.join(DATA_PATH, "dev.npy")
    dev_transcripts_filename = os.path.join(DATA_PATH, "dev_transcripts.npy")

    # criterion
    criterion = nn.CTCLoss().to(DEVICE)

    # # Validation dataloader
    val_data = RnnDataset(dev_filename, dev_transcripts_filename, letter2index, is_train=False)
    val_args = dict(shuffle=False, batch_size=args.batchsize, num_workers=hparams["num_workers"], drop_last=True,
                    collate_fn=collate_train_val)
    val_loader = DataLoader(val_data, **val_args)
    evaluate_model(val_loader, model, criterion, args.batchsize, args.beamwidth, DEVICE, quantized)


import requests
import json_extract
from bs4 import BeautifulSoup

# Create session
s = requests.session()

# Extract data from JSON files
site = json_extract.extract('site.json')[0]
urls = site.urls
widgets = site.widgets
ext = site.app_window_ext
login_data = json_extract.extract('login_data.json')[0]
keywords = json_extract.extract('keywords.json')[0]
resume_config = json_extract.extract('resume-config.json')[0]

# Log-in to website
s.post(urls.get('sign-in'), login_data)

# Scrape data from home page
# home_data = s.get(site.get('home'))

# Filter jobs by keywords
job_list_data = s.post(urls.get('jobs_list'), keywords)
job_list_soup = BeautifulSoup(job_list_data.text, 'html.parser')

# Fetch the titles of all jobs on the page
jobs_list = job_list_soup.findAll('div', {'class': 'list-item-title'})

for job in jobs_list:
    # Get job posting url and html
    job_link = job.find('a')
    job_url = urls.get('default') + job_link['href'] + ext
    job_data = s.get(job_url)
    job_soup = BeautifulSoup(job_data.text, 'html.parser')

    # Set job type
    mode = 'default_options'

    # Selecting documents
    resume_option = job_soup.find('div', {'id': widgets.resume})
    resume_option.get('option')['selected'] = 'selected>' + resume_config.get(mode).get('resume_name')

    cover_option = job_soup.find('div', {'id': widgets.cover_letter})
    resume_option.get('option')['selected'] = 'selected>' + resume_config.get(mode).get('cover_letter')

    transcript_option = job_soup.find('div', {'id': widgets.transcript})
    transcript_option.get('option')['selected'] = 'selected>' + resume_config.get(mode).get('transcript')

# Close session
s.close()


import torch
import torch.nn as nn
import os

class Model1(torch.nn.Module):
    def __init__(self):
        super().__init__()

        self.conv = nn.Conv2d(1, 1, 3, stride=1, padding=1,bias=True)
        self.conv.weight.data.fill_(1)
        self.conv.bias.data.fill_(0)

    def forward(self, x):
        x = self.conv(x)
        x = x.view(x.size(0), -1)
        return x

class Model2(torch.nn.Module):
    def __init__(self):
        super().__init__()

        self.conv = nn.Conv2d(1, 1, 3, stride=1, padding=1,bias=True)
        self.conv.weight.data.fill_(1)
        self.conv.bias.data.fill_(0)

    def forward(self, x):
        x = self.conv(x)
        # 用int函数求值
        batch = int(x.size(0))
        x = x.view(batch, -1)
        return x

# 这个包对应opset11的导出代码，如果想修改导出的细节，可以在这里修改代码
# import torch.onnx.symbolic_opset11
print("对应opset文件夹代码在这里：", os.path.dirname(torch.onnx.__file__))

model1 = Model1()
model2 = Model2()
dummy = torch.zeros(1, 1, 3, 3)
torch.onnx.export(model1,  (dummy,), "D:/0/demo1.onnx")
torch.onnx.export(model2,  (dummy,), "D:/0/demo2.onnx")

print("Done.!")


#1/usr/bin/env python

import icecube
from icecube import icetray, common_variables, PulseCore, dataio, dataclasses, phys_services

import numpy, math

from I3CutL7Module import *

from I3Tray import *

geofile = dataio.I3File(sys.argv[1])
gFrame = geofile.pop_frame()
gFrame = geofile.pop_frame()

geometry_ = gFrame["I3Geometry"]

def PCVertCut(frame):
  if(frame.Has("String1Pulses")):
    cogPos = common_variables.hit_statistics.calculate_cog(geometry_,frame["String1Pulses"].apply(frame))
    cut_diff = cogPos - dataclasses.I3Position(29.3,52.6,cogPos.z)
    cut_diff_mag = cut_diff.magnitude
    if(cut_diff_mag<180 and cogPos.z>-500 and cogPos.z<-180):
      return True
    else:
      return False
  else:
    return False

def myCOG(s3Time):
  string3X = 0
  string3Y = 0
  string3Z = 0
  string3T = 0
  totCharge = 0
  for i in xrange(len(s3Time)):
    string3X += s3Time[i][1]*s3Time[i][2][0]
    string3Y += s3Time[i][1]*s3Time[i][2][1]
    string3Z += s3Time[i][1]*s3Time[i][2][2]
    string3T += s3Time[i][1]*s3Time[i][0]
    totCharge += s3Time[i][1]
  return dataclasses.I3Position(string3X/totCharge,string3Y/totCharge,string3Z/totCharge),string3T/totCharge

def mightBeBackground(distance, timeDiff):
    if distance < 750:
        if timeDiff > -5*distance + 500:
            if timeDiff < distance/0.3 + 150:
                if timeDiff > distance/0.3 - 1850:
                    return True
    return False

def MyCausVetCut(frame):
  if(frame.Has("String1Pulses")):
    s3Time = [(p.time,p.charge,geometry_.omgeo[i].position,i.string) for i,j in frame["String1Pulses"].apply(frame) for p in j]
    s3Time.sort()
    mcogPos,mcogT = myCOG(s3Time)
#    trigTime = 0
 #   for trigger in frame["I3TriggerHierarchy"]:
 #     trigKey = trigger.key.config_id
 #     if trigKey==1011:
 #       trigTime = trigger.time
 #       mcogT = trigger.time
 #     for om, launchSeries in frame["InIceRawData"]:
 #         for launch in launchSeries:
 #             hitTime = launch.time
 #             if hitTime==trigTime:
 #                 refHitTime = hitTime
 #                 mcogPos = geometry_.omgeo[om].position

    nVetoHits=0
    for om, launchSeries in frame["InIceRawData"]:
      for launch in launchSeries:
        hitTime = launch.time
        hitPos = geometry_.omgeo[om].position
        hitDistance = (hitPos-mcogPos).magnitude
        hitTimeDiff = mcogT-hitTime

        if mightBeBackground(hitDistance, hitTimeDiff):
          nVetoHits+=1

    if(nVetoHits<=2):
      return True
    else:
      return False
  return False

tray = I3Tray()

tray.Add("I3Reader",FilenameList = [sys.argv[1]])

tray.Add(PCVertCut)

#tray.AddModule(I3CutL7Module, 'cutL7',
#               maxNVetoHits = 2
#               )

tray.Add(MyCausVetCut)

tray.Add("I3Writer",
  DropOrphanStreams = [icetray.I3Frame.DAQ],
  filename='/data/user/mamday/icesim/scripts/output/CutNuMu/'+sys.argv[2])

tray.Execute()


from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import time
import requests

def geturl(url):
    res = requests.head(url)
    url = res.headers.get('location')
    return url

a = 1
with open('id.txt', 'r') as x:
	for line in x:
		id = line.replace('\n', '')
		url = 'http://clients2.google.com/service/update2/crx?response=redirect&prodversion=49.0&acceptformat=crx3&x='+id+'%26installsource%3Dondemand%26uc'
		new = geturl(url)
		print(new)
		r= requests.get(new)
		name = str(a)+'.crx'
		with open(name, "wb") as code:
			code.write(r.content)
		a=a+1


from os import F_OK, access
import sys

# relax module imports.
from data_store import Relax_data_store; ds = Relax_data_store()
import dep_check
from info import Info_box
from lib.errors import RelaxError, RelaxFileError, RelaxFileOverwriteError, RelaxNoModuleInstallError, RelaxNoPipeError
from lib.io import get_file_path, mkdir_nofail
from pipe_control import exp_info
from pipe_control.mol_res_spin import create_spin, generate_spin_id, metadata_cleanup, return_spin, set_spin_element, set_spin_isotope
from pipe_control.pipes import cdp_name
from pipe_control.result_files import add_result_file
from specific_analyses.api import return_api
from status import Status; status = Status()
from version import version_full

def display(version='3.1'):
    """Display the results in the BMRB NMR-STAR format.

    @keyword version:   The NMR-STAR version to create.  This can be either '2.1', '3.0', or '3.1'.
    @type version:      str
    """

    # Call the write() function with stdout.
    write(file=sys.stdout, version=version)

def generate_sequence(N=0, spin_ids=None, spin_nums=None, spin_names=None, res_nums=None, res_names=None, mol_names=None, isotopes=None, elements=None):
    """Generate the sequence data from the BRMB information.

    @keyword N:             The number of spins.
    @type N:                int
    @keyword spin_ids:      The list of spin IDs.
    @type spin_ids:         list of str
    @keyword spin_nums:     The list of spin numbers.
    @type spin_nums:        list of int or None
    @keyword spin_names:    The list of spin names.
    @type spin_names:       list of str or None
    @keyword res_nums:      The list of residue numbers.
    @type res_nums:         list of int or None
    @keyword res_names:     The list of residue names.
    @type res_names:        list of str or None
    @keyword mol_names:     The list of molecule names.
    @type mol_names:        list of str or None
    @keyword isotopes:      The optional list of isotope types.
    @type isotopes:         list of str or None
    @keyword elements:      The optional list of element types.
    @type elements:         list of str or None
    """

    # The blank data.
    if not spin_nums:
        spin_nums = [None] * N
    if not spin_names:
        spin_names = [None] * N
    if not res_nums:
        res_nums = [None] * N
    if not res_names:
        res_names = [None] * N
    if not mol_names:
        mol_names = [None] * N

    # Generate the spin IDs.
    spin_ids = []
    for i in range(N):
        spin_ids.append(generate_spin_id(mol_name=mol_names[i], res_num=res_nums[i], spin_name=spin_names[i]))

    # Loop over the spin data.
    for i in range(N):
        # The spin already exists.
        spin = return_spin(spin_id=spin_ids[i])
        if spin:
            continue

        # Create the spin.
        spin = create_spin(spin_num=spin_nums[i], spin_name=spin_names[i], res_num=res_nums[i], res_name=res_names[i], mol_name=mol_names[i])[0]

        # Set the spin isotope and element.
        spin_id = spin._spin_ids[0]
        if elements:
            set_spin_element(spin_id=spin_id, element=elements[i], force=True)
        if isotopes and elements:
            isotope = "%s%s" % (isotopes[i], elements[i])
            set_spin_isotope(spin_id=spin_id, isotope=isotope, force=True)

    # Clean up the spin metadata.
    metadata_cleanup()

def list_sample_conditions(star):
    """Get a listing of all the sample conditions.

    @param star:    The NMR-STAR dictionary object.
    @type star:     NMR_STAR instance
    @return:        The list of sample condition names.
    @rtype:         list of str
    """

    # Init.
    sample_conds = []

    # Get the sample conditions.
    for data in star.sample_conditions.loop():
        # Store the framecode.
        sample_conds.append(data['sf_framecode'])

    # Return the names.
    return sample_conds

def molecule_names(data, N=0):
    """Generate the molecule names list.

    @param data:    An element of data from bmrblib.
    @type data:     dict
    @return:        The list of molecule names.
    @rtype:         list of str
    """

    # The molecule index and name.
    mol_index = []
    for i in range(N):
        if 'entity_ids' in data and data['entity_ids'] != None and data['entity_ids'][i] != None:
            mol_index.append(int(data['entity_ids'][i]) -1 )
        else:
            mol_index = [0]*N
    mol_names = []
    for i in range(N):
        mol_names.append(cdp.mol[mol_index[i]].name)

    # Return the names.
    return mol_names

def num_spins(data):
    """Determine the number of spins in the given data.

    @param data:    An element of data from bmrblib.
    @type data:     dict
    @return:        The number of spins.
    @rtype:         int
    """

    # The number of spins.
    N = 0

    # List of keys containing sequence information.
    keys = ['data_ids', 'entity_ids', 'res_names', 'res_nums', 's2']

    # Loop over the keys until a list is found.
    for key in keys:
        if key in data and data[key]:
            N = len(data[key])
            break

    # Return the number.
    return N

def read(file=None, dir=None, version=None, sample_conditions=None):
    """Read the contents of a BMRB NMR-STAR formatted file.

    @keyword file:              The name of the BMRB STAR formatted file.
    @type file:                 str
    @keyword dir:               The directory where the file is located.
    @type dir:                  None or str
    @keyword version:           The BMRB version to force the reading.
    @type version:              None or str
    @keyword sample_conditions: The sample condition label to read.  Only one sample condition can be read per data pipe.
    @type sample_conditions:    None or str
    """

    # Test if bmrblib is installed.
    if not dep_check.bmrblib_module:
        raise RelaxNoModuleInstallError('BMRB library', 'bmrblib')

    # Test if the current data pipe exists.
    pipe_name = cdp_name()
    if not pipe_name:
        raise RelaxNoPipeError

    # Make sure that the data pipe is empty.
    if not ds[pipe_name].is_empty():
        raise RelaxError("The current data pipe is not empty.")

    # Get the full file path.
    file_path = get_file_path(file_name=file, dir=dir)

    # Fail if the file does not exist.
    if not access(file_path, F_OK):
        raise RelaxFileError(file_path)

    # Read the results.
    api = return_api(pipe_name=pipe_name)
    api.bmrb_read(file_path, version=version, sample_conditions=sample_conditions)

def write(file=None, dir=None, version='3.1', force=False):
    """Create a BMRB NMR-STAR formatted file.

    @keyword file:      The name of the file to create or a file object.
    @type file:         str or file object
    @keyword dir:       The optional directory to place the file into.  If set to 'pipe_name', then it will be placed in a directory with the same name as the current data pipe.
    @type dir:          str or None
    @keyword version:   The NMR-STAR version to create.  This can be either '2.1', '3.0', or '3.1'.
    @type version:      str
    @keyword force:     A flag which if True will allow a currently existing file to be overwritten.
    @type force:        bool
    """

    # Test if bmrblib is installed.
    if not dep_check.bmrblib_module:
        raise RelaxNoModuleInstallError('BMRB library', 'bmrblib')

    # Test if the current data pipe exists.
    pipe_name = cdp_name()
    if not pipe_name:
        raise RelaxNoPipeError

    # Check the file name.
    if file == None:
        raise RelaxError("The file name must be specified.")

    # A file object.
    if isinstance(file, str):
        # The special data pipe name directory.
        if dir == 'pipe_name':
            dir = pipe_name

        # Get the full file path.
        file = get_file_path(file, dir)

        # Fail if the file already exists and the force flag is False.
        if access(file, F_OK) and not force:
            raise RelaxFileOverwriteError(file, 'force flag')

        # Print out.
        print("Opening the file '%s' for writing." % file)

        # Create the directories.
        mkdir_nofail(dir, verbosity=0)

    # Get the info box.
    info = Info_box()

    # Add the relax citations.
    for id, key in zip(['relax_ref1', 'relax_ref2'], ['dAuvergneGooley08a', 'dAuvergneGooley08b']):
        # Alias the bib entry.
        bib = info.bib[key]

        # Add.
        exp_info.citation(cite_id=id, authors=bib.author2, doi=bib.doi, pubmed_id=bib.pubmed_id, full_citation=bib.cite_short(doi=False, url=False), title=bib.title, status=bib.status, type=bib.type, journal_abbrev=bib.journal, journal_full=bib.journal_full, volume=bib.volume, issue=bib.number, page_first=bib.page_first, page_last=bib.page_last, year=bib.year)

    # Add the relax software package.
    exp_info.software(name=exp_info.SOFTWARE['relax'].name, version=version_full(), vendor_name=exp_info.SOFTWARE['relax'].authors, url=exp_info.SOFTWARE['relax'].url, cite_ids=['relax_ref1', 'relax_ref2'], tasks=exp_info.SOFTWARE['relax'].tasks)

    # Execute the specific BMRB writing code.
    api = return_api(pipe_name=pipe_name)
    api.bmrb_write(file, version=version)

    # Add the file to the results file list.
    if isinstance(file, str):
        add_result_file(type='text', label='BMRB', file=file)


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

@author: Nashrah
"""

import pandas as pd

monthly_death=pd.read_csv('monthly_deaths.csv')
monthly_death['Year']=[d.split('-')[0] for d in monthly_death['date']]
#print(type(monthly_death['deaths']))

sum_deaths1841=0
sum_births1841=0
year1841=monthly_death.loc[monthly_death["Year"]=="1841"]
for i in year1841["deaths"]:
    global sum_deaths1841
    sum_deaths1841+=i
for i in year1841["births"]:
    global sum_births1841
    sum_births1841+=i

sum_deaths1842=0
sum_births1842=0
year1842=monthly_death.loc[monthly_death["Year"]=="1842"]
for i in year1842["deaths"]:
    global sum_deaths1842
    sum_deaths1842+=i
for i in year1842["births"]:
    global sum_births1842
    sum_births1842+=i

sum_deaths1843=0
sum_births1843=0
year1843=monthly_death.loc[monthly_death["Year"]=="1843"]
for i in year1843["deaths"]:
    global sum_deaths1843
    sum_deaths1843+=i
for i in year1843["births"]:
    global sum_births1843
    sum_births1843+=i

sum_deaths1844=0
sum_births1844=0
year1844=monthly_death.loc[monthly_death["Year"]=="1844"]
for i in year1844["deaths"]:
    global sum_deaths1844
    sum_deaths1844+=i
for i in year1844["births"]:
    global sum_births1844
    sum_births1844+=i

sum_deaths1845=0
sum_births1845=0
year1845=monthly_death.loc[monthly_death["Year"]=="1845"]
for i in year1845["deaths"]:
    global sum_deaths1845
    sum_deaths1845+=i
for i in year1845["births"]:
    global sum_births1845
    sum_births1845+=i

sum_deaths1846=0
sum_births1846=0
year1846=monthly_death.loc[monthly_death["Year"]=="1846"]
for i in year1846["deaths"]:
    global sum_deaths1846
    sum_deaths1846+=i
for i in year1846["births"]:
    global sum_births1846
    sum_births1846+=i

sum_deaths1847=0
sum_births1847=0
year1847=monthly_death.loc[monthly_death["Year"]=="1847"]
for i in year1847["deaths"]:
    global sum_deaths1847
    sum_deaths1847+=i
for i in year1847["births"]:
    global sum_births1847
    sum_births1847+=i

sum_deaths1848=0
sum_births1848=0
year1848=monthly_death.loc[monthly_death["Year"]=="1848"]
for i in year1848["deaths"]:
    global sum_deaths1848
    sum_deaths1848+=i
for i in year1848["births"]:
    global sum_births1848
    sum_births1848+=i

sum_deaths1849=0
sum_births1849=0
year1849=monthly_death.loc[monthly_death["Year"]=="1849"]
for i in year1849["deaths"]:
    global sum_deaths1849
    sum_deaths1849+=i
for i in year1849["births"]:
    global sum_births1849
    sum_births1849+=i

col_names=["Year","Births","Deaths"]

dataframe=[(1841,sum_births1841,sum_deaths1841),
           (1842,sum_births1842,sum_deaths1842),
           (1843,sum_births1843,sum_deaths1843),
           (1844,sum_births1844,sum_deaths1844),
           (1845,sum_births1845,sum_deaths1845),
           (1846,sum_births1846,sum_deaths1846),
           (1847,sum_births1847,sum_deaths1847),
           (1848,sum_births1848,sum_deaths1848),
           (1849,sum_births1849,sum_deaths1849)]

new_df=pd.DataFrame(dataframe,columns=col_names)

new_df["Proportiona_deaths"]=new_df["Deaths"]/new_df["Births"]

import matplotlib.pyplot as plt
plt.plot(new_df["Year"],new_df["Proportiona_deaths"])
plt.scatter(new_df["Year"],new_df["Proportiona_deaths"])
plt.ylabel("proportions_death")
plt.xlabel("No of years")
plt.title("Decrease in proportions_death")


import pygame, random, sys, os
from pygame.locals import*
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
#set main directory and load sounds from 'sounds folder'
main_dir = os.path.dirname(os.path.abspath("__file__"))
bump1 = pygame.mixer.Sound(os.path.join(main_dir, "bump.wav"))
hit1 = pygame.mixer.Sound(os.path.join(main_dir, "bwubwub.wav"))
coin1 = pygame.mixer.Sound(os.path.join(main_dir, "beep.wav"))
pygame.mixer.music.load(os.path.join(main_dir, "music.wav"))
#set winsize and basic colours
WINSIZE = [640, 640]
white = (255, 255, 255)
black = (0, 0, 0)
#set paddlewidth since it doesn't change
PADDLEWIDTH = 15
Done = 0
pygame.init()
#load font and images
font = pygame.font.Font('Minecraft.ttf', 25)
titlefont = pygame.font.Font('Minecraft.ttf', 50)
coindwg = pygame.image.load(os.path.join(main_dir, 'coin.png'))
heart = pygame.image.load(os.path.join(main_dir, 'heart.png'))
#set ai offset, see ai move function in paddle class
aiOffset = 0

class paddle:
    def __init__(self, x, y, health, maxhealth, length, speed, bspeed):
        self.x = x
        self.y = y
        self.health = health
        self.length = length
        self.speed = speed
        self.bspeed = bspeed
        self.maxhealth = maxhealth

    def ai_move(self):
        #ignoring the ai offset this would check if the paddle center was at the ball center
        #and move it towards if it was not
        #with offset the hit is set to be between the top and bottom of the paddle
        #the purpose it to return the ball with some y velocity(see how y vel is set in ball collision)
        if self.y + (self.length / 2) < playball.y + (playball.size/2) - aiOffset:
            if self.y < WINSIZE[0] - self.length:
                self.y += self.speed#move towards at paddle speed
        if self.y + (self.length/ 2) > playball.y + (playball.size/2) - aiOffset:
            if self.y > 0:
                self.y -= self.speed

    def input(self):
        #same idea as ai move but with input from player
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit()
        keystate = pygame.key.get_pressed()
        if keystate[K_UP]:
            if self.y > 0:
                self.y -= self.speed
        if keystate[K_DOWN]:
            if self.y < WINSIZE[0] - self.length:
                self.y += self.speed

    def render(self):
        pygame.draw.rect(screen, white, (self.x, self.y, PADDLEWIDTH, self.length), 0)

class ball:
    def __init__(self, x, y, dirX, dirY, size):
        self.x = x
        self.y = y
        self.dirX = dirX
        self.dirY = dirY
        self.size = size
    def move(self):
        #move ball along its current path set by dirX and dirY
        self.x += self.dirX
        self.y += self.dirY
    def col_check(self):
        global aiOffset
        global score
        #ball hits top screen will set y velocity to be opposite
        if self.y < 0:
            if self.dirY < 0:#this checks to make sure that ball hasn't been bounced a bit out of bounds and is in the process of bouncing back in
                self.dirY = self.dirY * -1
                play_sound("bounce")
        #same thing but for bottom of screen
        if self.y + self.size > WINSIZE[1]:
            if self.dirY > 0:
                self.dirY *= -1
                play_sound("bounce")
        if self.x + self.size > WINSIZE[0]:
            #if ball hits player2(ai)side remove 1 of their health units, play hit sound and restart
            player2.health -= 1
            play_sound("hit")
            score += 5
            if player2.health < 1:
                win()
            restart()
        if self.x < 0:
            #same thing but checks for no health left and runs the you died function
            player1.health -= 1
            play_sound("hit")
            if player1.health < 1:
                you_died()
            restart()
        if self.dirX < 0:
            #checks for collision with paddle and bounces the ball back but..
            #only if the ball is headed towards you
            #done to avoid bouncing the ball again when its already headed away
            if collision(self, player1):
                self.dirX = 3
                self.dirY = (((playball.y + self.size/2) - (player1.y + player1.length/2))/(player1.length/2))*5
                play_sound("bounce")
        if self.dirX > 0:
            #same dealio but also set aiOffset after a bounce and create a new coin
            if collision(self, player2):
                self.dirX = -3
                self.dirY = (((playball.y + self.size/2) - (player2.y + player2.length/2))/(player2.length/2))*5
                coin.new(player2.x, (player2.y + player2.length/2))
                aiOffset = random.randrange(0, 48, 1)-24
                play_sound("bounce")
    def render(self):
        pygame.draw.rect(screen, white, (self.x, self.y, self.size, self.size), 0)

class coin:
    def __init__(self, x, y, size, speed):
        self.x = x
        self.y = y
        self.size = size
        self.speed = speed
    def new(x, y):
        speed = (random.random()*4) + 1
        newcoin = coin(x, y, 20, speed)
        coinlist.append(newcoin)
    def move(self):
        self.x -= self.speed
    def col_check(self):
        #calls collision, if you get the coin with the paddle score increases by 10
        global score
        if collision(self, player1):
            play_sound("coin")
            score += 10
            return(1)
    def draw(self):
        screen.blit(coindwg, (self.x, self.y))

def collision(ball, player):
    #basic collision function takes 2 objects.. yeah
    if((ball.x + ball.size >= player.x and ball.x <= player.x + PADDLEWIDTH) and (ball.y + ball.size > player.y and ball.y <= player.y + player.length)):
        return(1) #collision
    else:
        return(0)

def main():
    global screen
    screen = pygame.display.set_mode(WINSIZE)
    pygame.display.set_caption('pong legacy')

    menu_title()
    initialize_game()
    while not Done:
        run_game()
def menu_title():
    pygame.mixer.music.play(-1)
    ren = font.render("Paddle Mans Evloutionary Grinding Adventure", True, white)
    screen.blit(ren, (30, 100))
    ren = font.render("PRESS SPACE", True, white)
    screen.blit(ren, (225, 500))
    pygame.display.update()
    key_wait()
    ren = font.render("AKA", True, white)
    screen.blit(ren, (290, 165))
    pygame.display.update()
    key_wait()
    ren = titlefont.render("Pong Legacy", True, white)
    screen.blit(ren, (150, 220))
    pygame.display.update()
    key_wait()
    pygame.mixer.music.fadeout(2500)

def run_game():
    handle_coins()
    handle_paddles()
    playball.move()
    playball.col_check()
    render_all()
    pygame.display.update()
    screen.fill(black)
    clock.tick(60)

def initialize_game():
    global clock
    clock = pygame.time.Clock()
    global player1
    global player2
    player1 = paddle(10, 320, 1, 1, 20, 2, 1)
    player2 = paddle(615, 320, 12, 12, 50, 5, 1)
    global playball
    playball = ball(320, 320, 1, 1, 10)
    global coinlist
    coinlist = []
    global score
    score = 0

    global upgradelist
    upgradelist = []
    speedup = upgrade(10, 10, speed_up, "Paddle Speed increase", 0)
    sizeup = upgrade(10, 10, size_up, "Paddle length increase", 0)
    healthup = upgrade(30, 30, health_up, "Max life plus 1", 0)
    upgradelist.append(sizeup)
    upgradelist.append(speedup)
    upgradelist.append(healthup)
    restart()

def restart():
    for object in coinlist:
        coinlist.remove(object)
    render_all()
    pygame.time.wait(1000)
    ren = font.render("3", True, white)
    screen.blit(ren, (320, 280))
    pygame.display.update()
    play_sound("bounce")
    pygame.time.wait(1000)
    pygame.draw.rect(screen, black, (320, 280, 30, 30), 0)
    ren = font.render("2", True, white)
    screen.blit(ren, (320, 280))
    pygame.display.update()
    play_sound("bounce")
    pygame.time.wait(1000)
    pygame.draw.rect(screen, black, (320, 280, 30, 30), 0)
    ren = font.render("1", True, white)
    screen.blit(ren, (320, 280))
    pygame.display.update()
    play_sound("bounce")
    pygame.time.wait(1000)
    play_sound("coin")
    pygame.draw.rect(screen, black, (320, 280, 30, 30), 0)

    player1.y = 320
    player2.y = 320
    start = random.randrange(1, 4, 1)
    if start == 1 or start == 2:
        playball.dirX = 3
    if start == 3:
        playball.dirX = -3
    playball.dirY = random.random()*2
    playball.x = 320
    playball.y = 320
def render_all():
    heartX = 0
    heartY = 0
    for heartX in range (player1.health):
        screen.blit(heart, (heartX * 35 + 10, heartY))
    for heartX in range (player2.health):
        HDX = heartX*35 + 35
        if heartX > 7:
            heartY = 40
            HDX -= 9 * 35
        screen.blit(heart, (WINSIZE[0] - HDX, heartY))
    for object in coinlist:
        object.draw()
    player1.render()
    player2.render()
    playball.render()
    text = (str(score))
    ren = font.render(text, True, white)
    screen.blit(ren, (310, 10))

def handle_coins():
    #move and check if a coin has collision or is off the map
    for object in coinlist:
        object.move()
        if object.x < 0 - object.size:
            coinlist.remove(object)
            del object
        elif object.x < 50:
            if object.col_check():
                coinlist.remove(object)
                del object

def play_sound(event):
    #play sound based on what event is given when called
    if event == "bounce":
        bump1.play()
    if event == "hit":
        hit1.play()
    if event == "coin":
        coin1.play()

def you_died():
    #render the you died text and send you to the store
    ren = font.render("You Died", True, white)
    screen.blit(ren, (300, 280))
    pygame.display.update()
    pygame.time.wait(1000)
    store()

class upgrade:
    #class for upgrade, pretty simple
    def __init__(self, cost, costInc, function, name, level):
        self.cost = cost
        self.costInc = costInc
        self.function = function
        self.name = name
        self.level = level

def store():
    pygame.mixer.music.set_volume(.1)
    pygame.mixer.music.play(-1)
    pygame.key.set_repeat(100, 100)
    pos = 0
    instore = 1
    while instore:
        render_store(pos)
        pygame.display.update()
        screen.fill(black)
        pos, instore = store_input(pos, instore)
        if pos > 2:
            pos = 0
        if pos < 0:
            pos = 2
        clock.tick(60)
    pygame.key.set_repeat()

def render_store(pos):
    x = 200
    y = 150
    #draw the upgrade options from the upgrade list and draw a box beside the option you are on
    pygame.draw.rect(screen, white, (x - 30, y + 30 * pos, 20, 20), 0)
    for object in upgradelist:
        text = ("lv" + str(object.level) + " " + object.name + " " + str(object.cost))
        ren = font.render(text, True, white)
        screen.blit(ren, (x, y))
        y += 30
    text = (str(score))
    ren = font.render(text, True, white)
    screen.blit(ren, (310, 10))
    ren = font.render("Press Space to Upgrade", True, white)
    screen.blit(ren, (200, 450))
    ren = font.render("Press Enter to Begin Anew", True, white)
    screen.blit(ren, (200, 510))

def store_input(pos, instore):
    #cycle through upgrade options, pos is your cursor positin in the store
    global score
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_UP:
                pos -= 1
            if event.key == K_DOWN:
                pos += 1
            if event.key == K_SPACE:
                #space to buy and run the upgrade function if you can afford
                if score >= upgradelist[pos].cost:
                    score -= upgradelist[pos].cost
                    upgradelist[pos].cost += upgradelist[pos].costInc
                    upgradelist[pos].level += 1
                    upgradelist[pos].function()
                    play_sound("coin")
                else:
                    play_sound("bounce")
            #enter to go back and play again
            if event.key == K_RETURN:
                player1.health = player1.maxhealth
                player2.health = player2.maxhealth
                player1.y = 300
                player2.y = 300
                instore = 0
                score = 0
                pygame.mixer.music.fadeout(2500)
    return(pos, instore)

def speed_up():
    player1.speed += .5
def size_up():
    player1.length += 5
def health_up():
    player1.maxhealth += 1

def handle_paddles():
    player1.input()
    player2.ai_move()

def win():
    pygame.mixer.music.play(-1)
    ren = titlefont.render("You Defeated", True, white)
    screen.blit(ren, (150, 220))
    pygame.display.update()
    ren = font.render("Press Space to exit", True, white)
    screen.blit(ren, (200, 300))
    pygame.display.update()
    key_wait()
    pygame.quit(); sys.exit()

def key_wait():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                return

main()


from os import path

def play(sequence):
    current, next_3, rest = sequence[0], sequence[1:4], sequence[4:]
    for i in range(1, 9):
        cup = int(current) - i
        cup += 9 if cup < 1 else 0
        cup = rest.find(str(cup))
        if cup != -1:
            return rest[:cup + 1] + next_3 + (rest[cup + 1:] if cup + 1 < len(rest) else '') + current

with open(path.dirname(__file__) + '/input.txt') as f:
    print('Play the game and print the sequence')
    sequence = f.read().strip('\n')
    for i in range(100):
        sequence = play(sequence)
    i = sequence.find('1')
    print((sequence[i + 1:] if i + i < len(sequence) else '') + sequence[:i])


"""Test file to use pytest on Travis CI to test some plugin functions"""
from __future__ import print_function
import pytest

def GetVideoId(q, eventType, order, s_type):
	from src.YouTubeApi import GetKey, YouTubeApi
	youtube = YouTubeApi(
		client_id=GetKey('823351347975-bn15et5mgugmu127cw_OizDn7h39v5siv55vbp51blrtc.w_Oi63zDpps.goog75leusercont87ent.com'),
		client_secret=GetKey('njp3Ep36VCkMQuw15_OizDcePvZ27qEqFE'),
		developer_key=GetKey('Xhi3_LoIzw_OizD15SyDVOJNmQn27JyFy43wWcf39CO9DVximw-51vB9Vg'),
		refresh_token='')

	searchResponse = youtube.search_list_full(
		videoEmbeddable='',
		safeSearch='none',
		eventType=eventType,
		videoType='',
		videoDefinition='',
		order=order,
		part='id,snippet',
		q=q,
		relevanceLanguage='',
		s_type=s_type,
		regionCode='',
		maxResults='3',
		pageToken='')

	if s_type != 'video':
		for result in searchResponse.get('items', []):
			kind = result['id']['kind'].split('#')[1]
			playlistId = result['id'][kind+'Id']
		print('playlistId', playlistId)
		print('kind', kind)
		print('Thumbnail', result['snippet']['thumbnails']['default']['url'])
		print('Title', result['snippet']['title'])

		searchResponse = youtube.playlistItems_list(
			maxResults='3',
			playlistId=playlistId,
			pageToken='')

		for result in searchResponse.get('items', []):
			videos = result['snippet']['resourceId']['videoId']
	else:
		for result in searchResponse.get('items', []):
			videos = result['id']['videoId']

	print('Video Id', videos)

	searchResponse = youtube.videos_list(v_id=videos)
	for result in searchResponse.get('items', []):
		print('Id', result['id'])
		print('Thumbnail', result['snippet']['thumbnails']['default']['url'])
		print('Title', result['snippet']['title'])
		print('Views', result['statistics']['viewCount'])
		print('Duration', result['contentDetails']['duration'])
		print('Description', result['snippet']['description'])
		print('Likes', result['statistics']['likeCount'])
		print('Dislikes', result['statistics']['dislikeCount'])
		print('ThumbnailUrl', result['snippet']['thumbnails']['medium']['url'])
		print('ChannelId', result['snippet']['channelId'])
		print('PublishedAt', result['snippet']['publishedAt'])

	return videos

def GetUrl(videos):
	from src.YouTubeVideoUrl import YouTubeVideoUrl
	ytdl = YouTubeVideoUrl()
	videoUrl = ytdl.extract(videos)
	videoUrl = videoUrl.split('&suburi=', 1)[0]
	print('Video Url', videoUrl)
	return videoUrl

def CheckExample(q, eventType='', order='relevance', s_type='video', descr=''):
	try:
		videos = GetVideoId(q=q, eventType=eventType, order=order, s_type=s_type)
	except:
		print('Error in GetVideoId, try second time')
		from time import sleep
		sleep(10)
		videos = GetVideoId(q=q, eventType=eventType, order=order, s_type=s_type)
	CheckVideoUrl(videos, descr=descr)

def CheckVideoUrl(videos, descr):
	print('Test', descr)
	try:
		videoUrl = GetUrl(videos)
	except:
		print('Error in GetUrl, try second time')
		from time import sleep
		sleep(10)
		videoUrl = GetUrl(videos)
	from urllib2 import urlopen
	from src.__init__ import sslContext
	if sslContext:
		response = urlopen(videoUrl, context=sslContext)
	else:
		response = urlopen(videoUrl)
	info = response.info()
	print('Video Url info:')
	print(info, descr, 'Video Url exist')

def test_searchUrl():
	CheckExample(q='official video', descr='Search')

def test_searchLive():
	CheckExample(q='112', eventType='live', descr='Search Live')

def test_mostViewedFeeds():
	CheckExample(q='', eventType='', order='viewCount', descr='Most Viewed')

def test_playlist():
	CheckExample(q='youtube', eventType='', order='relevance', s_type='playlist', descr='Playlist')

_TESTS = [
		{'Id': 'UxxajLWwzqY', 'Description': 'Generic use_cipher_signature video'},
		{'Id': 'BaW_jenozKc', 'Description': 'Ue the first video ID in the URL'},
		{'Id': 'a9LDPn-MO4I', 'Description': '256k DASH audio (format 141) via DASH manifest'},
		{'Id': 'IB3lcPjvWLA', 'Description': 'DASH manifest with encrypted signature'},
		{'Id': 'nfWlot6h_JM', 'Description': 'JS player signature function name containing $'},
		{'Id': 'T4XJQO3qol8', 'Description': 'Controversy video'},
		{'Id': '__2ABJjxzNo', 'Description': 'YouTube Red ad is not captured for creator'},
		{'Id': 'lqQg6PlCWgI', 'Description': 'Olympics'},
		{'Id': 'FIl7x6_3R5Y', 'Description': 'Extraction from multiple DASH manifests'},
		{'Id': 'lsguqyKfVQg', 'Description': 'Title with JS-like syntax'},
		{'Id': 'M4gD1WSo5mA', 'Description': 'Video licensed under Creative Commons'},
		{'Id': 'eQcmzGIKrzg', 'Description': 'Channel-like uploader_url'},
		{'Id': 'uGpuVWrhIzE', 'Description': 'Rental video preview'},
		{'Id': 'iqKdEhx-dD4', 'Description': 'YouTube Red video with episode data'},
		{'Id': 'MgNrAu2pzNs', 'Description': 'Youtube Music Auto-generated description'},
	]

@pytest.fixture(params=_TESTS)
def video_data(request):
	return request.param

def test_videoUrls(video_data):
	CheckVideoUrl(videos=video_data['Id'], descr=video_data['Description'])


import os
import wave
import nltk
import logging
import contextlib
import environment as env
import speech_recognition as sr

from os import path
from recognizers import sphinx

# Duration, opens a wave file and finds the number of frames per rate
# Input:  a filename with a .wav file
# Output: returns the framerate
def duration(filename):
    # open the wave file
    with contextlib.closing(wave.open(filename, 'r')) as f:
        frames = f.getnframes()         # get frames
        rate = f.getframerate()         # get rate
        return frames / float(rate)     # return framerate

# Speech recognizer, recognizes speech from a wav file and returns the text
# Speech -> Text
# Input:  a file name of a .wav file
# Output: The recognized speec as text
def speech_rec(filename):

    audio_file = path.join(path.dirname(path.realpath(__file__)), filename)
    # instantiate a speech recognizer object
    r = sr.Recognizer()

    # try to open the audio file
    with sr.AudioFile(audio_file) as source:
        audio = r.record(source)

    # return the speech to text
    words = sphinx(r, audio)
    return words

# Word Count, counts the word in a sentence
# Input:  a sentence phrase
# Output: the length of the sentence
def word_count(phrase):
    return len(phrase.split())

# Part of Speech tagger, tags speech depending on the words in the sentence
# Input:  a sentence of words
# Ouptut: a list of tagged words
def pos_tagger(words):
    tag_words = []      # empty list of tagged words

    # append all of the words into the tagged words
    for word in words:
        tag_words.append(nltk.pos_tag(word))

    # return the tagged words
    return tag_words

# Attempt to set up a Python3 logger than will print custom messages
# based on each message's logging level.
# Overrides the default logger
# Input:  the logger message, ex. warning, info, error
# Output: returns the result
class CustomFormatter(logging.Formatter):
    """
    Modify the way messages are displayed.
    """
    def __init__(self):
        super().__init__(fmt="%(asctime)s: %(msg)s", datefmt=None, style='%')

    def format(self, record):

        # Remember the original format
        format_orig = self._fmt

        if record.levelno == logging.DEBUG:
            self._fmt = "DEBUG: %(msg)s"

        # Call the original formatter to do the grunt work
        result = logging.Formatter.format(self, record)

        # Restore the original format
        self._fmt = format_orig

        return result

# Class for a Logger, Handles the logging for our application
class Log():

    # initialization
    def __init__(self):
        # gets the logger from the sound count log
        self.logger = logging.getLogger('sound_count_log')
        # set the level of the degub message
        self.logger.setLevel(logging.DEBUG)

        # ceate a custom formatter
        self.formatter = CustomFormatter()

        # stdout logging
        self.stdout_handler = logging.StreamHandler()
        self.stdout_handler.setFormatter(self.formatter)

        # file handling
        self.file_handler = logging.FileHandler(env.app_vars['LOG_PATH'])
        self.file_handler.setFormatter(self.formatter)

        # add for handling for files and stdout
        self.logger.addHandler(self.stdout_handler)
        self.logger.addHandler(self.file_handler)

    # custom debugger message
    def debug(self, message):
        self.check_size()
        self.logger.debug("DEBUG: {0}".format(message))

    # custom info message
    def info(self, message):
        self.check_size()
        self.logger.info("INFO: {0}".format(message))

    # custom warning message
    def warning(self, message):
        self.check_size()
        self.logger.info("WARNING: {0}".format(message))

    # custom error message
    def error(self, message):
        self.check_size()
        self.logger.info("ERROR: {0}".format(message))

    # custom criticals message
    def critical(self, message):
        self.check_size()
        self.logger.info("CRITICAL: {0}".format(message))

    # checks the see if the size is too big, removes the log file if 512 Mb
    def check_size(self):
        if os.path.getsize(env.app_vars['LOG_PATH']) > env.app_vars['LOG_MAXSIZE']:
            os.remove(env.app_vars['LOG_PATH'])

# instantiate a logger
logger = Log()

# TESTING THE LOGGER
# logger.debug("This message")
# logger.info("That message")
# logger.warning("Bad message")
# logger.error("uh oh message")
# logger.critical("FFUUUUUU!")


"""Parser for virtual-machine sub-command."""
import argparse

from emulation_system.commands import EmulationSystemCommand

from .abstract_parser import AbstractParser
from .parser_utils import get_formatter

class EmulationSystemParser(AbstractParser):
    """Parser for virtual-machine sub-command."""

    @classmethod
    def get_parser(cls, parser: argparse.ArgumentParser) -> None:
        """Build parser for "emulation-system" command."""
        subparser = parser.add_parser(  # type: ignore
            "emulation-system",
            aliases=["em-sys"],
            formatter_class=get_formatter(),
            help="Create docker-compose files",
        )

        subparser.set_defaults(func=EmulationSystemCommand.from_cli_input)

        subparser.add_argument(
            "input_path",
            action="store",
            metavar="<input_path>",
            type=argparse.FileType("r"),
            help='Input path to read file from. Specify "-" to read from stdin.',
        )

        subparser.add_argument(
            "output_path",
            action="store",
            metavar="<output_path>",
            type=argparse.FileType("w"),
            help='Output path write compose file to. Specify "-" to write to stdout.',
        )

        subparser.add_argument(
            "--remote-only", action="store_true", help="Allow only remote source-types"
        )

        subparser.add_argument(
            "--dev", action="store_true", help="Create dev compose file"
        )


import fnmatch
import os
import glob
from pathlib import Path

class Tesztolok:

    def __init__(self, lepath=None, lofilter=None, izfolder=False):
        self.folderz = os.scandir(lepath)
        self.pathz = Path(lepath if lepath is not None else "/")
        self.lofilter = lofilter
        self.izfolder = izfolder

    def fold(self):
        for wasd in self.folderz:
            print(wasd.name)

    def paths(self):
        for asd in self.pathz.iterdir():
            if (os.path.isdir(asd) if self.izfolder else True) and (
            self.lofilter in asd.name if self.lofilter is not None else True):
                print(asd.name)

lopett = "e:/"
filtez = "asd"

leclass = Tesztolok(lopett, filtez, False)
leclass.paths()

for currentpath, folders, files in os.walk(lopett):
    # folders[:] = [d for d in folders if "ash" in d]
    for file in folders:
        # print(os.path.join(currentpath, file))
        if filtez in file:
            print(file)


from gtts import gTTS
import os
import pyglet
from time import *
import sys
f = open(os.devnull, 'w')
sys.stdout = f
def say(text):
    tts = gTTS(text=text, lang='en-uk')
    filename = '/tmp/temp.mp3'
    tts.save(filename)
    start2=time()
    music = pyglet.media.load(filename, streaming=False)
    music.play()
    end2=time()
    sleep(music.duration) #prevent from killing
    os.remove(filename) #remove temperory file
def babies(doing,error,times,said):
    for x in range(0,times):
        saymeup=str(times-x)+"little babies"+doing+error+"Mommy called the daddy and the daddy sed"+said
        if(x!=times-1):
            say(saymeup)
try:
    optional=sys.argv[4]
except IndexError:
    optional= " no more babies"+sys.argv[1]
babies(sys.argv[1],sys.argv[2],int(sys.argv[3]),optional)


from PIL import Image
from io import BytesIO
import requests
import sys
import numpy as np
import tflite_runtime.interpreter as tflite
# import time

img = Image.open(requests.get(sys.argv[1], stream=True).raw)
w, h = img.size
image = Image.new('RGB', (512, 512), "WHITE")  # RGM 스케일의 흰 정사각형 배경 이미지 생성
if w >= h:  # 리사이징 후 붙여넣기
    image.paste(img.resize((512, 512 * h // w)), (0, 256 * (w - h) // w))
else:
    image.paste(img.resize((512 * w // h, 512)), (256 * (h - w) // h, 0))
img = np.asarray(image, dtype=np.float32)
img = np.expand_dims(img, 0)  # 512×512×3 -> 1×512×512×3
img = (img - 128) / 64  # [0, 255] -> [-2, 2]
# print(np.min(img), np.max(img), img.shape) # Check [-2, 2], Shape

# Load the TFLite model and allocate tensors.
interpreter = tflite.Interpreter(model_path='./util/python/model_float32.tflite')
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test the model on random input data.
input_shape = input_details[0]['shape']
interpreter.set_tensor(input_details[0]['index'], img)

# t1 = time.time()
interpreter.invoke()
# t2 = time.time()
# print(t2 - t1)

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
# print(np.min(output_data), np.max(output_data))

out = 255 - np.squeeze(output_data) * 255
buffered = BytesIO()
if w >= h:  # 그레이 스케일로 변환 후 원래 비율로 크롭
    Image.fromarray(out).convert('L').crop(
        (0, 256 * (w - h) // w, 512, 256 * (w + h) // w)).save(buffered, format='PNG')
else:
    Image.fromarray(out).convert('L').crop(
        (256 * (h - w) // h, 0, 256 * (w + h) // h, 512)).save(buffered, format='PNG')
sys.stdout.buffer.write(buffered.getvalue())


"""
===========================
Create univariate functions
===========================
This example presents different ways to create univariate functions which can be used to create
a functional basis. This is the type of functions involved, for example, in the
:class:`~openturns.FunctionalChaosAlgorithm` class.

The univariate functions considered in this
example can be, in some cases, orthogonal to a distribution, but this is not a necessary
condition to create univariate functions. For example, Legendre polynomials are orthogonal
with respect to the uniform distribution, but the monomials of the canonical polynomial basis
are not necessarily orthogonal.
"""
# %%
# Description
# ===========
#
# We want to build univariate functions :math:`f : \mathbb{R} \mapsto \mathbb{R}`.
#
# We can do that:
#
# - Case 1: using orthogonal polynomials,
# - Case 2: using univariate polynomials,
# - Case 3: using orthogonal functions.
#
#
# Case 1: Orthogonal polynomials
# ==============================
#
# In that case, the polynomials are orthogonal with respect to a measure.
#
# For example: we consider the Legendre polynomials family, orthogonal with respect to the uniform
# distribution on :math:`[0,1]`. We use the :class:`~openturns.LegendreFactory` class.
# Its method :meth:`~openturns.LegendreFactory.build` applied to :math:`k` returns the polynomial number
# :math:`k` of the family.
import openturns as ot
import openturns.viewer as otv

f1 = ot.LegendreFactory().build(1)
f2 = ot.LegendreFactory().build(2)
f3 = ot.LegendreFactory().build(3)

print(type(f1))

g = f1.draw(-1.0, 1.0, 256)
g.add(f2.draw(-1.0, 1.0, 256))
g.add(f3.draw(-1.0, 1.0, 256))
g.setLegends([r'$\phi_1(x)$', r'$\phi_2(x)$', r'$\phi_3(x)$'])
g.setLegendPosition('bottomright')
g.setColors(ot.Drawable.BuildDefaultPalette(3))
g.setTitle('Legendre Polynomials')
view = otv.View(g)

# %%
# We get the measure associated to the polynomial family:
measure_Legendre = ot.LegendreFactory().getMeasure()
print('Measure orthogonal to Legendre polynomials = ', measure_Legendre)

# %%
# Case 2: Univariate polynomials
# ==============================
#
# Univariate polynomials are not necessarily orthogonal with respect to a measure.
#
# We can use:
#
# - the :class:`~openturns.UniVariatePolynomial` class,
# - the :class:`~openturns.MonomialFunctionFactory` class,
# - the :class:`~openturns.MonomialFunction` class.
#
# For example, we consider :
#
# .. math::
#
#     \begin{array}{lcl}
#       f(x) & = & 1+2x+3x^2+4x^3\\
#       g(x) & = & x^3
#     \end{array}

f = ot.UniVariatePolynomial([1.0, 2.0, 3.0, 4.0])
g1 = ot.MonomialFunctionFactory().build(3)
g2 = ot.MonomialFunction(3)
print('f = ', f)
print('g1 = ', g1)
print('g2 = ', g2)

# %%
# There is no associated measure: if it is uncommented, the following command will fail, as expected.

# print(ot.MonomialFunctionFactory().getMeasure())

# %%
# Case 3: Orthogonal functions
# ============================
#
# In that case, the functions are orthogonal with respect to a measure :math:`\mu`.
#
# We can use:
#
# - the :class:`~openturns.HaarWaveletFactory` class,
# - the :class:`~openturns.FourierSeriesFactory` class.
#
# The method :meth:`~openturns.HaarWaveletFactory.build` returns the function number :math:`k` of the family.
#
# For example, we consider a Haar Wawelet.
f1 = ot.HaarWaveletFactory().build(1)
f2 = ot.HaarWaveletFactory().build(2)
f3 = ot.HaarWaveletFactory().build(3)

g = f1.draw(0.0, 1.0, 256)
g.add(f2.draw(0.0, 1.0, 256))
g.add(f3.draw(0.0, 1.0, 256))
g.setLegends([r'$\phi_1(x)$', r'$\phi_21(x)$', r'$\phi_3(x)$'])
g.setLegendPosition('topright')
g.setColors(ot.Drawable.BuildDefaultPalette(3))
g.setTitle('Haar Wavelets')
view = otv.View(g)

# %%
# We get the measure: for the Haar Wavelet family, the :math:`\mathcal{U}(0,1)` distribution.
measure_Haar = ot.HaarWaveletFactory().getMeasure()
print('Measure orthogonal to Haar wavelets = ', measure_Haar)

# %%
# For example, we consider a Fourier Series.
f1 = ot.FourierSeriesFactory().build(1)
f2 = ot.FourierSeriesFactory().build(2)
f3 = ot.FourierSeriesFactory().build(3)

g = f1.draw(-3.0, 3.0, 256)
g.add(f2.draw(-3.0, 3.0, 256))
g.add(f3.draw(-3.0, 3.0, 256))
g.setLegends([r'$\phi_1(x)$', r'$\phi_21(x)$', r'$\phi_3(x)$'])
g.setLegendPosition('topright')
g.setColors(ot.Drawable.BuildDefaultPalette(3))
g.setTitle('Fourier Series')
view = otv.View(g)

# %%
# We get the measure: for the Fourier Series, the :math:`\mathcal{U}(-\pi, \pi)` distribution.
measure_Fourier = ot.FourierSeriesFactory().getMeasure()
print('Measure orthogonal to Fourier series = ', measure_Fourier)

# %%
otv.View.ShowAll()


import keras
from wnn_layer import WNN
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.utils import plot_model
import matplotlib.pyplot as plt

# Generate dummy data
import numpy as np

x = []
y = []
x_test = []
y_test = []
x_n = 0.01
l = 3.8

for i in range(0,10000):
    x_old = x_n
    x_n = l * x_n * (1 - x_n)
    x_nplus = l * x_n * (1 - x_n)
    x.append([x_old, x_n])
    y.append([x_nplus])

for i in range(0, 100):
    x_old = x_n
    x_n = l * x_n * (1 - x_n)
    x_nplus = l * x_n * (1 - x_n)

    x_test.append([x_old, x_n])
    y_test.append([x_nplus])

x_train = np.array(x)
y_train = np.array(y)

model = Sequential()
f_layer = WNN(1000, 1, input_dim=2)
model.add(f_layer)

model.compile(loss='mean_squared_error',
              optimizer='adagrad',
              metrics=['mae'])

model.fit(x_train, y_train,
          epochs=200,
          verbose=1,
          batch_size=100)

score = model.evaluate(np.array(x_test), np.array(y_test), verbose=True)
print(score)
pred = model.predict(np.array(x_test))

plt.ion()
plt.show()
plt.clf()
plt.title('Logistics map')
plt.ylabel('x[n-1]')
plt.xlabel('x[n]')

plt.plot(y_test, label='test', c=(0,0,0))
plt.plot(pred, label='pred', c=(1,0,0))
#plt.scatter([a[0] for a in x_train], [a[0] for a in y_train], c=(0,0,0), alpha=0.5,s=1)
#plt.scatter([a[0] for a in x_test], [a[0] for a in pred], c=(1,0,0), alpha=0.5,s=1)
plt.show()
plt.pause(120)


# REPL - Run , Evaluate , print - Loop
lst= [ 'mango', 'pinaple', 'cherry', 'orange', 'banana', 'papaya', 'berry']

for item in lst :
    print(item , " is my favorite fruit")

# Exercise - understanding for loop of list.
# create a list of 1 to 10 numbers
# use for loop to print only even numbers
# hint - need to use if command inside loop to check for odd and even.
# time - 10 min


import unittest

from pip import main
from user import user

class Testuser(unittest.TestCase):
    '''
    Test class that defines test cases for user class behaviors.
    unittest.TestCase: Testcase class that helps in creating test cases
    '''
    def setUp(self):
        '''
        setUp: method that runs before each testcases.
        '''
        self.new_user=user("Veronica","Rodriguez","2022")
    def test_init(self):
            '''
            test_init: test case to test if the object is initialized properly
            '''
            self.assertEqual(self.new_user.user_name,"Veronica")
            self.asserEqual(self.new_user.password,"2022")
    def test_save_user(self):
        '''
        test_save_user: test case to test if the user object is saved into the user list
        '''
        self.new_user.save_user()#save new contact
        self.asserEqual(len(user.user_list),1)
    def test_delete_user(self): #*****!!test delete user
        '''
        test_delete_contact:test if we can remove contact from contact list
        '''
        self.new_contact.save_contact()
        test_user=user("Test","User","0712345678","test@user.com") #new contact
        test_user.save_user()

        self.new_user.delete_user()#deleting a contact object
        self.assertEqual(len(user.user_list),1)
if __name__ == '__main__':
    unittest.main()


# https://leetcode.com/problems/merge-two-binary-trees/description/
#
# class TreeNode:
#     def __init__(self, val, left = None, right = None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        stack = [(t1, t2)]
        while stack:
            node1, node2 = stack.pop()
            if not (node1 or node2):
                continue
            node1[val] += node2[val]

            if not node1.left:
                node1.left = node2.left
            else:
                stack.append((node1.left, node2.left))

            if not node1.right:
                node1.right = node2.right
            else:
                stack.append((node1.right, node2.right))
        return t1


class TOH():

    def __init__(self,n=3):
        self.number_of_pegs = 3
        self.number_of_rings = n
        self.pegs = {}
        self.pegs['A'] = []
        self.pegs['B'] = []
        self.pegs['C'] = []
        self.steps = []
        for i in range(1,n+1):
            self.pegs['A'].append(n+1-i)
        # print("Initial condition ",self.pegs)
        self.steps.append({'A':self.pegs['A'][:],'B':self.pegs['B'][:],'C':self.pegs['C'][:]})

    def getAuxPeg(self,peg1,peg2):
        t = ['A','B','C']
        t.remove(peg1)
        t.remove(peg2)
        return t[0]

    def move(self,peg1, peg2, n):

        if n == 1:
            temp = self.pegs[peg1].pop()
            self.pegs[peg2].append(temp)
            # print(self.pegs)
            self.steps.append({'A':self.pegs['A'][:],'B':self.pegs['B'][:],'C':self.pegs['C'][:]})

        else:
            aux_peg = self.getAuxPeg(peg1,peg2)
            self.move(peg1,aux_peg,n-1)
            self.move(peg1,peg2,1)
            self.move(aux_peg,peg2,n-1)

    def solve(self):
        self.move('A','B',self.number_of_rings)

n = int(input("input = "))
t1 = TOH(n)
t1.solve()

steps = t1.steps

for i in range(0,len(steps)):
    if i == 0:
        print("Initial condition =",steps[i]["A"],steps[i]["B"],steps[i]["C"])
    else:
        print(f"Step {i} =",steps[i]["A"],steps[i]["B"],steps[i]["C"])