from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class MainWidgetUI:

    def __init__(self, parent, parent_widget):
        self.parent = parent
        self.parent_widget = parent_widget
        self.main = QWidget(parent_widget)
        self.main.setObjectName("Mongo Widget")
        self.main.resize(903, 672)
        self.current_procedure = {}
        self.open_in_browser = False

        self.procedures_list = QListWidget(self.main)
        self.procedures_list.itemClicked.connect(self.procedure_clicked)
        self.fill_procedure_list(parent.get_procedures())
        self.procedures_list.setGeometry(QRect(30, 50, 181, 201))
        self.procedures_list.setObjectName("procedures_list")

        self.documents_list = QListWidget(self.main)
        self.documents_list.itemDoubleClicked.connect(self.document_clicked)
        self.sync_document_list()
        self.documents_list.setGeometry(QRect(30, 300, 350, 600))
        self.documents_list.setObjectName("document_list")

        # Procedures text
        self.header_text = QLabel(self.main)
        self.header_text.setGeometry(QRect(30, 10, 181, 16))
        self.header_text.setObjectName("header_text")

        # Procedure parameter text
        self.header_text_procedure_param = QLabel(self.main)
        self.header_text_procedure_param.setGeometry(QRect(240, 10, 131, 16))
        self.header_text_procedure_param.setObjectName("header_text_procedure_param")

        # Procedure result text
        self.header_text_procedure_param_2 = QLabel(self.main)
        self.header_text_procedure_param_2.setGeometry(QRect(420, 10, 131, 16))
        self.header_text_procedure_param_2.setObjectName("header_text_procedure_param_2")

        # Document text
        self.header_text_documents = QLabel(self.main)
        self.header_text_documents.setGeometry(QRect(30, 270, 131, 16))
        self.header_text_documents.setObjectName("header_text_documents")

        # Call procedure button
        self.call_procedure_btn = QPushButton(self.main)
        self.call_procedure_btn.setGeometry(QRect(240, 90, 131, 32))
        self.call_procedure_btn.setObjectName("call_procedure_btn")
        self.call_procedure_btn.clicked.connect(self.get_procedure_result)

        # Open in browser checkbox
        self.open_in_browser_label = QLabel(self.main)
        self.open_in_browser_label.setGeometry(QRect(240, 150, 131, 16))
        self.open_in_browser_label.setObjectName("open_in_browser_label")

        self.open_browser_checkbox = QCheckBox(self.main)
        self.open_browser_checkbox.setGeometry(QRect(240, 160, 40, 40))
        self.open_browser_checkbox.setObjectName("open_in_browser_checbox")
        self.open_browser_checkbox.stateChanged.connect(lambda: self.set_in_browser_checkbox(self.open_browser_checkbox))

        # Procedure parameter input
        self.procedure_param = QLineEdit(self.main)
        self.procedure_param.textChanged[str].connect(self.procedure_param_changed)
        self.procedure_param.setGeometry(QRect(240, 50, 131, 21))
        self.procedure_param.setInputMethodHints(Qt.ImhNone)
        self.procedure_param.setObjectName("procedure_param")

        # Document name text
        self.document_name_text = QLabel(self.main)
        self.document_name_text.setGeometry(QRect(420, 690, 131, 16))
        self.document_name_text.setObjectName("docuement_name_text")

        # Document name
        self.document_name = QLineEdit(self.main)
        self.document_name.textChanged[str].connect(self.document_name_changed)
        self.document_name.setGeometry(QRect(420, 710, 230, 21))
        self.document_name.setInputMethodHints(Qt.ImhNone)
        self.document_name.setObjectName("procedure_param")

        self.procedure_result = QTableWidget(self.main)
        self.procedure_result.setGeometry(QRect(420, 50, 1400, 600))
        self.procedure_result.setObjectName("procedure_result")

        self.get_document_btn = QPushButton(self.main)
        self.get_document_btn.setGeometry(QRect(660, 705, 213, 32))
        self.get_document_btn.setObjectName("get_document_btn")
        self.get_document_btn.clicked.connect(self.get_document_clicked)

        QMetaObject.connectSlotsByName(self.main)

        self.header_text.setText('Procedures')
        self.call_procedure_btn.setText("Call procedure")
        self.header_text_procedure_param.setText("Procedure parameter")
        self.header_text_procedure_param_2.setText("Procedure result")
        self.document_name_text.setText("Document name")
        self.get_document_btn.setText("Create document")
        self.header_text_documents.setText("Documents")
        self.open_in_browser_label.setText('Open in browser')

    def set_in_browser_checkbox(self, checkox):
        if checkox.isChecked():
            self.parent.check_open_in_browser(True)
        else:
            self.parent.check_open_in_browser(False)

    def set_table_data(self, columns, data):
        self.procedure_result.setRowCount(0)

        self.data = data

        row_count = len(data)
        column_count = len(columns)

        self.procedure_result.setRowCount(row_count)
        self.procedure_result.setColumnCount(column_count)

        self.procedure_result.setHorizontalHeaderLabels(columns)
        for i in range(len(columns)):
            self.procedure_result.setColumnWidth(i, len(columns[i]) + 150)

        for row in range(row_count):
            for column in range(column_count):
                item = list(data[row].values())[column]
                self.procedure_result.setItem(row, column, QTableWidgetItem(item))

    def document_clicked(self, item):
        self.parent.open_document(item.text())

    def document_name_changed(self, text):
        self.parent.set_document_name(text)

    def get_document_clicked(self):
        self.parent.get_document()

    def procedure_clicked(self, item):
        self.current_procedure = {
            'name': item.text()
        }
        self.document_name.setText(item.text())

    def procedure_param_changed(self, text):
        self.current_procedure['param'] = text

    def get_procedure_result(self):
        self.parent.call_procedure(self.current_procedure)

    def widget(self):
        return self.main

    def fill_procedure_list(self, names: list):
        excluded = self.parent.get_excluded_procedures()
        for name in names:
            if name not in excluded:
                self.procedures_list.addItem(name)

    def sync_document_list(self):
        self.documents_list.clear()
        files = self.parent.get_local_documents()
        for file in files:
            self.documents_list.addItem(file)


from django.urls import path
from . import views

urlpatterns = [
    path('csv/', views.get_csv_file, name='get_csv'),
    path('booking/select-cinema/', views.select_cinema, name='select_cinema'),
    path("booking/select-movie/<int:cinema_pk>", views.select_movie, name="select_movie"),
    path("booking/select-time/<int:movie_pk>/<int:cinema_pk>", views.select_playing_time, name="select_playing_time"),
    path("booking/select-seats/<int:pk>/", views.select_seats, name="select_seats"),
    path("booking/confirm-reservation/<slug:uidb64>/", views.confirm_reservations, name="confirm_reservations"),
]


#!flask/bin/python
from flask import Flask, jsonify, request
import joblib
import pandas as pd

app = Flask(__name__)

@app.route('/predict/tx', methods=['GET'])
def create_task():
    tx_data = request.json
    model = joblib.load('house.model')
    res = model.predict([[1177.698,2,7,2,2,2]])
    return jsonify(res[0]), 201

if __name__ == '__main__':
    app.run(debug=True)


import subprocess

# Define the Unix command to run
cmd = 'ls -l'

# Run the command and capture its output
output = subprocess.check_output(cmd, shell=True)

# Convert the byte string output to a regular string
output = output.decode()

# Search for a string in the output
search_string = 'myfile.txt'
if search_string in output:
    print(f'{search_string} found in the output')
else:
    print(f'{search_string} not found in the output')


class Settings:
    """Класс для сохранения всех настроек игры"""

    def __init__(self, screen_width=1200, screen_height=800, bg_color=(230, 230, 230), ship_speed_factor=1.25,
                 bullet_speed_factor=0.75, bullet_color=(60, 60, 60),
                 bullets_allowed=3, alien_speed_factor=1, drop_speed=0.1, direction=1):
        self.screen_width = screen_width
        self.screen_height = screen_height
        self.bg_color = bg_color
        self.ship_speed_factor = ship_speed_factor

        self.bullet_speed_factor = bullet_speed_factor
        self.bullet_color = bullet_color
        self.bullets_allowed = bullets_allowed
        self.alien_speed_factor = alien_speed_factor
        self.drop_speed = drop_speed
        self.direction = direction  # Direction Равняется одному, если двгается вправа, равняется мимнус одному, если двигается влево


from crypt import methods
import imp
from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required, current_user
from .models import Todo
from . import db

views = Blueprint('views', __name__)

@views.route('/')
@login_required
def home():
    return render_template('home.html', user=current_user)

@views.route('/todos', methods=['GET', 'POST'])
@login_required
def todos():
    if request.method == 'POST':
        todoContent = request.form.get('content')
        if not todoContent or len(todoContent) < 1:
            flash('Todo is too short.', category='error')
            return redirect(url_for('views.todos'))

        new_todo = Todo(content=todoContent, user_id=current_user.id)
        db.session.add(new_todo)
        db.session.commit()
        flash('Todo added!', category='success')
        return redirect(url_for('views.home'))
    return render_template('todos.html', user=current_user)

@views.route('/delete-todo', methods=['POST'])
@login_required
def deleteTodo():
    todo = request.form.get('id')
    todo = Todo.query.get(id=int(todo), user_id=current_user.id).first()
    if todo:
        db.session.delete(todo)
        db.session.commit()
        flash('Todo deleted.', category='success')
    else:
        flash('Todo does not exist or you do not has permission to delete this todo.', category='error')
    return redirect(url_for('views.home'))


import os
import random
import pygame.mixer
try:
    import numpy as np
    import pygame.sndarray
    has_array = True
except ImportError:
    has_array = False
from .. import settings

class SoundCache(dict):
    def __missing__(self, sound_name):
        sound = pygame.mixer.Sound(os.path.join(settings.DATA_DIR, 'music', sound_name))
        options = [sound]
        if not has_array:
            return options
        base_sample = pygame.sndarray.array(sound)
        for factor in (0.98, 0.99, 1.01, 1.02):
            new_sample = change_pitch(base_sample, factor)
            options.append(pygame.sndarray.make_sound(new_sample))
        return options

SOUND_CACHE = SoundCache()

def playfx(sound_name):
    sound = random.choice(SOUND_CACHE[sound_name])
    sound.play()

def change_pitch(sound_array, factor):
    indices = np.round(np.arange(0, len(sound_array), factor))
    indices = indices[indices < len(sound_array)].astype(int)
    return sound_array[indices.astype(int)]


def lstmin():
    lst=[]
    num=int(input("Enter a number:"))
    for i in range(1,num+1):
        ele=int(input("Enter a values:"))
        lst.append(ele)
    print("list of elements:",lst)
    m=min(lst)
    return m

def main():
    print("Minimum element from list:",lstmin())
if __name__=="__main__":
    main()


import bs4
import requests as req
import io
import csv

