import os

from webkitpy.bugzilla import Bug, Attachment
from webkitpy.committers import CommitterList, Reviewer
from webkitpy.mock import Mock
from webkitpy.scm import CommitMessage
from webkitpy.webkit_logging import log

def _id_to_object_dictionary(*objects):
    dictionary = {}
    for thing in objects:
        dictionary[thing["id"]] = thing
    return dictionary

# FIXME: The ids should be 1, 2, 3 instead of crazy numbers.

_patch1 = {
    "id": 197,
    "bug_id": 42,
    "url": "http://example.com/197",
    "is_obsolete": False,
    "is_patch": True,
    "review": "+",
    "reviewer_email": "foo@bar.com",
    "commit-queue": "+",
    "committer_email": "foo@bar.com",
    "attacher_email": "Contributer1",
}

_patch2 = {
    "id": 128,
    "bug_id": 42,
    "url": "http://example.com/128",
    "is_obsolete": False,
    "is_patch": True,
    "review": "+",
    "reviewer_email": "foo@bar.com",
    "commit-queue": "+",
    "committer_email": "non-committer@example.com",
    "attacher_email": "eric@webkit.org",
}

_patch3 = {
    "id": 103,
    "bug_id": 75,
    "url": "http://example.com/103",
    "is_obsolete": False,
    "is_patch": True,
    "review": "?",
    "attacher_email": "eric@webkit.org",
}

_patch4 = {
    "id": 104,
    "bug_id": 77,
    "url": "http://example.com/103",
    "is_obsolete": False,
    "is_patch": True,
    "review": "+",
    "commit-queue": "?",
    "reviewer_email": "foo@bar.com",
    "attacher_email": "Contributer2",
}

_patch5 = {
    "id": 105,
    "bug_id": 77,
    "url": "http://example.com/103",
    "is_obsolete": False,
    "is_patch": True,
    "review": "+",
    "reviewer_email": "foo@bar.com",
    "attacher_email": "eric@webkit.org",
}

_patch6 = { # Valid committer, but no reviewer.
    "id": 106,
    "bug_id": 77,
    "url": "http://example.com/103",
    "is_obsolete": False,
    "is_patch": True,
    "commit-queue": "+",
    "committer_email": "foo@bar.com",
    "attacher_email": "eric@webkit.org",
}

_patch7 = { # Valid review, patch is marked obsolete.
    "id": 107,
    "bug_id": 76,
    "url": "http://example.com/103",
    "is_obsolete": True,
    "is_patch": True,
    "review": "+",
    "reviewer_email": "foo@bar.com",
    "attacher_email": "eric@webkit.org",
}

# This must be defined before we define the bugs, thus we don't use
# MockBugzilla.unassigned_email directly.
_unassigned_email = "unassigned@example.com"

# FIXME: The ids should be 1, 2, 3 instead of crazy numbers.

_bug1 = {
    "id": 42,
    "title": "Bug with two r+'d and cq+'d patches, one of which has an "
             "invalid commit-queue setter.",
    "assigned_to_email": _unassigned_email,
    "attachments": [_patch1, _patch2],
}

_bug2 = {
    "id": 75,
    "title": "Bug with a patch needing review.",
    "assigned_to_email": "foo@foo.com",
    "attachments": [_patch3],
}

_bug3 = {
    "id": 76,
    "title": "The third bug",
    "assigned_to_email": _unassigned_email,
    "attachments": [_patch7],
}

_bug4 = {
    "id": 77,
    "title": "The fourth bug",
    "assigned_to_email": "foo@foo.com",
    "attachments": [_patch4, _patch5, _patch6],
}

class MockBugzillaQueries(Mock):

    def __init__(self, bugzilla):
        Mock.__init__(self)
        self._bugzilla = bugzilla

    def _all_bugs(self):
        return map(lambda bug_dictionary: Bug(bug_dictionary, self._bugzilla),
                   self._bugzilla.bug_cache.values())

    def fetch_bug_ids_from_commit_queue(self):
        bugs_with_commit_queued_patches = filter(
                lambda bug: bug.commit_queued_patches(),
                self._all_bugs())
        return map(lambda bug: bug.id(), bugs_with_commit_queued_patches)

    def fetch_attachment_ids_from_review_queue(self):
        unreviewed_patches = sum([bug.unreviewed_patches()
                                  for bug in self._all_bugs()], [])
        return map(lambda patch: patch.id(), unreviewed_patches)

    def fetch_patches_from_commit_queue(self):
        return sum([bug.commit_queued_patches()
                    for bug in self._all_bugs()], [])

    def fetch_bug_ids_from_pending_commit_list(self):
        bugs_with_reviewed_patches = filter(lambda bug: bug.reviewed_patches(),
                                            self._all_bugs())
        bug_ids = map(lambda bug: bug.id(), bugs_with_reviewed_patches)
        # NOTE: This manual hack here is to allow testing logging in
        # test_assign_to_committer the real pending-commit query on bugzilla
        # will return bugs with patches which have r+, but are also obsolete.
        return bug_ids + [76]

    def fetch_patches_from_pending_commit_list(self):
        return sum([bug.reviewed_patches() for bug in self._all_bugs()], [])

# FIXME: Bugzilla is the wrong Mock-point.  Once we have a BugzillaNetwork
#        class we should mock that instead.
# Most of this class is just copy/paste from Bugzilla.

class MockBugzilla(Mock):

    bug_server_url = "http://example.com"

    unassigned_email = _unassigned_email

    bug_cache = _id_to_object_dictionary(_bug1, _bug2, _bug3, _bug4)

    attachment_cache = _id_to_object_dictionary(_patch1,
                                                _patch2,
                                                _patch3,
                                                _patch4,
                                                _patch5,
                                                _patch6,
                                                _patch7)

    def __init__(self):
        Mock.__init__(self)
        self.queries = MockBugzillaQueries(self)
        self.committers = CommitterList(reviewers=[Reviewer("Foo Bar",
                                                            "foo@bar.com")])

    def fetch_bug(self, bug_id):
        return Bug(self.bug_cache.get(bug_id), self)

    def fetch_attachment(self, attachment_id):
        # This could be changed to .get() if we wish to allow failed lookups.
        attachment_dictionary = self.attachment_cache[attachment_id]
        bug = self.fetch_bug(attachment_dictionary["bug_id"])
        for attachment in bug.attachments(include_obsolete=True):
            if attachment.id() == int(attachment_id):
                return attachment

    def bug_url_for_bug_id(self, bug_id):
        return "%s/%s" % (self.bug_server_url, bug_id)

    def fetch_bug_dictionary(self, bug_id):
        return self.bug_cache.get(bug_id)

    def attachment_url_for_id(self, attachment_id, action="view"):
        action_param = ""
        if action and action != "view":
            action_param = "&action=%s" % action
        return "%s/%s%s" % (self.bug_server_url, attachment_id, action_param)

class MockBuildBot(Mock):

    def builder_statuses(self):
        return [{
            "name": "Builder1",
            "is_green": True,
        }, {
            "name": "Builder2",
            "is_green": True,
        }]

    def red_core_builders_names(self):
        return []

class MockSCM(Mock):

    def __init__(self):
        Mock.__init__(self)
        self.checkout_root = os.getcwd()

    def create_patch(self):
        return "Patch1"

    def commit_ids_from_commitish_arguments(self, args):
        return ["Commitish1", "Commitish2"]

    def commit_message_for_local_commit(self, commit_id):
        if commit_id == "Commitish1":
            return CommitMessage("CommitMessage1\n" \
                "https://bugs.example.org/show_bug.cgi?id=42\n")
        if commit_id == "Commitish2":
            return CommitMessage("CommitMessage2\n" \
                "https://bugs.example.org/show_bug.cgi?id=75\n")
        raise Exception("Bogus commit_id in commit_message_for_local_commit.")

    def create_patch_from_local_commit(self, commit_id):
        if commit_id == "Commitish1":
            return "Patch1"
        if commit_id == "Commitish2":
            return "Patch2"
        raise Exception("Bogus commit_id in commit_message_for_local_commit.")

    def diff_for_revision(self, revision):
        return "DiffForRevision%s\n" \
               "http://bugs.webkit.org/show_bug.cgi?id=12345" % revision

    def svn_revision_from_commit_text(self, commit_text):
        return "49824"

    def modified_changelogs(self):
        # Ideally we'd return something more interesting here.  The problem is
        # that LandDiff will try to actually read the path from disk!
        return []

class MockUser(object):

    @staticmethod
    def prompt(message, repeat=1, raw_input=raw_input):
        return "Mock user response"

    def edit(self, files):
        pass

    def page(self, message):
        pass

    def confirm(self, message=None):
        return True

    def open_url(self, url):
        log("MOCK: user.open_url: %s" % url)
        pass

class MockStatusServer(object):

    def __init__(self):
        self.host = "example.com"

    def patch_status(self, queue_name, patch_id):
        return None

    def update_status(self, queue_name, status, patch=None, results_file=None):
        return 187

class MockBugzillaTool():

    def __init__(self):
        self.bugs = MockBugzilla()
        self.buildbot = MockBuildBot()
        self.executive = Mock()
        self.user = MockUser()
        self._scm = MockSCM()
        self.status_server = MockStatusServer()

    def scm(self):
        return self._scm

    def path(self):
        return "echo"


import time

import dramatiq

from challenge.application import repository  # noqa:F401
from challenge.application import app, projections, translator

@dramatiq.actor(queue_name="manual-translation")
def projections_task(id):
    """ Task for updating the read-model of an aggregate.

    As the read-model doesn't need to be updated in real-time, a worker
    is scheduled to do these updates when possible.

    Args:
        id (string): An aggregate UUID4 string.
    """
    projections.update(id)

@dramatiq.actor(queue_name="manual-translation")
def translation_task(id):
    """ Task for processing a translation.

    This task is responsible for requesting the translation service to
    translate a given text from English to Spanish.

    The Translation aggregate is already created and persisted, so this
    task must fetch its data. If for some reason the application goes
    down, it's possible to reprocess "requested" translations adding
    their IDs to the workers queue.

    Args:
        id (string): The translation aggregate UUID4 string.
    """
    translation = repository.get(id)
    translation = translator.process(translation)
    repository.save(translation)
    projections_task.send(id)

@dramatiq.actor(queue_name="machine-translation")
def nmt_task(id):
    """ Task for automatically processing a translation.

    This task is responsible for requesting the Marian-NMT server to
    translate a given text from English to Spanish.

    The Translation aggregate is already created and persisted, so this
    task must fetch its data. If for some reason the application goes
    down, it's possible to reprocess "requested" translations adding
    their IDs to the workers queue.

    Args:
        id (string): The translation aggregate UUID4 string.
    """
    translation = repository.get(id)
    translation = translator.nmt_process(translation)
    repository.save(translation)
    projections_task.send(id)


import msvcrt
import select
import sys

class myNonBlockingInput():
    def __init__(self):
        self.buffer = str()
        self.ret = str()

    def ReceiveInput(self):
        if(msvcrt.kbhit()):
            char = msvcrt.getch().decode("utf-8")
            self.buffer += char
            print(char,end="")
        if(len(self.buffer) > 0 and self.buffer[-1] == '\r'):
            self.ret = self.buffer[0:-1]
            self.buffer = ""
            print(self.ret)
            return self.ret
        else: return ""

'''
class myNonBlockingInput():
    def __init__(self):
        self.buffer = str()
        self.ret = str()

    def ReceiveInput(self):
        i, o, e = select.select( [sys.stdin], [], [], 1)
        if (i):
            self.buffer.append(sys.stdin.buffer.readline().strip())   #sys.stdin.readline() 可以讀取成str
#sys.stdin.buffer.readline() 讀取成bytes
        else:
            pass
        while len(self.buffer) > 0:
            self.ret = bytes(self.buffer.pop())
            print("(debug)[communicator.py][inputFunc]self.ret:",self.ret)
        return self.ret
        #print("(debug)[communicator.py][[testFunc]dataQueue:",dataQueue)
        #大感謝這個方法使input可以被中斷出來檢查flag是否轉為停止
        #https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout -Pontus
'''


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

# ---------------- EXERCITIUL 1 ----------------------
def exercitiul_unu():
    # Trebuie sa calculam derivatele partiale in functie de x si y pentru a determina matricile A si b
    # -----------------------
    # df1(x) = x - 8.0 * y - 7
    # df1(y) = -8.0 * x + 164 * y + 2
    # -----------------------
    # Determinarea matricelor A si b dupa calcularea derivatelor partiale
    A = np.array([[1, -8],[-8, 164]]).astype(float) # Matrice pozitiv definita
    b = np.array([[-7],[2]]).astype(float)

    if verif_sim_poz_def(A):
        # Daca matricea A este simetrica si pozitiv definita => f admite punct de minim
        # Retin pasii facuti la fiecare iteratie in vectori
        p_minim, steps_pas_desc = pas_descendent(A, b)
        p_minim, steps_grd_conj = gradient_conjugat(A, b)
        # Afisez graficul cu liniile de nivel
        # Pentru metoda pasului descendent
        linii_nivel(A, b, steps_pas_desc, steps_grd_conj, 1)
        # Pentru metoda gradientilor conjugati
        linii_nivel(A, b, steps_pas_desc, steps_grd_conj, 2)

