""" This module contains usecase unit tests """

from core.repository.book_repository import BaseRepository, BookRepository
from core.usecases.book_usecase import BookUseCase
from tests.mocked_books_formated import valid_book, valid_book_list, valid_updated_book

# BookUseCase adds a new business rule to the find_by_id method.
# Thus, we need to create new tests to evaluate it.

def test_book_usecase_find_by_id_valid_id(mocker):
    """Should return the mocked book"""
    # Arrange - here we are mocking the call for another method.
    mocker.patch("core.repository.book_repository.BookRepository.find_by_id")
    mocked_result = valid_book()
    BookRepository.find_by_id.return_value = mocked_result
    invalid_book_id = 1

    # Act
    book_found = BookUseCase().find_by_id(invalid_book_id)

    # Assert
    assert book_found == mocked_result

def test_book_usecase_find_by_id_invalid_id(mocker):
    """Should return None"""
    # Arrange
    mocker.patch("core.repository.book_repository.BookRepository.find_by_id")
    BookRepository.find_by_id.return_value = valid_book()
    invalid_book_id = 0

    # Act
    book_found = BookUseCase().find_by_id(invalid_book_id)

    # Assert
    assert book_found is None

# The same is true for Create and update methods, so we need to test their business rules as well.

def test_book_use_case_create_valid_book_success(mocker):
    """ creation method should return Success   """
    # Arrange
    mocker.patch("core.repository.book_repository.BookRepository.find_by_title")
    BookRepository.find_by_title.return_value = None

    book_to_create = valid_book()
    mocker.patch("core.repository.base_repository.BaseRepository.create")
    BaseRepository.create.return_value = True

    # Act
    created_successfully = BookUseCase().create(book_to_create)

    # Asert
    assert created_successfully

def test_book_use_case_create_existing_book_fail(mocker):
    """ should return false when book create fails """

    # Arrange
    mocker.patch("core.repository.book_repository.BookRepository.find_by_title")
    existing_book = valid_book_list()[0]
    BookRepository.find_by_title.return_value = existing_book

    book_to_create = existing_book
    mocker.patch("core.repository.base_repository.BaseRepository.create")
    BaseRepository.create.return_value = False

    # Act
    created_successfully = BookUseCase().create(book_to_create)

    # Asert
    assert not created_successfully

def test_book_use_case_update_or_patch_existing_book_succeed(mocker):
    """ Should return true when updating a existing book """

    # Arrange
    mocker.patch("core.repository.book_repository.BookRepository.find_by_id")
    existing_book = valid_book_list()[2]
    BookRepository.find_by_id.return_value = existing_book

    mocker.patch("core.repository.book_repository.BookRepository.update_or_patch")
    updated_book = valid_updated_book()
    BookRepository.update_or_patch.return_value = True

    # Act
    updated_successfully = BookUseCase().update_or_patch(updated_book.id, updated_book)

    # Assert
    assert updated_successfully

def test_book_use_case_update_or_patch_nonexistent_book_fail(mocker):
    """ should return false when updating an invalid book """

    # Arrange
    mocker.patch("core.repository.book_repository.BookRepository.find_by_id")
    existing_book = None
    BookRepository.find_by_id.return_value = existing_book

    mocker.patch("core.repository.book_repository.BookRepository.update_or_patch")
    updated_book = valid_updated_book()
    updated_book.id = 1
    BookRepository.update_or_patch.return_value = False

    # Act
    updated_successfully = BookUseCase().update_or_patch(updated_book.id, updated_book)

    # Assert
    assert not updated_successfully


from math import sqrt

def crivo(n):
    if (n == 1):
        return []
    if (n == 2):
        return [2]
    if (n == 3):
        return [2, 3]
    sq_n = int(sqrt(n)+1)
    primo = [1 for i in range (0, sq_n)]
    primo[0] = 0
    primo[1] = 0
    n1 = int(sqrt(sq_n)+1)
    for i in range (2, n1+1):
        if primo[i] == 1:
            for j in range (i*i, sq_n, i):
                primo[j] = 0
    inteiros = []
    for i in range (2, sq_n):
        if primo[i] == 1:
            inteiros.append (i)

    return inteiros

def decompor(n):
    primos_ate_n = crivo(n)
    fatores = list(); i = 0
    while n != 1:
        if n%primos_ate_n[i] == 0:
            n = n/primos_ate_n[i]
            fatores.append(primos_ate_n[i])
        else:
            i += 1
        if i == len(primos_ate_n):
            return [n]
    return fatores

def divisores(fatoresn):
    fatores_primos = fatoresn
    divisores = [1]
    for f in fatores_primos:
        divisores += [f*j for j in divisores if f*j not in divisores]
    return divisores

def despojado(n):
    fatores = decompor(n)
    if len(fatores) > 1 and fatores == list(set(fatores)):
        return True
    return False

n = int(input())
div = divisores(decompor(n))
print(div)
count = 0
for i in div:
    if despojado(i):
        count += 1
print(count)


class Solution:
    def getLucky(self, s: str, k: int) -> int:
        def transform(st):
            res = 0
            for s in st:
                res+=int(s)
            return res
        st = ""
        for ch in s:
            st+=str(ord(ch) - ord('a') + 1)
        while k > 0:
            st = transform(str(st))
            k-=1
        return st


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 23 22:46:26 2022

@author: anamm
"""
N=int(input("Enter A number:"))
str1=input("Enter String:")

new_str=""
for i in range(len(str1)):
    if (i>N):
        new_str = new_str + str1[i]
print ("The string after removal",N," upto character(s) : ",new_str)


#!/usr/bin/env python
#
# This is free and unencumbered software released into the public domain.
# See the UNLICENSE file for details.
#
# ------------------------------------------------------------------------
# cli.py
# ------------------------------------------------------------------------

"""
The monoqueue command line tool.
"""

import sys
from pprint import pprint

from . import Monoqueue, ui
from .log import log, setup_logging

def cmd_info(*args):
    if len(args) == 0:
        log.error("Please specify at least one term to match.")
        return 3

    mq = Monoqueue()
    mq.load()
    for url in mq.urls(active_only=False):
        if any(arg for arg in args if arg in url):
            metadata = mq.metadata(url)
            impact = mq.impact(url)
            item = mq.item(url)

            print(f"[{url}]")

            if metadata: pprint(metadata)
            else: print("<No local metadata>")

            if impact:
                pprint(impact.rules)
                print(f"Impact score: {impact.value}")
            else:
                print("<No computed impact>")

            if item: pprint(item)
            else: print("<No action item data>")

    return 0

def cmd_ls(*args):
    html = "--html" in args

    if html:
        raise RuntimeError("HTML export is not implemented yet")

    mq = Monoqueue()
    mq.load()
    urls = mq.urls()

    for i, url in enumerate(urls):
        if i > 10: break
        item = mq.item(url)
        impact = mq.impact(url)
        print(f"[{impact.value}] -- {url} -- {item['title']}")

    return 0

def cmd_ui(*args):
    ui.main(*args)
    return 0

def cmd_up(*args):
    mq = Monoqueue()

    # TODO: Is this too hacky? Think about it.
    mq.progress = lambda more: print(".", flush=True, end="" if more else None)

    mq.update()

    # Persist the updated action items to disk.
    mq.save(metadata_path=None)

    return 0

def main():
    setup_logging()

    usage = """
Usage: mq <command> [<args>]

Valid commands:
  info - show detailed info about action items
    ls - list action items by impact score
    ui - launch the interactive monoqueue user interface
    up - update action item data from linked sources
