"""Run the code with self-healing."""

import subprocess
import time
from pathlib import Path

import fire

from prompt_templates.information_retrieval import find_file_with_error_template
from prompt_templates.code_generation import fix_code_template
from utils.llm import send_templated_message_to_llm, query_llm
from utils.file_io import read_file, write_file, compute_diffs, get_main_script_name
from utils.log import log
from config import project_configs

def run_script_inside_subprocess_with_timeout(
    root_folder_name: str,
    bash_script: str,
    timeout: str | None = None
) -> tuple[str | None, str | None]:
    """Run the script inside a subprocess with a timeout."""
    start = time.time()
    process = subprocess.Popen([f"./{bash_script}"],
                               cwd=root_folder_name,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    while True:
        if process.poll() is not None:  # If the process has finished
            break
        if timeout is not None:
            if time.time() - start > timeout:  # If timeout has passed
                process.terminate()
                log.debug(f"Script was terminated after {timeout} seconds.")
                return None, None
        time.sleep(0.1)  # Sleep for a short time to prevent busy waiting

    stdout, stderr = process.communicate()

    return stdout, stderr

def run_with_self_healing_code(
    project_name: str,
    max_heal_attempts: int = 25,
    max_improvement_iterations_per_llm_query: int = 3
) -> None:
    """Run the code with self-healing.

    Args:
        project_path: The path to the project.
        max_fix_attempts: The maximum number of attempts to fix the code.
        max_improvement_iterations_per_llm_query:
            The maximum number of improvement iterations per LLM query.
    """
    project_requirements = read_file(Path(project_configs[project_name]["requirements_document"]))
    tech_spec = read_file(
        Path(project_configs[project_name]["project_path"]) / Path("technical_specification.md"))
    root_folder_name = project_configs[project_name]["project_path"]
    bash_script = get_main_script_name(root_folder_name)
    subprocess.run(["chmod", "+x", str(Path(root_folder_name) / Path(bash_script))])
    code_errors_out = True
    attempts = 1
    while code_errors_out and attempts <= max_heal_attempts:
        stdout, stderr = run_script_inside_subprocess_with_timeout(
            root_folder_name, bash_script)

        if stderr is None:
            code_errors_out = False
            log.info("Script ran successfully.")
        else:
            log.debug(f"Output from stdout: {stdout}")
            log.debug(f"Output from stderr: {stderr}")
            message_to_send = find_file_with_error_template(tech_spec, stdout, stderr)
            reply = query_llm(message_to_send)
            if reply == "There is no error.":
                code_errors_out = False
                log.info("Script ran successfully.")
            else:
                path_and_file_name = reply
                code = read_file(path_and_file_name)
                message_to_send = fix_code_template(
                    project_requirements, tech_spec, path_and_file_name, code, stderr)
                content = send_templated_message_to_llm(
                    message_to_send, max_improvement_iterations_per_llm_query)
                log.info(compute_diffs(code, content))
                write_file(path_and_file_name, content)
                attempts += 1

if __name__ == "__main__":
    fire.Fire(run_with_self_healing_code)


from examples.seismic import Model
import numpy as np

def demo_model(preset, **kwargs):
    # A simple circle in a 2D domain with a background velocity.
    # By default, the circle velocity is 2.5 km/s,
    # and the background veloity is 3.0 km/s.
    space_order = kwargs.pop('space_order', 2)

    dtype = kwargs.pop('dtype', np.float32)
    shape = kwargs.pop('shape', (101, 101))
    spacing = kwargs.pop('spacing', tuple([10. for _ in shape]))
    origin = kwargs.pop('origin', tuple([0. for _ in shape]))
    nbpml = kwargs.pop('nbpml', 10)
    vp = kwargs.pop('vp', 3.0)
    vp_background = kwargs.pop('vp_background', 2.5)
    r = kwargs.pop('r', 15)

    # Only a 2D preset is available currently
    assert(len(shape) == 2)

    v = np.empty(shape, dtype=dtype)
    v[:] = vp_background

    a, b = shape[0] / 2, shape[1] / 2
    y, x = np.ogrid[-a:shape[0]-a, -b:shape[1]-b]
    v[x*x + y*y <= r*r] = vp

    return Model(space_order=space_order, vp=v, origin=origin, shape=shape,
                 dtype=dtype, spacing=spacing, nbpml=nbpml, **kwargs)


import pathlib

from matplotlib import pyplot as plt
import logging

from astropy import units as u

import diskchef.chemistry.scikit
from diskchef.physics.williams_best import WilliamsBest2014

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s   %(name)-60s %(levelname)-8s %(message)s',
    datefmt='%m.%d.%Y %H:%M:%S',
)
logger = logging.getLogger(__name__)
bins = 100
folder = pathlib.Path("example")
folder.mkdir(parents=True, exist_ok=True)

physics = WilliamsBest2014(radial_bins=bins, vertical_bins=bins)
chem = diskchef.chemistry.scikit.SciKitChemistry(physics)
chem.run_chemistry()

logging.getLogger('matplotlib.font_manager').disabled = True
logging.getLogger('matplotlib.ticker').disabled = True

fig, ax = plt.subplots(2, 3, sharex=True, sharey=True, figsize=(15, 10))
physics.plot_density(axes=ax[0, 0])
tempplot = physics.plot_temperatures(axes=ax[1, 0])
tempplot.contours("Gas temperature", [20, 40] * u.K)

chem.plot_chemistry("CO", "HCO+", axes=ax[0, 1])
chem.plot_chemistry("CN", "HCN", axes=ax[1, 1])

coplot = chem.plot_absolute_chemistry("CO", "HCO+", axes=ax[0, 2], maxdepth=1e9)
coplot.contours("Gas temperature", [20, 40] * u.K, clabel_kwargs={"fmt": "T=%d K"})
chem.plot_absolute_chemistry("CN", "HCN", axes=ax[1, 2])

fig2, ax2 = plt.subplots(2, 2, sharex=True, figsize=(10, 10))

physics.plot_column_densities(axes=ax2[0, 0])
chem.plot_column_densities(axes=ax2[1, 0], species=["CO", "CS"])
chem.plot_column_densities(axes=ax2[0, 1], species=["CN", "HCN"])
chem.plot_column_densities(axes=ax2[1, 1], species=["N2H+", "HCO+"])

fig.savefig(folder / "report.pdf")
fig2.savefig(folder / "report_coldens.pdf")


import numpy as np
import math
import Matrices as Mat

def deltasc(A,J,E,B,D,sc):
    L=E-sc@B
    return (A+J)@sc+sc@(A.T+J.T)+D-L@(L.T)

def deltadesc(A,deA,J,E,B,D,sc,desc):
    L=E-sc@B
    return (deA@sc+sc@(deA.T)+(A+J)@(desc)+desc@(A.T+J.T)+desc@B@(L.T)+L@((desc@B).T))

def deltar(A,J,E,B,sc,dw,r,dt):
    L=E-sc@B
    return (A+J)@r+(2**(-0.5))*L@(dw/dt)

def deltader(A,deA,J,E,B,sc,desc,dw,dedw,r,der,dt):
    L=E-sc@B
    return deA@r+(A+J)@der-(2**(-0.5))*desc@B@(dw/dt)+(2**(-0.5))*L@(dedw/dt)

def RK4(var,f,args,dt):
    k1=f(**args)
    x=args['{}'.format(var)]
    args['{}'.format(var)]=x+k1*(dt/2)
    k2=f(**args)
    args['{}'.format(var)]=x+k2*(dt/2)
    k3=f(**args)
    args['{}'.format(var)]=x+k3*(dt)
    k4=f(**args)
    return (dt/6)*(k1+2*(k2+k3)+k4)

def fishsystem_nocost_RK4(r,der,sc,desc,A,deA,D,B,E,dt,dw,dedw,J): #in place of J you should use freq*identity(n)
    dr=RK4(var='r',f=deltar,args={'A':A,'J':J,'E':E,'B':B,'sc':sc,'dw':dw,'r':r,'dt':dt},dt=dt)
    dder=RK4(var='der',f=deltader,args={'A':A,'deA':deA,'J':J,'E':E,'B':B,'sc':sc,'desc':desc,'dw':dw,'dedw':dedw,'r':r,'der':der,'dt':dt},dt=dt)
    dsc=RK4(var='sc',f=deltasc,args={'A':A,'J':J,'E':E,'B':B,'D':D,'sc':sc},dt=dt)
    ddesc=RK4(var='desc',f=deltadesc,args={'A':A,'deA':deA,'J':J,'E':E,'B':B,'D':D,'sc':sc,'desc':desc},dt=dt)
    der=der+dder
    desc=desc+ddesc
    r=r+dr
    sc=sc+dsc
    return r,sc,der,desc

def exc_step(exc,Dyn,L,dt):
    dexc=dt*(Dyn@exc+exc@(Dyn.T)+2*L@(L.T))
    exc=exc+dexc
    return exc

def purity_like_rew(r,sc,exc,pow=0.5):
    su=sc+exc
    d1=np.linalg.det(su)
    d2=np.linalg.det(sc)
    h=d1-d2+1
    h=1/(h**pow)
    return h

def Matrices_Calculator(mode,params):
    if mode=='Optomech':
        A,D,B,E=Mat.Optomech(params)
        return A,D,B,E
    elif mode=='Cavity':
        A,D,B,E=Mat.Cavity(params)
        return A,D,B,E
    elif mode=='Fisher':
        A,deA,D,B,E=Mat.Fisher(params)
        return A,deA,D,B,E
    else:
        print('select mode "Optomech" or "Cavity"')

def check_param(param,range,pos):
    if param==None:
        if pos==False:
            param=np.random.uniform(-range,range)
        if pos==True:
            param=np.random.uniform(0,range)
        return param
    else:
        return param


"""
n個の整数を含む数列 Sと、q個の異なる整数を含む数列 Tを読み込み、
Tに含まれる整数の中で Sに含まれるものの個数 Cを出力するプログラムを作成してください。
"""
def binary_search(S, key):
    left = 0
    right = len(S)
    while left < right:
        mid = (left + right) // 2
        if S[mid] == key:
            return True
        elif key < S[mid]:
            right = mid
        else:
            left = mid + 1
    return False

n = int(input())
S = list(map(int, input().split()))
q = int(input())
T = list(map(int, input().split()))

C = 0
S.sort()

for i in range(q):
    if binary_search(S, T[i]):
        C += 1

print(C)


import networkx as nx

COUNT_MISSING_DATES = False
PRINT_TOP_N = 10

def normalize_dict(dct):  # makes all the values in range [0,1]
    lowest_val = 9999999.0
    highest_val = 0.0
    for key, value in dct.items():
        if value < lowest_val:
            lowest_val = value
        if value > highest_val:
            highest_val = value
    for key in dct.keys():
        dct[key] = (dct[key] - lowest_val) / (highest_val - lowest_val)
    return dct

def sort_list(in_list):
    return sorted(in_list.items(), key=lambda x: x[1])

def progressBar(title, value, endvalue, bar_length=20):
    import sys
    percent = float(value) / endvalue
    arrow = '-' * int(round(percent * bar_length) - 1) + '>'
    spaces = ' ' * (bar_length - len(arrow))

    sys.stdout.write("\r" + title + " [{0}] {1}% ({2} out of {3})".format(arrow + spaces, int(round(percent * 100)), value, endvalue))
    if value == endvalue:
        sys.stdout.write("\n")
    sys.stdout.flush()

