import asyncio
import logging

import aiorun
import clickhouse_connect
from geoip2.database import Reader
from clickhouse_connect.driver import exceptions as clickhouse_exceptions
from motor.core import Database
from motor.motor_asyncio import AsyncIOMotorClient
from nanoid import generate

from app.config import configuration
from app.consumers import Consumer
from app.consumers.handlers import HandleAnalytics, HandleLastVisitTime, HandleMetrics
from app.consumers.middleware import (
    ExceptionMiddleware,
    LoggingMiddleware,
    OrJSONMiddleware,
    TimingMiddleware,
)

async def main():
    db_client = AsyncIOMotorClient(configuration.mongo_dsn)
    clickhouse_client = clickhouse_connect.get_client(host="clickhouse", password="")
    ip_reader = Reader("./GeoLite2-Country.mmdb")
    try:
        clickhouse_client.command(
            "CREATE TABLE analytics (host String, path String, tiny_url String, timestamp DateTime, ip_address String, location String, device String, operating_system String, browser String, is_mobile Bool, is_bot Bool) ENGINE = MergeTree() PRIMARY KEY (tiny_url, timestamp, ip_address)"
        )
    except clickhouse_exceptions.DatabaseError:
        pass
    database: Database = db_client["test"]

    consumer_id = f"invisible-{generate(size=8)}"
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(consumer_id)

    consumer = Consumer(
        logger=logger,
        bootstrap_servers=f"{configuration.kafka_dsn.host}:{configuration.kafka_dsn.port}",
        client_id=consumer_id,
        services={
            "tinyurl_collection": database["tinyurl"],
            "host_metrics_collection": database["host_metrics"],
            "path_metrics_collection": database["path_metrics"],
            "clickhouse_client": clickhouse_client,
            "ip_reader": ip_reader,
        },
    )

    consumer.declare_middleware(OrJSONMiddleware())
    consumer.declare_middleware(ExceptionMiddleware(logger))
    consumer.declare_middleware(TimingMiddleware(logger))
    consumer.declare_middleware(LoggingMiddleware(logger))

    consumer.declare_handler(HandleLastVisitTime(), "URL.read")
    consumer.declare_handler(HandleMetrics(), ("URL.read", "URL.create"))
    consumer.declare_handler(HandleAnalytics(), ("URL.read"))

    await consumer.run()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    aiorun.run(main(), loop=loop)


import math
from project_utils.utilities import *
import pickle
from nltk import pos_tag

class Environment:

    def __init__(self, rewards, reward_func):

        self.actions = get_actions()
        self.states = get_actions()
        self.reward = rewards
        self.reward_func = reward_func
        self.prev_state = np.random.choice(list(self.states.keys()))
        self.prev_state_id = self.states[self.prev_state]
        self.terminal_states = [self.states['.']]
        self.t = 0

    def getNextState(self, action):
        self.t += 1
        self.next_state = action
        if self.reward_func == 2:
            bigram = [self.prev_state, self.next_state]
            tagged_bigram = pos_tag(bigram)
            reward = self.reward[tagged_bigram[0][1]][tagged_bigram[1][1]]
        else:
            reward = self.reward[self.prev_state][self.next_state]
        #reward = self.reward
        self.prev_state = self.next_state
        self.next_state_id = self.states[self.next_state]
        if self.next_state_id in self.terminal_states:
            run = 'terminate'
        elif self.t == 10:
            run = 'terminate'
        else:
            run = 'run'
        return run, reward


""" Play with CountVectorizer
"""
from sklearn.feature_extraction.text import CountVectorizer
from collections import Counter

def build_count_vectorizer():
    vectorizer = CountVectorizer()

    corpus = [
        'this is an apple',
        'apple is sweet and orange is sour.',
        'banana is yellow and apple is red',
        'grape is both sweet and sour',
    ]

    vectorizer.fit(corpus)

    word_list = vectorizer.get_feature_names_out()
    print(word_list)
    print(vectorizer.vocabulary_)

    # Try to encode using this vectorizer
    sample = "I love banana, orange and banana!"
    sample_vec = vectorizer.transform([sample]).toarray()
    print(sample_vec)
    for idx, val in enumerate(sample_vec[0]):
        if val >= 1:
            print(word_list[idx], val)
    return vectorizer

def fit_with_new_data():
    """ Fit with new data?
    """
    vectorizer = build_count_vectorizer()

    print("-"*10, "fit_with_new_data", "-"*10)
    # Fit some new data
    old_vocab = vectorizer.vocabulary_
    vectorizer = CountVectorizer(vocabulary=old_vocab)

    corpus_2 = [
        'this is an chicken',
        'chickens have two legs and pigs have four.',
    ]
    vectorizer.fit(corpus_2)
    word_list = vectorizer.get_feature_names_out()
    print(word_list)
    print(vectorizer.vocabulary_)

    sample = "I love banana, orange and banana, and I love chicken!"
    sample_vec = vectorizer.transform([sample]).toarray()

    print(sample_vec)
    for idx, val in enumerate(sample_vec[0]):
        if val >= 1:
            print(word_list[idx], val)

def fit_with_new_data_v2():
    """ Fit with new data?
    """
    vectorizer = build_count_vectorizer()
    old_word_list = vectorizer.get_feature_names_out().tolist()

    print("-"*10, "fit_with_new_data", "-"*10)
    corpus_2 = [
        'this is an chicken',
        'chickens have two legs and pigs have four.',
    ]
    vectorizer.fit(corpus_2)
    new_word_list = vectorizer.get_feature_names_out().tolist()

    final_word_list = old_word_list + new_word_list
    word_counter = Counter(final_word_list)
    final_vocab = dict()
    for idx, val in enumerate(list(word_counter)):
        final_vocab[val] = idx

    vectorizer = CountVectorizer(vocabulary=final_vocab)
    word_list = vectorizer.get_feature_names_out()
    sample = "I love banana, orange and banana, and I love chicken!"
    sample_vec = vectorizer.transform([sample]).toarray()
    print(sample_vec)
    for idx, val in enumerate(sample_vec[0]):
        if val >= 1:
            print(word_list[idx], val)

if __name__ == "__main__":
    fit_with_new_data_v2()


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

import re
import new
import sys
import Queue as queue
import types
import weakref
import threading

def _dummy(ticket):
    """Dummy guard condition function.

    It always matches.

    @param ticket: passed values from expositions.
    @type  ticket: Ticket object.
    @return: whether follower should be called or not.
    @rtype : boolean.
    """
    return True

class Identifier(object):
    """Event naming identifier.

    identifier is built by string.
    It supports wildcard.

    "sample:*" => match any action in "sample"
    "*:entry" => match any "entry" messsge
    "sample" => match with "sample:entry" and "sample:exit" message

    @future: including URI(for external followable node)
    """
    __slots__ = ("name", "action", "functions")
    _both_name_action = re.compile(r"(.*):(.*)")
    _every_action = re.compile(r"(.*):\*")
    _every_name = re.compile(r"\*:(.*)")

    def __init__(self, key_or_identifier, action=None, guard_condition=_dummy):
        self.functions = [None, None]
        if action is not None:
            self.name = key_or_identifier.name
            self.action = set([action])
            self.functions[0] = self.match_all
            return
        key = key_or_identifier
        match = self._every_action.match(key)
        if match:
            self.name = match.group(1)
            self.action = None
            self.functions[0] = self.match_name_only
        else:
            match = self._every_name.match(key)
            if match:
                self.name = None
                self.action = set([match.group(1)])
                self.functions[0] = self.match_action_only
            else:
                match = self._both_name_action.match(key)
                if match:
                    self.name = match.group(1)
                    if match.group(2) == "call":
                        self.action = set(["entry", "exit"])
                    else:
                        self.action = set([match.group(2)])
                    self.functions[0] = self.match_all
                else:
                    self.name = key
                    self.action = set(["entry", "exit"])
                    self.functions[0] = self.match_all
        self.functions[1] = guard_condition

    def __str__(self):
        name = "*" if self.name is None else self.name
        action = "*" if self.action is None else ",".join(sorted(self.action))
        return "<tdfw.Identifier object at %d: id=%s:%s>" % (
            id(self), name, action)

    @staticmethod
    def match_all(lhs, rhs):
        return (lhs.name == rhs.name) and (lhs.action & rhs.action)

    @staticmethod
    def match_name_only(lhs, rhs):
        return lhs.name == rhs.name

    @staticmethod
    def match_action_only(lhs, rhs):
        return lhs.action & rhs.action

    def is_match(self, expose_identifier, ticket=None):
        if self.functions[0](self, expose_identifier):
            return self.functions[1](ticket)
        return False

    def available_for_exposition(self):
        return self.name and self.action

class cond(object):
    def __init__(self, identifier, guard_condition=_dummy):
        self.targets = [Identifier(identifier, guard_condition=guard_condition)]

    def __and__(self, rhs):
        newtarget = target(None, None)
        newtarget.targets = self.targets + rhs.targets
        return newtarget

def _get_attributes(instance, typeobj):
    """Helper generator to implement TDFW.

    It returns match objects.
    """
    for key in dir(instance):
        if key.startswith("__"):
            continue
        value = getattr(instance, key)
        if type(value) == typeobj:
            yield value

class _weakmethod_ref(object):
    """This method wrapper comes from Python Cookbook 2nd 6.10"""
    __slots__ = ("_obj", "_func", "_clas")
    def __init__(self, fn):
        try:
            o, f, c = fn.im_self, fn.im_func, fn.im_class
        except AttributeError:
            self._obj = None
            self._func = fn
            self._clas = None
        else:
            if o is None:
                self._obj = None
            else:
                self._obj = weakref.ref(o)
            self._func = f
            self._clas = c

    def __call__(self):
        if self._obj is None:
            return self._func
        elif self._obj() is None:
            return None
        return new.instancemethod(self._func, self._obj(), self._clas)

class _dummy_method_ref(object):
    __slots__ = ("_func",)
    def __init__(self, fn):
        self._func = fn

    def __call__(self):
        return self._func

class InvalidExpositionName(Exception): pass

class TDFramework(object):
    _followers = {}
    _expositions = set()

    def __init__(self):
        pass

    def get_valid_followers(self):
        for name, followers in self._followers.items():
            for id_obj, function_wrapper, condition in followers:
                function = function_wrapper()
                if function is not None:
                    yield id_obj, function

    def get_valid_expositions(self):
        for id_obj, function_wrapper in self._expositions:
            function = function_wrapper()
            if function is not None:
                yield id_obj, function

    def regist_exposition(self, id_obj, function):
        self._expositions.add((id_obj, function))

    def regist_follower(self, id_obj, function):
        followers = self._followers.setdefault(id_obj.name, [])
        followers.append((id_obj, function))

    def twitter(self, id_obj, args, kwargs, counter=100):
        ticket = Ticket(id_obj, args, kwargs, counter)
        for follower in self._followers.get(id_obj.name, []):
            following_id, function = follower
            if not following_id.is_match(id_obj, ticket):
                continue
            if function() is None:
                continue # あとで削除
            if ThreadPool.empty():
                function()(ticket)
            else:
                ThreadPool.request_work(function(), ticket)

