"""Module contains common logger for seabattle app."""
import logging
import os
import uuid
from uuid import UUID

env_conf = os.environ.get("SEABATTLE_SETTINGS", "DevConfig")

def get_logger(game_id: UUID = uuid.uuid4(), name: str = "seabattle_default") -> logging.Logger:
    """
    Method defines common logger.
    Args:
        game_id: Game ID for logging.
        name: Logger name.

    Returns:
        logging.Logger: Logger object.
    """

    # Create logger object.
    logger_obj = logging.getLogger(str(game_id))

    # Define logger level.
    logger_obj.setLevel(logging.DEBUG if env_conf == "DevConfig" else logging.INFO)

    # Set up logger format and add handler to logger.
    log_format = f"%(asctime)s [%(threadName)-10s] [app: {name}, gameID: {game_id}] " \
                 "%(levelname)-8s - %(filename)s - %(funcName)s - line %(lineno)d - %(message)s"
    handler = logging.StreamHandler()
    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)
    logger_obj.addHandler(handler)

    return logger_obj

API_LOGGER = get_logger(name="seabattle_api")


def argmin(seq, fn):
    """Return an element with lowest fn(seq[i]) score; tie goes to first one.
    >>> argmin(['one', 'to', 'three'], len)
    'to'
    """
    best = seq[0]; best_score = fn(best)
    for x in seq:
        x_score = fn(x)
        if x_score < best_score:
            best, best_score = x, x_score
    return best


# Import module
import pandas as pd

# Create dataframe and dictionary
nato_df = pd.read_csv("Project/nato_phonetic_alphabet.csv")
nato_dict = {nato_df.at[index,'letter']:nato_df.at[index,'code'] for index,row in nato_df.iterrows()}

# Driver code
running = True
while running:
    print([nato_dict[letter] for letter in input("Enter a word: ").upper()])
    if not input("Type 'y' to play again\n>> ") =='y':
        running = False


import identification_graf as ident_graf

def return_v(find_x,i,j,n,matrix):
    while i<n+1:
        if matrix[(i,j)]==find_x:
            return i
        i=i+1

def filling_zero(matrix,i,n):
    j=0
    while j<n+1:
        try:
            if matrix[(i,j)]!=1:
                matrix_s[(i,j)]=0
            j=j+1
        except KeyError:
            matrix[(i,j)]=0
            j=j+1
    return matrix

def return_matrix_s(matrix,n,m):
    matrix_s={}
    graf=False
    if ident_graf.indefication(matrix)=='no oriented':
        graf=True
    i=0
    j=0
    while j<m+1:
        if graf==True:
            i1=return_v(1,i,j,n,matrix)
            i2=return_v(1,i1+1,j,n,matrix)
            matrix_s[(i1,i2)]=matrix_s[(i2,i1)]=1
            i=0
            j=j+1
        else:
            i1=return_v(-1,i,j,n,matrix)
            i2=return_v(1,i,j,n,matrix)
            matrix_s[(i1,i2)]=1
            i=0
            j=j+1
    while i<n+1:
        matrix_s=filling_zero(matrix_s,i,n)
        i=i+1
    return matrix_s


import csv
import datetime
from tkinter import *
from tkinter import messagebox

import twitter
from config import *

class MainMenu(Frame):
    def __init__(self, master):
        # klaar zetten van variablen
        super(MainMenu, self).__init__(master)
        self.button = []
        self.list = self.TweetOntvangen()
        self.frame = Frame
        self.grid()
        self.create_GUI()
        self.create_overige_GUI()
        self.twitter = twitter.Twitter()
        self.timer()

    def create_GUI(self):
        # Aanmaken van bovenste balk met de info overhoeveel berichten je hebt
        screen_width = mainWindow.winfo_screenwidth()
        self.label1 = Label(mainWindow, text=self.MainMessage()[0], width=screen_width, height="1",
                            background=self.KleurTweet(), anchor='w', font=(FONT, 16))
        self.label1.grid(row=0, column=0, sticky=W)
        self.label2 = Label(mainWindow, text=self.MainMessage()[1], width=screen_width, height="2",
                            background=self.KleurTweet(), anchor='w', font=(FONT, 16))
        self.label2.grid(row=1, column=0, sticky=W)

    def create_overige_GUI(self):
        # aanmaken refresh, exit en ns button
        self.photo = PhotoImage(file=IMG_PATH + "ns_logoklein.png")

        self.nsimage = Button(mainWindow, command=self.Onpressns, image=self.photo, width="200", height="97")
        self.nsimage.place(relx=1, rely=1, anchor=SE)

        self.refreshb = Button(mainWindow, text="Refresh", width=15, height="2", command=self.ref1, bg="#1c1c6b",
                               fg='white')
        self.refreshb.place(relx=1, rely=0.112, anchor=E)

        self.exit = Button(mainWindow, text="Exit", width=15, height="2", command=self.quit, bg="#1c1c6b", fg='white')
        self.exit.place(relx=0.939, rely=0.112, anchor=E)

    def tweetButtons(self):
        # aanmaken van de button voor de tweet die je hbet onvangen.
        self.list = self.TweetOntvangen()

        for b in self.button:
            b.destroy()

        self.button = []

        for i in range(len(self.TweetOntvangen())):  # self.list[i][0]
            if i > 9:
                break
            self.button.append(Button(mainWindow, text=(
                self.list[i][0] + ". \nontvangen door: " + self.list[i][1] + " om " + self.list[i][2]),
                                      command=lambda i=i: self.Onpress(i), width=self.buttonWidth(self.list[i][0]),
                                      anchor=CENTER, height="2", bg='#1c1c6b', fg='#ffffff', font=(FONT, 15)))
            self.button[i].place(relx=0.5, rely=0.20 + (0.082 * i), anchor=CENTER)

    def TweetOntvangen(self):
        # Alle Tweets met daarbij de verzender en tijd van verzenden word uit een CSV-bestand naar een list geschreven
        with open(CSV_PATH, "r") as MyCsvFile:
            reader = csv.DictReader(MyCsvFile)
            OntvangenTweets = []
            for row in reader:
                OntvangenTweets.append([row['tweet'], row['plaatser'], row['tijd']])
        return OntvangenTweets

    def IsTweetOntvangen(self):
        # Kijken of er tweets zijn ontvangen en daar een variable voor returnen
        if len(self.TweetOntvangen()) != 0:
            Tweet = 1
        else:
            Tweet = 0
        return Tweet

    def MainMessage(self):
        # Kijken hoeveel berichten er zijn en dit in een volledige tekst terug sturen
        bericht = ""
        bericht1 = ''
        if self.IsTweetOntvangen() == 0:
            bericht = 'U heeft geen bericht ontvangen.'
        if self.IsTweetOntvangen() == 1:
            if len(self.TweetOntvangen()[0]) > 1:
                bericht = "U heeft " + str(len(self.TweetOntvangen())) + " berichten"
                bericht1 = "Dit zijn de berichten:"
            else:
                bericht = "U heeft een bericht."
                bericht1 = "Dit is uw bericht:"
        return bericht, bericht1

    def ref1(self):
        # refreshen van de widgets
        self.tweetButtons()
        self.KleurTweet()
        self.create_GUI()

    def timer(self):
        # automatisch refreshen van widgets elke 15seconden
        self.tweetButtons()
        self.KleurTweet()
        self.create_GUI()
        self.after(15000, self.timer)

    def Onpressns(self):
        # message box maken met een tekst erin
        messagebox.showinfo("NS bericht", "De NS groet u.")

    def Onpress(self, i):
        # askBox maken warin wordt gevraagt of deze verzenden moet worden, daarna wordt bij ja wordt het bericht verstuurde naar twitter,
        # weggeschrijven naar log, tweet wordt verwijderd uit variable list, Tweet wordt verwijderd uit csv, en GUI wordt gerefreshed.
        # bij nee wordt het bovenstaande uitgevoerd zonder de tweet te versturen
        result = messagebox.askquestion("Tweet versturen", "Wilt u deze tweet versturen?", icon="warning")
        if result == 'yes':
            messagebox.showinfo("Bericht", "Tweet: " + self.list[i][0] + " van " + self.list[i][1] + " is verstuurd")
            self.twitter.postTweet(self.list[i][1] + ": " + self.list[i][0])
            self.logBestand(self.list[i][0], self.list[i][1], "Verstuurd")
            self.list.remove(self.list[i])
            self.TweetVerwijderen()
            self.ref1()
        else:
            messagebox.showinfo("Bericht", "Tweet: " + self.list[i][0] + " van " + self.list[i][1] + " is verwijderd")
            self.logBestand(self.list[i][0], self.list[i][1], "Afgewezen")
            self.list.remove(self.list[i])
            self.TweetVerwijderen()
            self.ref1()

    def TweetVerwijderen(self):
        # Tweet wordt uit CSV verwijdert
        with open(CSV_PATH, 'w', newline='') as f:
            writer = csv.writer(f, delimiter=',')
            writer.writerow(['tweet', 'plaatser', 'tijd'])
            for row in self.list:
                writer.writerow(row)

    def logBestand(self, tweet, plaatser, status):
        # tweet wordt in log gezet met de tijd van inzetten en of deze is verzonden of afgewezen
        with open(LOG_PATH, 'r') as rbestand:
            s = rbestand.read().splitlines()
        with open(LOG_PATH, "w") as bestand:
            for lines in s:
                bestand.write(lines + '\n')
            bestand.write(datetime.datetime.now().strftime("Time: %d-%m-%Y %H:%M:%S, ") + tweet + ', ')
            bestand.write(plaatser + "," + status)

    def KleurTweet(self):
        # als er geen tweet ontvanen is wordt de kleur van bovenste balk rood en anders is deze groen
        if self.IsTweetOntvangen() == 0:
            global kleur
            kleur = "red"
        else:
            kleur = "green"
        return kleur

    def buttonWidth(self, tweet):
        # als tweet langer is dan in de button past dan wordt de button vergroot
        width = 75
        if len(tweet) > width:
            width = len(tweet)
        return width

mainWindow = Tk()
mainWindow.title("TweetsCheck MainPanel")
MainMenu(mainWindow)
mainWindow.attributes('-fullscreen', True)
mainWindow.configure(background='#fcc917')
mainWindow.iconbitmap(IMG_PATH + "Ns.ico")
mainWindow.mainloop()


# passes only 3 of 4 tests because probably too high complexity

def fibonacci_n_digit(digits):
    a,b = 1,1
    counter = 1
    while len(str(a))<digits:
        a,b = b,a+b
        counter += 1
    return counter

if __name__ == '__main__':

    for _ in range(int(input())):
        print(fibonacci_n_digit(int(input())))


import glob
import os
from pathlib import Path
from typing import Dict, List, Literal, Optional, Union

import iceutils as ice
import numpy as np
import utilities as joughin_utils

from columbia.utils import write_names_to_stack