# Functia pentru care vreau sa calculez punctul de minim
def f1(x, y):
    return 0.5 * x ** 2 - 8.0 * x * y - 7.0 * x + 82.0 * y ** 2 + 2 * y

# Functie care verifica daca o matrice este simetrica si pozitiv definita
def verif_sim_poz_def(A):

    # Verific daca matricea este simetrica
    # Calculez transpusa matricei
    transpusa = A.transpose()
    este_simetrica = np.all(A == transpusa)

    # O matrice este simetrica daca este egala cu transpusa ei
    # Daca matricea nu este simetrica => returnam False
    if este_simetrica == False:
        return False

    # Verific daca este pozitiv definita cu Criteriul lui Sylvester
    # Fiecare minor trebuie sa fie strict pozitiv

    for i in range(A.shape[0]):
        # daca unul din minori este <= 0 => se va returna False
        if np.linalg.det(A[:i, :i]) <= 0:
            return False

    # Daca niciuna din verificarile de mai sus nu a returnat False =>
    # Matricea este simetrica si pozitiv definita
    return True

def grid_discret(A, b):
    """
    Construieste un grid discret si evaleaza f in fiecare punct al gridului
    """

    size = 100 # Numar de puncte pe fiecare axa
    x1 = np.linspace(-100, 100, size) # Axa x1
    x2 = np.linspace(-4, 6, size) # Axa x2
    X1, X2 = np.meshgrid(x1, x2) # Creeaza un grid pe planul determinat de axele x1 si x2

    X3 = np.zeros((size, size))
    for i in range(size):
        for j in range(size):
            x = np.array([X1[i,j], X2[i,j]]) # x e vectorul ce contine coordonatele unui punct din gridul definit mai sus
            # functia este de forma urmatoare
            # f(x) = 1/2 * x.T * A * x - b * x
            X3[i,j] = .5 * x @ A @ x - x @ b # Evaluam functia in punctul x

    return X1, X2, X3

def grafic_f(A,b):
    """
    Construieste graficul functiei f
    """

    # Construieste gridul asociat functiei
    (X1, X2, X3) = grid_discret(A, b)

    # Defineste o figura 3D
    fig1 = plt.figure()
    ax = plt.axes(projection="3d")

    # Construieste graficul functiei f folosind gridul discret X1, X2, X3=f(X1,X2)
    ax.plot_surface(X1, X2, X3, rstride=1, cstride=1, cmap='winter', edgecolor='none')

    # Etichete pe axe
    ax.set_xlabel('x1')
    ax.set_ylabel('x2')
    ax.set_zlabel('f(x1,x2)')

    # Titlu
    ax.set_title('Graficul functiei f')

    # Afiseaza figura
    plt.show()

def linii_nivel(A,b, steps_pas_desc, steps_grd_conj, metoda):
    """
    Construieste liniile de nivel ale functiei f
    """

    # Construieste gridul asociat functiei
    (X1, X2, X3) = grid_discret(A, b)

    # Ploteaza liniile de nivel ale functiei f
    fig2 = plt.figure()
    plt.contour(X1, X2, X3, levels = 10) # levels = numarul de linii de nivel

    # ------------- PLOTEAZA TOTI PASII ALGORITMULUI ---------------
    # De la metoda pasului descendent
    if metoda == 1:
        for i in range(len(steps_pas_desc)-1):
            plt.plot([steps_pas_desc[i][0][0], steps_pas_desc[i+1][0][0]], [steps_pas_desc[i][1][0], steps_pas_desc[i+1][1][0]], linestyle='-', linewidth=3)

    if metoda == 2:
    # De la metoda gradientilor conjugati
        for i in range(len(steps_grd_conj)-1):
            plt.plot([steps_grd_conj[i][0][0], steps_grd_conj[i+1][0][0]], [steps_grd_conj[i][1][0], steps_grd_conj[i+1][1][0]], linestyle='-', linewidth=3)

    # Etichete pe axe
    plt.xlabel('x1')
    plt.ylabel('x2')

    # Titlu
    if metoda == 1:
        plt.title('Liniile de nivel ale functiei f pentru metoda pasului descendent')

    if metoda == 2:
        plt.title('Liniile de nivel ale functiei f pentru metoda gradientilor conjugati')

    # Afiseaza figura
    plt.show()

# ----------- METODA PASULUI DESCENDENT ---------------------
def pas_descendent(A, b):
    # Pentru a aplica acest algoritm matricea trebuie sa fie simetrica si pozitiv definita
    # Aleg punctul initial
    x_k = np.array([[-10], [1]]).astype(float)
    # Trebuie sa retin punctele prin care trec
    x_puncte_grafic = [x_k]

    # Reziduu -> ne arata cat de aproape este de solutie valoarea calculata de noi
    reziduu = b - A @ x_k
    # Punctul de oprire
    eps = 1e-8

    # Folosesc norma 2
    norma = lambda x: np.linalg.norm(x, ord = 2)
    iteratii = 0
    while norma(reziduu) > eps:
        iteratii += 1
        # Aceasta valoare determina cat de mult trebuie sa coboram pe gradient -> arata "dimensiunea" pasului la fiecare iteratie
        learning_rate = (reziduu.T @ reziduu) / (reziduu.T @ A @ reziduu)
        x_k = x_k + learning_rate * reziduu

        # Adaug punctul la vectorul de pasi
        x_puncte_grafic.append(x_k)
        reziduu = b - A @ x_k

    # Afisez numarul de iteratii
    print("Rezultatele pentru exercitiul 1 cu metoda pasului descendent sunt: ")
    print(f"Numarul de iteratii este {iteratii}")
    print(f"Punctul de minim este {x_k}")
    # Returnez punctul de minim si vectorul cu valorile de la fiecare iteratie
    return [x_k, x_puncte_grafic]

# ----------------------- METODA GRADIENTILOR CONJUGATI ---------------------------
def gradient_conjugat(A, b):
    # Aleg punctul initial
    x_k = np.array([[-10], [1]]).astype(float)
    # Adaug punctul initial la vectorul de pasi
    x_puncte_grafic = [x_k]

    # Calculez reziduu
    reziduu = b - A @ x_k
    # Directia se alege astfel incat sa fie egala cu solutia sistemului Ax = b (adica reziduul in prima faza)
    directie = reziduu
    norma = lambda x: np.linalg.norm(x, ord = 2)
    iteratii = 0
    eps = 1e-8

    # Cat timp n-am ajuns la solutie continuam sa calculam
    while norma(reziduu) > eps:

        # Marim numarul de iteratii
        iteratii += 1
        learning_rate = (directie.T @ reziduu) / (directie.T @ A @ directie)
        # La fiecare iteratie se merge ortogonal cu directiile precedente => numarul de iteratii scade considerabil astfel(doar 2 pasi)
        x_k = x_k + learning_rate * directie
        next_reziduu = reziduu - learning_rate * A @ directie
        direction_rate = (next_reziduu.T @ next_reziduu) / (reziduu.T @ reziduu)
        directie = next_reziduu + direction_rate * directie

        reziduu = next_reziduu
        x_puncte_grafic.append(x_k)

    print("Rezultatele pentru exercitiul 1 cu metoda gradientilor conjugati sunt: ")
    print(f"Numarul de iteratii este {iteratii}")
    print(f"Punctul de minim este {x_k}")
    return [x_k, x_puncte_grafic]

# --------------- END EXERCITIUL 1 -----------------------------

# --------------- EXERCITIUL 2 ---------------------------------
# Functia pentru care vrem sa calculam aproximarea
def f2(x):
    return (-1) * math.sin((-4) * x) - 5 * math.cos(4 * x) - 23.55 * x

def noduri_chebyshev(k, mrg_inf, mrg_sup, N):
    # Se folosesc nodurile Chebysev pentru a se imbunatati din punct de vedere numeric eroarea de trunchiere(pentru a evita erorile mari in apropierea marginilor)
    return (mrg_inf + mrg_sup) / 2 + (mrg_sup - mrg_inf) / 2 * np.cos(np.pi * (N - k) / N)

# Functie ce construieste polinomul cu ajutorul coeficientilor aflati din rezolvarea sistemului
def evaluare(x, C, N, X):
    s = C[0]
    for i in range(1, N + 1):
        produs = C[i]
        for j in range(i):
            produs = produs * (X - x[j])
        s = s + produs

    return s

def exercitiul_doi():
    # Marginile inferioare si superioare([-pi, pi])
    a = - np.pi
    b = np.pi
    # Cat timp nu se indeplineste conditia ca eroarea maxima de trunchiere sa fie mai mica decat o valoare data(1e-5) continuam sa crestem N-ul
    # Cand conditia va fi satisfacuta => bucla se va opri si astfel va fi ales cel mai mic N
    N = 1
    while True:
        N = N + 1
        # Afisez N-urile pentru care nu se respecta conditia
        print(f"Pentru N = {N} nu se respecta conditia pentru eroarea de trunchiere")
        ret, coeficienti, x, erori, maxim, vals = interpolare_metoda_newton(N, a, b)
        if ret != -1:
            print(f"N-ul pentru care se respecta conditia cu eroarea de trunchiere:{N}")
            # Plotez graficul
            nr_puncte = 100
            x_grafic = np.linspace(a, b, nr_puncte)
            f3 = np.vectorize(f2)
            y_grafic = f3(x_grafic)

            y_aproximat = [evaluare(x,coeficienti,N,X) for X in x_grafic]

            # Afisez functia originala, nodurile de interpolare si polinomul
            plt.figure("Interpolare Lagrange: Metoda Newton")
            plt.plot(x_grafic, y_grafic, label = "Functia")
            plt.plot(x_grafic, y_aproximat, linestyle = "-.", label = "Polinom de interpolare")

            # Afisam pe grafic nodurile de interpolare
            plt.scatter(x, f3(x), label = "Nodurile de interpolare")
            plt.legend()
            plt.show()

            # Grafic cu eroarea de trunchiere
            plt.figure("Eroare interpolare cu polinoame Lagrange: metoda Newton")
            plt.plot(vals, erori, label = "Erori obtinute")
            plt.hlines(1e-5, xmin = a, xmax = b, color = 'blue')
            plt.hlines(maxim, xmin = a, xmax = b, color = 'orange', label = "Eroare maxima din algoritmul meu")
            plt.legend()
            plt.show()

            return

def interpolare_metoda_newton(N, mrg_inf, mrg_sup):

    # Determin intervalele folosindu-ma de nodurile Chebysev pentru a putea minimiza eroarea de trunchiere
    x = np.array([noduri_chebyshev(i, mrg_inf, mrg_sup, N) for i in range(N + 1)])

    # y = f(x)
    y = np.zeros((N + 1, 1))
    for i in range(len(x)):
        y[i] = f2(x[i])

    # Coeficientii se afla dintr-un sistem ce are deasupra diagonalei principale 0 si sub diagonala principala cate un produs de diferente
    # construim matricea A
    A = np.zeros((N + 1, N + 1))
    # Pe prima coloana sunt doar valori de 1
    A[:,0] = 1
    for i in range(1, N + 1):
        produs = 1
        for j in range(i):
            produs = produs * (x[i] - x[j])
            A[i][j + 1] = produs

    # Aflu coeficientii cu metoda substitutiei ascendente
    coeficienti = sub_ascendenta(A, y)

    nr_puncte = 100
    x_grafic = np.linspace(mrg_inf, mrg_sup, nr_puncte)
    f3 = np.vectorize(f2)
    y_grafic = f3(x_grafic)
    y_aproximat = [evaluare(x,coeficienti,N,val) for val in x_grafic]

    erori, er_max = eroare_trunchiere(y_grafic, y_aproximat)
    if er_max <= 1e-5:
        return N, coeficienti, x, erori, er_max, x_grafic

    return -1, None, None, None, None, None

def eroare_trunchiere(y, y_aproximat):
    eroare = np.abs(y - y_aproximat)
    maxim = np.max(eroare)

    return eroare, maxim

# ---------------- END EXERCITIUL 2 ----------------------------

# ----------------- EXERCITIUL 3 -------------------------------

def exercitiul_trei():
    # Marginea inferioara
    a = (-1) * math.pi
    # Marginea superioara
    b = math.pi
    int_spline_cubica(a, b)

