import math
import torch
from missile import Missile
import random
from Qtorch import QLearning
import numpy as np
MISSILE_STATUS = {0: "Flying", 1: "Locked", 2: "Intercepted", 3: "Escaped"}
max_lock_missiles = 10 # 每轮锁定导弹的上限

class Environment:
    def __init__(self, missile_list, q_learning=None):
        self.missile_list = missile_list
        self.current_round = 0
        self.intercepted_missiles = []
        self.locked_missiles = []
        self.escaped_missiles = []
        self.num_states = len(missile_list)
        self.total_reward = 0  # 用于存储累计奖励
        self.q_learning = q_learning

    def get_missile_list(self):
        return self.missile_list
    def get_current_round(self):
        return self.current_round
    def set_current_round(self, round):
        self.current_round = round

    def launch_missiles(self):
        game_duration = 16000
        rewards = []  # 创建一个奖励列表
        total_reward = 0
        for elapsed_time in range(game_duration):
            self.update_missile_positions()
            self.update_missile_statuses()
            self.lock_missiles()

             # 在每个回合的开始时检查导弹是否被拦截
            for missile in self.missile_list:
                if missile.get_status() == 1 and self.current_round >= missile.get_intercept_round():
                    distance_to_origin = math.sqrt(missile.x ** 2 + missile.y ** 2)
                    if distance_to_origin < 2:
                        missile.set_status(3)
                    else:
                        missile.set_status(2)
            # Q-learning 策略选择动作
            if self.q_learning is not None and elapsed_time % 8 == 7:
                self.lock_missiles()
                state = [self.current_round] + [m.get_status() for m in self.missile_list]
                actions = [str(m.number) for m in self.missile_list if m.get_status() == 0]
                action = self.q_learning.choose_action(state, actions)
                if action is None:  # 检查 action 是否为 None
                    continue  # 如果为 None，则跳过当前迭代
                action_missile = next((m for m in self.missile_list if m.number == int(action) and m.get_status() == 0), None)
                if action_missile is not None:
                    distance_to_origin = math.sqrt(action_missile.x ** 2 + action_missile.y ** 2)
                    if distance_to_origin < 2:
                        action_missile.set_status(3)
                        q_reward = self.calculate_reward(action_missile) # 使用 calculate_reward 方法计算奖励
                    else:
                        if action_missile.height == 1:
                            q_success_rate = 0.7
                        elif action_missile.height == 2:
                            q_success_rate = 0.8
                        else:
                            q_success_rate = 0.9
                        if random.random() < q_success_rate:
                            action_missile.set_status(2)
                            if action_missile not in self.intercepted_missiles:
                                self.intercepted_missiles.append(action_missile)
                        else:
                            action_missile.set_status(0)  # 导弹拦截失败，状态转为0
                        q_reward = self.calculate_reward(action_missile) # 使用 calculate_reward 方法计算奖励
                    rewards.append(q_reward)  # 将单个导弹的奖励添加到列表中
                    total_reward += q_reward  # 更新总奖励
                    print(f"Round {self.current_round}: Total reward = {total_reward}")  # 在每个回合打印总奖励
                    next_state = [self.current_round + 1] + [m.get_status() for m in self.missile_list]
                    next_available_actions = [str(m.number) for m in self.missile_list if m.get_status() == 0]
                    self.q_learning.update_table(state, action, q_reward, next_state, next_available_actions=next_available_actions)
            self.current_round += 1
            # 判断游戏是否结束
            if self.is_end():
                break
        return rewards  # 游戏结束时返回 rewards 列表

    def get_total_reward(self):
        return self.total_reward

    def calculate_reward(self, missile):
        reward = 0
        height = missile.get_height()
        status = missile.get_status()
        if status == 2 and height == 1:
            reward += 3
        elif status == 2 and height == 2:
            reward += 2
        elif status == 2 and height == 3:
            reward += 1
        elif status == 3:
            reward -= 10
        else:  # 拦截失败
            reward -= 1
        return reward

    def update_missile_positions(self):
        active_missiles = [missile for missile in self.missile_list if missile.get_status() in [0, 1] and missile.launch_round <= self.current_round]
        if not active_missiles:
            return
        positions = torch.tensor([[float(m.x), float(m.y)] for m in self.missile_list], dtype=torch.float)
        positions = positions.float()
        distances = torch.norm(positions, dim=1).float()
        directions = - positions / distances.view(-1, 1)
        new_positions = positions + directions * torch.tensor([float(m.speed) for m in self.missile_list]).view(-1, 1)
        for i, missile in enumerate(self.missile_list):
            if missile.get_status() in [0, 1] and missile.launch_round <= self.current_round:
                missile.set_position(new_positions[i][0].item(), new_positions[i][1].item())
                missile.distance = distances[i].item()

    def lock_missiles(self, actions=None):
        active_missiles = [missile for missile in self.missile_list if
                           missile.get_status() == 0 and missile.launch_round <= self.current_round]
        if not active_missiles:
            return
        if self.q_learning is not None and actions is not None:
            if not actions:
                return
            num_missiles_to_lock = min(len(actions), max_lock_missiles)
            chosen_actions = []
            for _ in range(num_missiles_to_lock):
                state = (self.current_round, len(active_missiles), len(actions))
                action = self.q_learning.choose_action(state, actions)
                chosen_actions.append(action)
                actions.remove(action)

            for action in chosen_actions:
                missile_number = int(action)
                missile = next(
                    (m for m in self.missile_list if m.number == missile_number), None)
                if missile is not None and missile.get_status() == 0:
                    distance_to_origin = math.sqrt(
                        missile.x ** 2 + missile.y ** 2)
                    if distance_to_origin < 2:
                        missile.set_status(3)
                    else:
                        missile.set_status(1)
                    intercept_time = distance_to_origin / (2 * missile.speed)
                    intercept_round = int(intercept_time)
                    missile.set_intercept_round(
                        self.current_round + intercept_round)

                    # 更新Q值
                    if missile.get_status() == 1:
                        state = (self.current_round, len(active_missiles), len(actions) + 1)
                        next_state = (self.current_round, len(active_missiles) - 1, len(actions))
                        next_available_actions = actions.copy()
                        next_available_actions.append(action)
                        reward = self.get_intercept_success_rate(missile) - 1
                        self.q_learning.update_table(state, action, reward, next_state, next_available_actions)

    def update_missile_statuses(self):
        for missile in self.missile_list:
            if missile.get_status() == 0:
                distance_to_origin = math.sqrt(missile.x ** 2 + missile.y ** 2)
                if distance_to_origin < 2:
                    missile.set_status(3)
            elif missile.get_status() == 1:
                distance_to_origin = math.sqrt(missile.x ** 2 + missile.y ** 2)
                intercept_round = int(distance_to_origin / (2 * missile.speed))
                missile.set_intercept_round(intercept_round)
                if self.current_round >= missile.launch_round + intercept_round:
                    if random.random() < self.get_intercept_success_rate(missile):
                        missile.set_status(2)
                        if missile not in self.intercepted_missiles:
                            self.intercepted_missiles.append(missile)
                    else:
                        missile.set_status(3)
                elif missile.get_status() == 2:
                    if missile not in self.intercepted_missiles:
                        self.intercepted_missiles.append(missile)

    def get_intercept_success_rate(self, missile):
        if missile.height == 1:
            return 0.7
        elif missile.height == 2:
            return 0.8
        else:
            return 0.9

    def remove_missiles(self, q_learning):
        intercepted_missiles = []
        escaped_missiles = []
        locked_missiles = []
        for missile in self.missile_list:
            if missile.get_status() == 2:  # Intercepted
                intercepted_missiles.append(missile)
            elif missile.get_status() == 3:  # Escaped
                escaped_missiles.append(missile)
            elif missile.get_status() == 1:  # Locked
                locked_missiles.append(missile)
        return self.missile_list, intercepted_missiles, escaped_missiles, locked_missiles

    def is_end(self):
        if all(missile.get_status() in [2, 3] for missile in self.missile_list):
            return True
        if self.get_current_round() > 20:
            return True
        return False

    def reset(self, missile_list):
        self.missile_list = missile_list
        self.score = 0
        self.locked_missiles = []
        self.intercepted_missiles = []
        self.escaped_missiles = []
        self.current_round = 0
        return self.get_state()

    def get_state(self):
        state = []
        for missile in self.missile_list:
            state.append(missile.status)
        return tuple(state)

    def get_intercepted_missiles(self):
        return self.intercepted_missiles

    def get_available_actions(self):
        actions = []
        for missile in self.missile_list:
            if missile.get_status() == 0:
                actions.append(str(missile.number))
        return actions


# https://mp.weixin.qq.com/s?__biz=MzI5MzQzMjU4Mw==&mid=2247487529&idx=1&sn=1de78b8e7141a118dd9c5c4eed15c8b2&chksm=ec736c41db04e557a639cd09722a3f3bec4643ca8f17bba17e92a2bd2b5802c6604355c5f001&scene=0&xtrack=1&key=dd5051400a9fb58f039a8acf24b9536d9ceca5303e36d6f09878cc021639e70a07a2aabff04519fe73d498d6c2477435848bde455e9d69c01dcd8e875574ba88afd10f012f06dabb3611ff790e6cd4c9&ascene=14&uin=MjA4NjMyMjkzOA%3D%3D&devicetype=Windows+10&version=62060833&lang=zh_CN&pass_ticket=I5KQYeQ4jpPG9uBdFjRVvm16WXRq6ukHz1Wq%2FLH61ndvGmkcVF5dkzqao5OLMBR3

import folium
import time
import requests
from urllib.request import quote
import numpy as np
import pandas as pd
import seaborn as sns
import webbrowser
from folium.plugins import HeatMap
address = ['北京','天津','石家庄','太原','呼和浩特','沈阳','大连','长春',
           '哈尔滨','上海','南京','杭州','宁波','合肥','福州','厦门','南昌',
           '济南','青岛','郑州','武汉','长沙','广州','深圳','南宁','海口',
           '重庆','成都','贵阳','昆明','拉萨','西安','兰州','西宁','银川','乌鲁木齐']

def getid(dizhi):
    url = "http://api.map.baidu.com/geocoder/v2/"
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36'}
    payload = {
        'output': 'json',
        'ak': 'X8zlxPUdSe2weshrZ1WqnWxb43cfBI2N'
    }
    addinfo = []
    for i in dizhi:
        payload['address'] = i
        try:
            content = requests.get(url, params=payload, headers=header).json()
            addinfo.append(content['result']['location'])
            print("正在获取{}的地址！".format(i))
        except:
            print("地址{}获取失败，请稍后重试！".format(i))
            pass
        time.sleep(.5)
    print("所有地址均已获取完毕！！！")
    return (addinfo)

if __name__ == "__main__":
    # 计时开始：
    t0 = time.time()
    myaddress = getid(address)
    t1 = time.time()
    total = t1 - t0
    print("消耗时间：{}".format(total))
    lon = np.array([i["lng"] for i in myaddress], dtype=float)
    lat = np.array([i["lat"] for i in myaddress], dtype=float)
    scale = np.random.randint(100, 500, len(address))
    data1 = [[lat[i], lon[i], scale[i]] for i in range(len(address))]

    map_osm = folium.Map(location=[35, 110], zoom_start=5)
    HeatMap(data1).add_to(map_osm)
    file_path = "E:/研一/cities.html"
    map_osm.save(file_path)
    webbrowser.open(file_path)


from .IdentifiedObject import IdentifiedObject

