import Chemins
from Utils.UTILS_Traduction import _
import wx
import six
from Ctrl import CTRL_Bouton_image
from PIL import Image
import FonctionsPerso

def pil2wx(image):
    """Convert a PIL image to wx image format"""
    imagewx=wx.EmptyImage(image.size[0], image.size[1])
    imagewx.SetData(image.tobytes('raw', 'RGB'))
    return imagewx

def load_image(fn):
    """Read a file into PIL Image object. Return the image and file size"""
    buf = six.BytesIO()
    f=open(fn,"rb")
    while 1:
        rdbuf=f.read(8192)
        if not rdbuf: break
        buf.write(rdbuf)
    f.close()
    buf.seek(0)
    image=Image.open(buf).convert("RGB")
    return image,len(buf.getvalue())

def save_image_buf(image,q=90):
    """Save a PIL Image into a byte buffer as a JPEG with the given quality.
    Return the buffer and file size.
    """
    buf = six.BytesIO()
    image.save(buf,format='JPEG',quality=q)
    buf.seek(0)
    return buf,len(buf.getvalue())

def wxtopil(image):
    """Convert wx.Image to PIL Image."""
    pil = Image.new('RGB', (image.GetWidth(), image.GetHeight()))
    pil.frombytes(image.GetData())
    return pil

class ImgBox(wx.Window):
    def __init__(self, parent, id=-1, image=None):
        wx.Window.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize, wx.NO_FULL_REPAINT_ON_RESIZE |wx.SUNKEN_BORDER)

        self.fichierImageSource = image
        self.InitImage()

        # Binds
        wx.EVT_PAINT(self, self.evt_paint)
        wx.EVT_SIZE(self, self.evt_size)

    def InitImage(self):
        # Chargement de l'image source
        self.sourcePIL, self.origsize = load_image(self.fichierImageSource)
        # Transforme l'image PIL en wx.Image
        self.source = pil2wx(self.sourcePIL)
        # Initialise les valeurs
        self.posxPhoto = None
        self.posyPhoto = None

        self.largeurDC = None
        self.hauteurDC = None

        self.tailleCadre = 384

    def ReinitImage(self):
        self.InitImage()
        self.evt_size(None)

    def Draw(self,dc):
        """Draw the image bitmap and decoration on the buffered DC"""
        dc.SetBackground(wx.BLACK_BRUSH)
        dc.Clear()
        dc.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'Arial'))

        # Dessin de la photo
        largeurImg, hauteurImg = self.bmp.GetSize()
        largeurDC, hauteurDC = self.GetClientSizeTuple()
        dc.DrawBitmap(self.bmp, (largeurDC / 2.0)  - (largeurImg / 2.0), (hauteurDC / 2.0) - (hauteurImg / 2.0), 0)

    def evt_paint(self, event):
        """Paint event handler with double buffering"""
        dc = wx.BufferedPaintDC(self, self._Buffer)

    def evt_size(self,event):
        """ OnSize """
        self.ResizePhoto()
        largeurDC, hauteurDC = self.GetClientSizeTuple()
        # Redessine toute l'image
        self._Buffer = wx.EmptyBitmap(largeurDC, hauteurDC)
        self.UpdateDrawing()

    def ResizePhoto(self):
        """ Redimensionne la photo"""
        largeurImg, hauteurImg = self.source.GetSize()
        self.ratio = self.GetParent().slider_ratio.GetValue() / 100.0
        source = self.source.Scale(largeurImg * self.ratio, hauteurImg * self.ratio)
        self.bmp=wx.BitmapFromImage(source)

    def UpdateDrawing(self):
        """Create the device context and draw the window contents"""
        dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
        dc.BeginDrawing()
        self.Draw(dc)
        dc.EndDrawing()

    def SetRatio(self):
        """ ratio """
        self.ResizePhoto()
        self.UpdateDrawing()

    def Rotation(self, VersDroite=True):
        """ Rotation de la photo """
        # Rotation
        self.source = self.source.Rotate90(VersDroite)
        # Réduction de l'image
        largeurImg, hauteurImg = self.source.GetSize()
        source = self.source.Scale(largeurImg * self.ratio, hauteurImg * self.ratio)
        self.bmp=wx.BitmapFromImage(source)
        # MAJ de l'affichage de la photo
        self.UpdateDrawing()

    def SaveImage(self):
        # Paramètres de sauvegarde
        jpeg_quality = 90

        # Création du nom de fichier
        nomFichier = "Photos/"
        codeIDfichier = self.RecupIDfichier()
        IDpersonne = self.GetGrandParent().IDpersonne
        nomFichier += codeIDfichier + str(IDpersonne) + ".jpg"

        # Récupération de l'image dans le cadre de sélection
        tailleImg = self.selection.GetSize()
        imgTemp = self.selection.GetSubBitmap( (0, 0, tailleImg[0], tailleImg[1]) )
        imgFinale = wxtopil(imgTemp.ConvertToImage())

        # Sauvegarde
        try:
            buf, bytes=save_image_buf(imgFinale, jpeg_quality)
            ok=1
            if ok:
                save_image_file(nomFichier,buf)
                print("Saved image to %s (%.f kB)" % (nomFichier, bytes/1024))
        except:
                print("Failed to save image!")
                return None
        return nomFichier

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------