def get_book_by_id(books_dict, requested_id):
    requested_id = int(requested_id)
    if len(books_dict) > requested_id:
        # TODO: dichotomia usage for faster search
        # actual_index = requested_id-1
        # curr_id = 0
        # while curr_id != requested_id:
        #     curr_id = int(books_dict[actual_index]['book_id'])
        #     if curr_id < requested_id:
        #         actual_index = curr_id + (requested_id - curr_id) // 2 - 1
        #     elif curr_id > requested_id:
        #         actual_index = requested_id + (curr_id - requested_id) // 2 - 1
        for actual_index in range(1, len(books_dict)):
            if len(books_dict[actual_index]['book_id']) > 0 and int(books_dict[actual_index]['book_id']) == requested_id:
                return books_dict[actual_index]

########### MEAN CENTRALITY #########

def calculate_mean_of_values_for_keys(d1, d2, d3, d4):
    final_dict = {}
    for key in d1.keys():
        final_dict[key] = (d1[key]+d2[key]+d3[key]+d4[key]) / 4
    return final_dict

##########################################################

def print_top_n(books_dict, all_list, print_graph=False):
    top = all_list[-PRINT_TOP_N:]

    top_names = []
    top_vals = []

    for ind in reversed(range(PRINT_TOP_N)):
        i = top[ind]
        if len(books_dict) > i[0]:
            book = get_book_by_id(books_dict, int(i[0]))
            top_names.append(book['book_title'] + " (" + book["book_release_year"] + ")" "\n" + book['book_author'])
            top_vals.append(i[1])
            print(i[0], book['book_id'], '"' + book['book_title'] + '"', book['book_author'], "(" + book['book_release_year'] + ")", book['book_score'], i[1])
        else:
            print('Неопознанная книга, id =', i[0])

    if print_graph:
        import matplotlib.pyplot as plt
        import numpy as np
        plt.rcdefaults()
        fig, ax = plt.subplots()

        y_pos = [i - 0.5 for i in np.arange(PRINT_TOP_N)]
        # print(y_pos)
        ax.barh(y_pos, top_vals, align='center',
                color='green', ecolor='black')
        ax.set_yticks(y_pos)
        ax.set_yticklabels(top_names)
        ax.invert_yaxis()  # labels read top-to-bottom
        ax.set_xlabel('Средняя центральность по произведениям')
        ax.xaxis.grid()
        # ax.set_title('How fast do you want to go today?')
        fig.tight_layout()
        fig.savefig('top_books_mean.png')
        fig.savefig('top_books_mean.jpg')
        # plt.tight_layout()
        # plt.show()

def analyze_books(books_dict, total_records_to_measure=-1):
    g = nx.DiGraph()

    # read all the books and append'em to the graph.
    cites_accounted = 0
    total_cites = 0
    for book_index in range(len(books_dict)):
        if book_index == total_records_to_measure:
            break
        progressBar("Building the books influence graph...", book_index, len(books_dict)-1, 20)
        book = books_dict[book_index]
        if book['book_id_exists'] == 'True':
            book_id = int(book['book_id'])

            if len(book['book_similar']) > 0:
                book_similar_list = list(map(lambda x: int(x), book['book_similar'].split(';')))
                for i in book_similar_list:
                    total_cites += 1
                    sim_book = get_book_by_id(books_dict, i)
                    if sim_book is not None and sim_book["book_author"] == book["book_author"]:
                        continue
                    if COUNT_MISSING_DATES:
                        if sim_book is not None and (sim_book["book_release_year"] == '' or book["book_release_year"] == '' or int(sim_book["book_release_year"]) < int(book["book_release_year"])):
                            cites_accounted += 1
                            g.add_edge(book_id, i)
                    else:
                        if sim_book is not None and (sim_book["book_release_year"] != '' and book["book_release_year"] != '' and int(sim_book["book_release_year"]) < int(book["book_release_year"])):
                            cites_accounted += 1
                            g.add_edge(book_id, i)

    # MEASUREMENTS
    print('------- BOOKS INFLUENCE ANALYSIS -------')
    print('Graph is built. Calculating in-degree centrality...')
    idg = normalize_dict(nx.in_degree_centrality(g))
    print_top_n(books_dict,sort_list(idg))

    print()
    print('Calculating closeness centrality...')
    cls = normalize_dict(nx.closeness_centrality(g))
    print_top_n(books_dict,sort_list(cls))

    print()
    print('Calculating harmonic centrality...')
    hrm = normalize_dict(nx.harmonic_centrality(g))
    print_top_n(books_dict,sort_list(hrm))

    print()
    print('Calculating PageRank centrality...')
    pgr = normalize_dict(nx.pagerank(g))
    print_top_n(books_dict,sort_list(pgr))

    print()
    print('Calculating mean centrality...')
    mean_centrality = normalize_dict(calculate_mean_of_values_for_keys(idg, cls, hrm, pgr))
    print_top_n(books_dict, sort_list(mean_centrality), print_graph=True)

    print()
    print("TOTAL:", total_cites, "cites;", "ACCOUNTED:", cites_accounted, "cites.")


# -*- coding: latin -*-

"""This is the talker configuration file"""

# GENERAL TALKER CONFIGURATION
### This is the port where the talker will be running
TALKER_PORT = 2223
### Maximum length of the TCP packets
TALKER_BLOCK_SIZE = 1024

# LOGIN SCREEN
### Maximum length of usernames
LOGIN_MAX_LENGTH = 20
### Below are the logins which perform some commands, and thus users
### can't use (case insensitive).
LOGIN_COMMANDS = "who, version, rules"
### This is the lower that quits the user from the talker (case insensitive).
LOGIN_QUIT = "quit"

# WELCOME SCREEN
### If 1 shows the welcome screen (contained in the file config/welcome, by
### default), if any available. To turn off, put 0 instead.
WELCOME_SHOW = 1
### This is the file where the welcome text is located.
WELCOME_FILE = "config/welcome"

# RULES SYSTEM
### If 1 shows the rules of the talker (contained in the file config/rules,
### by default), if any available. If 2 shows the rules and enforces users
### to either accept or decline them (thus quitting them of the talker). To
### turn off, put 0 instead.
RULES_SHOW = 2
### The users must write what's below (case insensitive) to accept the rules.
RULES_ACCEPT = "YES"
### The users must write what's below (case insensitive) to decline the rules
### and quit the talker.
RULES_DECLINE = "NO"
### This is the file where the rules are located.
RULES_FILE = "config/rules"

# COMMANDS
### The directory where the command files are located.
COMMANDS_DIR = "commands-en"
### Files in the above directory which are not commands
COMMANDS_EXCEPTIONS = "__init__.py"

# MOTD SCREEN
### If 1 shows the message of the day (contained in the file config/motd, by
### default), if any available. To turn off, put 0 instead.
MOTD_SHOW = 1
### This is the file where the motd is located.
MOTD_FILE = "config/motd"
### This is the file where the news are written.
NEWS_FILE = "config/news"

# USERS
### The directory where the user files are located.
USERS_DIR = "userfiles"

# ROOMS
### The directory where all room files stand.
ROOMS_DIR = "roomfiles"
### The room the users enter when not defined.
DEFAULT_ROOM = "lago"


lines = open("input").readlines()

instrs = []
for line in lines:
    instr, val = line.split()
    instrs.append((instr, int(val)))

visited, acc, ip = set(), 0, 0

while ip not in visited:
    visited.add(ip)

    if instrs[ip][0] == "jmp":
        ip += instrs[ip][1]
        continue

    if instrs[ip][0] == "acc":
        acc += instrs[ip][1]
    ip += 1

print(acc)


import cli_common
import os

class KamailioCli(object):
    """
    Cli for managing kamailio. OS support: Debian10
    """

    def install(self):
        """
        Call ansible role_kamailio_install role to install kamailio.

        :return:
        """

        # Full path of python file locates in
        var_full_path = os.path.dirname(os.path.realpath(__file__))

        var_install_kamailio = input("Install Kamailio? [y/n]: ")
        if var_install_kamailio.lower() == "y":
            var_host_target_kamailio = input("Enter deploying target machine (example: 192.168.1.20:8080): ")
            var_host_target_user_kamailio = input("Enter target machine user (default root): ") or "root"
        var_install_rtpengine = input("Install Rtpengine? [y/n]: ")
        if var_install_rtpengine.lower() == "y":
            var_host_target_rtpengine = input("Enter deploying target machine (example: 192.168.1.20:8080): ")
            var_host_target_user_rtpengine = input("Enter target machine user (default root): ") or "root"

        if var_install_kamailio.lower() == "y" or var_install_rtpengine.lower() == "y":
            var_external_kamailio_ip = input("Enter kamailio external ip: ")
            var_internal_kamailio_ip = input("Enter kamailio internal ip: ")

        if var_install_kamailio.lower() == "y":
            var_command = "ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook " + var_full_path + "/role_kamailio_install.yml -e 'ansible_python_interpreter=/usr/bin/python3'"
            var_command = cli_common.concat_command(var_command, var_host_target_kamailio, var_host_target_user_kamailio)
            if var_external_kamailio_ip:
                var_command = var_command + " -e var_external_kamailio_ip=" + var_external_kamailio_ip
            if var_internal_kamailio_ip:
                var_command = var_command + " -e var_internal_kamailio_ip=" + var_internal_kamailio_ip
            cli_common.execute_command(var_command)

        if var_install_rtpengine.lower() == "y":
            var_command = "ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook " + var_full_path + "/role_rtpengine_install.yml -e 'ansible_python_interpreter=/usr/bin/python3'"
            var_command = cli_common.concat_command(var_command, var_host_target_rtpengine, var_host_target_user_rtpengine)
            if var_external_kamailio_ip:
                var_command = var_command + " -e var_external_kamailio_ip=" + var_external_kamailio_ip
            if var_internal_kamailio_ip:
                var_command = var_command + " -e var_internal_kamailio_ip=" + var_internal_kamailio_ip
            cli_common.execute_command(var_command)


import socket
import threading
import os
import time

HOST = '0.0.0.0'
PORT = 8080
BASE_DIR = './page'
TIMEOUT = 20

# Status HTTP
HTTP_STATUS_CODES = {
    200: 'OK',
    404: 'Not Found',
    502: 'Bad Gateway'
}

# LOGS dos requests
def log_request(client_address, request, status_code):
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
    log_entry = f'{timestamp} - {client_address} - [{request}] - {status_code}\n'
    with open('server_log.txt', 'a') as log_file:
        log_file.write(log_entry)

def handle_client(client_socket, client_address):
    request_data = client_socket.recv(1024).decode('utf-8')

    if request_data:
        request_lines = request_data.split('\n')
        request_line = request_lines[0].strip().split()

        if len(request_line) >= 3:
            method, path, _ = request_line
            file_path = os.path.join(BASE_DIR, path.lstrip('/'))
            print(file_path)
            if method == 'GET':
                if os.path.exists(file_path) and os.path.isfile(file_path):
                    status_code = 200
                    response_body = open(file_path, 'rb').read()
                else:
                    status_code = 404
                    response_body = b'File Not Found'
            elif method in ('POST', 'DELETE'):
                status_code = 502
                response_body = b'Invalid Function'
            else:
                status_code = 501
                response_body = b'Not Implemented'
        else:
            status_code = 400
            response_body = b'Bad Request'
    else:
        status_code = 400
        response_body = b'Bad Request'

    response_headers = f'HTTP/1.1 {status_code} {HTTP_STATUS_CODES.get(status_code, "Unknown")}\r\n'
    response_headers += 'Content-Type: text/html\r\n'
    response_headers += f'Content-Length: {len(response_body)}\r\n\r\n'

    response = response_headers.encode('utf-8') + response_body
    client_socket.send(response)
    client_socket.close()

    log_request(client_address, request_line, status_code)

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print(f'Servidor HTTP rodando em http://localhost:{PORT}/')

while True:
    client_socket, addr = server_socket.accept()
    client_socket.settimeout(TIMEOUT)
    client_handler = threading.Thread(target=handle_client, args=(client_socket, addr))
    client_handler.start()


 #coding=utf-8