class WindContPType4bIEC(IdentifiedObject):
	'''
	P control model Type 4B.  Reference: IEC Standard 61400-27-1 Section 6.6.5.5.

	:dpmax: Maximum wind turbine power ramp rate (). It is project dependent parameter. Default: 0.0
	:tpaero: Time constant in aerodynamic power response (). It is type dependent parameter. Default: 0
	:tpord: Time constant in power order lag (). It is type dependent parameter. Default: 0
	:tufilt: Voltage measurement filter time constant (). It is type dependent parameter. Default: 0
	:WindTurbineType4bIEC: Wind turbine type 4B model with which this wind control P type 4B model is associated. Default: None
		'''

	cgmesProfile = IdentifiedObject.cgmesProfile

	possibleProfileList = {'class': [cgmesProfile.DY.value, ],
						'dpmax': [cgmesProfile.DY.value, ],
						'tpaero': [cgmesProfile.DY.value, ],
						'tpord': [cgmesProfile.DY.value, ],
						'tufilt': [cgmesProfile.DY.value, ],
						'WindTurbineType4bIEC': [cgmesProfile.DY.value, ],
						 }

	serializationProfile = {}

	__doc__ += '\n Documentation of parent class IdentifiedObject: \n' + IdentifiedObject.__doc__

	def __init__(self, dpmax = 0.0, tpaero = 0, tpord = 0, tufilt = 0, WindTurbineType4bIEC = None,  *args, **kw_args):
		super().__init__(*args, **kw_args)

		self.dpmax = dpmax
		self.tpaero = tpaero
		self.tpord = tpord
		self.tufilt = tufilt
		self.WindTurbineType4bIEC = WindTurbineType4bIEC

	def __str__(self):
		str = 'class=WindContPType4bIEC\n'
		attributes = self.__dict__
		for key in attributes.keys():
			str = str + key + '={}\n'.format(attributes[key])
		return str


import pyvisa
from time import sleep
from quantiphy import Quantity

rm = pyvisa.ResourceManager()
mp_dmm = rm.open_resource('ASRL/dev/ttyUSB0')

mp_dmm.baud_rate = 115200

print(mp_dmm.query("*IDN?"))

while True:
	print(Quantity(mp_dmm.query("MEAS?").strip(), "Ω"))
	sleep(1)


import os

from PIL import Image
from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse

from core.settings import BASE_DIR
from user_profile.forms import UserUpdateForm, ProfileUpdateForm

class MetaSetUp(TestCase):
    fixtures = ["test_db.json"]

    def setUp(self):
        self.client = Client()
        self.user = User.objects.get(username="test_user")
        self.client.force_login(user=self.user)

class ProfileViewTest(MetaSetUp):
    def setUp(self):
        super().setUp()
        self.response = self.client.get(
            reverse('profile-page', kwargs={'user_url': self.user.username})
        )

    def test_page(self):
        self.assertEqual(self.response.status_code, 200)

    def test_nonexistent_page(self):
        response = self.client.get(
            reverse('profile-page', kwargs={'user_url': 'non_existent'})
        )
        self.assertEqual(response.status_code, 404)

class ProfileEditTest(MetaSetUp):
    def setUp(self):
        super().setUp()
        self.url = reverse('profile-page-edit', kwargs={'user_url': self.user.username})
        self.response = self.client.get(self.url)

    def test_get_page(self):
        self.assertEqual(self.response.status_code, 200)
        self.assertTemplateUsed(self.response, 'profile/edit_profile.html')
        self.assertEqual(self.response.context['profile'], self.user.profile)

    def test_forms(self):
        f_user_update_data = {'first_name': 'test', 'last_name': 'usertest'}
        upus = UserUpdateForm(f_user_update_data, instance=self.user)
        self.assertTrue(upus.is_valid())
        f_profile_data = {
            'job': 'Have',
            'study': 'MIT',
            'biography': 'Something',
            'gender': 'M',
            'custom_url': self.user.profile.custom_url,
        }
        profile = ProfileUpdateForm(f_profile_data, instance=self.user.profile)
        self.assertTrue(profile.is_valid())

    def test_edit_profile(self):
        f_user_update_data = {'first_name': 'test', 'last_name': 'usertest'}
        f_profile_data = {
            'job': 'Have',
            'study': 'MIT',
            'biography': 'Something',
            'gender': 'M',
            'custom_url': self.user.profile.custom_url,
        }
        resp = self.client.post(self.url, {
            **f_user_update_data,
            **f_profile_data,
        })
        self.assertEqual(resp.status_code, 302)
        upuser = User.objects.get(id=self.user.id)
        self.assertEqual(upuser.profile.job, f_profile_data['job'])
        self.assertEqual(upuser.last_name, f_user_update_data['last_name'])

    def test_online(self):
        url = '/ajax/set_online/'
        resp = self.client.post(url)
        self.assertContains(resp, 'Success', status_code=200)

class AvatarManagingTest(MetaSetUp):
    def setUp(self):
        super().setUp()
        self.response = self.client.get(reverse('profile-change-avatar'))

    def test_get_page(self):
        self.assertEqual(self.response.status_code, 200)
        self.assertTemplateUsed(self.response, 'profile/change_avatar.html')

    def test_avatar_update(self):
        x_position = 0
        y_position = 0
        width = 1915
        height = 1915
        photo = Image.open(os.path.join(BASE_DIR, 'static/img/unknown_profile.jpg'))
        to_send_image = {
            'base_image': photo,
        }
        to_send_cropper = {
            'x': x_position,
            'y': y_position,
            'width': width,
            'height': height,
        }
        response = self.client.post(reverse('profile-change-avatar'), {
            **to_send_image,
            **to_send_cropper,

        })
        self.assertEqual(response.status_code, 302)

class FriendRequestTest(MetaSetUp):
    def setUp(self):
        super().setUp()

    def test_send_friend_request(self):
        response = self.client.post(
            reverse('friend-request-send', kwargs={'user_id': 2})
        )
        self.assertEqual(response.status_code, 302)

class FilePageTest(MetaSetUp):
    def setUp(self):
        super().setUp()

    def test_get_request(self):
        response = self.client.get(
            reverse('profile-files-page', kwargs={'user_url': 'test_user'})
        )
        self.assertEqual(response.status_code, 200)


from cmath import inf
from typing import List

class Solution88:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        first = m - 1
        second = n - 1
        index = -1

        while first >= 0 and second >= 0:
            if nums1[first] >= nums2[second]:
                nums1[index] = nums1[first]
                nums1[first] = float(-inf)
                first -= 1
            else:
                nums1[index] = nums2[second]
                second -= 1
            index -= 1

        while second >= 0:
            nums1[index] = nums2[second]
            index -= 1
            second -= 1


from django.urls import path
from . import views

urlpatterns = [
    path('contacts/', views.contacts_list, name='contacts_list'),
    path('contacts/<int:pk>/', views.contact_detail, name='contact_detail'),
    path('contacts/new/', views.contact_new, name='contact_new'),
    path('contacts/<int:pk>/edit/', views.contact_edit, name='contact_edit'),
    path('contacts/<int:pk>/delete/', views.contact_delete, name='contact_delete'),
    path('contacts/undo/delete/', views.contact_undo_delete, name='contact_undo_delete'),
]


@require_POST
def follow(request, user_pk):
    if request.user.is_authenticated:
        you = get_object_or_404(get_user_model(), pk=user_pk)
        me = request.user

        if you != me:
            if you.followers.filter(pk=me.pk).exists():
                you.followers.remove(me)
            else:
                you.followers.add(me)
        return redirect('accounts:profile', you.username)
    return redirect('accounts:login')


import time
import unittest

from basic_mcts_model import BasicMctsModel
from mcts_policy import MctsPolicy
from pacman_det_env import PacmanDetEnv
from gym.envs.atari import atari_env

class MctsPolicyFrozenLakeTest(unittest.TestCase):

    # RUN NOTES: (max_depth, num_simulations) and compute time.
    # 25, 25 worked pretty well, ~.5s per step
    # 10, 10 pretty fast, ~.1s per step, 1.0 discount achieves ~2200 score.
    def setUp(self):
        self.env = PacmanDetEnv()
        self.model = BasicMctsModel(self.env, discount=.9, max_depth=50)
        self.policy = MctsPolicy(self.env, self.model,
                                 num_simulations=50, discount=.9)

    # def test_second_to_final(self):
    #     # Move to the left and up of Goal state.
    #     self.env.set_states([RIGHT, RIGHT, DOWN, DOWN])
    #     logits = self.policy.get_policy_logits()
    #     # RIGHT is also ok.
    #     self.assertEqual(DOWN, self.policy.choose_action(logits))
    #     self.assertEqual(DOWN, self.policy.action())

    # def test_final(self):
    #     # Move to the left of Goal state.
    #     self.env.set_states([RIGHT, RIGHT, DOWN, DOWN, DOWN])
    #     self.assertEqual(RIGHT, self.policy.action())

    def test_game_deterministic(self):
        idx = 0
        total_reward = 0
        while True:
            start_time = time.time()
            print('Starting action calculation')
            action = self.policy.action()
            end_time = time.time()
            states, is_final, reward = self.env.step(action)
            total_reward += reward
            print('Action at iter %s: %s\nReward: %s\n'
                'TotalReward: %s\nCalc time: %s\n\n'
                % (idx, action, reward, total_reward,
                    end_time - start_time))
            self.env.env.render()
            if is_final:
                print("Hit is_final!")
                break
            idx += 1
        # for 10, 10 got over 2200 with discount 1
        # with discount 9, seems to not die, but runs longer, and pacman
        # cuts off the game at iter 900
        self.assertTrue(total_reward > 2200)

if __name__ == '__main__':
    unittest.main()


# -*- coding: utf-8 -*-
import json
import urllib.request as request
import os

def handleEsim():
    urlad = "http://172.16.139.92:8201/_cat/indices?h=index"
    req = request.Request(urlad)
    #req.add_header('Content-Type', 'application/json')
    response = request.urlopen(req)
    print(response)

from elasticsearch import Elasticsearch
from datetime import datetime

def handleEsim2():
    es = Elasticsearch(hosts="http://10.16.238.103:8200")
    for line in open("C:\\Users\\ay05\\Desktop\\new_e11.txt"):
        #print(es.search(index=line, body={"query": {"match_all": { }}}))
        #test(line)
        line = line.strip('\n')
        creation_date = test(line)
        print(creation_date)
        body ={"index": line, "creation_date": creation_date, "location": "E11"}
        es.index(index='index_create_date_e11', doc_type='_doc', body=body, id=None)

def test(indexname):
    req = request.Request("http://172.16.139.99:8201/"+indexname+"/_settings/index.creation_date")
    req.add_header('Content-Type', 'application/json')
    response = request.urlopen(req)
    jsonBody = json.loads(response.read())
    creation_date = jsonBody[indexname]["settings"]["index"]["creation_date"]
    return creation_date

if __name__ == '__main__':
    #test()
    handleEsim2()


from aquilon.exceptions_ import ArgumentError
from aquilon.worker.broker import BrokerCommand
from aquilon.aqdb.model import VlanInfo, PortGroup, Interface

class CommandDelVlan(BrokerCommand):

    required_parameters = ["vlan"]

    def render(self, session, vlan, **_):
        dbvi = VlanInfo.get_by_vlan(session, vlan_id=vlan, compel=ArgumentError)

        q1 = session.query(PortGroup.id)
        q1 = q1.filter_by(usage=dbvi.vlan_type, network_tag=dbvi.vlan_id)

        q2 = session.query(Interface.id)
        q2 = q2.filter_by(port_group_name=dbvi.port_group)

        if q1.count() or q2.count():
            raise ArgumentError("VLAN {0} is still in use and cannot be "
                                "deleted.".format(dbvi.vlan_id))

        session.delete(dbvi)
        return