"""

    args = sys.argv[1:]
    if len(args) == 0:
        sys.stderr.write(usage)
        return 1

    command = args[0]
    args = args[1:]

    if command == "info": return cmd_info(*args)
    if command == "ls": return cmd_ls(*args)
    if command == "ui": return cmd_ui(*args)
    if command == "up": return cmd_up(*args)

    log.error("Invalid subcommand: %s", command)
    sys.stderr.write(usage)
    return 250


import tensorflow as tf

from tensorflow_addons.text import crf_log_likelihood
from tensorflow_addons.utils import types

@tf.keras.utils.register_keras_serializable(package="Addons")
class CRFModelWrapper(tf.keras.Model):
    def __init__(
        self,
        base_model: tf.keras.Model,
        units: int,
        chain_initializer: types.Initializer = "orthogonal",
        use_boundary: bool = True,
        boundary_initializer: types.Initializer = "zeros",
        use_kernel: bool = True,
        **kwargs,
    ):
        super().__init__()

        # lazy import to solve circle import issue:
        # tfa.layers.CRF -> tfa.text.__init__ -> tfa.text.crf_wrapper -> tfa.layers.CRF
        from tensorflow_addons.layers.crf import CRF  # noqa

        self.crf_layer = CRF(
            units=units,
            chain_initializer=chain_initializer,
            use_boundary=use_boundary,
            boundary_initializer=boundary_initializer,
            use_kernel=use_kernel,
            **kwargs,
        )

        self.base_model = base_model

    def unpack_training_data(self, data):
        # override me, if this is not suit for your task
        if len(data) == 3:
            x, y, sample_weight = data
        else:
            x, y = data
            sample_weight = None
        return x, y, sample_weight

    def call(self, inputs, training=None, mask=None, return_crf_internal=False):
        base_model_outputs = self.base_model(inputs, training, mask)

        # change next line, if your model has more outputs
        crf_input = base_model_outputs

        decode_sequence, potentials, sequence_length, kernel = self.crf_layer(crf_input)

        # change next line, if your base model has more outputs
        # Aways keep `(potentials, sequence_length, kernel), decode_sequence, `
        # as first two outputs of model.
        # current `self.train_step()` expected such settings
        outputs = (potentials, sequence_length, kernel), decode_sequence

        if return_crf_internal:
            return outputs
        else:
            # outputs[0] is the crf internal, skip it
            output_without_crf_internal = outputs[1:]

            # it is nicer to return a tensor instead of an one tensor list
            if len(output_without_crf_internal) == 1:
                return output_without_crf_internal[0]
            else:
                return output_without_crf_internal

    def compute_crf_loss(
        self, potentials, sequence_length, kernel, y, sample_weight=None
    ):
        crf_likelihood, _ = crf_log_likelihood(potentials, y, sequence_length, kernel)
        # convert likelihood to loss
        flat_crf_loss = -1 * crf_likelihood
        if sample_weight is not None:
            flat_crf_loss = flat_crf_loss * sample_weight
        crf_loss = tf.reduce_mean(flat_crf_loss)

        return crf_loss

    def train_step(self, data):
        x, y, sample_weight = self.unpack_training_data(data)
        with tf.GradientTape() as tape:
            (potentials, sequence_length, kernel), decoded_sequence, *_ = self(
                x, training=True, return_crf_internal=True
            )
            crf_loss = self.compute_crf_loss(
                potentials, sequence_length, kernel, y, sample_weight
            )
            loss = crf_loss + tf.reduce_sum(self.losses)
        gradients = tape.gradient(loss, self.trainable_variables)
        self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))

        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, decoded_sequence)
        # Return a dict mapping metric names to current value
        orig_results = {m.name: m.result() for m in self.metrics}
        crf_results = {"loss": loss, "crf_loss": crf_loss}
        return {**orig_results, **crf_results}

    def test_step(self, data):
        x, y, sample_weight = self.unpack_training_data(data)
        (potentials, sequence_length, kernel), decode_sequence, *_ = self(
            x, training=False, return_crf_internal=True
        )
        crf_loss = self.compute_crf_loss(
            potentials, sequence_length, kernel, y, sample_weight
        )
        loss = crf_loss + tf.reduce_sum(self.losses)
        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, decode_sequence)
        # Return a dict mapping metric names to current value
        results = {m.name: m.result() for m in self.metrics}
        results.update({"loss": loss, "crf_loss": crf_loss})  # append loss
        return results

    def get_config(self):
        base_model_config = self.base_model.get_config()
        crf_config = self.crf_layer.get_config()

        return {**{"base_model": base_model_config}, **crf_config}

    @classmethod
    def from_config(cls, config):
        base_model_config = config.pop("base_model")
        base_model = tf.keras.Model.from_config(base_model_config)

        return cls(base_model=base_model, **config)


def loadInput():
    file = open('day3/input.txt', 'r')
    lines = file.readlines()
    return lines

def getGroupPriority(rucksack1, rucksack2, rucksack3):
    firstSet = set()
    for i in range(0, len(rucksack1)):
        firstSet.add(rucksack1[i])

    firstSecondSharedSet = set()
    for j in range(0, len(rucksack2)):
        if rucksack2[j] in firstSet:
            firstSecondSharedSet.add(rucksack2[j])

    for k in range(0, len(rucksack3)):
        if rucksack3[k] in firstSecondSharedSet:
            item = rucksack3[k]
            if ord(item) < ord('a'):
                return ord(item) - ord('A') + 27
            else:
                return ord(item) - ord('a') + 1

def main():
    lines = loadInput()
    groupPrioritySum = 0

    for i in range(0, len(lines), 3):
        groupPrioritySum += getGroupPriority(lines[i], lines[i+1], lines[i+2])

    print(groupPrioritySum)

main()


import sys

def f_gold ( n , k ) :
    p = 1
    if k % 2 != 0 :
        p = - 1
    return int ( pow ( n - 1 , k ) + p * ( n - 1 ) ) / n

if __name__ == '__main__':
    param = [
    (27,59,),
    (70,87,),
    (77,40,),
    (83,26,),
    (16,2,),
    (90,66,),
    (39,72,),
    (48,26,),
    (56,77,),
    (10,47,)
        ]
    n_success = 0
    print("class,mutant,test_index,result")
    for i, parameters_set in enumerate(param):
        try:
            print("NUMBER_WAYS_NODE_MAKE_LOOP_SIZE_K_UNDIRECTED_COMPLETE_CONNECTED_GRAPH_N_NODES," + sys.argv[1] + "," + str(i) + "," + str(f_gold(*parameters_set)))
        except:
            print("NUMBER_WAYS_NODE_MAKE_LOOP_SIZE_K_UNDIRECTED_COMPLETE_CONNECTED_GRAPH_N_NODES," + sys.argv[1] + "," + str(i) + ",EXCEPTION")


import socket
import struct
import sys

#dictionary of english months, used for converting whole response packet to human readable form
ENGLISH = {
    1: "January",
    2: "February",
    3: "March",
    4: "April",
    5: "May",
    6: "June",
    7: "July",
    8: "August",
    9: "September",
    10: "October",
    11: "November",
    12: "December"
}

def to_binary(a):
    """Given a specified bit length and number, return the binary representation"""
    number, length = a
    return_num = bin(number)[2:]
    if return_num[0] == 'b':
        return_num = return_num[1:]
    #add zeros to the front so that the binary string is the correct length
    while len(return_num) < length:
        return_num = '0' + return_num
    return return_num

def check_response(DT_response):
    """Given a response packet, go through a series of checks and determine
    that it is an acceptable response"""
    acceptable = False
    header, body = DT_response[:13], DT_response[13:] #split the text from the header
    #turn header and body into integers so bit operations can be performed
    response = int.from_bytes(header, byteorder='big', signed=False)
    text = int.from_bytes(body, byteorder='big', signed=False)

    magic_number = (response & 0xFFFF0000000000000000000000) >> 88
    packet_type = (response & 0xFFFF000000000000000000) >> 72
    language_code = (response & 0xFFFF00000000000000) >> 56
    year = (response & 0xFFFF0000000000) >> 40
    month = (response & 0xFF00000000) >> 32
    day = (response & 0xFF000000) >> 24
    hour = (response & 0xFF0000) >> 16
    minute = (response & 0xFF00) >> 8
    length = (response & 0xFF)

    #check magic number
    if magic_number != 0x497e:
        acceptable = False
        print("That's not the magic number!")
        print('\n')

    #check packet type
    if packet_type != 0x0002:
        acceptable = False
        print("That is an invalid packet type")
        print('\n')

    #check language code
    if not (language_code == 0x0001 or language_code == 0x0002 or language_code == 0x0003):
        acceptable = False
        print("That is an invalid language code")
        print('\n')

    #check year
    if year < 0 and year > 2100:
        acceptable = False
        print("That is an invalid value for the year")
        print('\n')

    #check month
    if month < 1 and month > 12:
        acceptable = False
        print("That is an invalid value for the month")
        print('\n')

    #check day
    if day < 1 and day > 31:
        acceptable = False
        print("That is an invalid value for the day")
        print('\n')

    #check hour
    if hour < 0 and hour > 23:
        acceptable = False
        print("That is an invalid value for the hours")
        print('\n')

    #check minute
    if minute < 0 and minute > 59:
        acceptable = False
        print("That is an invalid value for the minutes")
        print('\n')

    #check length makes sense
    if len(DT_response) == 13 + length:
        print("Success! Printing your request...")
        print('\n')
    else:
        acceptable = False
        print("The length of the packet does not match the specified length")
        print('\n')

    return acceptable

def prepare_request(request_type):
    """Prepare a request packet based on the type of response the client wants"""
    magic = int(0x497e)
    packet = int(0x0001)
    output = [(magic, 16), (packet, 16), (int(request_type), 16)]
    binary_string  = ''
    for a in output:
        binary_string += to_binary(a)
    integer = int(binary_string, 2)
    answer = bytearray()
    while integer:
        answer.append(integer & 0xff)
        integer >>= 8
    request = answer[::-1]
    return request

def print_response(DT_response):
    """Print out the contents of the response packet in a human-readable
    format"""
    header, body = DT_response[:13], DT_response[13:]
    response = int.from_bytes(header, byteorder='big', signed=False)

    magic_number = hex((response & 0xFFFF0000000000000000000000) >> 88)
    packet_type = int((response & 0xFFFF000000000000000000) >> 72)
    language_code = int((response & 0xFFFF00000000000000) >> 56)
    year = int((response & 0xFFFF0000000000) >> 40)
    month = int((response & 0xFF00000000) >> 32)
    day = int((response & 0xFF000000) >> 24)
    hour = int((response & 0xFF0000) >> 16)
    minute = int((response & 0xFF00) >> 8)
    length = int((response & 0xFF))
    text = body.decode("utf_8")

    if language_code == 1:
        lang = "English"
    elif language_code == 2:
        lang = "Te Reo Maori"
    elif language_code == 3:
        lang = "German"

    #print a human readbale version of the response packet
    print("-----------------RESPONSE PACKET----------------------")
    print(f"Magic number: {magic_number}")
    print(f"Packet type: {packet_type}")
    print(f"Language: {lang}")
    print(f"Year: {year}")
    print(f"Month: {ENGLISH[month]}")
    print(f"Day: {day}")
    print(f"Hour: {hour}")
    print(f"Minutes: {minute}")
    print(f"Message length: {length}")
    print(f"Message: {text}")
    print("------------------------------------------------------")

def print_outcome(DT_response):
    """Print the outcome of the response ie. the textual representation of the
    date or time"""
    body = DT_response[13:]
    text = body.decode("utf_8")
    print(text)
    print('\n')
    print('\n')

def main():
    """Open up the socket, get command line input to determine what request to
    send and then receive and unpack the response"""
    date_time = input("Date or time: ") #determine whether client wants to know the date or the time
    ip = str(input("Host IP: ")) #get the IP address of the host
    port = int(input("Port: ")) #get the port number the client wants to use; used to determine the response language
    print('\n')

    #check if response to date or time was valid
    if date_time != 'date' and date_time != 'time':
        print("You must enter either 'date' or 'time'")
        print('\n')
        sys.exit()

    #check that the port number was valid
    if port < 1024 or port > 64000:
        print("Port out of range! Must be between 1024 and 64000.")
        print('\n')
        sys.exit()

    #determine the request type based on the user input
    if date_time == 'date':
        request_type = 0x0001
    elif date_time == 'time':
        request_type = 0x0002

    #attempt to bind to the socket specified by the user input
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    except:
        print("Error establishing and binding to port. Terminating...")
        print('\n')
        sys.exit()

    #prepare the request
    request = prepare_request(request_type)
    is_running = True
    while True:
        #send the request to the server
        sock.sendto(request, (ip, port))
        sock.settimeout(1) #set the time out for response time

        try:
            #attempt to receive the response in time
            data, addr = sock.recvfrom(1024)
            if check_response(data): #check that the response is valid
                print_outcome(data) #print the textual rep of the response
                print_response(data) #print full response in human readable form
                is_running = False
                sys.exit()
            else:
                print("Packet invalid")
                print('\n')
                is_running = False
        except socket.timeout: #if the response is too slow
            print("Response not returned in time")
            print('\n')
            is_running = False

    #close the port
    sock.close()
    sys.exit()

main()


import string

fname = input("Please enter the file name: ")

try:
    fhand = open(fname)
except:
    print("File cannot be opend!")
    exit()

counts = dict()

for line in fhand:
    line = line.rstrip()
    line = line.translate(line.maketrans('','',string.punctuation)) #remove the puncuation from the line
##    print(line)
    line = line.lower()
    words = line.split()

    for word in words:
        if word not in counts:
            counts[word] = 1
        else:
            counts[word] += 1

print(counts)


'''scopes_ - области видимости и пространства имен'''

'''LEGB - '''
# Local - локальная
# enclosed - замкнутая
# Global - глобальная
# built-in - встроенная

# '''Область видимости''' - часть программы, где будет доступно
# то или иное имы (переменная, функция, класс и т.д)

# name = 'Janat'
# name = 'Akbar'
# print(name) # Akbar

# name = 'Marina' #global пространство
# def func():
#     name = 'Nikolay'
# print(name)    # Marina

# def func2():
#     print(name)  # local пространство
# func2()    #Marina

# def func3():
#     a = 10

# print(a)    # NameError:

'''имена из локальной области недоступны в глоальной области,
но в локальной области доступны имена из глобальной области!'''

# for i in range(1, 10):
#     res = i * 2
# print(res)    # 18

# number = 20
# if number % 2 == 0:
#     res2 = 35
# print(res2)    # табуляция не влияет на области видимости

# num = 10

# def func():
#     global num  # функция чтобы локальный превратить в глобальный
#     num = 50

# func()
# print(num)

# x = 20 # global

# def func_outer():
#     x = 15  # non local
#     def func_inner():
#         x = 25 # local
#         print(x)
#     func_inner()

# func_outer()    # 25

# number = 20
# def outer_func():
#     # nonlocal
#     number = 19   # 19
#     print(number)
#     def inner_func():
#         nonlocal number     # поменять
#         number = 25  # 25
#         print(number)
#     inner_func()
#     print(number)    # 19

# outer_func()

'''globals(), locals()'''

a = 20
# print(globals()) # словарь из встроенных имен
# globals() - показывает имена на глобальном уровне видимости

# print(locals()):
# def my_func():
#     var = 95
#     tel = 100
#     print(locals())
# my_func()         #{'var': 95, 'tel': 100}

# locals() - показывает доступные имена той области в которой была вызвана

def get_drade(mark):
    mark = 1
    if grade > 87:
        grade = 5
    return grade

get_grade(85)


# Collin Patterson
# Mr. Davis
# 10/7/2016
# Advanced Computer Programming

from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import random

root = Tk()

global daytonHealth1
global riveraHealth2
daytonHealth1 = int(100)
riveraHealth2 = int(100)

list1 = ('Attack', 'Defend', 'Special')
list2 = ('Attack', 'Defend', 'Special')

listvar1 = StringVar(value=list1)
listvar2 = StringVar(value=list2)

def aboutprint():
    messagebox.showinfo(title='Math Wars', message='Version .1')

def Fight():
    global daytonHealth1
    global riveraHealth2
    Attack1 = random.randint(1, 10)
    Attack2 = random.randint(1, 10)
    specialAttack1 = random.randint(10, 20)
    specialAttack2 = random.randint(10, 20)
    try:
        listboxselection1 = int(listbox1.curselection()[0])
        listboxselection2 = int(listbox2.curselection()[0])
        value1 = str(list1[listboxselection1])
        value2 = str(list2[listboxselection2])
        if value1 == 'Attack':
            if value2 == 'Attack':
                print('Mr. Rivera attacked Mr. Dayton!')
                daytonHealth1 = (daytonHealth1 - Attack1)
                print(daytonHealth1)
                print('')
                print('Mr. Dayton attacked Mr. Rivera!')
                riveraHealth2 = (riveraHealth2 - Attack2)
                print(riveraHealth2)
                print('------------------------------------------------------------------------------')
            elif value2 == 'Defend':
                print('Mr. Dayton was immune!')
                print('------------------------------------------------------------------------------')
            elif value2 == 'Special':
                print('Mr. Rivera attacked Mr. Dayton!')
                daytonHealth1 = (daytonHealth1 - Attack1)
                print(daytonHealth1)
                print('')
                print('Mr. Dayton attacked Mr. Rivera using his special move "Flaming 4 Square Ball"!')
                riveraHealth2 = (riveraHealth2 - specialAttack1)
                print(riveraHealth2)
                print('------------------------------------------------------------------------------')
            else:
                pass
        elif value1 == 'Defend':
            if value2 == 'Attack':
                print('Mr. Rivera was immune!')
                print('------------------------------------------------------------------------------')
            elif value2 == 'Defend':
                print('Both teachers were immune!')
                print('------------------------------------------------------------------------------')
            elif value2 == 'Special':
                print('Mr. Rivera was immune!')
                print('------------------------------------------------------------------------------')
            else:
                pass
        elif value1 == 'Special':
            if value2 == 'Attack':
                print('Mr. Rivera attacked Mr. Dayton using his special move "Exploding Kittens"!')
                daytonHealth1 = (daytonHealth1 - specialAttack1)
                print(daytonHealth1)
                print('')
                print('Mr. Dayton attacked Mr. Rivera!')
                riveraHealth2 = (riveraHealth2 - Attack1)
                print(riveraHealth2)
                print('------------------------------------------------------------------------------')
            elif value2 == 'Defend':
                print('Mr. Dayton was immune!')
                print('------------------------------------------------------------------------------')
            elif value2 == 'Special':
                print('Mr. Rivera attacked Mr. Dayton using his special move "Exploding Kittens"!!')
                daytonHealth1 = (daytonHealth1 - specialAttack1)
                print(daytonHealth1)
                print('')
                print('Mr. Dayton attacked Mr. Rivera using his special move "Flaming 4 Square Ball"!')
                riveraHealth2 = (riveraHealth2 - specialAttack2)
                print(riveraHealth2)
                print('------------------------------------------------------------------------------')
        else:
            pass

        if daytonHealth1 <= 0 and riveraHealth2 <= 0:
            messagebox.showinfo(title='Winner', message='Both teachers lost!')
            winner.configure(text='No one')
            fightbtn.configure(state='disabled')
        elif riveraHealth2 <= 0:
            winner.configure(text='Mr. Dayton!')
            fightbtn.configure(state='disabled')
            messagebox.showinfo(title='Winner', message='Mr. Dayton over crit Mr. Rivera!')
        elif daytonHealth1 <= 0:
            winner.configure(text='Mr. Rivera')
            fightbtn.configure(state='disabled')
            messagebox.showinfo(title='Winner', message='Mr. Rivera over crit Mr. Dayton!')
        else:
            pass

    except:
        pass

mainframe = ttk.Frame(root, padding=(3, 3, 12, 12))

topMenu = Menu(root)
root.config(menu=topMenu)

subMenu = Menu(topMenu)
topMenu.add_cascade(label='File', menu=subMenu)
subMenu.add_command(label='Exit', command=root.quit)

editMenu = Menu(topMenu)
topMenu.add_cascade(label='Help', menu=editMenu)
editMenu.add_command(label='About', command=aboutprint)

fightbtn = ttk.Button(root, text="Fight", command=Fight)
listbox1 = Listbox(root, listvariable=listvar1, selectmode='single', exportselection=0, height=10)
listbox2 = Listbox(root, listvariable=listvar2, selectmode='single', exportselection=0, height=10)
attack1 = ttk.Label(root, text='Attack: 1-10')
attack2 = ttk.Label(root, text='Attack: 1-10')
defence1 = ttk.Label(root, text='Defends: 3')
defence2 = ttk.Label(root, text='Defends: 3')
special1 = ttk.Label(root, text='Special: Exploding Kittens')
special2 = ttk.Label(root, text='Special: Flaming 4 Square')
player1 = ttk.Label(root, text='Mr. Rivera')
player2 = ttk.Label(root, text='Mr. Dayton')
wins = ttk.Label(root, text='Wins')
winner = ttk.Label(root, text='')

fightbtn.grid(column=1, row=4, sticky=S)
listbox1.grid(column=0, row=1, rowspan=3)
listbox2.grid(column=2, row=1, rowspan=3)
attack1.grid(column=0, row=4)
attack2.grid(column=2, row=4)
defence1.grid(column=0, row=5)
defence2.grid(column=2, row=5)
special1.grid(column=0, row=6)
special2.grid(column=2, row=6)
player1.grid(column=0, row=0)
player2.grid(column=2, row=0)
wins.grid(column=1, row=1)
winner.grid(column=1, row=2)

root.mainloop()


import pefile
import argparse
import os

if __name__=='__main__':
    parser = argparse.ArgumentParser(description='a script to strip the entrypoints of PE files')
    parser.add_argument('input', help='input file or directory')
    parser.add_argument('-r', help='specify replacement value - else will use default 0xcc00ffee', metavar='EP_VAL', action='store', type=lambda x: int(x,16), default=0xcc00ffee,)
    args = parser.parse_args()

    targets = []
    if os.path.isdir(args.input):
        for root,dirs,files in os.walk(args.input):
            for path in files:
                targets.append(os.path.join(root,path))
    elif os.path.isfile(args.input):
        targets.append(args.input)

    for target in targets:
        try:
            pe = pefile.PE(target)
        except pefile.PEFormatError:
            #print('file not in valid PE format:',target)
            continue

        # the EP attribute is of type int
        pe.OPTIONAL_HEADER.AddressOfEntryPoint = args.r

        # output
        pe.write('{0}_stripped{1}'.format(*os.path.splitext(target)))


from pycocotools import mask as maskUtils
import numpy as np

def annsToSeg(anns, coco_instance):
	'''
	converts COCO-format annotations of a given image to a PASCAL-VOC segmentation style label
	 !!!No guarantees where segmentations overlap - might lead to loss of objects!!!
	:param anns: COCO annotations as returned by 'coco.loadAnns'
	:param coco_instance: an instance of the COCO class from pycocotools
	:return: three 2D numpy arrays where the value of each pixel is the class id, instance number, and instance id.
	'''
	image_details = coco_instance.loadImgs(anns[0]['image_id'])[0]

	h = image_details['height']
	w = image_details['width']

	class_seg = np.zeros((h, w))
	instance_seg = np.zeros((h, w))
	id_seg = np.zeros((h, w))
	masks, anns = annsToMask(anns, h, w)

	for i, mask in enumerate(masks):
		class_seg = np.where(class_seg>0, class_seg, mask*anns[i]['category_id'])
		instance_seg = np.where(instance_seg>0, instance_seg, mask*(i+1))
		id_seg = np.where(id_seg > 0, id_seg, mask * anns[i]['id'])

	return class_seg, instance_seg, id_seg.astype(np.int64)

def annToRLE(ann, h, w):
	"""
	Convert annotation which can be polygons, uncompressed RLE to RLE.
	:return: binary mask (numpy 2D array)
	"""
	segm = ann['segmentation']
	if type(segm) == list:
		# polygon -- a single object might consist of multiple parts
		# we merge all parts into one mask rle code
		rles = maskUtils.frPyObjects(segm, h, w)
		rle = maskUtils.merge(rles)
	elif type(segm['counts']) == list:
		# uncompressed RLE
		rle = maskUtils.frPyObjects(segm, h, w)
	else:
		# rle
		rle = ann['segmentation']
	return rle

def annsToMask(anns, h, w):
	"""
	Convert annotations which can be polygons, uncompressed RLE, or RLE to binary masks.
	:return: a list of binary masks (each a numpy 2D array) of all the annotations in anns
	"""
	masks = []
	anns = sorted(anns, key=lambda x: x['area'])  # Smaller items first, so they are not covered by overlapping segs
	for ann in anns:
		rle = annToRLE(ann, h, w)
		m = maskUtils.decode(rle)
		masks.append(m)
	return masks, anns


import sys
from pyfiglet import Figlet

if len(sys.argv) != [0,2]:
    print("Invalid usage")
    sys.exit(1)

figlet = Figlet()

if len(sys.argv) == 0 :
    answer = input("input : ")
    font = figlet.getFonts(random.choice)
    print(figlet.renderText(answer))

if len(sys.argv) == 2 and sys.argv[1] == ["-f","--font"]:
    figlet.setFont(font=sys.argv[2])
    answer = input("Input : ")
    print(figlet.renderText(answer))


import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn.metrics import r2_score
import statsmodels.api as sm

file_path = './product_overview_selected_medinev2.csv'
df = pd.read_csv(file_path)
print(df.head())

# df = df.drop(['date_time'], axis=1)
# print(df.info())

sns.pairplot(df)
plt.show()

mask = np.tril(df.corr())
sns.heatmap(df.corr(), fmt='.1g', annot=True, cmap= 'cool', mask=mask)
plt.show()
# 'each_buyer_sales','product_page_views','search_clicks'
X = df.drop(['sale_grades','each_buyer_sales'], axis=1)
Y = df['sale_grades']

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.4)
print(X_train.shape,Y_train.shape,X_test.shape,Y_test.shape)

model = LinearRegression()
model.fit(X_train, Y_train)

print(model.intercept_)

coeff_df = pd.DataFrame(model.coef_, X.columns, columns =['Coefficient'])
print(coeff_df)

#驗証模型
y_pred = model.predict(X_test)

print('Mean Absolute Error:', metrics.mean_absolute_error(Y_test, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(Y_test, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(Y_test, y_pred)))
print('R Squared Score is:', r2_score(Y_test, y_pred))  # higher R² indicates a better fit for the model

# interpret and improve
X2 = sm.add_constant(X_train)
model_stats = sm.OLS(Y_train.values.reshape(-1,1), X2).fit()
print(model_stats.summary())

# #計算 50 for TV, 30 for radio and 10的收益
# example = [50, 30, 10]
# output = model.intercept_ + sum(example*model.coef_)
# print(f"Estimate Sales:{output}")

# example = [30, 50, 10]
# output = model.intercept_ + sum(example*model.coef_)
# print(f"Estimate Sales:{output}")

# example = [20, 50, 20]
# output = model.intercept_ + sum(example*model.coef_)
# print(f"Estimate Sales:{output}")


import pathlib
import hashlib
import shutil
import threading
import os
import logging
from pprint import pprint
from mutagen.easyid3 import EasyID3

class LocalFileInterfaz(object):
    def __init__(self, dirsInput=[], dirOutput=None):
        self.dirsInput = dirsInput
        self.dirOutput = dirOutput
        self.tipos = [".mp3", ".flac", ".aac", ".ogg", ".m4a"]
        self.localTracks = []
        self.templateTrack = {"titulo":"",
                "artista":"",
                "album":"",
                "path":""}

    def procesarDirsInput(self):
        self.localTracks = []
        for directorio in self.dirsInput:
            self.getPath(directorio = directorio)

    def getPath(self,directorio):
        lista = []
        for root, dirs, files in os.walk(directorio):
            for filename in files:
                t = threading.Thread(target=self.getDatos,args=(os.path.join(root, filename),lista,))
                t.start()
                t.join()
        self.localTracks.extend(lista)

    def getDatos(self, filename, lista):
        ext = pathlib.PurePosixPath(filename).suffix.lower()
        l = {"titulo":"",
                "artista":"",
                "album":"",
                "path":""}
        if ext in self.tipos:
            try:
                tag = EasyID3(filename)
                l["titulo"] = tag["title"][0]
                l["artista"] = tag["artist"]
                l["album"] = tag["album"][0]
                l["path"] = filename
                lista.append(l)
            except Exception as e:
                logging.error("Error con este archivo {} {}".format(filename, e))
        else:
            logging.info("Archivo no es audio {}".format(filename))

    def cpyArchivo(self, filnameIn):
        try:
            shutil.copy(filnameIn, self.dirOutput)
        except Exception as e:
            logging.error("Error al copiar archivo {} {}".format(filnameIn, e))

    def getLocalTracks(self):
        return self.localTracks


"""
    OMP CPU4.py
        by Tim Müller

    This file implements the analytical model for the fourth variation of the
    OpenMP CPU-optimised implementations.