import tensorflow as tf
import json
import re
import numpy as np
import random
from sklearn.metrics import r2_score
from scipy.stats import kendalltau
from sklearn import ensemble
import joblib

#邻接矩阵填充
def padding_zero_in_matrix(adjecent_matrix, module_operations):
    len_operations = len(module_operations)
    if len_operations != 7:
        # if the operations is less than 7
        for j in range(len_operations, 7):
            module_operations.insert(j - 1, 3)
        # print(important_metrics[i]['fixed_metrics']['module_operations'])

        padding_matrix = np.insert(adjecent_matrix, len_operations - 1,
                                       np.zeros([7 - len_operations, len_operations]), axis=0)
        padding_matrix = np.insert(padding_matrix, [len_operations - 1], np.zeros([7, 7 - len_operations]), axis=1)
    else:
        padding_matrix = np.array(adjecent_matrix)
    return padding_matrix, module_operations

#编码方法
def encode(adjecent_matrix, module_operations):
    #填充架构为相同大小的邻接矩阵和相同长度的节点标签列表
    padding_matrix, module_operations = padding_zero_in_matrix(adjecent_matrix, module_operations)
    #去除节点标签列表的in节点和out节点
    module_operations.remove(-1)
    module_operations.remove(-2)
    #将节点标签列表变成one-hot矩阵
    operations = []
    for i in range(0,len(module_operations)):
        ops = [ 0 for i in range(0,5)]
        if i < 3:
            ops[i] = 1
            operations.append(ops)
        else:
            operations.append(ops)
    operations = np.array(operations)
    #将邻接矩阵和节点标签列表化为一维并连接
    adj = list(np.ndarray.flatten(padding_matrix))
    operation = list(np.ndarray.flatten(operations))
    code = np.append(adj,operation)
    return code

#数据加载
def dataset_load(data_dir="data/data.json", graph_dir="data/generate_graphs.json", train_num=2500, test_num=500):
    #加载数据集中的key及对应的评估信息。
    model_id_regex="^"
    regex = re.compile(model_id_regex)
    with tf.gfile.Open(data_dir) as f:
        exist_models = json.load(f)
    exist_keys = [key for key in exist_models.keys() if regex.match(key)]
    random.shuffle(exist_keys)

    #分配训练集的key和测试集的key
    train_keys = exist_keys[0:train_num]
    test_keys = exist_keys[train_num:train_num+test_num]

    #获得key对应的架构的邻接矩阵和节点标签
    with tf.gfile.Open(graph_dir) as f:
        all_models = json.load(f)

    #分配训练集的邻接矩阵和节点标签以及标签（即性能）
    train_matrix = []
    train_ops = []
    train_label = []
    for i in range(len(train_keys)):
        key = train_keys[i]
        acc = exist_models[key]['evaluation_results'][2]['validation_accuracy']
        matrix = all_models[key][0]
        ops = all_models[key][1]
        train_matrix.append(matrix)
        train_ops.append(ops)
        train_label.append(acc)

    #分配测试集的邻接矩阵和节点标签以及标签（即性能）
    test_matrix = []
    test_ops = []
    test_label = []
    for i in range(len(test_keys)):
        key = test_keys[i]
        acc = exist_models[key]['evaluation_results'][2]['test_accuracy']
        matrix = all_models[key][0]
        ops = all_models[key][1]
        test_matrix.append(matrix)
        test_ops.append(ops)
        test_label.append(acc)
    return train_matrix, train_ops, train_label, test_matrix, test_ops, test_label

#获取模型
def get_model():
    model_random_forest_regressor = ensemble.RandomForestRegressor(n_estimators=230,max_features='auto')
    return model_random_forest_regressor

#数据编码
def encode_data(train_matrix, train_ops, train_label, test_matrix, test_ops, test_label):
    x_train = []
    for i in range(0,len(train_matrix)):
        x_train.append(encode(train_matrix[i],train_ops[i]))
    x_test = []
    for i in range(0,len(test_matrix)):
        x_test.append(encode(test_matrix[i],test_ops[i]))
    return x_train, train_label, x_test, test_label

#训练模型
def try_model(x_train, y_train, x_test, y_test, model):
    model.fit(x_train, y_train)
    result = model.predict(x_test)
    result = list(result)
    score = r2_score(y_test, result)
    result_arg = np.argsort(result)
    y_test_arg = np.argsort(y_test)
    result_rank = np.zeros(len(y_test_arg))
    y_test_rank = np.zeros(len(y_test_arg))
    for i in range(len(y_test_arg)):
        result_rank[result_arg[i]] = i
        y_test_rank[y_test_arg[i]] = i
    KTau, _ = kendalltau(result_rank, y_test_rank)
    joblib.dump(model, "output/RF_model.m") #save model
    print('KTau: {:}, R2score: {:}'.format(KTau, score))

if __name__ == '__main__':
    data_dir = "data/data.json"
    graph_dir = "data/generated_graphs.json"
    train_matrix, train_ops, train_label, test_matrix, test_ops, test_label = dataset_load(data_dir, graph_dir, 2000, 500)
    x_train, y_train, x_test, y_test = encode_data(train_matrix, train_ops, train_label, test_matrix, test_ops, test_label)
    model = get_model()
    try_model(x_train, y_train, x_test, y_test, model)


#!/usr/bin/python

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

"""
PyCOMPSs Testbench
========================
"""

# Imports
import unittest
import random

from pycompss.api.task import task
from pycompss.api.api import compss_wait_on
from pycompss.functions.elapsed_time import timeit

@timeit()
@task(returns=1)
def increment(value):
    return value + 1

class testTimeIt(unittest.TestCase):

    def testTimeIt(self):
        value = 1
        result = increment(value)
        result = compss_wait_on(result)
        self.assertEqual(len(result), 2)  # Check that returns a tuple with (result, timeit)
        self.assertEqual(result[0], value + 1)
        self.assertGreater(result[1], 0)


from math import log
class TFIDFVectorizer():
    def __init__(self, k=1.5, b=0.75):
        self.k = k
        self.b = b

    def tf(self,word,doc, doc_list):
        all_num=sum([doc[key] for key in doc])
        avg = 0
        for vb in doc_list:
            avg += sum([vb[key] for key in vb])
        avg = avg/len(doc_list)
        return (doc[word]*(self.k + 1))/(doc[word] + self.k*(1 - self.b + self.b*all_num/avg))

    def idf(self, word,doc_list):
        all_num=len(doc_list)
        word_count=0
        for doc in doc_list:
            if word in doc:
                word_count+=1
        return log((all_num+1)/(word_count+0.5))

    def tfidf(self, word,doc,doc_list):
        score = self.tf(word,doc, doc_list)*self.idf(word,doc_list)
        return score

if __name__=='__main__':
    doc1={'mik1':28,'aa':16,'web':14,'be':2,'python':1}
    doc2={'mik2':21,'ab':11,'web':14,'chal':5}
    doc3={'mik3':126,'bc':116,'web':74,'lelo':12,'foot':1}
    doc4={'mik4':8,'cd':3,'arbit':2,'da':1,'fork':1}
    doc_list=[doc1,doc2,doc3,doc4]
    tfidf = TFIDFVectorizer()
    for doc in doc_list:
        for word in doc:
            print( word,tfidf.tfidf(word,doc,doc_list))
import pandas as pd

# data = pd.read_csv('AspectJ.csv',  index_col=False)
# doc_list = data['summary']
# print(doc_list)


# time complexity of the merge sort is O(n log n)

def mergeSort(array):

    if len(array)>1:

        middleIdx = len(array)//2
        leftHalf = array[:middleIdx]
        rightHalf = array[middleIdx:]
        mergeSort(leftHalf)
        mergeSort(rightHalf)

        i = j = k = 0
        while i < len(leftHalf) and j < len(rightHalf):
            if leftHalf[i] < rightHalf[j]:
                array[k] = leftHalf[i]
                i += 1
            else:
                array[k] = rightHalf[j]
                j += 1
            k += 1

        while i  < len(leftHalf):
            array[k] = leftHalf[i]
            i += 1
            k += 1

        while j  < len(rightHalf):
            array[k] = rightHalf[j]
            k += 1
            j += 1

    return array

a = [30,2,41,56,12,11,22,41]
result = mergeSort(a)
print(result)


#!/usr/bin/python3
# File: 4-hidden_discovery.py
# Auth: Musa_kalamz A Ogunsolu

if __name__ == "__main__":
    """Print all names defined by hidden_4 module."""
    import hidden_4

    names = dir(hidden_4)

    for name in names:
        if name[:2] != "__":
            print(name)


import time
import random
import board
import digitalio
from PIL import Image, ImageDraw, ImageFont
#import adafruit_ssd1306
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1327

#def rounded_rectangle(self: ImageDraw, xy, corner_radius, fill=None, outline=None):

def rounded_rectangle(self: ImageDraw, color, x, y, w, h, r):
  '''Rounds'''
  self.ellipse((x,y,x+r,y+r),fill=color)
  self.ellipse((x+w-r,y,x+w,y+r),fill=color)
  self.ellipse((x,y+h-r,x+r,y+h),fill=color)
  self.ellipse((x+w-r,y+h-r,x+w,y+h),fill=color)

  '''rec.s'''
  self.rectangle((x+r/2,y, x+w-(r/2), y+h),fill=color)
  self.rectangle((x,y+r/2, x+w, y+h-(r/2)),fill=color)

ImageDraw.rounded_rectangle = rounded_rectangle

class Face:
  def __init__(self):

    # Setting some variables for our reset pin etc.
    RESET_PIN = digitalio.DigitalInOut(board.D4)

    self.serial = i2c(port=1, address=0x3C)

    #self.i2c = board.I2C()
    self.oled = ssd1327(self.serial, rotate=1)
    # adafruit_ssd1306.SSD1306_I2C(128, 32, self.i2c, addr=0x3C, reset=RESET_PIN)
    #self.oled.rotation = 1
    #self.oled.set_contrast(64)

    # Clear display
    self.oled.clear()
    self.oled.show()

    self.width = 128 #self.oled.width
    self.height = 128 #self.oled.height

    # Create blank image for drawing.
    self.image = Image.new("L", (128, 128)).convert(self.oled.mode)
    self.draw = ImageDraw.Draw(self.image)
    self.draw.rounded_rectangle = rounded_rectangle
    # Load a font in 2 different sizes.
    self.font = ImageFont.truetype("../fonts/EarlyGameBoy.ttf", 16)

  def drawEyes(self):
    x = random.randint(0, 42)
    y = random.randint(20, 64)

    # Draw a black filled box to clear the image.
    self.draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)
    #oled.fill(0)

    #self.draw.ellipse((x,y,x+28,y+28), outline=0, fill=255)
    #self.draw.ellipse((x+10,y+10,x+18,y+18), outline=0, fill=0)
    self.draw.rounded_rectangle(self.draw, 255, x, y, 20, 60, 10)
    self.draw.rounded_rectangle(self.draw, 255, x+64, y, 20, 60, 10)
    #self.draw.rectangle((x, y+30, x+10, y+40), outline=0, fill=0)

    # draw.text((0, 0), "Robo R01", font=font, fill=255)

    self.oled.display(self.image)
    self.oled.show()

  def drawHappyEyes(self):
    self.draw.rectangle((0,0,self.width,self.height), outline=0, fill=0)
    self.draw.rounded_rectangle(self.draw, 255, 6, 30, 20, 60, 20)
    self.draw.rectangle((0, 50, 32, 90), outline=0, fill=0)
    self.oled.display(self.image)
    self.oled.show()

  def drawSmallEyes(self):
    self.draw.rectangle((0,0,self.width,self.height), outline=0, fill=0)
    self.draw.rounded_rectangle(self.draw, 255, 6, 30, 20, 20, 20)
    self.oled.display(self.image)
    self.oled.show()

  def drawBlinkEyes(self):
    if not random.randint(0,3) % 2:
      self.draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)
      self.draw.rectangle((x+9, y+4, x+11, y+16), outline=0, fill=256)
      self.oled.display(self.image)
      self.oled.show()

  def poweroff(self):
    self.oled.cleanup()