with open("D:\DATA_NEWS\Book1.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        res = req.get(row[1])
        html_doc = res.text
        soup = bs4.BeautifulSoup(html_doc, 'lxml')

        match = soup.find('h1',class_='title-detail')

        a = match.string +"\n"
        matches = soup.find_all('p',class_='Normal')
        for tmp in matches:
            a = a + tmp.text + "\n"

        i = row[0]
        path = "D:\\DATA_NEWS\\data" + str(i) + ".txt"
        sor = open(path, "w", encoding="utf8")
        sor.write(a)
        sor.close()


from http import HTTPStatus

from django.contrib.auth import get_user_model
from django.test import Client, TestCase

from posts.models import Group, Post

User = get_user_model()

class PostURLTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.author = User.objects.create_user(username='author')
        Group.objects.create(title='Бандиты', slug='test-slug')
        cls.post = Post.objects.create(
            text='Рандомные слова',
            author=cls.author
        )

    def setUp(self):
        self.guest_client = Client()
        self.author_client = Client()
        self.author_client.force_login(self.author)
        self.user = User.objects.create_user(username='user')
        self.user_client = Client()
        self.user_client.force_login(self.user)

    def test_post_urls_exist_at_desired_location(self):
        """Страницы: /, /group/<slug>/, /profile/<username>/, /posts/<post_id>/
        доступны любому пользователю."""
        url_names = [
            '/',
            '/group/test-slug/',
            '/profile/author/',
            f'/posts/{self.post.id}/'
        ]
        for address in url_names:
            with self.subTest(address=address):
                response = self.guest_client.get(address)
                self.assertEqual(response.status_code, HTTPStatus.OK)

    def test_post_urls_redirect_anonymous(self):
        """Редирект страницы /create/, '/posts/<post_id>/edit/',
        'posts/<post_id>/comment/' для анонимного пользователя"""
        url_names = [
            '/create/',
            f'/posts/{self.post.id}/edit/',
            f'/posts/{self.post.id}/comment/'
        ]
        for address in url_names:
            with self.subTest(address=address):
                response = self.guest_client.get(address, follow=True)
                self.assertRedirects(response, f'/auth/login/?next={address}')

    def test_post_url_authorized_only(self):
        """Страница /create/ доступна авторизованному пользователю."""
        response = self.user_client.get('/create/')
        self.assertEqual(response.status_code, HTTPStatus.OK)

    def test_post_url_redirects_not_author(self):
        """Редирект страницы /posts/<post_id>/edit/
        для авторизованного пользователя"""
        response = self.user_client.get(f'/posts/{self.post.id}/edit/')
        self.assertRedirects(response, f'/posts/{self.post.id}/')

    def test_post_url_author_only(self):
        """Cтраница /posts/<post_id>/edit/ доступна автору поста"""
        response = self.author_client.get(f'/posts/{self.post.id}/')
        self.assertEqual(response.status_code, HTTPStatus.OK)

    def test_urls_uses_correct_template(self):
        """URL-адрес использует соответствующий шаблон."""
        templates_url_names = {
            '/': 'posts/index.html',
            '/group/test-slug/': 'posts/group_list.html',
            '/profile/author/': 'posts/profile.html',
            f'/posts/{self.post.id}/': 'posts/post_detail.html',
            f'/posts/{self.post.id}/edit/': 'posts/create_post.html',
            '/create/': 'posts/create_post.html'
        }
        for address, template in templates_url_names.items():
            with self.subTest(address=address):
                response = self.author_client.get(address)
                self.assertTemplateUsed(response, template)

    def test_url_uses_unexisting_page(self):
        """Запрос к несуществующей странице"""
        response = self.author_client.get('/unexisting_page/')
        self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)


class Entity:
    def __init__(self,health):
        self.health = health

class Player(Entity):
    def __init__(self,health,power):
        super().__init__(health)
        self.power = power
        print("New player created.\nHealth:{}\nPower:{}\n".format(self.health,self.power))

    def attack(self,enemy_object):
        print("I'm attacking to", enemy_object)
        enemy_object.health -= self.power
        print("Dealt {} damage to enemy\nEnemy has {} HP left".format(self.power,enemy_object.health))

    def heal(self):
        print("I'm healing myself!")
        self.health += 15
        print("Added 15 to my health. My health is now",self.health)

class Enemy1:
    health = 100
    power = 10

    def __init__(self):
        print("New Enemy1 created.\nHealth:{}\nPower:{}\n".format(self.health,self.power))

    def attack_player(self,player):
        if not isinstance(player, Player):
            print("Can't attack my ally")
        else:
            print("Enemy1 attacks you back!\nYou take {} damage".format(self.power))
            player.health -= self.power
            print(str(player.health) + " HP left")

class Enemy2:
    health = 200
    power = 8

    def __init__(self):
        print("New Enemy2 created.\nHealth:{}\nPower:{}\n".format(self.health,self.power))

    def attack_player(self,player):
        if not isinstance(player, Player):
            print("Can't attack my ally")
        else:
            print("Enemy2 attacks you back!\nYou take {} damage".format(self.power))
            player.health -= self.power
            print(str(player.health) + " HP left")

player1 = Player(150,15)
enemy1 = Enemy1()
enemy2 = Enemy2()

while True:
    print("\n1 -> ATTACK || 2 -> HEAL")
    key = int(input("Make your choice: "))
    if key == 2:
        player1.heal()
    elif key == 1:
        print("Enemy 1 or Enemy 2?")
        enemy_select = int(input())
        if enemy_select == 1:
            player1.attack(enemy1)
            enemy1.attack_player(player1)
        else:
            player1.attack(enemy2)
            enemy2.attack_player(player1)
    if enemy1.health <= 0 and enemy2.health <= 0:
        print("Congrats! You win!")
        break
    elif player1.health <= 0:
        print("You died! Game over!")
        break


import keyboard
import threading
import time

def print_time( threadName, delay):
   count = 0
   while count < 50:
      count += 1
      print ("%s: %s" % (count, time.ctime(time.time())))
      time.sleep(delay)

t = threading.Thread(target=print_time, args=("THREAD", 3.5, ))
t.start()

keyboard.add_hotkey('ctrl+s', t.stop)