class MyDialog(wx.Dialog):
    def __init__(self, parent, image=None, titre=_(u"Editeur photo")):
        wx.Dialog.__init__(self, parent, -1, title=titre, name="frm_photo", size=(700, 600))

        # Widgets
        self.imgbox = ImgBox(self,-1, image=image)

        self.staticBox_rotation = wx.StaticBox(self, -1, _(u"Rotation"))
        self.bouton_rotation_gauche = wx.BitmapButton(self, -1, wx.Bitmap(Chemins.GetStaticPath("Images/22x22/RotationGauche.png"), wx.BITMAP_TYPE_PNG))
        self.bouton_rotation_droite = wx.BitmapButton(self, -1, wx.Bitmap(Chemins.GetStaticPath("Images/22x22/RotationDroite.png"), wx.BITMAP_TYPE_PNG))

        self.staticBox_ratio = wx.StaticBox(self, -1, _(u"Taille de l'image"))
        self.slider_ratio = wx.Slider(self, -1,  100, 1, 200, size=(-1, -1), style=wx.SL_HORIZONTAL)
        self.img_loupe_plus = wx.StaticBitmap(self, -1, wx.Bitmap(Chemins.GetStaticPath("Images/22x22/zoomPlus.png"), wx.BITMAP_TYPE_ANY))
        self.img_loupe_moins = wx.StaticBitmap(self, -1, wx.Bitmap(Chemins.GetStaticPath("Images/22x22/zoomMoins.png"), wx.BITMAP_TYPE_ANY))

        self.staticBox_reinit = wx.StaticBox(self, -1, _(u"Réinitialisation"))
        self.bouton_reinit = wx.BitmapButton(self, -1, wx.Bitmap(Chemins.GetStaticPath("Images/22x22/Photo.png"), wx.BITMAP_TYPE_ANY), size=(70, -1))

        # Boutons
        self.bouton_aide = CTRL_Bouton_image.CTRL(self, texte=_(u"Aide"), cheminImage=Chemins.GetStaticPath("Images/32x32/Aide.png"))
        self.bouton_ok = CTRL_Bouton_image.CTRL(self, texte=_(u"Ok"), cheminImage=Chemins.GetStaticPath("Images/32x32/Valider.png"))
        self.bouton_annuler = CTRL_Bouton_image.CTRL(self, id=wx.ID_CANCEL, texte=_(u"Annuler"), cheminImage=Chemins.GetStaticPath("Images/32x32/Annuler.png"))

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnBoutonRotationGauche, self.bouton_rotation_gauche)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonRotationDroite, self.bouton_rotation_droite)
        self.Bind(wx.EVT_SCROLL, self.OnScrollSlider, self.slider_ratio)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonReinit, self.bouton_reinit)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonAide, self.bouton_aide)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonOk, self.bouton_ok)

    def __set_properties(self):
        self.SetTitle(_(u"Editeur de photo"))
        if 'phoenix' in wx.PlatformInfo:
            _icon = wx.Icon()
        else :
            _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Logo.png"), wx.BITMAP_TYPE_ANY))
        self.SetIcon(_icon)
        self.bouton_aide.SetToolTip(wx.ToolTip(_(u"Cliquez ici pour obtenir de l'aide")))
        self.bouton_ok.SetToolTip(wx.ToolTip(_(u"Cliquez ici pour valider l'image")))
        self.bouton_annuler.SetToolTip(wx.ToolTip(_(u"Cliquez ici pour annuler")))

        self.bouton_rotation_gauche.SetToolTip(wx.ToolTip(_(u"Cliquez ici pour effectuer une rotation de 90°\n dans le sens inverse des aiguilles d'une montre")))
        self.bouton_rotation_droite.SetToolTip(wx.ToolTip(_(u"Cliquez ici pour effectuer une rotation de 90°\n dans le sens des aiguilles d'une montre")))
        self.slider_ratio.SetToolTip(wx.ToolTip(_(u"Ajustez avec cette fonction ratio\nla taille de la photo")))
        self.bouton_reinit.SetToolTip(wx.ToolTip(_(u"Cliquez ici pour réinitialiser la position\net la taille de la photo initiale")))

    def __do_layout(self):
        sizer_base = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_base = wx.FlexGridSizer(rows=3, cols=1, vgap=0, hgap=0)

        # DC
        grid_sizer_base.Add(self.imgbox, 1, wx.LEFT|wx.TOP|wx.RIGHT|wx.EXPAND, 10)

        # Panneau de contrôle
        sizer_commandes = wx.FlexGridSizer(rows=1, cols=5, vgap=5, hgap=5)

        # Rotation
        staticBox_rotation = wx.StaticBoxSizer(self.staticBox_rotation, wx.HORIZONTAL)
        staticBox_rotation.Add(self.bouton_rotation_gauche, 0, wx.ALL, 2)
        staticBox_rotation.Add(self.bouton_rotation_droite, 0, wx.ALL, 2)
        sizer_commandes.Add(staticBox_rotation, 1, wx.EXPAND, 0)

        # ratio
        staticBox_ratio = wx.StaticBoxSizer(self.staticBox_ratio, wx.HORIZONTAL)
        staticBox_ratio.Add(self.img_loupe_moins, 0, wx.ALL, 2)
        staticBox_ratio.Add(self.slider_ratio, 1, wx.EXPAND | wx.ALL, 2)
        staticBox_ratio.Add(self.img_loupe_plus, 0, wx.ALL, 2)
        sizer_commandes.Add(staticBox_ratio, 1, wx.EXPAND, 0)

        # Reinit
        staticBox_reinit = wx.StaticBoxSizer(self.staticBox_reinit, wx.HORIZONTAL)
        staticBox_reinit.Add(self.bouton_reinit, 0, wx.ALL, 2)
        sizer_commandes.Add(staticBox_reinit, 1, wx.EXPAND, 0)

        grid_sizer_base.Add(sizer_commandes, 1, wx.EXPAND | wx.ALL, 10)

        sizer_commandes.AddGrowableRow(0)
        sizer_commandes.AddGrowableCol(1)

        # Boutons
        grid_sizer_boutons = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=10)
        grid_sizer_boutons.Add(self.bouton_aide, 0, 0, 0)
        grid_sizer_boutons.Add((20, 20), 0, wx.EXPAND, 0)
        grid_sizer_boutons.Add(self.bouton_ok, 0, 0, 0)
        grid_sizer_boutons.Add(self.bouton_annuler, 0, 0, 0)
        grid_sizer_boutons.AddGrowableCol(1)

        grid_sizer_base.AddGrowableCol(0)
        grid_sizer_base.AddGrowableRow(0)
        grid_sizer_base.Add(grid_sizer_boutons, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
        self.SetSizer(grid_sizer_base)
        sizer_base.Add(self, 1, wx.EXPAND, 0)
        self.Layout()
        self.CentreOnScreen()

    def Fermer(self):
        self.EndModal(wx.ID_CANCEL)

    def GetBmp(self):
        return self.imgbox.bmp

    def OnBoutonAide(self, event):
        from Utils import UTILS_Aide
        UTILS_Aide.Aide("")

    def OnBoutonOk(self, event):
        # Ferme la boîte de dialogue
        self.EndModal(wx.ID_OK)

    def OnBoutonRotationGauche(self, event):
        self.imgbox.Rotation(False)

    def OnBoutonRotationDroite(self, event):
        self.imgbox.Rotation(True)

    def OnScrollSlider(self, event):
        """ On Slider """
        self.imgbox.SetRatio()

    def OnBoutonReinit(self, event):
        self.slider_ratio.SetValue(100)
        self.imgbox.ReinitImage()

if __name__ == "__main__":
    app = wx.App(0)
    #wx.InitAllImageHandlers()
    frm = MyDialog(None, image="img.jpg")
    frm.ShowModal()
    app.MainLoop()


                                  # PAQUETERÍAS

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

                                  # PROBLEMA 1

print("PROBLEMA 1: Escribe un programa que realice una grafica del valor al que converge la probabilidad de tirar una moneda N veces (hay un resultado para Águila y uno para Sol).")

Ns = []    # Aquí guardamos el número de experimentos
ProbA = [] # Aquí se guardan los valores de la probabilidad de sacar águila.
ProbS = [] # Aquí se guardan los valores de la probabilidad de sacar sol.

for N in range(1,501):  # Definimos el número de experimentos N. Es el CICLO FOR principal.

    # La cantidad de veces que salió águila y sol comienzan en 0.
    aguilas = 0
    soles = 0
    # La probabilidad de obtener cada lado de la moneda comienza en 0 (Opcional).
    pA = 0
    pS = 0

    for i in range(N):
        lanzamiento = rnd.random()  # Definimos el lanzamiento de la moneda con rnd.random.
        if lanzamiento > 0.5:       # Si el número es mayor a 0.5, sumar 1 a "aguilas".
            aguilas += 1
        else:                       # En caso contrario, sumar 1 a "soles".
            soles += 1
        # Es decir, se acumula el número de veces que cayó cada lado de la moneda.

    pA = float(aguilas)/float(N) # Probabilidad de obtener águila.
    pS = float(soles)/float(N)   # Probabilidad de obtener sol.

    Ns.append(N)      # Agregamos cada valor de N en la lista con el mismo nombre.
    ProbA.append(pA)  # Agregamos los valores de pA para cada valor de N en la lista ProbA.
    ProbS.append(pS)  # Agregamos los valores de pS para cada valor de N en la lista ProbS.

plt.plot(Ns,ProbA,'.',color='brown')    # Gráfica de ProbA VS N.
plt.plot(Ns,ProbS,'.',color='gold')     # Gráfica de ProbS VS N.
plt.axhline(0.5,color='black')          # Línea horizontal en P(A,B)=0.5, el cual es el valor al que convergen las probabilidades.
plt.title("Gráfica de $P(A,S)$ vs $N$") # Título de la gráfica. Donde P(A,B) significa "Probabilidad de obtener Águila y Sol"
plt.xlabel("$N$")                       # Título del eje X "Número de experimentos o lanzamientos".
plt.ylabel("$P(A,B)$")                  # Título del eje Y "Probabilidad de obtener Águila y Sol"

plt.show()
                                   # PROBLEMA 2

print("PROBLEMA 2: Escribe un programa que realice una gráfica del valor al que converge la probabilidad de sacar un 3 al tirar un dado de 6 caras N veces.")

Ns_1 = []     # Aquí guardamos el número de experimentos
Prob3 = []  # Aquí se guardan los valores de la probabilidad de obtener un 3 al tirar un dado.

for n in range(1,701):  # Definimos el número de experimentos n. Es el CICLO FOR principal.

    # La cantidad de veces que salió un 3 comienza en 0.
    sacar3 = 0
    # Los valores de la probabilidad de sacar un 3 comienzan en 0 (Opcional).
    #p3 = 0

    for i in range(n):
        lanzamiento = rnd.randint(1,6)  # Se lanza el dado con rnd.randint(a,b) para que devuelva un número entero aleatorio entre 1 y 6.
        if lanzamiento == 3:            # Si el número obtenido es el 3, entonces sumar 1 a "sacar3".
            sacar3 += 1

    # La probabilidad de sacar un 3 se calcula dividiendo el número de veces que salió un 3 entre el número de experimentos.
    p3 = float(sacar3)/float(n)

    Ns_1.append(n)      # Agregamos cada valor de N en la lista con el mismo nombre.
    Prob3.append(p3)  # Agregamos los valores de p3 para cada valor de N en la lista Prob3.

plt.plot(Ns_1,Prob3,'.',color='navy')      # Gráfica de Prob3 VS n.
plt.axhline(1/6,color='orangered')       # Línea horizontal en P(3)=1/6, el cual es el valor al que converge la probabilidad.
plt.title("Gráfica de $P(3)$ vs $n$")    # Título de la gráfica. Donde P(3) significa "Probabilidad de obtener un 3 al tirar un dado"
plt.xlabel("$n$")                        # Título del eje X "Número de experimentos o lanzamientos".
plt.ylabel("$P(3)$")                     # Título del eje Y "Probabilidad de obtener un 3"

plt.show()
                                     # PROBLEMA 3

print("PROBLEMA 3: Escribe un programa que realice una gráfica del valor al que converge la probabilidad de tirar 2 dados de 6 caras N veces y que la suma de los valores sea igual a 8, así como la de no obtenerlo.")

Ns_2 = []           # Aquí guardamos el número de experimentos
ProbSuma8 = []    # Aquí se guardan los valores de la probabilidad de obtener un 8 mediante la suma de dos dados.
ProbNoSuma8 = []  # Aquí se guardan los valores de la probabilidad de no obtener un 8 mediante la suma de dos dados.

for N_1 in range(1,801):  # Definimos el número de experimentos N. Es el CICLO FOR principal.

    # La cantidad de veces que la suma fue 8 comienza en 0, así como la de no obtenerla.
    sacarSuma8 = 0
    sacarNoSuma8 = 0
    # Los valores de la probabilidad de que la suma sea 8 comienza en 0 (Opcional).
    #pSuma8 = 0
    # Los valores de la probabilidad de que la suma no sea 8 comienza en 0 (Opcional).
    #pSumaNo8 = 0

    for i in range(N_1):
        dado_1 = rnd.randint(1,6)  # Se lanzan dos dados con rnd.randint(a,b) para que devuelva un número entero aleatorio entre 1 y 6.
        dado_2 = rnd.randint(1,6)
        if dado_1 + dado_2 == 8:   # Si la suma da 8, sumar 1 a "sacarSuma8".
            sacarSuma8 += 1
        else:                      # En cualquier otro caso, sumar 1 a "sacarNoSuma8".
            sacarNoSuma8 += 1

    # Definición de las probabilidades (eventos favorables/total de eventos).
    pSuma8 = float(sacarSuma8)/float(N_1)
    pNoSuma8 = float(sacarNoSuma8)/float(N_1)

    # Agregamos los valores de "N" y las dos probabilidades en sus respectivas listas.
    Ns_2.append(N_1)
    ProbSuma8.append(pSuma8)
    ProbNoSuma8.append(pNoSuma8)

plt.plot(Ns_2,ProbSuma8,'.',color='navy')         # Gráfica de P(Suma8) VS N.
plt.plot(Ns_2,ProbNoSuma8,'.',color='orangered')  # Gráfica de P(NoSuma8) VS N.
plt.axhline(5/36,color='orangered')             # Línea horizontal en P(Suma8)=5/36, el cual es el valor al que converge la probabilidad.
plt.axhline(31/36,color='blue')                 # Línea horizontal en P(NoSuma8)=31/36, el cual es el valor al que converge la probabilidad.
plt.title("Gráfica de $P(Suma)$ vs $N$")        # Título de la gráfica.
plt.xlabel("$N$")                               # Título del eje X "Número de eventos".
plt.ylabel("$Probabilidad$")                    # Título del eje Y "Probabilidades"

plt.show()

print("A continuación se muestran las dos gráficas anterior por separado:")

print("Probabilidad de que la suma de ambos dados sea igual a 8.")
plt.plot(Ns_2,ProbSuma8,'.',color='green')
plt.axhline(5/36,color='red')
plt.title("$P(d_{1}+d_{2}=8)$ vs $N$")
plt.xlabel("$N$")
plt.ylabel("$Probabilidad$")
plt.show()

print("Probabilidad de que la suma de ambos dados sea diferente de 8.")
plt.plot(Ns_2,ProbNoSuma8,'.',color='navy')
plt.axhline(31/36,color='orangered')
plt.title("$P( d_{1}+d_{2} \in [2,7] \cup [9,12] )$ vs $N$")
plt.xlabel("$N$")
plt.ylabel("$Probabilidad$")
plt.show()


#!/usr/bin/python
# -*-encoding=utf8 -*-
# @Author         : imooc
# @Email          : imooc@foxmail.com
# @Created at     : 2018/11/30
# @Filename       : response.py
# @Desc           :

# 状态码
class ReturnCode:
    SUCCESS = 0
    FAILED = -100
    UNAUTHORIZED = -500
    BROKEN_AUTHORIZED_DATA = -501
    WRONG_PARMAS = -101
    RESOURCE_NOT_FOUND = -102

    @classmethod
    def message(cls, code):
        if code == cls.SUCCESS:
            return 'success'
        elif code == cls.FAILED:
            return 'failed'
        elif code == cls.UNAUTHORIZED:
            return 'unauthorized'
        elif code == cls.WRONG_PARMAS:
            return 'wrong params'
        else:
            return ''

def wrap_json_response(data=None, code=None, message=None):
    response = {}
    if not code:
        code = ReturnCode.SUCCESS
    if not message:
        message = ReturnCode.message(code)
    if data:
        response['data'] = data
    response['result_code'] = code
    response['message'] = message
    return response

class CommonResponseMixin(object):
    @classmethod
    def wrap_json_response(cls, data=None, code=None, message=None):
        response = {}
        if not code:
            code = ReturnCode.SUCCESS
        if not message:
            message = ReturnCode.message(code)
        if data:
            response['data'] = data
        response['result_code'] = code
        response['message'] = message
        return response


from os import system
def welcome(dictionary):
    for item in dictionary:
        if item == "money":
            break
        if dictionary[item] < 150:
            num = dictionary[item]
            if item == "coffee":
                unity = "g"
            else:
                unity = "mL"
            print(f"There's just {num}{unity} of {item}!")
    resposta = input("""
    What would you like?
    Espresso     $ 2.40 80 mL
    Latte        $ 3.45 300 mL
    Cappuccino   $ 2.80 100 mL
    """).title()
    return resposta
def not_enough(quantity, object):
    if object == "coffee":
        unity = "g"
    else:
        unity = "mL"
    vontade = input(f"Sorry, there is not enough {object}, only {quantity} {unity}. Type 'refill' to refill the {object}: ").lower()
    if vontade == "refill":
        colocado = input(f"How much {object} will you put on the machine? ").lower()
        new_colocado = ""
        for char in colocado:
            if char != "m" and char !="l" and char != "g" and char != " ":
                new_colocado += char
        new_colocado = int(new_colocado)
        if "l" in colocado and ("m" not in colocado):
            new_colocado  = new_colocado * 1000
        quantity += new_colocado
    return quantity

def insert_cash(missing):
    if missing == 0:
        print("Please, insert the coins")
    else:
        print(f"Please, insert {missing} dollars")
    quarters = int(input("How many quarters? "))
    dimes = int(input("How many dimes? "))
    nickles = int(input("How many nickles? "))
    pennies = int(input("How many pennies? "))
    cash = quarters * 0.25 + dimes * 0.10 + nickles * 0.05 + pennies * 0.01
    cash = 12 * 0.25 + 4 * 0.10 + 1 * 0.05 + 0 * 0.01
    cash = float("%.2f" %(cash))
    return cash

def check(answer, conteudo):
    falta = 0
    continuar = True
    if answer == "Espresso" or answer == "Latte" or answer == "Cappuccino":
        for item in conteudo["drinks"][answer]["ingredients"]:
            if conteudo[item] < conteudo["drinks"][answer]["ingredients"][item]:
                conteudo[item] = not_enough(conteudo[item], item)
                continuar = False
                break
        if continuar == True:
            for item in conteudo["drinks"][answer]["ingredients"]:
                conteudo[item] -= conteudo["drinks"][answer]["ingredients"][item]
            money = insert_cash(falta)
            price = conteudo["drinks"][answer]["cost"]
            while money < price:
                falta = price - money
                money += insert_cash(falta)
            conteudo["money"] += price
            if money == price:
                print(f"Here is your {answer}. Enjoy!☕")
            else:
                cash_back = money - price
                cash_back = "%.2f" %(cash_back)
                print(f"Here is your {cash_back} dollars in change and your {answer}. Enjoy!☕")
    elif answer == "Report":
        for item in conteudo:
            if item == "coffee":
                unidade = "g"
            elif item == "money":
                unidade = "$"
            elif item == "parar":
                break
            else:
                unidade = "mL"
            valor = conteudo[item]
            print(f"{item}: {valor} "+ unidade)
    elif answer == "Off":
        conteudo["parar"] = True
    return conteudo

content = {"milk": 500, "water": 500, "coffee": 700, "money": 0, "parar": False,
"drinks": {
"Espresso": {"ingredients": {"water": 80, "coffee": 20,}, "cost": 2.4},
"Latte": {"ingredients": {"water": 100, "milk": 100, "coffee": 50,}, "cost": 3.45},
"Cappuccino": {"ingredients": {"water": 100, "milk": 20, "coffee": 20,}, "cost": 2.8}
}
}
while content["parar"] != True:
    content = check(welcome(content), content)
    input()
    system("cls")


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

# import utils

def ls_solver(zeta, jacobian, covariance, x_init, epsilon=1e-6, max_num_iterations=10e3, force_full_calc=False,
              plot_progress=False):
    """
    Computes the least square solution for geolocation processing.

    Ported from MATLAB Code.

    Nicholas O'Donoughue
    14 January 2021

    :param zeta: Measurement vector function handle (accepts n_dim vector of source position estimate, responds with
                 error between received and modeled data vector)
    :param jacobian: Jacobian matrix function handle (accepts n_dim vector of source position estimate, and responds
                     with n_dim x n_sensor Jacobian matrix)
    :param covariance: Measurement error covariance matrix
    :param x_init: Initial estimate of source position
    :param epsilon: Desired position error tolerance (stopping condition)
    :param max_num_iterations: Maximum number of LS iterations to perform
    :param force_full_calc: Forces all max_num_iterations to be calculated
    :param plot_progress: Binary flag indicating whether to plot error/pos est over time
    :return x: Estimated source position.
    :return x_full: Iteration-by-iteration estimated source positions
    """

    # Parse inputs
    n_dims = np.size(x_init)

    # Initialize loop
    current_iteration = 0
    error = np.inf
    x_full = np.zeros(shape=(n_dims, max_num_iterations))
    x_prev = x_init
    x_full[:, current_iteration] = x_prev

    # Find the lower triangular cholesky decomposition of the covariance matrix
    covariance_lower = np.linalg.cholesky(covariance)

    # Initialize Plotting
    if plot_progress:
        _, ax = plt.subplots()
        plt.xlabel('Iteration Number')
        plt.ylabel('Change in Position Estimate')
        plt.yscale('log')

    # Divergence Detection
    num_expanding_iterations = 0
    max_num_expanding_iterations = 10
    prev_error = np.inf

    # Loop until either the desired tolerance is achieved or the maximum number of iterations have occurred
    while current_iteration < (max_num_iterations-1) and (force_full_calc or error >= epsilon):
        current_iteration += 1

        # Evaluate Residual and Jacobian Matrix
        y_i = zeta(x_prev)
        jacobian_i = np.squeeze(jacobian(x_prev))  # Use the squeeze command to drop the third dim (n_source = 1)

        # Compute delta_x^(i), according to 10.20
        # Using Cholesky decomposition:
        #    C = L@L', we solved for L outside the loop
        # [J @ C^{-1} @ J.T]^{-1} @ J @ C^{-1} @ y is
        # rewritten
        # [ a.T @ a ] ^{-1} @ a.T @ b
        # where a and b are solved via forward substitution
        # from the lower triangular matrix L.
        #   L @ a = J.T
        #   L @ b = y
        a = scipy.linalg.solve_triangular(covariance_lower, jacobian_i.T, lower=True)
        b = scipy.linalg.solve_triangular(covariance_lower, y_i, lower=True)
        # Then, we solve the system
        #  (a.T @ a) @ delta_x = a.T @ b
        delta_x, _, _, _ = np.linalg.lstsq(a.T @ a, a.T @ b, rcond=None)

        # Update predicted location
        x_full[:, current_iteration] = x_prev + np.squeeze(delta_x)

        # Update variables
        x_prev = x_full[:, current_iteration]
        error = np.linalg.norm(delta_x)

        if plot_progress:
            plt.plot(current_iteration, error, '.')

        # Check for divergence
        if error <= prev_error:
            num_expanding_iterations = 0
        else:
            num_expanding_iterations += 1
            if num_expanding_iterations >= max_num_expanding_iterations:
                # Divergence detected
                x_full[:, current_iteration:] = np.nan
                break

        prev_error = error

    # Bookkeeping
    if not force_full_calc:
        x_full[:, current_iteration+1:] = x_full[:, :current_iteration]

    x = x_full[:, -1]

    return x, x_full

def gd_solver(y, jacobian, covariance, x_init, alpha=0.3, beta=0.8, epsilon=1.e-6, max_num_iterations=10e3,
              force_full_calc=False, plot_progress=False):
    """
    Computes the gradient descent solution for localization given the provided measurement and Jacobian function
    handles, and measurement error covariance.

    Ported from MATLAB code.

    Nicholas O'Donoughue
    14 January 2021

    :param y: Measurement vector function handle (accepts n_dim vector of source position estimate, responds with error
              between received and modeled data vector)
    :param jacobian: Jacobian matrix function handle (accepts n_dim vector of source position estimate, and responds
                     with n_dim x n_sensor Jacobian matrix
    :param covariance: Measurement error covariance matrix
    :param x_init: Initial estimate of source position
    :param alpha: Backtracking line search parameter
    :param beta: Backtracking line search parameter
    :param epsilon: Desired position error tolerance (stopping condition)
    :param max_num_iterations: Maximum number of LS iterations to perform
    :param force_full_calc: Forces all max_num_iterations to be executed
    :param plot_progress: Binary flag indicating whether to plot error/pos est over time
    :return x: Estimated source position
    :return x_full: Iteration-by-iteration estimated source positions
    """
    # Parse inputs
    n_dims = np.size(x_init)

    # Initialize loop
    current_iteration = 0
    error = np.inf
    x_full = np.zeros(shape=(n_dims, max_num_iterations))
    x_prev = x_init
    x_full[:, current_iteration] = x_prev

    # Pre-compute covariance matrix inverses
    covariance_lower = np.linalg.cholesky(covariance)

    # Cost Function for Gradient Descent
    def cost_fxn(z):
        this_y = y(z)
        l_inv_y = scipy.linalg.solve_triangular(covariance_lower, this_y, lower=True)
        return np.conj(l_inv_y.T) @ l_inv_y

    # Initialize Plotting
    if plot_progress:
        fig_plot, ax_set = plt.subplots(ncols=1, nrows=2)
        plt.xlabel(ax_set[0], 'Iteration Number')
        plt.ylabel(ax_set[0], 'Change in Position Estimate')
        plt.yscale(ax_set[0], 'log')

        plt.xlabel(ax_set[1], 'x')
        plt.ylabel(ax_set[1], 'y')
    else:
        ax_set = None  # This removes a 'variable possibly unset' warning

    # Divergence Detection
    num_expanding_iterations = 0
    max_num_expanding_iterations = 5
    prev_error = np.inf

    # Loop until either the desired tolerance is achieved or the maximum
    # number of iterations have occurred
    while current_iteration < (max_num_iterations-1) and (force_full_calc or error >= epsilon):
        current_iteration += 1

        # Evaluate Residual and Jacobian Matrix
        y_i = y(x_prev)
        jacobian_i = np.squeeze(jacobian(x_prev))  # Use squeeze to remove third dimension (n_source=1)

        # Compute Gradient and Cost function
        a = scipy.linalg.solve_triangular(covariance_lower, jacobian_i.T, lower=True)
        b = scipy.linalg.solve_triangular(covariance_lower, y_i, lower=True)
        grad = -2 * a.T @ b

        # Descent direction is the negative of the gradient
        del_x = -np.squeeze(grad/np.linalg.norm(grad))

        # Compute the step size
        t = backtracking_line_search(cost_fxn, x_prev, grad, del_x, alpha, beta)

        # Update x position
        x_full[:, current_iteration] = x_prev + t*del_x

        # Update variables
        x_prev = x_full[:, current_iteration]
        error = t

        if plot_progress:
            plt.plot(ax_set[0], current_iteration, error, '.')
            plt.plot(ax_set[1], x_full[0, np.arange(current_iteration)], x_full[1, np.arange(current_iteration)], '-+')

        # Check for divergence
        if error <= prev_error:
            num_expanding_iterations = 0
        else:
            num_expanding_iterations += 1
            if num_expanding_iterations >= max_num_expanding_iterations:
                # Divergence detected
                x_full[:, current_iteration:] = np.NaN
                break

        prev_error = error

    # Bookkeeping
    if not force_full_calc:
        x_full[:, current_iteration+1:] = x_full[:, :current_iteration]

    x = x_full[:, -1]

    return x, x_full

def backtracking_line_search(f, x, grad, del_x, alpha=0.3, beta=0.8):
    """
    # Performs backtracking line search according to algorithm 9.2 of
    # Stephen Boyd's, Convex Optimization

    Ported from MATLAB Code

    Nicholas O'Donoughue
    14 January 2021

    :param f: Function handle to minimize
    :param x: Current estimate of x
    :param grad: Gradient of f at x
    :param del_x: Descent direction
    :param alpha: Constant between 0 and 0.5 (default=0.3)
    :param beta: Constant between 0 and 1 (default=0.8)
    :return t: Optimal step size for the current estimate x.
    """

    # Initialize the search parameters and direction
    t = 1
    starting_val = np.squeeze(f(x))
    slope = np.squeeze(np.conjugate(grad.T) @ del_x)

    # Make sure that x, del_x are arrays (not matrices)
    del_x = np.squeeze(del_x)
    x = np.squeeze(x)
    # Make sure the starting value is large enough
    while f(x+t*del_x) < starting_val+alpha*t*slope:
        t = 2*t

    # Conduct the backtracking line search
    while f(x+t*del_x) > starting_val+alpha*t*slope:
        t = beta*t

    return t

def ml_solver(ell, x_ctr, search_size, epsilon):
    """
    Execute ML estimation through brute force computational methods.

    Ported from MATLAB code.

    Nicholas O'Donoughue
    14 January 2021

    :param ell: Function handle for the likelihood of a given position must accept x_ctr (and similar sized vectors)
                as the sole input.
    :param x_ctr: Center position for search space (x, x/y, or z/y/z).
    :param search_size: Search space size (same units as x_ctr)
    :param epsilon: Search space resolution (same units as x_ctr)
    :return x_est: Estimated minimum
    :return A: Likelihood computed at each x position in the search space
    :return x_grid: Set of x positions for the entire search space (M x N) for N=1, 2, or 3.
    """

    # Set up the search space
    x_set, x_grid, out_shape = utils.make_nd_grid(x_ctr, search_size, epsilon)

    # Evaluate the likelihood function at each coordinate in the search space
    likelihood = ell(x_set.T)

    # Find the peak
    idx_pk = likelihood.argmax()
    x_est = x_set[idx_pk]

    return x_est, likelihood, x_grid

def bestfix(pdfs, x_ctr, search_size, epsilon):
    """
    Based on the BESTFIX algorithm, invented in 1990 by Eric Hodson (R&D Associates, now with Naval Postgraduate
    School).  Patent is believed to be in the public domain.

    Ref:
     Eric Hodson, "Method and arrangement for probabilistic determination of a target location,"
     U.S. Patent US5045860A, 1990, https://patents.google.com/patent/US5045860A

    Ported from MATLAB Code.

    Nicholas O'Donoughue
    14 January 2021

    :param pdfs: Lx1 cell list of PDF functions, each of which represents the probability that an input position
                 (Ndim x 3 array) is the true source position for one of the measurements.
    :param x_ctr: Center position for search space (x, x/y, or z/y/z).
    :param search_size: Search space size (same units as x_ctr)
    :param epsilon: Search space resolution (same units as x_ctr)
    :return x_est: Estimated position
    :return result: Likelihood computed at each x position in the search space
    :return x_grid: Set of x positions for the entire search space (M x N) for N=1, 2, or 3.
    """

    # Set up the search space
    x_set, x_grid, out_shape = utils.make_nd_grid(x_ctr, search_size, epsilon)

    # Apply each PDF to all input coordinates and then multiply across PDFs
    result = np.asarray([np.prod(np.asarray([this_pdf(this_x) for this_pdf in pdfs])) for this_x in x_set])

    # Reshape
    result = np.reshape(result, out_shape)

    # Find the highest scoring position
    idx_pk = result.argmax()
    x_est = x_set[idx_pk]

    return x_est, result, x_grid


from sources.array_cipher import *

def test_output_dimensions():
    input_array = np.random.rand(10,10,3)
    array_under_test = array_cipher(input_array, "T")

    returned_array = array_under_test.get_ciphered_array()

    assert input_array.shape == returned_array.shape

def test_plaintext_parsing():
    input_array = np.random.rand(10,10,3)
    array_under_test = array_cipher(input_array, "TEST")

    actual = array_under_test.plaintext_to_array()
    expected = np.array([84,69,83,84])

    assert len(actual) == len(expected)
    assert all([a == b for a, b in zip(actual, expected)])


from tkinter import *
from PIL import ImageTk, Image

root = Tk()
root.title("Learning Tkinter")
root.iconbitmap("./images/quality.ico")
root.geometry("1200x400")

my_entries = []

def something():
    entry_list=""
    for entries in my_entries:
        entry_list += str(entries.get()) + "\n"
        myLabel.config(text=entry_list)

for y in range(5):
    for x in range(5):
        my_entry = Entry(root, bd=4)
        my_entry.grid(row=y, column=x, pady=20, padx=5)
        my_entries.append(my_entry)

myButton = Button(root, text="Click Me!", command=something)
myButton.grid(row=6, column=0, pady=10)

myLabel = Label(root, text="")
myLabel.grid(row=7, column=0, pady=20)

root.mainloop();


#srinuneelapala

import requests
file_url = "http://10.11.4.25/2019-QPandKeys/Sem1/AT-1/CSE/QP's/E2/E2CSE-"
folder= 'C:\\Users\PYTHON\\Desktop\\OOPS-Weekend'
for i in range(1,9):
    sub='\\OOPS-AT'+str(i)+".pdf"
    url=file_url+sub
    r = requests.get(url)

    with open(folder+sub,"wb") as pdf:
        pdf.write(r.content)


from fastapi import FastAPI
from fastapi import Depends
from fastapi import HTTPException
from fastapi.responses import JSONResponse
from fastapi.responses import RedirectResponse

from Services.authenticate import authenticate
from Services.atualizacaoBancoDeDadosService import AtualizacaoBancoDeDadosService
from Services.listagemParceirosService import ListagemParceirosService
from Services.dadosParceiros import DadosParceiros

from models import BodyAtualizacaoParceiros

app = FastAPI()

@app.get("/", include_in_schema=False)
async def redirect_to_docs():
    return RedirectResponse(url="/docs")

@app.post("/atualizacaoParceiros")
async def atualiza_banco_de_dados(Body: BodyAtualizacaoParceiros,token: str = Depends(authenticate)):

    SERVICE = AtualizacaoBancoDeDadosService()

    endereco_csv = Body.url_csv_hosteado

    retorno = SERVICE.verifica_base_cnpjs(endereco_csv)
    base_input = retorno[0]
    validador = retorno[1]

    if validador == False:
        content = {"mensagem" : "CSV contem cpf na coluna cnpj, ou esta vazio, ou esta corrompido - Reveja seus dados", "response": {}}
        return JSONResponse(content=content, status_code=400)

    base_input = SERVICE.renomeia_colunas_data_frame(base_input)
    SERVICE.atualiza_banco_de_dados_via_data_frame(base_input,'parceiros','cnpj')

    base_ceps = SERVICE.pega_infs_ceps(base_input)
    SERVICE.atualiza_banco_de_dados_via_data_frame(base_ceps,'infs_cep_parceiros','cep')

    content = {"mensagem" : "Sucesso", "response": {}}
    return JSONResponse(content=content, status_code=200)

@app.get("/ListagemParceiros")
async def listagem(token: str = Depends(authenticate)):

    SERVICE = ListagemParceirosService()
    parceiros_atuais = SERVICE.listagem()

    return JSONResponse(content=parceiros_atuais, status_code=200)

@app.get("/DadosParceiros/{cnpj}")
async def dados_parceiros(cnpj: int,token: str = Depends(authenticate)):

    SERVICE = DadosParceiros()
    dados_parceiros = SERVICE.retorna_infs_parceiros(str(cnpj))
    dados_parceiros = dados_parceiros.to_dict(orient='records')

    return JSONResponse(content=dados_parceiros, status_code=200)


from explorer.credentials import CredentialsManager
import pytest
from moto import mock_secretsmanager
import boto3

@pytest.fixture
def create_mocked_secret_manager_connection():
    with mock_secretsmanager():
        yield boto3.session.Session().client(
            service_name="secretsmanager", region_name="us-east-1"
        )

@pytest.fixture
def create_test_secret(create_mocked_secret_manager_connection):
    create_mocked_secret_manager_connection.create_secret(
        Name="mock_secret", SecretString="""{"mock_secret_key": "mock_secret_value"}""",
    )

def test_retrieve_secret_string(
    monkeypatch, create_mocked_secret_manager_connection, create_test_secret
):
    def get_mocked_secret_manager(*args, **kwargs):
        return create_mocked_secret_manager_connection

    monkeypatch.setattr(
        CredentialsManager, "_create_boto_client", get_mocked_secret_manager,
    )

    credentials_client = CredentialsManager("mock_secret")

    assert credentials_client.retrieve_secret_string() == {
        "mock_secret_key": "mock_secret_value"
    }

def test_unexisting_secret():
    credentials_client = CredentialsManager("secret_that_doesnt_exist")

    with pytest.raises(Exception) as excinfo:
        credentials_client.retrieve_secret_string()

    assert "ResourceNotFoundException" in str(excinfo.errisinstance)
    assert "Secrets Manager can't find the specified secret" in str(excinfo.value)

def test_wrong_region():
    with pytest.raises(Exception) as excinfo:
        CredentialsManager(
            "some_secret", "region_that_doesnt_exist"
        ).retrieve_secret_string()

    assert (
        "Invalid endpoint: https://secretsmanager.region_that_doesnt_exist.amazonaws.com"
        in str(excinfo.value)
    )


from django.conf.urls.defaults import patterns, include,url
import settings
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    #url(r'^polls/$', 'polls.views.producto_view'),
    #url(r'^polls/$', 'polls.views.Contatcto_view'),

    url(r'^menu/$','polls.views.menu_view',name="menu"),
    url(r'^productos/$', 'polls.views.add_producto_view',name="addproductos"),
    url(r'^contactos/','polls.views.Contatcto_view',name="contactos"),
    url(r'^inicial/','polls.views.index',name="index"),
    url(r'^ver_productos/','polls.views.producto_view',name="ver_productos"),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.MEDIA_ROOT}),
)