class ThreadPool(object):
    _qin = queue.Queue()
    _qerr = queue.Queue()
    _pool = []

    @classmethod
    def _report_error(cls):
        cls._qerr.put(sys.exc_info()[:2])

    @staticmethod
    def _get_all_from_queue(Q):
        try:
            while True:
                yield Q.get_nowait()
        except queue.Empty:
            raise StopIterator

    @classmethod
    def do_work_from_queue(cls):
        while True:
            command, target_method, ticket = cls._qin.get()
            if command == "stop":
                break
            try:
                if command == "process":
                    target_method(ticket)
                else:
                    raise ValueError("Unknown command %r" % command)
            except:
                cls._report_error()

    @classmethod
    def make_thread_pool(cls, number):
        if number < 0:
            raise ValueError("'number' should be bigger than 0.")
        number -= len(cls._pool)
        if number > 0:
            for i in range(number):
                new_thread = threading.Thread(target=cls.do_work_from_queue)
                new_thread.setDaemon(True)
                cls._pool.append(new_thread)
                new_thread.start()
        elif number < 0:
            number = abs(number)
            for i in range(number):
                cls.request_work(None, None, "stop")

    @classmethod
    def empty(cls):
        return len(cls._pool) == 0

    @classmethod
    def clear_thread_pool(cls):
        alive_list = []
        for thread in cls._pool:
            if thread.isAlive():
                alive_list.append(thread)
        cls._pool = alive_list

    @classmethod
    def request_work(cls, target_function, ticket, command="process"):
        cls._qin.put((command, target_function, ticket))

    @classmethod
    def get_all_errors(cls):
        return cls._get_all_from_queue(cls._qerr)

    @classmethod
    def stop_thread_pool(cls):
        for i in range(len(cls._pool)):
            cls.request_work(None, None, "stop")
        for existing_thread in cls._pool:
            existing_thread.join()
        del cls._pool[:]

class OpenMethodAttribute(object):
    """This class is attached to exposition/following functions/methods.

    After initialization, this shows any information to draw connections.

    @sa exposition
    @sa following
    @sa following_method
    """
    __slots__ = ("expositions", "followers", "is_init")
    attribute_name = "__exposition_information"
    def __init__(self):
        self.expositions = []
        self.followers = []
        self.is_init = False

    @classmethod
    def add_follower(cls, id_obj, function):
        attribute = cls._set_open_method_attribute(function)
        attribute.followers.append(id_obj)

    @classmethod
    def add_exposition(cls, id_obj, function):
        attribute = cls._set_open_method_attribute(function)
        attribute.expositions.append(id_obj)

    @classmethod
    def _set_open_method_attribute(cls, function):
        attribute = getattr(function, cls.attribute_name, None)
        if attribute is None:
            attribute = cls()
            setattr(function, cls.attribute_name, attribute)
        return attribute

def expose(identifier):
    id_obj = Identifier(identifier)
    def _(f):
        if isinstance(f, types.FunctionType):
            if len(set(["entry", "exit"]) & id_obj.action) == 2:
                _tdfw.regist_exposition(id_obj, _dummy_method_ref(f))
                def __(*args, **kwargs):
                    _tdfw.twitter(Identifier(id_obj, "entry"), args, kwargs)
                    f(*args, **kwargs)
                    _tdfw.twitter(Identifier(id_obj, "exit"), args, kwargs)
                return __
            elif "exit" in id_obj.action:
                _tdfw.regist_exposition(id_obj, _dummy_method_ref(f))
                def __(*args, **kwargs):
                    f(*args, **kwargs)
                    _tdfw.twitter(Identifier(id_obj, "exit"), args, kwargs)
                return __
            elif "entry" in id_obj.action:
                _tdfw.regist_exposition(id_obj, _dummy_method_ref(f))
                def __(*args, **kwargs):
                    _tdfw.twitter(Identifier(id_obj, "entry"), args, kwargs)
                    f(*args, **kwargs)
                return __
            else:
                _tdfw.regist_exposition(id_obj, _dummy_method_ref(f))
            return f
        else:
            if id_obj.action.issubset(set(["entry", "exit"])):
                OpenMethodAttribute.add_exposition(id_obj, f)
                def __(*args, **kwargs):
                    _tdfw.twitter(Identifier(id_obj, "entry"), args, kwargs)
                    f(*args, **kwargs)
                    _tdfw.twitter(Identifier(id_obj, "exit"), args, kwargs)
                return __
            elif "exit" in id_obj.action:
                OpenMethodAttribute.add_exposition(id_obj, f)
                def __(*args, **kwargs):
                    f(*args, **kwargs)
                    _tdfw.twitter(Identifier(id_obj, "exit"), args, kwargs)
                return __
            elif "entry" in id_obj.action:
                OpenMethodAttribute.add_exposition(id_obj, f)
                def __(*args, **kwargs):
                    _tdfw.twitter(Identifier(id_obj, "entry"), args, kwargs)
                    f(*args, **kwargs)
                return __
            else:
                OpenMethodAttribute.add_exposition(id_obj, f)
            return f
    return _

expose_method = expose

def following(identifier, guard_condition=_dummy):
    id_obj = Identifier(identifier, guard_condition=guard_condition)
    def _(f):
        _tdfw.regist_follower(id_obj, _dummy_method_ref(f))
        return f
    return _

def following_method(identifier, guard_condition=_dummy):
    """This decorator is used for lazy instance method registration.

    @sa Follower
    @sa following
    """
    id_obj = Identifier(identifier, guard_condition=guard_condition)
    def _(f):
        OpenMethodAttribute.add_follower(id_obj, f)
        return f
    return _

class Follower(type):
    """Metaclass for definition of follower instance methods.

    use like this:

      class Logger(object):
          __metaclass__=Follower
          @following_method("function", "call")
          def log_function_call(self, ticket):
              ...

          @classmethod
          @following_classmethod("error", "raised")
          def show_error(cls, ticket):
              ...

          @staticmethod
          @following("thread", "created")
          def log_thread(ticket):
              ...
    """
    def __new__(cls, name, bases, dict):
        """Create exposition point for classmethod."""
        newtype = type.__new__(cls, name, bases, dict)
        for method in _get_attributes(newtype, types.MethodType):
            attribute = getattr(method, OpenMethodAttribute.attribute_name, None)
            if attribute is None:
                continue
            if method.im_self is None:
                continue
            for id_obj in attribute.followers:
                _tdfw.regist_follower(id_obj, _weakmethod_ref(method))
            for id_obj in attribute.expositions:
                _tdfw.regist_exposition(id_obj, _weakmethod_ref(method))
            attribute.is_init = True
        return newtype

    def __call__(cls, *args):
        """Create exposition point for instancemethod."""
        instance = type.__call__(cls, *args)
        for method in _get_attributes(instance, types.MethodType):
            attribute = getattr(method, OpenMethodAttribute.attribute_name, None)
            if attribute is None:
                continue
            if attribute.is_init:
                continue
            for id_obj in attribute.followers:
                _tdfw.regist_follower(id_obj, _weakmethod_ref(method))
            for id_obj in attribute.expositions:
                _tdfw.regist_exposition(id_obj, _weakmethod_ref(method))
        return instance

class Ticket(object):
    def __init__(self, id_obj, args, kwargs, counter):
        self._id_obj = id_obj
        self._args = args
        self._kwargs = kwargs
        self._counter = counter
        self.__dict__.update(kwargs)
        self.__dict__["args"] = args

    @property
    def name(self):
        return self._id_obj._name

    @property
    def action(self):
        return self._id_obj._action

    @property
    def args(self):
        return self._args

    @property
    def kwargs(self):
        return self._kwargs

    def twitter(self, id_obj, **kwargs):
        _tdfw.twitter(id_obj, kwargs, self._counter-1)

    def apply(self, func):
        """Utility method to enease method call deligation.

        You can use like this:
          @exposition("result", "show")
          def show_result(score):
              print("my score:", score)
              twitter("result", "show", username="shibu", score=score) # get 2 kwparams

          def log(username, score): # same params with exposition point.
              ...

          @following("result", "show")
          def log_score_exposition(ticket):
              ticket.apply(log) # use this!

        """
        return func(**self.kwargs)

_tdfw = TDFramework()

def set_multiplicity(number):
    if number != 0:
        ThreadPool.make_thread_pool(number)
    else:
        ThreadPool.clear_thread_pool()

def show_expositions():
    methods = []
    for id_obj, function_wrapper in _tdfw.get_valid_expositions():
        for action in id_obj.action:
            methods.append("%s:%s" % (id_obj.name, action))
    return sorted(set(methods))

def show_followers():
    methods = []
    for id_obj, function_wrapper in _tdfw.get_valid_followers():
        for action in id_obj.action:
            methods.append("%s:%s" % (id_obj.name, action))
    return sorted(set(methods))

def show_network():
    network = {}
    nodes = []
    edges = []
    classobjs = set()

    nodetype = {"class":{"shape":"box3d", "bgcolor":"#C1E4FF",
                         "pencolor":"#358ACC"},
                "joint":{"shape":"none"}}

    for name, action, method in _tdfw.get_valid_expositions():
        key = (name, action)
        net = network.setdefault(key, {"follower":[], "exposition":[]})
        if isinstance(method, types.MethodType):
            classobjs.add(method.__self__.__class__)
            net["exposition"].append(id(method.__self__.__class__))
        else:
            net["exposition"].append(None)

    for name, action, method in _tdfw.get_valid_followers():
        key = (name, action)
        net = network.setdefault(key, {"follower":[], "exposition":[]})
        if isinstance(method, types.MethodType):
            classobjs.add(method.__self__.__class__)
            net["follower"].append(id(method.__self__.__class__))
        else:
            net["follower"].append(None)

    for classobj in classobjs:
        nodes.append(["class", id(classobj), classobj.__name__])

    for key in network:
        followers = network[key]["follower"]
        expositions = network[key]["exposition"]
        if len(followers) == 1 and len(expositions) == 1:
            edges.append([expositions[0], followers[0],
                          {"label": "%s:%s"%key}])
        else:
            nodes.append(["joint", id(classobj), "%s:%s"%key])
            for exposition in expositions:
                edges.append([exposition, id(classobj),{"label":""}])
            for follower in followers:
                edges.append([id(classobj), follower,{"label":""}])
    result = ["digraph {"]

    for typename, objid, label in nodes:
        params = ['label="%s"' % label]
        params += ['%s="%s"' % item for item in nodetype[typename].items()]
        result.append("  %s [%s];" % (objid, ", ".join(params)))
    for start, end, params in edges:
        param_str = ['%s="%s"' % item for item in params.items()]
        result.append("  %s -> %s [%s];" % (start, end, ", ".join(param_str)))
    result.append("}")
    return "\n".join(result)

def twitter(identifier, *args, **kwargs):
    _tdfw.twitter(Identifier(identifier), args, kwargs)

fire = twitter
notify = twitter


import experiment as e
import numpy as np
import os
import path
import random
import xml_cnn
import windower

def make(fo):
	print('making artifacts, cnn bad epoch, xml files per block')
	cnn_model_name = 'cnn_5X5_2048_1'

	for i in range(1,49):
		p = e.Participant(i,fid2ort = fo)
		p.add_all_sessions()
		for s in p.sessions:
			for b in s.blocks:
				if not os.path.isfile(path.eeg100hz + windower.make_name(b) +'.npy'):
					continue
				if b.start_marker_missing or b.end_marker_missing:
					d = load_100hz_numpy_block(windower.make_name(b))
					w = windower.Windower(b,nsamples= d.shape[1], sf = 100)
				w = windower.Windower(b,sf = 100)
				if not os.path.isfile(path.artifact_data_all_pp+ w.name + '_pred.npy'):
					print(path.artifact_data_all_pp +w.name + '_pred.npy', 'no prediction file present')
					continue
				a = xml_cnn.xml_cnn(w)
				a.make_bad_epoch()
				a.bad_epochs2xml()
				a.write_bad_epoch_xml()
				print(w.name)

def load_100hz_numpy_block(name):
	return np.load(path.eeg100hz + name + '.npy')


from parlai.core.worlds import ExecutableWorld
import json
import os
import copy
from random import choice, randint

BOUNDARIES = {
    'hellskitchen': [3, 3],
    'williamsburg': [2, 8],
    'uppereast':    [3, 3],
    'fidi':         [2, 3],
    'eastvillage':  [3, 4],
}

