import math

import gmsh

gmsh.initialize()

gmsh.open("/Users/mcgurn/chrestScratch/ablateInputs/geom/slabMotor.3D.hex.msh")

# Load in the element
[allElementTypes, allElementTags, allNodeTags] = gmsh.model.mesh.getElements(3)

elementType = allElementTypes[0]
elementTags = allElementTags[0]
nodeTags = allNodeTags[0]

# Get the type info
typeInfo = gmsh.model.mesh.getElementProperties(elementType)

faceHistory = {}

# define the outward facing faces
faces = [
    [1, 2, 6, 5],
    [0, 4, 7, 3],
    [2, 3, 7, 6],
    [1, 5, 4, 0],
    [5, 6, 7, 4],
    [0, 3, 2, 1]]

for eleTag in elementTags:
    ele = gmsh.model.mesh.getElement(eleTag)
    nodes = ele[1]

    for face in faces:
        faceNodes = [];
        for n in face:
            faceNodes.append(nodes[n])

        faceNodes.sort()
        nodeKey = str(faceNodes)

        if nodeKey in faceHistory:
            faceHistory[nodeKey] += 1
        else:
            faceHistory[nodeKey] = 1

for nodeKey in faceHistory:
    if faceHistory[nodeKey] > 2:
        print("gMshDupeFace Duplicate: ", nodeKey)


import pdb
import importlib
import os
import sys
import traceback
import time
from configparser import ConfigParser

from mxsoftpy.def_http_code import WeMr
from mxsoftpy.exception import NotFoundError

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + os.sep + 'pyweb')

from utils.conf.mxconfig import MxConfig  # 导入配置
from utils.conf.mxlog import setup_log
from utils.conf.i18n import setup_language
from utils.public.mini_cache import MiniCache

# 全局flag，用于判断是否是初次请求，只有初次请求会实例化app
flag = False

# 框架入口
app = None

# 国际化支持
_ = None

# 缓存
# mini_cache = MiniCache()

def register_extensions(mx):
    """
    注册组件
    """
    from utils.middleware.before_request import cross_domain
    from utils.conf.register_module import register_module

    mx.before_request(cross_domain)
    register_module(app)

def create_app():
    """
    创建应用
    """
    global app
    global _
    from mxsoftpy import Mx
    app = Mx()
    setup_log(MxConfig.LOG_LEVEL)  # 配置日志
    _ = setup_language(MxConfig.LANGUAGES)  # 配置语言

    register_extensions(app)
    return app

def run(session):
    global flag
    global app
    if flag:
        pass
    else:
        app = create_app()
        flag = True
    #pdb.set_trace()
    try:
        try:
            app(session)
            return WeMr.WE_MR_OK
        except NotFoundError:
            url = session.GetUrl()

            # 获取请求路径
            path = url.GetPath()

            # url, prefix_ = path.split(".sy")
            if path.find('sy') > 0:
                urlno, prefix_ = path.split(".sy")
                urls = urlno.split("/")
            else:
                urls = path.split("/")
            # urls = url.split("/")
            num = len(urls) - 1
            active = urls[num]
            urls.pop(num)

            szMod = urls.pop(0)

            modules = ".".join(urls)
            modules = szMod + '.controller.' + modules

            obj = importlib.import_module('.', modules)

            # 判断是否需要重新加载文件
            reload = False
            cfg = ConfigParser()
            cfg.read(os.path.dirname(__file__) + '/conf/Pyconf.ini')
            if cfg.get('reload', 'reloadNum') == '1':
                reload = True

            # 调用模块方法
            if hasattr(obj, active):
                if reload:
                    obj = importlib.reload(obj)
                func = getattr(obj, active)
                func(session)
                return WeMr.WE_MR_OK
            else:
                if reload:
                    obj = importlib.reload(obj)
                class_ = getattr(obj, urls[int(num) - 2])
                cls = class_(session)
                attr_obj = getattr(cls, active)
                if hasattr(attr_obj, '__call__'):
                    attr_obj()

                return WeMr.WE_MR_OK
            # raise NotFoundError()

    except Exception:
        log_name = time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'
        path = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + '/middle/Pymod/'
        if not os.path.exists(path):
            os.makedirs(path)
        traceback.print_exc(file=open(path + log_name, 'w+'))
        return WeMr.WE_MR_FAILED


import sys
import os
import time
import threading
from tkinter import *
from database import initial_text
from choose_text import ChooseText

PINK = "#F56D91"
PURPLE = "#8D8DAA"
WHITE = "#F7F5F2"
GREY = "#DFDFDE"
BLUE = "#6F9EAF"
FONT_NAME = "Arial"
font = (FONT_NAME, 20, "normal")

def restart_test():
    python = sys.executable
    os.execl(python, python, *sys.argv)

class TypeSpeedInterface:
    def __init__(self, text_chosen: ChooseText):

        # Imports
        self.text_to_type = text_chosen.text

        # Variables
        self.users_typing = False
        self.timer = 0
        self.count_mistakes = 0

        # Create window
        self.window = Tk()
        self.window.title("Typing Speed Test")
        self.window.config(padx=100, pady=50, background=GREY)
        self.window.geometry("1250x970")

        # Labels
        self.initial_label = Label(font=(FONT_NAME, 26, "normal"), bg=GREY, fg=PINK, text="Test Your Typing Speed!")
        self.cpm_label = Label(font=(FONT_NAME, 16, "normal"), bg=GREY, fg="black", text="chars/min")
        self.wpm_label = Label(font=(FONT_NAME, 16, "normal"), bg=GREY, fg="black", text="words/min")
        self.accuracy_label = Label(font=(FONT_NAME, 16, "normal"), bg=GREY, fg="black", text="accuracy")

        # Canvas for Instructions
        self.canvas_instruction = Canvas(width=1000, height=250, background=WHITE)
        self.text_instruction = self.canvas_instruction.create_text(500, 125, text=initial_text, width=978,
                                                                    font=font, fill=PURPLE)

        # Canvas for the Text
        self.canvas_text = Canvas(width=1000, height=250, background=WHITE)
        self.text = self.canvas_text.create_text(500, 125, text=self.text_to_type, width=978,
                                                 font=(FONT_NAME, 20, "italic"), fill=PURPLE)
        self.text_to_write = self.canvas_text.itemcget(self.text, 'text')

        # Canvas for the speed and accuracy
        self.canvas_cpm = Canvas(width=100, height=100, background=WHITE)
        self.text_cpm = self.canvas_cpm.create_text(50, 50, text=self.timer, width=90,
                                                    font=font, fill=BLUE)
        self.canvas_wpm = Canvas(width=100, height=100, background=WHITE)
        self.text_wpm = self.canvas_wpm.create_text(50, 50, text=self.timer, width=90,
                                                    font=font, fill=BLUE)
        self.canvas_accuracy = Canvas(width=100, height=100, background=WHITE)
        self.text_accuracy = self.canvas_accuracy.create_text(50, 50, text=self.count_mistakes, width=90,
                                                              font=font, fill=BLUE)

        # Buttons
        self.start_button = Button(self.window, text="Start the Test", relief="groove", font=font, bg=PINK,
                                   fg=WHITE, command=self.start_test)
        self.restart_button = Button(self.window, text="Restart the Test", relief="groove", font=font, bg=PINK,
                                     fg=WHITE, command=restart_test)

        # Inputs
        self.text_input = Text(self.window, height=8, width=67, font=font, wrap=WORD)

        self.start()
        self.window.mainloop()

    def start(self):
        # Show the initial page of the program
        self.initial_label.grid(column=0, row=1, columnspan=3, pady=50, padx=20)
        self.canvas_instruction.grid(column=0, row=2, columnspan=3, pady=50, padx=20)
        self.start_button.grid(column=1, row=3, padx=20, pady=50)

        # Make the widgets centered
        self.window.rowconfigure(0, weight=1)
        self.window.rowconfigure(4, weight=1)

    def start_test(self):
        # Forget grid
        self.canvas_instruction.grid_forget()
        self.start_button.grid_forget()
        self.initial_label.grid_forget()

        # Undo the weights to make the widgets centered in the first window
        self.window.rowconfigure(0, weight=0)
        self.window.rowconfigure(4, weight=0)

        # Show necessary widgets
        self.canvas_text.grid(column=0, row=0, columnspan=3, pady=20, padx=20)

        self.text_input.grid(column=0, columnspan=3, row=1, pady=20, padx=20)
        self.text_input.focus()
        self.text_input.bind("<KeyRelease>", self.key_pressed)

        self.canvas_cpm.grid(column=0, row=2, pady=(20, 5), padx=20)
        self.canvas_wpm.grid(column=1, row=2, pady=(20, 5), padx=20)
        self.canvas_accuracy.grid(column=2, row=2, pady=(20, 5), padx=20)

        self.cpm_label.grid(column=0, row=3, padx=20, pady=(0, 20))
        self.wpm_label.grid(column=1, row=3, padx=20, pady=(0, 20))
        self.accuracy_label.grid(column=2, row=3, padx=20, pady=(0, 20))

        self.restart_button.grid(column=0, row=4, columnspan=3, padx=20, pady=20)

    def key_pressed(self, event):
        if not self.users_typing:
            # keycode is a number that represents a key in the keyboard (i.e. 9 = left TAB)
            if not event.keycode in [16, 17, 18, 9]:
                self.users_typing = True
                # Create threads and use it to run the app faster
                thread = threading.Thread(target=self.timer_thread)
                thread.start()

        # Check if users input == text chosen to change the color
        if not self.text_to_write.startswith(self.text_input.get("1.0", "end-1c")):
            self.text_input.config(fg=PINK)
            self.count_mistakes += 1
        else:
            self.text_input.config(fg="black")

        # Check if user wrote the entire text to change the color and stop the clock
        if self.text_input.get("1.0", "end-1c").rstrip() == self.text_to_write.rstrip():
            self.users_typing = False
            self.text_input.config(fg=BLUE)

    def timer_thread(self):
        # Start the clock when user starts typing
        while self.users_typing:
            time.sleep(0.1)
            self.timer += 0.1
            # Get the character per seconds
            cpm = len(self.text_input.get("1.0", "end-1c")) * 60 / self.timer

            # Get the word per minute
            wpm = len(self.text_input.get("1.0", "end-1c").split(" ")) * 60 / self.timer

            # Accuracy
            accuracy = len(self.text_input.get("1.0", "end-1c")) - self.count_mistakes
            accuracy_percent = accuracy * 100 / len(self.text_input.get("1.0", "end-1c"))

            # Update Canvas
            self.canvas_cpm.itemconfig(self.text_cpm, text=f"{cpm:.0f}")
            self.canvas_wpm.itemconfig(self.text_wpm, text=f"{wpm:.0f}")
            self.canvas_accuracy.itemconfig(self.text_accuracy, text=f"{accuracy_percent:.0f}%")


import numpy as np

import ConsonantVowelStructure
import pandas as pd
import PhoneticStructure
import CountingDict

def NumStrokesColumn(df, verbose=False):  #not yet used
    if "Strokes" in df.columns.tolist():
        dfWithoutStrokes = df[df['Strokes'].isnull()].copy(deep = True)
        dfWithoutStrokes['NumStrokes'] = np.NaN #Set it to NaN because the others will be numbers.  Don't use None
        df = df[df['Strokes'].notnull()].copy(deep = True)
        df["NumStrokes"] = df["Strokes"].apply(lambda x: len(x) if type(x) == list else None)
        if verbose:
            print("The average number of strokes per entry is {}.".format( round(np.mean(np.array(df['NumStrokes'])),1) ) )
            print("The median number of strokes per entry is {}.".format( round(np.mean(np.median(df['NumStrokes']))) ))
        df = pd.concat([df, dfWithoutStrokes], sort= False)
    elif verbose:
        print("No steno column, unable to make NoStrokes Column...")
    return df