from datetime import date

class FileManager:
    """A class designed to save data into the file."""

    def __init__(self):
        """Necessary attributes initialization."""
        self.filename = 'best_score.txt'
        self.filename_path = 'data/' + self.filename

        self.data = {}

    def save_data(self, score):
        """Saving the data with the highest score into the file."""
        if self._check_data(score):
            # Get the current date and time.
            date_now = date.today().strftime("%d-%m-%Y")

            # Preparation of data for saving.
            self.data['best_score'] = str(score)
            self.data['date'] = date_now

            with open(self.filename_path, 'w') as file_object:
                for key, value in self.data.items():
                    file_object.write(key + ': ' + value + '\n')

    def _check_data(self, score):
        """Checking the current data in the file."""
        try:
            with open(self.filename_path, 'r') as file_object:
                contents = file_object.read()
        except FileNotFoundError:
            return True

        # Preparation of data for saving.
        words = contents.split()
        try:
            self.data['best_score'] = words[1]
        except IndexError:
            return True

        # Convert a score to a number.
        best_score = int(self.data['best_score'])
        current_score = int(score)

        # Checking if a new record has been set.
        if current_score > best_score:
            return True

        return False


import os
import sys
import argparse
import yaml
import httpx

# Parse arguments
parser = argparse.ArgumentParser(description='Build functions')
parser.add_argument('-r', '--repo', default='', nargs='?', help='Repo')
parser.add_argument('-t', '--token', default='', nargs='?', help='Token')
arguments = parser.parse_args()