def is_action(msg, forward=False):
    if forward:
        return msg and (msg == 'ACTION:FORWARD' or msg == 'ACTION : FORWARD')
    return msg and msg.startswith('ACTION')

class Simulator():

    boundaries = None
    neighborhood = None
    agent_location = None
    target_location = None
    landmarks = None

    def __init__(self, opt):
        self.map = Map(opt['ttw_data'])
        self.feature_loader = GoldstandardFeatures(self.map)

    def _get_random_location(self):
        return [randint(self.boundaries[0], self.boundaries[2]),
                randint(self.boundaries[1], self.boundaries[3]),
                randint(0, 3)]

    def random_init(self):
        self.neighborhood = choice(list(BOUNDARIES.keys()))
        self.boundaries = [randint(0, BOUNDARIES[self.neighborhood][x])*2 for
                           x in range(2)]
        self.boundaries = self.boundaries + [x + 3 for x in self.boundaries]
        self.agent_location = self._get_random_location()
        self.target_location = self._get_random_location()

    def init_sim(self, neighborhood=None, boundaries=None, start_location=None,
                 target_location=None):

        if not neighborhood:
            self.random_init()
        else:
            self.boundaries = boundaries
            self.neighborhood = neighborhood
            self.agent_location = start_location
            self.target_location = target_location

        self.landmarks, self.target_location = self.map.get_landmarks(
                self.neighborhood,
                self.boundaries,
                self.target_location)

    def get_agent_location(self):
        return str((self.agent_location[0]-self.boundaries[0])*4 +
                   (self.agent_location[1]-self.boundaries[1]))

    def get_text_map(self):
        L = [y for x in zip(*self.landmarks) for y in x]
        txt = '\n'.join([(str(i) + ':' + ' and '.join(x)) for i, x in enumerate(L)])
        txt += '\n' + str(self.target_location[0]*4 + self.target_location[1]) + \
               ':Target'+'\n'
        return txt

    def get_current_view(self):
        return "\n".join(['see:'+x for x in self.feature_loader.get(
          self.neighborhood, self.agent_location)])

    def add_view_to_text(self, obs, action=None):
        action = action or obs.get('text')
        if action and is_action(action, forward=True):
            obs['text'] = obs.get('text', '') + self.get_current_view() + '\n'

    def execute_and_write(self, obs, action):
        self.execute(action)
        self.add_view_to_text(obs, action)

    def execute(self, text):
        """move the tourist"""
        if not is_action(text):
            return

        self.agent_location = self.map.step_aware(
                text,
                self.agent_location,
                self.boundaries)

class SimulateWorld(ExecutableWorld):

    boundaries = None
    neighborhood = None
    agent_location = None
    target_location = None
    guide = None
    tourist = None

    def __init__(self, opt, agents=None, shared=None):
        super().__init__(opt, agents, shared)

        if agents:
            self.tourist = agents[0]
            self.guide = agents[1]

        if shared:
            self.sim = shared['sim']
        else:
            self.sim = Simulator(opt)
            self.sim.init_sim()

        if agents:
            self.send_map(self.guide)
            self.send_view(self.tourist)

    def send_map(self, agent):
        agent.observe({'text': self.sim.get_text_map()})

    def send_view(self, agent):
        agent.observe({'text': self.sim.get_current_view()})

    def share(self):
        shared = super().share()
        shared['sim'] = self.sim
        return shared

    def execute(self, agent, act):
        self.sim.execute(act['text'])

    def episode_done(self):
        return self.guide_act.startswith('EVALUATE')

    def parley(self):
        act = self.tourist.act()
        while is_action(act['text']):
            self.execute(self.tourist, act)
            obs = self.observe(self.tourist, act)
            if obs is not None:
                self.tourist.observe(obs)
            act = self.tourist.act()
        self.guide.observe(act)
        self.guide_act = self.guide.act()
        obs = self.observe(self.guide, act)

        if obs is not None:
            self.tourist.observe(obs)
        self.update_counters()

    def observe(self, agent, act):
        self.sim.add_view_to_text(act)
        return act

class Map(object):
    """Map with landmarks"""

    def __init__(self, data_dir, include_empty_corners=True):
        super().__init__()
        self.coord_to_landmarks = dict()
        self.include_empty_corners = include_empty_corners
        self.data_dir = data_dir
        self.landmarks = dict()

        for neighborhood in BOUNDARIES.keys():
            self.coord_to_landmarks[neighborhood] = \
              [[[] for _ in range(BOUNDARIES[neighborhood][1] * 2 + 4)]
               for _ in range(BOUNDARIES[neighborhood][0] * 2 + 4)]
            self.landmarks[neighborhood] = json.load(
                open(os.path.join(data_dir, neighborhood, "map.json")))
            for landmark in self.landmarks[neighborhood]:
                coord = self.transform_map_coordinates(landmark)
                self.coord_to_landmarks[neighborhood][coord[0]][coord[1]].append(
                    landmark['type'])

    def transform_map_coordinates(self, landmark):
        x_offset = {"NW": 0, "SW": 0, "NE": 1, "SE": 1}
        y_offset = {"NW": 1, "SW": 0, "NE": 1, "SE": 0}

        coord = (landmark['x'] * 2 + x_offset[landmark['orientation']],
                 landmark['y'] * 2 + y_offset[landmark['orientation']])
        return coord

    def get(self, neighborhood, x, y):
        landmarks = self.coord_to_landmarks[neighborhood][x][y]
        if self.include_empty_corners and len(landmarks) == 0:
            return ['Empty']
        return landmarks

    def get_landmarks(self, neighborhood, boundaries, target_loc):
        landmarks = [[[] for _ in range(4)] for _ in range(4)]
        label_index = (target_loc[0] - boundaries[0], target_loc[1] - boundaries[1])
        for x in range(4):
            for y in range(4):
                landmarks[x][y] = self.get(
                    neighborhood, boundaries[0] + x, boundaries[1] + y)

        assert 0 <= label_index[0] < 4
        assert 0 <= label_index[1] < 4

        return landmarks, label_index

    def get_unprocessed_landmarks(self, neighborhood, boundaries):
        landmark_list = []
        for landmark in self.landmarks[neighborhood]:
            coord = self.transform_map_coordinates(landmark)
            if boundaries[0] <= coord[0] <= boundaries[2] \
               and boundaries[1] <= coord[1] <= boundaries[3]:
                landmark_list.append(landmark)
        return landmark_list

    def step_aware(self, action, loc, boundaries):
        orientations = ['N', 'E', 'S', 'W']
        steps = dict()
        steps['N'] = [0, 1]
        steps['E'] = [1, 0]
        steps['S'] = [0, -1]
        steps['W'] = [-1, 0]

        new_loc = copy.deepcopy(loc)
        if action == 'ACTION:TURNLEFT':
            # turn left
            new_loc[2] = (new_loc[2] - 1) % 4

        if action == 'ACTION:TURNRIGHT':
            # turn right
            new_loc[2] = (new_loc[2] + 1) % 4

        if action == 'ACTION:FORWARD':
            # move forward
            orientation = orientations[loc[2]]
            new_loc[0] = new_loc[0] + steps[orientation][0]
            new_loc[1] = new_loc[1] + steps[orientation][1]

            new_loc[0] = min(max(new_loc[0], boundaries[0]), boundaries[2])
            new_loc[1] = min(max(new_loc[1], boundaries[1]), boundaries[3])
        return new_loc

class GoldstandardFeatures:
    def __init__(self, map, orientation_aware=False):
        self.map = map
        self.allowed_orientations = {
            'NW': [3, 0], 'SW': [2, 3], 'NE': [0, 1], 'SE': [1, 2]}
        self.mod2orientation = {(0, 0): 'SW', (1, 0): 'SE', (0, 1): 'NW', (1, 1): 'NE'}
        self.orientation_aware = orientation_aware

    def get(self, neighborhood, loc):
        if self.orientation_aware:
            mod = (loc[0] % 2, loc[1] % 2)
            orientation = self.mod2orientation[mod]
            if loc[2] in self.allowed_orientations[orientation]:
                return self.map.get(neighborhood, loc[0], loc[1])
            else:
                return ['Empty']
        else:
            return self.map.get(neighborhood, loc[0], loc[1])


from setuptools import setup, find_packages
with open('pydepfile/version.py') as fp:
    version = fp.read().split('=')[1].strip()

setup(
    name='pydepfile',
    version=version,
    packages=find_packages(),
    entry_points={
        'console_scripts': [
            'pydepfile = pydepfile.main:main',
        ],
    },
)


from cato.runners.sync_comparison_settings import SyncComparisonSettings
from cato.runners.sync_reference_image_edits import SyncReferenceImageEdits
from cato.runners.sync_test_edits import SyncTestEdits
from cato_api_client.cato_api_client import CatoApiClient
from cato_common.domain.test_identifier import TestIdentifier
from tests.unittests.cato.runners.test_sync_comparison_settings import (
    create_comparison_settings_edit,
)
from tests.unittests.cato.runners.test_sync_reference_image_edits import (
    create_reference_image_edit,
)
from tests.utils import mock_safe

def test_sync_edits(config_fixture):
    reference_image_edit = create_reference_image_edit(
        TestIdentifier.from_string("some/test")
    )
    comparison_settings_edit = create_comparison_settings_edit(
        TestIdentifier.from_string("some/other_test")
    )
    mock_cato_api_client = mock_safe(CatoApiClient)
    mock_cato_api_client.get_test_edits_to_sync_for_run.return_value = [
        reference_image_edit,
        comparison_settings_edit,
    ]
    mock_update_comparison_settings = mock_safe(SyncComparisonSettings)
    mock_sync_reference_images = mock_safe(SyncReferenceImageEdits)
    sync_test_edits = SyncTestEdits(
        mock_cato_api_client,
        mock_update_comparison_settings,
        mock_sync_reference_images,
    )

    sync_test_edits.update(config_fixture.RUN_CONFIG, "the_path.json", 1)

    mock_update_comparison_settings.update.assert_called_with(
        config_fixture.RUN_CONFIG, "the_path.json", [comparison_settings_edit]
    )
    mock_sync_reference_images.update.assert_called_with(
        config_fixture.RUN_CONFIG, [reference_image_edit]
    )


#!/usr/bin/env python
__doc__ = '''Create images for SymChar font docs '''
__url__ = 'https://github.com/silnrsi/font-symchar'
__copyright__ = 'Copyright (c) 2023 SIL International (https://www.sil.org)'
__license__ = 'Released under the MIT License (https://opensource.org/licenses/MIT)'
__author__ = 'Victor Gaultney'

# Requires drawBot library
from drawBot import *
import csv

# Specs
fname = "SymCharK"
fsize = 36
height = 48
width = 96
incsv = "../source/glyph_data.csv"
outfolder = "../documentation/images/"

def uconvert(u):
    usv = u
    unicode = chr(int(usv.replace('U+', ''), 16))
    return unicode

def make_image(left, char, righta, rightb):
    ch = uconvert(char)
    fl = "" if left == "" else uconvert(left)
    fra = "" if righta == "" else uconvert(righta)
    frb = "" if rightb == "" else uconvert(rightb)
    filename = outfolder + "img_" + char[2:6] + ".png"
    #frame = fl + ch + fra + frb

    frame = FormattedString()
    frame.font(fname)
    frame.fontSize(fsize)
    frame.align("center")
    frame.append (fl, fill=(0, 0, 0, 0.3))
    frame.append (ch, fill=(0, 0, 0, 1))
    frame.append (fra, fill=(0, 0, 0, 0.3))
    frame.append (frb, fill=(0, 0, 0, 0.3))

    newDrawing()
    size(width, height)
    stroke(None)
    fill(1, 1, 1, 1)
    rect(0, 0, width, height)
    #font(fname, fsize)
    #fill(0, 0, 0, 1)
    textBox(frame, (0, -2, width, height))

    endDrawing()

    saveImage(filename)

