import re
import string
from aiogram import Dispatcher, types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import StatesGroup, State
from config import ADMIN
from keyboard.clent_kb import direct_markup, submit_markup, cancel_markup
from database import command_insert_sql

class FSMAdmin(StatesGroup):
    id_mentor = State()
    name_mentor = State()
    direct_mentor = State()
    age_mentor = State()
    group_mentor = State()
    submit = State()

async def start_fsm(message: types.Message):
    if message.from_user.id != ADMIN:
        await message.answer('Функция доступна только для админа!')
    else:
        await FSMAdmin.id_mentor.set()
        await message.answer('id ментора?', reply_markup=cancel_markup)

async def load_id_mentor(message: types.Message, state: FSMContext):
    if not message.text.isdigit():
        await message.answer('id должен состоять только из цифр')
    elif message.text.isdigit():
        if len(message.text) != 10:
            await message.answer('id должен содержать не менее 10 цифр')
        else:
            async with state.proxy() as data:
                data['id_mentor'] = message.text
            await FSMAdmin.next()
            await message.answer('Имя ментора?', reply_markup=cancel_markup)

async def load_name_mentor(message: types.Message, state: FSMContext):
    if not message.text.isalpha():
        if [i for i in message.text if i in string.digits]:
            await message.answer('Имя не должно содержать цифр')
        else:
            await message.answer('В имени присутствуют недопустимые символы.')
    else:
        async with state.proxy() as data:
            data['name_mentor'] = message.text
        await FSMAdmin.next()
        await message.answer('Направление ментора', reply_markup=direct_markup)

async def load_direct_mentor(message: types.Message, state: FSMContext):
    direct = ['backend', 'frontend', 'fullstack']
    if message.text not in direct:
        await message.answer('Такого направления нет')
    else:
        async with state.proxy() as data:
            data['direct_mentor'] = message.text
        await FSMAdmin.next()
        await message.answer('Какой возраст?', reply_markup=cancel_markup)

async def load_age_mentor(message: types.Message, state: FSMContext):
    normal_age = [str(i) for i in range(17, 60)]

    if not message.text.isdigit():
        await message.answer('Пиши только число')

    elif message.text.isdigit() and message.text not in normal_age:
        await message.answer('Возрастное ограничение')
    else:
        async with state.proxy() as data:
            data['age_mentor'] = message.text
        await FSMAdmin.next()
        await message.answer('какая группа?', reply_markup=cancel_markup)

async def load_group_mentor(message: types.Message, state: FSMContext):
    example = re.findall(r'[a-zA-Z-]+[1-9]+', message.text)
    print(len(example))
    if len(example) <= 0:
        await message.answer(f'Неправильное название группы. Нужно писать так, например\nPy-21 или UX-UI-12')
    else:
        async with state.proxy() as data:
            data['group_mentor'] = message.text
        await FSMAdmin.next()
        await message.answer(f"id_ментора: {data['id_mentor']}\nИмя ментора: {data['name_mentor']}"
                                          f"\nНаправление: {data['direct_mentor']}"
                                          f"\nВозраст: {data['age_mentor'] }\nГруппа: {data['group_mentor']}",)

        await message.answer('Все верно?', reply_markup=submit_markup)

async def submit_fsm(message: types.Message, state: FSMContext):
    if message.text not in ['да', 'нет']:
        await message.answer('Выбери ответ из списка!')
    else:
        if message.text.lower() == 'да':
            await command_insert_sql(state)
            await state.finish()
            await message.answer('Ты зареган')
        elif message.text.lower() == 'нет':
            await state.finish()
            await message.answer('Не хочешь, не надо!')