# Create environments folder
envs_path = '/opt/environments'
if not os.path.isdir(envs_path):
    os.mkdir(envs_path)

# Pull or clone repo
if arguments.repo and arguments.token:
    # Define repo auxiliar names
    full_repo_name = '.'.join(arguments.repo.split('https://github.com/')[1].split('.')[:-1])
    repo_name = '.'.join(arguments.repo.split('/')[-1].split('.')[:-1])

    # Clone into environments folder
    if os.path.isdir(os.path.join(envs_path, repo_name)):
        os.system('cd %s/%s && git pull origin main' % (envs_path, repo_name))
    else:
        os.system('git clone https://%s@github.com/%s %s/%s' % (arguments.token, full_repo_name, envs_path, repo_name))

    # Get configuration
    url = 'https://%s@raw.githubusercontent.com/%s/main/config.yaml' % (arguments.token, full_repo_name)
    config = yaml.load(httpx.get(url).text, Loader=yaml.Loader)

    # Install apt packages
    requirements_apt = ' '.join(config.get('requirements_apt', []))
    if requirements_apt:
        os.system('apt-get update && apt-get install --no-install-recommends -q -y %s' % (requirements_apt))

    # Install pip packages
    requirements_pip = ' '.join(config.get('requirements_pip', []))
    if requirements_pip:
        os.system('pip3 install %s' % (requirements_pip))

    # Install ops
    for op in config.get('ops', []):
        os.system('curl -s https://raw.githubusercontent.com/iortio/get_op/main/get_op.py | sudo python3 - -r %s -t %s' % (op, arguments.token))

    # Install jobs
    for job in config.get('jobs', []):
        os.system('curl -s https://raw.githubusercontent.com/iortio/get_op/main/get_job.py | sudo python3 - -r %s -t %s' % (job, arguments.token))


import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
path_json = 'credentials-serv-acc.json'

creds_auth = ServiceAccountCredentials\
    .from_json_keyfile_name(path_json, ['https://www.googleapis.com/auth/spreadsheets',
                                        'https://www.googleapis.com''/auth/drive'])\
    .authorize(httplib2.Http())

service = build('sheets', 'v4', http=creds_auth)

sheet_id = '1k40lGVdZNvytbByH2Ap45ojFGJfjLrG-MIQEBIUVIJY'

sss = service.spreadsheets()

r = sss.values().get(spreadsheetId=sheet_id, range='A2:E').execute()
print(r)


from __future__ import unicode_literals

import json
import logging

from . import resource

logger = logging.getLogger("timesketch_api.view")

class View(resource.BaseResource):
    """Saved view object.

    Attributes:
        id: Primary key of the view.
        name: Name of the view.
    """

    def __init__(self, view_id, view_name, sketch_id, api):
        """Initializes the View object.

        Args:
            view_id: Primary key ID for the view.
            view_name: The name of the view.
            sketch_id: ID of a sketch.
            api: Instance of a TimesketchApi object.
        """
        logger.info(
            "View objects will be deprecated soon, consider transitioning "
            "into using the search.Search object instead"
        )
        self.id = view_id
        self.name = view_name
        resource_uri = "sketches/{0:d}/views/{1:d}/".format(sketch_id, self.id)
        super().__init__(api, resource_uri)

    def _get_top_level_attribute(self, name, default_value=None, refresh=False):
        """Returns a top level attribute from a view object.

        Args:
            name: String with the attribute name.
            default_value: The default value if the attribute does not exit,
                defaults to None.
            refresh: If set to True then the data will be refreshed.

        Returns:
            The dict value of the key "name".
        """
        view = self.lazyload_data(refresh_cache=refresh)
        view_objects = view.get("objects")
        if not view_objects:
            return default_value
        if not len(view_objects) == 1:
            return default_value

        first_object = view_objects[0]
        return first_object.get(name, default_value)

    @property
    def description(self):
        """Property that returns the description value of a view.

        Returns:
            Description of the view as a string.
        """
        return self._get_top_level_attribute("description", default_value="")

    @property
    def user(self):
        """Property that returns the username of the view creator.

        Returns:
            A string with the username of the user generating the view.
        """
        user_dict = self._get_top_level_attribute("user", default_value={})
        username = user_dict.get("username")
        if not username:
            return "System"
        return username

    @property
    def query_string(self):
        """Property that returns the views query string.

        Returns:
            OpenSearch query as string.
        """
        return self._get_top_level_attribute("query_string", default_value="")

    @property
    def query_filter(self):
        """Property that returns the views filter.

        Returns:
            OpenSearch filter as a dict.
        """
        query_filter_string = self._get_top_level_attribute(
            "query_filter", default_value=""
        )
        if not query_filter_string:
            return ""
        return json.loads(query_filter_string)

    @property
    def query_dsl(self):
        """Property that returns the views query DSL.

        Returns:
            OpenSearch DSL as a dict.
        """
        dsl_string = self._get_top_level_attribute("query_dsl", default_value="")
        if not dsl_string:
            return ""
        return json.loads(dsl_string)


from functools import partial
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
from A_star_search import *
from graph import *
from time import sleep