def main():
    # read csv
    with open(incsv, mode='r') as csvfile:
        csv_reader = csv.DictReader(csvfile)
        line_count = 0
        for row in csv_reader:
            if row["usv"] != "":
                make_image(row["frame_l"], row["usv"], row["frame_r1"], row["frame_r2"])
            line_count += 1
        print(f'Created {line_count} images')

if __name__ == "__main__": main()


import random

class Student:
        def __init__(self,name):
            self.name = name
            self.gladness = 50
            self.progress = 0
            self.afk = 0
            self.alive=True

        def to_study(self):
            print('Time to study')
            self.progress += 0.12
            self.gladness -= 3
            self.afk = 2

        def to_afk(self):
            print('Go to work')
            self.progress += 1
            self.gladness += 3
            self.afk += 8

        def to_sleep(self):
             print('I will sleep')
             self.gladness += 3
             self.afk += 8

        def to_chill(self):
             print('Rest time')
             self.progress += 5
             self.gladness -= 0.1
             self.afk += 8

        def is_alive(self):
            if self.progress < -0.5:
              print('Cast out...')
              self.alive = False

            elif self.gladness <= 0:
              print('Depresion...')
              self.alive = False

            elif self.progress > 5:
                print('Passed externally...')
                self.alive=False

            elif self.afk > 8:
                print('not afk')

        def end_of_day(self):
                print(f'Gladness = {self.gladness}')
                print(f'Progress = {round(self.progress,2)}')
                print(f'afk = {self.afk,2}')

        def live(self,day):
                day = "Day" + str(day) + "of" + self.name + "life"
                print(f'{day:=^50}')
                print('1 - for study')
                print('2 - for sleep')
                print('3 - for chill')
                print('4 - for afk')
                live_cube=int(input('Enter your choice:'))
                if live_cube == 1:
                    print('You entered 1 variant (study)')
                    self.to_study()
                elif live_cube == 2:
                    print('You entered 2 variant (sleep)')
                    self.to_sleep()
                elif live_cube == 3:
                    print('You entered 3 variant (chill)')
                    self.to_chill()
                elif life_cube == 4:
                     print('You entered 4 variant (afk)')
                     self.to_afk()
                else:
                    print('You')
                self.end_of_day()
                self.is_alive()

nick=Student(name='Nick')
for day in range(365):
    if nick.alive==False:
        print('Student lose')
        break
    nick.live(day)


# ----------- FUNCTION TO READ THE FILE AND ADD THE NAMES AND IDs IN TO TUPLES

import cv2
import math
import time
from scipy.spatial import distance as dist

now_time = time.time()

face = cv2.CascadeClassifier('Haar/haarcascade_frontalface_alt.xml')
glass_cas = cv2.CascadeClassifier('Haar/haarcascade_eye_tree_eyeglasses.xml')

WHITE = [255, 255, 255]

def FileRead():
	# Open th text file in readmode
	Info = open("Names.txt", "r")
	# The tuple to store Names
	NAME = []
	# Read all the lines in the file and store them in two tuples
	while True:
		Line = Info.readline()
		if Line == '':
			break
		NAME.append(Line.split(",")[1].rstrip())
	# Return the two tuples
	return NAME
# Run the above Function to get the ID and Names Tuple

Names = FileRead()

# ------------------- FUNCTION TO FIND THE NAME  -----------------------------------------------------------

def ID2Name(ID, conf):

	if ID > 0:
		# Find the Name using the index of the ID
		NameString = "Name: " + Names[ID-1] + " Distance: " + (str(round(conf)))
	else:
		# Find the Name using the index of the ID
		NameString = " Face Not Recognised "

	return NameString

# ------------------- THIS FUNCTION READ THE FILE AND ADD THE NAME TO THE END OF THE FILE -----------------

def AddName():
	Name = input('Enter Your Name: ')
	Info = open("Names.txt", "r+")
	ID = ((sum(1 for line in Info))+1)
	Info.write(str(ID) + "," + Name + "\n")
	print("Name Stored in " + str(ID))
	Info.close()
	return ID

#     ------------------- DRAW THE BOX AROUND THE FACE, ID and CONFIDENCE  -------------------------------------

def DispID(x, y, w, h, NAME, Image):

	#  --------------------------------- THE POSITION OF THE ID BOX  ---------------------------------------------

	Name_y_pos = y - 10
	Name_X_pos = x + w/2 - (len(NAME)*7/2)

	if Name_X_pos < 0:
		Name_X_pos = 0
	elif Name_X_pos + 10 + (len(NAME) * 7) > Image.shape[1]:
		Name_X_pos = Name_X_pos - (Name_X_pos + 10 + (len(NAME) * 7) - (Image.shape[1]))
	if Name_y_pos < 0:
		Name_y_pos = y + h + 10

#  ------------------------------------    THE DRAWING OF THE BOX AND ID   --------------------------------------
	draw_box(Image, x, y, w, h)
	cv2.rectangle(Image, (int(Name_X_pos-10), int(Name_y_pos-25)), (int(Name_X_pos + 10) + (len(NAME) * 7), Name_y_pos-1), (0, 0, 0), -2)
	cv2.rectangle(Image, (int(Name_X_pos-10), int(Name_y_pos-25)), (int(Name_X_pos + 10) + (len(NAME) * 7), Name_y_pos-1), WHITE, 1)
	# Print the name of the ID
	cv2.putText(Image, NAME, (int(Name_X_pos), int(Name_y_pos - 10)), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE)

def draw_box(Image, x, y, w, h):
	cv2.line(Image, (x, y), (x + int(w/5), y), WHITE, 2)
	cv2.line(Image, (x+(int(w/5)*4), y), (x+w, y), WHITE, 2)
	cv2.line(Image, (x, y), (x, y+int(h/5)), WHITE, 2)
	cv2.line(Image, (x+w, y), (x+w, y+int(h/5)), WHITE, 2)
	cv2.line(Image, (x, (y+int(h/5*4))), (x, y+h), WHITE, 2)
	cv2.line(Image, (x, (y+h)), (x + int(w/5), y+h), WHITE, 2)
	cv2.line(Image, (x+(int(w/5)*4), y+h), (x + w, y + h), WHITE, 2)
	cv2.line(Image, (x+w, (y+int(h/5*4))), (x+w, y+h), WHITE, 2)

def eye_aspect_ratio(eye):
	# compute the euclidean distances between the two sets of
	# vertical eye landmarks (x, y)-coordinates
	A = dist.euclidean(eye[1], eye[5])
	B = dist.euclidean(eye[2], eye[4])
	# compute the euclidean distance between the horizontal
	# eye landmark (x, y)-coordinates
	C = dist.euclidean(eye[0], eye[3])
	# compute the eye aspect ratio
	ear = (A + B)/(2.0 * C)
	return ear

def DetectEyes(Image):
	Theta = 0
	rows, cols = Image.shape
	# This detects the eyes
	glass = glass_cas.detectMultiScale(Image)
	for (sx, sy, sw, sh) in glass:
		# The Image should have 2 eyes
		if glass.shape[0] == 2:
			if glass[1][0] > glass[0][0]:
				# Height difference between the glass
				DY = ((glass[1][1] + glass[1][3] / 2) - (glass[0][1] + glass[0][3] / 2))
				# Width differance between the glass
				DX = ((glass[1][0] + glass[1][2] / 2) - glass[0][0] + (glass[0][2] / 2))
			else:
				# Height difference between the glass
				DY = (-(glass[1][1] + glass[1][3] / 2) + (glass[0][1] + glass[0][3] / 2))
				# Width differance between the glass
				DX = (-(glass[1][0] + glass[1][2] / 2) + glass[0][0] + (glass[0][2] / 2))
			# Make sure the the change happens only if there is an angle
			if (DX != 0.0) and (DY != 0.0):
				# Find the Angle
				Theta = math.degrees(math.atan(round(float(DY) / float(DX), 2)))
				print("Theta  " + str(Theta))
				# Find the Rotation Matrix
				M = cv2.getRotationMatrix2D((cols / 2, rows / 2), Theta, 1)
				Image = cv2.warpAffine(Image, M, (cols, rows))
				# UNCOMMENT IF YOU WANT TO SEE THE RESULT
				# cv2.imshow('ROTATED', Image)
				# This detects a face in the image
				Face2 = face.detectMultiScale(Image, 1.3, 5)
				for (FaceX, FaceY, FaceWidth, FaceHeight) in Face2:
					CroppedFace = Image[FaceY: FaceY + FaceHeight, FaceX: FaceX + FaceWidth]
					return CroppedFace

def DrawBox(Image, x, y, w, h):
	# Draw a rectangle around the face
	cv2.rectangle(Image, (x, y), (x + w, y + h), (255, 255, 255), 1)

def tell_time_passed():
	print('TIME PASSED ' + str(round(((time.clock() - now_time)/60), 2)) + ' MINS')


# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

#     1
#    / \
#   2   2
#  / \ / \
# 3  4 4  3

# But the following [1,2,2,null,3,null,3] is not:

#     1
#    / \
#   2   2
#    \   \
#    3    3

def isSymmetricHelper(self, p, q):
    if not p or not q:
        return p == q
    if p.val != q.val:
        return False
    return (self.isSymmetricHelper(p.left, q.right)
            and self.isSymmetricHelper(p.right, q.left))

def isSymmetric(self, root: TreeNode) -> bool:
    if not root:
        return True
    return self.isSymmetricHelper(root.left, root.right)


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 09:08:05 2019