def addStructureCols(df, verbose = False):
    """This function adds Structure Columns to an existing dataframe that has been filterred1 already.
    It takes a dataframe as input and returns the same dataframe as output """
    if "Strokes" in df.columns.tolist():
        df["StenoCVCStructure"] = df['Strokes'].apply(lambda x: ConsonantVowelStructure.MakeStenoCVCs(x))

        if "syllables" in df.columns.tolist(): # syllables and strokes, notice indentation
            df["WordCVCStructure"] = df["syllables"].apply(lambda x: ConsonantVowelStructure.MakeWordCVCs(x) if x is not None else None)

            df["EqualStructureWithSyllables"] = df.apply(
                lambda x: True if x["WordCVCStructure"] == x["StenoCVCStructure"] else False,
                axis=1)  # TODO handle consonants... what does this TODO mean again?
            #break up the df into two parts and then recombine...

            dfWithStrokesAndSyllables = df[df['Strokes'].notnull() & df['syllables'].notnull() ].copy()
            dfWithStrokesAndSyllables['SameLengthStrokesAndSyllables'] = dfWithStrokesAndSyllables.apply(lambda x: len(x['Strokes']) == len(x['syllables']) , axis=1)

            dfWithoutStrokesAndSyllables = df[df['Strokes'].isnull() | df['syllables'].isnull()].copy()
            dfWithoutStrokesAndSyllables['SameLengthStrokesAndSyllables'] = None

            df = pd.concat([dfWithStrokesAndSyllables, dfWithoutStrokesAndSyllables], sort = False)
        elif(verbose):
            print("Expected syllables column in addStructureCols.")
    elif(verbose):
        print("Expected Strokes Column in addStructureCols.")

    if "Phonetics" in df.columns.tolist():
        df = PhoneticStructure.AddPhoneticStructureColumn(df, verbose= verbose)
    elif(verbose):
        print("Expected Phonetics Column in addStructureCols.")
    return df

def firstAndLastSyllablesColumn(df, verbose = False):
    """Adds a first and last
    syllable column to a dataframe and identical first stroke which sees if the first stoke is identical. """
    if verbose:
        print("Starting firstAndLastSyllablesColumn...")
    if "syllables" in df.columns.tolist() and "Strokes" in df.columns.tolist():

        dfWithSyllables = df[df['syllables'].notnull()].copy()
        if len(dfWithSyllables) >0 :

            dfWithSyllables['firstSyllable'] = dfWithSyllables.loc[: , 'syllables'].apply(lambda x: x[0])
            dfWithSyllables['lastSyllable'] = dfWithSyllables.loc[: , 'syllables'].apply(lambda x: x[-1])

            dfWithSyllablesAndStrokes = dfWithSyllables[dfWithSyllables['Strokes'].notnull()].copy()
            dfWithSyllablesButWithoutStrokes = dfWithSyllables[dfWithSyllables['Strokes'].isnull()].copy()

            dfWithSyllablesAndStrokes['identicalFirstStroke'] = dfWithSyllablesAndStrokes.apply(
                lambda x: True if x["Strokes"][0].lower() == x["firstSyllable"].lower() else False, axis=1)
            dfWithSyllablesAndStrokes['identicalLastStroke'] = dfWithSyllablesAndStrokes.apply(
                lambda x: True if x["Strokes"][-1].lower() == x["lastSyllable"].lower() else False, axis=1)

            dfWithSyllables = pd.concat([dfWithSyllablesAndStrokes, dfWithSyllablesButWithoutStrokes ])

            dfWithoutSyllables = df[df['syllables'].isnull()].copy()

            df= pd.concat([dfWithoutSyllables, dfWithSyllables], sort=False)

    elif(verbose):
        print("Expected syllables and Strokes Column in firstSyllablesColumn.")
    return  df

def syllablesPerStrokeColumn(df, verbose = False):
    """adds both a syllable per stroke Column and a syllableStrokeDifference to a dataframe that has a syllables column.
    Expects a dataframe as input and outputs a dataframe."""
    if verbose:
        print("Starting syllablesPerStrokeColumn...")
        print("first row of paramater entered:")
        print(str(df.iloc[0]))
    if "syllables" in df.columns.tolist() and "Strokes" in df.columns.tolist():
        dfWithSyllablesAndStrokes = df[np.logical_and(df["syllables"].notnull() , df['Strokes'].notnull() )].copy()

        if len(dfWithSyllablesAndStrokes) > 0:
            dfWithSyllablesAndStrokes['syllablesPerStroke'] = dfWithSyllablesAndStrokes.apply(lambda x: round(len(x['syllables']) / len(x['Strokes']),2), axis=1)
            dfWithSyllablesAndStrokes['syllableStrokeDifference'] = dfWithSyllablesAndStrokes.apply(lambda x: round(len(x['Strokes']) - len(x['syllables']),2), axis=1)

            dfWithoutSyllablesOrStrokes = df[np.logical_or(df["syllables"].isnull() , df['Strokes'].isnull() )].copy()

            df = pd.concat([dfWithSyllablesAndStrokes, dfWithoutSyllablesOrStrokes], sort= False)
    elif verbose:
        print("No 'syllables' and/or 'Strokes' column, not able to add 'syllablesPerStroke' Column.")
        print("returning the dataframe as is....")
    return df

def doAll(df, verbose = False):
    if verbose:
        print("Starting MakeColumnsForAnalysis.doall ...")
    df = syllablesPerStrokeColumn( NumStrokesColumn(df, verbose= verbose), verbose=verbose)
    df = firstAndLastSyllablesColumn(df, verbose= verbose)
    df = addStructureCols(df, verbose= verbose)
    df = NumStrokesColumn(df, verbose=True)
    return df

if __name__ == '__main__':
    import NoahAndChrisTesting, BigOuterMerge, FilterBeforeLogic, SplitPhoneticsAndSyllables

    TestDF = NoahAndChrisTesting.NoahDF
    TestDF = FilterBeforeLogic.filter1(BigOuterMerge.BigOuterMerge(TestDF), verbose= True)

    print("first break point...")
    #ChrisBoth, ChrisSyllablesOnly, ChrisPhoneticsOnly = SplitPhoneticsAndSyllables.SplitDF(ChrisDF)
    #ChrisBoth = TestDF.copy(deep=True)
    TestDF = NumStrokesColumn(
        syllablesPerStrokeColumn(
            firstAndLastSyllablesColumn(
                addStructureCols(TestDF)
            )
        )
    )

    print("about to close...")
    quit()


import os
import platform
#unpack
import gzip
import tarfile
import zipfile
#internet streaming
from urllib import request
from io import StringIO, FileIO
import requests
#flags
import config

def create_dir(dirpath):
    if not os.path.isdir(dirpath):
        os.mkdir(dirpath)

def unpickle(batchfile):
    if platform.python_implementation() == 'PyPy':
        from zodbpickle import pickle
    else:
        import _pickle as cPickle
    with open(batchfile, 'rb') as fd:
        dict_ = cPickle.load(fd, encoding='latin1')
    return dict_

def download_file_from_google_drive(fid, destination):
    from google_drive_downloader import GoogleDriveDownloader as gdd
    gdd.download_file_from_google_drive(file_id=fid,dest_path=destination)

def download_file_from_aws(s3path, destination):
    from os import system
    system("aws s3 cp {} {} --request-payer requester".format(s3path, destination))

def exists_or_download(filename, url, unpack=False, google_drive=False, amazon_aws=False):
    if not os.path.exists(filename):
        print("Download:", filename, "from:",url)
        if google_drive:
            download_file_from_google_drive(url,filename)
        elif amazon_aws:
            download_file_from_aws(url,filename)
        else:
            response = request.urlopen(url)
            with open(filename,'wb') as output:
                CHUNK_SIZE = 16 * 1024
                while True:
                    chunk = response.read(CHUNK_SIZE)
                    if not chunk:
                        break
                    else:
                        output.write(chunk)

    if unpack:
        print("unpack:", filename)
        if filename.endswith("zip"):
            if not os.path.exists(filename[:filename.rfind(".zip")]):
                zip_ = zipfile.ZipFile(filename, "r")
                zip_.extractall(config.SAVE)
                zip_.close()
        elif filename.endswith("tar.gz"):
            if not os.path.exists(filename[:filename.rfind(".tar.gz")]):
                tar = tarfile.open(filename, "r:gz")
                tar.extractall(config.SAVE)
                tar.close()
        elif filename.endswith("tar"):
            if not os.path.exists(filename[:filename.rfind(".tar")]):
                tar = tarfile.open(filename, "r:")
                tar.extractall(config.SAVE)
                tar.close()
        elif filename.endswith("gz"):
            outputpath = os.path.splitext(filename)[0]
            if not os.path.exists(outputpath):
                with open(filename,'wb') as ingzfile:
                    decompressedFile = gzip.GzipFile(fileobj=ingzfile, mode='rb')
                    with open(outputpath,'wb') as output:
                        output.write(decompressedFile.read())

def exists_or_download_list(filename, urlinfo_list):
    """
        urlinfo_list = [
            ( url, unpack, type )
        ]
        where type is a string which could be: None/download (standard), google or amazon
    """
    for info in urlinfo_list:
        if not os.path.exists(filename):
            url, unpack, dtype = info
            dw_google = dw_amazon = False
            if dtype in ('g',"google"):
                dw_google = True
            if dtype in ('aws', "amazon"):
                dw_amazon = True
            exists_or_download(filename, url, unpack=unpack,google_drive=dw_google, amazon_aws=dw_amazon)


from unittest import TestCase

from ......messaging.models.base import BaseModelError

from .....didcomm_prefix import DIDCommPrefix

from ...message_types import DIDX_COMPLETE
from ..complete import DIDXComplete

THID = "dummy-thid"
PTHID = "dummy-pthid"

class TestDIDXComplete(TestCase):
    def test_init_type(self):
        complete = DIDXComplete()
        assert complete._type == DIDCommPrefix.qualify_current(DIDX_COMPLETE)

    def test_serde(self):
        obj = {"~thread": {"thid": THID, "pthid": PTHID}}
        complete = DIDXComplete.deserialize(obj)
        assert complete._type == DIDCommPrefix.qualify_current(DIDX_COMPLETE)

        complete_dict = complete.serialize()
        assert complete_dict["~thread"] == obj["~thread"]

class TestDIDXCompleteSchema(TestCase):
    def test_make_model(self):
        complete = DIDXComplete()
        complete.assign_thread_id(THID, PTHID)
        data = complete.serialize()
        model_instance = DIDXComplete.deserialize(data)
        assert isinstance(model_instance, DIDXComplete)

    def test_serde_x(self):
        DIDXComplete.deserialize({})  # no thread attachment: OK as model
        x_complete = DIDXComplete()  # no thread attachment: should not deserialize
        with self.assertRaises(BaseModelError):
            data = x_complete.serialize()


import appdaemon.plugins.hass.hassapi as hass
from appdaemon.adbase import ADBase
import datetime

#
# Kiosk
#
# Args:
#input: input_boolean.test_kiosk
#state: "on"
#sequence:
#  - uri: https://ha.domain.me
#    delay: 60
#  - uri: https://dakboard.com/app/screenPredefined?p=id
#    delay: 180
#
# on publish <topic> <uri>
# off publish <topic> off
# tab publish <topic> tab://##