# ..............................................................................
# Translate
# ..............................................................................
def binary_to_tif(
        binary_track_path: str,
        tif_path: str):
    """Converts Dr. Joughin's binary raster files to geotiff raster files.

    Args:
        binary_track_path: Path to track directory with binary rasters
            to translate.
        tif_path: Path to directory to store output GeoTiff raster files.
    """
    binary_track_dir = binary_track_path.split('/')[-1]

    # Create geoimage objects
    vel = joughin_utils.geoimage(geoType='velocity')
    err = joughin_utils.geoimage(geoType='error')

    # Read binary data
    binary_file_path = f'{binary_track_path}/mosaicOffsets'
    vel.readData(binary_file_path)
    err.readData(binary_file_path)

    # Parse date
    date = vel.parseMyMeta(f'{binary_file_path}.meta')
    datestr = date.strftime('%Y%m%d')

    # Create directory for storing GeoTIFF outputs of loaded track
    tif_track_path = f'{tif_path}/{binary_track_dir}'
    Path(tif_track_path).mkdir(parents=True, exist_ok=True)

    # Construct file name, e.g. 'track-0000_yyyymmdd.vx.tif'
    # ('.vx.tif' extension will be appended automatically)
    tif_file = f'{binary_track_dir}_{datestr}'
    tif_file_path = f'{tif_track_path}/{tif_file}'

    # Output to GeoTiff
    vel.writeMyTiff(tif_file_path)
    err.writeMyTiff(tif_file_path)

def _translate_rasters(binary_path: str, tif_path: str):
    """Translates dataset of binary rasters to GeoTiff rasters.

    Args:
        binary_path: Path to directory of track folders.
        tif_path: Path to directory to store output GeoTiff raster files.
    """
    binary_track_paths = glob.glob(f'{binary_path}/*')
    for binary_track_path in binary_track_paths:
        binary_to_tif(binary_track_path, tif_path)

# ..............................................................................
# Build Stack
# ..............................................................................
def _extract_raster_contents(
        tif_path: str,
        vel_type: Literal['v', 'vx', 'vy'],
        vel_nd_value: Union[int, float],
        err_type: Optional[Literal['ex', 'ey']] = None,
        err_nd_value: Optional[Union[int, float]] = None):
    """Extracts date, name, and data from each raster of the same type.

    Args:
        tif_path: Path to directory of translated GeoTiff raster tracks.
        vel_type: Type of data to build stack from.
        vel_nd__value: Value of invalid data for Stack.
    """
    init_tdec, init_names, init_data = [], [], []
    init_hdr = None
    init_weights = None if err_type is None else []

    for raster_path in glob.glob(f'{tif_path}/*/*.{vel_type}.tif'):
        # Parse name and date from file name
        raster_file = raster_path.split('/')[-1]

        # Remove extension
        raster_file = raster_file.split('.')[0]
        name, date = raster_file.split('_')
        tdec = ice.datestr2tdec(
            yy=int(date[0:4]),
            mm=int(date[4:6]),
            dd=int(date[6:8]))

        # Parse data
        raster = ice.Raster(rasterfile=raster_path)
        data = np.array(raster.data)
        data[data == vel_nd_value] = np.nan

        # Load weights if they exist
        weights = None
        if err_type is not None:
            err_path = raster_path.replace(vel_type, err_type)
            err = ice.Raster(rasterfile=err_path)
            err = np.array(err.data)
            err[err == err_nd_value] = np.nan
            weights = 1/err

        # Add to stack dataset
        init_tdec.append(tdec)
        init_names.append(name)
        init_data.append(data)

        if init_weights is not None:
            init_weights.append(weights)

        if init_hdr is None:
            # All headers are the same, so just store the first one
            init_hdr = raster.hdr

    return init_tdec, init_names, init_data, init_hdr, init_weights

def build_joughin_stack(
        tif_path: str,
        stack_file_path: str,
        vel_type: Literal['v', 'vx', 'vy'],
        vel_nd_value: Union[int, float],
        err_type: Optional[Literal['ex', 'ey']] = None,
        err_nd_value: Optional[Union[int, float]] = None):
    """Builds a Stack with all GeoTiff rasters of the same type.

    Args:
        tif_path: Path to directory of translated GeoTiff raster tracks.
        stack_file_path: Path to save stack file as (includes Stack file name).
        vel_type: Type of data to build stack from.
        vel_nd_value: Value of invalid data for Stack.
    """
    # Parse dates, names and data from files
    tdec, names, data, init_hdr, weights = _extract_raster_contents(
        tif_path, vel_type, vel_nd_value, err_type, err_nd_value
    )

    # Sort contents by date
    tdec_sort = np.argsort(tdec)
    tdec_sorted = np.array(tdec)[tdec_sort]
    data_sorted = np.array(data)[tdec_sort]
    names_sorted = np.array(names)[tdec_sort]

    # Write stack to file
    stack = ice.Stack(stack_file_path, mode='w', init_tdec=tdec_sorted,
                      init_rasterinfo=init_hdr)
    stack['data'] = data_sorted

    if weights is not None:
        weights_sorted = np.array(weights)[tdec_sort]
        stack['weights'] = weights_sorted

    write_names_to_stack(stack, names_sorted)
    stack.fid.close()

# ..............................................................................
# Preprocess Data
# ..............................................................................
def preprocess_joughin_dataset(
        raw_path: str,
        preprocessed_path: str,
        binary_dir: str,
        tif_dir: str,
        stack_file_pattern: str,
        nd_values: Dict[str, Union[float, int]] = dict(
            v=-1, vx=-2e9, vy=-2e9, ex=-1, ey=-1),
        vel_types: List[str] = ['v', 'vx', 'vy'],
        vel_errs: Dict[str, Optional[str]] = dict(v=None, vx='ex', vy='ey'),
        translate: bool = True,
        build_stack: bool = True):
    """Translates rasters from binary to GeoTiff and merges rasters of the
    same type into Stacks.

    Args:
        raw_path: Path for storing raw data.
        preprocessed_path: Path for storing preprocessed data (e.g., stacks).
        binary_dir: Directory in the raw path containing binary raster tracks.
        tif_dir: Directory in the raw path to store translated GeoTiff
            raster tracks.
        stack_file_pattern: Name of the output stack file pattern, with a
            {stack_type} variable that is filled in automatically.
            e.g., 'columbia_{stack_type}_stack.hdf5' becomes
            'columbia_vx_stack.hdf5'.
        nd_values: Dictionary storing the invalid data value for each stack
            type mentioned above.
        vel_types: Stack types in Dr. Joughin's velocity dataset to build
            stacks for in set, ('v', 'vx', 'vy')
        err_types: Dictionary of error type corresponding to each vel type.
        translate: Whether or not to translate the binary rasters to GeoTiff.
        build_stack: Whether or not to build Stacks from the GeoTiff rasters.
    """
    binary_path = os.path.join(raw_path, binary_dir)
    tif_path = os.path.join(raw_path, tif_dir)

    Path(tif_path).mkdir(parents=True, exist_ok=True)

    if translate:
        _translate_rasters(binary_path, tif_path)

    if build_stack:
        for vel_type in vel_types:
            stack_file = stack_file_pattern.format(vel_type=vel_type)
            stack_file_path = os.path.join(
                preprocessed_path, stack_file)

            overwrite = 'y'
            if os.path.exists(stack_file_path):
                overwrite = input(
                    f'{stack_file_path} exists. Do you want to overwrite? y or n: ')

            if overwrite == 'y':
                err_type = vel_errs[vel_type]
                err_nd_type = None
                if err_type is not None and err_type in nd_values.keys():
                    err_nd_type = nd_values[err_type]

                build_joughin_stack(
                    tif_path, stack_file_path, vel_type, nd_values[vel_type],
                    err_type, err_nd_type
                )


'''Ch12Ex4: Change the urllinks.py program to extract and count paragraph (p) tags from the retrieved HTML document
and display the count of the paragraphs as the output of your program. Do not display the paragraph text, only count them.
Test your program on several small web pages as well as some larger web pages.
'''
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup

urlstr = input('Please enter a URL like http://data.pr4e.org: ')
try:
    req = urllib.request.Request(urlstr, headers={'User-Agent': 'Mozilla/5.0'})
    fhand = urllib.request.urlopen(req).read()
except:
    print('The URL was incorrectly entered or does not exist. Please try again.')
    quit()
counter = 0
soup = BeautifulSoup(fhand,'lxml')
tags = soup('head')
for tag in tags:
    counter +=1

print('Paragraph tag count: ',counter)


import os
from ...utils import print_table
from .configobj import ConfigObj
from .errors import ConfigError
from .utils import colorify
from .apps import APP2CLASS, OPTION2APPTYPE, APPTYPES

def build_supermatrix_workflow(wname):
    try:
        cog_selector, alg_concatenator, treebuilder = map(lambda x: "@%s" %x, wname.split("-"))
    except ValueError:
        raise ConfigError("Invalid supermatrix workflow: %s" %wname)

    workflow = {wname: {
        "_app": "supermatrix",
        "_cog_selector": cog_selector,
        "_alg_concatenator": alg_concatenator,
        "_aa_tree_builder": treebuilder,
        "_nt_tree_builder": treebuilder,
        "_appset":"@builtin_apps"}
    }
    return workflow

def build_genetree_workflow(wname):
    try:
        aligner, trimmer, modeltester, treebuilder = map(lambda x: "none" if x.lower() == "none" else "@%s"%x,
                                                         wname.split("-"))
    except ValueError:
        raise ConfigError("Invalid genetree workflow: %s" %wname)

    workflow = {wname: {
        "_app": "genetree",
        "_aa_aligner": aligner,
        "_aa_alg_cleaner": trimmer,
        "_aa_model_tester": modeltester,
        "_aa_tree_builder": treebuilder,
        "_nt_aligner": aligner,
        "_nt_alg_cleaner": trimmer,
        "_nt_model_tester": modeltester,
        "_nt_tree_builder": treebuilder,
        "_appset":"@builtin_apps"}
    }
    return workflow

def list_workflows(config, target_type=None):

    if not target_type or target_type == 'supermatrix':
        print()
        avail_meta = [(k, config["workflow_desc"].get(k, ""), len(v)) for k,v in config.get('supermatrix_meta_workflow', {}).items()]
        print_table(avail_meta, fix_col_width=[45, 60, 10], header=["Worflow name", "Description", "threads"], title="Supermatrix shortcut workflow names", row_line=True)

    if not target_type or target_type == 'genetree':
        print()
        avail_meta = [(k, config["workflow_desc"].get(k, ""), len(v)) for k,v in config.get('genetree_meta_workflow', {}).items()]
        print_table(avail_meta, fix_col_width=[45, 60, 10], header=["Worflow name", "Description", "threads"], title="GeneTree shortcut workflow names", row_line=True)

def list_apps(config, target_apps = None):
    for appname, validapps in APPTYPES.items():
        if target_apps:
            if appname not in target_apps and target_apps & validapps:
                validapps = target_apps & validapps
            elif appname in target_apps:
                pass
            else:
                continue

        avail_blocks = [[blockname, block["_app"], block.get("_desc", "")] for blockname, block in config.items() if block.get("_app") in validapps]
        print_table(avail_blocks, header=["name", "app type", "desc."], max_col_width=70, title=appname, row_line=True)
        print()

