import scipy.misc
import numpy as np
import matplotlib.pyplot as plt
import cv2

def getIntersetion(l1, l2, toPrint = False):
	def lineParams(p1, p2):
		if(p1[0] == p2[0]):
			raise("You can't take lines parallel to the image plane")
		m = (p1[1] - p2[1])/(p1[0] - p2[0])
		c = p1[1] - m * p1[0]
		return [m , c]
	def lines(params):
		return "y = " + str(params[0]) + "*x + " + str(params[1])
	def intersectionPoints(par1, par2):
		if(par1[0] == par2[0]):
			raise("the lines shouldn't be parallel!!!")
		x = (par1[1] - par2[1])/(par2[0] - par1[0])
		y = par1[0]*x + par1[1]
		return (x, y)
	params1 = lineParams(l1[0], l1[1])
	params2 = lineParams(l2[0], l2[1])
	if(toPrint):
		print("The first line equation is " + lines(params1))
		print("The second line equation is " + lines(params2))
		print("------------------------------------------------------------------------------------------")
	return intersectionPoints(params1, params2)

def getVanishingPoints(nLines = 4):
	plt.title("Click the start and end cordinates for "+str(nLines//2)+" set of parallel lines(Total " +str(nLines)+" lines).")
	points = plt.ginput(nLines*2)
	vanishingPoints = []
	for i in range(0, len(points), nLines):
		A1 = points[i]
		A2 = points[i+1]
		B1 = points[i+2]
		B2 = points[i+3]
		plt.plot([A1[0], A2[0]], [A1[1], A2[1]], marker = 'o')
		plt.plot([B1[0], B2[0]], [B1[1], B2[1]], marker = 'o')
		vanishingPoints.append(getIntersetion([A1, A2], [B1, B2], True))
	return vanishingPoints

def getPointsForObj():
	points = plt.ginput(n = 2, timeout = 0)
	top = points[0]
	bottom = points[1]
	plt.plot([top[0], bottom[0]], [top[1], bottom[1]], marker = 'o')
	return top, bottom

def getHeight(height, refTop, refBottom, heightPlt):
	return height * (np.linalg.norm(np.array(heightPlt)-np.array(refBottom))*1.0/np.linalg.norm(np.array(refTop)-np.array(refBottom)))

image = scipy.misc.imread("img.jpg")
N = int(input("Enter the number of objects for which you want to get the height: "))
plt.imshow(image)
vanishingPoints = getVanishingPoints()
plt.imshow(image)
plt.title("Click the coordinates for the pole(ref obj) (Top - Bottom)")
pole_top, pole_bottom = getPointsForObj()
poleHeight = 1.65
heights = ""
for i in range(1, N+1):
	plt.title("Click the coordinates of the obj-"+str(i)+" for which height is to be calculated (Top - Bottom)")
	obj_top, obj_bottom = getPointsForObj()

	vlPoint = getIntersetion([pole_bottom, obj_bottom], [vanishingPoints[0], vanishingPoints[1]])
	toGetHeightPlt = getIntersetion([pole_top, pole_bottom], [obj_top, vlPoint])

	plt.plot([vlPoint[0], toGetHeightPlt[0]], [vlPoint[1], toGetHeightPlt[1]], marker = 'o')
	plt.plot([obj_bottom[0], vlPoint[0]], [obj_bottom[1], vlPoint[1]], marker = 'o')
	plt.plot([obj_top[0], vlPoint[0]], [obj_top[1], vlPoint[1]], marker = 'o')

	objHeight = getHeight(poleHeight, pole_top, pole_bottom, toGetHeightPlt)
	print("Height of the obj"+str(i)+" : " + str(objHeight))
	heights += "Height of obj-" + str(i) + ": " + str(objHeight) + "\n"

print("\n----------------------------------------------------\n")
forCameraHeight = getIntersetion([pole_bottom, pole_top], [vanishingPoints[0], vanishingPoints[1]])
cameraHeight = getHeight(poleHeight, pole_top, pole_bottom, forCameraHeight)
print("Height of camera : "+ str(cameraHeight))
heights += "Height of camera"+ ": " + str(cameraHeight) + "\nThe dotted line is the vanishing line"
plt.title("")
plt.text(0, 0, heights)
plt.plot([vanishingPoints[0][0], vanishingPoints[1][0]], [vanishingPoints[0][1], vanishingPoints[1][1]], color='red', marker = 'o', linestyle='dashed')
plt.show()


import asyncio
import logging
from typing import List

from asyncpg import LockNotAvailableError
from buildpg.asyncpg import BuildPgConnection

from .. import glove
from ..settings import BaseSettings
from .helpers import DummyPgPool
from .patches import Patch, get_sql_section
from .utils import AsyncPgContext

logger = logging.getLogger('foxglove.db.migrations')

__all__ = ('run_migrations',)

migrations_table_name = 'migrations'
migrations_table_sql = f"""
create table if not exists {migrations_table_name} (
  id serial primary key,
  ts timestamptz not null default current_timestamp,
  ref varchar(255) not null,
  sql_section text not null,
  fake boolean not null,
  unique (ref, sql_section)
);
"""

async def run_migrations(settings: BaseSettings, patches: List[Patch], live: bool, *, fake: bool = False) -> int:
    """
    Migrations in foxglove are handled by patches which are run automatically if
    foxglove spots they haven't been run before
    """
    migration_patches = [p for p in patches if p.auto_run]
    if not migration_patches:
        return 0

    count = 0
    up_to_date = 0
    async with AsyncPgContext(settings.pg_dsn) as conn:
        tr = conn.transaction()
        await tr.start()

        if not await conn.fetchval('select 1 from pg_tables where tablename=$1', migrations_table_name):
            await conn.execute(migrations_table_sql)
            logger.info('%s table created', migrations_table_name)

        try:
            await conn.execute(f'lock table {migrations_table_name} nowait')
        except LockNotAvailableError:
            logger.debug('another transaction has locked %s, skipping migrations here', migrations_table_name)
            await tr.rollback()
            return 0

        default_pg = getattr(glove, 'pg', None)
        glove.pg = DummyPgPool(conn)
        logger.info('checking %d migration patches...', len(migration_patches))
        for patch in migration_patches:
            if patch.auto_sql_section:
                content = get_sql_section(patch.auto_sql_section, settings.sql)
                sql_section = f'{patch.auto_sql_section}::\n{content}'
            else:
                # '-' is required to make the unique constraint work since null would mean rows wouldn't conflict
                sql_section = '-'

            patch_ref = patch.func.__name__
            if isinstance(patch.auto_run, str):
                patch_ref += f':{patch.auto_run}'
            migration_id = await conn.fetchval(
                f"""
                insert into {migrations_table_name} (ref, sql_section, fake)
                values ($1, $2, $3)
                on conflict (ref, sql_section) do nothing
                returning id
                """,
                patch_ref,
                sql_section,
                fake,
            )
            if migration_id is None:
                up_to_date += 1
                continue

            if fake:
                logger.info('faked migration %s', patch_ref)
            else:
                successful = await run_patch(conn, patch, patch_ref, live)
                if not successful:
                    logger.warning('patch failed, rolling back all %d migration patches in this session', count)
                    await tr.rollback()
                    glove.pg = default_pg
                    return 0

            count += 1

        glove.pg = default_pg
        verb = 'faked' if fake else 'run'
        if live:
            await tr.commit()
            if count == 0:
                logger.info('all %d migrations already up to date ✓', up_to_date)
            else:
                logger.info('%d migration patches %s, %d already up to date ✓', count, verb, up_to_date)
        else:
            await tr.rollback()
            logger.info(
                '%d migration patches %s, %d already up to date, not live rolling back', count, verb, up_to_date
            )

    return count

async def run_patch(conn: BuildPgConnection, patch: Patch, ref: str, live: bool) -> bool:
    kwargs = dict(conn=conn, live=live, args={'__migration__': 'true'}, logger=logger)
    logger.info('{:-^50}'.format(f' {ref} ... '))
    try:
        if asyncio.iscoroutinefunction(patch.func):
            result = await patch.func(**kwargs)
        else:
            result = patch.func(**kwargs)
        if result is not None:
            logger.info('result: %s', result)
    except BaseException:
        logger.info('{:-^50}'.format(f' {ref} failed '))
        logger.exception('Error running %s migration patch', patch.func.__name__)
        return False
    else:
        logger.info('{:-^50}'.format(f' {ref} ✓ '))
        return True


# 1 - необязательно формировать список перед тем, как сделать список. Пользуйтесь методом append и наполняйте изначально пустой
# 2 - старайтесь не повторять свой собственный код. Чтобы избежать повторения, можно было сразу узнать, какая строка больше.
# main_string, text2 = max(str1, str2, key=len), min(str1,str2, key=len)
# 3- весьма хорошо, только забыли учесть отрицательные числа
# 4 - тоже верно

# Сформировать список из N членов последовательности.
# Для N = 5: 1, -3, 9, -27, 81 и т.д.

print('###### HW1 - Задание 1 ######')
print('Введите N=')
N = int(input())
Nl = list(range(N))
Nl[0] = 1
for i in range(1, N):
    Nl[i] = (-3)**i
print(f'список из N={N} членов последовательности:\n{Nl}')
print('******************************\n')

# Пользователь задаёт две строки. Определить количество вхождений одной строки в другой.

print('###### HW1 - Задание 2 ######')
print('Введите строку №1:')
str1 = str(input())
print('Введите строку №2:')
str2 = str(input())
index = -1
count = 0
if str1 == str2:
    print('Строки однаковы')
elif len(str1) > len(str2):
    while True:
        index = str1.find(str2, index+1)
        if index == -1:
            break
        count += 1
    print(f'вторая страка входит в первую {count} раз')
else:
    while True:
        index = str2.find(str1, index+1)
        if index == -1:
            break
        count += 1
    print(f'первая строка входит во вторую {count} раз')
print('******************************\n')

# # Подсчитать сумму цифр в вещественном числе.

print('###### HW1 - Задание 3 ######')
print('Введите вещественном число N=')
No = float(input())
Ns = str(No)
Ns = Ns.replace(".", "")
Sum = 0
for elm in Ns:
    Sum += int(elm)
print(f'сумма цифр в вещественном числе {No} = {Sum}')
print('******************************\n')

# # Написать программу получающую набор произведений чисел от 1 до N.
# # Пример: пусть N = 4, тогда  [ 1, 2, 6, 24 ]

print('###### HW1 - Задание 4 ######')
print('Введите N=')
Nr = int(input())
Nls = list(range(Nr))
Nls[0] = 1
for j in range(1, Nr):
    Nls[j] = Nls[j-1]*(j+1)
print(Nls)
print('******************************\n')

exit()

# Для тех, кому этих задач будет мало, еще несколько не слишком сложных для начала.
#* Экстра-задачи:
#
# 1. Написать функцию write_in_morse, которая принимает строку на английском языке и возвращает ее перевод на символьный язык Морзе. Ввод не должен зависеть от регистра.
# Да поможет вам этот словарь:
# char_to_dots = {
#   'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
#   'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
#   'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
#   'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
#   'Y': '-.--', 'Z': '--..', ' ': ' ', '0': '-----',
#   '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
#   '6': '-....', '7': '--...', '8': '---..', '9': '----.',
#   '&': '.-...', "'": '.----.', '@': '.--.-.', ')': '-.--.-', '(': '-.--.',
#   ':': '---...', ',': '--..--', '=': '-...-', '!': '-.-.--', '.': '.-.-.-',
#   '-': '-....-', '+': '.-.-.', '"': '.-..-.', '?': '..--..', '/': '-..-.'
# }
#

# 2. Есть такая вещь - палиндром. Это когда слово читается с обеих сторон одинаково. Например, слово "шалаш". Также есть числовой палиндром. Если при обратном чтении числа (124 - 421) не получается то же самое, то они складываются (124+421) и проверяются вновь. Попробуйте написать функцию (или просто программу, но лучше все же функцию), находящую числовой палиндром.
#

# 3. Напишите программу, смысл которой вот в чем. Программа загадывает вам число из ограниченного диапазона. Ваша цель — отгадать это за log(количество вариантов) попыток. Подсказками компьютера могут служить слова «больше» или «меньше»
#

# 4. Напишите программу, обратную предыдущей: теперь вы загадываете число, а компьютер отгадывает.
#

# 5. Эта задача больше на интерес и «для души». Попробуйте написать текстовый квест, где он выбранных ответов зависит исход игры. Подходит людям с писательскими способностями. Пример:
#
# >>> Ты просыпаешься. Оценив взглядом помещение, ты понимаешь, что это явно не твоя комната. Нужно выбраться отсюда. Перед тобой — невзрачный шкаф, стоящий посередине  стены, дверь, на которой почему-то весит замок, стол и окно. Куда подойдешь?
# >>> Дверь
# >>>Ты подошел к двери. На ней кодовый замок из 4 цифр. Ввести код или попробовать сбить его?
# >>>Попробовать сбить
# >>>Вы наделали много шума, но результата это не дало. Попробовать ввести код?
# >>> Да
# >>>Код:
# >>>5386
# >>>Неверно
# >>>5347
# >>>Неверно
# >>>Назад
# >>>Перед тобой — невзрачный шкаф, стоящий посередине стены, дверь, на которой почему-то весит замок, стол и окно. Куда подойдешь?
# >>> Стол
# >>> На столе есть фотография. На ней — какой-то улыбающийся мальчик. Есть также какая-то папка, органайзер с ручками и ваза. Что хочешь осмотреть?
# >>> Осмотреть фотографию.
# >>> На обороте написано: «Коленьке 6 лет. 06.11.2004»
# >>> Назад
# >>> Перед тобой — невзрачный шкаф, стоящий посередине стены, дверь, на которой почему-то весит замок, стол и окно. Куда подойдешь?
# >>> Дверь
# >>>Ты подошел к двери. На ней кодовый замок из 4 цифр. Ввести код или попробовать сбить его?
# >>>Ввести код
# >>> Код:
# >>> 0611
# >>>Замок открывается. Ты тянешь ручку двери на себя, дверь открывается. Ты оказываешься в коридоре. Слышишь рычание. Оборачиваешься и видишь жуткого зверя. Видимо, ты издал слишком много шума, чем привлек его внимание или пробудил ото сна. Кажется, это конец. Или нет?
# >>> Конец игры. Открыта одна из концовок.


import random
import os
import sys
sys.path.insert(0, 'rws/')
import rw5
sys.path.insert(0, '')

def calisma(word_list,mean_list,backup_words,backup_means,setting2,setting3):
  forms = ['en-tr','tr-en']
  while True:

    if bool(word_list) == False and bool(mean_list) == False:
      print('Calisma Bitti')
      if setting3 == 'EU':
        os.system('setxkbmap eu')
      elif setting3 == 'TR':
        os.system('setxkbmap tr')
      break

    else:
      form = random.choice(forms)
      if form == 'en-tr':
        random_word = random.choice(word_list)
        r_line = rw5.bul(random_word,word_list)
        answer = mean_list[r_line - 1]

        if setting2 == 'ON':
          os.system('setxkbmap tr')
        quest = input(random_word + ' = ')

        if quest == answer:
          word_list.remove(random_word)
          mean_list.remove(answer)
        else:
          print('yanlis cevap ! ' + answer + ' olacakti .')
          word_list.remove(random_word)
          mean_list.remove(answer)
          backup_words.append(random_word)
          backup_means.append(answer)

      elif form == 'tr-en':
        random_mean = random.choice(mean_list)
        m_line = rw5.bul(random_mean,mean_list)
        answer = word_list[m_line - 1]

        if setting2 == 'ON':
          os.system('setxkbmap eu')
        quest = input(random_mean + ' = ')

        if quest == answer:
          word_list.remove(answer)
          mean_list.remove(random_mean)
        else:
          print('yanlis cevap ! ' + answer + ' olacakti .')
          mean_list.remove(random_mean)
          word_list.remove(answer)
          backup_means.append(random_mean)
          backup_words.append(answer)


"""
1031. Number of Enclaves

steps:

1. mark starting point of island in a hashmap to be 0 or 1 if on boundry
2. also store number of islands in another hasmap with parent of each island as key
3. if not on boundry (0 for boundry , 1 for not) add the number to result
4. return result

"""

class Solution(object):
    def numEnclaves(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
        lands = {}
        islands = {}
        seen = set()

        def getLand(r,c,parent):

            if (r,c) in seen:
                return
            seen.add((r,c))
            islands[parent]+=1
            if r == 0 or r == len(A)-1:
                lands[parent] = lands[parent]*0
            else:
                lands[parent] = lands[parent]*1

            if c == 0 or c == len(A[r])-1:
                lands[parent] = lands[parent]*0
            else:
                lands[parent] = lands[parent]*1

            #go up
            if r-1 >=0 and A[r-1][c] == 1:
                getLand(r-1,c,parent)

            #go down
            if r+1 < len(A) and A[r+1][c] ==1 :
                getLand(r+1,c,parent)

            #go left
            if c-1 >=0 and A[r][c-1] ==1 :
                getLand(r,c-1,parent)

            #go right
            if c+1 < len(A[r]) and A[r][c+1] ==1:
                getLand(r,c+1,parent)

        for i,x in enumerate(A):
            for j,y in enumerate(x):
                if (i,j) not in seen and A[i][j] == 1:
                    lands[(i,j)] = 1
                    islands[(i,j)] = 0
                    getLand(i,j,(i,j))

        r = 0
        for x in lands:
            if lands[x] != 0:
                r += islands[x]

        return r


import cv2
import numpy as np
import pandas as pd
from tqdm import tqdm
from scipy.spatial.distance import directed_hausdorff
from itertools import combinations
from .utils import (is_black_image, create_overlapping_image,
                    scale_down, draw_hausdorff_lines, read_binary,
                    make_hyperlink, create_overlapping_images,
                    _max_dim_diff)
import pyximport
pyximport.install()
from .distance import get_distance_matrix

def get_canny_edge(img:np.ndarray, threshold1=0, threshold2=255,
                **kwargs)->np.ndarray:
    """
    Extract line by Canny Edge Method.
    """
    cnt = cv2.Canny(img, threshold1, threshold2)
    return np.argwhere(cnt>0)

def get_contour(img:np.ndarray, retrieve_mode:int=cv2.RETR_TREE,
               approximation:int=cv2.CHAIN_APPROX_SIMPLE, **kwargs)->np.ndarray:

    """
    Extract line by cv2.findContours().
    """
    cnt, _ = cv2.findContours(img1, retrieve_mode, approximation)
    r, _, c = cnt[0].shape
    cnt_line = cnt[0].reshape(r,c)

    return cnt_line

def get_raw_points(img:np.ndarray, **kwargs)->np.ndarray:
    """
    Extract every point from binary image.
    """
    return np.argwhere(img>0)

def get_thin_line(img:np.ndarray, **kwargs)->np.ndarray:
    """
    Extract line by thinning method.
    """
    return np.argwhere(cv2.ximgproc.thinning(img) >0)

def average_hausdorff(segmentation: np.ndarray,
                      ground_truth: np.ndarray,
                      balanced:bool=False) -> float:

    """
    Implementation of O.U. Aydin, A.A. Taha, A. Hilbert, A.A Khalil,
    I. Galinovic, J.B. Fiebach, D. Frey, V.I. Madai. (2021).
    On the usage of average Hausdorff distance for segmentation
    performance assessment: hidden error when used for ranking.

    """

    S = segmentation.shape[0]
    G = ground_truth.shape[0]
    segmentation=np.asarray(segmentation, dtype=np.int32, order='c')
    ground_truth=np.asarray(ground_truth, dtype=np.int32, order='c')
    distance_matrix = get_distance_matrix(segmentation, ground_truth)
    StoG = distance_matrix.min(axis=0).sum()
    GtoS = distance_matrix.min(axis=1).sum()

    if balanced:
        return ((StoG / G) + (GtoS / G)) / 2

    return ((StoG / S) + (GtoS) / G) /2

def hausdorff_distance(img1:np.ndarray, img2: np.ndarray,
                      extraction_method:str='canny',
                      retrieve_mode:int=cv2.RETR_EXTERNAL,
                      approximation:int=cv2.CHAIN_APPROX_TC89_KCOS,
                      threshold1=0,
                      threshold2=255,
                      **kwargs):

    extraction_methods = {
        "thin" : get_thin_line,
        "canny" : get_canny_edge,
        "contour" : get_contour,
        "raw_points" : get_raw_points
    }

    na = (-1.0, (-1.0,(0,0),(0,0)), (-1.0, (0,0), (0,0)))
    ignore_error = kwargs.get('ignore_error')
    tolerance = kwargs.get('tolerance')
    index = kwargs.get('index')
    raters = kwargs.get('raters')
    point_threshold = kwargs.get('point_threshold')
    average= kwargs.get('average')
    balanced = kwargs.get('balanced') if kwargs.get('balanced') else False

    if ignore_error:
        if ((is_black_image(img1))
        or (is_black_image(img2))):
            return na

        if img1.shape != img2.shape:
            if tolerance is None:
                return na

            tol_pixel, dimension = tolerance
            pixel_difference = _max_dim_diff(img1, img2, dimension)

            if pixel_difference > tol_pixel:
                return na

    else:
        assert img1.shape == img2.shape, \
        f"""Unequal image size at {index}:\n
        ``{'Image 1' if not raters else raters[0]}`'s image has size {img1.shape}\n
        while `{'Image 2' if not raters else raters[1]}`'s image has size {img2.shape}\n"""

    line1 = extraction_methods[extraction_method](img1,
                                                  retrieve_mode=retrieve_mode,
                                                  approximation=approximation,
                                                  threshold1=threshold1,
                                                  threshold2=threshold2)
    line2 = extraction_methods[extraction_method](img2,
                                                  retrieve_mode=retrieve_mode,
                                                  approximation=approximation,
                                                  threshold1=threshold1,
                                                  threshold2=threshold2)

    if ignore_error:
        if not (line1).all() or not (line2).all():
            return na

    if point_threshold:
        if (len(line1.ravel()) < point_threshold
         or len(line2.ravel()) < point_threshold):
            return na

    hAB, hBA = directed_hausdorff(line1,line2), directed_hausdorff(line2,line1)

    if average:
        hd, AtoB, BtoA = (average_hausdorff(line1, line2, balanced),
                          hAB[1:], hBA[1:])
    else:
        hd, AtoB, BtoA = max(hAB[0], hBA[0]), hAB[1:], hBA[1:]

    return (hd,
            (hAB[0], tuple(line1[AtoB[0]][::-1]), tuple(line2[AtoB[1]][::-1])),
            (hBA[0], tuple(line2[BtoA[0]][::-1]), tuple(line1[BtoA[1]][::-1])))
    # Deprecated
    # return hd

def hausdorff_distances(df:pd.DataFrame, **kwargs)->pd.DataFrame:

    """
    Get Hausdorff Distance from all images in a DataFrame with image path.
    """

    assert len(df.columns) > 1, \
    "DataFrame must contain more than 1 rater."

    if kwargs.get('ignore_inconsistent_name') == False:
        assert not inconsistent_name(df), \
        "DataFrame contains inconsistent names. Please check file names again."

    repeated_image = kwargs.get('repeated_image')
    ignore_error = kwargs.get('ignore_error')
    point_threshold = kwargs.get('point_threshold')
    tolerance = kwargs.get('tolerance')
    output_dir = kwargs.get('output_dir')
    create_overlapping_image = kwargs.get('create_overlapping_image')
    average = kwargs.get('average')
    balanced = kwargs.get('balanced')
    extraction_method = kwargs.get('extraction_method')

    hd_df = pd.DataFrame()
    temp_dfs = []
    tqdm.pandas()
    hyperlink_df = None

    if repeated_image:
        indices = df.index.values
    else:
        indices = np.vectorize(lambda x: x.name)(df[df.columns[0]].values)

    for comb in combinations(df.columns, 2):
        carrier_df = pd.DataFrame()
        rater_a, rater_b = comb
        print(f'Comparing {rater_a} and {rater_b} ...')
        temp = df.progress_apply(
        lambda x : hausdorff_distance(read_binary(x[rater_a]),
                                      read_binary(x[rater_b]),
                                      index=x.name,
                                      extraction_method=extraction_method,
                                      raters=(rater_a, rater_b),
                                      ignore_error=ignore_error,
                                      point_threshold=point_threshold,
                                      tolerance=tolerance,
                                      average=average,
                                      balanced=balanced),
                                      axis = 1).apply(pd.Series)
        carrier_df[['hd', 'hAB', 'hBA']] = temp
        hd_df[f"Hausdorff_Distance-{rater_a}-{rater_b}"] = carrier_df['hd']

        if create_overlapping_image:
            if not kwargs.get('output_dir'): continue
            print('creating overlapped images....')
            distances = carrier_df[['hAB', 'hBA']].apply(tuple, axis=1)
            paths = create_overlapping_images(df[rater_a],
                                              df[rater_b],
                                              output_dir=output_dir,
                                              indices=indices,
                                              raters=(rater_a, rater_b),
                                              distances=distances,
                                              channels='rgb')

            temp_df = pd.DataFrame(hd_df[f"Hausdorff_Distance-{rater_a}-{rater_b}"]
                                    .astype('string') + "#" + paths)
            temp_df.fillna('-1.0#0', inplace=True)

            temp_df = temp_df.applymap(lambda x : make_hyperlink(x))
            temp_dfs.append(temp_df)

    if create_overlapping_image:
        hyperlink_df = pd.concat(temp_dfs, axis=1)
        hyperlink_df = hyperlink_df.set_index(indices)

    return hd_df.set_index(indices), hyperlink_df


def bubble_sort(arr):
    '''
    Bubble sort keep swaping that is it
    '''

    i = 0
    while (i < len(arr)):

        j = 0
        while j < len(arr) - 1:

            # swap the values here
            if arr[j+1] <= arr[j]:
                temp = arr[j]
                arr[j] = arr[j+1]
                arr[j+1] = temp

            j += 1

        i += 1

    return arr

if __name__ == '__main__':
    lst = [3, 5, 6, 2, 4, 1, 9, 8, 10]
    print(bubble_sort(lst))


from __future__ import annotations

import logging
import os
import re
import shutil
from typing import Any, Callable, Sequence, Sized

import torch
from accelerate import Accelerator
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from tqdm.auto import tqdm

try:
    from torch.optim.lr_scheduler import LRScheduler
except ImportError:
    from torch.optim.lr_scheduler import _LRScheduler as LRScheduler

logger = logging.getLogger(__name__)

class Trainer:
    def __init__(
        self,
        *,
        model: torch.nn.Module,
        train_dataloader: DataLoader,
        optimizer: Optimizer,
        accelerator: Accelerator,
        validation_dataloader: DataLoader | None = None,
        epochs: int = 3,
        lr_scheduler: LRScheduler | None = None,
        log_interval: int = 50,
        save_on_epoch_end: bool = True,
        epoch_end_callbacks: Sequence[Callable[['Trainer'], None]] | None = None,
    ):
        self.model = model
        self.optimizer = optimizer
        self.train_dataloader = train_dataloader
        self.validation_dataloader = validation_dataloader
        self.lr_scheduler = lr_scheduler
        self.accelerator = accelerator
        self.epochs = epochs
        self.log_interval = log_interval
        self.save_on_epoch_end = save_on_epoch_end

        self.train_loss_tracker = LossTracker()
        self.validation_loss_tracker = LossTracker()
        if isinstance(self.train_dataloader.dataset, Sized):
            num_steps_per_epoch = len(self.train_dataloader)
        else:
            num_steps_per_epoch = None
        self.progress_bar = DistributedTqdmProgressBar(self.epochs, num_steps_per_epoch=num_steps_per_epoch)
        self.epoch_end_callbacks = epoch_end_callbacks or []
        self.current_step = 0

    def train(self):
        for current_epoch in range(1, self.epochs + 1):
            self.model.train()
            self.progress_bar.on_epoch_start()

            for batch_index, batch in enumerate(self.train_dataloader):
                with self.accelerator.accumulate(self.model):
                    self.optimizer.zero_grad()
                    batch_output = self.model(**batch)
                    loss = batch_output['loss']
                    self.accelerator.backward(loss)
                    self.optimizer.step()
                    if self.lr_scheduler is not None:
                        self.lr_scheduler.step()
                    self.train_loss_tracker.update(loss)

                self.progress_bar.update()
                self.current_step += 1
                if batch_index % self.log_interval == 0:
                    self.log_metrics(
                        {'loss': self.train_loss_tracker.loss},
                        step=self.current_step,
                    )

            train_metrics = self.add_prefix({'loss': self.train_loss_tracker.loss}, 'train')
            self.accelerator.log(train_metrics, step=current_epoch)
            self.train_loss_tracker.on_epoch_end()
            self.progress_bar.on_epoch_end()

            if self.validation_dataloader:
                validation_loss = evaluate(
                    self.model,
                    self.validation_dataloader,
                    self.validation_loss_tracker,
                )
                validation_metrics = self.add_prefix({'loss': validation_loss}, 'validation')
                self.accelerator.print(f'Epoch {current_epoch} Validation loss: {validation_loss:.4f}')
                self.accelerator.log(validation_metrics, step=current_epoch)

            if self.save_on_epoch_end:
                self.accelerator.save_state(self.get_checkpoint_dir())

            if self.epoch_end_callbacks:
                for callback in self.epoch_end_callbacks:
                    callback(self)

        self.accelerator.end_training()

    def log_metrics(self, metrics: dict[str, float], step: int):
        self.accelerator.log(metrics, step=step)
        self.progress_bar.show_metrics(metrics)

    @staticmethod
    def add_prefix(values: dict[str, Any], prefix: str):
        return {f'{prefix}/{k}': v for k, v in values.items()}

    def get_checkpoint_dir(self):
        # COPY FROM accelerator to fix Checkpoint bug
        self.accelerator.project_configuration.automatic_checkpoint_naming = False
        output_dir = os.path.join(self.accelerator.project_dir, 'checkpoints')
        if self.accelerator.is_local_main_process:
            os.makedirs(output_dir, exist_ok=True)
            folders = [os.path.join(output_dir, folder) for folder in os.listdir(output_dir)]
            if self.accelerator.project_configuration.total_limit is not None and (
                len(folders) + 1 > self.accelerator.project_configuration.total_limit
            ):

                def _inner(folder):
                    return list(map(int, re.findall(r'[\/]?([0-9]+)(?=[^\/]*$)', folder)))[0]

                folders.sort(key=_inner)
                logger.warning(
                    f'Deleting {len(folders) + 1 - self.accelerator.project_configuration.total_limit}'
                    'checkpoints to make room for new checkpoint.'
                )
                for folder in folders[: len(folders) + 1 - self.accelerator.project_configuration.total_limit]:
                    shutil.rmtree(folder)

        output_dir = os.path.join(output_dir, f'checkpoint_{self.accelerator.save_iteration}')
        if self.accelerator.is_local_main_process:
            os.makedirs(output_dir, exist_ok=True)
        logger.info(f'Saving current state to {output_dir}')
        return output_dir

def evaluate(
    model: torch.nn.Module,
    dataloader: DataLoader,
    loss_tracker: LossTracker | None = None,
):
    model = model.eval()
    loss_tracker = loss_tracker or LossTracker()
    for batch in dataloader:
        with torch.inference_mode():
            batch_output = model(**batch)
            loss_tracker.update(batch_output['loss'])
    loss = loss_tracker.loss
    loss_tracker.on_epoch_end()
    return loss

class DummyProgressBar:
    def update(self, n: int = 1) -> None:
        pass

    def close(self) -> None:
        pass

    def set_description(self, description: str) -> None:
        pass

class DistributedTqdmProgressBar:
    def __init__(self, epochs: int, num_steps_per_epoch: int | None, **kwargs) -> None:
        self.accelerator = Accelerator()
        self.epochs = epochs
        self.current_epoch = 1
        self.num_steps_per_epoch = num_steps_per_epoch
        self.tqdm_kwargs = kwargs

    def on_epoch_start(self):
        if self.accelerator.is_main_process:
            self.progress_bar = tqdm(total=self.num_steps_per_epoch, **self.tqdm_kwargs)
        else:
            self.progress_bar = DummyProgressBar()

    def update(self, n: int = 1) -> None:
        self.progress_bar.update(n)

    def close(self) -> None:
        self.progress_bar.close()

    def on_epoch_end(self) -> None:
        self.current_epoch += 1
        self.progress_bar.close()

    def show_metrics(self, metrics: dict[str, float]) -> None:
        description = f'Epoch {self.current_epoch}/{self.epochs}'
        for name, score in metrics.items():
            description += f' - {name}: {score:.4f}'
        self.progress_bar.set_description(description)

class LossTracker:
    def __init__(
        self,
        ndigits=4,
    ) -> None:
        self.ndigits = ndigits
        self._loss: float = 0.0
        self.loss_count: int = 0
        self.history: list[float] = []

    def update(self, loss_tensor: torch.Tensor):
        loss = loss_tensor.item()
        self._loss = (self._loss * self.loss_count + loss) / (self.loss_count + 1)
        self.loss_count += 1

    def reset(self):
        self._loss = 0
        self.loss_count = 0

    def on_epoch_end(self, reset: bool = True):
        self.history.append(self.loss)
        if reset:
            self.reset()

    @property
    def loss(self) -> float:
        return round(float(self._loss), self.ndigits)


import torch
import torch.nn as nn
import torchvision.models as models

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class EncoderCNN(nn.Module):
    def __init__(self, embed_size):
        super(EncoderCNN, self).__init__()
        resnet = models.resnet50(pretrained=True)
        for param in resnet.parameters():
            param.requires_grad_(False)

        modules = list(resnet.children())[:-1]
        self.resnet = nn.Sequential(*modules)
        self.embed = nn.Linear(resnet.fc.in_features, embed_size)

    def forward(self, images):
        features = self.resnet(images)
        features = features.view(features.size(0), -1) #reshape to send to linear for creating a fixed embedded layer for encoder
        features = self.embed(features)
        return features

class DecoderRNN(nn.Module):

    def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):
#         super( DecoderRNN, self).__init__()

        ''' Initialize the layers of this model.'''

        super().__init__()
        self.embed_size = embed_size
        self.hidden_size = hidden_size
        self.vocab_size = vocab_size
        self.num_layers = num_layers
        # embedding layer that turns words into a vector of a specified size
        self.word_embeddings = nn.Embedding(vocab_size, embed_size)

        # the LSTM takes embedded word vectors (of a specified size) as inputs
        # and outputs hidden states of size hidden_dim
        self.lstm = nn.LSTM(input_size = self.embed_size, hidden_size = self.hidden_size, num_layers  = self.num_layers,batch_first = True)

        # the linear layer that maps the hidden state output dimension
        # to the number of tags we want as output (in this case this is vocab_size)
        self.fc = nn.Linear( self.hidden_size , self.vocab_size  )

    def init_hidden( self,batch_size ):
        a = torch.zeros( self.num_layers , batch_size , self.hidden_size).to(device)
        b = torch.zeros( self.num_layers , batch_size , self.hidden_size).to(device)
        return (a,b)

#         return ( torch.zeros( self.num_layers , batch_size , self.hidden_size, device='cuda:0'),torch.zeros( self.num_layers , batch_size , self.hidden_size,device='cuda:0'))
#         return ( torch.zeros( self.num_layers , batch_size , self.hidden_size),torch.zeros( self.num_layers , batch_size , self.hidden_size))

#         initialize the hidden state (see code below)
#         self.hidden_dim = hidden_dim
#         self.hidden = self.init_hidden()

#     def init_hidden(self):
#     ''' At the start of training, we need to initialize a hidden state;
#        there will be none because the hidden state is formed based on perviously seen data.
#        So, this function defines a hidden state with all zeroes and of a specified size.'''
#         # The axes dimensions are (n_layers, batch_size, hidden_dim)
#         return (torch.zeros(1, 1, self.hidden_dim),
#                 torch.zeros(1, 1, self.hidden_dim))

    def forward(self, features, captions):
        ''' Define the feedforward behavior of the model.'''
        # create embedded word vectors for each word in a sentence from caption
        captions = captions[:, :-1]
        self.batch_size = features.shape[0]
        self.hidden = self.init_hidden( self.batch_size )

        embeds = self.word_embeddings(captions)
        input_embeds = torch.cat((features.unsqueeze(dim = 1), embeds), dim = 1)

        # get the output and hidden state by passing the lstm over our word embeddings
        # the lstm takes in our embeddings and hiddent state
        lstm_out, self.hidden = self.lstm(input_embeds , self.hidden)
#         embeds.view(len(sentence), 1, -1), self.hidden

        # get the scores for the most likely tag for a word
        outputs = self.fc( lstm_out )

        return outputs

    def sample(self, inputs, states=None, max_len=20):

        " accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) "
        output_sentence = []
        batch = inputs.shape[0]
        hidden = self.init_hidden(batch)
        for i in range(max_len):
            lstm_outputs, hidden = self.lstm(inputs,hidden)
            outputs = self.fc(lstm_outputs)
            outputs = outputs.squeeze(1)
            _ ,max_pick = torch.max(outputs,dim=1)
            output_sentence.append(max_pick.cpu().numpy()[0].item())
            inputs = self.word_embeddings(max_pick).unsqueeze(1)

        return output_sentence


from ..common import *
from .common import *

# all extensions will be in lower case
ACCEPTABLE_EXCEL_EXTENSIONS = ('.xlsx',)
ACCEPTABLE_CSV_EXTENSIONS = ('.csv', '.csv.gz')
ACCEPTABLE_TSV_EXTENSIONS = ('.tsv', '.tsv.gz')

def load_dataframe(
    file: FileStorage,
    *,
    skiprows=0,
    nrows=None,
) -> pd.DataFrame:

    filename = str(file.filename)
    filename_lower = filename.lower()

    common_params = {
        'skiprows': skiprows,
        'nrows': nrows,
        'parse_dates': False,
        'na_values': ('缺',),
    }

    if filename_lower.endswith(ACCEPTABLE_EXCEL_EXTENSIONS):
        return pd.read_excel(file, **common_params)
    elif filename_lower.endswith(ACCEPTABLE_CSV_EXTENSIONS):
        return pd.read_csv(file, **common_params)
    elif filename_lower.endswith(ACCEPTABLE_TSV_EXTENSIONS):
        return pd.read_csv(file, **common_params, sep='\t')
    else:
        raise ImportTableError(f'无法识别的表格：{filename}')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug  3 03:19:30 2020

@author: AkashTyagi
"""
floor = 6
egg = 2

t = [[0]*(floor+1) for i in range(egg+1)]

c = 0

for i in range(floor+1):
    t[1][i] = i

for e in range(2,egg+1):
    for f in range(1,floor+1):
        t[e][f] = float('inf')

        for k in range(1,f+1):
            c= 1+max(t[e-1][k-1],
                     t[e][f-k])

            if c<t[e][f]:
                t[e][f] = c

print(t[egg][floor])


import sys
import subprocess
import time
import os

device_dict={'C6':'FA68W0312642'}
device_list=['C1','C2','C3','C4','C5','C6','C7','C8','C9','C10']
processes=set()

def op(device_name, command):
    if device_name=='all':
        pass
    else:
        device_id=device_dict[device_name]
        text=command%(device_id)
        seg=text.split(' ')
        processes.add(subprocess.Popen(seg))

def op_sc(device_name, command):
    if device_name=='all':
        for device_name in device_list:
            device_id=device_dict[device_name]
            text=command%(device_id, device_name)
            seg=text.split(' ')
            processes.add(subprocess.call(text, shell=True))
    else:
        device_id=device_dict[device_name]
        text=command%(device_id, device_name)
        #print(text)
        seg=text.split(' ')
        processes.add(subprocess.call(text, shell=True))

def op_check(device_name):
    device_id=device_dict[device_name]
    text='adb -s %s shell ls -l mnt/sdcard/DCIM/Camera'%(device_id)
    seg=text.split(' ')
    out1=subprocess.check_output(seg).decode('utf-8')
    #out1_list=[l for l in out1.split('\n') if l[-4:]=='.mp4']
    print(out1)

def op_copy(device_name):
    if device_name=='all':
        pass
    else:
        device_id=device_dict[device_name]
        text='adb -s %s shell ls -l mnt/sdcard/DCIM/Camera'%(device_id)
        seg=text.split(' ')
        out1=subprocess.check_output(seg).decode('utf-8')
        out1_list=[l for l in out1.split('\n') if l[-4:]=='.mp4']
        #print(out1_list)
        time.sleep(2)
        out2=subprocess.check_output(seg).decode('utf-8')
        out2_list=[l for l in out2.split('\n') if l[-4:]=='.mp4']
        #print(out2_list)
        for s in out1_list:
            if s in out2_list:
                video_name=s.split(' ')[-1].strip()
                print('copy %s'%(video_name))
                os.system('adb -s %s pull mnt/sdcard/DCIM/Camera/%s ./'%(device_id, video_name))
                outmp=subprocess.check_output(seg).decode('utf-8')
                outmp_list=[l for l in outmp.split('\n') if l[-4:]=='.mp4']
                print('s:', s)
                print('outmp:', outmp_list)
                if s in outmp_list:
                    print('delete %s'%(video_name))
                    os.system('adb -s %s shell rm mnt/sdcard/DCIM/Camera/%s'%(device_id, video_name))

if __name__=='__main__':
    request=sys.argv[1]
    device_name=sys.argv[2]
    if not device_name=='all':
        assert device_name in device_list

    if request=='wake_up':
        op(device_name, 'adb -s %s shell input keyevent 224')
        time.sleep(2)
        op(device_name, 'adb -s %s shell input swipe 300 1000 300 500')
    elif request=='open_camera':
        op(device_name, 'adb -s %s shell am start -a android.media.action.VIDEO_CAPTURE')
    elif request=='start_video':
        op(device_name, 'adb -s %s shell input keyevent 24')
    elif request=='end_video':
        op(device_name, 'adb -s %s shell input keyevent 24')
        time.sleep(2)
        op(device_name, 'adb -s %s shell input keyevent 24')
    elif request=='screen_cap':
        op_sc(device_name, 'adb -s %s exec-out screencap -p > %s.png')
    elif request=='check_video':
        op_check(device_name)
    elif request=='copy_video':
        op_copy(device_name)
    if request=='exception':
        op(device_name, 'adb -s %s shell input keyevent 187')
        time.sleep(2)
        op(device_name, 'adb -s %s shell input swipe 300 1000 300 500')
    time.sleep(1)


#!/usr/bin/env python
"""
Integration test for the 'joint_distance_measurer' node.

"""

import rospy
import unittest
import rostest
import std_msgs.msg
import sensor_msgs.msg
import mcr_manipulation_msgs.msg

PKG = 'mcr_manipulation_measurers'

class TestJointDistanceMeasurer(unittest.TestCase):
    def setUp(self):
        """
        Sets up the test fixture before exercising it.

        """
        # params
        self.result = None
        self.wait_for_result = None

        # publishers
        self.event_out = rospy.Publisher(
            '~event_out', std_msgs.msg.String, latch=True
        )
        self.pub_current_joints = rospy.Publisher(
            '~current_joint_values', sensor_msgs.msg.JointState
        )
        self.pub_target_joints = rospy.Publisher(
            '~target_joint_values', sensor_msgs.msg.JointState
        )

        # subscribers
        self.component_output = rospy.Subscriber(
            '~component_output', mcr_manipulation_msgs.msg.JointDistance,
            self.result_callback
        )

    def tearDown(self):
        """
        Deconstructs the test fixture after testing it.

        """
        self.component_output.unregister()
        self.event_out.unregister()
        self.pub_current_joints.unregister()
        self.pub_target_joints.unregister()

    def test_joint_distance_measurer(self):
        """
        Verifies that the node returns correctly the distances between
        the current and target joint positions.

        """
        current_joints = sensor_msgs.msg.JointState()
        current_joints.name = ['a', 'b', 'c', 'd', 'e', 'f']
        current_joints.position = [0.2, 1.8, 2.4, 0.6, 2.5, 1.7]

        target_joints = sensor_msgs.msg.JointState()
        target_joints.name = ['b', 'd', 'f']
        target_joints.position = [0.2, 1.8, 1.7]

        expected_result = mcr_manipulation_msgs.msg.JointDistance()
        expected_result.distance = [-1.6, 1.2, 0.0]
        expected_result.name = ['b', 'd', 'f']

        while not self.wait_for_result:
            self.pub_target_joints.publish(target_joints)
            self.pub_current_joints.publish(current_joints)
            self.event_out.publish('e_start')

        for i, result in enumerate(self.result.distance):
                self.assertAlmostEqual(result, expected_result.distance[i])

        self.assertEqual(self.result.name, expected_result.name)

    def result_callback(self, msg):
        self.result = msg
        self.wait_for_result = True

if __name__ == '__main__':
    rospy.init_node('joint_distance_measurer_test')
    rostest.rosrun(PKG, 'joint_distance_measurer_test', TestJointDistanceMeasurer)


class Author:
    def __init__(self, name):
        self.name = name
        self.books = []

    def publish(self, title):
        if self.books.__contains__(title): #searches list for identical items
            print(f'The list of published books already contains "{title}"')
        else:
            self.books.append(title)

    def __str__(self):
        book_list = ', '.join(self.books) or 'No published books'
        return f'Author name: {self.name}. Published books: {book_list}'

wendy = Author('Wendy Dendy')
wendy.publish('The Third Book')

print(wendy)

wendy.publish('The Third Book')


import os
import flaskr
import unittest
import tempfile

class FlaskrTestCase(unittest.TestCase):

    def setUp(self):
        db_fd = tempfile.mkstemp()
        self.db_fd, flaskr.app.config['DATABASE'] = db_fd
        flaskr.app.config['TESTING'] = True
        self.client = flaskr.app.test_client()
        self.app = flaskr.app

    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(flaskr.app.config['DATABASE'])

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


def data_file():
    with open('12_route.txt', "r") as file_input:
        lines = file_input.read().splitlines()
    return lines

def chart(array):
    course = {"N": 0, "S": 0, "E": 0, "W": 0, "F": "E"}
    rose = ["E", "S", "W", "N"]
    test = ["L", "R"]
    for arr in array:
        dire = arr[0]
        num = int(arr[1:])
        if dire in course:
            if dire == "F":
                course[course["F"]] += num
                continue
            course[dire] += num
        if dire in test:
            course["F"] = angleCalc(num, dire, rose)
    north, south, east, west = course.get("N"), course.get("S"), course.get("E"), course.get("W")
    ns = [north, south]
    ew = [east, west]
    ns.sort(reverse=True)
    ew.sort(reverse=True)
    ns = ns[0] - ns[1]
    ew = ew[0] - ew[1]
    return ns, ew

def angleCalc(rotation, change, angle):
    arit = rotation // 90
    if change == "R":
        for ind in range(0, arit):
            x = angle.pop(0)
            angle.append(x)
    if change == "L":
        for ind in range(0, arit):
            x = angle.pop()
            angle.insert(0, x)
    return angle[0]

routing = chart(data_file())
print(routing[0] + routing[1])


import math
import cmath

def bit_reverse_copy(array):
    n = len(array)
    result_array = [0] * n

    for i in range(n):
        number = bin(i)[2:]
        number = ('0' * (int(math.log(n, 2)) - len(number))) + number
        result_array[i] = array[int(number[::-1], 2)]

    return result_array

def iter_fft(array):
    array = bit_reverse_copy(array)

    n = len(array)
    for s in range(1, int(math.log(n, 2)) + 1):
        m = 2 ** s
        omega_m = cmath.exp((2 * math.pi * 1j) / m)
        omega = 1

        for j in range(0, m // 2):
            for k in range(j, n, m):
                t = omega * array[k + m // 2]
                u = array[k]
                array[k] = u + t
                array[k + m // 2] = u - t

            omega = omega * omega_m

    return array


import sys

sys.stdin = open("input.txt", "r")

INF = int(1e9)
answer = INF
graph = [[INF] * (n + 1) for _ in range(n + 1)]

n, m = map(int, sys.stdin.readline().split())
for _ in range(m):
    a, b, c = map(int, sys.stdin.readline().split())
    graph[a][b] = c

# 2차원 리스트, 초기화
graph = [[INF] * ( n + 1) for _ in range(n + 1)]

# (출발지 == 도착지) = 0
for a in range(1, n + 1):
    for b in range(1, n + 1):
        if a == b:
            graph[a][b] = 0

for k in range(1, n + 1):
    for a in range(1, n + 1):
        for b in range(1, n + 1):

            # a -> b, a -> k -> b 비교
            if graph[a][k] + graph[k][b] < graph[a][b]:
                graph[a][b] = graph[a][k] + graph[k][b]

for a in range(1, n + 1):
    # 출발지와 도착지가 동일
    answer = min(answer, graph[a][a])

if answer == INF:
    print(-1)
else:
    print(answer)

# # 갈 수 없는 경우
# if graph[a][b] == INF:
#     # print(-1)
#     continue

# else:
#     print(graph[a][b])

# V, E = map(int, input().split())
# #거리를 저장할 matrix
# matrix = [[int(1e9)] * (V+1) for _ in range(V+1)]
# for _ in range(E):
#     x, y, c = map(int, input().split())
#     matrix[x][y] = c

# #경유지 k, 출발지 i, 도착지 j 로 3중 for문을 돌면서
# for k in range(1, V+1):
#     for i in range(1, V+1):
#         for j in range(1, V+1):
#             # i->j 가 빠른지 i->k->j가 빠른지를 검사한다.
#             if matrix[i][k] + matrix[k][j] < matrix[i][j]:
#                 matrix[i][j] = matrix[i][k] + matrix[k][j]

# answer = 1e9
# for i in range(1, V+1):
#    #사이클은 결국 출발지와 도착지가 같은 경우이므로 i->i를 확인
#     answer = min(answer, matrix[i][i])

# #최소값이 없으면 -1, 있으면 최소값을 출력
# if answer == 1e9:
#     print(-1)
# else:
#     print(answer)


import os
import json
import random

#os.system('clear')
directorios = [
    './categorias/ciencias',
    './categorias/entretenimiento',
    './categorias/finanzas',
    './categorias/salud',
    './categorias/tecnologia'
]

def obtener_carpetas(directorio):
    try:
        elementos = os.listdir(directorio)
        carpetas = [os.path.join(directorio, elemento).replace('.', '') for elemento in elementos if os.path.isdir(os.path.join(directorio, elemento)) and elemento != '__pycache__']
        return carpetas
    except OSError as e:
        print(f"[Barlow (ERROR); Error al acceder a la ruta {directorio}. {e}]")
        return []

diccionario_carpetas = {}
for i, directorio in enumerate(directorios, start=1):
    carpetas = obtener_carpetas(directorio)
    clave = f'cat{i}'
    carpetas_aleatorias = random.sample(carpetas, len(carpetas))
    diccionario_carpetas[clave] = carpetas_aleatorias

with open('./categorias/logs.json', 'w', encoding='utf-8') as archivo:
    json.dump(diccionario_carpetas, archivo, ensure_ascii=False)
print("[Barlow; Fichero 'logs.json' creado correctamente].")


import numpy as np
import torch
from scipy import io as sio
import binvox_rw
import matplotlib.pyplot as plt
from PIL import Image
import projtransform
import numpy
from stl import mesh

def cuboid3D_to_unitbox3D(cub3D):
    device = cub3D.device
    dst = torch.tensor(
        [[-1.0, -1.0], [1.0, -1.0], [-1.0, 1.0], [1.0, 1.0]], device=device, dtype=torch.float32
    )
    dst = dst.view(1, 4, 2).expand(cub3D.shape[0], -1, -1)
    # for (x,z) plane
    txz = projtransform.ProjectiveTransform()
    src = torch.stack(
        [
            torch.stack([cub3D[:, 0, 0], cub3D[:, 4, 0]], dim=1),
            torch.stack([cub3D[:, 0, 1], cub3D[:, 4, 0]], dim=1),
            torch.stack([cub3D[:, 2, 0], cub3D[:, 4, 1]], dim=1),
            torch.stack([cub3D[:, 2, 1], cub3D[:, 4, 1]], dim=1),
        ],
        dim=1,
    )
    if not txz.estimate(src, dst):
        raise ValueError("Estimate failed")
    # for (y,z) plane
    tyz = projtransform.ProjectiveTransform()
    src = torch.stack(
        [
            torch.stack([cub3D[:, 1, 0], cub3D[:, 4, 0]], dim=1),
            torch.stack([cub3D[:, 1, 1], cub3D[:, 4, 0]], dim=1),
            torch.stack([cub3D[:, 3, 0], cub3D[:, 4, 1]], dim=1),
            torch.stack([cub3D[:, 3, 1], cub3D[:, 4, 1]], dim=1),
        ],
        dim=1,
    )
    if not tyz.estimate(src, dst):
        raise ValueError("Estimate failed")
    return txz, tyz

def box2D_to_cuboid3D(zranges, Ks, boxes, im_sizes):
    device = boxes.device

    if boxes.shape[0] != Ks.shape[0] != zranges.shape[0]:
        raise ValueError("Ks, boxes and zranges must have the same batch dimension")
    if zranges.shape[1] != 2:
        raise ValueError("zrange must have two entries per example")
    w, h = im_sizes.t()
    sx, px, py = Ks.t()
    sy = sx
    x1, y1, x2, y2 = boxes.t()
    # transform 2d box from image coordinates to world coordinates
    x1 = w - 1 - x1 - px
    y1 = h - 1 - y1 - py
    x2 = w - 1 - x2 - px
    y2 = h - 1 - y2 - py

    cub3D = torch.zeros((boxes.shape[0], 5, 2), device=device, dtype=torch.float32)
    for i in range(2):
        z = zranges[:, i]
        x3D_min = x2 * z / sx
        x3D_max = x1 * z / sx
        y3D_min = y2 * z / sy
        y3D_max = y1 * z / sy
        cub3D[:, i * 2 + 0, 0] = x3D_min
        cub3D[:, i * 2 + 0, 1] = x3D_max
        cub3D[:, i * 2 + 1, 0] = y3D_min
        cub3D[:, i * 2 + 1, 1] = y3D_max
    cub3D[:, 4, 0] = zranges[:, 0]
    cub3D[:, 4, 1] = zranges[:, 1]
    return cub3D

def transform_verts(verts, R, t):
    """
    Transforms verts with rotation R and translation t
    Inputs:
        - verts (tensor): of shape (N, 3)
        - R (tensor): of shape (3, 3) or None
        - t (tensor): of shape (3,) or None
    Outputs:
        - rotated_verts (tensor): of shape (N, 3)
    """

    rot_verts = verts.clone().t()

    if R is not None:
       # R[0][2] *= -1
       # R[1][2] *= -1
       # R[2][2] *= -1

        assert R.dim() == 2
        assert R.size(0) == 3 and R.size(1) == 3
        rot_verts = torch.mm(R, rot_verts)

    if t is not None:
        assert t.dim() == 1
        assert t.size(0) == 3
        rot_verts = rot_verts + t.unsqueeze(1)

    rot_verts = rot_verts.t()

    return rot_verts

def read_voxel(voxelfile):
    """
    Reads voxel and transforms it in the form of verts
    """
    #voxel = sio.loadmat(voxelfile)["voxel"]

    #print("DEBUGGING READ_VOXEL FROM SHAPE.PY")

    with open(voxelfile, 'rb') as f:
            voxel = binvox_rw.read_as_3d_array(f)

    #print("voxel dimensions: ", voxel.dims)

    voxel = voxel.data
    voxel = np.array( voxel > 0, dtype=int)
    #print("voxel dimensions after np.array(voxel > 0): ", voxel.shape)

    #voxel = np.rot90(voxel, k=3, axes=(1, 2))
    #print("voxel dimensions after np.rot90: ", voxel.shape)

    verts = np.argwhere(voxel > 0).astype(np.float32, copy=False)
    #print("verts after np.argwhere(voxel > 0: ",verts.shape)

    # centering and normalization

    #normalize pixel values
    min_x = np.min(verts[:, 0])
    max_x = np.max(verts[:, 0])
    min_y = np.min(verts[:, 1])
    max_y = np.max(verts[:, 1])
    min_z = np.min(verts[:, 2])
    max_z = np.max(verts[:, 2])

    #centralize pixel values
    verts[:, 0] = verts[:, 0] - (max_x + min_x) / 2
    verts[:, 1] = verts[:, 1] - (max_y + min_y) / 2
    verts[:, 2] = verts[:, 2] - (max_z + min_z) / 2
    scale = np.sqrt(np.max(np.sum(verts ** 2, axis=1))) * 2
    verts /= scale

    verts = torch.tensor(verts, dtype=torch.float32)
    #print("verts final: ", verts.size())

    #print("-- END -- DEBUGGING READ_VOXEL FROM SHAPE.PY")

    return verts


"""Standardized layouts."""

# local
from pyiem.plot.use_agg import plt
from pyiem.plot.util import draw_logo, fitbox, update_kwargs_apctx
from pyiem.reference import TWITTER_RESOLUTION_INCH

@update_kwargs_apctx
def figure(logo="iem", title=None, subtitle=None, **kwargs):
    """Return an opinionated matplotlib figure.

    Parameters:
      figsize (width, height): in inches for the figure, defaults to something
        good for twitter.
      dpi (int): dots per inch
      logo (str): Currently, 'iem', 'dep' is supported. `None` disables.
      title (str): Title to place on the figure.
      subtitle (str): SubTitle to place on the figure.
      apctx (dict, optional): autoplot context.
      fig (matplotlib.figure.Figure): Figure passed in for modification for
        figsize only currently.
    """
    kwargs.pop("apctx", None)
    kwargs["figsize"] = kwargs.get("figsize", TWITTER_RESOLUTION_INCH)
    fig = kwargs.pop("fig", None)
    if fig is None:
        fig = plt.figure(**kwargs)
    else:
        fig.set_size_inches(kwargs["figsize"])
    draw_logo(fig, logo)
    titlebounds = [0.1, 0.98, 0.91, 0.98]
    if subtitle is not None:
        titlebounds[2] = 0.94
    fitbox(fig, title, *titlebounds)
    fitbox(fig, subtitle, 0.1, 0.98, 0.91, 0.935)
    return fig

def figure_axes(logo="iem", title=None, subtitle=None, **kwargs):
    """Return an opinionated matplotlib figure and one axes.

    Parameters:
      figsize (width, height): in inches for the figure, defaults to something
        good for twitter.
      dpi (int): dots per inch
      logo (str): Currently, 'iem', 'dep' is supported. `None` disables.
      title (str): Title to place on the figure.
      subtitle (str): SubTitle to place on the figure.
    """
    fig = figure(logo=logo, title=title, subtitle=subtitle, **kwargs)
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    return fig, ax


n, t = [int(_) for _ in input().split()]
ppl = [[int(_) for _ in input().split()] for i in range(n)]

ppl.sort(key = lambda x: (-x[0], x[1]))

money = 0
busy = [False] * t
for i in range(n):
    for j in range(ppl[i][1], -1, -1):
        if not busy[j]:
            money += ppl[i][0]
            busy[j] = True
            break
print(money)


from card import Card
from suit import Suit
from random import shuffle
from player import Player
from init_ai import init_AI
from second_ai import second_AI
from team import Team
from comp import Comp
from termcolor import colored

import random

game_run = True
match_run = True
# human = Player(1)
human = second_AI(1,0, 1)
teammate = second_AI(1, 1, 0)
opponent_1 = second_AI(2, 2, 3)
opponent_2 = second_AI(2, 3, 2)
team1 = Team(human, teammate)
team2 = Team(opponent_1, opponent_2)

list_of_players_1 = [human, opponent_1, teammate, opponent_2]
list_of_players_2 = [opponent_1, teammate, opponent_2, human]
list_of_players_3 = [teammate, opponent_2, human, opponent_1]
list_of_players_4 = [opponent_2, human, opponent_1, teammate, ]
# the order if the player at each position wins, this is with the player and teammate being at
# posistion 0 and 1
iteration_of_players = {
    0: list_of_players_1,
    1: list_of_players_3,
    2: list_of_players_2,
    3: list_of_players_4

}

# cards on table is a dic that keeps the cards in a specific order,
# 0 is the player, 1 is the teammate, 2 and 3 or the opponents cards.
cards_on_table = {
    0: Card(Suit.NONE, -1),
    1: Card(Suit.NONE, -1),
    2: Card(Suit.NONE, -1),
    3: Card(Suit.NONE, -1)
}
inital_suit = Suit.HEART

def __init_deck():
    deck = list()
    for i in range(2, 15):
        deck.append(Card(Suit.HEART, i))
        deck.append(Card(Suit.DIAMOND, i))
        deck.append(Card(Suit.SPADE, i))
        deck.append(Card(Suit.CLUB, i))

    return deck

def shuffle_cards(current_deck):
    for i in range(random.randint(1, 10)):
        shuffle(current_deck)
        return current_deck

def deal_5(deck):
    five_cards = list()
    for i in range(5):
        five_cards.append(deck.pop())
    return five_cards

def deal_4(deck):
    four_cards = list()
    for i in range(4):
        four_cards.append(deck.pop())
    return four_cards

def shift_list(winning_pos):
    if winning_pos == 0:
        return 0
    elif winning_pos == 1:
        return -1
    elif winning_pos == 2:
        return -2
    return 1

deck = __init_deck()
current_cards = shuffle_cards(deck)

# pick the first hawkhem(the first king)
index_of_king = random.randint(0, 3)
index_of_starter = index_of_king
first = True
comp = Comp()
while match_run:

    for player in iteration_of_players[index_of_king]:
        player.add_cards(deal_5(current_cards))
        if first:
            comp.set_hokm(player.select_hokm())
            print('Hokm is {0}'.format(comp.hokm))
            first = False

    # break
    for player in iteration_of_players[index_of_king]:
        player.hokm = comp.hokm

    for i in range(2):
        for player in iteration_of_players[index_of_king]:
            player.add_cards(deal_4(current_cards))

    # print(teammate.play_card(None, None, -1))
    # for player in iteration_of_players[index_of_king]:
    #      print(player.player_number, '   ', player.hand)
    # break
    while game_run:
        for player in iteration_of_players[index_of_starter]:
            comp.set_and_comp(player.player_number,
                              player.play_card(comp.initial_suit, comp.switcher_2, comp.high_card_index))

        index_of_starter = comp.high_card_index

        comp.print_cards()
        # allow AI to know which cards have been played.
        for player in iteration_of_players[index_of_starter]:
            player.update_cards_played(comp.switcher_2, comp.initial_suit)

        if comp.high_card_index < 2:

            team1.hands_won = team1.hands_won + 1
            print(colored('Team1 won the hand', 'cyan'))
            string1 = '\nteam 1 has {0} points team2 has {1} points\n'.format(team1.hands_won, team2.hands_won)
            print(colored(string1, 'red'))
            if team1.hands_won == 7:
                team1.games_won = team1.games_won + 1

                string1 = 'End of Game team 1 won {0} games and team 2 won {1}'.format(team1.games_won,
                                                                                team2.games_won)
                print(colored(string1, 'magenta', attrs=['bold', 'dark']))
                team1.hands_won = 0
                team2.hands_won = 0
                if index_of_king > 1:
                    index_of_king = (index_of_king - 1) % 2
                comp.new_game_reset()
                break
        else:

            team2.hands_won = team2.hands_won + 1
            print(colored('Team2 won the hand', 'yellow'))
            string1 = '\nTeam1 has {0} points Team2 has {1} points\n'.format(team1.hands_won, team2.hands_won)
            print(colored(string1, 'red'))
            if team2.hands_won == 7:
                team2.games_won = team2.games_won + 1

                string1 = 'End of Game team 1 won {0} games and team 2 won {1}'.format(team1.games_won,
                                                                                team2.games_won)
                print(colored(string1, 'magenta', attrs=['bold', 'dark']))
                team1.hands_won = 0
                team2.hands_won = 0
                if index_of_king < 1:
                    index_of_king = index_of_king + 2
                comp.new_game_reset()
                break
        comp.after_hand_reset()

    index_of_starter = index_of_king
    first = True
    current_cards = shuffle_cards(__init_deck())
    for player in iteration_of_players[index_of_starter]:
        player.reset_hand()

    if team1.games_won == 7 or team2.games_won == 7:
        string1 = 'End of Match team 1 won {0} games and team 2 won {1}'.format(team1.games_won, team2.games_won)
        print(colored(string1, 'magenta', attrs=['bold', 'dark']))
        break


import sys,pygame

# from pygame. locals import *
pygame.init()
screen_info = pygame.display.Info()
# set the width and height to the size of screen
size = (width, height) = ((int(screen_info.current_w), int(screen_info.current_h)))
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
color = (110, 170, 255)

fish_image = pygame.image.load("fish.png")
fish_image = pygame.transform.smoothscale(fish_image,(280, 160))

fish_rect = fish_image.get_rect()

fish_rect.center = (width//2, height//2)

speed=pygame.math.Vector2(0,0)

def movefish():
    global color
    global fish_image
    size = (width, hight) = (int(screen_info.current_w), int(screen_info.current_h))
    fish_rect.move_ip(speed)

    fish_rect.left < 0
    fish_rect.right
    fish_rect.top

    if fish_rect.bottom > height:
        speed[1] *= -1

        color = (255,125, 20)
    if fish_rect.top < (0):
        speed[1] *= -1
        color = (255, 120, 120)
    if fish_rect.right > width:
        speed[0] *= -1
        color = (0,255, 120)
        fish_image = pygame.transform.flip(fish_image, True, False)
    if fish_rect.left < (0):
        speed[0] *= -1
        color = (110, 170, 255)
        fish_image = pygame.transform.flip(fish_image, True, False)
def main():

    while True:

        global speed
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit()
                main = fales

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT or event.key == ord('a'):
                    print ('left')
                    speed[0] =(-2)
                if event.key == pygame.K_RIGHT or event.key == ord('d'):
                    print ('right')
                    speed[0] =(2)
                if event.key == pygame.K_UP or event.key == ord('w'):
                    print ('jump')
                    speed[1] =(-2)
                if event.key == pygame.K_DOWN or event.key == ord('s'):
                    print ('down')
                    speed[1] =(2)
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == ord('a'):
                    print('left stop')
                    speed[0] = (0)
                if event.key == pygame.K_RIGHT or event.key == ord('d'):
                    print('right stop')
                    speed[0] = (0)
                if event.key == pygame.K_UP or event.key == ord('w'):
                    print('up stop')
                    speed[1] = (0)
                if event.key == pygame.K_DOWN or event.key == ord('s'):
                    print('down stop')
                    speed[1] = (0)

        clock.tick(60)
        movefish()
        screen.fill(color)
        screen.blit(fish_image,fish_rect)
        pygame.display .flip()

if __name__ == '__main__':
    main()


from parseStr import *
from booleanNetwork import *

import numpy as np
from copy import copy

def hammingDistance(pat0, pat1):
	return (pat0 != pat1).sum()

class Evaluator(object):
	def __init__(self, patterns):
		self.setPatterns(patterns)
		self.patternMutProb = 0.15
		self.patternEvals = len(patterns[0])
		self.fitnessPower = 5

	def setPatterns(self, patterns):
		self.patterns = map(np.array, patterns)

	def evaluateNetwork(self, genotype):
		networkConnections = parse2d(genotype)
		size = len(networkConnections)
		self.network = BooleanNetwork(networkConnections, np.zeros(size))
		netScore = 0.0
		for pat in self.patterns:
			netScore += self.evaluateNetworkWithPattern(pat)
		netScore /= len(self.patterns)
		return netScore

	def evaluateNetworkWithPattern(self, pattern):
		score = 0.0
		for i in xrange(self.patternEvals):
			testPat = self.perturbedPattern(pattern, i)
			self.network.setState(testPat)
#			print('Evaluated network ' + str(self.network.con) + ' with pattern ' + str(testPat))
			if self.network.findAttractor(attractorMaxTrials=20):
				score += np.power(1.0 - float(hammingDistance(pattern, self.network.attractor))/float(len(pattern)), self.fitnessPower)
#				print('Attractor found (' + str(self.network.attractor)+ '), Hamming distance to ' + str(pattern) + ' is ' + str(hammingDistance(pattern, self.network.attractor)))
		score /= self.patternEvals
#		print('Evaluated network ' + str(self.network.con) + ' with pattern ' + str(pattern) + ' (' + str(self.patternEvals) + ' evaluations made, score ' + str(-1.0*np.expm1(-3.0*score)) + ')')
		return -1.0*np.expm1(-3.0*score)

	def mutatedPattern(self, pattern):
		mutPattern = copy(pattern)
		size = len(pattern)
		for i in xrange(size):
			if np.random.rand() < self.patternMutProb:
				mutPattern[i] = 1 if mutPattern[i] == -1 else -1
		return mutPattern

	def perturbedPattern(self, pattern, position):
		perPattern = copy(pattern)
		perPattern[position] = 1 if perPattern[position] == -1 else -1
		return perPattern


import torch
from torch import nn  # 神经网路蝉蛹

# from torch import functional as F  # 旧版
from torch.nn import functional as F  # 常用函数
from torch import optim  # 优化工具包
import torchvision  # 视觉
from matplotlib import pyplot as plt
from utils import plot_image, plot_curve, one_hot

# 1. 加载数据集, 通过touchvision工具包直接下载, 并行读取多张图片. 这里的图片是28x28
# 70k图片是用来训练,
batch_size = 512
train_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST(
        "data/mnist_data",
        train=True,
        download=True,
        transform=torchvision.transforms.Compose(
            [
                torchvision.transforms.ToTensor(),
                # 数据下载以后不是一个正态分布, 可以使用这个来进行正态分布, 主要影响的是性能, 其他的都不变
                torchvision.transforms.Normalize((0.1307,), (0.3081,)),
            ]
        ),
    ),
    batch_size=batch_size,  # 每次训练加载多少张图片
    shuffle=True,
)

test_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST(
        "data/mnist_data/",
        train=False,
        download=True,
        transform=torchvision.transforms.Compose(
            [
                torchvision.transforms.ToTensor(),
                torchvision.transforms.Normalize((0.1307,), (0.3081,)),
            ]
        ),
    ),
    batch_size=batch_size,
    shuffle=False,
)

# 显示图片
x, y = next(iter(test_loader))
# 如果不添加Normalize, 会均匀地分布在0-1之间, 而现在就变换成了这样, 是的数据在0附近
# torch.Size([512, 1, 28, 28]) torch.Size([512]) tensor(-0.4242) tensor(2.8215)
print(x.shape, y.shape, x.min(), x.max())
# plot_image(x, y, "image sample")  # 打印数据

###
# 创建网络
###
class Net(nn.Module):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        ## 新建三层, 每一层wx+b
        self.fc1 = nn.Linear(28 * 28, 256)  # 输入28*28, 输出256
        self.fc2 = nn.Linear(256, 64)
        self.fc3 = nn.Linear(64, 10)  # 输出层

    ## 定义一个计算过程, 输入包含x
    def forward(self, x):
        # x: [b, 1, 28, 28]
        # h1 = relu(wx+b)
        x = F.relu(self.fc1(x))
        # h2 = relu(h1w2+b2)
        x = F.relu(self.fc2(x))
        # h3 = h2w3+b3  暂时不加激活函数
        x = self.fc3(x)
        return x

net = Net()

# net.parameters() 当中包含的就是 [w1,b1,w2,b2,w3,b3]
# Momentum: SGD 在 ravines 的情况下容易被困住， ravines 就是曲面的一个方向比另一个方向更陡，
# 这时 SGD 会发生震荡而迟迟不能接近极小值
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)

train_loss = []
## 测试/训练
# 训练三遍
for epoch in range(3):
    # 对内部层数迭代一次, 每一次迭代拿到一个batch512个文件
    for batch_inx, (x, y) in enumerate(train_loader):
        # print(x.shape, y.shape)  # torch.Size([512, 1, 28, 28]) torch.Size([512])
        # 将向量flattern平铺拉伸
        x = x.view(x.size(0), 28 * 28)  # => [b, 10]
        out = net(x)
        # 将y转换为Onehot
        y_onehot = one_hot(y)
        # print(y_onehot.shape) # torch.Size([512, 10])
        loss = F.mse_loss(out, y_onehot)  # 计算mse

        # 清零梯度, grad = 0, 否则的话grad就会加载上一次grad的总和上
        optimizer.zero_grad()
        loss.backward()
        # 更新梯度 w' = w - lr*grad
        optimizer.step()

        train_loss.append(loss.item())
        if batch_inx % 10 == 0:
            print(epoch, batch_inx, loss.item())
    """ end batch """
""" end epoch """

# 获得了[w1, b1, w2, b2, w3, b3]
# plot_curve(train_loss) # 打印训练的loss值

# 我们观察一下测试
total_correct = 0
for x, y in test_loader:
    x = x.view(x.size(0), 28 * 28)
    out = net(x)
    # out: [512, 10] => pred: [b]
    pred = out.argmax(dim=1)
    correct = pred.eq(y).sum().float()
    total_correct += correct

# 获取所有数据集的数量
total_num = len(test_loader.dataset)
acc = total_correct / total_num
print("================================")
print("acc:{}".format(acc))  # acc:0.6884999871253967
print("================================")

# 我们对之前的sample进行预测
x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28 * 28))
pred = out.argmax(dim=1)
plot_image(x, pred, "test")


from utils import *
from pprint import pprint

# Input:
# [M] [H]         [N]
# [S] [W]         [F]     [W] [V]
# [J] [J]         [B]     [S] [B] [F]
# [L] [F] [G]     [C]     [L] [N] [N]
# [V] [Z] [D]     [P] [W] [G] [F] [Z]
# [F] [D] [C] [S] [W] [M] [N] [H] [H]
# [N] [N] [R] [B] [Z] [R] [T] [T] [M]
# [R] [P] [W] [N] [M] [P] [R] [Q] [L]
#  1   2   3   4   5   6   7   8   9

stacks = [
    ['R', 'N', 'F', 'V', 'L', 'J', 'S', 'M'],
    ['P', 'N', 'D', 'Z', 'F', 'J', 'W', 'H'],
    ['W', 'R', 'C', 'D', 'G'],
    ['N', 'B', 'S'],
    ['M', 'Z', 'W', 'P', 'C', 'B', 'F', 'N'],
    ['P', 'R', 'M', 'W'],
    ['R', 'T', 'N', 'G', 'L', 'S', 'W'],
    ['Q', 'T', 'H', 'F', 'N', 'B', 'V'],
    ['L', 'M', 'H', 'Z', 'N', 'F']
  ]

steps = []

for line in splitFile("day_05_input.txt", "\n"):
    elements = splitString(line, " ")
    steps.append(
        [int(elements[1]), int(elements[3])-1, int(elements[5])-1]
    )

for step in steps:
    targetStack = stacks[step[1]]
    rangeToModify = slice(len(targetStack) - step[0], len(targetStack))
    stacks[step[2]].extend(targetStack[rangeToModify])
    del targetStack[rangeToModify]

    # for i in range(0, step[0]):
    #     stacks[step[2]].append(stacks[step[1]].pop())

pprint(stacks)

result = ''
for stack in stacks:
    result += stack.pop()
print(result)


import cv2 as cv
import numpy as np
import math

areaVal1 = 10000
areaVal2 = 250
negVal1 = -10000

def calcCentroid(contoursList, numContours):

    if numContours == 2:
        contours = contoursList[0]
        contours2 = contoursList[1]

        cx, cy, cx2, cy2, xL, yL, xR, yR = twoCentroid(contours, contours2)
    #else:
        #implement to only calculate one centroid

def twoCentroid(contours, contours2):
    cx, cy = areaVal1, areaVal2
    xL, yL = areaVal1, areaVal2
    cx2, cy2 = negVal1, areaVal2
    xR, yR = negVal1, areaVal2

    if len(contours) > 0:
            #outputs a dictionary of all moments calculated like area, centroid, etc
            M, maxcontour = findMoments(contours)
            #calculate centroid
            cx, xL, cy, yL = centroidCoords(M, maxcontour, False)

    if len(contours2) > 0:
        #outputs a dictionary of all moments calculated like area, centroid, etc
        M, maxcontour = findMoments(contours2)
        #calculate centroid
        cx2, xR, cy2, yR = centroidCoords(M, maxcontour, True)

    return cx, cy, cx2, cy2, xL, yL, xR, yR

def findMoments(contours):
    maxcontour = max(contours, key = cv.contourArea)
    return cv.moments(maxcontour), maxcontour

def centroidCoords(M, maxcontour, neg):
    if M['m00'] > 0 and cv.contourArea(maxcontour) > 100:
        #calculation of centroid
        cx = int(M['m10'] / M['m00'])
        x = int(M['m10'] / M['m00'])
        cy = int(M['m01'] / M['m00'])
        y = int(M['m01'] / M['m00'])
    else:
        if neg == False:
            cx, cy = areaVal1, areaVal2
            x, y = areaVal1, areaVal2
        else:
            cx, cy = negVal1, areaVal2
            x, y = negVal1, areaVal2

    return cx, x, cy, y


from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from litner.models import LitnerModel, LitnerKarNameModel, LitnerKarNameDBModel
from litner.serializer import LitnerSerializer, LitnerDetailSerializer, LitnerTakeExamSerializer

class LitnerListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, pk=None):
        if pk is None:
            try:
                leitners = LitnerModel.objects.all()
                serializer = LitnerSerializer(leitners, many=True)
                return Response({'data': serializer.data}, status.HTTP_200_OK)
            except Exception as ins:
                return Response({'message': str(ins)},status.HTTP_404_NOT_FOUND)
        else:
            try:
                leitners = LitnerModel.objects.get(pk=pk)
                serializer = LitnerDetailSerializer(leitners)
                serializer = LitnerDetailSerializer(leitners)
                return Response({'data': serializer.data}, status.HTTP_200_OK)
            except Exception as ins:
                return Response({'message': 'Leitner notFound'}, status.HTTP_404_NOT_FOUND)

    def post(self, request, pk):

        exam = get_object_or_404(LitnerModel, pk=pk)
        try:
            exam.is_open = True
            karname = LitnerKarNameModel.objects.get(user=request.user, exam_id=exam)
            answers = LitnerKarNameDBModel.objects.filter(karname=karname)
            is_corrects = []
            is_false = []
            is_null = []
            print(answers)
            for answer in answers:
                if not answer.is_correct is None:
                    if answer.is_correct == True:
                        is_corrects.append(
                            {
                                'question_id': answer.question.id,
                                # 'question_text': answer.question.question_text,
                                # 'answer_text': answer.answerss
                            })
                    else:
                        if answer.is_correct == False:
                            is_false.append({
                                'question_id': answer.question.id,
                                # 'question_text': answer.question.question_text,
                                # 'answer_text': answer.answerss
                            })
                else:
                    is_null.append({
                        'question_id': answer.question.id,
                        # 'question_text': answer.question.question_text,
                        # 'answer_text': answer.answerss
                    })
            result = {
                'True answers': is_corrects,
                'False answers': is_false,
                'None answers': is_null
            }
            exam.save()
            return Response(result)

        except:
            # just questions that have answer
            # [
            #     {
            #         "question": 1,
            #         "is_correct": true or false
            #     }
            # ]
            data = {'user': request.user.id, "exam_id": pk}
            if request.data:
                data['karname'] = request.data
            else:
                data['karname'] = []
            serializer = LitnerTakeExamSerializer(data=data, context={'request': request, 'exam': pk})
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status.HTTP_200_OK)
            else:
                return Response(serializer.errors, status.HTTP_404_NOT_FOUND)

    def put(self, request, pk):
        # request.data example: you should send new questions and their choices
        # [
        #     {
        #         "question":1,    #our questuin
        #         "choice":2      #client's answer
        #     },
        #     ...
        # ]
        data = {'user': request.user.id, "exam_id": pk}
        if request.data:
            data['karname'] = request.data
        else:
            data['karname'] = []
        exam = get_object_or_404(LitnerModel, pk=pk)
        karname = get_object_or_404(LitnerKarNameModel, user=request.user, exam_id=exam)
        serializer = LitnerTakeExamSerializer(instance=karname, data=data, context={'request': request, 'exam': pk},
                                              partial=True)
        if serializer.is_valid():
            try:
                serializer.save()
            except Exception:
                return Response(serializer.errors, status.HTTP_404_NOT_FOUND)
        else:
            return Response(serializer.errors, status.HTTP_404_NOT_FOUND)
        return Response(serializer.data)

class LitnerView(APIView):
    permission_classes = [IsAdminUser]

    def post(self, request):
        data = LitnerDetailSerializer(data=request.data)
        data.is_valid(raise_exception=True)
        data.save()
        return Response(data.data)

    def delete(self, request, pk):
        try:
            instance = LitnerModel.objects.get(pk=pk)
            instance.delete()
            return Response({"massage": "leitner remove successfully"}, status.HTTP_204_NO_CONTENT)
        except Exception:
            return Response(
                {"massage": "leitner not found"}, status.HTTP_404_NOT_FOUND)

    def put(self, request):
        pass

# a = {
#     'exam': 1,
#     'user': 20,
#     'answer': [
#         {
#             "id_question": 5,
#             "choice": None  # null
#         }
#     ],
#     # 'true_answer': [
#     #     {
#     #         "question_text": "سوال اول آزمون ریاضی که بود؟",
#     #         "answers_text": "رضا"
#     #     },
#     #     {
#     #         "question_text": "سوال 2 آزمون مامایی که بود؟",
#     #         "answers_text": "احمد"
#     #     },
#     #     {
#     #         "question_text": "سوال اول آزمون عربی که بود؟",
#     #         "answers_text": "علی"
#     #     },
#     # ],
#     # 'no_answer': [
#     #     {
#     #         "question_text": "امیر نمره ریاضیش چند بود؟",
#     #         "answers_text": "10"
#     #     },
#     #     {
#     #         "question_text": "سوال 2 آزمون مامایی که بود؟",
#     #         "answers_text": "احمد"
#     #     },
#     #     {
#     #         "question_text": "سوال اول آزمون عربی که بود؟",
#     #         "answers_text": "علی"
#     #     },
#     # ],
#     # 'false_answer': [
#     #     {
#     #         "question_text": "سوال اول آزمون ریاضی که بود؟",
#     #         "answers_text": "رضا"
#     #     },
#     #     {
#     #         "question_text": "سوال 2 آزمون مامایی که بود؟",
#     #         "answers_text": "احمد"
#     #     },
#     #     {
#     #         "question_text": "سوال اول آزمون عربی که بود؟",
#     #         "answers_text": "علی"
#     #     },
#     # ],
# }


from django.contrib import admin
from .models import TextField

# Register your models here.

class TextFieldAdmin(admin.ModelAdmin):
    list_display=(
        'name',
        'about_title',
        'about_blurb'
    )

    ordering = (
        'name',
    )

admin.site.register(TextField, TextFieldAdmin)


#!/usr/bin/env python3
# By Guy Serbin, EOanalytics Ltd.
# Talent Garden Dublin, Claremont Ave. Glasnevin, Dublin 11, Ireland
# email: guyserbin <at> eoanalytics <dot> ie

# Irish Earth Observation (IEO) Python Module
# version 1.5

# This script creates VRTs from ingested Landsat data and catalogue files

import os, sys, glob, datetime, argparse#, ieo
from subprocess import Popen
from osgeo import ogr

try: # This is included as the module may not properly install in Anaconda.
    import ieo
except:
    ieodir = os.getenv('IEO_INSTALLDIR')
    if not ieodir:
        print('Error: IEO failed to load. Please input the location of the directory containing the IEO installation files.')
        ieodir = input('IEO installation path: ')
    if os.path.isfile(os.path.join(ieodir, 'ieo.py')):
        sys.path.append(ieodir)
        import ieo
    else:
        print('Error: that is not a valid path for the IEO module. Exiting.')
        sys.exit()

parser = argparse.ArgumentParser('This script creates VRT files for Landsat data.')

parser.add_argument('-i', '--indir', type = str, default = None, help = 'Input directory. If this is set then --nodataval must also be set. Otherwise, default values will be used.')
parser.add_argument('-o', '--outdir', type = str, default = None, help = 'Data output directory.')
parser.add_argument('-y', '--year', type = int, default = None, help = 'Process secenes only for a specific year.')
parser.add_argument('--overwrite', action = "store_true", help = 'Overwrite existing files.')
parser.add_argument('--nodataval', type = int, default = None, help = 'No data value. This must be set if --indir is also set.')
#parser.add_argument('--minrow', type = int, default = 21, help = 'Lowest WRS-2 Row number.')
parser.add_argument('--rowspath', type = int, default = 4, help = 'Max WRS-2 Rows per Path.')
args = parser.parse_args()

# nodatavals = {'SR': '-9999', 'Fmask': '255', 'BT': '-9999', 'NDVI': '0', 'EVI': '0', 'pixel_qa': '1'}
{'SR': '-9999', 'aerosol_qa': '1', 'ST': '-9999', 'NDVI': '0', 'EVI': '0', 'pixel_qa': '1', 'radsat_qa' : '255'}

if args.indir and args.nodataval:
    nodatavals = {os.path.basename(args.indir): args.nodataval}
elif args.indir and not args.nodataval:
    indirs = [args.indir]
    if not os.path.basename(args.indir) in nodatavals.keys():
        args.nodataval = input('Error: --indir set and --nodataval not set. Please input a no data value:')
        nodatavals = {args.indir: args.nodataval}
else:
    indirs = [ieo.srdir, ieo.aerosolqadir, ieo.stdir, ieo.ndvidir, ieo.evidir, ieo.pixelqadir, ieo.radsatqadir]
    nodatavals = {'SR': '-9999', 'aerosol_qa': '1', 'ST': '-9999', 'NDVI': '0', 'EVI': '0', 'pixel_qa': '1', 'radsat_qa' : '255'}

def makefiledict(dirname, year):
    if args.year:
        flist = glob.glob(os.path.join(dirname, 'L*{}*.dat'.format(args.year)))
    else:
        flist = glob.glob(os.path.join(dirname, 'L*.dat'))
    filedict = {}
    if len(flist) >= 2:
        if os.path.basename(flist[0]).find('_') == 3:
            rangerow = [4, 4, 11]
        elif len(os.path.basename(flist[0])) > 40:
            rangerow = [7, 10, 17]
        else:
            rangerow = [6, 9, 16]
        if rangerow[0] != rangerow[1] and len(flist) == 2 and os.path.basename(flist[0])[rangerow[0]:rangerow[1]] == os.path.basename(flist[1])[rangerow[0]:rangerow[1]]:
            filedict = None
            return filedict
        for f in flist:
            basename = os.path.basename(f)
            if not basename[rangerow[1]:rangerow[2]] in filedict.keys():
                filedict[basename[rangerow[1]:rangerow[2]]] = [f]
            elif not f in filedict[basename[rangerow[1]:rangerow[2]]]:
                filedict[basename[rangerow[1]:rangerow[2]]].append(f)
    return filedict

def getpathrows():
    pathrowdict = {'paths': {}, 'rows': []}
    driver = ogr.GetDriverByName("GPKG")
    data_source = driver.Open(ieo.ieogpkg, 0)
    layer = data_source.GetLayer(ieo.WRS2)
    for feature in layer:
        path = feature.GetField('PATH')
        row = feature.GetField('ROW')
        if not path in pathrowdict['paths']:
            pathrowdict['paths'][path] = [row]
        elif not row in pathrowdict['paths'][path]:
            pathrowdict['paths'][path].append(row)
        if not row in pathrowdict['rows']:
            pathrowdict['rows'].append(row)

    data_source = None
    for path in pathrowdict['paths'].keys():
        sorted(pathrowdict['paths'][path])
    sorted(pathrowdict['rows'])

    return pathrowdict

def makevrtfilename(outdir, filelist):
    numscenes = len(filelist)
    basename = os.path.basename(filelist[0]).replace('.dat', '.vrt')
    if basename.find('_') == 3:
        startrow = 0
        endrow = 0
        outbasename = '{}.vrt'.format(basename[:11])
    elif len(basename) < 40:
        startrow = basename[8:9]
        endrow = os.path.basename(filelist[-1])[8:9]
        outbasename = '{}{}{}{}{}'.format(basename[:6], numscenes, startrow, endrow, basename[9:])
    else:
        startrow = basename[9:10]
        endrow = os.path.basename(filelist[-1])[9:10]
        outbasename = '{}{}{}{}{}'.format(basename[:7], numscenes, startrow, endrow, basename[10:])
    vrtfilename = os.path.join(outdir, outbasename)
    return vrtfilename

def writetocsv(catfile, vrt, filelist, d, pathrowdict):
    if os.path.basename(vrt).find('_') == 3:
        minrow = ''
    else:
        minrow = min(pathrowdict['rows'])
    datetuple = datetime.datetime.strptime(d, '%Y%j')
    scenelist = ['None'] * args.rowspath
    for f in filelist:
        if os.path.basename(vrt).find('_') == 3:
            sceneID = os.path.basename(f)[:11]
            i = 0
            path = 0
        elif len(os.path.basename(f)) < 40:
            sceneID = os.path.basename(f)[:21]
            i = int(sceneID[7:9]) - minrow
            path = sceneID[3:6]
        else:
            sceneID = os.path.basename(os.path.basename(f))[:40]
            i = int(sceneID[8:10]) - minrow
            path = sceneID[4:7]
        scenelist[i] = sceneID
    header = 'Date,Year,DOY,Path'
    for x in pathrowdict['rows']:
        header += ',R{:03d}'.format(x)
        header += ',VRT'
    if not os.path.isfile(catfile): # creates catalog file if missing
        with open(catfile, 'w') as output:
            output.write('{}\n'.format(header))
    outline = '{},{},{},{}'.format(datetuple.strftime('%Y-%m-%d'), datetuple.strftime('%Y'), datetuple.strftime('%j'), path)
    for s in scenelist:
        outline += ',{}'.format(s)
    with open(catfile, 'a') as output:
        output.write('{}\n'.format(outline))

def makevrt(filelist, catfile, vrt, d, pathrowdict):
    dirname, basename = os.path.split(vrt)
    print('Now creating VRT: {}'.format(basename))
    proclist = ['gdalbuildvrt', '-srcnodata', nodatavals[os.path.basename(os.path.dirname(filelist[0]))], vrt]
#    scenelist.append(vrt)
    for f in filelist:
        if f:
            proclist.append(f)
#    print(proclist)
    p = Popen(proclist)
    print(p.communicate())
    writetocsv(catfile, vrt, filelist, d, pathrowdict)

today = datetime.datetime.today()
catdir = os.path.join(ieo.catdir, 'Landsat')
pathrowdict = getpathrows()

for indir in indirs:
    print('Now processing files in subdir {}, number {} of {}.'.format(os.path.basename(indir), indirs.index(indir) + 1, len(indirs)))
    if args.outdir:
        vrtdir = args.outdir
    else:
        vrtdir = os.path.join(indir, 'vrt')
    print('New VRTs will be written to: {}'.format(vrtdir))

    if not os.path.isdir(vrtdir):
        os.mkdir(vrtdir)
    catfile = os.path.join(catdir, '{}_vrt.csv'.format(os.path.basename(indir)))
    print('New VRTs created will be logged in: {}'.format(catfile))

    filedict = makefiledict(indir, args.year)
    keylist = sorted(filedict.keys())
    if len(keylist) > 0:
        for key in keylist:
            if len(filedict[key]) > 1:
                filedict[key].sort()
                vrt = makevrtfilename(vrtdir, filedict[key])
                if args.overwrite or not os.path.isfile(vrt):
                    print('Now processing {}, number {} of {}.'.format(os.path.basename(vrt), keylist.index(key) + 1, len(keylist)))
                    makevrt(filedict[key], catfile, vrt, key, pathrowdict)
                else:
                    print('{} exists and no overwrite set, skipping.'.format(os.path.basename(vrt)))
            else:
                print('An insufficient number of scenes for dat {} exist, skipping.'.format(key))

print('Processing complete.')


import sys
import hashlib

if len(sys.argv) != 3:
    print("""Usage: %s --create|<hash-digest> <file>

Creates an md5sum hash digest of the specified file content
and compares it with the given hash digest.

If --create is used instead of a hash digest, it will simply
print out the hash digest of specified file content.
""" % sys.argv[0])
    sys.exit(1)

if sys.argv[2] == '-':
    fh = sys.stdin
    filename = "<stdin>"
else:
    filename = sys.argv[2]
    fh = open(filename)

hexdigest = hashlib.md5(fh.read()).hexdigest()
if sys.argv[1] == '--create':
    print(hexdigest)
elif hexdigest == sys.argv[1]:
    print("md5sum check passed:", filename)
else:
    print("md5sum check FAILED:", filename)
    sys.exit(1)