# Functia care trebuie aproximata
def f3(x):
    return 3 * math.sin((-2) * x) - 4 * math.cos(4 * x) - 0.31 * x

# Derivata acestei functii
def df3(x):
    return (-6) * math.cos(2 * x) + 16 * math.sin(4 * x) - 0.31

def int_spline_cubica(mrg_inf, mrg_sup):

    # Numarul de intervale
    N = 144
    # Am ales N-ul 144 dupa o verificare intr-un while la fiecare pas, l-am sters deoarece dura prea mult sa se ajunga la acest rezultat

    # Diviziune a intervalului [mrg_inf, mrg_sup] ([-pi, pi])
    x = np.zeros((N+1, 1))
    x = np.linspace(mrg_inf, mrg_sup, N + 1)
    y = np.zeros((N + 1, 1))
    for i in range(len(x)):
        y[i] = f3(x[i])

    # Calculam coeficientii
    # A - ul
    # a = f(xj) (a = y)
    a = y.copy()

    # b - ul
    # Mai intai se formeaza o matrice
    '''
    Matricea b este de forma = (1 0 0 0 .......
                                1 4 1 0 0 .....
                                0 1 4 1 0 0 ...
                                ...............
                                ...............
                                0 0 0 0 0 0 0 1)
    '''
    B = np.zeros((N+1, N+1))

    # Prima valoare din matrice este 1
    B[0][0] = 1
    # Construim urmatoarele linii (cu exceptia ultimei valori din matrice) dupa urmatorul tipar
    # La fiecare pas se shifteaza spre dreapta valorile 1 4 1
    for i in range(1, N):
        B[i][i - 1] = 1
        B[i][i] = 4
        B[i][i + 1] = 1

    # Ultima valoare din matrice este 1
    B[N][N] = 1

    # Folosesc o discretizare echidistanta, h-ul este mereu acelasi(deoarece si intervalele sunt echidistante)
    h = x[1] - x[0]

    # Trebuie sa rezolvam sistemul
    # Calculez valorile din matricea W(rezultate din formulele de recurenta)
    W = np.zeros((N + 1, 1))
    W[0] = df3(x[0])
    for i in range(1, N):
        W[i] = 3 * (y[i + 1] - y[i - 1]) / h
    W[N] = df3(x[N])

    # Determin b-ul cu ajutorul factorizarii LU(Gauss cu pivotare partiala)
    b = factorizare_pivotare_partiala(B, W)

    # Calculam c si d(cu ajutorul lui b calculat anterior)
    c = np.zeros((N, 1))
    d = np.zeros((N, 1))
    for i in range(N):
        c[i] = 3 * (y[i + 1] - y[i]) / (h * h) - (b[i + 1] + 2 * b[i]) / h
        d[i] = (-2) * (y[i + 1] - y[i]) / (h * h * h) + (b[i + 1] + b[i]) / (h * h)

    # Construiesc polinomul cu valorile coeficietilor a, b, c si d
    def polinom(j):
        def spline(X):
            return a[j] + b[j] * (X - x[j]) + c[j] * (X - x[j]) ** 2 + d[j] * (X - x[j]) ** 3
        return spline

    # ---------- GRAFICUL --------
    # Calculez functia in nr_puncte(=100)
    nr_puncte = 100
    f4 = np.vectorize(f3)
    x_grafic = np.linspace(mrg_inf, mrg_sup, nr_puncte)
    y_grafic = f4(x_grafic)

    # Functie definita pe intervale(care indeplinesc o anumita conditie)

    y_aproximat = np.piecewise(
    x_grafic,
    [
        # conditii
        (x[i] <= x_grafic) & (x_grafic < x[i + 1])
        for i in range(N - 1)
    ],
    [
        # polinoamele
        polinom(i)
        for i in range(N)
    ]
    )

    # Plotez graficul cu punctele de interpolare
    plt.figure("Interpolare spline cubica")
    plt.plot(x_grafic, y_grafic, linestyle='--', label="Functia")
    plt.plot(x_grafic, y_aproximat, label="Interpolarea spline cubica")
    plt.scatter(x, y, label='Nodurile de interpolare')
    plt.legend()
    plt.show()

    # Calculez eroarea de trunchiere
    plot_eroare_trunchiere_ex_3(x_grafic, y_grafic, y_aproximat, mrg_inf, mrg_sup)

# ----------- Metoda pentru afisarea erorii de trunchiere
def plot_eroare_trunchiere_ex_3(x_grafic, y_grafic, y_aprox, mrg_inf, mrg_sup):

    eroare = np.abs(y_grafic - y_aprox)
    # determinam maximul erorii dintre cele calculate
    er_max = np.max(eroare)

    plt.figure("Eroarea de trunchiere")
    plt.plot(x_grafic, eroare)
    # afisez pe grafic valoarea 1e-5
    plt.hlines(1e-5, xmin = mrg_inf, xmax=mrg_sup, color="blue")
    # afisez pe grafic cea mai mare eroare pe care o am eu
    plt.hlines(er_max, label="Eroarea maxima din algoritmul meu", xmin = mrg_inf, xmax=mrg_sup, color="orange")
    plt.legend()
    plt.show()

# Factorizare LU
def factorizare_pivotare_partiala(U, b):

    # verific daca sistemul are solutie unica
    if abs(np.linalg.det(U)) > 1e-15:
        n = U.shape[0] #dimensiunea matricei
        index = np.arange(0, n) #vector pentru indecsii solutiilor
        L = np.zeros((n, n)) # initializam toata matricea L cu zero
        # aplic algoritmul de pivotare partiala pe matricea U
        for k in range(0, n-1):

            p = np.argmax(abs(U[k:,k])) + k
            if U[p][k] == 0:
                return "Matricea nu admite factorizare LU"

            if p != k:
                # daca indicele pivotului nu corespunde cu cel curent => trebuie sa interschimbam liniile si in U si subliniile(elementele de sub diagonala principala) din L
                U[[k, p]] = U[[p, k]]
                aux = np.array(L[p,:k])
                L[p,:k] = np.array(L[k,:k])
                L[k,:k] = np.array(aux)
                # deoarece am interschimbat doua coloane => trebuie sa schimbam si ordinea necunoscutelor sistemului cu ajutorul vectorului index
                index[p], index[k] = index[k], index[p]

            for l in range(k+1, n):
                # matricea L contine raportul dintre elementul de pe linia curenta si pivot
                L[l][k] = U[l][k] / U[k][k]
                U[l] = U[l] - L[l][k] * U[k]

        if U[n-1][n-1] == 0:
            return "Matricea nu admite factorizare LU"

        size_b = b.shape[0] # dimensiunea vectorului b(numarul de linii)
        b_copy = np.copy(b) # copie a vectorului b

        # interschimb elementele vectorului coloana b conform permutarii indecsilor din vectorul index(folosindu-ma de vectorul copie al lui b)
        for i in range(size_b):
            b[i] = b_copy[index[i]]

        # adun la matricea L matricea identitate pentru a avea pe diagonala principala 1
        # aceasta este o matrice inferior triunghiulara
        L = L + np.identity(n)

        # il scriem pe A = LU
        # LUx = b <=> il notam pe Ux cu un y si rezolvam sistemul Ly = b => Ux = y si aflam solutia sistemului
        sol_aux = np.zeros((n, 1))

        if isinstance(sub_ascendenta(L, b), int):
            return "Matricea nu admite factorizare LU"
        else:
            sol_aux = sub_ascendenta(L, b)
            return sub_descendenta(U, sol_aux)
    else:
        return "Sistemul nu admite solutie unica."

def sub_ascendenta(U, b):

    # Algoritm pentru metoda substitutiei ascendente(elementele de deasupra diagonalei principale sunt egale cu 0)
    # dimensiunea matricei asociate sistemului(este patratica)
    n = U.shape[0]
    # initializam x(vectorul solutie) cu zero
    x = np.zeros(n)
    # daca determinantul este egal cu 0(aproximarea sa) => sistemul nu are solutie unica
    # altfel  => are solutie unica(este compatibil determinat)
    # punem conditie ca acesta sa fie mai mare decat o aproximare a lui 0 data de noi(in modul)
    if abs(np.linalg.det(U)) > 1e-15:
        # merg de la prima ecuatie catre ultima
        for i in range(0, n):
            suma = 0
            for j in range(i+1):
                # calculez suma produselor din fiecare ecuatie, exceptand elementul ce trebuie aflat
                suma = suma + U[i][j] * x[j]
            suma = (b[i] - suma) / U[i][i]
            x[i] = suma
        return x
    else:
        # returnez -1 daca determinantul este egal cu 0
        return -1

def sub_descendenta(U, b):
    # Algoritm pentru metoda substitutiei ascendente(elementele de sub diagonala principala sunt egale cu 0)
    # dimensiunea matricei asociate sistemului(este patratica)
    n = U.shape[0]
    x = np.zeros((n, 1))
    if abs(np.linalg.det(U)) > 1e-15:
        # parcurgem ecuatiile de la ultima(ce are doar o necunoscuta) spre prima
        for i in range(n-1, -1, -1):
            suma = 0
            for j in range(i+1, n):
                # calculez suma produselor elementelor aflate pana la ecuatia data
                suma = suma + U[i][j] * x[j]
            suma = (b[i] - suma) / U[i][i]
            x[i] = suma

        return x
    else:
        # returnez -1 daca sistemul nu are solutie unica
        return -1

# ----------------- END EXERCITIUL 3

# ------------------ APELURILE ------------------------
if __name__ == "__main__":

    # --------------------- EXERCITIUL 1 ----------------
    print("---------------- EXERCITIUL 1 ---------------------")
    exercitiul_unu()

    # --------------------- EXERCITIUL 2 ---------------
    print("--------------- EXERCITIUL 2 -----------------------")
    exercitiul_doi()

    # ---------------------- EXERCITIUL 3 ----------------
    print("--------------- EXERCITIUL 3 ------------------------")
    exercitiul_trei()


import tkinter as tk
import random
import threading
import time