async def cancel_fsm(message:types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is not None:
        await state.finish()
        await message.answer('Регистрация отменена')

def register_fsm_handlers(dp: Dispatcher):
    dp.register_message_handler(cancel_fsm,  state='*', commands=['cancel'])
    dp.register_message_handler(cancel_fsm, Text(equals='cancel', ignore_case=True), state='*',)
    dp.register_message_handler(start_fsm, commands=['reg'])
    dp.register_message_handler(load_id_mentor, state=FSMAdmin.id_mentor)
    dp.register_message_handler(load_name_mentor, state=FSMAdmin.name_mentor)
    dp.register_message_handler(load_direct_mentor, state=FSMAdmin.direct_mentor)
    dp.register_message_handler(load_age_mentor, state=FSMAdmin.age_mentor)
    dp.register_message_handler(load_group_mentor, state=FSMAdmin.group_mentor)
    dp.register_message_handler(submit_fsm, state=FSMAdmin.submit)


from socket import *

def data_receive(x,y):

    result = str(x)+","+str(y)+',3,4,5,6,0,0,0,10,10,10,10,0'
    print("result : ", result)
    return result

clientSock = socket(AF_INET, SOCK_STREAM)
clientSock.connect(('192.168.35.9', 8080))

li_x = [3,5,0,0,10,10 ]
li_y = [4,6,0,10,10,0 ]
print('연결 확인 됐습니다.')

li = data_receive(li_x[5],li_y[5])
clientSock.send(li.encode('utf-8'))

print('메시지를 전송했습니다.')

data = clientSock.recv(1024)
print('받은 데이터 : ', data.decode('utf-8'))


from typing import Any

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from dependency_injector.wiring import Provide, inject
from mmpy_bot import ActionEvent, Plugin, listen_webhook

from src.bot.services.matching import MatchingService
from src.bot.services.notify_service import NotifyService
from src.core.db.models import MatchReviewAnswerEnum
from src.depends import Container

MONDAY_TIME_SENDING_MESSAGE = 10
DAY_OF_WEEK_MONDAY = "mon"
FRIDAY_TIME_SENDING_MESSAGE = 11
DAY_OF_WEEK_FRIDAY = "fri"
SUNDAY_TIME_SENDING_MESSAGE = 11
DAY_OF_WEEK_SUNDAY = "sun"
WEDNESDAY_TIME_SENDING_MESSAGE = 11
DAY_OF_WEEK_WEDNESDAY = "wed"

class WeekRoutine(Plugin):
    @inject
    def on_start(
        self,
        notify_service: NotifyService = Provide[Container.week_routine_service,],
        matching_service: MatchingService = Provide[Container.matching_service],
        scheduler: AsyncIOScheduler = Provide[Container.scheduler],
    ) -> None:
        scheduler.add_job(
            notify_service.notify_all_users,
            "cron",
            day_of_week=DAY_OF_WEEK_FRIDAY,
            hour=FRIDAY_TIME_SENDING_MESSAGE,
            kwargs=dict(plugin=self, title="Еженедельный пятничный опрос"),
        )
        scheduler.add_job(
            matching_service.run_matching,
            "cron",
            day_of_week=DAY_OF_WEEK_SUNDAY,
            hour=SUNDAY_TIME_SENDING_MESSAGE,
        )
        scheduler.add_job(
            notify_service.meeting_notifications,
            "cron",
            day_of_week=DAY_OF_WEEK_MONDAY,
            hour=MONDAY_TIME_SENDING_MESSAGE,
            kwargs=dict(plugin=self),
        )
        scheduler.add_job(
            self.wednesday_notification_and_closing_meetings,
            "cron",
            day_of_week=DAY_OF_WEEK_WEDNESDAY,
            hour=WEDNESDAY_TIME_SENDING_MESSAGE,
            kwargs=dict(notify_service=notify_service, matching_service=matching_service),
        )
        scheduler.start()

    @inject
    async def _change_user_status(
        self, user_id: str, notify_service: NotifyService = Provide[Container.week_routine_service,]
    ) -> None:
        await notify_service.set_waiting_meeting_status(user_id)

    @listen_webhook("set_waiting_meeting_status")
    async def add_to_meeting(
        self,
        event: ActionEvent,
    ) -> None:
        await self._change_user_status(event.user_id)
        self.driver.respond_to_web(
            event,
            {
                "update": {"message": "До встречи!", "props": {}},
            },
        )

    @listen_webhook("not_meeting")
    async def no(self, event: ActionEvent) -> None:
        self.driver.respond_to_web(
            event,
            {
                "update": {"message": "На следующей неделе отправлю новое предложение.", "props": {}},
            },
        )

    @listen_webhook("match_review_is_complete")
    async def answer_yes(
        self,
        event: ActionEvent,
    ) -> None:
        await self._save_user_answer(event.user_id, MatchReviewAnswerEnum.IS_COMPLETE)
        self.driver.respond_to_web(
            event,
            {
                "update": {
                    "message": "Поделитесь итогами вашей встречи в канале "
                    '"Coffee на этой неделе", отправьте фото и '
                    "краткие эмоции, чтобы мотивировать других "
                    "поучаствовать в Random Coffee!",
                    "props": {},
                },
            },
        )

    @listen_webhook("match_review_is_not_complete")
    async def answer_no(
        self,
        event: ActionEvent,
    ) -> None:
        await self._save_user_answer(event.user_id, MatchReviewAnswerEnum.IS_NOT_COMPLETE)
        user_nickname = await self._get_pair_nickname(event.user_id)
        self.driver.respond_to_web(
            event,
            {
                "update": {
                    "message": f"Неделя скоро закончится, не забудь "
                    f"познакомиться с новым человеком и провести "
                    f"время за классным разговором, напиши "
                    f"{user_nickname} точно ждёт вашей встречи",
                    "props": {},
                },
            },
        )

    @inject
    async def _save_user_answer(
        self, user_id: str, answer: str, notify_service: NotifyService = Provide[Container.week_routine_service,]
    ) -> None:
        await notify_service.set_match_review_answer(user_id, answer)

    @inject
    async def _get_pair_nickname(
        self, user_id: str, matching_service: MatchingService = Provide[Container.matching_service,]
    ) -> Any:
        return await matching_service.get_match_pair_nickname(user_id)

    async def wednesday_notification_and_closing_meetings(
        self,
        notify_service: NotifyService,
        matching_service: MatchingService,
    ) -> None:
        await notify_service.match_review_notifications(plugin=self)
        await matching_service.run_closing_meetings()


from word_collector import *
from article_recommendation import *
import pandas as pd
import pickle
import gzip
import os
import sys

def make_text(room):
	perfect = True
	text = "어제 하루 동안 다음과 같은 단어를 사용하였습니다.\n\
		-----------------------------\n"
	for word in room.wordDict.keys():
		w = room.wordDict[word]
		if w.history != 0:
			text += "<{0}> 혐오도 : {1}, 사용한 횟수 : {2}\n".format(w.word,w.score,w.history)
			text += "사용하신 단어 <"+word+">와 관련된 다음과 같은 기사를 추천드립니다!\n"+get_article(word)+"\n\n"
			perfect = False
		w.history = 0

	if perfect:
		text =  "축하합니다! 어제 하루동안 설정된 단어를 하나도 사용하지 않았습니다!"

	return text

def daily_report(): #사용한 단어 초기화
	with gzip.open(roomFile,'rb') as f:
		data = pickle.load(f)

	output = []
	room_list = data.keys()
	for room in room_list:
		room_json = {
			"room" : room,
			"text" : make_text(data[room])
		}
		output.append(room_json)
	return output


import re
from statistics import median
from operator import itemgetter

def le_assinatira():
    """
        The function reads the values of the linguistic features
        of the model and returns a signature to be compared with
        the texts provided.
    """
    print("Welcome to the automatic COH-PIAH detector.")

    wal = float(input("Enter the average word size: "))
    ttr = float(input("Enter the Type-Token interface: "))
    hlr = float(input("Enter the Reason Hapax Legomana: "))
    sal = float(input("Enter the sentence size: "))
    sac = float(input("Enter the average sentence complexity: "))
    pal = float(input("Enter the average sentence size: "))

    return [wal, ttr, hlr, sal, sac, pal]

def le_textos():
    i = 1
    textos = []
    texto = input(f"Enter text {str(i)} (press enter to exit): ")
    while texto:
        textos.append(texto)
        i += 1
        texto = input(f"Enter text {str(i)} (press enter to exit): ")
    return textos

def separa_sentencas(texto: str) -> list:
    """
       The function receives a text and returns a list of sentences
       within the text.
    """
    sentencas = re.split(r"[.!?]+", texto)
    if sentencas[-1] == "":
        del sentencas[-1]
    return sentencas

def separa_frases(sentenca: str) -> list:
    """
        The function receives a sentence and returns
        a list of phrases within the sentence.
    """
    return re.split(r"[,:;]+", sentenca)

def separa_palavras(frase: str) -> list:
    """
        The function receives a sentence and returns a list
        of words within the sentence.
    """
    return frase.split()

def n_palavras_unicas(lista_palavras):
    """
        This function receives a list of words and returns the
        number of words that appear only once.
    """
    freq = dict()
    unicas = 0
    for palavra in lista_palavras:
        p = palavra.lower()
        if p in freq:
            if freq[p] == 1:
                unicas -= 1
            freq[p] += 1
        else:
            freq[p] = 1
            unicas += 1

    return unicas

def n_palavras_diferentes(lista_palavras):
    """
        This function receives a list of words and returns the
        number of different words used.
    """
    freq = dict()
    for palavra in lista_palavras:
        p = palavra.lower()
        if p in freq:
            freq[p] += 1
        else:
            freq[p] = 1

    return len(freq)

def compara_assinatura(as_a, as_b):
    """
        TO IMPLEMENT. This function receives two text signatures
        and must return the degree of similarity in the signatures.
    """
    diferenca = sum(abs(a - b) for a, b in zip(as_a, as_b))
    print(diferenca)
    print(diferenca / 6)
    return diferenca / 6

def calcula_assinatura(texto):
    """
        TO IMPLEMENT. This function receives a text and must return
        the text signature.
    """
    return [
        calcula_tamanho_medio_palavra(texto),
        calcula_type_token(texto),
        calcula_hapax_legomana(texto),
        calcula_tamanho_medio_sentenca(texto),
        calcula_complexidade_sentenca(texto),
        calcula_tamanho_medio_frase(texto),
    ]

def avalia_textos(textos, ass_cp):
    """
        TO IMPLEMENT. This function receives a list of texts and
        an ass_cp signature and must return the number (1 to n) of
        the text most likely to have been infected with COH-PIAH.
    """
    aux = {}
    for k, v in enumerate(textos):
        ass = calcula_assinatura(v)
        aux[k + 1] = compara_assinatura(ass_cp, ass)
    aux = sorted(aux.items(), key=itemgetter(1))
    return aux[0][0]

def calcula_tamanho_medio_palavra(texto: str) -> float:
    frases = retorna_lista_frases(texto)
    palavras = []
    for frase in frases:
        palavras.extend([len(palavra) for palavra in separa_palavras(frase)])

    return sum(palavras) / len(palavras)

def calcula_type_token(texto: str) -> float:
    frases = retorna_lista_frases(texto)
    palavras = []
    for frase in frases:
        palavras.extend(separa_palavras(frase))
    return n_palavras_diferentes(palavras) / len(palavras)

def calcula_hapax_legomana(texto: str) -> float:
    frases = retorna_lista_frases(texto)
    palavras = []
    for frase in frases:
        palavras.extend(separa_palavras(frase))
    return n_palavras_diferentes(palavras) / n_palavras_unicas(palavras)

def calcula_tamanho_medio_sentenca(texto: str) -> float:
    average = []
    for item in separa_sentencas(texto):
        average.append(len(item))
    return median(average)

def calcula_complexidade_sentenca(texto: str) -> float:
    sentencas = separa_sentencas(texto)
    return len(retorna_lista_frases(texto)) / len(sentencas)

def calcula_tamanho_medio_frase(texto: str) -> float:
    tamanho_das_frases = [len(item) for item in retorna_lista_frases(texto)]
    return sum(tamanho_das_frases) / len(retorna_lista_frases(texto))

def retorna_lista_frases(texto: str) -> list:
    frases = []
    sentencas = separa_sentencas(texto)
    for item in sentencas:
        frases.extend(separa_frases(item))
    return frases

if __name__ == "__main__":
    assinatura = le_assinatira()
    textos = le_textos()
    result = avalia_textos(textos, assinatura)
    print(result)


from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth/', include('authentication.urls', namespace='auth')),
    path('', include('expenses.urls', namespace='expenses')),
    path('', include('income.urls', namespace='income')),
    path('preferences/', include('userpreferences.urls', namespace='preferences')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


#
# @lc app=leetcode id=567 lang=python3
#
# [567] Permutation in String
#

# @lc code=start
class Solution:
    # Prune 版本
    def checkInclusion(self, s1: str, s2: str) -> bool:
        mp, mp_sub = {}, {}
        start = 0

        for char in s1:
            mp_sub[char] = mp_sub.get(char, 0) + 1

        for end in range(len(s2)):
            char = s2[end]
            # 如果非验证集里，跳过，reset start and mp
            if char not in mp_sub:
                start = end + 1
                mp = {}
            else:
                # 如果在，添加，验证，缩窗口
                mp[char] = mp.get(char, 0) + 1
                if mp == mp_sub:
                    return True
                while mp[char] > mp_sub[char]:
                    if s2[start] in mp:
                        mp[s2[start]] -= 1
                        start += 1

        return False

# 粗暴一点的办法
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        # Step 1
        # 定义需要维护的变量
        # 因为和排列相关 (元素相同，顺序可以不同)，使用哈希表
        hashmap2 = {}

        # Step 1.1: 同时建立s1的哈希表 (这个哈希表不需要维护，为定值)
        hashmap1 = {}
        for char in s1:
            hashmap1[char] = hashmap1.get(char, 0) + 1

        # Step 2: 定义窗口的首尾端 (start, end)， 然后滑动窗口
        start = 0
        for end in range(len(s2)):
            # Step 3: 更新需要维护的变量 (hashmap2)， 如果hashmap1 == hashmap2，代表s2包含s1的排列，直接return
            tail = s2[end]
            hashmap2[tail] = hashmap2.get(tail, 0) + 1
            if hashmap1 == hashmap2:
                    return True

            # Step 4:
            # 根据题意可知窗口长度固定，所以用if
            # 窗口左指针前移一个单位保证窗口长度固定, 同时提前更新需要维护的变量 (hashmap2)
            if end >= len(s1) - 1:
                head = s2[start]
                hashmap2[head] -= 1
                if hashmap2[head] == 0:
                    del hashmap2[head]
                start += 1
        # Step 5： 没有在s2中找到s1的排列，返回False
        return False

# @lc code=end


# -*- coding:utf-8 -*-
# @Time     :2023/1/30 6:32 下午
# @Author   :CHNJX
# @File     :loader_swagger.py
# @Desc     :
import json
from os import path, listdir
from os.path import isdir

import six
import yaml

def get_loader(filename):
    if filename.endswith(('.json', '.yml', '.yaml')):
        loader = json.load if filename.endswith('.json') else yaml.load
    else:
        with open(filename, 'r', 'utf-8') as f:
            contents = f.read().strip()
            loader = json.load if contents[0] in ['{', '['] else yaml.load
    return loader

def modify_spec_data(field, spec_data, data):
    if not isinstance(spec_data, dict) or not isinstance(data, dict):
        return None
    for k, v in data.items():
        if k in spec_data[field]:
            spec_data[field][k].update(v)
        else:
            spec_data[field][k] = v

def get_ref_filepath(filename, ref_file):
    ref_file = path.normpath(path.join(path.dirname(filename), ref_file))
    return ref_file

def load_file(filename, spec_data):
    loader = get_loader(filename)
    with open(filename, 'r', encoding='utf-8') as f:
        data = loader(f) if filename.endswith('.json') else loader(f, yaml.Loader)
        spec_data.update(data)
        for field, values in six.iteritems(data):
            if field not in ['definitions', 'parameters', 'paths'] or not isinstance(values, dict):
                continue
            for _field, value in six.iteritems(values):
                if _field == '$ref' and value.endswith('.yml'):
                    _filepath = get_ref_filepath(filename, value)
                    field_data = load_swagger(_filepath)
                    spec_data[field] = field_data
                elif '$ref' in value:
                    v = value.pop('$ref', '')
                    if not v:
                        continue
                    _filepath = get_ref_filepath(filename, v)
                    field_data = load_swagger(_filepath)
                    modify_spec_data(field, spec_data, field_data)

def load_swagger(filename):
    spec_data = {}
    files = listdir(filename) if isdir(filename) else [filename]
    for f in files:
        if f != filename:
            f = filename + '/' + f
        load_file(f, spec_data)
    return spec_data


from django.test import TestCase
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from .models import Video

'''
reverse wil convert the name of the url into an actual path.

'''

class TestHomePageMessage(TestCase):

    def test_app_title_message_shown_on_home_page(self):
        url = reverse('home')
        response = self.client.get(url)
        self.assertContains(response, 'Music Videos')

class TestAddVideos(TestCase):

    def test_add_video(self):  # Adding a video, added to DB and video_id created.

        valid_video = {
            'name': 'Jon Spencer',
            'url': 'https://www.youtube.com/watch?v=IWY4gmbOz24',
            'notes': 'Song Worm Town'
        }
        url = reverse('add_video')
        response = self.client.post(url, data=valid_video, follow=True)  # follow will allow redirect to the youtube page to not error.

        self.assertTemplateUsed('video_collection/video_catalog.html')
        # does the video catelog show the new video
        self.assertContains(response, 'Jon Spencer' )
        self.assertContains(response, 'Song Worm Town')
        self.assertContains(response, 'https://www.youtube.com/watch?v=IWY4gmbOz24')

        video_count= Video.objects.count()
        self.assertEqual(1, video_count)  # checking database is getting added.

        video = Video.objects.first()

        self.assertEqual( 'Jon Spencer', video.name)
        self.assertEqual( 'Song Worm Town', video.notes)
        self.assertEqual( 'https://www.youtube.com/watch?v=IWY4gmbOz24', video.url)
        self.assertEqual( 'IWY4gmbOz24', video.video_id)

    def test_add_video_invalid_urls_not_added(self):

        invalid_video_urls = [
            'https://www.youtube.com/'
            'https://www.youtube.com/watch?'
            'https://www.youtube.com/watch?abc123'
            'https://www.youtube.com/watch?v='
            'https://www.youtube.com/watch'
            'https://minneapolis.edu'
            'https://minneapolis.edu?v=098786'
        ]
        for  invalid_video_url in  invalid_video_urls:

            new_video = {
                'name': 'example',
                'url':  invalid_video_url,
                'notes': 'example note'
            }
            url = reverse('add_video')
            response = self.client.post(url, new_video)

            self.assertTemplateNotUsed('video_collection/add.html')

            messages = response.context['messages']
            message_texts = [ message.message for message in messages]

            self.assertIn('Invalid YouTube URL', message_texts)
            self.assertIn('Please check that you enter data all in the fields.', message_texts)

        video_count= Video.objects.count()
        self.assertEqual(0, video_count)  # checking database is mot getting added to.

class TestVideoCatelog(TestCase):

    def test_all_videos_displayed_in_correct_order(self):

        v1 =Video.objects.create(name='ZYX', notes='example', url='https://www.youtube.com/watch?v=123')
        v2 =Video.objects.create(name='abc', notes='example', url='https://www.youtube.com/watch?v=124')
        v3 =Video.objects.create(name='AAA', notes='example', url='https://www.youtube.com/watch?v=125')
        v4 =Video.objects.create(name='lmn', notes='example', url='https://www.youtube.com/watch?v=126')

        expected_video_order = [v3,v2,v4,v1]  # simply list in order expected

        url = reverse('video_catalog')
        response = self.client.get(url)

        videos_in_template = list(response.context['videos'])

        self.assertEqual(videos_in_template, expected_video_order)

    def test_no_video_message(self):
        url = reverse('video_catalog')
        response = self.client.get(url)
        self.assertContains(response, 'No Videos')  # must match, same as empty in HTML template
        self.assertEqual(0, len(response.context['videos']))

    def test_one_video_number_message_one_video(self):
        v1 =Video.objects.create(name='ZYX', notes='example', url='https://www.youtube.com/watch?v=123')
        url = reverse('video_catalog')
        response = self.client.get(url)

        self.assertContains(response, '1 video')
        self.assertNotContains(response, '1 videos')

    def test_video_number_message_two_video(self):
        v1 =Video.objects.create(name='ZYX', notes='example', url='https://www.youtube.com/watch?v=123')
        v2 =Video.objects.create(name='abc', notes='example', url='https://www.youtube.com/watch?v=124')
        url = reverse('video_catalog')
        response = self.client.get(url)

        self.assertContains(response, '2 videos')

class TestVideoSearch(TestCase):

    pass

class TestVideoMode(TestCase):

    def test_invalid_url_raises_validation_error(self):
        invalid_video_urls = [
            'https://www.youtube.com/watch',
            'https://www.youtube.com/watch/somethingelse',
            'https://www.youtube.com/watch/somethingelse?v=1234567',
            'https://www.youtube.com/watch?',
            'https://www.youtube.com/watch?abc=123',
            'https://www.youtube.com/watch?v=',
            'https://github.com',
            '12345678',
            'htttttttttps://www.youtube.com/watch',
            'http://www.youtube.com/watch/somethingelse?v=1234567',
            'https://minneapolis.edu',
            'https://minneapolis.edu?v=123456'
        ]

        for  invalid_video_url in  invalid_video_urls:
            with self.assertRaises(ValidationError):
                Video.objects.create(name='example', url=invalid_video_url, notes='example note')

        self.assertEqual(0, Video.objects.count())

    def test_duplicate_video_raises_intgrety_error(self):
        v1 =Video.objects.create(name='ZYX', notes='example', url='https://www.youtube.com/watch?v=123')
        with self.assertRaises(IntegrityError):
            Video.objects.create(name='ZYX', notes='example', url='https://www.youtube.com/watch?v=123')


from django.core.exceptions import ValidationError

BLOCK_LIST = ['FUCK', 'SHIT', 'Omar']

# 1- Clear input and Block list
# 2- Sum
# 3- if has error
# 4- iterate invalid items

def block(value):
    # 1- Clear input and Block list
    init_value = f"{value}".lower()
    init_items = set(init_value.split())
    block_list = set(x.lower() for x in BLOCK_LIST)

    # 2- Sum
    valid_words = list(init_items & block_list)
    has_error = len(valid_words) > 0

    # 3- if has error
    if has_error:
        invalid_items = []
        # 4- iterate invalid items
        for i, word in enumerate(valid_words):
            invalid_items.append(ValidationError("%(value)s is word blocked", params={
                                 'value': word}, code=f"blocked-word-{i}"))
        raise ValidationError(invalid_items)

    return value

2- Models ( updated - expanded )/src/products/validators.py


from selenium import webdriver
from selenium.webdriver.common.by import By ## 추가
import re
driver = webdriver.Chrome('chromedriver.exe')

baseurl = 'https://www.kkc.or.kr/megazine/megazine_02.html?page='
lasturl = '&key='

namelist = [] # 크롤링 해온 이름을 넣을 list
# linelist =[] # 크롤링 해온 Line01 클래스를 넣을 list
# line2list =[] # 크롤링 해온 Line02 클래스를 넣을 list
namedict ={} # json 저장을 위해 dict 하나 생성

for i in range(14):
    if i == 0:
        continue
    driver.get(baseurl+str(i)+lasturl) #url을 분석한 결과 baseurl과 lasturl 사이에 숫자만 바뀌면 페이지가 넘어감
    name=driver.find_elements(By.CLASS_NAME,"kind") # 견종 이름 가져오기

    for j in name:
        namelist.append(j.text) # 가져온 견종 이름 namelist에 넣기 # 몇번? -> name만큼

    '''
    line =driver.find_elements(By.CLASS_NAME,'line01')
    for i in line:
        linelist.append(i.text)
    ''' # line01이라는 class에 있는 데이터(text) 가져오기 # 무슨 데이터야? -> 강아지의 원산지

    '''
    line2 = driver.find_elements(By.CLASS_NAME,'line02')
    for i in line2:
        linelist2.append(i.text)
    ''' # line02라는 class에 있는 데이터(text) 가져오기 # 무슨 데이터야? -> 강아지의 체고, 체중, 운동량, 그룹 모두 담겨 있음 ;;;

    # print(namelist) # 중간중간 namelist가 점점 늘어나는 걸 확인하는 용

#print(namelist) # 위 for 문 안에 넣으면 for문이 끝날때마다 출력되나, 여기에다가 print를 쓰면 결과만 만옴
#print(linelist)
#print(linelist2)

## 리스트에서 특정 문자열 제거
namelist2 =[]

for i in namelist :
    text = re.sub('[A-Z(/s]','',i).strip()
    namelist2.append(text)
print(namelist2)

for i in range(len(namelist2)): # list 만큼 dict에
    namedict[i] = namelist2[i] # 넣어줌
print(namedict) # 그 dict가 제대로 됐는지 확인

import json
with open("dognames.json",'w', encoding='utf-8') as file :
    json.dump(namedict,file, indent='\t', ensure_ascii=False) # dict를 json으로 저장


'''
Escribe un programa que pida al usuario una palabra y luego imprima la misma
palabra pero con las letras en orden inverso
'''

#OP 1
palabra = input("INGRESE UNA PALABRA: ")

#LIST() CREA LISTA DEL PARAMETRO
pl = list(palabra)

pl.reverse()

for x in pl:
	print(x)

#OP 2
palabra = input("Escriba cualquier palabra: ")

for i in range(len(palabra), 0, -1):
	print(palabra[i-1])


from univention.admin.layout import Tab, Group
import univention.admin.syntax
import univention.admin.filter
import univention.admin.handlers
import univention.admin.localization

translation=univention.admin.localization.translation('univention.admin.handlers.policies')
_=translation.translate

class dhcp_scopeFixedAttributes(univention.admin.syntax.select):
	name='dhcp_scopeFixedAttributes'
	choices=[
		('univentionDhcpUnknownClients',_('Unknown clients')),
		('univentionDhcpBootp',_('BOOTP')),
		('univentionDhcpBooting',_('Booting')),
		('univentionDhcpDuplicates',_('Duplicates')),
		('univentionDhcpDeclines',_('Declines'))
		]

module='policies/dhcp_scope'
operations=['add','edit','remove','search']

policy_oc="univentionPolicyDhcpScope"
policy_apply_to=["dhcp/service", "dhcp/subnet", "dhcp/host", "dhcp/sharedsubnet", "dhcp/shared"]
policy_position_dn_prefix="cn=scope,cn=dhcp"
policies_group="dhcp"
usewizard=1
childs=0
short_description=_('Policy: DHCP Allow/Deny')
policy_short_description=_('Allow/Deny')
long_description=''
options={
}
property_descriptions={
	'name': univention.admin.property(
			short_description=_('Name'),
			long_description='',
			syntax=univention.admin.syntax.policyName,
			multivalue=0,
			include_in_default_search=1,
			options=[],
			required=1,
			may_change=0,
			identifies=1,
		),
	'scopeUnknownClients': univention.admin.property(
			short_description=_('Unknown clients'),
			long_description=_('Dynamically assign addresses to unknown clients. Allowed by default. This option should not be used anymore.'),
			syntax=univention.admin.syntax.AllowDenyIgnore,
			multivalue=0,
			options=[],
			required=0,
			may_change=1,
			identifies=0
		),
	'bootp': univention.admin.property(
			short_description=_('BOOTP'),
			long_description=_('Respond to BOOTP queries. Allowed by default.'),
			syntax=univention.admin.syntax.AllowDenyIgnore,
			multivalue=0,
			options=[],
			required=0,
			may_change=1,
			identifies=0
		),
	'booting': univention.admin.property(
			short_description=_('Booting'),
			long_description=_('Respond to queries from a particular client. Has meaning only when it appears in a host declaration. Allowed by default.'),
			syntax=univention.admin.syntax.AllowDenyIgnore,
			multivalue=0,
			options=[],
			required=0,
			may_change=1,
			identifies=0
		),
	'duplicates': univention.admin.property(
			short_description=_('Duplicates'),
			long_description=_('If a request is received from a client that matches the MAC address of a host declaration, any other leases matching that MAC address will be discarded by the server, if this is set to deny. Allowed by default. Setting this to deny violates the DHCP protocol.'),
			syntax=univention.admin.syntax.AllowDeny,
			multivalue=0,
			options=[],
			required=0,
			may_change=1,
			identifies=0
		),
	'declines': univention.admin.property(
			short_description=_('Declines'),
			long_description=_("Honor DHCPDECLINE messages. deny/ignore will prevent malicious or buggy clients from completely exhausting the DHCP server's allocation pool."),
			syntax=univention.admin.syntax.AllowDenyIgnore,
			multivalue=0,
			options=[],
			required=0,
			may_change=1,
			identifies=0
		),
	'requiredObjectClasses': univention.admin.property(
			short_description=_('Required object classes'),
			long_description='',
			syntax=univention.admin.syntax.string,
			multivalue=1,
			options=[],
			required=0,
			may_change=1,
			identifies=0
			),
	'prohibitedObjectClasses': univention.admin.property(
			short_description=_('Excluded object classes'),
			long_description='',
			syntax=univention.admin.syntax.string,
			multivalue=1,
			options=[],
			required=0,
			may_change=1,
			identifies=0
			),
	'fixedAttributes': univention.admin.property(
			short_description=_('Fixed attributes'),
			long_description='',
			syntax=dhcp_scopeFixedAttributes,
			multivalue=1,
			options=[],
			required=0,
			may_change=1,
			identifies=0
			),
	'emptyAttributes': univention.admin.property(
			short_description=_('Empty attributes'),
			long_description='',
			syntax=dhcp_scopeFixedAttributes,
			multivalue=1,
			options=[],
			required=0,
			may_change=1,
			identifies=0
			),
}

layout = [
	Tab(_('Allow/Deny'), _('Allow/Deny/Ignore statements'), layout = [
		Group( _( 'General' ), layout = [
			'name',
			[ 'scopeUnknownClients', 'bootp' ],
			[ 'booting','duplicates' ],
			'declines'
		] ),
	] ),
	Tab(_('Object'),_('Object'), advanced = True, layout = [
		[ 'requiredObjectClasses' , 'prohibitedObjectClasses' ],
		[ 'fixedAttributes', 'emptyAttributes' ]
	] ),
]

mapping=univention.admin.mapping.mapping()
mapping.register('name', 'cn', None, univention.admin.mapping.ListToString)
mapping.register('scopeUnknownClients', 'univentionDhcpUnknownClients', None, univention.admin.mapping.ListToString)
mapping.register('bootp', 'univentionDhcpBootp', None, univention.admin.mapping.ListToString)
mapping.register('booting', 'univentionDhcpBooting', None, univention.admin.mapping.ListToString)
mapping.register('duplicates', 'univentionDhcpDuplicates', None, univention.admin.mapping.ListToString)
mapping.register('declines', 'univentionDhcpDeclines', None, univention.admin.mapping.ListToString)

mapping.register('requiredObjectClasses', 'requiredObjectClasses')
mapping.register('prohibitedObjectClasses', 'prohibitedObjectClasses')
mapping.register('fixedAttributes', 'fixedAttributes')
mapping.register('emptyAttributes', 'emptyAttributes')

class object(univention.admin.handlers.simplePolicy):
	module=module

	def __init__(self, co, lo, position, dn='', superordinate=None, attributes = [] ):
		global mapping
		global property_descriptions

		self.mapping=mapping
		self.descriptions=property_descriptions

		univention.admin.handlers.simplePolicy.__init__(self, co, lo, position, dn, superordinate, attributes )

	def _ldap_pre_create(self):
		self.dn='%s=%s,%s' % (mapping.mapName('name'), mapping.mapValue('name', self.info['name']), self.position.getDn())

	def _ldap_addlist(self):
		return [
			('objectClass', ['top', 'univentionPolicy', 'univentionPolicyDhcpScope'])
		]

def lookup(co, lo, filter_s, base='', superordinate=None, scope='sub', unique=0, required=0, timeout=-1, sizelimit=0):

	filter=univention.admin.filter.conjunction('&', [
		univention.admin.filter.expression('objectClass', 'univentionPolicyDhcpScope'),
		])

	if filter_s:
		filter_p=univention.admin.filter.parse(filter_s)
		univention.admin.filter.walk(filter_p, univention.admin.mapping.mapRewrite, arg=mapping)
		filter.expressions.append(filter_p)

	res=[]
	try:
		for dn, attrs in lo.search(unicode(filter), base, scope, [], unique, required, timeout, sizelimit):
			res.append( object( co, lo, None, dn, attributes = attrs ) )
	except:
		pass
	return res

def identify(dn, attr, canonical=0):

	return 'univentionPolicyDhcpScope' in attr.get('objectClass', [])


import inspect
import numpy as np
from collections import defaultdict
from sklearn.model_selection import StratifiedKFold
from helpers.classification.metrics import classification_metric
from helpers.utils.validators import validate_x_y_numpy_array, validate_x_y_observation_count
from helpers.utils.logger import Logger

@validate_x_y_numpy_array
@validate_x_y_observation_count
def cross_validate_classifier(X,
                              y,
                              model,
                              threshold=0.5,
                              metrics=("mcc", "acc", "sen", "spe"),
                              num_folds=10,
                              num_repetitions=20,
                              seed=42,
                              logger=None):
    """
    Cross-validate the binary classification model

    This function cross-validates the input classification model using X, y. The
    cross-validation is set by num_folds and num_repetitions. After the model is
    cross-validated, several metrics are computed.

    Parameters
    ----------

    X : numpy array
        2D feature matrix (rows=observations, cols=features)

    y : numpy array
        1D labels array

    model : class that implements fit, and predict methods
        Initialized binary classification model

    threshold : float, optional, default 0.5
        Threshold for encoding the predicted probability as a class label

    metrics : tuple, optional, default ("mcc", "acc", "sen", "spe")
        Tuple with classification metrics to compute

    num_folds : int, optional, default 10
        Number of cross-validation folds

    num_repetitions : int, optional, default 20
        Number of cross-validation runs

    seed : int, optional, default 42
        Random generator seed

    logger : Logger, optional, default None
        Logger class

    Returns
    -------

    Default dictionary with keys=metric names, vals=metric arrays

    Raises
    ------

    TypeError
        Raised when X or y is not an instance of np.ndarray

    ValueError
        Raised when X and y have not the same number of rows (observations)
    """

    # Prepare the logger
    logger = logger if logger else Logger(inspect.currentframe().f_code.co_name)

    # Prepare the results table for the cross-validation results
    table_cv_data = defaultdict(list)

    # Run the desired number of cross-validation repetitions
    for repetition in range(num_repetitions):
        for train_i, test_i in StratifiedKFold(n_splits=num_folds, random_state=seed, shuffle=True).split(X, y):

            # Split the data to train, test sets
            X_train, X_test = X[train_i], X[test_i]
            y_train, y_test = y[train_i], y[test_i]

            try:

                # fit the classifier
                model.fit(X_train, y_train)

                # Evaluate the classifier
                predicted = model.predict(X_test)

                # Encode the labels
                y_true = np.array(y_test, dtype=np.int16)
                y_pred = np.array([0 if y_hat < threshold else 1 for y_hat in predicted], dtype=np.int16)

                # Compute the classification metrics
                for metric in metrics:
                    computed = classification_metric(metric, y_true, y_pred)
                    computed = computed if computed and np.isfinite(computed) else None
                    if computed:
                        table_cv_data[metric].append(computed)

            except Exception as e:
                if "Input contains NaN, infinity or a value too large" in str(e):
                    logger.warning("Poor performance detected, skipping current validation fold")
                    continue
                else:
                    logger.exception(e)

    return table_cv_data


# python3

def parallel_processing(n, m, data):
    output = []
    next = 0
    time = [0] * n
    for i in range(m):
        thread = next
        start_time = time[thread]
        end_time = start_time + data[i]
        time[thread] = end_time
        next = (next + 1) % n
        output.append((thread, start_time))
    return output

def main():
    n , m = map(int, input(">:: \t").split())
    data = list(map(int, input(">:: \t").split()))
    result = parallel_processing(n,m,data)
    for i,j in result:
        print(i, j)

if __name__ == "__main__":
    main()


import math
import os

import numpy
import requests

import numpy as np
from astropy.table import Table
from astroquery.sdss import SDSS
from astropy import coordinates as coords
import logging
_logger = logging.getLogger(__name__)

class atlas_refcat2:
    ''' Interface to query consolidated sqlite3 db file that was generated from Tonry (2018) refcat2
    '''

    FILTERMAPPING = {}
    FILTERMAPPING['up'] = {'refMag': 'umag', 'colorTerm': 0.0, 'airmassTerm': 0.59, 'defaultZP': 0.0}
    FILTERMAPPING['gp'] = {'refMag': 'gmag', 'colorTerm': 0.0, 'airmassTerm': 0.14, 'defaultZP': 0.0}
    FILTERMAPPING['rp'] = {'refMag': 'rmag', 'colorTerm': 0.0, 'airmassTerm': 0.08, 'defaultZP': 0.0}
    FILTERMAPPING['ip'] = {'refMag': 'imag', 'colorTerm': 0.0, 'airmassTerm': 0.06, 'defaultZP': 0.0}
    FILTERMAPPING['zp'] = {'refMag': 'zmag', 'colorTerm': 0.0, 'airmassTerm': 0.04, 'defaultZP': 0.0}
    FILTERMAPPING['zs'] = {'refMag': 'zmag', 'colorTerm': 0.0, 'airmassTerm': 0.04, 'defaultZP': 0.0}
    FILTERMAPPING['Y'] = {'refMag': 'ymag', 'colorTerm': 0.0, 'airmassTerm': 0.03, 'defaultZP': 0.0}
    FILTERMAPPING['U'] = {'refMag':  'U', 'colorTerm': 0.0, 'airmassTerm': 0.54, 'defaultZP': 0.0}
    FILTERMAPPING['B'] = {'refMag':  'B', 'colorTerm': 0.0, 'airmassTerm': 0.23, 'defaultZP': 0.0}
    FILTERMAPPING['V'] = {'refMag':  'V', 'colorTerm': 0.0, 'airmassTerm': 0.12, 'defaultZP': 0.0}
    FILTERMAPPING['R'] = {'refMag':  'R', 'colorTerm': 0.0, 'airmassTerm': 0.09, 'defaultZP': 0.0}
    FILTERMAPPING['Rc'] = {'refMag':  'R', 'colorTerm': 0.0, 'airmassTerm': 0.09, 'defaultZP': 0.0}
    FILTERMAPPING['I'] = {'refMag':  'I', 'colorTerm': 0.0, 'airmassTerm': 0.04, 'defaultZP': 0.0}

    ###  PS to SDSS color transformations according to  Finkbeiner 2016
    ###  http://iopscience.iop.org/article/10.3847/0004-637X/822/2/66/meta#apj522061s2-4 Table 2
    ###  Note that this transformation is valid for stars only. For the purpose of photometric
    ###  calibration, it is desirable to select point sources only from the input catalog.

    ## Why reverse the order of the color term entries? Data are entered in the order as they are
    ## shown in paper. Reverse after the fact to avoid confusion when looking at paper

    ps1colorterms = {}
    ps1colorterms['umag'] = [+0.04438, -2.26095, -0.13387, +0.27099][::-1]
    ps1colorterms['gmag'] = [-0.01808, -0.13595, +0.01941, -0.00183][::-1]
    ps1colorterms['rmag'] = [-0.01836, -0.03577, +0.02612, -0.00558][::-1]
    ps1colorterms['imag'] = [+0.01170, -0.00400, +0.00066, -0.00058][::-1]
    ps1colorterms['zmag'] = [-0.01062, +0.07529, -0.03592, +0.00890][::-1]
    ps1colorterms['ymag'] = [+0.08924, -0.20878, 0.10360,  -0.02441][::-1]
    JohnsonCousin_filters = ['B', 'V', 'R', 'I', 'U']

    def __init__(self, refcat2_url):
        self.refcat2_url = refcat2_url

    def isInCatalogFootprint(self, ra, dec):
        return True

    def SDSS2Johnson (self, table):
        """ Based on Jordi, Grebel, & Ammon 2005  http://www.sdss3.org/dr8/algorithms/sdssUBVRITransform.php
        """

        transformations={}
        # 0 -> sdss base mag
        # 1,2 -> sdss color to use
        # 3 -> color term
        # 4 -> zero point
        transformations['B'] = ['gmag', 'gmag', 'rmag',  0.313,  0.219]
        transformations['V'] = ['gmag', 'gmag', 'rmag', -0.565, -0.016]
        transformations['R'] = ['rmag', 'rmag', 'imag', -0.153, -0.117]
        transformations['I'] = ['imag', 'imag', 'zmag', -0.386, -0.397]
        transformations['U'] = ['B'   , 'umag', 'gmag', +0.79,  -0.93]

        for filter in transformations:
            transformation = transformations[filter]
            table.add_column(numpy.NaN, name=filter)
            table.add_column(numpy.NaN, name=f'{filter}err')
            table[filter] = table [transformation[0]] + (table[transformation[1]] - table[transformation[2]]) * transformation[3] + transformation[4]
            table[f'{filter}err'] = 0
        return table

    def PStoSDSS(self, table):
        """
        Modify table in situ from PS1 to SDSS, requires column names compatible with ps1colorterms definition.

        :param table:
        :return: modified table.
        """
        if table is not None:
            pscolor = table['gmag'] - table['imag']
            for filter in self.ps1colorterms:
                colorcorrection = np.polyval(self.ps1colorterms[filter], pscolor)
                if filter == "umag":
                    table['umag'] = table['gmag'] - colorcorrection
                    table['umagerr'] = table['gmagerr']
                elif filter == 'ymag':
                    table['ymag'] = table['zmag'] - colorcorrection
                    table['ymagerr'] = table['zmagerr']
                else:
                    table[filter] -= colorcorrection

        return table

    def get_reference_catalog(self, ra, dec, radius, generateJohnson = False):
        " Read region of interest from the catalog"
        try:
            response = requests.get(self.refcat2_url + 'radius', params={'ra': ra, 'dec': dec, 'radius': radius})
            response.raise_for_status()
            table = Table(response.json())
        except Exception as e:
            _logger.exception(f"While trying to read from refcat2: {e}")
            return None

        table = self.PStoSDSS(table)

        if generateJohnson:
            table = self.SDSS2Johnson(table)

        return table


from lab_python_oop import Circle, Rectangle, Square, Color
from lab_python_oop.AF import Figure
from datetime import datetime

def main():
    BLUE = Color.Color("Синий")
    GREEN = Color.Color("Зелёный")
    RED = Color.Color("Красный")

    r = Rectangle.Rectangle(2,2,BLUE)
    print(f"{r}")
    print("="*60)
    c = Circle.Circle(2, GREEN)
    print(f"{c}")
    print("="*60)
    s = Square.Square(2,RED)
    print(f"{s}")
    print("="*60)

    print(f"Текущая дата: {datetime.now()}") #получение текущего времени

if __name__ == "__main__":
    main()


import copy

env = {}
s = 0

watcher_s = 0

class IF_COND:

	# expr: Bedingung unter der der if-Block ausgeführt wird
	# if_stat: Programmcode der ausgeführt wird wenn expr == True
	# fl_stat: Der immer auf den if-Block folgende Code
	def __init__(self, expr, if_stat, fl_stat):
		self.expr = expr
		self.if_stat = if_stat
		self.fl_stat = fl_stat

	def ausgabe(self, v):
		return v * " " + "IF\n" + self.expr.ausgabe(v + 1) + "\n" + self.if_stat.ausgabe(
			v + 2) + "\n" + self.fl_stat.ausgabe(v)

class WHILE:

	# expr: Bedingung unter der der while-Block ausgeführt wird
	# wh_stat: Programmcode der ausgeführt wird wenn expr == True
	# fl_stat: Der immer auf den if-Block folgende Code
	def __init__(self, expr, wh_stat, fl_stat):
		self.expr = expr
		self.wh_stat = wh_stat
		self.fl_stat = fl_stat

	def ausgabe(self, v):
		return v * " " + "WHILE\n" + self.expr.ausgabe(v + 1) + "\n" + self.wh_stat.ausgabe(
			v + 1) + "\n" + self.fl_stat.ausgabe(v)

class ASSIGN:

	# id: Name der Variable
	# expr: Wert der Variable (bisher nur integer)
	# fl_stat: Die folgenden Statements
	def __init__(self, id, expr, fl_stat):
		self.id = id
		self.expr = expr
		self.fl_stat = fl_stat

	def ausgabe(self, v):
		return v * " " + "ASSIGN\n" + self.id + "\n" + self.expr.ausgabe(v + 1) + "\n" +\
			   self.fl_stat.ausgabe(v)

	def generiere_asm(self):
		global s

		asm = self.expr.generiere_asm()

		# Speicher Offset von $sp zu der Variable
		env[self.id] = s
		# Verschiebe Offset um 4 Byte
		s -= 4

		asm += self.fl_stat.generiere_asm()

		return asm

class FL_STAT:

	def __init__(self, fl_stat):
		self.fl_stat = fl_stat # Das hier ist ein String, soll aber nicht

	def ausgabe(self, v):
		if self.fl_stat == "END":
			return self.fl_stat
		else:
			return self.fl_stat.ausgabe(v)

	def generiere_asm(self):
		if self.fl_stat == "END":
			return "\n"
		else:
			return self.fl_stat.generiere_asm()

class START:

	def __init__(self, fl_stat):
		self.fl_stat = fl_stat

	def ausgabe(self):
		print(self.fl_stat.ausgabe(0))

class EXPRm1:
	def __init__(self, e0, comparandm1=None):
		self.e0 = e0
		self.comparandm1 = comparandm1

	def ausgabe(self, v):
		ausgabe = v * " "
		if self.comparandm1 != None:
			ausgabe = "==\n" + self.comparandm1.ausgabe(v)
		return self.e0.ausgabe(v + 1) + ausgabe

	def generiere_asm(self):
		return self.e0.generiere_asm()

class EXPR0:

	# EXPR0 nimmt Instanz von Typ EXPR1 (e1)
	# summand0: optionaler Summand von Typ (e0)
	def __init__(self, e1, summand0=None):
		self.e1 = e1
		self.summand0 = summand0

	def ausgabe(self, v):
		ausgabe = v * " "
		if self.summand0 != None:
			ausgabe = "+\n"+self.summand0.ausgabe(v + 1)
		return self.e1.ausgabe(v + 1)+ausgabe

	def generiere_asm(self):
		global s
		global watcher_s
		#--Erinnerung:--#
		# Stack-Pointer wird in ASSIGN.generiere_asm() dekrementiert

		# Speicher den Wert von dem linken Summant in $t0
		asm = self.e1.generiere_asm()

		# Speicher den Wert von $t0 in den Stack an 0($sp)
		asm += "sw $t0 "+str(s)+"($sp)\n"

		# Wenn ein rechter Summant vorhanden ist dann mache das:
		if self.summand0 != None:
			# Der Offset wird geupdatet um den nächsten RAM Eintrag weiter unten im Stack zu speichern
			s -= 4
			# Speicher den Wert des rechten Summanten in $t0
			asm += self.summand0.generiere_asm()

			# Der Offset wird geupdatet um wieder wie normal auf den oberen Eintrag im Stack zuzugreifen
			s += 4
			# Speicher den Wert in 0($sp) in $t1
			asm += "lw $t1 "+str(s)+"($sp)\n"

			# Addiere den Wert in $t0 udn in $t1 in $t0
			asm += "add $t0 $t0 $t1\n"

			# Speicher den Wert von $t0 in 0($sp)
			asm += "sw $t0 "+str(s)+"($sp)"+"\n"

		return asm

class EXPR1:

	# EXPR1 nimmt Instanz von Typ EXPR2 (e2)
	# factor1: optionaler Faktor von Typ EXPR1 (factor1)
	def __init__(self, e2, factor1=None):
		self.e2 = e2
		self.factor1 = factor1

	def ausgabe(self, v):
		ausgabe = v * " "
		if self.factor1 != None:
			ausgabe = "*\n"+self.factor1.ausgabe(v + 1)
		return self.e2.ausgabe(v + 1)+ausgabe

	def generiere_asm(self):
		global s
		global watcher_s
		#--Erinnerung:--#
		# Stack-Pointer wird in ASSIGN.generiere_asm() dekrementiert

		# Speicher den Wert von dem linken Faktor in $t0
		asm = self.e2.generiere_asm()

		# Speicher den Wert von $t0 in den Stack an 0($sp)
		asm += "sw $t0 "+str(s)+"($sp)\n"

		# Wenn ein rechter Faktor vorhanden ist dann mache das:
		if self.factor1 != None:
			# Der Offset wird geupdatet um den nächsten RAM Eintrag weiter unten im Stack zu speichern
			s -= 4

			# Speicher den Wert des rechten Faktor in $t0
			asm += self.factor1.generiere_asm()

			# Der Offset wird geupdatet um wieder wie normal auf den oberen Eintrag im Stack zuzugreifen
			s += 4
			# Speicher den Wert in 0($sp) in $t1
			asm += "lw $t1 "+str(s)+"($sp)\n"

			# Addiere den Wert in $t0 udn in $t1 in $t0
			asm += "mul $t0 $t0 $t1\n"

			# # Speicher den Wert von $t0 in 0($sp)
			# asm += "sw $t0 "+str(s)+"($sp)\n"

		return asm

class EXPR2:

	# EXPR2 nimmt entweder einen negative Instanz von Typ EXPR2 (negated2)
	# oder nimmt Instanz von Typ EXPR3 (e3)
	# Keine Rechnung
	def __init__(self, negated2=None, e3=None):
		self.negated2 = negated2
		self.e3 = e3

	def ausgabe(self, v):
		if self.negated2 != None:
			ausgabe = "\n-" +self.negated2.ausgabe(v + 1)
		else:
			ausgabe = self.e3.ausgabe(v + 1)
		return v * " " + ausgabe

	def generiere_asm(self):
		if self.negated2 != None:
			asm = self.negated2.generiere_asm()
		else:
			asm = self.e3.generiere_asm()
		return asm

class EXPR3:

	# Entweder Variablenname (ident), Zahl (lit) oder eingeklammerte Instanz von Typ EXPR0 (e0)
	def __init__(self, ident=None, lit=None, e0=None):
		self.ident = ident
		self.lit = lit
		self.e0 = e0

	def ausgabe(self, v):
		if self.ident != None:
			ausgabe = self.ident
		elif self.lit != None:
			ausgabe = self.lit
		else:
			ausgabe = "(\n" + self.e0.ausgabe(v + 1) + "\n" + v * " " + ")"
		return v * " " + ausgabe

	def generiere_asm(self):
		asm = ""
		if self.ident != None:
			#
			voffset = env[self.ident]
			asm = "lw $t0 "+str(voffset)+"($sp)\n"
			#asm = "li $t0 5\n"
		elif self.lit != None:
			asm = "li $t0 "+self.lit+"\n"
		else:
			asm = self.e0.generiere_asm()
		return asm


nmes=[1,2,3,4,5,6,7,8,9,10,11,12]
m30=[1,3,5,7,8,10,12]
m31=[4,6,9,11]

def fecha(d,m,a):
        if bisiesto(a)=='no' and m==2 and d==29:
            return "fecha incorrecta"
        elif m==2 and d <= 29:
                return "fecha correcta"
        elif m in m30 and d <= 30:
            return "fecha correcta"
        elif m in m31 and d <=31:
            return "fecha correcta"
        else:
            return "fecha incorrecta"

def bisiesto(año):
    if not año%4:
        return "si"
    else:
        return "no"

if __name__=="__main__":
    print(fecha(int(input("Introduzca el dia de la fecha a comprobar: ")),int(input("Introduzca el mes de la fecha a comprobar: ")),int(input("Introduzca el año de la fecha a comprobar: "))))


from fastapi import APIRouter, Depends, status, HTTPException, Response
from sqlalchemy.orm import Session

from .. import model, schemas, database, oauth2

router = APIRouter(prefix="/vote", tags=["Vote"])

@router.post("/", status_code=status.HTTP_201_CREATED)
def vote(
    vote: schemas.Vote,
    db: Session = Depends(database.get_db),
    user_id: schemas.TokenData = Depends(oauth2.get_current_user),
):
    vote_query = db.query(model.Vote).filter(
        model.Vote.post_id == vote.post_id, model.Vote.user_id == user_id.id
    )
    found_vote = vote_query.first()
    if vote.dir == 1:
        if found_vote:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT, detail="Already voted"
            )
        new_vote = model.Vote(post_id=vote.post_id, user_id=user_id.id)
        db.add(new_vote)
        db.commit()
        return {"message": "successfully added vote"}
    if not found_vote:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT, detail="vote not exists"
        )
    vote_query.delete(synchronize_session=False)
    db.commit()
    return {"message": "successfully deleted vote"}