def block_detail(block_name, config, color=True):
    blocks_to_show = {}
    iterable_types = set([set, list, tuple, frozenset])
    if block_name not in config:
        try:
            next_block = [x.lstrip('@') for x in config.get('genetree_meta_workflow', {})[block_name]]
            metaworkflow = True
        except Exception as e:
            print(e)
            raise ValueError('block name not found [%s]' %block_name)
    else:
        metaworkflow = False
        next_block = [block_name]

    pos = 0
    while next_block:
        block = next_block.pop()
        blocks_to_show[block] = pos
        for k1, v1 in config[block].items():
            if type(v1) in iterable_types:
                for v2 in v1:
                    if isinstance(v2, str) and v2.startswith('@'):
                        next_block.append(v2[1:])
            elif isinstance(v1, str) and v1.startswith('@'):
                next_block.append(v1[1:])
        pos += 1

    if metaworkflow and color:
        print(colorify('[genetree_meta_workflow]', 'yellow'))
        print("%s = %s" %(block_name, ', '.join(config["genetree_meta_workflow"][block_name])))
        print()
    elif metaworkflow:
        print('[genetree_meta_workflow]')
        print("%s = %s" %(block_name, ', '.join(config["genetree_meta_workflow"][block_name])))
        print()

    for b, pos in sorted(list(blocks_to_show.items()), key=lambda x: x[1]):
        if b == "builtin_apps":
            continue
        if color:
            print(colorify('[%s]' %b, 'green'))
        else:
            print('[%s]' %b)

        for k,v in sorted(config[b].items()):
            if k == "_inherits":
                continue
            if type(v) in iterable_types:
                v = ', '.join(map(str, v))+','

            if color:
                if k == '_app':
                    print(colorify('% 35s = %s' %(k, v), "lblue"))
                else:
                    print('%s = %s' %(colorify("% 35s" %k, "orange"), v))
            else:
                print('% 40s = %s' %(k, v))
        print()

def parse_block(blockname, conf):
    blocktype = conf[blockname].get('_app', 'unknown')
    for attr, v in list(conf[blockname].items()):
        conf[blockname][attr] = check_type(blocktype, attr, v)
        if isinstance(conf[blockname][attr], list):
            for i in conf[blockname][attr]:
                check_block_link(conf, blockname, i, attr)
        else:
            check_block_link(conf, blockname, conf[blockname][attr], attr)

    # Check for missing attributes
    for tag, tester in CHECKERS.items():
        if tag[0] == blocktype and (tester[2] and tag[1] not in conf[blockname]):
            raise ConfigError('[%s] attribute expected in block [%s]' %(tag[1], blockname))

def check_config(fname):
    conf = ConfigObj(fname, list_values=True)

    # expand meta_workflows
    for meta_name, meta_wf in conf["genetree_meta_workflow"].items():
        for wkname in meta_wf:
            conf.update(build_genetree_workflow(wkname.lstrip("@")))
    for meta_name, meta_wf in conf["supermatrix_meta_workflow"].items():
        for wkname in meta_wf:
            conf.update(build_supermatrix_workflow(wkname.lstrip("@")))

    # expand inherits options
    for k, v in list(conf.items()):
        if '_inherits' in v:
            base = v['_inherits']
            try:
                new_dict = dict(conf[base])
            except KeyError:
                raise ConfigError('[%s] config block is referred in [%s] but not present in config file' %(base, k))
            new_dict.update(v)
            conf[k] = new_dict

    # check blocks
    for blockname in list(conf.keys()):
        parse_block(blockname, conf)

    # Check that the number of columns in main workflow definition is the same in all attributes
    for flow_name in conf.keys():
        if conf[flow_name].get("_app", "") != "main":
            continue
        npr_config = [len(v) for k, v in conf[flow_name].items()
                      if type(v) == list and k != "target_levels"]
        if len(set(npr_config)) != 1:
            raise ConfigError("List values in [%s] should all have the same length" %flow_name)
    return conf

def check_type(blocktype, attr, v):
    tag = (blocktype, attr)
    if tag in CHECKERS:
        tester, kargs, required = CHECKERS[tag]
        return tester(v, **kargs)
    else:
        return v

def check_block_link(conf, parent, v, attr_name):
    if isinstance(v, str) and v.startswith('@'):
        if v[1:] not in conf:
            raise ConfigError('[%s] config block referred in [%s] but not found in config' %(v, parent))
        if attr_name in OPTION2APPTYPE and conf[v[1:]]["_app"] not in OPTION2APPTYPE[attr_name]:
            raise ConfigError('[%s] is not valid [%s] application block' %(v, attr_name))

def is_file(value):
    if os.path.isfile(value):
        return value
    else:
        raise ConfigError("Not valid file")

def is_dir(value):
    if os.path.isdir(value):
        return value
    else:
        raise ConfigError("Not valid file")

def check_number(value, cast, minv=0, maxv=None):
    try:
        typed_value = cast(value)
    except ValueError:
        raise ConfigError("Expected [%s] number. Found [%s]" %(cast, value))
    else:
        if (minv is not None and typed_value < cast(minv)) or \
           (maxv is not None and typed_value > cast(maxv)):
            _minv = minv if minv is not None else "any"
            _maxv = maxv if maxv is not None else "any"
            raise ConfigError("[%s] not in the range (%s,%s)" %
                              (value, _minv, _maxv))
    return typed_value

def is_set(value):
    if not isinstance(value, list):
        raise ConfigError("Expected a list of values. Found [%s]" %value)
    return set(value)

def is_appset_entry(value):
    if not isinstance(value, list) or len(value) != 2:
        raise ConfigError("unexpected application format [%s]. Expected [appname, maxcpus] format" %value)
    try:
        cores = int(value[2])
    except ValueError:
        raise ConfigError("unexpected application format [%s]. Expected [appname, maxcpus] format (maxcpus as integer)" %value)

    return [value[0], cores]

def is_float_list(value, minv=0, maxv=None):
    is_list(value)
    typed_value = []
    for v in value:
        typed_value.append(check_number(v, float, minv, maxv))
    return typed_value

def is_integer_list(value, minv=0, maxv=None):
    is_list(value)
    typed_value = []
    for v in value:
        typed_value.append(check_number(v, int, minv, maxv))
    return typed_value

def is_float(value, minv=None, maxv=None):
    return check_number(value, float, minv, maxv)

def is_integer(value, minv=None, maxv=None):
    return check_number(value, int, minv, maxv)

def is_list(value):
    if not isinstance(value, list):
        raise ConfigError("[%s] is not a list" %value)
    return value

def is_app_link(value, allow_none=True):
    if allow_none and value == 'none':
        return value
    elif value.startswith('@'):
        return value
    else:
        raise ConfigError('[%s] is not a valid block link' %value)

def is_app_list(value, allow_none=True):
    is_list(value)
    for v in value:
        is_app_link(v, allow_none=allow_none)
    return value

def is_boolean(value):
    if str(value).lower() in set(["1", "true", "yes"]):
        return True
    elif str(value).lower() in set(["0", "false", "no"]):
        return False
    else:
        raise ConfigError('[%s] is not a boolean value' %(value))

def is_integer_list(value, maxv=None, minv=None):
    is_list(value)
    return [is_integer(v, maxv=maxv, minv=minv) for v in value]

def is_correlative_integer_list(value, minv=None, maxv=None):
    is_list(value)
    typed_value = []
    last_value = 0
    for v in value:
        cv = is_integer(v, minv=None, maxv=None)
        typed_value.append(cv)
        if cv <= last_value:
            raise ConfigError("[%s] Numeric values are not correlative" %value)
        last_value = cv
    return typed_value

def is_text(value):
    if isinstance(value, str):
        return value
    else:
        raise ConfigError("[%s] is not a valid text string" %value)

def is_percent(value):
    try:
        is_float(value.rstrip('%'))
    except ConfigError:
        raise ConfigError('[%s] should a percentage value (i.e. 0.4%%)' %value)
    return value

def is_integer_or_percent(value):
    try:
        return is_integer(value)
    except ConfigError:
        try:
            is_percent(value)
        except ConfigError:
            raise ConfigError('[%s] should be an integer or a percentage (i.e. 15 or 0.4%%)' %value)
    return value

def is_choice(value, choices):
    if value in choices:
        return value
    else:
        raise ConfigError('[%s] should be one of %s' %(value, choices))

def is_raxml_bootstrap(value):
    try:
        return is_integer(value)
    except ValueError:
        if value == 'alrt' or value == 'alrt_phyml':
            return value
        else:
            raise ConfigError('[%s] bootstrap value should an integer, "alrt" or "phyml_alrt"' %(value))