class Kiosk(ADBase):
   def initialize(self):
     self.hass = self.get_plugin_api("HASS")
     self.mqtt = self.get_plugin_api("MQTT")
     self.log("Kiosk startup")
     self.log_level = 1
     if "log_level" in self.args:
        self.log_level = self.args["log_level"]
     if "input" in self.args and "topic" in self.args:
        if self.log_level > 0:
           self.log("Subscribing to event for {}".format(self.args["input"]))
        self.hass.listen_state(self.state_change, self.args["input"])
        self.kiosk_index = 0
        self.loop = False
        self.kiosk_enabled = False
        self.switch_enabled = False
        self.send_off()
        if "enabled" in self.args:
           self.kiosk_enabled = self.hass.get_state(self.args["enabled"]) == "on"
           self.hass.listen_state(self.kiosk_state_change, self.args["enabled"])
        self.publish_state = False
        if "state_topic" in self.args:
           self.state_topic = self.args["state_topic"]
           self.publish_state = True

        self.initial_entry = False
        self.sequence = self.args["sequence"]
        if self.hass.get_state(self.args["input"]) == "on" and self.kiosk_enabled:
          self.switch_enabled = True
          self.initial_entry = True
          self.update_kiosk(False)

   def log(self, kwargs):
      self.hass.log(kwargs)
   # def mqtt_sub(self, event_name, data, kwargs):
   #    self.log("T:{} P:{} K:{}".format(event_name, data, kwargs))

   def kiosk_state_change(self, entity, attribute, old, new, kwargs):
      if (new == "on" and old == "off"):
         self.kiosk_enabled = True
         self.state_change(entity, attribute, old, new, kwargs)
      elif(new == "off" and old == "on"):
         self.kiosk_enabled = False
         self.state_change(entity, attribute, old, new, kwargs)

   def send_off(self):
      if "off_payload" in self.args:
         payload = self.args["off_payload"]
      else:
         payload = "off"
      self.switch_enabled = False
      if self.log_level > 0:
         self.log("sending {} to {}".format(payload, self.args["topic"]))
      self.mqtt.mqtt_publish(self.args["topic"], payload = payload)

   def state_change(self, entity, attribute, old, new, kwargs):
      if self.log_level > 0:
         self.log("{} turned {} from {}".format(entity, new, old))
      if (new == "on" and old == "off"):
         self.switch_enabled = True
         self.update_kiosk(False)
      elif new == "off" and old == "on":
         self.kiosk_index = 0
         self.loop = False
         self.send_off()

   def update_kiosk(self, useDelay):
      if (not self.switch_enabled or not self.kiosk_enabled):
         return

      entry = self.sequence[self.kiosk_index]
      self.kiosk_index+=1
      loop = False
      if (self.kiosk_index >= len(self.sequence)):
         self.kiosk_index = 0
         if (len(self.sequence) > 1):
            loop = True

      if (self.loop):
         uri = "tab://"
      else:
         uri = entry["uri"]

      if (loop):
         self.loop = loop

      if (self.initial_entry and useDelay):
         self.initial_entry = False
         delay = self.sequence[0]["delay"]
      else:
         if (useDelay):
            delay = entry["delay"]
         else:
            delay = 0

      state_payload = ""
      if self.publish_state:
         state_payload = entry["state_payload"]

      if self.log_level > 0:
         self.log("Action {} in {}".format(uri, delay))

      if (useDelay and len(self.sequence) > 1 or not useDelay):
         self.hass.run_in(self.action, delay, topic = self.args["topic"], uri = uri, state_payload = state_payload, fullUri = entry['uri'])

   def action(self, kwargs):
      if self.log_level > 1:
         self.log("Publish {} to {}".format(kwargs["fullUri"], kwargs["topic"]))
      if (not self.kiosk_enabled or not self.switch_enabled):
         if self.log_level > 1:
            self.log("Publish aborted for {}".format(kwargs["fullUri"]))
         return
      self.mqtt.mqtt_publish(kwargs["topic"], payload = kwargs["uri"])
      if (self.publish_state):
         self.mqtt.mqtt_publish(self.state_topic, payload = kwargs["state_payload"])
      if (self.kiosk_enabled):
         self.update_kiosk(True)


def allCount(s, t):
    """
        Ищет вхождение подстроки с ПЕРЕСЕЧЕНИЕМ
    :param s: строка
    :param t: строка
    :return: кол-во вхождений
    """
    s_size = len(s)
    i = 0
    for x in range(s_size):
        if s.startswith(t, x, s_size):
            i += 1
    return i

s = input()
t = input()
print(allCount(s, t))


from apitools.base.py import encoding
import six

__all__ = [
    'YieldFromList',
]

def _GetattrNested(message, attribute):
    """Gets a possibly nested attribute.

    Same as getattr() if attribute is a string;
    if attribute is a tuple, returns the nested attribute referred to by
    the fields in the tuple as if they were a dotted accessor path.

    (ex _GetattrNested(msg, ('foo', 'bar', 'baz')) gets msg.foo.bar.baz
    """
    if isinstance(attribute, six.string_types):
        return getattr(message, attribute)
    elif len(attribute) == 0:
        return message
    else:
        return _GetattrNested(getattr(message, attribute[0]), attribute[1:])

def _SetattrNested(message, attribute, value):
    """Sets a possibly nested attribute.

    Same as setattr() if attribute is a string;
    if attribute is a tuple, sets the nested attribute referred to by
    the fields in the tuple as if they were a dotted accessor path.

    (ex _SetattrNested(msg, ('foo', 'bar', 'baz'), 'v') sets msg.foo.bar.baz
    to 'v'
    """
    if isinstance(attribute, six.string_types):
        return setattr(message, attribute, value)
    elif len(attribute) < 1:
        raise ValueError("Need an attribute to set")
    elif len(attribute) == 1:
        return setattr(message, attribute[0], value)
    else:
        return setattr(_GetattrNested(message, attribute[:-1]),
                       attribute[-1], value)

def YieldFromList(
        service, request, global_params=None, limit=None, batch_size=100,
        method='List', field='items', predicate=None,
        current_token_attribute='pageToken',
        next_token_attribute='nextPageToken',
        batch_size_attribute='maxResults',
        get_field_func=_GetattrNested):
    """Make a series of List requests, keeping track of page tokens.

    Args:
      service: apitools_base.BaseApiService, A service with a .List() method.
      request: protorpc.messages.Message, The request message
          corresponding to the service's .List() method, with all the
          attributes populated except the .maxResults and .pageToken
          attributes.
      global_params: protorpc.messages.Message, The global query parameters to
           provide when calling the given method.
      limit: int, The maximum number of records to yield. None if all available
          records should be yielded.
      batch_size: int, The number of items to retrieve per request.
      method: str, The name of the method used to fetch resources.
      field: str, The field in the response that will be a list of items.
      predicate: lambda, A function that returns true for items to be yielded.
      current_token_attribute: str or tuple, The name of the attribute in a
          request message holding the page token for the page being
          requested. If a tuple, path to attribute.
      next_token_attribute: str or tuple, The name of the attribute in a
          response message holding the page token for the next page. If a
          tuple, path to the attribute.
      batch_size_attribute: str or tuple, The name of the attribute in a
          response message holding the maximum number of results to be
          returned. None if caller-specified batch size is unsupported.
          If a tuple, path to the attribute.
      get_field_func: Function that returns the items to be yielded. Argument
          is response message, and field.

    Yields:
      protorpc.message.Message, The resources listed by the service.

    """
    request = encoding.CopyProtoMessage(request)
    _SetattrNested(request, current_token_attribute, None)
    while limit is None or limit:
        if batch_size_attribute:
            # On Py3, None is not comparable so min() below will fail.
            # On Py2, None is always less than any number so if batch_size
            # is None, the request_batch_size will always be None regardless
            # of the value of limit. This doesn't generally strike me as the
            # correct behavior, but this change preserves the existing Py2
            # behavior on Py3.
            if batch_size is None:
                request_batch_size = None
            else:
                request_batch_size = min(batch_size, limit or batch_size)
            _SetattrNested(request, batch_size_attribute, request_batch_size)
        response = getattr(service, method)(request,
                                            global_params=global_params)
        items = get_field_func(response, field)
        if predicate:
            items = list(filter(predicate, items))
        for item in items:
            yield item
            if limit is None:
                continue
            limit -= 1
            if not limit:
                return
        token = _GetattrNested(response, next_token_attribute)
        if not token:
            return
        _SetattrNested(request, current_token_attribute, token)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools, os
import Actions
import time
import copy
import signal
from State import print_state
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from random import choice
from Debug import Debug

hasard_nb, policy_nb = 0, 0
interrupt_flag = False

def signal_handler(signal, frame):
        global interrupt_flag
        print('interrupt!')
        interrupt_flag = True