import tkinter as tk
from tkinter import simpledialog
from tkinter import *
from tkinter import messagebox

def get_wordmaster_answers():
    words = set()
    with open("words.txt", "r") as f:
        for line in f:
            words.add(line.strip())
    return words

possible = get_wordmaster_answers()

alpha = "abcdefghijklmnopqrstuvwxyz"
valid = "012"

window = Tk()
window.geometry('600x300')
window.title("Wordle Info")

header = Label(window, text="~~~Info based upon Wordle progress~~~", font=("Arial Bold", 20))
header.grid(column=0, row=0)

# ~~~~~~~~~~~~~~~~~~~~~~~~~~ GUESS STUFF ~~~~~~~~~~~~~~~~~~~~~~~~~~~
wordPrompt = Label(window, text = "Input your word: ")
wordPrompt.grid(column = 0, row = 1)

word = Entry(window,width=10)
word.grid(column=1, row=1)

guessInfo = Label(window, text = "")
guessInfo.grid(column = 0, row = 2)

def clickedOK():
    status = 0
    guess = word.get().lower()
    # make sure it's letters only
    for let in guess:
        if let not in alpha:
            status = 1
    # and that it's 5 letters
    if len(guess) == 5 and status == 0:
        res = "Your guess was " + guess.upper()
        guessInfo.configure(text = res)
    else:
        guessInfo.configure(text = "Your guess must be 5 letters. Try again.")