class Dashboard:
    def __init__(self, root):
        self.root = root
        self.root.title("Dashboard")
        self.root.geometry("500x400")

        # create the text boxes
        self.textboxes = []
        colors = [
            "light steel blue",
            "misty rose",
            "seashell4",
            "lightsalmon2",
            "light goldenrod",
            "lavender",
        ]
        for i in range(6):
            textbox = tk.Label(
                self.root,
                text="0",
                font=("Arial", 24),
                bg=colors[i],
                width=10,
                height=5,
            )
            textbox.grid(row=(i // 3), column=(i % 3), padx=10, pady=10)
            self.textboxes.append(textbox)

        # create the threads for updating the text boxes
        self.threads = []
        self.threads.append(
            threading.Thread(target=self.update_textbox, args=(0, 10, 20, 1))
        )
        self.threads.append(
            threading.Thread(target=self.update_textbox, args=(1, -10, 10, 2))
        )
        self.threads.append(
            threading.Thread(target=self.update_textbox, args=(2, -100, 0, 5))
        )
        self.threads.append(
            threading.Thread(target=self.update_textbox, args=(3, 0, 20, 3))
        )
        self.threads.append(
            threading.Thread(target=self.update_textbox, args=(4, -40, 40, 6))
        )
        self.threads.append(
            threading.Thread(target=self.update_textbox, args=(5, 100, 200, 4))
        )

        # start the threads
        for thread in self.threads:
            thread.start()

    def update_textbox(self, index, min, max, increment):
        while True:
            # generate a random number in the specified range
            number = random.randint(min, max)

            # update the text box
            self.textboxes[index].config(text=str(number))

            # sleep for the specified time
            time.sleep(increment)

root = tk.Tk()
dashboard = Dashboard(root)
root.mainloop()


'''
    date: 2021/4/4 17:03
    this method take integrated disease similarity circRNA_4_mer_gip feature into GAE, respectively.
'''
import pandas as pd
import numpy as np
import os

class Feature_loader(object):
    def __init__(self, rna_file, disease_file):
        self.seq_df = pd.DataFrame(self.load_RNA_fea(rna_file)).transpose()
        self.dis_df = pd.DataFrame(self.load_disease_fea(disease_file)).transpose()
    def load_RNA_fea(self, file):
        '''
        加载circRNA的特征并存入字典中
        :param file: rna嵌入节点特征
        :return:
        '''
        dic={}
        with open(file, 'r') as f:
            for line in f:
                if ":" in line:
                    sample = line.split(":")
                    name = sample[0]
                    fea = [ eval(i) for i in sample[1].split(' ')]
                    dic[name] = fea
        return dic
    def load_disease_fea(self, file):
        return self.load_RNA_fea(file)
    def clear(self, file):
        '''
        清理原始的特征列
        :param file:
        :return:
        '''
        df = pd.read_csv(file)
        df = df[['label','Disease Name', 'circBase ID']]
        df.to_csv(file)
        return
    def fea_match(self, file):
        '''
        将样本特征匹配过去
        :param file:
        :return:
        '''
        df = pd.read_csv(file, index_col=0)
        self.dis_df.index.name='Disease Name'
        self.seq_df.index.name='circBase ID'
        df = df.merge(self.dis_df,how='left',left_on='Disease Name',right_on='Disease Name')
        df = df.merge(self.seq_df,how='left',left_on='circBase ID',right_on='circBase ID')
        df.to_csv(file)
if __name__ == '__main__':
    circRNA_fea_file = r"./cirRna_GAE_node_emb_ep5000_split.txt"
    disease_fea_file = r"./disease_GAE_node_emb_ep2000_split.txt"
    feaLoader = Feature_loader(circRNA_fea_file, disease_fea_file)
    for i in [1, 2, 3, 'random']:
        # feaLoader.clear(r"./method{}_sample_picked.csv".format(i))
        feaLoader.fea_match(r"./method{}_sample_picked.csv".format(i))


from concurrent.futures import ThreadPoolExecutor
from threading import Lock

class JobWorker:
    def __init__(self):
        self.task_set = set()
        self.lock = Lock()
        self.executor = ThreadPoolExecutor(max_workers=4)

    def submit_job(self, id, func, *args):
        self.lock.acquire()
        if id in self.task_set:
            self.lock.release()
            return
        self.task_set.add(id)
        self.lock.release()

        self.executor.submit(func, *args)


import numpy as np
from scipy.optimize import linear_sum_assignment

from ...utils._param_validation import StrOptions, validate_params
from ...utils.validation import check_array, check_consistent_length

__all__ = ["consensus_score"]

def _check_rows_and_columns(a, b):
    """Unpacks the row and column arrays and checks their shape."""
    check_consistent_length(*a)
    check_consistent_length(*b)
    checks = lambda x: check_array(x, ensure_2d=False)
    a_rows, a_cols = map(checks, a)
    b_rows, b_cols = map(checks, b)
    return a_rows, a_cols, b_rows, b_cols

def _jaccard(a_rows, a_cols, b_rows, b_cols):
    """Jaccard coefficient on the elements of the two biclusters."""
    intersection = (a_rows * b_rows).sum() * (a_cols * b_cols).sum()

    a_size = a_rows.sum() * a_cols.sum()
    b_size = b_rows.sum() * b_cols.sum()

    return intersection / (a_size + b_size - intersection)

def _pairwise_similarity(a, b, similarity):
    """Computes pairwise similarity matrix.

    result[i, j] is the Jaccard coefficient of a's bicluster i and b's
    bicluster j.

    """
    a_rows, a_cols, b_rows, b_cols = _check_rows_and_columns(a, b)
    n_a = a_rows.shape[0]
    n_b = b_rows.shape[0]
    result = np.array(
        [
            [similarity(a_rows[i], a_cols[i], b_rows[j], b_cols[j]) for j in range(n_b)]
            for i in range(n_a)
        ]
    )
    return result

@validate_params(
    {
        "a": [tuple],
        "b": [tuple],
        "similarity": [callable, StrOptions({"jaccard"})],
    },
    prefer_skip_nested_validation=True,
)
def consensus_score(a, b, *, similarity="jaccard"):
    """The similarity of two sets of biclusters.

    Similarity between individual biclusters is computed. Then the
    best matching between sets is found using the Hungarian algorithm.
    The final score is the sum of similarities divided by the size of
    the larger set.

    Read more in the :ref:`User Guide <biclustering>`.

    Parameters
    ----------
    a : tuple (rows, columns)
        Tuple of row and column indicators for a set of biclusters.

    b : tuple (rows, columns)
        Another set of biclusters like ``a``.

    similarity : 'jaccard' or callable, default='jaccard'
        May be the string "jaccard" to use the Jaccard coefficient, or
        any function that takes four arguments, each of which is a 1d
        indicator vector: (a_rows, a_columns, b_rows, b_columns).

    Returns
    -------
    consensus_score : float
       Consensus score, a non-negative value, sum of similarities
       divided by size of larger set.

    References
    ----------

    * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis
      for bicluster acquisition
      <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2881408/>`__.
    """
    if similarity == "jaccard":
        similarity = _jaccard
    matrix = _pairwise_similarity(a, b, similarity)
    row_indices, col_indices = linear_sum_assignment(1.0 - matrix)
    n_a = len(a[0])
    n_b = len(b[0])
    return matrix[row_indices, col_indices].sum() / max(n_a, n_b)


from flask import Blueprint, request
from op import image_op as io
image=Blueprint("image",__name__)

'''
根据图片获取字符串
'''
@image.route('/image_translation',methods=['POST'])
def image_translation():
    image = request.form.get('image')
    name = request.form.get('name')
    print(name)
    if not (image and name):
        return 'no data'
    return io.image_translation_op(name,image)


from pyray import *
import numpy as np

from .anim import Anim

def draw_anim(root: Vector3, anim: Anim, frame: int):
    gpos = anim.global_positions + np.asarray([root.x, root.y, root.z])
    parents = anim.skeleton.parents

    nframes = gpos.shape[0]
    nbones = gpos.shape[1]

    frame = int(clamp(frame, 0, nframes - 1))

    for j in range(nbones):
        pos = Vector3(gpos[frame, j, 0], gpos[frame, j, 1], gpos[frame, j, 2])
        draw_sphere(pos, 0.01, BLACK)

    for j in range(nbones):
        if parents[j] < 0:
            continue
        pos = Vector3(gpos[frame, j, 0], gpos[frame, j, 1], gpos[frame, j, 2])
        parent_pos = Vector3(gpos[frame, parents[j], 0], gpos[frame, parents[j], 1], gpos[frame, parents[j], 2])
        draw_line_3d(parent_pos, pos, BLACK)


from sys import stdin
n, m = map(int, stdin.readline().split())
bm = 1
idx = 1
bj = 1
'''
100 99 98 97 96 95 94
100-6=95
'''
for i in range(n, n-m, -1):
    bm *= i
    bj *= idx
    idx += 1

print(int(bm//bj))


def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])
    return parent[x]

def union(a, b):
    a = find(a)
    b = find(b)

    if a < b:
        parent[b] = a
    else:
        parent[a] = b

N, M = map(int, input().split())
edges = sorted([tuple(map(int, input().split())) for _ in range(M + 1)], key=lambda x: -x[2])
parent = [i for i in range(N + 1)]
max_total, min_total = 0, 0

for a, b, cost in edges:
    if find(a) == find(b):
        continue
    union(a, b)
    min_total += 1 if cost == 0 else 0

edges.sort(key=lambda x: x[2])
parent = [i for i in range(N + 1)]
for a, b, cost in edges:
    if find(a) == find(b):
        continue
    union(a, b)
    max_total += 1 if cost == 0 else 0

print(max_total ** 2 - min_total ** 2)

백준/Gold/13418. 학교 탐방하기/학교 탐방하기.py


# def find_longesr_reversiable_string(a):

#     result=a[0]
#     result_max=""
#     for current_position in range(len(a)):
#        mid_point=current_position+1
#        repeat_time=1
#        edge=0
#        print("loop",current_position)
#        while True:
#          if mid_point+1>len(a)-1:
#                 print ("early break mid point:",mid_point)
#                 print ("break early")
#                 break
#          else:
#              if a[mid_point]==a[mid_point+1]:
#                  result=a[mid_point-repeat_time:mid_point+1+1]
#                  mid_point+=1
#                  repeat_time+=1
#              elif a[mid_point-repeat_time-edge]==a[mid_point+edge+1]:
#                  print ("repeat_time",repeat_time)
#                  print ("mid_point",mid_point)
#                  print ("edge",edge)
#                  result=a[mid_point-repeat_time-edge:mid_point+edge+1+1]
#                  edge+=1
#                  print ("result",result)
#                  if mid_point+edge==len(a)-1:
#                      break
#              if len(result)>len(result_max):
#                  result_max=result
#        if mid_point+1==len(a)-1:
#               break
#     return result_max
### use two function to solve the problem, above code only uses one function, which is too complicated
def longest_palindrome(s: str) -> str:
    if not s:
        return ""

    start = 0
    end = 0
    for i in range(len(s)):
        len1 = expand_around_center(s, i, i)           # odd
        len2 = expand_around_center(s, i, i + 1)       # even
        max_len = max(len1, len2)

        if max_len > (end - start):
            start = i - (max_len - 1) // 2
            end = i + max_len // 2

    return s[start:end+1]

def expand_around_center(s: str, left: int, right: int) -> int:
    while left >= 0 and right < len(s) and s[left] == s[right]:
        left -= 1
        right += 1
    return right - left - 1

a = "aaba"
print(longest_palindrome(a))


from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, uic, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from braphy.gui.widgets.binary_plot_settings_widget import BinaryPlotSettingsWidget
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT
import numpy as np

class NavigationToolbar(NavigationToolbar2QT):
    def edit_parameters(self):
        super(NavigationToolbar, self).edit_parameters()
        self.callback_function()

    def set_callback_function(self, callback_function):
        self.callback_function = callback_function

class BinaryPlotVisualizer(FigureCanvas):
    def __init__(self, parent = None, width = 8, height = 6, dpi = 100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        fig.subplots_adjust(bottom = 0.15)
        self.ax = fig.add_subplot(111)
        self.ax.set_ylabel('Value')
        self.ax.set_title(' ')
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        self.binary_plot_settings_widget = BinaryPlotSettingsWidget(parent = self, update_function = self.update_visualization)
        self.binary_plot_settings_widget.raise_()
        self.binary_plot_settings_widget.show()
        self.plots = {}
        self.confidence_intervals = {}
        self.action_legend = None

        self.toolbar = NavigationToolbar(self, self)
        self.toolbar.set_callback_function(self.settings_callback)
        self.toolbar.hide()

    def settings_callback(self):
        self.show_legend(self.ax.get_legend())
        self.draw()

    def set_legend_action(self, action):
        self.action_legend = action

    def add_plot(self, info_string, values, confidence_interval = None):
        settings = self.binary_plot_settings_widget.get_plot_settings()

        values = values[np.argsort(values[:,0])]

        if confidence_interval is not None:
            CI = self.ax.fill_between(values[:, 0], confidence_interval[0], confidence_interval[1],
                                      facecolor = settings['ci_color'],
                                      alpha = settings['ci_alpha'])
            self.confidence_intervals[info_string] = CI
        plot = self.ax.plot(values[:, 0], values[:, 1], color = settings['line_color'],
                            linestyle = settings['line_style'], marker = settings['marker_style'],
                            markerfacecolor = settings['marker_color'], linewidth = settings['line_width'],
                            markersize = settings['marker_size'], label = info_string)
        self.plots[info_string] = plot
        self.ax.tick_params(top = False, bottom = True, labeltop = False, labelbottom = True)
        plt.setp(self.ax.get_xticklabels(), fontsize = 7)
        plt.setp(self.ax.get_yticklabels(), fontsize = 7)
        self.ax.relim()
        self.ax.autoscale_view()
        self.show_legend(self.ax.get_legend())
        self.draw()

    def remove_plot(self, info_string):
        self.plots[info_string][0].remove()
        del self.plots[info_string]
        if info_string in self.confidence_intervals.keys():
            self.confidence_intervals[info_string].remove()
            del self.confidence_intervals[info_string]
        self.ax.relim()
        self.ax.autoscale_view()
        self.show_legend(self.ax.get_legend())
        self.draw()

    def resizeEvent(self, event):
        try:
            super().resizeEvent(event)
        except:
            pass
        self.binary_plot_settings_widget.update_move()

    def update_visualization(self):
        settings = self.binary_plot_settings_widget.get_plot_settings()
        for plot in self.plots.values():
            plot[0].set_color(settings['line_color'])
            plot[0].set_linestyle(settings['line_style'])
            plot[0].set_marker(settings['marker_style'])
            plot[0].set_markerfacecolor(settings['marker_color'])
            plot[0].set_markersize(settings['marker_size'])
            plot[0].set_linewidth(settings['line_width'])
        for ci in self.confidence_intervals.values():
            ci.set_facecolor(settings['ci_color'])
            ci.set_alpha(settings['ci_alpha'])
        self.show_legend(self.ax.get_legend())
        self.draw()

    def clear_plot(self):
        for plot in self.plots.values():
            plot[0].remove()
        for confidence_interval in self.confidence_intervals.values():
            confidence_interval.remove()
        self.plots = {}
        self.confidence_intervals = {}
        self.show_legend(False)
        self.draw()

    def show_legend(self, show):
        if show:
            self.ax.legend()
            self.check_legend_action()
        else:
            legend = self.ax.get_legend()
            if legend:
                legend.remove()
        self.draw()

    def check_legend_action(self):
        if self.action_legend is not None:
            self.action_legend.blockSignals(True)
            self.action_legend.setChecked(True)
            self.action_legend.blockSignals(False)

    def set_x_label(self, label):
        self.ax.set_xlabel(label)

    def get_actions(self):
        actions = self.toolbar.actions()
        return actions


from __future__ import print_function

import sys
from TestCase import TestCase

def main():
    '''This program runs SU2 and ensures that the output matches specified values.
       This will be used to do checks when code is pushed to github
       to make sure nothing is broken. '''

    test_list = []

    ######################################
    ### RUN TUTORIAL CASES             ###
    ######################################

    ### Compressible Flow

    # Inviscid Bump
    tutorial_inv_bump            = TestCase('inviscid_bump_tutorial')
    tutorial_inv_bump.cfg_dir    = "../Tutorials/compressible_flow/Inviscid_Bump"
    tutorial_inv_bump.cfg_file   = "inv_channel.cfg"
    tutorial_inv_bump.test_iter  = 0
    tutorial_inv_bump.test_vals  = [-1.437425, 4.075857, 0.003000, 0.012720] #last 4 columns
    tutorial_inv_bump.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_inv_bump.timeout    = 1600
    tutorial_inv_bump.tol        = 0.00001
    tutorial_inv_bump.no_restart = True
    test_list.append(tutorial_inv_bump)

    # Inviscid Wedge
    tutorial_inv_wedge            = TestCase('inviscid_wedge_tutorial')
    tutorial_inv_wedge.cfg_dir    = "../Tutorials/compressible_flow/Inviscid_Wedge"
    tutorial_inv_wedge.cfg_file   = "inv_wedge_HLLC.cfg"
    tutorial_inv_wedge.test_iter  = 0
    tutorial_inv_wedge.test_vals  = [-0.481460, 5.253008, -0.292159, 0.052922] #last 4 columns
    tutorial_inv_wedge.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_inv_wedge.timeout    = 1600
    tutorial_inv_wedge.tol        = 0.00001
    tutorial_inv_wedge.no_restart = True
    test_list.append(tutorial_inv_wedge)

    # Inviscid ONERA M6
    tutorial_inv_onera            = TestCase('inviscid_onera_tutorial')
    tutorial_inv_onera.cfg_dir    = "../Tutorials/compressible_flow/Inviscid_ONERAM6"
    tutorial_inv_onera.cfg_file   = "inv_ONERAM6.cfg"
    tutorial_inv_onera.test_iter  = 0
    tutorial_inv_onera.test_vals  = [-5.204928, -4.597762, 0.247124, 0.085734] #last 4 columns
    tutorial_inv_onera.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_inv_onera.timeout    = 1600
    tutorial_inv_onera.tol        = 0.00001
    tutorial_inv_onera.no_restart = True
    test_list.append(tutorial_inv_onera)

    # Laminar Cylinder
    tutorial_lam_cylinder            = TestCase('laminar_cylinder_tutorial')
    tutorial_lam_cylinder.cfg_dir    = "../Tutorials/compressible_flow/Laminar_Cylinder"
    tutorial_lam_cylinder.cfg_file   = "lam_cylinder.cfg"
    tutorial_lam_cylinder.test_iter  = 0
    tutorial_lam_cylinder.test_vals  = [-6.162141, -0.699617, 0.186570, 69.267308] #last 4 columns
    tutorial_lam_cylinder.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_lam_cylinder.timeout    = 1600
    tutorial_lam_cylinder.tol        = 0.00001
    tutorial_lam_cylinder.no_restart = True
    test_list.append(tutorial_lam_cylinder)

    # Laminar Flat Plate
    tutorial_lam_flatplate            = TestCase('laminar_flatplate_tutorial')
    tutorial_lam_flatplate.cfg_dir    = "../Tutorials/compressible_flow/Laminar_Flat_Plate"
    tutorial_lam_flatplate.cfg_file   = "lam_flatplate.cfg"
    tutorial_lam_flatplate.test_iter  = 0
    tutorial_lam_flatplate.test_vals  = [-2.821818, 2.657591, -0.400044, 0.029413] #last 4 columns
    tutorial_lam_flatplate.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_lam_flatplate.timeout    = 1600
    tutorial_lam_flatplate.tol        = 0.00001
    tutorial_lam_flatplate.no_restart = True
    test_list.append(tutorial_lam_flatplate)

    # Turbulent Flat Plate
    tutorial_turb_flatplate            = TestCase('turbulent_flatplate_tutorial')
    tutorial_turb_flatplate.cfg_dir    = "../Tutorials/compressible_flow/Turbulent_Flat_Plate"
    tutorial_turb_flatplate.cfg_file   = "turb_SA_flatplate.cfg"
    tutorial_turb_flatplate.test_iter  = 0
    tutorial_turb_flatplate.test_vals  = [-2.258584, -4.899502, -0.429387, 0.201236] #last 4 columns
    tutorial_turb_flatplate.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_turb_flatplate.timeout    = 1600
    tutorial_turb_flatplate.tol        = 0.00001
    tutorial_turb_flatplate.no_restart = True
    test_list.append(tutorial_turb_flatplate)

    # Transitional FlatPlate
    tutorial_trans_flatplate            = TestCase('transitional_flatplate_tutorial')
    tutorial_trans_flatplate.cfg_dir    = "../Tutorials/compressible_flow/Transitional_Flat_Plate"
    tutorial_trans_flatplate.cfg_file   = "transitional_BC_model_ConfigFile.cfg"
    tutorial_trans_flatplate.test_iter  = 0
    tutorial_trans_flatplate.test_vals  = [-22.021786, -15.330906, 0.000000, 0.023952] #last 4 columns
    tutorial_trans_flatplate.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_trans_flatplate.timeout    = 1600
    tutorial_trans_flatplate.tol        = 0.00001
    tutorial_trans_flatplate.no_restart = True
    test_list.append(tutorial_trans_flatplate)

    # Turbulent ONERA M6
    tutorial_turb_oneram6            = TestCase('turbulent_oneram6_tutorial')
    tutorial_turb_oneram6.cfg_dir    = "../Tutorials/compressible_flow/Turbulent_ONERAM6"
    tutorial_turb_oneram6.cfg_file   = "turb_ONERAM6.cfg"
    tutorial_turb_oneram6.test_iter  = 0
    tutorial_turb_oneram6.test_vals  = [-4.564441, -11.522435, 0.332640, 0.098274] #last 4 columns
    tutorial_turb_oneram6.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_turb_oneram6.timeout    = 1600
    tutorial_turb_oneram6.tol        = 0.00001
    test_list.append(tutorial_turb_oneram6)

    # NICD Nozzle
    tutorial_nicfd_nozzle           = TestCase('nicfd_nozzle')
    tutorial_nicfd_nozzle.cfg_dir   = "../Tutorials/compressible_flow/NICFD_nozzle"
    tutorial_nicfd_nozzle.cfg_file  = "NICFD_nozzle.cfg"
    tutorial_nicfd_nozzle.test_iter = 20
    tutorial_nicfd_nozzle.test_vals = [-1.909272, -6.407306, 4.284191, 0.000000, 0.000000]
    tutorial_nicfd_nozzle.su2_exec  = "mpirun -np 2 SU2_CFD"
    tutorial_nicfd_nozzle.timeout   = 1600
    tutorial_nicfd_nozzle.tol       = 0.00001
    tutorial_nicfd_nozzle.no_restart = True
    test_list.append(tutorial_nicfd_nozzle)

    # Unsteady NACA0012
    tutorial_unst_naca0012               = TestCase('unsteady_naca0012')
    tutorial_unst_naca0012.cfg_dir       = "../Tutorials/compressible_flow/Unsteady_NACA0012"
    tutorial_unst_naca0012.cfg_file      = "unsteady_naca0012.cfg"
    tutorial_unst_naca0012.test_iter     = 500
    tutorial_unst_naca0012.test_vals     = [500, 0, 0.302003, 0.665069, -5.300141, 0.000000,  0.0000e+00,  0.0000e+00]
    tutorial_unst_naca0012.su2_exec      = "mpirun -np 2 SU2_CFD"
    tutorial_unst_naca0012.timeout       = 1600
    tutorial_unst_naca0012.tol           = 0.00001
    tutorial_unst_naca0012.unsteady      = True
    test_list.append(tutorial_unst_naca0012)

    ### Design

    # Inviscid NACA 0012 Design
    tutorial_design_inv_naca0012            = TestCase('design_inv_naca0012')
    tutorial_design_inv_naca0012.cfg_dir    = "../Tutorials/design/Inviscid_2D_Unconstrained_NACA0012"
    tutorial_design_inv_naca0012.cfg_file   = "inv_NACA0012_basic.cfg"
    tutorial_design_inv_naca0012.test_iter  = 0
    tutorial_design_inv_naca0012.test_vals  = [-3.585391, -2.989014, 0.134515, 0.208523] #last 4 columns
    tutorial_design_inv_naca0012.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_design_inv_naca0012.timeout    = 1600
    tutorial_design_inv_naca0012.tol        = 0.00001
    tutorial_design_inv_naca0012.no_restart = True
    test_list.append(tutorial_design_inv_naca0012)

    # Turbulent RAE 2822 Design
    tutorial_design_turb_rae2822            = TestCase('design_turb_rae2822')
    tutorial_design_turb_rae2822.cfg_dir    = "../Tutorials/design/Turbulent_2D_Constrained_RAE2822"
    tutorial_design_turb_rae2822.cfg_file   = "turb_SA_RAE2822.cfg"
    tutorial_design_turb_rae2822.test_iter  = 0
    tutorial_design_turb_rae2822.test_vals  = [-1.700114, -4.941261, 0.218432, 0.190639] #last 4 columns
    tutorial_design_turb_rae2822.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_design_turb_rae2822.timeout    = 1600
    tutorial_design_turb_rae2822.tol        = 0.00001
    tutorial_design_turb_rae2822.no_restart = True
    test_list.append(tutorial_design_turb_rae2822)

    # Multi Objective Design
    tutorial_design_multiobj            = TestCase('design_multiobj')
    tutorial_design_multiobj.cfg_dir    = "../Tutorials/design/Multi_Objective_Shape_Design"
    tutorial_design_multiobj.cfg_file   = "inv_wedge_ROE_multiobj_combo.cfg"
    tutorial_design_multiobj.test_iter  = 0
    tutorial_design_multiobj.test_vals  = [2.657333, -3.020635, 324840.000000, 0.000000] #last 4 columns
    tutorial_design_multiobj.su2_exec   = "mpirun -np 2 SU2_CFD"
    tutorial_design_multiobj.timeout    = 1600
    tutorial_design_multiobj.tol        = 0.00001
    tutorial_design_multiobj.no_restart = True
    test_list.append(tutorial_design_multiobj)

    ######################################
    ### RUN TESTS                      ###
    ######################################

    pass_list = [ test.run_test() for test in test_list ]

    # Tests summary
    print('==================================================================')
    print('Summary of the parallel tests')
    print('python version:', sys.version)
    for i, test in enumerate(test_list):
        if (pass_list[i]):
            print('  passed - %s'%test.tag)
        else:
            print('* FAILED - %s'%test.tag)

    if all(pass_list):
        sys.exit(0)
    else:
        sys.exit(1)
    # done

if __name__ == '__main__':
    main()


from sklearn.mixture import GaussianMixture
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt

dataset = np.loadtxt("result1.txt", dtype=float)
dataset = dataset/1000
X = dataset.reshape(5,1000).T
kmeans = KMeans(2, random_state=0)
sse = {}

# for k in range(1, 10):
#     kmeans = KMeans(n_clusters=k, max_iter=1000).fit(X)
#     #X["clusters"] = kmeans.labels_
#     #print(data["clusters"])
#     sse[k] = kmeans.inertia_ # Inertia: Sum of distances of samples to their closest cluster center
# plt.figure()
# plt.plot(list(sse.keys()), list(sse.values()))
# plt.xlabel("Number of cluster")
# plt.ylabel("SSE")
# plt.show()

model = kmeans.fit(X)
labels = model.predict(X)

acc = model.score(X)
print(acc)
plt.scatter(X[:, 0], X[:, 1], c=labels)
plt.show()

# gmm = GaussianMixture(n_components=5,covariance_type='diag').fit(X)
# labels1 = gmm.predict(X)
# plt.scatter(X[:, 0], X[:, 1], c=labels1, s=40, cmap='viridis');
# plt.show()


#!/usr/bin/env python3

"""This python script populates a dictionary 'taxa_dic' derived from a list 'taxa', mapping order names to sets of taxa"""

taxa = [ ('Myotis lucifugus','Chiroptera'),
         ('Gerbillus henleyi','Rodentia',),
         ('Peromyscus crinitus', 'Rodentia'),
         ('Mus domesticus', 'Rodentia'),
         ('Cleithrionomys rutilus', 'Rodentia'),
         ('Microgale dobsoni', 'Afrosoricida'),
         ('Microgale talazaci', 'Afrosoricida'),
         ('Lyacon pictus', 'Carnivora'),
         ('Arctocephalus gazella', 'Carnivora'),
         ('Canis lupus', 'Carnivora'),
        ]

# Write a short python script to populate a dictionary called taxa_dic
# derived from  taxa so that it maps order names to sets of taxa.
# E.g. 'Chiroptera' : set(['Myotis lucifugus']) etc.

# Method 1
taxa_dic = {}
order = set([row[1] for row in taxa])
for i in range(10):
        for j in order:
                if taxa[i][1] == j:
                        taxa_dic.setdefault(j, set([])).add(taxa[i][0])

print(taxa_dic)

# Method 2
# from collections import defaultdict
# taxa_dict = defaultdict(list)
# for i in range(10):
#         taxa_dict[taxa[i][1]].append(taxa[i][0])

# taxa_dic = {}
# order = set([row[1] for row in taxa])
# for i in order:
#         taxa_dic[i] = set(taxa_dict[i])
# taxa_dic


import pandas as pd
import numpy as np
from pathlib import Path
import re

waste_sd = {
    "General Waste" : {
    "0.12" : 12.6,
    "0.24" : 25.2,
    "0.66" : 69.3,
    "1.1" : 115.5,
    "1.5" : 157.5,
    "3" : 315.0,
    "4.5" : 472.5
},
"Dry Waste" : {
    "0.12" : 8.4,
    "0.24" : 16.8,
    "0.66" : 46.2,
    "1.1" : 77,
    "1.5" : 105,
    "3" : 210,
    "4.5" : 315
},
"Comingle" : {
    "0.12" : 7.2,
    "0.24" : 14.4,
    "0.66" : 39.6,
    "1.1" : 66.0,
    },
 "Paper/Cardboard":{
     "0.12" : 6,
    "0.24" : 12,
    "0.66" : 33,
    "1.1" : 55,
    "1.5" : 75,
    "3" : 150,
    "4.5" : 225
 },
 "Paper":{
    "0.12" : 10.8,
    "0.24" : 21.6,
    "0.66" : 59.4
 },
"Glass" : {
    "0.12" : 24,
    "0.24" : 48,
    "0.66" : 132
},
"Organics" : {
    "0.12" : 33.6,
    "0.24" : 67.2
}
}

path = "../../ubuntuShareDrive/Datasets/Nabour_report_ds/1825.csv"

df = pd.read_csv(path, dtype={"Customer number": np.float64 ,"Schd Time Start": str, "PO": str, 'PostCode': str})

# df['Customer number'] =
# df = df.round({'Customer number' : 3})
df['Customer number'] = df['Customer number'].round(3)

others = df[df['Customer number'].isin([1887,3763,3268,3483,2317,4236,3476,4156,3966])]
df_4138 = df.loc[(df['Customer number'] > 4138.000) & (df['Customer number'] <= 4138.1)]
df_1021 = df.loc[(df['Customer number'] > 1021.000) & (df['Customer number'] <= 1021.1)]
df_2505 = df.loc[(df['Customer number'] > 2505.000) & (df['Customer number'] <= 2505.1)]
df_3139 = df.loc[(df['Customer number'] >= 3139.000) & (df['Customer number'] <= 3139.1)]

# 4138 group
df_4138_group = df_4138.groupby('Customer number')
df_4138_group_keys = list(df_4138_group.indices.keys())

# 1021 group
df_1021_group = df_1021.groupby('Customer number')
df_1021_group_keys = list(df_1021_group.indices.keys())

# others Group
others_group = others.groupby('Customer number')
others_group_keys = list(others_group.indices.keys())

# 2505 Group
df_2505_group = df_2505.groupby('Customer number')
df_2505_group_keys = list(df_2505_group.indices.keys())

# =====================================================================
df_3139_group = df_3139.groupby('Customer number')
df_3139_group_keys = list(df_3139_group.indices.keys())
# =====================================================================

# =======================================================
# df From Own database
df_1825 = df.groupby('Customer number')
df_1825_key = list(df_1825.indices.keys())
# =======================================================

for customer_key in df_1825_key:

    naber_df = df_1825.get_group(customer_key)

    # Pick address as File name
    # in case There is more than 1 address in that customer
    addresses = naber_df.groupby('Address 1').indices.keys()
    addresses = [re.sub('[^a-zA-Z0-9]+', '_', address_name) for address_name in addresses]
    address_name = addresses[0]

    # 4138.003, 4138.004, 4138.005, 4138.006, 4138.007, 4138.008

    # df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)
    def cal_weight(status, waste_type, qty_serviced, bin_volume, weight):

        if weight == 0:
            if status == 'C':
        #         waste type =>  Food Waste => Organics / Cardboard => Paper/Cardboard
                if waste_type == 'Food Waste':
                    return qty_serviced * waste_sd['Organics'][str(bin_volume)]

                elif waste_type == 'Cardboard' or waste_type == 'Paper/Cardboard':
                    if str(bin_volume) == '3.0':
                        return qty_serviced*waste_sd['Paper/Cardboard']['3']
                    else:
                        return qty_serviced*waste_sd['Paper/Cardboard'][str(bin_volume)]
                elif waste_type == 'Secure Bin':
                    return qty_serviced*waste_sd['Paper'][str(bin_volume)]

                return qty_serviced*waste_sd[waste_type][str(bin_volume)]
            else:
                return np.nan
        else:
            return weight

    naber_df['Total weight picked up - kg (if available)'] = (naber_df.apply(
                                                                lambda df: cal_weight(
                                                                    df['Status'],
                                                                    df['Waste Type'],
                                                                    df['Qty Serviced'],
                                                                    df['Bin Volume'],
                                                                    df['Weight']
                                                                ),
                                                                axis=1
                                                            ))

    def facility(waste_type):
        facility = {
            'General Waste' : 'Veolia Waste Centre Clyde',
            'Dry Waste' : 'Veolia Waste Centre Clyde',
            'Food Waste' : 'Eathpower Technologies',
            'Organics' : 'Eathpower Technologies',
            'Paper/Cardboard' : 'Grima Recycling',
            'Cardboard' : 'Grima Recycling',
            'Comingle' : 'Visy Recycling',
            'Secure Bin' : 'Grima Recycling'
        }
        return facility[waste_type]
    naber_df["Processing Facility sent to (Optional)"] = naber_df['Waste Type'].transform(facility)

    def standardize_waste_type(waste_type):
        if waste_type == 'Food Waste':
            return 'Organics'
        elif waste_type == 'Cardboard' or waste_type == 'Paper/Cardboard':
            return 'Paper & Cardboard'
        elif waste_type == 'Comingle':
            return 'Mixed recycling'
        return waste_type

    naber_df['Waste Type'] = (naber_df.apply(lambda df: standardize_waste_type(df['Waste Type']), axis=1))

    naber_df["Equipment"] = "Mobile bin"
    naber_df["Bin Rejected due to contamination (Optional)"] = np.nan

    naber_df['Dock (can omit if only 1)'] = np.nan
    naber_df['Version:3'] = np.nan

    # City	State	PostCode

    naber_df['Site Address (StreetNumber Street Name, Suburb, State, Postcode)'] = naber_df[['Address 1','City','State','PostCode']].agg(','.join, axis=1)
# ==========================================================================
    # Date Format is change per dataframe
    # Sort by Date

    # naber_df['Date'] = pd.to_datetime(naber_df['Date'], format='%d/%m/%y')

    # naber_df['Date'] = pd.to_datetime(naber_df['Date'], format='%d/%m/%Y')

    naber_df['Date'] = pd.to_datetime(naber_df['Date'], format='%Y-%m-%d')

    naber_df.sort_values(["Date"],ascending=True, inplace=True)

    naber_df['Date'] = naber_df['Date'].dt.date

    # naber_df['Date'] = pd.DatetimeIndex(df['Date'])
    # df.set_index(df['Date'], inplace=False)
    def is_fut_bin(status, served_bins):
        if status == 'F' or status == 'V':
            return 0
        return served_bins

    naber_df['Units Collected'] = naber_df.apply(lambda df : is_fut_bin(df['Status'], df['Qty Serviced']),axis=1)

    # 'Qty Serviced' :

    naber_df = (naber_df
    .rename(columns={
        'Date' : 'Pick-up Date (dd/mm/yyyy)',
        # 'Address 1': 'Site Address',
        'Bin Volume' : 'Size (m3)'
        })
    )

    # naber_df = (naber_df[
    #     ['Pick-up Date (dd/mm/yyyy)',
    #     'Site Address',
    #     'Waste Type',
    #     'Equipment',
    #     'Size (m3)',
    #     'Units Collected',
    #     'Total weight picked up - kg (if available)',
    #     'Processing Facility sent to (Optional)',
    #     'Bin Rejected due to contamination (Optional)',

    #     ]])

    fileExt = ".xlsx"
#  + fileExt

    naber_df.to_excel(Path(str(address_name)+"_"+str(customer_key)+fileExt),sheet_name=str(customer_key),columns=[
        'Pick-up Date (dd/mm/yyyy)',
        'Site Address (StreetNumber Street Name, Suburb, State, Postcode)',
        'Dock (can omit if only 1)',
        'Waste Type',
        'Equipment',
        'Size (m3)',
        'Units Collected',
        'Total weight picked up - kg (if available)',
        'Processing Facility sent to (Optional)',
        'Bin Rejected due to contamination (Optional)',
        'Version:3'
        ], index=False)


# Faça um programa que jogue par ou ímpar com o pc. O jogo será interrompido quando o jogador PERDER,
# mostrando o total de vitórias consecutivas que ele conquistou no final do jogo.

from random import randint

margin = '-' * 20
print(f'{margin} Vamos jogar ÍMPAR ou PAR! {margin}')

wins = 0
while True:
    user_num = int(input('Digite um número: '))
    pc_num = randint(0, 50)
    total = pc_num + user_num

    user_guess = ' '
    while user_guess not in 'PI':
        user_guess = str(input('Escolha entre PAR ou ÌMPAR [I/P]: ')).strip().upper()[0]

    if user_guess == 'P':
        if user_num % 2 == 0:
            print('PARABÉNS! Você venceu!')
            wins += 1
        else:
            break

    elif user_guess == 'I':
        if user_num % 2 != 0:
            print('PARABÉNS! Você venceu!')
            wins += 1
        else:
            break

print(f'GAME OVER!\nVocê teve {wins} vitórias.')


# -*- coding: utf-8 -*-
"""
Created on Sun Jun  5 12:04:18 2016

@author: ericgrimson
"""

from mortgage import *

class Fixed(Mortgage):
    def __init__(self, loan, r, months):
        Mortgage.__init__(self, loan, r, months)
        self.legend = 'Fixed, ' + str(round(r*100, 2)) + '%'

class FixedWithPts(Mortgage):
    def __init__(self, loan, r, months, pts):
        Mortgage.__init__(self, loan, r, months)
        self.pts = pts
        self.paid = [loan*(pts/100)]
        self.legend = 'Fixed, ' + str(round(r*100, 2)) + '%, '\
                       + str(pts) + ' points'

class TwoRate(Mortgage):
    def __init__(self, loan, r, months, teaserRate, teaserMonths):
        Mortgage.__init__(self, loan, teaserRate, months)
        self.teaserMonths = teaserMonths
        self.teaserRate = teaserRate
        self.nextRate = r/12
        self.legend = str(teaserRate*100)\
                      + '% for ' + str(self.teaserMonths)\
                      + ' months, then ' + str(round(r*100, 2)) + '%'

    def makePayment(self):
        if len(self.paid) == self.teaserMonths + 1:
            self.rate = self.nextRate
            self.payment = findPayment(self.outstanding[-1],
                                       self.rate,
                                       self.months - self.teaserMonths)
        Mortgage.makePayment(self)

def compareMortgages(amt, years, fixedRate, pts, ptsRate,
                     varRate1, varRate2, varMonths):
    totMonths = years*12
    fixed1 = Fixed(amt, fixedRate, totMonths)
    fixed2 = FixedWithPts(amt, ptsRate, totMonths, pts)
    twoRate = TwoRate(amt, varRate2, totMonths, varRate1, varMonths)
    morts = [fixed1, fixed2, twoRate]
    for m in range(totMonths):
        for mort in morts:
            mort.makePayment()
    for m in morts:
        print(m)
        print(' Total payments = $' + str(int(m.getTotalPaid())))

compareMortgages(amt=200000, years=30, fixedRate=0.07,
                 pts = 3.25, ptsRate=0.05, varRate1=0.045,
                 varRate2=0.095, varMonths=48)


from django.test import TestCase, Client
from django.urls import reverse

from forms.models import User, FormResponse, INVESTIGATION_ROLES
from forms.tests.factories import FormResponseFactory, FormInstanceFactory, TagFactory, UserFactory, \
    InvestigationFactory, FormFactory

def url_for_response(form_response):
    form = form_response.form_instance.form
    return reverse("response_json_edit", kwargs=dict(investigation_slug=form.investigation.slug,
                                                     form_slug=form.slug,
                                                     response_id=form_response.id))

class FormReponseListViewTest(TestCase):
    def setUp(self):
        owner = UserFactory.create()
        self.investigation = InvestigationFactory.create()
        self.investigation.add_user(owner, INVESTIGATION_ROLES.OWNER)

        self.form = FormFactory(investigation=self.investigation)
        self.client.force_login(owner)

    def make_singe_step_instance(self, properties):
        return FormInstanceFactory.create(form_json=[
            {
                "schema":
                    {
                        "title": "first",
                        "slug": "first",
                        "properties": properties
                    }
            }
        ], form=self.form)

    def test_edit_fails_for_viewer(self):
        form_instance = self.make_singe_step_instance({"name": {"type": "string"}})
        form_response = FormResponseFactory.create(json={"name": "Gödel"}, form_instance=form_instance)

        viewer = UserFactory.create()
        self.investigation.add_user(viewer, "V")
        self.client.force_login(viewer)

        response = self.client.post(url_for_response(form_response), data={"json__name": "Escher"})
        self.assertEqual(response.status_code, 403)

        updated_response = FormResponse.objects.get(id=form_response.id)
        self.assertEqual(updated_response.json["name"], "Gödel")

    def test_edit(self):
        form_instance = self.make_singe_step_instance({"name": {"type": "string"}})
        form_response = FormResponseFactory.create(json={"name": "Gödel"}, form_instance=form_instance)

        response = self.client.post(url_for_response(form_response), data={"json__name": "Escher"})
        self.assertEqual(response.status_code, 302)

        updated_response = FormResponse.objects.get(id=form_response.id)
        self.assertEqual(updated_response.json["name"], "Escher")

    def test_edit_non_existing_field(self):
        properties = {"name": {"type": "string"}}
        form_instance = self.make_singe_step_instance(properties)
        form_response = FormResponseFactory.create(json={"name": "Gödel"}, form_instance=form_instance)

        response = self.client.post(url_for_response(form_response), data={"json__color": "Red"})
        self.assertEqual(response.status_code, 400)

        updated_response = FormResponse.objects.get(id=form_response.id)
        self.assertDictEqual(updated_response.json, {"name": "Gödel"})

    def test_add_new_field_to_response(self):
        properties = {"name": {"type": "string"}, "color": {"type": "string"}}
        form_instance = self.make_singe_step_instance(properties)
        form_response = FormResponseFactory.create(json={"name": "Gödel"}, form_instance=form_instance)

        response = self.client.post(url_for_response(form_response), data={"json__color": "Red"})
        self.assertEqual(response.status_code, 302)

        updated_response = FormResponse.objects.get(id=form_response.id)
        self.assertDictEqual(updated_response.json, {"name": "Gödel", "color": "Red"})

    def test_with_json_schema(self):
        properties = {"email": {"type": "string", "format": "email"}}
        form_instance = self.make_singe_step_instance(properties)
        form_response = FormResponseFactory.create(json={"email": "test@example.com"}, form_instance=form_instance)

        response = self.client.post(url_for_response(form_response), data={"json__email": "not an email address"})
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, b"'not an email address' is not a 'email'")

        updated_response = FormResponse.objects.get(id=form_response.id)
        self.assertDictEqual(updated_response.json, {"email": "test@example.com"})


import multiprocessing
from time_track import time_track
from volatility_sort_and_print import *

def volatility_count(file_name):
    ticker = None
    max_price = 0
    min_price = 0

    with open(file_name, 'r', encoding='utf8') as file:
        file.readline()
        for line in file:
            sec_id, trade_time, price, quantity = line[:-1].split(',')
            price = float(price)
            if sec_id != ticker:
                ticker = sec_id
                max_price, min_price = price, price
            elif max_price < price:
                max_price = price
            elif min_price > price:
                min_price = price

    half_sum = (max_price + min_price) / 2
    volatility = round((((max_price - min_price) / half_sum) * 100), 2)

    return ticker, volatility

@time_track
def main(path):
    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    vol_list = pool.map(volatility_count, path_to_file(path=path))
    pool.close()
    pool.join()
    sort(dict(vol_list))

if __name__ == '__main__':
    path = 'trades'
    main(path=path)


"""Measures for chaotic dynamical systems."""
from __future__ import annotations

from typing import Callable

import numpy as np

def largest_lyapunov_exponent(
    iterator_func: Callable[[np.ndarray], np.ndarray],
    starting_point: np.ndarray,
    deviation_scale: float = 1e-10,
    steps: int = int(1e3),
    part_time_steps: int = 15,
    steps_skip: int = 50,
    dt: float = 1.0,
    initial_pert_direction: np.ndarray | None = None,
    return_convergence: bool = False,
) -> float | np.ndarray:
    """Numerically calculate the largest lyapunov exponent given an iterator function.

    See: Sprott, Julien Clinton, and Julien C. Sprott. Chaos and time-series analysis.
    Vol. 69. Oxford: Oxford university press, 2003.

    Args:
        iterator_func: Function to iterate the system to the next time step:
                       x(i+1) = F(x(i))
        starting_point: The starting_point of the main trajectory.
        deviation_scale: The L2-norm of the initial perturbation.
        steps: Number of renormalization steps.
        part_time_steps: Time steps between renormalization steps.
        steps_skip: Number of renormalization steps to perform, before tracking the log
                    divergence. Avoid transients by using steps_skip.
        dt: Size of time step.
        initial_pert_direction:
            - If np.ndarray: The direction of the initial perturbation.
            - If None: The direction of the initial perturbation is assumed to be
                np.ones(..).
        return_convergence: If True, return the convergence of the largest LE; a numpy
                            array of the shape (N, ).

    Returns:
        The largest Lyapunov Exponent. If return_convergence is True: The convergence
        (np.ndarray), else just the float value, which is the last value in the
        convergence.
    """
    x_dim = starting_point.size

    if initial_pert_direction is None:
        initial_pert_direction = np.ones(x_dim)

    initial_perturbation = initial_pert_direction * (
        deviation_scale / np.linalg.norm(initial_pert_direction)
    )

    log_divergence = np.zeros(steps)

    x = starting_point
    x_pert = starting_point + initial_perturbation

    for i_n in range(steps + steps_skip):
        for i_t in range(part_time_steps):
            x = iterator_func(x)
            x_pert = iterator_func(x_pert)
        dx = x_pert - x
        norm_dx = np.linalg.norm(dx)
        x_pert = x + dx * (deviation_scale / norm_dx)
        if i_n >= steps_skip:
            log_divergence[i_n - steps_skip] = np.log(norm_dx / deviation_scale)

    if return_convergence:
        return np.array(
            np.cumsum(log_divergence) / (np.arange(1, steps + 1) * dt * part_time_steps)
        )
    else:
        return float(np.average(log_divergence) / (dt * part_time_steps))


import numpy as np
import csv
from sklearn.neural_network import BernoulliRBM, MLPClassifier
import plot
from rbm import error, percent_error, reformat_data, gen_even_slices

def make_rbm(data, components=50, n_iter=20):
    model = BernoulliRBM(n_components=components, learning_rate=0.1, batch_size=10, n_iter=n_iter,
    	random_state=None, verbose=0)
    model = model.fit(data)
    print("error: {}".format(percent_error(model.gibbs(data), data)))
    return model

def make_dbn(data, components=[150,50], iterations=None):
    if iterations == None:
        iterations = [1]*len(components)
    result = []
    for size, n_iter in zip(components, iterations):
        rbm = make_rbm(data, components=size, n_iter=n_iter)
        result.append(rbm)
        data = np.round(rbm._mean_hiddens(data)).astype(int)
    return result

def run_together(data, layers):
    for layer in layers:
        data = layer._sample_hiddens(data, layer.random_state_)
    for layer in reversed(layers):
        data = layer._sample_visibles(data, layer.random_state_)
    return data

def read_to_array(inf):
    data = []
    with open(inf) as f:
    	reader = csv.reader(f)
    	for row in reader:
    		data.append(np.array([int(_) for _ in row]))
    return np.array(data)

if __name__ == "__main__":
    train_data = read_to_array('binMNIST_data\\bindigit_trn.csv')
    test_data = read_to_array('binMNIST_data\\bindigit_tst.csv')
    train_class = read_to_array('binMNIST_data\\targetdigit_trn.csv')
    test_class = read_to_array('binMNIST_data\\targetdigit_tst.csv')
    print("train data: {}, test data: {}".format(len(train_data), len(test_data)))

    dbn = make_dbn(train_data, [150, 100], [10, 100, 500])
    mlp = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(784, 512), random_state=1)
    mlp.fit(train_data, train_class)

    print("sample / sample error: {}".format(percent_error(dbn[0]._sample_hiddens(train_data, dbn[0].random_state_), dbn[0]._sample_hiddens(train_data, dbn[0].random_state_))))
    print("rounded mean / sample error: {}".format(percent_error(np.round(dbn[0]._mean_hiddens(train_data)).astype(int), dbn[0]._sample_hiddens(train_data, dbn[0].random_state_))))

    #for i in [27, 4, 18, 1, 3, 2, 15, 10, 7, 6]:
    #    #plot.plot_heatmap(reformat_data(test_data[i-1]))
    #    #plot.plot_heatmap(reformat_data(dbn[0].gibbs(test_data[i-1])))
    #    plot.plot_heatmap(reformat_data(run_together(test_data[i-1], dbn)))

    result = run_together(test_data, dbn)
    rbm_result = dbn[0].gibbs(test_data)
    print("first layer total error: {}".format(percent_error(rbm_result, test_data)))
    print("total error: {}".format(percent_error(result, test_data)))
    print(sum([1 if a == b else 0 for a, b in zip(mlp.predict(result), test_class)])/len(result))
    print(sum([1 if a == b else 0 for a, b in zip(mlp.predict(rbm_result), test_class)])/len(rbm_result))


from abc import ABC, abstractmethod
from typing import Optional

from state import State

class Solver(ABC):
    @staticmethod
    @abstractmethod
    def solve(state: State, order: str) -> Optional[State]:
        if not state.is_solvable():
            raise Exception("Not solvable")
        if len(order) != 4 or 'L' not in order or 'R' not in order or 'U' not in order or 'D' not in order:
            raise Exception("Invalid search order")

        return


import cv2
import numpy as np

filepath = './aruco_photo/'
markersX = 1  # X轴上标记的数量
markersY = 1  # Y轴上标记的数量
markerLength = 100  # 标记的长度，单位是像素
markerSeparation = 20  # 每个标记之间的间隔，单位像素
margins = markerSeparation  # 标记与边界之间的间隔
borderBits = 10  # 标记的边界所占的bit位数
showImage = True

width = markersX * (markerLength + markerSeparation) - markerSeparation + 2 * margins
height =markersY * (markerLength + markerSeparation) - markerSeparation + 2 * margins

dictionary = cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_250)  # 生成标记的字典ID
board = cv2.aruco.GridBoard_create(markersX, markersY, float(markerLength), float(markerSeparation), dictionary)
print(cv2.aruco_GridBoard.getGridSize(board))
img = cv2.aruco_GridBoard.draw(board, (500, 500), 1)
cv2.imwrite(filepath + '1.png', img)