"""

import sequential

# FORWARD PASS
def t_fwd(pi, beta, pi_simd, beta_simd, L, P):
    result = 0
    for l in range(1, L):
        result += P[l] * (sequential.t_f_sum(pi_simd, beta_simd, P[l - 1]) + sequential.t_f_act(pi, beta))
    return result

# BACKWARD PASS - HIDDEN
def t_bck_hid(pi, beta, pi_simd, beta_simd, L, P):
    result = 0
    for l in range(1, L - 1):
        result += t_bh_delta(pi, beta, pi_simd, beta_simd, P[l], P[l + 1]) + \
                  sequential.t_b_updbias(pi_simd, beta_simd, P[l]) + \
                  sequential.t_b_updweights(pi_simd, beta_simd, P[l - 1], P[l])
    return result

def t_bh_delta(pi, beta, pi_simd, beta_simd, p, p1):
    return p * (sequential.t_bh_sum(pi_simd, beta_simd, p1) + sequential.t_bh_comp(pi, beta))

# Use what we can from sequential, but take different pi's and beta's into account
def predict(sample_parameters, machine_parameters, n_threads):
    L = int(sample_parameters[0]) + 2
    P = [int(sample_parameters[4])] + [int(sample_parameters[1])] * (L - 2) + [int(sample_parameters[5])]
    N = int(sample_parameters[2])
    S = int(sample_parameters[3])

    pi = machine_parameters[n_threads][0] * 1000000000
    beta = machine_parameters[n_threads][1] * 1000000000
    pi_simd = machine_parameters[n_threads][2] * 1000000000
    beta_simd = machine_parameters[n_threads][3] * 1000000000

    fwd_time = t_fwd(pi, beta, pi_simd, beta_simd, L, P)
    bck_out_time = sequential.t_bck_out(pi_simd, beta_simd, L, P)
    bck_hid_time = t_bck_hid(pi, beta, pi_simd, beta_simd, L, P)
    updates_time = sequential.t_updates(pi_simd, beta_simd, L, P)
    total_time = N * (S * (fwd_time + bck_out_time + bck_hid_time) + updates_time)

    return [total_time, fwd_time, bck_out_time, bck_hid_time, updates_time]


from serializer import *
from struct import *
from smbus2 import SMBus, i2c_msg

i2c_bus = 0
address = 0x0f

def set_bus(bus_val, address_val):
    i2c_bus = bus_val
    address = address_val
    print(i2c_bus, address)

def get():
    with SMBus(i2c_bus) as bus:
        block = bytes(bus.read_i2c_block_data(address, 1, 16))
        out = unpack("<ffff", block)
        return out

def send_reset():
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, reset())
        bus.i2c_rdwr(msg)

def send_pid(p, i, d):
    with SMBus(i2c_bus) as bus:
        if p != None:
            #bus.write_block_data(address, 0, bytes(set_kp(p)))
            msg = i2c_msg.write(address, set_kp(p))
            bus.i2c_rdwr(msg)

        if i != None:
            msg = i2c_msg.write(address, set_ki(i))
            bus.i2c_rdwr(msg)

        if d != None:
            msg = i2c_msg.write(address, set_kd(d))
            bus.i2c_rdwr(msg)

def send_limits(pwm, max, min):
    print(pwm)
    with SMBus(i2c_bus) as bus:
        if pwm != None:
            msg = i2c_msg.write(address, limit_pwm(pwm))
            bus.i2c_rdwr(msg)

        if max != None:
            msg = i2c_msg.write(address, limit_target_max(max))
            bus.i2c_rdwr(msg)

        if min != None:
            msg = i2c_msg.write(address, limit_target_min(min))
            bus.i2c_rdwr(msg)

def send_enable(state):
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, enable(state))
        bus.i2c_rdwr(msg)

def send_mode_pwm():
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, mode_pwm())
        bus.i2c_rdwr(msg)

def send_mode_pid():
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, mode_pid())
        bus.i2c_rdwr(msg)

def send_mode_pnumatic():
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, mode_pnumatic())
        bus.i2c_rdwr(msg)

def send_target(value):
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, set_target(value))
        bus.i2c_rdwr(msg)

def send_homing_speed(value):
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, set_home(value))
        bus.i2c_rdwr(msg)

def send_encoder_pol(value):
    with SMBus(i2c_bus) as bus:
        msg = i2c_msg.write(address, encoder_polarity(value))
        bus.i2c_rdwr(msg)


"""
    Name: logFreqLogMag
    Date: Jun 2019
    Programmer: Christian Dittmar, Yiğitcan Özer

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    If you use the 'NMF toolbox' please refer to:
    [1] Patricio López-Serrano, Christian Dittmar, Yiğitcan Özer, and Meinard
        Müller
        NMF Toolbox: Music Processing Applications of Nonnegative Matrix
        Factorization
        In Proceedings of the International Conference on Digital Audio Effects
        (DAFx), 2019.

    License:
    This file is part of 'NMF toolbox'.
    https://www.audiolabs-erlangen.de/resources/MIR/NMFtoolbox/
    'NMF toolbox' is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by the
    the Free Software Foundation, either version 3 of the License, or (at
    your option) any later version.

    'NMF toolbox' is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details.

    You should have received a copy of the GNU General Public License along
    with 'NMF toolbox'. If not, see http://www.gnu.org/licenses/.
