import math,time # Importing mathematics and time modules

def sumavec(f1,theta1,f2,theta2):
    try:
        #First vector components
        theta1 = math.radians(theta1)
        f1x = f1*math.cos(theta1)
        f1y = f1*math.sin(theta1)
        #print("Vector 1 components\nX:{x} Y:{y}".format(x = round(f1x,4),y = round(f1y,4)))

        #Second vector components
        theta2 = math.radians(theta2)
        f2x = f2*math.cos(theta2)
        f2y = f2*math.sin(theta2)
        #print("Vector 2 components\nX:{x} Y:{y}".format(x= round(f2x,4),y =round(f2y,4)))

        #Vector addition
        frx = f1x+f2x
        fry = f1y+f2y
        Fr = math.sqrt(math.pow(frx,2)+math.pow(fry,2))
        Fr = round(Fr,4) #Rounding the result to 4 figures
        print('Resultant vector components\nX:{x}, Y:{y}'.format(x = round(frx,4), y = round(fry,4)))

        #Vector angle
        if frx != 0:
            angle = math.degrees(math.atan(abs(fry)/abs(frx)))
            print('Resultant vector angle\nTeta:{x}'.format(x = round(angle,4)))
        if Fr != 0:
            #When frx is greater than zero
            if frx > 0:
                if fry < 0:
                    polar = 360 - angle #calculating angle using  absolute values of the components
                else:
                    polar = angle
            elif frx < 0:
                if fry < 0:
                    polar = 180 + angle
                else:
                    polar = 180 - angle
            else:
                if fry > 0:
                    polar = 90
                else:
                    polar = 270
        else:
            polar = 0.0
            print('Vectors cancelled each other')

        if round(polar,4) == 360: #Rounding angles very close to  360 degrees and set it to zero degrees
            polar = 0

        print("Resulting vector\nMagnitude:{x} Polar Angle:{y}".format(x = round(Fr,4),y = round(polar,4)))

    except TypeError:
        print('Something goes wrong...')
        time.sleep(2) #Do nothhing for 2 seconds
        print('Variable type error')
    return

def ingresovalores():
    F1 = 'x'
    t1 = 'x'
    F2 = 'x'
    t2 = 'x'
    #Inputting values
    print('Defining 2D vector number 1')
    while F1 == 'x' and t1 == 'x':
        try:
            F1 =float(input('Magnitude:'))
            if F1 < 0:
                print('Something goes wrong...')
                time.sleep(2)
                raise ValueError #Rasing a Value Error when a negative number is input
            t1 =float(input('Angle:'))

        except ValueError: #Used for type errors (wrong type of variables)
            print('Something goes wrong...')
            time.sleep(2)
            print('Incorrect value for vector 1')
            F1 = 'x'
            t1 = 'x'
            print('Input the correct values for vector 1')

    print('Defining 2D vector number 2')
    while F2 == 'x' and t2 == 'x':
        try:
            F2 =float(input('Magnitude:'))
            if F2 < 0:
                print('Something goes wrong...')
                time.sleep(2)
                raise ValueError #Rasing a Value Error when a negative number is input
            t2 =float(input('Angle:'))
            sumavec(F1,t1,F2,t2)
        except ValueError: #Used for type errors (wrong type of variables)
            print('Something goes wrong...')
            time.sleep(2)
            print('Incorrect value for vector 2')
            F2 = 'x'
            t2 = 'x'
            print('Input the correct values for vector 2')
    return

#Variables default values

ans = 's' #Default variable 'ans'  value
ingresovalores()
while 1:
    ans = input('Would you like to sum other two vectors? Y/N ')
    ans = ans.lower() #Turning string to lower case
    if ans == 'n':
        print('Thanks for using the 2D vector adder')
        break
    elif ans == 'y':
        ingresovalores()
    else:
        print('Choose a valid option')


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

# Django's Libraries
from django.conf.urls import url

# Own's Libraries
from .views import ComprobanteProveedorList
from .views import ComprobanteProveedorView

from .views import ComprobanteClienteList
from .views import ComprobanteEmpleadoList
from .views import ResumenList
from .views import LogList
from .views import ObtenerFacturas
from .views import ValidarFactura
from .views import MarcarPago
from .views import ReconocerFactura

apps_name = "facturas"

urlpatterns = [
    url(
        r'^comprobantes/proveedores/(?P<empresa>.*?)/(?P<anio>.*?)/(?P<mes>.*?)/$',
        ComprobanteProveedorList.as_view(),
        name='proveedor_lista'
    ),
    url(
        r'^comprobantes/proveedores/(?P<uuid>.+)/$',
        ComprobanteProveedorView.as_view(),
        name='proveedor_view'
    ),
    url(
        r'^comprobantes/clientes/(?P<empresa>.*?)/(?P<anio>.*?)/(?P<mes>.*?)/$',
        ComprobanteClienteList.as_view(),
        name='cliente_lista'
    ),
    url(
        r'^comprobantes/empleados/(?P<empresa>.*?)/(?P<anio>.*?)/(?P<mes>.*?)/$',
        ComprobanteEmpleadoList.as_view(),
        name='empleado_lista'
    ),
    url(
        r'^comprobantes/resumen/$',
        ResumenList.as_view(),
        name='resumen_lista'
    ),
    url(
        r'^comprobantes/logs/$',
        LogList.as_view(),
        name='log_lista'
    ),
    url(
        r'^comprobantes/obtener/$',
        ObtenerFacturas.as_view(),
        name='obtener_facturas'
    ),
    url(
        r'^comprobantes/validar_factura/(?P<type>.*)/(?P<uuid>.+)/$',
        ValidarFactura.as_view(),
        name='validar_factura'
    ),
    url(
        r'^comprobantes/marcar_pago/(?P<type>.*)/(?P<uuid>.+)/(?P<value>.+)/$',
        MarcarPago.as_view(),
        name='marcar_pago'
    ),
    url(
        r'^comprobantes/reconocer_factura/(?P<type>.*)/(?P<uuid>.+)/(?P<value>.+)/$',
        ReconocerFactura.as_view(),
        name='reconocer_factura'
    ),
]


'''
In this problem the graph is like y = sin(x)
I need to find the values of:
-----------------------------
5 * sin(theta) + 3 = 0
-----------------------------
'''

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

theta = math.asin(-3/5)
'''
old_theta_deg = math.fabs(theta*(180/math.pi))
'''

old_theta_deg = math.fabs(math.degrees(theta))
print(old_theta_deg)
theta_1 = old_theta_deg + 180

theta_2 = 360 - old_theta_deg

t_1 = float("{0:.3f}".format(theta_1))
t_2 = float("{0:.3f}".format(theta_2))

print("Hence the value for theta from 0 to 360 is {} deg. or {} deg.".format(t_1, t_2))

'''
The code for the graph
I am trying to plot the graph which will ensure that I plot the values properly.
This will be achieved by creating the angles like in previous problem.

'''

angles = np.linspace(0,360)

x = [math.radians(j) for j in angles]

y = [5*math.sin(i) + 3 for i in x]

plt.plot(angles,y)
plt.grid()
plt.show()


import pygame
from pygame.sprite import Sprite

class Star(Sprite):
    def __init__(self, screen):
        super().__init__()
        self.screen = screen
        self.screen_rect = self.screen.get_rect()
        #Load star
        self.image = pygame.image.load('../images/star.png')
        self.rect = self.image.get_rect()

    def update(self):
        self.rect.y += 1 # drop a bit


# Django
from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _

from django.core.mail import EmailMessage
from django.template.loader import render_to_string

# Utilities
from utils.models import BaseModel