CHECKERS = {
    # (app_name, attr_name): (checker_fn, args, required_attr)
    ("main", "_npr"): (is_app_list, {}, True),
    ("main", "_workflow"): (is_app_list, {"allow_none":False}, True),
    ("main", "_appset"): (is_app_link, {"allow_none":False}, True),

    ("npr", "_max_iters"): (is_integer, {"minv":1}, True),
    ("npr", "_switch_aa_similarity"): (is_float, {"minv":0, "maxv":1}, True),
    ("npr", "_max_seq_similarity"): (is_float, {"minv":0, "maxv":1}, True),
    ("npr", "_min_branch_support"): (is_float, {"minv":0, "maxv":1}, True),
    ("npr", "_min_npr_size"): (is_integer, {"minv":3}, True),
    ("npr", "_tree_splitter"): (is_app_link, {}, True),
    ("npr", "_target_levels"): (is_list, {}, False),

    ("genetree", "_aa_aligner"): (is_app_link, {}, True),
    ("genetree", "_nt_aligner"): (is_app_link, {}, True),
    ("genetree", "_aa_alg_cleaner"): (is_app_link, {}, True),
    ("genetree", "_nt_alg_cleaner"): (is_app_link, {}, True),
    ("genetree", "_aa_model_tester"): (is_app_link, {}, True),
    ("genetree", "_nt_model_tester"): (is_app_link, {}, True),
    ("genetree", "_aa_tree_builder"): (is_app_link, {}, True),
    ("genetree", "_nt_tree_builder"): (is_app_link, {}, True),
    ("genetree", "_appset"): (is_app_link, {"allow_none":False}, True),

    ("supermatrix", "_cog_selector"): (is_app_link, {}, True),
    ("supermatrix", "_alg_concatenator"): (is_app_link, {}, True),
    ("supermatrix", "_aa_tree_builder"): (is_app_link, {}, True),
    ("supermatrix", "_nt_tree_builder"): (is_app_link, {}, True),
    ("genetree", "_appset"): (is_app_link, {"allow_none":False}, True),

    ("concatalg", "_default_aa_model"): (is_text, {}, True),
    ("concatalg", "_default_nt_model"): (is_text, {}, True),

    #("concatalg", "_workflow"): (is_app_link, {"allow_none":False}, True),

    ("cogselector", "_species_missing_factor"): (is_float, {"minv":0, "maxv":1}, True),
    ("cogselector", "_max_cogs"): (is_integer, {"minv":1}, True),

    ("treesplitter", "_max_outgroup_size"): (is_integer_or_percent, {}, True),
    ("treesplitter", "_min_outgroup_support"): (is_float, {"minv":0, "maxv":1}, True),
    ("treesplitter", "_outgroup_topology_dist"): (is_boolean, {}, True),
    ("treesplitter", "_first_split"): (is_text, {}, True),

    ("metaaligner", "_aligners"): (is_app_list, {}, True),
    ("metaaligner", "_alg_trimming"): (is_boolean, {}, True),

    ("prottest", "_lk_mode"): (is_choice, {"choices":set(['phyml', 'raxml'])}, True),
    ("prottest", "_models"): (is_list, {}, True),

    ("pmodeltest", "_aa_models"): (is_text, {}, True),
    ("pmodeltest", "_nt_models"): (is_text, {}, True),

    ("raxml", "_aa_model"): (is_text, {}, True),
    ("raxml", "_method"): (is_choice, {"choices":set(['GAMMA', 'CAT'])}, True),
    ("raxml", "_bootstrap"): (is_raxml_bootstrap, {}, True),
    ("raxml", "_model_suffix"): (is_text, {}, True),

    ("raxml-sse", "_aa_model"): (is_text, {}, True),
    ("raxml-sse", "_method"): (is_choice, {"choices":set(['GAMMA', 'CAT'])}, True),
    ("raxml-sse", "_alrt_calculation"): (is_choice, {"choices":set(['phyml', 'raxml'])}, True),

    ("raxml-avx", "_aa_model"): (is_text, {}, True),
    ("raxml-avx", "_method"): (is_choice, {"choices":set(['GAMMA', 'CAT'])}, True),
    ("raxml-avx", "_alrt_calculation"): (is_choice, {"choices":set(['phyml', 'raxml'])}, True),

    ("appset", "muscle"): (is_appset_entry, {}, True),
    ("appset", "mafft"): (is_appset_entry, {}, True),
    ("appset", "clustalo"): (is_appset_entry, {}, True),
    ("appset", "trimal"): (is_appset_entry, {}, True),
    ("appset", "readal"): (is_appset_entry, {}, True),
    ("appset", "tcoffee"): (is_appset_entry, {}, True),
    ("appset", "phyml"): (is_appset_entry, {}, True),
    ("appset", "raxml-pthreads"): (is_appset_entry, {}, True),
    ("appset", "raxml"): (is_appset_entry, {}, True),
    # ("appset", "raxml-pthreads-sse3"): (is_appset_entry, {}, True),
    # ("appset", "raxml-sse3"): (is_appset_entry, {}, True),
    # ("appset", "raxml-pthreads-avx"): (is_appset_entry, {}, True),
    # ("appset", "raxml-avx"): (is_appset_entry, {}, True),
    # ("appset", "raxml-pthreads-avx2"): (is_appset_entry, {}, True),
    # ("appset", "raxml-avx2"): (is_appset_entry, {}, True),
    ("appset", "dialigntx"): (is_appset_entry, {}, True),
    ("appset", "fasttree"): (is_appset_entry, {}, True),
    ("appset", "statal"): (is_appset_entry, {}, True),

    }


def containsDuplicate(nums: list[int]) -> bool:
    hashset = set()

    for n in nums:
        if n in hashset:
            return True

        hashset.add(n)

    return False

if __name__ == "__main__":

    A = [1,2,3,1]
    B = [1,2,3,4]
    C = [1,1,1,3,3,4,3,2,4,2]

    X = containsDuplicate(A)
    print(X)

    Y = containsDuplicate(B)
    print(Y)

    Z = containsDuplicate(C)
    print(Z)


def stor(ftp=None):
    """Same as ftplib's storbinary() but just sends dummy data
    instead of reading it from a real file.
    """
    if ftp is None:
        ftp = connect()
        quit = True
    else:
        quit = False
    ftp.voidcmd('TYPE I')
    with contextlib.closing(ftp.transfercmd("STOR " + TESTFN)) as conn:
        chunk = b'x' * BUFFER_LEN
        total_sent = 0
        while True:
            sent = conn.send(chunk)
            total_sent += sent
            if total_sent >= FILE_SIZE:
                break
    ftp.voidresp()
    if quit:
        ftp.quit()
    return ftp


from collections import *

"""
    1st: hashtable

    Time    O(N)
    Space   O(N)
"""

class Solution:
    def countPoints(self, rings: str) -> int:
        ht = defaultdict(set)
        for i in range(0, len(rings), 2):
            color = rings[i]
            pos = rings[i+1]
            ht[pos].add(color)
        res = 0
        for key in ht:
            if len(ht[key]) == 3:
                res += 1
        return res


def insertion(n, m, i, j):
    for k in range(i, j+1):
        mask = ~(1 << k)
        n &= mask
    m <<= i
    return n | m

def longest_sequence_ones(n):
    curr = 0
    prev = 0
    max_len = 0
    for i in range(32):
        if n & (1 << i) != 0:
            curr += 1
        else:
            prev = curr
            curr = 0

        max_len = max(curr + prev + 1, max_len)

    return max_len

def conversion(a, b):
    c = a ^ b
    count = 0
    while c != 0:
        if c & 1 == 1:
            count += 1
        c >>= 1
    return count

def pairwise_swap(n):
    odd = 1
    even = 0
    mask = 0b11
    while odd < 32:
        odd_bit = (n & (1 << odd))
        even_bit = (n & (1 << even))
        n &= ~mask
        n |= (odd_bit >> 1)
        n |= (even_bit << 1)
        odd += 2
        even += 2
        mask <<= 2
    return n

if __name__ == '__main__':
    print(bin(pairwise_swap(0b11101001)))


from sympy import isprime

def get_prop_prime(nums):
    # return number of primes in nums / len of nums
    return [isprime(num) for num in nums].count(True) / len(nums)

def smart_get_diags(sidelen):
    # to generate the diagonals, simply start at 1, then add 2 4 times, then add 4 4 times, then 6, etc.
    assert sidelen % 2 == 1, "sidelen must be odd"
    maxadd = sidelen - 1
    diags = [1]
    adding = 2
    while adding <= maxadd:
        for _ in range(4):
            diags.append(diags[-1] + adding)
        adding += 2
    return diags

if __name__ == "__main__":
    prop = 1
    sidelen = 1
    # do a binary search of sorts by taking big steps until you get below 0.1, then find where exactly it crosses 0.1
    step = 512
    while step > 1:
        while prop >= 0.1:
            sidelen += step
            diags = smart_get_diags(sidelen)
            prop = get_prop_prime(diags)
            print(sidelen, prop)
        sidelen = sidelen - step
        step //= 2
        prop = 1
    print(sidelen + 2)


from __future__ import absolute_import, division, print_function
from libtbx import easy_pickle
from libtbx.utils import Abort
from libtbx import object_oriented_patterns as oop
from libtbx import adopt_init_args
import libtbx.callbacks # import dependency
from six.moves import queue
import threading
import warnings
import traceback
import signal
import time
import os
import sys

class thread_with_callback_and_wait(threading.Thread):

  def __init__(self,
          run,
          callback,
          first_callback=None,
          run_args=(),
          run_kwds={}):
    self._run = run
    self._run_args = run_args
    self._run_kwds = dict(run_kwds) # copy, to avoid side effects
    self._run_kwds['callback'] = self._callback_proxy
    self._callback = callback
    self._first_callback = first_callback
    self._caller_wait = queue.Queue(0)
    self._queue = queue.Queue(0)
    threading.Thread.__init__(self)

  def run(self):
    self._run(*self._run_args, **self._run_kwds)

  def start_and_wait_for_first_callback(self):
    self.start()
    self._caller_wait.get()

  def _callback_proxy(self, *args, **kwds):
    if (self._first_callback is not None):
      result = self._first_callback(*args, **kwds)
      self._first_callback = None
      self._caller_wait.put(None)
    else:
      result = self._callback(*args, **kwds)
    if (result == False):
      return False
    last_iteration = self._queue.get()
    if (last_iteration):
      return False
    return result

  def resume(self, last_iteration=False):
    if (self.is_alive()):
      self._queue.put(last_iteration)
    return self

null_callback = oop.null()

class queue_monitor_thread(threading.Thread):
  def __init__(self, q, callback, sleep_interval=1.0):
    self.q = q
    self.cb = callback
    self._exit = False
    self._sleep_interval = sleep_interval
    threading.Thread.__init__(self)

  def run(self):
    t = self._sleep_interval
    while not self._exit :
      if (self.q.qsize() > 0):
        result = self.q.get(timeout=1)
        self.cb(result)
      else :
        time.sleep(t)

  def exit(self):
    self._exit = True

class file_monitor_thread(threading.Thread):
  def __init__(self, dir_name, file_names, callback, sleep_interval=1.0):
    assert os.path.isdir(dir_name)
    self.cb = callback
    self.dir_name = dir_name
    self.file_names = file_names
    self._exit = False
    self._sleep_interval = sleep_interval
    threading.Thread.__init__(self)

  def run(self):
    t = self._sleep_interval
    existing_files = []
    pending_files = []
    while not self._exit :
      files = os.listdir(self.dir_name)
      for file_name in files :
        if (file_name in existing_files):
          continue
        elif (file_name in pending_files):
          data = easy_pickle.load(os.path.join(self.dir_name, file_name))
          existing_files.append(file_name)
          #pending_files.remove(file_name)
          self.cb(data)
        elif (file_name in self.file_names):
          pending_files.append(file_name)
      time.sleep(t)

  def exit(self):
    self._exit = True

class simple_task_thread(threading.Thread):
  def __init__(self, thread_function, parent_window=None):
    threading.Thread.__init__(self)
    self.f = thread_function
    self.return_value = None
    self._exception = None

  def is_complete(self):
    return (self.return_value is not None)

  def exception_raised(self):
    return (self._exception is not None)

  def run(self):
    try :
      self.return_value = self.f()
    except Exception as e :
      sys.stderr.write(str(e))
      self._exception = e

  def get_error(self):
    return str(self._exception)

class child_process_message(object):
  def __init__(self, message_type, data):
    adopt_init_args(self, locals())

class child_process_pipe(object):
  def __init__(self, connection_object):
    adopt_init_args(self, locals())

  def send_confirm_abort(self, info=None):
    message = child_process_message(message_type="aborted", data=info)
    self.connection_object.send(message)

  def send(self, *args, **kwds):
    return self.connection_object.send(*args, **kwds)

  def recv(self, *args, **kwds):
    return self.connection_object.recv(*args, **kwds)

# fake filehandle, sends data up pipe to parent process
class stdout_pipe(object):
  def __init__(self, connection):
    self._c = connection
    self._data = ""

  def write(self, data):
    self._data += data
    self.flush() # this needs to be done immediately for some reason

  def flush(self):
    self._flush()

  def _flush(self):
    try :
      if self._data != "" :
        message = child_process_message(message_type="stdout", data=self._data)
        self._c.send(message)
        self._data = ""
    except Exception as e :
      sys.__stderr__.write("Exception in stdout_pipe: %s\n" % str(e))

  def close(self):
    pass

wait_before_flush = 0.2 # minimum time between send() calls
max_between_flush = 5