"""

import numpy as np

from nmfTools.NMFtoolbox.midi2freq import midi2freq

def logFreqLogMag(A, deltaF, binsPerOctave=36.0, upperFreq=22050.0, lowerFreq=midi2freq(24), logComp=1.0):
    """Given a magnitude spectrogram, this function maps it onto a compact
    representation with logarithmically spaced frequency axis and logarithmic
    magnitude compression.

    Parameters
    ----------
    A: array-like
        The real-valued magnitude spectrogram oriented as numBins x numFrames,
        it can also be given as a list of multiple spectrograms

    deltaF: array-like
        The spectral resolution of the spectrogram

    binsPerOctave: array-like
        The spectral selectivity of the log-freq axis

    upperFreq: float
        The upper frequency border

    lowerFreq: float
        The lower frequency border

    logComp: float
        Factor to control the logarithmic magnitude compression

    Returns
    -------
    logFreqLogMagA: array-like
        The log-magnitude spectrogram on logarithmically spaced frequency axis

    logFreqAxis: array-like
        An array giving the center frequencies of each bin along the
        logarithmically spaced frequency axis
    """

    # convert to list if necessary
    if not isinstance(A, list):
        wasArrInput = True
        A = [A]
    else:
        wasArrInput = False

    # get number of components
    numComp = len(A)

    logFreqLogMagA = list()

    for k in range(numComp):
        # get component spectrogram
        compA = A[k]

        # get dimensions
        numLinBins, numFrames = compA.shape

        # set up linear frequency axis
        linFreqAxis = np.arange(0, numLinBins) * deltaF

        # get upper limit
        upperFreq = linFreqAxis[-1]

        # set up logarithmic frequency axis
        numLogBins = np.ceil(binsPerOctave * np.log2(upperFreq / lowerFreq))
        logFreqAxis = np.arange(0, numLogBins)
        logFreqAxis = lowerFreq * np.power(2.0, logFreqAxis / binsPerOctave)

        # map to logarithmic axis by means of linear interpolation
        logBinAxis = logFreqAxis / deltaF

        # compute linear interpolation for the logarithmic mapping
        floorBinAxis = np.floor(logBinAxis).astype(np.int) - 1
        ceilBinAxis = floorBinAxis + 1
        fraction = logBinAxis - floorBinAxis - 1

        # get magnitude values
        floorMag = compA[floorBinAxis, :]
        ceilMag = compA[ceilBinAxis, :]

        # compute weighted sum
        logFreqA = floorMag * (1 - fraction).reshape(-1, 1) + ceilMag * fraction.reshape(-1, 1)

        # apply magnitude compression
        logFreqLogMagA.append(np.log(1 + (logComp * logFreqA)))

    # revert back to matrix if necessary
    if wasArrInput:
        logFreqLogMagA = np.array(logFreqLogMagA[0])

    return logFreqLogMagA, logFreqAxis.reshape(-1, 1)


# -*- coding: utf-8 -*-
"""
Created on Wed Mar  2 12:30:05 2022