class App:
    def __init__(self):
        self.a_star = AStarSearch()
        self.graph = Graph()

        self.parameters = {}
        self.clear_buttons = []

        self.master = tk.Tk()
        self.master.title("A* visualization")
        #self.master.geometry("400x200")
        self.img = tk.PhotoImage()
        button_frame = tk.Frame(self.master)

        size = tk.Label(button_frame, text="Size: ")
        size.grid(row=0,column=0)
        size_entry = tk.Entry(button_frame, width = 10)
        size_entry.insert(tk.END,"5")
        self.parameters["Size"] = size_entry
        size_entry.grid(row=0,column=1)

        btn_resize = tk.Button(button_frame, text="Resize", command=lambda: self.resize(int(size_entry.get())))
        btn_resize.grid(row=1,column=0)

        btn_place_start = tk.Button(button_frame, text="Place Start",  width=20, command=self.placeStart)
        btn_place_start.grid(row=2,columnspan=2, pady=10)

        btn_place_end = tk.Button(button_frame, text="Place End",  width=20, command=self.placeEnd)
        btn_place_end.grid(row=3,columnspan=2, pady=10)

        #btn_place_barriers = tk.Button(button_frame, text="Place Barriers", width=20, command=self.placeBarriers)
        #btn_place_barriers.grid(row=4,columnspan=2,pady=10)

        heuristic_label = tk.Label(button_frame, text="Heuristic: ")
        options = ["City Block", "Euclidean"]
        heuristic_var = tk.StringVar(button_frame)
        heuristic_var.set(options[0])
        heuristic_menu = tk.OptionMenu(button_frame, heuristic_var, *options)
        self.parameters["Heuristic"]=heuristic_menu
        heuristic_menu.config(width=8)
        #heuristic_combobox = ttk.Combobox(button_frame)
        #heuristic_combobox['values'] = ("City Block", "Euclidean")
        #heuristic_combobox.current(0)
        heuristic_label.grid(row=4,column=0,pady=10)
        heuristic_menu.grid(row=4,column=1,pady=10)

        speed_label = tk.Label(button_frame, text="Speed: ")
        speed_options = ["Slow", "Medium", "Fast", "Very Fast"]
        speed_var = tk.StringVar(button_frame)
        speed_var.set(speed_options[1])
        speed_menu = tk.OptionMenu(button_frame, speed_var, *speed_options)
        self.parameters["Speed"]=speed_menu
        speed_menu.config(width=8)
        speed_label.grid(row=5,column=0,pady=10)
        speed_menu.grid(row=5,column=1,pady=10)

        btn_clear = tk.Button(button_frame, text="Clear", width=20, command=self.clearPath)
        btn_clear.grid(row=6,columnspan=2,pady=10)
        self.clear_buttons.append(btn_clear)

        btn_clear_all = tk.Button(button_frame, text="Clear All", width=20,command=self.clearGraph)
        btn_clear_all.grid(row=7,columnspan=2,pady=10)
        self.clear_buttons.append(btn_clear_all)

        btn_go = tk.Button(button_frame, text="Go!", width=20, command=lambda: self.go(heuristic_var.get(), speed_var.get()))
        btn_go.grid(row=8, columnspan=2,pady=10)

        button_frame.grid(row=0,column=0, padx=2)

        self.graph_frame = tk.Frame(self.master)
        self.graph_buttons = self.buildGraphFrame()
        self.graph_frame.grid(row=0,column=1)

    def run(self):
        self.master.mainloop()

    def placeStart(self):
        self.disableButtons()

        size = self.graph.size

        for i in range(size):
            for j in range(size):
                self.graph_buttons[i][j].configure(command = partial(self.colorButtonEndOrStart, (i,j), Spaces.START))

    def placeEnd(self):
        self.disableButtons()

        size = self.graph.size

        for i in range(size):
            for j in range(size):
                self.graph_buttons[i][j].configure(command = partial(self.colorButtonEndOrStart, (i,j), Spaces.END))

    def colorButtonEndOrStart(self, position, endorstart):
        result = self.graph.setEndPoint(position, endorstart)

        if result == 1:

            if endorstart == Spaces.END:
                self.graph_buttons[position[0]][position[1]].configure(bg="red")
            elif endorstart == Spaces.START:
                self.graph_buttons[position[0]][position[1]].configure(bg="green")
            self.enableBarrierToggles()
            self.enableButtons()

    def enableClearButtons(self):
        for c in self.clear_buttons:
            c.configure(state="normal")

    def enableButtons(self):
        for c in self.master.winfo_children()[0].winfo_children():
                c.configure(state="normal")

    def disableButtons(self):
        for c in self.master.winfo_children()[0].winfo_children():
                c.configure(state="disable")

    def placeBarriers(self):
        pass

    def toggleBarrier(self, position):
        res = self.graph.toggleBarrier(position)

        if res == 0:
            self.graph_buttons[position[0]][position[1]].configure(bg="tan")
        elif res == 1:
            self.graph_buttons[position[0]][position[1]].configure(bg="gray")
        elif res == -1:
            pass

    def clearGraph(self):
        self.enableButtons()
        self.graph.resetMatrix()
        size = self.graph.size

        for i in range(size):
            for j in range(size):
                if i == 0 and j == 0:
                    self.graph_buttons[i][j].configure(bg="green")
                elif i == size-1 and j == size-1:
                    self.graph_buttons[i][j].configure(bg="red")
                else:
                    self.graph_buttons[i][j].configure(bg="tan")

    def clearPath(self):
        self.enableButtons()
        size = self.graph.size
        for i in range(size):
            for j in range(size):
                if self.graph.getPosition(i,j) == Spaces.START:
                    self.graph_buttons[i][j].configure(bg="green")
                elif self.graph.getPosition(i,j) == Spaces.END:
                    self.graph_buttons[i][j].configure(bg="red")
                elif self.graph.getPosition(i,j) == Spaces.BARRIER:
                    self.graph_buttons[i][j].configure(bg="gray")
                else:
                    self.graph_buttons[i][j].configure(bg="tan")

    def go(self, heuristic, speed):

        speeds = {"Slow":0.3, "Medium":0.2, "Fast": 0.1, "Very Fast": 0.05}
        s = speeds[speed]

        self.disableButtons()

        if heuristic == "Euclidean":
            h = EuclideanHeuristic
        else:
            h = CityBlockHeuristic
        self.a_star.setGraph(self.graph.matrix)
        self.a_star.setHeuristic(h)

        self.a_star.startSearch(self.graph.start, self.graph.end)

        n = None

        while n == None:
            n = self.a_star.iterateSearch(self.graph.end)
            #s.enter(0.2, 1, self.colorExploredSet, (self.a_star.explored_set,))
            #s.run()
            sleep(s)
            self.colorExploredSet(self.a_star.explored_set)

        if n == TERMINATE:
            pass
        else:
            self.colorPath(n, self.graph.start, self.graph.end)
        self.a_star.clearSearch()

        self.enableClearButtons()

    def colorExploredSet(self, explored_set):

        #for n in explored_set:
        x = explored_set[-1].position[0]
        y = explored_set[-1].position[1]
        #self.graph_buttons[x][y].after(1000, lambda: self.graph_buttons[x][y].configure(bg="blue"))
        self.graph_buttons[x][y].configure(bg="blue")
        self.master.update()

    def colorPath(self, node, start, end):
        while node != None:
            x = node.position[0]
            y = node.position[1]
            self.graph_buttons[x][y].configure(bg="orange")
            node = node.parent

        self.graph_buttons[start[0]][start[1]].configure(bg="green")
        self.graph_buttons[end[0]][end[1]].configure(bg="red")

    def resize(self, new_size):
        if new_size > MAX_SIZE or new_size < MIN_SIZE:
            messagebox.showerror("Size error", f"Input size must be {MIN_SIZE} <= size <= {MAX_SIZE}.")
        else:
            self.graph.resizeMatrix(new_size)
            self.graph_frame.destroy()
            self.graph_frame = tk.Frame(self.master)
            self.graph_buttons = self.buildGraphFrame()
            self.graph_frame.grid(row=0,column=1)

    def buildGraphFrame(self):
        size = self.graph.size

        buttons = []

        for i in range(size):
            buttons.append([])
            for j in range(size):

                square_button = tk.Button(self.graph_frame, image=self.img)

                if self.graph.getPosition(i,j) == Spaces.START:
                    square_button.configure(bg="green")
                elif self.graph.getPosition(i,j) == Spaces.END:
                    square_button.configure(bg="red")
                elif self.graph.getPosition(i,j) == Spaces.BARRIER:
                    square_button.configure(bg="gray", command=partial(self.toggleBarrier, (i,j)))
                else:
                    square_button.configure(bg="tan", command=partial(self.toggleBarrier, (i,j)))

                square_button.config(width=150/ size, height = 150 /size)
                square_button.grid(column=j,row=i)
                buttons[i].append(square_button)

        return buttons

    def enableBarrierToggles(self):
        size = self.graph.size
        for i in range(size):
            for j in range(size):
                if self.graph.getPosition(i,j) == Spaces.START:
                    self.graph_buttons[i][j].configure(bg="green")
                elif self.graph.getPosition(i,j) == Spaces.END:
                    self.graph_buttons[i][j].configure(bg="red")
                elif self.graph.getPosition(i,j) == Spaces.BARRIER:
                    self.graph_buttons[i][j].configure(bg="gray", command=partial(self.toggleBarrier, (i,j)))
                else:
                    self.graph_buttons[i][j].configure(bg="tan", command=partial(self.toggleBarrier, (i,j)))


def premik(ukaz, x, y, smer):
    smeri = "NESW"
    premiki = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    ismer = smeri.index(smer)
    if ukaz == "R":
        smer = smeri[(ismer + 1) % 4]
    elif ukaz == "L":
        smer = smeri[(ismer - 1) % 4]
    else:
        dx, dy = premiki[ismer]
        x += dx * ukaz
        y += dy * ukaz
    return x, y, smer

def izvedi(ime_datoteke):
    trojke = [(0, 0, 'N')]
    ukazi = []
    datoteka = open(ime_datoteke)
    for vrstica in datoteka:
        n = vrstica.strip()
        if n == 'DESNO' :
            ukazi.append("R")
        elif n == 'LEVO' :
            ukazi.append("L")
        else:
            ukazi.append(int(n[7:]))
    for ukaz in ukazi:
        for x, y, smer in trojke:
            a = premik(ukaz, x, y, smer)
        trojke.append(a)
    datoteka.close()
    return trojke

def opisi_stanje(x, y, smer):
    smeri = {"N" : "^", "S" : "v", "E" : ">", "W" : "<"}
    return ("{: >3}:{: <3}{: >2}".format(x, y, smeri[smer]))

def prevedi(ime_vhoda, ime_izhoda):
    datoteka = open(ime_izhoda, "w")
    for x, y, smer in izvedi(ime_vhoda):
        datoteka.write(opisi_stanje(x, y, smer)+"\n")
    datoteka.close()


lines = open("input.txt").read().splitlines()

molecule = lines[-1]

substitutions = dict()
for l in lines:
    if '=>' not in l:
        continue
    l = l.split()
    if l[0] in substitutions:
        substitutions[l[0]].append(l[-1])
    else:
        substitutions[l[0]] = [l[-1]]

molecules = set()
for sub in substitutions:
    l = len(sub)
    for n in range(l, len(molecule)+1):
        if molecule[n-l:n] == sub:
            for s in substitutions[sub]:
                molecules.add(molecule[:n-l] + s + molecule[n:])

print("part1:", len(molecules))


#!/usr/bin/python2.7

import os,ConfigParser
from mplayer import Player, CmdPrefix
from random import randint
from time import sleep

conf_loc = os.path.expanduser("~/.config/alarm/alarm.conf")
conf = ConfigParser.SafeConfigParser()
conf.read(conf_loc)

music = conf.get('player','music_dir')
randomize = conf.getboolean('player','randomize')
working_dir = conf.get('player','working_dir')

def snooze(player,minutes=15):
    '''
    Pauses playback for minutes.
    Defaults to 15 minutes.
    '''
    player.pause()
    #Convert minutes to seconds for sleep()
    sleep(minutes*60)
    player.pause()

def get_songs(music_dir):
    """
    Returns a list of all songs in
    music_dir and subdirectories.
    Songs are in absolute path format
    """
    songs = []
    for entry in os.walk(music_dir):
        for song in entry[2]:
            songs.append(os.path.join(entry[0],song))
    return songs

def start_playback(songs_list,randomize_songs):
    """
    Initalizes the player and begins playback.
    Player must be assigned else it's garbage collected.
    """

    Player.cmd_prefix = CmdPrefix.PAUSING_KEEP
    player = Player('-loop -1')

    if randomize_songs:
        rand_song= randint(0,len(songs_list)-1)
        player.loadfile(songs_list[rand_song])
    else:
        player.loadfile(songs_list[0])

    return player