def clickedCONFIRM():
    guess = word.get().lower()
    status = 0
    for let in guess:
        if let not in alpha:
            status = 1
    if len(guess) == 5 and status ==0:
        global currentGuess
        currentGuess = guess
    else:
        guessInfo.configure(text = "Your guess must be 5 letters. Try again.")

btOK = Button(window, text = "OK", command = clickedOK)
btOK.grid(column = 2, row = 1)

btCONFIRM = Button(window, text = "CONFIRM", command = clickedCONFIRM)
btCONFIRM.grid(column = 1, row = 2)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# ~~~~~~~~~~~~~~~~~~~~~~~~~~ FEEDBACK STUFF ~~~~~~~~~~~~~~~~~~~~~~~~
feedbackPrompt = Label(window, text = "Input the feedback you recieved: \n (0 = gray, 1 = yellow, 2 = green)")
feedbackPrompt.grid(column = 0, row = 3)

feedback = Entry(window,width=10)
feedback.grid(column=1, row=3)

feedbackInfo = Label(window, text = "")
feedbackInfo.grid(column = 0, row = 4)

def clickedOK2():
    status = 0
    info = feedback.get()
    # make sure it's 0,1,2 only
    for num in info:
        if num not in valid:
            status = 1
    # and that it's 5 letters
    if len(info) == 5 and status == 0:
        colored = [0 for i in range(5)]
        for i in range(5):
            if info[i] == "0":
                colored[i] = "GRAY"
            if info[i] == "1":
                colored[i] = "YELLOW"
            if info[i] == "2":
                colored[i] = "GREEN"
        colorstr = ", ".join(colored)
        res = "Your feedback was: [" + (colorstr) +"]"
        feedbackInfo.configure(text = res)
    else:
        feedbackInfo.configure(text = "Your guess must be 5 digits - 0, 1, or 2. Try again.")

