"""
Requerimientos:

Crea un programa que lea una ip y determine su clase según su rango, la información que debe mostrar debe ser la siguiente:

°Clase de ip (clase a, b o c)
°Cuantos host pueden haber en esa subred

Ej: en una clase c pueden haber 254 host por cada red, por lo tanto imprimiría 254 por la red actual)

Ejemplo de la salida del programa:

"Tu ip es 192.168.0.1 es de clase C y pueden haber 254 host en tu red actual"

code:prog_b7_tuuser.py

Datos para elegir el tipo de IP

Class        Networks                     mask          CDIR       leading bits
A       0.0.0.0   - 127.255.255.255     255.0.0.0         /8        0
B       128.0.0.0 - 191.255.255.255     255.255.0.0       /16       10
C       192.0.0.0 - 223.255.255.255     255.255.0.0       /24       110
D       224.0.0.0 - 239.255.255.255         not defined             1110        Multicast
E       240.0.0.0 - 247.255.255.255         not defined             1111        Reserved

información procedente de:
https://en.wikipedia.org/wiki/Classful_network

LIBRERIAS ADICIONALES

"""
import ipaddress
import sys

# Interactua con el usuario para pedir la IP
def pedir_ip ():
    ip_s = input  ("Introduce una IP en notación clásica o CIDR: ")
    return ip_s

def comprobar_tipos (ipt):
    if ipt.is_multicast:
        print (f'La ip {ipt} es multicast.')
    if ipt.is_private:
        print (f'La ip {ipt} es private.')
    if ipt.is_global:
        print (f'La ip {ipt} es global.')
    if ipt.is_unspecified:
        print (f'La ip {ipt} es sin especificar.')
    if ipt.is_reserved:
        print (f'La ip {ipt} es reservada.')
    if ipt.is_loopback:
        print (f'La ip {ipt} es loopback.')
    if ipt.is_link_local:
        print (f'La ip {ipt} es link local.')

def es_ip (ip_s):
    """

    """
    ip      = None
    network = None
    clase   = None
    tipo    = None
    # tipo de ip 1-> notación clásica, 2-> CIDR
    dir_ok  = False

    try:
        ip = ipaddress.IPv4Address(ip_s)
        # si pasa la IP con notación clásica es valida')
        dir_ok = True
        tipo = 1
    except:
        # si no pasa la IP no es valida
        dir_ok = False

    if not dir_ok:
        try:
            network = ipaddress.IPv4Network(ip_s, strict=False)
            # si pasa es una IP con notación CIDR
            ip, _ = ip_s.split('/')
            ip = ipaddress.IPv4Address(ip)
            dir_ok = True
            tipo = 2    # Es notación CIDR, ya hemos guardo IP y network
        except:
            # si no pasa no es ningún
            dir_ok = False

    if tipo == 1:   # es notación clasica, vemos de que clase sería.
        a, b, c, d = ip_s.split('.')
        a, b, c, d = int(a), int (b), int (c), int (d)

        if a < 128:
            clase = "A"
            full_ip = ip_s +'/8'
        elif a < 192:
            clase = 'B'
            full_ip = ip_s +'/16'
        elif a < 224:
            clase = 'C'
            full_ip = ip_s +'/24'
        elif a < 240:
            clase = 'D'
            full_ip = None
        else:
            clase = 'E'
            full_ip = None

        try:
            # generamos la variable network para los calculos de prefijo, mascara ...
            network = ipaddress.IPv4Network(full_ip, strict=False)
        except:
            network = None

    # devolvera ('None', 'None', 'None', 'None') si lo introducido no es una IP valida
    # en otro caso devolera los valores correctos, de IP, network, clase y tipo
    return (ip, network, clase, tipo)

def imprimir (data):

    print (f"Dirección ip: {data[0]}")
    if data[2]:
        print (f'Es una red de clase {data[2]}.')
    else:
        # data[1] -> network, sacamos el prefijo de la red, para luego calcular los hosts
        prefijo = data[1].prefixlen
        print ('Has introducido la dirección IP en formato CIDR.')
        # Aunque se ha usado notación CIDR, usamos el prefijo para saber que clase de red sería
        if prefijo == 24:
            print ('Que por la máscara de red podría ser de clase C')
        elif prefijo == 16:
            print ('Que por la máscara de red podría ser de clase B')
        elif prefijo == 8:
            print ('Que por la máscara de red podría ser de clase A')

    if data[1]:
        print (f'La máscara de red es: {str(data[1].netmask)}')
        # para calcular los host (2^(32-prefijo))-2
        # 32-prefijo -> número de 0 que hay en la máscara
        # -2, 1 por la IP de net y 1 por la IP de broadcast
        prefijo = data[1].prefixlen
        hosts = (2**(32-prefijo))-2 # 1 por broadcast y otro por dirección de red
        print (f'En esta red puede haber {hosts} hosts')
    else:
        print ('Es una red reservada, por tanto el numero de hosts es "not defined"')
        # Esto es por definición de las redes de clase D y E

    comprobar_tipos(data[0])

def main_chequear_IP ():
    """

    """

    data = (None, None, None, None)

    while data[0] == None:
        ip = pedir_ip ()
        data = es_ip (ip)

    imprimir (data)

# programa PRINCIPAL
if __name__ == "__main__":
    arguments_count=len(sys.argv)

    print ("________________________________________________________________________________")
    print ('Ejercicio b7. Para una dirección IP mostrar clase y número de hosts que admite.')
    print ('@jabaselga')
    print (f'Para ejecutar el comando: {sys.argv[0]} [IP|IP/mask|IP/prefix]')
    print ('Ejemplo de notación clásica: 192.168.4.2')
    print ('Ejemplo de notación CIDR: 192.168.4.2/23 o 192.168.5.2/255.255.240.0')
    print ("________________________________________________________________________________")

    if arguments_count > 2:
        print ('Para ejecutar el comando:')
        print (f'{sys.argv[0]} [IP|IP/mask|IP/prefix]')

    elif arguments_count == 2:
        data = es_ip (sys.argv[1])
        if data[0] != None:
            imprimir(data)
        else:
            print (f'El argumento "{sys.argv[1]}" introducido no es una dirección IP válida')
    else:
        main_chequear_IP()


def sendMessages(messages):
    i = 0
    for msg in messages:
        printMsg = f"{msg.title()}"
        print(printMsg)
        sentMsgList.append(msg)
        msgList[i] = 'null'
        i += 1

msgList = ['a', 'b', 'c', 'd', 'e', 'f']
sentMsgList = []
sendMessages(msgList)
print(msgList), print(sentMsgList)


# импортируем библиотеку sqlalchemy и ее функции
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# константа, указывающая способ соединения с базой данных
DB_PATH = "sqlite:///albums.sqlite3"

# создаем базовый класс моделей таблиц
Base = declarative_base()

# класс, описывающий структуру таблицы album для хранения записей музыкальной библиотеки
class Album(Base):

	# задаем название таблицы
	__tablename__ = "album"

	# описываем столбцы таблицы
	id = sa.Column(sa.INTEGER, primary_key=True)
	year = sa.Column(sa.INTEGER)
	artist = sa.Column(sa.TEXT)
	genre = sa.Column(sa.TEXT)
	album = sa.Column(sa.TEXT)

# Функция, которая устанавливает соединение к базе данных, создает таблицы, если их еще нет и возвращает объект сессии
def connect_db():

	#создаем соединение с БД:
	engine = sa.create_engine(DB_PATH)
	# создаем описанные таблицы
	Base.metadata.create_all(engine)
	# создаем фабрику сессий
	session = sessionmaker(engine)
	return session()

# задаем функцию для поиска и формирования списка названий альбомов artist (передается в GET-запросе)
def find(artist):
	session = connect_db()
	albums = session.query(Album).filter(Album.artist == artist).all()
	return albums

# данная функция принимает параметры нового альбома, передаваемые в POST-запросе, и записывает их в таблицу sqlite
def save_new_album(year, artist, genre, album):
	# валидация передаваемых данных по их типу:
	assert isinstance(year, int), "Некорректный формат данных года. Введите число"
	assert isinstance(artist, str), "Некорретный формат данных. Введите текст"
	assert isinstance(genre, str), "Некорретный формат данных. Введите текст"
	assert isinstance(album, str), "Некорретный формат данных. Введите текст"

	session = connect_db()
	saved_album = session.query(Album).filter(Album.album == album, Album.artist == artist).first()
	if saved_album is not None:
		raise AlreadyExists("Альбом уже существует и имеет номер {}".format(saved_album.id))

	album = Album(
		year=year,
		artist=artist,
		genre=genre,
		album=album
		)

	session.add(album)
	session.commit()
	return album


from flux_query_builder.functions.base import FluxQueryFunction

class ActionFromLevel(FluxQueryFunction):
    """pagerduty.actionFromLevel() converts a monitoring level to a PagerDuty action.(Required)
Monitoring level to convert to a PagerDuty action.

    Params:

        level
        - (Required)
Monitoring level to convert to a PagerDuty action.

    """
    name = "actionFromLevel"
    package="pagerduty"

    def __init__(self, level, ):
            super().__init__(level=level, )


"""Random Module"""

# import random

# random_integer = random.randint(1,10)
# print(random_integer)

# random_float = random.random()
# print(random_float)

"""Heads or Tails exercise"""

# You are going to write a virtual coin toss program. It will randomly tell the user "Heads" or "Tails".

### CODE ###

# #Write your code below this line 👇
# #Hint: Remember to import the random module first. 🎲

# import random

# coin = round(random.random())

# if coin == 1:
#     print("Heads")
# else:
#     print("Tails")

# ## 👆

"""Python Lists"""

# states_of_india = ["Haryana", "Maharashtra", "Bihar"]

# print(states_of_india)          # ['Haryana', 'Maharashtra', 'Bihar']

# print(states_of_india[0])       # Haryana
# print(states_of_india[1])       # Maharashtra
# print(states_of_india[2])       # Bihar

# print(states_of_india[-1])      # Bihar

# states_of_india[0] = "Jammu and Kashmir"
# print(states_of_india)           # ['Jammu and Kashmir', 'Maharashtra', 'Bihar']

# states_of_india.append("Punjab")
# print(states_of_india)          # ['Jammu and Kashmir', 'Maharashtra', 'Bihar', 'Punjab']

# states_of_india.extend(["Mizoram", "Meghalaya"])
# print(states_of_india)          # ['Jammu and Kashmir', 'Maharashtra', 'Bihar', 'Punjab', 'Mizoram', 'Meghalaya']

"""Who's Paying Exercise"""

# You are going to write a program which will select a random name from a list of names.
# The person selected will have to pay for everybody's food bill.

### CODE ###

# import random

# # Split string method
# names_string = input("Give me everybody's names, separated by a comma. ")
# names = names_string.split(", ")
# # 🚨 Don't change the code above 👆

# #Write your code below this line 👇

# pick = round(random.random() * len(names)) - 1
# print(f"{names[pick]} is going to pay!")

# ## 👆

"""Nested Lists"""

# dirty_dozen = ["strawberries", "celery", "apples", "cherries", "potato" ,"spinach"]
# print(dirty_dozen)

# fruits = ["strawberries", "apples", "cherries"]
# vegetables = ["celery", "potato", "spinach"]

# dirty_dozen = [fruits, vegetables]
# print(dirty_dozen)

"""Treasure Island Exercise"""

# You are going to write a program which will mark a spot with an X.

# In the starting code, you will find a variable called map.

# This map contains a nested list. When map is printed this is what the nested list looks like:

# ['⬜', '⬜', '⬜'],['⬜', '⬜', '⬜'],['⬜', '⬜', '⬜']

# In the starting code, we have used new lines (\n) to format the three rows into a square, like this:

# ['⬜', '⬜', '⬜']
# ['⬜', '⬜', '⬜']
# ['⬜', '⬜', '⬜']

### CODE ###