# Databricks notebook source
# MAGIC %md
# MAGIC ##### Storage access setup

# COMMAND ----------

# MAGIC %run ../includes/access_setup

# COMMAND ----------

# MAGIC %md
# MAGIC ##### Managed tables

# COMMAND ----------

# MAGIC %sql
# MAGIC CREATE DATABASE IF NOT EXISTS f1_gold;

# COMMAND ----------

rr_df = spark.read.parquet(f"{gold}/races_results")
rr_df.write.mode("overwrite").format("parquet").saveAsTable("f1_gold.races_results")

# COMMAND ----------

ds_df = spark.read.parquet(f"{gold}/drivers_standings");
ds_df.write.mode("overwrite").format("parquet").saveAsTable("f1_gold.drivers_standings");

# COMMAND ----------

cs_df = spark.read.parquet(f"{gold}/constructors_standings");
cs_df.write.mode("overwrite").format("parquet").saveAsTable("f1_gold.constructors_standings");

# COMMAND ----------

# MAGIC %sql
# MAGIC SHOW TABLES IN f1_gold

# COMMAND ----------

# MAGIC %sql
# MAGIC SELECT * FROM f1_gold.races_results LIMIT 10;
# MAGIC --SELECT * FROM f1_gold.drivers_standings LIMIT 10;
# MAGIC --SELECT * FROM f1_gold.constructors_standings LIMIT 10;