btOK2 = Button(window, text = "OK", command = clickedOK2)
btOK2.grid(column = 2, row = 3)

def clickedCONFIRM2():
    info = feedback.get()
    if len(info) == 5:
        colored = [0,0,0,0,0]
        for i in range(5):
            if info[i] == "0":
                colored[i] = "GRAY"
            if info[i] == "1":
                colored[i] = "YELLOW"
            if info[i] == "2":
                colored[i] = "GREEN"
        global currentInfo
        currentInfo = colored
    else:
        feedbackInfo.configure(text = "Your guess must be 5 digits - 0, 1, or 2. Try again.")

btCONFIRM2 = Button(window, text = "CONFIRM", command = clickedCONFIRM2)
btCONFIRM2.grid(column = 1, row = 4)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# ~~~~~~~~~~~~~~~~~~~~ POSSIBILITIES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
number = str(len(possible))
possibleInfo = Label(window, text = "There are currently " + number + " possible words.")
possibleInfo.grid(column = 0, row = 6)

possiblePrompt = Label(window, text = "Would you like to see the new number of possibilities?")
possiblePrompt.grid(column = 0, row = 7)

possibleFeedback = Label(window, text = "")
possibleFeedback.grid(column = 0, row = 8)

def updatePossible(currentGuess, currentInfo):
    global possible
    temppos = possible.copy()
    for i in range(5):
        letter = currentGuess[i]
        # is there a green(s)? remove every word without that letter in that spot
        if currentInfo[i] == "GREEN":
            for word in possible:
                if word[i] != letter:
                    temppos.remove(word)
            possible = temppos.copy()

        # is there a yellow? remove every word without that letter at all
        elif currentInfo[i] == "YELLOW":
            for word in possible:
                if letter not in word:
                    temppos.remove(word)
                elif word[i] == letter:
                    temppos.remove(word)
            possible = temppos.copy()

        # a gray? remove every word with that letter
        elif currentInfo[i] == "GRAY":
            # duplicate letter - ignore tihs one, look at the next since gray
            if letter in currentGuess[i+1:]:
                break

            for word in possible:
                if letter in word:
                    temppos.remove(word)
            possible = temppos.copy()

    newNumber = str(len(possible))
    possibleInfo.configure(text = "There are now " + newNumber + " possible words.")