import pandas as pd
import xlrd
from sklearn.cluster import KMeans

from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot as plt

main_frame = pd.read_excel('dataframe_data.xlsx')

#plt.scatter(main_frame.Age,main_frame.Interest)
#plt.xlabel('Age')
#plt.ylabel('Gender')
#plt.show()

km = KMeans(n_clusters=2)
predict = km.fit_predict(main_frame[['Age','Interest']])

main_frame["cluster"] = predict

"""
df1 = main_frame[main_frame.cluster == 0]
df2 = main_frame[main_frame.cluster == 1]
plt.scatter(df1.Age,df1.Interest,color = 'green')
plt.scatter(df2.Age,df2.Interest,color = 'red')
print(km.cluster_centers_)
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],color='purple',marker='*',label='centroid')   #Centoids of clusterz
plt.xlabel('Age')
plt.ylabel('Interest')
#plt.show()"""

#scaler = MinMaxScaler()

#scaler.fit(main_frame[['Interest']])
#main_frame['Interest'] = scaler.transform(main_frame[['Interest']])

#scaler.fit(main_frame[['Age']])
#main_frame['Age'] = scaler.transform(main_frame[['Age']])
#df1 = main_frame[main_frame.cluster == 0]
#df2 = main_frame[main_frame.cluster == 1]
#plt.scatter(df1.Age,df1.Interest,color = 'green')
#plt.scatter(df2.Age,df2.Interest,color = 'red')
#print(km.cluster_centers_)
#plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],color='purple',marker='*',label='centroid')   #Centoids of clusterz
#plt.xlabel('Age')
#plt.ylabel('Interest')
#plt.show()

#Elbow Plot
sse = []
k_rng = range(1,10)
for k in k_rng:
    km = KMeans(n_clusters=k)
    km.fit(main_frame[['Age','Interest']])
    sse.append(km.inertia_)

plt.xlabel('K')
plt.ylabel('Euclidean distance')
plt.plot(k_rng,sse)
plt.show()


# Input for the program (change those)
initialID = 1575 # the show's id.
toPrintOnlyLinks = False # If True, will ALSO print the output list as only links.
http_timeout = 60 # If the Anilist does not respond after http_timeout seconds the script will fail.

# filters below does not apply to the initial id!
filterUnknownFormat = True # If True, the output will not contain entries with unannounced format (TV, TV Short, Movie, etc).
filterTV = False # If True, the output will not contain entries of TV format.
filterTVShort = True # If True, the output will not contain entries of TV Short format.
filterMovie = False # If True, the output will not contain entries of Movie format.
filterSpecial = False # If True, the output will not contain entries of Special format.
filterOVA = False # If True, the output will not contain entries of OVA format.
filterONA = False # If True, the output will not contain entries of ONA format.
filterMusic = True # If True, the output will not contain entries of Music format.
filterUnknownDuration = True # If True, the output will not contain entries with unannounced length of episode.
minimumDuration = 14 # How many minutes does a episode has to have in order to be included in the output.


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

import numpy as np
import abc
from scipy.optimize import brentq
from scipy.integrate import quad
from scipy.special import erf
from functools import partial
from functools import lru_cache
from ito_diffusions import SABR
from volmodels import Vol_model, ONE_BP

# ## SABR generic class
# Possible SABR calculations include :
# * Hagan normal implied vol
# * Hagan lognormal implied
# * Monte Carlo
class SABR_base_model(Vol_model):
    """Generic class for SABR model
    """
    def __init__(self,
                 beta: float=1.0,
                 vov: float=1.0,
                 rho: float=0.0,
                 ATM=None,
                 sigma_0=None,
                 f=None,
                 T_expiry: float=1.0,
                 vol_type=None,
                 marking_mode: str='ATM',
                 logmoneyness_lo=None,
                 logmoneyness_hi=None,
                 K_lo=None,
                 K_hi=None,
                 strike_type: str='logmoneyness',
                 n_strikes: int=50
                ) -> None:
        """Implementation of SABR implied vol and approximated price formula.
        beta, vov and rho are marked.
        One can either mark the ATM vol and the forward and solve for sigma_0,
        or mark sigma_0 directly.
        """
        super().__init__(f=f,
                         T_expiry=T_expiry,
                         vol_type=vol_type,
                         logmoneyness_lo=logmoneyness_lo,
                         logmoneyness_hi=logmoneyness_hi,
                         K_lo=K_lo,
                         K_hi=K_hi,
                         strike_type=strike_type,
                         n_strikes=n_strikes
                        )
        self._beta = beta
        self._vov = vov
        self._rho = rho

        # ATM or sigma_0
        self._marking_mode = marking_mode

        self._ATM = ATM
        self._sigma_0 = sigma_0

        if self._marking_mode == 'ATM' and self._ATM == None:
            raise NameError( "ATM must be marked in ATM marking mode" )
        elif self._marking_mode == 'sigma_0' and self._sigma_0 == None:
            raise NameError( "sigma_0 must be marked in sigma_0 marking mode" )

    def __str__(self):
        return r'T_expiry={}y, $\beta$={:.2f}, vov={:.2%}, $\rho$={:.2%}, f={:.2%}, $\sigma_0$={:.2%}'    .format(self.T_expiry, self.beta, self.vov, self.rho, self.f, self.sigma_0)

    @property
    def beta(self):
        return self._beta
    @beta.setter
    def beta(self, new_beta):
        self._beta = new_beta

    @property
    def rho(self):
        return self._rho
    @rho.setter
    def rho(self, new_rho):
        self._rho = new_rho

    @property
    def vov(self):
        return self._vov
    @vov.setter
    def vov(self, new_vov):
        self._vov = new_vov

    @property
    def ATM_LN(self):
        if self.vol_type == 'LN':
            return self.ATM
        elif self.vol_type == 'N':
            return self.ATM/self.f
    @property
    def ATM_N(self):
        if self.vol_type == 'N':
            return self.ATM
        elif self.vol_type == 'LN':
            return self.ATM*self.f

    @property
    def ATM(self):
        if self.marking_mode == 'ATM':
            return self._ATM
        elif self.marking_mode == 'sigma_0':
            return self.ATM_func(self.sigma_0)
    @ATM.setter
    def ATM(self, new_ATM):
        if self.marking_mode == 'sigma_0':
            raise NameError( "Impossible to mark ATM in sigma_0 marking mode" )
        elif self.marking_mode == 'ATM':
            self._ATM = new_ATM

    @property
    def sigma_0(self):
        if self.marking_mode == 'ATM':
            if self.vol_type == 'LN':
                try:
                    return brentq(lambda sigma_0: self.ATM_func(sigma_0) - self.ATM,                                  self.ATM * (self.f ** (1-self.beta))-0.1,                                  self.ATM * (self.f ** (1-self.beta))+0.1)
                except:
                    return self.ATM * (self.f ** (1-self.beta))
            elif self.vol_type == 'N':
                try:
                    return brentq(lambda sigma_0: self.ATM_func(sigma_0) - self.ATM,                                  self.ATM * (self.f ** (-self.beta))-0.1,                                  self.ATM * (self.f ** (-self.beta))+0.1)
                except:
                    return self.ATM * (self.f ** (-self.beta))
        elif self.marking_mode == 'sigma_0':
            return self._sigma_0
    @sigma_0.setter
    def sigma_0(self, new_sigma_0):
        if self.marking_mode == "ATM":
            raise NameError( "Impossible to mark sigma_0 in ATM marking mode" )
        elif self.marking_mode == 'sigma_0':
            self._sigma_0 = new_sigma_0

    @property
    def marking_mode(self):
        if self._marking_mode not in ['ATM', 'sigma_0']:
            raise NameError( "Unsupported marking mode : {}".format(self._marking_mode) )
        else:
            return self._marking_mode
    @marking_mode.setter
    def marking_mode(self, new_marking_mode):
        self._marking_mode = new_marking_mode

    def ATM_LN_func(self, sigma_0):
        """Reduction of Hagan's lognormal formula when K --> f
        Used to calibrate sigma_0 to marked ATM vol
        """
        return sigma_0/(self.f**(1-self.beta))*    (1+(((1-self.beta)**2)/24*sigma_0**2/(self.f**(2-2*self.beta))     +0.25*self.rho*self.beta*self.vov*sigma_0/(self.f**(1-self.beta))     +(2-3*self.rho**2)/24*self.vov**2)*self.T_expiry)

    def ATM_N_func(self, sigma_0):
        """Reduction of Hagan's normal formula when K --> f
        Used to calibrate sigma_0 to marked ATM vol
        """
        return sigma_0 * (self.f**self.beta)*    (1+     ((-self.beta*(2-self.beta)*sigma_0**2)/(24*self.f**(2-2*self.beta))     +0.25*self.rho*self.vov*self.beta*sigma_0/(self.f**(1-self.beta))     +(2-3*self.rho**2)/24*self.vov**2)*self.T_expiry)

    def ATM_func(self, sigma_0):
        if self.vol_type == 'LN':
            return self.ATM_LN_func(sigma_0)
        elif self.vol_type == 'N':
            return self.ATM_N_func(sigma_0)

    @abc.abstractmethod
    def smile_func(self, K):
        pass

# ### Hagan lognormal (Black) implied vol expansion
class SABR_Hagan_LN(SABR_base_model):
    """SABR model using lognormal implied vol quoting from Hagan's formula
    """
    def __init__(self,
                 beta: float=1.0,
                 vov: float=1.0,
                 rho: float=0.0,
                 ATM=None,
                 sigma_0=None,
                 f=None,
                 T_expiry: float=1.0,
                 marking_mode: str='ATM',
                 logmoneyness_lo=None,
                 logmoneyness_hi=None,
                 K_lo=None,
                 K_hi=None,
                 strike_type: str='logmoneyness',
                 n_strikes: int=50,
                ) -> None:
        super().__init__(beta=beta,
                         vov=vov,
                         rho=rho,
                         ATM=ATM,
                         sigma_0=sigma_0,
                         f=f,
                         T_expiry=T_expiry,
                         vol_type='LN',
                         marking_mode=marking_mode,
                         logmoneyness_lo=logmoneyness_lo,
                         logmoneyness_hi=logmoneyness_hi,
                         K_lo=K_lo,
                         K_hi=K_hi,
                         strike_type=strike_type,
                         n_strikes=n_strikes
                        )

    def __str__(self):
        return r'$T_expiry={}y, \beta$={:.2f}, vov={:.2%}, $\rho$={:.2%}, ATM={:.2%}, f={:.2%}, $\sigma_0$={:.2%}'    .format(self.T_expiry, self.beta, self.vov, self.rho, self.ATM, self.f, self.sigma_0)

    @property
    def model_name(self):
        return 'SABR_Hagan_LN'

    def smile_func(self, K):
        """Hagan lognormal smile approximation around ATM as written in the
        original 'Managing Smile Risk' paper (A.69c)
        K: strike
        """
        if np.abs(K-self.f)<ONE_BP/100:
            return self.ATM
        else:
            log_moneyness = np.log(self.f/K)
            zeta = self.vov/self.sigma_0*(self.f*K)**((1-self.beta)/2)*log_moneyness
            q_zeta = 1-2*self.rho*zeta+zeta**2
            x_zeta = np.log((np.sqrt(q_zeta)-self.rho+zeta)/(1-self.rho))
            f_avg = np.sqrt(self.f*K)
            return self.sigma_0/                                (f_avg**(1-self.beta)*(1                                    +((1-self.beta)**2)/24*log_moneyness**2                                   +((1-self.beta)**4)/1920*log_moneyness**4))*    (zeta/x_zeta)*    (1+(((1-self.beta)**2)/24*self.sigma_0**2/(f_avg**(2-2*self.beta))     +0.25*self.rho*self.beta*self.vov*self.sigma_0/(f_avg**(1-self.beta))     +(2-3*self.rho**2)/24*self.vov**2)*self.T_expiry)

