import numpy as np
from anytree import Node, RenderTree, find_by_attr
from anytree.dotexport import RenderTreeGraph
from anytree.exporter import DotExporter
import pip

def createMatrix(reference, alignments, diff_by_gene_relative):
	'''
		Returns the features matrix, i.e. a matrix having reads as rows,
		and diffs as columns. Matrix[i][j] = 1 if the i-eth read has
		the j-eth diff, 0 otherwise. In order to remember to which
		row each reads corresponds to, a list of sequence_ids is also returned,
		such that sequences_list[i] corresponds to the i-eth row.

		:param alignments:
            A dict of the form {align_id_1 : value, align_id_2 : value, etc.}

        :param diff_by_gene_relative:
        	A dict of differences {gene_id:[differences]} where information
            about the different codons involved in the difference is provided

        :returns:
	        A tuple where:
	                - the first element is the matrix as described above

	                - the second element is a list of sequences_id,
	                  such that the i-eth row in the matrix corresponds to
	                  the i-eth sequence_id
	'''

	### FIRST CREATE AN EMPTY MATRIX

	# Find total numeber of differences
	differences_no = 0
	for gene_id in diff_by_gene_relative.keys():
		for diff in diff_by_gene_relative[gene_id]:
			differences_no = differences_no + 1

	# Find total number of sequences
	sequences_no = len(alignments.keys())

	# Create matrix having as rows the sequences, and as columns the differences
	# + 1 since reference also needs to be considered
	matrix = np.zeros((sequences_no+1,differences_no))
	# print("Sequences_no", sequences_no)
	# print("Differences_no",differences_no)

	### NOW FILL THE MATRIX

	# Convert sequences to list
	sequences_list = list(alignments.keys())
	# Add reference to keys
	sequences_list.append(list(reference.keys())[0])

	# For each diff
	column = 0
	for gene_id in diff_by_gene_relative.keys():
		for diff in diff_by_gene_relative[gene_id]:
			# For all sequences where the diff happens
			for seq in diff['where']:
				# Find position in sequences_list (= row)
				row = sequences_list.index(seq)

				matrix[row][column] = 1

			column = column + 1

	# print("Matrix",matrix.astype(int))
	# print("Shape",matrix.shape)
	np.savetxt('../Outputs/Part3/matrix.out', matrix, fmt="%d", delimiter=',')

	return (sequences_list, matrix)

def containsForbidden(original_matrix):
	'''
		Returns wheter or not a given matrix contains the forbidden matrix

		:param original_matrix:
            A matrix of features 0/1

        :returns:
	        A boolean whose value is True if original_matrix contains
	        the forbidden matrix, False otherwise
	'''

	# if original_matrix is None:
	# 	return False

	n_one = np.array([])

	### STEP 1: Sort original_matrix by column, according to the number
	###		    of 1 in each column

	transpose_matrix = original_matrix.transpose()
	#Count number of 1s in each column
	for original_col in transpose_matrix:
		cont = 0
		for val in original_col:
			if val == 1:
				cont = cont +1
		n_one = np.append(n_one,cont)

	# Sort by descending number of 1s
	n_one_sort = sorted(n_one, reverse= True)

	# Holds the column number in the sorted matrix
	pos_new = 0
	aux_matrix = np.zeros(original_matrix.shape)

	for i in n_one_sort:

		# Holds the column number in the original matrix
		pos_old = 0

		# Find the column number in the original matrix
		for j in n_one:
			if i == j:
				# Column has been found
				# -1 is a sentinel value
				n_one[pos_old] = -1

				# Copy the old column in the new one
				row = 0
				while row != len(transpose_matrix[0]):
					aux_matrix[row][pos_new] = original_matrix[row][pos_old]
					row = row + 1

				# Move to the next column
				pos_new = pos_new + 1

			pos_old = pos_old + 1

	#print("Sorted matrix\n", aux_matrix)

	### STEP 2: Find, for each 1 in the sorted matrix, the position
	###		    of the previous 1 in the same row

	#Create auxillary matrix
	row = 0

	aux_matrix = np.zeros(original_matrix.shape)

	for curr_line in original_matrix:
		col = 0

		#contains the last column where 1 was found
		cont = -1

		for val in curr_line:
			if val == 1:
				# set to last column with 1
				aux_matrix[row][col] = cont
				# store the current column index
				cont = col + 1
			else:
				aux_matrix[row][col] = 0
			col = col + 1

		row = row + 1

	#print("Aux matrix\n", aux_matrix)

	### STEP 3: Check if the forbidden matrix is actually present
	###         in aux_matrix

	is_prohibited = False

	# Check column by column
	for j in range(0, aux_matrix.shape[1]):
		# For each row
		for i in range(0, aux_matrix.shape[0]):
			if aux_matrix[i][j] == 0:
				continue
			else:
				# For all other rows
				for k in range (0, aux_matrix.shape[0]):
					if aux_matrix[i][j] != aux_matrix[k][j] and aux_matrix[k][j] != 0:
						is_prohibited = True
						break

		if is_prohibited:
			break

	return is_prohibited

def createTree(sequences_list, original_matrix):
	'''
		Returns the philogenetic tree obtained from a 0/1 matrix

		:param original_matrix:
			A matrix of features 0/1

		:param sequences_list:
            a list of sequences_id, such that the i-eth row
            in the matrix corresponds to the i-eth sequence_id

        :returns:
	        A list of edges (Node1, Node2)
	'''

	# Initialize root
	root = dict()
	root['id'] = "Root"
	#root['reads'] = list() # Should always be empty
	root['reads'] = sequences_list.copy() # All sequences start in node 0
	root['edges'] = list()

	### STEP 1: Create tree

	# For each row
	for i in range(0,original_matrix.shape[0]):

		# The first 1 in each row starts from Root
		curr_node = root

		# For each column
		for j in range(0,original_matrix.shape[1]):
			# Initialize dict for current column
			node_to_add = dict()

			if original_matrix[i][j] == 1:

				# Create node
				node_to_add['id'] = "C" + str(j+1)
				node_to_add['reads'] = []
				node_to_add['reads'].append(sequences_list[i])
				node_to_add['edges'] = []

				# Remove read from curr_node
				# it will "move down" the tree
				curr_node['reads'].remove(sequences_list[i])

				found = False
				# Check if edge already exists
				for adj_node in curr_node['edges']:
					if node_to_add['id'] == adj_node['id']:
						found = True
						# just add the read to the node
						adj_node['reads'].append(sequences_list[i])
						# restart from said node
						curr_node = adj_node
						break

				# Create new node
				if not found:
					# add an edge to new node
					curr_node['edges'].append(node_to_add)
					# restart from said node
					curr_node = node_to_add

	### STEP 2: Convert to list of edges (start,end)

	result = visit(root)

	#print("Root is",root)
	return result

def visit(tree):
	'''
		Performs a visit on the resulting tree, in order to obtain
		a list of pairs (starting_node, ending_node) to feed in
		to the tree visualization algorithm.

		:param tree:
            a tree where nodes are represented as dicts, and each has a
            list edges, where the adjacent nodes are present

        :returns:
	        A list of pairs (starting_node, ending_node)

	'''
	result = []

	for read in tree['reads']:
		result.append((tree['id'],read))

	for adj_node in tree['edges']:
		result.append((tree['id'],adj_node['id']))
		result.extend(visit(adj_node))

	return result

def findBiggestNotForbidden(matrix):
	new_matrix = matrix[:,0:1].astype(int)

	for i in range(1,matrix.shape[1]):
		curr_column = matrix[:,i:i+1].astype(int)

		new_matrix = np.concatenate((new_matrix, curr_column),axis=1)

		if containsForbidden(new_matrix):
			new_matrix = new_matrix[:,:-1]

	return new_matrix

def printTree(edges_list):
	# create root
	root = Node("Root")

	for (node1, node2) in edges_list:
		Node(node2, parent=find_by_attr(root, node1))
	for pre, _, node in RenderTree(root):
		print("%s%s" % (pre, node.name))

	# Print to file --- GRAPVIZ MUST BE INSTALLED!!!
	installed_packages = ["%s" % i.key for i in pip.get_installed_distributions()]

	if 'graphviz' in installed_packages:
		RenderTreeGraph(root).to_picture("../Outputs/Part3/tree.png")
		print('Tree generated correctly')

# def nodenamefunc(node):
# 	return '%s:%s' % (node.name, node.depth)
# def edgeattrfunc(node, child):
# 	return 'label="%s"' % (node.edge)
# def edgetypefunc(node, child):
#     return '--'
# def printcopy(root):
#     for line in DotExporter(root, graph="graph",
# 						nodenamefunc=nodenamefunc,
# 						edgeattrfunc=edgeattrfunc,
# 						edgetypefunc=edgetypefunc):
#     	print(line)

def main():
	# m1 = np.array([
	# 	[0,1],
	# 	[1,0],
	# 	[1,1]
	# ])

	# print("Is forbidden?",containsForbidden(m1))

	m2 = np.array([
		[0,1],
		[1,0],
		[0,0],
	])

	print("Is forbidden?",containsForbidden(m2))
	#print("Tree:",createTree(["read0","read1","read2"],m2))
	nodes = createTree(["read0","read1","read2"],m2)
	printTree(nodes)

if __name__ == "__main__":
    main()


'''
Nalu Zou, Yuming Tsang, Jerome Orille
3/13/20
Project Part 2 - Crew Member Data Wrangling
This is a test file used for testing similar code
in 'dept_info.py' and 'crew_info.py.'
'''

from test_util import assert_equals
from crew_dept_info import populate_department, total_department
import pandas as pd
from ast import literal_eval

def main():
    # Import data
    crew = pd.read_csv('crew_info.csv')

    # Randomly get one row
    sample = crew.sample()

    # Change data type of values in 'crew' column
    # from string to list of dictionaries
    member = sample['crew']
    member = member.apply(literal_eval)

    # Populate crew type information
    sample['department'] = member.apply(populate_department)
    count_departments = total_department(sample['department'])
    print(count_departments)
    tot_crew_types = count_departments['Count'].sum()

    # Populate information for total number of crew members
    sample['total_crew'] = member.apply(lambda x: len(x))
    count_total_crew = sample[['title', 'total_crew']]
    count_total_crew = count_total_crew.rename(
        columns={'title': 'Movie', 'total_crew': 'Total Crew per Movie'})
    print(count_total_crew)
    tot_crew = count_total_crew['Total Crew per Movie'].sum()

    # Check to see if number of crew types matches total crew
    print('Checking number of crew types to total crew...')
    assert_equals(tot_crew_types, tot_crew)
    print('Total count from count_departments: ' + str(tot_crew_types))
    print('Total count from count_total_crew: ' + str(tot_crew))

if __name__ == '__main__':
    main()


##To count the number of pairs of subtuples in a tuple where (a,b) are even
#evetup.py
#28-11-22
#By Anupam Kanoongo

print("Welcome to the Even Tuple Finder")
print()
tup = eval(input("Enter a pairs of tuples :"))
lt = len(tup)
nums = range(0,10000,2)
cnt = 0
a, b = 0, 0

for i in tup:
    a, b = i
    if a in nums and b in nums:
        cnt += 1

print("Out of the above tuple",cnt,"pair(s) contain both even numbers")

# Output
# Welcome to the Even Tuple Finder

# Enter a pairs of tuples :((1,2),(2,4),(3,6),(4,8))
# Out of the above tuple 2 pair(s) contain both even numbers


import boto3
from dateutil.parser import parse
import re
from os.path import exists

s3 = boto3.resource('s3')
bucket = s3.Bucket('stellar.health.test.t.choudhury')
filename = 'patients.log'
new_filename = 'patients.log.corrected'

def download_log_file():
    for obj in bucket.objects.all():
        key = obj.key
        s3.Object(bucket.name, key).download_file(filename)

def upload_new_log_file():
    if exists(new_filename):
        s3.Object(bucket, new_filename).upload_file(
            Filename="patients.log.corrected")