@author: s525501
"""
#Import needed packages
from github import Github
from github_token import ACCESS_TOKEN
import degrees_modules
import networkx as nx
import matplotlib.pyplot as plt
from ordered_set import OrderedSet
import warnings
warnings.filterwarnings('ignore')

#Seed the user for the first node
SEED_USER = 'wilsjame'

fig = plt.figure(figsize=(15, 15))
ax = fig.add_subplot(111)

gitGraph = nx.Graph()

#Set up github api requirements
client = Github(ACCESS_TOKEN)
user = client.get_user(SEED_USER)

userSet = OrderedSet()

#Add first node on graph
gitGraph.add_node(user.login, type='user')

#Update user set for seed's followers
users = degrees_modules.addUserFollowers(gitGraph, user)
userSet |= (users)

#Continuously branch out using followers until torvalds is found
def useFollowers(userSet):
    foundTorvalds = False
    while foundTorvalds is False:
        for user in userSet:
            if user.following < 11000:
                userSet |= (degrees_modules.addFollowing(gitGraph, user))
            print('still alive after user ' + str(user))
            if gitGraph.has_node('torvalds') is True:
                foundTorvalds = True
                break

#Branch out using repositories and stargazers
def useGazers(userSet):
    foundTorvalds = False
    while foundTorvalds is False:
        for user in userSet:
            repos = degrees_modules.addStars(gitGraph, user)
            for repo in repos:
                userSet |= degrees_modules.addStargazers(gitGraph, repo)
            if gitGraph.has_node('torvalds') is True:
                foundTorvalds = True
                break

#useFollowers(userSet)
useGazers(userSet)

#Store the generated graph for manipulation
nx.write_gpickle(gitGraph, 'graphStars.pkl')
print('pickle made!')


import os
import re
import time
from datetime import date

import requests

from framework import scheduler
from framework.logger import get_logger

from .model import ModelSetting, ModelScheduler
from .api_ffmpeg import APIFFmpeg
from .crypto_js import AES

package_name = __name__.split(".", maxsplit=1)[0]
logger = get_logger(package_name)

class LogicNormal(object):
    download_list = set()

    @staticmethod
    def scheduler_function(job_id):
        scheduler_model = ModelScheduler.find(job_id)
        content_id = LogicNormal.get_content_id(scheduler_model.url)
        if content_id is None:
            logger.debug("scheduler url error %s", scheduler_model.url)
            return
        for i in range(120):  # 10초 간격으로 최대 120번. 즉, 20분
            video_url = LogicNormal.get_video_url(content_id)
            if video_url is None:
                time.sleep(10)  # 10초 대기
                continue
            logger.debug("scheduler download %s", scheduler_model.url)
            filename = date.today().strftime("%y%m%d") + "_" + scheduler_model.filename
            download = APIFFmpeg.download(
                package_name,
                f"{package_name}_{job_id}_{i}",
                video_url,
                filename,
                save_path=scheduler_model.save_path,
            )
            if download["ret"] != "success":
                logger.debug("scheduler download fail %s", download["ret"])
                logger.debug(download.get("log"))
                time.sleep(10)  # 10초 대기
                continue
            scheduler_model.update()
            while True:
                time.sleep(5)  # 5초 대기
                status = APIFFmpeg.status(package_name, f"{package_name}_{job_id}_{i}")
                if status["ret"] != "success":
                    logger.debug("scheduler status fail %s", status["ret"])
                    logger.debug(status.get("log"))
                    return
                if status["data"]["status"] == 0:
                    continue
                if status["data"]["status"] not in [5, 6, 7]:
                    # 혹시라도 다운로드 실패하면 처음부터
                    break
                # 다운로드 성공. 탈출
                return
            continue

    @staticmethod
    def get_scheduler():
        ret = []
        for scheduler_model in ModelScheduler.get_list(True):
            scheduler_model["last_time"] = (
                scheduler_model["last_time"].strftime("%m-%d %H:%M:%S"),
            )
            scheduler_model["path"] = os.path.join(
                scheduler_model["save_path"],
                date.today().strftime("%y%m%d") + "_" + scheduler_model["filename"],
            )
            scheduler_model["is_include"] = scheduler.is_include(
                f"{package_name}_{scheduler_model['id']}"
            )
            scheduler_model["is_running"] = scheduler.is_running(
                f"{package_name}_{scheduler_model['id']}"
            )
            ret.append(scheduler_model)
        return ret

    @staticmethod
    def add_scheduler(form):
        from .logic import Logic

        pattern = re.compile(r".+\..+$")
        if form["db_id"]:
            data = {
                "save_path": form["save_path"],
                "filename": form["filename"]
                if pattern.findall(form["filename"])
                else form["filename"] + ".mp4",
                "interval": form["interval"],
            }
            scheduler_model = ModelScheduler.find(form["db_id"])
            scheduler_model.update(data)
            if scheduler.is_include(f"{package_name}_{scheduler_model.id}"):
                Logic.scheduler_stop(scheduler_model.id)
                Logic.scheduler_start(scheduler_model.id)
        else:
            content_id = LogicNormal.get_content_id(form["url"])
            if content_id is None:
                logger.debug("url error %s", form["url"])
                return None
            content_info = LogicNormal.get_content_info(content_id)
            if content_info is None:
                logger.debug("url error %s", form["url"])
                return None
            is_old = len(content_id) < 6
            data = {
                "url": f"https://now.naver.com/player/{content_id}"
                if is_old
                else f"https://now.naver.com/l/{content_id}",
                "title": content_info["title"],
                "host": ", ".join(content_info["hosts"]),
                "save_path": form["save_path"],
                "filename": form["filename"]
                if pattern.findall(form["filename"])
                else form["filename"] + ".mp4",
                "interval": form["interval"],
            }
            scheduler_model = ModelScheduler.create(data)
            if ModelSetting.get_bool("auto_start"):
                Logic.scheduler_start(scheduler_model.id)
        return LogicNormal.get_scheduler()

    @staticmethod
    def del_scheduler(db_id):
        from .logic import Logic

        logger.debug("del_scheduler %s", db_id)
        scheduler_model = ModelScheduler.find(db_id)
        if scheduler.is_include(f"{package_name}_{scheduler_model}"):
            Logic.scheduler_stop(scheduler_model.id)
        scheduler_model.delete()
        return LogicNormal.get_scheduler()

    @staticmethod
    def get_content_id(url):
        pattern = re.compile(r"^https?://now\.naver\.com/((player/)|(l/))?(\d+)")
        match = pattern.findall(url)
        if not match:
            return None
        return match[0][3]

    @staticmethod
    def get_content_info(content_id):
        is_old = len(content_id) < 6
        if is_old:
            url = f"https://apis.naver.com/now_web/nowcms-api-xhmac/cms/v1/streams/{content_id}/shows/"
        else:
            url = f"https://apis.naver.com/now_web/oldnow_web/v4/streams/{content_id}/shows"
        headers = {"Referer": "https://now.naver.com/"}
        json = requests.get(url, headers=headers).json()
        if not json["title"]:
            return None
        return json

    @staticmethod
    def get_video_url(content_id):
        is_old = len(content_id) < 6
        if is_old:
            url = f"https://apis.naver.com/now_web/nowapi-xhmac/nnow/v2/stream/{content_id}/livestatus/"
        else:
            url = f"https://apis.naver.com/now_web/oldnow_web/v4/stream/{content_id}/livestatus/"
        headers = {"Referer": "https://now.naver.com/"}
        json = requests.get(url, headers=headers).json()
        if json["status"]["status"] != "ONAIR":
            return None
        video_url = json["status"]["streamUrl"]
        secret_key = json["status"]["color"]  # 이젠 키도 받아야함
        m3u8 = AES.decrypt(video_url, secret_key)  # 주소가 암호화 되어 있음
        return m3u8


import sys
input = sys.stdin.readline

t, w = map(int, input().rstrip().split())
arr = [int(input().rstrip()) for _ in range(t)]

# dp[i][j][k] : i 번 자두나무 아래에서 / j 번 자두까지 먹고 / k 번 이동했을 때
dp = [[[0 for _ in range(w+2)] for _ in range(t+1)] for _ in range(3)]
for i in range(1, t+1):
    for j in range(1, w+2):
        dp[1][i][j] = max(dp[1][i-1][j] + (1 if arr[i-1] == 1 else 0), dp[2][i-1][j-1] + (1 if arr[i-1] == 1 else 0))
        if i != 1 or j != 1: dp[2][i][j] = max(dp[2][i-1][j] + (1 if arr[i-1] == 2 else 0), dp[1][i-1][j-1] + (1 if arr[i-1] == 2 else 0))

res = 0
for i in range(1, w+2):
    res = max(res, dp[1][t][i], dp[2][t][i])
print(res)


def mergeSort(arr):
    if len(arr) <= 1:
        return arr

    # dividing
    mid = len(arr)//2
    #print(min)
    arr1 = arr[:mid]
    arr2 = arr[mid:]

    # conquering with recursion
    mergeSort(arr1)
    mergeSort(arr2)
    return merge(arr1, arr2, arr)

"""
This uses the approach of dividing and conquering.add()The array is
recursively split down to individual items.
The helper function merge() then scans through the array and
joins the items by creating the order
"""
def merge(arr1, arr2, arr):
    i = 0 # index in the sub-array arr1
    j = 0 # index in sub-array  arr2
    k = 0 # index in the main array arr

# while we have not reached the end of both arrays
    while k < len(arr):
        # pick from the second array if we reached the end of the first array
        if i >= len(arr1):
            arr[k] = arr2[j]
            k += 1
            j += 1

        # pick from the first array if we reached the end of the second array
        elif j >= len(arr2):
            arr[k] = arr1[i]
            k += 1
            i += 1

        # if both arrays are non empty, pick the smaller of arr1[i] and arr2[2]
        else:
            if arr1[i] <= arr2[j]:
                arr[k] = arr1[i]
                i += 1
                k += 1
            else:
                arr[k] = arr2[j]
                j += 1
                k += 1

    return arr

"""
arr should not contain duplicate values
this algorithm runs in O(n^2)
Approach: Scan through the array, between the current index and the end
of the array,find the minimum and swap it with the current element