# ### Hagan normal implied vol expansion
class SABR_Hagan_N(SABR_base_model):
    """SABR model using normal implied vol quoting from Hagan's formula
    """
    def __init__(self,
                 beta: float=1.0,
                 vov: float=1.0,
                 rho: float=0.0,
                 ATM=None,
                 sigma_0=None,
                 f=None,
                 T_expiry:float =1.0,
                 marking_mode: str='ATM',
                 logmoneyness_lo=None,
                 logmoneyness_hi=None,
                 K_lo=None,
                 K_hi=None,
                 strike_type: str='logmoneyness',
                 n_strikes: int=50,
                ):
        super().__init__(beta=beta,
                         vov=vov,
                         rho=rho,
                         ATM=ATM,
                         sigma_0=sigma_0,
                         f=f,
                         T_expiry=T_expiry,
                         vol_type='N',
                         marking_mode=marking_mode,
                         logmoneyness_lo=logmoneyness_lo,
                         logmoneyness_hi=logmoneyness_hi,
                         K_lo=K_lo,
                         K_hi=K_hi,
                         strike_type=strike_type,
                         n_strikes=n_strikes
                        )

    def __str__(self):
        return r'T_expiry={}y, $\beta$={:.2f}, vov={:.2%}, $\rho$={:.2%}, ATM={:.2f}bps, f={:.2%}, $\sigma_0$={:.2%}'    .format(self.T_expiry, self.beta, self.vov, self.rho, self.ATM/ONE_BP, self.f, self.sigma_0)

    @property
    def model_name(self):
        return 'SABR_Hagan_N'

    def smile_func(self, K):
        """Hagan normal smile approximation around ATM as written in the
        original 'Managing Smile Risk' paper (A.69a)
        K: strike
        """
        if np.abs(K-self.f)<ONE_BP/100:
            return self.ATM
        else:
            f_avg = np.sqrt(self.f*K)
            log_moneyness = np.log(self.f/K)
            zeta = self.vov/self.sigma_0*(f_avg)**(1-self.beta)*log_moneyness
            q_zeta = 1-2*self.rho*zeta+zeta**2
            x_zeta = np.log((np.sqrt(q_zeta)-self.rho+zeta)/(1-self.rho))
            g = -self.beta*(2-self.beta)/(24*(f_avg)**(2-2*self.beta))
            return self.sigma_0*(f_avg)**(self.beta)*        (1+1/24*log_moneyness**2+1/1920*log_moneyness**4)/        (1         +((1-self.beta)**2)/24*log_moneyness**2         +((1-self.beta)**4)/1920*log_moneyness**4)*    (zeta/x_zeta)*    (1+     (g*self.sigma_0**2      +0.25*self.rho*self.vov*self.sigma_0*self.beta/(f_avg**(1-1*self.beta))      +(2-3*self.rho**2)/24*self.vov**2)*self.T_expiry)

    def smile_func_full(self, K):
        """Hagan normal smile approximation around ATM as written in the
        original 'Managing Smile Risk' paper (A.67a)
        K: strike
        """
        if np.abs(K-self.f)<ONE_BP/100:
            return self.ATM
        else:
            #local_vol_int = (self.f**(1-self.beta)-K**(1-self.beta))/(1-self.beta)
            f_avg = np.sqrt(self.f*K)
            #f_avg = 0.5*(self.f+K)
            zeta = self.vov/self.sigma_0*(self.f-K)/(f_avg**self.beta)
            q_zeta = 1-2*self.rho*zeta+zeta**2
            x_zeta = np.log((np.sqrt(q_zeta)-self.rho+zeta)/(1-self.rho))
            g = -self.beta*(2-self.beta)/(24*(f_avg)**(2-2*self.beta))
            return self.sigma_0*(1-self.beta)*(self.f-K)        /(self.f**(1-self.beta)-K**(1-self.beta))*(zeta/x_zeta)*        (1+         (g*self.sigma_0**2+0.25*self.rho*self.vov*self.sigma_0*self.beta/(f_avg**(1-self.beta))          +(2-3*self.rho**2)/24*self.vov**2)         *self.T_expiry)

# Monte Carlo pricer, by discretizing the SABR SDEs
class SABR_MC(SABR_base_model):
    """SABR model with Monte Carlo pricing
    """
    def __init__(self,
                 beta: float=1.0,
                 vov: float=1.0,
                 rho: float=0.0,
                 ATM=None,
                 sigma_0=None,
                 f=None,
                 T_expiry: float=1.0,
                 vol_type: str='LN',
                 marking_mode: str='ATM',
                 logmoneyness_lo=None,
                 logmoneyness_hi=None,
                 K_lo=None,
                 K_hi=None,
                 strike_type: str='logmoneyness',
                 n_strikes: int=50,
                 n_sim: int = int(1e3),
                 scheme_steps: int=int(1e2)
                ) -> None:
        super().__init__(beta=beta,
                         vov=vov,
                         rho=rho,
                         ATM=ATM,
                         sigma_0=sigma_0,
                         f=f,
                         T_expiry=T_expiry,
                         vol_type=vol_type,
                         marking_mode=marking_mode,
                         logmoneyness_lo=logmoneyness_lo,
                         logmoneyness_hi=logmoneyness_hi,
                         K_lo=K_lo,
                         K_hi=K_hi,
                         strike_type=strike_type,
                         n_strikes=n_strikes
                        )
        self._n_sim = n_sim
        self._scheme_steps = scheme_steps

    @property
    def model_name(self):
        return 'SABR_Hagan_MC'

    @property
    def n_sim(self):
        return self._n_sim
    @n_sim.setter
    def n_sim(self, new_n_sim):
        self._n_sim = new_n_sim

    @property
    def scheme_steps(self):
        return self._scheme_steps
    @scheme_steps.setter
    def scheme_steps(self, new_scheme_steps):
        self._scheme_steps = new_scheme_steps

    @property
    def MC_generator(self):
        return SABR(x0=[self.f, self.sigma_0], T=self.T_expiry,                        scheme_steps=self._scheme_steps, keys=['F', 'vol'],                        beta=self.beta, vov=self.vov, rho=self.rho,                        barrier=[0,None], barrier_condition='absorb')

    @property
    @lru_cache(maxsize=None)
    def MC_paths(self):
        gen = self.MC_generator
        F_terminal_samples = []
        for i in range(self.n_sim):
            df = gen.simulate()
            F_terminal_samples.append(df['F'].iloc[-1])
        return F_terminal_samples

    def clear_MC_cache(self):
        self.MC_paths.cache_clear()

    def payoff_helper(self, payoff):
        """Returns a lambda with the specification of the payoff name
        """
        if payoff == 'Call':
            return lambda X, K: max(X-K,0)
        elif payoff == 'Put':
            return lambda X, K: max(K-X, 0)
        else:
            raise NameError( "Unsupported payoff name : {}".format(payoff) )

    def option_price(self, K, payoff='Call', regen_paths=False):
        """Returns the call/put price estimated from Monte Carlo simulations
        of the spot/vol SABR dynamics
        """
        payoff_func = self.payoff_helper(payoff)
        payoff_sims = []

        if regen_paths:
            gen = self.MC_generator
            for i in range(self.n_sim):
                df = gen.simulate()
                F_terminal = df['F'].iloc[-1]
                payoff_sims.append(payoff_func(F_terminal, K))
        else:
            F_terminal_samples = self.MC_paths
            for F_terminal in F_terminal_samples:
                payoff_sims.append(payoff_func(F_terminal, K))
        return np.mean(payoff_sims)

    def smile_func(self, K):
        """Implied vol smile converted from option Monte Carlo prices
        K: strike
        """
        if K <= self.f:
            payoff = 'Put'
        else:
            payoff = 'Call'

        price = self.option_price(K, payoff=payoff)
        return self.IV.vol_from_price(price, self.f, K, self.T_expiry, payoff=payoff)

# Normal SABR
# SABR formula for $\beta=0$ with an adjusted $\sigma_0$ to account for the actual local vol in the model.
class SABR_Goes_Normal(SABR_base_model):
    """SABR model with beta = 0 and ajusted sigma_0 to account for the actual local vol.
    Lognormal quoting.
    """
    def __init__(self,
                 beta: float=1.0,
                 vov: float=1.0,
                 rho: float=0.0,
                 ATM=None,
                 sigma_0=None,
                 f=None,
                 T_expiry: float=1.0,
                 vol_type: str='LN',
                 marking_mode: str='ATM',
                 logmoneyness_lo=None,
                 logmoneyness_hi=None,
                 K_lo=None,
                 K_hi=None,
                 strike_type: str='logmoneyness',
                 n_strikes: int=50,
                 n_integral: int=1
                ) -> None:
        super().__init__(beta=beta,
                         vov=vov,
                         rho=rho,
                         ATM=ATM,
                         sigma_0=sigma_0,
                         f=f,
                         T_expiry=T_expiry,
                         vol_type=vol_type,
                         marking_mode=marking_mode,
                         logmoneyness_lo=logmoneyness_lo,
                         logmoneyness_hi=logmoneyness_hi,
                         K_lo=K_lo,
                         K_hi=K_hi,
                         strike_type=strike_type,
                         n_strikes=n_strikes
                        )
        # number of discretization step of the integral in the approximation formula
        self._n_integral = n_integral

    @property
    def n_integral(self):
        return self._n_integral
    @n_integral.setter
    def n_integral(self, new_n_integral):
        self._n_integral = new_n_integral

    @property
    def step_integral(self):
        return self.T_expiry/self._n_integral

    def sigma_0_effective(self, K):
        """Adjusted initial vol to match first order of ATM expansion when using
        normal SABR as base model
        """
        if np.abs(K-self.f)<ONE_BP/100:
            return self.sigma_0*(self.f**self.beta)
        else:
            return self.sigma_0*(1-self.beta)*(K-self.f)/(K**(1-self.beta)-self.f**(1-self.beta))

    def vov_scaled(self, K):
        """Helper function for the call/put price approximation
        """
        return self.vov/self.sigma_0_effective(K)

    def q(self, z, K):
        """Helper function for the call/put price approximation
        """
        return 1-2*self.rho*self.vov_scaled(K)*z+(self.vov_scaled(K)**2)*(z**2)

    def J(self, x, K):
        """Helper function for the call/put price approximation
        """
        X_0 = self.f-K
        num = np.sqrt(self.q(x, K))-self.rho+self.vov_scaled(K)*x
        denom = np.sqrt(self.q(X_0, K))-self.rho+self.vov_scaled(K)*X_0
        return 1/(self.vov)*np.log(num/denom)

    def dJ(self, x, K):
        """Helper function for the call/put price approximation
        """
        return 1/(self.sigma_0_effective(K)*np.sqrt(self.q(x, K)))

    def local_time(self, t, x, K=None):
        """Density of (S_t-K)/(alpha_t) at x under the stochastic vol measure
        """
        return 1/np.sqrt(2*np.pi*t)*self.dJ(x, K)*np.exp(-self.J(x, K)**2/(2*t))

    def integrand(self, K, t, x):
        """Integrand to compute E[J^-1(W_t)], used as an adjustment for the missing drift
        """
        return self.local_time(t, x, K)*x

    def option_price(self, K, payoff='Call'):
        """Returns the call/put price approximation derived for normal SABR
        in "SABR Goes Normal".
        """
        if payoff == "Call":
            return self.call_price(K)
        elif payoff == "Put":
            return self.call_price(K) + (K-self.f)

    def int_local_time(self, t, K):
        """Explicit form for the integral of the local time between 0 and t
        """
        dJ = self.dJ(0, K)
        J = self.J(0, K)
        return dJ*np.exp(-J**2/(2*t))*np.sqrt(2/np.pi)*np.sqrt(t)    +dJ*J*(np.erf(J/(np.sqrt(2*t)))-1)

    def call_price(self, K):
        """Returns the call price approximation derived from normal SABR
        """
        X_0 = self.f-K
        intrinsic_value = max(X_0, 0)

        #s = self.int_local_time(self.T_expiry, K)

        s = 0
        time_steps = [t*self.step_integral for t in range(self.n_integral)]
        for t in time_steps:
            t_next = t + self.step_integral
            t_mid = 0.5*(t+t_next)

            f = partial( self.integrand, K, t_mid )
            L = X_0 - quad(f, -np.inf, np.inf, limit=10)[0]
            s += self.local_time(t_mid, -L, K=K)*self.step_integral
        return intrinsic_value+0.5*self.sigma_0_effective(K)**2*s