@author: yyh
"""
import numpy as np
import pandas as pd
import os
import h5py
region = np.load('open_region.npy')  #Import candidate region files (open chromatin regions or TSS regions)
name = pd.read_excel("sample_ID.xlsx",sheet_name='Sheet1',usecols=[0])  #Sample ID of the dataset
name_array = np.array(name)
name_list = name_array.tolist()
n = len(name_list)
End = np.zeros([561414,n])  #Create a matrix to store the results

for i in range(1,n+1):
    print(i)
    nam = name_list[i-1]
    nam2 = "".join(nam)
    path = os.path.join("dataset_path",nam2,'data_n')   #Full path to the splice sample file
    pos = 0

    for j in range(1,23):  #Treat each chromosome sequentially
        j_str = str(j)
        mat = ''.join(['chr',j_str,'.mat'])
        mat2 = os.path.join(path,mat)
        mat3 = h5py.File(mat2,'r')
        #print(mat3.keys())
        read = np.transpose(mat3['read'])   #Extract the reads of the sample
        num = read.shape[0]

        region_len = mat3['region_len']  #Total length of chromosome extracted
        size = int(region_len[0,0])
        chrom = np.zeros([size,1])

        reg = region[region[:,0]==j]
        num2 = reg.shape[0]

        for k in range(1,num+1):
            end = int(read[k-1,0]+read[k-1,1]-1) #Counting the position and number of fragment ends
            chrom[end-1,0] += 1

        for m in range (1,num2+1):  #Counting the total number of fragment ends in each region
            End[pos+m-1,i-1] = sum(chrom[(reg[m-1,1]-1):reg[m-1,2],0])

        pos += num2

np.save('end.npy',End)


import unittest
import tools.data_helper as helper

class TestDataHelper(unittest.TestCase):

    def test_invalid_url_download_economic_accounts_for_agri(self):
        with self.assertRaises(SystemExit):
            helper.download_file('https://ec.europa.eu/eurostat/web/main/homsdfsde')

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


# Given an integer n, return the number of trailing zeroes in n!.

# Example 1:

# Input: 3
# Output: 0
# Explanation: 3! = 6, no trailing zero.

# Example 2:

# Input: 5
# Output: 1
# Explanation: 5! = 120, one trailing zero.

class Solution:

    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        x = 5
        ans = 0
        while n >= x:
            ans += n // x
            x *= 5
        return ans

print(Solution().trailingZeroes(1808548329))


from __future__ import print_function
import os
import sys
import pickle
import time
import matplotlib.pyplot as plt
import numpy as np
import h5py
import flowdatacheck_taxi
from keras.layers import (
    Input,
    Activation,
    merge,
    Dense,
    Reshape,
    Flatten,
    add,
    multiply,
GlobalAveragePooling2D
)
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.layers.convolutional import Conv2D, UpSampling2D, Conv2DTranspose
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import MaxPooling2D
from keras.models import Model
import numpy as np
from keras.optimizers import RMSprop, Adam

np.random.seed(1337)

X_train, Y_train, X_test, Y_test = flowdatacheck_taxi.X_train, flowdatacheck_taxi.Y_train, flowdatacheck_taxi.X_test, flowdatacheck_taxi.Y_test

def _shortcut(input, residual):
    return merge([input, residual], mode='sum')

def _bn_relu_conv(nb_filter, nb_row, nb_col, subsample=(1, 1), bn=False):
    def f(input):
        if bn:
            input = BatchNormalization(mode=0, axis=1)(input)
        activation = Activation('relu')(input)
        return Conv2D(64, (3, 3), strides=(1, 1), padding="same")(activation)
    return f

def _residual_unit(nb_filter, init_subsample=(1, 1)):
    def f(input):
        residual = _bn_relu_conv(nb_filter, 3, 3, subsample=init_subsample)(input)
        residual = _bn_relu_conv(nb_filter, 3, 3, subsample=init_subsample)(residual)
        return _shortcut(input, residual)
    return f

def SE_block_T(len_seq):
    def f(input):
        excitation = Flatten()(input)
        #excitation = GlobalAveragePooling2D()(input)
        excitation = Dense(output_dim=64, activation='relu')(excitation)
        excitation = Dense(output_dim=10 * 20 * len_seq*2, activation='sigmoid')(excitation)
        excitation = Reshape((len_seq*2, 10, 20))(excitation)
        return excitation
    return f

def SE_block():
    def f(input):
        excitation = Flatten()(input)
        excitation = Dense(output_dim=64, activation='relu')(excitation)
        excitation = Dense(output_dim=10 * 20 * 64, activation='sigmoid')(excitation)
        excitation = Reshape((64, 10, 20))(excitation)
        return excitation
    return f

def down_up_block():
    def f(input):
        input = Conv2D(64, kernel_size=(3, 3), strides=(1, 1), activation='relu', padding='same')(input)
        #input = MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(input)

        #input = MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(input)
        input = Conv2D(64, kernel_size=(3, 3), strides=(1, 1), activation='sigmoid', padding='same')(input)
        input = Conv2DTranspose(64, kernel_size=(3, 3), strides=(1, 1), activation='sigmoid', padding='same')(input)

        input = Conv2DTranspose(64, kernel_size=(3, 3), strides=(1, 1), activation='sigmoid', padding='same')(input)
        return input
    return f

def ResUnits(nb_filter, block_repetations=1):
    def f(input):
        for i in range(block_repetations):
            init_subsample = (1, 1)
            input = _residual_unit(nb_filter=nb_filter,
                                  init_subsample=init_subsample)(input)
        return input
    return f

def AttenResUnits(nb_filter, block_repetations=1):
    def f(input):
        for i in range(block_repetations):
            #down_up_input = down_up_block()(input)
            SE_block_input = SE_block()(input)
            init_subsample = (1, 1)
            input = _residual_unit(nb_filter=nb_filter,
                                  init_subsample=init_subsample)(input)
            #M_x = merge([down_up_input, input], mode='mul')
            M_x = merge([SE_block_input, input], mode='mul')
        return M_x
    return f

def stresnet(c_conf=(4, 2, 10, 20), p_conf=(3, 2, 10, 20), t_conf=(1, 2, 10, 20), nb_residual_unit=1):
    '''
    C - Temporal Closeness
    P - Period
    T - Trend
    conf = (len_seq, nb_flow, map_height, map_width)
    external_dim
    '''

    # main input
    main_inputs = []
    outputs = []
    for conf in [c_conf, p_conf, t_conf]:
        if conf is not None:
            len_seq, nb_flow, map_height, map_width = conf
            input = Input(shape=(nb_flow * len_seq, map_height, map_width))
            main_inputs.append(input)

            if len_seq != 1:
                SE_block_t = SE_block_T(len_seq=len_seq)(input)
                input = merge([SE_block_t, input], mode='mul')

            # Conv1
            conv1 = Conv2D(64, kernel_size=(3, 3), strides=(1, 1), padding="same")(input)
            # [nb_residual_unit] Residual Units
            #residual_output = ResUnits(nb_filter=64, block_repetations=nb_residual_unit)(conv1)
            residual_output = AttenResUnits(nb_filter=64, block_repetations=nb_residual_unit)(conv1)
            #residual_output = SE_ResUnits(block_repetations=nb_residual_unit)(conv1)
            # Conv2
            activation = Activation('relu')(residual_output)
            conv2 = Conv2D(64, kernel_size=(3, 3), strides=(1, 1), padding="same")(activation)
            outputs.append(conv2)

    # parameter-matrix-based fusion
    if len(outputs) == 1:
        main_output = outputs[0]
    else:
        import iLayer
        new_outputs = []
        for output in outputs:
            new_outputs.append(iLayer.iLayer()(output))
        main_output = merge(outputs, mode='sum')

    conv3 = Conv2D(2, kernel_size=(3, 3), strides=(1, 1), padding="same")(main_output)

    main_output = Activation('sigmoid')(conv3)
    model = Model(input=main_inputs, output=main_output)

    return model

def rmse(Y_true, Y_pred):
    # https://www.kaggle.com/wiki/RootMeanSquaredError
    from sklearn.metrics import mean_squared_error
    print("===RMSE===")
    # in
    RMSE = mean_squared_error(Y_true[:, 0].flatten(), Y_pred[:, 0].flatten())**0.5
    print('inflow: ', RMSE)
    print(RMSE*1289)
    # out
    if Y_true.shape[1] > 1:
        RMSE = mean_squared_error(Y_true[:, 1].flatten(), Y_pred[:, 1].flatten())**0.5
        print('outflow: ', RMSE)
        print(RMSE * 1289)

    RMSE = mean_squared_error(Y_true.flatten(), Y_pred.flatten())**0.5

    print("total rmse: ", RMSE)
    print(RMSE * 1289)

    print("===RMSE===")
    return RMSE

def mean_absolute_percentage_error(y_true, y_pred):
    idx = np.nonzero(y_true)
    return np.mean(np.abs((y_true[idx] - y_pred[idx]) / y_true[idx])) * 100

def eval_threshold(y, pred_y, threshold=0.007758):
    pickup_y = y[:, 0]
    dropoff_y = y[:, 1]
    pickup_pred_y = pred_y[:, 0]
    dropoff_pred_y = pred_y[:, 1]
    pickup_mask = pickup_y > threshold
    dropoff_mask = dropoff_y > threshold
    print("===eval_threshold===")
    #pickup part
    if np.sum(pickup_mask)!=0:
        avg_pickup_mape = np.mean(np.abs(pickup_y[pickup_mask]-pickup_pred_y[pickup_mask])/pickup_y[pickup_mask])
        avg_pickup_rmse = np.sqrt(np.mean(np.square(pickup_y[pickup_mask]-pickup_pred_y[pickup_mask])))
        print('inflowRMSE: ', avg_pickup_rmse)
        print(avg_pickup_rmse*1289)
        print('inflowMAPE: ', avg_pickup_mape)
    #dropoff part
    if np.sum(dropoff_mask)!=0:
        avg_dropoff_mape = np.mean(np.abs(dropoff_y[dropoff_mask]-dropoff_pred_y[dropoff_mask])/dropoff_y[dropoff_mask])
        avg_dropoff_rmse = np.sqrt(np.mean(np.square(dropoff_y[dropoff_mask]-dropoff_pred_y[dropoff_mask])))
        print('outflowRMSE: ', avg_dropoff_rmse)
        print(avg_dropoff_rmse * 1289)
        print('outflowMAPE: ', avg_dropoff_mape)

    return (avg_pickup_rmse, avg_pickup_mape), (avg_dropoff_rmse, avg_dropoff_mape)

def eval_threshold_all(y, pred_y, threshold=0.007758):
    pickup_y = y

    pickup_pred_y = pred_y

    pickup_mask = pickup_y > threshold

    print("===eval_threshold_all===")
    #pickup part
    if np.sum(pickup_mask)!=0:
        avg_pickup_mape = np.mean(np.abs(pickup_y[pickup_mask]-pickup_pred_y[pickup_mask])/pickup_y[pickup_mask])
        avg_pickup_rmse = np.sqrt(np.mean(np.square(pickup_y[pickup_mask]-pickup_pred_y[pickup_mask])))
        print('allRMSE: ', avg_pickup_rmse)
        print(avg_pickup_rmse*1289)
        print('allMAPE: ', avg_pickup_mape)
    return (avg_pickup_rmse, avg_pickup_mape)

def mape(Y_true, Y_pred):
    print("===MAPE===")
    # in
    MAPE = mean_absolute_percentage_error(Y_true[:, 0].flatten(), Y_pred[:, 0].flatten())
    print("inflow: ", MAPE)
    # out
    MAPE = mean_absolute_percentage_error(Y_true[:, 1].flatten(), Y_pred[:, 1].flatten())
    print("outflow: ", MAPE)
    MAPE = mean_absolute_percentage_error(Y_true.flatten(), Y_pred.flatten())
    print("total mape: ", MAPE)
    print("===MAPE===")
    return MAPE

def draw(Y_true, Y_pred, flow=0, r=5, c=11, yl=1000):
    y_true1 = Y_true[:, flow, r, c].flatten()
    y_pred1 = Y_pred[:, flow, r, c].flatten()
    x1 = range(len(y_true1))
    x2 = range(len(y_pred1))
    y_true1 = y_true1 * 1289
    y_pred1 = y_pred1 * 1289

    plt.plot(x1, y_true1, color="red", linewidth=1, linestyle="-", label="ground truth")
    plt.plot(x2, y_pred1, color="blue", linewidth=1, linestyle="-", label="prediction")
    plt.xlim(0, len(y_true1))
    plt.ylim(0, yl)
    plt.show()

def drawday(Y_true, Y_pred, flow=0, r=5, c=11, yl=1000, days=10, daye=106):
    y_true1 = Y_true[:, flow, r, c].flatten()
    y_pred1 = Y_pred[:, flow, r, c].flatten()
    x1 = range(len(y_true1))
    x2 = range(len(y_pred1))
    y_true1 = y_true1 * 1289
    y_pred1 = y_pred1 * 1289

    plt.plot(x1, y_true1, color="red", linewidth=1, linestyle="-", label="ground truth")
    plt.plot(x2, y_pred1, color="blue", linewidth=1, linestyle="-", label="prediction")
    plt.xlim(days, daye )
    plt.ylim(0, yl)
    plt.show()

if __name__ == '__main__':
    len_closeness = 4
    len_period = 3
    len_trend = 1
    nb_residual_unit = 1
    lr = 0.0001
    nb_epoch = 500  # number of epoch at training stage
    nb_epoch_cont = 100  # number of epoch at training (cont) stage
    batch_size = 32  # batch size
    T = 48  # number of time intervals in one day
    path_result = 'RET'
    if os.path.isdir(path_result) is False:
        os.mkdir(path_result)
    path_model = 'MODEL'
    if os.path.isdir(path_model) is False:
        os.mkdir(path_model)

    # rmsprop = RMSprop(lr=0.00045, decay=0.0)
    rmsprop = Adam(lr=lr)
    stresnet = stresnet(nb_residual_unit=nb_residual_unit)
    stresnet.compile(optimizer=rmsprop, loss='mse', )
    stresnet.summary()
    hyperparams_name = 'c{}.p{}.t{}.resunit{}.lr{}'.format(
        len_closeness, len_period, len_trend, nb_residual_unit, lr)
    fname_param = os.path.join('MODEL', '{}.best.h5'.format(hyperparams_name))
    early_stopping = EarlyStopping(monitor='val_loss', patience=20, mode='min')
    model_checkpoint = ModelCheckpoint(fname_param, monitor='val_loss', verbose=0, save_best_only=True, mode='min')

    print('=' * 10)
    print("training model...")
    ts = time.time()
    history = stresnet.fit(X_train, Y_train,
                           epochs=nb_epoch,
                           batch_size=batch_size,
                           validation_split=0.1,
                           callbacks=[early_stopping, model_checkpoint],
                           verbose=1)
    stresnet.save_weights(os.path.join(
        'MODEL', '{}.h5'.format(hyperparams_name)), overwrite=True)
    pickle.dump((history.history), open(os.path.join(
        path_result, '{}.history.pkl'.format(hyperparams_name)), 'wb'))
    print("\nelapsed time (training): %.3f seconds\n" % (time.time() - ts))

    print('=' * 10)
    print('evaluating using the model that has the best loss on the valid set')
    ts = time.time()
    stresnet.load_weights(fname_param)
    score = stresnet.evaluate(X_train, Y_train, batch_size=Y_train.shape[
                                                               0], verbose=0)
    print('Train mse : %.6f rmse (real): %.6f' %
          (score, (score ** 0.5) * (1283 - 0)))
    score = stresnet.evaluate(
        X_test, Y_test, batch_size=Y_test.shape[0], verbose=0)
    print('Test mse : %.6f rmse (real): %.6f' %
          (score, (score ** 0.5) * (1289 - 0)))
    print("\nelapsed time (eval): %.3f seconds\n" % (time.time() - ts))

    print('=' * 10)
    print("training model (cont)...")
    ts = time.time()
    fname_param = os.path.join(
        'MODEL', '{}.cont.best.h5'.format(hyperparams_name))
    model_checkpoint = ModelCheckpoint(
        fname_param, monitor='val_loss', verbose=0, save_best_only=True, mode='min')

    history = stresnet.fit(X_train, Y_train, epochs=nb_epoch_cont, verbose=1, batch_size=batch_size,
                           callbacks=[model_checkpoint])

    pickle.dump((history.history), open(os.path.join(
        path_result, '{}.cont.history.pkl'.format(hyperparams_name)), 'wb'))
    stresnet.save_weights(os.path.join(
        'MODEL', '{}_cont.h5'.format(hyperparams_name)), overwrite=True)
    print("\nelapsed time (training cont): %.3f seconds\n" % (time.time() - ts))

    print('=' * 10)
    print('evaluating using the final model')
    score = stresnet.evaluate(X_train, Y_train, batch_size=Y_train.shape[0], verbose=0)
    print('Train mse (norm): %.6f rmse (real): %.6f' %
          (score, (score ** 0.5) * (1283 - 0)))
    ts = time.time()
    score = stresnet.evaluate(X_test, Y_test, batch_size=32, verbose=0)
    print('Test mse (norm): %.6f rmse (real): %.6f' %(score, (score ** 0.5) * (1289 - 0)))
    print("\nelapsed time (eval cont): %.3f seconds\n" % (time.time() - ts))

    print('\nTesting ------------')


def hi():
  print("django")
hi()
if 2>2:
  print("gopika")
else:
  print("haris")
def hello(name):
  print("hai "+  name)
hello("lbs")
girls=['gopika','arya']
for name in girls:
  hello(name)


# Baekjoon 1541
# Silver 2
# 그리디

eq = input()
try:
    eq.index("-")
    res = 0
    for i, sen in enumerate(eq.split("-")):
        if i == 0:
            for nums in sen.split("+"):
                res += int(nums)
        else:
            part_res = 0
            for nums in sen.split("+"):
                part_res += int(nums)
            res -= part_res
    print(res)
except:
    res = 0
    for nums in eq.split("+"):
        res += int(nums)
    print(res)


from replit import clear
from art import logo

print(logo)
continue_prog = True
bid = {}

while continue_prog:

    name = input("Enter your name: ")
    bid_amount = int(input("Enter your bid: $"))

    bid[name] = bid_amount

    other_bidders = input("Any other biders? Type 'Yes' or 'No': ").lower()

    highest_bid = 0
    for highest in bid:
        if bid[highest] > highest_bid:
            highest_bid = bid[highest]
            highest_bidder = highest
    print(f"Highest bidder is {highest_bidder} with the bid of ${highest_bid}.")

    if other_bidders == 'yes':
        clear()
    else:
        continue_prog = False
        print(f"Highest bidder is {highest_bidder} with the bid of ${highest_bid}.")


A, B, C, D, E, F = map(int, input().split())

water = set()
for i in range(F//(100*A) + 1):
    for j in range(F // (100*B) + 1):
        if 100*A * i + 100*j*B <= F:
            water |= {100*A * i + 100*j*B}
        else:
            break

sugar = set()
for i in range(F//C + 1):
    for j in range(F // D + 1):
        if C * i + D*j <= F:
            sugar |= {C * i + D*j}
        else:
            break
ans = [100*A, 0]
for x in water:
    if x == 0:
        continue
    for y in sugar:
        if x + y <= F and y <= (x/100)*E:
            if ans[1]/ans[0] < y / (x+y):
                ans = [x+y, y]

print(ans[0], ans[1])


import pickle
from flask import Flask, request, jsonify, make_response

app = Flask("IA API")

# ========= CONSTANTES =========
COLUNAS_ANALISE_SOLO_CULTURA = ["Nitrogênio", "Fósforo", "Potássio", "Temperatura", "Umidade", "pH", "Chuva"]
COLUNAS_ANALISE_SOLO_FERTILIZANTE = ["Temperatura", "Umidade do Ar", "Umidade do Solo", "Nitrogênio",
                                     "Potássio", "Fósforo"]
COLUNAS_ANALISE_AGUA = ["Alumínio", "Amônia", "Arsênio", "Bário", "Cádmio", "Cloro", "Cromo",
                        "Cobre", "Flúor", "Bactérias", "Vírus", "Chumbo", "Nitrato", "Nitrito",
                        "Mercúrio", "Perclorato", "Rádio", "Selênio", "Prata", "Urânio"]
COLUNAS_PREVISAO_SAFRA = ["Cultura", "Ano", "Pesticidas (ton)", "Temperatura", "Chuva Anual"]
COLUNAS_RECOMENDACAO_IRRIGACAO = ["Cultura", "Dias Ativos (Cultura)", "Umidade do Solo",
                                  "Temperatura", "Umidade do Ar"]
COLUNAS_RECOMENDACAO_PESTICIDA = ["Quantidade de Insetos", "Uso de Pesticida", "Número de Doses Semanais",
                                  "Número de Semanas de Uso", "Número de Semanas sem Uso"]
DICIONARIO_ANALISE_SOLO_CULTURA = {
    0: 'Arroz',
    1: 'Milho',
    2: 'Juta',
    3: 'Algodão',
    4: 'Coco',
    5: 'Mamão',
    6: 'Laranja',
    7: 'Maçã',
    8: 'Melão',
    9: 'Melancia',
    10: 'Uva',
    11: 'Manga',
    12: 'Banana',
    13: 'Romã',
    14: 'Lentilha',
    15: 'Feijão Preto',
    16: 'Feijão Fradinho',
    17: 'Feijão Mariposa',
    18: 'Feijão Guandu',
    19: 'Feijão Roxo',
    20: 'Grão de Bico',
    21: 'Café'
}
DICIONARIO_ANALISE_SOLO_FERTILIZANTE = {
    0: 'Ureia',
    1: 'Fosfato Diamônico (DAP)',
    2: 'Fertilizante Proporção 28-28-0',
    3: 'Fertilizante Proporção 14-35-14',
    4: 'Fertilizante Proporção 20-20',
    5: 'Fertilizante Proporção 17-17-17',
    6: 'Fertilizante Proporção 10-26-26'
}
DICIONARIO_ANALISE_AGUA = {
    0: "Insalubre",
    1: "Potável"
}
DICIONARIO_CULTURAS_PREVISAO_SAFRA = {
    "Mandioca": 0,
    "Milho": 1,
    "Batata": 2,
    "Arroz": 3,
    "Sorgo": 4,
    "Soja": 5,
    "Batata Doce": 6,
    "Trigo": 7,
    "Inhame": 8
}
DICIONARIO_CULTURAS_RECOMENDACAO_IRRIGACAO = {
    "Cana-de-Açúcar": 0,
    "Trigo": 1,
    "Batata": 2,
    "Arroz": 3,
    "Café": 4,
    "Amendoim": 5,
    "Flores": 6,
    "Milho": 7,
    "Vagem": 8
}
DICIONARIO_USO_PESTICIDA = {
    "Nunca Usado Anteriormente": 1,
    "Usado Anteriormente": 2,
    "Usando Atualmente": 3
}
DICIONARIO_RECOMENDACAO_IRRIGACAO = {
    0: "Irrigação não é necessária.",
    1: "Irrigação recomendada."
}
DICIONARIO_RECOMENDACAO_PESTICIDA = {
    0: "O uso de pesticidas está a discrição do produtor.",
    1: "O uso de pesticidas não é recomendado nessa semana.",
    2: "O uso de pesticidas é recomendado nessa semana."
}

# ========= FUNÇÕES =========
"""
Cada rota da API aceitará somente um conjunto específico de parâmetros para o modelo. Caso a requisição
seja feita com parâmetros incorretos ou fora de ordem, a resposta será um erro HTTP 400. Essa função
compara os dados JSON enviados no pedido POST com os parâmetros e verifica se o pedido é válido.
"""
def verificar_colunas(dados: dict, colunas: list):
    if list(dados.keys()) != colunas:
        resposta = make_response(
            jsonify(
                {"Aviso!": f"As colunas enviadas não estão de acordo com o exigido. O conjunto correto é {colunas}"}),
            400)
        resposta.headers["Content-Type"] = "application/json"
        return resposta
    else:
        return False

"""
Uma vez que as colunas tenham sido verificadas, o modelo é invocado e utilizado para prever o resultado
com base nos parâmetros. Como o resultado é numérico, um dicionário com as respostas equivalentes ao
entregue deve ser usado para a conversão antes de envio da resposta. Essa função realiza esse processo
por inteiro.
"""
def resposta_modelo(dados: dict, modelo_arquivo: str, dicionario: dict):
    modelo = pickle.load(open(modelo_arquivo, "rb")) # Importando o modelo
    resultado = modelo.predict([list(dados.values())]) # Prevendo o resultado
    resultado = dicionario[resultado[0]] # Transformando o resultado para algo legível
    resposta = make_response(
        jsonify(
            {"Resposta": f"{resultado}"}),
        200)
    resposta.headers["Content-Type"] = "application/json"
    return resposta

"""
Alguns modelos tem como seus parâmetros strngs. Logo, é necessário verificar se a string enviada no
POST contempla as possíveis que o modelo abrange. Essa função faz isso.
"""
def verificar_valores(valor: str, dicionario: dict, parametro: str):
    if valor not in dicionario.keys():
        resposta = make_response(
        jsonify(
            {"Aviso!": f"Valor inválido! Os valores disponíveis para {parametro} são {list(dicionario.keys())}"}),
        400)
        resposta.headers["Content-Type"] = "application/json"
        return resposta
    else:
        return False

# ========= ROTAS DA API =========
# Rota para a previsão de culturas (Análise do Solo)
@app.route("/analise/solo/cultura/", methods=["POST"])
def previsao_cultura():
    dados = request.get_json()

    if not verificar_colunas(dados, COLUNAS_ANALISE_SOLO_CULTURA):
        return resposta_modelo(dados, "modelos/analise_cultura.sav", DICIONARIO_ANALISE_SOLO_CULTURA)
    else:
        return verificar_colunas(dados, COLUNAS_ANALISE_SOLO_CULTURA)

# Rota para a recomendação de fertilizantes (Análise do Solo)
@app.route("/analise/solo/fertilizante/", methods=["POST"])
def previsao_fertilizante():
    dados = request.get_json()

    if not verificar_colunas(dados, COLUNAS_ANALISE_SOLO_FERTILIZANTE):
        return resposta_modelo(dados, "modelos/analise_fertilizante.sav", DICIONARIO_ANALISE_SOLO_FERTILIZANTE)
    else:
        return verificar_colunas(dados, COLUNAS_ANALISE_SOLO_FERTILIZANTE)

# Rota para a indicação de água potável (Análise de Água)
@app.route("/analise/agua/", methods=["POST"])
def previsao_agua():
    dados = request.get_json()

    if not verificar_colunas(dados, COLUNAS_ANALISE_AGUA):
        return resposta_modelo(dados, "modelos/analise_agua.sav", DICIONARIO_ANALISE_AGUA)
    else:
        return verificar_colunas(dados, COLUNAS_ANALISE_AGUA)

# Rota para a Recomendação de Irrigação
@app.route("/recomendacao/irrigacao/", methods = ["POST"])
def previsao_irrigacao():
    dados = request.get_json()
    if not verificar_colunas(dados, COLUNAS_RECOMENDACAO_IRRIGACAO):
        dados = list(dados.values())
        if not verificar_valores(dados[0], DICIONARIO_CULTURAS_RECOMENDACAO_IRRIGACAO, "culturas"):
            dados[0] = DICIONARIO_CULTURAS_RECOMENDACAO_IRRIGACAO[dados[0]] # Transformando a string em número
            modelo = pickle.load(open("modelos/recomendacao_irrigacao.sav", "rb")) # Importando o modelo
            resultado = modelo.predict([dados]) # Prevendo o resultado
            resultado = DICIONARIO_RECOMENDACAO_IRRIGACAO[resultado[0]]
            resposta = make_response(
                jsonify(
                    {"Recomendação": f"{resultado}"}),
                200)
            resposta.headers["Content-Type"] = "application/json"
            return resposta
        else:
            return verificar_valores(dados[0], DICIONARIO_CULTURAS_RECOMENDACAO_IRRIGACAO, "culturas")
    else:
        return verificar_colunas(dados, COLUNAS_RECOMENDACAO_IRRIGACAO)

# Rota para a recomendação de pesticidas.
@app.route("/recomendacao/pesticida/", methods = ["POST"])
def previsao_pesticida():
    dados = request.get_json()
    if not verificar_colunas(dados, COLUNAS_RECOMENDACAO_PESTICIDA):
        dados = list(dados.values())
        if not verificar_valores(dados[1], DICIONARIO_USO_PESTICIDA, "uso de pesticida"):
            dados[1] = DICIONARIO_USO_PESTICIDA[dados[1]]
            modelo = pickle.load(open("modelos/recomendacao_pesticida.sav", "rb"))
            resultado = modelo.predict([dados])
            resultado = DICIONARIO_RECOMENDACAO_PESTICIDA[resultado[0]]
            resposta = make_response(
                jsonify(
                    {"Recomendação": f"{resultado}"}),
                200)
            resposta.headers["Content-Type"] = "application/json"
            return resposta
        else:
            return verificar_valores(dados[1], DICIONARIO_USO_PESTICIDA, "uso de pesticida")
    else:
        return verificar_colunas(dados, COLUNAS_RECOMENDACAO_PESTICIDA)

"""
Rota para a previsão de safra