# COMMAND ----------


from django.forms import ModelForm
from .models import Post, Comment

class PostForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(PostForm, self).__init__(*args, **kwargs)
        self.fields['group'].empty_label = None
        self.fields['group'].widget.choices = self.fields['group'].choices

    class Meta:
        model = Post
        fields = ('text', 'group', 'image')
        labels = {
            'text': 'Текст поста',
            'group': 'Группа',
        }

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('text',)


import csv

# Node Construction
class Node:
    def __init__(self, name):
        self.name = name
        self.parent = []
        self.child = []
        self.evidence = {}
        self.value = ['T', 'F']
        self.specific_value = None

# Graph Construction
class Graph:
    def __init__(self):
        self.node_dict = {}
        self.edges_lib = {}
        self.Var = []

    def add_node(self, node):
        if isinstance(node, Node) and node.name not in self.node_dict:
            self.node_dict[node.name] = node

    def add_Var(self):
        for key in self.node_dict:
            self.Var.append(self.node_dict[key])


import openpyxl

# 写入
def write07Excel(path):
	#创建文件
    wb = openpyxl.Workbook()
    #创建sheet，修改sheet的名字
    sheet = wb.active
    sheet.sheet_properties.tabColor = "1072BA"
    sheet.title = '2007测试表'
    #在末尾创建另一张sheet
    sheet2 = wb.create_sheet("Mysheet")

    value = [["名称", "价格", "出版社", "语言"],
             ["如何高效读懂一本书", "22.3", "机械工业出版社", "中文"],
             ["暗时间", "32.4", "人民邮电出版社", "中文"],
             ["拆掉思维里的墙", "26.7", "机械工业出版社", "中文"]]
    for i in range(0, 4):
        for j in range(0, len(value[i])):
            sheet.cell(row=i+1, column=j+1, value=str(value[i][j]))

    # 保存文件在path地址
    wb.save(path)
    print("写入数据成功！")
    print('----------')