class SABR_Goes_Normal_LN(SABR_Goes_Normal):
    """SABR model with beta = 0 and ajusted sigma_0 to account for the actual local vol.
    Lognormal quoting.
    """
    def __init__(self,
                 beta: float=1.0,
                 vov: float=1.0,
                 rho: float=0.0,
                 ATM=None,
                 sigma_0=None,
                 f=None,
                 T_expiry: float=1.0,
                 marking_mode: str='ATM',
                 logmoneyness_lo=None,
                 logmoneyness_hi=None,
                 K_lo=None,
                 K_hi=None,
                 strike_type: str='logmoneyness',
                 n_strikes: int=50,
                 n_integral: int=1
                ) -> None:
        super().__init__(beta=beta,
                         vov=vov,
                         rho=rho,
                         ATM=ATM,
                         sigma_0=sigma_0,
                         f=f,
                         T_expiry=T_expiry,
                         vol_type='LN',
                         marking_mode=marking_mode,
                         logmoneyness_lo=logmoneyness_lo,
                         logmoneyness_hi=logmoneyness_hi,
                         K_lo=K_lo,
                         K_hi=K_hi,
                         strike_type=strike_type,
                         n_strikes=n_strikes,
                         n_integral=n_integral
                        )

    @property
    def model_name(self):
        return 'SABR_Goes_Normal_LN'

    def smile_func(self, K):
        """Hagan normal smile approximation around ATM for beta = 0 as written in the
        original 'Managing Smile Risk' paper (A.70b)
        K: strike
        """
        b_0 = self.sigma_0_effective(K)
        if np.abs(K-self.f)<ONE_BP/100:
            return b_0/self.f*(1                               + ((b_0**2)/(24*self.f**2) + (2-3*self.rho**2)/24*self.vov**2)                               *self.T_expiry)
        else:
            log_moneyness = np.log(self.f/K)
            f_avg = np.sqrt(self.f*K)
            zeta = self.vov/b_0*f_avg*log_moneyness
            q_zeta = 1-2*self.rho*zeta+zeta**2
            x_zeta = np.log((np.sqrt(q_zeta)-self.rho+zeta)/(1-self.rho))

            return b_0*log_moneyness/(self.f-K)*zeta/x_zeta*                (1 + ((b_0**2)/(24*self.f*K) + (2-3*self.rho**2)/24*self.vov**2)*self.T_expiry)

class SABR_Goes_Normal_N(SABR_Goes_Normal):
    """SABR model with beta = 0 and ajusted sigma_0 to account for the actual local vol.
    Normal quoting.
    """
    def __init__(self,
                 beta: float=1.0,
                 vov: float=1.0,
                 rho: float=0.0,
                 ATM=None,
                 sigma_0=None,
                 f=None,
                 T_expiry: float=1.0,
                 marking_mode: str='ATM',
                 logmoneyness_lo=None,
                 logmoneyness_hi=None,
                 K_lo=None,
                 K_hi=None,
                 strike_type: str='logmoneyness',
                 n_strikes: int=50,
                 n_integral: int=1
                ) -> None:
        super().__init__(beta=beta,
                         vov=vov,
                         rho=rho,
                         ATM=ATM,
                         sigma_0=sigma_0,
                         f=f,
                         T_expiry=T_expiry,
                         vol_type='N',
                         marking_mode=marking_mode,
                         logmoneyness_lo=logmoneyness_lo,
                         logmoneyness_hi=logmoneyness_hi,
                         K_lo=K_lo,
                         K_hi=K_hi,
                         strike_type=strike_type,
                         n_strikes=n_strikes,
                         n_integral=n_integral,
                        )

    @property
    def model_name(self):
        return 'SABR_Goes_Normal_N'

    def smile_func(self, K):
        """Hagan normal smile approximation around ATM for beta = 0 as written in the
        original 'Managing Smile Risk' paper (A.70a)
        K: strike
        """
        b_0 = self.sigma_0_effective(K)
        if np.abs(K-self.f)<ONE_BP/100:
            return b_0*(1                        + ((2-3*self.rho**2)/24*self.vov**2)*self.T_expiry)
        else:
            log_moneyness = np.log(self.f/K)
            f_avg = np.sqrt(self.f*K)
            zeta = self.vov/b_0*f_avg*log_moneyness
            q_zeta = 1-2*self.rho*zeta+zeta**2
            x_zeta = np.log((np.sqrt(q_zeta)-self.rho+zeta)/(1-self.rho))

            return b_0*zeta/x_zeta*        (1+((2-3*self.rho**2)/24*self.vov**2)*self.T_expiry)


import Random

#Create functions?
#Store information about move history (How many times did you/computer play r/p/s? longest win streak? What is the move history? What was
# played most often)
#Add custom program break
#Take edge cases into account i.e What if an input is not a string?
#Add two player and one player option

print("Endless Rock Paper Scissors")
move = ""
comp_wins = 0
player_wins = 0
ties = 0
round = 0

while(move is not -1):
    round += 1
    print("Round " + str(round) + "\n")
    set = ["r", "p", "s"]
    comp = set[random.randint(0, 2)]
    move = str(input("What's your move?")).lower()
    print("")

    if comp == "r":
        if move == "r" or move == "rock":
            ties += 1
            print("Both played ROCK")
        elif move == "p" or move == "paper":
            player_wins += 1
            print("You played PAPER\nComputer played ROCK")
        else:
            print("You played SCISSORS\nComputer played ROCK")
    elif comp == "p":
        if move == "r" or move == "rock":
            comp_wins += 1
            print("You played ROCK\n\Computer played PAPER")
        elif move == "p" or move == "paper":
            ties += 1
            print("Both played PAPER")
        else:
            player_wins += 1
            print("You played SCISSORS\n\Computer played PAPER")
    else:
        if move == "r" or move == "rock":
            player_wins += 1
            print("You played ROCK\nComputer played SCISSORS")
        elif move == "p" or move == "paper":
            comp_wins += 1
            print("You played PAPER\nComputer played SCISSORS")
        else:
            ties += 1
            print("Both played SCISSORS")

    print("You: " + str(player_wins) + "\tComputer: " + str(comp_wins) + "\tTies: " + str(ties) + "\n")


import PyPDF2

path = 'C:\\Users\\LYPC\\Desktop\\简历.pdf'
pdfWriter = PyPDF2.PdfFileWriter()