def clickedYES():
    status = 0
    if 'currentGuess' not in globals():
        status += 1
    if 'currentInfo' not in globals():
        status += 2
    if status == 1:
        possibleFeedback.configure(text ="Ruh-roh. You never confirmed your word.")
    if status == 2:
        possibleFeedback.configure(text = "Ruh-roh. You never confirmed your feedback.")
    if status == 3:
        possibleFeedback.configure(text ="Ruh-roh. You never confirmed your word or feedback.")
    if status == 0:
        possibleFeedback.configure(text="")
        updatePossible(currentGuess, currentInfo)

btYES = Button(window, text = "YES", command = clickedYES)
btYES.grid(column = 1, row = 7)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

word.focus()
window.mainloop()

# TODO: fix the same things that are wrong in wordleinfo.py


K = int(input())
directions = []
widths = []
dtemp = []
wtemp = []
for i in range(6) :
    d, w = map(int, input().split())
    if directions.count(d) > 0 :
        index = directions.index(d)
        oldWidth = widths[index]
        dtemp.append(d)
        if w < oldWidth :
            wtemp.append(w)
        else :
            directions.remove(d)
            directions.append(d)
            widths[index] = w
            wtemp.append(oldWidth)
    else  :
        directions.append(d)
        widths.append(w)
# print(f"directions = {directions}")
# print(f"widths = {widths}")
# print(f"dtemp = {dtemp}")
# print(f"wtemp = {wtemp}")
templi = [x for x in directions if x not in dtemp]
bigSquare = widths[directions.index(templi[0])] * widths[directions.index(templi[1])]
smallSquare = wtemp[0] * wtemp[1]
result = (bigSquare - smallSquare) * K
print(result)
# print(f"({bigSquare} - {smallSquare}) * {K} = {(bigSquare - smallSquare) * K}")


from step_2_ttl_triple_creator import triples_list

# IMPORTANT: CHANGE FILE NAME WITH EACH NEW VERSION IF THE FILE IS TO BE IMPORTED TO PROTEGE.
# Protege does not always understand that this is a new file if the file name is the same with a previously imported file.
file_obj = open("Output//pure_bib_head_100k_0.8.3.ttl", "w")
# file_obj = open("Output//pure_bib_limited_0.6.5.ttl", "w")  # use for test version

for each_triple in triples_list:
    file_obj.write(each_triple)
    file_obj.write('\n')

print ("Success: The triples are written to the specified file.")

# NOTE: Check the integrity of the produced .ttl file in command line
# > ttl <path to file>
# e.g.,
# > ttl .\pure_bib_head_100k_0.7.0.ttl
# If ttl validator is not installed, it can be obtained from:
# https://github.com/IDLabResearch/TurtleValidator
# (or, npm install -g turtle-validator)


# 90%대에서 틀렸습니다. 예외 케이스 존재

import sys
from collections import deque
n, m = map(int, sys.stdin.readline().split())

a = [list(map(int, sys.stdin.readline().split())) for i in range(n)]
d = [[0]*m for i in range(n)]
q = deque()
q.append((a[0][0], 0, 0))
d[0][0] = a[0][0]
while q:
    candy, r, c = q.popleft()
    for dr, dc in ((1,0),(0,1),(1,1)):
        nr = r + dr
        nc = c + dc
        if nr < 0 or nc < 0 or nr >= n or nc >= m: continue
        if d[r][c] + a[nr][nc] > d[nr][nc]:
            d[nr][nc] = d[r][c] + a[nr][nc]
            q.append((d[nr][nc], nr, nc))

print(d[n-1][m-1])


from ..common import *