Essa rota é um pouco especial por se tratar de um caso de regressão, e não de classificação. Logo,
ao invés de fazer uso da função resposta_modelo, a predição é feita de modo "manual".

Pequena observação: o resultado do modelo é em Hectogramas por Hectare, mas o mesmo é convertido
para Kilogramas por Hectare em prol de retorna uma resposta que possibilita melhor entendimento.
"""
@app.route("/previsao/safra/", methods=["POST"])
def previsao_safra():
    dados = request.get_json()

    if not verificar_colunas(dados, COLUNAS_PREVISAO_SAFRA):
        dados = list(dados.values()) # Extraindo os valores

        if not verificar_valores(dados[0], DICIONARIO_CULTURAS_PREVISAO_SAFRA, "culturas"):
            dados[0] = DICIONARIO_CULTURAS_PREVISAO_SAFRA[dados[0]] # Transformando a string em número
            modelo = pickle.load(open("modelos/previsao_safra.sav", "rb")) # Importando o modelo
            resultado = modelo.predict([dados]) # Prevendo o resultado
            resposta = make_response(
                jsonify(
                    {"Previsão": f"{resultado[0]/10 :.2f} Kilogramas por Hectare"}),
                200)
            resposta.headers["Content-Type"] = "application/json"
            return resposta
        else:
            return verificar_valores(dados[0], DICIONARIO_CULTURAS_PREVISAO_SAFRA, "culturas")

    else:
        return verificar_colunas(dados, COLUNAS_PREVISAO_SAFRA)

app.run(host = "0.0.0.0", debug=False)


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def searchBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if root is None:
            return None

        # 用二叉树的先序遍历直接做
        return self.preOrderTraverse(root, val)

    def preOrderTraverse(self, root, val):

        nodes = []

        nodes.append(root)

        while len(nodes) > 0:
            node = nodes.pop()

            if node.val == val:
                return node

            else:
                if node.right is not None:
                    nodes.append(node.right)

                if node.left is not None:
                    nodes.append(node.left)

        return None


import isolearn.keras as iso

import numpy as np

import pandas as pd

import scipy.sparse as sp
import scipy.io as spio

import matplotlib.pyplot as plt

import seaborn as sns

def plot_logo_w_hexamer_scores(pwm, iso_pred, cut_pred, hexamer_scores, cse_start_pos=70, annotate_peaks=None, sequence_template=None, figsize=(12, 3), width_ratios=[1, 7], logo_height=1.0, usage_unit='log', plot_start=0, plot_end=164, save_figs=False, fig_name=None, fig_dpi=300) :

    n_samples = pwm.shape[0]

    #Slice according to seq trim index
    pwm = pwm[:, plot_start: plot_end, :]
    cut_pred = cut_pred[:, plot_start: plot_end]
    sequence_template = sequence_template[plot_start: plot_end]

    iso_pred = np.mean(iso_pred, axis=0)
    cut_pred = np.mean(cut_pred, axis=0)
    pwm = np.sum(pwm, axis=0)

    pwm += 0.0001
    for j in range(0, pwm.shape[0]) :
        pwm[j, :] /= np.sum(pwm[j, :])

    entropy = np.zeros(pwm.shape)
    entropy[pwm > 0] = pwm[pwm > 0] * -np.log2(pwm[pwm > 0])
    entropy = np.sum(entropy, axis=1)
    conservation = 2 - entropy

    fig = plt.figure(figsize=figsize)

    gs = gridspec.GridSpec(2, 2, width_ratios=[width_ratios[0], width_ratios[-1]], height_ratios=[1, 1])

    ax0 = plt.subplot(gs[0, 0])
    ax1 = plt.subplot(gs[0, 1])
    ax2 = plt.subplot(gs[1, 0])
    ax3 = plt.subplot(gs[1, 1])

    plt.sca(ax0)
    plt.axis('off')
    plt.sca(ax2)
    plt.axis('off')

    annot_text = 'Samples = ' + str(int(n_samples))
    if usage_unit == 'log' :
        annot_text += '\nUsage = ' + str(round(np.log(iso_pred[0] / (1. - iso_pred[0])), 4))
    else :
        annot_text += '\nUsage = ' + str(round(iso_pred[0], 4))

    ax2.text(0.99, 0.5, annot_text, horizontalalignment='right', verticalalignment='center', transform=ax2.transAxes, color='black', fontsize=12, weight="bold")

    l2, = ax1.plot(np.arange(plot_end - plot_start), cut_pred, linewidth=3, linestyle='-', label='Predicted', color='red', alpha=0.7)

    if annotate_peaks is not None :
        objective_pos = 0
        if annotate_peaks == 'max' :
            objective_pos = np.argmax(cut_pred)
        else :
            objective_pos = annotate_peaks - plot_start

        text_x, text_y, ha = -30, -5, 'right'
        if objective_pos < 30 :
            text_x, text_y, ha = 30, -5, 'left'

        annot_text = '(CSE+' + str(objective_pos + plot_start - (cse_start_pos + 6) + 0) + ') ' + str(int(round(cut_pred[objective_pos] * 100, 0))) + '% Cleavage'
        ax1.annotate(annot_text, xy=(objective_pos, cut_pred[objective_pos]), xycoords='data', xytext=(text_x, text_y), ha=ha, fontsize=10, weight="bold", color='black', textcoords='offset points', arrowprops=dict(connectionstyle="arc3,rad=-.1", headlength=8, headwidth=8, shrink=0.15, width=1.5, color='black'))

    plt.sca(ax1)

    plt.xlim((0, plot_end - plot_start))
    #plt.ylim((0, 2))
    plt.xticks([], [])
    plt.yticks([], [])
    plt.legend(handles=[l2], fontsize=12, prop=dict(weight='bold'), frameon=False)
    plt.axis('off')

    height_base = (1.0 - logo_height) / 2.

    for j in range(0, pwm.shape[0]) :
        sort_index = np.argsort(pwm[j, :])

        for ii in range(0, 4) :
            i = sort_index[ii]

            nt_prob = pwm[j, i] * conservation[j]

            nt = ''
            if i == 0 :
                nt = 'A'
            elif i == 1 :
                nt = 'C'
            elif i == 2 :
                nt = 'G'
            elif i == 3 :
                nt = 'T'

            color = None
            if sequence_template[j] != 'N' :
                color = 'black'

            if ii == 0 :
                letterAt(nt, j + 0.5, height_base, nt_prob * logo_height, ax3, color=color)
            else :
                prev_prob = np.sum(pwm[j, sort_index[:ii]] * conservation[j]) * logo_height
                letterAt(nt, j + 0.5, height_base + prev_prob, nt_prob * logo_height, ax3, color=color)

            text_x, text_y, ha = -30, -5, 'right'
            if objective_pos < 30 :
                text_x, text_y, ha = 30, -5, 'left'

            if j < len(hexamer_scores) :
                #annot_text = str(hexamer_scores[j][0]) + " = " + str(round(hexamer_scores[j][1], 2))

                annot_text = str(hexamer_scores[j][1])
                ax3.text(j + 0.25, 2.0, annot_text, size=50, rotation=90., ha="left", va="bottom", fontsize=8, weight="bold", color='black')

    plt.sca(ax3)

    plt.xlim((0, plot_end - plot_start))
    plt.ylim((0, 2.5))
    plt.xticks([], [])
    plt.yticks([], [])
    plt.axis('off')
    ax3.axhline(y=0.01 + height_base, color='black', linestyle='-', linewidth=2)

    for axis in fig.axes :
        axis.get_xaxis().set_visible(False)
        axis.get_yaxis().set_visible(False)

    plt.tight_layout()

    if save_figs :
        plt.savefig(fig_name + '.png', transparent=True, dpi=fig_dpi)
        plt.savefig(fig_name + '.svg')
        plt.savefig(fig_name + '.eps')

    plt.show()
    #plt.close()

mer6_dict = {}
i = 0
for b1 in ['A', 'C', 'G', 'T'] :
    for b2 in ['A', 'C', 'G', 'T'] :
        for b3 in ['A', 'C', 'G', 'T'] :
            for b4 in ['A', 'C', 'G', 'T'] :
                for b5 in ['A', 'C', 'G', 'T'] :
                    for b6 in ['A', 'C', 'G', 'T'] :
                        mer6_dict[b1 + b2 + b3 + b4 + b5 + b6] = i
                        i += 1

def get_hexamer_pred_both_regions(seq) :
    preds = []
    for cell_line, w, w_0 in zip(['hek', 'hela', 'mcf7', 'cho'], [hek_both_regions_w, hela_both_regions_w, mcf7_both_regions_w, cho_both_regions_w], [hek_both_regions_w_0, hela_both_regions_w_0, mcf7_both_regions_w_0, cho_both_regions_w_0]) :
        pred = w_0

        region_1 = seq[5: 40]
        for j in range(0, len(region_1) - 5) :
            pred += w[mer6_dict[region_1[j: j+6]]]

        region_2 = seq[48: 83]
        for j in range(0, len(region_2) - 5) :
            pred += w[4096 + mer6_dict[region_2[j: j+6]]]

        preds.append(1. / (1. + np.exp(-pred)))

    return np.array(preds)

def get_hexamer_diff_scores_both_regions(seq, cell_1, cell_2) :
    scores = []

    w_dict = {
        'hek' : hek_both_regions_w,
        'hela' : hela_both_regions_w,
        'mcf7' : mcf7_both_regions_w,
        'cho' : cho_both_regions_w
    }

    w_cell_1 = w_dict[cell_1]
    w_cell_2 = w_dict[cell_2]

    scores.extend([('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', '')])

    region_1 = seq[5: 40]
    for j in range(0, len(region_1) - 5) :
        hexamer_score_cell_1 = w_cell_1[mer6_dict[region_1[j: j+6]]]
        hexamer_score_cell_2 = w_cell_2[mer6_dict[region_1[j: j+6]]]

        scores.append((region_1[j: j+6], str(round(hexamer_score_cell_1 - hexamer_score_cell_2, 2))))

    scores.extend([('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', '')])

    region_2 = seq[48: 83]
    for j in range(0, len(region_2) - 5) :
        hexamer_score_cell_1 = w_cell_1[4096 + mer6_dict[region_2[j: j+6]]]
        hexamer_score_cell_2 = w_cell_2[4096 + mer6_dict[region_2[j: j+6]]]

        scores.append((region_2[j: j+6], str(round(hexamer_score_cell_1 - hexamer_score_cell_2, 2))))

    return scores

def get_hexamer_preds_both_regions(seqs) :
    preds = np.zeros((len(seqs), 4))

    for i, seq in enumerate(seqs) :
        preds[i, :] = get_hexamer_pred_both_regions(seq)

    return preds

def get_hexamer_pred(seq) :
    preds = []
    for cell_line, w, w_0 in zip(['hek', 'hela', 'mcf7', 'cho'], [hek_w, hela_w, mcf7_w, cho_w], [hek_w_0, hela_w_0, mcf7_w_0, cho_w_0]) :
        pred = w_0

        region_1 = seq[5: 40]
        for j in range(0, len(region_1) - 5) :
            pred += w[mer6_dict[region_1[j: j+6]]]

        preds.append(1. / (1. + np.exp(-pred)))

    return np.array(preds)

def get_hexamer_diff_scores(seq, cell_1, cell_2) :
    scores = []

    w_dict = {
        'hek' : hek_w,
        'hela' : hela_w,
        'mcf7' : mcf7_w,
        'cho' : cho_w
    }

    w_cell_1 = w_dict[cell_1]
    w_cell_2 = w_dict[cell_2]

    scores.extend([('_', ''), ('_', ''), ('_', ''), ('_', ''), ('_', '')])
    region_1 = seq[5: 40]
    for j in range(0, len(region_1) - 5) :
        hexamer_score_cell_1 = w_cell_1[mer6_dict[region_1[j: j+6]]]
        hexamer_score_cell_2 = w_cell_2[mer6_dict[region_1[j: j+6]]]

        scores.append((region_1[j: j+6], str(round(hexamer_score_cell_1 - hexamer_score_cell_2, 2))))

    return scores

def get_hexamer_preds(seqs) :
    preds = np.zeros((len(seqs), 4))

    for i, seq in enumerate(seqs) :
        preds[i, :] = get_hexamer_pred(seq)

    return preds

def decode_onehot_consensus(onehot) :
    seq = ''

    for i in range(onehot.shape[0]) :
        max_j = np.argmax(onehot[i, :])

        if max_j == 0 :
            seq += 'A'
        elif max_j == 1 :
            seq += 'C'
        elif max_j == 2 :
            seq += 'G'
        elif max_j == 3 :
            seq += 'T'

    return seq

def decode_onehots_consensus(onehots) :
    seqs = [
        decode_onehot_consensus(onehots[i, :, :, 0]) for i in range(onehots.shape[0])
    ]

    return seqs


# This algorithm is used to find the minima of a continuous multivariate nonlinear function using hyperplanes that
# will be used in a iterative way to minimse the function in steps that are adapated as the
# alogrithm progresses.
# The algorithm takes as an input the the non linear function (func), two points (x1,x2)
# and the number of iterations (niter).
# The algorithm returns the global minimum of the function (xmin) and the value of the function at the minimum (fmin).
# in the specified interval, we allow as well for the user to specify the step size (step)
# and the seed for the random generator (seed).
# This program was runned using an Ubuntu distribution of Linux and Python 3.10.6

import matplotlib
import numpy as np
from scipy.optimize import differential_evolution
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from autograd import grad, numpy as anp
matplotlib.use('TkAgg')

def check_sol(func, K, bounds, seed=23):
    """Check if there is a solution to the equation func(x_1,...,x_n) = K.

    Arguments:
    - func: a function object that accepts a 1D numpy array and returns a real number.
    - K: the real number to which the function should be equal.
    - bounds: a list of tuples specifying the lower and upper bounds for each dimension.
    - seed: a seed for the random number generator.

    Returns:
    - True and a solution point (as a 1D numpy array) if a solution is found, False otherwise.
    """
    # Define a new function that is the absolute difference between the original function and K
    def diff_func(x):
        return np.abs(func(x) - K)

    # Use differential evolution to find the minimum of this new function
    result = differential_evolution(diff_func, bounds, seed=seed)

    # If the function's minimum is zero, return True and the solution point
    if result.fun < 1e-6:  # 1e-6 to account for numerical errors
        return [True, result.x]
    else:  # If the function's minimum is not zero, return False
        return [False, None]

def bounder(a,b):
    """
    Generates a list of lists of the form [[a1,b1],[a2,b2],...,[an,bn]] where a1 <= b1, a2 <= b2, ..., an <= bn.
    """
    I = []
    for i in range(len(a)):
        I.append([min(a[i],b[i]),max(a[i],b[i])])
    return I

def comparsion(func,a,b):
    if func(a) <= func(b):
        return [a,func(a)]
    else:
        return [b,func(b)]

def bars(func,a,b,niter,step=2, DIFFERENTIAL=False):
    """
    Finds a global minimum in a given interval of a continuous multivariate nonlinear function using hyperplanes
    """
    i = 0
    x_n = []
    x_n.append(comparsion(func,a,b))
    bounds = bounder(a,b)  # Use the function to generate the bounds
    while i <= niter:
        solution = check_sol(func, x_n[-1][-1]- step**(1-i), bounds)
        if solution[0]:
            print(f"Numerical solution found, the hyperplane is intersecting the function with step {step**(1-i)}" + f" - {i}")
            x_n.append([check_sol(func, x_n[-1][-1]- step**(1-i), bounds)[1],func(check_sol(func, x_n[-1][-1]- step**(1-i), bounds)[1])])
        else:
            print(f"Numerical solution not found, the hyperplane is not intersecting the function with step {step**(1-i)}" + f" - {i}")
            i += 1

    print("Solutions: \n", x_n)

    # Check the gradient at each point

    if DIFFERENTIAL == True:
        def func(x):
            return -20 * anp.exp(-0.2 * anp.sqrt(0.5 * (x[0]**2 + x[1]**2))) - anp.exp(0.5* (anp.cos(2 * anp.pi * x[0] ) + anp.cos(2 * anp.pi * x[1]))) + anp.exp(1) + 20
            #put your function here, has to be the same as the one used above

        func_grad = grad(func)
        gradients = []
        for solution in x_n:
            point = solution[0]
            point = np.array(point, dtype=float)
            gradient_at_point = func_grad(point)
            gradients.append(gradient_at_point)

        print("Gradient vectors: \n", gradients)
        print("Norms of the gradient vectors: \n", [np.linalg.norm(gradient) for gradient in gradients])

    # Visualize the solution path

    # If the problem is 2D, visualize using a contour plot
    if len(bounds) == 1:
    # Create an array of x values based on the bounds
        x = np.linspace(bounds[0][0], bounds[0][1], 400)
        # Calculate the corresponding y values for each x
        y = func([x])

        # Make a line plot
        plt.figure(figsize=(10,6))
        plt.plot(x, y, 'b-')

        # Mark all the points used by the algorithm
        for sol in x_n:
            plt.plot(sol[0], sol[1], 'r.', markersize=10)

        plt.show()

    # If the problem is 3D, visualize using a 3D plot
    if len(bounds) == 2:
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')

        x = np.linspace(bounds[0][0], bounds[0][1], 100)
        y = np.linspace(bounds[1][0], bounds[1][1], 100)
        X, Y = np.meshgrid(x, y)

        # Calculate the corresponding Z values for each pair of x and y
        Z = func([X,Y])

        # Make a surface plot
        ax.plot_surface(X, Y, Z, cmap='RdYlBu_r', alpha=0.3)

        # Mark the solution path
        sol_x = [pt[0][0] for pt in x_n]
        sol_y = [pt[0][1] for pt in x_n]
        sol_z = [pt[1] for pt in x_n]
        ax.plot(sol_x, sol_y, sol_z, 'r.-')

        plt.show()

    # If it is 4D function, visualize using a 3D plot
    if len(bounds) == 3:
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')

        x = np.linspace(bounds[0][0], bounds[0][1], 100)
        y = np.linspace(bounds[1][0], bounds[1][1], 100)
        z = np.linspace(bounds[2][0], bounds[2][1], 100)
        X, Y, Z = np.meshgrid(x, y, z)

        # Mark the solution path
        sol_x = [pt[0][0] for pt in x_n]
        sol_y = [pt[0][1] for pt in x_n]
        sol_z = [pt[1] for pt in x_n]
        ax.plot(sol_x, sol_y, sol_z, 'r.-')

        plt.show()

    return x_n[-1][0], x_n[-1][1]

def func(x):
    return -20 * np.exp(-0.2 * np.sqrt(0.5 * (x[0]**2 + x[1]**2))) - np.exp(0.5 * (np.cos(2 * np.pi * x[0] ) + np.cos(2 * np.pi * x[1]))) + np.exp(1) + 20
    #check the function used in the algorithm

#use my algorithm
bars(func,[-5,-5],[5,5], 2, 10, DIFFERENTIAL=True)

#use scipy algorithm
from scipy.optimize import minimize
x0 = np.array([-5, -5]) #initial guess
res = minimize(func, x0)
print(res.x,func(res.x))