def read_file():
    file = open(filename, 'r', encoding='utf8')
    lines = file.readlines()

    for line in lines:
        if 'DOB' in line:
            unformatted_dob = line.strip().split(' ')[6]
            dob = unformatted_dob.split('\'')[1]
            if is_valid_date(dob):
                if len(dob.split('/')[2]) < 4:
                    dob = append_century_to_year(dob)

                new_dob = modify_date(dob)

                if len(dob.split('/')[2]) > 3:
                    result = modify_line(line, new_dob)
                    append_to_new_log_file(result)
            else:
                append_to_new_log_file(line)
        else:
            append_to_new_log_file(line)

    upload_new_log_file()

    file.close()

def append_to_new_log_file(line):
    fout = open(new_filename, "a", encoding='utf-8')
    fout.write(line)
    fout.close()

def is_valid_date(date_text, fuzzy=False):
    try:
        parse(date_text, fuzzy=fuzzy)
        if len(date_text.split('/')) < 2:
            return False
        return True
    except ValueError:
        return False

def append_century_to_year(date_text):
    year = int(date_text.split('/')[2])

    if year > 22:
        new_date = date_text.replace('44', '1944')
    else:
        new_date = date_text.replace('44', '2044')

    return new_date

def modify_date(date_text):
    month = date_text.split('/')[0]
    day = date_text.split('/')[1]
    new_date = date_text.replace(month, "X", 1).replace(day, "X", 1)

    return new_date

def modify_line(line, new_date):
    regex = r'(\d{1,2})/(\d{1,2})/(\d{4})'
    result = re.sub(regex, new_date, line, 1)
    return result


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

import cv2

URL = "http://172.29.156.201:8081/"
s_video = cv2.VideoCapture(URL)

while True:
  ret, img = s_video.read()
  cv2.imshow("Stream Video",img)
  key = cv2.waitKey(1) & 0xff
  if key == ord('q'): break


#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import sys
import json
import argparse

import numpy as np

from gensim.models import word2vec
import scipy.spatial.distance as dis

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_validate

# -----------------------------------------------------------------------------
# word2vec
# -----------------------------------------------------------------------------

def load_word2vec(path):

    if os.path.exists(path):
        model = word2vec.Word2Vec.load(path)
    else:
        model = None

    return model

def get_words(model, persons, criminals, victims, names):

    words = []
    for person in persons:
        try:
            wvec = model[person]
        except:
            continue
        if person in names:
            # まだらの紐の登場人物は学習に含めない
            continue
        if person in criminals:
            words.append([person, wvec, "r", 0])
        elif person in victims:
            words.append([person, wvec, "c", 1])
        else:
            words.append([person, wvec, "y", 2])
    return words

# -----------------------------------------------------------------------------
# 分類
# -----------------------------------------------------------------------------

def classify_eval(words, w2v):

    arr = np.zeros((len(words),words[0][1].shape[0]), dtype="float32")
    y = np.zeros(len(words), dtype="int32")
    for i, word in enumerate(words):
        arr[i] += word[1]
        y[i] = word[3]

    scoring = ["accuracy", "precision_macro", "recall_macro", "f1_macro"]
    model = RandomForestClassifier(n_estimators=10, max_depth=5, random_state=5)
    skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)

    result = cross_validate(model, arr, y, cv=skf, scoring=scoring, return_train_score=False)

    keys = result.keys()
    #keys.sort()
    for key in keys:
        print(key+": "+str(result[key].mean()))

def classify(words, w2v, names):

    arr = np.zeros((len(words),words[0][1].shape[0]), dtype="float32")
    y = np.zeros(len(words), dtype="int32")
    for i, word in enumerate(words):
        arr[i] += word[1]
        y[i] = word[3]

    model = RandomForestClassifier(n_estimators=10, max_depth=5, random_state=5)
    model.fit(arr, y)

    test = np.zeros((len(names),words[0][1].shape[0]), dtype="float32")
    for i, name in enumerate(names):
        test[i] += w2v[name]

    result = model.predict_proba(test)

    for i, res in enumerate(result):
        print(names[i]+": "+str(res))

# -----------------------------------------------------------------------------
# Main
# -----------------------------------------------------------------------------

def main():

    arg_parser = argparse.ArgumentParser(description="")
    arg_parser.add_argument("-s", required=True, action="store", dest="setting_path", help="Setting file path")
    arg_parser.add_argument("-e", action="store_true", default=False, dest="classify_eval", help="")
    args = arg_parser.parse_args()

    settings = ""
    with open(args.setting_path, "r") as f:
        settings = json.load(f)

    if settings == "":
        return False

    w2v_model = load_word2vec(settings["path"]["word2vec"])
    words = get_words(w2v_model, settings["data"]["persons"], settings["data"]["criminals"], settings["data"]["victims"], settings["data"]["names"])

    if args.classify_eval:
        classify_eval(words, w2v_model)
    else:
        classify(words, w2v_model, settings["data"]["names"])

    return True

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 16:34:08 2019

@author: supaul
"""

#
import requests
url = ('https://newsapi.org/v2/top-headlines?'
       'country=in&'
       'apiKey='+config.SECRETKEY)
response = requests.get(url)
jsonObject=response.json()
msg = ("Hello this is your news update !"+"\n")
print(jsonObject)
listOfArticles=jsonObject["articles"]
for article in listOfArticles[:10]:
    print(article["title"])
    print(article["urlToImage"])
    msg+=article["title"]+"\n";
    msg+=("Link to this story:"+article["url"]+"\n");
    print("Link to this story:",article["url"])
    print()

'''
goodReadResponse = requests.get('http://quotes.rest/qod.json')
quoteJson=goodReadResponse.json()
quoteContent=quoteJson['contents']
qt=quoteContent['quotes']
finalQuote=qt[0]
print(finalQuote['quote'])
print(finalQuote['author'])

print(msg)
msg+=(finalQuote['quote']+"-"+finalQuote['author'])
'''

import smtplib

import config

def send_email(subject, msg,senderemail):
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(config.USERNAME,config.PASSWORD)
        message = 'Subject: {}\n\n{}'.format(subject, msg)
        server.sendmail(config.USERNAME,senderemail,message)
        server.quit()
        print("Success: Email sent!")
    except:
        print("Email not sent")

subject = "News letter of the day"

with open('EmailList.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='\n')
    for row in csv_reader:
        if(len(row)!=0):
            send_email(subject, msg,row[0])


import json  # загружаем библиотеки
import requests  # загружаем библиотеку для запроса по url адресу
import telebot  # загружаем библиотеку телебота
from telebot import types  # загружаем библиотеку для создания кнопок
from confing import tok, api  # импортируем токен

bot = telebot.TeleBot(tok)  # токен бота
API =  api # api сайта погоды

@bot.message_handler(commands=["start"])  # создаем команду, для старта бота
def start(message):
    bot.send_message(message.chat.id,
                     f'Привет, {message.from_user.first_name}, введите текст')  # обращаемся к пользователю по первому имени

@bot.message_handler(content_types=["text"])  # получпем ответ пользователя
def get_markup(message):
    markup = types.InlineKeyboardMarkup()  # создаем  кнопки в чате
    item1 = types.InlineKeyboardButton(text='Новости', callback_data='Новости')
    item2 = types.InlineKeyboardButton(text='Посмотреть погоду', callback_data='Погода')
    item3 = types.InlineKeyboardButton(text='Курсы валют', callback_data='курсы')
    markup.row(item1, item2, item3)  # указываем на рассположение кнопок
    bot.reply_to(message, 'Выбери, чем помочь', reply_markup=markup)

@bot.callback_query_handler(func=lambda callback: True)  # обрабатываем кнопки
def city_message(callback):
    if callback.data == 'Погода':
        bot.send_message(callback.message.chat.id, 'Введите город: ')
        bot.register_next_step_handler(callback.message, my_weather)
    elif callback.data == 'Новости':
        markup = types.InlineKeyboardMarkup()
        item4 = types.InlineKeyboardButton(text='IT', callback_data='новости', url='https://devby.io')
        item5 = types.InlineKeyboardButton(text='Авто!', callback_data='новости авто', url='https://cars.av.by/')
        markup.row(item4, item5)
        bot.reply_to(callback.message, 'Давайте узнаем последние новости', reply_markup=markup)
    elif callback.data == 'курсы':
        markup = types.InlineKeyboardMarkup()
        item6 = types.InlineKeyboardButton(text='курсы валют', url='https://select.by/kurs/')
        markup.add(item6)
        bot.send_message(callback.message.chat.id, f'Сегодня', reply_markup=markup)
        bot.register_next_step_handler(callback.message, get_markup)

def my_weather(message):  # получаем город от пользователя
    global temp
    city = message.text.strip().lower()
    weth = requests.get(
        f'https://api.openweathermap.org/data/2.5/find?q={city}&type=like&APPID={API}&units=metric')  # отправляем запрос на сайт погоды
    try:  # проверяем на правильность написания города
        data = json.loads(weth.text)
        temp = round(data["list"][0]["main"]["temp"], 1)  # получаем температуру и округляем до десятых
        bot.send_message(message.chat.id,
                         f'Сейчас погода в: {city}  {temp} градусов')  # отправляем ответ пользователю
        image_sun = 'sun.png'
        image_cloud = 'cloud.png'
        if temp <= 15:
            file = open('./' + image_cloud, 'rb')
            bot.send_photo(message.chat.id, file)
        else:
            file = open('./' + image_sun, 'rb')
            bot.send_photo(message.chat.id, file)

    except:
        bot.send_message(message.chat.id,
                         f'Город указан не верно,введите еще раз: ')
        bot.register_next_step_handler(message, my_weather)

bot.polling(none_stop=True, interval=0)


import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5 import uic

class Menu(QtWidgets.QWidget):

    switch_mainWindow = QtCore.pyqtSignal()
    switch_addSum = QtCore.pyqtSignal(dict)
    switch_takeSum = QtCore.pyqtSignal(dict)

    def __init__(self, user):
        QtWidgets.QWidget.__init__(self)
        uic.loadUi('./ui/menu.ui', self)
        self.addS.clicked.connect(self.add)
        self.takeS.clicked.connect(self.take)
        self.exit.clicked.connect(self.menu)

        self.name.setText(f"Имя: {user['first_name']}")
        self.surname.setText(f"Фамилия: {user['last_name']}")
        self.patronymic.setText(f"Отчество: {user['patronymic']}")
        self.login.setText(f"Логин: {user['login']}")
        self.bir_date.setText(f"Дата рождения: {user['birth_date']}")
        self.date_join.setText(f"Дата регистрации: {user['date_joined']}")
        self.account.setText(f"Счёт: {user['money']}")

        self.user = user

    def menu(self):
        """Закрытие нынешнего окна и открытие меню"""

        self.close()
        self.switch_mainWindow.emit()

    def add(self):
        """Закрытие нынешнего окна и открытие окна пополнения средств"""

        self.close()
        self.switch_addSum.emit(self.user)

    def take(self):
        """Закрытие нынешнего окна и открытие окна снятия средств"""

        self.close()
        self.switch_takeSum.emit(self.user)


import argparse
import os
import logging
import sys
import subprocess

logging.getLogger().setLevel(logging.INFO)

root_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..", ".."))
sdk_dir = os.path.join(root_dir, "sdk")

def run_black(service_dir):
    logging.info("Running black for {}".format(service_dir))

    out = subprocess.Popen([sys.executable, "-m", "black", "-l", "120", "sdk/{}".format(service_dir)],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd = root_dir
    )

    stdout,stderr = out.communicate()

    if stderr:
        raise RuntimeError("black ran into some trouble during its invocation: " + stderr)

    if stdout:
        if "reformatted" in stdout.decode('utf-8'):
            return False

    return True

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Run black to verify formatted code."
    )
    parser.add_argument(
        "--service_directory", help="Directory of the package being tested"
    )

    parser.add_argument(
        "--validate", help=("Flag that enables formatting validation.")
    )

    args = parser.parse_args()
    if args.validate != "False":
        if not run_black(args.service_directory):
            raise ValueError("Found difference between formatted code and current commit. Please re-generate with the latest autorest.")

    else:
        print("Skipping formatting validation")


#
# @lc app=leetcode.cn id=423 lang=python3
#
# [423] 从英文中重建数字
#medium
'''
给你一个字符串 s ，其中包含字母顺序打乱的用英文单词表示的若干数字（0-9）。按 升序 返回原始的数字。

示例 1：

输入：s = "owoztneoer"
输出："012"
示例 2：

输入：s = "fviefuro"
输出："45"

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/reconstruct-original-digits-from-english
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
'''
# @lc code=start
class Solution:
    def originalDigits(self, s: str) -> str:
        c = Counter(s)

        cnt = [0] * 10
        cnt[0] = c["z"]
        cnt[2] = c["w"]
        cnt[4] = c["u"]
        cnt[6] = c["x"]
        cnt[8] = c["g"]

        cnt[3] = c["h"] - cnt[8]
        cnt[5] = c["f"] - cnt[4]
        cnt[7] = c["s"] - cnt[6]

        cnt[1] = c["o"] - cnt[0] - cnt[2] - cnt[4]

        cnt[9] = c["i"] - cnt[5] - cnt[6] - cnt[8]

        return "".join(str(x) * cnt[x] for x in range(10))
    '''
    作者：LeetCode-Solution
    链接：https://leetcode-cn.com/problems/reconstruct-original-digits-from-english/solution/cong-ying-wen-zhong-zhong-jian-shu-zi-by-9g1r/
    来源：力扣（LeetCode）
    著'作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
    '''
# @lc code=end

423.从英文中重建数字.py


"""
===================
Make a 1D Histogram
===================