def create_fifo(path):
    '''
    Creates the fifo. Deleting the old one
    if it exist.
    '''
    fifo_path = os.path.join(path,"command.fifo")
    if os.path.exists(fifo_path):
        os.unlink(fifo_path)
    os.mkfifo(fifo_path)
    return fifo_path

def run():
    """
    Grabs songs, begins playback and
    creates the command fifo.
    Reads from the fifo until it catches
    "quit" or "snooze <time>"
    """

    songs = get_songs(music)
    player = start_playback(songs,randomize)

    fifo_loc =  create_fifo(working_dir)
    fifo = open(fifo_loc)

    while True:
        #Reads command from fifo, strips trailing
        #newline and splits to list.
        command = fifo.read().strip().split(" ")
        if command[0] == "quit":
            quit(player,fifo_loc)
            break
        elif command[0] == "snooze":
            try:
                time = int(command[1])
                snooze(player,time)
            except:
                snooze(player)

    return player

def quit(player,fifo_path):
    os.unlink(fifo_path)
    player.quit()

p = run()


"""
Epplorative analysis of the accounts file

Conclusions:
The following columns are not populated and therefore can be removed
'first_name','last_name', 'street_addr', 'city', 'state', 'country', 'zip', 'gender',
'birth_date', 'ssn', 'lon', 'lat']
dsply_nm and acct_id are a one-to-one mapping
All accounts have type SAV
All account have status A(ctive)
All accounts have USD as reporting currency
allw account have prior_sar_count = True
All account have the same branch id
All acount have the same open_dt and close_dt
initial deposit is between 50K and 100K
All acount have the same tx_behavior_id and bank_a

summary:
Only the fields acct_id, prior SAR count, initial deposit contain usefull information.

"""
#%%
import pandas as pd
import os
#%%
acct_file = os.getcwd() + "/data/bank_a/accounts.csv"
#%%
# load file
acct = pd.read_csv(acct_file)
acct.columns
# %%
acct.describe()
acct.groupby('acct_stat').count()
acct.groupby('type').count()
#...
acct['initial_deposit'].plot.hist(bins=20)

# %%


#!/usr/bin/python

import sys
import os
import os.path
import cherrypy
from cherrypy.lib import cptools

sys.path.append(os.getcwd())
sys.path.append(os.path.dirname( os.path.realpath( __file__ ) )+'/../server/')
from utils import fgLog
from subprocess import Popen
from subprocess import PIPE

import IRUtil

## Class distributions
class distributions() :

    ############################################################
    # __init__
    ############################################################
    def __init__(self):
        self._log = fgLog.fgLog(IRUtil.getLogFile(), IRUtil.getLogLevel(), "getDistributions", False)
        self.returnCode = 0
        kernel = self.runCmd('uname -s')
        if kernel == "Darwin\n" :
            self._log.info("Using Darwin kernel ")
            self.openssl_dist = 'http://www.openssl.org/source/openssl-1.0.0d.tar.gz'
            self.openssl_dir = 'openssl-1.0.0d'
            self.cherrypy_dist = 'http://download.cherrypy.org/cherrypy/3.2.0/CherryPy-3.2.0.tar.gz'
            self.cherrypy_dir = 'CherryPy-3.2.0'
            cmdOutput = 'x86_64\n'#runCmd('uname -p')
        if cmdOutput == "i386\n" :
            self.mongo_dist = 'http://fastdl.mongodb.org/osx/mongodb-osx-i386-1.8.2.tgz'
            self.mongo_dir = 'mongodb-osx-i386-1.8.2'
        elif cmdOutput == 'x86_64\n' :
            self._log.info('Using osx x86_64')
            self.mongo_dist = 'http://fastdl.mongodb.org/osx/mongodb-osx-x86_64-1.8.2.tgz'
            self.mongo_dir = 'mongodb-osx-x86_64-1.8.2'
        elif kernel == "Linux\n" :
            self.info('Using Linux kernel')
            self.openssl_dist = 'http://www.openssl.org/source/openssl-1.0.0d.tar.gz'
            self.openssl_dir = 'openssl-1.0.0d'
            self.cherrypy_dist = 'http://download.cherrypy.org/cherrypy/3.2.0/CherryPy-3.2.0.tar.gz'
            self.cherrypy_dir = 'CherryPy-3.2.0'
            cmdOutput = 'x86_64\n' #runCmd('uname -p')
            if cmdOutput == "i386\n" :
                self.mongo_dist = 'http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.2.tgz'
                self.mongo_dir = 'mongodb-linux-i686-1.8.2'
            elif cmdOutput == "x86_64\n" :
                self.mongo_dist = 'http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-1.8.2.tgz'
                self.mongo_dir = 'mongodb-linux-x86_64-1.8.2'

    ## Execute shell based command
    # @param cmd the command string
    def runCmd(self, cmd, isShell = False):
        print("Executing command " + cmd)
        if isShell == True :
            p = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE, shell = True)
        else :
            p = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)

        std = p.communicate()
        self.returnCode = p.returncode
        if len(std[0]) > 0:
            self._log.debug('stdout: '+std[0])

        if p.returncode != 0:
            self._log.error('Command: '+cmd+' failed, status: '+str(p.returnCode)+' --- '+std[1])

        return std[0]

    ## Retrieve openssl distribution
    # Return code 0:  succesful installation,  return code 1:  unsuccessful
    def getopenssl(self) :
        install_dir = 'ssl'
        path_name = '/usr/local/ssl/bin/openssl'
        exitStat = 2
        # Retrieve distribution
        self.runCmd('wget ' + self.openssl_dist)
        if (self.returnCode != 0) :
            return self.returnCode
        self.runCmd('tar -xvf ' + self.openssl_dir + '.tar.gz')
        if (self.returnCode != 0) :
            return self.returnCode
        cmd = 'mv -f ' + self.openssl_dir + ' ' + install_dir
        return self.returnCode

    ## Retrieve openssl distribution
    # Return code 0 - succesful installation, return code 1 unsucessful
    def getmongo(self):
        install_dir = 'mongodb'
        self.runCmd('wget ' + self.mongo_dist)
        if (self.returnCode != 0) :
            return self.returnCode
        self.runCmd('tar -xvf ' + self.mongo_dir + '.tgz')
        if (self.returnCode != 0) :
            return self.returnCode
        cmd = 'mv -f ' + mongo_dir + ' ' + install_dir
        self.runCmd(cmd)
        if (self.returnCode != 0) :
            return self.returnCode

        return 0

    ## Retrieve cherrypy distribution
    # Return code 0 - succesful installation, return code 1 unsuccesful
    def getcherrypy(self):
        install_dir = 'cherrypy'
        try :
            import cherrypy
        except ImportError:
            print ("---RETRIEVING CHERRYPY DISTRIBUTION-----")
            self.runCmd('wget ' + self.cherrypy_dist)
            if (self.returnCode != 0) :
                return self.returnCode
            self.runCmd('tar -xvf ' + self.cherrypy_dir + '.tar.gz')
            cmd = 'mv -f ' + self.cherrypy_dir + ' ' + install_dir
            self.runCmd(cmd)
            if (self.returnCode != 0) :
                return self.returnCode

        try :
            import cherrypy
        except ImportError:
            print("unable to install cheryypy")
            return 1
        return 0


import random
import profiler
import motifs
import score
import entropy

def randomKmers(dna, k):
    """
    return t random kmers from dna as list of strings
    TESTED- works
    """
    kmers = []
    for seq in dna:
        n = len(seq)
        i = random.randint(0, n-k)
        kmer = seq[i:i+k]
        kmers.append( kmer)
    return kmers

def randomizedMotifSearch(dna, k, method="score"):
    """
    runs one iteration of randomized motif search
    """
    if method == "score":
        scoreFunc = score.score
    if method == "entropy":
        scoreFunc =  entropy.totalEntropy
    newMotifs = randomKmers(dna, k)
    bestMotifs = newMotifs[:]
    while True:
        profile = profiler.profiler(newMotifs)
        newMotifs = motifs.motifs(dna, profile, k)
        if scoreFunc(newMotifs) < scoreFunc(bestMotifs):
            bestMotifs = newMotifs[:]
        else:
            return bestMotifs

def MCMotifSearch(dna, k, iterations, method="score"):
    if method == "score":
        scoreFunc = score.score
    if method == "entropy":
        scoreFunc =  entropy.totalEntropy
    #first iteration to find starting motifs and score:
    bestMotifs = randomizedMotifSearch(dna, k)
    bestScore = scoreFunc(bestMotifs)

    #Do {iterations} more searches to find a better estimate:
    for i in range(iterations):
        newMotifs = randomizedMotifSearch(dna, k-1, method)
        newScore = scoreFunc(newMotifs)

        if newScore < bestScore:
            bestScore = newScore
            bestMotifs = newMotifs[:]
        print(f"The Score for iteration {i} is: {score.score(bestMotifs)}. The Entropy is  {entropy.totalEntropy(bestMotifs)}")
    return [bestMotifs, bestScore]

"""
#############################################################################
#                   DEBUGING CODE:
#
#TESTING MCMotifSearch:
#Motifs are AAA
k = 1000

dna = [
    "AAA",
    "AAA",
    "AAA",
    "AAA",
    "AAA"
]
print("The motifs should be AAA: ", MCMotifSearch(dna, 3, k))

#Motifs are AAA in larger alignment
dna = [
    "GGGGGAAAGGGGGGG",
    "CCCCCAAACCCCCCC",
    "TTTTTAAATTTTTTT",
    "AAAAAAAAAAAAAAA",
    "GCTAGCTGCTAGCTGCTAGCTAAAGCTAGCT"
]
print("The motifs should be AAA: ", MCMotifSearch(dna, 3, k))

#Motifs are mixed
dna = [
    "GGGGGAAAGGGGGGGAGGGGGGG",
    "CCCCCACACCCCCCCCCCCCCCC",
    "TTTTTAAATTTTTTTTTTTTTTT",
    "AAAAAAAAAAAAAAA",
    "GCTAGCTGCTAGCTGCTAGCTAAAGCTAGCT"
]
print("The motifs should be mixed: ", MCMotifSearch(dna, 3, k))
"""
"""
##############################################
#
#TESTING randomized motif search:
#
#Motifs are AAA

dna = [
    "AAA",
    "AAA",
    "AAA",
    "AAA",
    "AAA"
]
print("The motifs should be AAA: ", randomizedMotifSearch(dna, 3))

#Motifs are AAA in larger alignment
dna = [
    "GGGGGAAAGGGGGGG",
    "CCCCCAAACCCCCCC",
    "TTTTTAAATTTTTTT",
    "AAAAAAAAAAAAAAA",
    "GCTAGCTGCTAGCTGCTAGCTAAAGCTAGCT"
]
print("The motifs should be AAA: ", randomizedMotifSearch(dna, 3))

#Motifs are mixed
dna = [
    "GGGGGAAAGGGGGGG",
    "CCCCCACACCCCCCC",
    "TTTTTAAATTTTTTT",
    "AAAAAAAAAAAAAAA",
    "GCTAGCTGCTAGCTGCTAGCTAAAGCTAGCT"
]
print("The motifs should be AAA: ", randomizedMotifSearch(dna, 3))

"""


import numpy as np
import pandas as pd
import scipy.io as sio

class_dic = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]

dic = {'AM': 0, 'SSB': 1, 'PSK': 2, '2FSK': 3,  'CW': 4,
       'Saopin': 5,  'Interp': 6, 'SingleSound': 7, 'AM_expand_large': 8,
       'Interp_flash': 9, 'Unknow': 10, 'Saopin_large': 11, 'Noise': 12, 'CW_fast': 13}