def get_possible_dirty_cells(grid_size, base_pos):
    """
    Etant donné une taille de grille et une position de la base dans la grille, retourne la liste de toutes les
    combinaisons de cellules salles possible
    :param grid_size: un tuple (x,y) représentant la taille de la grille
    :param base_pos: [x, y] la position de la base
    :return:
    """
    possible_grid_list = [list(i) for i in itertools.product([0, 1], repeat=grid_size[0] * grid_size[1]) if
                          list(i)[base_pos[0] + base_pos[1] * grid_size[0]] == 0]

    possible_dirty_cells = list()
    for possible in possible_grid_list:
        l = list()
        for index, case in enumerate(possible):
            if case == 1:
                l.append([index % grid_size[0], index // grid_size[0]])
        possible_dirty_cells.append(l)

    return possible_dirty_cells

def get_all_states(max_battery_level, grid_size):
    states = list()
    coords = [[x, y] for x in range(grid_size[0]) for y in range(grid_size[1])]
    for level in range(max_battery_level + 1):
        for robot_pos in coords:
            for base_pos in coords:
                for dirty_cells in get_possible_dirty_cells(grid_size, base_pos):
                    state = {
                        "base_pos": base_pos,
                        "robot_pos": robot_pos,
                        "dirty_cells": sorted(dirty_cells),
                        "battery_level": level
                    }

                    states.append(state)

    return states

def dynamic_programming(all_states, simulator, gamma, epsilon):
    """
    Implémentation de l'optimisation de la politique par dynamic programming
    :param all_states: la liste de tous les états
    :param simulator: le simulateur
    :param gamma:
    :param epsilon:
    :return policy: la politique optimale
    """

    # Initialisation de la politique et de la fonction de valeur
    value_function = dict()
    value_function_bis = dict()
    policy = dict()
    for state in all_states:
        value_function[str(state)] = 0
        value_function_bis[str(state)] = 1
        policy[str(state)] = "stay"

    stop_criteria = max([abs(value_function[i] - value_function_bis[i]) for i in value_function.keys()])
    mean_values = [0.]
    x = [0]
    while stop_criteria > epsilon:
        value_function_bis = Actions.reasign(value_function)

        mean_value = 0.
        for state in all_states:
            to_maximize = []
            action_list = simulator.get_actions(state)
            for i, action in enumerate(action_list):
                reward, future = simulator.get_with_model(action, state)
                to_maximize.append(reward)

                for proba, future_state in future:
                    to_maximize[i] += gamma * proba * value_function[str(future_state)]

            value_function[str(state)] = max(to_maximize)
            mean_value += value_function[str(state)]

            opti_action = action_list[to_maximize.index(value_function[str(state)])]
            policy[str(state)] = opti_action

        stop_criteria = max([abs(value_function[i] - value_function_bis[i]) for i in value_function.keys()])
        print("dynamic programming iteration:", stop_criteria, "<", epsilon, "?")

        # for plotting
        x.append(x[-1] + 1)
        mean_value = mean_value / len(all_states)
        mean_values.append(mean_value)

    # plot
    dirname = os.path.dirname(os.path.abspath(__file__))
    # plt.figure()

    plt.plot(x, mean_values)

    title = 'DP, EPSILON=' + "{:3}".format(epsilon) + " GRID=" + "{:9}".format(str(simulator.grid_size)) + "BAT:" + str(
        simulator.max_battery_level) + " - mean_values of policy"
    plt.title(title)
    plt.ylabel('Mean value')
    plt.xlabel('Iteration')
    plt.draw()
    plt.savefig(dirname + "/plots/" + title + ".png")

    return policy

def a_epsilon_greedy(simulator, state, epsilon, policy):
    """
    Etant donnée un état, et un hyperparamètre epsilon retourne en fonction d'un tirage dépendant de epsilon
    une action pris au hasard dans la liste des actions possibles, ou celles prescrite par la politique
    :param simulator: le simulateur
    :param state: un état
    :param epsilon: un hyperparamètre
    :param policy: la politique
    :return: une action
    """
    global policy_nb, hasard_nb
    action_list = simulator.get_actions(state)
    if simulator.roll_dice(1 - epsilon + epsilon/len(action_list)):
        policy_nb += 1
        return policy[str(state)]
    else:
        hasard_nb += 1
        a = choice(action_list)
        return a

def q_epsilon_greedy(simulator, state, epsilon, action_list, q_function):
    """
    Fonction epsillon greedy qui renvoit l'action de la fonction de Qvaleur associée à un état
    :param simulator: Notre simulateur comprenant des focntionnalités de tirage aléatoire
    :param state: Etat du système actuel
    :param epsillon: Paramètre de convergence
    :param action_list: Liste des actions possibles pour l'état state
    :param q_function: Représentation de notre fonction de Qvaleur
    :return: l'action de la fonction de Qvaleur associée à un état selon la loie epsilon greedy
    """
    if simulator.roll_dice(1 - epsilon + epsilon/len(action_list)):
        q_action_list = [q_function[str(state), action] for action in action_list]
        action_index = q_action_list.index(max(q_action_list))
        # print(1 - epsilon + epsilon / len(action_list), "Qvaleur maximisée")
        return action_list[action_index]
    else:
        a = choice(action_list)
        # print(1 - epsilon + epsilon / len(action_list), "Qvaleur hasard")
        return a

def monte_carlo(all_states, simulator, time_limit, T, gamma, epsilon, alpha, initial_state, step=1):
    """
    Implémentation de l'optimisation de la politique par monte_carlo control
    :param all_states: la liste de tous les états
    :param simulator: le simulateur
    :param time_limit: la limite de temps en seconde
    :param T: la longueur des épisodes générés
    :param gamma: un hyperparamètre
    :param epsilon: un autre hyperparamètre
    :param alpha: encore un
    :param initial_state: l'état initial
    :return policy: la politique
    """
    global policy_nb, hasard_nb
    # Initialisation de la q_function et la policy
    q_function = dict()
    policy = dict()
    for state in all_states:
        possible_actions = simulator.get_actions(state)
        policy[str(state)] = choice(possible_actions)
        for action in possible_actions:
            q_function[str(state), action] = 0

    start_time = time.time()
    time_spent, count = 0, 1
    iter = 0
    mean_rewards, x = [], []
    v_s0 = []
    episode = []
    stop = True
    while time.time() - start_time < time_limit:
        s0 = Actions.reasign(initial_state)

        # on print toutes les 10 secondes pour ne pas polluer la console
        time_spent = time.time() - start_time
        if time_spent > step * count:
            count += 1
            action_list = simulator.get_actions(s0)
            q_values_s0 = [q_function[str(s0), action] for action in action_list]
            Debug("monte_carlo iteration, elapsed time", time.time() - start_time, v_s0=max(q_values_s0))
            # Debug(policy_nb=policy_nb, hasard_nb=hasard_nb, epsilon=epsilon,
            #       policy_proba=1 - epsilon + epsilon/len(action_list))

            # add value to vector for plot
            mean_reward = total_reward/T
            mean_rewards.append(mean_reward)
            v_s0.append(max(q_values_s0))
            x.append(step * count)

        # generation d'un episode
        episode = []
        policy_nb, hasard_nb = 0, 0
        for t in range(T + 1):
            a0 = a_epsilon_greedy(simulator, s0, epsilon, policy)
            # print(s0, a0)
            reward, future_state = simulator.get(a0, s0)
            episode.append((s0, a0, reward))
            s0 = future_state

        total_reward = 0
        for t, event in enumerate(episode):
            # calcul du retour
            retour = 0
            for k in range(t, T + 1):
                retour += (gamma ** (k - t)) * episode[k][2]
            total_reward += event[2]

            # maj q _value
            q_function[str(event[0]), event[1]] += alpha * (retour - q_function[str(event[0]), event[1]])

            # maj politique
            q_action_list = [q_function[str(event[0]), action] for action in simulator.get_actions(event[0])]
            action_index = q_action_list.index(max(q_action_list))
            policy[str(event[0])] = simulator.get_actions(event[0])[action_index]
        if epsilon > 0.1:
            epsilon /= 1.00001

        if interrupt_flag:
            break

    # Print final
    print("### FIN du calcul ###")
    print("actions en s0:", simulator.get_actions(initial_state))
    print("q_val associées:",
          ["{:05.2f}".format(q_function[str(initial_state), action]) for action in simulator.get_actions(initial_state)])
    print("monte_carlo iteration, elapsed time: {:05.2f},".format(time.time() - start_time),
          "v(s0) = {:6.2f}".format(max([q_function[str(initial_state), action] for action in simulator.get_actions(initial_state)])))

    dirname = os.path.dirname(os.path.abspath(__file__))
    print(dirname)
    # plt.figure()
    plt.plot(x, mean_rewards)
    title = 'MC, T=' + "{:3}".format(T) + " GRID=" + "{:9}".format(str(simulator.grid_size)) + "BAT:" + str(simulator.max_battery_level) + " T_LIMIT:" + "{:5}".format(time_limit) + " - mean_reward"
    plt.title(title)
    plt.ylabel('Récompense moyenne')
    plt.xlabel('Time(s)')
    plt.draw()
    print(os.path.join(dirname, "/plots/", title + ".png"))
    plt.savefig(dirname + "/plots/" + title + ".png")

    plt.clf()
    plt.plot(x, v_s0)
    title = 'MC, T=' + "{:3}".format(T) + " GRID=" + "{:9}".format(str(simulator.grid_size)) + "BAT:" + str(simulator.max_battery_level) + " T_LIMIT:" + "{:5}".format(time_limit) + " - v_s0(t)"
    plt.ylabel('v(s0)')
    plt.xlabel('Time(s)')
    plt.draw()
    plt.savefig(dirname + "/plots/" + title + ".png")

    return policy

def q_learning(all_states, simulator, time_limit, gamma, epsilon, alpha, initial_state):

    # Initialisation de la q_function et la policy
    q_function = dict()
    policy = dict()
    for state in all_states:
        policy[str(state)] = choice(simulator.get_actions(state))
        for action in simulator.get_actions(state):
            q_function[str(state), action] = 0

    s0 = Actions.reasign(initial_state)
    a0 = a_epsilon_greedy(simulator, s0, epsilon, policy)

    # Algorithme de Q Learning
    start_time = time.time()
    count = 1
    q_values_s0, t = [], []
    while time.time() - start_time < time_limit:
        global interrupt_flag
        # print("q_Learning iteration, elapsed time:", time.time() - start_time)

        reward, future_state = simulator.get(a0, s0)
        future_action = q_epsilon_greedy(simulator, future_state, epsilon, simulator.get_actions(future_state), q_function)
        delta = reward + gamma * q_function[str(future_state), future_action] - q_function[str(s0), a0]

        # Maj q_value
        q_function[str(s0), a0] += alpha * delta
        s0 = future_state
        a0 = future_action

        # Maj politique
        action_list = simulator.get_actions(s0)
        q_action_list = [q_function[str(s0), action] for action in action_list]
        policy[str(s0)] = action_list[q_action_list.index(max(q_action_list))]

        if reward == simulator.dead_reward:
            s0 = Actions.reasign(initial_state)
            a0 = a_epsilon_greedy(simulator, initial_state, epsilon, policy)

        # Debug
        time_spent = time.time() - start_time
        if time_spent > 1 * count:
            count += 1
            t.append(time_spent)
            q_values = [q_function[str(initial_state), action] for action in simulator.get_actions(initial_state)]
            q_value_s0 = max(q_values)
            q_values_s0.append(q_value_s0)
            Debug("time spent", time_spent, q_value_s0=q_value_s0)

        if interrupt_flag:
            break

    # Plot
    dirname = os.path.dirname(os.path.abspath(__file__))
    plt.plot(t, q_values_s0)
    title = 'QL, GRID=' + "{:9}".format(str(simulator.grid_size)) + "BAT:" + str(simulator.max_battery_level) + " T_LIMIT:" + "{:5}".format(time_limit) + " - q_value_s0"
    plt.title(title)
    plt.ylabel('q_value_s0')
    plt.xlabel('Time(s)')
    plt.draw()
    plt.savefig(os.path.join(dirname, "plots", str(title) + ".png"))

    return policy


from django.db import models

# Create your models here.

class Habitaciones(models.Model):
    imagen = models.CharField( max_length=150)
    tipo =  models.CharField(max_length=50)
    precio = models.DecimalField(max_digits=20, decimal_places=10)
    capacidad = models.IntegerField()
    caracteristicas = models.TextField(max_length=500)
    numero = models.IntegerField()
    disponibilidad = models.BooleanField(default=True)

    def __str__(self):
        return self.numero


#Author: Adam Ferrante
#Class: CIT-135-01
#Assignment: Python 2.1 ( First Program )
#Date Assigned: September 6, 2017
#Due Date and Time: September 11, 2017
#Description: This program inputs dimensions of a room, and calculates how much paint is needed for the walls and ceiling with 2 coats each.
###
#Certification of Authenticity:  I certify that this is entirely my own work,
#except where I have given fully-documented references to the work of others.
#I understand the definition and consequences of plagiarism and acknowledge
#that the assessor of this assignment may, for the purpose of assessing
#this assignment: - Reproduce this assignment and provide a copy
#to another member of academic staff; and/or Communicate a copy
#of this assignment to a plagiarism checking service (which may then retain
#a copy of this assignment on its database for the purpose of
#future plagiarism checking)
###

import math

#Prompt the user for the dimensions of the room.
length = int(input("What is the length, in feet, of the room?: "))
width = int(input("What is the width, in feet, of the room?: "))
height = int(input("What is the height, in feet, of the room?: "))

#Finds the area of the walls in the room.
wall_area = (length * height) * 2
wall_area_2 = (width * height) * 2

#Calculates the total square-footage of paint needed to paint the room with 2 coats of paint.
walls_total = (wall_area + wall_area_2) * 2

#Calculates how many gallons of paint are needed for this project.
wall_cans_needed = math.ceil(walls_total / 250)

print("You will need {} can(s) of paint to complete the walls of this room.".format(wall_cans_needed))

# Calculates the surface area of the ceiling.
ceiling_surface_area = length * width

# Calculates the amount of paint cans needed for the ceiling.
ceiling_paint_needed = ceiling_surface_area * 2
ceiling_cans_needed = math.ceil(ceiling_paint_needed / 200)

print("You will need {} can(s) of paint to complete the walls of this room.".format(ceiling_cans_needed))


class Relation:
    def xMethod(self, name1, name2, relation, degree):
        if relation == 'child':
            if name1 in name2.get_children(name2):
                return 'Yes'
            else:
                return 'No'

        if relation == 'sibling':
            if name2 in name1.get_siblings():
                return 'yes'
            else:
                return 'no'

        if relation == 'ancestor':
            if name1 in self.getAncestors(name2):
                return 'yes'
            else:
                return 'no'

        if relation == 'cousin':
            if self.isCousin(name1, name2) is True:
                return 'yes'
            else:
                return 'no'

        if relation == 'cousin' and degree > -1:
            if self.isCousin2(name1, name2, degree) is True:
                return 'Yes'
            else:
                return 'No'

        if relation == 'unrelated':
            if self.isRelated(name1, name2) is True:
                return 'no'
            else:
                return 'yes'

    def wMethod(self, name1, relation, tree, degree):

        if relation == 'child':
            plist = list()
            for a in name1.get_children():
                plist.append(a.get_name())

            plist.sort()
            return plist

        if relation == 'sibling':
            slist = []
            for a in name1.get_siblings():
                slist.append(a.get_name())

            slist.sort()
            return slist

        if relation == 'ancestor':
            alist = list()
            for a in self.getAncestors(name1):
                if a.get_name() not in alist:
                    alist.append(a.get_name())

            alist.sort()
            return alist

        if relation == 'cousin':
            clist = list()
            for a in self.getCousins(name1, tree):
                if a.get_name() not in clist:
                    clist.append(a.get_name())

            clist.sort()
            return clist

        if relation == 'cousin' and degree > -1:
            clist = list()
            for a in self.getCousins2(name1, tree, degree):
                if a.get_name() not in clist:
                    clist.append(a.get_name())

            clist.sort()
            return clist

        if relation == 'unrelated':
            rlist = list()
            for a in self.getUnrelated(name1, tree):
                if a.get_name() not in rlist:
                    rlist.append(a.get_name())

            rlist.sort()
            return rlist

    def getAncestors(self, name):
        ancestors = list()
        if name is None:
            return []
        if len(name.get_parents()) < 1:
            return []
        else:
            ancestors.append(name.get_parents()[0])
            ancestors.append(name.get_parents()[1])
            ancestors.extend(self.getAncestors(name.get_parents()[0]))
            ancestors.extend(self.getAncestors(name.get_parents()[1]))

        return ancestors

    def isRelated(self, name1, name2):
        result = False
        memberAncestors = self.getAncestors(name1)
        relativeAncestors = self.getAncestors(name2)

        # check if they share common ancestor
        for person1 in memberAncestors:
            for person2 in relativeAncestors:
                if person1 == person2:
                    result = True

        # check if one is a direct ancestor
        for person in memberAncestors:
            if person == name2:
                result = True

        for person in relativeAncestors:
            if person == name1:
                result = True

        return result

    def isCousin(self, name1, name2):
        result = False
        memberAncestors = self.getAncestors(name1)
        relativeAncestors = self.getAncestors(name2)

        # check if they share common ancestor
        for person1 in memberAncestors:
            for person2 in relativeAncestors:
                if person1 == person2:
                    result = True

        # check if one is a direct ancestor
        for person in memberAncestors:
            if person == name2:
                result = False

        for person in relativeAncestors:
            if person == name1:
                result = False

        return result

    def isCousin2(self, name1, name2, degree):  # not finished *************
        result = False
        memberAncestors = self.getAncestors(name1)
        relativeAncestors = self.getAncestors(name2)

        # check if they share common ancestor
        for person1 in memberAncestors:
            for person2 in relativeAncestors:
                if person1 == person2:
                    result = True

        # check if one is a direct ancestor
        for person in memberAncestors:
            if person == name2:
                result = False

        for person in relativeAncestors:
            if person == name1:
                result = False

        return result

    def getUnrelated(self, name, familyTree):
        unRelated = list()

        if name is None:
            return []
        else:
            for person1 in familyTree.values():
                if self.isRelated(person1, name) is False:
                    unRelated.append(person1)
        return unRelated

    def getCousins(self, name, tree):
        if name is None:
            return []
        cousins = list()
        for cousin in tree.values():
            if self.isCousin(name, cousin) and name != cousin:
                    cousins.append(cousin)
        return cousins

    def getCousins2(self, name, tree, degree):  # not finished *************
        if name is None:
            return []
        cousins = list()
        for cousin in tree.values():
            if self.isCousin(name, cousin) and name != cousin:
                    cousins.append(cousin)
        return cousins


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
import cv2
import imageio

class Nucleation:
    def __init__(self, x, y, m, g, sig, t):
        self.x = int(x)
        self.y = int(y)
        self.m = m
        self.g = g
        self.sig = sig
        self.radius = 0.
        self.create_time = t

    def get_coordinates(self):
        return np.asarray([self.x, self.y])

    def update_radius(self, t):
        # fix radius growth to 1 per time step
        self.radius += self.g

    def calc_circular_radius(self):
        vol = self.sig * self.radius ** (self.m - 1)
        return int(np.sqrt(vol))

def simulation(t, state, time_state, is_dissociated, nucleation_list, m, n, g, sig, sim_protein=False, min_repair_t=3.):
    # Growth
    for nucleation in nucleation_list:
        nucleation.update_radius(t)
        circ_radius = nucleation.calc_circular_radius()
        state = cv2.circle(state, nucleation.get_coordinates(), circ_radius, 1., -1)

    mask = np.logical_and(state == 1., time_state == -1)
    time_state[mask] = t

    if sim_protein:
        is_dissociated = np.logical_or(
            np.logical_and(
                t - time_state > min_repair_t + np.random.exponential(scale=1.),
                time_state != -1.
            ),
            is_dissociated
        )
        state[is_dissociated] = 0

    nucleation_candidates = np.random.binomial(1, p=n, size=state.shape) == 1
    new_nucleation = zip(*np.where(np.logical_and(nucleation_candidates, time_state == -1.)))
    for x, y in new_nucleation:
        nucleation_list.append(Nucleation(x, y, m, g, sig, t))

    return state, nucleation_list

def run_simulation(
        m,
        theta,
        n_p,
        g_p,
        sig_p,
        to_time=80,
        shape=(200, 200),
        do_sort=False,
        save_gif=False,
        sim_protein=False,
        min_repair_t=3.
):
    state = np.zeros(shape)
    time_state = -np.ones(shape)
    is_dissociated = np.zeros(shape, dtype='bool')
    nucleation_list = []
    state_list = []
    sim_rep_frac = []

    plt.ion()
    norm = Normalize(vmin=0, vmax=1)
    plt.figure(figsize=(8, 7))
    ax = plt.gca()
    for t in np.arange(to_time):
        state, nucleation_list = simulation(
            t,
            state,
            time_state,
            is_dissociated,
            nucleation_list,
            m,
            n_p,
            g_p,
            sig_p,
            sim_protein,
            min_repair_t
        )
        ax.clear()
        if do_sort:
            y_sort = np.argsort(state).reshape(-1)
            x_sort = np.repeat(np.arange(state.shape[0]), state.shape[1]).reshape(-1)
            ax.imshow(state[x_sort, y_sort].reshape(state.shape), cmap='Reds', norm=norm)
            state_list.append(state[x_sort, y_sort].reshape(state.shape))
        else:
            ax.imshow(state, cmap='Reds', norm=norm)
            state_list.append(state.astype('uint8').copy() * 255)
        ax.set_title('Time %s' % t)
        fig = plt.gcf()
        fig.canvas.draw()

        coloured = np.sum(state == 1.)
        sim_rep_frac.append((coloured / state.size) * theta)

        fig.canvas.flush_events()

    if save_gif:
        save_name = 'sorted' if do_sort else 'random'
        imageio.mimsave('figures/gif/%s_500.gif' % save_name, state_list, format='GIF-PIL', fps=10)

    plt.ioff()
    plt.close('all')
    return sim_rep_frac


import bpy, mathutils, math, os

class ahs_maincurve_fleshout(bpy.types.Operator):
	bl_idname = 'object.ahs_maincurve_fleshout'
	bl_label = "肉付け"
	bl_options = {'REGISTER', 'UNDO'}

	items = [
		('Basic', "基本", "", 'MOD_CURVE', 1),
		('Sphere', "円", "", 'SPHERECURVE', 2),
		]
	taper_type = bpy.props.EnumProperty(items=items, name="テーパー", default='Basic')

	items = [
		('Sphere', "円", "", 'SURFACE_NCIRCLE', 1),
		('Sharp', "シャープ", "", 'LINCURVE', 2),
		('V', "切り込み", "", 'FILE_TICK', 3),
		('Corrugated', "ギザギザ", "", 'RNDCURVE', 4),
		]
	bevel_type = bpy.props.EnumProperty(items=items, name="ベベル", default='Sphere')

	scale = bpy.props.FloatProperty(name="サイズ", default=0.2, min=0, max=10, soft_min=0, soft_max=10, step=3, precision=2)
	scale_y = bpy.props.FloatProperty(name="平たさ", default=0.5, min=0, max=1, soft_min=0, soft_max=1, step=3, precision=2)

	@classmethod
	def poll(cls, context):
		try:
			for ob in context.selected_objects:
				if ob.type == 'CURVE': break
			else: return False
		except: return False
		return True

	def draw(self, context):
		self.layout.prop(self, 'taper_type')
		self.layout.prop(self, 'bevel_type')
		self.layout.prop(self, 'scale')
		self.layout.prop(self, 'scale_y', slider=True)

	def execute(self, context):
		# すでにテーパーかベベルとして指定されているオブジェクトをリスト
		taper_and_bevel_objects = [c.taper_object for c in context.blend_data.curves] + [c.bevel_object for c in context.blend_data.curves]

		blend_path = os.path.join(os.path.dirname(__file__), "_append_data.blend")

		for ob in context.selected_objects:
			if ob in taper_and_bevel_objects: continue
			if ob.type != 'CURVE': continue

			curve = ob.data

			# すでにテーパーかベベルがあって参照が1つの場合は削除
			if curve.taper_object:
				if len([c.taper_object for c in context.blend_data.curves if c.taper_object == curve.taper_object]) == 1:
					o, c = curve.taper_object, curve.taper_object.data
					if o: context.blend_data.objects.remove(o, do_unlink=True)
					if c: context.blend_data.curves.remove(c, do_unlink=True)
			if curve.bevel_object:
				if len([c.bevel_object for c in context.blend_data.curves if c.bevel_object == curve.bevel_object]) == 1:
					o, c = curve.bevel_object, curve.bevel_object.data
					if o: context.blend_data.objects.remove(o, do_unlink=True)
					if c: context.blend_data.curves.remove(c, do_unlink=True)

			# テーパーオブジェクトをアペンドして割り当て
			with context.blend_data.libraries.load(blend_path) as (data_from, data_to):
				data_to.objects = ["Taper_" + self.taper_type]
			taper_curve_ob = data_to.objects[0]
			taper_curve = taper_curve_ob.data
			name = ob.name + ":Taper"
			taper_curve_ob.name, taper_curve.name = name, name
			context.scene.objects.link(taper_curve_ob)
			curve.taper_object = taper_curve_ob

			# ベベルオブジェクトをアペンドして割り当て
			with context.blend_data.libraries.load(blend_path) as (data_from, data_to):
				data_to.objects = ["Bevel_" + self.bevel_type]
			bevel_curve_ob = data_to.objects[0]
			bevel_curve = bevel_curve_ob.data
			name = ob.name + ":Bevel"
			bevel_curve_ob.name, bevel_curve.name = name, name
			context.scene.objects.link(bevel_curve_ob)
			curve.bevel_object = bevel_curve_ob

			# 位置変更
			if not len(curve.splines): continue
			end_co = ob.matrix_world * mathutils.Vector(curve.splines[0].points[-1].co[:3])
			taper_curve_ob.location, bevel_curve_ob.location = end_co.copy(), end_co.copy()

			# 拡縮変更
			taper_curve_ob.scale = (self.scale, self.scale, self.scale)
			bevel_curve_ob.scale = (self.scale, self.scale * self.scale_y, self.scale)

		return {'FINISHED'}


""" Random model generating predictions based on a uniform distribution.

"""

import ccobra
import numpy as np
import copy
from bidict import bidict

class PreferredModel(ccobra.CCobraModel):
    def __init__(self, name='PMM 2020 Baseline'):
        super(PreferredModel, self).__init__(name, ['syllogistic-generalized'], ['single-choice'])

        self.axioms = {
        'All': self.axiom_all,
        'Most': self.axiom_most,
        'Most not': self.axiom_few,
        'Some': self.axiom_some,
        'Some not': self.axiom_some_not,
        }

    def sharing_rows(self, model, x, y, invert_row = None):
        copy_model = copy.copy(model)
        if invert_row:
            copy_model[:, invert_row] = np.invert(copy_model[:, invert_row])

        count = 0
        for row in copy_model:
            if row[x] and row[y]:
                count += 1
        return count

    def axiom_all(self, model, x, y):
        return  (model[:, x].sum() != 0 and
        model[:, y].sum() != 0 and
        model[:, x].sum() == self.sharing_rows(model, x, y)) #and
        #model[:, y].sum() == self.sharing_rows(model, x, y))

    def axiom_some(self, model, x, y):
        return  (self.sharing_rows(model, x, y) != 0 and
                self.sharing_rows(model, x, y) == self.sharing_rows(model, x, y, invert_row=y))

    def axiom_some_not(self, model, x, y):
        return  (0 != self.sharing_rows(model, x, y, invert_row=y) and
                self.sharing_rows(model, x, y) == self.sharing_rows(model, x, y, invert_row=y))

    def axiom_most(self, model, x, y):
        return  (self.sharing_rows(model, x, y, invert_row=y) < self.sharing_rows(model, x, y) and
                0 != self.sharing_rows(model, x, y, invert_row=y))

    def axiom_few(self, model, x, y):
        return  (self.sharing_rows(model, x, y, invert_row=y) > self.sharing_rows(model, x, y) and
                0 != self.sharing_rows(model, x, y))

    def fill_first_premise(self, model, quantifier, instance_a, instance_b):
        if quantifier == 'All':
            model[0, instance_a] = 1
            model[0, instance_b] = 1
        elif quantifier == 'Most':
            model[0:3, instance_a] = 1
            model[0:2, instance_b] = 1
        elif quantifier == 'Few' or quantifier == 'Most not':
            model[0:3, instance_a] = 1
            model[0, instance_b] = 1
        elif quantifier == 'Some' or quantifier == 'Some not':
            model[0:2, instance_a] = 1
            model[0, instance_b] = 1
            model[2, instance_b] = 1
        else:
            model[0, instance_a] = 1
            model[1, instance_b] = 1

        return model

    def fill_instance_c(self, model, max_num, instance_c, instance_b):
        for i in range(model.shape[0]-1, -1, -1):
                if model[:, instance_c].sum() == max_num:
                    break
                if model[i, instance_b] == 1:
                    model[i, instance_c] = 1
        return model

    def fill_second_premise(self, model, quantifier, instance_b, instance_c, instance_a):
        if quantifier == 'All':
            for i in range(model.shape[0]):
                if model[i, instance_b] == 1:
                    model[i, instance_c] = 1

        # For each quantifier
        num_a = model[:, instance_a].sum()

        if quantifier == 'Most':
            # Fill instance B ...
            for i in range(num_a, model.shape[0]):
                if model[:, instance_b].sum() == 3:
                    break
                if model[i, instance_b] == 0 and model[i, instance_a] == 0:
                    model[i, instance_b] = 1
            # Then instance C
            model = self.fill_instance_c(model, 2, instance_c, instance_b)

        if quantifier == 'Most not':
            # Fill instance B ...
            for i in range(num_a, model.shape[0]):
                if model[:, instance_b].sum() == 3:
                    break
                if model[i, instance_b] == 0 and model[i, instance_a] == 0:
                    model[i, instance_b] = 1

            model = self.fill_instance_c(model, 1, instance_c, instance_b)

        if quantifier == 'Some' or quantifier == 'Some not':
            # Fill instance B ...
            for i in range(num_a, model.shape[0]):
                if model[:, instance_b].sum() >= 2:
                    break
                if model[i, instance_b] == 0:
                    model[i, instance_b] = 1

            model = self.fill_instance_c(model, 1, instance_c, instance_b)

        if quantifier == 'No':
            for i in reversed(range(model.shape[0])):
                if model[i, instance_b] == 0:
                    model[i, instance_c] = 1
                    break
        return model

    def predict(self, item, **kwargs):
        """
        Generate random response prediction.
        """
        model = np.zeros((6, 3), dtype=bool)

        syl = ccobra.syllogistic_generalized.GeneralizedSyllogism(item)

        if syl.figure == 2:
            prs = item.task_str.split("/")
            new_task = prs[1] + "/" + prs[0]
            new_item = ccobra.Item(item.identifier, item.domain, new_task,
                                   item.response_type, item.choices_str,
                                   item.sequence_number)
            syl = ccobra.syllogistic_generalized.GeneralizedSyllogism(new_item)

        instances = bidict({syl.A: 0, syl.B: 1, syl.C: 2})

        # Fill first premise
        q1, i0, i1 = syl.p1
        model = self.fill_first_premise(model, q1, instances[i0], instances[i1])

        # Fill model with second premise
        q2, i2, i3 = syl.p2
        model = self.fill_second_premise(model, q2, 1, 2, 0)

        print(syl.task)
        if syl.task[0][0] == 'Some' and syl.task[1][0] == 'Some':
            print(model.astype(int))

        for quantifier in self.axioms:
            if self.axioms[quantifier](model, 0, 2):
                print('Prediction1', quantifier, syl.A, syl.C)
                return [[quantifier, syl.A, syl.C]]

        print('No conclusion possible')
        return [['NVC']]


from pyspark.sql.types import DecimalType, StructField, StructType, ArrayType, DataType

def assert_schema(
    actual: StructType,
    expected: StructType,
    ignore_nullability: bool = False,
    ignore_column_order: bool = False,
    ignore_decimal_scale: bool = False,
    ignore_decimal_precision: bool = False,
) -> None:
    """
    When actual schema does not match the expected schema,
    raises an AssertionError with an error message starting with 'Schema mismatch'.

    The function provides options to provide a more lenient comparison for either
    special cases or to allow a stepwise implementation of more strict checks.
    """
    if actual == expected:
        return

    strict = not (
        ignore_nullability
        or ignore_column_order
        or ignore_decimal_precision
        or ignore_decimal_scale
    )
    if strict:
        _raise(f"Expected {expected}, but got {actual}.")

    actual_fields = actual.fields
    expected_fields = expected.fields

    if ignore_column_order:
        actual_fields = sorted(actual_fields, key=lambda f: f.name)
        expected_fields = sorted(expected_fields, key=lambda f: f.name)

    for actual_field, expected_field in zip(actual_fields, expected_fields):
        _assert_column_name(actual_field, expected_field)
        _assert_field(
            actual_field,
            expected_field,
            ignore_decimal_precision,
            ignore_decimal_scale,
            ignore_nullability,
        )

def _assert_field(
    actual: StructField,
    expected: StructField,
    ignore_decimal_precision: bool,
    ignore_decimal_scale: bool,
    ignore_nullability: bool,
) -> None:
    if not ignore_nullability:
        _assert_struct_field_nullability(actual, expected)
    _assert_data_type(
        actual.dataType,
        expected.dataType,
        expected.name,
        ignore_decimal_precision,
        ignore_decimal_scale,
    )

def _assert_struct_field_nullability(
    actual: StructField, expected: StructField
) -> None:
    if actual.nullable != expected.nullable:
        _raise(
            f"Expected column name '{expected.name}' to have nullable={expected.nullable}, but got nullable={actual.nullable}"
        )

    _assert_data_type_nullability(actual.dataType, expected.dataType)

def _assert_data_type_nullability(actual: DataType, expected: DataType) -> None:
    """Recursively asserts that nullability of array type elements matches."""
    if not isinstance(actual, ArrayType) or not isinstance(expected, ArrayType):
        return

    if actual.containsNull != expected.containsNull:
        _raise(
            f"Expected array with element type '{expected.elementType}' to have nullable={expected.containsNull}, but got nullable={actual.containsNull}"
        )

    _assert_data_type_nullability(actual.elementType, expected.elementType)

def _assert_column_name(actual: StructField, expected: StructField) -> None:
    if actual.name != expected.name:
        _raise(f"Expected column name '{expected.name}', but found '{actual.name}'")

def _assert_data_type(
    actual: DataType,
    expected: DataType,
    column_name: str,
    ignore_decimal_precision: bool,
    ignore_decimal_scale: bool,
) -> None:
    if actual == expected:
        return

    if isinstance(actual, ArrayType) and isinstance(expected, ArrayType):
        _assert_data_type(
            actual.elementType,
            expected.elementType,
            column_name,
            ignore_decimal_precision,
            ignore_decimal_scale,
        )
        return

    if not isinstance(actual, DecimalType) or not isinstance(expected, DecimalType):
        _raise(
            f"Expected column name '{column_name}' to have type {expected}, but got type {actual}"
        )

    if not ignore_decimal_precision and actual.precision != expected.precision:
        _raise(
            f"Decimal precision error: Expected column name '{column_name}' to have type {expected}, but got type {actual}"
        )

    if not ignore_decimal_scale and actual.scale != expected.scale:
        _raise(
            f"Decimal scale error: Expected column name '{column_name}' to have type {expected}, but got type {actual}"
        )

def _raise(error_message: str) -> None:
    raise AssertionError(f"Schema mismatch. {error_message}")


# Ricky Galliani
# Hanna
# onboard.py

from typing import Any, Dict, List, Tuple

import logging
import os
import json
import robin_stocks as r

def ask_user_input(prompt: str) -> str:
    """
    Asks the user the prompt and returns the response.
    """
    return input(prompt)

def ask_security(ac_name: str) -> Tuple[str, str]:
    """
    Asks the user for the symbol of a security to add and returns the
    security's id and name.
    """
    sec_sym: str = ask_user_input(
        "\t\tEnter the symbol for the new {} security: ".format(ac_name)
    )
    instrument: Dict[str, Any] = r.get_instruments_by_symbols([sec_sym])[0]
    return (instrument["id"], instrument["name"])

def ask_confirm_security(sec_name: str) -> bool:
    """
    Asks the user to confirm the name of a security. Returns True if the user
    confirms and False otherwise.
    """
    confirm_security_str: str = ask_user_input(
        "\t\t\tConfirm {}: [Y/n] ".format(sec_name)
    )
    return confirm_security_str.lower() == "y" or confirm_security_str == ""

def ask_allow_purchase() -> bool:
    """
    Asks the user whether to allow purchasing (of a previously displayed
    security). Returns True if the user confirms and False otherwise.
    """
    allow_purchase_str: str = ask_user_input("\t\t\tAllow purchase: [Y/n] ")
    return allow_purchase_str.lower() == "y" or allow_purchase_str == ""

def ask_asset_class_name(first: bool) -> str:
    """
    Asks the user for an asset class name and returns the user's response.
    """
    ac_name: str = ask_user_input(
        "Enter the name of {} asset class: ".format(
            "an" if first else "the next"
        )
    )
    if ac_name == "":
        ask_asset_class_name(first)
    return ac_name

def ask_target_pct(ac_name: str, pct_left: float) -> float:
    """
    Asks the user for a target percentage for an asset class and returns the
    user's response.
    """
    ac_target_pct_str: str = ask_user_input(
        "\tEnter target percentage of the {} (min: 0.0, max: {}): ".format(
            ac_name, pct_left
        )
    )
    ac_target_pct: float = 0.0
    try:
        ac_target_pct = float(ac_target_pct_str)
    except ValueError as e:
        print("\t{}".format(e))
        ask_target_pct(ac_name, pct_left)
    if ac_target_pct < 0 or ac_target_pct > pct_left:
        print("\tTarget percentage must be in [0.0, {}]".format(pct_left))
        ask_target_pct(ac_name, pct_left)
    return ac_target_pct

def setup_security(ac_name: str) -> Tuple[str, bool]:
    """
    Collects user input to set up a security".
    """
    security: Tuple[str, str] = ask_security(ac_name)
    security_id: str = security[0]
    security_name: str = security[1]
    confirm_security: bool = ask_confirm_security(security_name)
    if not confirm_security:
        setup_security(ac_name)
    allow_purchase: bool = ask_allow_purchase()
    return (security_id, allow_purchase)

def setup_asset_class(
    first: bool, existing_total_pct: float
) -> Dict[str, str]:
    """
    Collects user input to set up an asset class.
    """
    asset_class: Dict[str, Any] = {}

    # Get name
    ac_name: str = ask_asset_class_name(first)
    asset_class["name"] = ac_name

    # Get target percentage
    pct_left: float = 1.0 - existing_total_pct
    ac_target_pct: float = ask_target_pct(ac_name, pct_left)
    asset_class["target_percentage"] = ac_target_pct

    # Get securities and buy restrictions
    asset_class["securities"] = []
    asset_class["buy_restrictions"] = []
    add_sec: bool = True
    while add_sec:
        security: Tuple[str, bool] = setup_security(ac_name)
        security_id: str = security[0]
        allow_purchase: bool = security[1]
        asset_class["securities"].append(security_id)
        if not allow_purchase:
            asset_class["buy_restrictions"].append(security_id)
        add_sec_str: str = ask_user_input(
            "\tAdd another security to {}? [Y/n] ".format(ac_name)
        )
        add_sec = add_sec_str.lower() == "y" or add_sec_str == ""
    return asset_class

if __name__ == "__main__":

    logging.basicConfig(
        format="%(asctime)-15s %(levelname)s: %(message)s", level=logging.INFO
    )
    log = logging.getLogger("onboard")

    # Get portfolio configuration from user
    portfolio_config_file = os.path.join(
        os.getcwd(), "config", "test_portfolio.json"
    )
    portfolio_config: List[Dict[str, Any]] = []
    first: bool = True
    total_pct: float = 0.0
    while total_pct < 1:
        ac: Dict[str, Any] = setup_asset_class(first, total_pct)
        portfolio_config.append(ac)
        total_pct += ac["target_percentage"]
        first = False

    # Get Robinhood credentials from user (only to store locally)
    credentials_config_file = os.path.join(
        os.getcwd(), "config", "test_credentials.json"
    )
    credentials_config: Dict[str, str] = {}
    credentials_config["username"] = ask_user_input(
        "Enter Robinhood username/email: "
    )
    credentials_config["password"] = ask_user_input(
        "Enter Robinhood password: "
    )

    # Write config data to local machine
    with open(portfolio_config_file, "w") as f:
        f.write(json.dumps(portfolio_config, indent=4))
    print("\nPortfolio config written to {}".format(portfolio_config_file))
    with open(credentials_config_file, "w") as f:
        f.write(json.dumps(credentials_config, indent=4))
    print("\nCredentials written to {}".format(credentials_config_file))


from itertools import permutations

def solution(n, weak, dist):
    length=len(weak)
    for i in range(length):
        weak.append(weak[i]+n)

    answer=len(dist)+1
    for start in range(length):
        for friends in list(permutations(dist,len(dist))):
            count=1
            position=weak[start]+friends[count-1]
            for index in range(start,start+length):
                if position<weak[index]:
                    count+=1
                    if count>len(dist):
                        break
                    position=weak[index]+friends[count-1]
            answer=min(answer,count)
    if answer > len(dist):
        return -1
    return answer

if __name__ == "__main__":
  n=0
  weak=[]
  dist=[]
  with open("input14.txt","r")as file:
    n=int(file.readline())
    weak=list(map(int,file.readline().split()))
    dist=list(map(int,file.readline().split()))
  solution(n,weak,dist)


import logging
from hbp_nrp_cle.brainsim.BrainInterface import ILeakyIntegratorAlpha, \
    IDCSource, IACSource, INCSource, ILeakyIntegratorExp, IPopulationRate, \
    IFixedSpikeGenerator, ISpikeRecorder, IPoissonSpikeGenerator

from hbp_nrp_cle.brainsim.pynn.PyNNCommunicationAdapter import PyNNCommunicationAdapter
from .devices import PyNNNestACSource, PyNNNestDCSource, PyNNNestNCSource, \
    PyNNNestLeakyIntegratorAlpha, PyNNNestLeakyIntegratorExp, PyNNNestFixedSpikeGenerator, \
    PyNNNestPopulationRate, PyNNNestSpikeRecorder, PyNNNestPoissonSpikeGenerator

logger = logging.getLogger(__name__)

__author__ = 'Dimitri Probst, Sebastian Krach'

# Pylint for some reason does not see that the methods is_population and create_view are already
# overridden
# pylint: disable=abstract-method
class PyNNNestCommunicationAdapter(PyNNCommunicationAdapter):
    """
    Represents the communication adapter to the neuronal simulator
    """
    # In this dictionary, the association of spike generator types to classes
    # implementing their functionality is established
    __device_dict = {IFixedSpikeGenerator: PyNNNestFixedSpikeGenerator,
                     IDCSource: PyNNNestDCSource,
                     IACSource: PyNNNestACSource,
                     INCSource: PyNNNestNCSource,
                     ILeakyIntegratorAlpha: PyNNNestLeakyIntegratorAlpha,
                     ILeakyIntegratorExp: PyNNNestLeakyIntegratorExp,
                     IPopulationRate: PyNNNestPopulationRate,
                     ISpikeRecorder: PyNNNestSpikeRecorder,
                     IPoissonSpikeGenerator: PyNNNestPoissonSpikeGenerator}

    def initialize(self):
        """
        Marks the PyNN adapter as initialized
        """
        super(PyNNNestCommunicationAdapter, self).initialize()

    def _get_device_type(self, device_type):
        """
        Returns the pynn specific implementation for specified device type
        :param device_type: the device type for which the implementation type is requested
        :return: the concrete type
        """

        if device_type in self.__device_dict:
            return self.__device_dict[device_type]
        return super(PyNNNestCommunicationAdapter, self)._get_device_type(device_type)


'''Detect Cycle in a directed graph using DFS'''

from collections import defaultdict

class Graph:
    def __init__(self,V):
        self.graph = defaultdict(list)
        self.V = V
    def addEdge(self,src,dest):
        self.graph[src].append(dest)

    def cycleUtil(self,node,visited,recStack):

        visited[node] = True
        recStack[node] = True

        for x in self.graph[node]:
            if visited[x] == False:
                if self.cycleUtil(x,visited,recStack) == True:
                    return True
            elif recStack[x] == True:
                return True
        recStack[node] = False
        return False

    def isCyclic(self):

        visited = [False]*self.V
        recStack = [False]*self.V  # created a recurssion stack

        for i in range(self.V):
            if visited[i] == False:
                if self.cycleUtil(i,visited,recStack) == True:
                    return True
        return False

g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
if g.isCyclic() == 1:
    print("Graph has a cycle")
else:
    print("Graph has no cycle")

'''Detect Cycle in a directed graph using BFS'''


from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib import messages
from usuarios.forms import RegistroForm

def register(request):
    if request.method == 'POST':
        f = RegistroForm(request.POST)
        if f.is_valid():
            f.save()
            messages.success(request, 'Cuenta creada, ya puedo hacer Login')
            return redirect('/accounts/registrar/')
    else:
        f = RegistroForm()
    return render(request, 'usuarios/registrar.html', {'form': f})


from django.urls import path, include
from django.views.decorators.cache import cache_page

from rest_framework.routers import DefaultRouter
from .views import GroupsListView, OrderListView, ShopIndexView, \
    ProductsDetailsView, ProductListView, OrderDetailView, CreateProductView, ProductUpdateView, ProductDeleteView, \
    OrderUpdateView, OrderDeleteView, OrderCreateView, ProductsDataExportView, OrdersDataExportView, ProductViewSet, \
    OrderViewSet, LatestProductsFeed, UserOrdersListView, export_orders

app_name = 'shopapp'
routers = DefaultRouter()
routers.register('products', ProductViewSet)
routers.register('orders', OrderViewSet)

urlpatterns = [
    path('', cache_page(90)(ShopIndexView.as_view()), name='index'),
    path('groups/', GroupsListView.as_view(), name='groups'),
    path('products/', ProductListView.as_view(), name='products'),
    path('products/create/', CreateProductView.as_view(), name='create_product'),
    path('products/export/', ProductsDataExportView.as_view(), name='products-export'),
    path('orders/export/', OrdersDataExportView.as_view(), name='orders-export'),
    path('products/<int:pk>', ProductsDetailsView.as_view(), name='detail_product'),
    path('products/<int:pk>/update', ProductUpdateView.as_view(), name='update_product'),
    path('products/<int:pk>/delete', ProductDeleteView.as_view(), name='delete_product'),
    path('orders/', OrderListView.as_view(), name='orders'),
    path('orders/<int:pk>', OrderDetailView.as_view(), name='order_detail'),
    path('orders/<int:pk>/update', OrderUpdateView.as_view(), name='order_update'),
    path('orders/<int:pk>/delete', OrderDeleteView.as_view(), name='order_delete'),
    path('orders/create/', OrderCreateView.as_view(), name='create_order'),
    path('api/', include(routers.urls)),
    path('products/latest/feed/', LatestProductsFeed(), name='products-feed'),
    path('users/<int:user_id>/orders/', UserOrdersListView.as_view(), name='user_orders'),
    path('users/<int:user_id>/orders/export/', export_orders, name='export_orders'),
]


# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
"""
Created on Sun May 21 13:28:04 2023

@author: 35385
"""
# import libraries
import pandas as pd
import csv
import numpy as np

#number of blocks
block_number=111

#list for each household data that includes dataframe for each individual
households=[]

#weather obsolute path address
weahther_path=r'/var/share/rs1/LCL_DATA/raw_LCL_DATA/weather_hourly_darksky.csv'

#read the weather data
weather=pd.read_csv(weahther_path)

#print the description of the weather csv file
print('\t \t  \t***the weather file summery*** \n',weather.describe())

#Convert the time column in weather file to date format
weather['time']=pd.to_datetime(weather['time'])
weather['year'] = weather['time'].dt.year
weather['month'] = weather['time'].dt.month
weather['day'] = weather['time'].dt.day
weather['hour']=weather['time'].dt.hour

# holydays file path
holydays_path=r'/var/share/rs1/LCL_DATA/raw_LCL_DATA/uk_bank_holidays.csv'

#read the holydays file
holydays=pd.read_csv(holydays_path)
#convert the time column to date format
holydays['Bank holidays']=pd.to_datetime(holydays['Bank holidays']).dt.date
holydays=holydays['Bank holidays']

#read the acron data
acron=pd.read_csv(r'/var/share/rs1/LCL_DATA/raw_LCL_DATA/informations_households.csv')

#print the description of the holydays csv file
print('\t \t  \t***the weather file summery*** \n',holydays.describe())

#convert string tpye columns to float and clean the data
def to_numeric_(dataframe, columns_list):
    for column in columns_list:
        dataframe[column]= pd.to_numeric(dataframe[column], errors='coerce')
        #check if there is any null value and get a count of null values
        print(f'\n number of null values in the{column} column is',dataframe[column].isnull().sum())
        # Linear interpolation to fill null values
        dataframe[column] = dataframe[column].interpolate()

#coputing the mean and median of a columns of the data frome
def mean_median_colums(data, columns):
    for column in columns:
        print('mean',data[column].mean(),'******','median',data[column].median())

#create sperate dataframe for each hosuehold
def house_holds(dataframe,block):
    #get the IDs of households in the dataframe
    households_uniques=dataframe['LCLid'].unique()
    #print the number of unique households in a dataframe
    print(f'number of unique households in the block_{block} is ', len(households_uniques))
    #dreate a list of dataframes for each houshold
    for house in households_uniques:
        househod_dataframe=dataframe[dataframe['LCLid']==house]
        households.append(househod_dataframe)
        # Save the DataFrame as a CSV file
        househod_dataframe.to_csv(fr'/var/share/rs1/LCL_DATA/preparded_houshold_data/block{block}_{house}.csv')
    for house in households:
        print(f'number of dataponts for indivudual household{house} is ',len(house['LCLid']))

#list of columns to be converted to numeric and get clean
to_numeric_list=['energy(kWh/hh)', 'visibility','windBearing','temperature','dewPoint','pressure',
                 'apparentTemperature','windSpeed','humidity']

''' Create a dataset for a block'''

for block in range(0,block_number):
    #read the csv file and print describtion
    df0=pd.read_csv( fr'/var/share/rs1/LCL_DATA/raw_LCL_DATA/halfhourly_dataset/halfhourly_dataset/block_{block}.csv')

    #print describtion
    print(f'\t \t  \t***the block{block} file summery*** \n',df0.describe())

    # convert the time column to date format
    df0['tstp']=pd.to_datetime(df0['tstp'])

    # Extract year, month, and hour
    df0['year'] = df0['tstp'].dt.year
    df0['month'] = df0['tstp'].dt.month
    df0['day'] = df0['tstp'].dt.day
    df0['hour'] = df0['tstp'].dt.hour

    #merge two dataframes based on their data with hour precision
    weather_merged = pd.merge(df0, weather, on=['year', 'month', 'day','hour'], how='left')

    #create a mask for holydays
    mask=weather_merged['tstp'].dt.date.isin(holydays)

    #add holydays to the dataframe, 1 for holydays and zero for working days
    weather_merged['holydays']=mask.astype(int)

    weather_merged['weekday']=weather_merged['tstp'].dt.weekday

    #update the holydays column for weeknds
    weather_merged.loc[weather_merged['weekday']>=5,'holydays']=1

    #merge two dataframes  based on their household ID
    weather_merged = pd.merge(weather_merged, acron, on=['LCLid'], how='left')

    print(f'number of the rows in entire data dataframe for block{block}',len(weather_merged['LCLid']))

    #convert and clean columns
    to_numeric_(weather_merged,to_numeric_list)
    #create seperate dataframes for each house hold
    house_holds(weather_merged,block)


class configure:
    def __init__(self,command):
        command_process_configure(command)

    def configure_init():
        m2_zone = False
        apikey_in = input("[api_key] :")
        secret_in = input("[secret key} :")
        zone_in = input("[data center] or type 'help' to check all aviliable zones :")
        while(zone_in == 'help' or zone_in not in ZONE):
            for name in ZONE:
                print(name)
            zone_in = input("[data center] or type 'help' to check supported zones :")
    #    for i in ZONE:
    #        if(zone_in.lower() == i):
    #            zone_in=i
        response = input("[response type] or type help to check supported response :")
        if zone_in == "KOR-Seoul M2":
            m2_zone = True
        t = open("credit.txt","w")
        t.write(apikey_in+"\n")
        t.write(secret_in+"\n")
        t.write(zone_in+"\n")
        t.write(response+"\n")
        t.write(str(m2_zone)+ "\n")
        t.close()
        return
    def configure_list():
        credit = open("credit.txt" , "r")
        print("API_KEY : ", credit.readilne())
        print("Secret Key : ", credit.readilne())
        print("Zone : ", credit.readline())
        print("response Type: ", credit.readline())
        return
    def command_process_configure(command):
        if command == "init":
            configure_init()
        elif command == "list":
            configure_list()
        else:
            print("no command matched")
        exit(-1)

    ##def command_process_server(command):
    ##    if ctype == "List"
    ##
    ##    elif ctype == "ListAvailableProductTypes":
    ##        ListAvailableProductTypes()
    ##    elif ctype == "deployVirtualMachnine":
    ##        deployVirtualMachine()
    ##    elif ctype == "startVirtualMachine" :
    ##        startVirutualMachine()
    ##    else:
    ##        print("no command matched")


from MpApi.aio.chunky import Chunky
from mpapi.constants import get_credentials
from mpapi.module import Module

user, pw, baseURL = get_credentials()

def test_init():
    chunker = Chunky(baseURL=baseURL, pw=pw, user=user)
    assert chunker
    print(chunker)

def test_analyze_related():
    source = "C:/m3/MpApi-Replacer/sdata/temp485397.zml.xml"
    m = Module(file=source)

    chunker = Chunky(baseURL=baseURL, pw=pw, user=user)
    L = chunker.analyze_related(data=m)
    print(L)


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

book  = cv2.imread('res/book.jpg', 0)
scene = cv2.imread('res/scene.jpg', 0)

orb = cv2.ORB_create()

kp1, des1 = orb.detectAndCompute(book, None)
kp2, des2 = orb.detectAndCompute(scene, None)

bruteForce = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

match = bruteForce.match(des1, des2)
match = sorted(match, key = lambda x:x.distance)

matches = cv2.drawMatches(book, kp1, scene, kp2, match, None, flags=2)

plt.imshow(matches)
plt.show()


# Advent of Code 2020 - Day 13

# Author:   Rachael Judy
# Date:     12/13/2020
# Purpose:  Find the soonest train that is after the start time
#           Find first time with all trains departing at time + index in original read in that matches

import os
import sys
import math

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import parseMod

# get input
information = parseMod.readCSV_rowEl('data/13loop.csv', ',')

target = int(information[0][0])  # initialize the target value
buses, indices = [], []  # track the spots where a bus actually is
min_bus_departure = 10_000_000  # used to store minimum departure time available
bus_id = 0  # bus to take

# Part 1, setup for part 2
# go through each bus and find first time it can be taken
for element in information[1]:
    if element.isnumeric():  # if not x, store bus
        buses.append(int(element))
        indices.append(information[1].index(element))

        # save closest_possible_departure possible departure time for this bus - calculates first time can leave
        closest_possible_departure = math.ceil(target / float(element)) * int(element)
        if closest_possible_departure < min_bus_departure:  # save bus id and the time
            min_bus_departure = closest_possible_departure
            bus_id = int(element)

print("Part 1: ", (min_bus_departure-target) * bus_id)

# Part 2
# use CRT and Euclidean to determine the x that meets conditions:
#       x % bus_id_i == (-index_i) % bus_id_i for all i in buses
mod = math.prod(buses)
x = 0
for offset, id in zip(indices, buses):  # check each bus
    z = int(mod / id)
    y = pow(z, -1, id)  # python 3.8 method - mod inverse of z mod id
    w = (y * z) % mod  # weight
    x += (-offset) * w

# compute minimum
x %= mod
print("Part 2: ", x)


from bs4 import BeautifulSoup
import requests

response = requests.get("https://www.empireonline.com/movies/features/best-movies-2/")
movie_data = response.text
soup = BeautifulSoup(movie_data, "html.parser")
movie_title = soup.find_all(name="h3", class_="jsx-4245974604")
all_movies_list = [title.getText for title in movie_title]
movie = all_movies_list[::-1]

with open("100-best_movies_of_all_time", mode="w") as file:
    file.write(f"{movie}\n")


# 이탈리아에서 아이스크림 사먹는 한윤정
# N: 아이스크림 종류 수, M: 섞어먹으면 안되는 조합의 갯수, (1 ≤ N ≤ 200, 0 ≤ M ≤ 10,000)
# M 조합을 피해 섞어 먹을 수 있는 조합의 수

# Set 자료형 -> 메모리 초과
from itertools import combinations

n, m = map(int, input().split())
data = [i for i in range(1, n+1)]
combination_set = list(map(set, combinations(data, 3)))
# print(combination_set)
# print(type(combination_set[0]))
not_com = []

for _ in range(m):
    input_set = set(map(int, input().split()))
    not_com.append(input_set)

result = 0
for i  in range(len(combination_set)):
    if len(combination_set[i]-not_com[0]) == 1:
        print(combination_set)
        result += 1
print(result)

# print(not_com)
# print(not_com[0])
# print(combination_set[1])
# print(len(combination_set[3]-not_com[0]))

# 함수형: 메모리 초과
from itertools import combinations

def find_list(x, y, list_com):
    new_list =[]
    for combi in enumerate(list_com):
        if x in combi and y in combi:
            pass
        else:
            new_list.append(combi)
    return new_list

n, m = map(int, input().split())
data = [i for i in range(1, n+1)]
combination_set = list(map(list, combinations(data, 3)))

not_com = []
for _ in range(m):
    input_set = list(map(int, input().split()))
    not_com.append(input_set)

for i in range(m):
    x = not_com[i][0]
    y = not_com[i][1]
    temp_list = find_list(x, y, combination_set)

print(len(temp_list))

# 테스트
for i in range(len(combination_set)):
    for j in range(len(not_com)):
        if not_com[j][0] in i and not_com[j][1] in i:
            combination_set.remove(combination_set[i])
        print(combination_set)

# ==> 시간 초과
result = 0
for i  in range(len(combination_set)):
    for j in range(len(not_com)):
        if not_com[j][0] not in combination_set[i] and not_com[j][1] not in combination_set[i]:
            result += 1
print(result)

# ==> 시간 초과
from itertools import combinations
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
combination_list = list(map(list, combinations(range(n), 3)))
not_com = [list(map(int, input().split())) for i in range(m)]

result = 0
for i  in range(len(combination_list)):
    for j in range(m):
        if not_com[j][0] not in combination_list[i] and not_com[j][1] not in combination_list[i]:
                result += 1
print(result)


left= {'q', 'w', 'e', 'r', 't', 'a', 's', 'd', 'f', 'g', 'z', 'x', 'c', 'v', 'b'}
right= {'y', 'u', 'i', 'o', 'p', 'h', 'j', 'k', 'l', 'n', 'm'}

text = input('pls enter a text\t:')
text_1=set(text)
left_bool = bool(text_1 -left)
right_bool = bool(text_1 - right)

if left_bool and right_bool:
    print(f'{text} is comfortable words')
else:
    print('{} is uncomfortable'.format(text))


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

import torch
import torch.nn as nn

class DilatedCNN(torch.nn.Module):
    def __init__(self, hidden_size=64, depth=12):
        super(DilatedCNN, self).__init__()
        model = []
        model += [nn.ReflectionPad1d(2**depth - 1)]
        model += [nn.Conv1d(1, hidden_size, kernel_size=3, dilation=1)]
        model += [nn.BatchNorm1d(hidden_size)]
        model += [nn.ReLU()]
        for l in range(1, depth):
            model += [nn.Conv1d(hidden_size, hidden_size, kernel_size=3, dilation=2**l)]
            model += [nn.BatchNorm1d(hidden_size)]
            model += [nn.ReLU()]
        model += [nn.Conv1d(hidden_size, 1, kernel_size=1)]
        self.model = nn.Sequential(*model)

    def forward(self, x):
        z = self.model(x)

        return z

class RandomModel(torch.nn.Module):
    # This model outputs random numbers between 0 and 1, with the same shape as
    # the input batch:
    def __init__(self):
        super(RandomModel, self).__init__()
        self.model = []

    def forward(self, x):
        return torch.rand(x.shape).cuda()