class User(BaseModel, AbstractUser):
    """User model."""
    email = models.EmailField(max_length=254, unique=True, verbose_name='Correo')
    photo = models.CharField(max_length=254, blank=True, verbose_name='Foto')
    telephone = models.CharField(max_length=64, blank=True, verbose_name='Telefono')
    birthday = models.DateField(null=True, blank=True, verbose_name='Cumpleaños')
    interest = models.CharField(max_length=254, blank=True, verbose_name='Intereses')
    is_verified = models.BooleanField(default=False, verbose_name='¿Esta verificado?')
    is_completed = models.BooleanField(default=False, verbose_name='¿Esta completo?')
    description = models.CharField(max_length=120, blank=True, verbose_name='Descripción')

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    university = models.ForeignKey('places.University', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Universidad')
    city = models.ForeignKey('places.City', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Ciudad')

    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )

    def send_registration_email(self, rol):
        body = render_to_string('new-user.html',
            {'first_name': self.first_name, 'last_name': self.last_name, 'rol': rol},)
        email_message = EmailMessage(
            subject='Registro Helptutor',
            body=body,
            from_email=settings.EMAIL_HOST_USER,
            to=[self.email],
        )
        email_message.content_subtype = 'html'
        email_message.send()

    def __str__(self):
        return "[{}] {}".format(self.id, self.email)


"""Training Transformer for WMT17 Dataset

This implements the machine translation benchmark tasks,
# TODO add link to docs
"""
import argparse
import json
import logging
import os
import time
from copy import deepcopy
import unittest.mock as mock

import numpy as np
import torch
import torch.distributed as dist

# Parser is defined and called before the rest of the import
# because we need to inject the collaborative heads into mlbench_core
# with `use_collaborative_heads` and `key_query_dim` parameter
# before importing the rest of the modules
parser = argparse.ArgumentParser(description="Process run parameters")
parser.add_argument("--run_id", type=str, default="1", help="The id of the run")
parser.add_argument(
    "--root-dataset",
    type=str,
    default="/datasets",
    help="Default root directory to dataset.",
)
parser.add_argument(
    "--root-checkpoint",
    type=str,
    default="/checkpoint",
    help="Default root directory to checkpoint.",
)
parser.add_argument(
    "--root-output",
    type=str,
    default="/output",
    help="Default root directory to output.",
)
parser.add_argument(
    "--validation_only",
    action="store_true",
    default=False,
    help="Only validate from checkpoints.",
)
parser.add_argument("--gpu", action="store_true", default=False, help="Train with GPU")
parser.add_argument(
    "--light",
    action="store_true",
    default=False,
    help="Train to light target metric goal",
)
parser.add_argument("--rank", type=int, default=1, help="The rank of the process")
parser.add_argument(
    "--backend", type=str, default="mpi", help="PyTorch distributed backend"
)
parser.add_argument("--hosts", type=str, help="The list of hosts")
parser.add_argument("--uid", type=str, default="allreduce", help="Name of the run")

# Collaborative heads
parser.add_argument(
    "--use_collaborative_heads",
    action="store_true",
    default=False,
    help="Use collaborative heads instead of concatenation",
)

parser.add_argument(
    "--key_query_dim",
    type=int,
    default=None,
    help="Dimension of the key/query projections, default is the hidden size of the transformer",
)

if __name__ == "__main__":
    args = parser.parse_args()

    # Inject the collaborative head into mlbench-core transformer.
    # We specify key_query_dim and use_collaborative_heads with a partial application
    # to make the signature of CollaborativeMultiheadAttention exactly the same as MultiheadAttention
    if args.use_collaborative_heads or args.key_query_dim is not None:
        import mlbench_core.models.pytorch.transformer.modules.multihead_attention
        from collab_multihead_attention import CollaborativeMultiheadAttention
        import functools
        import sys

        mlbench_core.models.pytorch.transformer.modules.multihead_attention.MultiheadAttention = functools.partial(
            CollaborativeMultiheadAttention,
            key_query_dim=args.key_query_dim,
            use_collaborative_heads=args.use_collaborative_heads,
        )

        reload_mods = [
            mod
            for mod in sys.modules
            if "mlbench" in mod and "multihead_attention" not in mod
        ]
        for mod in reload_mods:
            del sys.modules[mod]

from mlbench_core.controlflow.pytorch.checkpoints_evaluation import (
    CheckpointsEvaluationControlFlow,
)
from mlbench_core.controlflow.pytorch.controlflow import (
    record_train_batch_stats,
    record_validation_stats,
)
from mlbench_core.dataset.nlp.pytorch import WMT17Dataset, get_batches
from mlbench_core.dataset.util.pytorch import partition_dataset_by_rank
from mlbench_core.evaluation.goals import task4_time_to_bleu_goal
from mlbench_core.evaluation.pytorch.criterion import LabelSmoothing
from mlbench_core.evaluation.pytorch.metrics import BLEUScore
from mlbench_core.lr_scheduler.pytorch.lr import SQRTTimeDecayLRWithWarmup
from mlbench_core.models.pytorch.transformer import SequenceGenerator, TransformerModel
from mlbench_core.utils import Tracker
from mlbench_core.utils.pytorch import initialize_backends
from mlbench_core.utils.pytorch.checkpoint import Checkpointer, CheckpointFreq
from torch.utils.data import DataLoader

from utils import (
    Arguments,
    build_optimizer,
    compute_loss,
    get_full_batch_size,
    opt_step,
    prepare_batch,
    validation_round,
)

try:
    import horovod.torch as hvd
except ImportError as e:
    hvd = None

def equalize_batches(batches, world_size, seed):
    """Given a list of batches, makes sure each workers has equal number
    by adding new batches using bootstrap sampling

    Args:
        batches (list): The list of batches
        world_size (int): Distributed world size
        seed (int): Random seed to use (must be the same across all workers)

    Returns:
        (list): The new extended batches
    """
    to_add = world_size - (len(batches) % world_size)
    if to_add == 0:
        return batches
    np.random.seed(seed)
    bootstrapped = np.random.choice(np.arange(len(batches)), size=to_add)

    to_add = [batches[i] for i in bootstrapped]
    return batches + to_add

def get_max_tokens(world_size, update_freq, max_tokens_batch=2 ** 17):
    """Returns the max number of tokens a batch should have

    Args:
        world_size (int): Distributed world size
        update_freq (int): Update frequency (min 1)
        max_tokens_batch (int): Max tokens per batch over all workers

    Returns:
        (int): The max number of tokens per batch per worker
    """
    return int(max_tokens_batch / (world_size * update_freq))

logger = logging.getLogger("mlbench")

DEFAULT_TRANSFORMER_ARCH = {
    "max_source_positions": 256,
    "max_target_positions": 256,
    "dropout": 0.3,
    "attention_dropout": 0.1,
    "relu_dropout": 0.1,
    "encoder_embed_path": None,
    "encoder_embed_dim": 1024,
    "encoder_ffn_embed_dim": 4096,
    "encoder_layers": 6,
    "encoder_attention_heads": 16,
    "encoder_normalize_before": True,
    "encoder_learned_pos": False,
    "decoder_embed_path": None,
    "decoder_embed_dim": 1024,
    "decoder_ffn_embed_dim": 4096,
    "decoder_layers": 6,
    "decoder_attention_heads": 16,
    "decoder_learned_pos": False,
    "decoder_normalize_before": True,
    "share_decoder_input_output_embed": False,
    "share_all_embeddings": False,
    "no_token_positional_embeddings": False,
    "softmax_type": None,
}

def train_loop(
    run_id,
    dataset_dir,
    ckpt_run_dir,
    output_dir,
    validation_only=False,
    use_cuda=False,
    light_target=False,
    seed=42,
):
    """Train loop"""
    train_epochs = 9

    math_mode = "fp16"
    rank = dist.get_rank()
    world_size = dist.get_world_size()

    # Dataset arguments
    update_freq = max(16 // world_size, 1)
    max_tokens = get_max_tokens(world_size, update_freq)
    max_source_positions, max_target_positions = 80, 80
    seq_len_multiple = 2
    left_pad = (True, False)
    lang = ("en", "de")

    # specific arch
    model_args = deepcopy(DEFAULT_TRANSFORMER_ARCH)
    model_args["max_source_positions"] = max_source_positions
    model_args["max_target_positions"] = max_target_positions
    model_args["share_all_embeddings"] = True
    model_args["dropout"] = 0.1
    model_args["softmax_type"] = "fast_fill"

    lr = 1.976e-3
    optimizer_args = {"lr": lr, "eps": 1e-9, "betas": (0.9, 0.98)}
    scheduler_args = {"base_lr": lr, "warmup_init_lr": 0.0, "warmup_steps": 1000}

    loss_scaling_fp16 = {
        "init_scale": 2.0 ** 7,
        "scale_factor": 2,
        "scale_window": 2000,
    }

    criterion_args = {"smoothing": 0.1, "fast_xentropy": True}

    # Horovod stuff
    use_horovod = (math_mode == "fp16") and dist.get_backend() == dist.Backend.MPI
    if use_horovod:
        hvd.init()
        logger.info("Using horovod rank={}".format(hvd.rank()))
        tensor = torch.tensor([1])
        res = hvd.allreduce(tensor, op=hvd.Sum)
        assert res[0] == world_size

    # Load train and validation datasets
    train_set = WMT17Dataset(
        dataset_dir,
        download=True,
        train=True,
        shuffle=True,
        lang=lang,
        left_pad=left_pad,
        max_positions=(max_source_positions, max_target_positions),
        seq_len_multiple=seq_len_multiple,
    )

    validation_set = WMT17Dataset(
        dataset_dir,
        download=False,
        test=True,
        shuffle=True,
        lang=lang,
        left_pad=left_pad,
        max_positions=(max_source_positions, max_target_positions),
        seq_len_multiple=seq_len_multiple,
    )
    src_dict, trg_dict = train_set.src_dict, train_set.trg_dict

    train_batches = get_batches(
        train_set, max_tokens=max_tokens, bsz_mult=8, shuffle=True, seed=seed
    )
    val_batches = get_batches(
        validation_set, max_tokens=max_tokens, bsz_mult=8, shuffle=False
    )

    train_batches = equalize_batches(train_batches, world_size, seed=seed)

    # Partition by rank
    train_batches = partition_dataset_by_rank(train_batches, rank, world_size)
    val_batches = partition_dataset_by_rank(val_batches, rank, world_size)

    total_train_points = sum(len(b) for b in train_batches)

    validate_every = update_freq * round(
        len(train_batches) * 0.30 / update_freq
    )  # Validate every 30%

    assert (validate_every % update_freq) == 0
    logger.info(
        "Using {} total train points, {} batches".format(
            total_train_points, len(train_batches)
        )
    )

    train_loader = DataLoader(
        train_set,
        num_workers=1,
        pin_memory=False,
        collate_fn=train_set.collater,
        batch_sampler=train_batches,
    )

    val_loader = DataLoader(
        validation_set,
        num_workers=1,
        pin_memory=False,
        collate_fn=validation_set.collater,
        batch_sampler=val_batches,
    )

    model = TransformerModel(Arguments(model_args), src_dict, trg_dict)
    criterion = LabelSmoothing(padding_idx=src_dict.pad(), **criterion_args)

    if use_cuda:
        model = model.cuda()
        criterion = criterion.cuda()
    fp_optimizer, optimizer, model = build_optimizer(
        model,
        optimizer_args,
        math_mode=math_mode,
        scaling_args=loss_scaling_fp16,
        use_horovod=use_horovod,
        use_cuda=use_cuda,
    )

    scheduler = SQRTTimeDecayLRWithWarmup(optimizer, **scheduler_args)

    metrics = [BLEUScore(use_raw=True)]
    checkpointer = Checkpointer(
        ckpt_run_dir=ckpt_run_dir, rank=rank, freq=CheckpointFreq.BEST
    )

    translator = SequenceGenerator(
        model,
        src_dict=deepcopy(src_dict),
        trg_dict=deepcopy(trg_dict),
        beam_size=4,
        stop_early=True,
        normalize_scores=True,
        len_penalty=0.6,
        sampling=False,
        sampling_topk=-1,
        minlen=1,
    )
    if not validation_only:

        goal = None
        # if light_target:
        #     goal = task4_time_to_bleu_goal(20)
        # else:
        #     goal = task4_time_to_bleu_goal(25)

        num_batches_per_device_train = len(train_loader)
        tracker = Tracker(metrics, run_id, rank, goal=goal)

        dist.barrier()
        tracker.start()

        for epoch in range(0, train_epochs):
            if torch.cuda.is_available():
                torch.cuda.empty_cache()

            model.train()
            tracker.train()

            iter_sample_size = 0
            for batch_idx, sample in enumerate(train_loader):
                sample = prepare_batch(sample, use_cuda=use_cuda)
                tracker.batch_start()

                is_last = batch_idx == len(train_loader)
                update = (batch_idx % update_freq) == update_freq - 1
                init = (batch_idx % update_freq) == 0
                # Clear gradients in the optimizer.
                if init:
                    fp_optimizer.zero_grad()
                    iter_sample_size = 0
                    tracker.record_batch_init()

                # Compute the output
                output = model(**sample["net_input"])
                tracker.record_batch_fwd_pass()

                loss, sample_size = compute_loss(sample, output, criterion)
                loss_per_sample = loss.item() / sample_size
                iter_sample_size += sample_size
                tracker.record_batch_comp_loss()

                # Backprop
                fp_optimizer.backward_loss(loss)
                tracker.record_batch_backprop()

                if update or is_last:
                    # Optimize
                    full_bs = get_full_batch_size(
                        iter_sample_size, world_size=world_size, use_cuda=use_cuda
                    )

                    updated = opt_step(
                        fp_optimizer, full_bs, update_freq, math_mode, world_size
                    )
                    tracker.record_batch_opt_step()

                    if updated:
                        scheduler.step()

                tracker.batch_end()

                record_train_batch_stats(
                    batch_idx=batch_idx,
                    loss=loss_per_sample,
                    output=torch.Tensor([0]),
                    target=None,
                    metrics=[],
                    tracker=tracker,
                    num_batches_per_device_train=num_batches_per_device_train,
                )

                if (batch_idx + 1) % validate_every == 0:
                    if torch.cuda.is_available():
                        torch.cuda.empty_cache()

                    metric_values, loss = validation_round(
                        val_loader,
                        metrics,
                        criterion,
                        translator,
                        tracker=tracker,
                        use_cuda=use_cuda,
                    )
                    record_validation_stats(metric_values, loss, tracker, rank)
                    if tracker.goal_reached:
                        break

                    model.train()
                    tracker.train()

            if torch.cuda.is_available():
                torch.cuda.empty_cache()

            metric_values, loss = validation_round(
                val_loader,
                metrics,
                criterion,
                translator,
                tracker=tracker,
                use_cuda=use_cuda,
            )
            is_best = record_validation_stats(metric_values, loss, tracker, rank)
            checkpointer.save(
                tracker, model, optimizer, scheduler, tracker.current_epoch, is_best
            )
            tracker.epoch_end()

            if tracker.goal_reached:
                print("Goal Reached!")
                time.sleep(10)
                return
    else:
        cecf = CheckpointsEvaluationControlFlow(
            ckpt_dir=ckpt_run_dir,
            rank=rank,
            world_size=world_size,
            checkpointer=checkpointer,
            model=model,
            epochs=train_epochs,
            loss_function=criterion,
            metrics=metrics,
            use_cuda=use_cuda,
            dtype="fp32",
            max_batch_per_epoch=None,
        )

        train_stats = cecf.evaluate_by_epochs(train_loader)
        with open(os.path.join(output_dir, "train_stats.json"), "w") as f:
            json.dump(train_stats, f)

        # val_stats = cecf.evaluate_by_epochs(val_loader)
        # with open(os.path.join(output_dir, "val_stats.json"), "w") as f:
        #     json.dump(val_stats, f)

def main(
    run_id,
    dataset_dir,
    ckpt_run_dir,
    output_dir,
    rank,
    backend,
    hosts,
    validation_only=False,
    gpu=False,
    light_target=False,
):
    r"""Main logic."""
    with initialize_backends(
        comm_backend=backend,
        hosts=hosts,
        rank=rank,
        logging_level="INFO",
        logging_file=os.path.join(output_dir, "mlbench.log"),
        use_cuda=gpu,
        seed=43,
        cudnn_deterministic=False,
        ckpt_run_dir=ckpt_run_dir,
        delete_existing_ckpts=not validation_only,
    ):
        train_loop(
            run_id,
            dataset_dir,
            ckpt_run_dir,
            output_dir,
            validation_only,
            use_cuda=gpu,
            light_target=light_target,
            seed=43,
        )

if __name__ == "__main__":
    uid = args.uid
    dataset_dir = os.path.join(args.root_dataset, "torch", "wmt17")
    ckpt_run_dir = os.path.join(args.root_checkpoint, uid)
    output_dir = os.path.join(args.root_output, uid)
    os.makedirs(dataset_dir, exist_ok=True)
    os.makedirs(ckpt_run_dir, exist_ok=True)
    os.makedirs(output_dir, exist_ok=True)

    main(
        args.run_id,
        dataset_dir,
        ckpt_run_dir,
        output_dir,
        rank=args.rank,
        backend=args.backend,
        hosts=args.hosts,
        validation_only=args.validation_only,
        gpu=args.gpu,
        light_target=args.light,
    )


import pandas as pd

def make_submission(predictions, test_path, file_name):
    '''Creates a .csv submission file.'''

    # Create submission
    sample_submission = pd.read_csv(test_path)
    IDs = sample_submission["encounter_id"]

    to_submit = {'encounter_id': IDs, 'diabetes_mellitus': predictions}
    df_to_submit = pd.DataFrame(to_submit).set_index(['encounter_id'])

    df_to_submit.to_csv(file_name)
    print("Submission ready.")


#User function Template for python3

class Solution:
    def AllParenthesis(self,n):
        #code here
        results = []
        stack = []
        stack.append(('', n, n))
        while stack:
            sofar, left, right = stack.pop()
            if left == 0 and right == 0:
                results.append(sofar)
            if left > 0:
                stack.append((sofar + "(", left-1, right))
            if right > left:
                stack.append((sofar + ")", left, right-1))
        return results

#{
#  Driver Code Starts
#Initial Template for Python 3

if __name__=="__main__":
    t=int(input())
    for i in range(0,t):
        n=int(input())
        ob=Solution()
        result=ob.AllParenthesis(n)
        result.sort()
        for i in range(0,len(result)):
            print(result[i])

# } Driver Code Ends


from typing import List
from .customer import Customer
from .equipment import Equipment
from .exercise_plan import ExercisePlan
from .subscription import Subscription
from .trainer import Trainer

class Gym:

    def __init__(self):
        self.customers: List[Customer] = []
        self.trainers: List[Trainer] = []
        self.equipment: [Equipment] = []
        self.plans: List[ExercisePlan] = []
        self.subscriptions: List[Subscription] = []

    def add_customer(self, customer: Customer) -> None:
        # customers_ids = [customer.id for customer in self.customers]
        # if customer.id not in customers_ids:
        #     self.customers.append(customer)
        if customer not in self.customers:
            self.customers.append(customer)

    def add_trainer(self, trainer: Trainer) -> None:
        # trainers_ids = [trainer.id for trainer in self.trainers]
        # if trainer.id not in trainers_ids:
        #     self.trainers.append(trainer)
        if trainer not in self.trainers:
            self.trainers.append(trainer)

    def add_equipment(self, equipment: Equipment) -> None:
        # equipments_ids = [equipment.id for equipment in self.equipment]
        # if equipment.id not in equipments_ids:
        #     self.equipment.append(equipment)
        if equipment not in self.equipment:
            self.equipment.append(equipment)

    def add_plan(self, plan: ExercisePlan) -> None:
        # plans_ids = [plan.id for plan in self.plans]
        # if plan.id not in plans_ids:
        #     self.plans.append(plan)
        if plan not in self.plans:
            self.plans.append(plan)

    def add_subscription(self, subscription: Subscription) -> None:
        # subscriptions_ids = [subscription.id for subscription in self.subscriptions]
        # if subscription.id not in subscriptions_ids:
        #     self.subscriptions.append(subscription)
        if subscription not in self.subscriptions:
            self.subscriptions.append(subscription)

    def subscription_info(self, subscription_id: int):
        subscriptions_ids = [subscription.id for subscription in self.subscriptions]
        info = []

        # if subscription_id in subscriptions_ids:
        #     idx = subscriptions_ids.index(subscription_id)
        #     subscription = self.subscriptions[idx]
        #     info.append(str(subscription))
        #     customer = self.customers[idx]
        #     info.append(str(customer))
        #     trainer = self.trainers[idx]
        #     info.append(str(trainer))
        #     equipment = self.equipment[idx]
        #     info.append(str(equipment))
        #     plan = self.plans[idx]
        #     info.append(str(plan))

        if subscription_id in subscriptions_ids:
            subscription = self.subscriptions[subscription_id - 1]
            info.append(str(subscription))

            customer = self.customers[subscription.customer_id - 1]
            info.append(str(customer))

            trainer = self.trainers[subscription.trainer_id - 1]
            info.append(str(trainer))

            plan = self.plans[subscription.trainer_id - 1]
            equipment = self.equipment[plan.equipment_id - 1]

            info.append(str(equipment))
            info.append(str(plan))

        return "\n".join(info)


import os
import warnings
import numpy as np
from matplotlib.colors import ColorConverter

import settings
CONFIG_KEYS = [
    # file names that are considered when computing networkwise properties
    "all_fnames",
    # name of the blacklist filename
    "blacklist_fname",
    # number of bootstrap samples, required by compstats
    # (and by some plotting routines)
    "bootstrap_samples",
    # coverage of the bootstrap interval, required by compstats
    # (and by some plotting routines)
    "bootstrap_coverage",
    # network density, 0.01 equals to 1\%
    # then the network has density*(n*(n-1))/2 links in it
    "density",
    # range of network densities, if sweeped over a range of network densities
    "density_range",
    # filenames corresponding to the first group,
    # when comparative statistics are made
    "group_1_mat_fnames",
    # filenames corresponding to second group
    # when comparative statistics are made
    "group_2_mat_fnames",
    # group labels, used in plotting
    "group_1_label",
    "group_2_label",
    # group colors, used in plotting
    "group_1_color",
    "group_2_color",
    # include mst, used when thresholding
    "include_mst",
    # which community detection algorithm to use
    # number of iterations used with the Louvain community detection algorithm
    # (Louvain algorithm is stochastic, thus runs can yeild different results)
    "n_it_comdet",
    # number of permutations used in the
    "n_it_permutation",
    # information about the network nodes
    "node_info_fname",
    # where to put all the output data
    "outdata_dir",
    # whether any comparisons are made in a paired fashion or not,
    # used in compstats
    "paired",
    # number of cpus used in the computation
    "n_cpus",
    # node properties
    "node_props",
    # global unweighted properties
    "global_uw_props",
    # global weighted properties
    "global_w_props"
]

def get_default_config():
    """
    Get a default config dictionary, which is filled as much is reasonably
    possible.

    Returns
    -------
    cfg : dict
        default brainnets config dict
    """
    cfg = {}
    return fill_defaults(cfg)

def check_full_config(cfg):
    """
    Checks the validity of all config parameters.
    See :py:func:require.

    Parameters
    ----------
    cfg : dict
        a brainnets config dict to be checked

    Returns
    -------
    valid : bool
        True, if all parameters were ok.

    Raises
    ------
    AssertionError
        If some property is not valid.
    """
    return require(cfg, CONFIG_KEYS)

def fill_defaults(cfg):
    """
    Fills in the default parameters for each key, for which no value is
    currently defined.

    Parameters
    ----------
    cfg : dict
        a brainnets config dict.

    Returns
    -------
    cfg : dict
        the (possibly updated) cfg dict
    """
    for key in CONFIG_KEYS:
        if key not in cfg:
            set_default(cfg, key)
    return cfg

def set_default(cfg, key):
    """
    Fills the default input variables to the extent reasonable
    defaults can be defined.

    Parameters
    ----------

    cfg : dict
        the brainnets config dict
    key : str
        the specific key of the config dictionary to be set as default.

    Returns
    -------
    cfg : dict
        the updated config dict.
    """
    val = ""
    if key is "all_fnames":
        val = None  # no proper default
    elif key is "blacklist_fname":
        val = None  # no proper default
    elif key is "bootstrap_samples":
        val = 10e5  # to be safe
    elif key is "bootstrap_coverage":
        val = 95  # pretty standard
    elif key is "density":
        val = 0.02  # corresponding to 2%, arbitrary
    elif key is "density_range":
        # arbitrary, but reasonable sweep for fine-grained networks:
        val = 2 ** np.linspace(-4, 4, 17) * 0.01
    elif key is "group_1_mat_fnames":
        val = None
    elif key is "group_2_mat_fnames":
        val = None
    elif key is "group_1_label":
        val = "group1"
    elif key is "group_2_label":
        val = "group2"
    elif key is "group_1_color":
        val = "red"
    elif key is "group_2_color":
        val = "blue"
    elif key is "include_mst":
        val = False  # do not include mst by default
    elif key is "n_it_comdet":
        val = 100
    elif key is "paired":
        val = None  # no proper default
    elif key is "outdata_dir":
        try:
            val = os.path.dirname(cfg["all_fnames"][0])
        except:
            try:
                val = os.path.dirname(cfg["group_1_mat_fnames"][0])
            except Exception:
                val = None
    elif key is "n_it_permutation":
        if "paired" in cfg and cfg["paired"] is True:
            val = "all"
        else:
            val = 10e5
    elif key is "node_info_fname":
        val = None  # no proper default
    elif key is "n_cpus":
        val = 1
    elif key is "node_props":
        val = settings.node_props
    elif key is "global_w_props":
        val = settings.global_w_props
    elif key is "global_uw_props":
        val = settings.global_uw_props
    elif key is "com_det_algo":
        val = "louvain"
    cfg[key] = val
    return cfg

def check_property(cfg, key):
    """
    Checks the validity (in a loose sense) of the brainnets
    config dictionary's (``cfg``) value corresponding to ``key``.key

    Parameters
    ----------
    cfg : dict
        brainnets config dict
    key : str
        the key of the dictionary, which should be checked

    Returns
    -------
    valid : bool
        True, if all parameters were ok.

    Raises
    ------
    AssertionError
        If the value of ``cfg[key]`` was not valid.
    """
    key_in_config = (key in cfg) and cfg[key] is not None
    assert key_in_config, "config key \"" + str(key) + "\" is not specified"

    props_tags = ["node_props", "global_uw_props", "global_w_props"]
    settings_props_list = [settings.node_props,
                           settings.global_uw_props,
                           settings.global_w_props]

    def _asm():
        return "config key " + str(key) + " is not properly set," + \
            "\n value: " + str(val)

    val = cfg[key]
    # check the actual assertions
    if key is "density":
        assert (0 <= val and val <= 1), _asm()

    elif key in ["group_1_color", "group_2_color"]:
        try:
            cc = ColorConverter()
            cc.to_rgba(val)
        except ValueError:
            raise AssertionError(_asm())

    elif key in ["all_fnames", "group_1_mat_fnames", "group_2_mat_fnames",
                 "node_info_fname", "blacklist_fname", "outdata_dir"]:
        if type(val) is not list:
            val = [val]
        for fname in val:
            assert os.path.exists(fname), "check key: " + key
    elif key == "bootstrap_samples":
        try:
            float(val)
            assert val > 10, _asm() + " (may be too low)"
        except:
            assert val == "all", _asm()
    elif key is "bootstrap_coverage":
        assert val > 0 and val < 101, _asm()
    elif key is "density_range":
        val = np.array(val)
        assert ((val <= 1) * (val >= 0)).all(), _asm()
    elif key in ["group_1_label", "group_2_label"]:
        assert len(val) > 0 and type(val) is str, _asm()
    elif key in ["paired", "include_mst"]:
        assert type(val) is bool, _asm()
    elif key is "n_it_comdet":
        assert val >= 1, _asm()
    elif key is "n_it_permutation":
        if type(val) is str:
            assert val == "all", _asm()
        else:
            assert val >= 4
            if key is "n_it_permutation" and val < 100:
                warnings.warn("Low number of permutations for key " + str(key)
                              + ": " + str(val))
    elif key is "n_cpus":
        assert (type(val) is int) and val >= 1
    elif key in props_tags:
        i = props_tags.index(key)
        props_should_be_in = settings_props_list[i]
        for v in val:
            assert v in props_should_be_in, _asm()
    elif key not in CONFIG_KEYS:
        warnings.warn('Omitting the check of custom config param ' + str(key))
    else:
        warnings.warn("The validity of " + str(key) +
                      " was not properly checked ")
    return True

def require(cfg, keys):
    """
    Checks the validity of config dictionary's values corresponding to the
    ``keys``.

    Parameters
    ----------
    cfg : dict
        the brainnets config dictionary
    keys : list of strings
        the validity of the keys to be checked

    Returns
    -------
    valid : bool
        True, if all parameters were ok.

    Raises
    ------
    AssertionError
        If at least one of the keys is not properly defined.
    """
    for key in keys:
        check_property(cfg, key)
    return True


import numpy as np
import matplotlib.pyplot as plt
#if using termux
import subprocess
import shlex
#end if
a=5
b=2
#defining function
def f(x):
	return(((a)**2)+((b)**2)-2*((a)*(b))*(np.cos(x-(a*x)/b)));

#defining derivative of f(x)
df=lambda x:(-2*(a)*(b)*(np.sin(x-((a*x)/b)))*(1-(a/b)));

#for maxima using gradient ascent
cur_x1=0.5
previous_step_size1=1
iters1=0
precision=0.000000001
alpha=0.0001
max_iters=100000000

while (previous_step_size1>precision)&(iters1<max_iters):
	prev_x=cur_x1
	cur_x1+=alpha*df(prev_x)
	previous_step_size1=abs(cur_x1-prev_x)
	iters1+=1
max_val=f(cur_x1)
k=np.sqrt(max_val)
print('maximum value  of x is',max_val)
#Plotting f(x)
x=np.linspace(-10,10,100)
y=f(x)
label_str = "$(a^2+b^2-2abcos(x-ax/b))$"
plt.plot(x,y,label=label_str)
#Labelling points
plt.plot(cur_x1,max_val,'.',label='point of maxima'  )
print("maximum distance is",k)

plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.grid()
plt.legend()
#plt.savefig('op1.png')
#if using termux
plt.savefig('/sdcard/Download/codes/opti/fig1.pdf')
subprocess.run(shlex.split("termux-open /sdcard/Download/codes/opti/fig1.pdf"))
#plt.show()


import csv
import simpy
import numpy as np
import datetime
import matplotlib.pyplot as plt

def parse_csv(file):
    # parses csv into to lists
    # convert service times to seconds
    # convert invocations into invocations/second

    with open(file, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        lines = 0
        lam = 0
        sum_lam = 0
        avg_service_times = []
        avg_arrival_rates = []
        weights = []
        for row in csv_reader:
            avg_service_times.append(int(row["AvgServiceTimeMillisec"])/1000)
            lam = int(row["Invocations30Days"])/(30*24*60*60)
            avg_arrival_rates.append(lam)
            sum_lam += lam
            lines += 1

        # compiles a list of weights to be used in a discrete distribution sampler
        for i in range(len(avg_service_times)):
            weights.append(avg_arrival_rates[i]/sum_lam)

    return avg_service_times, weights, sum_lam

class g:
    no_runs = 1 # used to repeat with different M
    no_trials = 5 # repeats each model this many times
    sim_duration = 60*60*24 # runs sim for this many simulated seconds
    f = 10861 # no. functions
    cold_start = 0.5 #cold start rate
    avg_service_times, weights, sum_lam = parse_csv('trace-final.csv')

class Request:
    def __init__(self, f_id):
        self.id = f_id

class Faas_Model:

    def __init__(self, trial_no, m, file_name):
        self.env = simpy.Environment()

        self.trial_no = trial_no
        self.m = m
        self.results_file = file_name

        # tracks status of each f 0: not in m, 1: idle, 2: executing
        self.status = np.ones(self.m).tolist() + np.zeros(g.f-self.m).tolist()

        # initializes memory with the first m functions all idle
        self.idle_queue = np.arange(self.m).tolist()

        # measures
        self.request_counter = 0
        self.cold_start_counter = 0
        self.lost_request_counter = 0
        self.memory_full_loss = 0
        self.already_running_loss = 0
        self.completions = 0

        # lists for graphs
        self.obs_time = []
        self.obs_cold_ratio = []
        self.obs_loss_rate = []

    def generate_requests(self):
        # generates requests using aggregate poisson process
        # sample a discrete distribution to assign the request a function

        while True:

            yield self.env.timeout(generate_time_to_request())

            self.request_counter += 1

            r_id = int(np.random.choice(a=g.f, p=g.weights)) # split poisson to stream f
            r = Request(r_id)

            self.env.process(self.service_request(r))

    def service_request(self, request):

        # check if f is running and reject request
        if self.status[request.id] == 2:
            self.already_running_loss += 1
            self.lost_request_counter += 1

        # check if f is idle and start executing
        elif self.status[request.id] == 1:

            self.status[request.id] = 2
            self.env.process(self.complete_request(request))

        # if f is not in memory check if everything in memory is executing
        else:
            self.mem_in_use = self.status.count(2)

            if self.mem_in_use >= self.m:
                # m is full reject request
                self.memory_full_loss += 1
                self.lost_request_counter += 1

            else:
                # Check top of the idle queue for which function to remove
                evict = self.idle_queue[0]
                self.status[evict] = 0
                self.idle_queue = remove_values_from_list(self.idle_queue, evict)

                self.status[request.id] = 2

                self.cold_start_counter += 1

                # sample cold start time
                yield self.env.timeout(generate_time_to_start())

                self.env.process(self.complete_request(request))

    def complete_request(self, request):
        # remove f from idle queue
        self.idle_queue = remove_values_from_list(self.idle_queue, request.id)

        # sample service time
        yield self.env.timeout(generate_time_to_service(request.id))

        self.completions += 1

        # return to idling, add f to the end of the idle queue
        self.status[request.id] = 1
        self.idle_queue.append(request.id)

    def observe(self):
        # records measure every second
        while True:
            try:

                self.obs_cold_ratio.append(self.cold_start_counter/self.request_counter)
                self.obs_time.append(self.env.now)
                self.obs_loss_rate.append(self.lost_request_counter/self.obs_time[-1])
            except:
                pass
            yield self.env.timeout(1)

    def run(self):

        # start sim
        self.env.process(self.generate_requests())
        self.env.process(self.observe())
        self.env.run(until=g.sim_duration)

        # Output to terminal
        print(f'\nTrial {self.trial_no+1} of {g.no_trials}')
        print(f'Simulated for {str(datetime.timedelta(seconds=g.sim_duration))}')
        print(f'M Capacity: {self.m}')

        print(f'\nRequests made: {self.request_counter}')
        print(f'Requests lost: {self.lost_request_counter}')
        print(f'Memory full lost: {self.memory_full_loss}')
        print(f'Already Running lost: {self.already_running_loss}')
        print(f'Completions: {self.completions}')
        print(f'Cold starts: {self.cold_start_counter}')

        print(f'\nCold start ratio = {self.obs_cold_ratio[-1]}')
        print(f'Loss rate = {self.obs_loss_rate[-1]}\n')

        # Output to graphs
        ax.plot(model.obs_time, model.obs_cold_ratio, label=f'{self.m}')
        ax2.plot(model.obs_time, model.obs_loss_rate, label=f'{self.m}')

        # Output to csv
        with open(self.results_file, "a") as f:
            writer = csv.writer(f, delimiter=',')
            results_to_write = [self.trial_no,
                                self.obs_cold_ratio[-1],
                                self.obs_loss_rate[-1]]
            writer.writerow(results_to_write)

def generate_time_to_request():
    # aggregated poisson
    return np.random.exponential(scale=(1.0/g.sum_lam))

def generate_time_to_service(id):
    # exponential service time sampler
    return np.random.exponential(scale=(g.avg_service_times[id]))

def generate_time_to_start():
    # exponential cold start time sampler
    return np.random.exponential(scale=1.0/g.cold_start)

def remove_values_from_list(l, val):
    # removes all values = val from list l
    c = l.count(val)
    for i in range(c):
        l.remove(val)

    return l

# initialize graphs
fig = plt.figure(figsize=(12, 6))

ax = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

# each loop here modifies the size of m
for run in range(g.no_runs):
    m = 40 + run * 5

    #creates a csv file for each size of m simulated and writes coloumn headers
    file_name = f'sim_out/trial_results_{m}.csv'

    with open(file_name, "w") as f:
        writer = csv.writer(f, delimiter=',')
        coloumn_headers = ["run", "cold_start_ratio", "loss_rate"]
        writer.writerow(coloumn_headers)

    #repeats this capacity
    for trial in range(g.no_trials):
        model = Faas_Model(trial, m, file_name)
        model.run()

#finializes and shows graphs
ax.set_title('Cold Start Ratio')
ax2.set_title('Loss Rate')

ax.set_ylim([0, 0.3])
ax.set_xlim(left=0)

ax2.set_ylim([0, 100])
ax2.set_xlim(left=0)

plt.show()


class Node:
    def __init__(self):
        self.end = False
        self.next = {}

class Trie:

    def __init__(self):
        self.node = Node()

    def insert(self, word: str) -> None:
        temp = self.node
        for letter in word:
            if letter in temp.next:
                temp = temp.next[letter]
            else:
                temp.next[letter] = Node()
                temp = temp.next[letter]
        temp.end = True

    def search(self, word: str) -> bool:
        temp = self.node
        for letter in word:
            if letter in temp.next:
                temp = temp.next[letter]
            else:
                return False
        return temp.end

    def startsWith(self, prefix: str) -> bool:
        temp = self.node
        for letter in prefix:
            if letter in temp.next:
                temp = temp.next[letter]
            else:
                return False
        return True

# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)


# coding: utf-8
from PyQt4.QtCore import QVariant
from qgis.gui import QgsQueryBuilder
from qgis.core import (QgsFeature,
                       QgsField, QgsGeometry,
                       QgsMapLayerRegistry,
                       QgsPoint,
                       QgsVectorLayer)

# Prepare data to demonstrate the QgsQueryBuilder class

# create layer
vl = QgsVectorLayer("Point?crs=epsg:4326&index=yes",
                    "temporary_points", "memory")
pr = vl.dataProvider()

# add fields
pr.addAttributes([
    QgsField("name", QVariant.String),
    QgsField("age", QVariant.Int),
    QgsField("size", QVariant.Double)
])
vl.updateFields()  # tell the vector layer to fetch changes from the provider

infos = [
    [10, 10, "John", 24, 1.73],
    [40, -60, "Paul", 29, 1.86],
    [60, 5, "George", 34, 1.69],
    [0, 45, "Ringo", 73, 1.75]
]

# add features
for i in infos:
    fet = QgsFeature()
    fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(i[0], i[1])))
    fet.setAttributes(i[2:5])
    pr.addFeatures([fet])

# update layer's extent when new features have been added
# because change of extent in provider is not propagated to the layer
vl.updateExtents()

QgsMapLayerRegistry.instance().addMapLayer(vl)

query_builder = QgsQueryBuilder(vl)
query_builder.setSql(u'"age" > 30')
query_builder.accept()
query_builder.show()


"""
Write a python program to check whether a given number is palindrome or not using a python program.

"""
number = int(input("ENTER A NUMBER : "))

if len(str(number)) == 1:
    print("THE NUMBER", number,"ONLY HAS A SINGLE DIGIT")

else:
    rem, rev, temp = 0, 0, number
    while temp > 0:
        rem = temp % 10
        rev = (rev * 10) + rem
        temp //= 10

    if number == rev:
        print(number, "IS A PALINDROME")

    else:
        print(number, "IS NOT A PALINDROME")


import os
import sys
import time
import yaml
from mss import mss

def capture_screen(file_name):
    dir_path = os.path.dirname(file_name)
    if dir_path and not os.path.exists(dir_path):
        os.makedirs(dir_path)
    with mss() as capture:
        capture.shot(mon=-1, output=file_name)
    return file_name

def get_current_dir(*args):
    """
    :param args: use like os.path.join(path, *path)
    :return: absolute path
    For Linux OS
    """
    current_path = os.path.dirname(os.path.realpath(sys.argv[0]))
    if args:
        path = os.path.join(current_path, *args)
    else:
        path = current_path
    return "/".join(path.split("\\"))

class __Logging:
    def __init__(self, output=True, divide='Hour'):
        """
        :param output: default when logging file also print msg, if False will not print
        :param divide: default create new log file every hour, if value == 'day', create file every day
        """
        self.__report_path = os.path.join(get_current_dir(), 'Test_Report')
        self.__log_path = os.path.join(self.__report_path, 'log')
        self.divide = divide
        if not os.path.exists(self.__report_path):
            os.mkdir(self.__report_path)
        if not os.path.exists(self.__log_path):
            os.mkdir(self.__log_path)
        self.style = '\033[1;31;1m#msg#\033[0m'
        self.print = output

    def log(self, rank, _log):
        # dynamic refresh file name according time each hour
        if self.divide.lower() == 'day':
            log_name = time.strftime("%Y-%m-%d", time.localtime()) + ".log"
        elif 'mb' in self.divide.lower():
            log_name = time.strftime("%Y-%m-%d-%H-%M", time.localtime()) + ".log"
            file_size = int(self.divide.lower().replace('mb', ''))
            if os.path.getsize(log_name) > file_size * 1024 * 1024:
                log_name = time.strftime("%Y-%m-%d-%H-%M", time.localtime()) + ".log"
        else:
            log_name = time.strftime("%Y-%m-%d-%H", time.localtime()) + ".log"
        log_file_path = os.path.join(self.__log_path, log_name)
        if not os.path.exists(self.__log_path):
            os.makedirs(self.__log_path)

        cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print_msg = "{} \t {} \t {}".format(cur_time, rank, _log)
        line = "[{}] \t".format(cur_time) + print_msg + '\n'

        if not os.access(log_file_path, os.F_OK):
            with open(log_file_path, "w", encoding='utf-8') as f:
                f.writelines(line)
        else:
            with open(log_file_path, "a", encoding='utf-8') as f:
                f.writelines(line)

        if self.print:
            print(self.style.replace('#msg#', print_msg))

class Logger(__Logging):
    def __init__(self, output=True):
        super().__init__(output=output)
        self.log_level = self.__read_debug_level()

    @staticmethod
    def __analyze_name(name):
        file_name = name
        if os.path.exists(file_name):
            name, ext = os.path.splitext(file_name)
            file_name = name + time.strftime("%H%M%S", time.localtime()) + ext
        return file_name

    @staticmethod
    def __read_debug_level():
        config_path = get_current_dir('Test_Data', 'td_common', 'global_config.yml')
        if not os.path.exists(config_path):
            return 3  # error level
        else:
            with open(config_path) as f:
                return int(yaml.safe_load(f)['log']['log_level'])

    def info(self, msg, name=''):
        if self.log_level > 2:
            rank = '[INFO]'
            self.style = '\033[1;21;1m#msg#\033[0m'
            self.log(rank, msg)
            if name != '':
                capture_screen(self.__analyze_name(name))

    def warning(self, msg, name=''):
        if self.log_level > 1:
            self.style = '\033[1;33;1m#msg#\033[0m'
            rank = '[WARNING]'
            self.log(rank, msg)
            if name != '':
                capture_screen(self.__analyze_name(name))

    def error(self, msg, name=''):
        if self.log_level > 0:
            self.style = '\033[1;31;1m#msg#\033[0m'
            rank = '[ERROR]'
            self.log(rank, msg)
            if name != '':
                capture_screen(self.__analyze_name(name))

    def debug(self, msg, name=''):
        if self.log_level > 3:
            self.style = '\033[1;21;1m#msg#\033[0m'
            rank = '[DEBUG]'
            self.log(rank, msg)
            if name != '':
                capture_screen(self.__analyze_name(name))

log = Logger()


def partition( arr , l , h ) :
    piv = l
    i = l

    for j in range(i + 1, h) :
        if arr[j] < arr[piv] :
            i+=1
            arr[i],arr[j] = arr[j],arr[i]

    arr[i] , arr[piv] = arr[piv] , arr[i]
    # print(arr)
    return i

def quickSort(arr , l , h ) :
    if  l < h :
        i = partition(arr , l , h )
        quickSort(arr, l , i)
        quickSort(arr , i+1 , h )

if __name__ == "__main__" :

    arr = [3,4,1,5,2]
    arr = [14, 12, 70, 15, 95, 65, 22, 30]

    quickSort(arr , 0 , len(arr))
    # i = partition(arr , 0 , len(arr) )
    print(arr)


# -*- coding: utf-8 -*-
# __author__ = 'zhujuan'

"""报告计算VIF方差膨胀因子"""

import os
import re
import glob
from biocluster.workflow import Workflow
from comm_table import CommTableWorkflow
from mbio.packages.meta.common_function import envname_restore

class EnvVifWorkflow(CommTableWorkflow):
    def __init__(self, wsheet_object):
        self._sheet = wsheet_object
        super(EnvVifWorkflow, self).__init__(wsheet_object)
        options = [
            {"name": "update_info", "type": "string"},
            {"name": "geneset_id", "type": "string"},
            {"name": "anno_id", "type": "string"},
            {"name": "group_id", "type": "string"},
            {"name": "params", "type": "string"},
            {"name": "abund_file", "type": "infile", "format": "meta.otu.otu_table"},
            {"name": "group_detail", "type": "string"},
            {"name": "group", "type": "infile", "format": "meta.otu.group_table"},
            {"name": "env_id", "type": "string"},
            {"name": "env_labs", "type": "string"},
            {"name": "viflim", "type": "int", "default": 10},
            {"name": "env_file", "type": "infile", 'format': "meta.otu.group_table"},
            {"name": "abund_method", "type": "string"},
            {"name": "main_id", "type": "string"},
        ]
        self.add_option(options)
        self.set_options(self._sheet.options())
        self.vif = self.add_tool('statistical.env_vif')
        self.sort_samples = self.add_tool("meta.otu.sort_samples_mg")

    def run_sort_samples(self):
        self.logger.info("正常运行啦")
        if self.option("abund_file").is_set:
            abund_table = self.option("abund_file")
        else:
            self.logger.info("对啦对啦")
            abund_table = self.abundance.option("out_table").prop['path']
        self.logger.info(abund_table)
        # self.sort_samples = self.add_tool("meta.otu.sort_samples_mg")
        self.sort_samples.set_options({
            "in_otu_table": abund_table,
            "group_table": self.option("group"),
            "sample_del_warn": "T"
        })
        self.sort_samples.on("end", self.run_env_vif)
        self.sort_samples.run()

    def run_env_vif(self):
        abund_table = self.sort_samples.option("out_otu_table").prop['path']
        num_lines = open(abund_table, 'r').readlines()
        if len(num_lines) < 3:
            raise OptionError('丰度表数据少于2行，请重新设置参数!', code="12801501")
        options = {
            "abundtable": self.sort_samples.option("out_otu_table"),
            "envtable": self.option('env_file'),
            "viflim": self.option("viflim")
        }
        self.vif.set_options(options)
        self.vif.on('end', self.set_db)
        self.vif.run()

    def set_db(self):
        self.logger.info("正在写入mongo数据库")
        api_env_vif = self.api.api("metagenomic.env_vif")
        env_result = glob.glob(self.vif.output_dir + "/*")
        for file in env_result:
            if re.search("final_.*_vif.txt", file):
                final_path = file
                api_env_vif.add_env_vif_detail(final_path, "after_vif", self.option("main_id"))
            elif re.search("raw_.*_vif.txt", file):
                raw_path = file
                api_env_vif.add_env_vif_detail(raw_path, "before_vif", self.option("main_id"))
        self.end()

    def run(self):
        if self.option("abund_file").is_set:
            self.run_sort_samples()
        else:
            #self.run_get_abund_table()
            self.run_abundance(self.run_sort_samples)
            self.abundance.run()
        self.output_dir = self.vif.output_dir
        super(EnvVifWorkflow, self).run()

    @envname_restore
    def end(self):
        env_result = glob.glob(self.vif.output_dir + "/*")
        result_dir = self.add_upload_dir(self.output_dir)
        if re.search("cca_vif.txt", env_result[0]):
            result_dir.add_relpath_rules([
                [".", "", "VIF方差膨胀因子分析结果目录", 0, "120204"],
                ["./raw_cca_vif.txt", "txt", "筛选前VIF方差膨胀因子分析结果表", 0, "120205"],
                ["./final_cca_vif.txt", "txt", "筛选后VIF方差膨胀因子分析结果表", 0, "120206"],
                ["./DCA.txt", "txt", "判断计算VIF方差膨胀因子分析的方法文件", 0, "120207"]
            ])
        else:
            result_dir.add_relpath_rules([
                [".", "", "VIF方差膨胀因子分析结果目录", 0, "120204"],
                ["./raw_rda_vif.txt", "txt", "筛选前VIF方差膨胀因子分析结果表", 0, "120205"],
                ["./final_rda_vif.txt", "txt", "筛选后VIF方差膨胀因子分析结果表", 0, "120206"],
                ["./DCA.txt", "txt", "判断计算VIF方差膨胀因子分析的方法文件", 0, "120207"]
            ])
        super(EnvVifWorkflow, self).end()


import matplotlib.pyplot as plt
import numpy as np
from src.lib.intcode import Amplifier

class Arcade:
	def __init__(self, verbose=False):
		self.board = {}
		self.score = 0
		self.ball = None
		self.paddle = None
		self.verbose = verbose

	def plot_game(self):
		colors = [0, 1, 2, 1, 3]
		r = np.zeros((max(v[1] for v in self.board.keys()) + 1, max(v[0] for v in self.board.keys()) + 1))
		for (pos_x, pos_y), c in self.board.items():
			r[pos_y, pos_x] = colors[c]
		plt.imshow(r)
		plt.show()

	def next_move(self):
		if self.verbose:
			print(f'## Ball at {self.ball}, paddle at {self.paddle}, returns {np.sign(self.ball[0] - self.paddle[0])}')
		return np.sign(self.ball[0] - self.paddle[0])

if __name__ == '__main__':
	with open('../inputs/Day13_input.txt', 'r') as f:
		program = list(map(int, f.read().strip().split(',')))

	outputs = []
	amp = Amplifier(program[:])
	arcade = Arcade()
	while not amp.done:
		x, y, tile_id = amp.run(), amp.run(), amp.run()
		arcade.board[(x, y)] = tile_id
	print(f"The result of first star is {sum(tile_id == 2 for tile_id in arcade.board.values())}.")

	program[0] = 2
	amp = Amplifier(program[:])
	arcade = Arcade()
	start_playing = False
	while not amp.done:
		if start_playing:
			amp.inputs = [arcade.next_move()]
		x, y, value = amp.run(), amp.run(), amp.run()
		if (x, y) == (-1, 0):
			arcade.score = value
			start_playing = True
			if arcade.verbose:
				print(f"Current score is {arcade.score}")
		else:
			if value == 4:
				arcade.ball = (x, y)
				if arcade.verbose:
					print(f"Ball is at {(x, y)}")
			elif value == 3:
				arcade.paddle = (x, y)
				if arcade.verbose:
					print(f"Paddle is at {(x, y)}")
			arcade.board[(x, y)] = value

	print(f'The result of second star is {arcade.score}.')


import pytest
import numpy as np
from Visualization.main2 import monte_carlo

def seed(num):
    np.random.seed(num)
    return np.random.randint(0, 1000, 10000000)

def expert(trials):

    score = {
        999: 100,
        777: 200,
        555: 50,
        333: 15,
        111: 10
    }
    balance = 0

    for i in trials:
        value = score.get(i)
        if value:
            balance += value
        elif i % 100 == 77:
            balance += 5
        elif i % 10 == 7:
            balance += 3
        elif i % 100 == 0:
            balance += 2
        elif i % 10 == 0:
            balance += 1

    res = round(balance / len(trials), 5)
    return res

@pytest.mark.parametrize(
        'trials, result',
        [[[999], 100], [[777], 200], [[555], 50], [[333], 15],
         [[111], 10], [[677], 5], [[667], 3], [[100], 2], [[10], 1]]
)
def test_conditions(trials, result):
    assert monte_carlo(trials) == result,  f'Условие для {trials} реализовано некорректно'

@pytest.mark.parametrize(
        'num', [42, 13, 7]
)
def test_result(num):
    assert monte_carlo(seed(num)) == expert(seed(num))


import xlsxwriter

def convert_xlsx(dicionario):
    workbook = xlsxwriter.Workbook('Expenses01.xlsx')
    worksheet = workbook.add_worksheet()
    row = 0

    def formatar(lista):
        spreadsheet = []
        spreadsheet.append(define_protocolo(lista[0])) #número de protocolo
        spreadsheet.append(lista[4].upper()) #nome da cidade
        spreadsheet.append(compara(lista[5], 0)) #causa relatada
        spreadsheet.append(compara(lista[5], 1)) #prazo SLA
        spreadsheet.append('SIM') #abriu chamado?
        spreadsheet.append((lista[3].split(' ')[0] +' '+ lista[3].split(' ')[1][1:6] + ':00')) #horário inicial
        spreadsheet.append((lista[6].split(' ')[0] +' '+ lista[3].split(' ')[1][1:6] + ':00')) #horário final
        if lista[1] =='WIKI TELECOM':
            spreadsheet.append('WIKITELECOM') #operadora
            spreadsheet.append('ADESÃO IEMA') #contrato
        elif lista[1] =='OI':
            spreadsheet.append('OI')
            spreadsheet.append('ADESÃO MPMA')

        return spreadsheet

    def define_protocolo(protocolo):
        if protocolo[0] == '0': #se começar com 0 não retorna nada, pois não existe protocolo
            return None
        else:
            return protocolo
    def compara(causa, flag):

        #probabilidade de ocorrencias
        casos = {
        'INDISPONIBILIDADE DO LINK': 0,
        'LINK FORA DO AR': 0,
        'SEM LINK': 0,
        'ROMPIMENTO DE FIBRA': 0,
        'LENTIDÃO': 1,
        'INTERNET LENTA': 1,
        'LENTIDÃO DO LINK': 1,
        'LINK LENTO': 1,
        'DEFEITO NO PFSENSE': 2,
        'PFSENSE COM DEFEITO': 2,
        'PROBLEMA NO PFSENSE': 2,
        'REFAZER PFSENSE': 2,
        'SEM ENERGIA': 3,
        'FALTA DE ENERGIA': 3
        }
        resposta = '?'
        for caso in casos:

            if caso == causa.upper():
                resposta = caso

        #ocorrencias reais usadas na planilha
        causa_real = [
            'LINK FORA DO AR', #0
            'LENTIDÃO DO LINK', #1
            'DEFEITO NO PFSENSE', #2
            'SEM ENERGIA' #3
        ]

        if resposta !='?':
            for i in range(4):
                if casos[resposta] == i:
                    resposta = causa_real[i]

        if flag == 0:
            return resposta
        if flag == 1:
            if resposta =='?':
                return resposta

            elif casos[resposta] == 0 or casos[resposta] == 1:
                return '08hs'

            else:
                return '04hs'

    for num in dicionario:
        col = 0
        formatado = formatar(dicionario[num])
        for lista in formatado:
            worksheet.write(row, col, lista)
            col = col + 1
        row +=1

    workbook.close()


from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from sklearn.datasets import load_iris
import numpy as np

iris = load_iris()
features = iris.data
label = iris.target
dt_clf = DecisionTreeClassifier()

# 5개의 폴드세트로 분리하는 KFold객체와 폴드 세트별 정확도를 담을 리스트객체 생성.
kfold = KFold(n_splits=5, random_state=11)
cv_accuracy =[]

print("붓꽃 데이터 세트 크기 :",features.shape[0])

n_iter =0
# print(kfold.split(features))

# KFold 객체의 split() 호출하면 폴드 별 학습용, 검증용 테스트의 로우 인덱스를 array로 반환
# kfold.split() 하면 학습과 검증용 index가 만들어짐
for train_index, test_index in kfold.split(features): # kfold.split(features)은 ndarray의 위치 인덱스를 반환해줌
    # kfold.split() 으로 반환된 인덱스를 이용하여 학습용, 검증용 데스트 데이터 추출
    x_train, x_test = features[train_index], features[test_index]
    y_train, y_test = label[train_index], label[test_index]
    # print(train_index,test_index)
    #  학습 및 예측
    dt_clf.fit(x_train,y_train)
    pred = dt_clf.predict(x_test)
    n_iter +=1

    # 반복시 마다 정확도 측정
    accuracy = np.round(accuracy_score(y_test,pred),4)
    train_size = x_train.shape[0]
    test_size = x_test.shape[0]

    print("\n {} 교차 검증 정확도 : {}, 학습 데이터 크기 : {}, 검증 데이터 크기 : {}".format(n_iter,accuracy,train_size,test_size))
    print(" {} 검증 세트 인덱스 : {}".format(n_iter,test_index))

    cv_accuracy.append(accuracy)

# 개별 iteration별 정확도를 합하여 평균 정확도 계산
print("\n 평균 검증 정확도 : ", np.mean(cv_accuracy))


import requests
import time
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

##Meraki Constants
MERAKI_URL = 'https://dashboard.meraki.com/api/v0/'
headers = {'x-cisco-meraki-api-key': format(str('6bec40cf957de430a6f1f2baa056b99a4fac9ea0')),'Content-Type': 'application/json'}
OrgKey = '681155' # Meraki Sandbox

print("Start of Script")
print("\nGathering Organization Info from Sandbox Meraki Organization # : " + OrgKey)
networks = requests.get(MERAKI_URL + 'organizations' + '/' + OrgKey + '/' + 'networks', headers=headers, verify=False).json()

payload = {'id': 'L_566327653141843049', 'organizationId': '681155', 'name': 'STR-1272', 'timeZone': 'America/New_York', 'tags': None, 'type': 'combined', 'disableMyMerakiCom': False, 'disableRemoteStatusPage': True}

#networks = requests.post(MERAKI_URL + 'organizations' + '/' + OrgKey + '/' + 'networks', headers=headers, verify=False,data=json.dumps(payload))

time.sleep(1)

print("Network Data Gathered")

for networks in networks:

    if 'combined' in networks['type']:

        devices = requests.get(MERAKI_URL + 'organizations' + '/' + OrgKey +
                               '/' + 'networks' + '/' + networks['id'] + '/' +
                               'devices', headers=headers, verify=False).json()

        time.sleep(0.10)

        for devices in devices:

            if 'MX' in devices['model']:

                # print("\nNow getting Cell Information from " + devices['model'] +
                #      " " + devices['serial'])

                clients = requests.get(MERAKI_URL + 'devices' + '/' + devices['serial'] +
                                      '/' + 'clients?timespan=2592000', headers=headers, verify=False).json()
                try:

                 for clients in clients:
                    #print(clients)

                    if clients['vlan'] == 5:

                     policy = requests.get(MERAKI_URL + '/' + 'networks' + '/' + networks['id'] + '/' +
                               'clients/' + clients['mac'] + '/policy', headers=headers, verify=False).json()

                     for policy in policy:
                         print(policy)

                except KeyError as e:

                    badkey = e.args[0]
                    print("\nError in " + clients['ip'] + " at this Key : " + badkey + " for " + networks['name'] + "\n")

print("End of Script")


from typing import Optional, Text, Dict, Any, Union, List, Tuple, TYPE_CHECKING
import copy
import numpy as np

import rasa.shared.utils.common
import rasa.shared.utils.io
import rasa.nlu.utils.bilou_utils
from rasa.shared.constants import NEXT_MAJOR_VERSION_FOR_DEPRECATIONS
from rasa.nlu.constants import NUMBER_OF_SUB_TOKENS
import rasa.utils.io as io_utils
from rasa.utils.tensorflow.constants import (
    LOSS_TYPE,
    SIMILARITY_TYPE,
    EVAL_NUM_EXAMPLES,
    EVAL_NUM_EPOCHS,
    EPOCHS,
    SOFTMAX,
    MARGIN,
    AUTO,
    INNER,
    COSINE,
    CROSS_ENTROPY,
    TRANSFORMER_SIZE,
    NUM_TRANSFORMER_LAYERS,
    DENSE_DIMENSION,
    CONSTRAIN_SIMILARITIES,
    MODEL_CONFIDENCE,
)
from rasa.shared.nlu.constants import (
    ACTION_NAME,
    INTENT,
    ENTITIES,
    SPLIT_ENTITIES_BY_COMMA,
)
from rasa.shared.core.constants import ACTIVE_LOOP, SLOTS
from rasa.core.constants import DIALOGUE
from rasa.shared.exceptions import InvalidConfigException

if TYPE_CHECKING:
    from rasa.nlu.extractors.extractor import EntityTagSpec
    from rasa.nlu.tokenizers.tokenizer import Token

def normalize(values: np.ndarray, ranking_length: Optional[int] = 0) -> np.ndarray:
    """Normalizes an array of positive numbers over the top `ranking_length` values.

    Other values will be set to 0.
    """
    new_values = values.copy()  # prevent mutation of the input
    if 0 < ranking_length < len(new_values):
        ranked = sorted(new_values, reverse=True)
        new_values[new_values < ranked[ranking_length - 1]] = 0

    if np.sum(new_values) > 0:
        new_values = new_values / np.sum(new_values)

    return new_values

def update_similarity_type(config: Dict[Text, Any]) -> Dict[Text, Any]:
    """
    If SIMILARITY_TYPE is set to 'auto', update the SIMILARITY_TYPE depending
    on the LOSS_TYPE.
    Args:
        config: model configuration

    Returns: updated model configuration
    """
    if config.get(SIMILARITY_TYPE) == AUTO:
        if config[LOSS_TYPE] == CROSS_ENTROPY:
            config[SIMILARITY_TYPE] = INNER
        elif config[LOSS_TYPE] == MARGIN:
            config[SIMILARITY_TYPE] = COSINE

    return config

def update_deprecated_loss_type(config: Dict[Text, Any]) -> Dict[Text, Any]:
    """If LOSS_TYPE is set to 'softmax', update it to 'cross_entropy' since former is deprecated.

    Args:
        config: model configuration

    Returns:
        updated model configuration
    """
    # TODO: Completely deprecate this with 3.0
    if config.get(LOSS_TYPE) == SOFTMAX:
        rasa.shared.utils.io.raise_deprecation_warning(
            f"`{LOSS_TYPE}={SOFTMAX}` is deprecated. "
            f"Please update your configuration file to use"
            f"`{LOSS_TYPE}={CROSS_ENTROPY}` instead.",
            warn_until_version=NEXT_MAJOR_VERSION_FOR_DEPRECATIONS,
        )
        config[LOSS_TYPE] = CROSS_ENTROPY

    return config

def align_token_features(
    list_of_tokens: List[List["Token"]],
    in_token_features: np.ndarray,
    shape: Optional[Tuple] = None,
) -> np.ndarray:
    """Align token features to match tokens.

    ConveRTTokenizer, LanguageModelTokenizers might split up tokens into sub-tokens.
    We need to take the mean of the sub-token vectors and take that as token vector.

    Args:
        list_of_tokens: tokens for examples
        in_token_features: token features from ConveRT
        shape: shape of feature matrix

    Returns:
        Token features.
    """
    if shape is None:
        shape = in_token_features.shape
    out_token_features = np.zeros(shape)

    for example_idx, example_tokens in enumerate(list_of_tokens):
        offset = 0
        for token_idx, token in enumerate(example_tokens):
            number_sub_words = token.get(NUMBER_OF_SUB_TOKENS, 1)

            if number_sub_words > 1:
                token_start_idx = token_idx + offset
                token_end_idx = token_idx + offset + number_sub_words

                mean_vec = np.mean(
                    in_token_features[example_idx][token_start_idx:token_end_idx],
                    axis=0,
                )

                offset += number_sub_words - 1

                out_token_features[example_idx][token_idx] = mean_vec
            else:
                out_token_features[example_idx][token_idx] = in_token_features[
                    example_idx
                ][token_idx + offset]

    return out_token_features

def update_evaluation_parameters(config: Dict[Text, Any]) -> Dict[Text, Any]:
    """
    If EVAL_NUM_EPOCHS is set to -1, evaluate at the end of the training.

    Args:
        config: model configuration

    Returns: updated model configuration
    """

    if config[EVAL_NUM_EPOCHS] == -1:
        config[EVAL_NUM_EPOCHS] = config[EPOCHS]
    elif config[EVAL_NUM_EPOCHS] < 1:
        raise ValueError(
            f"'{EVAL_NUM_EXAMPLES}' is set to "
            f"'{config[EVAL_NUM_EPOCHS]}'. "
            f"Only values > 1 are allowed for this configuration value."
        )

    return config

def load_tf_hub_model(model_url: Text) -> Any:
    """Load model from cache if possible, otherwise from TFHub"""

    import tensorflow_hub as tfhub

    # needed to load the ConveRT model
    # noinspection PyUnresolvedReferences
    import tensorflow_text
    import os

    # required to take care of cases when other files are already
    # stored in the default TFHUB_CACHE_DIR
    try:
        return tfhub.load(model_url)
    except OSError:
        directory = io_utils.create_temporary_directory()
        os.environ["TFHUB_CACHE_DIR"] = directory
        return tfhub.load(model_url)

def _replace_deprecated_option(
    old_option: Text,
    new_option: Union[Text, List[Text]],
    config: Dict[Text, Any],
    warn_until_version: Text = NEXT_MAJOR_VERSION_FOR_DEPRECATIONS,
) -> Dict[Text, Any]:
    if old_option not in config:
        return {}

    if isinstance(new_option, str):
        rasa.shared.utils.io.raise_deprecation_warning(
            f"Option '{old_option}' got renamed to '{new_option}'. "
            f"Please update your configuration file.",
            warn_until_version=warn_until_version,
        )
        return {new_option: config[old_option]}

    rasa.shared.utils.io.raise_deprecation_warning(
        f"Option '{old_option}' got renamed to "
        f"a dictionary '{new_option[0]}' with a key '{new_option[1]}'. "
        f"Please update your configuration file.",
        warn_until_version=warn_until_version,
    )
    return {new_option[0]: {new_option[1]: config[old_option]}}

def check_deprecated_options(config: Dict[Text, Any]) -> Dict[Text, Any]:
    """Update the config according to changed config params.

    If old model configuration parameters are present in the provided config, replace
    them with the new parameters and log a warning.

    Args:
        config: model configuration

    Returns: updated model configuration
    """
    # note: call _replace_deprecated_option() here when there are options to deprecate

    return config

def check_core_deprecated_options(config: Dict[Text, Any]) -> Dict[Text, Any]:
    """Update the core config according to changed config params.

    If old model configuration parameters are present in the provided config, replace
    them with the new parameters and log a warning.

    Args:
        config: model configuration

    Returns: updated model configuration
    """
    # note: call _replace_deprecated_option() here when there are options to deprecate
    new_config = {}
    if isinstance(config.get(TRANSFORMER_SIZE), int):
        new_config = override_defaults(
            new_config,
            _replace_deprecated_option(
                TRANSFORMER_SIZE, [TRANSFORMER_SIZE, DIALOGUE], config
            ),
        )

    if isinstance(config.get(NUM_TRANSFORMER_LAYERS), int):
        new_config = override_defaults(
            new_config,
            _replace_deprecated_option(
                NUM_TRANSFORMER_LAYERS, [NUM_TRANSFORMER_LAYERS, DIALOGUE], config
            ),
        )

    if isinstance(config.get(DENSE_DIMENSION), int):
        new_config = override_defaults(
            new_config,
            _replace_deprecated_option(
                DENSE_DIMENSION, [DENSE_DIMENSION, INTENT], config
            ),
        )
        new_config = override_defaults(
            new_config,
            _replace_deprecated_option(
                DENSE_DIMENSION, [DENSE_DIMENSION, ACTION_NAME], config
            ),
        )
        new_config = override_defaults(
            new_config,
            _replace_deprecated_option(
                DENSE_DIMENSION, [DENSE_DIMENSION, ENTITIES], config
            ),
        )
        new_config = override_defaults(
            new_config,
            _replace_deprecated_option(
                DENSE_DIMENSION, [DENSE_DIMENSION, SLOTS], config
            ),
        )
        new_config = override_defaults(
            new_config,
            _replace_deprecated_option(
                DENSE_DIMENSION, [DENSE_DIMENSION, ACTIVE_LOOP], config
            ),
        )

    config.update(new_config)
    return config

def entity_label_to_tags(
    model_predictions: Dict[Text, Any],
    entity_tag_specs: List["EntityTagSpec"],
    bilou_flag: bool = False,
    prediction_index: int = 0,
) -> Tuple[Dict[Text, List[Text]], Dict[Text, List[float]]]:
    """Convert the output predictions for entities to the actual entity tags.

    Args:
        model_predictions: the output predictions using the entity tag indices
        entity_tag_specs: the entity tag specifications
        bilou_flag: if 'True', the BILOU tagging schema was used
        prediction_index: the index in the batch of predictions
            to use for entity extraction

    Returns:
        A map of entity tag type, e.g. entity, role, group, to actual entity tags and
        confidences.
    """
    predicted_tags = {}
    confidence_values = {}

    for tag_spec in entity_tag_specs:
        predictions = model_predictions[f"e_{tag_spec.tag_name}_ids"].numpy()
        confidences = model_predictions[f"e_{tag_spec.tag_name}_scores"].numpy()

        if not np.any(predictions):
            continue

        confidences = [float(c) for c in confidences[prediction_index]]
        tags = [tag_spec.ids_to_tags[p] for p in predictions[prediction_index]]

        if bilou_flag:
            (
                tags,
                confidences,
            ) = rasa.nlu.utils.bilou_utils.ensure_consistent_bilou_tagging(
                tags, confidences
            )

        predicted_tags[tag_spec.tag_name] = tags
        confidence_values[tag_spec.tag_name] = confidences

    return predicted_tags, confidence_values

def override_defaults(
    defaults: Optional[Dict[Text, Any]], custom: Optional[Dict[Text, Any]]
) -> Dict[Text, Any]:
    """Override default config with the given config.

    We cannot use `dict.update` method because configs contain nested dicts.

    Args:
        defaults: default config
        custom: user config containing new parameters

    Returns:
        updated config
    """
    if defaults:
        config = copy.deepcopy(defaults)
    else:
        config = {}

    if custom:
        for key in custom.keys():
            if isinstance(config.get(key), dict):
                config[key].update(custom[key])
            else:
                config[key] = custom[key]

    return config

def update_confidence_type(component_config: Dict[Text, Any]) -> Dict[Text, Any]:
    """Set model confidence to cosine if margin loss is used.

    Args:
        component_config: model configuration

    Returns:
        updated model configuration
    """
    # TODO: Remove this once model_confidence is set to cosine by default.
    if (
        component_config[LOSS_TYPE] == MARGIN
        and component_config[MODEL_CONFIDENCE] == SOFTMAX
    ):
        rasa.shared.utils.io.raise_warning(
            f"Overriding defaults by setting {MODEL_CONFIDENCE} to "
            f"{COSINE} as {LOSS_TYPE} is set to {MARGIN} in the configuration."
        )
        component_config[MODEL_CONFIDENCE] = COSINE
    return component_config

def validate_configuration_settings(component_config: Dict[Text, Any]) -> None:
    """Performs checks to validate that combination of parameters in the configuration are correctly set.

    Args:
        component_config: Configuration to validate.
    """
    _check_loss_setting(component_config)
    _check_confidence_setting(component_config)
    _check_similarity_loss_setting(component_config)

def _check_confidence_setting(component_config: Dict[Text, Any]) -> None:
    if component_config[MODEL_CONFIDENCE] == SOFTMAX:
        rasa.shared.utils.io.raise_warning(
            f"{MODEL_CONFIDENCE} is set to `softmax`. It is recommended "
            f"to set it to `cosine`. It will be set to `cosine` by default, "
            f"Rasa Open Source 3.0.0 onwards.",
            category=UserWarning,
        )
        if component_config[LOSS_TYPE] not in [SOFTMAX, CROSS_ENTROPY]:
            raise InvalidConfigException(
                f"{LOSS_TYPE}={component_config[LOSS_TYPE]} and "
                f"{MODEL_CONFIDENCE}={SOFTMAX} is not a valid "
                f"combination. You can use {MODEL_CONFIDENCE}={SOFTMAX} "
                f"only with {LOSS_TYPE}={CROSS_ENTROPY}."
            )
        if component_config[SIMILARITY_TYPE] not in [INNER, AUTO]:
            raise InvalidConfigException(
                f"{SIMILARITY_TYPE}={component_config[SIMILARITY_TYPE]} and "
                f"{MODEL_CONFIDENCE}={SOFTMAX} is not a valid "
                f"combination. You can use {MODEL_CONFIDENCE}={SOFTMAX} "
                f"only with {SIMILARITY_TYPE}={INNER}."
            )

def _check_loss_setting(component_config: Dict[Text, Any]) -> None:
    if not component_config[CONSTRAIN_SIMILARITIES] and component_config[LOSS_TYPE] in [
        SOFTMAX,
        CROSS_ENTROPY,
    ]:
        rasa.shared.utils.io.raise_warning(
            f"{CONSTRAIN_SIMILARITIES} is set to `False`. It is recommended "
            f"to set it to `True` when using cross-entropy loss. It will be set to `True` by default, "
            f"Rasa Open Source 3.0.0 onwards.",
            category=UserWarning,
        )

def _check_similarity_loss_setting(component_config: Dict[Text, Any]) -> None:
    if (
        component_config[SIMILARITY_TYPE] == COSINE
        and component_config[LOSS_TYPE] == CROSS_ENTROPY
        or component_config[SIMILARITY_TYPE] == INNER
        and component_config[LOSS_TYPE] == MARGIN
    ):
        rasa.shared.utils.io.raise_warning(
            f"`{SIMILARITY_TYPE}={component_config[SIMILARITY_TYPE]}`"
            f" and `{LOSS_TYPE}={component_config[LOSS_TYPE]}` "
            f"is not a recommended setting as it may not lead to best results."
            f"Ideally use `{SIMILARITY_TYPE}={INNER}`"
            f" and `{LOSS_TYPE}={CROSS_ENTROPY}` or"
            f"`{SIMILARITY_TYPE}={COSINE}` and `{LOSS_TYPE}={MARGIN}`.",
            category=UserWarning,
        )

def init_split_entities(
    split_entities_config, default_split_entity
) -> Dict[Text, bool]:
    """Initialise the behaviour for splitting entities by comma (or not).

    Returns:
        Defines desired behaviour for splitting specific entity types and
        default behaviour for splitting any entity types for which no behaviour
        is defined.
    """
    if isinstance(split_entities_config, bool):
        # All entities will be split according to `split_entities_config`
        split_entities_config = {SPLIT_ENTITIES_BY_COMMA: split_entities_config}
    else:
        # All entities not named in split_entities_config will be split
        # according to `split_entities_config`
        split_entities_config[SPLIT_ENTITIES_BY_COMMA] = default_split_entity
    return split_entities_config


"""
Given a list of n integers arr[0..(n-1)], determine the number
of different pairs of elements within it which sum to k. If an
integer appears in the list multiple times, each copy is
considered to be different; that is, two pairs are considered
different if one pair includes at least one array index which
the other doesn't, even if they include the same values.
"""

from collections import defaultdict

def numberOfWays(arr, k):
    tracker, ans = defaultdict(int), 0
    for num in arr:
        if num in tracker:
            ans += tracker[num]
        tracker[k - num] += 1
    return ans

print(numberOfWays([1, 2, 3, 4, 3], 6))
print(numberOfWays([1, 5, 3, 3, 3], 6))
print("The values above should be 2 and 4.")