face = Face()
face.drawEyes()
time.sleep(1)
face.drawEyes()
time.sleep(2)
face.drawEyes()
time.sleep(3)
face.drawEyes()
time.sleep(3)
face.poweroff()


import json
import os
from copy import deepcopy
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Any, Dict, Optional

from neural_compressor.ux.components.model.repository import ModelRepository
from neural_compressor.ux.components.optimization import Optimizations
from neural_compressor.ux.utils.consts import Precisions
from neural_compressor.ux.utils.exceptions import ClientErrorException, InternalException
from neural_compressor.ux.utils.json_serializer import JsonSerializer
from neural_compressor.ux.utils.logger import log
from neural_compressor.ux.utils.utils import (
    get_file_extension,
    get_framework_from_path,
    get_predefined_config_path,
)
from neural_compressor.ux.utils.workload.config import Config

class Workload(JsonSerializer):
    """Workload class."""

    def __init__(self, data: Dict[str, Any]):
        """Initialize Workload class."""
        super().__init__()
        self.config: Config = Config()

        self.id: str = str(data.get("id", ""))
        if not self.id:
            raise ClientErrorException("Workload ID not specified.")

        self.project_name: str = str(data.get("project_name", ""))
        if not self.project_name:
            raise ClientErrorException("project_name not specified.")

        now = datetime.now(timezone.utc)
        self.created_at: str = str(data.get("created_at", now.isoformat()))

        self.model_path: str = data.get("model_path", "")
        if not self.model_path:
            raise ClientErrorException("Model path is not defined!")

        self.model_name = Path(self.model_path).stem

        self.domain: str = data.get("domain", None)

        if not self.domain:
            raise ClientErrorException("Domain is not defined!")

        self.domain_flavour: str = data.get("domain_flavour", "")

        self.framework: str = data.get(
            "framework",
            get_framework_from_path(self.model_path),
        )

        self.workspace_path = os.path.join(os.environ.get("HOME", ""), "workdir")
        self.workload_path = data.get(
            "workload_path",
            os.path.join(
                self.workspace_path,
                "workloads",
                f"{self.model_name}_{self.id}",
            ),
        )

        self.set_workspace()

        self.eval_dataset_path: str = data.get("eval_dataset_path", "")
        self.calib_dataset_path: str = data.get("eval_dataset_path", "")
        self.set_dataset_paths(data)

        for dataset_path in [self.eval_dataset_path, self.calib_dataset_path]:
            if dataset_path != "no_dataset_location" and not os.path.exists(
                dataset_path,
            ):
                raise ClientErrorException(
                    f'Could not found dataset in specified location: "{dataset_path}".',
                )

        if not ModelRepository.is_model_path(self.model_path):
            raise ClientErrorException(
                f'Could not found model in specified location: "{self.model_path}".',
            )

        self.supports_profiling: bool = self.check_if_supports_profiling()

        self.accuracy_goal: float = data.get("accuracy_goal", 0.01)

        self.config_name = "config.yaml"
        self.predefined_config_path = data.get(
            "config_path",
            get_predefined_config_path(self.framework, self.domain, self.domain_flavour),
        )
        self.config_path = os.path.join(
            self.workload_path,
            self.config_name,
        )

        self.input_precision: str = Precisions.FP32.value  # TODO: Detect input model precision
        self.output_precision = data.get("precision", data.get("output_precision"))

        self.mode = self.get_optimization_mode()
        self.tune = data.get("tune", data.get("tuning", False))
        # FP32 precision works with GraphOptimization without auto-tune
        if self.output_precision == "fp32":
            self.tune = False

        self.execution_mode = ExecutionMode.BASIC
        self.set_execution_mode(data)

        self.initialize_config(data)

        self.input_nodes: Optional[str] = data.get("inputs", data.get("input_nodes"))
        self.output_nodes: Optional[str] = data.get("outputs", data.get("output_nodes"))

        self.model_output_path = os.path.join(
            self.workload_path,
            self.model_output_name,
        )
        self.version = "5.0"

    def initialize_config(self, data: dict) -> None:
        """Initialize config."""
        if not os.path.isfile(self.config_path):
            self.config.load(self.predefined_config_path)
        else:
            self.config.load(self.config_path)

        config_initializers = {
            Optimizations.TUNING: self.initialize_tuning_config,
            Optimizations.GRAPH: self.initialize_graph_optimization_config,
        }
        initializer = config_initializers.get(self.mode, None)
        if initializer is None:
            raise ClientErrorException(f"Could not initialize config for {self.mode} mode.")
        self.config.model.name = self.model_name
        self.config.set_evaluation_dataset_path(self.eval_dataset_path)
        self.config.set_workspace(self.workload_path)
        self.config.set_accuracy_goal(self.accuracy_goal)
        initializer()

    def initialize_tuning_config(self) -> None:
        """Initialize tuning config."""
        self.config.set_quantization_dataset_path(self.calib_dataset_path)
        if not self.tune:
            self.config.tuning.set_performance_only(True)

    def initialize_graph_optimization_config(self) -> None:
        """Initialize graph optimization config."""
        self.config.pruning = None
        self.config.set_optimization_precision(self.framework, self.output_precision)

    def get_optimization_mode(self) -> str:
        """Get optimization mode based on precision."""
        modes_map = {
            Precisions.INT8: Optimizations.TUNING,
            Precisions.FP32: Optimizations.GRAPH,
            Precisions.BF16: Optimizations.GRAPH,
        }
        mode = modes_map.get(self.output_precision, None)
        if mode is None:
            raise ClientErrorException(
                f"Could not found optimization mode for {self.output_precision} precision.",
            )
        return mode

    def check_if_supports_profiling(self) -> bool:
        """
        Check if supports profiling.

        returns true if model supports profiling else returns false.
        """
        if self.domain.lower() in ["nlp", "recommendation"]:
            return False
        model = ModelRepository().get_model(self.model_path)
        return model.supports_profiling

    def set_dataset_paths(self, data: dict) -> None:
        """Set calibration and evaluation dataset path."""
        if data.get("evaluation", {}).get("dataset_path"):
            self.eval_dataset_path = data.get("evaluation", {}).get("dataset_path")
        if data.get("quantization", {}).get("dataset_path"):
            self.calib_dataset_path = data.get("quantization", {}).get("dataset_path")

        if not self.eval_dataset_path:
            self.eval_dataset_path = data.get("dataset_path", "")
        if not self.calib_dataset_path:
            self.calib_dataset_path = data.get("dataset_path", "")

    def set_workspace(self) -> None:
        """Create (if missing) necessary folders for workloads."""
        os.makedirs(self.workspace_path, exist_ok=True)
        os.makedirs(self.workload_path, exist_ok=True)

    def dump(self) -> None:
        """Dump workload to yaml."""
        json_path = os.path.join(self.workload_path, "workload.json")
        with open(json_path, "w") as f:
            json.dump(self.serialize(), f, indent=4)

        log.debug(f"Successfully saved workload to {json_path}")

    @property
    def model_output_name(self) -> str:
        """Get output model name."""
        output_name = self.model_name
        if self.mode == Optimizations.TUNING:
            output_name += "_tuned_" + self.output_precision
        elif self.mode == Optimizations.GRAPH:
            output_name = self.model_name + "_optimized_"
            if self.tune:
                output_name += "tuned_"
            output_name += "_".join(
                [precision.strip() for precision in self.output_precision.split(",")],
            )
        else:
            raise ClientErrorException(f"Mode {self.mode} is not supported.")

        if os.path.isfile(self.model_path):
            output_name += "." + get_file_extension(self.model_path)

        return output_name

    def set_execution_mode(self, data: dict) -> None:
        """Set execution_mode."""
        if "execution_mode" in data:
            try:
                execution_mode = data.get("execution_mode", ExecutionMode.BASIC)
                self.execution_mode = ExecutionMode(execution_mode)
            except ValueError:
                self.execution_mode = ExecutionMode.BASIC
        elif data.get("tuning", False):
            self.execution_mode = ExecutionMode.ADVANCED

class ExecutionMode(Enum):
    """Supported execution modes."""

    BASIC = "basic"
    ADVANCED = "advanced"

class WorkloadMigrator:
    """Workload migrator."""

    def __init__(self, workload_json_path: str):
        """Initialize workloads list migrator."""
        self.workload_json = workload_json_path
        self.workload_data: dict = {}
        self.version_migrators = {
            2: self._migrate_to_v2,
            3: self._migrate_to_v3,
            4: self._migrate_to_v4,
            5: self._migrate_to_v5,
        }

    @property
    def current_version(self) -> int:
        """Get version of current workload format."""
        self.ensure_workload_loaded()
        return int(float(self.workload_data.get("version", 1)))

    @property
    def require_migration(self) -> bool:
        """Check if workload require migration."""
        if not os.path.isfile(self.workload_json):
            log.debug("Workload does not exits.")
            return False
        if self.current_version >= max(self.version_migrators.keys()):
            log.debug("Workload already up to date.")
            return False
        return True

    def load_workload_data(self) -> None:
        """Load workload data from json."""
        with open(self.workload_json, encoding="utf-8") as workload_json:
            self.workload_data = json.load(workload_json)

    def ensure_workload_loaded(self) -> None:
        """Make sure that workloads list is loaded."""
        if not self.workload_data and os.path.isfile(self.workload_json):
            self.load_workload_data()

    def dump(self) -> None:
        """Dump workloads information to json."""
        with open(self.workload_json, "w") as workload_json:
            json.dump(self.workload_data, workload_json, indent=4)

    def migrate(self) -> None:
        """Migrate workload to latest version."""
        self.ensure_workload_loaded()
        if not self.require_migration:
            return

        migration_steps = range(self.current_version, max(self.version_migrators.keys()))
        for step in migration_steps:
            migration_version = step + 1
            self._migrate_workload(migration_version)

    def _migrate_workload(self, migration_version: int) -> None:
        """Migrate workload one version up."""
        print(f"Migrate called with {migration_version} migration version.")
        migrate = self.version_migrators.get(migration_version, None)
        if migrate is None:
            raise InternalException(f"Could not parse workload from version {migration_version}")
        migrate()

    def _migrate_to_v2(self) -> None:
        """Parse workload from v1 to v2."""
        log.info("Migrating workload.json to v2...")
        new_data = {
            "input_precision": "fp32",
            "output_precision": "int8",
            "mode": "tuning",
            "tune": True,
            "version": 2,
        }
        parsed_workload = deepcopy(self.workload_data)
        parsed_workload.update(new_data)

        try:
            parsed_workload["config"]["tuning"].update({"objective": "performance"})
        except KeyError:
            log.debug("Could not set tuning objective.")
        try:
            input_nodes = self.workload_data["config"]["model"]["inputs"].split(",")
        except KeyError:
            input_nodes = []
        parsed_workload.update({"input_nodes": input_nodes})

        try:
            output_nodes = self.workload_data["config"]["model"]["outputs"].split(",")
        except KeyError:
            output_nodes = []
        parsed_workload.update({"output_nodes": output_nodes})

        self.workload_data = parsed_workload

    def _migrate_to_v3(self) -> None:
        """Parse workload from v2 to v3."""
        log.info("Migrating workload.json to v3...")
        self.workload_data.update(
            {
                "project_name": os.path.basename(self.workload_data.get("model_path", "")),
                "created_at": "2021-07-15T14:19:18.860579",
                "version": 3,
            },
        )

    def _migrate_to_v4(self) -> None:
        """Parse workload from v3 to v4."""
        log.info("Migrating workload.json to v4...")
        self.workload_data.update(
            {
                "supports_profiling": False,
                "version": 4,
            },
        )

    def _migrate_to_v5(self) -> None:
        """Parse workload form v4 to v5."""
        log.info("Migrating workload.json to v5...")
        objective = self.workload_data.get("config", {}).get("tuning", {}).get("objective", None)
        self.workload_data.update(
            {
                "version": 5,
            },
        )
        if isinstance(objective, str):
            del self.workload_data["config"]["tuning"]["objective"]
            self.workload_data["config"]["tuning"].update(
                {
                    "multi_objective": {
                        "objective": [objective],
                    },
                },
            )