"""
def selectionSort(arr):
    i = 0
    while i < len(arr):
        # find the index of min in arr
        min = findMin(arr,i)
        minIndex = arr.index(min)
        print(min)
        #swap min and the ith element of arr
        arr[i], arr[minIndex] = arr[minIndex],arr[i]
        i += 1
    return arr

def findMin(arr, i):
    min = arr[i]
    while i < len(arr):
        if arr[i] < min:
            min = arr[i]
        i += 1
    return min

def quickSort(arr):
    if len(arr)<=1:
        return
    else:
        pivot = arr[len(arr)-1]
        left = []
        right = []
        for item in arr:
            if item<pivot:
                left.append(item)
            else:
                right.append(item)
        left = quickSort(left)
        right = quickSort(right)
        result = [*left,pivot,*right]
        return result

def partition(arr, low, high):
    pivot = arr[high]

arr = [1, 32, 100, -9, 43, -56, 23, -254, 400, -12,]
# sorted =  selectionSort(arr)#mergeSort(arr)
sorted = quickSort(arr)
print(sorted)
# print(findMin(arr,0))


#!/usr/bin/python3
"""lock boxes interview task
"""

def canUnlockAll(boxes):
    lenght = len(boxes)
    opn_box = set()
    opn_box.add(0)

    for x in range(lenght):
        init_len = len(opn_box)
        for index, box in enumerate(boxes):
            if index not in opn_box:
                continue
            for item in box:
                if item < lenght and item >= 0:
                    opn_box.add(item)
        new_len = len(opn_box)
        if new_len == init_len:
            break

    len_set = len(opn_box)
    if len_set == lenght:
        return True
    else:
        return False


import getopt
import glob
import json
import ntpath
import os
import shlex
import shutil
import subprocess
import sys
import traceback
from datetime import datetime, time
from zipfile import ZipFile, ZIP_DEFLATED
import constants

def get_incremented_dir_path(path):
    """
    returns the incremented dir path
    ex: /a/b/c/0 if not exists returns /a/b/c/0 else /a/b/c/1
    :param path:
    :return:
    """
    while os.path.exists(path):
        try:
            base = str(int(os.path.basename(path)) + 1)
            path = os.path.join(os.path.dirname(path), base)
        except ValueError:
            path = os.path.join(path, '0')
    return path

def backup_dir(path):
    bck_str = '__backup'
    if os.path.exists(path):
        bck_files = [l for l in os.listdir(path) if bck_str not in l]
        if len(bck_files) > 0:
            bck_dir = get_incremented_dir_path(os.path.join(path, bck_str))
            os.makedirs(bck_dir)
            for file in bck_files:
                shutil.move(os.path.join(path, file), bck_dir)
            return bck_dir
    return None

def create_dir_if_not_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)
    return path

def copy_files_with_prefix(src_dir, prefix, dest_dir):
    create_dir_if_not_exists(dest_dir)
    for filename in glob.glob(os.path.join(src_dir, prefix)):
        shutil.copy(filename, os.path.join(dest_dir, ntpath.basename(filename)))

def move_files_with_prefix(src_dir, prefix, dest_dir):
    create_dir_if_not_exists(dest_dir)
    for filename in glob.glob(os.path.join(src_dir, prefix)):
        shutil.move(filename, os.path.join(dest_dir, ntpath.basename(filename)))

def create_zip_with_prefix(src_dir, regex, dest_zip, comp=ZIP_DEFLATED, clean_up=False):
    with ZipFile(dest_zip, 'w', compression=comp) as zip_file:
        for filename in glob.glob(os.path.join(src_dir, regex)):
            zip_file.write(filename, arcname=os.path.basename(filename))
            if clean_up:
                os.remove(filename)
    return dest_zip

def delete_files_with_prefix(src_dir, prefix):
    for filename in glob.glob(os.path.join(src_dir, prefix)):
        os.remove(filename)

def get_em_real_dir(wrf_home=constants.DEFAULT_WRF_HOME):
    return os.path.join(wrf_home, constants.DEFAULT_EM_REAL_PATH)

def run_em_real(wrf_config):
    print('Running em_real...')

    wrf_home = wrf_config['wrf_home']
    em_real_dir = get_em_real_dir(wrf_home)
    procs = wrf_config['procs']
    run_id = wrf_config['run_id']
    output_dir = create_dir_if_not_exists(os.path.join(wrf_config['nfs_dir'], 'results', run_id, 'wrf'))
    archive_dir = create_dir_if_not_exists(os.path.join(wrf_config['archive_dir'], 'results', run_id, 'wrf'))

    print('run_em_real|output_dir: ', output_dir)
    print('run_em_real|archive_dir: ', archive_dir)

    print('Backup the output dir')
    backup_dir(output_dir)

    logs_dir = create_dir_if_not_exists(os.path.join(output_dir, 'logs'))

    print('Copying metgrid.zip')
    metgrid_dir = os.path.join(wrf_config['nfs_dir'], 'metgrid')

    copy_files_with_prefix(metgrid_dir, wrf_config['run_id'] + '_metgrid.zip', em_real_dir)
    metgrid_zip = os.path.join(em_real_dir, wrf_config['run_id'] + '_metgrid.zip')

    print('Extracting metgrid.zip')
    ZipFile(metgrid_zip, 'r', compression=ZIP_DEFLATED).extractall(path=em_real_dir)

    # logs destination: nfs/logs/xxxx/rsl*
    try:
        try:
            print('Starting real.exe')
            print('em_real_dir : ', em_real_dir)
            run_subprocess('mpirun -np %d ./real.exe' % procs, cwd=em_real_dir)
        finally:
            print('Moving Real log files...')
            create_zip_with_prefix(em_real_dir, 'rsl*', os.path.join(em_real_dir, 'real_rsl.zip'), clean_up=True)
            move_files_with_prefix(em_real_dir, 'real_rsl.zip', logs_dir)
        try:
            print('Starting wrf.exe')
            run_subprocess('mpirun -np %d ./wrf.exe' % procs, cwd=em_real_dir)
        finally:
            print('Moving WRF log files...')
            create_zip_with_prefix(em_real_dir, 'rsl*', os.path.join(em_real_dir, 'wrf_rsl.zip'), clean_up=True)
            move_files_with_prefix(em_real_dir, 'wrf_rsl.zip', logs_dir)
    finally:
        print('Moving namelist input file')
        move_files_with_prefix(em_real_dir, 'namelist.input', output_dir)

    print('WRF em_real: DONE! Moving data to the output dir')

    print('Extracting rf from domain3')
    d03_nc = glob.glob(os.path.join(em_real_dir, 'wrfout_d03_*'))[0]
    ncks_query = 'ncks -v %s %s %s' % ('RAINC,RAINNC,XLAT,XLONG,Times', d03_nc, d03_nc + '_rf.nc')
    run_subprocess(ncks_query)

    print('Extracting rf from domain1')
    d01_nc = glob.glob(os.path.join(em_real_dir, 'wrfout_d01_*'))[0]
    ncks_query = 'ncks -v %s %s %s' % ('RAINC,RAINNC,XLAT,XLONG,Times', d01_nc, d01_nc + '_rf.nc')
    run_subprocess(ncks_query)

    print('Moving data to the output dir')
    move_files_with_prefix(em_real_dir, 'wrfout_d03*_rf.nc', output_dir)
    move_files_with_prefix(em_real_dir, 'wrfout_d01*_rf.nc', output_dir)
    print('Moving data to the archive dir')
    move_files_with_prefix(em_real_dir, 'wrfout_*', archive_dir)

    print('Cleaning up files')
    delete_files_with_prefix(em_real_dir, 'met_em*')
    delete_files_with_prefix(em_real_dir, 'rsl*')
    os.remove(metgrid_zip)

def run_subprocess(cmd, cwd=None, print_stdout=False):
    print('Running subprocess %s cwd %s' % (cmd, cwd))
    print('Running subprocess %s cwd %s' % (cmd, cwd))
    start_t = time.time()
    output = ''
    try:
        output = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT, cwd=cwd)
    except subprocess.CalledProcessError as e:
        print('Exception in subprocess %s! Error code %d' % (cmd, e.returncode))
        print(e.output)
        raise e
    finally:
        elapsed_t = time.time() - start_t
        print('Subprocess %s finished in %f s' % (cmd, elapsed_t))
        if print_stdout:
            print('stdout and stderr of %s\n%s' % (cmd, output))
    return output

def get_wps_dir(wrf_home=constants.DEFAULT_WRF_HOME):
    return os.path.join(wrf_home, constants.DEFAULT_WPS_PATH)

try:
    print('WPS process triggered...')
    workflow = '1'
    run_day = '0'
    data_hour = '00'
    model = ''
    run_date = ''
    path = '/mnt/disks/data/wrf_run'
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:m:w:d:p:", [
            "hour=", "model=", "workflow=", "run_date=", "path="
        ])
    except getopt.GetoptError:
        print('Input error.')
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--hour"):
            data_hour = arg  # '00'|'06'|'12'|'18'
        elif opt in ("-m", "--model"):
            model = arg  # 'A'|'C'|'E'|'SE'
        elif opt in ("-w", "--workflow"):
            workflow = arg  # '0'|'1'
        elif opt in ("-p", "--path"):
            path = arg  #
        elif opt in ("-d", "--run_date"):
            run_date = arg  # '2019-08-21'
    print("GFS data hour : ", data_hour)
    print("GFS run_date : ", run_date)
    with open('config.json') as json_file:
        config = json.load(json_file)
        gfs_data_path = os.path.join(path, 'wrf{}/d{}/{}/gfs/{}'.format(workflow, run_day, data_hour, run_date))
        wps_path = os.path.join(path, 'wrf{}/d{}/{}/wps/{}'.format(workflow, run_day, data_hour, run_date))
        if os.path.exists(path):
            gfs_date = '{}_{}:00'.format(run_date, data_hour)
            config['gfs_date'] = gfs_date
            namelist_updated_path = os.path.join(path, 'wrf{}/d{}/{}/{}/{}'.format(workflow,
                                                 run_day, data_hour, model, run_date), 'namelist.input')
            config['namelist_updated'] = namelist_updated_path
            wps_dir = get_wps_dir(config['wrf_home'])
            print('wps_dir : ', wps_dir)
            shutil.rmtree(config['gfs_dir'])
            delete_files_with_prefix(wps_dir, 'FILE:*')
            delete_files_with_prefix(wps_dir, 'PFILE:*')
            delete_files_with_prefix(wps_dir, 'geo_em.*')
            run_em_real(config)
except Exception as e:
    traceback.print_exc()


from flask import jsonify, current_app
from flask.views import MethodView
from flask_smorest import Blueprint

from server.extensions.database import handle_database_connection
from server.schemas import SportSchema, SportUpdateSchema
from server.utility.exceptions import create_exceptions

sportBlueprint = Blueprint("Sports", "sports", description="Operations on sports")

@sportBlueprint.route("/sport/<string:sport_id>")
class Sport(MethodView):
    @sportBlueprint.response(200, SportSchema)
    @handle_database_connection
    def get(self, cursor, sport_id):
        cache = current_app.config["CACHE"]
        cached_sport = cache.get(sport_id)
        if cached_sport:
            return jsonify(cached_sport)

        cursor.execute('SELECT * FROM sport WHERE name = %s', (sport_id,))
        sport = cursor.fetchone()

        if sport is None:
            return jsonify({"error": "Sport not found"}), 404

        cache.set(sport_id, sport, timeout=60)
        return jsonify(sport)

    @handle_database_connection
    def delete(self, cursor, sport_id):

        cursor.execute('SELECT * FROM sport WHERE name = %s', (sport_id,))
        sport = cursor.fetchone()
        if not sport:
            return jsonify({"error": "Sport not found"}), 404
        delete_query = 'DELETE FROM sport WHERE name = %s'
        cursor.execute(delete_query, (sport_id,))

        return {"message": "Sport deleted."}

    @handle_database_connection
    @sportBlueprint.arguments(SportUpdateSchema)
    @sportBlueprint.response(200, SportSchema)
    def put(self, cursor, sport_data, sport_id):

        cursor.execute('SELECT * FROM sport WHERE name = %s', (sport_id,))
        sport = cursor.fetchone()
        if not sport:
            return jsonify({"error": "Sport not found"}), 404

        slug = sport_data.get('slug')
        active = sport_data.get('active')

        if slug is not None and active is not None:
            update_query = 'UPDATE sport SET slug = %s, active = %s WHERE name = %s RETURNING *'
            cursor.execute(update_query, (slug, active, sport_id))
        elif slug is not None:
            update_query = 'UPDATE sport SET slug = %s WHERE name = %s RETURNING *'
            cursor.execute(update_query, (slug, sport_id))
        elif active is not None:
            update_query = 'UPDATE sport SET active = %s WHERE name = %s RETURNING *'
            cursor.execute(update_query, (active, sport_id))
        updated_sport = cursor.fetchone()

        return jsonify(updated_sport)

@sportBlueprint.route("/sport")
class SportList(MethodView):
    @handle_database_connection
    @sportBlueprint.response(200, SportSchema(many=True))
    def get(self, cursor):
        cursor.execute('SELECT name, slug, active FROM sport')
        sports = cursor.fetchall()

        return jsonify(sports)

    @create_exceptions
    @sportBlueprint.arguments(SportSchema)
    @sportBlueprint.response(201, SportSchema)
    @handle_database_connection
    def post(self, cursor, sport_data):
        cursor.execute(
            "INSERT INTO sport (name, slug, active) VALUES (%s, %s, %s) RETURNING name, slug, active;",
            (sport_data["name"], sport_data["slug"], sport_data["active"]),
        )
        item = cursor.fetchone()

        return jsonify(item)


import logging

# IP address of virtual site
VIRTUAL_SITE_IP = '172.22.134.8'

# IP address of backend server
BACKEND_IP = '172.18.0.100'

# Concurrent virtual user count
VIRTUAL_USERS = 200

# Desired load per tunnel (KB/s)
TRAFFIC_LOAD_PER_TUNNEL = 200

# how long should the test run(with seconds)
DURATION = 60

# tunnel type 'TCP', 'UDP', 'DTLS', 'DTLSv1', 'DTLSv12', for DTLS tunnel, if you don't know how to choose, please use 'DTLS'
TUNNEL_TYPE = 'DTLSv1'

# encrypt UDP('True' or 'False')
IS_UDP_TUNNEL_ENCRYPT = True

# payload type, 'ICMP' or 'UDP'
PAYLOAD_TYPE = 'UDP'

# payload src port
PAYLOAD_SRC_PORT = 8888

# payload dst port, default is 9000
PAYLOAD_DST_PORT = 9000

# UDP server processes, default value is 4 since the server side default process number is 4
UDP_SERVER_PROCESS_NUMBER = 4

# payload packet size(Bytes), the packet size is include: include payload ip header and protocol header
# for TCP tunnel the max packet size is: PAYLOAD_PACKET_SIZE = MTU - 20(IP Header) - 8(TCP header) = 1472
# for UDP tunnel and DTLS tunnel, the max packet size is: PAYLOAD_PACKET_SIZE = MTU - 20 - 8 - 4(array udp tunnel header)
PAYLOAD_PACKET_SIZE = 1300

# LOG LEVEL, by default "logging.ERROR" (debug < info < warning < error < critical, NOTSET means do not out put log)
LOGGING_LEVEL = logging.NOTSET


from tkinter import *
import math
root=Tk()
root.title("Scientific Calculator")
root.resizable(width=False, height=False)
root.geometry("520x407+200+100")
e = Frame(root)

e=Entry(root,width=42,borderwidth=5,font=('Cambria',16,'bold'),bd=7,justify='right',fg="white",bg="grey")
e.grid(row=0,column=0,columnspan=4,pady=10)

def value(num):
    current =e.get()
    e.delete(0,END)
    e.insert(0,str(current)+str(num))
def clear():
    e.delete(0,END)
def add():
    global f_num
    f_num = e.get()
    global operation
    operation="add"
    e.delete(0,END)
def sub():
    global f_num
    f_num = e.get()
    global operation
    operation="sub"
    e.delete(0,END)
def mul():
    global f_num
    f_num = e.get()
    global operation
    operation="mul"
    e.delete(0,END)
def div():
    global f_num
    f_num = e.get()
    global operation
    operation="div"
    e.delete(0,END)
def cos():
    res = math.cos(math.radians(float(e.get())))
    e.delete(0,END)
    e.insert(0,res)
def sin():
    res = math.sin(math.radians(float(e.get())))
    e.delete(0,END)
    e.insert(0,res)
def tan():
    res = math.tan(math.radians(float(e.get())))
    e.delete(0,END)
    e.insert(0,res)
def pi():
    e.delete(0,END)
    res = math.pi
    e.insert(0,res)
def cosh():
    res = math.cosh(math.radians(float(e.get())))
    e.delete(0,END)
    e.insert(0,res)
def sinh():
    res = math.sinh(math.radians(float(e.get())))
    e.delete(0,END)
    e.insert(0,res)
def tanh():
    res = math.tanh(math.radians(float(e.get())))
    e.delete(0,END)
    e.insert(0,res)
def squareroot():
    res = math.sqrt(float(e.get()),1/2)
    e.delete(0,END)
    e.insert(0,res)
def cuberoot():
    res = math.pow(float(e.get()),1/10)
    e.delete(0,END)
    e.insert(0,res)
def delete():
    num=e.get()[:-1]
    e.delete(0,END)
    e.insert(0,num)
def pm():
    num = e.get()
    e.delete(0,END)
    e.insert(0,-(float(num)))
def CE():
    e.delete(0,END)
    e.insert(0,0)
def log():
    res = math.log(float(e.get()))
    e.delete(0,END)
    e.insert(0,res)
def log10():
    res = math.log10(float(e.get()))
    e.delete(0,END)
    e.insert(0,res)
def log2():
    res = math.log2(float(e.get()))
    e.delete(0,END)
    e.insert(0,res)
def e_val():
    e.delete(0,END)
    e.insert(0,math.e)
def exp():
    res = math.exp(float(e.get()))
    e.delete(0,END)
    e.insert(0,res)
def deg():
    res = math.degrees(float(e.get()))
    e.delete(0,END)
    e.insert(0,res)
def mod():
    global f_num
    f_num = float(e.get())
    global operation
    operation = "mod"
    e.delete(0,END)
def lgamma():
    res = math.lgamma(float(e.get()))
    e.delete(0,END)
    e.insert(0,res)
def byx():
    res = 1.0/float(e.get())
    e.delete(0,END)
    e.insert(0,res)
def absolute():
    res = abs(float(e.get()))
    e.delete(0,END)
    e.insert(0,res)
def factorial():
    num = float(e.get())
    if(not num.is_integer()):
        print("not an integer")
        return

    res = math.factorial(int(num))
    e.delete(0,END)
    e.insert(0,res)

def equal():
    s_num=e.get()
    e.delete(0,END)
    if(operation=="add"):
        e.insert(0,float(f_num)+float(s_num))
    if(operation=="sub"):
        e.insert(0,float(f_num)-float(s_num))
    if(operation=="mul"):
        e.insert(0,float(f_num)*float(s_num))
    if(operation=="div"):
        e.insert(0,float(f_num)/float(s_num))
    if(operation=="mod"):
        e.insert(0,float(f_num)%float(s_num))

button_1 = Button(root,text="1",command=lambda: value(1),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_2 = Button(root,text="2",command=lambda: value(2),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_3 = Button(root,text="3",command=lambda: value(3),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_4 = Button(root,text="4",command=lambda: value(4),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_5 = Button(root,text="5",command=lambda: value(5),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_6 = Button(root,text="6",command=lambda: value(6),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_7 = Button(root,text="7",command=lambda: value(7),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_8 = Button(root,text="8",command=lambda: value(8),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_9 = Button(root,text="9",command=lambda: value(9),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_0 = Button(root,text="0",command=lambda: value(0),bg="grey",fg="white",width=10,height=2,font=('Cambria',16,'bold'))
button_dot = Button(root,text=".",command=lambda: value("."),width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_clear = Button(root,text="Clear",command=clear,width=10,height=2,bg="light blue",font=('Cambria',16,'bold'))
button_CE = Button(root,text="CE",command=CE,width=10,height=2,bg="light blue",font=('Cambria',16,'bold'))
button_del=Button(root,text="DEL",command=delete,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_add = Button(root,text="+",command=add,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_equal = Button(root,text="=",command=equal,width=10,height=2,bg="red",fg="white",font=('Cambria',16,'bold'))
button_sub = Button(root,text="-",command=sub,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_mul = Button(root,text="*",command=mul,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_div = Button(root,text="/",command=div,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_pm = Button(root,text=chr(177),command=pm,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_squareroot = Button(root,text="\u221A",command=squareroot,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_cos = Button(root,text="cos",command=cos,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_sin = Button(root,text="sin",command=sin,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_tan = Button(root,text="tan",command=tan,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_cuberoot = Button(root,text="\u221B",command=cuberoot,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_pi = Button(root,text="pi",command=pi,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_cosh = Button(root,text="cosh",command=cosh,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_sinh = Button(root,text="sinh",command=sinh,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_tanh = Button(root,text="tanh",command=tanh,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_log = Button(root,text="log",command=log,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_log10 = Button(root,text="log10",command=log10,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_log2 = Button(root,text="log2",command=log2,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_e = Button(root,text="e",command=e_val,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_exp = Button(root,text="exp",command=exp,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_gamma = Button(root,text="gamma",command=lgamma,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_1byx = Button(root,text="1/x",command=byx,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_deg = Button(root,text="deg",command=deg,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_mod = Button(root,text="mod",command=mod,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_abs = Button(root,text="|x|",command=absolute,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))
button_factorial = Button(root,text="x!",command=factorial,width=10,height=2,bg="blue",fg="white",font=('Cambria',16,'bold'))

button_1.grid(row=2,column=0)
button_2.grid(row=2,column=1)
button_3.grid(row=2,column=2)
button_add.grid(row=1,column=3)
button_4.grid(row=3,column=0)
button_5.grid(row=3,column=1)
button_6.grid(row=3,column=2)
button_sub.grid(row=2,column=3)
button_7.grid(row=4,column=0)
button_8.grid(row=4,column=1)
button_9.grid(row=4,column=2)
button_mul.grid(row=3,column=3)
button_0.grid(row=5,column=0)
button_dot.grid(row=5,column=1)
button_div.grid(row=4,column=3)
button_equal.grid(row=5,column=3)
button_clear.grid(row=1,column=0)
button_CE.grid(row=1,column=1)
button_pm.grid(row=5,column=2)
button_del.grid(row=1,column=2)
button_squareroot.grid(row=1,column=4)
button_cos.grid(row=1,column=5)
button_sin.grid(row=1,column=6)
button_tan.grid(row=1,column=7)
button_cuberoot.grid(row=2,column=4)
button_cosh.grid(row=2,column=5)
button_sinh.grid(row=2,column=6)
button_tanh.grid(row=2,column=7)
button_pi.grid(row=3,column=4)
button_log.grid(row=3,column=5)
button_log10.grid(row=3,column=6)
button_log2.grid(row=3,column=7)
button_e.grid(row=4,column=4)
button_exp.grid(row=4,column=5)
button_gamma.grid(row=4,column=6)
button_1byx.grid(row=4,column=7)
button_deg.grid(row=5,column=4)
button_mod.grid(row=5,column=5)
button_abs.grid(row=5,column=6)
button_factorial.grid(row=5,column=7)

def Standard():
    root.resizable(width=False,height=False)
    root.geometry("520x407+0+0")
def Scientific():
    root.resizable(width=False,height=False)
    root.geometry("1041x407+0+0")
def mexit():
    return
menubar = Menu(root)
Filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File",menu=Filemenu)
Filemenu.add_command(label="Standard",command=Standard)
Filemenu.add_command(label="Scientific",command=Scientific)
Filemenu.add_separator()
Filemenu.add_command(label="Exit",command=mexit)

root.config(menu=menubar)
root.mainloop()


import sys
from collections import deque

dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]

n = int(sys.stdin.readline().rstrip())
matrix = []
max_val = 0
for _ in range(n):
    tmp = list(map(int, sys.stdin.readline().rstrip().split()))
    matrix.append(tmp)
    max_val = max(max_val, max(tmp))

answer = 0
for k in range(max_val):
    isWet = [[False] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if matrix[i][j] <= k:
                isWet[i][j] = True

    cnt = 0
    q = deque()
    for i in range(n):
        for j in range(n):
            if isWet[i][j]:
                continue
            cnt += 1
            q.append([i, j])
            isWet[i][j] = True
            while q:
                y, x = q.popleft()
                for g in range(4):
                    ny = y + dy[g]
                    nx = x + dx[g]
                    if 0 <= ny < n and 0 <= nx < n:
                        if not isWet[ny][nx]:
                            isWet[ny][nx] = True
                            q.append([ny, nx])
    answer = max(answer, cnt)
print(answer)


#!/usr/bin/python3
from mod import EnemyModDrop, MissionDrop
from mission import Mission, GenericDropLocation
from fuzzywuzzy import process, fuzz, utils

def dprint(*args, **kwargs):
    if __name__ == '__main__':
        print(*args, **kwargs)

mods = eval(open('data/mods.db').read())
missions = eval(open('data/missions.db').read())
item_names = list(set([x.name for x in mods] + [x.dropped_by for x in mods] + [x.name for x in missions] + [x.dropped_by for x in missions]))

def query(q):
    nameScoreTuples = process.extractBests(q, item_names, utils.full_process, fuzz.WRatio, 25, 1)
    #Sort the results so the higher scored ones will be right above the console cursor
    nameScoreTuples.sort(key=lambda x: x[1])
    m = []
    for tuple in nameScoreTuples:
        name = tuple[0]
        m += [""]
        interpretingAsText = f"Interpreting as \"{name}\""
        mt = [x for x in mods if x.name == name] + \
            [x for x in missions if x.name == name]
        if len(mt) == 0:
            # Probably this is a mission or enemy name
            mt = [x for x in missions if x.dropped_by == name]
            if len(mt) == 0:
                # Probably this is an enemy name
                mt = [x for x in mods if x.dropped_by == name]
                # Sort by chance.
                mt.sort(key = lambda x: x.total_chance, reverse=True)
                if not len(mt) == 0:
                    interpretingAsText += " (enemy)"
            else:
                # Sort by rotation and chance.
                mt.sort(key = lambda x:
                    x.total_chance - 100 * ((ord(x.rotation) - ord("A")) if len(x.rotation) > 0 else 0)
                , reverse=True)
                interpretingAsText += " (mission)"
            # Return the reverse name that contains the item instead of the mission/enemy name, the latter being the search query in this case
            mt = [x.reversedName() for x in mt]
        else:
            mt.sort(key=lambda x: x.total_chance, reverse=True)
            interpretingAsText += " (item)"
        m += [interpretingAsText]
        m = m + mt
    return m

if __name__ == '__main__':
    global debug
    debug = True
    while True:
        for d in query(input('> ')):
            dprint(d)


__copyright__ = """
Copyright 2008 Sean Ross-Ross
"""
__license__ =  """
This file is part of SLIMpy .