if __name__ == '__main__':
    #读取保存结果，每64个代表整段1.25MHz频谱
    final_co = np.load('result.npz',allow_pickle = True)['final_co']
    final_sc = np.load('result.npz',allow_pickle = True)['final_sc']
    final_cl = np.load('result.npz', allow_pickle=True)['final_cl']
    #经过融合后结果
    total_co = []
    total_sc =[]
    total_cl =[]
    total_frequce =[]
    N_times = 40
    N_class = 14
    #初始化检查结果,40次，20类

    for i in range (0,N_times * 64):
        time_i = int(np.floor(i / 64))
        real_freq = np.fmod(i,64)
        co = final_co[i]
        sc = final_sc[i]
        cl = final_cl[i]

        for j in range(len(co)):
            #当前频率检测结果
            center_fre = (co[j][0]+co[j][1])/2 + real_freq * 1250/ 64

            # center_cls = cl[j]
            center_cls = class_dic[cl[j]]
            center_sc = sc[j]

            sub_flag = 0
            sub_ti =[]
            #判断是否可以融合
            for ti in range(len(total_frequce)):
                sub_fre =np.abs(center_fre-total_frequce[ti])
                #中心频率相差1KHz以内,检测为位置同一信号
                if sub_fre < 1 :
                    #融合位置sub_ti
                    sub_ti = ti
                    sub_flag = 1
                    continue

            #若可以融合
            if sub_flag:
                total_cl[sub_ti][time_i][center_cls] += 1

                total_co[sub_ti][time_i][0] = co[j][0] + real_freq * 1250 / 64
                total_co[sub_ti][time_i][1] = co[j][1] + real_freq * 1250 / 64

            else:
            #新建中心频率，BW，类别

                ini_fi = np.zeros((N_times, N_class))
                ini_fi[time_i][center_cls] = 1
                total_frequce.append(center_fre)
                total_cl.append(ini_fi)

                ini_co = np.zeros((N_times, 2))
                ini_co[time_i][0] = co[j][0] + real_freq * 1250 / 64
                ini_co[time_i][1] = co[j][1] + real_freq * 1250 / 64
                total_co.append(ini_co)

    print(len(total_frequce))
    total_cl = np.array(total_cl)
    total_co = np.array(total_co)
    total_frequce = np.array(total_frequce)
    sio.savemat('results.mat', {'total_cl': total_cl, 'total_co': total_co , 'total_frequce':total_frequce})


from  func_testpy import fact,fac1
from collections.abc import Iterable

#import builtins; builtins.abs = 10

#测试fact阶乘计算函数 递归调用
print(fact(4))

print(fac1(9))

'''
汉诺塔
'''
def move(n,a,b,c):
    if n==1:
        print('move',a,'-->',c)
    else:
        move(n-1,a,c,b)
        move(1,a,b,c)
        move(n-1,b,a,c)

move(3,'A','B','C')

#测试是否可迭代
print(isinstance('ABC',Iterable))
print(isinstance([1,2,3],Iterable))
print(isinstance(123,Iterable))
print(isinstance('123',Iterable))

#enumerate可以把一个list变成索引-元素对
for i,value in enumerate([1,2,3]):
    print(i,value)

#列表生成式
print(list(range(1,11)))

L=[]
for x in range(1,11):
    L.append(x*x)
print(L)

print([x*x for x in range(1,11)])

print([x*x for x in range(1,11) if x%2==0] )

print([m+n for m in 'ABC' for n in 'XYZ'])

L1=['Hello', 'World', 'IBM', 'Apple']
print([ s.lower() for s in L1])

L2 = ['Hello', 'World', 18, 'Apple', None]

L2=[x.lower() for x in L2 if isinstance(x,str)]
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('测试通过!')
else:
    print('测试失败!')

'''
生成器：
斐波那契数列
'''
L3=(x*x for x in range(10))
print(L3)
print('next：',next(L3))#交互式环境下测试

#循环
def fib(max):
    n,a,b=0,0,1
    while n<max:
        print(b)
        a,b=b,a+b
        n=n+1
    return 'done'

fib(6)

def fib1(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

print('yield 测试')
for x in fib1(10):
    print(x)

#拿return返回值
g=fib1(4)
while True:
    try:
        x=next(g)
        print('g:',x)
    except StopIteration as e:
        print('Generator return value:',e.value)
        break

print(abs)


from PIL import Image as im
from helper.functions import getFilesInPath
import argparse, numpy as np, os, shutil

def findIndex(search,list):
    for i, l in enumerate(list):
        if l[0:len(search)] == search:
            return i
    return -1

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Stack different files')
    parser.add_argument('--original', help='Original datasets', required=True)
    parser.add_argument('--stacked', help='Stacked file', required=True)
    parser.add_argument('--outputFileType', help='type of file to ouput', required=True)
    args = parser.parse_args()

    folders = args.original.split('__')

    files = [getFilesInPath(f,fullPath=False) for f in folders]

    if os.path.exists(args.stacked):
        shutil.rmtree(args.stacked)

    os.makedirs(args.stacked)

    fusedFiles = []
    for i in range(len(files[0])):
        if files[0][i][-3:] == 'bmp':
            currFile = np.array(im.open(os.path.join(folders[0], files[0][i])).convert('RGB'))
        else:
            currFile = np.array(im.open(os.path.join(folders[0],files[0][i])))
        if (len(currFile.shape) < 3):
            currFile = currFile.reshape((100,100,1))
        for j in range(1,len(files)):
            indexFiles = findIndex(files[0][i][:-4],files[j])
            imageOpened = np.array(im.open(os.path.join(folders[j],files[j][indexFiles])))
            if len(imageOpened.shape) < 3:
                imageOpened = imageOpened.reshape((100,100,1))
            currFile = imageOpened if currFile is None else np.concatenate((currFile,imageOpened),axis=2)

        fileName = files[0][i][:-4]
        if args.outputFileType == 'npy':
            np.save(os.path.join(args.stacked,fileName),currFile)
        else:
            imageFile = im.fromarray(currFile)
            fullFilePath = os.path.join(args.stacked,fileName+'.'+args.outputFileType)
            imageFile.save(fullFilePath)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023-04-11 下午1:49
# @Author  : MaybeShewill-CV
# @Site    :
# @File    : insseg_model.py
# @IDE: PyCharm Community Edition
"""
instance segmentation model with sam and clip
"""
import numpy as np
import cv2
from PIL import Image
import torch

from models.detector import utils
from models.clip import tokenize
from models import build_clip_model
from models import build_sam_mask_generator

class SamClipInsSegmentor(object):
    """

    """
    def __init__(self, sam_cfg, clip_cfg, insseg_cfg):
        """

        :param sam_cfg:
        :param clip_cfg:
        :param insseg_cfg:
        """
        self.mask_generator = build_sam_mask_generator(sam_cfg)
        self.clip_model, self.clip_preprocess = build_clip_model(clip_cfg)
        self.device = torch.device(insseg_cfg.MODEL.DEVICE)
        self.top_k_objs = insseg_cfg.INS_SEG.TOP_K_MASK_COUNT
        self.cls_score_thresh = insseg_cfg.INS_SEG.CLS_SCORE_THRESH
        self.max_input_size = insseg_cfg.INS_SEG.MAX_INPUT_SIZE
        self.obj365_text_prompts = utils.generate_object365_text_prompts()
        self.obj365_text_token = tokenize(self.obj365_text_prompts).to(self.device)
        self.text_token = None

    def _set_text_tokens(self, texts):
        """

        :param texts:
        :return:
        """
        self.text_token = tokenize(texts=texts).to(self.device)
        return

    def _generate_sam_mask(self, input_image: np.ndarray):
        """

        :param input_image:
        :return:
        """
        masks = self.mask_generator.generate(input_image)
        most_stable_mask = sorted(masks, key=lambda d: d['area'])
        if len(most_stable_mask) > self.top_k_objs:
            most_stable_mask = most_stable_mask[-self.top_k_objs:]
        sam_masks = {
            'segmentations': [tmp['segmentation'] for tmp in most_stable_mask],
            'bboxes': [tmp['bbox'] for tmp in most_stable_mask],
            'stability_scores': [tmp['stability_score'] for tmp in most_stable_mask],
        }
        return sam_masks

    @staticmethod
    def _crop_rotate_image_roi(input_image, seg_mask):
        """

        :param input_image:
        :param seg_mask:
        :return:
        """
        y, x = np.where(seg_mask == 1)
        fg_pts = np.vstack((x, y)).transpose()
        src_image = cv2.bitwise_or(input_image, input_image, mask=np.asarray(seg_mask, dtype=np.uint8))
        roi_x, roi_y, roi_w, roi_h = cv2.boundingRect(fg_pts)
        extend_size = 20
        if roi_x - extend_size >= 0:
            roi_x -= extend_size
            roi_w += extend_size
        if roi_y - extend_size >= 0:
            roi_y -= extend_size
            roi_h += extend_size
        roi_image = src_image[roi_y:roi_y + roi_h, roi_x:roi_x + roi_w, :]
        if np.any(np.shape(roi_image) < (3, 3)):
            return None
        return roi_image

    def _classify_image(self, input_image: np.ndarray, text=None):
        """

        :param input_image:
        :return:
        """
        image = Image.fromarray(input_image)
        image = self.clip_preprocess(image).unsqueeze(0).to(self.device)
        if text is None:
            logits_per_image, logits_per_text = self.clip_model(image, self.obj365_text_token)
        else:
            if self.text_token is None:
                text_token = tokenize(texts=text).to(self.device)
                logits_per_image, logits_per_text = self.clip_model(image, text_token)
            else:
                logits_per_image, logits_per_text = self.clip_model(image, self.text_token)
        probs = logits_per_image.softmax(dim=-1).cpu().numpy()[0, :]
        cls_id = np.argmax(probs)
        score = probs[cls_id]
        if text is None:
            if score < 0.15:
                cls_id = probs.shape[0] - 1
            return cls_id
        else:
            if score < self.cls_score_thresh:
                cls_id = probs.shape[0] - 1
            return cls_id

    def _classify_mask(self, input_image, mask, text=None):
        """

        :param input_image:
        :param mask:
        :return:
        """
        bboxes_cls_names = []
        for idx, bbox in enumerate(mask['bboxes']):
            roi_image = self._crop_rotate_image_roi(input_image, mask['segmentations'][idx])
            if roi_image is None:
                cls_name = 'background'
                bboxes_cls_names.append(cls_name)
                continue
            # cv2.imwrite('{:d}_mask.png'.format(idx), roi_image[:, :, (2, 1, 0)])
            cls_id = self._classify_image(roi_image, text=text)
            if text is None:
                cls_name = self.obj365_text_prompts[cls_id].split('a photo of')[1].strip(' ')
                bboxes_cls_names.append(cls_name)
            else:
                cls_name = text[cls_id]
                if cls_name.startswith('a photo of'):
                    cls_name = cls_name.split(' ')[3]
                bboxes_cls_names.append(cls_name)

        mask['bbox_cls_names'] = bboxes_cls_names
        return

    def seg_image(self, input_image_path, unique_label=None, use_text_prefix=False):
        """

        :param input_image_path:
        :param unique_label:
        :param use_text_prefix:
        :return:
        """
        # read input image
        input_image = cv2.imread(input_image_path, cv2.IMREAD_COLOR)
        if input_image.shape[0] > self.max_input_size[0] or input_image.shape[1] > self.max_input_size[1]:
            h, w, _ = input_image.shape
            hw_ratio = h / w if h > w else w / h
            if h > w:
                dsize = (int(self.max_input_size[1] / hw_ratio), self.max_input_size[1])
            else:
                dsize = (self.max_input_size[0], int(self.max_input_size[0] / hw_ratio))
            input_image = cv2.resize(input_image, dsize=dsize)
        input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB)

        with torch.no_grad():
            # extract mask from sam model
            masks = self._generate_sam_mask(input_image)
            # classify each mask's label
            if unique_label is None:
                self._classify_mask(input_image, masks, text=None)
            else:
                texts = utils.generate_text_prompts_for_instance_seg(
                    unique_labels=unique_label,
                    use_text_prefix=use_text_prefix
                )
                self._set_text_tokens(texts)
                self._classify_mask(input_image, masks, text=texts)

        # visualize segmentation result
        input_image = cv2.cvtColor(input_image, cv2.COLOR_RGB2BGR)
        ins_seg_mask = utils.visualize_instance_seg_results(masks, draw_bbox=True)
        ins_seg_add = cv2.addWeighted(input_image, 0.5, ins_seg_mask, 0.5, 0.0)

        ret = {
            'source': input_image,
            'ins_seg_mask': ins_seg_mask,
            'ins_seg_add': ins_seg_add
        }

        return ret


# 用计算机计算生成结合成多张鱼眼照片进行训练。

import math
import cv2 as cv
import numpy as np
from undistortionCamera import init_K_D

K, D, DIM = init_K_D()
rvecs = np.zeros((3, 1), dtype=np.float64)
tvecs = np.zeros((3, 1), dtype=np.float64)