"""Reasonable test inputs:
integer = x = 5
power = n = 3

Pseudocode:
Create function
Create If statement
Create base case where the power is equal to 1,
and therefore the answer is equal to the integer.
Create recursive case, where the integer is
multiplied by the function raise_power recursively, or in other
words, it is multiplied by itself n-1 times.
"""

def raise_power(x, n):
    # base case: if power (n) is equal to 1,
    if n == 1:
        # return integer (x)
        return x
    else:
        # otherwise multiply x by raise_power()
        # recursively x, n-1 times, which is the same
        # as raising it by the power of n,
        # and return the result
        return x * raise_power(x, n-1)

print(raise_power(5,3))

def test_raise_power():
    if raise_power(4,2) == 16:
        print("The test works!")
        return True
    else:
        print("The test does not work!")
        return False

test_raise_power()


import numpy as np
import pandas as pd
from enum import Enum
from copy import deepcopy

MAX_OUTS = 3
MAX_RUNS_PER_INNING = 5
MAX_INNINGS = 4

class Player:
    p1b = 1.0
    p2b = 1.0
    p3b = 0.0
    phr = 0.0
    pso = 0.0 #struck out
    pbo = 0.0 #hit but thrown out at first (useful for advancing a player)

    def __init__(self, hit_probs):
        self.p1b, self.p2b, self.p3b, self.phr, self.pso, self.pbo = hit_probs
        if ((self.p1b + self.p2b + self.p3b + self.phr + self.pso + self.pbo) != 1.0):
            print("Error with setting player")
            print(hit_probs)
            print((self.p1b + self.p2b + self.p3b + self.phr + self.pso + self.pbo))
        self.hit_probs = [self.p1b, self.p2b, self.p3b, self.phr, self.pso, self.pbo]
    def get_hit(self):
        return np.random.choice(['p1b','p2b','p3b','phr','pso','pbo'], 1,
                           p = self.hit_probs)

class BaseBallAction(Enum):
    Single = 1
    Double = 2
    Triple = 3
    HomeRun = 4
    StrikeOut = 5
    ThrownOut = 6

class BaseballState():
    def __init__(self, inning, runs, outs, base3, base2, base1, inning_start_runs = 0.0, likelihood = 1.0):
        self.inning = inning
        self.runs = runs
        self.inning_start_runs = inning_start_runs
        self.outs = outs
        self.base3 = base3
        self.base2 = base2
        self.base1 = base1
        self.likelihood = likelihood
    def __repr__(self):
         return "Inning: {}, Runs: {}, Inning Start Runs: {}, \n                  Outs: {}, First: {}, Second: {}, Third: {}, \n                  Likelihood: {}".format(self.inning, self.runs, self.inning_start_runs,                                         self.outs, self.base1, self.base2, self.base3, self.likelihood)

    def reset_bases(self):
        self.base1 = 0
        self.base2 = 0
        self.base3 = 0

    def increment_inning(self):
        self.inning = self.inning + 1
        self.reset_bases()
        self.outs = 0
        self.inning_start_runs = self.runs

    def advance_bases(self, count, new_runner):
        while(count != 0):
            if (self.base3):
                self.runs = self.runs + 1
                self.base3 = self.base2
                self.base2 = self.base1
                self.base1 = new_runner
                #max runs advance inning
                if ((self.runs - self.inning_start_runs)%MAX_RUNS_PER_INNING == 0):
                    self.increment_inning()
                    break
            else:
                self.base3 = self.base2
                self.base2 = self.base1
                self.base1 = new_runner
            new_runner = 0 #only new runner first time through
            count = count - 1

    def next_state(self,action, action_probability):
        new_state = deepcopy(self)
        new_state.likelihood = new_state.likelihood*action_probability
        if (action == BaseBallAction.StrikeOut) or (action == BaseBallAction.ThrownOut):
            new_state.outs = new_state.outs + 1
            if (new_state.outs == MAX_OUTS):
                #max outs advance inning
                new_state.increment_inning()
            elif (action == BaseBallAction.ThrownOut): #don't always advance base but will here...also usually throw to first
                new_state.advance_bases(count = 1, new_runner = 0)
        elif (action == BaseBallAction.Single):
            new_state.advance_bases(count = 1, new_runner = 1)
        elif (action == BaseBallAction.Double):
            new_state.advance_bases(count = 2, new_runner = 1)
        elif (action == BaseBallAction.Triple):
            new_state.advance_bases(count = 3, new_runner = 1)
        elif (action == BaseBallAction.HomeRun):
            new_state.advance_bases(count = 4, new_runner = 1)
        return new_state

'''
    Runs a multi-hypothesis set of scenarios to determine likelihoods for each final state ate end of game
    This looks like a tree once it is completed where the leaf nodes are the possible final states
'''

def run_player_scenario_mh(all_players, order):
    players = [all_players[i] for i in order]

    runs = [0.0 for i in range(0,MAX_INNINGS*MAX_RUNS_PER_INNING + 1)]
    def run_next_iter(cur_state, player_idx, baseball_action, probability):
        new_state = cur_state.next_state(baseball_action, probability)
        if(new_state.inning > MAX_INNINGS):
            runs[new_state.runs] = runs[new_state.runs] + new_state.likelihood
        else:
            run_next_player(new_state,(player_idx + 1)%len(players))

    def run_next_player(cur_state, player_idx):
        current_player = players[player_idx%len(players)]
        if(current_player.p1b > 0.0):
            run_next_iter(cur_state,player_idx,BaseBallAction.Single, current_player.p1b)
        if(current_player.p2b > 0.0):
            run_next_iter(cur_state,player_idx,BaseBallAction.Double, current_player.p2b)
        if(current_player.p3b > 0.0):
            run_next_iter(cur_state,player_idx,BaseBallAction.Triple, current_player.p3b)
        if(current_player.phr > 0.0):
            run_next_iter(cur_state,player_idx,BaseBallAction.HomeRun, current_player.phr)
        if(current_player.pso > 0.0):
            run_next_iter(cur_state,player_idx,BaseBallAction.StrikeOut, current_player.pso)
        if(current_player.pbo > 0.0):
            run_next_iter(cur_state,player_idx,BaseBallAction.ThrownOut, current_player.pbo)

    start_state = BaseballState(1,0,0,0,0,0)
    state_player_idx = 0
    run_next_player(start_state, state_player_idx)

    w_sum = 0
    for idx, val in enumerate(runs):
        w_sum = w_sum + val*idx
    #return w_sum
    return MAX_INNINGS*MAX_RUNS_PER_INNING - w_sum

'''
    Runs a a monte-carlo using the players to figure out statistical return
'''

def run_player_scenario_mc_standalone(all_players, order):
    players = [all_players[i] for i in order]

    df = pd.DataFrame(data = [], columns = ['Inning', 'Runs', 'Outs', 'Inning Runs'])
    OUTS = 3
    MAX_RUNS_PER_INNING = 5
    MAX_INNINGS = 4
    MAX_MC_RUNS = 100

    for sim_runs in range(0,MAX_MC_RUNS):
        runs = 0
        inning = 1
        current_batter = 0
        bases = [0,0,0] #b1, b2, b3
        outs = 0
        start_runs = 0

        while inning <= MAX_INNINGS:
            batting = True
            result = players[current_batter % len(players)].get_hit()
            current_batter = current_batter + 1
            if (result == 'pbo') or (result == 'pso'):
                outs = outs + 1
                if (outs == 3):
                    #max outs advance inning
                    df.loc[sim_runs*MAX_INNINGS + inning] = (inning, runs, outs, runs - start_runs)
                    inning = inning + 1
                    bases = [0,0,0]
                    outs = 0
                    start_runs = runs
                elif (result == 'pbo'):
                    if (bases[2]):
                        runs = runs + 1
                        bases[2] = bases[1]
                        bases[1] = bases[0]
                        bases[0] = 0
                        #max runs advance inning
                        if ((runs - start_runs)%MAX_RUNS_PER_INNING == 0):
                            df.loc[sim_runs*MAX_INNINGS + inning] = (inning, runs, outs, runs - start_runs)
                            inning = inning + 1
                            bases = [0,0,0]
                            outs = 0
                            start_runs = runs
                    else:
                        bases[2] = bases[1]
                        bases[1] = bases[0]
                        bases[0] = 0
            elif (result == 'p1b'):
                if (bases[2]):
                    runs = runs + 1
                    bases[2] = bases[1]
                    bases[1] = bases[0]
                    bases[0] = 1
                    #max runs advance inning
                    if ((runs - start_runs)%MAX_RUNS_PER_INNING == 0):
                        df.loc[sim_runs*MAX_INNINGS + inning] = (inning, runs, outs, runs - start_runs)
                        inning = inning + 1
                        bases = [0,0,0]
                        outs = 0
                        start_runs = runs
                else:
                    bases[2] = bases[1]
                    bases[1] = bases[0]
                    bases[0] = 1
            elif (result == 'p2b'):
                if (bases[2] or bases[1]):
                    runs = min(runs + bases[2] + bases[1],start_runs + MAX_RUNS_PER_INNING)
                    bases[2] = bases[0]
                    bases[1] = 1
                    bases[0] = 0
                    #max runs advance inning
                    if ((runs - start_runs)%MAX_RUNS_PER_INNING == 0):
                        df.loc[sim_runs*MAX_INNINGS + inning] = (inning, runs, outs, runs - start_runs)
                        inning = inning + 1
                        bases = [0,0,0]
                        outs = 0
                        start_runs = runs
                else:
                    bases[2] = bases[0]
                    bases[1] = 1
                    bases[0] = 0
            elif (result == 'p3b'):
                if (bases[2] or bases[1] or bases[0]):
                    runs = min(runs + bases[2] + bases[1] + bases[0],start_runs + MAX_RUNS_PER_INNING)
                    bases[2] = 1
                    bases[1] = 0
                    bases[0] = 0
                    #max runs advance inning
                    if ((runs - start_runs)%MAX_RUNS_PER_INNING == 0):
                        df.loc[sim_runs*MAX_INNINGS + inning] = (inning, runs, outs, runs - start_runs)
                        inning = inning + 1
                        bases = [0,0,0]
                        outs = 0
                        start_runs = runs
                else:
                    bases[2] = 1
                    bases[1] = 0
                    bases[0] = 0
            elif (result == 'phr'):
                runs = min(runs + bases[2] + bases[1] + bases[0] + 1,start_runs + MAX_RUNS_PER_INNING)
                bases[2] = 0
                bases[1] = 0
                bases[0] = 0
                #max runs advance inning
                if ((runs - start_runs)%MAX_RUNS_PER_INNING == 0):
                    df.loc[sim_runs*MAX_INNINGS + inning] = (inning, runs, outs, runs - start_runs)
                    inning = inning + 1
                    bases = [0,0,0]
                    outs = 0
                    start_runs = runs
    return df

#Standalone runner to get a min
def run_player_scenario_mc(all_players, order):
    df = run_player_scenario_mc_standalone(all_players,order)
    average_total_runs = df[df.Inning == MAX_INNINGS]['Runs'].sum()/df[df.Inning == MAX_INNINGS]['Runs'].count()
    #return max runs - average_total since it is a cost not a score
    return MAX_INNINGS*MAX_RUNS_PER_INNING - average_total_runs