``tttrlib`` offers some functions and classes for the creation of histograms.
They are part of ``tttrlib`` to offer more performance in direct comparison to
general purpose routines for analysis methods as Photon Distribution Analysis
(PDA) that make heady use of repeated histogram calculations.

.. note::

    These function and ``classes`` are not intended as a substitution for more
    general functions, e.g., offered by `NumPy <https://www.numpy.org/>`_ and
    are less tested. They offer performance advantages for histograms
    calculated on a logarithmic (log10) scale and a linear scale in direct
    comparison to NumPy.

One dimensional histograms
--------------------------

``tttrlib`` supports one dimensional histograms with linear, logarithmic, or
arbitrary spaced bins.

#.. plot:: ../examples/miscellaneous/histogram_1D.py
   :include-source:

In the example shown above, the histograms for the three bin spacings are shown.

Multi dimensional histograms
----------------------------

In addition to simple one dimensional histograms ``tttrlib`` can calculate
multidimensional histograms with an arbitrary number of dimensions. For that,
first a new object of the class ``doubleHistogram`` is created. Here, *double*
refers to the data type double - a floating point number. Next, axes are added
to the Histogram by calling the method ``setAxis``. The first argument is the
number of the axis, the second the name of the axis, the third and the fourth
the range of the axis, the fifth the number of bins, and the sixth the type of
the axis. The ``Histogram`` class support arbitrary axis types. However, when
initializing an axis via ``setAxis`` the axis type must be either *lin* or
*log10* for a linear or an logarithmic axis with base 10. Next, the data are
assigned to the histogram by the ``setData`` method and the histogram is
calculated by the ``update`` method. A working example for 2D normal
distributed data is shown below.

#.. plot:: ../examples/miscellaneous/histogram_2D.py
   :include-source:

Above, a two dimensional histogram with linear spaced bins is shown.

"""
import tttrlib
import numpy as np
import pylab as p

fig, ax = p.subplots(3, 1)

# Linear histograms
data = np.random.normal(10, 2, int(2e6))
bins = np.linspace(0, 20, 32000, dtype=np.float)
hist = np.zeros(len(bins), dtype=np.float)
weights = np.ones_like(data)
tttrlib.histogram1D_double(data, weights, bins, hist, 'lin', True)
ax[0].plot(bins, hist, 'g')

# Logarithmic histogram
bins = np.logspace(0, 3.5, 32000, dtype=np.float)
data = np.random.lognormal(3.0, 1, int(2e6))
hist = np.zeros(len(bins), dtype=np.float)
weights = np.ones_like(data)
tttrlib.histogram1D_double(data, weights, bins, hist, '', True)
ax[1].semilogx(bins, hist, 'r')

# Histogram with arbitrary spacing
bins1 = np.linspace(1, 600, 16000, dtype=np.float)
bins2 = np.logspace(np.log10(bins1[-1]+0.1), 3.0, 16000, dtype=np.float)
bins = np.hstack([bins1, bins2])
hist = np.zeros(len(bins), dtype=np.float)
weights = np.ones_like(data)
tttrlib.histogram1D_double(data, weights, bins, hist, '', True)
ax[2].semilogx(bins, hist, 'y')

p.show()


array = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]

#  Counting Sort
# 1
# def counting_sort(array):
# 	zero = 0
# 	one = 0
# 	two = 0

# 	for value in array: # O(n)
# 		if value == 0:
# 			zero += 1
# 		elif value == 1:
# 			one += 1
# 		elif value == 2:
# 			two += 1
# 		else:
# 			print('Error in input')
# 			break

# 	new_array = list()

# 	new_array.extend([0] * zero) # O(k)
# 	new_array.extend([1] * one) # O(p)
# 	new_array.extend([2] * two) # O(m)

# 	print(new_array)

# counting_sort(array)

# 2
# def counting_sort(array):

# 	max_element = max(array) # O(n)

# 	new_array = [0] * len(array)
# 	counts = [0] * (max_element + 1)

# 	for value in array: # O(n)
# 		counts[value] += 1

# 	for index in range(1, len(counts)): # O(n)
# 		counts[index] += counts[index - 1]

# 	for value in array: # O(n)
# 		new_array[counts[value]-1] = value
# 		counts[value] -= 1

# 	print(new_array)
# counting_sort(array)

# Dutch National Flag Algorithm

def dutch_national_flag(array):
	low = 0
	mid = 0
	high = len(array) - 1
	temp = None
	while mid <= high:
		if array[mid] == 0:
			temp = array[mid]
			array[mid] = array[low]
			array[low] = temp
			mid += 1
			low += 1
		elif array[mid] == 1:
			mid += 1
		elif array[mid] == 2:
			temp = array[mid]
			array[mid] = array[high]
			array[high] = temp
			high -= 1

	print(array)

dutch_national_flag(array)


from details_widget_button_list import WidgetButtonList
from floater_opener import FloaterListOpener

class WidgetActionsList(WidgetButtonList):
    def _floater_list_items_update(self):
        items_list = []
        for item in self._list_get_cb():
            if item.startswith("@") and item.endswith("@0.00"):
                fixedname = item[1:item.rindex("@")]
                items_list.append((fixedname, item))
        return items_list

    def _floater_actions_init(self):
        self._floater.action_add("None", self._none_selected)
        FloaterListOpener._floater_actions_init(self)

    def _none_selected(self, *args):
        self.value_set("")
        self._floater_cancel()


from django.urls import path
from . import views

app_name = "travel"

urlpatterns = [
    path('list/', views.PlaceListView.as_view(), name='place_list'),
    path(
        'create_setting/',
        views.SettingCreateView.as_view(),
        name='create_setting'),
    path('done_setting/', views.setting_done, name='done_setting'),
    path(
        'setting_list/',
        views.SettingListView.as_view(),
        name='setting_list'),
    path(
        'update_setting/<uuid:id>/',
        views.SettingUpdateView.as_view(),
        name='update_setting'),
    path(
        'setting_update_done/',
        views.setting_update_done,
        name='setting_update_done'),
    path(
        'delete_setting/<uuid:id>/',
        views.SettingDeleteView.as_view(),
        name='delete_setting'),
    path(
        'setting_delete_done/',
        views.delete_done,
        name='setting_delete_done'),
    path('place_save/', views.place_save, name='place_save'),
    path('place_delete/', views.place_delete, name='place_delete'),
    path(
        'saved_place/',
        views.SavedPlaceListView.as_view(),
        name='saved_place'),
    path(
        'share_place/<uuid:id>/',
        views.SharePlaceView.as_view(),
        name='share_place'),
    path(
        'shared_place_list/',
        views.SharedPlaceListView.as_view(),
        name='shared_place_list'),
]


# -*- coding: utf-8 -*-
import os
import shutil

pathfileraw = '../vn_news'
pathcountry = './country'
pathfiledata = '../vn_news_country'
if not (os.path.exists(pathfiledata) or os.path.isdir(pathfiledata)):
    os.makedirs(pathfiledata)

with open(pathcountry, "r") as f:
    listcountry = f.readlines()
listcountry2 = []
for country in listcountry:
    listcountry2.append(country.strip())

listfile = os.listdir(pathfileraw)

for filename in listfile:
    with open(pathfileraw + '/' + filename, 'r') as f:
        text = f.read().split()

    for namecountry in listcountry2:
        if namecountry in text:
            shutil.copy2(pathfileraw + '/' + filename, pathfiledata + '/' + namecountry + filename)
            break


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

import os
from setuptools import find_packages, setup

# Package meta-data.
NAME = 'imageprep'
DESCRIPTION = 'Image Preparation Utilities'
URL = 'https://github.com/adbeda/imageprep'
EMAIL = 'adbedada@gmail.com'
AUTHOR = 'Adane Bedada'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = 0.4

with open("README.md") as f:
    long_description = f.read()

REQUIRED = [
    'pillow',
    'click',
    'numpy'
]

EXTRA_REQUIRED = {
    'test': ['mock',
             'pytest',
             'pytest-cov',
             'codecov']}

here = os.path.abspath(os.path.dirname(__file__))

setup(
    name=NAME,
    version=VERSION,
    description=DESCRIPTION,
    long_description=long_description,
    long_description_content_type='text/markdown',
    author=AUTHOR,
    author_email=EMAIL,
    python_requires=REQUIRES_PYTHON,
    url=URL,
    packages=find_packages(exclude=('data', 'examples')),
    install_requires=REQUIRED,
    extras_require=EXTRA_REQUIRED,
    include_package_data=True,
    license='MIT',
    entry_points='''
             [console_scripts]
             imageprep=imageprep.imcli:commands
                 ''',
    classifiers=[
        # Trove classifiers
        # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy'
    ]
)


"""
A module to extract raw text from tolkien books in epub format. Assumes a lot of things.
I used it for books with following md5sums:

5d513bf5255f055636203d0d50560be7 hobbit.epub
8e3fe0113aa5e632907c397d535c3694 hurin.epub
82cdaf6ed62b2a2f3de870a044a19c37 lotr.epub