# 🚨 Don't change the code below 👇
row1 = ["⬜","⬜","⬜"]
row2 = ["⬜","⬜","⬜"]
row3 = ["⬜","⬜","⬜"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆

#Write your code below this row 👇

horizontal = int(position[0])
vertical = int(position[1])
map[vertical - 1][horizontal - 1] = "X"

#Write your code above this row 👆

# 🚨 Don't change the code below 👇
print(f"{row1}\n{row2}\n{row3}")


import json
from roamon_verify import roamon_verify_checker
from roamon_verify import roamon_verify_getter
import roamon_alert_watcher
import os
import signal
import daemon
import daemon.pidfile
import sys
import logging
import time

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

class RoamonAlertDaemon():
    def __init__(self, file_path_pid_lockfile, log_path, checker, watch_interval):
        self.path_pid_lockfile = file_path_pid_lockfile
        self.log_file_path = log_path
        self.checker = checker
        self.watch_interval = watch_interval  # 分指定

    @classmethod
    def __start_daemon_with_func(cls, func, *args, logpath, pidpath, **kws):
        logger.debug("DAEMON_INVOKER: invoke daemon")
        # [ここ](https://qiita.com/KosukeJin/items/e626ddda850aa8407cee)からコピペ気味
        # 多重起動防止
        if pidpath:
            pid = daemon.pidfile.PIDLockFile(pidpath)
            logger.debug("DAEMON_INVOKER: pid: {}".format(pid))
            if pid.is_locked():
                raise Exception('Process is already started.')

        # PID指定がなければフォアグラウンド
        else:
            pid = None
        # ログ
        if logpath:
            std_out = open(logpath, mode='a+', encoding='utf-8')
            std_err = std_out

        # 指定がなければ標準出力
        else:
            std_out = sys.stdout
            std_err = sys.stderr

        dc = daemon.DaemonContext(
            umask=0o002,

            pidfile=pid,
            stdout=std_out,
            stderr=std_err,
        )

        # 内部で実行される
        def forever():
            # while 1は実行失敗時にまた行うためのもの(渡されるfuncは中でループするので基本的にこっちではループしないはず)
            while 1:
                try:
                    func(*args, **kws)

                # kill -SIGTERM {pid} で停止する
                except SystemExit as e:
                    print('Killed by SIGTERM.')
                    raise

                # それ以外のエラーは無視して動き続ける
                except Exception as e:
                    print('Uncaught exception was raised, but process continue.', e)

        with dc:
            forever()

    # デーモンが実行するループ
    def main_loop(self, kws=None):
        logger.debug("enter main_loop")

        while 1:
            logger.debug("start loop")
            # TODO: やっつけ実装なので、一定間隔でこれらを実行するいい案を考える (非同期にするとそれはそれで面倒で、ダウンロード中や処理中のファイルを開こうとするときはやめてリトライとかする必要がありそう。でもそうすべきかなー)

            # BGP経路情報とVRPのフェッチ
            self.checker.fetch_rib_data()
            self.checker.fetch_vrps_data()

            # BGP経路情報とVRP,および連絡先情報をロードし直す
            self.checker.load_all_data()
            # 異常がないかチェック
            self.checker.check_roa_with_all_watched_asn()

            logger.debug("end working in loop")

            # 　規定時間まつ
            time.sleep(60 * self.watch_interval)
            logger.debug("end loop")

            # 以下はもしもっと正確にやるならこんな感じというやつ...(未完成)
            # interval_min_fetch_rib = self.watch_interval
            # interval_min_fetch_vrps = self.watch_interval
            # interval_min_check_roa_with_wtached_asn = self.watch_interval
            # # 現在時刻と次回起動時刻
            # t = datetime.now().replace(second=0, microsecond=0)
            # next_up_time_fetch_rib  = t + timedelta(minutes=interval_min_fetch_rib)
            # next_up_time_fetch_vrps = t + timedelta(minutes=interval_min_fetch_vrps)
            # next_up_time_check_roa_with_wtached_asn = t + timedelta(minutes=interval_min_check_roa_with_wtached_asn)
            #
            # # intervalの倍数ジャストに起動 (非同期でやらないのは、書き込み中のファイルを読み込んだりしないように)
            # if t.minute % interval_min_fetch_rib == 0:
            #     self.checker.fetch_rib_data()
            # # 1周目 次回実行時間まで調整
            # else:
            #     stop = stop = interval_min_fetch_rib - t.minute % interval_min_fetch_rib
            #     n = t + timedelta(minutes=stop)
            #
            # if t.minute % interval_min_fetch_vrps == 0:
            #     self.checker.fetch_vrps_data()
            #
            # if t.minute % interval_min_check_roa_with_wtached_asn == 0:
            #     self.checker.check_roa_with_all_watched_asn()
            #
            # w = (n - datetime.now()).total_seconds()
            # log_to_stdout('[INFO]', 'Sleep', w, 'seconds.')
            # time.sleep(w)

    # デーモン起動
    def start(self):
        logger.debug("call start daemon!")
        self.__start_daemon_with_func(self.main_loop, logpath=self.log_file_path, pidpath=self.path_pid_lockfile,
                                      kws=None)

    # デーモン停止
    def stop(self):
        # PIDファイルがあるかどうか見る。あるなら既に起動中のはず
        if not os.path.exists(self.path_pid_lockfile):
            logger.error("PID file for the daemon is not found at {}".format(self.path_pid_lockfile))

        pid = daemon.pidfile.PIDLockFile(self.path_pid_lockfile)

        # デーモンのプロセスを終了させる
        daemon_pid = pid.read_pid()
        logger.debug("killing daemon process with PID:{}...".format(daemon_pid))
        try:
            os.kill(daemon_pid, signal.SIGTERM)
        except ProcessLookupError:
            # プロセスが動いてなかったらここでおしまい
            logger.error("Process PID:{} is not running.".format(daemon_pid))
            return

        # PIDファイルを始末
        logger.debug("releasing daemon process with PID file:{}...".format(self.path_pid_lockfile))
        pid.break_lock()


#1
def check_age(age):
    if age < 0:
        raise ValueError("Вік вказанно некореткно!")
    elif age % 2 == 0:
        return "Парне"
    else:
        return "Непарне"

def main():
    try:
        age = int(input("Твій вік: "))
        result = check_age(age)
        print(f"Твій вік {result}.")
    except ValueError as i:
        print(f"Error: {i}")
    except Exception as o:
        print(f"Сталася неочікувана помилка: {0}")

if __name__ == "__main__":
    main()
#2
def day_of_week(number):
    if number == 1:
        return "Понеділок"
    elif number == 2:
        return "Вівторок"
    elif number == 3:
        return "Середа"
    elif number == 4:
        return "Четвер"
    elif number == 5:
        return "П'ятниця"
    elif number == 6:
        return "Субота"
    elif number == 7:
        return "Неділя"
    else:
        return "Такого дня у неділі немає!"

def main():
    try:
        number = int(input("Введи число (1-7), щоб отримати відповідний день тижня: "))
        if 1 <= number <= 7:
            day = get_day_of_week(number)
            print(f"Обранний день тижня це {day}.")
        else:
            print("Помилка. Вводіть число від 1 до 7.")
    except ValueError:
        print("Вводити можна лише число.")

if __name__ == "__main__":
    main()

SashaZaitsev/HW11/PRACTICAL TASKS Exception [GITHUB].py


def bubble_sort(A):
    for i in range(len(A)):

        # Last i elements are already in place
        for j in range(0, len(A)-i-1):
            if A[j] > A[j+1]:
                A[j], A[j+1] =  A[j+1], A[j]
    return A

if __name__ == "__main__":
    print (bubble_sort([5,2,4,9,6,8]))


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
 @Author :yicg
 @Time : 2021/3/1 下午10:27
 @Version : 1.0
 @Description :   测试script
"""
from time import sleep

from selenium import webdriver

class TestJs():
    driver_path = '/Users/yicg/Downloads/chromedrivers/chromedriver'

    def setup(self):
        self.driver = webdriver.Chrome(executable_path=self.driver_path)
        self.driver.maximize_window()
        self.driver.implicitly_wait(5)  # 隐式等待

    def teardown(self):
        sleep(3)
        self.driver.quit()

    def test_js_1(self):
        """
        案例1：滑动到浏览器底部或者顶部
        1.打开百度首页
        2.输入搜索关键字
        3.点击搜索后，跳转到搜索结果页
        4.滑动到底部点击下一页

        :return:
        """
        self.driver.get("http://www.baidu.com")
        self.driver.find_element_by_id("kw").send_keys("selenium测试")
        ele=self.driver.execute_script("return document.getElementById('su')")  #js
        ele.click()
        sleep(3)
        #滑动到最低端
        self.driver.execute_script("document.documentElement.scrollTop=10000")
        #点击下一页
        self.driver.find_element_by_xpath('//*[@class="n"]').click()
        sleep(3)
        #在滑一次
        self.driver.execute_script("document.documentElement.scrollTop=10000")

    def test_js_2(self):
        """
        js案例2
        1.打开12306网站
        2.移除时间的只读模式
        3.输入新的时间
        :return:
        """
        self.driver.get("https://www.12306.cn/index/")
        #移除只读模式
        self.driver.execute_script(" a=document.getElementById('train_date');a.removeAttribute('readonly');")
        #输入新的时间
        self.driver.execute_script("a=document.getElementById('train_date');a.value='2020-3-20'")


import sys

input_value = sys.argv[1]
len_input_value = len(input_value)

p_h = []
for i in range(0, len_input_value + 1):
	column = {}
	for j in range(1, 6):
		column[j] = 0
	p_h.append(column)

# Initial probability of h1, h2, h3, h4, h5
p_h[0][1] = 0.1
p_h[0][2] = 0.2
p_h[0][3] = 0.4
p_h[0][4] = 0.2
p_h[0][5] = 0.1

# Initial probability of cherry
p_c = {}
p_c[1] = 1
p_c[2] = 0.75
p_c[3] = 0.50
p_c[4] = 0.25
p_c[5] = 0

# Initial probability of lime
p_l = {}
p_l[1] = 0
p_l[2] = 0.25
p_l[3] = 0.50
p_l[4] = 0.75
p_l[5] = 1

p_q_c = {}
p_q_l = {}

# Initial probability of observation sequence for cherry and lime
p_q_c[0] = p_h[0][1] * p_c[1] + p_h[0][2] * p_c[2] + p_h[0][3] * p_c[3] + p_h[0][4] * p_c[4] + p_h[0][5] * p_c[5]
p_q_l[0] = p_h[0][1] * p_l[1] + p_h[0][2] * p_l[2] + p_h[0][3] * p_l[3] + p_h[0][4] * p_l[4] + p_h[0][5] * p_l[5]

file = open('result.txt', 'w')

#print("Observation sequence Q: " + input_value + "\n")
#print("Length of Q: " + str(len_input_value) + "\n")
file.write ("Observation sequence Q: " + input_value + "\n")
file.write ("Length of Q: " + str(len_input_value) + "\n")

i = 1

for alphabet in input_value:
	file.write ("After Observation " + str(i) + " = " + alphabet + "\n\n")
	#print("After Observation " + str(i) + " = " + alphabet + "\n\n")
	if alphabet == "L":
		p_q_l[i] = 0
		for j in range(1, 6):
			p_h[i][j] = (p_l[j] * p_h[i-1][j]) / p_q_l[i-1]
			p_q_l[i] = p_q_l[i] + (p_h[i][j] * p_l[j])

			file.write ("P(h" + str(j) + "| Q) = " + str(round(p_h[i][j], 5)) + "\n")
			#print("P(h" + str(j) + "| Q) = " + str(round(p_q_c[i], 5)) + "\n")

		p_q_c[i] = 1 - p_q_l[i]

		file.write("Probability that next candy we pick will be C, given Q: %.5f\n" % round(p_q_c[i], 5))
		file.write("Probability that next candy we pick will be L, given Q: %.5f\n" % round(p_q_l[i], 5))
		#print("Probability that next candy we pick will be C, given Q: %.5f\n" % round(p_q_c[i], 5))
		#print("Probability that next candy we pick will be L, given Q: %.5f\n" % round(p_q_l[i], 5))

	elif alphabet == "C":
		p_q_c[i] = 0
		for j in range(1, 6):
			p_h[i][j] = (p_c[j] * p_h[i-1][j]) / p_q_c[i-1]
			p_q_c[i] = p_q_c[i] + (p_h[i][j] * p_c[j])

			file.write ("P(h" + str(j) + "| Q) = " + str(round(p_h[i][j], 5)) + "\n")
			#print("P(h" + str(j) + "| Q) = " + str(round(p_q_l[i], 5)) + "\n")

		p_q_l[i] = 1 - p_q_c[i]

		file.write("Probability that next candy we pick will be C, given Q: %.5f\n" % round(p_q_c[i], 5))
		file.write("Probability that next candy we pick will be L, given Q: %.5f\n" % round(p_q_l[i], 5))
		#print(round(p_q_c[i], 5))
		#print(round(p_q_l[i], 5))

	i = i + 1

file.close()


import pandas as pd
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import roc_auc_score
from model_training_functions.kfold_cross_validation import train_model_by_kfold
import matplotlib.pyplot as plt
import seaborn as sns

def max_depth(data, do_plot=False):
    depths = range(1, 10)
    all_scores = pd.DataFrame()

    for depth in depths:
        model = DecisionTreeClassifier(max_depth=depth)
        scores = train_model_by_kfold(data, model)
        all_scores = all_scores.append({'max_depth': depth,
                                        'test_score': scores['test_score'].mean(),
                                        'training_score': scores['training_score'].mean()}, ignore_index=True)
    if do_plot:
        plot_max_depth(all_scores)

    return all_scores

def criterion(data, do_plot=False):
    criterions = ['gini', 'entropy']
    all_scores = pd.DataFrame()

    for criterion in criterions:
        model = DecisionTreeClassifier(max_depth=5, criterion=criterion)
        scores = train_model_by_kfold(data, model)
        all_scores = all_scores.append({'criterion':  criterion,
                                        'test_score': scores['test_score'].mean(),
                                        'training_score': scores['training_score'].mean() }, ignore_index=True)

    if do_plot:
        plot_criterion(all_scores)

    return all_scores

def min_samples_leaf(data, do_plot=False):
    min_samples = range(1, 200, 10)
    all_scores = pd.DataFrame()

    for min_sample in min_samples:
        model = DecisionTreeClassifier(max_depth=5, criterion='entropy', min_samples_leaf=min_sample)
        scores = train_model_by_kfold(data, model)
        all_scores = all_scores.append({'min_samples_leaf':  min_sample,
                                        'test_score': scores['test_score'].mean(),
                                        'training_score': scores['training_score'].mean()}, ignore_index=True)

    if do_plot:
        plot_min_sample_leaf(all_scores)

    return all_scores

def min_impurity_decrease(data, do_plot=False):
    min_impurities = [i / 1000 for i in range(10)]
    all_scores = pd.DataFrame()
    for min_impurity in min_impurities:
        model = DecisionTreeClassifier(max_depth=5, criterion='entropy', min_samples_leaf=140, min_impurity_decrease=min_impurity)
        scores = train_model_by_kfold(data, model)
        all_scores = all_scores.append({'min_impurity_decrease': min_impurity,
                                        'test_score': scores['test_score'].mean(),
                                        'training_score': scores['training_score'].mean()}, ignore_index=True)
    if do_plot:
        plot_min_impurity(all_scores)

    return all_scores

def plot_max_depth(all_scores):
    print(all_scores)
    plt.figure(figsize=(12, 5))
    ax1 = sns.lineplot(x=all_scores['max_depth'], y=all_scores['test_score'], label='Validation')
    ax2 = sns.lineplot(x=all_scores['max_depth'], y=all_scores['training_score'], label='Training')
    ax1.set(xlabel='Max Depth', ylabel='ROC-AOC Score')
    ax2.set(xlabel='Max Depth', ylabel='ROC-AOC Score')
    plt.legend()
    plt.title('Max Depth Tuning')
    plt.show()

def plot_criterion(all_scores):
    plt.figure(figsize=(12, 5))
    temp = pd.melt(all_scores, id_vars='criterion')
    ax1 = sns.catplot(x='criterion', y='value',
                      hue='variable', data=temp, kind='bar', legend=False)
    ax1.set(xlabel='Criterion', ylabel='ROC-AOC Score')
    plt.title('Criterion Tuning')
    plt.ylim(temp['value'].min() - 0.01, temp['value'].max() + 0.01)
    plt.legend()
    plt.show()

def plot_min_sample_leaf(all_scores):
    plt.figure(figsize=(12, 5))
    ax1 = sns.lineplot(x=all_scores['min_samples_leaf'], y=all_scores['test_score'], label='Validation')
    ax2 = sns.lineplot(x=all_scores['min_samples_leaf'], y=all_scores['training_score'], label='Training')
    ax1.set(xlabel='Min Sample Leaf', ylabel='ROC-AOC Score')
    ax2.set(xlabel='Min Sample Leaf', ylabel='ROC-AOC Score')
    plt.legend()
    plt.title('Min Sample Leaf')
    plt.show()

def plot_min_impurity(all_scores):
    plt.figure(figsize=(12, 5))
    ax1 = sns.lineplot(x=all_scores['min_impurity_decrease'], y=all_scores['test_score'], label='Validation')
    ax2 = sns.lineplot(x=all_scores['min_impurity_decrease'], y=all_scores['training_score'], label='Training')
    ax1.set(xlabel='Min Impurity Decrease', ylabel='ROC-AOC Score')
    ax2.set(xlabel='Min Impurity Decrease', ylabel='ROC-AOC Score')
    plt.legend()
    plt.title('Min Impurity Decrease')
    plt.show()

def plot_Decision_Tree(df):
    X = df.drop(columns=['target'])
    Y = df['target']
    model = DecisionTreeClassifier(max_depth=5, criterion='entropy', min_samples_leaf=130, min_impurity_decrease=0.002)
    model.fit(X,Y)
    plt.figure(figsize=(60, 40))
    plot_tree(model, filled=True, class_names=True,feature_names=X.columns[:])
    plt.title("Decision Tree Model")
    plt.show()

def feature_importance(df):
    X = df.drop(columns=['target'])
    Y = df['target']
    model = DecisionTreeClassifier(max_depth=5, criterion='entropy', min_samples_leaf=130, min_impurity_decrease=0.002)
    model.fit(X,Y)
    importance = model.feature_importances_
    for i, v in enumerate(importance):
        print('Feature: %0d, Score: %.5f' % (i, v))
    plot_feature_importance(df, model, importance,X)

def plot_feature_importance(df, model, importance,X):
    plt.figure(figsize=(15, 7))
    pd.Series(model.feature_importances_).plot.bar(color='steelblue')
    plt.bar(range(len(model.feature_importances_)), model.feature_importances_)
    plt.xticks([0,1,2,3,4,5],X.columns[:],rotation=30)
    plt.tick_params(axis='both', which='minor', labelsize=4)
    plt.ylabel('Feature_importance', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.title('DT Feature Importance')
    plt.show()


from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from urllib.parse import quote_plus

from django.urls import reverse, reverse_lazy

from django.contrib.auth.decorators import login_required

from django.contrib import messages

# local
from .forms import ArticleForm
from .models import Article, ArticleMedia

# Create your views here.

@login_required
def create(request):
    form = ArticleForm(request.POST or None, request.FILES or None)
    files = request.FILES.getlist('images')
    if form.is_valid():
        # import pdb; pdb.set_trace()
        # instance = form.save(commit=False)
        title = form.cleaned_data.get("title")
        content = form.cleaned_data.get("content")
        publish = form.cleaned_data.get("publish")

        image = files[0]

        instance = Article.objects.create(user=request.user, title=title, image = image, content=content, publish=publish)
        instance.save()

        for f in files:
            instance_fichier = ArticleMedia.objects.create(photos=f, article=instance)
            instance_fichier.save()
        messages.success(request, "L'article a bien été créé")

        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        "form": form,
    }

    return render(request, "evenements/create.html", context)

def articles(request):
    instances = Article.objects.all()

    context = {
        "instances": instances,
    }

    return render(request, "evenements/articles.html", context)

def detail(request, id=None, slug=None):
    instance = get_object_or_404(Article, id=id, slug=slug)

    share_string = quote_plus(instance.content)
    photos = ArticleMedia.objects.filter(article_id=instance.id)

    context = {
        "instance": instance,
        "photos": photos,
        "share_string": share_string,
    }

    return render(request, "evenements/detail.html", context)

@login_required
def update(request, id=None, slug=None):
    instance = get_object_or_404(Article, id=id, slug=slug)
    if instance.user != request.user:
        response = HttpResponse("Vous ne pouvez pas modifier cette publication car vous n'en êtes pas le propriétaire.")
        response.status_code = 403
        return response
    form = EvenementForm(request.POST or None, request.FILES or None, instance=instance)
    files = request.FILES.getlist("image")
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        for f in files:
            instance_fichier = FichierModel(photos=f, evenement=instance)
            instance_fichier.save()
        messages.success(request, "L'évenement a bien été modifié !")
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        # "ville": instance.ville,
        "instance": instance,
        "form": form,
    }

    return render(request, "evenements/create.html", context)

@login_required
def delete(request, id, slug):
    try:
        instance = Article.objects.get(id=id, slug=slug)
    except:
        raise Http404

    if instance.user != request.user:
        response = HttpResponse("Vous ne pouvez pas supprimer l'évenement car vous n'en êtes pas le propriétaire.")
        response.status_code = 403
        return response

    if request.method == "POST":
        instance.delete()
        messages.success(request, "This has been deleted.")
        return HttpResponseRedirect(reverse_lazy("home"))

    context = {
        "instance": instance,
    }

    return render(request, "evenements/confirme_delete.html", context)


import unittest
from Built_in_library import Settings
from External_library.selenium_driver import SeleniumDriver
from External_library.decorator import log_decorator

class Test_Log(unittest.TestCase):

    def setUp(self):
        self.st = Settings()
        self.driver = SeleniumDriver(type=None)
        self.driver.Wait()
        self.base_url = "http://baidu.com"

    @log_decorator(Settings().log)
    def test_log(self):
        # 调用函数
        st = self.st
        # 打开网页
        driver = self.driver
        driver.open(self.base_url)

    def tearDown(self):
        self.driver.quit()


from odoo import api, fields, models, tools, _
from . import pe_exchange_rate
import datetime
import pytz

_URL_SBS_DEFAULT = "https://www.sbs.gob.pe/app/pp/SISTIP_PORTAL/Paginas/Publicacion/TipoCambioPromedio.aspx"
_URL_SUNAT_DEFAULT = "https://www.sunat.gob.pe/a/txt/tipoCambio.txt"

TYPES = [('purchase', _('Purchase')), ('sale', _('Sale'))]
FROM_TYPES = [('sbs', _('SBS')), ('sunat', _('SUNAT'))]

import logging

_logger = logging.getLogger(__name__)

class Currency(models.Model):
    _inherit = "res.currency"
    _description = "Currency"

    from_type = fields.Selection(FROM_TYPES, string='Origin', default='sunat')

    type = fields.Selection(TYPES, string='Type', default='sale')

    def get_url_service(self, from_url):
        _identity = 'exchange.{from_url}.url'.format(from_url=from_url)
        get_param = self.env['ir.config_parameter'].sudo().get_param
        url = get_param(_identity, _URL_SBS_DEFAULT)
        return url

    def action_exchange_rate_sale(self, company):
        rec = self
        if rec.type == "sale":
            success, date_exchange, exchange_rate = pe_exchange_rate.exchange_rate_sale(
                rec.get_url_service(rec.from_type), rec.from_type)
            _logger.info("success")
            _logger.info(success)
            _logger.info("date_exchange")
            _logger.info(exchange_rate)
            _logger.info("exchange_rate")
            _logger.info(success)
            local_pytz = pytz.timezone(company.partner_id.tz)
            time_created_day = datetime.datetime.now(local_pytz)
            if success:
                if date_exchange.date() == time_created_day.date():
                    currency_rates = rec._pg_get_rates(company, date_exchange)
                    rate_id = currency_rates.get(rec.id, False)
                    if rate_id:
                        rate_currency = self.env["res.currency.rate"].browse(int(rate_id))
                        if rate_currency.name == date_exchange.date():
                            rate_currency.write({
                                "rate_exchange": exchange_rate
                            })
                        else:
                            self.env["res.currency.rate"].create({
                                'currency_id': rec.id,
                                'name': date_exchange.date(),
                                'rate_exchange': exchange_rate,
                                'company_id': company.id
                            })
                    else:
                        self.env["res.currency.rate"].create({
                            'currency_id': rec.id,
                            'name': date_exchange.date(),
                            'rate_exchange': exchange_rate,
                            'company_id': company.id
                        })

    def action_exchange_rate_purchase(self, company):
        for rec in self.search([('active', '=', True), ('name', '=', 'USD')]):
            if rec.type == "purchase" and rec.symbol.upper() == "$":
                success, date_exchange, exchange_rate = pe_exchange_rate.exchange_rate_purchase(
                    rec.get_url_service(rec.from_type), rec.from_type)
                local_pytz = pytz.timezone(company.partner_id.tz)
                time_created_day = datetime.datetime.now(local_pytz)
                if success:
                    if date_exchange.date() == time_created_day.date():
                        currency_rates = rec._pg_get_rates(company, date_exchange)
                        rate_id = currency_rates.get(rec.id, False)
                        if rate_id:
                            rate_currency = self.env["res.currency.rate"].browse(int(rate_id))
                            if rate_currency.name == date_exchange.date():
                                rate_currency.write({
                                    "rate_exchange": exchange_rate
                                })
                            else:
                                self.env["res.currency.rate"].create({
                                    'currency_id': rec.id,
                                    'name': date_exchange.date(),
                                    'rate_exchange': exchange_rate
                                })
                        else:
                            self.env["res.currency.rate"].create({
                                'currency_id': rec.id,
                                'name': date_exchange.date(),
                                'rate_exchange': exchange_rate
                            })

    @api.model
    def get_pe_exchange_rate(self):
        self = self.sudo()
        country_pe = self.env.ref('base.pe')
        _logger.info("get_pe_exchange_rate")
        _logger.info(country_pe.id)
        companies = self.env['res.company'].search([('country_id', '=', country_pe.id)])
        _logger.info("companies")
        _logger.info(companies)
        currency_usd = self.search([('active', '=', True), ('name', '=', 'USD')], limit=1)
        for company in companies:
            is_updated = currency_usd.is_updated(company)
            _logger.info("is_updated")
            _logger.info(is_updated)
            if not is_updated:
                currency_usd.action_exchange_rate_sale(company)
                currency_usd.action_exchange_rate_purchase(company)
        return True

    def get_exchange_rate(self):
        for rec in self:
            rec.get_pe_exchange_rate()

    def is_updated(self, company):
        local_pytz = pytz.timezone(company.partner_id.tz)
        time_created_day = datetime.datetime.now(local_pytz)
        _logger.info("time_created_day")
        _logger.info(time_created_day.date())
        currency_rates = self._pg_get_rates(company, time_created_day.date())
        rate_id = currency_rates.get(self.id, False)
        if rate_id:
            rate_currency = self.env["res.currency.rate"].browse(int(rate_id))
            _logger.info("rate_currency")
            _logger.info(rate_currency)
            _logger.info("rate_currency.name")
            _logger.info(rate_currency.name)
            if rate_currency.name == time_created_day.date():
                return True
        return False

    def _pg_get_rates(self, company, date):
        if not self.ids:
            return {}
        self.env['res.currency.rate'].flush(['rate', 'currency_id', 'company_id', 'name'])
        query = """SELECT c.id,
                          COALESCE((SELECT r.id FROM res_currency_rate r
                                  WHERE r.currency_id = c.id AND r.name <= %s
                                    AND (r.company_id IS NULL OR r.company_id = %s)
                               ORDER BY r.company_id, r.name DESC
                                  LIMIT 1), 0) AS rate
                   FROM res_currency c
                   WHERE c.id IN %s"""
        self._cr.execute(query, (date, company.id, tuple(self.ids)))
        currency_rates = dict(self._cr.fetchall())
        return currency_rates

class CurrencyRate(models.Model):
    _inherit = "res.currency.rate"
    _description = "Currency Rate"

    type = fields.Selection(related="currency_id.type", store=True)


import pygame
from random import randint
from settings import tilesize, display

walls = [] # List to hold the walls
tiles = []

class Tilemap(object):
    def __init__(self):
        self.map = [
                    [10,2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,11],
                    [4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5],
                    [4, 0, 0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
                    [4, 0, 0, 0, 6, 5,10,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
                    [4, 0, 0, 0,12, 2,13, 1, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 5],
                    [4, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 6, 5, 4, 0, 0, 0, 5],
                    [4, 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 5, 3, 4, 0, 0, 0, 5],
                    [4, 0, 0, 0, 5, 3, 3, 4, 0, 0, 0, 0, 0,12, 2,13, 0, 0, 0, 5],
                    [4, 0, 0, 0,12, 2, 2,13, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 5],
                    [4, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
                    [4, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5],
                    [8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9]
                ]
        self.mapHeight = len(self.map)
        self.mapWidth = len(self.map[0])

    def getRandomFloorTile(self):
        row = randint(0, self.mapHeight-1)
        col = randint(0, self.mapWidth-1)
        if self.map[row][col] == 0:
            return col*tilesize, row*tilesize
        else:
            return 0, 0

class Wall(object):
    def __init__(self, x, y, index):
        tiles.append(self)
        self.x = x
        self.y = y
        self.width = tilesize
        self.height = tilesize
        self.rect = pygame.Rect(self.x, self.y, tilesize, tilesize)
        self.image = pygame.Surface((self.width, self.height), pygame.SRCALPHA, 32)
        self.index = index
        if self.index != 0 and self.index != 1 and self.index != 6:
            walls.append(self)

    def draw(self, sheet):
        if self.index == 0: # Floor tile
            self.chooseSprite(sheet, 2, 3)

        if self.index == 1: # Wall Front
            self.chooseSprite(sheet, 1, 1)

        if self.index == 2: # Wall Block Top
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 0, 0)

        if self.index == 3: # Wall Block
            self.chooseSprite(sheet, 4, 6)

        if self.index == 4: # Wall Block Left
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 16, 2)

        if self.index == 5: # Wall Block Right
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 18, 2)

        if self.index == 6: # Wall Top
            self.chooseSprite(sheet, 2, 3)
            self.chooseSprite(sheet, 0, 0)

        if self.index == 7: # Wall Block Front
            self.chooseSprite(sheet, 1, 1)

        if self.index == 8: # Wall Block LeftFront
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 16, 3)

        if self.index == 9: # Wall Block RightFront
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 18, 3)

        if self.index == 10: # Wall TopLeft Corner
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 16, 0)

        if self.index == 11: # Wall TopRight Corner
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 18, 0)

        if self.index == 12: # Wall BottomLeft L Corner
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 19, 2)

        if self.index == 13: # Wall BottomRight L Corner
            self.chooseSprite(sheet, 4, 6)
            self.chooseSprite(sheet, 20, 2)

        display.blit(self.image, (self.x, self.y))

    def chooseSprite(self, sheet, xpos, ypos):
        self.image.blit(sheet, (0,0), (xpos*tilesize,ypos*tilesize, self.width, self.height))

#Create the walls based on tilemap
for row in range(Tilemap().mapHeight):
    for col in range(Tilemap().mapWidth):
        for index in range(max(Tilemap().map[row])+1):
            if Tilemap().map[row][col] == index:
                Wall(col*tilesize, row*tilesize, index)


# 규칙 찾아내서 풀기 (통과)
N = int(input())
if N == 1:
    print(N)
else:
    card_list = list(range(0, N+1, 2))
    for i in range(1, 20):
        if N <= 2**i:
            print(card_list[N - 2**(i-1)])
            break

# 큐로 풀기 (시간초과)
N = int(input())
card_list = list(range(1, N+1))

while len(card_list) > 1:
    card_list.pop(0)
    card_list.append(card_list.pop(0))
print(card_list[0])

# 덱으로 풀기 (통과)
from collections import deque

n = int(input())
queue = deque(range(1, n + 1))

while len(queue) > 1:
    queue.popleft()
    queue.append(queue.popleft())

print(queue[0])

# 신기한 풀이 1번이랑 비슷한데 더 스마트함
n = int(input())

a = 1
while n > a * 2:
    a *= 2

print((n - a) * 2 or n)


"""I2C rotary encoder NeoPixel color picker and brightness setting example."""
import board
from adafruit_seesaw import seesaw, rotaryio, digitalio

addresses = [0x37, 0x36, 0x3A]

class Knob:
    def __init__(
        self,
        num,
        handler,
    ):
        self.seesaw = seesaw.Seesaw(board.I2C(), addresses[num-1])
        self.encoder = rotaryio.IncrementalEncoder(self.seesaw)
        self.seesaw.pin_mode(24, self.seesaw.INPUT_PULLUP)
        self.switch = digitalio.DigitalIO(self.seesaw, 24)

        self.last_position = -1
        self.num = num

        self.handler = handler

    def update(self):
        # negate the position to make clockwise rotation positive
        position = -self.encoder.position
        if position != self.last_position:
            self.handler(position - self.last_position)
            self.last_position = position

class Knobs:
    def __init__(
        self,
        handlers
    ):
        self.knobs = [Knob(1, handlers[0]), Knob(2, handlers[1]), Knob(3, handlers[2])]

    def update(self):
        for k in self.knobs:
            k.update()


# 1702. Maximum Binary String After Change
class Solution:
    def maximumBinaryString(self, binary: str) -> str:
        '''
        1/2 Bubble sort.
        The op2 will decrease the local number, but it's worth doing when it
        contributes to '00' which becomes '10' and increases the total number.

        This process is like bubble sort, a zero can bubble up to the left,
        once we have two zeros, we move the second zero to the left,
        virtually, then replace them by '10'. E.g., '1010' -> '1001' -> '1101

        Time: O(n) where n is len(binary)
        Space: O(n)
        '''
        arr = deque()
        n = len(binary)
        zeros = 0
        for a in binary:
            if a == '0':
                zeros += 1
                if zeros == 2:
                    arr.appendleft('1')
                    zeros -= 1
                else:
                    arr.append('0')
            else:
                arr.append('1')
        return ''.join(arr)
        '''
        2/2 A more concise process, based on bubble sort

        We don't have to do the process in 1/2 step by step, becaue we know in
        the final number, there's up to 1 zero, and all other zeros will be
        ones. The key is to find the lowest possible position of the single
        zero.
        We can't move the leftmost zero further left, but we can virtually
        push it right by gathering '00' and replacing with '10' like in 1/2.
        Overall, if the leftmost zero is at index 'start', all the 'k' ones in
        nums[start:] stay on the right, all zeros in nums[start:] will be
        moved left to meet the zero at 'start', and then we replace all zeros
        by '111..110', effectively push the only 0 to the right as far as
        possible.
        At the end, we have 'k' ones on the right, 'n-k-1' ones on the left,
        and one zero in the middle. If there is no zero in the input, just
        return the original input.
        '''
        if '0' not in binary: return binary
        n = len(binary)
        start = binary.find('0')
        k = binary.count('1', start)
        return '1' * (n - k - 1) + '0' + '1' * k

medium/1702. Maximum Binary String After Change.py


import cv2
import matplotlib
import matplotlib.pylab as plt
import numpy as np

def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

img = cv2.imread('06_pie.png')

sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
# cv2.CV_64F是为了在np数值上保留负数值，但对于RGB图仍需作如下转换
sobelx = cv2.convertScaleAbs(sobelx)
# cv_show('sobel', sobelx)

sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
sobely = cv2.convertScaleAbs(sobely)

res = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0)
cv_show('edge', res)


from configurator.modules.Utilities.py.util import *
from configurator.modules.Utilities.py.file_manager import FileManager
from ..utils.utils import DjangoRegex as DR, StringModify
import os, shutil as sh
FM = FileManager()
from .components.settings import *
from .components.views import *
from .components.tables import *

class DjangoConfig():
    def __init__(self):
        self.conf = {}
        self.conf['settings'] = self.setUpConf(loc = os.path.join(self.server_loc,'settings.py'),subcategory=['middleware','apps','database','oauth'])
        self.conf['tables'] = {}
        for app in self.app_locs:
            loc = os.path.join(self.app_locs[app],'models.py')
            if not os.path.isfile(loc):
                raise ValueError(f'FATAL ERROR: models.py in {app} folder does not exist!')
            self.conf['tables'][app] = self.setUpConf(loc = loc,
            subcategory=[table for table in self.db_settings['tables'][app]])

        with open(file = self.conf['settings']['loc'], mode = 'r', encoding = 'utf-8-sig') as s:
            txt = str(s.read())
            self.conf['settings']['text'] = txt
            s.close()

    def setUpConf(self, loc: os.PathLike, subcategory: list):
        conf_dict = \
        {
            'loc':loc,
            'text':None,
        }
        for subc in subcategory:
            conf_dict[subc] = {'removed':[],'added':[]}
        return conf_dict

    def updateConf(self, curr_list: list, app_list: list, category: str, type: str):
        app_uniques = buildDictBoolbyArr(arr = app_list)
        cur_uniques = buildDictBoolbyArr(arr = curr_list)
        self.conf[category][type]['added'] = getDictDiffArr(dict_1 = cur_uniques, dict_2 = app_uniques)
        self.conf[category][type]['removed'] = getDictDiffArr(dict_2 = cur_uniques, dict_1 = app_uniques)

class DjangoWriter():
    def __init__(self, server_name: str, config_data: dict):
        print('Initialized DjangoWriter')
        self.server_name = server_name
        self.engines=\
            {
                'postgres':'django.db.backends.postgresql_psycopg2'
            }

        self.server_loc = config_data['Server_Locations'][self.server_name]
        self.app_locs = config_data['App_Locations'][self.server_name]
        self.server_settings = config_data['Server_Settings'][self.server_name]
        self.db_settings = config_data['Database_Settings'][self.server_name]
        self.api_settings = config_data['API_Settings'][self.server_name]
        self.be_root = config_data['Back_End_Path']
        self.it_root = config_data['Root_Path']

    def processSettings(self):
        settings_py = os.path.join(self.server_loc,'settings.py')
        txt = FM.extractText(file = settings_py, open_file = True)
        dj_settings = DjangoSettings(server_settings = self.server_settings, db_settings = self.db_settings,
                                    app_locations = self.app_locs, loc = settings_py, txt = txt)
        dj_settings.setInstalledApps()
        dj_settings.setDatabase()
        dj_settings.setMiddleWare()
        dj_settings.setAllowHosts()
        for st in self.server_settings['storage']:
            dj_settings.setStorage(type = st)
        dj_settings.setAuthentication()
        dj_settings.writeSettings()

    def processViews(self):
        for app in self.api_settings:
            app_oauth = self.api_settings[app]['oauth']
            app_auth_type = self.api_settings[app]['auth_type']
            app_auth_type = app_auth_type.split('|') if '|' in app_auth_type else app_auth_type
            app_csrf = self.api_settings[app]['csrf']
            views_dict = self.api_settings[app]['apis']
            ser_py = os.path.join(self.app_locs[app],'serializer.py')
            view_py = os.path.join(self.app_locs[app],'views.py')
            urls_py = os.path.join(self.app_locs[app],'urls.py')
            dj_views = DjangoViews(app_oauth = app_oauth, app_auth_type=app_auth_type,app_csrf = app_csrf, view_loc = view_py, ser_loc = ser_py, url_loc = urls_py)
            for api in views_dict:
                dj_views.prepAPI(api_dict = views_dict[api], api_name = api)
            dj_views.SERIALIZER.writeSerializer()
            dj_views.URLS.writeURLs()
            dj_views.writeViews()

    def processModels(self):
        for app in self.app_locs:
            models_py = os.path.join(self.app_locs[app],'models.py')
            dj_table = DjangoTables(server_oauth = self.server_settings["oauth"], models_py = models_py)
            for table in self.db_settings['tables'][app]:
                table_dict = self.db_settings['tables'][app][table]
                dj_table.prepTable(tbl_name = table, table_dict= table_dict)
            dj_table.writeTables()

    def processContainer(self):
        port = self.server_settings["port"] #For Docker-Compose/NGINX to Use
        containers = self.server_settings["containers"] #Not required for django but is for NGINX deployment

    def processAPIs(self):
        curr_util_dir = './configurator/modules'
        new_util_dir = os.path.join(self.be_root,'modules')
        FM.copyDir(src = curr_util_dir, dst = new_util_dir)

    def process(self):
        for i in [mro for mro in str(DjangoWriter.__mro__).split(',')]:
            print(i)
        self.processSettings()
        self.processModels()
        self.processAPIs()
        self.processViews()


import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import KFold
import scipy.sparse
import scipy

class DataProcessing:
    def __init__(self, data_path):
        self.data_path = data_path
        self.main_df = None
        self.encoder = OneHotEncoder(categories='auto')
        self.X = None
        self.y = None

    def get_batch(self, batch_size, X, y):
        for i in range(0, y.shape[0], batch_size):
            # X = self.X[i:i + batch_size, :]
            X_b = X[i:i + batch_size, :]
            y_b = y[i:i + batch_size, :]

            yield X_b, y_b

    def preprocess_data(self):
        self.main_df = pd.read_csv(self.data_path, names=["User_ID", "Rating", "Date"])
        # self.__get_movie_ratings()

        movies_df = self.__get_movie_ratings()

        self.main_df = self.main_df[pd.notnull(self.main_df['Rating'])]
        self.main_df = self.main_df.reset_index(drop=True)
        self.main_df["Movie_ID"] = movies_df

        print('Original Shape: {}'.format(self.main_df.shape))

        self.__encode_data()

    def save_data(self, fname):
        self.main_df.to_csv(fname)

    def load_data(self, fname):
        self.main_df = pd.read_csv(fname, index_col=0).drop_duplicates()
        self.__encode_data()
        self.main_df = None  # cleaning the mess
        # self.main_df_arr = np.array_split(self.main_df, self.num_batches)

    def get_data_shape(self):
        return self.X.shape

    def get_fold(self, n_folds=5):
        kf = KFold(n_splits=n_folds, shuffle=True)
        for train_index, test_index in kf.split(self.X):
            X_train, X_test = self.X.tocsr()[train_index], self.X.tocsr()[test_index]
            y_train, y_test = self.y[train_index], self.y[test_index]

            yield (X_train, X_test), (y_train, y_test)

    def __encode_data(self):
        usr_mat = self.encoder.fit_transform(np.asarray(self.main_df["User_ID"]).reshape(-1, 1))
        mov_mat = self.encoder.fit_transform(np.asarray(self.main_df["Movie_ID"]).reshape(-1, 1))
        date_mat = self.encoder.fit_transform(np.asarray(self.main_df["Date"]).reshape(-1, 1))
        self.X = scipy.sparse.hstack([usr_mat, mov_mat, date_mat])
        self.y = np.asarray(self.main_df['Rating']).reshape(-1, 1)  # does not encode actually

    def __get_movie_ratings(self):
        temp_movies_col = np.array([])
        end_df = pd.DataFrame(np.array([["0:", None, None]]),
                              columns=['User_ID', "Rating", "Date"])  # auxiliary appendix
        dframe_aux = self.main_df.append(end_df, ignore_index=True)
        null_rat = [i + 1 for i, frame in enumerate(pd.isnull(dframe_aux.Rating)) if frame]

        print(self.main_df.shape)
        print(len(null_rat))

        for i, curr_val in enumerate(null_rat):
            try:
                temp_movies_col = np.append(temp_movies_col, np.full((1, null_rat[i + 1] - curr_val - 1), i + 1))
            except:
                break

        movies_col = pd.DataFrame(temp_movies_col, columns=["Movie_ID"])
        return movies_col


import base64
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlencode
import frappe
import requests
from frappe import _
from frappe.utils import cint, cstr, get_datetime
from pytz import timezone
import random
import webbrowser
import json

class CreateTiktokClient:

	def start_connecting( self, app_key , app_secret, is_sandbox ):
		return self.createAuthRequest(app_key,app_secret,is_sandbox)

	def createAuthRequest( self, app_key , app_secret, is_sandbox ):
		url='empty'
		if( is_sandbox == True ):
			url = 'https://auth-sandbox.tiktok-shops.com'
		else:
			url = 'https://auth.tiktok-shops.com'
		state = random.randint(0,10000)
		params = {'app_key' : app_key,'state' : state }
		qstr = urlencode(params)
		url = url+'/?'+qstr
		return url

	def refreshToken( self ):
			app_details = frappe.get_doc('Tiktok with ERPnext')
			url='empty'
			if( app_details.is_sandbox == True ):
				url = 'https://auth-sandbox.tiktok-shops.com'
			else:
				url = 'https://auth.tiktok-shops.com'
			state = random.randint(0,10000)
			url = url+'/api/v2/token/refresh'
			url = url+"?app_key="+str(app_details.app_key)+"&app_secret="+app_details.get_password('app_secret')+"&refresh_token="+app_details.refresh_token+"&grant_type=refresh_token"
			headers = {
				'Content-Type': 'application/json'
				}
			response = requests.request("GET", url, headers=headers )
			data = response.json()
			if( data['message']=='success' ):
				frappe.db.set_value('Tiktok with ERPnext','','access_token',data['data']['access_token'])
				frappe.db.set_value('Tiktok with ERPnext','','refresh_token',data['data']['refresh_token'])
				frappe.db.commit()

				url = frappe.utils.get_url()+app_details.get_url()
			else :
				print(f"\n\n not working like this ")

	def get_token_from_code():
		frappe.msgprint(frappe.request.args)

@frappe.whitelist( )
def redirect_to_auth(  ):
	app_details = frappe.get_doc('Tiktok with ERPnext')
	if( app_details.app_key!='' and app_details.app_secret != '' and app_details.enable_tiktok ):
			connect = CreateTiktokClient()
			url = connect.start_connecting ( app_details.app_key,app_details.app_secret,app_details.is_sandbox )
			if( url ):
				print (f"Redirecting to auth from function {url}")
				response_ = {'url':url}
				return response_
				exit()

	return


#####################
#importing libraries#
#####################

from astropy.io import fits
import numpy as np
import os
import shutil
import matplotlib.pyplot as plt
import matplotlib.gridspec as gsp
import statistics
import copy
import scipy.stats as sstat

#figure settings
plt.rcParams["axes.titlesize"]="x-large"
plt.rcParams["axes.labelsize"]="medium"
plt.rcParams["legend.fontsize"]="small"
plt.rcParams["legend.loc"]="upper left"
plt.rcParams["legend.framealpha"]=1

######################
#functions definition#
######################

def checkexistence(maindir,subdir=""):
    home=os.getcwd()
    if not os.path.isdir(os.path.join(home,maindir)):
        os.mkdir(maindir)
        print("directory ",maindir," succesfully created")
    if subdir!="":
        if not os.path.isdir(os.path.join(home,maindir,subdir)):
            os.chdir(maindir)
            os.mkdir(subdir)
            os.chdir("..")
            print("directory ",subdir," succesfully created")

def clean(sample):
    #removing nan and inf values
    i=0
    while i<36:
        arr=sample[i]
        sample[i]=arr[np.isfinite(arr)]
        if i>6 and i<25:
            sample[i+1]=sample[i+1][np.isfinite(arr)]
            i+=2
        elif i>24 and i<31:
            sample[i+1]=sample[i+1][np.isfinite(arr)]
            sample[i+2]=sample[i+2][np.isfinite(arr)]
            i+=3
        else:
            i+=1

    #sigma-clipping
    N=4
    i=0
    while i<36:
        for j in range(7):
            arr=sample[i]
            if i>6 and i<25:
                sample[i+1]=sample[i+1][np.logical_and(arr>arr.mean()-N*arr.std(),arr<arr.mean()+N*arr.std())]
                sample[i]=arr[np.logical_and(arr>arr.mean()-N*arr.std(),arr<arr.mean()+N*arr.std())]
            elif i>24 and i<31:
                sample[i+1]=sample[i+1][np.logical_and(arr>arr.mean()-N*arr.std(),arr<arr.mean()+N*arr.std())]
                sample[i+2]=sample[i+2][np.logical_and(arr>arr.mean()-N*arr.std(),arr<arr.mean()+N*arr.std())]
                sample[i]=arr[np.logical_and(arr>arr.mean()-N*arr.std(),arr<arr.mean()+N*arr.std())]
            else:
                sample[i]=arr[np.logical_and(arr>arr.mean()-N*arr.std(),arr<arr.mean()+N*arr.std())]
        if i>6 and i<25:
            i+=2
        elif i>24 and i<31:
            i+=3
        else:
            i+=1
    return sample

def adjust_on_y(x,y):
    #removing nan and inf values
    x=x[np.isfinite(y)]
    y=y[np.isfinite(y)]

    #sigma-clipping
    N=4
    for j in range(7):
        x=x[np.logical_and(y>y.mean()-N*y.std(),y<y.mean()+N*y.std())]
        y=y[np.logical_and(y>y.mean()-N*y.std(),y<y.mean()+N*y.std())]

    return x,y

def adjust_on_x(x,y):
    #removing nan and inf values
    y=y[np.isfinite(x)]
    x=x[np.isfinite(x)]

    #sigma-clipping
    N=4
    for j in range(7):
        y=y[np.logical_and(x>x.mean()-N*x.std(),x<x.mean()+N*x.std())]
        x=x[np.logical_and(x>x.mean()-N*x.std(),x<x.mean()+N*x.std())]

    return x,y

def gauss(bins,media,sigma):
    x=np.zeros(len(bins)-1)
    for i in range(len(x)):
        x[i]=(bins[i]+bins[i+1])/2
    return x, 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(x-media)**2/(2*sigma**2))

#1d plots function
def genhist(arr,name,sample,nbins=50):
    if name=="z":       #estimation of mean and standard deviation without python standard modules
        mean=0
        for i in arr:
            mean+=i
        mean=mean/len(arr)
        std=0
        for i in arr:
            std+=(i-mean)**2
        std=np.sqrt(std/(len(arr)-1))
    else:               #assignment of mean and standard deviation with python standard modules
        mean=arr.mean()
        std=arr.std()
    median=statistics.median(arr)
    meanerr=std
    medianerr=1.4826*statistics.median(np.absolute(arr-median))

    #creating subplots
    plt.figure(1,figsize=(10,5))
    fig=gsp.GridSpec(1,3,wspace=0.5,hspace=0.25)
    #mean-histogram generation
    axhist1=plt.subplot(fig[0])
    counts,bins,ign=axhist1.hist(arr,nbins,density=True)
    p1=plt.axvline(mean,c="k",ls="--")
    p2=plt.axvspan(mean-meanerr,mean+meanerr,color="g",alpha=0.25)
    plt.xlabel(name)
    axhist1.set_title("mean_plot")
    #plotting gaussian
    x,mod=gauss(bins,mean,std)
    p3,=axhist1.plot(x,mod,c="g",ls="--",lw=2)
    axhist1.legend([p1,p2,p3],["mean","error","gaussian"])
    #median-histogram generation
    axhist2=plt.subplot(fig[2])
    axhist2.hist(arr,nbins,density=True)
    p1=plt.axvline(median,c="k",ls="--")
    p2=plt.axvspan(median-medianerr,median+medianerr,color="r",alpha=0.25)
    plt.xlabel(name)
    axhist2.set_title("median_plot")
    axhist2.legend([p1,p2],["median","error"])

    #file output
    res = np.zeros(1, dtype=[('var1', 'U29'), ('var2', float), ('var3', float), ('var4', float), ('var5', float)])
    res["var1"]=name
    res["var2"]=mean
    res["var3"]=std
    res["var4"]=median
    res["var5"]=medianerr
    filename="output/"+sample+".dat"
    f=open(filename,"a")
    f.write(os.linesep)
    np.savetxt(f,res,delimiter=" ",fmt="%s   %f   %f   %f   %f",newline=os.linesep)
    f.close()
    return x,counts,mod,fig

#residuals function
def genresid(axid,arr,counts,mod,name,sample):
    ax=plt.subplot(axid)
    resid=(counts-mod)
    ax.scatter(arr,resid)
    ax.axhline(resid.mean(),c="0.3",ls="--")
    ax.axhspan(resid.mean()-resid.std(),resid.mean()+resid.std(),color="0.3",alpha=0.25)
    ax.set_title("residuals_plot")
    title="plot/"+sample+"/"+name+".png"
    plt.savefig(title,dpi=150)
    plt.clf()

#2d plots function
def gencorr(arr1,arr2,sample,name):
    arr1,arr2=adjust_on_y(arr1,arr2)
    arr1,arr2=adjust_on_x(arr1,arr2)
    plt.figure(1,figsize=(10,5))
    fig=gsp.GridSpec(1,2,wspace=0.25,hspace=1)
    deg=[0,1]
    fits=["constant","linear"]
    for c in range(len(deg)):
        #fit
        res=np.polyfit(arr1,arr2,deg[c])
        y_bf=np.polyval(res,arr1)
        #creating subplots
        ax=plt.subplot(fig[c])
        p1=ax.scatter(arr1,arr2,edgecolor="k")
        p2,=ax.plot(arr1,y_bf,c="orange",ls="--",linewidth=2.5)
        plt.xlabel("redshift")
        plt.ylabel(name)
        ax.set_title(fits[c]+" correlation")
        ax.legend([p1,p2],["data",fits[c]+" fit"])
    title="plot/"+sample+"/z_"+name+".png"
    #searching for correlations
    r=sstat.pearsonr(arr1,arr2)
    if np.absolute(r[0])>=0.5:
        #creation of directory for plots from redshift bins
        s="z_correlation_w_"
        os.chdir("plot")
        checkexistence(sample,s)
        os.chdir("..")
        #appending quantity name on file
        filename="output/"+sample+".dat"
        f=open(filename,"a")
        f.write(os.linesep+"#"+s+name)
        f.close()
        #drawing bins on figure1
        for k in range(5):
            n="bin_"+str(k+1)
            if k!=0:
                ax.axvline(0.02*k,c="k",ls="--")
            plt.text(0.1+0.2*k,0.01,n,ha="center",transform=ax.transAxes)
        plt.savefig(title,dpi=150)
        plt.clf()
        #plotting bins on figure2
        for k in range(5):
            n="bin_"+str(k+1)
            ybins=arr2[np.logical_and(arr1<0.02*(k+1),arr1>0.02*k)]
            a,counts,mod,fig=genhist(ybins,n,sample,50)
            genresid(fig[1],a,counts,mod,s+"/"+name+"-"+n,sample)
    else:
        plt.savefig(title,dpi=150)
        plt.clf()

#color plots function
def gencol(arr1,arr2,carr,n1,n2,name):
    os.chdir("plot")
    checkexistence("diagrams",name)
    os.chdir("..")
    #cleaning data
    savearr2=copy.deepcopy(arr2)
    arr1,arr2=adjust_on_y(arr1,arr2)

    savearr1=copy.deepcopy(arr1)
    carr,savearr2=adjust_on_y(carr,savearr2)

    arr1,arr2=adjust_on_x(arr1,arr2)
    savearr1,carr=adjust_on_x(savearr1,carr)
    #producing theorical relation
    sortedindexes=arr1.argsort()
    carr=carr[sortedindexes]
    arr2=arr2[sortedindexes]
    arr1=arr1[sortedindexes]
    y_rel=[]
    rel=""
    if name=="BPT":
        #mask on x
        carr=carr[arr1<0.038]
        arr2=arr2[arr1<0.038]
        arr1=arr1[arr1<0.038]
        y_rel=0.61/(arr1-0.05)+1.3
        #mask on y
        carr=carr[y_rel>-1.5]
        arr2=arr2[y_rel>-1.5]
        arr1=arr1[y_rel>-1.5]
        y_rel=y_rel[y_rel>-1.5]

        a=""
        rel=r'log([OIII]/Hβ) = 0.61/(log([NII]/Hα) - 0.05) + 1.3'
        xlab=r'log([NII]/Hα)'
        ylab=r'log([OIII]/Hβ)'
    elif name=="color-mass":
        y_rel=-0.495+0.25*arr1
        rel=r'(u − r) = −0.495 + 0.25 ∗ log10(M/M⊙)'
        xlab=r'log10(M/M⊙)'
        ylab=r'u − r'
    elif name=="SFR-mass":
        y_rel=-8.64+0.76*arr1
        rel=r'SFR = −8.64 + 0.76 ∗ log10(M/M⊙)'
        xlab=r'log10(M/M⊙)'
        ylab=r'SFR'

    #generating plot
    plt.figure(1,figsize=(10,5))
    fig=gsp.GridSpec(1,1,wspace=0.25,hspace=0.25)
    ax=plt.subplot(fig[0])
    scatter=ax.scatter(arr1,arr2,c=carr,cmap="copper")
    cb=plt.colorbar(scatter)
    cb.set_label("redshift")
    p2,=ax.plot(arr1,y_rel,c="k",ls="--",linewidth=2.5)
    plt.xlabel(xlab)
    plt.ylabel(ylab)
    ax.set_title(name+"_diagram")
    ax.legend([scatter,p2],["data",rel])
    title="plot/diagrams/"+name+"/diagram.png"
    plt.savefig(title)
    plt.clf()
    #generating histograms
    xinf=arr1[arr2<y_rel]
    xsup=arr1[arr2>y_rel]
    yinf=arr2[arr2<y_rel]
    ysup=arr2[arr2>y_rel]
    l=[xinf,xsup,yinf,ysup]
    n=[n1+"_blw_relation",n1+"_abv_relation",n2+"_blw_relation",n2+"_abv_relation"]
    filename="output/diagrams.dat"
    f=open(filename,"a")
    f.write(os.linesep+"#"+name)
    f.close()
    for i in range(4):
        a,counts,mod,fig=genhist(l[i],n[i],"diagrams",50)
        genresid(fig[1],a,counts,mod,name+"/"+n[i],"diagrams")

#main function for figures
def genplot(x,headers,j,tplot,arr1index=6):
    filename="output/"+j+".dat"
    f=open(filename,"w")
    f.write("#quantity  mean  std  median  err_mediana")
    f.close()
    i=6
    while i<36:
        if tplot=="hist":
            a,counts,mod,fig=genhist(x[i],headers[i],j)
            genresid(fig[1],a,counts,mod,headers[i],j)
        elif tplot=="fit" and i!=arr1index and ((i>14 and i<18)or (i>24 and i<32)):
            gencorr(x[arr1index],x[i],j,headers[i])
        if i>6 and i<25:
            i+=2
        elif i>24 and i<30:
            i+=3
        else:
            i+=1

###########
#main code#
###########

print("WARNING: the following warning messages are caused by the use of deprecated modules; the code runs properly despite them")

#organizing folders

dirname="project_SimonePucci"
checkexistence(dirname)
os.chdir(dirname)
checkexistence("data")
checkexistence("output")

home=os.getcwd()
ls=["parentsample","subsample","subsample_z","diagrams"]
for i in ls:
    checkexistence("plot",i)

if not os.path.isfile(os.path.join(home,"data","data_SDSS_Info.fit")):
    os.chdir("..")
    shutil.move("data_SDSS_Info.fit",os.path.join(home,"data"))
#uncomment the following line if using Linux and use that rather than shutil
    #os.system("mv data_SDSS_Info.fit project_SimonePucci/data")
    print("file 'data_SDSS_Info.fit' succesfully moved to folder 'data'")
    os.chdir(dirname)

#opening file
hdul=fits.open("data/data_SDSS_Info.fit")
data=hdul[1]
cols=data.columns
headers=cols.names

print("column_name\tindex")
c=0
for i in headers:
    print(i," ",c)
    c+=1

values=data.data
hdul.close()

#reading sample
parentdata=[]
for i in headers:
    parentdata.append(values[i])

#reading subsample
myid=16
mask=[values["ID"]==myid]
subdata=[]
for i in headers:
    subdata.append(values[i][mask])

subdataz=copy.deepcopy(subdata)

#cleaning samples
parentdata=clean(parentdata)
subdata=clean(subdata)
#array conversion
parentdata=np.array(parentdata)
subdata=np.array(subdata)
subdataz=np.array(subdataz)

#generating histograms
genplot(parentdata,headers,"parentsample","hist")
genplot(subdata,headers,"subsample","hist")
genplot(subdataz,headers,"subsample_z","fit",6)

#step IV
#getting data
nii=values["nii_6584_flux"][mask]
oii=values["oiii_5007_flux"][mask]
bptx=np.log10(nii/(values["h_alpha_flux"][mask]))
bpty=np.log10(oii/(values["h_beta_flux"][mask]))
mass=values["lgm_tot_p50"][mask]
ur=values["petroMag_u"][mask]-values["petroMag_r"][mask]
sfr=values["sfr_tot_p50"][mask]
#creating output file
filename="output/diagrams.dat"
f=open(filename,"w")
f.write("#quantity  mean  std  median  err_mediana")
f.close()
#generating plots
names=["BPT","color-mass","SFR-mass"]
ns=[["n_alpha_flux","o_beta_flux"],["mass","u_r_Mag"],["mass","sfr"]]
variables=[[bptx,bpty],[mass,ur],[mass,sfr]]
for i in range(3):
    gencol(variables[i][0],variables[i][1],values["z"][mask],ns[i][0],ns[i][1],names[i])


import pandas as pd
import random
import numpy as np
from scipy.stats import poisson, kstwo, geom, binom # just used for PMF/PDF/CDF calculation
from datetime import datetime
from math import exp, log
from typing import List
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from utilities import *

def part_a(st: pd.DataFrame, state: str, col: str) -> List[str]:
	#### PART A ####
	print('PART A for %s data in %s' % (col, state))
	feb_21 = st[
		(st["date"] >= datetime(2021, 2, 1)) & (st["date"] <= datetime(2021, 2, 28))
	]

	# get H0 from february
	h0= sum(feb_21[col]) / feb_21.shape[0]
	# get population standard deviation
	pop_sigma = stddev(st[col])

	# get sample data
	mar_21 = st[
		(st["date"] >= datetime(2021, 3, 1)) & (st["date"] <= datetime(2021, 3, 31))
	]

	# run hypothesis tests assuming D ~ (X1, ... Xn) ~ Poisson(lambda)
	print("""ONE SAMPLE TESTS""")
	for t in (t_test, walds_test, z_test):
		if t.__name__ == "t_test":
			t_stat, p_value, cv = t(data=mar_21[col].values, pop_mean=h0)

		if t.__name__ == "walds_test":
			t_stat, p_value, cv = t(data=mar_21[col].values, null_hypothesis=h0)

		if t.__name__ == "z_test":
			t_stat, p_value, cv = t(data=mar_21[col].values, pop_mean=h0, pop_sigma=pop_sigma)
		should = "SHOULD" if abs(t_stat) > cv else "SHOULD NOT"
		print(f"State: {state} | For {' '.join(t.__name__.split('_'))}:")
		print('Size of data set: %d' % len(mar_21[col]))
		print(f"Null Hypothesis mean: {h0}")
		print('Critical value: %.6f' % cv)
		print(f"T statistic: {t_stat}, p-value {p_value}")
		print(f"This indicates we {should} reject the null hypothesis that\nthe mean #{col} from March is the same as in February.")

	# two sample tests
	print("""TWO SAMPLE TESTS""")
	for ts in (two_sample_t_test, two_sample_walds_test):
		if ts.__name__ == "two_sample_t_test":
			t_stat, p_value, cv = ts(
				data_1=feb_21[col].values, data_2=mar_21[col].values
			)

		if ts.__name__ == "two_sample_walds_test":
			t_stat, p_value, cv = ts(
				data_1=feb_21[col].values, data_2=mar_21[col].values
			)
		should = "SHOULD" if abs(t_stat) > cv else "SHOULD NOT"
		print(f"State: {state} | For {' '.join(ts.__name__.split('_'))}:")
		print('Size of data sets: %d, %d' % (len(feb_21[col]), len(mar_21[col])))
		print('Critical value: %.6f' % cv)
		print(f"T statistic: {t_stat}, p-value {p_value}")
		print(f"This indicates we {should} reject the null hypothesis that\nthe mean #{col} from March is the same as in February.")
	print()

def part_b(dfs):
	print('PART B')
	states = list(dfs.keys())
	start = pd.to_datetime('2021-9-1')
	stop = pd.to_datetime('2022-1-1')
	for col in dfs[states[0]]:
		h0 = ' the null hypothesis that the distribution of daily #\nof %s in %s and %s is equal' % (col, states[0], states[1])
		print('Analyzing %s data' % col)
		s1 = dfs[states[0]][col]
		s2 = dfs[states[1]][col]
		s1 = s1[(s1['date'] >= start) & (s1['date'] < stop)]
		s2 = s2[(s2['date'] >= start) & (s2['date'] < stop)]
		# 1 sample K-S tests
		# poisson
		lamb_mme = s1[col].sum() / s1.shape[0]
		def cdf(x):
			return poisson.cdf(x, lamb_mme)
		ks, p = ks_test1(cdf, s2[col])
		print('1 Sample KS-test with Poisson distribution')
		print('K-S Statistic: %.4f' % ks)
		print('p-val: %.4f' % p)
		pref = 'We reject' if p < 0.05 else 'We fail to reject'
		print(pref + h0)

		# geometric
		p_mme = 1 / (s1[col].sum() / s1.shape[0])
		def cdf(x):
			return geom.cdf(x, p_mme)
		ks, p = ks_test1(cdf, s2[col])
		print('1 Sample KS-test with Geometric distribution')
		print('K-S Statistic: %.4f' % ks)
		print('p-val: %.4f' % p)
		pref = 'We reject' if p < 0.05 else 'We fail to reject'
		print(pref + h0)

		# binomial
		ex = s1[col].sum() / s1.shape[0]
		ex2 = sum(s1[col].to_numpy() ** 2) / s1.shape[0]
		s = ex2 - ex ** 2
		n_mme = ex ** 2 / (ex - s)
		p_mme = (ex - s) / ex
		if (n_mme < 0 or p_mme < 0):
			print('MME for binomial distribution returned negative values')
			# do not proceed with test
			# https://piazza.com/class/kxyzhcwa3ie43m?cid=157
		else:
			def cdf(x):
				return binom.cdf(x, n_mme, p_mme)
			ks, p = ks_test1(cdf, s2[col])
			print('1 Sample KS-test with Binomial distribution')
			print('K-S Statistic: %.4f' % ks)
			print('p-val: %.4f' % p)
			pref = 'We reject' if p < 0.05 else 'We fail to reject'
			print(pref + h0)

		# 2 sample K-S test
		ks, p = ks_test2(s1[col], s2[col])
		print('2 Sample KS-test')
		print('K-S Statistic: %.4f' % ks)
		print('p-val: %.4f' % p)
		pref = 'We reject' if p < 0.05 else 'We fail to reject'
		print(pref + h0)
		#plt.figure()
		#x = s1[col].sort_values()
		#y = np.linspace(0, 1, num=len(s1[col]))
		#plt.plot(x, y)
		#x = s2[col].sort_values()
		#y = np.linspace(0, 1, num=len(s2[col]))
		#plt.plot(x, y)
		#plt.savefig('test-%s.pdf' % col)

		# Permutation test
		p = permutation_test(s1[col], s2[col])
		print('Permutation Test')
		print('p-val: %.6f' % p)
		pref = 'We reject' if p < 0.05 else 'We fail to reject'
		print(pref + h0)
	print()

def part_c(dfs):
	print("PART C")
	dates = set()
	first = True
	start = pd.to_datetime("2020-6-1")
	stop = start + pd.Timedelta(days=7 * 8)
	# remove any dates with missing data
	for state in dfs:
		for col in dfs[state]:
			df = dfs[state][col]
			df = df[(df["date"] >= start) & (df["date"] < stop)]
			dfs[state][col] = df
			if first:
				dates.update(dfs[state][col]["date"])
				first = False
			else:
				dates.intersection_update(dfs[state][col]["date"])
	combined = pd.DataFrame(columns=["date", "count"])
	dates = sorted(list(dates))
	combined["date"] = dates
	combined["count"] = np.zeros(len(dates))
	for state in dfs:
		for col in dfs[state]:
			combined["count"] = combined["count"].values + dfs[state][col][col].values
	stop = start + pd.Timedelta(days=7 * 4)
	first_four = combined[combined["date"] < stop]
	lamb_mme = first_four["count"].sum() / first_four.shape[0]
	logpdfs = [gen_exp_logpdf(1 / lamb_mme)]
	for week in range(4):
		start = stop
		stop += pd.Timedelta(days=7)
		data = combined[(combined["date"] >= start) & (combined["date"] < stop)]
		logpdfs.append(gen_logpdf(logpdfs[-1], data["count"]))
	num = 3000
	stop = 3000
	dx = stop / num
	x = np.linspace(0, stop, num=num)
	maps = []
	for logpdf in logpdfs:
		logs = logpdf(x)
		# adding a constant is equivalent to linear scaling of pdf
		# scale it up for numerical stability
		logs -= max(logs)
		y = np.exp(logs)
		total = sum(y) * dx
		y /= total
		maps.append(max(range(len(y)), key=lambda i: y[i]))
		plt.plot(x, y)
	plt.ylim((0, plt.ylim()[1]))
	legend = ["Original Prior"]
	for i in range(5, 9):
		legend.append("Prior after %dth week" % i)
		print("MAP for posterior after %dth week: %d" % (i, maps[i - 4]))
	plt.legend(legend)
	plt.ylabel("Likelihood")
	plt.xlabel("λ")
	plt.title("Bayesian Probability Distributions for λ (2c)")
	plt.savefig("2c.pdf")
	print()


#백준 1002 터렛
#두 원의 교점의 개수를 구하기

#두 원의 중심과 반지름을 입력했을때, 두 원사이의 접점의 개수구하는 문제!

import math

T = int(input())

for _ in range(T): #테스트케이스 돌면서
    x1,y1,r1,x2,y2,r2 =list(map(int, input().split()))

    #두 원의 중심 사이의 거리/터렛 좌표사이거리
    dis= math.sqrt((x2-x1)**2 + (y2-y1)**2)

    ##접점 출력

    if dis ==0: # 두 원의 중심이 같을 경우
        if r1 == r2: #두 원의 크기가 같아 겹치는 경우
            print(-1)

        else:        #한원이 다른 원 안에 들어가 있는경우
            print(0)

    else:      #두 원의 중심이 다른경우
        if r1+r2 == dis or abs(r2-r1) ==dis: #한점에서 만나는경우
            print(1)

        elif ((abs(r1-r2) < dis ) and (dis<r1+r2)):  #두점에서 만나는경우
            print(2)

        else:
            print(0)


# -*- coding: utf-8 -*-
"""
Created on Thu Dec 17 05:56:30 2020

@author: gape
"""

import copy
from collections import Counter, defaultdict
import re

import aoc_helper

data = aoc_helper.get_input(17, force=True).strip()
# data = aoc_helper.get_input(17).strip()
print('Day 17 input (first 10 lines):')
print('\n'.join(data.split('\n')[:10]))
print('\nTotal input length: ', len(data))
print('Total input row count: ', len(data.split('\n'))-1)
print("\n############################################################\n")

class Cube:
    def __init__(self, x,y,z,w):
        self.active = 0
        self.x = x
        self.y = y
        self.z = z
        self.w = w
        self.count = 0
        self.active_old = 0

    def infect(self, cubes, part=1):
        if part == 1:
            w_s, w_e = 0, 1
        elif part == 2:
            w_s, w_e = self.w-1, self.w+2
        for x in range(self.x-1, self.x+2):
            for y in range(self.y-1, self.y+2):
                for z in range(self.z-1, self.z+2):
                    for w in range(w_s, w_e):
                        if self.x == x and self.y == y and self.z == z and self.w == w:
                            continue
                        else:
                            if (x,y,z,w) not in cubes:
                                cubes[(x,y,z,w)] = Cube(x,y,z,w)
                            cubes[(x,y,z,w)].count += 1

def show(active):
    xs, xe = min(active, key=lambda x: x[0])[0], max(active, key=lambda x: x[0])[0]+1
    ys, ye = min(active, key=lambda x: x[1])[1], max(active, key=lambda x: x[1])[1]+1
    zs, ze = min(active, key=lambda x: x[2])[2], max(active, key=lambda x: x[2])[2]+1
    ws, we = min(active, key=lambda x: x[3])[3], max(active, key=lambda x: x[3])[3]+1
    for w in range(ws, we):
        for z in range(zs, ze):
            print("z={},w={}".format(z,w))
            for y in range(ys, ye):
                for x in range(xs, xe):
                    if (x,y,z,w) not in active:
                        print('.',end='')
                    else:
                        print('#', end='')
                print()
            print()

def run(data, part=1, verbose=False):
    cubes = dict()
    active = dict()
    z = 0
    w = 0
    for y, row in enumerate(data.split()):
        for x, c in enumerate(row):
            cube = Cube(int(x),int(y),z,w)
            cubes[(x,y,z,w)] = cube
            if c == '#':
                cube.active = 1
                active[(x,y,z,w)] = cube
    for r in range(6):
        if verbose:
            print("Runda", r, len(active))
            show(active)
        for cube in cubes.values():
            cube.count = 0
            cube.active_old = cube.active

        for cube in active.values():
            cube.infect(cubes, part=part)

        active = dict()
        for cube in cubes.values():
            if ((not cube.active_old and cube.count == 3)
            or cube.active_old and (cube.count == 2 or cube.count == 3)):
                cube.active = 1
                active[(cube.x, cube.y, cube.z, cube.w)] = cube
            else:
                cube.active = 0
    return len(active)

print("Part 1 answer: ", run(data, part=1))
print("Part 2 answer: ", run(data, part=2))


from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
from random import uniform,randint,random,seed
from time import time
import numpy as np
from pdb import set_trace
import pickle

from HVE import hve

class Model(object):
    def any(self):
        while True:
            for i in range(0,self.decnum):
                self.dec[i]=uniform(self.bottom[i],self.top[i])
            if self.check(): break

    def __init__(self):
        self.bottom=[0]
        self.top=[0]
        self.decnum=0
        self.objnum=0
        self.dec=[]
        self.lastdec=[]
        self.obj=[]
        self.any()

    def eval(self):
        return sum(self.getobj())

    def copy(self,other):
        self.dec=other.dec[:]
        self.lastdec=other.lastdec[:]
        self.obj=other.obj[:]
        self.bottom=other.bottom[:]
        self.top=other.top[:]
        self.decnum=other.decnum
        self.objnum=other.objnum

    def getobj(self):
        return []

    def check(self):
        for i in range(0,self.decnum):
            if self.dec[i]<self.bottom[i] or self.dec[i]>self.top[i]:
                return False
        return True

"Models:"
class DTLZ1(Model):
    def __init__(self,n=10,m=2):
        self.bottom=[0]*n
        self.top=[1]*n
        self.decnum=n
        self.objnum=m
        self.dec=[0]*n
        self.lastdec=[]
        self.obj=[]
        self.any()

    def getobj(self):
        if self.dec==self.lastdec:
            return self.obj
        f=[]
        g=self.decnum-self.objnum+1
        for x in self.dec[self.objnum-1:]:
            g=g+np.square(x-0.5)-np.cos((x-0.5)*20*np.pi)
        g=g*100
        for i in xrange(self.objnum):
            tmp=0.5*(1+g)
            for x in self.dec[:self.objnum-1-i]:
                tmp=tmp*x
            if not i==0:
                tmp=tmp*(1-self.dec[self.objnum-i])
            f.append(tmp)
        self.lastdec=self.dec
        self.obj=f
        return f

class DTLZ3(Model):
    def __init__(self,n=10,m=2):
        self.bottom=[0]*n
        self.top=[1]*n
        self.decnum=n
        self.objnum=m
        self.dec=[0]*n
        self.lastdec=[]
        self.obj=[]
        self.any()

    def getobj(self):

        if self.dec==self.lastdec:
            return self.obj

        f=[]
        g=self.decnum-self.objnum+1
        for x in self.dec[self.objnum-1:]:
            g=g+np.square(x-0.5)-np.cos((x-0.5)*20*np.pi)
        g=g*100
        for i in xrange(self.objnum):
            tmp=1+g
            for x in self.dec[:self.objnum-1-i]:
                tmp=tmp*np.cos(x*np.pi/2)
            if not i==0:
                tmp=tmp*np.sin(self.dec[self.objnum-i]*np.pi/2)
            f.append(tmp)
        self.lastdec=self.dec
        self.obj=f
        return f

class DTLZ5(Model):
    def __init__(self,n=10,m=2):
        self.bottom=[0]*n
        self.top=[1]*n
        self.decnum=n
        self.objnum=m
        self.dec=[0]*n
        self.lastdec=[]
        self.obj=[]
        self.any()

    def getobj(self):

        if self.dec==self.lastdec:
            return self.obj

        f=[]
        g=0
        for x in self.dec[self.objnum-1:]:
            g=g+np.square(x-0.5)
        theta=[np.pi*self.dec[0]/2]
        for x in self.dec[1:self.objnum-1]:
            theta.append((1+2*g*x)*np.pi/(4*(1+g)))
        for i in xrange(self.objnum):
            tmp=1+g
            for x in theta[:self.objnum-1-i]:
                tmp=tmp*np.cos(x*np.pi/2)
            if not i==0:
                tmp=tmp*np.sin(theta[self.objnum-i-1]*np.pi/2)
            f.append(tmp)
        self.lastdec=self.dec
        self.obj=f
        return f

class DTLZ7(Model):
    def __init__(self,n=10,m=2):
        self.bottom=[0]*n
        self.top=[1]*n
        self.decnum=n
        self.objnum=m
        self.dec=[0]*n
        self.lastdec=[]
        self.obj=[]
        self.any()

    def getobj(self):
        if self.dec==self.lastdec:
            return self.obj
        f=[]
        g=1+9/(self.decnum-self.objnum+1)*np.sum(self.dec[self.objnum-1:])
        h=self.objnum
        for i in xrange(self.objnum-1):
            f.append(self.dec[i])
            h=h-f[i]/(1+g)*(1+np.sin(3*np.pi*f[i]))
        f.append((1+g)*h)
        self.lastdec=self.dec
        self.obj=f
        return f

class Tunee(Model):
    def __init__(self,**kwargs):
        self.decname=[]
        self.decnum=0
        self.objnum=1
        self.bottom=[]
        self.top=[]
        self.kw=kwargs
        self.dec=[]
        for key in kwargs:
            if type(kwargs[key])==type([]):
                if len(kwargs[key])==3:
                    self.decname.append(key)
                    self.decnum=self.decnum+1
                    self.bottom.append(kwargs[key][1])
                    self.top.append(kwargs[key][2])
                    self.dec.append(kwargs[key][0])

        self.lastdec=[]
        self.obj=[]

    def getobj(self):
        if self.dec==self.lastdec:
            return self.obj
        for i,key in enumerate(self.decname):
            self.kw[key]=self.dec[i]
        f=optimize(**self.kw)
        self.lastdec=self.dec
        self.obj=[f]
        return [f]

    def copy(self,other):
        self.decname=other.decname[:]
        self.kw.update(other.kw)
        self.dec=other.dec[:]
        self.lastdec=other.lastdec[:]
        self.obj=other.obj[:]
        self.bottom=other.bottom[:]
        self.top=other.top[:]
        self.decnum=other.decnum
        self.objnum=other.objnum

def optimize(**kwargs):
    min=kwargs['min']
    max=kwargs['max']
    optimizer=kwargs['optimizer']
    del kwargs['min']
    del kwargs['max']
    del kwargs['optimizer']
    return hve(optimizer(**kwargs),min,max,100000)

"DE, maximization"
def differential_evolution(model,**kwargs):

    def mutate(candidates,f,cr,xbest):
        for i in xrange(len(candidates)):
            tmp=range(len(candidates))
            tmp.remove(i)
            while True:
                abc=np.random.choice(tmp,3)
                a3=[candidates[tt] for tt in abc]
                xold=candidates[i]
                r=randint(0,xold.decnum-1)
                xnew=model(**kwargs)
                xnew.any()
                for j in xrange(xold.decnum):
                    if random()<cr or j==r:
                        xnew.dec[j]=a3[0].dec[j]+f*(a3[1].dec[j]-a3[2].dec[j])
                    else:
                        xnew.dec[j]=xold.dec[j]
                if xnew.check(): break
            if xnew.eval()>xbest.eval():
                xbest.copy(xnew)
                print("!",end="")
            elif xnew.eval()>xold.eval():
                print("+",end="")
            else:
                xnew=xold
                print(".",end="")
            yield xnew

    nb=10
    maxtries=10
    f=0.75
    cr=0.3
    xbest=model(**kwargs)
    candidates=[xbest]
    for i in range(1,nb):
        x=model(**kwargs)
        x.any()
        candidates.append(x)
        if x.eval()>xbest.eval():
            xbest.copy(x)
    for tries in range(maxtries):
        print(", Retries: %2d, : Best solution: %s, " %(tries,xbest.dec),end="")
        candidates=[xnew for xnew in mutate(candidates,f,cr,xbest)]
        print("")
    print("Best solution: %s, " %xbest.dec,"hv: %s, " %xbest.getobj(),
          "evals: %s * %s" %(nb,maxtries))
    try:
        return xbest.kw
    except:
        return xbest.dec

"""
def better_gen(pf_new,pf,rate):
    count=0
    for a in pf:
        for b in pf_new:
            if is_bd(b,a):
                count=count+1
    whole=len(pf)*len(pf_new)
    if count>-int(whole*rate):
        return True
    else:
        return False
"""

"is a binary dominate b? smaller is better"
def is_bd(a,b):
    try:
        obj_a=a.getobj()
    except:
        obj_a=a
    try:
        obj_b=b.getobj()
    except:
        obj_b=b
    if obj_a==obj_b:
        return False
    for i in xrange(a.objnum):
        if obj_b[i]<obj_a[i]:
            return False
    return True

def crossover(a,b,baby):
    while True:
        x=randint(0,len(a.dec))
        baby.dec=list(np.array(a.dec)[:x])+list(np.array(b.dec)[x:])
        if baby.check():
            return baby

def mutate(baby):
    baby.any()
    return baby

"Update pf_best"
def compete(pf_best,pf_new):
    tmp=[]
    for a in pf_new:
        for b in pf_best:
            if is_bd(a,b):
                tmp.append(a)
                pf_best.remove(b)
    if tmp:
        pf_best.extend(tmp)
        return True
    else:
        return False

""
def init(Model,decnum=10,objnum=2,num=10000):
    can=[Model(decnum,objnum) for _ in xrange(num)]
    max=[np.max([c.getobj()[i] for c in can]) for i in range(objnum)]
    min=[np.min([c.getobj()[i] for c in can]) for i in range(objnum)]
    return min,max

def GeneticAlgorithm(Model=DTLZ1,decnum=10,objnum=2,the_seed=-1,candidates=100,generations=1000,mutation_rate=0.05,lifes=5):
    if the_seed>=0:
        seed(the_seed)
    candidates=int(candidates)
    lifes=int(lifes)
    can=[Model(decnum,objnum) for _ in xrange(candidates)]

    pf=[]
    for a in can:
        flag=True
        for b in can:
            if is_bd(b,a):
                flag=False
                break
        if flag:
            pf.append(a)
    pf_best=pf[:]
    life=0
    for i in xrange(generations):
        can_new=[]
        for j in xrange(candidates):
            baby=Model()
            pick=np.random.choice(len(pf),2,replace=True)
            crossover(pf[pick[0]],pf[pick[1]],baby)
            if random()<mutation_rate*(2**life):
                mutate(baby)
            can_new.append(baby)
        pf_new=[]
        for a in can:
            flag=True
            for b in can:
                if is_bd(b,a):
                    flag=False
                    break
            if flag:
                pf_new.append(a)
        change=compete(pf_best,pf_new)
        if change:
            life=0
        else:
            life=life+1
        if life==lifes:
            break
        #print("Frontier num: "+str(len(pf_best)))

        can=can_new
        pf=pf_new

    return pf_best

"""
def upminmax(min,max,pf):
    for c in pf:
        for i in xrange(len(min)):
            if min[i]>c.getobj()[i]:
                min[i]=c.getobj()[i]
            elif max[i]<c.getobj()[i]:
                max[i]=c.getobj[i]
    return min,max
"""

if __name__ == '__main__':
    candidates=100
    generations=1000
    mutation_rate=0.05
    lifes=5

    models=[DTLZ1,DTLZ3,DTLZ5,DTLZ7]
    objs=[2,4,6,8]
    decs=[10,20,40]
    hv={}
    for model in models:
        hv[model.__name__]={}
        for objnum in objs:
            hv[model.__name__][objnum]={}
            for decnum in decs:
                hv[model.__name__][objnum][decnum]={'untuned':[],'tuned':[]}
                min,max=init(model,decnum=decnum,objnum=objnum,num=100000)
                kw=differential_evolution(Tunee,optimizer=GeneticAlgorithm,min=min,max=max,Model=model,decnum=decnum,
                                          objnum=objnum,the_seed=-1,candidates=[100,10,1000],generations=1000,
                                          mutation_rate=[0.05,0.01,0.5],lifes=[5,1,10])
                del kw['optimizer']
                del kw['min']
                del kw['max']
                for the_seed in xrange(20):
                    pf1=GeneticAlgorithm(Model=model,decnum=decnum,objnum=objnum,the_seed=the_seed,candidates=candidates,
                                        generations=generations,mutation_rate=mutation_rate,lifes=lifes)
                    pf2=GeneticAlgorithm(**kw)
                    #min,max=upminmax(min,max,pf)
                    hv[model.__name__][objnum][decnum]['untuned'].append(hve(pf1,min,max,100000))
                    hv[model.__name__][objnum][decnum]['tuned'].append(hve(pf2,min,max,100000))

    with open('./data/hypervolumn.pickle', 'wb') as handle:
        pickle.dump(hv, handle)


from collections import deque

n,m=map(int,input().split())

arr=[]
answer=0

for i in range(n):
    # arr.append(list(map(str,input())))
    arr.append(list(map(lambda x:0 if x=='H' else int(x),map(str,input()))))

visited=[[False]*m for _ in range(n)]
cnt_arr=[[0]*m for _ in range(n)]
flag=False

def bfs(a,b):
    global flag
    dx=[1,0,-1,0]
    dy=[0,-1,0,1]
    q=deque()
    q.append((a,b))
    visited[a][b]=True

    while q:
        x,y=q.popleft()
        for i in range(4):
            nx=x+dx[i]*arr[x][y]
            ny=y+dy[i]*arr[x][y]
            if nx<0 or ny<0 or nx>=n or ny>=m:
                continue
            if visited[nx][ny]:
                print(nx,ny)
                cnt_arr[nx][ny]=cnt_arr[x][y]+1
                if arr[nx][ny]+nx<n or arr[nx][ny]+ny<m:
                    flag=True
                break
            if arr[nx][ny]==0:
                visited[nx][ny]=True
                cnt_arr[nx][ny]=cnt_arr[x][y]
                continue

            visited[nx][ny]=True
            if cnt_arr[nx][ny]<=cnt_arr[x][y]:
                cnt_arr[nx][ny]=cnt_arr[x][y]+1
            q.append((nx,ny))

bfs(0,0)
for i in range(n):
    for j in range(m):
        answer=max(answer,cnt_arr[i][j])

# print(visited)
if flag:
    print(-1)
else:
    print(answer+1)


from IPython.display import clear_output
from os import system, name
def display_board():
    #clear_output
    system('clear')
    print(' ' + boards[1] + ' | ' + boards[2] + ' | ' + boards[3] )
    print('------------')
    print(' ' + boards[4] + ' | ' + boards[5] + ' | ' + boards[6] )
    print('------------')
    print(' ' + boards[7] + ' | ' + boards[8] + ' | ' + boards[9] )

def player_input() :
    choose = ('X','O')
    inp = ' '
    while inp not in choose:
        inp = input('1st player, you want to play X or O, please choose X,O :')
    mark_1 = inp
    mark_2 = choose[choose.index(inp)-1]
    print("you picked " + mark_1 + " 2nd player will be " + mark_2)
    return (mark_1, mark_2)

def lay_o_danh(player):
    vi_tri = '0'
    while int(vi_tri) not in range(1,10) or not check_hop_le(int(vi_tri)):
        vi_tri = input("Ban %r chon o nao de danh : 1 - 9 :" %(player))
    return int(vi_tri)

def check_hop_le(vi_tri):
    return boards[vi_tri] == ' '

def check_full():
    return ' ' not in boards
def danh_dau(vi_tri,bi_tu):
    boards[vi_tri] = bi_tu

def lay_ten():
    a = input("ten nguoi 1 :")
    b = input("ten nguoi 2 :")
    return (a,b)

def check_win(mark):
    return ((boards[7] == mark and boards[8] == mark and boards[9] == mark) or  # across the top
            (boards[4] == mark and boards[5] == mark and boards[6] == mark) or  # across the middle
            (boards[1] == mark and boards[2] == mark and boards[3] == mark) or  # across the bottom
            (boards[7] == mark and boards[4] == mark and boards[1] == mark) or  # down the middle
            (boards[8] == mark and boards[5] == mark and boards[2] == mark) or  # down the middle
            (boards[9] == mark and boards[6] == mark and boards[3] == mark) or  # down the right side
            (boards[7] == mark and boards[5] == mark and boards[3] == mark) or  # diagonal
            (boards[9] == mark and boards[5] == mark and boards[1] == mark))  # diagonal

print("Chao mung den caro : ")

while True :
    boards = [" "] * 10
    boards[0] = "ok"
    ten = lay_ten()
    bieu_tuong = player_input()
    on_game = True
    Luot = ten[0]
    while on_game :
            display_board()
            vi_tri = lay_o_danh(Luot)
            danh_dau(vi_tri,bieu_tuong[ten.index(Luot)])
            if check_win(bieu_tuong[ten.index(Luot)]):
                print("Chuc mung %r da chien thang!!"%(Luot))
                on_game = False
            else :
                if check_full():
                    print("Khong ai thang ca :( ")
                    on_game = False
                else :
                    Luot = ten[ten.index(Luot)-1]
    choi_tiep = input(" Ban co muon choi tiep : Y / N : ")
    if choi_tiep == 'N' :
        exit(0)