def test():
    players =[Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0])]
    w_sum_mh = run_player_scenario_mh(players, [0,1,2,3,4,5,6,7,8,9])
    w_sum_mc = run_player_scenario_mc(players, [0,1,2,3,4,5,6,7,8,9])
    print(w_sum_mh,w_sum_mc)

    players =[Player([0.5, 0.0, 0.0, 0.0, 0.0, 0.5]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([0.5, 0.0, 0.0, 0.0, 0.0, 0.5]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([0.5, 0.0, 0.0, 0.0, 0.0, 0.5]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
          Player([1.0, 0.0, 0.0, 0.0, 0.0, 0.0])]
    w_sum_mh = run_player_scenario_mh(players, [0,1,2,3,4,5,6,7,8,9])
    w_sum_mc = run_player_scenario_mc(players, [0,1,2,3,4,5,6,7,8,9])
    print(w_sum_mh,w_sum_mc)

    w_sum_mh = run_player_scenario_mh(players, [0,1,2,3,4,5,6,7,8,9])
    w_sum_mc = run_player_scenario_mc(players, [0,1,2,3,4,5,6,7,8,9])
    print(w_sum_mh,w_sum_mc)


#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/sum-equals-to-sum/0

def sol(arr, n):
    """
    For every sum of two elements store it in a hash where 'sum' is the key
    and list of sorted indexes are values. If for a given sum the indexes
    do not already exist return True
    """
    sh = {}
    for i in range(n-1):
        for j in range(i+1, n):
            s = arr[i]+arr[j]
            k = sorted((i, j))
            if s in sh and k not in sh[s]:
                return 1
            else:
                sh[s] = [k]
    return 0


"""Solving and counting Drive Ya Nuts puzzles.

A Drive Ya Nuts puzzle is a list of 7 hexagonal nuts, each identified by
a permutation of marks 0 through 5 arranged counterclockwise around its
edges. The nuts are arranged with puzzle[6] in the center, and
puzzle[0:6] in a ring counterclockwise around the center, with the k-th
edge of puzzle[6] facing the 0-th edge of puzzle[k].

The puzzle is solved when the nuts are permuted and rotated so that all
facing marks match, both with the center (puzzle[6][k] == puzzle[k][0])
and consecutively around the ring (puzzle[k][1] == puzzle[k - 1][-1]).
"""

from itertools import permutations, product, groupby
from multiprocessing import Pool
import numpy as np
import heapq
from collections import Counter

def align(nut, mark):
    """Return rotated nut so align(nut, mark)[0] == mark."""
    k = nut.index(mark)
    return nut[k:] + nut[:k]

def all_solutions(puzzle):
    """Generate all solutions of given puzzle."""

    # Start with each nut 0-aligned to eliminate trivial permutations of
    # duplicates.
    for nuts in set(permutations(align(nut, 0) for nut in puzzle)):
        ring = tuple(align(nut, mark) for mark, nut in zip(nuts[-1], nuts[:-1]))
        solved = True
        for k in range(6):
            if ring[k][1] != ring[k - 1][-1]:
                solved = False
                break
        if solved:
            yield ring + (nuts[-1],)

# Pre-compute mappings between puzzle nuts and "packed" integer indices.
packed = dict()
unpacked = dict()
for index, p in enumerate(permutations(range(1, 6))):
    packed[(0,) + p] = index
    unpacked[index] = (0,) + p

def pack(puzzle):
    """Convert puzzle to minimal integer representation."""
    return int.from_bytes(sorted(packed[align(nut, 0)] for nut in puzzle),
                          byteorder='big')

def unpack(index):
    """Convert integer back to puzzle."""
    return tuple(unpacked[nut] for nut in index.to_bytes(7, byteorder='big'))

def all_puzzles(center):
    """Generate all packed puzzles with given center nut."""

    # Find possible sequences of matching marks around the ring.
    for matching in product(range(6), repeat=6):
        halves = tuple(zip(matching, center, matching[-1:] + matching[:-1]))

        # If the result is valid, we can freely permute the remaining 3
        # outer marks on each nut around the ring.
        if all(len(set(inner)) == 3 for inner in halves):
            for ring in product(*([inner + outer
                                   for outer in permutations(
                                       set(range(6)) - set(inner))]
                                  for inner in halves)):
                yield pack(ring + (center,))

def save_puzzles(center):
    """Save sorted(all_puzzles(center)) to corresponding binary file."""
    filename = ''.join(str(mark) for mark in center)
    with open(filename, 'wb') as f:
        a = np.fromiter(all_puzzles(center), dtype=np.uint64)
        a.sort()
        a.tofile(f)

def load_puzzles(center):
    """Generate puzzles loaded from save_puzzles(center)."""
    filename = ''.join(str(mark) for mark in center)
    with open(filename, 'rb') as f:
        puzzle = f.read(8)
        while puzzle:
            yield int.from_bytes(puzzle, byteorder='little')
            puzzle = f.read(8)

if __name__ == '__main__':

    # Parallelize save_puzzles(.) for all possible center nuts.
    with Pool(6) as pool:
        for k, _ in enumerate(pool.imap_unordered(save_puzzles, packed)):
            print('{0} of {1} completed.'.format(k + 1, len(packed)))

    # Merge sort all files, counting distinct puzzles by multiplicity.
    counts = Counter(len(list(group)) for puzzle, group in groupby(
        heapq.merge(*(load_puzzles(center) for center in packed))))

    # Display results.
    for count in sorted(counts):
        print('{0:10} with {1:2} solutions.'.format(counts[count], count))
    print('{0:10} total unique puzzles.'.format(sum(counts.values())))

##    3899636160 with  1 solutions.
##     819638640 with  2 solutions.
##     169424400 with  3 solutions.
##      54822000 with  4 solutions.
##      14079840 with  5 solutions.
##       6587880 with  6 solutions.
##       2049120 with  7 solutions.
##        994080 with  8 solutions.
##        317520 with  9 solutions.
##        185760 with 10 solutions.
##         77760 with 11 solutions.
##         27240 with 12 solutions.
##         13680 with 13 solutions.
##          5040 with 14 solutions.
##          1440 with 15 solutions.
##          2160 with 16 solutions.
##          1800 with 20 solutions.
##    4967864520 total unique puzzles.

##Restrict to puzzles containing (0,1,2,3,4,5):
##     221013350 with  1 solutions.
##      46401870 with  2 solutions.
##       9627016 with  3 solutions.
##       3102349 with  4 solutions.
##        802208 with  5 solutions.
##        371888 with  6 solutions.
##        117102 with  7 solutions.
##         56392 with  8 solutions.
##         18030 with  9 solutions.
##         10512 with 10 solutions.
##          4452 with 11 solutions.
##          1565 with 12 solutions.
##           798 with 13 solutions.
##           282 with 14 solutions.
##            84 with 15 solutions.
##           120 with 16 solutions.
##            93 with 20 solutions.
##     281528111 total unique puzzles.


import cv2
from detection import AccidentDetectionModel
import numpy as np
import os
import streamlit as st
from PIL import Image
def load_image(img):
    return Image.open(img)

st.title('Vehicle Accident Identificaiton System')
model = AccidentDetectionModel("model.json", 'model_weights.h5')
font = cv2.FONT_HERSHEY_SIMPLEX

src_file=st.file_uploader('Upload Image',type=['png','jpg','jpeg'])

if src_file is not None:
    st.image(load_image(src_file),width=250)
    with open('src.jpg','wb') as f:
        f.write(src_file.getbuffer())

    frame = cv2.imread('src.jpg')
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    roi = cv2.resize(gray_frame, (250, 250))

    pred, prob = model.predict_accident(roi[np.newaxis, :, :])
    st.success(pred)
    if(pred == "Accident"):
        prob = (round(prob[0][0]*100, 2))
        st.write(prob)


from PySide2 import QtWidgets
import styles

class CustomMenu(QtWidgets.QWidget):

    def __init__(self, parent=None, type=None):
        QtWidgets.QWidget.__init__(self, parent)

        self.layout = QtWidgets.QGridLayout()
        # self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.setLayout(self.layout)
        self.input = QtWidgets.QLineEdit()
        self.layout.addWidget(self.input, 0, 0)

        self.set_button = QtWidgets.QPushButton()
        self.layout.addWidget(self.set_button, 0, 1)
        range_lbl = QtWidgets.QLabel()
        self.layout.addWidget(range_lbl, 1, 0, 2, 1)
        if type == 1:
            self.set_button.setText('Set DAC')
            range_lbl.setText('Min: 0, Max: 3300')
        else:
            self.set_button.setText('Set Vdelta')
            range_lbl.setText('Min: 0, Max: 500')


from flask import Flask
from providers.redis import RedisProvider
from providers.mongo import MongoProvider
from providers.in_memory import InMemoryProvider
from providers.postgres_direct import PostgresDirectProvider
from experiments.hit_count import HitCountExperiment
from experiments.single_entity import SingleEntityExperiment
from experiments.two_entity_join import TwoEntitiesJoinedExperiment

app = Flask(__name__)

providers = [
    RedisProvider(),
    MongoProvider(),
    InMemoryProvider(),
    PostgresDirectProvider(),
]

experiments = [
    HitCountExperiment(),
    SingleEntityExperiment(),
    TwoEntitiesJoinedExperiment(),
]

@app.route("/")
def overview():

    all_results = []

    for provider in providers:

        all_results.append(" ")
        all_results.append(" ")
        all_results.append(" ")

        all_results.append("TESTING {}".format(provider.name))

        for experiment in experiments:
            all_results.append("----------")
            all_results.append("Experiment: {}".format(experiment.name))

            exp_results = experiment.run_the_experiment(provider)
            all_results.extend(exp_results)

    return "<br />".join(all_results)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)


import math

def soma(vetor1, vetor2):
    resultado = []
    for i in range(len(vetor1)):
        resultado.append(vetor1[i] + vetor2[i])
    return resultado

def subtracao(vetor1, vetor2):
    resultado = []
    for i in range(len(vetor1)):
        resultado.append(vetor1[i] - vetor2[i])
    return resultado

def multipicacao_escalar(vetor, k):
    resultado = []
    for i in range(len(vetor)):
        resultado.append(vetor[i] * k)
    return resultado

def modulo(vetor):
    resultado = 0
    for i in range(len(vetor)):
        resultado += vetor[i] ** 2
    return math.sqrt(resultado)

def produto_escalar(vetor1, vetor2):
    resultado = 0
    for i in range(len(vetor1)):
        resultado += vetor1[i] * vetor2[i]
    return resultado

def angulo_entre_vetores(vetor1, vetor2):
    produto_escalar_vetores = produto_escalar(vetor1, vetor2)
    modulo_vetor1 = modulo(vetor1)
    modulo_vetor2 = modulo(vetor2)
    cos_angulo = produto_escalar_vetores / (modulo_vetor1 * modulo_vetor2)
    return math.degrees(math.acos(cos_angulo))

vetorA = []
vetorB = []
vetorC = []

for i in range(3):
    valor_a = float(input(f"Insira o valor {i + 1} do vetor A: "))
    vetorA.append(valor_a)

for i in range(3):
    valor_b = float(input(f"Insira o valor {i + 1} do vetor B: "))
    vetorB.append(valor_b)

for i in range(3):
    valor_c = float(input(f"Insira o valor {i + 1} do vetor C: "))
    vetorC.append(valor_c)

print("Vetor A: ", vetorA)
print("Vetor B: ", vetorB)
print("Vetor C: ", vetorC)

k = float(input('Digite o valor de k: '))

while True:
    opcao = int(input('Digite uma opção:\n'
                      '1-Calcular soma entre vetores\n'
                      '2-Calcular subtração entre vetores\n'
                      '3-Calcular Multiplicao por escalar\n'
                      '4-Calcular Módulo\n'
                      '5-Calcular Produto Escalar\n'
                      '6-Calcular Angulo entre vetores\n'
                      '0 - Finalizar\n'))
    if opcao == 1:
        opcaoParaSomar = int(
            input('Quais vetores voce deseja somar?\n1-Os Tres\n2-Vetor A e B\n3-Vetor B e C\n4-Vetor A e C\n'))
        if (opcaoParaSomar == 1):
            resultado = soma(soma(vetorA, vetorB), vetorC)
        elif (opcaoParaSomar == 2):
            resultado = soma(vetorA, vetorB)
        elif (opcaoParaSomar == 3):
            resultado = soma(vetorB, vetorC)
        elif (opcaoParaSomar == 4):
            resultado = soma(vetorA, vetorC)
        resultado = [round(x, 2) for x in resultado]
        print(resultado)

    elif opcao == 2:
        opcaoParaSubtrair = int(
            input('Quais vetores voce deseja subtrair?\n1-Os Tres\n2-Vetor A e B\n3-Vetor B e C\n4-Vetor A e C\n'))
        if (opcaoParaSubtrair == 1):
            resultado = subtracao(subtracao(vetorA, vetorB), vetorC)
        elif (opcaoParaSubtrair == 2):
            resultado = subtracao(vetorA, vetorB)
        elif (opcaoParaSubtrair == 3):
            resultado = subtracao(vetorB, vetorC)
        elif (opcaoParaSubtrair == 4):
            resultado = subtracao(vetorA, vetorC)
        resultado = [round(x, 2) for x in resultado]
        print(resultado)

    elif opcao == 3:
        opcaoParaMultiplicacaoEscalar = int(input('Qual vetor voce deseja multiplicar por k?\n'
                                                  '1 - Para vetor A\n'
                                                  '2- Para vetor B\n'
                                                  '3 - Para vetor C\n'))
        if (opcaoParaMultiplicacaoEscalar == 1):
            resultado = multipicacao_escalar(vetorA, k)
        elif (opcaoParaMultiplicacaoEscalar == 2):
            resultado = multipicacao_escalar(vetorB, k)
        elif (opcaoParaMultiplicacaoEscalar == 3):
            resultado = multipicacao_escalar(vetorC, k)

        for i in range(len(resultado)):
            resultado[i] = round(resultado[i], 2)

        for i in range(len(resultado)):
            resultado[i] = round(resultado[i], 2)

        print(resultado)

    elif opcao == 4:
        opcaoParaCalcularModulo = int(input('Qual vetor voce obter o módulo\n'
                                            '1 - Para vetor A\n'
                                            '2- Para vetor B\n'
                                            '3 - Para vetor C\n'))
        if (opcaoParaCalcularModulo == 1):
            resultado = modulo(vetorA)
        elif (opcaoParaCalcularModulo == 2):
            resultado = modulo(vetorB)
        elif (opcaoParaCalcularModulo == 3):
            resultado = modulo(vetorC)
        print(round(resultado, 2))
    elif opcao == 5:
        opcaoParaCalcularProdutoEscalar = int(input('Entre quais vetores voce deseja calcular o Produto Escalar\n'
                                                    '1 - Entre A e B\n'
                                                    '2- Entre B e C\n'
                                                    '3- Entre A e C\n'))
        if (opcaoParaCalcularProdutoEscalar == 1):
            resultado = produto_escalar(vetorA, vetorB)
        elif (opcaoParaCalcularProdutoEscalar == 2):
            resultado = produto_escalar(vetorB, vetorC)
        elif (opcaoParaCalcularProdutoEscalar == 3):
            resultado = produto_escalar(vetorA, vetorC)
        print(round(resultado, 2))
    elif opcao == 6:
        opcaoParaCalcularAnguloEntreVetores = int(input('Entre quais vetores voce deseja calcular o Angulo entre os '
                                                        'Vetores\n'
                                                        '1- Entre A e B\n'
                                                        '2- Entre B e C\n'))
        if (opcaoParaCalcularAnguloEntreVetores == 1):
            resultado = angulo_entre_vetores(vetorA, vetorB)
        elif (opcaoParaCalcularAnguloEntreVetores == 2):
            resultado = angulo_entre_vetores(vetorB, vetorC)
        print(round(resultado, 2))
    elif opcao == 0:
        break


from pathlib import Path
import os
from django.urls import reverse_lazy

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-n)-zr5fm*3dvd7dj@$t%1zuj_(v#e)uh33i1&*v76l5_4q+w9a'

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.noticia',
    'apps.usuario',
    'apps.comentario',
    'django_quill',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'source.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(os.path.dirname(BASE_DIR),'template')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'source.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'es-ar'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(os.path.dirname(BASE_DIR),'static'),
    )
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'media')