class Solution(object):
    def maxKilledEnemies(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        result = 0
        if not grid or not grid[0]:
            return result
        height = len(grid)
        width = len(grid[0])
        down = [[0 for _ in xrange(len(grid[0]))] for _ in xrange(len(grid))]
        right = [[0 for _ in xrange(len(grid[0]))] for _ in xrange(len(grid))]
        for y in xrange(height-1, -1, -1):
            for x in xrange(width-1, -1, -1):
                if grid[y][x] == "W":
                    down[y][x] = 0; right[y][x] = 0
                else:
                    check = int(grid[y][x] == "E")
                    if y == height -1:
                        down[y][x] = check
                    else:
                        down[y][x] = down[y+1][x] + check
                    if x == width - 1:
                        right[y][x] = check
                    else:
                        right[y][x] = right[y][x+1] + check
        left = 0
        result = 0
        up = [0 for _ in xrange(width)]
        for y in xrange(height):
            left = 0
            for x in xrange(width):
                if grid[y][x] == "E":
                        left += 1; up[x] = up[x] + 1
                elif grid[y][x] == "W":
                    left = 0; up[x] = 0
                else:
                    result = max(result , down[y][x] + right[y][x] + left + up[x])
        #print down, right, up
        return result


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, absolute_import, unicode_literals

import sys
import numpy as np

try:
    import talib
except:
    print('请安装TA-Lib库')
    sys.exit(-1)
from etasdk import *

'''
期货策略：海龟交易法
本策略通过计算FG801.CF和rb1801.CF的ATR.唐奇安通道和MA线,
-- 当价格上穿唐奇安通道且短MA在长MA上方时开多仓;
-- 当价格下穿唐奇安通道且短MA在长MA下方时开空仓(8手)
若有多仓则在价格跌破唐奇安平仓通道下轨的时候全平仓位,否则根据跌破
持仓均价 - x(x=0.5,1,1.5,2)倍ATR把仓位平至6/4/2/0手
若有空仓则在价格涨破唐奇安平仓通道上轨的时候全平仓位,否则根据涨破
持仓均价 + x(x=0.5,1,1.5,2)倍ATR把仓位平至6/4/2/0手
撮合周期为:1分钟
回测时间为:2017-09-15 到2017-10-01
'''

def onInitialize(api):
    print("analyzer initialize")
    # 设置响应模式
    api.setGroupMode(5000, False)
    # 设置关注的合约标的
    api.tickersCode = ["FG1801.CF", "rb1801.CF"]

    # api.parameter 分别为唐奇安开仓通道.唐奇安平仓通道.短ma.长ma.ATR的参数
    api.parameter = [55, 20, 10, 60, 20]
    api.tar = api.parameter[4]

    api.data_len = 600

    api.setSymbolPool(symbols=api.tickersCode)
    api.setRequireBars(ETimeSpan.MIN_1, api.data_len)

def onBeforeMarketOpen(api, tradeDate):
    # print(tradeDate)
    api.trading_day = tradeDate
    # 订阅行情
    api.setFocusSymbols(api.tickersCode)

def onBar(api, bar):
    bar_data = api.getBarsHistory(symbol=bar.symbol, timeSpan=ETimeSpan.MIN_1, count=api.data_len,
                                  priceMode=EPriceMode.FORMER, fields=None, df=True)
    close = bar_data["close"].values[-1]
    # 计算ATR
    atr = talib.ATR(bar_data["high"].values, bar_data["low"].values, bar_data["close"].values,
                    timeperiod=api.tar)[-1]

    # 计算唐奇安开仓和平仓通道
    api.don_open = api.parameter[0] + 1
    upper_band = talib.MAX(bar_data['close'].values[:-1], timeperiod=api.don_open)[-1]
    api.don_close = api.parameter[1] + 1
    lower_band = talib.MIN(bar_data['close'].values[:-1], timeperiod=api.don_close)[-1]

    # 若没有仓位则开仓
    position_long = api.getSymbolPosition(symbol=bar.symbol, positionSide=EPositionSide.LONG)
    position_short = api.getSymbolPosition(symbol=bar.symbol, positionSide=EPositionSide.SHORT)

    print(position_long)
    print(position_short)

    if not position_long.posQty and not position_short.posQty:
        # 计算长短ma线.DIF
        ma_short = talib.MA(bar_data['close'].values, timeperiod=(api.parameter[2] + 1))[-1]
        ma_long = talib.MA(bar_data['close'].values, timeperiod=(api.parameter[3] + 1))[-1]

        diff = ma_short - ma_long

        # 获取当前价格
        # 上穿唐奇安通道且短ma在长ma上方则开多仓
        if bar.close > upper_band and (diff > 0):
            api.targetPosition(symbol=bar.symbol, qty=8, positionSide=EPositionSide.LONG)
            print(bar.symbol, '市价单开多仓8手')
        # 下穿唐奇安通道且短ma在长ma下方则开空仓
        if bar.low < lower_band and (diff < 0):
            api.targetPosition(symbol=bar.symbol, qty=8, positionSide=EPositionSide.SHORT)
            print(bar.symbol, '市价单开空仓8手')

    elif position_long.posQty:
        # 价格跌破唐奇安平仓通道全平仓位止损
        if close < lower_band:
            api.targetPosition(symbol=bar.symbol, qty=0, positionSide=EPositionSide.LONG)
            print(bar.symbol, '市价单全平仓位')
        else:
            # 获取持仓均价
            vwap = position_long.posPrice
            # 根据持仓以来的最高价计算不同的止损价格带
            band = vwap - np.array([2, 1.5, 1, 0.5]) * atr
            # 计算最新应持仓位
            if bar.close <= band[0]:
                api.targetPosition(symbol=bar.symbol, qty=0, positionSide=EPositionSide.LONG)
                print(bar.symbol, '市价单平仓至0手')
            elif band[0] < bar.close <= band[1]:
                api.targetPosition(symbol=bar.symbol, qty=2, positionSide=EPositionSide.LONG)
                print(bar.symbol, '市价单平仓至2手')
            elif band[1] < bar.close <= band[2]:
                api.targetPosition(symbol=bar.symbol, qty=4, positionSide=EPositionSide.LONG)
                print(bar.symbol, '市价单平仓至4手')
            elif band[2] < bar.close <= band[3]:
                api.targetPosition(symbol=bar.symbol, qty=6, positionSide=EPositionSide.LONG)
                print(bar.symbol, '市价单平仓至6手')

    elif position_short.posQty:
        # 价格涨破唐奇安平仓通道或价格涨破持仓均价加两倍ATR平空仓
        if close > upper_band:
            api.targetPosition(symbol=bar.symbol, qty=0, positionSide=EPositionSide.SHORT)
            print(bar.symbol, '市价单全平仓位')
        else:
            # 获取持仓均价
            vwap = position_long.posPrice
            # 根据持仓以来的最高价计算不同的止损价格带
            band = vwap + np.array([2, 1.5, 1, 0.5]) * atr
            # 计算最新应持仓位
            if bar.close >= band[0]:
                api.targetPosition(symbol=bar.symbol, qty=0, positionSide=EPositionSide.SHORT)
                print(bar.symbol, '市价单平仓至0手')
            elif band[0] > bar.close >= band[1]:
                api.targetPosition(symbol=bar.symbol, qty=2, positionSide=EPositionSide.SHORT)
                print(bar.symbol, '市价单平仓至2手')
            elif band[1] > bar.close >= band[2]:
                api.targetPosition(symbol=bar.symbol, qty=4, positionSide=EPositionSide.SHORT)
                print(bar.symbol, '市价单平仓至4手')
            elif band[2] > bar.close >= band[3]:
                api.targetPosition(symbol=bar.symbol, qty=6, positionSide=EPositionSide.SHORT)
                print(bar.symbol, '市价单平仓至6手')

def onTerminate(api, exit_info):
    print("Finished test")
    pass


import os
import numpy as np

import statsmodels.api as sm
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.diagnostic import het_goldfeldquandt
from statsmodels.stats.diagnostic import het_white
from statsmodels.stats.diagnostic import het_breuschpagan

def _check_heteroskedasticity(**params):

	print ("Trying to _check_heteroskedasticity")

	tmp_df = params.get("df")
	main_direc = params.get("direc")
	log = params.get("log")
	ind_col = params.get("id_col")
	time_col = params.get("time_col")

	tmp_df = tmp_df.drop(columns = [ind_col, time_col], errors = 'ignore')

	X = np.asarray(tmp_df.iloc[:, :-1])
	Y = np.asarray(tmp_df.iloc[:, -1])
	X = sm.add_constant(X)

	report_str = "Goldfeld-Quandt homoskedasticity test."
	report_str += "The Null hypothesis is that the variance in the two sub-samples are the same.\n"
	fval, pval, alternative = het_goldfeldquandt(Y, X)
	if pval < 0.05:
		report_str += f"Null hypothesis rejected. The alternative: errors are {alternative}.\n\n"
	else:
		report_str += f"Null hypothesis not rejected.\n\n"

	report_str = "White’s Lagrange Multiplier Test for Heteroscedasticity"
	report_str += "Null (H0): Homoscedasticity is present. Alternative (HA). "+\
					"Heteroscedasticity is present\n"
	ols = OLS(Y, X).fit()
	ols_res = ols.resid
	_, pval, _, _ = het_white(ols_res, X)
	if pval < 0.05:
		report_str += f"Null hypothesis rejected. Alternative: Heteroscedasticity is present\n\n"
	else:
		report_str += f"Null hypothesis not rejected. No sufficient evidence to say heteroscedasticity is present.\n\n"

	_, pval, _, _ = het_breuschpagan(ols_res, X)
	report_str = "Breusch-Pagan Test for Heteroscedasticity"
	report_str += "Null (H0): Homoscedasticity is present. Alternative (HA). "+\
					"Heteroscedasticity is present\n"
	if pval < 0.05:
		report_str += f"Null hypothesis rejected. Alternative: Heteroscedasticity is present\n\n"
	else:
		report_str += f"Null hypothesis not rejected. No sufficient evidence to say heteroscedasticity is present.\n\n"

	log.info(report_str)


from pymongo import MongoClient

## creación de una sesión
sesion  = MongoClient("mongodb://localhost:27017/")

## conexión a la base de datos test
db = sesion.test

## La colección que nos interesa
contactos = db.contactos

## Empezamos limpiándola
contactos.drop()

## Creación de un contacto
first_contacto = {
       'name': 'Linus Torvalds',
       'tel': '06 01 02 03 04',
       'date_nai': '28-12-1969'
       }

result = contactos.insert_one(first_contacto)

## Desde otro contacto
otro_contacto = {
       'name': 'Luke Skywalker',
       'tel': '06 01 02 03 04',
       'date_nai': '28-12-1969',
       'comment': 'Chevalier Djedi'
       }
result = contactos.insert_one(otro_contacto)

## Visualización de los contactos creados
for doc in db.contactos.find():
   print(doc)


from mcpi.minecraft import Minecraft
mc = Minecraft.create()
from random import randrange
from time import sleep
for i in range(10):
        x,y,z=mc.player.getTilePos()
        x = x+i
        for j in range(10):
            color=randrange(0,16)
            z=z+1
            mc.setBlock(x,y,z,35,color)
ans= randrange(0,16)
t=0
while True:
    hits=mc.events.pollBlockHits()
    if len(hits)>0:
        hit=hits[0]
        block = mc.getBlockWithData(hit.pos)
        data=block.data
        if data==ans:
            mc.postToChat("找到了!")
            mc.setBlock(hit.pos,57)
            break
        elif data<ans:
            mc.postToChat("Try biggger")
        elif data>ans:
            mc.postToChat("Try smaller")
            t=t+1
            if t>5:
                mc.postToChat("猜太多次了~~~~塊陶")
                sleep(3)
                x,y,z=mc.player.getTilePos()
                mc.createExplosion(x,y,z)
                break


from distutils import extension
import random

class Parking():
    def __init__(self, ticket, parking_spaces):
                self.ticket =  [i for i in (range(ticket + 1)[1:])]
                self.parking_spaces = [i for i in range(parking_spaces + 1) [1:]]
                self.in_use_spaces = {}
                self.ticket_number = None
#CHANGED TICKET_NUMBER TO  A VARIABLE IN PARKING () SO WE  CAN USE IT LATER
    def takeTicket(self):
        rand_ticket = input('Press enter to take a ticket: ') #ADDED THIS FOR  FLOW
        self.ticket_number = random.randint(1,15) # Program will select a ramdom number from 1-15 for the ticket number
        self.ticket.remove(self.ticket_number) #REPLACE POP WITH  .REMOVE(TICKET_NUMBER) SO IT REMMOVES THAT  SPECIFIC TICKET NUMBER
        self.parking_spaces.remove(self.ticket_number)#REPLACE POP WITH  .REMOVE(TICKET_NUMBER) SO IT REMMOVES THAT  SPECIFIC TICKET NUMBER
        self.in_use_spaces[self.ticket_number] = False
        print(f"Ticket #{self.ticket_number}")

    def payForParking(self):
        print_ticket = print("How many hours would you like to prepay for?")
        amount_time = {1: "$5.00", 2: "$7.00", 3: "$10.00", 4: "$15.00", "All Day": "$25.00"}
        for time, money in amount_time.items():
            print(f"{time}: {money}")
        choice = int(input("Make your selection 1-5: "))
        if choice == 1:   #I wanted to do this if statement in 2 lines but could not get it to work
                print("You have 1 hour remaining")
                self.in_use_spaces[self.ticket_number] = True #MADE SO SELF.TICKET_NUMBER DOESNT REMOVE KEY FROM THE DICT
        elif choice == 2:
            print("You have 2 hours remaining")
            self.in_use_spaces[self.ticket_number] = True #MADE SO SELF.TICKET_NUMBER DOESNT REMOVE KEY FROM THE DICT
        elif choice == 3:
            print("You have 3 hours remaining")
            self.in_use_spaces[self.ticket_number] = True #MADE SO SELF.TICKET_NUMBER DOESNT REMOVE KEY FROM THE DICT
        elif choice == 4:
            print("You have 4 hours remaining")
            self.in_use_spaces[self.ticket_number] = True #MADE SO SELF.TICKET_NUMBER DOESNT REMOVE KEY FROM THE DICT
        else:
            print("See you in 24 hours!")
            self.in_use_spaces[self.ticket_number] = True #MADE SO SELF.TICKET_NUMBER DOESNT REMOVE KEY FROM THE DICT

    def leavingGarage(self):
        parked = True
        while parked:
            extended = input("Would you like to extend your time? (Y/N)")
            if extended.upper() == "Y":
                more_time = int(input("Plase make a slection between 1-5: "))
            else:
                print("Thank you! Hope to see you again soon.")
                break

            if more_time == 1:
                print("You have 1 hour remaining")
            elif more_time == 2:
                print("You have 2 hours remaining")
            elif more_time == 3:
                print("You have 3 hours remaining")
            elif more_time == 4:
                print("You have 4 hours remaining")
            else:
                print("See you in 24 hours!")
       # add_ticket = len(self.ticket) + 1 #REMOMVED BC SELF.TICKET_NUMBER
        self.ticket.append(self.ticket_number)
        self.parking_spaces.append(self.ticket_number)
        self.ticket_number = None #ADDED THIS SO AT THE END THERE  IS N0 SELF.TICKET_NUMBER
        self.in_use_spaces = {} #MOVED WHAT WAS HERE TO THE PAYFORPARKING  SECTION SO THAT WHEN THEY LEAVE THE GARAGE, PARKING_SPACES IS NOW EMPTY

car1 = Parking(15, 15)
print(car1.__dict__)
car1.takeTicket()
print(car1.__dict__)
car1.payForParking()
print(car1.__dict__)
car1.leavingGarage()
print(car1.__dict__)


from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.properties import ListProperty, ObjectProperty
from kivy.uix.popup import Popup
from kivy.uix.progressbar import ProgressBar
from kivy.clock import Clock
from tensorflow.keras.applications import VGG16
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras import Model
from tensorflow.keras.utils import to_categorical
from numpy import asarray
from sklearn import preprocessing
import os
import cv2
import numpy as np
import threading

from loadFile import PickerLayout

class TrainModel(FloatLayout):
    images = ListProperty([])
    labels = ListProperty([])

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # orientation = 'horizontal'
        size_hint = (1,0.4)
        self.progress_value = 0
        self.thread_flag = False
        # self.image = image

        self.trainBox = BoxLayout(orientation = 'horizontal',
                                  size_hint = (None, None),
                                  width = 100,
                                  height = 40,
                                  pos_hint = {'center_x':0.5, 'center_y': 0.5})
        self.trainButton = Button(text = "Train Data",
                                  size = (100,40))
        self.trainBox.add_widget(self.trainButton)
        self.add_widget(self.trainBox)

        self.progressBar = ProgressBar()
        self.progressPop = Popup(title = 'Please wait while we train your images',
                                 content = self.progressBar,
                                 size_hint=(0.8, 0.2),
                                 auto_dismiss = False)

        self.trainButton.bind(on_press = self.progressUp)
        self.data = PickerLayout()

    def getImage(self, myPickerLayout, images):
        self.images = images

    def getLabel(self, myPickerLayout, labels):
        self.labels = labels

    def progressUp(self, instance):
        self.progressPop.open()
        self.thread_flag = True
        self.ev = threading.Event()
        self.thread = threading.Thread(target = self.train)
        self.thread.start()

    def dismiss(self, *args):
        self.ev.clear()
        self.thread_flag = False
        self.progressPop.dismiss()

    def clock(self, *args):
        #Stops the clock when the progress bar value reaches its maximum
        if self.progress_value >= 100:
            Clock.unschedule(self.clock)
        self.progressBar.value = self.progress_value

    def train(self):
        Clock.schedule_interval(self.clock, 1 / 60)
        image_input = []
        label_input = []
        for i in self.images:
            image_input.append(i)
        image_input = np.array(image_input)

        for i in self.labels:
            label_input.append(i)
        preprocess_label = preprocessing.LabelEncoder()
        label = preprocess_label.fit_transform(label_input)
        label = to_categorical(label)
        print(label.shape)
        num_label = len(label[0])
        model = VGG16(weights='imagenet',
                                  input_shape=(224, 224, 3),
                                  include_top=False)
        for layer in model.layers:
	        layer.trainable = False

        flat = Flatten()(model.layers[-1].output)
        flat2 = Dense(1024, activation='relu')(flat)
        output = Dense(num_label, activation='softmax')(flat2)
        # define new model
        model = Model(inputs=model.inputs, outputs=output)
        model.compile(optimizer='adam',
                      loss='binary_crossentropy',
                      metrics=['accuracy'])

        epochs = 3
        value = round(100 / epochs)
        for e in range(epochs):
            model.fit(image_input, label, epochs = 1, batch_size = 2)
            self.progress_value += value
        self.dismiss()
        # model.save("new model.h5")
        # print("model saved!")

        # y = model.predict(image_input)
        # print(y)
        # x = y.argmax(axis=-1)
        # print(x)
        # z = preprocess_label.inverse_transform(x)
        # print(z)


# matrix utils module

import json
import requests

def is_number(s):
  try:
    int(s)
    return True
  except ValueError:
    return False

def verifyTaxa(sci_name):

  sanitized_sci_name = sci_name.replace('H_', '')
  sanitized_sci_name = sanitized_sci_name.replace('"', '')
  sanitized_sci_name = sanitized_sci_name.replace("'", '')

  verifiedTaxa = []

  # NCBI is what Morphobank uses, checking all data sources to verify as close to 100% as possible
  # NCBI will be our preferred
  data_sources = '4'
  gnparser_url = 'http://resolver.globalnames.org/name_resolvers.json?perferred_data_sources=' + data_sources + '&best_match_only=true&resolve_once=false&names='

  gnparser = requests.get(gnparser_url + sanitized_sci_name + '&with_context=true')
  if 200 == gnparser.status_code:
    gnp_json = json.loads( gnparser.content )

    for data in gnp_json['data']:
      if data['is_known_name']:

        verifiedTaxa.append({
          "datasource": data['results'][0]['data_source_title'],
          "match_value": data['results'][0]['match_value'],
          "name_string": data['results'][0]['name_string']
        })

  return verifiedTaxa


import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline

def solve():
    N = int(rl())
    Y = list(map(int, rl().split()))

    dp = [[0] * (10 ** 4 + 1) for _ in range(N + 1)]
    for i in range(N):
        dp[i + 1][0] = dp[i][0] + Y[i]
        for j in range(1, 10 ** 4 + 1):
            dp[i + 1][j] = min(dp[i + 1][j - 1], dp[i][j] + abs(j - Y[i]))
    print(min(dp[N]))

if __name__ == '__main__':
    solve()


from admin import get_admin_info
from client import Admin, Client

def collect_requires() -> dict:
    """
    클라이언트의 요구사항을 수집하는 함수
    실제 서비스에선 Bootstrap의 Form 템플릿을 활용하기 때문에 해당 함수 불필요
    코드맵과 맵핑해야 하는 지역 및 직업은 select option으로 입력 처리
    True/False 입력값을 기대하는 키값들은 checkbox로 입력 처리
    나머지 키값들은 text로 입력 처리
    """

    requires = dict()

    requires['locations'] = input('희망하는 지역을 입력해주세요. ').split()
    requires['jobs'] = input('희망하는 직업을 입력해주세요. ').split()
    requires['assay'] = input('합격자소서 항목을 보시겠습니까? (Y/N) ') == 'Y'
    requires['skill'] = input('기술역량 항목을 보시겠습니까? (Y/N) ') == 'Y'
    # requires['skill_map'].append(input('기술역량 워드클라우드를 보시겠습니까? (Y/N)')) == 'Y'
    requires['salary_map'] = input('지역별 연봉 지도를 보시겠습니까? (Y/N) ') == 'Y'
    requires['count'] = input('검색할 채용공고 개수를 입력해주세요. (최대 110) ')
    requires['companies'] = list(input('희망하는 회사를 입력해주세요. (생략가능) '))

    return requires

def make_client(admin: Admin) -> Client:
    """
    클라이언트의 요청을 토대로 클라이언트 객체를 생성하고 반환하는 함수
    실제 서비스에선 Bootstrap의 Form 템플릿을 활용하기 때문에 입력값 검증 불필요
    """

    name = input('이름을 입력해주세요. ')
    address = input('이메일 주소를 입력해주세요. ')
    requires = collect_requires()
    return Client(name, address, requires, admin)

def debug_requires() -> dict:
    """
    디버그용 함수
    input()을 거치지 않고 미리 지정된 클라이언트 요구사항을 반환
    """

    requires = dict()

    requires['locations'] = ['서울']
    requires['jobs'] = ['인공지능']
    requires['assay'] = True
    requires['skill'] = True
    requires['salary_map'] = False
    requires['count'] = '5'
    requires['companies'] = ['비포플레이']

    return requires

def debug_client(admin: Admin) -> Client:
    """
    디버그용 함수
    input()을 거치지 않고 미리 지정된 정보를 사용해 클라이언트 생성
    """

    name = 'minyeamer'
    address = 'abcd1234@gmail.com'
    requires = debug_requires()
    return Client(name, address, requires, admin)

def main():
    """
    메인 함수
    관리자 및 클라이언트 객체를 생성하고 클라이언트에게 메일을 일괄적으로 전송
    """

    # admin.get_admin_info()는 개인정보 문제로 숨김 처리
    # Admin() 객체 생성 파라미터에 본인 이름, 메일주소, 메일비밀번호 순으로 입력
    admin_info = get_admin_info()
    admin = Admin(admin_info[0], admin_info[1], admin_info[2])

    # 클라이언트 요청이 있으면
    if True:
        # client = make_client(admin)
        client = debug_client(admin)
        client.request_contents()

    # 메일 발송 이벤트가 생기면 (관리자의 수동 조작 또는 자동 실행 봇 등)
    if True:
        admin.send_mail()

if __name__ == '__main__':
    main()


"""
TimeSlot node.
"""
from sqlalchemy import or_

from opendf.applications.smcalflow.nodes.time_nodes import *
from opendf.defs import VIEW, posname
from opendf.applications.smcalflow.exceptions.python_exception import TimeSlotException
from opendf.utils.utils import flatten_list, to_list, Message

SI_START = 10  # partial time interval as start
SI_END = 11
SI_BOUND = 12
SI_INTER = 13
SI_DUR = 14

class slot_interval:
    def __init__(self, iv, obj=None, typ=None, dur=None, durtyp=None, comp=None):
        self.interval = iv  # partial interval (None for dur)
        self.typ = typ  # PT_START/...
        self.dur = dur  # python datedelta for dur, else None
        self.durtyp = durtyp  # 'eq' / 'lt' ...
        self.obj = obj  # the original TimeSlot?()
        self.comp = comp  # compound slot

    si_names = {SI_START: 'start', SI_END: 'end', SI_DUR: 'dur', SI_BOUND: 'bound', SI_INTER: 'inter', }

    def __repr__(self):
        s = '%s %s' % (self.si_names[self.typ], self.interval if self.interval else 'obj=%s' % self.obj)
        return s

    def comparable_slot(self, other, mode=None):
        if self.typ == SI_DUR or other.typ == SI_DUR:
            return True
        return self.interval.comparable(other.interval, mode)

    def compatible_dur(self, other):
        if self.typ != SI_DUR or other.typ != SI_DUR:
            return True
        if self.durtyp == 'eq' or other.durtyp == 'eq':
            return False
        if self.durtyp in ['lt', 'le'] and other.durtyp in ['lt', 'le']:
            return False
        if self.durtyp in ['gt', 'ge'] and other.durtyp in ['gt', 'ge']:
            return False
        if self.durtyp in ['lt', 'le'] and other.durtyp in ['gt', 'ge'] and self.dur >= other.dur:
            return False
        if self.durtyp in ['gt', 'ge'] and other.durtyp in ['lt', 'le'] and self.dur <= other.dur:
            return False
        return True

    def compatible_bound(self, other):
        if self.typ != SI_BOUND or other.typ != SI_BOUND:
            return True
        if not self.interval.comparable(other.interval):
            return True
        if self.interval.intersect(other.interval):  # no negative bounds...
            return True
        return False

    def compatible_inter(self, other):
        if self.typ != SI_INTER or other.typ != SI_INTER:
            return True
        if not self.interval.comparable(other.interval):
            return True
        # always true for positive. For negative may not be true
        siv, oiv = self.interval, other.interval
        if siv.typ == 'nitv':
            if oiv.typ in ['nitv', 'neq']:
                return siv.intersect(oiv)
            else:
                return siv.bounds(oiv)
        if oiv.typ == 'nitv':
            return siv.intersect(oiv)
        if siv.typ in ['eq', 'neq'] and oiv.typ in ['eq', 'neq'] and siv.intersect(oiv):
            return False
        return True

    # update a list for a specific field - add new interval, and possibly remove older, incompatible, ones
    def update_field_list(self, curr, prune):
        upd = []
        typ = self.typ
        for o in curr:
            compat = self.compatible_dur(o) if typ == SI_DUR else \
                self.compatible_bound(o) if typ == SI_BOUND else \
                    self.compatible_inter(o) if typ == SI_INTER else \
                        self.interval.compatible(o.interval)
            if compat:
                upd.append(o)
            elif o not in prune:
                prune.append(o)
        upd.append(self)
        return upd, prune

    # TODO: verify logic for all the prune_xx_list cases

    # curr is a list of bound constraints.
    # self is an interval (of a type not bound - that was already covered in update_field_list).
    # prune bounds which are incompatible with self.
    def prune_bound_list(self, curr, prune):
        upd = []
        typ = self.typ
        for o in curr:
            compat = True
            if typ in [SI_START, SI_END]:
                compat = True if not self.interval.comparable(o.interval) else o.interval.bounds(self.interval)
            elif typ == SI_DUR:
                compat = self.dur > o.interval.length()
            elif typ == SI_INTER:
                compat = False  # TODO:
            if compat:
                upd.append(o)
            elif o not in prune:
                prune.append(o)
        return upd, prune

    def prune_inter_list(self, curr, prune):
        upd = []
        typ = self.typ
        for o in curr:
            compat = True
            if typ == SI_START:
                compat = not self.interval.strictly_after(o.interval)
            elif typ == SI_END:
                compat = not self.interval.strictly_before(o.interval)
            elif typ == SI_DUR:
                compat = True
            elif typ == SI_BOUND:
                compat = False  # TODO:
            if compat:
                upd.append(o)
            elif o not in prune:
                prune.append(o)
        return upd, prune

    # handles only bound, inter, and direct interaction with start - no INDIRECT interaction between start/end/dur
    def prune_start_list_simp(self, curr, prune):
        upd = []
        typ = self.typ
        for o in curr:
            compat = True
            if typ == SI_BOUND:
                compat = not (self.interval.strictly_before(o.interval) or self.interval.strictly_after(o.interval))
            elif typ == SI_INTER:
                compat = not self.interval.strictly_before(o.interval)
            elif typ == SI_END:
                compat = not self.interval.strictly_before(o.interval)  # direct interaction (end before start)
            if compat:
                upd.append(o)
            elif o not in prune:
                prune.append(o)
        return upd, prune

    # handles only bound, inter, and direct interaction with end - no INDIRECT interaction between start/end/dur
    def prune_end_list_simp(self, curr, prune):
        upd = []
        typ = self.typ
        for o in curr:
            compat = True
            if typ == SI_BOUND:
                compat = not (self.interval.strictly_before(o.interval) or self.interval.strictly_after(o.interval))
            elif typ == SI_INTER:
                compat = not self.interval.strictly_after(o.interval)
            elif typ == SI_START:
                compat = not self.interval.strictly_after(o.interval)
            if compat:
                upd.append(o)
            elif o not in prune:
                prune.append(o)
        return upd, prune

    # handles only bound, inter, and direct interaction with end - no INDIRECT interaction between start/end/dur
    def prune_dur_list_simp(self, curr, prune):
        upd = []
        typ = self.typ
        for o in curr:
            compat = True
            if typ == SI_BOUND:
                compat = self.interval.length() < o.dur
            elif typ == SI_INTER:
                compat = True
            if compat:
                upd.append(o)
            elif o not in prune:
                prune.append(o)
        return upd, prune

    # This is called when the latest interval is a bound
    # - the interval is already added to the curr_bound, as the last element.
    # - the curr_bound list does NOT have to be updated - it was updated in the previous turn, and adding a new
    #   bound (which might have pruned a previous bound object) will not cause any more bounds to be pruned
    def prune_lists_by_bound(self, curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune):
        curr_inter, prune = self.prune_inter_list(curr_inter, prune)
        curr_start, prune = self.prune_start_list_simp(curr_start, prune)
        curr_end, prune = self.prune_end_list_simp(curr_end, prune)
        curr_dur, prune = self.prune_dur_list_simp(curr_dur, prune)
        return curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune

    def prune_lists_by_inter(self, curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune):
        curr_bound, prune = self.prune_bound_list(curr_bound, prune)
        curr_start, prune = self.prune_start_list_simp(curr_start, prune)
        curr_end, prune = self.prune_end_list_simp(curr_end, prune)
        curr_dur, prune = self.prune_dur_list_simp(curr_dur, prune)
        return curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune

    def prune_lists_by_start(self, curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune):
        curr_bound, prune = self.prune_bound_list(curr_bound, prune)
        curr_inter, prune = self.prune_inter_list(curr_inter, prune)
        curr_end, prune = self.prune_end_list_simp(curr_end, prune)
        curr_dur, prune = self.prune_dur_list_simp(curr_dur, prune)
        # curr interval (self) is start.
        # find which is the last constraint (from end or dur) which is comparable (compatible?) with it, and prune
        # the "other". for now - aggressively prune the other if comparable
        # TODO: we should prune only if the "other" is incompatible with the combination of self+"last"
        c_end = [o for o in curr_end if self.interval.comparable(o.interval)]
        c_dur = [o for o in curr_dur if self.interval.comparable(o.interval)]
        if c_end and c_dur:
            if c_end[-1].obj.created_turn > c_dur[-1].obj.created_turn:
                curr_dur = [o for o in curr_dur if o not in c_dur]
                prune += c_dur
            else:
                curr_end = [o for o in curr_end if o not in c_end]
                prune += c_end
        return curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune

    def prune_lists_by_end(self, curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune):
        curr_bound, prune = self.prune_bound_list(curr_bound, prune)
        curr_inter, prune = self.prune_inter_list(curr_inter, prune)
        curr_start, prune = self.prune_start_list_simp(curr_start, prune)
        curr_dur, prune = self.prune_dur_list_simp(curr_dur, prune)
        c_start = [o for o in curr_start if self.interval.comparable(o.interval)]
        c_dur = [o for o in curr_dur if self.interval.comparable(o.interval)]
        if c_start and c_dur:
            if c_start[-1].obj.created_turn > c_dur[-1].obj.created_turn:
                curr_dur = [o for o in curr_dur if o not in c_dur]
                prune += c_dur
            else:
                curr_start = [o for o in curr_start if o not in c_start]
                prune += c_start
        return curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune

    def prune_lists_by_dur(self, curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune):
        curr_bound, prune = self.prune_bound_list(curr_bound, prune)
        curr_inter, prune = self.prune_inter_list(curr_inter, prune)
        curr_start, prune = self.prune_start_list_simp(curr_start, prune)
        curr_end, prune = self.prune_end_list_simp(curr_end, prune)
        c_start = [o for o in curr_start if o.interval.comparable(self.interval)]
        c_end = [o for o in curr_end if o.interval.comparable(self.interval)]
        if c_start and c_end:
            if c_start[-1].obj.created_turn >= c_end[-1].obj.created_turn:
                curr_end = [o for o in curr_end if o not in c_end]
                prune += c_end
            else:
                curr_start = [o for o in curr_start if o not in c_start]
                prune += c_start
        return curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune

    def prune_curr(self, curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune):
        typ = self.typ

        # 1. separate update per field
        if typ == SI_START:
            curr_start, prune = self.update_field_list(curr_start, prune)
        elif typ == SI_END:
            curr_end, prune = self.update_field_list(curr_end, prune)
        elif typ == SI_DUR:
            curr_dur, prune = self.update_field_list(curr_dur, prune)
        elif typ == SI_BOUND:
            curr_bound, prune = self.update_field_list(curr_bound, prune)
        elif typ == SI_INTER:
            curr_inter, prune = self.update_field_list(curr_inter, prune)

        # 2. prune with interactions
        # don't try to prune again same type - the interval is already in the curr_... - will prune itself
        if typ == SI_BOUND:
            curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune = \
                self.prune_lists_by_bound(curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune)

        elif typ == SI_INTER:
            curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune = \
                self.prune_lists_by_inter(curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune)

        elif typ == SI_START:
            curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune = \
                self.prune_lists_by_start(curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune)

        elif typ == SI_END:
            curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune = \
                self.prune_lists_by_end(curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune)

        elif typ == SI_DUR:
            curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune = \
                self.prune_lists_by_dur(curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune)

        return curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune

def bound_surround_event(bound, start_column, end_column, selection, kwargs):
    """
    Add conditions to `selection` in order to check if `bound` surrounds the interval defined by `start_column` and
    `end_column`.

    :param bound: the bound
    :type bound: Range
    :param start_column: the start column
    :type start_column: Any
    :param end_column: the end column
    :type end_column: Any
    :param selection: the selection
    :type selection: Any
    :param kwargs: additional parameters
    :type kwargs: Dict[str, Any]
    :return: the new selection, with the surrounding conditions
    :rtype: Any
    """
    qualifier = kwargs.get("qualifier")
    kwargs["qualifier"] = GE()
    selection = bound.input_view("start").generate_sql_where(selection, start_column, **kwargs)
    kwargs["qualifier"] = LE()
    selection = bound.input_view("end").generate_sql_where(selection, end_column, **kwargs)
    kwargs["qualifier"] = qualifier
    return selection

def event_surround_point(start_column, end_column, point, selection, kwargs):
    """
    Add conditions to `selection` in order to check if the event, represented by `start_column` and `end_column`
    surrounds the `point` in time.

    :param start_column: the start column
    :type start_column: Any
    :param end_column: the end column
    :type end_column: Any
    :param point: the point in time
    :type point: Date or Time or DateTime
    :param selection: the selection
    :type selection: Any
    :param kwargs: additional parameters
    :type kwargs: Dict[str, Any]
    :return: the new selection, with the surrounding conditions
    :rtype: Any
    """
    qualifier = kwargs.get("qualifier")
    kwargs["qualifier"] = LE()
    selection = point.generate_sql_where(selection, start_column, **kwargs)
    kwargs["qualifier"] = GE()
    selection = point.generate_sql_where(selection, end_column, **kwargs)
    kwargs["qualifier"] = qualifier
    return selection

class TimeSlot(Node):
    """
    Describes a time slot.
    """

    # TimeSlot unifies values and constraints which describe a time slot object / constraint.
    # The basic object has start, end, and duration; additionally, constraints can specify a (partial) time span
    # which the slot should be bound by or intersect with.
    # Since all these arguments are inter-connected, processing can not be done independently.
    # TimeSlot implements the logic for the interaction between them.
    # In the simplified annotation, we use modifiers to create constraints, so we can expect the following timeslots:
    #  - for an object from the DB - start, end, duration (as one TimeSlot object)
    #    - when converted to a constraint, it will be separated to 3 TimeSlot constraints - for start, end, duration
    #  - from a modifier:
    #    - this translates to a constraint with only one field:
    #       - has_start / has_end / has_duration - start / end / duration only (similarly for the negative ones)
    #          - at least for now, we assume the argument is one of:
    #                  - simple time value:                 DateTime, Date, Time - 9AM
    #                  - qualifier over simple time value:  DateTime, Date, Time - GT(9AM)
    #                  - range:              DateTimeRange, DateRange, TimeRange - Morning(), TimeRange(9AM, 11AM)
    #                       - which is internally converted to AND(GE(start), LE(end))
    #                         so that the default match() will work
    #                  i.e. - the argument can be represented by one interval
    #             - if there are aggregators, they will be outside the modifiers, not inside
    #               - >> any contradictory examples?
    #       - at_time - one argument (time point or interval), simple values, without any operators (quals / aggs)
    #             - e.g. at time(morning()) / at_time(9AM)
    #             - argument can be represented by one interval
    #          the plan is to translate this, depending on context, to either timeslot.bound or timeslot.inter
    #          - find event at_time(time point/range) means intersection
    #               - the point is during the event, or there is an intersection between the event and the range
    #          - create event at_time(range) means bounding interval:
    #               - create event EXACTLY at this range, or sub part of this range

    def __init__(self):
        super().__init__(type(self))
        self.signature.add_sig('start', [Date, Time, DateTime, TimeRange, DateRange, DateTimeRange])
        self.signature.add_sig('end', [Date, Time, DateTime, TimeRange, DateRange, DateTimeRange])
        self.signature.add_sig('duration', Period)
        # 'bound' - means the time slot is bounded to be within a time range
        #           (i.e. both start and end are within that range)
        #           e.g. "create a meeting in the afternoon / tomorrow"
        #         we could interpret point (as opposed to range) input as whole day / month / hour / ... ??
        #         note - "not in the morning" translates to negative 'inter', not 'bound' - no negative bounds
        self.signature.add_sig('bound', [Date, Time, DateTime, TimeRange, DateRange, DateTimeRange], custom=True)
        # 'inter' - means the time slot intersects a time point/range
        #      e.g. "find an event at 10AM / in the afternoon"
        self.signature.add_sig('inter', [Date, Time, DateTime, TimeRange, DateRange, DateTimeRange], custom=True)

    def generate_sql_where(self, selection, parent_id, **kwargs):
        """
        Generates the SQL where conditions to select objects conforming to TimeSlot.

        :param selection: the previous selection
        :type selection: Any
        :param parent_id: the parent id
        :type parent_id: Any
        :param kwargs: the mapping from the database columns to the time slot fields, must contain a mapping for
        start and end
        :type kwargs: Dict[str, Any]
        :return: the SQL query with the conditions
        :rtype: Any
        """
        start_column = kwargs["start"]
        end_column = kwargs["end"]

        if "start" in self.inputs:
            selection = self.input_view("start").generate_sql_where(selection, start_column, **kwargs)

        if "end" in self.inputs:
            selection = self.input_view("end").generate_sql_where(selection, end_column, **kwargs)

        if "duration" in self.inputs:
            selection = self.input_view("duration").generate_sql_where(selection, parent_id, **kwargs)

        # In order for it to work properly, the DateTime, Date or Time must be fully specified
        if "bound" in self.inputs:
            bound = self.input_view("bound")
            if isinstance(bound, Range):
                selection = bound_surround_event(bound, start_column, end_column, selection, kwargs)
            else:
                selection = bound.generate_sql_where(selection, start_column, **kwargs)
                selection = bound.generate_sql_where(selection, end_column, **kwargs)

        # In order for it to work properly, the DateTime, Date or Time must be fully specified
        if "inter" in self.inputs:
            bound = self.input_view("inter")
            if isinstance(bound, Range):
                conditions = []
                # we have start_column twice in the call below, because we want to check if the bound surrounds the
                # start of the event. Same for the end_column
                start = bound.input_view('start')
                end = bound.input_view('end')
                conditions.append(
                    bound_surround_event(bound, start_column, start_column, select(), kwargs).whereclause.self_group())
                conditions.append(
                    bound_surround_event(bound, end_column, end_column, select(), kwargs).whereclause.self_group())
                conditions.append(
                    event_surround_point(start_column, end_column, start, select(), kwargs).whereclause.self_group())
                conditions.append(
                    event_surround_point(start_column, end_column, end, select(), kwargs).whereclause.self_group())
                selection = selection.where(or_(*conditions).self_group())
            else:
                # intersect is a point
                selection = event_surround_point(start_column, end_column, bound, selection, kwargs)

        return selection

    def custom_match(self, nm, obj, iview=VIEW.INT, oview=None, check_level=False, match_miss=False):
        # self is a TimeSlot constraint, obj is a "real" TimeSlot object (not a constraint)
        # since obj is real object, guaranteed that intervals are always comparable
        if nm == 'bound':
            c = self.input_view('bound')  # constraint should be a simple object! (check?)
            pt = c.to_partialInterval()
            si = obj.to_slot_interval().interval
            return pt.bounds(si)
        elif nm == 'inter':
            c = self.input_view('inter')
            pt = c.to_partialInterval()
            si = obj.to_slot_interval().interval
            return pt.intersect(si)
        return True

    def describe(self, params=None):
        s = ''
        obj = []
        pp = [] if params is None else params
        if isinstance(params, dict):
            pp['add_prep'] = 1
        else:
            pp += ['add_prep']
        if 'start' in self.inputs:
            msg = self.input_view('start').describe(pp)
            t, o = msg.text, msg.objects
            if t:
                s += ' starting ' + t
            obj += o
        if 'end' in self.inputs and ('start' not in self.inputs or 'duration' not in self.inputs):
            msg = self.input_view('end').describe(pp)
            t, o = msg.text, msg.objects
            if t:
                s += ' ending ' + t
            obj += o
        if 'duration' in self.inputs:
            msg = self.input_view('duration').describe(params)
            t, o = msg.text, msg.objects
            if t:
                s += ' lasting ' + t
            obj += o
        if 'bound' in self.inputs:
            msg = self.input_view('bound').describe(params)
            t, o = msg.text, msg.objects
            if t:
                s += ' during ' + t
            obj += o
        if 'inter' in self.inputs:
            msg = self.input_view('inter').describe(params)
            t, o = msg.text, msg.objects
            if t:
                s += ' intersecting ' + t
            obj += o
        return Message(s, objects=obj)

    def slot_ctree_str(self, sep_date=True, open_slot=True):
        """
        Converts the timeslot field of an ACTUAL event into ONE timeslot constraint.

        :type sep_date: bool
        :param open_slot: if `True`, create strings for printing (not for construction)
        :type open_slot: bool
        :rtype: List[str]
        """
        prms = []
        if 'start' in self.inputs:
            # TODO: sep_date - separate year/month/day to individual constraints
            #   e.g. if the user specifies month, then we should not prune the whole date (year, day) as well
            st = self.input_view('start')
            s = []
            if 'date' in st.inputs:
                s.append('date=%s' % id_sexp(st.input_view('date')))
            if 'time' in st.inputs:
                s.append('time=%s' % id_sexp(st.input_view('time')))
            if s:
                if sep_date:
                    prms.extend(['start=DateTime(%s)' % i for i in s])
                else:
                    prms.append('start=DateTime(' + ','.join(s) + ')')
        if 'end' in self.inputs:
            # TODO: sep_date - separate year/month/day to individual constraints?
            en = self.input_view('end')
            s = []
            if 'date' in en.inputs:
                s.append('date=%s' % id_sexp(en.input_view('date')))
            if 'time' in en.inputs:
                s.append('time=%s' % id_sexp(en.input_view('time')))
            if s:
                if sep_date:
                    prms.extend(['end=DateTime(%s)' % i for i in s])
                else:
                    prms.append('end=DateTime(' + ','.join(s) + ')')
        if 'duration' in self.inputs:
            prms.append('duration=%s' % id_sexp(self.input_view('duration')))
        # actual object - does not have 'bound', 'inter'
        if not prms:
            return None
        if open_slot:
            return prms
        return ['slot=TimeSlot?(%s)' % p for p in prms]

    @staticmethod
    def get_ptime_and_qual(nd):
        t = nd.typename()
        if nd.not_operator():
            v = nd.to_partialDateTime()
            return v, 'eq'
        if nd.is_qualifier():
            tp = t.lower() if t in ['LT', 'LE', 'GT', 'GE', 'EQ'] else None
            n = nd.input_view(posname(1))
            if tp and n:
                v = n.to_partialDateTime()
                return v, tp
        raise TimeSlotException('Error - get_ptime_val %s\n%s' % (nd, nd.show()))

    @staticmethod
    def input_to_interval(nd, neg=False):
        """
        Converts input to an interval.
        Assumes input is either:
           1. simple time value (Date, Time, DateTime);
           2. simple time value with a qualifier;
           3. AND(x, y) where x,y are of type 2.
        """
        if isinstance(nd, Range):
            nd, _ = Node.call_construct_eval(nd.to_constr_sexp(), nd.context)  # temp context. new nodes will be discarded
        if nd.typename() == 'AND':
            s, e = nd.get_input_views([posname(1), posname(2)])  # verify pos input names...
            if s and e:
                v1, t1 = TimeSlot.get_ptime_and_qual(s)
                v2, t2 = TimeSlot.get_ptime_and_qual(e)
                tt = t1[0] + t2[0]
                if tt in ['lg', 'gl']:  # make sure this corresponds to a valid time range
                    if tt == 'lg':
                        v1, t1, v2, t2 = v2, t2, v1, t1
                    incl = ('(' if t1 == 'gt' else '[') + (')' if t2 == 'lt' else ']')
                    return PartialInterval(v1, v2, incl=incl, neg=neg)
        if nd.not_operator():
            v = nd.to_partialDateTime()
            return PartialInterval(v, None, neg=neg)
        if nd.is_qualifier():
            v, tp = TimeSlot.get_ptime_and_qual(nd)
            return PartialInterval(v, None, tp, neg=neg)
        raise TimeSlotException('Error - input_to_interval %s\n %s' % (nd, nd.show()))

    def to_slot_interval(self, neg=False):
        """
        Converts a TimeSlot to a slot_interval. The input to start, end, bound, inter may be a simple time value,
        or a simple tree (i.e. a tree which can be represented as one interval).
        """
        start, end, dur, bound, inter = self.get_input_views(['start', 'end', 'duration', 'bound', 'inter'])
        if start:
            return slot_interval(TimeSlot.input_to_interval(start, neg), typ=SI_START, obj=self)  # obj=start)
        if end:
            return slot_interval(TimeSlot.input_to_interval(end, neg), typ=SI_END, obj=self)  # , obj=end)
        if bound:
            return slot_interval(TimeSlot.input_to_interval(bound, neg), typ=SI_BOUND, obj=self)  # , obj=bound)
        if inter:
            return slot_interval(TimeSlot.input_to_interval(inter, neg), typ=SI_INTER, obj=self)  # , obj=inter)
        if dur:
            typ, t = dur.typename(), 'eq'
            if typ in ['LT', 'LE', 'GT', 'GE', 'EQ'] and posname(1) in dur:
                dur = dur.input_view(posname(1))
                t = typ.lower()
                t = neg_typ[t] if neg else t
                typ = dur.typename()
            if typ == 'Period':
                d = dur.to_Ptimedelta()
                pt = dur.to_partialDateTime()
                return slot_interval(pt, typ=SI_DUR, dur=d, durtyp=t, obj=self)  # , obj=dur)
        raise TimeSlotException('Error - to_slot_interval %s\n%s' % (self, self.show()))

    @staticmethod
    def to_interval_clusters(t, neg=False):
        """
        For each OR - return all the objects under it as a set of objects.
        """
        typ = t.typename()
        if typ == 'NOT':
            return TimeSlot.to_interval_clusters(t.input_view(posname(1)), not neg)
        elif typ == 'AND':
            iv = []
            for i in t.inputs:
                iv.append(TimeSlot.to_interval_clusters(t.input_view(i), neg)[0])
            return iv
        elif typ == 'OR':
            return [[TimeSlot.to_interval_clusters(t.input_view(i), neg)[0] for i in t.inputs]]
        elif typ == 'TimeSlot':
            return [t.to_slot_interval(neg=neg)]
        else:
            raise TimeSlotException('Error - to comp interval: %s\n%s' % (t, t.show()))

    # do the two clusters have comparable elements?
    # c1, c2 are lists of slot_interval
    @staticmethod
    def comparable_clusters(c1, c2):
        for i1 in to_list(c1):
            for i2 in to_list(c2):
                if i1.comparable_slot(i2, mode='L4'):
                    return True
        return False

    # TODO: verify
    @staticmethod
    def get_prune(turns):
        """
        Finds TimeSlots which need to be pruned.

        This is run on a TimeSlot constraint tree it is possible that the TimeSlot constraint tree is a truncation of a
        different tree (e.g. and Event tree) - in that case, we want to prune the original (Event) tree, not the
        TimeSlot tree, so we return the objects to be pruned, but don't prune the tree.

        Pruning time slots is tricky since the different fields (start/end/duration) are interdependent. The turns in
        the turn tree are assumed to be combined with an AND. If a turn has multiple constraints, unless there is an
        OR in the turn, we extract the separate constraints from the tree and combine them with an AND.

        In case of OR: (note that here we are only concerned with pruning. OR is not a problem for matching...). We
        don't forbid the use of OR, but it can be tricky to prune constraints with OR. The current strategy is to allow
        OR turns but prune previous OR turns if there is a chance they could contradict later turns. If there is an
        OR (or several ORs) (possibly combined with ANDs), we group all the constraints under an OR to a cluster.
        For now, we simply check if there is any later turn which is comparable (i.e. uses intersecting time
        components), and if so, we prune the whole OR cluster. This is overly aggressive, but because of the interaction
        between the different fields, we can't be sure that constraints on different fields don't contradict. If an
        OR cluster survives this, we treat it as if it was an AND - it should not affect the pruning results.

        :return: a list of TimeSlot nodes to be pruned (they are NOT pruned yet - this is done somewhere else)
        """
        turn_ivs = []  # list of lists - intervals for each turn
        all_ivs, turn_bnds, niv = [], [], 0  # intervals for all turns, with indices showing start/end of each turn
        has_ors = []

        prune = []  # list of slot_intervals

        # 1. get intervals / interval-clusters per turn
        for t in turns:
            iv = []
            h = False
            if t:
                if t.get_subnodes_of_type('OR'):
                    iv = TimeSlot.to_interval_clusters(t)
                    h = True
                else:
                    pos, neg = t.get_pos_neg_objs()
                    ipos, prune_pos = TimeSlot.slot_to_interval(pos)
                    ineg, prune_neg = TimeSlot.slot_to_interval(neg, neg=True)
                    # ipos, ineg = [o.to_slot_interval() for o in pos], [o.to_slot_interval(neg=True)
                    #                                                    for o in neg]
                    prune.extend(prune_pos)  # TODO - fix - this is not a slot_interval
                    prune.extend(prune_neg)
                    iv = ipos + ineg
            has_ors.append(h)
            turn_ivs.append(iv)
            turn_bnds.append((niv, niv + len(iv)))
            all_ivs.extend(iv)
            niv += len(iv)

        prune_slots = set()  # slot intervals to prune

        # 2. prune OR clusters - if comparable
        #    after this (aggressive) pruning, there are no comparable OR's left, so it should not
        #    matter if it's interpreted as AND or OR
        for i, ti in enumerate(turn_ivs):
            for j, tj in enumerate(turn_ivs):
                if j > i and ti and tj and (has_ors[i] or has_ors[j]):
                    for ki in ti:
                        for kj in tj:
                            if isinstance(ki, list) or isinstance(kj, list):
                                if TimeSlot.comparable_clusters(ki, kj):
                                    prune_slots.update(set(to_list(ki)))

        # 3. collect intervals which were not pruned
        all_ivs = [i for i in flatten_list(turn_ivs) if i not in prune_slots]

        # 4. collect intervals to prune

        # go over all intervals, from old to new. At each interval:
        #   1. update a (pruned) list of intervals, separately for each one of (start, end, dur);
        #   2. prune previous intervals taking into account interactions between different types.

        curr_start, curr_end, curr_dur, curr_bound, curr_inter = [], [], [], [], []
        for siv in all_ivs:
            curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune = \
                siv.prune_curr(curr_start, curr_end, curr_dur, curr_bound, curr_inter, prune)

        return prune

    @staticmethod
    def slot_to_interval(time_slots, neg=False):
        intervals = []
        prune = []
        for time_slot in time_slots:
            try:
                intervals.append(time_slot.to_slot_interval(neg=neg))
            except TimeSlotException:
                prune.append(time_slot)

        return intervals, prune


import math
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from collections import Counter
from sklearn.neighbors import KNeighborsClassifier
from random import random
import time
def L(x, y, p=2):
    if len(x) == len(y) and len(x) > 1:
        sum = 0
        for i in range(len(x)):
            sum += math.pow(x[i] - y[i], p)
        return math.pow(sum, 1 / p)
    else:
        return 0

class knn:
    def __init__(self, x_train, y_train, k=3, p=2):
        self.k = k
        self.p = p
        self.x_train = x_train
        self.y_train = y_train

    def predict(self, x):
        knn_list = []
        for i in range(self.k):
            dist = np.linalg.norm(x - x_train[i], ord=self.p)
            knn_list.append((dist, self.y_train[i]))

        for i in range(self.k, len(self.x_train)):
            max_index = knn_list.index(max(knn_list, key=lambda x: x[0]))
            dist = np.linalg.norm(x - x_train[i], ord=self.p)
            if knn_list[max_index][0] > dist:
                knn_list[max_index] = (dist, self.y_train[i])
        knn = [k[-1] for k in knn_list]
        count_pairs = Counter(knn)
        max_count = sorted(count_pairs.items(), key=lambda x: x[1])[-1][0]
        return max_count

    def score(self, x_test, y_test):
        right = 0
        for x, y in zip(x_test, y_test):
            label = self.predict(x)
            if label == y:
                right += 1
        return right / len(x_test)

# kd_tree
class KdNode(object):
    def __init__(self,dom_elt,split,left,right):
        self.dom_elt=dom_elt
        self.split=split
        self.left=left
        self.right=right

class KdTree(object):
    def __init__(self,data):
        k=len(data[0])
        def CreateNode(splite,data_set):
            if not data_set:
                return None
            data_set.sort(key=lambda x:x[splite])
            splite_position=len(data_set)//2
            median=data_set[splite_position]
            splite_next=(splite+1)%k
            return KdNode(median,splite,
                          CreateNode(splite_next,data_set[:splite_position]),
                          CreateNode(splite_next,data_set[splite_position+1:]))
        self.root=CreateNode(0,data)

def preorder(root):
    print(root.dom_elt)
    if root.left:
        preorder(root.left)
    if root.right:
        preorder(root.right)

from math import sqrt
from collections import namedtuple

result=namedtuple("result_tuple","nearest_point nearest_dist nodes_visited")

def find_nearest(tree,point):
    k=len(point)
    def travel(kd_node,target,max_dist):
        if kd_node is None:
            return result([0]*k,float("inf"),0)
        nodes_visited=1
        s=kd_node.split
        pivot=kd_node.dom_elt
        if target[s]<=pivot[s]:
            near_node=kd_node.left
            further_node=kd_node.right
        else:
            near_node=kd_node.right
            further_node=kd_node.left
        temp1=travel(near_node,target,max_dist)
        nearest=temp1.nearest_point
        dist=temp1.nearest_dist
        nodes_visited+=temp1.nodes_visited

        if dist<max_dist:
            max_dist=dist
        temp_dist=abs(pivot[s]-target[s])
        if max_dist<temp_dist:
            return result(nearest,dist,nodes_visited)

        temp_dist=sqrt(sum((p1-p2)**2 for p1,p2 in zip(pivot,target)))
        if temp_dist<dist:
            nearest=pivot
            dist=temp_dist
            max_dist=dist
        temp2=travel(further_node,target,max_dist)
        nodes_visited+=temp2.nodes_visited
        if temp2.nearest_dist<dist:
            nearest=temp2.nearest_point
            dist=temp2.nearest_dist
        return result(nearest,dist,nodes_visited)
    return travel(tree.root,point,float("inf"))

def random_point(k):
    return [random() for _ in range(k)]

def random_points(k,n):
    return [random_point(k) for _ in range(n)]

if __name__ == '__main__':
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['label'] = iris.target
    df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
    print(df)

    data = np.array(df.iloc[:, :])
    x, y = data[:, :-1], data[:, -1]
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    print(x, y)

    clk = knn(x_train, y_train)
    score = clk.score(x_test, y_test)
    print(score)

    clk_sk = KNeighborsClassifier()
    clk_sk.fit(x_train, y_train)
    score_sk=clk.score(x_test, y_test)
    print(score_sk)

    N=400000
    t0=time.process_time()
    kd=KdTree(random_points(3,N))
    result=find_nearest(kd,[0.1,0.5,0.8])
    t1=time.process_time()
    print(t1-t0)
    print(result)


import tensorflow as tf, os, glob, random

def make_pipeline_multy_label(path, batch_size=256, shuffle=True, class_names=None, labels=True, par=False, im_size=(256, 256, 3)):
    AUTOTUNE = tf.data.experimental.AUTOTUNE
    W, H, D = im_size[0], im_size[1], im_size[2]
    if labels == True:
        addrs = glob.glob(path + str('*\\*.jpg' if path[-2:] == '\\' else '\\*\\*.jpg'))
    else:
        addrs = glob.glob(path + str('*.jpg' if path[-2:] == '\\' else '\\*.jpg'))

        if par == True:
            addrs2 = [int(name.split('\\')[-1].split('.')[0]) for name in addrs]
            addrs2 = sorted(addrs2)
            addrs = [path + f'\\{i}.jpg' for i in addrs2]

    if class_names == None:
        class_names = ['truck_crane',
                       'car',
                       'excavator',
                       'human',
                       'dump_truck',
                       'mining_loader',
                       'rink',
                       'bulldozer']

    if shuffle:
        random.shuffle(addrs)

    def parse_image(filename):
        parts = tf.strings.split(filename, os.path.sep)

        image = tf.io.read_file(filename)
        image = tf.image.decode_jpeg(image, channels=D)
        image = tf.image.convert_image_dtype(image, tf.float32)
        image = tf.image.resize(image, [W, H])
        if labels == True:
            label = []
            for i in range(len(class_names)):
                label.append(1 if parts[-2] == class_names[i] else 0)
            return image, label
        else:
            return image

    def create_dataset(file_list):
        ds=tf.data.Dataset.from_tensor_slices(file_list)
        ds=ds.map(parse_image, num_parallel_calls=AUTOTUNE)
        ds=ds.batch(batch_size)
        ds = ds.prefetch(AUTOTUNE)
        return ds

    return create_dataset(addrs)


from sympy import symbols
import numpy as np
from sklearn import datasets
import math
from sympy import plot_implicit as plt_eq
from sympy import lambdify
import matplotlib.pyplot as plt

#Reading Datasets
iris = datasets.load_iris()

#apriori probabilities
P_setosa = 1/3
P_virginica = 1/3
P_versicolor = 1/3

X_setosa_temp = iris.data[:50,:]
X_versicolor_temp = iris.data[50:100,:]
X_virginica_temp = iris.data[100:150,:]

np.random.shuffle(X_setosa_temp)
np.random.shuffle(X_versicolor_temp)
np.random.shuffle(X_virginica_temp)

X_setosa = X_setosa_temp[:40,:]
X_versicolor = X_versicolor_temp[:40,:]
X_virginica = X_virginica_temp[:40,:]

X_setosa_test = X_setosa_temp[40:,:]
X_versicolor_test = X_versicolor_temp[40:,:]
X_virginica_test = X_virginica_temp[40:,:]

#mean calculated
mean_X_setosa = np.mean(X_setosa,axis = 0)
mean_X_versicolor = np.mean(X_versicolor,axis = 0)
mean_X_virginica = np.mean(X_virginica,axis = 0)

#calculate covariance matrices
covariance_X_setosa = np.cov(X_setosa.T)
covariance_X_versicolor = np.cov(X_versicolor.T)
covariance_X_virginica = np.cov(X_virginica.T)

#inverses calcualtion
inv_covariance_X_setosa = np.linalg.inv(covariance_X_setosa)
inv_covariance_X_versicolor = np.linalg.inv(covariance_X_versicolor)
inv_covariance_X_virginica =np.linalg.inv(covariance_X_virginica)

#determinant calculation
det_covariance_X_setosa = np.linalg.det(covariance_X_setosa)
det_covariance_X_versicolor = np.linalg.det(covariance_X_versicolor)
det_covariance_X_virginica =np.linalg.det(covariance_X_virginica)

x1,x2,x3,x4 = symbols("x1 x2 x3 x4")

X_new_point = np.array([[x1],[x2],[x3],[x4]])

A_setosa=-(.5)*inv_covariance_X_setosa
B_setosa=np.matmul(inv_covariance_X_setosa,mean_X_setosa)
C_setosa= math.log(P_setosa) - (.5*math.log(det_covariance_X_setosa))- (.5*(np.matmul(mean_X_setosa.T,np.matmul(inv_covariance_X_setosa,mean_X_setosa))))

A_versicolor=-(.5)*inv_covariance_X_versicolor
B_versicolor=np.matmul(inv_covariance_X_versicolor,mean_X_versicolor)
C_versicolor=math.log(P_versicolor) - (.5*math.log(det_covariance_X_versicolor))- (.5*(np.matmul(mean_X_versicolor.T,np.matmul(inv_covariance_X_versicolor,mean_X_versicolor))))

A_virginica=-(.5)*inv_covariance_X_virginica
B_virginica=np.matmul(inv_covariance_X_virginica,mean_X_virginica)
C_virginica=math.log(P_virginica) - .5*math.log(det_covariance_X_virginica)- .5*(np.matmul(mean_X_virginica.T,np.matmul(inv_covariance_X_virginica,mean_X_virginica)))

#curve g1 g2
#curve g1 g3
#curve g2 g3

#Generating Discriminant Functions
G1 = np.matmul(X_new_point.T,np.matmul(A_setosa,X_new_point)) + np.matmul(B_setosa,X_new_point)+C_setosa
G2 = np.matmul(X_new_point.T,np.matmul(A_versicolor,X_new_point)) + np.matmul(B_versicolor,X_new_point)+C_versicolor
G3 = np.matmul(X_new_point.T,np.matmul(A_virginica,X_new_point)) + np.matmul(B_virginica,X_new_point)+C_virginica

G1 = G1[0][0]
G2 = G2[0][0]
G3 = G3[0][0]

error_count = 0

print("\nGiving 10 Setosa inputs - \n")
for i,each in enumerate(X_setosa_test):
    r1,r2,r3,r4 = each
    g1_val=G1.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    g2_val=G2.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    g3_val=G3.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    if(g1_val>g2_val and g1_val>g3_val):
        print(i,"Setosa")
    if(g2_val>g1_val and g2_val>g3_val):
        print(i,"Versicolor")
        error_count+=1
    if(g3_val>g2_val and g3_val>g1_val):
        error_count+=1
        print(i,"Virginica")

print("\nGiving 10 Versicolor inputs - \n")
for i,each in enumerate(X_versicolor_test):
    r1,r2,r3,r4 = each
    g1_val=G1.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    g2_val=G2.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    g3_val=G3.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    if(g2_val>g1_val and g2_val>g3_val):
        print(i,"Versicolor")
    if(g1_val>g2_val and g1_val>g3_val):
        error_count+=1
        print(i,"Setosa")
    if(g3_val>g2_val and g3_val>g1_val):
        error_count+=1
        print(i,"Virginica")

print("\nGiving 10 Virginica inputs - \n")
for i,each in enumerate(X_virginica_test):
    r1,r2,r3,r4 = each
    g1_val=G1.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    g2_val=G2.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    g3_val=G3.subs([(x1, r1), (x2, r2), (x3, r3),(x4,r4)])
    if(g1_val>g2_val and g1_val>g3_val):
        error_count+=1
        print(i,"Setosa")
    if(g2_val>g1_val and g2_val>g3_val):
        error_count+=1
        print(i,"Versicolor")
    if(g3_val>g2_val and g3_val>g1_val):
        print(i,"Virginica")

#Accuracy Calculation
print("accuracy = "+str(1-(error_count/150)))


import unittest

outcome_points = {
  "A": {
    "X": 3,
    "Y": 6,
    "Z": 0,
  },
  "B": {
    "X": 0,
    "Y": 3,
    "Z": 6,
  },
  "C": {
    "X": 6,
    "Y": 0,
    "Z": 3,
  },
}

shape_points = {
  "X": 1,
  "Y": 2,
  "Z": 3,
}

outcomes = {
  "A": {
    "X": "Z",
    "Y": "X",
    "Z": "Y",
  },
  "B": {
    "X": "X",
    "Y": "Y",
    "Z": "Z",
  },
  "C": {
    "X": "Y",
    "Y": "Z",
    "Z": "X",
  },
}

def count_points(shapes):
    return shape_points[shapes[1]] + outcome_points[shapes[0]][shapes[1]]

def determine_outcomes(shapes):
    return [shapes[0], outcomes[shapes[0]][shapes[1]]]

def solve_1(input):
    return sum([count_points(line.split(" ")) for line in input])

def solve_2(input):
    return sum([count_points(determine_outcomes(line.split(" "))) for line in input])

with open("./input.txt") as f:
    input = f.read().splitlines()

class Test(unittest.TestCase):
    def test_solve_1(self):
        self.assertEqual(solve_1(input), 10994)

    def test_solve_2(self):
        self.assertEqual(solve_2(input), 12526)

unittest.main()


import sys
sys.path.append('../src/')
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
import numpy as np
from time import time, localtime, strftime

from nn.DQN import DQN_R
from nn.DoubleDQN import DoubleDQN

# np.random.seed(2020)

def train(conf, config, sofa):
    if conf['mode'] == 'DQN':
        rl = DQN_R(config)
    elif conf['mode'] == 'DoubleDQN':
        rl = DoubleDQN(config)

    num_users = sofa.num_users
    # num_episodes = num_users * 1000
    cumu_rewards = []
    learnstep_cr = []
    load_time, learn_time = 0, 0
    begin_time = time()
    # filename = conf["data.input.path"] + conf["data.input.dataset"] + '_' + \
    #     conf["data.gen_model"] + '_' + conf["data.debiasing"] + '_plot.pdf'
    # plot_data_file = conf["data.input.path"] + conf["data.input.dataset"] + '_' + \
    #     conf["data.gen_model"] + '_' + conf["data.debiasing"] + '_plot.data'
    filename = conf["data.input.path"] + config['SAVE_MODEL_FILE'] + 'plot.pdf'
    plot_data_file = conf["data.input.path"] + config['SAVE_MODEL_FILE'] + 'plot.data'

    users = np.arange(num_users, dtype=int)
    testuser_only = False
    if testuser_only and conf["data.input.dataset"].lower() == 'yahoo':
        test_file = conf["data.input.path"] + conf["data.input.dataset"] + "_test.ascii"
        RatingM = np.loadtxt(test_file).astype(int)
        users = users[np.where(np.sum(RatingM, axis=1)==0, False, True)]
        print("When learning a policy, we only use the user appeared in the testset. The number is %d" % users.shape[0], flush=True)
        num_users = users.shape[0]

    # ## for remove the non-click users
    # print("*********** Please note we remove the non-click users")
    # clicks = np.where(sofa.ratings > 3, 1, 0)
    # clicks_peruser = np.sum(clicks, axis=1)
    # keepusers = np.where(clicks_peruser<=4, False, True)
    # users = np.arange(num_users, dtype=int)[keepusers]
    # print("********** After removing clicks < 4, we have %d users" % (users.shape[0]))

    step = 0
    batch_size = 10
    epoch = 3000
    trick1_happen = 0
    for epoch in range(epoch):
        np.random.shuffle(users)

        ## single user interaction
        # for idx in range(num_users):
        #     # user_id = np.random.randint(num_users)
        #     user_id = users[idx]
        #     sofa.reset(user_id)
        #     state = sofa.state
        #     history = []
        #     cumu_reward = 0
        #     while True:
        #         action = rl.choose_action(state)
        #         history.append(action)
        #         (state_, reward, done) = sofa.step(action)
        #         cumu_reward += reward
        #         state = state_
        #         rl.store_memory(state, action, reward, state_)
        #         if done:
        #             break
        #     cumu_rewards.append(cumu_reward)
        #     rl.learn()
        #     step += 1

        # multi-user interaction
        losses = []
        start_idx = 0
        while start_idx < num_users:
            user_ids = users[start_idx:(start_idx+batch_size)]
            user_batch = user_ids.shape[0]
            start_idx += batch_size
            sofa.reset(user_ids)
            states = sofa.state.copy()
            cumu_reward = np.zeros(user_ids.shape[0])
            states_actions_batch = []
            while True:
                actions = rl.choose_actions(states, sofa.step_count)
                (states_, rewards, done) = sofa.step(actions)
                # print(states.shape, states_.shape)
                cumu_reward += rewards
                states_actions_batch.append((states.copy(), actions, rewards, states_.copy()))
                rl.store_memorys(states, actions, np.where(rewards==0, -1, 2), states_, sofa.step_count-1, sofa.step_count)
                # rl.store_memorys(states, actions, rewards, states_, sofa.step_count-1, sofa.step_count)
                states = states_.copy()
                if done:
                    break
            # if rl.epsilon == rl.epsilon_min:
            #     keep = np.where(cumu_reward<1, False, True)
            #     for turn in range(len(states_actions_batch)):
            #         (s, a, r, s_) = states_actions_batch[turn]
            #         trick1_happen += (user_batch - np.sum(keep))
            #         if np.sum(keep) == 0:
            #             continue
            #         rl.store_memorys(s[keep], a[keep], np.where(r==0, -1, 2)[keep], s_[keep], turn, turn+1)
            # else:
            #     for turn in range(len(states_actions_batch)):
            #         (s, a, r, s_) = states_actions_batch[turn]
            #         rl.store_memorys(s, a, np.where(r==0, -1, 2), s_, turn, turn+1)
            cumu_rewards += list(cumu_reward)
            for _ in range(4):
                loss = rl.learn()
                if loss is None:
                    break
                # print(loss)
                losses.append(loss)

            if rl.learn_step_counter == 0:
                continue
            if rl.learn_step_counter % 1000 == 0:
                # print(cumu_rewards)
                avg_cumulativeReward = np.mean(cumu_rewards)
                cumu_rewards = []
                learnstep_cr.append([rl.learn_step_counter, avg_cumulativeReward])
                if (len(learnstep_cr) % 10 == 0):
                    plot_cumuReward(learnstep_cr, filename, plot_data_file)
            ## save model
            if rl.learn_step_counter % 5000 == 0:
                print("\nlearning step : %d, time consuming %4e s" % (rl.learn_step_counter, time()-begin_time), flush=True)
                print("learning step: %d, lr : %.5e, epsilon: %2f" % (rl.learn_step_counter, rl.get_lr(), rl.epsilon))
                print("loss:%.3e" % (np.mean(losses)), flush=True)
                begin_time = time()
                rl.save_model()
    if (epoch + 1) % 100 == 0:
        print("Till epoch %d, the trick-1 works for %d times" % (epoch+1, trick1_happen))

    plot_cumuReward(learnstep_cr, filename, plot_data_file)
    print("plot save into file:%s" % filename)

def plot_cumuReward(learnstep_cr, filename='line_plot.pdf', plot_data_file='line_plot.data'):
    np.savetxt(plot_data_file, np.array(learnstep_cr))
    # print("plot save into file:%s" % filename )
    import matplotlib.pyplot as plt
    learnstep_cr = np.array(learnstep_cr)
    plt.plot(learnstep_cr[:, 0].astype('int'), learnstep_cr[:, 1].astype('float'))
    plt.ylabel('Cumulative_Click')
    plt.xlabel('training steps')
    plt.savefig(filename)
    plt.show()
    plt.close()


from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import random
import time
class MainPage:
    def __init__ (self,Ui,Db,Con):
        self.Dialog=QtWidgets.QDialog()
        self.ui=Ui
        self.db=Db
        self.con=Con
        self.qPixmapVar = QPixmap()
        self.rspPicture=["image/paper.PNG","image/Scissors.PNG","image/rock.PNG"]
        self.nexonImage=["image/nexon1.PNG","image/nexon2.PNG","image/nexon3.PNG","image/nexon4.PNG","image/nexon5.PNG","image/nexon6.png"]
        self.planeGame=["image/plane.PNG","image/attack.jpg","image/monster.PNG","image/attack2.jpg"]
        self.pictureSet(1800,300,2,self.nexonImage[0])
        self.monTrue=1
        for index in range(0,3):
            number=6+index
            if number==7:
                self.pictureSet(80,30,number,self.planeGame[3])
            else:self.pictureSet(150,120,number,self.planeGame[index])
        self.locate=0
        self.num=0
        self.playerNum=0
        self.score=0
    def mainFlow(self,value):
        if value==4:
            pass
        elif value==5:
            pass
        elif value==3:
            self.ui.stackedWidget.setCurrentIndex(0)
            self.gameReset()
            self.con.reset(self.ui.joinCheckList,self.ui.widEtc4List,self.ui.loginLineList,self.ui.findIdpageList,self.ui.joinEnterList)
        else:
            self.playerRSP(value)

    def pictureSet(self,wid,high,num,image):
        self.qPixmapVar.load(image)
        self.qPixmapVar = self.qPixmapVar.scaledToWidth(wid)
        self.qPixmapVar = self.qPixmapVar.scaledToHeight(high)
        self.ui.mainPic3List[num].setPixmap(self.qPixmapVar)

    def playerRSP(self,value):
        self.playerNum=value
        self.pictureSet(120,80,4,self.rspPicture[value])
        self.enemy(value)

    def rspAiPrint(self,random): # computer 와 같이 변환 가능
        self.pictureSet(120,80,5,self.rspPicture[random])

    def enemy(self,player):
        randAi=random.randint(0,2)
        self.pictureSet(120,80,5,self.rspPicture[randAi])
        if player==randAi:
            self.result="DRAW"
        elif player==2 and randAi==1:
            self.result="WIN"
        elif player==1 and randAi==0:
            self.result="WIN"
        elif player==0 and randAi==2:
            self.result="WIN"
        else:
            self.result="ROSE"
        self.ui.mainPic3List[3].setText(self.result)

    def mainPictureChange(self,num):
        self.pictureSet(1800,300,2,self.nexonImage[num])
        self.ui.mainPic3List[1].setText(str(num+1)+"/6")

    def scrollChange(self,value):
        X,Y,high2=value[0],value[1],value[2]
        X+=11
        Y+=45
        if self.ui.verticalScrollBar2.value()!=0:
            high=self.ui.verticalScrollBar2.value()
            high-=high2
            self.ui.MainWindow.setGeometry(X,Y-high*8,892,1985)
            print(Y-high)

    def location(self):
        X = self.ui.MainWindow.x()
        Y = self.ui.MainWindow.y()
        high=self.ui.verticalScrollBar2.value()
        self.locate=[X,Y,high]

    def attack(self,X):
        self.pictureSet(80,30,7,self.planeGame[1])
        self.ui.mainPic3List[7].setGeometry(220+X,1850,80,30)

        if X>=350:
            self.pictureSet(150,120,8,self.planeGame[3])
            self.pictureSet(80,30,7,self.planeGame[3])
            self.ui.mainPic3List[7].setGeometry(220,1850,80,30)
            self.score+=1
            self.ui.mainLogo3List[8].setText("score :"+str(self.score))
            self.monTrue=0

    def gameReset(self):
        self.monTrue=1
        self.pictureSet(150,120,8,self.planeGame[2])