Inspect and adjust to your own versions of the texts
"""
from pathlib import Path
from xml.etree import ElementTree as ET
import json

from nltk import tokenize
import ebooklib
from ebooklib import epub

from .to_frames import cap_to_ascii, match
from .to_final import reduce_frames, get_frame_mapping, extract_frames
from ..config import tolkien_fldr, tolkien_conf, coco_train_conf
from ..utils import ask_overwrite

w3c = "{http://www.w3.org/1999/xhtml}"

def xml_to_text(x):
    root = x
    if root[1].tag != f"{w3c}body" or root[1][0].tag != f"{w3c}div":
        print("Error")
        assert False

    chapter = root[1][0]
    for t in (f"{w3c}a", f"{w3c}h1"):
        junk = chapter.findall(t)
        for j in junk:
            chapter.remove(j)

    text = [t.strip() for t in chapter.itertext()]
    return " ".join(text)

def get_book_text(book_path):
    book = epub.read_epub(book_path)
    chapters = [
        doc
        for doc in book.get_items_of_type(ebooklib.ITEM_DOCUMENT)
        if "chap" in str(doc)
    ]
    chapters = [str(c.content, "utf-8") for c in chapters]
    chapters = list(map(ET.fromstring, chapters))

    return " ".join([xml_to_text(x) for x in chapters])

def to_txt():
    if not ask_overwrite(tolkien_conf["txt"]):
        return

    books = Path(tolkien_fldr).iterdir()

    tolk = " ".join([get_book_text(b) for b in books if b.suffix == ".epub"])
    tolk = " ".join(tolk.split())
    tolk = cap_to_ascii(tolk)
    sents = tokenize.sent_tokenize(tolk)

    with open(tolkien_conf["txt"], "wt") as f:
        for sent in filter(lambda s: len(s.split()) > 5, sents):
            f.write(f"{sent}\n")

    with open(tolkien_conf["txt"]) as in_f, open(tolkien_conf["basic"], "wt") as out_f:
        basic = [{"caption": line.strip()} for line in in_f.readlines()]
        json.dump(basic, out_f, indent=2)

def main():
    to_txt()
    match(tolkien_conf["conll"], tolkien_conf["basic"], tolkien_conf["frames"])

    if not ask_overwrite(tolkien_conf["final"]):
        return

    with open(coco_train_conf["frames"]) as cf:
        coco = json.load(cf)

    fmap = get_frame_mapping(extract_frames(coco))
    fmap = {f"{key}_FRAME": f"{val}_FRAME" for key, val in fmap.items()}

    reduce_frames(tolkien_conf["frames"], tolkien_conf["final"], fmap)

if __name__ == "__main__":
    main()


import helper

data = helper.read_inp("input.txt")

def follow(hy, hx, ty, tx):
    if abs(hy - ty) == 2 and abs(hx - tx) == 2:
        return [(hy + ty) // 2, (hx + tx) // 2]

    if abs(hy - ty) == 2:
        return [(ty + hy) // 2, hx]

    elif abs(hx - tx) == 2:
        return [hy, (tx + hx) // 2]

    else:
        return [ty, tx]

r = [[0, 0] for _ in range(10)]
res = {str([0, 0])}

for step in data:
    d, l = step.split(" ")
    for _ in range(int(l)):
        if d == "U":
            r[0][0] -= 1
        elif d == "D":
            r[0][0] += 1
        elif d == "R":
            r[0][1] += 1
        elif d == "L":
            r[0][1] -= 1

        prev = r[0]
        for i in range(1, len(r)):
            r[i] = follow(prev[0], prev[1], r[i][0], r[i][1])
            prev = r[i]

        res.add(str(r[-1]))

print(len(res))


import os
import sys
import json
import random
from pprint import pprint
from io import BytesIO
import onnxruntime
from PIL import Image
import torchvision.transforms.functional as T
import requests

#from utils import to_numpy
#from dataset import max_size, labels_reference

labels_reference = [
    "background",
    "barcode-qrcode",
    "credit-card",
    "fingerprint",
    "id-card",
    "iris",
    "ssn-card",
    "signature",
    "palmprint",
    "receipt",
    "license-plate",
    "retina",
    "floorplans",
    "chemical-structure",
]

image_mean = [0.485, 0.456, 0.406]
image_std = [0.229, 0.224, 0.225]
min_size = 800
max_size = 1333

def to_numpy(tensor):
    return (
        tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
    )

def load_ort(onnx_model_path):
    _name = onnx_model_path
    _so = onnxruntime.SessionOptions()
    _so.log_severity_level = 3
    _hardware = 'CUDAExecutionProvider'
    ort_session = onnxruntime.InferenceSession(
        _name, _so, providers=[_hardware]
    )
    return ort_session

def run_image(ort_session, image):
    # preprocessing
    background = Image.new("RGBA", image.size, (255, 255, 255))
    img = Image.alpha_composite(background, image).convert("RGB")
    x = to_numpy(T.to_tensor(img.resize((max_size, max_size))).unsqueeze(0))

    ort_inputs = {ort_session.get_inputs()[0].name: x}

    # calculate output
    coords, labels, scores = ort_session.run(None, ort_inputs)

    output = []
    for i in range(len(labels)):
        output.append({
            'prediction': labels_reference[labels[i]],
            'confidence': str(scores[i]),
            'bbox': [str(c) for c in list(coords[i])]
        })

    #print(output)
    #with open('test.json', 'w') as f:
    #    json.dump(output, f, indent=4)
    return output

# if __name__ == '__main__':
#     imfile = sys.argv[1]
#     ort_session = load_ort()
#     output = run_image(ort_session, imfile, [0])
#     pprint(output)

# ort_session = load_ort("./onnx/2.1_oos_18oct.onnx")

# run_image(ort_session, 'sample_barcodes/001.jpg', 1)[0]


# -*- coding: utf-8 -*-
# Find the time and value of max load for each of the regions
# COAST, EAST, FAR_WEST, NORTH, NORTH_C, SOUTHERN, SOUTH_C, WEST
# and write the result out in a csv file, using pipe character | as the delimiter.
# An example output can be seen in the "example.csv" file.
import xlrd
import os
import csv
from zipfile import ZipFile
datafile = "2013_ERCOT_Hourly_Load_Data.xls"
outfile = "2013_Max_Loads.csv"

headers = ["Station","Year","Month","Day","Hour","Max Load"]

regions = [("COAST",1),
           ("EAST",2),
           ("FAR_WEST",3),
           ("NORTH",4),
           ("NORTH_C",5),
           ("SOUTHERN",6),
           ("SOUTH_C",7),
           ("WEST",8)]

def open_zip(datafile):
    with ZipFile('{0}.zip'.format(datafile), 'r') as myzip:
        myzip.extractall()

def parse_file(datafile):
    workbook = xlrd.open_workbook(datafile)
    sheet = workbook.sheet_by_index(0)
    data = []
    # YOUR CODE HERE
    # Remember that you can use xlrd.xldate_as_tuple(sometime, 0) to convert
    # Excel date to Python tuple of (year, month, day, hour, minute, second)

    for region in regions:
        name = region[0]
        index = region[1]
        load_col = sheet.col_values(index,start_rowx=1, end_rowx=None)
        max_load = max(load_col)

        #now lets handle dates for the corresponding rows
        max_load_index = load_col.index(max_load)

        max_load_time_tuple = xlrd.xldate_as_tuple(sheet.cell_value(max_load_index + 1,0), 0)

        summary = [name] + list(max_load_time_tuple)[0:4] + [max_load]

        data.append(summary)

    return data

def save_file(data, filename):

    with open(filename,'wb') as f:
        w = csv.writer(f, delimiter='|',
                            quotechar='"', quoting=csv.QUOTE_MINIMAL)

        w.writerow(headers)

        for row in data:
            w.writerow(row)

def test():
    open_zip(datafile)
    data = parse_file(datafile)
    save_file(data, outfile)

    ans = {'FAR_WEST': {'Max Load': "2281.2722140000024", 'Year': "2013", "Month": "6", "Day": "26", "Hour": "17"}}

    fields = ["Year", "Month", "Day", "Hour", "Max Load"]
    with open(outfile) as of:
        csvfile = csv.DictReader(of, delimiter="|")
        for line in csvfile:
            s = line["Station"]
            if s == 'FAR_WEST':
                for field in fields:
                    assert ans[s][field] == line[field]

test()


# -*- coding: utf-8 -*-
# @Time    : 2021/10/22 9:54
# @Author  : ColorOfNight
# @Email   : 852477089@qq.com
# @File    : grid_trail.py
# @Software: PyCharm
# @Description: 根据网格的中心点坐标生成轨迹 临时的abaqus需求

import math

def calc_time(point1, point2, velocity):
    """
    计算时间

    :param point1: 点1
    :param point2: 点2

    :param velocity: 速度
    :return: 时间
    """
    distance = math.sqrt(
        (point1[0] - point2[0]) * (point1[0] - point2[0]) + (point1[1] - point2[1]) * (point1[1] - point2[1]) +
        (point1[2] - point2[2]) * (point1[2] - point2[2]))
    return distance / velocity

def generate_line(time, point, flag, offset=0.0):
    """
    生成点的信息
    """
    return str(round(time + offset, 1)) + ',' + str(point[0]) + ',' + str(point[1]) + ',' + str(
        point[2] + offset) + ',' + str(flag) + '\n'

def read_from_file(file_path):
    """
    读取文件

    :param file_path: 文件路径
    :return: 网格中心点列表
    """
    with open(file_path) as f:
        content = f.readlines()
        result = [list(map(float, line.replace('\n', '').split(',')[1:])) for line in content]
        # print(result)
    return result

def generate_trail(grid, length_per_line, v1=1, v2=10):
    """

    :param grid: 网格列表
    :param length_per_line: 每条轨迹的网格个数
    :param v1: 速度1
    :param v2: 速度2
    :return: 字符串
    """
    time = 0.0
    file_content = generate_line(time, grid[0], 1)
    for i in range(1, len(grid)):
        p1 = grid[i - 1]
        p2 = grid[i]
        time = time + calc_time(p1, p2, v2) if i % length_per_line == 0 else time + calc_time(p1, p2, v1)
        if i % length_per_line == 0:
            file_content += generate_line(time, p2, 0, -0.1)
        file_content += generate_line(time, p2, 1)
        if (i + 1) % length_per_line == 0:
            file_content += generate_line(time, p2, 0, 0.1)
    print(file_content)
    return file_content

if __name__ == '__main__':
    lists = read_from_file('./centrenode.csv')
    content = generate_trail(lists, 16)
    with open('./trail.csv', 'w+') as f:
        f.write(content)


#!/usr/bin/python2
###############################################################################
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html
###############################################################################
# -*- coding: utf-8 -*-
# helper functions for schema validation
#

from __future__ import print_function
import os
import re
from distutils.version import LooseVersion, StrictVersion

from . import globalvars

def isIPaddr(varin):
    ValidIpAddressRegex = "^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.(([0-9]|[0-9]{2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([0-9]|[0-9]{2}|0[0-9]{2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
    return (re.match(ValidIpAddressRegex,str(varin)) is not None)

def isMac(varin):
    MacRegex=r'[0-9a-f]{2}([:])[0-9a-f]{2}(\1[0-9a-f]{2}){4}$'
    return (re.match(MacRegex,str(varin),re.IGNORECASE) is not None)

def isPort(varin):
    PortRegex=r'^(swp)*[0-9]+$'
    return (re.match(PortRegex,str(varin),re.IGNORECASE) is not None)

def isRegex(varin):
    RegexPattern=r'.*\|(,|$)'
    return (re.match(RegexPattern,str(varin)) is not None)

def isIPrange(varin):
    ip=[]
    ip=str(varin).split('-')
    return len(ip)==2 and isIPaddr(ip[0]) and isIPaddr(ip[1])

def isMacHosts(varin):
    machosts=[]
    machosts=str(varin).split('|')
    for machost in machosts:
        entry=[]
        entry=machost.split('!')
        if not isMac(entry[0]):
           return False
    return True

def isNicips(varin):
    nicips=[]
    nicips=str(varin).split(',')
    for nicip in nicips:
        entry=[]
        entry=nicip.split('!')
        if len(entry)>2:
            return False
        ips=[]
        if len(entry) == 2:
            if isRegex(entry[1]):
                continue
            ips=entry[1].split('|')
        for ip in ips:
            if not isIPaddr(ip) or isRegex(ip):
                return False
    return True

def underpath(filename,path):
    if re.match(r'^'+os.path.realpath(path)+r'\/',os.path.realpath(filename)):
        return True
    else:
        return False

# return a list of the files in list "infilelist" and the files included in them
def getfileanddeplist(infilelist,rootdir=None):
    #helper function to return a dict whose keys are file "filename" specified and files included by it
    def getincfiledict(filename,filedict={},rootdir=None):
        regex_include=r'^#INCLUDE:\s*([^#]+)#$'
        if filename in filedict.keys():
            return
        if rootdir and underpath(filename,rootdir):
            filedict[os.path.join(os.sep,os.path.relpath(filename,rootdir))]=1
        else:
            filedict[filename]=1
        filepath=filename
        if rootdir and os.path.isabs(filename) and not underpath(filename,rootdir):
            filepath=os.path.join(rootdir,os.path.relpath(filename,os.sep))
        if os.path.isfile(filepath):
            with open(filepath) as fileobj:
                filelines = fileobj.readlines()
            olddir=os.getcwd()
            curdir=os.path.dirname(filepath)
            os.chdir(curdir)
            for line in filelines:
                matchobj_include=re.search(regex_include,line.strip())
                if matchobj_include:
                    incfile=matchobj_include.group(1).strip()
                    incfile=os.path.realpath(incfile)
                    if incfile not in filedict.keys():
                        getincfiledict(incfile,filedict,rootdir)
            os.chdir(olddir)
        return

    filedict={}

    #in case the input is some ancient inventory format, such as a list of files delimited with COMMA(,)
    if type(infilelist) is not list:
        infilelist=infilelist.split(',')

    for filename in infilelist:
        getincfiledict(filename,filedict,rootdir)
    return filedict.keys()

def strsubst(string,subdict={}):
    for k in subdict.keys():
        if k:
            string=string.replace(k,subdict[k])
    return string

def xcatversion():
    return LooseVersion(globalvars.xcat_verno)

if __name__ == "__main__":
    pass


from pico2d import *
from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode
import BackgroundSelection
import EnemyHP
import PlayerHP
import random
import game_world
import game_framework
import main_state
import DeckSelection
STAND_TIME_PER_ACTION=1
STANDACTION_PER_TIME= 1.0/STAND_TIME_PER_ACTION
STAND_PER_ACTION=9

#skill1
SKILL1TIME_PER_ACTION=2
SKILL1ACTION_PER_TIME= 1.0/SKILL1TIME_PER_ACTION
SKILL1_PER_ACTION=24

#skill2
SKILL2TIME_PER_ACTION=2
SKILL2ACTION_PER_TIME= 1.0/SKILL2TIME_PER_ACTION
SKILL2_PER_ACTION=20

#skill3
SKILL3TIME_PER_ACTION=2
SKILL3ACTION_PER_TIME= 1.0/SKILL3TIME_PER_ACTION
SKILL3_PER_ACTION=20
# iku lastspell Action Speed
LASTTIME_PER_ACTION=2
LASTACTION_PER_TIME= 0.5/LASTTIME_PER_ACTION
LASTCHEAK_PER_ACTION=35
#Damage
DAMAGETIME_PER_ACTION=1
DAMAGEACTION_PER_TIME= 1.0/DAMAGETIME_PER_ACTION
DAMAGE_PER_ACTION=4

#Down
DOWNTIME_PER_ACTION=3
DOWNACTION_PER_TIME= 1.0/DOWNTIME_PER_ACTION
DOWN_PER_ACTION=21

#ItemUse
ITEM1TIME_PER_ACTION=1
ITEM1ACTION_PER_TIME= 1.0/ITEM1TIME_PER_ACTION
ITEM1_PER_ACTION=7

#motion speed
PIXEL_PER_METER=(10.0/0.3)
MOTION_SPEED_KMPH = 0.2
MOTION_SPEED_MPM = (MOTION_SPEED_KMPH*1000.0/60.0)
MOTION_SPEED_MPS=(MOTION_SPEED_MPM/60.0)
MOTION_SPEED_PPS=(MOTION_SPEED_MPS*PIXEL_PER_METER)
# iku Event
Stand,Skill1,Skill2,Skill3, Last, Damage,Down,Item1,Item2,Item3 = range(10)

# Iku States
ationcheak = 0
damagecheak=1
class StandState:

    @staticmethod
    def enter(iku, event):
        global ationcheak,damagecheak
        iku.motion = 0
        iku.frame1 = 0
        iku.frame2 = 0
        iku.Standframe1 = [0, 73, 140, 200, 265, 324, 385, 446, 510, 580]
        iku.Standframe2 = [74, 64, 60, 62, 58, 59, 63, 65, 70]
        ationcheak = 0

    @staticmethod
    def exit(iku, event):
        pass
    @staticmethod
    def do(iku):
        global ationcheak,damagecheak,ation
        iku.frame1 = (iku.frame1 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9
        iku.frame2 = (iku.frame2 + STAND_PER_ACTION * STANDACTION_PER_TIME * game_framework.frame_time) % 9
        main_state.Enemy_Motion_Cheak = False
        if DeckSelection.character == 0 and main_state.reimu_skill1_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 0 and main_state.reimu_skill2_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 0 and  main_state.reimu_skill3_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 0 and main_state.reimu_last_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 1 and main_state.marisa_skill1_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 1 and main_state.marisa_skill2_atk_cheak==1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 1 and main_state.marisa_skill3_atk_cheak ==1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 1 and main_state.marisa_last_atk_cheak==1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 2 and main_state.iku_skill1_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 2 and main_state.iku_skill2_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 2 and main_state.iku_skill3_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 2 and main_state.iku_last_atk_cheak== 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 3 and main_state.tenshi_skill1_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 3 and main_state.tenshi_skill2_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 3 and main_state.tenshi_skill3_atk_cheak == 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if DeckSelection.character == 3 and main_state.tenshi_last_atk_cheak== 1:
            iku.damage_sound.play()
            iku.add_event(Damage)
        if main_state.HPcheak==0 and int(EnemyHP.damage) >252:
            iku.down_sound.play()
            iku.add_event(Down)
        if main_state.HPcheak == 0and int(EnemyHP.damage) < 251:
            if ationcheak == 1: #test
                iku.skill1_sound.play()
                main_state.P_HP += 20 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff
                iku.add_event(Skill1)
            if ationcheak == 2: #test
                iku.skill2_sound.play()
                main_state.P_HP += 30 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff
                iku.add_event(Skill2)
            if ationcheak == 3: #test
                iku.skill3_sound.play()
                main_state.P_HP += 40 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff
                iku.add_event(Skill3)
            if ationcheak == 4: #test
                iku.last_sound.play()
                main_state.P_HP += 50 * main_state.Enemy_AtkBuff * main_state.Player_DefBuff
                iku.add_event(Last)
            if ationcheak == 5: #test
                iku.item_sound.play()
                main_state.Enemy_DefBuff = 0
                iku.add_event(Item1)
            if ationcheak == 6: #test
                iku.item_sound.play()
                main_state.Enemy_AtkBuff = 3
                iku.add_event(Item2)
            if ationcheak == 7: #test
                iku.item_sound.play()
                main_state.HP -= 100
                EnemyHP.damage -= 100
                iku.add_event(Item3)

    @staticmethod
    def draw(iku):
        if iku.motion ==0:
            iku.stand.clip_draw(iku.Standframe1[int(iku.frame1)], 0, iku.Standframe2[int(iku.frame2)], 130, iku.x, iku.y)

class Skill1State:

    @staticmethod
    def enter(iku, event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.skill1cheak = 0
        iku.Skill1frame1 = [0, 68, 133, 193, 259, 329, 390, 470, 543, 615, 680, 745]
        iku.Skill1frame2 = [68, 65, 60, 66, 68, 59, 78, 74, 70, 63, 68]
        if event == Skill1:
            iku.motion = 1

    @staticmethod
    def exit(iku, event):
        pass
    @staticmethod
    def do(iku):
        main_state.Enemy_Motion_Cheak = True
        global HP, HPcheak , ationcheak
        if int(iku.skill1cheak) < 8:
            iku.frame1 = (iku.frame1 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11
            iku.frame2 = (iku.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11
        if int(iku.skill1cheak) >= 7 and int(iku.skill1cheak) < 20:
            main_state.Skill1_Start = True
        if int(iku.skill1cheak) > 20:
            iku.frame1 = (iku.frame1 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11
            iku.frame2 = (iku.frame2 + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 11
        iku.skill1cheak = (iku.skill1cheak + SKILL1_PER_ACTION * SKILL1ACTION_PER_TIME * game_framework.frame_time) % 24
        if int(iku.skill1cheak) >= 22:
            iku.skill1cheak=0
            iku.add_event(Stand)
            main_state.Skill1_Start = False
            main_state.Enemy_AtkBuff = 1
            main_state.Player_DefBuff = 1
            main_state.turn = 1
            main_state.DeckShow = 1

    @staticmethod
    def draw(iku):
        if iku.motion == 1:
            iku.skill1.clip_draw(iku.Skill1frame1[int(iku.frame1)], 0, iku.Skill1frame2[int(iku.frame2)], 145, iku.x, iku.y)
class Skill2State:
    @staticmethod
    def enter(iku,event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.S2frame = 0
        iku.Skill2Eframe1 = 0
        iku.skill2cheak = 0
        iku.skill2Px = 300
        iku.skill2Mx = 330
        iku.Skill2frame1 = [0, 70, 130, 200, 283, 356, 422, 490, 597, 732, 912, 1087, 1247, 1375, 1463, 1520]
        iku.Skill2frame2 = [70, 60, 70, 83, 73, 66, 66, 101, 133, 178, 173, 157, 124, 83, 63]
        if event == Skill2:
            iku.motion = 2

    @staticmethod
    def exit(iku,event):
        pass
    @staticmethod
    def do(iku):
        main_state.Enemy_Motion_Cheak = True
        global HP, HPcheak
        if int(iku.skill2cheak) < 11:
            iku.frame1 = (iku.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15
            iku.frame2 = (iku.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15
        if int(iku.skill2cheak) > 5 and int(iku.skill2cheak) < 15:
            if iku.skill2cheak > 8:
                main_state.Skill2_Start = True
                iku.skill2Px += int(MOTION_SPEED_PPS)
        if int(iku.skill2cheak) >= 15:
            iku.frame1 = (iku.frame1 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15
            iku.frame2 = (iku.frame2 + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 15
            main_state.Skill2_Start = False
            iku.skill2Px -= int(MOTION_SPEED_PPS)
        iku.skill2cheak = (iku.skill2cheak + SKILL2_PER_ACTION * SKILL2ACTION_PER_TIME * game_framework.frame_time) % 20
        if int(iku.skill2cheak) >= 19:
            iku.skill2cheak = 0
            iku.add_event(Stand)
            main_state.Enemy_AtkBuff = 1
            main_state.Player_DefBuff = 1
            main_state.turn = 1
            main_state.DeckShow = 1

    @staticmethod
    def draw(iku):
        if iku.motion == 2:
            iku.skill2.clip_draw(iku.Skill2frame1[int(iku.frame1)], 0, iku.Skill2frame2[int(iku.frame2)], 145,iku.x-iku.skill2Px, iku.y)

class Skill3State:
    @staticmethod
    def enter(iku,event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.S3frame = 0
        iku.Skill3Eframe1 = 0
        iku.skill3cheak = 0
        iku.Skill3frame1 = [0, 64, 126, 196, 268, 338, 405]
        iku.Skill3frame2 = [64, 62, 70, 72, 67, 68]
        if event == Skill3:
            iku.motion = 3

    @staticmethod
    def exit(iku,event):
        pass

    @staticmethod
    def do(iku):
        main_state.Enemy_Motion_Cheak = True
        global HP, HPcheak
        if int(iku.skill3cheak) < 19:
            if int(iku.skill3cheak) < 5:
                iku.frame1 = (iku.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6
                iku.frame2 = (iku.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6
            if int(iku.skill3cheak) >= 5:
                main_state.Skill3_Start=True
                if int(iku.skill3cheak) > 17:
                    iku.frame1 = (iku.frame1 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6
                    iku.frame2 = (iku.frame2 + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 6
            iku.skill3cheak = (iku.skill3cheak + SKILL3_PER_ACTION * SKILL3ACTION_PER_TIME * game_framework.frame_time) % 20
        if int(iku.skill3cheak) >= 18:
            iku.skill3cheak = 0
            iku.add_event(Stand)
            main_state.Skill3_Start = False
            main_state.Enemy_AtkBuff = 1
            main_state.Player_DefBuff = 1
            main_state.turn = 1
            main_state.DeckShow = 1

    @staticmethod
    def draw(iku):
        if iku.motion == 3:
            iku.skill3.clip_draw(iku.Skill3frame1[int(iku.frame1)], 0, iku.Skill3frame2[int(iku.frame2)], 145,iku.x, iku.y)

class Laststate:
    @staticmethod
    def enter(iku, event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.lastcheak = 0
        iku.Lastframe1 = [0, 60, 120, 180, 243, 315, 440, 570, 700, 825, 945, 1035]
        iku.Lastframe2 = [60, 60, 60, 63, 72, 125, 130, 130, 125, 120]

        if event == Last:
            iku.motion = 4

    @staticmethod
    def exit(iku, event):
        pass

    @staticmethod
    def do(iku):
        main_state.Enemy_Motion_Cheak = True
        if int(iku.lastcheak) < 34:
            if int(iku.lastcheak) < 8:
                iku.frame1 = (iku.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10
                iku.frame2 = (iku.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10
            if int(iku.lastcheak) >= 8:
                main_state.Last_Start=True
            if int(iku.lastcheak) >= 32:
                iku.frame1 = (iku.frame1 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10
                iku.frame2 = (iku.frame2 + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) % 10

        iku.lastcheak = (iku.lastcheak + LASTCHEAK_PER_ACTION * LASTACTION_PER_TIME * game_framework.frame_time) %35
        if int(iku.lastcheak) >= 34:
            iku.lastcheak = 0
            iku.add_event(Stand)
            main_state.Last_Start = False
            main_state.Enemy_AtkBuff = 1
            main_state.Player_DefBuff = 1
            main_state.turn = 1
            main_state.DeckShow = 1

    @staticmethod
    def draw(iku):
        if iku.motion == 4:
            iku.Lastspell.clip_draw(iku.Lastframe1[int(iku.frame1)], 0, iku.Lastframe2[int(iku.frame2)], 140,iku.x, iku.y)

class Damagestate:
    @staticmethod
    def enter(iku, event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.Damagecheak = 0
        iku.Damageframe = 0
        iku.Damageframe1 = [0, 94, 174, 245]
        iku.Damageframe2 = [94, 80, 73]
        if event == Damage:
            iku.motion = 5
    @staticmethod
    def exit(iku, event):
        pass

    @staticmethod
    def do(iku):
        if int(iku.Damagecheak) < 3:
            iku.frame1 = (iku.frame1+ DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3
            iku.frame2 = (iku.frame2 +DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time) % 3
            iku.Damagecheak = ( iku.Damagecheak + DAMAGE_PER_ACTION * DAMAGEACTION_PER_TIME * game_framework.frame_time)%4
        if int(iku.Damagecheak) >= 3:
            iku.Damagecheak = 0
            iku.add_event(Stand)

    @staticmethod
    def draw(iku):
        if iku.motion == 5:
            iku.Damage.clip_draw(iku.Damageframe1[int(iku.frame1)],0,iku.Damageframe2[int(iku.frame2)],135, iku.x, iku.y)

class Downstate:
    @staticmethod
    def enter(iku, event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.Downcheak=0
        iku.Downframe1 = [0, 125, 240, 374, 514, 651, 793, 945]
        iku.Downframe2 = [125, 115, 134, 140, 136, 140, 158]

        if event == Down:
            iku.motion = 6

    @staticmethod
    def exit(iku, event):
        pass

    @staticmethod
    def do(iku):
        if int(iku.Downcheak) < 20:
            if int(iku.Downcheak) < 6:
                iku.frame1 = (iku.frame1 + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7
                iku.frame2 = (iku.frame2 +DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time) % 7
            iku.Downcheak = (iku.Downcheak + DOWN_PER_ACTION * DOWNACTION_PER_TIME * game_framework.frame_time)%21
        if int(iku.Downcheak) >= 20:
            iku.Downcheak = 20
            #iku.add_event(Stand)

        #iku.timer -= 1

    @staticmethod
    def draw(iku):
        if iku.motion == 6:
            iku.Down.clip_draw(iku.Downframe1[int(iku.frame1)], 0, iku.Downframe2[int(iku.frame2)], 105, iku.x, iku.y-30)
class Item_Doll:
    @staticmethod
    def enter(iku,event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.item1cheak = 0
        iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405]
        iku.item1frame2 = [64, 62, 70, 72, 67, 68]
        if event == Item1:
            iku.motion = 7
    @staticmethod
    def exit(iku,event):
        pass
    @staticmethod
    def do(iku):
        global HP,HPcheak,skillcheak
        if int(iku.item1cheak) < 6:
            if int(iku.item1cheak) < 5:
                iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6
                iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6

            iku.item1cheak = (iku.item1cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7
        if int(iku.item1cheak) >= 6:
            iku.item1cheak = 0
            iku.add_event(Stand)
            main_state.turn = 1
            main_state.DeckShow = 1

    @staticmethod
    def draw(iku):
        if iku.motion == 7:
            iku.item_use.clip_draw(0, 0, 40, 65, 600, 280)
            iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 0, iku.item1frame2[int(iku.frame2)], 145,iku.x, iku.y)
class Item_Potion:
    @staticmethod
    def enter(iku,event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.item2cheak = 0
        iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405]
        iku.item1frame2 = [64, 62, 70, 72, 67, 68]
        if event == Item2:
            iku.motion = 8
    @staticmethod
    def exit(iku,event):
        pass
    @staticmethod
    def do(iku):
        global HP,HPcheak,skillcheak
        if int(iku.item2cheak) < 6:
            if int(iku.item2cheak) < 5:
                iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6
                iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6

            iku.item2cheak = (iku.item2cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7
        if int(iku.item2cheak) >= 6:
            iku.item2cheak = 0
            iku.add_event(Stand)
            main_state.turn = 1
            main_state.DeckShow = 1

    @staticmethod
    def draw(iku):
        if iku.motion == 8:
            iku.item_use.clip_draw(40, 0, 40, 65, 600, 280)
            iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 0, iku.item1frame2[int(iku.frame2)], 145, iku.x,iku.y)

class Item_Clock:
    @staticmethod
    def enter(iku,event):
        iku.frame1 = 0
        iku.frame2 = 0
        iku.item3cheak = 0
        iku.item1frame1 = [0, 64, 126, 196, 268, 338, 405]
        iku.item1frame2 = [64, 62, 70, 72, 67, 68]
        if event == Item3:
            iku.motion = 9
    @staticmethod
    def exit(iku,event):
        pass
    @staticmethod
    def do(iku):
        global HP,HPcheak,skillcheak
        if int(iku.item3cheak) < 6:
            if int(iku.item3cheak) < 5:
                iku.frame1 = (iku.frame1 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6
                iku.frame2 = (iku.frame2 + ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time) % 6

            iku.item3cheak = (iku.item3cheak+ ITEM1_PER_ACTION * ITEM1ACTION_PER_TIME * game_framework.frame_time)%7
        if int(iku.item3cheak) >= 6:
            iku.item3cheak = 0
            iku.add_event(Stand)
            main_state.turn = 1
            main_state.DeckShow = 1

    @staticmethod
    def draw(iku):
        if iku.motion == 9:
            iku.item_use.clip_draw(80, 0, 40, 65, 600, 280)
            iku.skill3.clip_draw(iku.item1frame1[int(iku.frame1)], 0, iku.item1frame2[int(iku.frame2)], 145, iku.x,iku.y)
next_state_table = {
    StandState: {Skill1: Skill1State, Skill2: Skill2State, Skill3:Skill3State,Last:Laststate, Damage:Damagestate,Down:Downstate,Item1:Item_Doll,Item2:Item_Potion,Item3:Item_Clock},
    Skill1State: {Skill1: StandState,  Stand:StandState,Down:Downstate},
    Skill2State: {Skill2: StandState, Stand:StandState,Down:Downstate},
    Skill3State: {Skill3: StandState ,Stand: StandState,Down:Downstate},
    Laststate: {Last:StandState,Stand: StandState,Down:Downstate},
    Damagestate: {Damage:StandState, Stand:StandState,Down:Downstate},
    Downstate: {Down:StandState,Stand:StandState,Damage:StandState,Skill1: StandState,Skill2: StandState,Skill3: StandState,Last:StandState,Item1:StandState,Item2:StandState,Item3:StandState},
    Item_Doll:{Item1:StandState, Stand:StandState,Down:Downstate},
Item_Potion:{Item2:StandState, Stand:StandState,Down:Downstate},
Item_Clock:{Item3:StandState, Stand:StandState,Down:Downstate}

}

class Enemy_Iku:

    def __init__(self):
        self.x, self.y = 600, 200
        self.stand = load_image('./FCGimage/Iku-Standing-Motion.png')

        self.skill1 = load_image('./FCGimage/IkuSkill1-Motion.png')

        self.skill2 = load_image('./FCGimage/IkuSkill2-Motion.png')

        self.skill3 = load_image('./FCGimage/IkuSkill3-Motion.png')

        self.Lastspell = load_image('./FCGimage/IkuLastspell-Motion.png')
        self.Lasteffect = load_image('./FCGimage/IkuLastspell1-1.png')
        self.Lasteffect2 = load_image('./FCGimage/IkuLastspell1-2.png')

        self.Damage = load_image('./FCGimage/IkuDamage-Motion.png')

        self.Down = load_image('./FCGimage/Iku-Down-Motion.png')
        self.skill1_sound = load_wav('./voice/iku-skill1.wav')
        self.skill1_sound.set_volume(50)
        self.skill2_sound = load_wav('./voice/iku-skill2.wav')
        self.skill2_sound.set_volume(50)
        self.skill3_sound = load_wav('./voice/iku-skill3.wav')
        self.skill3_sound.set_volume(50)
        self.last_sound = load_wav('./voice/iku-Last.wav')
        self.last_sound.set_volume(50)
        self.damage_sound = load_wav('./voice/iku-damage.wav')
        self.damage_sound.set_volume(30)
        self.down_sound = load_wav('./voice/iku-down.wav')
        self.down_sound.set_volume(70)
        self.item_sound = load_wav('./voice/iku-item.wav')
        self.item_sound.set_volume(50)
        self.item_use = load_image('./FCGimage/commonCard.png')
        self.dir = 1
        self.motion = 0
        self.frame = 0
        self.timer = 0
        self.build_behavior_tree()
        self.event_que = []
        self.cur_state = StandState
        self.cur_state.enter(self, None)

    def turn_cheak(self):
        if main_state.turn == -1:
            return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL
    def action_cheak(self):
        global ationcheak
        if ationcheak ==0:
            return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL
    def finish_atk_cheak(self):
        global ationcheak
        if PlayerHP.damage >=212:
            ationcheak=3
            return BehaviorTree.SUCCESS
        else:
            return  BehaviorTree.FAIL
    def buff_ready_cheak(self):
        global ationcheak
        if main_state.Enemy_DefBuff==0 or main_state.Enemy_AtkBuff==3:
            ationcheak= random.randint(1,4)
            return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL
    def atk_cheak(self):
        global ationcheak
        if main_state.Enemy_DefBuff == 1 and main_state.Enemy_AtkBuff == 1:
            ationcheak = random.randint(1, 7)
            return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL
    def enemy_atk_buff_cheak(self):
        if main_state.Enemy_AtkBuff ==3:
            return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL
    def player_atk_buff_cheak(self):
        global ationcheak
        if main_state.Player_AtkBuff==3:
            success_cheak=random.randint(1,100)
            if success_cheak>75:
                ationcheak=5
                return BehaviorTree.SUCCESS
            else:
                ationcheak=random.randint(1, 7)
                return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL
    def enemy_HP_cheak(self):
        global ationcheak
        if EnemyHP.damage>200:
            success_cheak = random.randint(1, 100)
            if success_cheak>50:
                ationcheak=7
                return BehaviorTree.SUCCESS
            else:
                ationcheak=random.randint(1, 7)
                return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL

    def Hard_finish_atk_cheak(self):
        global ationcheak
        if PlayerHP.damage >=102:
            ationcheak=4
            return BehaviorTree.SUCCESS
        else:
            return  BehaviorTree.FAIL

    def build_behavior_tree(self):
        turn_cheak_node = LeafNode("Turn Cheak", self.turn_cheak)
        action_cheak_node = LeafNode("Action Stand", self.action_cheak)
        finish_atk_cheak_node = LeafNode("Finish_Atk", self.finish_atk_cheak)
        buff_ready_cheak_node = LeafNode("Buff Ready Cheak", self.buff_ready_cheak)
        atk_cheak_node = LeafNode("Atk", self.atk_cheak)
        ##Hard
        enemy_atk_buff_cheak_node =  LeafNode("Atk_Buff_Cheak", self.enemy_atk_buff_cheak)
        Hard_finish_atk_cheak_node = LeafNode("Finish_Atk", self.Hard_finish_atk_cheak)
        player_atk_buff_cheak_node = LeafNode("Player_Buff_Cheak", self.player_atk_buff_cheak)
        enemy_hp_cheak_node = LeafNode("Enemy_HP_Cheak", self.enemy_HP_cheak)

        ##Nomal
        Finsh_node = SequenceNode("Finish")
        Finsh_node.add_children(turn_cheak_node, action_cheak_node,finish_atk_cheak_node)
        Buff_Atk_node =SequenceNode("BuffAtk")
        Buff_Atk_node.add_children(turn_cheak_node,action_cheak_node,buff_ready_cheak_node)
        Atk_node = SequenceNode("Atk")
        Atk_node.add_children(turn_cheak_node, action_cheak_node,atk_cheak_node)
        action_chase_node = SelectorNode("ActionChase")
        action_chase_node.add_children(Finsh_node, Buff_Atk_node,Atk_node)
        ##Hard
        Hard_Finsh_node = SequenceNode("Hard-Finish")
        Hard_Finsh_node.add_children(turn_cheak_node,action_cheak_node, enemy_atk_buff_cheak_node, Hard_finish_atk_cheak_node)
        Hard_Block_node = SequenceNode("Hard-Block")
        Hard_Block_node.add_children(turn_cheak_node, action_cheak_node,player_atk_buff_cheak_node)
        Hard_HP_node = SequenceNode("Hard-Block")
        Hard_HP_node.add_children(turn_cheak_node, action_cheak_node, enemy_hp_cheak_node)
        Hard_action_chase_node = SelectorNode("Hard_ActionChase")
        Hard_action_chase_node.add_children(Hard_Finsh_node, Hard_Block_node, Hard_HP_node,Buff_Atk_node,Atk_node)
        if BackgroundSelection.Level_cheak==1:
            self.ation = BehaviorTree(action_chase_node)
        if BackgroundSelection.Level_cheak == 2:
            self.ation = BehaviorTree(Hard_action_chase_node)

    def add_event(self, event):
        self.event_que.insert(0, event)

    def update(self):
        self.ation.run()
        self.cur_state.do(self)
        if len(self.event_que) > 0:
            event = self.event_que.pop()
            self.cur_state.exit(self, event)
            self.cur_state = next_state_table[self.cur_state][event]
            self.cur_state.enter(self, event)

    def draw(self):
        self.cur_state.draw(self)

    def handle_event(self, event):
        pass


import requests
import json
import logging

headers = {
  'content-type': 'application/json',
  'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'
}

def get(url, params=None, format=True):
    try:
        res = requests.get(url, params=params, headers=headers)
        if format:
            res = json.loads(res.text)
        return res
    except Exception as e:
        logging.error(e)
        return None


r'''Evaluation related functions.
'''

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import os
import six

from google.protobuf import message
import numpy as np
from tensorflow.core.framework import summary_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary as core_summary
from tensorflow.python.training import basic_session_run_hooks
from tensorflow.python.training import moving_averages
from tensorflow.python.training import session_run_hook
from tensorflow.python.training import slot_creator
from tensorflow.python.training import training_util

from hybridbackend.tensorflow.framework.context import Context
from hybridbackend.tensorflow.framework.device import device_function
from hybridbackend.tensorflow.framework.ops import ModeKeys
from hybridbackend.tensorflow.framework.rewriting import GraphRewriting
from hybridbackend.tensorflow.framework.rewriting import scope
from hybridbackend.tensorflow.training.variables import disable_variable_update
from hybridbackend.tensorflow.training.variables import reuse_variables

class EvaluationRewriting(GraphRewriting):
  r'''Rewriting evaluation.
  '''
  def __init__(self, ):
    super().__init__()
    self._prev_create_slot_var = None
    self._prev_assign_moving_average = None
    self._patched = False

  def wraps_create_slot_var(self, fn):
    r'''wraps create slot var to eliminate out scope
    '''
    def wrapped_create_slot_var(primary, *args, **kwargs):
      variable_scope_name = vs.get_variable_scope()._name  # pylint: disable=protected-access
      if (not isinstance(primary, variables.Variable)
          and ModeKeys.EVAL in variable_scope_name):
        vs.get_variable_scope()._name = variable_scope_name.replace(  # pylint: disable=protected-access
          ModeKeys.EVAL, '')
      return fn(primary, *args, **kwargs)
    return wrapped_create_slot_var

  def wraps_assign_moving_average(self, assign_moving_avg_fn):
    r'''disable the update of slot variables within moving average
    '''
    def wrapped_assign_moving_average(
        variable, value, decay, zero_debias=True, name=None):
      with disable_variable_update():
        return assign_moving_avg_fn(
          variable, value, decay, zero_debias=zero_debias, name=name)
    return wrapped_assign_moving_average

  def begin(self):
    r'''Rewrites API.
    '''
    if Context.get().options.mode == ModeKeys.EVAL:
      self._prev_create_slot_var = slot_creator._create_slot_var  # pylint: disable=protected-access
      slot_creator._create_slot_var = self.wraps_create_slot_var(  # pylint: disable=protected-access
        self._prev_create_slot_var)
      self._prev_assign_moving_average = moving_averages.assign_moving_average
      moving_averages.assign_moving_average = self.wraps_assign_moving_average(
        self._prev_assign_moving_average)
      self._patched = True

  def end(self):
    r'''Revert API rewriting.
    '''
    if self._patched:
      slot_creator._create_slot_var = self._prev_create_slot_var  # pylint: disable=protected-access
      moving_averages.assign_moving_average = self._prev_assign_moving_average

GraphRewriting.register(EvaluationRewriting)

EvaluationSpec = collections.namedtuple(
  'EvaluationSpec', ['name', 'hooks', 'update_op', 'eval_dict'])

class EvaluationHook(session_run_hook.SessionRunHook):
  r'''Hook to make evaluation along with training.
  '''
  def __init__(
      self, fn,
      steps=100,
      every_n_iter=1000,
      summary_dir=None,
      history=None):
    r'''Evaluates specific function.

    Args:
      fn: Function returns update_op, metric ops and hooks.
      steps: Number of steps for which to evaluate model.
      every_n_iter: `int`, runs the evaluator once every N training iteration.
      summary_dir: Directory for summaries.
      history: History of eval metrics. history should support `append` method.
    Raises:
      ValueError: if `every_n_iter` is non-positive or it's not a single machine
        training
    '''
    if every_n_iter is None or every_n_iter <= 0:
      raise ValueError(f'invalid every_n_iter={every_n_iter}.')
    self._fn = fn
    self._steps = steps
    self._every_n_iter = every_n_iter
    self._summary_dir = summary_dir
    self._history = history

  def begin(self):
    r'''Preprocess global step and evaluation's hooks.
    '''
    self._evaluation_specs = ops.get_collection_ref(EvaluationSpec.__name__)
    if len(self._evaluation_specs) > 0:
      raise ValueError('Only one evaluation spec allowed in a graph')

    self._timer = None
    self._iter_count = 0
    self._hooks = []

    self._timer = basic_session_run_hooks.SecondOrStepTimer(
      every_steps=self._every_n_iter)
    self._timer.reset()

    with ops.device(device_function), reuse_variables(vs.AUTO_REUSE):
      with scope(mode=ModeKeys.EVAL, comm_pool_name=ModeKeys.EVAL):
        with ops.name_scope(ModeKeys.EVAL):
          eval_spec = self._fn()
          if isinstance(eval_spec, dict):
            eval_dict = {}
            update_ops = []
            for metric_name, metric_val_and_update in eval_spec.items():
              if not isinstance(metric_name, six.string_types):
                raise ValueError(f'Metric name {metric_name} should be a str')
              if (not isinstance(metric_val_and_update, (tuple, list))
                  or len(metric_val_and_update) != 2):
                raise ValueError(
                  f'{metric_val_and_update} should be a tuple '
                  'of (metric, update_op)')
              eval_dict[metric_name] = metric_val_and_update[0]
              update_ops.append(metric_val_and_update[1])
            update_op = control_flow_ops.group(update_ops)
            eval_spec = EvaluationSpec(
              name=EvaluationSpec.__name__,
              hooks=None,
              update_op=update_op,
              eval_dict=eval_dict)
          if not isinstance(eval_spec, EvaluationSpec):
            raise ValueError('eval_fn should return a dict or a EvaluationSpec')
          self._evaluation_specs.append(eval_spec)
          if eval_spec.hooks:
            self._hooks.extend(eval_spec.hooks)
          eval_dict = dict(eval_spec.eval_dict)
          if ops.GraphKeys.GLOBAL_STEP not in eval_dict:
            global_step_tensor = training_util.get_global_step(
              ops.get_default_graph())
            eval_dict[ops.GraphKeys.GLOBAL_STEP] = global_step_tensor
          for h in self._hooks:
            h.begin()
          self._update_op = eval_spec.update_op
          self._metrics = eval_dict

  def after_create_session(self, session, coord):  # pylint: disable=unused-argument
    r'''Call evaluation's hooks.
    '''
    if ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS):
      raise ValueError(
        'EvaluationHook does not support saveables other than global '
        'variables.')
    for h in self._hooks:
      h.after_create_session(session, coord)

  def after_run(self, run_context, run_values):  # pylint: disable=unused-argument
    r'''Runs evaluator after session run.
    '''
    self._iter_count += 1
    if self._timer.should_trigger_for_step(self._iter_count):
      ctx_stop_requested = run_context.stop_requested
      run_context._stop_requested = False  # pylint: disable=protected-access
      self._evaluate(run_context)
      run_context._stop_requested = ctx_stop_requested  # pylint: disable=protected-access

  def _call_before_run_hooks(
      self, run_context, fetch_dict, user_feed_dict=None):
    r'''Call hooks.before_run and handle requests from hooks.
    '''
    hook_feeds = {}
    for hook in self._hooks:
      request = hook.before_run(run_context)
      if request is not None:
        if request.fetches is not None:
          fetch_dict[hook] = request.fetches
        if request.feed_dict:
          hook_feeds.update(request.feed_dict)

    if not hook_feeds:
      return user_feed_dict

    if not user_feed_dict:
      return hook_feeds

    hook_feeds.update(user_feed_dict)
    return hook_feeds

  def _run(self, run_context, fetches):
    r'''Run the evaluation.
    '''
    if isinstance(fetches, dict):
      actual_fetches = fetches
    else:
      actual_fetches = {fetches: fetches}
    eval_metrics = self._call_before_run_hooks(
      run_context, actual_fetches)
    eval_results = run_context.session.run(
      actual_fetches, feed_dict=eval_metrics)
    for hook in self._hooks:
      hook.after_run(
        run_context,
        session_run_hook.SessionRunValues(
          results=eval_results.pop(hook, None),
          options=config_pb2.RunOptions(),
          run_metadata=config_pb2.RunMetadata()))
    return eval_results

  def _write_dict_to_summary(self, dictionary):
    r'''Write evaluation results to summary directory.
    '''
    current_global_step = dictionary[ops.GraphKeys.GLOBAL_STEP]
    prev_np_printoptions = np.get_printoptions()
    np.set_printoptions(suppress=True)
    stats = ', '.join(
      f'{k} = {v}'
      for k, v in sorted(six.iteritems(dictionary))
      if not (
        isinstance(v, six.binary_type)
        or k == ops.GraphKeys.GLOBAL_STEP))
    np.set_printoptions(**prev_np_printoptions)
    logging.info('Saving metrics for step %d: %s', current_global_step, stats)

    summary_dir = self._summary_dir
    if Context.get().world_size > 1:
      summary_dir = os.path.join(summary_dir, f'{Context.get().rank}')
    summary_writer = core_summary.FileWriterCache.get(summary_dir)
    summary_proto = summary_pb2.Summary()

    for key in dictionary:
      if dictionary[key] is None:
        continue
      if key == 'global_step':
        continue
      if isinstance(dictionary[key], (np.float32, float)):
        summary_proto.value.add(tag=key, simple_value=float(dictionary[key]))
      elif isinstance(dictionary[key], (np.int64, np.int32, int)):
        summary_proto.value.add(tag=key, simple_value=int(dictionary[key]))
      elif isinstance(dictionary[key], six.binary_type):
        try:
          summ = summary_pb2.Summary.FromString(dictionary[key])
          for i, _ in enumerate(summ.value):
            summ.value[i].tag = f'{key}/{i}'
          summary_proto.value.extend(summ.value)
        except message.DecodeError:
          logging.warning(
            'Skipping summary for %s, cannot parse string to Summary.', key)
          continue
      elif isinstance(dictionary[key], np.ndarray):
        value = summary_proto.value.add()
        value.tag = key
        value.node_name = key
        tensor_proto = tensor_util.make_tensor_proto(dictionary[key])
        value.tensor.CopyFrom(tensor_proto)
        # pylint: disable=line-too-long
        logging.info(
          'Summary for np.ndarray is not visible in Tensorboard by default. '
          'Consider using a Tensorboard plugin for visualization (see '
          'https://github.com/tensorflow/tensorboard-plugin-example/blob/master/README.md'
          ' for more information).')
        # pylint: enable=line-too-long
      else:
        logging.warning(
          'Skipping summary for %s, must be a float, np.float32, np.int64, '
          'np.int32 or int or np.ndarray or a serialized string of Summary.',
          key)
    summary_writer.add_summary(summary_proto, current_global_step)
    summary_writer.flush()

  def _evaluate(self, run_context):
    r'''Evaluate on run context.
    '''
    for _ in range(self._steps):
      if not run_context.stop_requested:
        self._run(run_context, self._update_op)
    metric_values = self._run(run_context, self._metrics)
    if metric_values is not None:
      if self._history is not None:
        self._history.append(metric_values)
      self._write_dict_to_summary(metric_values)
    self._timer.update_last_triggered_step(self._iter_count)


"""
Graph is a data structure with vertex and edges, an edge is a
representation of a relationship between two vertex, ex:
A -- B is the same of B -- A