QUILL_CONFIGS = {
    'default':{
        'theme': 'snow',
        'modules': {
            'syntax': True,
            'toolbar': [
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block', 'link'],

                [{ 'header': 1 }, { 'header': 2 }, { 'header': 3 }],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'script': 'sub'}, { 'script': 'super' }],
                [{ 'indent': '-1'}, { 'indent': '+1' }],
                [{ 'direction': 'rtl' }],

                [{ 'size': ['small', True, 'large', 'huge'] }],
                [{ 'header': [1, 2, 3, 4, 5, 6, False] }],

                [{ 'color': [] }, { 'background': [] }],
                [{ 'font': [] }],
                [{ 'align': [] }],

                ['clean']
            ]
        }
    }
}
# Default primary key field type
LOGIN_REDIRECT_URL = reverse_lazy('index')
LOGOUT_REDIRECT_URL = reverse_lazy('index')
LOGIN_URL = reverse_lazy('usuario:login')
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

import django_heroku
django_heroku.settings(locals())


import os
import cv2
import numpy as np
import json
from tqdm import tqdm
from copy import deepcopy
from pathlib import Path

img_exts=['jpg', 'png', 'jpeg', 'bmp', 'tif']

def img_resize(image, width_new = 1280, height_new = 720):
    height, width = image.shape[0], image.shape[1]
    # 设置新的图片分辨率框架
    # 判断图片的长宽比率
    if width / height >= width_new / height_new:
        img_new = cv2.resize(image, (width_new, int(height * width_new / width)))
    else:
        img_new = cv2.resize(image, (int(width * height_new / height), height_new))
    return img_new

def make_label(root, save_path):
    label_dict={}
    root=Path(root)

    cls_list=list(filter(lambda x:os.path.isdir(root / x), os.listdir(root)))

    for i, cls in enumerate(cls_list):
        imgs=os.listdir(root / cls)
        for img in imgs:
            if img[img.rfind('.')+1:].lower() in img_exts:
                label_dict[os.path.join(cls, img)] = i

    with open(save_path, 'w', encoding='utf8') as f:
        json.dump(label_dict, f, ensure_ascii=False)
    return label_dict

if __name__ == '__main__':
    root='images_group/' #图像文件夹路径
    label_dict=make_label(root, 'dataset.json')


from view import *
from vector import *
from world import *
from entity import *
from comps import *

# Paricle

# Constants
G = 10
FRICTION = 10
SIMULATION_TICK = 1
TARGET_FPS = 60

# Collider Shapes
CIRCLE = 0
SQUARE = 1
HEXAGON = 2
TRIANGLE = 3

class Particle(Entity):
    particles = []

    def __init__(self, pos, shape = CIRCLE, mass = 1):
        Entity.__init__(self)
        Particle.particles.append(self)
        self.add_comp(Position(pos))
        self.add_comp(Physics(mass))

# INIT
view = View()
world = view.WORLD

# Setup
x = Particle((100, -300, 0), mass=200)
# x.comps["Physics"].velocity = Vector(50, 0, 0)
world.place_entity(x)
y = Particle((400, -500, 0), mass=200)
# y.comps["Physics"].velocity = Vector(0, 50, 0)
world.place_entity(y)
z = Particle((600, -200, 0), mass=200)
# z.comps["Physics"].velocity = Vector(0, 50, 0)
world.place_entity(z)

delta_time = 0

while view.running == True:
    start = time.time()
    view.main_loop(delta_time)
    world.physics_suspended = view.physics_suspended
    world.simulate_physics(delta_time)
    delta_time = time.time() - start


import threading
import time
from encryption import encrypt
from decryption import decrypt

class BruteForceDecrypt:
    def __init__(self):
        self.correct_keys = []
        self.lock = threading.Lock()

    def _brute_force(self, pairs, start, end):
        for key in range(start, end):
            key_str = '{0:010b}'.format(key)
            for plaintext, ciphertext in pairs:
                decrypted = decrypt(ciphertext, key_str)
                if decrypted != plaintext:
                    break
            else:
                with self.lock:
                    if len(key_str) == 10:
                        self.correct_keys.append(key_str)

    def single_thread_brute_force(self, pairs):
        self._brute_force(pairs, 0, 2 ** 10)
        return self.correct_keys

    def multi_thread_brute_force(self, pairs):
        threads = []
        for i in range(8):
            start = i * (2 ** 9)
            end = (i + 1) * (2 ** 9)
            thread = threading.Thread(target=self._brute_force, args=(pairs, start, end))
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()
        return self.correct_keys

    def decrypt(self, plaintext_str, ciphertext_str):
        # Split the input strings into lists of plaintexts and ciphertexts
        plaintexts = plaintext_str.split(";")
        ciphertexts = ciphertext_str.split(";")

        # Zip the plaintexts and ciphertexts together to create pairs
        pairs = list(zip(plaintexts, ciphertexts))

        # Single-threaded brute force
        start_time = time.time()
        single_result = self.single_thread_brute_force(pairs)
        single_time = time.time() - start_time
        self.correct_keys.clear()  # Reset for the next brute force

        # Multi-threaded brute force
        start_time = time.time()
        multi_result = self.multi_thread_brute_force(pairs)
        multi_time = time.time() - start_time

        return {
            "single_thread": {
                "keys": single_result,
                "time": single_time
            },
            "multi_thread": {
                "keys": multi_result,
                "time": multi_time
            }
        }


from openerp.addons.payroll_employee_benefit.tests.\
    test_employee_benefit import TestEmployeeBenefitBase

class TestEmployeeBenefit(TestEmployeeBenefitBase):

    def setUp(self):
        super(TestEmployeeBenefit, self).setUp()

        self.rates[1].write({
            'amount_type': 'percent_gross',
            'line_ids': [(5, 0)],
        })

        self.rate_lines = [
            self.rate_line_model.create({
                'parent_id': line[0].id,
                'employee_amount': line[1],
                'employer_amount': line[2],
                'date_start': line[3],
                'date_end': line[4],
            })
            for line in [
                (self.rates[1], 2, 3, '2015-01-01', '2015-06-30'),
                (self.rates[1], 4, 5, '2015-07-01', False),
            ]
        ]

        self.rule.write({
            'amount_python_compute': """
payslip.set_gross_salary(2000)
payslip.compute_benefits()
result = rule.sum_benefits(payslip)
"""
        })

    def test_compute_payslip(self):
        payslip = self.compute_payslip()

        self.assertEqual(payslip['RULE_1'], 20 + 2000 * 2 / 100)
        self.assertEqual(payslip['RULE_2'], 2000 * 3 / 100)


from sklearn.preprocessing import PolynomialFeatures
from fastsklearnfeature.declarative_automl.optuna_package.optuna_utils import id_name

class PolynomialFeaturesOptuna(PolynomialFeatures):
    def generate_hyperparameters(self, space_gen, depending_node=None):
        self.name = id_name('PolynomialFeatures_')

        space_gen.generate_number(self.name + "degree", 2, depending_node=depending_node, low=2, high=3, is_float=False)
        space_gen.generate_cat(self.name + "interaction_only", ['False', 'True'], 'False', depending_node=depending_node)
        space_gen.generate_cat(self.name + "include_bias", ['True', 'False'], 'True', depending_node=depending_node)