# this slows down the output so it won't stall a GUI
class stdout_pipe_buffered(stdout_pipe):
  def __init__(self, *args, **kwds):
    stdout_pipe.__init__(self, *args, **kwds)
    self._last_t = time.time()

  def write(self, data):
    self._data += data
    t = time.time()
    if (t >= (self._last_t + max_between_flush)):
      self.flush()

  def flush(self):
    t = time.time()
    if (t >= (self._last_t + wait_before_flush)):
      self._flush()
      self._last_t = t

  def close(self):
    pass

  def __del__(self):
    if self._data != "" :
      self._flush()

try:
  import multiprocessing
except ImportError:
  class process_with_callbacks(object):
    def __init__(self, *args, **kwds):
      raise ImportError("The multiprocessing module is not available.")
else:
  class _process_with_stdout_redirect(multiprocessing.Process):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs={},
        connection=None, buffer_stdout=True):
      multiprocessing.Process.__init__(self, group, target, name, args, kwargs)
      self._c = connection
      if buffer_stdout :
        self._stdout = stdout_pipe_buffered(connection)
      else :
        self._stdout = stdout_pipe(connection)

    def run(self):
      import libtbx.callbacks # import dependency
      libtbx.call_back.add_piped_callback(self._c)
      old_stdout = sys.stdout
      sys.stdout = self._stdout
      message = None
      old_showwarning = warnings.showwarning
      warnings.showwarning = libtbx.call_back.showwarning
      try :
        try :
          if self._target :
            return_value = self._target(self._args, self._kwargs, self._c)
            message = child_process_message(message_type="return",
                                            data=return_value)
        except Abort :
          message = child_process_message(message_type="abort", data=None)
        except Exception as e :
          if e.__class__.__module__ == "Boost.Python" :
            e = RuntimeError("Boost.Python.%s: %s" % (e.__class__.__name__,
              str(e)))
          elif hasattr(e, "reset_module"):
            e.reset_module()
          traceback_str = "\n".join(traceback.format_tb(sys.exc_info()[2]))
          message = child_process_message(message_type="exception",
                                          data=(e, traceback_str))
      finally :
        if message is not None :
          self._stdout._flush()
          self._c.send(message)
        warnings.showwarning = old_showwarning
      sys.stdout = old_stdout

  #XXX: target functions must use this call signature!!!
  # I normally just write a very short wrapper function that invokes the
  # command I actually care about with args/kwds.
  def _process_target_function(args, kwds, connection):
    connection.send(True)

  # not really a process, but a wrapper for one.
  class process_with_callbacks(threading.Thread):
    def __init__(self,
        target,
        args=(),
        kwargs={},
        callback_stdout=null_callback,
        callback_final=null_callback,
        callback_err=null_callback,
        callback_abort=null_callback,
        callback_other=null_callback,
        callback_pause=null_callback,  # XXX experimental
        callback_resume=null_callback, # XXX experimental
        buffer_stdout=True,
        sleep_after_start=None):
      threading.Thread.__init__(self)
      self._target = target
      self._args = args
      self._kwargs = dict(kwargs)
      assert (hasattr(callback_stdout, "__call__") and
              hasattr(callback_final, "__call__") and
              hasattr(callback_err, "__call__") and
              hasattr(callback_abort, "__call__") and
              hasattr(callback_other, "__call__") and
              hasattr(callback_pause, "__call__") and
              hasattr(callback_resume, "__call__"))
      self._cb_stdout = callback_stdout
      self._cb_final  = callback_final
      self._cb_err    = callback_err
      self._cb_abort  = callback_abort
      self._cb_other  = callback_other
      self._cb_pause  = callback_pause
      self._cb_resume = callback_resume
      self._buffer_stdout = buffer_stdout
      self._abort = False
      self._killed = False
      self._completed = False
      self._error = False
      self._pid = None
      self._child_process = None
      assert ((sleep_after_start is None) or
              isinstance(sleep_after_start, int) or
              isinstance(sleep_after_start, float))
      self._sleep_after_start = sleep_after_start

    def abort(self, force=False):
      self._abort = True
      if (force):
        self.kill()

    # XXX experimental
    def kill(self):
      if (self._child_process is not None):
        try :
          self._child_process.terminate()
          self.join(0.1)
          self._killed = True
        except OSError as e :
          print(e)
        else :
          self._cb_abort()

    def send_signal(self, signal_number) : # XXX experimental
      """
      Signals the process using os.kill, which despite the name, can also
      pause or resume processes on Unix.
      """
      assert (self._child_process is not None)
      try :
        os.kill(self._child_process.pid, signal_number)
      except OSError as e :
        print(e)
        if (not self._child_process.is_alive()):
          self._cb_abort() # XXX not sure if this is ideal
        return False
      else :
        return True

    def pause(self):
      if sys.platform != "win32":
        if (self.send_signal(signal.SIGSTOP)):
          self._cb_pause()
      else:
        import psutil # really should use psutil globally as it is platform independent
        p = psutil.Process(self._child_process.pid)
        p.suspend()
        self._cb_pause()

    def resume(self):
      if sys.platform != "win32":
        if (self.send_signal(signal.SIGCONT)):
          self._cb_resume()
      else:
        import psutil
        p = psutil.Process(self._child_process.pid)
        p.resume()
        self._cb_resume()

    def run(self):
      if (self._sleep_after_start is not None):
        time.sleep(self._sleep_after_start)
      child_process = None
      parent_conn, child_conn = multiprocessing.Pipe()
      try :
        child_process = _process_with_stdout_redirect(
          target        = self._target,
          args          = self._args,
          kwargs        = self._kwargs,
          connection    = child_process_pipe(connection_object=child_conn),
          buffer_stdout = self._buffer_stdout)
        os.environ["OMP_NUM_THREADS"] = "1"
        self._child_process = child_process
        child_process.start()
      except Exception as e :
        sys.__stderr__.write("Error starting child process: %s\n" % str(e))
        child_process = None
      while child_process is not None :
        if (self._killed) : break
        if self._abort :
          child_process.terminate()
          self._cb_abort()
          break
        if not parent_conn.poll(1):
          continue
        pipe_output = parent_conn.recv()
        if isinstance(pipe_output, child_process_message):
          message = pipe_output
          (error, traceback_info) = (None, None)
          if message.message_type == "aborted" :
            child_process.terminate()
            self._cb_abort()
            break
          elif message.message_type == "stdout" :
            self._cb_stdout(message.data)
          elif message.message_type == "return" :
            self._cb_final(message.data)
            self._completed = True
            break
          elif message.message_type == "exception" :
            (error, traceback_info) = message.data
            self._cb_err(error, traceback_info)
            self._error = True
            child_process.terminate()
            break
        else :
          self._cb_other(pipe_output)
      if child_process is not None and child_process.is_alive():
        child_process.join()


import random
import os
import sys
import w3lib
from pathlib import Path
PROG_NAME = os.path.splitext(sys.argv[0])[0]
DATASET_DIR = os.path.join(os.getcwd(), "datasets/{}".format(PROG_NAME))

def proteinTranslation(rna) :
    CODON_LEN = 3
    genetic_code = w3lib.CODON_TABLE
    peptide = []

    for i in range(0, len(rna)-CODON_LEN+1, CODON_LEN) :
        codon = rna[i:i+CODON_LEN]

        if genetic_code[codon] != "STOP" :
            peptide.append(genetic_code[codon])

    return "".join(peptide)

def main() :
    util = w3lib.Week3Library()
    description = '''\
        Given a string of RNA, it will translate to sequence of amino acids.

        Input File format :
        ---------------------------------------
        AUGGCCAUGGCGCCCAGAACUGAGAUCAAUAGUACCCGUAUUAACGGGUGA

        Expected output :
        ---------------------------------------
        MAMAPRTEINSTRING
        '''
    args = util.create_parser(__file__, description)

    dataset_path = "{}/real_dataset.txt".format(DATASET_DIR)

    # Default to the dataset folder, if not provided
    if not args.file : args.file = dataset_path

    # Read from dataset file
    with open(args.file, 'r') as f :
        rna = f.readline().strip()

    peptide = proteinTranslation(rna)
    print(peptide)

if __name__ == "__main__":
    main()


import numpy as np
import pygame

# Implementation of a Gridworld environment
# Gridworld consist of a grid that the agent can move around
# The action space of gridworld consist of four actions
#   0: move left
#   1: move up
#   2: move right
#   3: move down
# The observatino space of gridworld consist of two values:
#   0: x position
#   1: y position
class Gridworld:

    def __init__(self, x, y):
        self.observation_space = np.array([x, y])
        self.action_space = np.array([0, 1, 2, 3])
        self.agent_position = [0, 0]
        self.reward_position = [x - 1, y-1]

    def step(self, action):
        reward = 0
        terminated = False
        truncated = False

        self.move_agent(action)

        if self.agent_position == self.reward_position:
            terminated = True
            reward = 1

        # return result
        return self.agent_position, reward, terminated, truncated

    def move_agent(self, action):
        # convert action to movement
        x, y = self.action_to_movement(action)

        # Check that move is valid
        new_pos_x = self.agent_position[0] + x
        new_pos_y = self.agent_position[1] + y
        if new_pos_x < 0 or new_pos_x > self.observation_space[0] - 1:
            return
        if new_pos_y < 0 or new_pos_y > self.observation_space[1] - 1:
            return

        # Actually move agent
        self.agent_position[0] = new_pos_x
        self.agent_position[1] = new_pos_y

    def action_to_movement(self, action):
        if action == 0:
            return [-1, 0]
        if action == 1:
            return [0, -1]
        if action == 2:
            return [1, 0]
        if action == 3:
            return [0, 1]

        print(f"invalid action: {action}")
        return [0, 0]

    def reset(self, random = False):
        # Move agent to start position
        if not random:
            self.agent_position = [0, 0]
            return self.agent_position

        x = np.random.randint(0, self.observation_space[0])
        y = np.random.randint(0, self.observation_space[1])
        self.agent_position = [x, y]
        return self.agent_position

    def sample(self):
        random_action = np.random.randint(0, 4)
        return self.action_space[random_action]

class QLearn:

    def __init__(self, observation_space, action_space, alpha, gamma):
        self.alpha = alpha
        self.gamma = gamma
        self.Q = np.zeros([observation_space[0]] + [observation_space[1]] + [action_space.shape[0]])
        print(self.Q)
        self.Q = np.random.random(size=([observation_space[0]] + [observation_space[1]] + [action_space.shape[0]]))
        print(self.Q)

    def learn(self, action, state, reward, new_state):
        self.Q[state[0], state[1]][action] = self.bellmann(action, state, reward, new_state)

    def bellmann(self, action, state, reward, new_state):
        return (1 - self.alpha) * self.Q[state[0], state[1]][action] + self.alpha * (reward + self.gamma * np.max(self.Q[new_state[0], new_state[1]]))

    def policy(self, state):
        return np.argmax(self.Q[state[0], state[1]])

alpha = 0.05 # learning rate
gamma = 0.95 # discount factor
epsilon = 0.2 # Exploration rate

env = Gridworld(5, 5)
model = QLearn(env.observation_space, env.action_space, alpha, gamma)

observation = env.reset()