A DiGraph is a direct graph with arrows pointing to the next item ex:
A -> B -> C

Breadth First Search says if there are a path from A to B
If there are a path, the breadth first search gives the minimum path

Breadth First Search has O(V + E) complexity, where V is the number of
vertex and E is a number of edges, then it's complexity is O(N)

Applications:

1 - Write a AI algorithm that calcule the minimum amount of necessary
moviments to win a checkers game.

2 - Write a Spell Checker that calcule the minimum number of editions
to fix a wrong message in a correct message, ex: REABER to READER

3 - Find the doctor that suits your health plan most close to you
"""
from collections import deque

di_graph = {}

# direct friends
di_graph["You"] = ["Claire", "Alice", "Bob"]

# friends of friends
di_graph["Bob"] = ["Anuj", "Peggy"]
di_graph["Claire"] = ["Thom", "Jonny"]
di_graph["Alice"] = ["Peggy"]

# friends of friends of friends
di_graph["Anuj"] = []
di_graph["Peggy"] = []
di_graph["Thom"] = []
di_graph["Jonny"] = []

# no relation
di_graph["Alone"] = []

def breadth_first_search(di_graph, from_vertice, to_vertice):
    verified_list = set()
    queue_to_search = deque()
    queue_to_search.extend(di_graph[from_vertice])
    while queue_to_search:
        friend = queue_to_search.popleft()
        if friend not in verified_list:
            if friend == to_vertice:
                return True

        queue_to_search.extend(di_graph[friend])
        verified_list.add(friend)

    return False

assert breadth_first_search(di_graph, "You", "Bob") is True
assert breadth_first_search(di_graph, "You", "Claire") is True
assert breadth_first_search(di_graph, "You", "Alice") is True

assert breadth_first_search(di_graph, "You", "Anuj") is True
assert breadth_first_search(di_graph, "You", "Peggy") is True
assert breadth_first_search(di_graph, "You", "Thom") is True
assert breadth_first_search(di_graph, "You", "Jonny") is True

assert breadth_first_search(di_graph, "You", "Alone") is False


import pygame, sys
from pygame.locals import *
import random, time, math

class Game:
    def __init__(self):
        # Initialize Pygame
        self.initialized = False
        self._initializeGame()

        # Screen information
        self.SCREEN_WIDTH = 800
        self.SCREEN_HEIGHT = 600
        self.DISPLAY = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
        self.clock = pygame.time.Clock()
        self.FPS = 60
        self.GAME_OVER_SCREEN_DURATION = 3

        # Setting up game variables
        self.game_over = False
        self.score = 0
        self.PLAYER_DIMENTIONS = (80, 80)
        self.TARGET_DIMENTIONS = (40, 40)
        self.TARGET_NUMBER = 3
        self.SPEED = 5
        self.GAME_DURATION = 10

        #Setting up Fonts
        self.font = pygame.font.SysFont("Verdana", 60)
        self.font_small = pygame.font.SysFont("Verdana", 30)

        # Predefined some colors
        self.BLUE  = (0, 0, 255)
        self.RED   = (255, 0, 0)
        self.GREEN = (0, 255, 0)
        self.BLACK = (0, 0, 0)
        self.WHITE = (255, 255, 255)

        # Creating player
        self.player = self.Player(self.PLAYER_DIMENTIONS, self.RED)
        self.player.moveTo(self.SCREEN_WIDTH//2, self.SCREEN_HEIGHT//2)

        #Creating Sprites Groups
        self.targets = pygame.sprite.Group()
        self.all_sprites = pygame.sprite.Group()
        self.all_sprites.add(self.player)

        #Initializing Targets
        self._initializeTargets()

    class Target(pygame.sprite.Sprite):
        def __init__(self, dimensions, color):
            super().__init__()
            self.width = dimensions[0]
            self.height = dimensions[1]
            self.rect = pygame.Rect(0, 0, self.width, self.height)
            self.color = color

        def draw(self, surface):
            pygame.draw.rect(surface, self.color, self.rect)

        def moveTo(self, x, y):
            self.rect.center = (x, y)

    class Player(pygame.sprite.Sprite):
        def __init__(self, dimensions, color):
            super().__init__()
            self.rect = pygame.Rect(0,0,dimensions[0],dimensions[1])
            self.color = color

        def draw(self, surface):
            pygame.draw.rect(surface, self.color, self.rect)

        def moveTo(self, x, y):
            self.rect.center = (x, y)

    def _movePlayer(self):
        pressed_keys = pygame.key.get_pressed()

        if self.player.rect.top > 0:
            if pressed_keys[K_UP]:
                self.player.rect.move_ip(0, -5)

        if self.player.rect.bottom < self.SCREEN_HEIGHT:
            if pressed_keys[K_DOWN]:
                self.player.rect.move_ip(0,5)

        if self.player.rect.left > 0:
            if pressed_keys[K_LEFT]:
                self.player.rect.move_ip(-5, 0)

        if self.player.rect.right < self.SCREEN_WIDTH:
            if pressed_keys[K_RIGHT]:
                self.player.rect.move_ip(5, 0)

    def _initializeGame(self):
        if self.initialized:
            return
        self.initialized = True
        pygame.init()
        pygame.display.set_caption("Game")

    def _initializeTargets(self):
        # Calculate position of all targets
        for i in range(self.TARGET_NUMBER):
            newTarget = self.Target(self.TARGET_DIMENTIONS, self.BLUE)
            while True:
                newTarget.moveTo(random.randint(newTarget.width/2, self.SCREEN_WIDTH - newTarget.width/2),
                                    random.randint(newTarget.height/2, self.SCREEN_HEIGHT - newTarget.height/2))
                #check if newTarget is colliding with any other sprite
                collision = pygame.sprite.spritecollideany(newTarget, self.all_sprites)
                if not collision:
                    self.all_sprites.add(newTarget)
                    self.targets.add(newTarget)
                    break

    def _gameOver(self):
        self.game_over = True
        self.DISPLAY.fill(self.BLACK)
        text = self.font.render("Game Over", True, self.WHITE)
        text_rect = text.get_rect()
        text_x = self.DISPLAY.get_width() / 2 - text_rect.width / 2
        text_y = self.DISPLAY.get_height() / 2 - text_rect.height / 2
        self.DISPLAY.blit(text, [text_x, text_y])
        pygame.display.flip()

        timeToClose = self.GAME_OVER_SCREEN_DURATION
        while timeToClose > 0:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        self.reset()
                        self.play()
                        return
            self.clock.tick(self.FPS)
            timeToClose -= 1/self.FPS

        pygame.quit()
        sys.exit()

    def reset(self):
        self.score = 0
        self.game_over = False
        self.all_sprites.empty()
        self.all_sprites.add(self.player)
        self.targets.empty()
        self._initializeTargets()
        self.player.moveTo(self.SCREEN_WIDTH//2, self.SCREEN_HEIGHT//2)

    def play(self):
        # Initialize Pygame if not initialized
        if not self.initialized:
            self._initializeGame()

        # Game Loop
        playTime = self.GAME_DURATION
        while playTime > 0:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        self.reset()
                        playTime = self.GAME_DURATION

            #Draws the background
            self.DISPLAY.fill(self.BLACK)

            #Moves and Re-draws all Sprites
            self._movePlayer()
            self.player.draw(self.DISPLAY)
            for entity in self.targets:
                entity.draw(self.DISPLAY)

            #To be run if collision occurs between Player and Target
            collision = pygame.sprite.spritecollideany(self.player, self.targets)
            if collision:
                self.score += 1
                collision.kill()
                newTarget = self.Target(self.TARGET_DIMENTIONS, self.BLUE)
                while True:
                    newTarget.moveTo(random.randint(newTarget.width/2, self.SCREEN_WIDTH - newTarget.width/2),
                                        random.randint(newTarget.height/2, self.SCREEN_HEIGHT - newTarget.height/2))
                    #check if newTarget is colliding with any other sprite
                    collision = pygame.sprite.spritecollideany(newTarget, self.all_sprites)
                    if not collision:
                        self.all_sprites.add(newTarget)
                        self.targets.add(newTarget)
                        newTarget.draw(self.DISPLAY)
                        break

            #Draws the score
            scoreText = self.font.render("Score: " + str(self.score), True, self.WHITE)
            self.DISPLAY.blit(scoreText, (10,10))

            #Draws the timer
            timer = self.font_small.render(str(math.ceil(playTime)), True, self.WHITE)
            self.DISPLAY.blit(timer, (self.SCREEN_WIDTH/2 - timer.get_rect().width/2, 10))

            pygame.display.update()
            self.clock.tick(self.FPS)
            playTime -= 1/self.FPS  #Reduce the timer by 1/60 second per frame
        self.game_over = True
        self._gameOver()

    def GetScore(self):
        return self.score

if __name__ == "__main__":
    game = Game()
    game.play()
    print(game.GetScore())