pdfFileObj = open(path, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

for pageNum in range(0, pdfReader.numPages - 1):
    pageObj = pdfReader.getPage(pageNum)
    pdfWriter.addPage(pageObj)

pdfOutput = open('C:\\Users\\LYPC\\Desktop\\resume.pdf', 'wb')
pdfWriter.write(pdfOutput)
pdfOutput.close()


#!/usr/bin/python3
import sys, os
import datetime

# Set name from command line
sensor_name = None
for argu in sys.argv[1:]:
    if "=" in argu:
        thearg = str(argu).split('=')[0]
        thevalue = str(argu).split('=')[1]
        if thearg == 'name':
            sensor_name = thevalue
    elif argu == "--help" or argu == '-h':
        print(" Script for logging modular sensors")
        print(" ")
        print(" This requres the sensor to be configured in the remote gui.")
        print(" ")
        print(" name=sensor unique name")
        print("")
        sys.exit(0)
    elif argu == "-flags":
        print("name=")
        sys.exit(0)

if sensor_name == None:
    print("Sensor not identified, please include name= in the commandline arguments.")
    sys.exit()

# Read the settings file
homedir = os.getenv("HOME")
sys.path.append(homedir + '/Pigrow/scripts/')
try:
    import pigrow_defs
except:
    print("pigrow_defs.py not found, unable to continue.")
    print("make sure pigrow software is installed correctly")
    sys.exit()

pigrow_config_path  = homedir + '/Pigrow/config/pigrow_config.txt'
error_log           = homedir + '/Pigrow/logs/err_log.txt'
pigrow_settings = pigrow_defs.load_settings(pigrow_config_path)

# Read the sensor info from the settigns file
sensor_type = None
sensor_log = None
sensor_loc = None
sensor_extra = ""
for key, value in list(pigrow_settings.items()):
    sensor_key = "sensor_" + sensor_name
    if sensor_key in key:
        if "type" in key:
            sensor_type = value
        elif "log" in key:
            sensor_log = value
        elif "loc" in key:
            sensor_loc = value
        elif "extra" in key:
            sensor_extra = value
if sensor_type == None or sensor_log == None or sensor_loc == None:
    err_msg = "Sensor settings not found in " + pigrow_config_path
    print(err_msg)
    pigrow_defs.write_log('log_sensor_module.py', err_msg, error_log)
    sys.exit()

### TESTING
print (sensor_type, sensor_log, sensor_loc, sensor_extra)

# Add sensor modules path to sys
sensor_modules_path = homedir + '/Pigrow/scripts/gui/sensor_modules/'
try:
    sys.path.append(sensor_modules_path)
except:
    err_msg = "Failed to add modules folder: " + sensor_modules_path
    print(err_msg)
    pigrow_defs.write_log('log_sensor_module.py', err_msg, error_log)
    sys.exit()

# Import Sensor Module
module_name = "sensor_" + sensor_type
try:
    exec('import ' + module_name + ' as sensor_module', globals())
except:
    err_msg = "Failed to import sensor module for " + sensor_type
    print(err_msg)
    pigrow_defs.write_log('log_sensor_module.py', err_msg, error_log)
    sys.exit()

# Read Sensor
sensor_values = sensor_module.read_sensor(location=sensor_loc, extra=sensor_extra, sensor_name=sensor_name)

# Create log line containing each returned value
line = ""
for x in sensor_values:
    line = line + str(x[0]) + "=" + str(x[1]) + ">"
line = line[:-1] + "\n"

# Write log line to log
try:
    with open(sensor_log, "a") as f:
        f.write(line)
except:
    err_msg = "Error writing to log, " + sensor_log
    print[err_msg]
    pigrow_defs.write_log('log_sensor_module.py', err_msg, error_log)
    raise

# Report to user
print("Written log; " + line)


from artworks.past_artworks_getter import *
from to_database.update_db import *

#The same as the comment in 'upcoming_online.py', instead using 'past_auctions.txt' which stores the past auction links.

r = get_all_artworks_all_auctions(browser, 'past_auctions.txt', 1)

browser.close()

print(r[0])
print(r[1])

#update the database.
update_database(r[0])


import bson
import colander
import datetime
import logging

__all__ = []

log = logging.getLogger(__file__)

class ObjectId(object):

    def serialize(self, node, value):
        """ Return an ObjectId as is.
        """

        if value is colander.null:
            return colander.null

        if not isinstance(value, bson.objectid.ObjectId):
            raise colander.Invalid(node, '%s is not an ObjectId' % value)

        return str(value)

    def deserialize(self, node, value):

        if value is colander.null or isinstance(value, bson.objectid.ObjectId):
            return value

        try:
            value = bson.objectid.ObjectId(value)

        except (TypeError, bson.errors.InvalidId):
            raise colander.Invalid(node, '%s is not a valid ObjectId' % value)

        else:
            return value


#!/usr/bin/env python
# encoding: utf-8
"""
@author: LiYuHong
@file: 166_the-area-for-intersect-rectangles.py
@time: 2023/8/8 22:08
@project: huawei-od-python
@desc: 166 矩形相交的面积
"""

def solve_method(areas):
    new_points = []
    # 后面两个坐标转化成正常值（变成右下角坐标点）
    for area in areas:
        x, y, w, h = area
        new_points.append([x, y, x + w, y - h])

    # 初始化一个空的相交区域为原点，记录它的左上角和右下角的坐标值
    inter_area = []

    # 将所有的area，每个坐标通过zip函数分别集合到一起，
    # 比如三个area的左上x，左上y，右下x，右下y
    # 按照如下规则进行查找，然后能找到满足最小的矩形。
    # 找左上x里的较大值（注意坐标系左负右正，上正下负），即靠右，
    # 找左上y里的较小值，即靠下，
    # 找右下x里的较小值，即靠左，
    # 找右下y里的较大值，即靠上，
    # 这四个极值找到后就是重叠区域的左上和右下坐标。
    for ind, coro in enumerate(zip(*new_points)):
        if ind == 0 or ind == 3:
            inter_area.append(max(coro))
        if ind == 1 or ind == 2:
            inter_area.append(min(coro))

    # 右下x一定大于左上x，左上y一定大于右下y，否则不存在相交区域
    # 如果不相交，也会求取一个面积，为他们最近点围成的面积，需要去掉这个不相交的面积，
    # 如果下面两个条件任意一个小于等于0，则表示不相交。
    if (inter_area[2] - inter_area[0]) <= 0 or (inter_area[1] - inter_area[3]) <= 0:
        return 0
    else:
        return (inter_area[2] - inter_area[0]) * (inter_area[1] - inter_area[3])

if __name__ == '__main__':
    areas = [[1, 6, 4, 4],
             [3, 5, 3, 4],
             [0, 3, 7, 3]]
    assert solve_method(areas) == 2  # 相交，面积为2
    areas = [[2, 0, 2, 2],
             [0, 2, 2, 2],
             [4, 2, 2, 2]]
    assert solve_method(areas) == 0  # 不相交，面积为0
    areas = [[1, 7, 2, 2],
             [4, 2, 2, 2],
             [8, 7, 2, 2]]
    assert solve_method(areas) == 0  # 不相交，面积为15


import tkinter as tk
import turtle

def create_pen():
    # root = tk.Tk()
    root_window = tk.Tk()
    root_window.state('zoomed')
    # root_window = tk.Frame(root,width=1000,height=700)
    l1 = tk.Label(root_window, text = "Rectangular dual")

    l1.grid(row=1,column=0)

    # root_window.geometry(str(1366) + 'x' + str(700))
    # root_window.resizable(0, 0)
    root_window.grid_columnconfigure(0, weight=1, uniform=1)
    root_window.grid_rowconfigure(0, weight=1)
    border_details = {'highlightbackground': 'black', 'highlightcolor': 'black', 'highlightthickness': 1}

    canvas = tk.Canvas(root_window, **border_details,width = 100, height =200)
    canvas.pack_propagate(0)
    canvas.grid(row=0, column=0, sticky='nsew', padx=4, pady=4)

    scroll_x = tk.Scrollbar(root_window, orient="horizontal", command=canvas.xview)
    scroll_x.grid(row=1, column=0, sticky="ew")

    scroll_y = tk.Scrollbar(root_window, orient="vertical", command=canvas.yview)
    scroll_y.grid(row=0, column=1, sticky="ns")

    canvas.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
    canvas.configure(scrollregion=canvas.bbox("all"))

    pen = turtle.RawTurtle(canvas)
    pen.speed(100)
    # root_window.mainloop()
    return pen, root_window

if __name__ == '__main__':
    pen , root = create_pen()
    root.mainloop()


import os
from arancino.utils.ArancinoUtils import ArancinoLogger
from gunicorn.glogging import Logger

class GunicornLogger(Logger):
    def setup(self, cfg):
        super().setup(cfg)
        self.access_log = ArancinoLogger.Instance().getLogger()
        self.error_log = ArancinoLogger.Instance().getLogger()

bind = '0.0.0.0:1475'
workers = 1
worker_class = 'sync'
timeout = 300
keepalive = 2

logger_class = GunicornLogger
# errorlog = os.path.join(os.getenv('ARANCINOLOG'), 'arancino.error.log')
# loglevel = 'info'
# accesslog = os.path.join(os.getenv('ARANCINOLOG'), 'arancino.log')
daemon = False


import geomagic.app.v3
from geomagic.app.v3.imports import *

#################################################
path = "F:\\1耳朵测量项目\\5.特征提取\\TXT\\"	#在引号中输入保存TXT文件的路径，路径中的\需改成\\，且最后以\\结尾
#################################################

# Get the currently selected model in the model manager.
activeModel = geoapp.getActiveModel()

import time

def text(name, msg, pa):
    pa = pa + name + '.txt'
    file = open(pa, 'a+')
    file.write(msg+"\n")
    file.close()

# Make sure there is a model selected.
if activeModel != None:
	planes = []
	features = geoapp.getFeatures(activeModel)
	p=path + str(activeModel.name) + '.txt'
	file = open(p, 'w')
	file.write("")
	print("\n\n输出完成!\n文件"+str(activeModel.name)+".txt已保存在"+path+"目录下！\n时间： "+time.strftime('%Y-%m-%d %H:%M:%S'))
	for feature in features:
		text(str(activeModel.name), str(feature.position.x()*1000), path)
		text(str(activeModel.name), str(feature.position.y()*1000), path)
		text(str(activeModel.name), str(feature.position.z()*1000), path)
		if isinstance(feature, Plane):
			planes.append(feature)

else:
	print("No model selected")

03输出点坐标的脚本.py

03输出点坐标的脚本.py


from pydub import AudioSegment
from pydub.playback import play
import os
import tkinter.messagebox
from tkinter import *
from tkinter import ttk
from tkinter import PhotoImage
from tkinter import filedialog
from pygame import mixer
import pygame
import threading
import pydub
from os.path import isdir, join, basename, splitext

#CONSTANTES
FRAMES_PADY = 30
FRAMES_PADX = 30
CHANNELS = 24
SONGEND = pygame.constants.USEREVENT

class CellPad:
    def __init__(self):
        pass
    busy = False
    file_name = None
    channel = None
    sound = None
    volume = 0.7
    paused = False
    played = False
    stopped = True
    loop = False

    def drawPad(self, master=None):
        pad = ttk.Frame(master, width=115, height=160, relief=GROOVE)
        pad.pack_propagate(0)
        pad.grid_propagate(0)
        pad.pack(side=LEFT, padx=5, pady=10)

        self.topframe = Frame(pad, width=100, height=25, relief=FLAT)
        self.topframe.pack(side=TOP, pady=2)
        self.topframe.pack_propagate(0)

        self.labelframe = Frame(self.topframe, relief=FLAT, width=80, height=25)
        self.labelframe.pack(side=LEFT, pady=2)
        self.labelframe.pack_propagate(0)

        self.closeframe = Frame(self.topframe, relief=FLAT)
        self.closeframe.pack(side=RIGHT, pady=2)

        self.label_name = ttk.Label(self.labelframe, text=os.path.basename(self.file_name if self.busy else "..."), relief=FLAT, font='Times 10 italic')
        self.label_name.pack(pady=2, side=LEFT)

        '''self.closeframe = Frame(pad, relief=FLAT, width=20, height=160)
        self.closeframe.pack(side=RIGHT, pady=5)
        self.closeframe.pack_propagate(0)'''

        self.close = ttk.Button(self.closeframe, text="X", command=self.onClose, width=0)
        self.close.pack(side=RIGHT, anchor=W, fill=X)

        self.playphoto = PhotoImage(file='icons/play-button.png')
        self.playbtn = Button(pad, image=self.playphoto, command=self.onPause)
        self.playbtn.pack()

        self.continuephoto = PhotoImage(file='icons/next.png')

        self.buttons = ttk.Frame(pad, padding='5 5')
        self.buttons.pack()

        self.stopphoto = PhotoImage(file='icons/stop16.png')
        self.stopbtn = ttk.Button(self.buttons, image=self.stopphoto, command=self.onStop)
        self.stopbtn.grid(row=0, column=0)

        self.pausephoto = PhotoImage(file='icons/pause.png')
        '''self.pausebtn = ttk.Button(self.buttons, image=self.pausephoto, command=None)
        self.pausebtn.grid(row=0, column=1)'''

        self.loopphoto = PhotoImage(file='icons/circular-arrow16.png')
        self.loopbtn = ttk.Checkbutton(self.buttons, image=self.loopphoto, style='Toolbutton', command=self.onLoop)
        self.loopbtn.grid(row=0, column=1)
        #self.loopImg = Label(self.buttons, image=self.loopphoto)

        #self.loopbtn["onvalue"] = True
        #self.loopbtn["offvalue"] = False
        #self.loopbtn["variable"] = self.loop

        self.sclBtns = ttk.Frame(pad, padding='5 5')
        self.sclBtns.pack()

        self.scale = ttk.Scale(self.sclBtns, from_=0, to=100, orient=HORIZONTAL, command=self.setVol)
        self.scale.set(70)  # implement the default value of self.scale when music player starts
        self.scale.pack()

    def onLoop(self):
        self.loop = not self.loop
        if self.loop:
            self.stopbtn["state"] = DISABLED
            self.close["state"] = DISABLED
            self.loopbtn.select()
        else:
            self.stopbtn["state"] = ACTIVE
            self.close["state"] = ACTIVE
            self.loopbtn.deselect()
        statusbar["text"] = self.loop

    def getChannel(self):
        for i in range(CHANNELS):
            if not mixer.Channel(i).get_busy():
                return i
            else:
                if i== CHANNELS-1:
                    tkinter.messagebox.showerror('Channels full', 'Number maximum of channels reached')
                    return None

    def onPause(self):
        statusbar["text"] = self.file_name
        if self.stopped:
            self.played = True
            self.stopped = False
            self.paused = False
            self.channel = mixer.Channel(self.getChannel())
            self.sound = mixer.Sound(self.file_name)
            self.channel.play(self.sound)
            playinglist.append(self)
        else:
            if self.paused:
                self.channel.unpause()
                self.paused = False
            else:
                self.channel.pause()
                self.paused = True

        if self.played:
            if self.paused:
                self.playbtn.configure(image=self.continuephoto)
            else:
                self.playbtn.configure(image=self.pausephoto)
        else:
            self.playbtn.configure(image=self.playphoto)

    def onStop(self):
        if not self.stopped:
            self.channel.stop()
            self.stopped = True
            self.playbtn.configure(image=self.playphoto)
        else:
            pass

    def setVol(self, val):
        self.volume = float(val) / 100
        self.channel.set_volume(self.volume)

    def onClose(self):
        if self.stopped:
            statusbar["text"] = "close"
            self.label_name["text"] = "..."
            self.file_name = None
            self.busy = False
        else:
            statusbar["text"] = "close"
            self.loopbtn.grid_forget()
            self.loop = False
            self.loopbtn.grid(row=0, column=1)
            self.channel.stop()
            self.file_name = None
            self.channel = None
            self.sound = None
            self.busy = False
            self.paused = False
            self.played = False
            self.stopped = True
            self.label_name["text"] = "..."
            self.playbtn.configure(image=self.playphoto)

'''class FancyListbox(tkinter.Listbox):

    def __init__(self, parent, mscSongs, evrSongs, efxSongs, *args, **kwargs):
        Listbox.__init__(self, parent, *args, **kwargs)

        self.mscsgs = mscSongs
        self.evrsgs = evrSongs
        self.efxsgs = efxSongs

        self.addmenu = Menu(self)

        self.popup_menu = Menu(self, tearoff=0)
        self.popup_menu.add_cascade(label="Add", menu=self.addmenu)

        self.addmenu.add_command(label="to Music")
        self.addmenu.add_command(label="to Environment")
        self.addmenu.add_command(label="to Effect")

        self.bind("<Button-3>", self.popup) # Button-2 on Aqua

    def popup(self, event):
        try:
            self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popup_menu.grab_release()

    def toMusic(self):
        selection = Listbox.curselection(0)
        selection = int(selection[0])
        for p in self.mscsgs:
            if not p.busy:
                p.file_name = songslist[selection]
                p.labelname.config(text=p.file_name)
                statusbar.config(text=p.file_name)
        pass

    def toEnviro(self):
        pass

    def toEffect(self):
        pass'''

root = Tk()
root.attributes("-fullscreen", True)

#create a statusbar
statusbar = ttk.Label(root, text="Welcome to Melody", relief=SUNKEN, anchor=W, font='Times 10 italic')
statusbar.pack(side=BOTTOM, fill=X)

# Create the menubar
menubar = Menu(root)
root.config(menu=menubar)

# Create the submenu

subMenu = Menu(menubar, tearoff=0)

pygame.init()
mixer.init()
mixer.set_num_channels(CHANNELS)

playinglist = []

songslist = []

# songslist - contains the full path + filename
# songsListbox - contains just the filename
# Fullpath + filename is required to play the music inside play_music load function

def browse_file():
    global filename_path
    filename_path = filedialog.askopenfilename(multiple=True)
    [add_to_songslist(f) for f in filename_path]

def add_to_songslist(filename):
    full_filename = filename
    filename = os.path.basename(full_filename)
    songsListbox.insert(END, filename)
    songslist.append(full_filename)

menubar.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Open", command=browse_file)
subMenu.add_command(label="Exit", command=root.destroy)

def about_us():
    tkinter.messagebox.showinfo('About SoundPadPy', 'This is a music player build using Python Tkinter by '
                                                    '@mrlactobacilo\nThe code base to this project is '
                                                    '\nhttps://github.com/attreyabhatt/Python-Music-Player')

subMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Help", menu=subMenu)
subMenu.add_command(label="About Us", command=about_us)

def convertMP3toOGG(songpath, path):
    statusbar["text"] = "Converting " + songpath
    soundname = basename(songpath)
    sound = pydub.AudioSegment.from_mp3(songpath)
    sound.export(join(path, splitext(soundname)[0] + ".ogg"), format="ogg")

def file_conversor():
    path = join(os.getcwd(), "converted_songs")
    try:
        if not isdir(path):
            os.mkdir(path)
    except OSError:
        tkinter.messagebox.showinfo('Error', 'Creation of directory %s failed' % path)
    filespath = filedialog.askopenfilename(multiple=True, title="Files to converter")

    try:
        statusbar["text"] = "Converting files..."
        [convertMP3toOGG(f, path) for f in filespath]
    except OSError:
        tkinter.messagebox.showinfo('Error', 'Conversion of file(s) failed!')
    else:
        tkinter.messagebox.showinfo('Successful', 'Conversion of file(s) done!')

subMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Converter", menu=subMenu)
subMenu.add_command(label="MP3 to OGG", command=file_conversor)

mixer.init()

# Root Window - StatusBar, LeftFrame, RightFrame
# LeftFrame - The listbox (songslist)
# RightFrame - TopFrame,MiddleFrame and the BottomFrame

musicpads = []
environmentpads = []
effectpads = []

def del_song():
    selected_song = songsListbox.curselection()
    selected_song = int(selected_song[0])
    songsListbox.delete(selected_song)
    songslist.pop(selected_song)

def toMusic():
    selected_song = songsListbox.curselection()
    selected_song = int(selected_song[0])
    idx = 0
    for p in musicpads:
        if not p.busy:
            p.file_name = songslist[selected_song]
            p.label_name["text"] = os.path.basename(p.file_name)
            p.busy = True
            statusbar["text"] = p.file_name
            break
        else:
            if idx == len(musicpads)-1:
                tkinter.messagebox.showerror('Pads full', 'This audio pad is full, please delete a item to add another')
                break
        idx += 1

def toEnviro():
    selected_song = songsListbox.curselection()
    selected_song = int(selected_song[0])
    idx = 0
    for p in environmentpads:
        if not p.busy:
            p.file_name = songslist[selected_song]
            p.label_name["text"] = os.path.basename(p.file_name)
            p.busy = True
            statusbar["text"] = p.file_name
            break
        else:
            if idx == len(environmentpads) - 1:
                tkinter.messagebox.showerror('Pads full', 'This audio pad is full, please delete a item to add another')
                break
        idx += 1

def toEffect():
    selected_song = songsListbox.curselection()
    selected_song = int(selected_song[0])
    idx = 0
    for p in effectpads:
        if not p.busy:
            p.file_name = songslist[selected_song]
            p.label_name["text"] = os.path.basename(p.file_name)
            p.busy = True
            statusbar["text"] = p.file_name
            break
        else:
            if idx == len(effectpads) - 1:
                tkinter.messagebox.showerror('Pads full', 'This audio pad is full, please delete a item to add another')
                break
        idx += 1

def busyMonitory():
    while True:
        for cell in playinglist:
            if not cell.channel.get_busy():
                if cell.loop:
                    cell.channel.play(cell.sound)
                else:
                    cell.stopped = True
                    cell.playbtn.configure(image=cell.playphoto)
                    playinglist.remove(cell)

        #statusbar["text"] = len(playinglist)

# ---LEFT FRAME---
leftframe = Frame(root)
leftframe.pack(side=LEFT, padx=30, pady=30)

addButtons = Frame(leftframe)
addButtons.pack(side=TOP)

addMscBtn = ttk.Button(addButtons, text="+ Musics", command=toMusic)
addMscBtn.pack(side=LEFT)

addEvrBtn = ttk.Button(addButtons, text="+ Environments", command=toEnviro)
addEvrBtn.pack(side=LEFT)

addEfxBtn = ttk.Button(addButtons, text="+ Efects", command=toEffect)
addEfxBtn.pack(side=LEFT)

songsListbox = Listbox(leftframe, width=30, height=30)
songsListbox.pack(pady=10)

addBtn = ttk.Button(leftframe, text="+ Add", command=browse_file)
addBtn.pack(side=LEFT)

delBtn = ttk.Button(leftframe, text="- Del", command=del_song)
delBtn.pack(side=RIGHT)

# ---RIGHT FRAME---
rightframe = Frame(root)
rightframe.pack(pady=10)

# TOP FRAME -> Pads for background musics
topframe = ttk.Frame(rightframe, relief=SUNKEN)
topframe.pack(pady=5)

musiclabel = Label(topframe, relief=FLAT, text="Music Pads")
musiclabel.pack(pady=5)

for i in range(8):
    pad = CellPad()
    musicpads.append(pad)
    musicpads[i].drawPad(topframe)

# MIDDLE FRAME -> Pads for background and environment songs
middleframe = ttk.Frame(rightframe, relief=SUNKEN)
middleframe.pack(pady=5)

environmentlabel = Label(middleframe, relief=FLAT, text="Environment Pads")
environmentlabel.pack(pady=5)

for i in range(8):
    pad = CellPad()
    environmentpads.append(pad)
    environmentpads[i].drawPad(middleframe)

# BOTTOM FRAME -> Pads for effect songs
bottomframe = ttk.Frame(rightframe, relief=SUNKEN)
bottomframe.pack(pady=5)

effectlabel = Label(bottomframe, relief=FLAT, text="Effect Pads")
effectlabel.pack(pady=5)

for i in range(8):
    pad = CellPad()
    effectpads.append(pad)
    effectpads[i].drawPad(bottomframe)

t1 = threading.Thread(target=busyMonitory)
t1.start()

tkinter.messagebox.showinfo('Wellcome to SoundPadPy', 'This sound pad just works with WAV and OGG audio files, '
                             'for another file format please use the converter tool.')

root.mainloop()


f = open("/home/ralf/Downloads/rosalind_kmp.txt","r")
seq = f.read().strip()
def kmp(seq):
    m = len(seq)
    kmpNext = m * [0]
    j = kmpNext[0]
    for i in range(1,m):
        while j > 0 and seq[i] != seq[j]:
            j = kmpNext[j-1]
        if seq[i] == seq[j] :
            j = j + 1
        kmpNext[i] = j
    return kmpNext
tab = kmp(seq)
output = open("res_kmp.txt","w")
output.writelines( "%s " % item for item in tab )
output.close()


from unittest import TestCase
from numpy import loadtxt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

class TestFinetune_class(TestCase):
    def test_finetune_class(self):
        from build import finetune_class
        dataset = loadtxt('./data/diabetes.csv', delimiter=',', skiprows=1)
        X = dataset[:, 0:8]
        y = dataset[:, 8]
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=13)

        param_grid = {"criterion": ['gini', 'entropy'],
                      "n_estimators": [10, 20, 30],
                      "max_depth": [None, 6, 8, 10],
                      "max_leaf_nodes": [None, 5, 10, 20],
                      "min_impurity_split": [0.1, 0.2, 0.3]}

        y_pred, _ = finetune_class(X_train, X_test, y_train, param_grid)
        acc = accuracy_score(y_pred, y_test)

        self.assertGreaterEqual(acc, 0.7)