episodes = 100000
for i in range(episodes):
    observation = env.reset(True)

    if i % int(episodes/10) == 0:
        print(i)

    while True:
        # env.render()
        action = model.policy(observation)

        # Some moves are random
        if np.random.uniform(0, 1) <= epsilon:
            action = env.sample()

        old_observation = observation.copy()
        observation, reward, terminated, truncated = env.step(action)

        model.learn(action, old_observation, reward, observation)

        if terminated or truncated:
            break

# =============================================================================
# Pygame
# =============================================================================

# Constants
WHITE = (255, 255, 255)
BLACK = (0,0,0)
RED = (200,0,0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
PURPLE = (255, 0, 255)
BROWN  = (0, 255, 255)

WIDTH = 640
HEIGHT = 480
TILE_SIZE = 60

def update_pos(screen, pos):
    # update square
    rect = pygame.Rect(pos[0] * TILE_SIZE, pos[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
    pygame.draw.rect(screen, RED, rect)

    # write debugging info
    font = pygame.font.SysFont("None", 24)
    text_pos = font.render(f"pos {pos}", True, BLACK)
    screen.blit(text_pos, (WIDTH - 2 * TILE_SIZE, TILE_SIZE))

    pygame.display.update()

def draw_grid(screen, q_table):
    screen.fill(WHITE)
    for x in range(env.observation_space[0]):
        for y in range(env.observation_space[1]):
            cell = pygame.Surface([TILE_SIZE, TILE_SIZE])
            cell.fill(WHITE)
            rect = pygame.Rect(0, 0, TILE_SIZE, TILE_SIZE)
            pygame.draw.rect(cell, BLACK, rect, 1)

            # Draw and orient arrow
            pygame.draw.polygon(cell, BLACK, ((0, 10), (0, 20), (20, 20), (20, 30), (30, 15), (20, 0), (20, 10)))
            oriented_cell = pygame.transform.rotate(cell, float(np.argmax(q_table[x, y])) * -90 + 180)
            screen.blit(oriented_cell, (x * TILE_SIZE, y * TILE_SIZE))

    # Draw termination state (goal)
    rect = pygame.Rect(env.reward_position[0] * TILE_SIZE , env.reward_position[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
    pygame.draw.rect(screen, BLUE, rect)

# setup
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Gridworld")

for i in range(20):
    observation = env.reset(True)

    while True:
        # Visuals
        pygame.time.delay(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

        draw_grid(screen, model.Q)
        update_pos(screen, observation)

        # Actual model
        action = model.policy(observation)
        observation, reward, terminated, truncated = env.step(action)

        if terminated or truncated:
            break

print(model.Q)
pygame.quit()


from queue import PriorityQueue

# adj는 가중치를 포함하는 인접리스트의 형태의 그래프이고 start는 prim 알고리즘의 시작정점
def prim(adj, start):
    # 최소 신장 트리에 이미 포함된 정점을 표시하기 위해 covered변수를 set으로 선언한다.
    covered = set()

    # prim 알고리즘의 결과 그래프를 간선들의 목록으로 return하기 위해 res_edges 변수를 list로 선언한다.
    res_edges = []

    # 후보 간선들을 관리할 우선순위큐를 queue변수에 선언한다.
    queue = PriorityQueue()

    # 후보 간선들은 (간선의 가중치, 도착 정점, 시작 정점)으로 표현된다.
    # start 정점에서 알고리즘을 시작하도록 아래처럼 넣는다.
    queue.put((0, start, None))

    while not queue.empty():
        u_cost, u, u_src = queue.get()
        # 맘닐 정점 u가 최소신장트리에 이미 포함되어 있으면 이 간선은 MST에 cycle을 만들기 때문에 무시한다.
        if u in covered:
            continue
        # 이 시점에 정점 u를 최소신장트리에 포함시키는 것이기 때문에 covered에 u를 넣어서 MST에 정점 u가
        # 포함되었다고 표시

        covered.add(u)

        # 정점 u와 연결하는 현재의 간선을 res_edges에 추가
        # u_src 변수가 none일 경우 간선이 아닌 최초 queue에 넣어둔 특수한 값이기 때문에 무시한다.
        if u_src is not None:
            res_edges.append((u_cost, u, u_src))

        # 정점 u와 연결된 모든 간선 (u, v)중에 v가 최소신장트리에 포함되지 않은경우에만 cost와 함께 queue에 넣어준다.
        for v_cost, v in adj[u]:
            # v가 최소신장에 포함되는 간선은 cycle을 만들기에 넣지 않는다.
            if v not in covered:
                queue.put((v_cost, v, u))

    return res_edges

# [(29, '2', '1'), (34, '6', '2'), (23, '4', '6'), (7, '3', '4'), (13, '7', '4'), (53, '5', '6')]

adj = {
    "1": [(29, "2"), (75, "5")],
    "2": [(29, "1"), (35, "3"), (34, "6")],
    "3": [(35, "2"), (7, "4")],
    "4": [(7, "3"), (23, "6"), (13, "7")],
    "5": [(75, "1"), (53, "6")],
    "6": [(34, "2"), (23, "4"), (53, "5"), (25, "7")],
    "7": [(13, "4"), (25, "6")],
}

edges = prim(adj, "1")

cost_sum = 0
for u_cost, u, v in edges:
    print((u_cost, u, v))
    cost_sum += u_cost

print(cost_sum)

# import heapq
# import collections
# import sys

# sys.setrecursionlimit(10**6)
# input = sys.stdin.readline

# n, m = map(int, input().split())
# graph = collections.defaultdict(list)  # 빈 그래프 생성
# # 노드의 방문 정보 초기화
# visited = [0] * (n + 1)

# # 무방향 그래프 생성
# for i in range(m):
#     u, v, weight = map(int, input().split())
#     graph[v].append([weight, u, v])
#     graph[v].append([weight, v, u])

# def prim(graph, start_node):
#     # 방문 갱신
#     visited[start_node] = 1
#     # 인접 간선 추출
#     candidate = graph[start_node]
#     # 우선순위 큐 생성
#     heapq.heapify(candidate)
#     # 최소스패닝트리 리스트
#     mst = []
#     # 전체 가중치
#     total_weight = 0

#     while candidate:
#         weight, u, v = heapq.heappop(candidate)
#         # 방문하지 않았다면
#         if visited[v] == 0:
#             # 방문 갱신
#             visited[v] = 1
#             # mst 삽입
#             mst.append((u, v))
#             # 전체 가중치 갱신
#             # 다음 인접 간선 탐색
#             total_weight += weight
#             for edge in graph[v]:
#                 # 방문한 노드가 아니라면(순환 방지)
#                 if visited[edge[2]] == 0:
#                     # 우선순위 큐에 edge 삽입
#                     heapq.heappush(candidate, edge)

#     return total_weight

# edges = prim(graph, 1)

# print(edges)

# cost_sum = 0
# print(edges)
# for u_cost, u, v in edges:
#     print((u_cost, u, v))
#     cost_sum += u_cost

# print(cost_sum)

# import collections
# import heapq

# graph = collections.defaultdict(list)  # 빈 그래프 생성
# # n, m = map(int, input().split())  # 노드 수, 간선 수
# visited = [0] * (8)  # 노드의 방문 정보 초기화

# # for i in range(m):  # 간성 정보 입력 받기
# #     u, v, weight = map(int, input().split())
# #     graph[u].append([weight, u, v])
# #     graph[v].append([weight, v, u])

# def prim(tree, start):
#     queue = []
#     heapq.heappush(queue, (0, start))  # 비용, 노드
#     sum_ = 0

#     while queue:
#         weight, u, v = heapq.heappop(queue)
#         if visited[v]:  # 큐에 같은 노드가 여러번 들어가있을 수 있으므로 한번 더 체크 필수
#             continue
#         else:
#             visited[v] = True
#             sum_ += weight

#         for nextV in tree[v]:  # 다음노드, 비용
#             if not visited[nextV[0]]:
#                 heapq.heappush(queue, (nextV[1], nextV[0]))
#     return sum_

# tree = {
#     "1": [(29, "2"), (75, "5")],
#     "2": [(29, "1"), (35, "3"), (34, "6")],
#     "3": [(35, "2"), (7, "4")],
#     "4": [(7, "3"), (23, "6"), (13, "7")],
#     "5": [(75, "1"), (53, "6")],
#     "6": [(34, "2"), (23, "4"), (53, "5"), (25, "7")],
#     "7": [(13, "4"), (25, "6")],
# }

# print(prim(graph, "1"))


# multimodal_entailment.py
# Training a multimodal model for predicting entailment.
# Introduction
# This example builds and trains a model for predicting multimodal
# entailment. It will be using the multimodal entailment dataset
# recently introduced by Google Research.
# What is multimodal entailment?
# On social media platforms, to audit and moderate content we may want
# to find answers to the following questions in near real-time:
# -> Does a given piece of information contradict the other?
# -> Does a given piece of information imply the other?
# In NLP, this task is called analyzing textual entailment. However,
# that's only when the information comes from text content. In
# practice, it's often the case the information available comes not
# just from text content, but from a multimodal combination of text,
# images, audio, video, etc. Multimodal entailment is simply the
# extension of textual entailment to a variety of new input modalities.
# Requirements
# This example requires Tensorflow 2.5 or higher. In addition,
# Tensorflow Hub and Tensorflow Text are required for the BERT model
# (Devlin et al.).
# Source: https://keras.io/examples/nlp/multimodal_entailment/
# Tensorflow 2.7.0
# Python 3.7
# Windows/MacOS/Linux

import os
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
import tensorflow_hub as hub
import tensorflow_text as text
#import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

def main():
	# Defina a label map.
	label_map = {"Contradictory": 0, "Implies": 1, "NoEntailment": 2}

	# Collect the dataset.
	# The original dataset is available here. It comes with URLs of
	# images which are hosted on Twitter's photo storage system called
	# the Photo Blob Storage (PBS for short). This example will be
	# working with the downloaded images along with additional data
	# that comes with the original dataset. Thanks to Nilabhra Roy
	# Chowdhury who worked on preparing the image data.
	image_base_path = keras.utils.get_file(
		"tweet_images",
		"https://github.com/sayakpaul/Multimodal-Entailment-Baseline/releases/download/v1.0.0/tweet_images.tar.gz",
		untar=True,
	)

	# Read the dataset and apply basic preprocessing.
	df = pd.read_csv(
		"https://github.com/sayakpaul/Multimodal-Entailment-Baseline/raw/main/csvs/tweets.csv"
	)
	df.sample(10)

	# The columns we are interested in are the following:
	# -> text_1
	# -> image_1
	# -> text_2
	# -> image_2
	# -> label
	# The entailment task is formulated as the following:
	# "Given the pairs of (text_1, image_1) and (text_2, image_2) do
	# they entail (or not entail or contradict) each other?"
	# image_1 is downloaded as id1 as its filename and image2 is
	# downloaded as id2 as its filename. In the next step, will add twp
	# more columns to df - filepaths of image_1s and image_2s.
	images_one_paths = []
	images_two_paths = []

	for idx in range(len(df)):
		current_row = df.iloc[idx]
		id_1 = current_row["id_1"]
		id_2 = current_row["id_2"]
		extension_one = current_row["image_1"].split(".")[-1]
		extension_two = current_row["image_2"].split(".")[-1]

		image_one_path = os.path.join(image_base_path, str(id_1) + f".{extension_one}")
		image_two_path = os.path.join(image_base_path, str(id_2) + f".{extension_two}")

		images_one_paths.append(image_one_path)
		images_two_paths.append(image_two_path)

	df["image_1_path"] = images_one_paths
	df["image_2_path"] = images_two_paths

	# Create another column containing the integer ids of the string
	# labels.
	df["label_idx"] = df["label"].apply(lambda x: label_map[x])

	# Dataset visualization.
	'''
	def visualize(idx):
		current_row = df.iloc[idx]
		image_1 = plt.imread(current_row["image_1_path"])
		image_2 = plt.imread(current_row["image_2_path"])
		text_1 = current_row["text_1"]
		text_2 = current_row["text_2"]
		label = current_row["label"]

		plt.subplot(1, 2, 1)
		plt.imshow(image_1)
		plt.axis("off")
		plt.title("Image One")
		plt.subplot(1, 2, 2)
		plt.imshow(image_2)
		plt.axis("off")
		plt.title("Image Two")
		plt.show()

		print(f"Text one: {text_1}")
		print(f"Text two: {text_2}")
		print(f"Label: {label}")

	random_idx = np.random.choice(len(df))
	visualize(random_idx)

	random_idx = np.random.choice(len(df))
	visualize(random_idx)
	'''

	# Train/test split
	# The dataset suffers from class imbalance problem.
	print(df["label"].value_counts())

	# To account for that, go for a stratefied split.
	# 10% for test.
	train_df, test_df = train_test_split(
		df, test_size=0.1, stratify=df["label"].values, random_state=42
	)

	# 5% for validation.
	train_df, val_df = train_test_split(
		train_df, test_size=0.05, stratify=train_df["label"].values,
		random_state=42
	)

	print(f"Total training examples: {len(train_df)}")
	print(f"Total validation examples: {len(val_df)}")
	print(f"Total test examples: {len(test_df)}")

	# Data input pipeline.
	# Tensorflow Hub provides variety of BERT family of models. Each of
	# those models comes with a corresponding preprocessing layer. Can
	# learn more about those models and their preprocessing layers from
	# this resource.
	# To keep the runtime of this example relatively short, use a
	# smaller variant of the original BERT model.
	# Define TF Hub paths to the BERT encoder and its preprocessor.
	bert_model_path = (
		"https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-256_A-4/1"
	)
	bert_preprocess_path = "https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3"

	# The text preprocessing code mostly comes from this tutorial. It
	# is highly encouraged to check out the tutorial to learn about the
	# input preprocessing.
	def make_bert_preprocessing_model(sentence_features, seq_length=128):
		# Returns model mapping string features to BERT inputs.
		# @param: sentence_features, a list with the names of
		#	string-valued features.
		# @param: seq_length, an integer that defines the sequence
		#	length of BERT inputs.
		# @return: returns a keras model that can be called on a list
		#	or dict of string Tensors (with the order or names, resp.,
		#	given by sentence_features) and returns a dict of tensors
		#	for input to BERT.
		input_segments = [
			tf.keras.layers.Input(shape=(), dtype=tf.string, name=ft)
			for ft in sentence_features
		]

		# Tokenize the text to word pieces.
		bert_preprocess = hub.load(bert_preprocess_path)
		tokenizer = hub.KerasLayer(bert_preprocess.tokenize, name="tokenizer")
		segments = [tokenizer(s) for s in input_segments]

		# Optional: Trim segments in a smart way to fit seq_length.
		# Simple cases (like this example) can skip this step and let
		# the next step apply a default truncation to approximately
		# equal lengths.
		truncated_segments = segments

		# Pack inputs. The details (start/end token ids, dict of output
		# tensors) are model-dependent, so this gets loaded from the
		# SavedModel.
		packer = hub.KerasLayer(
			bert_preprocess.bert_pack_inputs,
			arguments=dict(seq_length=seq_length),
			name="packer",
		)
		model_inputs = packer(truncated_segments)
		return keras.Model(input_segments, model_inputs)

	bert_preprocess_model = make_bert_preprocessing_model(
		["text_1", "text_2"]
	)
	'''
	keras.utils.plot_model(
		bert_preprocess_model, show_shapes=True, show_dtype=True
	)
	'''

	# Run the preprocessor on a sample input
	idx = np.random.choice(len(train_df))
	row = train_df.iloc[idx]
	sample_text_1, sample_text_2 = row["text_1"], row["text_2"]
	print(f"Text 1: {sample_text_1}")
	print(f"Text 2: {sample_text_2}")

	test_text = [np.array([sample_text_1]), np.array([sample_text_2])]
	text_preprocessed = bert_preprocess_model(test_text)

	print("Keys           : ", list(text_preprocessed.keys()))
	print("Shape Word Ids : ", text_preprocessed["input_word_ids"].shape)
	print("Word Ids       : ", text_preprocessed["input_word_ids"][0, :16])
	print("Shape Mask     : ", text_preprocessed["input_mask"].shape)
	print("Input Mask     : ", text_preprocessed["input_mask"][0, :16])
	print("Shape Type Ids : ", text_preprocessed["input_type_ids"].shape)
	print("Type Ids       : ", text_preprocessed["input_type_ids"][0, :16])

	# Create tf.data.Dataset objects from the dataframes.
	# Note that the text inputs will be preprocessed as part of the
	# data input pipeline. But the preprocessing modules can also be a
	# part of their corresponding BERT models. This helps reduce the
	# training/serving skew and lets the models operate with raw text
	# inputs. Follow this tutorial to learn more about how to
	# incorperate the preprocessing modules directly inside the models.
	def dataframe_to_dataset(dataframe):
		columns = ["image_1_path", "image_2_path", "text_1", "text_2", "label_idx"]
		dataframe = dataframe[columns].copy()
		labels = dataframe.pop("label_idx")
		ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
		ds = ds.shuffle(buffer_size=len(dataframe))
		return ds

	# Preprocessing utilities
	resize = (128, 128)
	bert_input_features = ["input_word_ids", "input_type_ids", "input_mask"]

	def preprocess_image(image_path):
		extension = tf.strings.split(image_path)[-1]

		image = tf.io.read_file(image_path)
		if extension == b"jpg":
			image = tf.image.decode_jpeg(image, 3)
		else:
			image = tf.image.decode_png(image, 3)
		image = tf.image.resize(image, resize)
		return image

	def preprocess_text(text_1, text_2):
		text_1 = tf.convert_to_tensor([text_1])
		text_2 = tf.convert_to_tensor([text_2])
		output = bert_preprocess_model([text_1, text_2])
		output = {feature: tf.squeeze(output[feature]) for feature in bert_input_features}
		return output

	def preprocess_text_and_image(sample):
		image_1 = preprocess_image(sample["image_1_path"])
		image_2 = preprocess_image(sample["image_2_path"])
		text = preprocess_text(sample["text_1"], sample["text_2"])
		return {"image_1": image_1, "image_2": image_2, "text": text}

	# Create the final datasets.
	batch_size = 32
	auto = tf.data.AUTOTUNE

	def prepare_dataset(dataframe, training=True):
		ds = dataframe_to_dataset(dataframe)
		if training:
			ds = ds.shuffle(len(train_df))
		ds = ds.map(lambda x, y: (preprocess_text_and_image(x), y)).cache()
		ds = ds.batch(batch_size).prefetch(auto)
		return ds

	train_ds = prepare_dataset(train_df)
	validation_ds = prepare_dataset(val_df, False)
	test_ds = prepare_dataset(test_df, False)

	# Model building utilities
	# Final model will accept two images along with their text
	# counterparts. While the images will be direclyy fed to the model
	# the text inputs will first be preprocessed and then will make it
	# into the model. Below is a visual illustration of this approach:
	# The model consists of the following elements:
	# -> A standalone encoder for the images. Use a ResNet50V2
	#	pre-trained on the ImageNet-1K dataset for this.
	# -> A standalone encoder for the images. A pre-trained BERT will
	#	be used for this.
	# After extracting the individual embeddings, they will only be
	# projected in an identical space. Finally, their projections will
	# be concatentated and be fed to the final classification layer.
	# This is a multi-class classification problem involving the
	# following classes:
	# -> NoEntailment
	# -> Implies
	# -> Contradictory
	# project_embeddings(), create_vision_encoder(), and
	# create_text_encoder() utilities are referred from this example
	# (CLIP/Natural Language Image Search with a Dual Encoder).
	# Projection utilities
	def project_embeddings(
			embeddings, num_projection_layers, projection_dims,
			dropout_rate
		):
		projected_embeddings = keras.layers.Dense(units=projection_dims)(embeddings)
		for _ in range(num_projection_layers):
			x = tf.nn.gelu(projected_embeddings)
			x = keras.layers.Dense(projection_dims)(x)
			x = keras.layers.Dropout(dropout_rate)(x)
			x = keras.layers.Add()([projected_embeddings, x])
			projected_embeddings = keras.layers.LayerNormalization()(x)
		return projected_embeddings

	# Vision encoder utilities
	def create_vision_encoder(
			num_projection_layers, projection_dims, dropout_rate,
			trainable=False
		):
		# Load the pre-trained ResNet40V2 model to be used as the base
		# encoder.
		resnet_v2 = keras.applications.ResNet50V2(
			include_top=False, weights="imagenet", pooling="avg"
		)

		# set the trainability of the base encoder.
		for layer in resnet_v2.layers:
			layer.trainable = trainable

		# Receive the images as inputs.
		image_1 = keras.Input(shape=(128, 128, 3), name="image_1")
		image_2 = keras.Input(shape=(128, 128, 3), name="image_2")

		# Preprocess the input image.
		preprossessed_1 = keras.applications.resnet_v2.preprocess_input(image_1)
		preprossessed_2 = keras.applications.resnet_v2.preprocess_input(image_2)

		# Generate the embeddings for the images using the resnet_v2
		# model. Concatenate them.
		embeddings_1 = resnet_v2(preprossessed_1)
		embeddings_2 = resnet_v2(preprossessed_2)
		embeddings = keras.layers.Concatenate()([embeddings_1, embeddings_2])

		# Project the embeddings produced by the model.
		outputs = project_embeddings(
			embeddings, num_projection_layers, projection_dims, dropout_rate
		)

		# Create the vision encoder model.
		return keras.Model([image_1, image_2], outputs, name="vision_encoder")

	# Text encoder utilities
	def create_text_encoder(
			num_projection_layers, projection_dims, dropout_rate,
			trainable=False
		):
		# Load the pre-trained BERT model to be used as the base
		# encoder.
		bert = hub.KerasLayer(bert_model_path, name="bert")

		# Set the trainability of the base encoder.
		bert.trainable = trainable

		# Receive the text as inputs.
		bert_input_features = ["input_type_ids", "input_mask", "input_word_ids"]
		inputs = {
			feature: keras.Input(shape=(128,), dtype=tf.int32, name=feature)
			for feature in bert_input_features
		}

		# Generate embeddings for the preprocessed text using the BERT
		# model.
		embeddings = bert(inputs)["pooled_output"]

		# Project the embeddings produced by the model.
		outputs = project_embeddings(
			embeddings, num_projection_layers, projection_dims, dropout_rate
		)

		# Create the text encoder model.
		return keras.Model(inputs, outputs, name="text_encoder")

	# Multimodal model utilities
	def create_multimodal_model(
			num_projection_layers=1, projection_dims=256, dropout_rate=0.1,
			vision_trainable=False, text_trainable=False,
		):
		# Receive the images as inputs.
		image_1 = keras.Input(shape=(128, 128, 3), name="image_1")
		image_2 = keras.Input(shape=(128, 128, 3), name="image_2")

		# Receive the text as inputs.
		bert_input_features = ["input_type_ids", "input_mask", "input_word_ids"]
		text_inputs = {
			feature: keras.Input(shape=(128,), dtype=tf.int32, name=feature)
			for feature in bert_input_features
		}

		# Create the encoders.
		vision_encoder = create_vision_encoder(
			num_projection_layers, projection_dims, dropout_rate,
			vision_trainable
		)
		text_encoder = create_text_encoder(
			num_projection_layers, projection_dims, dropout_rate,
			text_trainable
		)

		# Fetch the embedding projections.
		vision_projections = vision_encoder([image_1, image_2])
		text_projections = text_encoder(text_inputs)

		# Concatenate the projections and pass through the
		# classification layer.
		concatenated = keras.layers.Concatenate()([vision_projections, text_projections])
		outputs = keras.layers.Dense(3, activation="softmax")(concatenated)
		return keras.Model([image_1, image_2, text_inputs], outputs)

	multimodal_model = create_multimodal_model()
	'''
	keras.utils.plot_model(multimodal_model, show_shapes=True)
	'''

	# Can inspect the structure of the individual encoders as well by
	# setting the expand_nested argument of plot_model() to true. You
	# are encouraged to play with different hyperparameters involved in
	# building this model and observe how the final performance is
	# affected.

	# Compile and train the model
	multimodal_model.compile(
		optimizer="adam", loss="sparse_categorical_crossentropy",
		metrics=["accuracy"]
	)
	history = multimodal_model.fit(
		train_ds, validation_data=validation_ds, epochs=10
	)

	# Evaluate the model
	_, acc = multimodal_model.evaluate(test_ds)
	print(f"Accuracy on the test set: {round(acc * 100, 2)}%.")

	# Additional notes regarding training
	# Incorperateing regularization:
	# The training logs suggest that the model is starting to overfit
	# and may have benefitted from regularization. Dropout (Srivastava
	# et al.) is a simple yet powerful regularization technique that
	# can be used in the model. But how should it be applied here?
	# Could always introduce Dropout (keras.layers.Dropout) in between
	# different layers of te model. But here is another recipe. The
	# model expects inputs from two different data modalities. What if
	# either of the modalities is not present during inference? To
	# account for this, can introduce Dropout to the individual
	# projections just before they get concatenated:
	# vision_projections = keras.layers.Dropout(rate)(vision_projections)
	# text_projections = keras.layers.Dropout(rate)(text_projections)
	# concatenated = keras.layers.Concatenate()([vision_projections, text_projections])
	# Attending to what matters:
	# Do all parts of the images correspond equally to their textual
	# counterparts? It's likely not the case. To make the model only
	# focus on the most important bits of the images that relate well
	# to their corresponding textual parts, use "cross-attention":
	# Embeddings.
	# vision_projections = vision_encoder([image_1, image_2])
	# text_projections = text_encoder(text_inputs)
	# Cross-attention (Luong-style).
	# query_value_attention_seq = keras.layers.Attention(
	# 	use_scale=True, dropout=0.2
	# )([vision_projections, text_projections])
	# Concatenate.
	# concatenated = keras.layers.Concatenate()([vision_projections, text_projections])
	# contextual = keras.layers.Concatenate()([concatenated, query_value_attention_seq])
	# To see this in action, refer to this notebook.
	# Handling class imbalance:
	# The dataset suffers from class imbalance. Investigating the
	# confusion matrix of the above model reveals that it performs
	# poorly on the minority classes. If we had used a weighted loss
	# then the training would have been more guided. You can check out
	# this notebook that takes class-imbalance into account during
	# model training.
	# Using only text inputs:
	# Also, what if we only incorperated text inputs for the entailment
	# task? Because of the nature of the text inputs encountered on
	# social media platforms, text inputs alone would have hurt the
	# final perfomance. Under a similar training setup, by only using
	# text inputs we get to 67.14% top-1 accuracy on the same test set.
	# Refer to this notebook for details.

	# Final remarks
	# -> The architecture used in this example is too large for the
	#	number of data points available for training. It's going to
	#	benefit from more data.
	# -> The example used a smaller variant of the original BERT model.
	#	Chances are high that with a larger variant, this performance
	#	will be improved. Tensorflow Hub provides a number of different
	#	BERT models that can be experimented with.
	# -> The example kept the pre-trained models frozen. Fine-tuning
	#	them on the multimodal entailment task would have resulted in
	#	better performance.
	# -> This example build a simple baseline model for the multimodal
	#	entailment task. There are various approaches that have been
	#	proposed to tackle the entailment problem. This presentation
	#	deck from the Recognizing Multimodal Entailment tutorial
	#	provides a comprehensive overview.

	# Exit the program.
	exit(0)

if __name__ == '__main__':
	main()


import logging
import re
import time

logger = logging.getLogger(__name__)

class GpioDevice:

    def __init__(self):
        import RPi.GPIO as GPIO
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)

    def setup(self, pin):
        import RPi.GPIO as GPIO
        GPIO.setup(pin, GPIO.OUT)
        self.set_pin(pin, False)

    def cleanup(self):
        import RPi.GPIO as GPIO
        GPIO.cleanup()

    def set_pin(self, pin, value):
        import RPi.GPIO as GPIO
        assert isinstance(pin, int)
        assert isinstance(value, bool)
        GPIO.output(pin, GPIO.LOW if value else GPIO.HIGH)

    def get_pin(self, pin):
        import RPi.GPIO as GPIO
        return GPIO.input(pin) == GPIO.LOW

class TempSensorDevice:

    CRE = re.compile(r" t=(-?\d+)$")

    def __init__(self, name, address, offset=0.0):
        self.__address = address
        self.__path = "/sys/bus/w1/devices/%s/w1_slave" % address
        self.__offset = offset

    def __read_temp_raw(self):
        with open(self.__path, "r") as f:
            return [line.strip() for line in f.readlines()]

    def value(self):
        # Retry up to 3 times
        try:
            for _ in range(3):
                raw = self.__read_temp_raw()
                if len(raw) == 2:
                    crc, data = raw
                    if crc.endswith("YES"):
                        logger.debug("Temp sensor raw data: %s" % str(data))
                        # CRC valid, read the data
                        match = TempSensorDevice.CRE.search(data)
                        temperature = int(match.group(1)) / 1000. + self.__offset if match else None
                        # Range check, sometimes bad values pass the CRC check
                        if 5 < temperature < 100:
                            return temperature
                        else:
                            logger.debug("Temp outside range: %f" % temperature)
                    else:
                        logger.debug("Bad CRC: %s" % str(raw))
                time.sleep(0.1)
        except OSError:
            logger.exception("Unable to read temperature (%s)" % self.name)
        return None


import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()

xlist= [1,2,3]
ylist = [4,5,6,7]

X,Y = np.meshgrid(xlist, ylist)

print(xlist)
print(ylist)
print(X)
print(Y)
#ax.scatter(X, Y, color="green")

Z = (Y)
cp = ax.contour(X, Y, Z)
plt.colorbar(cp)

plt.clf()
###

import numpy as np

fig = plt.figure(figsize=(6,5))
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax = fig.add_axes([left, bottom, width, height])

start, stop, n_values = 0, 3, 5

x_vals = np.linspace(start, stop, n_values)
y_vals = np.linspace(start, stop, n_values)
X, Y = np.meshgrid(x_vals, y_vals)

Z = X*Y

cp = plt.contourf(X, Y, Z)
plt.colorbar(cp)

ax.set_title('Contour Plot')
ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')
plt.show()

plt.clf()

name = 'GLUT5_in'
ec = np.loadtxt('../gate_dists/extracellular/%s.EC.xvg' %name)[:,1]
ic = np.loadtxt('../gate_dists/intracellular/%s.IC.xvg' %name)[:,1]
time = np.loadtxt('../gate_dists/extracellular/%s.EC.xvg' %name)[:,0]

x,y = np.meshgrid(ec,ic)
z = np.zeros(np.shape(x))
z[0][0] = 0
z[1][1] = 1000
z[2][2] = 2000

plt.contourf(x,y,z)
plt.show()
plt.clf()

################
ec = [1, 1, 2, 2, 3, 4]
ic = [5, 5, 5, 6, 6, 6]
time =[0, 1, 2, 3, 4, 5]

x,y = np.meshgrid(ec,ic)
z = np.zeros(np.shape(x))
for n,val in enumerate(time):
    z[n][n] = val


# coding:utf-8
import numpy as np
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt

class LR(object):

    def __init__(self, D):
        self.w = np.random.randn(D, 1)
        self.b = 0

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def predict(self, x):
        return self.w.T.dot(x) + self.b

    def fit(self, x, y, it=10000, a=0.1):
        # N,D   x.shape
        # 1,N   y.shape
        # 1,D   w.shape
        pass
        N, D = x.shape

        for i in range(it):
            h = self.sigmoid(self.w.T.dot(x) + self.b)
            # print(h.shape) (1, 250)
            dw = np.sum((h - y) * x, axis=1) / N * a
            # print(dw.shape)  (2,)
            db = np.sum(h - y, keepdims=False) / N * a
            self.w -= dw.reshape(2, 1)
            self.b -= db

    def predict(self, x):
        return self.w.T.dot(x) + self.b

if __name__ == '__main__':
    x, y = make_moons(250, noise=0.25)

    # print(x.shape)  # (250, 2)
    # print(y.shape)  # (250,)

    col = {0: 'r', 1: 'b'}
    lr = LR(2)
    lr.fit(x.T, y.reshape(1, -1))

    #show result
    plt.figure()
    for i in range(x.shape[0]):
        col = {0: 'r', 1: 'b'}
        plt.plot(x[i, 0], x[i, 1], col[y[i]] + 'o')
    plt.ylim([-1.5, 1.5])

    xpts = np.linspace(-1.5, 2.5)
    ypts = (lr.w[0] * xpts) / (-lr.w[1])

    plt.plot(xpts, ypts, 'g-', lw=2)
    plt.show()


def f(m, n):
    min = 0
    if(m >= n):
        min = n
    else:
        min = m
    cntA = cntB = sum = 0
    for i in range(1, min + 1):
        if(m % i == 0 and n % i == 0):
            cntA += 1
            sum += 1
    for i in range(1 , m + 1):
        if(m % i == 0 and n % i == 1):
            cntB += 1
    print("a)", cntA)
    print("a)", cntB)
    print("c)", sum)
m = int(input("Nhap m: "))
n = int(input("Nhap n: "))
f(m, n)