import re
import logging
import shutil
import os

logger = logging.getLogger(__name__)

cppkeyword = ('alignas',   'continue',     'friend',   'register',         'true',
              'alignof',   'decltype'      'goto',     'reinterpret_cast', 'try',
              'asm',       'default',      'if',       'return',           'typedef',
              'auto',      'delete',       'inline',   'short',            'typeid',
              'bool',      'do',           'int',      'signed',           'typename',
              'break',     'double',       'long',     'sizeof',           'union',
              'case',      'dynamic_cast', 'mutable',  'static',           'unsigned',
              'catch',     'else',         'namespace', 'static_assert',    'using',
              'char',      'enum',         'new',      'static_cast',      'virtual',
              'char16_t',  'explicit',     'noexcept', 'struct',           'void',
              'char32_t',  'export',       'nullptr',  'switch',           'volatile',
              'class',     'extern',       'operator', 'template',         'wchar_t',
              'const',     'false',        'private',  'this',             'while',
              'constexpr', 'float',        'protected', 'thread_local',
              'const_cast', 'for',          'public',   'throw')

cppconst = ('NULL', 'TRUE', 'FALSE', 'True', 'False')

appconst = ('IN', 'OUT', 'interface')

def camel_name(name):
    name = name.lower()
    name = name.replace('-', '_')
    camelName = ''
    for nm in name.split('_'):
        camelName = camelName + nm.capitalize()
    return camelName

def lower_name(name):
    name = name.replace('-', '_')
    name = name.lower()
    return name

def pbname(name):
    name = name.replace('-', '_')
    name = name.lower()
    if name in cppkeyword:
        name += '_'
    return name

def cppname(name):
    name = name.lower()
    name = name.replace('-', '_')
    camelName = ''
    for nm in name.split('_'):
        camelName = camelName + nm.capitalize()
    return camelName

def cppnormalize(name):
    name = re.sub('\s*<\s*', '_LT_', name)
    name = re.sub('\s*<=\s*', '_LE_', name)
    name = re.sub('\s*>\s*', '_GT_', name)
    name = re.sub('\s*>=\s*', '_GE_', name)
    name = re.sub('\s*=\s*', '_EQ_', name)
    name = re.sub('\s*\+\s*', '_PS_', name)
    name = re.sub('\s+', '_', name)
    if name[0] in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
        name = '_' + name
    name = re.sub('[^a-zA-Z0-9_]', '_', name)

    if name in cppkeyword:
        name += '_'
    elif name in cppconst:
        name += '_'
    elif name in appconst:
        name += '_'

    return name

def allzero(default):
    for ch in default:
        if ch != '0':
            return False
    return True

def ipv4str(i):
    ipstr = "%d.%d.%d.%d" % (i & 0xFF, i >> 8 & 0xFF,
                             i >> 16 & 0xFF, i >> 32 & 0xFF)
    return ipstr

def mkdir(inDir, inRemove=False):
    dir = os.path.dirname(inDir)
    if dir == '':
        return

    if inRemove and os.path.exists(dir):
        shutil.rmtree(inDir)

    if os.path.exists(dir):
        logger.debug('%s already exist', dir)
    else:
        os.makedirs(dir)
        logger.debug('makedirs %s', dir)

# Lookup table for non-utf8, with necessary escapes at (o >= 127 or o < 32)
_cescape_byte_to_str = ([r'%02X' % i for i in range(0, 32)] +
                        [r'%2s' % chr(i) for i in range(32, 127)] +
                        [r'%02X' % i for i in range(127, 256)])
_cescape_byte_to_str_hex = ([r'\%02X' % i for i in range(0, 256)])

def cescape(text, hexed=False):
    if hexed:
        return ''.join(_cescape_byte_to_str_hex[ord(c)] for c in text)
    else:
        return ''.join(_cescape_byte_to_str[ord(c)] for c in text)

class EncodeUtil(object):
    @staticmethod
    def DecodeBigEndian32(buffer):
        i = 1
        result = ord(buffer[0])
        while i < 4:
            result = result * 256 + ord(buffer[i])
            i = i + 1
        return result

    @staticmethod
    def DecodeLittleEndian32(buffer):
        i = 4
        result = ord(buffer[3])
        while i > 1:
            i -= 1
            result = result * 256 + ord(buffer[i - 1])
        return result

    @staticmethod
    def EncodeLittleEndian32(i):
        buffer = bytearray(4)
        buffer[0] = i & 0xFF
        buffer[1] = i >> 8 & 0xFF
        buffer[2] = i >> 16 & 0xFF
        buffer[3] = i >> 24 & 0xFF
        return buffer


# 1948. 날짜 계산기

t = int(input())
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

for tc in range(1, t + 1):
    start_m, start_d, end_m, end_d = map(int, input().split())
    result = 0

    if start_m == end_m:
        result = end_d - start_d + 1

    else:
        result += days[start_m - 1] - start_d + end_d + 1

        for i in range(12):
            if start_m < i + 1 < end_m:
                result += days[i]
    print(f'#{tc} {result}')


def mutate_string(string, position, character):
    line = string
    line1 = line[:position]
    line2 = line[position+1:]
    return line1 + character + line2

if __name__ == '__main__':
    s = input()
    i, c = input().split()
    s_new = mutate_string(s, int(i), c)
    print(s_new)


import json
import os
import torch
from utils import set_seed, get_checkpoint_name
from transformers import AutoTokenizer, AutoModelForSequenceClassification, DataCollatorWithPadding
from torch.nn import functional as F
from collections import defaultdict
from utils import calculate_IR_metrics
from data import load_all_samples
from torch.utils.data import DataLoader
import numpy as np
import math
from utils import calculate_true_label_probs, count_true_label_correct, RPF1, RPF1_binary, create_pickle

def evaluate_data(model, data_loader, config, device):
    """
    Evaluate the given model on a data loader and calculate various metrics.

    Args:
        model (torch.nn.Module): The model to evaluate.
        data_loader (torch.utils.data.DataLoader): DataLoader containing the evaluation data.
        config (dict): A configuration dictionary with options for evaluation.
        device (torch.device): The device (CPU or GPU) on which to perform evaluation.

    Returns:
        tuple: A tuple containing:
            a. preds (torch.Tensor): Model predictions.
            b. labels (torch.Tensor): Ground truth labels.
            c. avg_loss (float): Average loss over the evaluation dataset.
            d. metrics (dict): Dictionary of evaluation metrics (e.g., 'r1', 'r2', 'mrr') if not in debug mode.

    Note:
        This function evaluates the given model on a provided data loader, calculates the average loss,
        and optionally computes additional evaluation metrics such as Recall@1 (r1), Recall@2 (r2),
        and Mean Reciprocal Rank (MRR) if not in debug mode.
    """
    model.eval()
    print('Evaluate...')
    total_loss = 0
    labels = []
    preds = []
    sentence_ids = []
    option_ids = []

    for i, batch in enumerate(data_loader):
        inputs = {key: value.to(device) for key, value in batch.items() if key not in ['sentence_id','option_id']}
        outputs = model(**inputs)
        total_loss += outputs.loss.item()
        # Get predictions
        preds.append(outputs.logits.cpu().detach())
        labels.append(batch['labels'].cpu().detach())

        sentence_ids.extend(batch['sentence_id'])
        option_ids.extend(batch['option_id'])

    # Concatenate predictions and labels
    preds = torch.cat(preds, dim=0) # torch tensor (num_val_examples, 2)
    labels = torch.cat(labels, dim=0) # torch tensor (num_val_examples)

    if config['calculate_probs']:
        preds = calculate_probs(preds) # torch tensor (num_val_examples, 2)

    grouped_data, labeled_data = group_data(sentence_ids, option_ids, preds, labels)

    sorted_data = sort_grouped_data(grouped_data)
    metrics = {}
    r_1, r_2, mrr = calculate_IR_metrics(sorted_data, labeled_data)
    p, r, f1 = RPF1(grouped_data, labeled_data)

    binary_precision, binary_recall, binary_f1_score = RPF1_binary(preds, labels)

    metrics['r1'] = r_1
    metrics['r2'] = r_2
    metrics['mrr'] = mrr
    metrics['precision'] = p
    metrics['recall'] = r
    metrics['f1'] = f1
    metrics['binary_precision'] = binary_precision
    metrics['binary_recall'] = binary_recall
    metrics['binary_f1_score'] = binary_f1_score

    avg_loss = total_loss / len(data_loader)
    model.train()

    return preds, labels, avg_loss, metrics, grouped_data, labeled_data

def group_data(sentence_ids, option_ids, probabilities, labels):
    """
    Group data based on sentence IDs and create a mapping of labeled data.

    Args:
        sentence_ids (list[int]): List of sentence IDs.
        option_ids (list[int]): List of option IDs.
        probabilities (list[float]): List of tuples containing prediction probabilities for negative and positive class respectively
        labels (list[int]): List of labels (0 or 1).

    Returns:
        tuple (dict, dict): A tuple containing two dictionaries -
            a. grouped_data: A dictionary mapping sentence IDs to a list of (option_id, positive_probability) tuples.
            b. labeled_data: A dictionary mapping sentence IDs to the option_id with a positive label.
    """
    grouped_data = defaultdict(list) # {sentence_id : [(option_id, predict_positive_prob),..]}
    labeled_data = defaultdict(int) # {sentence_id : option_id}
    # Iterate through the lists and group based on sentence IDs
    for sentence_id, option_id, probability, label in zip(sentence_ids, option_ids, probabilities, labels):
        #tensor to scalar
        sentence_id, option_id = sentence_id.item(), option_id.item()
        #! take at position 1 because
        pos_probability, label = probability[1].item(), label.item()

        grouped_data[sentence_id].append((option_id, pos_probability))
        if label == 1:
            labeled_data[sentence_id] = option_id

    return grouped_data, labeled_data

def sort_grouped_data(grouped_data): # grouped_data {sentence_id : [(option_id, predict_positive_prob),..]}
    # for each sentence_id sort the options in decreasing order
    """
    Sort grouped data based on prediction probabilities.

    Args:
        grouped_data (dict): A dictionary mapping sentence IDs to a list of (option_id, positive_probability) tuples produced from group_data method.

    Returns:
        sorted_grouped_data (dict): A dictionary mapping sentence IDs to a list of option IDs sorted in decreasing order of probabilities.
    """
    sorted_grouped_data = {}
    for sentence_id in grouped_data.keys():
        # Create pairs of values and probabilities
        pairs = grouped_data[sentence_id]

        # Sort the pairs based on probabilities
        sorted_pairs = sorted(pairs, key=lambda x: x[1], reverse=True)

        # Extract the sorted option_ids from the sorted pairs
        sorted_option_ids = [pair[0] for pair in sorted_pairs]

        # Store the sorted values in the result dictionary
        sorted_grouped_data[sentence_id] = sorted_option_ids
    return sorted_grouped_data

def calculate_probs(logits):
    """
    Calculate probabilities from logits using softmax.

    Args:
        logits (tensor): Input logits.

    Returns:
        probs (tenosr): Probability values obtained using softmax in the last dimension.
    """
    probs = F.softmax(logits, dim=-1)
    return probs

def load_config(path):
    # Open and read the JSON file
    with open(path, 'r') as file:
        config = json.load(file)
    return config


## (C) 2016 Muthiah Annamalai,
from . import views
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
                       # evaluate code by enqueuing in file
                       url(r'^eval/$',views.evaluate),

                       # check status of job in queue - (nojob, processing, queued, completed)
                       url(r'^query/?P<job>.+$',views.query),

                       # result of the job
                       url(r'^result/?P<job>.+$',views.result),

                       # delete the job
                       url(r'^delete/?P<job>.+$',views.delete_qjob),
                       )