SLIMpy is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SLIMpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with SLIMpy . If not, see <http://www.gnu.org/licenses/>.
"""

from unittest import TestCase,defaultTestLoader
from slimpy_base.Core.Command.Command import Command
from slimpy_base.Core.Command.Converter import MapFunctions as mf

NI = False

class MapFunctionsTester( TestCase ):

    def testtruefalseHelper( self ):

        command = Command( 'tag', None, this=True, that=False )

        command = mf.truefalseHelper( command, true='tt', false='ff' )
#        command, true='y', false='n'

        self.failUnlessEqual( command['this'],'tt')
        self.failUnlessEqual( command['that'],'ff')

    def testkeep( self ):

        command = Command( 'tag', None, this=True, that=False )

        command = mf.keep(command, ['this','foo'] )

        self.failIf( command.has_key('that') )

        self.failUnless( command.has_key('this') )

    def testsplit( self ):

        command = Command( 'tag', None, this=True, that=False )

        c1,c2 = mf.split(command)

        self.failUnlessEqual( c1, c2 )
        self.failIfEqual( id(c1), id(c2) )

    def testdiscard( self ):
        command = Command( 'tag', None, this=True, that=False )

        cmd = mf.discard(command, ['that'] )

        self.failUnless( cmd.has_key('this') )
        self.failIf( cmd.has_key('that') )

    def testkeywordmap( self ):

        command = Command( 'tag', None, this=True, that='False' )

        cmd = mf.keywordmap(command, {'that':'spam'} )

        self.failUnless( cmd.has_key('spam') )
        self.failUnlessEqual(cmd['spam'],  'False' )
        self.failIf( cmd.has_key('that') )

    def testpack( self ):

        raise NotImplementedError('not implemented')

def suite():
    return defaultTestLoader.loadTestsFromTestCase( MapFunctionsTester )


# Exemplo com sensor MPU6050
import board
from busio import I2C
from time import sleep
import adafruit_mpu6050

# Configura o sensor
i2c = I2C(sda=board.GP16, scl=board.GP17)
sensor = adafruit_mpu6050.MPU6050(i2c)

# Laco principal
G = 9.8
while True:
    x,y,z = sensor.acceleration
    print ('Aceleracao X:{:.1f}g y:{:.1f}g Z:{:.1f}g'.format(x/G, y/G, z/G))
    x,y,z = sensor.gyro
    print ('Giroscopio X:{:.1f} y:{:.1f} Z:{:.1f}'.format(x,y,z))
    print ('Temperatura: {:.1f}C'.format(sensor.temperature))
    print ()
    sleep(2)


import shutil
import os
import datetime
import sys
import time

x = 1

mod = input('Mod to play: \n >>')
#if

if mod == 'vc' or 'VC':
	dest = 'C:\\Users\\coust\\Documents\\Mount&Blade Warband Savegames - Backup\\VC'
	source = 'C:\\Users\\coust\\Documents\\Mount&Blade Warband Savegames\\Viking Conquest\\'
elif mod == 'pop' or 'POP':
	source = 'C:\\Users\\coust\\Documents\\Mount&Blade Warband Savegames\\Prophesy of Pendor V3.9.2\\'
	dest = 'C:\\Users\\coust\\Documents\\Mount&Blade Warband Savegames - Backup\\PoP'

while x:
    timestamp = datetime.datetime.now()
    for adi_dir, dirs, files in os.walk(source):
        for file in files:
            time   .sleep(60*5)
            source_path = source + file
            file_creation_time = os.path.getmtime(source_path)
            dest_path = dest + file + timestamp.strftime('-%Y%m%dT%H%M%S')
            if not os.path.exists(dest):
                try:
                    os.makedirs(os.path.dirname(dest))
                except:  # Guard against race condition
                    print('Directory could not be made')
            shutil.copyfile(source_path, dest_path)
            nowtime = datetime.datetime.now()
            print('[{}]: Save Backed-up'.format(nowtime))


import PySimpleGUI as sg
import main as downloader
import webbrowser as web
from sys import platform

cfg = downloader.config()
downloader.terminal_msgs(0, 0)
sg.theme(cfg.color_theme) # Color Scheme

# OS based default directory lookup
downloader.terminal_msgs(0, 1)
if cfg.use_default_directory or (not cfg.use_default_directory and cfg.custom_default_directory == ''):
    if platform == 'win32':
        user_dir = cfg.check_for_OneDrive()
        logo = 'logo.ico'
    if platform == 'linux' or platform == 'linux2':
        user_dir = '~/Documents/YT-Download'
        logo = 'logo.png'
else:
    user_dir = cfg.custom_default_directory
    if platform == 'win32':
        logo = 'logo.ico'
    if platform == 'linux' or platform == 'linux2':
        logo = 'logo.png'

font = (None, 10, 'underline')

# GUI layout
layout = [ [sg.Text("Thank you for using YT Download!")],
           [sg.Text("YouTube URL:"), sg.InputText(key='URL')],
           [sg.Checkbox('Download as an audio file (mp3)?', default=cfg.default_as_audio, key='isAudio')],
           [sg.Text('File path. Leave blank to save download to:')],
           [sg.Text(user_dir)],
           [sg.Input(key='DIR'), sg.FolderBrowse()],
           [sg.Button('Download'), sg.Button('Settings'), sg.Cancel(button_text='Exit'), sg.Push(), sg.Text(f'Version: {cfg.version}', tooltip='https://github.com/Joey451-OG/YT-Download', enable_events=True, key='GITHUB', font=font)]
    ]

# Main logic function. Calls the appropriate functions in main.py and handles input errors.
def GUI_checks(audio_val: str, url_val: str, dir_val: str):

    download = True

    if 'playlist?list=' in url_val and cfg.playlist_confirmation: # URL is a playlist and playlist confirmation is True
        playlist_window = sg.Window('YT Download', playlist_layout, icon=logo)

        while True: # Open the confirmation popup
            p_event, p_val = playlist_window.read()
            print(p_event, p_val)
            if p_event == 'Yes': # If yes, continue downloading and close the popup
                playlist_window.close()
                break

            elif p_event == 'No' or p_event == sg.WIN_CLOSED: # If no (or popup was closed), stop downloading and close the popup
                sg.popup('Not downloading playlist...', icon=logo, title='YT Download')
                playlist_window.close()
                download = False
                break

    if download:
        # Reason for setting title to playlist
        '''
        I set the title to playlist first to handle the condition in which the user is trying to download a playlist.
        title will be changed if the user is not downloading a playlist.
        '''
        title = 'playlist'

        if 'playlist?list=' not in url_val:
            title = downloader.return_title(url_val)

        if dir_val == '': # Check to see if user wants to use the default dir
            dir_val = user_dir

        if audio_val: # Check to see if the user want to download as an audio file
            file_type = '.mp3'
        else:
            file_type = '.mp4'

        if url_val == '': # Check to see if the url field is empty, then warn the user if it is.
            sg.popup('Please make sure to provide a URL', icon=logo, title='YT Download')
        else:
            if title == 'ERROR': # Check for an invalid url
                sg.popup('INVALID YOUTUBE URL', icon=logo, title='YT Download')
                title = False

            if title != False: # Start downloading
                yt_download = downloader.logic(url_val, audio_val, dir_val)

                if yt_download == 'FFMPEG ERROR': # Check for a FFMPEG error
                    sg.popup('It looks like FFmpeg is not installed. Try reinstalling YT Download or add FFmpeg to the PATH manually.', icon=logo, title='YT Download')
                elif cfg.file_downloaded: # Downloaded confirmation popup
                    sg.popup(f'Downloaded {title} as a {file_type} file to {dir_val}', icon=logo, title='YT Download')

# Main logic behind the settings menu window. Calls appropriate functions in main.py.
def settings_menu():
    print(f'\n\n{"x" * 10}\nNOW ENTERING SETTINGS MENU. ALL EVENT/VALUE PAIRS ARE SPECIFIC TO THE SETTINGS WINDOW.\n{"x" * 10}\n\n')
    settings_window = sg.Window('YT Download', settings_layout, icon=logo)
    while True:
        s_event, s_value = settings_window.read()
        print(s_event, s_value)

        if s_event == sg.WIN_CLOSED or s_event == 'Exit': # Check to see if the user closes the settings window or clicks the EXIT button
            settings_window.close()
            break
        if s_event == 'Apply': # Check to see if the user clicks the APPLY button
            # Package the settings menu data
            s_value.pop('Browse') # Remove the data associated with the BROWSE key. This is duplicate information as the INPUT (key: 2) field. Since the INPUT field can be used independently of BROWSE, we keep it.
            setting_list = list(s_value.values())

            # Check for accidental overwrite of the custom default directory
            if not cfg.use_default_directory and s_value[2] == '':
                setting_list[1] = cfg.custom_default_directory

            # Send data to main.py for writing to config file
            cfg.update_config_file(setting_list)
            cfg.update_class_vars()

            # Restart YT Download
            settings_window.close()
            sg.popup('Closing YT Download in five seconds... \nClick OK to shutdown now.',title='YT Download', auto_close=True, auto_close_duration=5, icon=logo)
            window.close()

# Main setup loop. Calls GUI_checks()
downloader.terminal_msgs(0, 2)
window = sg.Window('YT Download', layout, icon=logo)
while True:

    # Playlist Layout
    playlist_layout = [
        [sg.Push(), sg.Text('You are trying to download a Playlist. Do you want to continue?'), sg.Push()],
        [sg.Push(), sg.Button('Yes'), sg.Button('No'), sg.Push()]
    ]

    # Settings Menu Layout
    settings_layout = [
        [sg.Push(), sg.Text('Settings Menu'), sg.Push()],
        [sg.Push(), sg.Text('~' * 15), sg.Push()],
        [sg.Text('Directory Settings'), sg.HorizontalSeparator(pad=(10, 5))],
        [sg.Checkbox('Use default directory', default=cfg.use_default_directory)],
        [sg.Text('Custom default directory:', tooltip='Custom default directory will not be used if USE DEFAULT DIRECTORY is checked')],
        [sg.Input(tooltip='Custom default directory will not be used if USE DEFAULT DIRECTORY is checked'), sg.FolderBrowse(tooltip='Custom default directory will not be used if USE DEFAULT DIRECTORY is checked')],
        [sg.Text('Popup Settings'), sg.HorizontalSeparator(pad=(10, 5))],
        [sg.Checkbox('Show playlist confirmation popup', default=cfg.playlist_confirmation)],
        [sg.Checkbox('Show file downloaded popup', default=cfg.file_downloaded)],
        [sg.Text('Miscellaneous Settings'), sg.HorizontalSeparator(pad=(10, 5))],
        [sg.Checkbox('Download as .mp3 by default', default=cfg.default_as_audio)],
        [sg.Text('Color Theme:'), sg.Combo(sg.theme_list(), default_value=cfg.color_theme)],
        [sg.Push(), sg.Text('~' * 15), sg.Push()],
        [sg.Button('Apply', tooltip='YT Download will shutdown in order to apply your changes'), sg.Push(), sg.Button('Exit', tooltip='Exiting will not save any changes')]

    ]

    event, values = window.read() # Check the active event and the value dictionary.
    print(event, values) # Print event and values for debugging in the command line.

    if event == sg.WIN_CLOSED or event == 'Exit': # Break the loop if the window is closed or the 'Cancel' button is pressed
        break

    if event == 'GITHUB': # If the linked is clicked, open the GitHub repo.
        web.open("https://github.com/Joey451-OG/YT-Dowload")

    if event == 'Download': # If the Download button was clicked, being file download
        GUI_checks(values['isAudio'], values['URL'], values['DIR'])

    if event == 'Settings': # If the Settings button is clicked, open the settings Menu
        settings_menu()

window.close() # Kill the program