# 读取
def read07Excel(path):
	#打开并读取文件
    wb = openpyxl.load_workbook(path)
    #读取指定sheet
    sheet = wb.get_sheet_by_name('2007测试表')

    for row in sheet.rows:
        for cell in row:
            print(cell.value, "\t", end="")
        print()
    print('读取完成')

file_2007 = '/Users/jk/www/interface/mypackage/data_config2007.xlsx'
write07Excel(file_2007)
read07Excel(file_2007)


import time
import json
import numpy as np
import torch
import glob
import os
import logging
from statistics import mean
from modules.train_eval import model_eval, calc_accuracy
from modules.viz import plot_training_curves

def train_loop(model, train_loader, val_loader, device, optimizer, criterion, lr_scheduler,
               epochs, es_pat, run_dir):
    """
    Perform a full training loop for a model using the dataloader objects and hyper parameters passed.
    """
    # ---------------------
    #  Hold Epoch Results
    # ---------------------
    train_loss_epc = []
    train_acc_epc = []
    val_loss_epc = []
    val_acc_epc = []

    min_val_loss = np.Inf                   # Setting initial validation loss metric to infinity
    train_batches = len(train_loader)       # No. of training batches

    # ---------------------
    #  Begin Training Loop
    # ---------------------
    for epoch in range(epochs):

        model.train()                       # Put model in training mode

        # ---------------------
        #  Hold Batch Results
        # ---------------------
        train_loss_btc = []
        train_acc_btc = []
        val_loss_btc = []
        val_acc_btc = []
        batch_start = time.process_time()

        for images, labels in train_loader:
            # ---------------------
            #  Batch Training
            # ---------------------
            images, labels = images.to(device), labels.type(torch.LongTensor).to(device)
            optimizer.zero_grad()

            # Predict classes from model inputs:
            mod_preds = model(images)

            # Calculate loss:
            train_loss = criterion(mod_preds, labels)

            # Calculate accuracy of predictions:
            train_acc = calc_accuracy(mod_preds, labels)

            # Calculate gradients and update model:
            train_loss.backward()
            optimizer.step()

            # ---------------------
            #  Batch Eval.
            # ---------------------
            # Put model in evaluation mode:
            model.eval()

            # Turn off gradients for validation:
            with torch.no_grad():
                val_loss, val_acc = model_eval(model, val_loader, criterion, device)

            # ---------------------
            #  Store Batch Results
            # ---------------------
            train_loss_btc.append(train_loss.item())
            train_acc_btc.append(train_acc)
            val_loss_btc.append(val_loss)
            val_acc_btc.append(val_acc)

        # ---------------------
        #  Log Results
        # ---------------------
        # Averaging loss and accuracies across batches:
        av_bch_tl = mean(train_loss_btc)
        av_bch_ta = mean(train_acc_btc)
        av_bch_vl = mean(val_loss_btc)
        av_bch_va = mean(val_acc_btc)

        time_taken = time.process_time() - batch_start

        logging.info(
            "[Epoch %d/%d] [Batches: %d] [Train Loss: %f] [Train Acc: %f] [Val Loss: %f] [Val Acc: %f] [Time Taken: %f]"
            % (epoch + 1, epochs, train_batches, av_bch_tl, av_bch_ta, av_bch_vl, av_bch_va, time_taken)
        )

        # ---------------------
        #  Store Epoch Results
        # ---------------------
        train_loss_epc.append(av_bch_tl)
        train_acc_epc.append(av_bch_ta)
        val_loss_epc.append(av_bch_vl)
        val_acc_epc.append(av_bch_va)

        # ---------------------
        #  Manual Callbacks
        # ---------------------
        # Saving best model (epoch with lowest av. validation loss) throughout training:
        if av_bch_vl <= min_val_loss:
            # Remove previous best model in dir:
            for modpath in glob.glob(os.path.join(run_dir, '*.pth')):
                os.remove(modpath)
            torch.save(model.state_dict(), '%s/vl_%.4f.pth' % (run_dir, av_bch_vl))
            # Updating min_val_loss to new lowest:
            min_val_loss = av_bch_vl

        # Early stopping:
        last_x_epochs = val_loss_epc[-es_pat:]
        if min(last_x_epochs) > min(val_loss_epc):
            logging.info("Training ended. No improvement in val. loss for %d epochs." % es_pat)
            break

        # Update learning rate scheduler (reduces lr if val_loss plateaus):
        lr_scheduler.step(av_bch_vl)

    # ---------------------
    #  Storing Metrics
    # ---------------------
    res_dict = {'train_loss': train_loss_epc, 'train_acc': train_acc_epc,
                'val_loss': val_loss_epc, 'val_acc': val_acc_epc}

    with open('training_results.json', 'w') as f:                       # Save logs to json file
        json.dump(res_dict, f)

    plot_training_curves(res_dict, run_dir)                             # Saving plots of training stats

    logging.info("[------ Training complete. Lowest validation loss of %.4f during training.]" % min(val_loss_epc))

    opt_model_path = '%s/vl_%.4f.pth' % (run_dir, min_val_loss)         # Path to optimal model during training

    return opt_model_path


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