class TD_M2M_NH_44(CoAPTestCase):
    """

TD_M2M_NH_44:
    cfg: M2M_CFG_01
    obj: AE creates a <contentInstance> resource in each group member
    pre:
      - A group is created containing 2 members of type <container>
    ref: 'TS-0001 [1], clause 10.2.7.6; TS-0004 [2], clause 7.3.14.3.1'
    seq:
    - s:
      - 'AE is requested to send a Create Request to create <contentInstance> in each group member'
      - - Type = 0 (CON)
        - Code = 2 (POST)
        - Content-format option
        - Non-empty Payload

    - c:
      - 'Sent POST request contains'
      - - Type=0 and Code=2
        - Uri-Host = IP address or the FQDN of registrar CSE
        - Uri-Path = {CSEBaseName}/{group}/fanoutPoint
        - content-type=application/vnd.oneM2M-res+xml or application/vnd.oneM2M-res+json
        - oneM2M-TY=4
        - oneM2M-FR=AE-ID
        - oneM2M-RQI=token-string (-> CRQI)
        - Non-empty Payload

    - v:
        - 'Check if possible that the <contentInstance> resource is created in each member hosting CSE'

    - c:
        - 'Registrar CSE sends response containing'
        - - Code=2.01(Created)
          - oneM2M-RSC=2001
          - oneM2M-RQI=CRQI
          - Non-empty Payload:aggregated response

    - v:
      - 'AE indicates successful operation'

    """

    @classmethod
    @typecheck
    def get_stimulis(cls) -> list_of(Value):
        """
        Get the stimulis of this test case. This has to be be implemented into
        each test cases class.

        :return: The stimulis of this TC
        :rtype: [Value]

        .. note::
            Check the number/value of the uri query options or not?
        """
        return [
            CoAP(type='con', code='post')
        ]

    def run (self):
        self.match('client', CoAP (type="con", code="post",pl=Not(b'')), 'fail')
        self.match('client', CoAP(opt=Opt(CoAPOptionContentFormat())), 'fail')
        self.match('client', CoAP(opt=Opt(CoAPOptionOneM2MFrom())), 'fail')
        self.match('client', CoAP(opt=Opt(CoAPOptionOneM2MTY('4'))), 'fail')

        if self.match('client', CoAP(opt=Opt(CoAPOptionOneM2MRequestIdentifier())), 'fail'):
            CMID = self.coap['mid']
            CTOK = self.coap['tok']
            OPTS = self.coap['opt']
            RI = OPTS[CoAPOptionOneM2MRequestIdentifier]
            RIVAL = RI[2]

            self.next()

            self.match('server', CoAP(code=2.01, mid=CMID, tok=CTOK, pl=Not(b'')), 'fail')
            self.match('server', CoAP(opt=Opt(CoAPOptionContentFormat())), 'fail')
            self.match('server', CoAP(opt=Opt(CoAPOptionOneM2MResponseStatusCode('2001'))), 'fail')
            self.match('server', CoAP(opt=Opt(CoAPOptionOneM2MRequestIdentifier(RIVAL))), 'fail')
            self.match('server', CoAP(opt=Opt(CoAPOptionLocationPath())), 'fail')


from time import time
from typing import Type, TypeVar, MutableMapping, Any, Iterable, Generator, Union
import arrow
import datetime
import math

from datapipelines import (
    DataSource,
    PipelineContext,
    Query,
    NotFoundError,
    validate_query,
)

from .common import KernelSource, APINotFoundError
from ...data import Platform, Queue, QUEUE_IDS
from ...dto.match import MatchDto, MatchListDto, TimelineDto
from ..uniquekeys import convert_region_to_platform

T = TypeVar("T")

def _get_current_time(
    query: MutableMapping[str, Any], context: PipelineContext = None
) -> int:
    return int(time()) * 1000