# Monte Carlo with Exploring Starts

import invertedPendulumGame as ipg
import numpy as np
#import matplotlib.pyplot as plt
import pygame
import sys, os, argparse
import pickle
from pygame.locals import *
from collections import defaultdict

WINDOWDIMS = (1200, 600)
CARTDIMS = (50, 10)
PENDULUMDIMS = (6, 200)
GRAVITY = 0.13
REFRESHFREQ = 100
A_CART = 0.15

class MCESagent(object):
    def __init__(self, pendulum, max_episode_length, soft_policy_prob, alpha):
        """accepts bin divisions to create discretized states
        x_bins and theta_bins given in range 0 to 1
        v_bins and omega_bins given in actual values
        """
        assert isinstance(pendulum, ipg.InvertedPendulum)
        self.pendulum = pendulum
        self.max_episode_length = max_episode_length
        self.soft_policy_prob = soft_policy_prob
        self.alpha = alpha
        self.epsilon = 10 ** (-10)
        self.x_bins = [self.pendulum.CARTWIDTH / 2,
                       self.pendulum.WINDOWWIDTH - self.pendulum.CARTWIDTH / 2 - self.epsilon,
                       np.inf]
        self.coarse_xs = [-1, 0, 1]
        self.theta_bins = [-np.pi / 2, -0.2, -0.1, -0.05, 0, 0.05, 0.1, 0.2,
                           np.pi / 2 - self.epsilon, np.inf]
        self.coarse_thetas = [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]
        self.v_bins = [-10 * self.pendulum.A_CART,
                       -1 * self.pendulum.A_CART,
                       self.pendulum.A_CART - self.epsilon,
                       10 * self.pendulum.A_CART, np.inf]
        self.coarse_vs = [-2, -1, 0, 1, 2]
        self.omega_bins = [-0.01, -0.001, 0.001, 0.01, np.inf]
        self.coarse_omegas = [-2, -1, 0, 1, 2]
        self.Q = defaultdict(float)

    @staticmethod
    def fine_to_coarse(value, bins, labels):
        for i, b in enumerate(bins):
            if value <= b:
                return labels[i]

    def coarse_state(self):
        is_dead, t, x, v, theta, omega = self.pendulum.get_state()
        x_coarse = self.fine_to_coarse(x, self.x_bins, self.coarse_xs)
        v_coarse = self.fine_to_coarse(v, self.v_bins, self.coarse_vs)
        theta_coarse = self.fine_to_coarse(theta, self.theta_bins,
                                           self.coarse_thetas)
        omega_coarse = self.fine_to_coarse(omega, self.omega_bins,
                                           self.coarse_omegas)
        return is_dead, (x_coarse, v_coarse, theta_coarse, omega_coarse)

    def actions(self, previous_action, coarse_state):
        """defines available actions given state and previous action-
        must stop moving in one direction before moving in the other
        """
        x, _, _, _ = coarse_state
        result = ['None']
        if previous_action != 'Right' and x != self.coarse_xs[0]:
            result.append('Left')
        if previous_action != 'Left' and x != self.coarse_xs[-1]:
            result.append('Right')
        return result

    def random_init(self):
        x = np.random.uniform(self.pendulum.CARTWIDTH / 2,
                              self.pendulum.WINDOWWIDTH - self.pendulum.CARTWIDTH / 2)
        theta = np.random.uniform(-np.pi / 2, np.pi / 2)
        v = np.random.normal(0, 1.0)
        omega = np.random.normal(0, 0.1)
        is_dead = False
        return is_dead, x, v, theta, omega

    def nice_init(self):
        is_dead = False
        x = np.random.choice([self.pendulum.CARTWIDTH / 2,
                              self.pendulum.WINDOWWIDTH / 2,
                              self.pendulum.WINDOWWIDTH - self.pendulum.CARTWIDTH / 2])
        x = self.pendulum.WINDOWWIDTH / 2
        v = 0
        theta = np.random.uniform(-0.01, 0.01)
        omega = 0
        return is_dead, x, v, theta, omega

    def optimal_policy(self, previous_action, state):
        return max(self.actions(previous_action, state),
                   key=lambda a:self.Q[(previous_action,state,a)])

    def epsilon_policy(self, previous_action, state):
        if np.random.uniform(0,1) > self.soft_policy_prob:
            return self.optimal_policy(previous_action, state)
        else:
            return np.random.choice(self.actions(previous_action, state))

    def episode(self, init, policy = None):
        if policy is None:
            policy = self.epsilon_policy
        is_dead, x, v, theta, omega = init
        self.pendulum.set_state((is_dead, 0, x, v, theta, omega))
        previous_action = "None"
        is_dead, state = self.coarse_state()
        action = policy(previous_action, state)
        state_actions = []
        i = 0
        while not is_dead and i < self.max_episode_length:
            # Check the state you will go into
            self.pendulum.update_state(action)
            is_dead, new_state = self.coarse_state()
            old_Q = self.Q[(previous_action, state, action)]
            new_Q = self.Q[(action, new_state, self.optimal_policy(action, new_state))]
            # Update the value estimate
            self.Q[(previous_action, state, action)] += self.alpha * (1 + new_Q - old_Q)
            state_actions.append((previous_action, state, action))
            # Change your state
            previous_action, state = action, new_state
            action = policy(previous_action, state)
            i += 1
        return state_actions

    @staticmethod
    def plot_episode(state_action):
        theta_coarse = [theta for (_, (_, _, theta, _), _) in state_action]
        plt.scatter(range(len(theta_coarse)), theta_coarse)
        plt.show()

    def run(self, num_runs, train=False, policy=None):
        run_durations = []
        for i in range(num_runs):
            init = self.random_init() if train else self.nice_init()
            state_action = self.episode(init, policy=policy)
            run_durations.append(len(state_action))
        return run_durations

    def test(self):
        #assert self.fine_to_coarse(0, self.theta_bins, self.coarse_thetas) == 0
        assert self.fine_to_coarse(-3 * A_CART, self.v_bins, self.coarse_vs) == -1
        assert self.actions("Left", (0, 0, 0, 0)) == ["None", "Left"]
        print("Tests passed")