from pekipeki.constants import status, event

def nullpo(skype, evt):
    u'''
    ぬるぽに ｶﾞｯ する
    '''

    body = evt.get_body()

    if u'ぬるぽ' in body:
        evt.reply(u'ｶﾞｯ')

    return status.CONTINUE

def haisho(skype, evt):
    u'''
    拝承
    '''

    body = evt.get_body()

    if body.endswith(u'たく'):
        evt.reply(u'拝承')

    return status.CONTINUE

def init_skype(skp, args):
    u'''
    ハンドラ登録
    '''

    skp.register_message_handler(event.RECEIVED, nullpo)
    skp.register_message_handler(event.RECEIVED, haisho)


import pickle
import argparse
import numpy as np
import json
from collections import defaultdict

argp = argparse.ArgumentParser()
argp.add_argument('--just_best', default=None)
argp.add_argument('--test', default=False)
args = argp.parse_args()

model_sizes = ('', '-medium', '-large', '-xl')

top_p_hyps = (0.89, 0.9, 0.92, 0.95, 0.99)
epsilon_hyps = (0.001, 0.0009, 0.0006, 0.0003, 0.0001)
eta_hyps = (0.004, 0.002, 0.0009, 0.0006, 0.0003)
typ_hyps = (0.9, 0.92, 0.95, 0.2)

top_p_seeds_valid = (1, 2, 3, 4, 5)
epsilon_seeds_valid = (1, 2, 3, 4, 5)
eta_seeds_valid = (200, 201, 202, 203, 204, 1, 2, 3, 4, 5)
typ_seeds_valid = (0, 1, 2, 3, 4, 5)

lengths = (128, 256, 512, 1024)

path = 'outputs/webtext_gpt2{}/metrics/basic/mauve_L{}_valid_p{}_k0_t1.0_e{}_h{}_seed{}_kmeans_l2_500_0.9.p'

generation_path = 'outputs/webtext_gpt2{}/generations/basic/sentences_valid_p{}_k0_t1.0_e{}_h{}_seed{}.p'

generations = {}
mauves = {}

def results_helper(hyps, seeds, typ):
  results = {hyp: [] for hyp in hyps}
  for hyp in hyps:
    for seed in seeds:
      try:
        if typ == 'p':
          resolved_path = path.format(model_size, length, hyp, 0.0, 0.0, seed)
          resolved_generation_path = generation_path.format(model_size, hyp, 0.0, 0.0, seed)
        elif  typ == 'e':
          resolved_path = path.format(model_size, length, 1.0, hyp, 0.0, seed)
          resolved_generation_path = generation_path.format(model_size, 1.0, hyp, 0.0, seed)
        elif typ == 'h':
          resolved_path = path.format(model_size, length, 1.0, 0.0, hyp, seed)
          resolved_generation_path = generation_path.format(model_size, 1.0, 0.0, hyp, seed)
        elif typ == 't':
          resolved_path = path.format(model_size, length, 1.0, 0.0, 0.0, seed).replace('h0.0', 'h0.0_typ{}'.format(hyp))
          resolved_generation_path = generation_path.format(model_size, 1.0, 0.0, 0.0, seed).replace('h0.0', 'h0.0_typ{}'.format(hyp))
        result = pickle.load(open(resolved_path, 'rb'))[0]
        generation = pickle.load(open(resolved_generation_path, 'rb'))
        generations[str((typ, hyp, seed))] = generation
        mauves[str((typ, hyp, seed))] = result
        results[hyp].append(result)
        #print(typ, hyp, seed)
      except:
        pass
  print(results)
  results = {hyp: (round(np.mean(results[hyp]),4), np.std(results[hyp]), len(results[hyp])) for hyp in results}
  if args.just_best:
    print(list(sorted(results.items(), key=lambda x: 100 if np.isnan(x[1][0]) else -x[1][0]))[0])
  else:
    for hyp in hyps:
      print(hyp, results[hyp])

for model_size in model_sizes:
  for length in lengths:
    if args.test:
      path = 'outputs/webtext_gpt2{}/metrics/basic/mauve_L{}_test_p{}_k0_t1.0_e{}_h{}_seed{}_kmeans_l2_500_0.9.p'
      generation_path = 'outputs/webtext_gpt2{}/generations/basic/sentences_test_p{}_k0_t1.0_e{}_h{}_seed{}.p'
      if model_size == '':
        top_p_hyps = (0.9,)
        eta_hyps = (0.002,)
        epsilon_hyps = (0.0006,)
        typ_hyps = (0.9,)
      if model_size == '-medium':
        top_p_hyps = (0.89,)
        eta_hyps = (0.002,)
        epsilon_hyps = (0.0009,)
        typ_hyps = (0.9,)
      if model_size == '-large':
        top_p_hyps = (0.95,)
        eta_hyps = (0.0006,)
        epsilon_hyps = (0.0003,)
        typ_hyps = (0.92,)
      if model_size == '-xl':
        top_p_hyps = (0.95,)
        eta_hyps = (0.0003,)
        epsilon_hyps = (0.0003,)
        typ_hyps = (0.92,)
    print()
    print(model_size if model_size != '' else 'small', length)
    results_helper(top_p_hyps, top_p_seeds_valid,  'p')
    results_helper(epsilon_hyps, epsilon_seeds_valid, 'e')
    results_helper(eta_hyps, eta_seeds_valid, 'h')
    results_helper(typ_hyps, typ_seeds_valid, 't')

with open('generations.json', 'w') as fout:
  json.dump(generations, fout)

with open('mauves.json', 'w') as fout:
  json.dump(mauves, fout)