class MatchAPI(KernelSource):
    @DataSource.dispatch
    def get(
        self,
        type: Type[T],
        query: MutableMapping[str, Any],
        context: PipelineContext = None,
    ) -> T:
        pass

    @DataSource.dispatch
    def get_many(
        self,
        type: Type[T],
        query: MutableMapping[str, Any],
        context: PipelineContext = None,
    ) -> Iterable[T]:
        pass

    _validate_get_match_query = (
        Query.has("id").as_(int).also.has("platform").as_(Platform)
    )

    @get.register(MatchDto)
    @validate_query(_validate_get_match_query, convert_region_to_platform)
    def get_match(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> MatchDto:
        parameters = {"platform": query["platform"].value}
        endpoint = "lol/match/v4/matches/{id}".format(id=query["id"])
        try:
            data = self._get(endpoint=endpoint, parameters=parameters)
        except APINotFoundError as error:
            raise NotFoundError(str(error)) from error

        data["gameId"] = query["id"]
        data["region"] = query["platform"].region.value
        for p in data["participantIdentities"]:
            aid = p.get("player", {}).get("currentAccountId", None)
            if aid == 0:
                p["player"]["bot"] = True
        return MatchDto(data)

    _validate_get_many_match_query = (
        Query.has("ids").as_(Iterable).also.has("platform").as_(Platform)
    )

    @get_many.register(MatchDto)
    @validate_query(_validate_get_many_match_query, convert_region_to_platform)
    def get_many_match(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> Generator[MatchDto, None, None]:
        def generator():
            parameters = {"platform": query["platform"].value}
            for id in query["ids"]:
                endpoint = "lol/match/v4/matches/{id}".format(id=id)
                try:
                    data = self._get(endpoint=endpoint, parameters=parameters)
                except APINotFoundError as error:
                    raise NotFoundError(str(error)) from error

                for participant in data["participants"]:
                    participant.setdefault("runes", [])
                for p in data["participantIdentities"]:
                    aid = p.get("player", {}).get("currentAccountId", None)
                    if aid == 0:
                        p["player"]["bot"] = True

                data["gameId"] = id
                data["region"] = query["platform"].region.value
                yield MatchDto(data)

        return generator()

    _validate_get_match_list_query = (
        Query.has("accountId")
        .as_(str)
        .also.has("platform")
        .as_(Platform)
        .also.has("beginTime")
        .as_(int)
        .also.can_have("endTime")
        .as_(int)
        .also.has("beginIndex")
        .as_(int)
        .also.has("maxNumberOfMatches")
        .as_(float)
        .also.can_have("champion.ids")
        .as_(Iterable)
        .also.can_have("queues")
        .as_(Iterable)
    )

    @get.register(MatchListDto)
    @validate_query(_validate_get_match_list_query, convert_region_to_platform)
    def get_match_list(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> MatchListDto:
        parameters = {"platform": query["platform"].value}

        riot_index_interval = 100
        riot_date_interval = datetime.timedelta(days=7)

        begin_time = query["beginTime"]  # type: arrow.Arrow
        end_time = query.get("endTime", arrow.now())  # type: arrow.Arrow
        if isinstance(begin_time, int):
            begin_time = arrow.get(begin_time / 1000)
        if isinstance(end_time, int):
            end_time = arrow.get(end_time / 1000)

        def determine_calling_method(begin_time, end_time) -> str:
            """Returns either "by_date" or "by_index"."""
            matches_per_date_interval = 10  # This is an assumption
            seconds_per_day = 60 * 60 * 24
            riot_date_interval_in_days = (
                riot_date_interval.total_seconds() / seconds_per_day
            )  # in units of days
            npulls_by_date = (
                (end_time - begin_time).total_seconds()
                / seconds_per_day
                / riot_date_interval_in_days
            )
            npulls_by_index = (
                (arrow.now() - begin_time).total_seconds()
                / seconds_per_day
                / riot_date_interval_in_days
                * matches_per_date_interval
                / riot_index_interval
            )
            if math.ceil(npulls_by_date) < math.ceil(npulls_by_index):
                by = "by_date"
            else:
                by = "by_index"
            return by

        calling_method = determine_calling_method(begin_time, end_time)

        if calling_method == "by_date":
            parameters["beginTime"] = begin_time.int_timestamp * 1000
            if "endTime" in query:
                parameters["endTime"] = min(
                    (begin_time + riot_date_interval).int_timestamp * 1000,
                    query["endTime"],
                )
            else:
                parameters["endTime"] = (
                    begin_time + riot_date_interval
                ).int_timestamp * 1000
        else:
            parameters["beginIndex"] = query["beginIndex"]
            parameters["endIndex"] = query["beginIndex"] + min(
                riot_index_interval, query["maxNumberOfMatches"]
            )
            parameters["endIndex"] = int(parameters["endIndex"])

        if "champion.ids" in query:
            champions = query["champion.ids"]
            parameters["champion"] = champions
        else:
            champions = set()

        if "queues" in query:
            queues = {Queue(queue) for queue in query["queues"]}
            parameters["queue"] = {QUEUE_IDS[queue] for queue in queues}
        else:
            queues = set()

        endpoint = "lol/match/v4/matchlists/by-account/{accountId}".format(
            accountId=query["accountId"]
        )
        try:
            data = self._get(endpoint=endpoint, parameters=parameters)
        except APINotFoundError:
            data = {"matches": []}

        data["accountId"] = query["accountId"]
        data["region"] = query["platform"].region.value
        data["champion"] = champions
        data["queue"] = queues
        if calling_method == "by_index":
            data["beginIndex"] = parameters["beginIndex"]
            data["endIndex"] = parameters["endIndex"]
            data["maxNumberOfMatches"] = query["maxNumberOfMatches"]
        else:
            data["beginTime"] = parameters["beginTime"]
            data["endTime"] = parameters["endTime"]
        for match in data["matches"]:
            match["accountId"] = query["accountId"]
            match["region"] = Platform(match["platformId"]).region.value
        return MatchListDto(data)

    _validate_get_many_match_list_query = (
        Query.has("accountIds")
        .as_(Iterable)
        .also.has("platform")
        .as_(Platform)
        .also.can_have("beginTime")
        .as_(int)
        .also.can_have("endTime")
        .as_(int)
        .also.can_have("beginIndex")
        .as_(int)
        .also.can_have("endIndex")
        .as_(int)
        .also.can_have("champion.ids")
        .as_(Iterable)
        .also.can_have("queues")
        .as_(Iterable)
    )

    @get_many.register(MatchListDto)
    @validate_query(_validate_get_many_match_list_query, convert_region_to_platform)
    def get_many_match_list(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> Generator[MatchListDto, None, None]:
        parameters = {"platform": query["platform"].value}

        if "beginIndex" in query:
            parameters["beginIndex"] = query["beginIndex"]

        if "endIndex" in query:
            parameters["endIndex"] = query["endIndex"]

        if "champion.ids" in query:
            parameters["champion"] = {query["champion.ids"]}

        if "queues" in query:
            queues = {Queue(queue) for queue in query["queues"]}
            parameters["queue"] = {QUEUE_IDS[queue] for queue in queues}
        else:
            queues = set()

        def generator():
            for id in query["accountIds"]:
                endpoint = "lol/match/v4/matchlists/by-account/{accountId}".format(
                    accountId=id
                )
                try:
                    data = self._get(endpoint=endpoint, parameters=parameters)
                except APINotFoundError as error:
                    raise NotFoundError(str(error)) from error

                data["accountId"] = id
                data["region"] = query["platform"].region.value
                if "beginIndex" in query:
                    data["beginIndex"] = query["beginIndex"]
                if "endIndex" in query:
                    data["endIndex"] = query["endIndex"]
                if "champion.ids" in query:
                    data["champion"] = parameters["champion"]
                if "queues" in query:
                    parameters["queue"] = queues
                yield MatchListDto(data)

        return generator()

    _validate_get_timeline_query = (
        Query.has("id").as_(int).also.has("platform").as_(Platform)
    )

    @get.register(TimelineDto)
    @validate_query(_validate_get_timeline_query, convert_region_to_platform)
    def get_match_timeline(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> TimelineDto:
        parameters = {"platform": query["platform"].value}
        endpoint = "lol/match/v4/timelines/by-match/{id}".format(id=query["id"])
        try:
            data = self._get(endpoint=endpoint, parameters=parameters)
        except APINotFoundError as error:
            raise NotFoundError(str(error)) from error

        data["matchId"] = query["id"]
        data["region"] = query["platform"].region.value
        return TimelineDto(data)

    _validate_get_many_timeline_query = (
        Query.has("ids").as_(Iterable).also.has("platform").as_(Platform)
    )

    @get_many.register(TimelineDto)
    @validate_query(_validate_get_many_timeline_query, convert_region_to_platform)
    def get_many_match_timeline(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> Generator[TimelineDto, None, None]:
        parameters = {"platform": query["platform"].value}

        def generator():
            for id in query["ids"]:
                endpoint = "lol/match/v4/timelines/by-match/{id}".format(id=id)
                try:
                    data = self._get(endpoint=endpoint, parameters=parameters)
                except APINotFoundError as error:
                    raise NotFoundError(str(error)) from error

                data["matchId"] = id
                data["region"] = query["platform"].region.value
                yield TimelineDto(data)

        return generator()


from ..import model
from ...lib import config
import logging, jwt
_LOGGER = logging.getLogger()

class Notification:
    def __init__(self):
        _LOGGER.info("[init] Notification")
        self.model = model.model('notification')

    def _mapOne(self, rDocument):
        rDocument["_id"] = str(rDocument["_id"])
        return rDocument

    def _map(self, rDocuments):
        for (i, doc) in enumerate(rDocuments):
            rDocuments[i]["_id"] = str(doc["_id"])
        return rDocuments

    def get(self, doc, ifNone={}):
        _LOGGER.info("getting... ")
        _LOGGER.info(f"{doc}")
        rDocument = [self.model.find_one(doc)]
        _LOGGER.info(rDocument)
        if(rDocument == [None]): return ifNone
        return list(map(self._mapOne, rDocument))[0]

    def getMany(self, doc):
        res = [self.model.find(doc)]
        _LOGGER.info(res)
        return list(map(self._map, res))

    # def new(self,user,doc):
    def new(self, doc):
        _LOGGER.info("inserting... ")
        _LOGGER.info(f"{doc}")
        # res = self.model.update_one(user, {"$set": doc})
        res = self.model.insert_one(doc)
        _LOGGER.info(res)
        return 0
        # return str(res.documentIds[0])

    def redact(self, _id, doc):
        _LOGGER.info("redacting... ")
        _LOGGER.info(f"{doc}")
        res = self.model.update_one({"_id": _id}, {"$set": doc})
        _LOGGER.info(res)
        return 0
        # return str(res.documentIds[0])

    # - RESERVED FOR FUTER UPDATE
    # def delete(self,doc):
    #     _LOGGER.info("deleting... ")
    #     _LOGGER.info(f"{doc}")
    #     res = self.model.delete_one(doc)
    #     _LOGGER.info(res)
    #     return 0


import re
from decimal import Decimal
from typing import List, Optional

from adapters.repositories.repository import BaseRepository
from entities.entities import ExchangeRequest, UserBalance

class ExchangeRequestRepository(BaseRepository):

    @staticmethod
    async def parse_message(msg: str) -> List[Optional[str]]:
        """
        Parse income message and return amount and currencies

        :param msg: - message for parsing
        :return: list with amount, from which currency to do operation, to which currency to do operation
        """

        pattern = r'(\w+)\s+([\d.]+)\s+([A-Za-z]+)\s*[-/.\\_ ]\s*([A-Za-z]+)'
        match = re.match(pattern, msg)
        if match:
            return match.group(1).lower(), Decimal(match.group(2)), match.group(3), match.group(4)
        else:
            return None, None, None, None

    async def create_exchange_request(self, entity: ExchangeRequest):

        await self._db_session.execute(
            f'''insert into exchange_requests(
                msg_id, external_user_id, chat_id, status, msg_text,
                currency_from, currency_to, amount, created_at, updated_at,
                price
            ) values
            (
                {entity.msg_id}, {entity.external_user_id}, {entity.chat_id}, '{entity.status}', '{entity.msg_text}',
                '{entity.currency_from}', '{entity.currency_to}', {entity.amount}, '{entity.created_at}'::timestamp,
                '{entity.updated_at}'::timestamp, {entity.price}
            );'''
        )

    async def get_data_for_week(self, entity: UserBalance):

        await self._db_session.fetch(
            f'''
                select sum(amount), currency_from, currency_to
                from exchange_requests
                where external_user_id = {entity.external_user_id}
                  and status = 'finished'
                group by currency_from, currency_to;
            '''
        )


# A self-dividing number is a number that is divisible by every digit it contains.
#
# For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
# A self-dividing number is not allowed to contain the digit zero.
#
# Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right].

class Solution:
    def selfDividingNumbers(self, left: int, right: int) -> List[int]:
        result = []

        for n in range(left, right + 1):
            valid = True
            for c in str(n):
                if c == '0' or n % int(c) != 0:
                    valid = False
                    break

            if valid:
                result.append(n)

        return result

# Math

Math - Greedy/728. [Easy] Self Dividing Numbers.py


#!/usr/bin/env python

from __future__ import division, print_function, absolute_import

import numpy as np
from numpy.testing import run_module_suite, assert_allclose, assert_

import pywt

def test_upcoef_docstring():
    data = [1, 2, 3, 4, 5, 6]
    (cA, cD) = pywt.dwt(data, 'db2', 'smooth')
    rec = pywt.upcoef('a', cA, 'db2') + pywt.upcoef('d', cD, 'db2')
    expect = [-0.25, -0.4330127, 1., 2., 3., 4., 5.,
              6., 1.78589838, -1.03108891]
    assert_allclose(rec, expect)
    n = len(data)
    rec = (pywt.upcoef('a', cA, 'db2', take=n) +
           pywt.upcoef('d', cD, 'db2', take=n))
    assert_allclose(rec, data)

def test_upcoef_reconstruct():
    data = np.arange(3)
    a = pywt.downcoef('a', data, 'haar')
    d = pywt.downcoef('d', data, 'haar')

    rec = (pywt.upcoef('a', a, 'haar', take=3) +
           pywt.upcoef('d', d, 'haar', take=3))
    assert_allclose(rec, data)

def test_downcoef_multilevel():
    rstate = np.random.RandomState(1234)
    r = rstate.randn(16)
    nlevels = 3
    # calling with level=1 nlevels times
    a1 = r.copy()
    for i in range(nlevels):
        a1 = pywt.downcoef('a', a1, 'haar', level=1)
    # call with level=nlevels once
    a3 = pywt.downcoef('a', r, 'haar', level=nlevels)
    assert_allclose(a1, a3)

def test_compare_downcoef_coeffs():
    rstate = np.random.RandomState(1234)
    r = rstate.randn(16)
    # compare downcoef against wavedec outputs
    for nlevels in [1, 2, 3]:
        for wavelet in pywt.wavelist():
            wavelet = pywt.Wavelet(wavelet)
            max_level = pywt.dwt_max_level(r.size, wavelet.dec_len)
            if nlevels <= max_level:
                a = pywt.downcoef('a', r, wavelet, level=nlevels)
                d = pywt.downcoef('d', r, wavelet, level=nlevels)
                coeffs = pywt.wavedec(r, wavelet, level=nlevels)
                assert_allclose(a, coeffs[0])
                assert_allclose(d, coeffs[1])

def test_upcoef_multilevel():
    rstate = np.random.RandomState(1234)
    r = rstate.randn(4)
    nlevels = 3
    # calling with level=1 nlevels times
    a1 = r.copy()
    for i in range(nlevels):
        a1 = pywt.upcoef('a', a1, 'haar', level=1)
    # call with level=nlevels once
    a3 = pywt.upcoef('a', r, 'haar', level=nlevels)
    assert_allclose(a1, a3)

def test_wavelet_repr():
    from pywt._extensions import _pywt
    wavelet = _pywt.Wavelet('sym8')

    repr_wavelet = eval(wavelet.__repr__())

    assert_(wavelet.__repr__() == repr_wavelet.__repr__())

def test_dwt_max_level():
    assert_(pywt.dwt_max_level(16, 2) == 4)
    assert_(pywt.dwt_max_level(16, 8) == 1)
    assert_(pywt.dwt_max_level(16, 9) == 1)
    assert_(pywt.dwt_max_level(16, 10) == 0)
    assert_(pywt.dwt_max_level(16, 18) == 0)

if __name__ == '__main__':
    run_module_suite()


from __future__ import annotations

import re
from typing import List

from docinpy import Struct

"""
This module is for parse and extract comments
"""

# three_quote_pattern is multi-line comment pattern
three_quote_pattern = re.compile(r'(^|\n)\s*?"""([^(""")]*?)"""', re.DOTALL)

def prepare_raw_comment_struct(parent_src: str) -> List[Struct]:
    min_pos_for_line = get_min_pos_for_line(parent_src)
    min_line_no = 1
    comment_struct_list = []
    matches = three_quote_pattern.finditer(parent_src)
    for match in matches:
        comment_content = match.group(2)
        start = match.group(1)
        start_pos, end_pos = match.span()
        start_pos += len(start)
        start_line_no = find_line_no(start_pos, min_line_no, min_pos_for_line)
        end_line_no = find_line_no(end_pos, start_line_no, min_pos_for_line)
        min_line_no = end_line_no
        comment_pos = (start_line_no, end_line_no)
        comment_struct_list.append(Struct("raw_comment", comment_content, comment_pos))
    return comment_struct_list

def get_min_pos_for_line(src: str) -> List[int]:
    src_lines = src.split("\n")
    min_pos_for_line = [0]
    for line in src_lines:
        min_pos_for_line.append(min_pos_for_line[-1] + len(line) + 1)
    return min_pos_for_line

def find_line_no(pos: int, min_line_no, min_pos_for_line: List[int]) -> int:
    for i in range(min_line_no - 1, len(min_pos_for_line)):
        if pos < min_pos_for_line[i]:
            return i

section_pattern = re.compile(r"(\n\s*?#+ .*)")

def parse_raw_comments(root_struct: Struct):
    new_children = []
    for i, struct in enumerate(root_struct.children):
        if struct.struct_type == "raw_comment":
            comment_content = struct.obj
            comment_structs = process_raw_comment_content(comment_content)
            new_children.extend(comment_structs)
        else:
            new_children.append(struct)
            if struct.struct_type == "class":
                parse_raw_comments(struct)
    root_struct.children = new_children

def process_raw_comment_content(comment_content: str) -> List[Struct]:
    min_pos_for_line = get_min_pos_for_line(comment_content)
    min_line_no = 1

    structs_in_comment = []
    # Find all sections which should start with one or more # followed by a space
    section_matches = section_pattern.finditer(comment_content)
    last_section_end = 0
    for section_match in section_matches:
        section_markdown = section_match.group(1)[1:].lstrip()
        # find first non-# character
        section_title = section_markdown.lstrip("#")
        section_level = len(section_markdown) - len(section_title)
        section_title = section_title.strip()
        section_start, section_end = section_match.span()
        start_line_no = find_line_no(section_start, min_line_no, min_pos_for_line)
        end_line_no = find_line_no(section_end, start_line_no, min_pos_for_line)
        min_line_no = end_line_no
        comment_text_before_section = comment_content[last_section_end + 1:section_start]
        last_section_end = section_end
        if len(comment_text_before_section) > 0:
            structs_in_comment.append(
                Struct("comment", comment_text_before_section, (0, start_line_no)))
        structs_in_comment.append(
            Struct("section", (section_title, section_level),
                   (start_line_no, end_line_no)))
    if last_section_end < len(comment_content):
        remaining_text = comment_content[last_section_end:].strip()
        if len(remaining_text) > 0:
            last_section_end_line_no = find_line_no(last_section_end, min_line_no, min_pos_for_line)
            structs_in_comment.append(Struct("comment", remaining_text,
                                         (last_section_end_line_no, len(min_pos_for_line)-1)))
    return structs_in_comment