class MCESgame(ipg.InvertedPendulumGame):
    def __init__(self, windowdims, cartdims, penddims,
                 gravity, a_cart, refreshfreq, agent):
        assert isinstance(agent, MCESagent)
        self.agent = agent
        super(MCESgame, self).__init__(windowdims, cartdims, penddims,
                                       gravity, a_cart, refreshfreq,
                                       agent.pendulum)

    def game_round(self):
        self.agent.pendulum.reset_state()
        previous_action = "None"
        while not self.agent.pendulum.is_dead:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYUP:
                    if event.key == K_ESCAPE:
                        pygame.quit()
                        sys.exit()
            is_dead, state = self.agent.coarse_state()
            action = self.agent.optimal_policy(previous_action, state)
            t, x, _, theta, _ = self.agent.pendulum.update_state(action)
            previous_action = action
            self.time = t
            self.surface.fill(self.WHITE)
            self.draw_cart(x, theta)

            time_text = "t = {}".format(self.time_seconds())
            self.render_text(time_text, (0.1 * self.WINDOWWIDTH, 0.1 * self.WINDOWHEIGHT),
                             position = "topleft", fontsize = 40)
            if action == 'Left':
                action_text = '<-       '
            elif action == 'None':
                action_text = '    |    '
            elif action == 'Right':
                action_text = '       ->'
            self.render_text(action_text, (0.1 * self.WINDOWWIDTH, 0.2 * self.WINDOWHEIGHT),
                             position = "topleft", fontsize = 40)
            state_text = str(state)
            self.render_text(state_text, (0.1 * self.WINDOWWIDTH, 0.3 * self.WINDOWHEIGHT),
                             position = "topleft", fontsize = 40)

            pygame.display.update()
            self.clock.tick(self.REFRESHFREQ)
        if (self.time_seconds()) > self.high_score:
            self.high_score = self.time_seconds()

    def game(self):
        self.starting_page()
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        pygame.quit()
                        sys.exit()
            self.game_round()
            self.end_of_round()
            pygame.time.wait(500)

def main():
    parser = argparse.ArgumentParser(
        description="Pass name of pickle to use or write to")
    parser.add_argument('filename', type=str)
    args = parser.parse_args()
    FILEPATH = os.getcwd() + "/" + args.filename + ".pickle"
    if os.path.exists(FILEPATH):
        with open(FILEPATH, 'rb') as f:
            agent = pickle.load(f)
    else:
        pend = ipg.InvertedPendulum(WINDOWDIMS, CARTDIMS, PENDULUMDIMS,
                                    GRAVITY, A_CART)
        agent = MCESagent(pend, 20000, 0.1, 0.05)
        agent.test()
        performance = []
        for i in range(10):
            agent.run(100)
            durations = agent.run(50, train=False, policy=agent.optimal_policy)
            avg_duration = np.mean(durations)
            performance.append(avg_duration)
            print("Step: {}, Average Duration {}".format(i+1, avg_duration))
    ##        if i % 50 == 0:
    ##            e = agent.episode(agent.nice_init())
    ##            agent.plot_episode(e)
        with open(FILEPATH, 'wb') as output:
            pickle.dump(agent, output)
    game = MCESgame(WINDOWDIMS, CARTDIMS, PENDULUMDIMS, GRAVITY, A_CART,
                    REFRESHFREQ, agent)
    game.game()

if __name__ == "__main__":
    main()


import random
import numpy as np
import cv2
import networkx as nx
import matplotlib.pyplot as plt

#Competidores
Grupo_Papaya=["P1","P2","P3","P4","P5"]
Grupo_Coche=["C1","C2","C3","C4","C5"]
Grupo_Amor=["A1","A2","A3","A4","A5"]
Grupo_Netflix=["N1","N2","N3","N4","N5"]
Grupo_Madagascar=["M1","M2","M3","M4","M5"]
print('Carrera 1:',Grupo_Papaya)
print('Carrera 2:',Grupo_Coche)
print('Carrera 3:',Grupo_Amor)
print('Carrera 4:',Grupo_Netflix)
print('Carrera 5:',Grupo_Madagascar)

#Arreglos de Velocidad

Velocidad=np.zeros((5,5))
Dimension=Velocidad.shape
for x in range(Dimension[0]):
    for y in range(Dimension[0]):
        Velocidad[x,y]=random.randint(1,200)
print('\nResultados')

for x in range(5):
    Velocidad[x].sort()

Velocidad=Velocidad[np.argsort(Velocidad[:,-1])]
for x in range(5):
    print("Carrera",5-x,":",Velocidad[x])
#Arreglo Para las primeras 5 carreras
for x in range(5):
    print('ganador grupo',5-x,Velocidad[x,4])
#Arreglo de carrera 6
Carrera_6 =Velocidad[np.argsort(Velocidad[:, -1])]
Carrera_6.sort()
for x in range(5):
  print(Carrera_6[x])
print("Carrera 6:", Carrera_6, "\n")
print("Caballo más rapido: ", int(Carrera_6[4,4]), "Velocidad tope\n")
#Arreglo de carrera 7
Carrera_7= [Carrera_6[2, 4], Carrera_6[3, 4], Carrera_6[3, 3], Carrera_6[4, 3], Carrera_6[4, 2]]
Carrera_7.sort()
print("Carrera 7:", Carrera_7, "\n")
print ("Caballo en segundo lugar: ", int(Carrera_7[4]), "Velocidad tope")
print(" Podio:\n primer lugar: ",int(Carrera_6[4,4]),"en velocidad tope ","\n En segundo lugar: ",int(Carrera_7[4]),"en velocidad tope")

#Grafo
Primer_Lugar= Carrera_6[4,4]
Segundo_Lugar= Carrera_7[4]
Podio = nx.Graph()
Podio.add_edge('Podio ',Primer_Lugar)
Podio.add_edge('Podio ',Segundo_Lugar)
fig, ax = plt.subplots()
nx.draw(Podio, ax=ax, with_labels=True, )
plt.show()

Carrera de CAballos 19310462/Carrera_de_CAballos_19310462.py


with open('basnicka.txt', encoding='utf-8') as soubor:
    kytice = soubor.read()

def obrat_poradi_versu(text):
    '''
    Dostane text, obrati poradi versu a text vypise.
    '''
    seznam = text.split('\n')
    seznam.reverse()

    for radek in seznam:
        print(radek)

obrat_poradi_versu(kytice)

def obrat_poradi_slov(text):
    '''
    Dostane text, obrati poradi slov v jednotlivzch versich
    a text vypise.
    '''
    seznam = text.split('\n')

    for radek in seznam:
        slova = radek.split(' ')
        slova.reverse()
        print(' '.join(slova))

obrat_poradi_slov(kytice)

def obrat_poradi_slok(text):
    '''
    Dostane text, obrati poradi slok a text vypise.
    '''
    seznam = text.split('\n\n')
    seznam.reverse()

    for sloka in seznam:
        print(sloka, end='\n\n')

obrat_poradi_slok(kytice)