def tesd(img, ratio=0.5, center_ratio=0.5):
    rows, cols, _ = img.shape
    fish_image = np.zeros([rows, cols, 3], dtype=np.uint8)
    # 调整这个中心点的值可以帮助改变图像畸变后的映射位置
    u0 = cols*center_ratio
    v0 = rows/2
    # 调整这个ratio有助于生成更加鱼眼畸变的相机，ratio越小畸变越明显
    sigma_u = u0*ratio
    sigma_v = v0*ratio
    k = D[1]  # 随便取一个相机的畸变参数即可

    def project_p(col, row):
        x = (col - u0) / sigma_u
        y = (row - v0) / sigma_v
        r = math.sqrt(x ** 2 + y ** 2)
        theta = math.atan(r)
        theta_d = theta * (
                    1 + k[0] * pow(theta, 2) + k[1] * pow(theta, 4) + k[2] * pow(theta, 6) + k[3] * pow(theta, 8))
        if theta_d != 0:
            xd = theta_d * x / r
            yd = theta_d * y / r
        else:
            xd = 0
            yd = 0
        ud = int(xd * sigma_u + u0)
        vd = int(yd * sigma_v + v0)
        return ud, vd

    # 计算每个点的映射
    for col in range(cols):
        for row in range(rows):
            ud, vd = project_p(col, row)
            fish_image[vd][ud] = img[row][col]

    # 计算原图中四个角映射后的坐标，用于裁剪
    edge = np.zeros([4, 2], dtype=int)
    edge[0] = project_p(0, 0)  # 左上角
    edge[1] = project_p(cols, 0)  # 右上角
    edge[2] = project_p(0, rows)  # 左下角
    edge[3] = project_p(cols, rows)  # 右下角角

    for i in range(4):
        cv.circle(fish_image, (edge[i][0], edge[i][1]), 5, color=(0, 255, 250), thickness=-1)
    out = fish_image[edge[0][1]:edge[3][1], edge[0][0]:edge[3][0]]
    return out, fish_image

if __name__ == '__main__':
    # for i in range(5):
    #     name = 'image/training data generator/'+ str(i) + '.jpg'
    #     img = cv.imread(name, 1)
    #     img = cv.resize(img, (0, 0), None, 0.3, 0.3)
    #     cv.imshow('TESE', img)
    #     cv.imwrite(name, img)

    img = cv.imread('image/training data generator/4.jpg', 1)
    img = cv.resize(img, (0, 0), None, 0.5, 0.5)
    # 进行patch，因为照片里车照的有点大了
    ratio = 1.3
    rows, cols, _ = img.shape
    patched_img = np.ones([int(rows*ratio), int(cols*ratio), 3], dtype=np.uint8)
    patched_img = patched_img * 255
    start_u = (patched_img.shape[0] - rows)//2
    start_v = (patched_img.shape[1] - cols)//2
    patched_img[start_v:start_v+rows, start_u:start_u+cols, :] = img

    out, fish_img = tesd(patched_img, center_ratio=0.5)
    cv.imshow('TESE', fish_img)
    cv.imshow('TESE2', out)

    # save_path = 'image/training data generator/logout/diff_central_7.jpg'
    # cv.imwrite(save_path, fish_img)
    cv.waitKey(0)


# Bài 09: Cho số tự nhiên N lớn hơn 1 bất kỳ (đã gán trước đó) , In ra khai triển thành tích các số nguyên tố tính từ nhỏ đến lớn
# *Vd:
# 9--> 3.3
# 12--> 2.2.3
index = []
input1 = 999
tich_so = ''
if input1 == 0:
    print('0')
    exit()
elif input1 == 1:
    print('1')
    exit()
for z in range(2, input1 + 1):
    while input1 % z == 0 and input1 >= z:
            input1 /= z
            index.append(str(z))
sap_lai_list = (sorted(index))
for i in range(0, len(sap_lai_list)):
    tich_so += sap_lai_list[i]
    tich_so +='.'
print(tich_so[0:len(tich_so) - 1])


# --*-- coding:utf8 --*--

from WebUI.common.BasePage import BasePage
from units.file_reader import Excel_Reader
from units.config import Config, Base_Path
import os, time

class open(BasePage):

    url = 'https://www.baidu.com'
    excel_file = os.path.join(Base_Path, 'data', 'UIelements.xlsx')
    test_elements = Excel_Reader(excel_file, 'login').data
    value_loc = test_elements['value_loc']
    submit_loc = test_elements['submit_loc']

    def open(self):
        self._open(self.url)

    def search_value(self, value="天气"):
        self.find_element(self.value_loc).send_keys(value)

    def submit_button(self):
        self.find_element(self.value_loc).click()


from threading import Thread
import socket
import sys,time
from PyQt5 import QtWidgets , uic,QtGui
def Send():
    msg=sc.txte.toPlainText()
    msg2=msg
    if(msg != ""):
        msg = msg.encode("utf-8")
        client.send(msg)
        sc.txte.setPlainText("")
        sys.stdout = open("output.txt", "a")
        print("Server :"+msg2+"
")
        sys.stdout.close()
    f=open("output.txt",'r')
    sc.txt.setHtml(f.read())
    f.close()
def rec():
    recep.start()
def Reception():
    while True:
        requete_client = client.recv(500)
        requete_client = requete_client.decode('utf-8')
        out="Client :"+str(requete_client)
Host = "127.0.0.1"
Port = 6390
#Création du socket
socket = socket.socket()

socket.bind((Host,Port))
socket.listen(1)

#Le script s'arrête jusqu'a une connection
client, ip = socket.accept()
print("Le client d'ip",ip,"s'est connecté")
recep = Thread(target=Reception,args=(), daemon=True)
if __name__== '__main__':
    App=QtWidgets.QApplication(sys.argv)
    sc=uic.loadUi("IPC.ui")
    sc.setWindowTitle("Server")
    sc.send_2.clicked.connect(Send)
    sc.actionreceive.triggered.connect(rec)
    sc.show()
    App.exec_()
    App.exit()
client.close()
socket.close()


import numpy as np
nrand = int (1e5 )

### Constants ####
C = 343 #c is the speed of sound
#####

# uniformt fordelte verdier mellom 0.0 og 1.0

m = np.ones(nrand)

d=2*m
#tau=m

#d = np.random.uniform(low=3, high=4, size=nrand) # den ideele d verdien
tau = np.random.uniform(low=0.1, high=1.0, size=nrand) #den ideele tau verdien
tauvec = (1 + 2*0.01*( np . random . rand ( nrand ) - 0.5)) # delta d
dvec = (1 + 2*0.02*( np . random . rand ( nrand ) - 0.5)) # telta tau

teta_ideell = np.arccos(tau/d)
teta_feil = np.arccos((tau*tauvec/(d*dvec)))

relativ_feil = teta_feil/teta_ideell

print("Max error:",np.max(relativ_feil))


import unittest

import numpy as np
import pandas as pd
from numpy import testing as nptest

from openoa.utils import power_curve
from openoa.utils.power_curve.parametric_forms import logistic5param, logistic5param_capped

noise = 0.1

class TestPowerCurveFunctions(unittest.TestCase):
    def setUp(self):
        np.random.seed(42)
        params = [1300, -7, 11, 2, 0.5]
        self.x = pd.Series(np.random.random(100) * 30)
        self.y = pd.Series(logistic5param(self.x, *params) + np.random.random(100) * noise)

        # power curve source: https://github.com/NREL/turbine-models/blob/master/Offshore/2020ATB_NREL_Reference_15MW_240.csv
        self.nrel_15mw_wind = pd.Series(np.arange(4, 26))
        self.nrel_15mw_power = pd.Series(
            np.array(
                [
                    720,
                    1239,
                    2271,
                    3817,
                    5876,
                    8450,
                    11536,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    15000,
                    1500,
                ]
            )
        )

    def test_IEC(self):
        # Create test data using logistic5param form
        curve = power_curve.IEC(self.x, self.y)
        y_pred = curve(self.x)
        # Does the IEC power curve match the test data?
        nptest.assert_allclose(
            self.y, y_pred, rtol=1, atol=noise * 2, err_msg="Power curve did not properly fit."
        )

    def test_IEC_with_bounds(self):
        # Create the power curve with bounds at 4m/s adn 25m/s and bin width from power curve of 1m/s
        cut_in = 4
        cut_out = 25
        curve = power_curve.IEC(
            self.nrel_15mw_wind,
            self.nrel_15mw_power,
            windspeed_start=cut_in,
            windspeed_end=cut_out,
            bin_width=1,
        )

        # Create the test data
        test_windspeeds = np.arange(0, 31)
        test_power = curve(test_windspeeds)

        # Test all windspeeds outside of cut-in and cut-out windspeeds produce no power
        should_be_zeros = test_power[(test_windspeeds < cut_in) | (test_windspeeds > cut_out)]
        nptest.assert_array_equal(should_be_zeros, np.zeros(should_be_zeros.shape))

        # Test all the valid windspeeds are equal
        valid_power = test_power[(test_windspeeds >= cut_in) & (test_windspeeds <= cut_out)]
        nptest.assert_array_equal(self.nrel_15mw_power, valid_power)

    def test_logistic_5_param(self):
        # Create test data using logistic5param form
        curve = power_curve.logistic_5_parametric(self.x, self.y)
        y_pred = curve(self.x)
        # Does the logistic-5 power curve match the test data?
        nptest.assert_allclose(
            self.y, y_pred, rtol=1, atol=noise * 2, err_msg="Power curve did not properly fit."
        )

    def test_gam(self):
        # Create test data using logistic5param form
        curve = power_curve.gam(windspeed_col=self.x, power_col=self.y, n_splines=20)
        y_pred = curve(self.x)
        # Does the spline-fit power curve match the test data?
        nptest.assert_allclose(
            self.y, y_pred, rtol=0.05, atol=20, err_msg="Power curve did not properly fit."
        )

    def test_3paramgam(self):
        # Create test data using logistic5param form
        winddir = pd.Series(np.random.random(100), name="winddir")
        airdens = pd.Series(np.random.random(100), name="airdens")
        curve = power_curve.gam_3param(
            windspeed_col=self.x,
            wind_direction_col=winddir,
            air_density_col=airdens,
            power_col=self.y,
            n_splines=20,
        )
        y_pred = curve(self.x, winddir, airdens)
        # Does the spline-fit power curve match the test data?
        nptest.assert_allclose(
            self.y, y_pred, rtol=0.05, atol=20, err_msg="Power curve did not properly fit."
        )

    def tearDown(self):
        pass

class TestParametricForms(unittest.TestCase):
    def setUp(self):
        pass

    def test_logistic5parameter(self):
        y_pred = logistic5param(np.array([1.0, 2.0, 3.0]), *[1300.0, -7.0, 11.0, 2.0, 0.5])
        y = np.array([2.29403585, 5.32662505, 15.74992462])
        nptest.assert_allclose(y, y_pred, err_msg="Power curve did not properly fit.")

        y_pred = logistic5param(np.array([1, 2, 3]), *[1300.0, -7.0, 11.0, 2.0, 0.5])
        y = np.array([2.29403585, 5.32662505, 15.74992462])
        nptest.assert_allclose(
            y, y_pred, err_msg="Power curve did not handle integer inputs properly."
        )

        y_pred = logistic5param(np.array([0.01, 0.0]), 1300, 7, 11, 2, 0.5)
        y = np.array([1300.0, 1300.0])
        nptest.assert_allclose(y, y_pred, err_msg="Power curve did not handle zero properly (b>0).")

        y_pred = logistic5param(np.array([0.01, 0.0]), 1300, -7, 11, 2, 0.5)
        y = np.array([2.0, 2.0])
        nptest.assert_allclose(y, y_pred, err_msg="Power curve did not handle zero properly (b<0).")

    def test_logistic5parameter_capped(self):
        # Numpy array + Lower Bound
        y_pred = logistic5param_capped(
            np.array([1.0, 2.0, 3.0]), *[1300.0, -7.0, 11.0, 2.0, 0.5], lower=5.0, upper=20.0
        )
        y = np.array([5.0, 5.32662505, 15.74992462])
        nptest.assert_allclose(y, y_pred, err_msg="Power curve did not properly fit.")

        # Numpy array + Upper and Lower Bound
        y_pred = logistic5param_capped(
            np.array([1.0, 2.0, 3.0]), *[1300.0, -7.0, 11.0, 2.0, 0.5], lower=5.0, upper=10.0
        )
        y = np.array([5.0, 5.32662505, 10.0])
        nptest.assert_allclose(y, y_pred, err_msg="Power curve did not properly fit.")

        # Pandas Series + Upper and Lower Bound
        y_pred = logistic5param_capped(
            pd.Series([1.0, 2.0, 3.0]), *[1300.0, -7.0, 11.0, 2.0, 0.5], lower=5.0, upper=20.0
        )
        y = pd.Series([5.0, 5.32662505, 15.74992462])
        nptest.assert_allclose(y, y_pred, err_msg="Power curve did not properly fit.")

        # Pandas Series + Upper and Lower Bound
        y_pred = logistic5param_capped(
            pd.Series([1.0, 2.0, 3.0]), *[1300.0, -7.0, 11.0, 2.0, 0.5], lower=5.0, upper=10.0
        )
        y = pd.Series([5.0, 5.32662505, 10.0])
        nptest.assert_allclose(y, y_pred, err_msg="Power curve did not properly fit.")

    def tearDown(self):
        pass