import random
import time
CT=0
dtime=0
realhealth=20
r = 0
Puses = 0
# axeD == 0
# pickaxeD == 0
# swordD == 0

i = [ 0 , 0 , 0 , 0 , 0 , 0]
#_ =[ 0 , 1 , 2 , 3 , 4 , 5]
#i = [ STICKS , LOGS , PLANKS , COBBLE , Iron , Torches]

d = [ 0 , 0 , 0 , 0]
#d = [Pickaxe , Sword, Sovel , Axe]
# 1=WOOD 2=STONE 3=IRON

f = [ 0 , 0 , 0]
#f = [Rotten Flesh , Bones , Steak]

o = [0 , 0]
#o = [Coal , Iron Ore]

if d[1]== 0:
	Suses =0

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#OVERWORLD OVERWORLD OVERWORLD OVERWORLD OVERWORLD OVERWORLD OVERWORLD
def overworld():

	global dtime

	print ('\n {OUTSIDE}.')
	choice = input('>chop< OR >mine< OR >craft<? OR >smelt< ')
	choice = str(choice)
	if choice == 'chop':
		trees()
	elif choice == 'mine':
		mine()
	elif choice == 'smelt':
		furnace()
	elif choice == 'i':
		invintory()
	elif choice == 'd':
		hud()
	elif choice == 't':
		atime()
	elif choice == 'o':
		ores()
	elif choice == 'addtime':
		dtime += 5
		if dtime >=10 and dtime <= 25:
			night()
		else:
			overworld()
	elif choice == 'h':
		health()
	elif choice == 'f':
		food()
	elif choice == 'craft':
		craft()
	elif choice == 'cancel':
		print('Thanks for Playing')
	elif choice == 'help':
		help()
	else:
		overworld()

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# NIGHT NIGHT NIGHT NIGHT NIGHT NIGHT NIGHT NIGHT NIGHT NIGHT NIGHT

def night():

	global dtime
	global realhealth
	global strat
	global livesLost

	while dtime >=10 and dtime < 25:
		monster = random.randint(1,5)
		if monster == 1: #ZOMBIE
				print('\nZOMBIE attacks')
				fightMonster()
		elif monster == 2: #SKELETON
				print('\nSKELETON attacks')
				fightMonster()
		elif monster == 3: #CREEPER
				print('\nCREEPER attacks')
				fightMonster()
	#SAFE
		elif monster == 4 or monster == 5:
			print('\n SAFE')

			strat = input ('____? ')
			if strat == 'run':
				timepassed = random.randint(2,5)
				dtime += timepassed
				night()
			if strat == 'hide':
				timePassedTierI = random.randint(1,3)
				if timePassedTierI == 1:
					timepassed = random.randint(2,8)
					dtime += timepassed
					night()
				if timePassedTierI == 2:
					timepassed = random.randint(4,6)
					dtime += timepassed
					night()
				if timePassedTierI == 3:
					timepassed = random.randint(3,7)
					dtime += timepassed
					night()
	dtime = 0
	overworld()
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#FIGHT DEM MONSTERS

def fightMonster():
	global realhealth
	global livesLost
	global monster
	global dtime
	global swordD

	strat = input('_____? ')
	live = random.randint(1,5)
#RUN AWAY
	if strat == 'run' and live != 4:
		print ('You LIVE')
		dtime += 1
		night()
	if strat == 'fight' and live !=4:
#FIGHT (NO SWORD)
		if d[1] == 0:
			print ('You need a SWORD to fight.')
			live = random.randint(1,5)
			if live == 3 or live == 2:
				print ('You LIVE')
				# global monster
				# if monster == 1:
				# 	monsterDrops = random.randint(1,3)
				# 	print ('{} Rotten Flesh'.format(monsterDrops))

				dtime += 1
				night()
			else:
				livesLost = 0
				livesLost = random.randint(2,7)
				if livesLost >= realhealth:
					die()
				else:
					print('- {} HP'.format(livesLost))
					realhealth -= livesLost
					print ('{} HP'.format(realhealth))
					night()
#FIGHT WITH SWORD
		elif d[1] == 1:
			if live == 1:
				livesLost = 0
				livesLost = random.randint(3,8)
				if livesLost >= realhealth:

					if d[1] == 0:
						Suses = 0
					elif d[1] > 0:
						Suses -= 1
						if Suses == 0:
							print('Your SWORD broke')
							d[0] == 0
					else:
						print('Sword HP: {}'.format(Suses))

					die()

				else:
					('- {} HP'.format(livesLost))
					realhealth -= livesLost
					print ('{} HP'.format(realhealth))

				if d[1] == 0:
					Suses = 0
				elif d[1] > 0:
					Suses -= 1
					if Suses == 0:
						print('Your SWORD broke')
						d[0] == 0
				else:
					print('Sword HP: {}'.format(Suses))

					night()
			else:
				print ('You LIVE')
				night()
#LOST SOME LIFE
	elif live == 4:
		livesLost = 0
		livesLost = random.randint(3,8)
		if livesLost >= realhealth:
			die()
		else:
			print('- {} HP'.format(livesLost))
			realhealth -= livesLost
			print ('{} HP'.format(realhealth))
			night()
#ASK FOR THE TIME
	elif strat == 't':
			print('{}'.format(time))
			night()
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE DIE

def die():
	global dtime
	global r
	global repeat
	global i

	dtime += 3
	print ('You DIED')

	# while repeat <= 4:
	# 	rd == 5
	# 	if i[rd] > 4:
	# 		i[rd] -= 5
	# 		rd += 1
	# 		repeat += 1
	# 	else:
	# 		i[rd]== 0
	# 		rd += 1
	# 		repeat += 1

	# for x in range(len(i)):
	# 	r == 0
	# 	if i[r] > 4:
	# 		i[r] -= 5
	# 		r += 1
	# 	else:
	# 		i[r]== 0
	# 		# rd += 1
	# stuffLost = random.randint(5,7)
	# r = 1
	# goagain = 0
	# while goagain <= 4:
	# 	if i[r] < 3:
	# 		i[r] = 4
	# 		r += 1
	# 	else:
	# 		i[r] -= stufflost
	# 		r += 1
	i = [ 0 , 0 , 0 , 0 , 0 , 0]

	print('I = {}'.format(i))

	d = [0 , 0 , 0 ,0]
	if dtime >=10 and dtime <= 25:
		night()
	else:
		overworld()
		dtime = 0

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# TREES TREES TREES TREES TREES TREES TREES TREES TREES TREES TREES

def trees():
	global logsDropped
	global dtime
	global Auses
	print ('\n Chop.' , end = '\r')
	time.sleep(0.30) #delay
	print (' Chop..' , end = '\r')
	time.sleep(0.30) #delay
	print (' Chop...')
	time.sleep(0.30) #delay

	dtime += int(1)

	print('\n')

	SticksDropped = random.randint(0,4)
	SticksDropped += d[3]
	if SticksDropped != 0:
		print ('+ {} STICKS'.format(SticksDropped))
		i[0] += SticksDropped

	logsDropped = random.randint(4,7)
	logsDropped += d[3]
	print ('+ {} LOGS'.format(logsDropped))
	i[1] += logsDropped

	if d[3] == 0:
		Auses = 0

	elif d[3] > 0:
		Auses -= 1
		if Auses == 0:
			print('Your AXE broke')
			d[3] = 0
		else:
			print('Axe HP: {}'.format(Auses))
	overworld()

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# MINE MINE MINE MINE MINE MINE MINE MINE MINE MINE MINE MINE MINE MINE

def mine():

	global dtime
	global Puses

	if dtime <10:
		print ('\nMine.' , end='\r')
		time.sleep(0.40) #delay
		print ('Mine..' , end='\r')
		time.sleep(0.40) #delay
		print ('Mine...')
		time.sleep(0.40) #delay

		dtime += int(1)

		print('\n')

		if d[0]==0:
			print ('Craft a PICKAXE to mine')
		if d[0]==1:
			CobbleDropped = random.randint(4,7)
			print ('+ {} COBBLESTONE.'.format(CobbleDropped))
			i[3] += CobbleDropped

			CoalDropped = random.randint(0,3)
			if CoalDropped != 0:
				print('+ {} COAL.'.format(CoalDropped))
				o[0] += CoalDropped

		if d[0]==2:
			CobbleDropped = random.randint(6,9)
			print ('+ {} COBBLESTONE.'.format(CobbleDropped))
			i[3] += CobbleDropped

			CoalDropped = random.randint(3,6)
			print('+ {} COAL.'.format(CoalDropped))
			o[0] += CoalDropped

			IronOreDropped = random.randint(0,2)
			if IronOreDropped != 0:
				print('+ {} IRON ORE.'.format(IronOreDropped))
				o[1]+= IronOreDroppd

	if d[0] == 0:
		Puses = 0

	elif d[0] > 0:
		Puses -= 1
		if Puses == 0:
			print('Your PICKAXE broke')
			d[0] = 0
		else:
			print('Pickaxe HP: {}'.format(Puses))
	overworld()

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# OTHERS OTHERS OTHERS OTHERS OTHERS OTHERS OTHERS OTHERS OTHERS OTHERS
def invintory():
	print ('\n{}'.format(i))
	print(' S, L, P, Cb ,Ii,T')
	overworld()

def hud():
	print ('{}'.format(d))
	print('P,S,Sh,A')
	overworld()

def atime():
	global atime
	print ('{}'.format(dtime))
	if dtime <10:
		overworld()
	else:
		night()

def health():
	global realhealth
	print ('{} HP'.format(realhealth))
	overworld()

def food():
	print('{}'.format(f))
	overworld()

def ores():
	print('{}'.format(o))
	print('Cl,Io')
	overworld()

def help():
	print('\nWelcome to MinePath. You have entered the help tutorial.')
	print('To make a choice in the {OVERWORLD}, enter in the >code<')
	print('Other {OVERWOLD} commands are: >t< >i< >o< >d< >h<')
	print('\n>t< gives you the time')
	print('>i< and >o< will give you your invintory and ore invin.')
	print('>d< shows you your tools and >h< shows your health')
	print('Most commands can be run wherever there is a promt')
	print('\n>d< will give you a list of numbers.')
	print('-The first slot is your Pickaxe, second Sword, third Shovel, fourth Axe.')
	print('-The number in each slot is the material. 1=wood 2=stone 3=iron')
	print('\nIn the craft and smelt interface you enter the whole command or just the first letter.')
	print('-When asked if you want to smelt or craft again (____?)...')
	print(' You may enter " " or "yes" to craft again.')
	print('\nYou can reaccess this tutorial whenever you are in the {OVERWORLD}')
	time.sleep(5) #delay

	overworld()

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# CRAFT CRAFT CRAFT CRAFT CRAFT CRAFT CRAFT CRAFT CRAFT CRAFT CRAFT CRAFT

def craft():
	global CT
	global inputt
	global Auses
	global Puses
	global Suses

	while CT == 0:
		if i[1] == 0:
			print('You dont have any materials.')
			overworld()
#No plank
		if i[1] > 0 and i[2]< 4:
			inputt = input('>PLANKS< OR >STICKS< >cancel<')
			if inputt=='planks' or inputt=='p':
				i[1] -= 1
				i[2] += 4
				print('+ 4 PLANKS')
				inputt = input('Craft Again?')
				if inputt == ' ' or inputt == 'yes':
					craft()
				else:
					overworld()

		if inputt == 'sticks' or inputt=='s' and i[2]>=2:
				i[2] -= 2
				i[0] += 4
				print('+ 4 STICKS')
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()

#has planks
		elif i[2] >= 4:
			inputt = input('>planks< OR >sticks< OR >crafting table< OR >cancel< ')
			if inputt == 'planks' or inputt=='p' and i[1]>=1:
				i[1] -= 1
				i[2] += 4
				print('+ 4 PLANKS')
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
				else:
					break

			if inputt == 'sticks' or inputt=='s' and i[2]>=2:
				i[2] -= 2
				i[0] += 4
				print('+ 4 STICKS')
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
				else:
					break

			if inputt == 'torch' or inputt=='t'and i[0] >=1 and o[0]>= 1:
				i[0]-= 1
				o[0] -= 1
				i[5] += 4
				print('+ 4 TORCHES')
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
				else:
					break

			elif inputt == 'ct' or inputt == 'craftingtable' and i[2]>=4:
				i[2] -= 4
				CT += 1
				print('+ CRAFTING TABLE')
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
				else:
					break

			elif inputt == 'cancel':
				overworld()
			else:
				print('Sorry, you dont have enough materials')
				print('{}'.format(i))

#has CT~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	if CT == 1:
		inputt = input('craft ____?')
#Planks
		if inputt == 'planks' or inputt=='p' and i[1]>=1:
			i[1] -= 1
			i[2] += 4
			print('+ 4 PLANKS')
			inputt = input('Craft Again?')
			if inputt == ' ':
				craft()
#Sticks
		if inputt == 'sticks' or inputt=='t'and i[0] >=1 and o[0]>= 1:
			i[2] -= 2
			i[0] += 4
			print('+ 4 STICKS')
			inputt = input('Craft Again?')
			if inputt == ' ':
				craft()

		if inputt == 'torch' or inputt=='t'and i[0] >=1 and o[0]>= 1:
			i[0]-= 1
			o[0] -= 1
			i[5] += 4
			print('+ 4 TORCHES')
			inputt = input('Craft Again?')
			if inputt == ' ':
				craft()

#Pickaxe
		if inputt == 'pickaxe':
			pickaxeM = input ('Material?')
	#Wood
			if pickaxeM == 'wood' and i[0]>=2 and i[2]>=3:
				i[0] -= 2
				i[2] -= 3
				d[0] -= d[0]
				d[0] += 1
				Puses -= Puses
				Puses += 5
				print ('+ WOOD PICKAXE')
				print('Pickaxe HP:{}'.format(Puses))
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()

	#Stone
			elif pickaxeM == 'stone' and i[0]>=2 and i[3]>=3:
				i[0] -= 2
				i[3] -= 3
				d[0] -= d[0]
				d[0] += 2
				Puses -= Puses
				Puses += 10
				print ('+ STONE PICKAXE')
				print('Pickaxe HP:{}'.format(Puses))
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
	#Iron
			elif pickaxeM == 'iron' and i[0]>=2 and i[4]>=3:
				i[0]-=2
				i[4] -= 3
				d[0] -= d[0]
				d[0] += 3
				Puses -= Puses
				Puses += 15
				print('+ Iron Pickaxe')
				print('Pickaxe HP:{}'.format(Puses))
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
			else:
				print('Sorry, you dont have enough materials.')
				print('{}'.format(i))
#Axe
		if inputt == 'axe':
			axeM = input ('Material?')
	#Wood
			if axeM == 'wood' and i[0]>=2 and i[2]>=3:
				i[0] -= 2
				i[2] -= 3
				d[3] -= d[3]
				d[3] += 1
				Auses -= Auses
				Auses += 5
				print ('+ WOOD AXE')
				print('Axe HP:{}'.format(Auses))
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
	#Stone
			elif axeM == 'stone' and i[0]>=2 and i[3]>=3:
				i[0] -= 1
				i[3] -= 2
				d[3] -= d[3]
				d[3] += 1
				Auses -= Auses
				Auses += 10
				print('Axe HP:{}'.format(Auses))
				print('+ STONE AXE')
				inputt = input('Craft Again?')
				if inputt == ' ':
					craft()
			else:
				print('Sorry, you dont have enough materials.')
				print('{}'.format(i))
#Sword
		if inputt == 'sword':
			swordM = input ('Material?')
	#Wood
			if swordM == 'wood' and i[0]>=1 and i[2]>=2:
				i[0] -= 1
				i[2] -= 2
				d[1] -= d[1]
				d[1] += 1
				Suses -= Suses
				Suses += 5
				print ('+ WOOD SWORD')
				print('Sword HP:{}'.format(Suses))
				inputt = input('Craft?')
				if inputt == ' ':
					craft()
	#Stone
			elif swordM == 'stone' and i[0]>=1 and i[3]>=2:
				i[0] -= 1
				i[3] -= 2
				d[1] -= d[1]
				d[1] += 1
				Suses -= Suses
				Suses += 5
				print('+ STONE SWORD')
				print('Sword HP:{}'.format(Suses))
				inputt = input('Craft?')
				if inputt == ' ':
					craft()
			else:
				print('Sorry, you dont have enough materials.')
				print('{}'.format(i))

		elif inputt == 'cancel':
			overworld()
		else:
			craft()

	overworld()
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Furnace Furnace
# ace Furnace Furnace Furnace Furnace Furnace Furnace
def furnace():
	inputt = input('Smelt _____?')

#IronIngots
	if inputt == 'iron' and o[0]>=1 and o[1]>=3:
		print('Smelting..' , end='\r')
		time.sleep(0.30) #delay
		print('Smelting...' , end='\r')
		time.sleep(0.30) #delay
		if o[1]<=3:
			i[4] == o[1]#Add Iron to Invintory
			o[1] == 0#Set Iron Ore to 0
			o[0] -= 1#Coal - 1
			print('+ {} Iron'.format(o[1]))
			inputt = input('Smelt Again?')
			if inputt == ' ':
				furnace()
		else:
			i[4] += o[1]#Add Iron to Invintory
			o[1] -= 3#Iron ore - 3
			o[0] -= 1#Coal - 1
			print('+ 3 Iron')
			inputt = input('Smelt Again?')
			if inputt == ' ':
				furnace()
			else:
				overworld()
#Logs
	if inputt == 'logs' and i[1]>=2:
		print('Smelting..' , end='\r')
		time.sleep(0.30) #delay
		print('Smelting...')
		time.sleep(0.30) #delay
		i[1]-=2
		o[0]+=1
		print('+ 1 coal')
		inputt = input('Smelt Again?')
		if inputt == ' ':
			furnace()
		else:
			overworld()

	if inputt == 'cancel':
		overworld()
	else:
		print('Insufficient materials.')
		overworld()

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# START START START START START START START START START START START

print ('Generating Realty...')

time.sleep(0.25) #delay

overworld()


#!/usr/bin/env python3
'''Unittest for review'''
from unittest import TestCase
from models.review import Review

class TestReview(TestCase):
    '''Tests Review class'''
    def test_init(self):
        obj = Review()
        self.assertIsInstance(obj, BaseModel)
        self.assertIs(type(obj), Review)

    def test_text(self):
        obj = Review()
        self.assertIs(obj.text, '')


import json
from dataclasses import dataclass
from lxml import etree
from typing import Union, Optional
from functools import update_wrapper
from flask import make_response, jsonify, Response, request
from ..extensions import logger
from .helpers import DefaultJSONEncoder

def json_response(data_dict: Union[dict, list, dataclass()], cors=False):
    response = make_response(json.dumps(data_dict, cls=DefaultJSONEncoder))
    response.mimetype = 'application/json'
    if cors:
        response.headers['Access-Control-Allow-Origin'] = '*'
    return response

def success_response(data: Union[dict, list, str], count: Optional[int] = None) -> dict:
    result = {'status': 0, 'data': data}
    if count is not None:
        result['count'] = count
    return result

def jsonify_success(data: Union[dict, list, str], count: Optional[int] = None) -> Response:
    response = success_response(data, count)
    return jsonify(response)

def error_response(error: Union[dict, list, str] = 'common') -> dict:
    return {'status': 400, 'error': error}

def jsonify_error(error: Union[dict, list, str] = 'common') -> Response:
    response = error_response(error)
    return jsonify(response)

def svg_response(xml_tree: etree, cors: bool = False):
    response = make_response(etree.tostring(xml_tree, pretty_print=False, encoding='UTF-8', xml_declaration=True))
    response.mimetype = 'image/svg+xml'
    if cors:
        response.headers['Access-Control-Allow-Origin'] = '*'
    return response

def log_request(log_file: str = 'requests'):
    def decorator(fn):
        def wrapped_function(*args, **kwargs):
            if request.data:
                logger.info(log_file, '>> %s' % json.dumps(request.json, cls=DefaultJSONEncoder, sort_keys=True, indent=2))
            result = fn(*args, **kwargs)
            if isinstance(result, Response):
                logger.info(log_file, '<< %s' % result.get_data(True))
            elif type(result) is dict or type(result) is list:
                logger.info(log_file, '<< %s' % json.dumps(result, cls=DefaultJSONEncoder))
            else:
                logger.info(log_file, '<< invalid response type %s' % type(result))
            return result

        return update_wrapper(wrapped_function, fn)

    return decorator

def protobuf_response(data: bytes):
    response = make_response(data)
    response.headers['Content-Type'] = 'application/x-protobuf'
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response


import random
import threading
import time
import logging

number_of_users = 20
minimum_value = 1
maximum_value = 6

logging.basicConfig(level=logging.DEBUG,format='[%(levelname)s] (%(threadName)-10s) %(message)s',)

# calculation service
def my_calculation(minimum_value,maximum_value):
    logging.debug('Starting my function service')
    var_result = random.randint(minimum_value,maximum_value)
    logging.debug('the function returned a value of : %d', var_result )
    logging.debug('Exiting my function service')
# worker activity
def worker(minimum_value,maximum_value):
    logging.debug('Starting my worker process ')
    #time sleep
    #time.sleep(1)
    my_calculation(minimum_value,maximum_value)
    logging.debug('Exiting my worker process ')

# Threading
for users in range(number_of_users) :
	users_count = users + 1
	worker_user_name = 'WORKER %d ACTIVITY ' % users_count
	w = threading.Thread(name=worker_user_name, target=worker, args=(minimum_value,maximum_value,))
	w.start()

# Zeroing variables
number_of_users = 0
minimum_value = 0
maximum_value = 0


import argparse
import viewController
import modelController

class KeysController:

    parser = argparse.ArgumentParser()

    parser.add_argument('-sdate')
    parser.add_argument('-sname')
    parser.add_argument('-add')
    parser.add_argument('-d')
    parser.add_argument('-t')
    parser.add_argument('-remove')
    parser.add_argument('-all', action='store_true')

    def __init__(self, model, view):
        self.model = model
        self.model.loadData()
        self.view = view

    def mainMenu(self):
        self.args = self.parser.parse_args()
        if self.args.sdate:
            note = self.model.searchByDate(self.args.sdate)
            self.view.printSingleNote(note)
        elif self.args.sname:
            note = self.model.searchByName(self.args.sname)
            self.view.printSingleNote(note)
        elif self.args.add and self.args.d and self.args.t:
            self.model.setNewEl(self.args.add, self.args.d, self.args.t)
            self.model.saveData()
        elif self.args.remove:
            self.model.deleteNote(name)
            self.model.saveData()
        elif self.args.all:
            self.view.notesView()


N, C = map(int, input().split())
M = int(input())

arr = []
for _ in range(M):
    arr.append(list(map(int, input().split())))

arr.sort(key=lambda x: x[1])

lst = [C] * N
cnt = 0
for start, end, box in arr:
    min_value = C
    for i in range(start, end):
        if min_value > min(lst[i], box):
            min_value = min(lst[i], box)

    for i in range(start, end):
        lst[i] -= min_value
    cnt += min_value

print(cnt)


#       --------Part 1--------   --------Part 2--------
# Day       Time   Rank  Score       Time   Rank  Score
#  21   02:43:32    569      0   02:49:19    552      0
#Gigantic waste of time due to handling matrices manually with list of lists. I really should leanr numpy

from collections import defaultdict
data = open('day21.txt').read().strip()
# data = open('day21_t.txt').read().strip()
data = data.split('\n')

rulesS = []
rulesD = []
for line in data:
    if line[2] == '/':
        rulesS.append([list(line[0:2]), list(line[3:5])])
        rulesD.append([list(x) for x in line.split(' => ')[1].split('/')])
    else:
        rulesS.append([list(x) for x in line.split(' => ')[0].split('/')])
        rulesD.append([list(x) for x in line.split(' => ')[1].split('/')])
print('rules')
print(rulesS)
print(rulesD)

# .#.
# ..#
# ###

g = [ list('.#.'),
list('..#'),
list('###'), ]

# g = [ list('123'),
# list('456'),
# list('789'), ]

print("g")
print(g)
print()
def rotate(g):
    if len(g) == 2:
        return [[g[1][0], g[0][0]], [g[1][1], g[0][1]]]
    if len(g) == 3:
        return [
            [g[2][0], g[1][0], g[0][0]],
            [g[2][1], g[1][1], g[0][1]],
            [g[2][2], g[1][2], g[0][2]],
        ]

def flip_v(g):
    if len(g) == 2:
        return [g[1], g[0]]
    else:
        return [g[2], g[1], g[0]]

def flip_h(g):
    return [list(reversed(row)) for row in g]

def gen_variations(g):
    for _ in range(0, 4):
        yield g
        yield flip_v(g)
        yield flip_h(g)
        g = rotate(g)

# print("var g")
# for ng in gen_variations(g):
#     for x in ng:
#         print(x)
#     print()

def find_match(to_match):
    for (i, r) in enumerate(rulesS):
        for var_r in gen_variations(r):
            if to_match == var_r:
                return rulesD[i]
    return None

def extract(g, y, x, size):
    lines = g[y*size:(y*size)+size]
    return [line[x*size:(x*size)+size] for line in lines]

def gen_next_g(g):
    if len(g) % 2 == 0:
        size = 2
    else:
        size = 3

    new_size = (len(g) // size) * (size + 1)
    return [ [' '] * new_size ] * new_size

def inject(new_g, matched, y, x):
    # print('inject', y, x)
    # print('matched')
    # print(matched)
    # print('new_g')
    # print(new_g)
    size = len(matched)
    for i in range(0, size):
        replace_from = size * x
        replace_to = replace_from + size
        line = new_g[(y * size) + i]
        new_g[y * size + i] = line[0:replace_from] + matched[i] + line[replace_to:]
        # print('new_g')
        # print(new_g)
    return new_g

for _ in range(0, 18):
    print(_)
    if len(g) % 2 == 0:
        size = 2
    else:
        size = 3

    new_g = gen_next_g(g)
    # print('new_g')
    # print(new_g)
    for y in range(0, len(g) // size):
        for x in range(0, len(g) // size):
            to_match = extract(g, y, x, size)
            # print('to_match')
            # print(to_match)
            matched = find_match(to_match)
            new_g = inject(new_g, matched, y, x)
            # print('matched')
            # print(matched)
            # print('new_g')
            # print(new_g)
            # import sys
            # sys.exit()
    g = new_g

print()
# print(new_g)
flattened = ''.join([i for line in new_g for i in line])
print(flattened)
print(sum(1 for elem in flattened if elem == '#'))


import pyttsx3 #pip install pyttsx3
import datetime
import speech_recognition as sr #pip install speechRecognition
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
import random
#from selenium import webdriver

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices)
engine.setProperty('voice', voices[0].id)
#engine.setProperty('rate',170)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        print("Good Morning sir!")
        speak("Good Morning sir!")

    elif hour>=12 and hour<18:
        print("Good Afternoon sir!")
        speak("Good Afternoon sir!")

    else:
        print("Good Evening sir!")
        speak("Good Evening sir!")

    print("I am HP. How can I help you?")
    speak("I am HP. How can I help you?")

def takeCommand():
    #It takes microphone input from the user and returns string output

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-us')
        #if ("HP") in query:
        print(f"You said: {query}\n")
        #else:
            #return "None"

    except Exception as e:
        print(e)
        print("Sorry sir, I don't understand")
        speak("Sorry sir, I don't understand")
        return "None"
    return query

#def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('mukundvashisht3@gmail.com', 'mukund557')
    server.sendmail('mukundvashisht3@gmail.com', to, content)
    server.close()

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()

        # Logic for executing tasks based on query
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to Wikipedia")
            print(results)
            speak(results)

        elif 'open youtube' in query:
            webbrowser.get('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe %s').open("https://youtube.com")

        elif 'open google' in query:
            webbrowser.get('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe %s').open("https://google.com")

        elif 'open stack overflow' in query:
            webbrowser.get('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe %s').open("https://stackoverflow.com")

        elif 'open gfg' in query:
            webbrowser.get('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe %s').open("https://www.geeksforgeeks.org")

        #elif 'open gmail' in query:
            #webbrowser.get('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe %s').open("https://accounts.google.com/b/0/AddMailService")

        elif 'play music' in query:
            n=random.randint(0,3)
            #print(n)
            music_dir = r'C:\Users\mukun\Music\Music'
            songs = os.listdir(music_dir)
            #print(songs)
            os.startfile(os.path.join(music_dir,songs[n]))
            print("playing music")
            speak("playing music")
            break

        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")
            print(f"Sir, the time is {strTime}")
            speak(f"Sir, the time is {strTime}")

        elif 'open Visual Studio' in query:
            codePath = r"E:\Microsoft VS Code\Code.exe "
            speak("opening...")
            os.startfile(codePath)

        elif 'open python 310' in query:
            codePath =r"C:\Users\mukun\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10\IDLE (Python 3.10 64-bit)"
            speak("opening...")
            os.startfile(codePath)

        elif 'open python 38' in query:
            codePath =r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.8\IDLE (Python 3.8 64-bit)"
            speak("opening...")
            os.startfile(codePath)

        elif 'open edge' in query:
            codePath ="C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
            speak("opening...")
            os.startfile(codePath)

        #elif 'open chrome' in query:
            #codePath ="C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
            #speak("opening...")
            #os.startfile(codePath)

        elif 'open control panel' in query:
            codePath ="C:\\Users\\mukun\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\System Tools\\Control Panel.lnk"
            speak("opening...")
            os.startfile(codePath)

        elif 'open screen recorder' in query:
            codePath ="E:\\OBS\\obs-studio\\bin\\64bit\\obs64.exe"
            speak("opening...")
            os.startfile(codePath)

        #elif 'send a mail' in query:
        #    try:
        #       speak("what should I say...")
        #        content = takeCommand()
        #       to = ("mukundvashisht3@gmail.com")
        #       sendEmail(to, content)
        #        speak("Email has been sent!")
        #    except Exception as e:
        #        print(e)
        #       speak("Sorry sir, email not sent")

        elif 'exit' in query:
            print("Exiting...")
            speak("Exiting...")
            break

        elif 'take a break' in query:
            print("Ok sir, if need any help you can call me")
            speak("Ok sir, if need any help you can call me")
            print("I am there for you")
            speak("I am there for you")
            break

        elif 'youtube search' in query:
            print("ok sir, This is what I found")
            speak("ok sir, This is what I found")
            query=query.replace("youtube search","")
            web='https://www.youtube.com/results?search_query='+query
            webbrowser.open(web)
            speak("Done Sir")

        elif 'google search' in query:
            print("ok sir, This is what I found")
            speak("ok sir, This is what I found")
            query=query.replace("google search","")
            web='https://www.google.com/search?q='+query
            webbrowser.open(web)
            speak("Done Sir")


# Day_08_02_mnist_2.py
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import math

mnist = input_data.read_data_sets('Data/mnist/', one_hot=True)
print(type(mnist))          # train, validation, test
print(type(mnist.train))

def xavier_init(n_inputs, n_outputs, uniform=True):
  """Set the parameter initialization using the method described.
  This method is designed to keep the scale of the gradients roughly the same
  in all layers.
  Xavier Glorot and Yoshua Bengio (2010):
           Understanding the difficulty of training deep feedforward neural
           networks. International conference on artificial intelligence and
           statistics.
  Args:
    n_inputs: The number of input nodes into each output.
    n_outputs: The number of output nodes for each input.
    uniform: If true use a uniform distribution, otherwise use a normal.
  Returns:
    An initializer.
  """
  if uniform:
    # 6 was used in the paper.
    init_range = math.sqrt(6.0 / (n_inputs + n_outputs))
    return tf.random_uniform_initializer(-init_range, init_range)
  else:
    # 3 gives us approximately the same limits as above since this repicks
    # values greater than 2 standard deviations from the mean.
    stddev = math.sqrt(3.0 / (n_inputs + n_outputs))
    return tf.truncated_normal_initializer(stddev=stddev)

learning_rate = 0.1
training_epoches = 25
batch_size = 100
display_step= 1

x = tf.placeholder(tf.float32, [None, 784])     # 28x28 = 784
y = tf.placeholder(tf.float32, [None,  10])

# --------------------------------------------------- #

learning_rate = 0.01
training_epoches = 15

# W1 = tf.Variable(tf.random_normal([784, 256]))
# W2 = tf.Variable(tf.random_normal([256, 256]))
# W3 = tf.Variable(tf.random_normal([256,  10]))
#
# B1 = tf.Variable(tf.random_normal([256]))
# B2 = tf.Variable(tf.random_normal([256]))
# B3 = tf.Variable(tf.random_normal([ 10]))

# W1 = tf.get_variable('W1', shape=[784, 256], initializer=xavier_init(784, 256))
# W2 = tf.get_variable('W2', shape=[256, 256], initializer=xavier_init(256, 256))
# W3 = tf.get_variable('W3', shape=[256,  10], initializer=xavier_init(256,  10))

W1 = tf.get_variable('W1', shape=[784, 256],
                     initializer=tf.contrib.layers.xavier_initializer())
W2 = tf.get_variable('W2', shape=[256, 256],
                     initializer=tf.contrib.layers.xavier_initializer())
W3 = tf.get_variable('W3', shape=[256,  10],
                     initializer=tf.contrib.layers.xavier_initializer())

B1 = tf.Variable(tf.zeros([256]))
B2 = tf.Variable(tf.zeros([256]))
B3 = tf.Variable(tf.zeros([ 10]))

L1 = tf.nn.relu(tf.add(tf.matmul(x, W1), B1))
L2 = tf.nn.relu(tf.add(tf.matmul(L1, W2), B2))

activation = tf.add(tf.matmul(L2, W3), B3)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(activation, y))

# --------------------------------------------------- #

optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(training_epoches):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)  # 55000/100 = 550

        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)

            _, c = sess.run([optimizer, cost],
                            feed_dict={x: batch_xs, y: batch_ys})

            # sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
            # c = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})

            avg_cost += c / total_batch

        if (epoch+1)%display_step == 0:
            print('epoch: {}, cost: {}'.format(epoch+1, avg_cost))

    # ---------------------------------------- #

    pred = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(pred, tf.float32))

    print('accuracy :',
          sess.run(accuracy, {x: mnist.test.images, y: mnist.test.labels}))
    # print('accuracy :', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

# 결과
# epoch: 13, cost: 0.1890449569780718
# epoch: 14, cost: 0.18120451631193807
# epoch: 15, cost: 0.17360281172123823
# accuracy : 0.9496

# epoch: 13, cost: 0.18784428118982102
# epoch: 14, cost: 0.18013680148531105
# epoch: 15, cost: 0.17296383041549832
# accuracy : 0.9507


n, m = list(map(int, input().split()))
point = sorted([int(input())for _ in range(n)])
min, max = point[1]-point[0], point[-1]-point[0]
current_gap = 0

while min <= max:
    gap = (min + max)//2
    modem = point[0]
    count = 1
    for i in range(1, len(point)):
        if point[i]-modem >= gap:
            modem = point[i]
            count += 1

    if count >= m:
        min = gap+1
        current_gap = gap
    else:
        max = gap-1

print(current_gap)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Python module for using pandas in peak analysis.

Created on Sat Jan  7 16:29:38 2023

@author: Eivind Tostesen

"""

import pandas as pd
from itertools import chain
from utilities import ChainedAttributes

# Alias when None means "use default":
_default = None

# Classes:

class PeakTreePandas(ChainedAttributes):
    """Pandas methods to be owned by a PeakTree."""

    def __init__(
        self,
        tree,
        attrname="pandas",
        X=None,
        objecttype = (
            "node root parent full top children high low"
            "root_path top_path subtree high_descendants "
            "low_descendants full_nodes leaf_nodes "
            "branch_nodes linear_nodes").split(),
        **kwargs,
    ):
        """Attach this pandas-aware object to a PeakTree."""
        super().__init__()
        self.setattr(obj=tree, attrname=attrname)
        if X is None:
            self.x_start = lambda n: n.start
            self.x_end = lambda n: n.end
        else:
            self.x_start = lambda n: X[n.start]
            self.x_end = lambda n: X[n.end]
        self.node = lambda n: n
        self.root = lambda n: self.rootself.root()
        self.high = (
            lambda n: self.rootself.high(n) if self.rootself.has_children(n) else None
        )
        for name in (
            "parent children low full top is_nonroot "
            "has_children size height base_height _index"
        ).split():
            setattr(self, name, getattr(self.rootself, name))
        for name in (
            "root_path top_path subtree high_descendants "
            "low_descendants full_nodes leaf_nodes "
            "branch_nodes linear_nodes"
        ).split():
            setattr(
                self,
                name,
                lambda node, attr=name: list(getattr(self.rootself, attr)(node)),
            )
        self.objecttype = objecttype
        self.set_definitions(**kwargs)

    def set_definitions(self, **kwargs):
        """Set attributes with functions, mappings or Series."""
        for name in kwargs:
            setattr(self, name, kwargs[name])

    def series(self, name="node", filter=_default, *, definitions={}):
        """Return series with one row per PeakTree node."""
        if filter is _default:
            filter = self.rootself
        dtype="object" if name in self.objecttype else None
        s = pd.Series(filter, dtype=dtype).map(
                definitions[name] if name in definitions else getattr(self, name),
                na_action="ignore",
            ).rename(name)
        if name not in self.objecttype:
            s.convert_dtypes()
        return s

    def dataframe(self, columns="node", filter=_default, *, definitions={}):
        """Return dataframe with one row per PeakTree node."""
        if filter is _default:
            filter = self.rootself
        nodes = list(iter(filter))
        return pd.concat(
            [
                self.series(name, nodes, definitions=definitions)
                for name in columns.split()
            ],
            axis=1,
        )

    def assign_columns(self, dataframe, columns="", *, definitions={}):
        """Assign extra columns to a given dataframe."""
        return dataframe.assign(
            **{
                name: self.series(name, dataframe["node"], definitions=definitions)
                for name in columns.split()
            }
        )

    def sort(self, dataframe, by="_index", **kwargs):
        """Return sorted dataframe."""
        return dataframe.sort_values(
            by="node",
            key=lambda col: col.map(getattr(self.rootself, by)),
            ignore_index=True,
            **kwargs,
        )

    def sort_by_height_and_size(self, dataframe, **kwargs):
        """Return dataframe sorted by descending height and size."""
        return dataframe.pipe(self.sort, "size", ascending=False, **kwargs).pipe(
            self.sort, "height", ascending=False, kind="stable", **kwargs
        )

    # Out-of-the-box dataframes:

    def dump_data_attributes(self):
        """Return a dump of the PeakTree's data attributes."""
        df = pd.DataFrame(self.rootself.as_dict_of_dicts())
        df.index.name = "node"
        return df.reset_index().convert_dtypes().pipe(self.sort)

    def tree_structure(self):
        """Return dataframe with topological attributes."""
        return self.dataframe(
            "top children node parent full root",
            filter=chain.from_iterable(
                self.rootself.path(node, self.rootself.full(node), self.rootself.parent)
                for node in self.rootself.leaf_nodes()
            ),
        )

    def numeric_properties(self):
        """Return dataframe with numeric (vertical) properties."""
        return self.dataframe("node height size base_height").pipe(self.sort_by_height_and_size)

    def location_properties(self):
        """Return dataframe with locational (horizontal) properties."""
        return self.dataframe(
            "node location x_start x_end",
            definitions=dict(
                location=lambda n: f"{self.x_start(n)}..{self.x_end(n)}",
            ),
        )


from commands.utils.youtube import Youtube
from urllib.parse import urlparse
from utils.embeds import send_failed_embed

class PlayCmd():
    def __init__(self, client, manager):
        self.client = client
        self.manager = manager

    async def run(self, message, args):
        author_voicech = message.author.voice.voice_channel
        if not author_voicech:
            await send_failed_embed(self.client, message,
                                    command='play',
                                    text='You are not in a voice channel.')
            return
        current_server = message.server

        # checks the channel, connects, etc
        if self.client.is_voice_connected(current_server):
            voice_client = self.client.voice_client_in(current_server)
        else:
            voice_client = await self.client.join_voice_channel(author_voicech)

        bot_voice_channel = voice_client.channel

        # checks where the author is, so she can move
        if author_voicech:
            if not bot_voice_channel == author_voicech:
                await voice_client.move_to(author_voicech)

            # checks current server in dict of server_id->servermanager
            if f'{current_server.id}' not in self.manager.managers.keys():
                self.manager.insert_server(self.client, message.channel)

            server_mng = self.manager.managers[f'{current_server.id}']

            """
                checks if it is a youtube link, playlist,
                common video, or search query
            """
            url = urlparse(args[0])
            if url.netloc == 'youtube.com' or url.netloc == 'www.youtube.com':
                if 'list=' in url.query:
                    if '/watch' in url.path:
                        split = url.query.split('&')
                        index = None
                        for j in split:
                            if j.startswith('t='):
                                split.remove(j)
                            if j.startswith('index='):
                                index = int(j.split('=')[1])
                                split.remove(j)

                        playlist_id = split[1].split('=')[1]
                        await server_mng.load_playlist(playlist_id,
                                                       start_index=index)
                    elif '/playlist' in url.path:
                        playlist_id = url.query.split('=')[1]
                        await server_mng.load_playlist(playlist_id)

                    return
                else:
                    if '/watch' in url.path:
                        video_id = url.query.split('=')[1]
                        await server_mng.add_to_playlist(video_id,
                                                         None,
                                                         message)
            else:
                video_id, video_title = Youtube().search(' '.join(args))
                await server_mng.add_to_playlist(video_id,
                                                 video_title,
                                                 message)


#!/usr/bin/env python3
"""Class module to create a library of manuals."""

import requests
import bs4
from time import sleep
from utils.database import DB
from manual import Manual

class Library:
    """Create a library of manuals."""

    def __init__(self):
        """Construct the library object."""
        self.all_manuals = []  # A list with all manuals
        self.link = ''

    def list_manuals(self, db):
        """List all manuals of library."""
        self.all_manuals = db.list_library()

    def show_list_manuals(self, db):
        """Show a list of manuals retrieved of local database."""
        print("=" * 70)
        print(str.center("Recuperando a lista de manuais...", 70))
        print("=" * 70)
        print()
        if not self.all_manuals:
            self.list_manuals(db)
        print(*((f'[ {str.rjust(str(ordem), 2)} ] - {item[1]}') for ordem, item in enumerate(self.all_manuals, 1)), sep='\n')

    def download_all_manuals(self):
        """Download all manuals of library."""
        pass

    def sync_library(self, db):
        """Sync data with server before update the local database."""
        print("=" * 70)
        print(str.center("Sincronizando a lista de manuais com o servidor...", 70))
        print("=" * 70)
        print()
        try:
            # First, check if self.all_manuals alredy exists. If it doesn't
            # exist we call list_manuals function that set this var.
            if not self.all_manuals:
                self.list_manuals(db)

            # Retrieve link of local database.
            self.link = db.consult_link()

            # Start request to server.
            res = requests.get(self.link)
            res.raise_for_status()
            manuals_bs4 = bs4.BeautifulSoup(res.text, features="lxml")
            manuals = manuals_bs4.select('.titulo-marcadores-1 > a[href]')

            # Create a iter with download data.
            index_library = [((item.getText()).strip(), (item.get('href')).strip()) for item in manuals]
            if not index_library:
                raise Exception()
            return index_library
        except Exception as exc:
            print(exc)
            sleep(1)
            print("=" * 70)
            print(str.center("Erro ao carregar os dados do servidor.", 70))
            print("=" * 70)
            print()

    def update_manuals(self, db):
        """Add one manual to library."""
        try:
            index_library = self.sync_library(db)
            if not index_library:
                raise Exception()
            # Create a iter with data to compare with download data.
            list_currently = [(item[1], item[2]) for item in self.all_manuals]
            # Compare the two iter. In first comparison the difference
            # will be add to database. In second comparison the difference
            # will be delete of database. This will become the local database
            # and server equals.
            # Call function that realize the update in local database.
            data_add = list(set(index_library).difference(list_currently))
            db.update_library(data_add)

            # Now, we consult again the db to examine if there is
            # one manual that don't exists in server.
            # If there is one remove_manual_from_library removes it.
            self.list_manuals(db)
            list_currently = [(item[1], item[2]) for item in self.all_manuals]
            data_rem = [(item[0],) for item in (list(set(list_currently).difference(index_library)))]
            if data_rem:
                db.remove_manual_from_library(data_rem)
            print("Banco de dados atualizado com sucesso.")
            return True
        except Exception as exc:
            print(exc)
            sleep(1)
            print("=" * 70)
            print(str.center("Erro ao carregar a lista de capítulos.", 70))
            print("=" * 70)
            print()
            return False

    def update_library(self, db):
        """Update manuals and documents."""
        try:
            update_lib = self.update_manuals(db)
            if not update_lib:
                raise Exception()
            for item in self.all_manuals:
                manual = Manual(item)
                manual.update_manual_chapters(db)
        except Exception as exc:
            print(exc)
            sleep(1)
            print("=" * 70)
            print(str.center("Verifique a sua conexão com a INTRANET. Lembre-se", 70))
            print(str.center("de estar conectado a intranet para atualizar o banco de dados.", 70))
            print("=" * 70)

if __name__ == '__main__':
    db = DB()
    library = Library()
    # library.update_library(db)
    # library.list_manuals(db)
    library.show_list_manuals(db)


import gradio as gr
import pandas as pd
from gradio import Interface, components
import matplotlib.cm as cm
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from PIL import Image, ImageSequence
from math import factorial
from tqdm import tqdm
from sklearn.cluster import DBSCAN

def create_trajectory_gif(k1=3, k2=20, p=0.1, u1=1, u2=2, u3=2.3, timesteps=6, grid_interval=0.1):
    k1 = int(round(k1))
    k2 = int(round(k2))
    timesteps = int(round(timesteps))

    # Computes the probability of a strategy being best response to a given sample of k
    def xtp1(x1, x2, k):
        probs = np.zeros(3)
        for i in range(k):
            for j in range(k-i):
                if 1.* i/k *u1 > 1.*j/k *u2 and 1.* i/k*u1 > 1.*(k-i-j)/k *u3:
                    probs[0] +=  factorial(k)/(factorial(j)* factorial(i) * factorial(k-i-j) ) *(x1)**i * (x2)**j * (1-x1-x2)**(k-i-j)
                elif 1.* j/k *u2 > 1.*i/k *u1 and 1.* j/k*u2 > 1.*(k-i-j)/k *u3:
                    probs[1] +=  factorial(k)/(factorial(j)* factorial(i) * factorial(k-i-j) ) *(x1)**i * (x2)**j * (1-x1-x2)**(k-i-j)
                else:
                    probs[2] +=  factorial(k)/(factorial(j)* factorial(i) * factorial(k-i-j) ) *(x1)**i * (x2)**j * (1-x1-x2)**(k-i-j)
        return probs

    def W(x1, x2):
        return p*xtp1(x1, x2, k1) + (1-p)* xtp1(x1, x2, k2)

    # Define the system of differential equations
    def system(Y, t=0):
        x1, x2 = Y
        w = W(x1, x2)
        dx1dt = w[0] - x1
        dx2dt = w[1] - x2
        return [dx1dt, dx2dt]

    # time space
    t = np.linspace(0, timesteps, int(timesteps*5))
    grid_points = [(x, y) for x in np.arange(0, 1.1, grid_interval) for y in np.arange(0, 1.1, grid_interval) if x + y <= 1]

    # Generating a color map
    colors = cm.rainbow(np.linspace(0, 1, len(grid_points)))

    final_points = []
    frames = []
    for t_val in tqdm(t):
        plt.figure(figsize=(12, 8))
        for ic, color in zip(grid_points, colors):
            t_segment = np.linspace(0, t_val, 100)  # 100 points for each trajectory segment
            sol = odeint(system, ic, t_segment)
            plt.plot(sol[:, 0], sol[:, 1], color=color, alpha=0.5)
            if t_val == t[-1]:  # If it's the last timestep, collect the final point
                final_points.append(sol[-1])

        plt.title(f"Attractor plot at time = {t_val:.2f}")
        plt.xlabel("x1")
        plt.ylabel("x2")
        plt.grid(True)
        plt.tight_layout()

        # Save the current frame to a file and add to the list of frames
        filename = f"./temp/temp_frame_{int(t_val*10):04d}.png"
        plt.savefig(filename)
        frames.append(Image.open(filename))
        plt.close()

    # Save frames as a GIF
    gif_filename = './trajectory_animation2.gif'
    frames[0].save(gif_filename, save_all=True, append_images=frames[1:], loop=0, duration=100)

    # Cleanup temporary frame files
    for frame in frames:
        frame.close()

    # Cluster the final points using DBSCAN
    clustering = DBSCAN(eps=0.1, min_samples=1).fit(final_points)
    cluster_labels = clustering.labels_

    # Determine the stable points by averaging the points in each cluster
    stable_points = []
    for label in set(cluster_labels):
        points_in_cluster = np.array(final_points)[cluster_labels == label]
        stable_point = np.around(np.mean(points_in_cluster, axis=0), decimals = 2)
        stable_points.append(stable_point)

    list_of_lists = [list(arr) + [1 - sum(arr)] for arr in stable_points]
    df = pd.DataFrame(list_of_lists, columns=['x1', 'x2', 'x3'])

    return gif_filename, df

iface = gr.Interface(
    fn= create_trajectory_gif,
    inputs=[
        gr.Number( label="Sample Size 1"),
        gr.Number( label="Sample Size 2"),
        gr.Slider(minimum=0, maximum=1, step=0.01, label="Proportion of Cohort 1 (with sample size 1)"),
        gr.Number(label="Payoff u1"),
        gr.Number(label="Payoff u2"),
        gr.Number(label="Payoff u3"),
        gr.Number(label="Timesteps"),
        gr.Number(label="Grid resolution"),
    ],
    outputs=[
        gr.Image(label="Simulation GIF"),
        gr.Dataframe(type="pandas", label="Stable equilibria")
    ],
    examples=[
        [3, 20, 0.1, 1, 2, 2.3, 6, 0.1]
    ]
)

iface.launch()


import uuid
from datetime import datetime

context = {}

def new_request(name, slots={}):
    req_env = {
        "session": {
            "sessionId": f"amzn1.echo-api.session.{uuid.uuid1()}",
            "application": {
                "applicationId": f"amzn1.echo-sdk-ams.app.{uuid.uuid1()}"
            },
            "user": {
                "userId": f"amzn1.ask.account.{uuid.uuid1()}"
            },
            "new": False,
        },
        "request": {
            "requestId": f"amzn1.echo-api.request.{uuid.uuid1()}",
            "timestamp": f"{datetime.now().replace(second=0, microsecond=0).isoformat()}",
            "locale": "en-US",
            "type": "IntentRequest" if name.endswith('Intent') else name,
        }
    }

    if name.endswith('Intent'):
        req_env['request']['intent'] = {
            'name': name,
            'slots': {k: {'name': k, 'value': v} for k, v in slots.items()}
        }

    return req_env


#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100).astype(np.float32)

a = 50
b = 40
Y = a * X + b

plt.plot(X, Y)
plt.show()


import sys
from router_class import Router

def format(route):
    destination_ip, from_port, to_port, connection_ip, connection_port, mtu = tuple(route.strip().split(' '))
    return (destination_ip, int(from_port), int(to_port), connection_ip, int(connection_port), 0, int(mtu))

_, ip, port, path = sys.argv

with open(path) as routes:
    table = [format(route) for route in routes]

print("Creando Router")
router = Router(ip, int(port), table)

print("Router Iniciado")
while True:
    print("Esperando Paquete")
    router.listen()


import os
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader

import torchvision.transforms as T

# 이미지를 읽는 함수를 정의
def get_image(p:str):
    return Image.open(p).convert("RGB")

class baseDataset(Dataset):
    name2idx = {
        'airplane' : 0, 'automobile' : 1, 'bird' : 2,
        'cat' : 3, 'deer' : 4, 'dog' : 5, 'frog' : 6,
        'horse' : 7, 'ship' : 8, 'truck' : 9
    }

    def __init__(self, root:str="./datasets/CIFAR-10", istrain:bool=True):
        super().__init__()
        root = os.path.join(root, 'train') if istrain else os.path.join(root, 'val')

        # 데이터 리스트 생성
        data_list = []
        for class_name in os.listdir(root):  # 수정된 부분
            class_dir = os.path.join(root, class_name)  # 수정된 부분
            for img in os.listdir(class_dir):  # 수정된 부분
                img_path = os.path.join(class_dir, img)
                data_list.append((self.name2idx[class_name], img_path))
        self.data_list = data_list

        # 훈련과 검증과정에서 서로 다른 augmentatation 기법을 사용
        if istrain:
            self.transform = T.Compose([
                T.RandomHorizontalFlip(),  # 랜덤으로 이미지를 수평으로 뒤집음
                T.RandomCrop(32, padding=4),  # 이미지를 랜덤하게 자르고 크기를 32x32로 조정
                T.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),  # 이미지의 색감을 랜덤으로 조정
                T.RandomRotation(15),  # 이미지를 랜덤하게 회전
                T.ToTensor(),  # 이미지를 텐서로 변환
                T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
            ])
        else:
            self.transform = T.Compose([
                T.CenterCrop(32),
                T.ToTensor(),
                T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
            ])

    def __len__(self):
        return len(self.data_list)

    def __getitem__(self, idx:int):
        # 인덱스에 해당하는 데이터 반환
        number, img_path = self.data_list[idx]
        img_obj = get_image(img_path)
        img_tensor = self.transform(img_obj)

        return img_tensor, number

if __name__ == "__main__":
    # test baseDataset Class
    train_dataset, val_dataset = baseDataset("./datasets/CIFAR-10", True), baseDataset("./datasets/CIFAR-10", False)
    print(f"# Length of data, TRAIN : {len(train_dataset)}, VAL : {len(val_dataset)}")

    # test tensor shape
    tensor, number = train_dataset[200]
    print(f"# Tensor Shape(unbatched) : {tensor.shape}")


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

"""
@project: project201901
@time: 2019-01-04  09-50-39
@description:
    XGBoost Model
"""

from lib.dataio import DataBox, prepare_data_pipline
from lib.datacleaning import data_cleaning_pipline

import xgboost as xgb
import matplotlib.pyplot as plt
import numpy as np

def xgboost_model(data_box, k_fold=5):
    assert isinstance(data_box, DataBox)

    # dtrain = xgb.DMatrix(data_box.train_df, label=data_box.train_label)
    # dvali = xgb.DMatrix(data_box.vali_df, label=data_box.vali_label)
    dtest = xgb.DMatrix(data_box.test_df)

    # param = {'eta': 0.005,
    #          'max_depth': 10,
    #          'subsample': 0.8,
    #          'colsample_bytree': 0.8,
    #          'objective': 'reg:linear',
    #          'eval_metric': 'rmse',
    #          'silent': True,
    #          'nthread': 4}
    # num_round = 5000
    # evallist = [(dtrain, 'train'), (dvali, 'vali')]
    # xgb_module = xgb.train(param, dtrain, num_round, evallist, early_stopping_rounds=100)

    predictions_xgb = np.zeros(data_box.test_df.shape[0])
    for train_df, train_label, vali_df, vali_label in data_box.k_folds(k_fold, shuffle=True):
        dtrain = xgb.DMatrix(train_df, label=train_label)
        dvali = xgb.DMatrix(vali_df, label=vali_label)
        # dtest = xgb.DMatrix(data_box.test_df)

        param = {'eta': 0.005,
                 'max_depth': 10,
                 'subsample': 0.8,
                 'colsample_bytree': 0.8,
                 'objective': 'reg:linear',
                 'eval_metric': 'rmse',
                 'silent': True,
                 'nthread': 4}
        num_round = 5000
        evallist = [(dtrain, 'train'), (dvali, 'vali')]
        xgb_module = xgb.train(param, dtrain, num_round, evallist, early_stopping_rounds=100)
        predictions_xgb += xgb_module.predict(dtest, ntree_limit=xgb_module.best_ntree_limit)/k_fold

    data_box.submit_result = predictions_xgb
    plt.plot(data_box.vali_label.tolist())
    plt.plot(xgb_module.predict(dtest, ntree_limit=xgb_module.best_ntree_limit))
    plt.show()
    data_box.saving_submit_result()

if __name__ == "__main__":
    all_df = prepare_data_pipline()
    all_df = data_cleaning_pipline(all_df)
    data_box = DataBox(all_df)
    xgboost_model(data_box)


# https://leetcode.com/problems/add-two-numbers

# input: l1 = [2,4,3], l2 = [5,6,4]   // see input image
# output: [7,0,8] //  342 + 465 = 807

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def addTwoNumbers(p, q):
        dummyHead = ListNode(-1)           # strategy of dummy head, to have an initial pointer to start (and eventually return)
        carry = 0
        curr = dummyHead

        while p or q:
            x = p.val if p else 0         # it could be that one of the nodes is None
            y = q.val if q else 0

            sum = x + y + carry            # the carry is very important!
            carry = sum // 10

            curr.next = ListNode(sum % 10) # update pointers of the result
            curr = curr.next

            if p:                          # keep traversing the linked lists (if theres any next node)
                p = p.next
            if q:
                q = q.next

        if carry > 0:                      # if there was a carry at the very end, a new Node must be created
            curr.next = ListNode(carry)

        return dummyHead.next              # return everything after the dummy head

# O(n) time
# O(1) space


# Uses python3

def get_change(m):
    # write your code here
    money = 0
    count = 0
    coin = [10, 5, 1]

    for i in range(0, 3):
        while(money + coin[i] <= m):
            money += coin[i]
            count += 1
    return count

if __name__ == '__main__':
    m = int(input())
    print(get_change(m))


import textwrap
from room import Room
from player import Player
from item import Item

# Declare all the items

sword = Item('sword', 'Cuts through all things')
dagger = Item('dagger', 'Stabs all things')
diamond = Item('diamond', 'Sell for some money')
health = Item('health', 'Restores health')

item_one = [sword, diamond, health]
item_two = [dagger, sword, health]

# Declare all the rooms

room = {
    'outside':  Room("Outside Cave Entrance",
                     "North of you, the cave mount beckons", item_one),

    'foyer':    Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""", item_two),

    'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm.""", item_one),

    'narrow':   Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""", item_two),

    'treasure': Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south.""", item_two),
}

# Link rooms together

room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']

#
# Main
#

# Make a new player object that is currently in the 'outside' room.
player_one = Player('Ready Player', 'outside')
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#

def print_room_details(room_label):
    print('Location: ' + room[room_label].name)
    text_to_wrap = textwrap.wrap(room[room_label].description, 40)
    print('Description: ')
    for text in text_to_wrap:
        print(text)

def set_travel_direction(direction):
    direction_selected = f'{direction}_to'
    # checks to see if there is an attribute that matches what is in the method
    if getattr(room[player_one.current_room], direction_selected) != '':
        next_room = getattr(room[player_one.current_room], direction_selected)
        player_one.current_room = list(room.keys())[
            list(room.values()).index(next_room)]  # same Room memory address for the next_room
        print_room_details(player_one.current_room)
    else:
        print(
            f"You can't go in direction {direction}. Try the other 3 options")

for key in room:
    if key == player_one.current_room:
        print_room_details(key)
        for item in room[key].items:
            print(item.name)

    user_input = ''

    while not user_input:
        user_input = input(
            'Where thou moveth to?\n[n] - north\n[s] - south\n[e] - east\n[w] - west\n').split(' ')
        if len(user_input) == 2:
            if user_input[0].lower() in ['get', 'take']:
                for item in room[player_one.current_room].items:
                    if user_input[1].lower() == item.name:
                        player_one.items.append(item)
                        item.on_take()
                        room[player_one.current_room].items.remove(item)
                    else:
                        print(f'{user_input[1]} is not available in location - {player_one.current_room}')
            if user_input[0].lower() in ['drop', 'remove']:
                for item in player_one.items:
                    if user_input[1].lower() == item.name:
                        player_one.items.remove(item)
        elif len(user_input) == 1:
            if user_input[0] in ['i', 'inventory']:
                for item in player_one.items:
                    print(item.name)
            if user_input[0] == 'q':
                quit()
            elif user_input[0] in ['n', 's', 'e', 'w']:
                set_travel_direction(user_input[0])
            else:
                print('Direction not allowed. Press [n], [s], [e] or [w] keys')

# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.

#
# If the user enters "q", quit the game.

""" Old but working code
# elif player_one.current_room == 'outside' and user_input == 'n':
        #     print_room_details('foyer')
        #     player_one.current_room = 'foyer'
        # elif player_one.current_room == 'foyer' and user_input == 's':
        #     print_room_details('outside')
        #     player_one.current_room = 'outside'
        # elif player_one.current_room == 'foyer' and user_input == 'n':
        #     print_room_details('overlook')
        #     player_one.current_room = 'overlook'
        # elif player_one.current_room == 'foyer' and user_input == 'e':
        #     print_room_details('narrow')
        #     player_one.current_room = 'narrow'
        # elif player_one.current_room == 'overlook' and user_input == 's':
        #     print_room_details('foyer')
        #     player_one.current_room = 'foyer'
        # elif player_one.current_room == 'narrow' and user_input == 'w':
        #     print_room_details('foyer')
        #     player_one.current_room = 'foyer'
        # elif player_one.current_room == 'narrow' and user_input == 'n':
        #     print_room_details('treasure')
        #     player_one.current_room = 'treasure'
        # elif player_one.current_room == 'treasure' and user_input == 's':
        #     print_room_details('narrow')
        #     player_one.current_room = 'narrow'
"""


import pandas as pd
import glob
from fpdf import FPDF
from pathlib import Path

filepaths = glob.glob("invoices/*.xlsx")

for filepath in filepaths:

    filename = Path(filepath).stem
    invoice_no, invoice_date = filename.split("-")
    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.add_page()

    pdf.set_font(family='Times', style='B', size=16)
    pdf.cell(w=50, h=8, txt=f"Invoice nr.{invoice_no}", ln=1)

    pdf.set_font(family='Times', style='B', size=16)
    pdf.cell(w=50, h=8, txt=f"Date {invoice_date}", ln=1)

    df = pd.read_excel(filepath, sheet_name="Sheet 1")

    headers = list(df.columns)
    headers = [item.replace('_', ' ').title() for item in headers]
    pdf.set_font(family='Times', size=10, style="B")
    pdf.cell(w=30, h=8, txt=headers[0], border=1)
    pdf.cell(w=70, h=8, txt=headers[1], border=1)
    pdf.cell(w=30, h=8, txt=headers[2], border=1)
    pdf.cell(w=30, h=8, txt=headers[3], border=1)
    pdf.cell(w=30, h=8, txt=headers[4], border=1, ln=1)

    for index, rows in df.iterrows():
        pdf.set_font(family='Times', size=10)
        pdf.cell(w=30, h=8, txt=str(rows['product_id']), border=1)
        pdf.cell(w=70, h=8, txt=str(rows['product_name']), border=1)
        pdf.cell(w=30, h=8, txt=str(rows['amount_purchased']), border=1)
        pdf.cell(w=30, h=8, txt=str(rows['price_per_unit']), border=1)
        pdf.cell(w=30, h=8, txt=str(rows['total_price']), border=1, ln=1)

    total_sum = df['total_price'].sum()
    pdf.set_font(family='Times', size=10)
    pdf.cell(w=30, h=8, txt='', border=1)
    pdf.cell(w=70, h=8, txt='', border=1)
    pdf.cell(w=30, h=8, txt='', border=1)
    pdf.cell(w=30, h=8, txt='', border=1)
    pdf.cell(w=30, h=8, txt=str(total_sum), border=1, ln=1)
    pdf.ln(10)

    pdf.set_font(family='Times', size=12, style="B")
    pdf.cell(w=30, h=8, txt=f"The total due amount is {total_sum} euros", ln=1)
    pdf.cell(w=25, h=8, txt="PythonHow")
    pdf.image('pythonhow.png', w=10)
    pdf.output(f"PDFs/{filename}.pdf")


import sys
import os
try:
    operands = []
    comps = []
    openoperands = open(sys.argv[1], "r")
    opencomparisondata = open(sys.argv[2], "r")
    operand = list(openoperands.read().splitlines())
    comparisondata = list(opencomparisondata.read().splitlines())
    def roundy(x):
        if float(x) - int(float(x)) >= 0.5:
            return int(float(x)) + 1
        else:
            return int(float(x))
    for i in range(len(operand)):
        try:
            comps.append(comparisondata[i].split(" "))
            operands.append(operand[i].split(" "))
            div = roundy(operands[i][0])
            divmod = roundy(operands[i][1])
            rangeof = list(range(roundy(operands[i][2]), roundy(operands[i][3])+1))
            print("-" * 12)
            myresults = []
            for x in rangeof:
                if x % div == 0 and x % divmod != 0:
                    myresults.append(x)
            print("My results:\t\t",*myresults)
            print("Results to compare:\t", *comps[i])
            [str(myresults) for i in range(len(myresults))]
            assert len(myresults) == len(comps[i])
        except AssertionError:
            print("AssertionError: results don’t match.")
        except ZeroDivisionError:
            print("ZeroDivisionError: You can’t divide by 0.\nGiven input: ",*operands[i])
        except ValueError:
            print("-" * 12)
            print("ValueError: only numeric input is accepted.\nGiven input: ",*operands[i])
        except IndexError:
            print("-" * 12)
            print("IndexError: number of operands less than expected.\nGiven input:",*operands[i])
        except:
            print("-" * 12)
            print("kaBOOM: run for your life!")
        else:
            print("Goool!!!")
except IndexError:
    if len(sys.argv) > 2:
            print("IndexError: there is no comparison data to compare.")
    else:
        print("IndexError: number of input files less than expected.")
except IOError:
    if os.path.exists(f'{os.path.abspath(os.getcwd())}/{sys.argv[1]}') == False and os.path.exists(f'{os.path.abspath(os.getcwd())}/{sys.argv[1]}') == False:
        probleminput = f"{sys.argv[1]} and {sys.argv[2]}"
    elif os.path.exists(f'{os.path.abspath(os.getcwd())}/{sys.argv[1]}') == False:
        probleminput = f"{sys.argv[1]}"
    else:
        probleminput = f"{sys.argv[2]}"
    finalmessage = f"IOError: cannot open {probleminput}"
    print(finalmessage)
finally:
    print("\n˜ Game Over ˜")

#Şükriye Öztürk 2210356110


DIRECTIONS = [(0, 1), (0, -1), (1, 0), (-1, 0)]

class Solution:
    """
    @param matrix: a matrix
    @return: the minimum height
    """

    # Attemp1: NOT WORKING since 4 directions you will have dead loop using dfs
    # dfs. return min path sum.
    # Time: O(4^n) space: O(n^2)

    # def minPathSumII(self, matrix):
    #     if not matrix:
    #         return 0
    #     m, n = len(matrix), len(matrix[0])
    #     return self.dfs(matrix, m - 1, 0)

    # def dfs(self, matrix, i, j):
    #     if i < 0 or j < 0 or i >= len(matrix) or j >= len(matrix[0]):
    #         return sys.maxsize
    #     if i == 0 and j == len(matrix[0]) - 1:
    #         return matrix[i][j]
    #     return matrix[i][j] + min(self.dfs(matrix, i + 1, j), self.dfs(matrix, i - 1, j), self.dfs(matrix, i, j + 1), self.dfs(matrix, i, j - 1))

    # APP1: dp + dfs. f[i][j]:min path sum from (n - 1, 0) to (i, j)
    # dfs: fill dp f[i][j]. from 4 directions. if out boundary or matrix[_i][_j] + cursum >= f[_i][_j], continue.
    # Time: O(4^n) with pruning. Space: O(n^2)
    def minPathSumII(self, matrix):
        if not matrix or not matrix[0]:
            return 0
        f = [[sys.maxsize] * len(matrix[0]) for _ in range(len(matrix))]
        self.dfs(matrix, len(matrix) - 1, 0, matrix[-1][0], f)
        return f[0][-1]

    def dfs(self, matrix, i, j, cursum, f):
        f[i][j] = cursum
        for dx, dy in DIRECTIONS:
            x, y = i + dx, j + dy
            if self.is_valid(matrix, x, y, cursum, f):
                self.dfs(matrix, x, y, matrix[x][y] + cursum, f)

    def is_valid(self, matrix, x, y, cursum, f):
        if x < 0 or y < 0 or x >= len(matrix) or y >= len(matrix[0]):
            return False
        if cursum + matrix[x][y] >= f[x][y]:
            return False
        return True

    # APP2: bfs. enqueue adjacent pos. reenter queue when dis < previous
    # Time: O(4^n) space: O(n^2)
    def minPathSumII(self, matrix):
        if not matrix or not matrix[0]:
            return 0
        m, n = len(matrix), len(matrix[0])
        q, visited = collections.deque([(m - 1, 0)]), {(m - 1, 0): matrix[m - 1][0]}
        while q:
            x, y = q.popleft()
            for dx, dy in DIRECTIONS:
                _x, _y = x + dx, y + dy
                if self.is_valid(matrix, _x, _y, visited, x, y):
                    q.append((_x, _y))
                    visited[(_x, _y)] = matrix[_x][_y] + visited[(x, y)]
        return visited[(0, n - 1)]

    def is_valid(self, matrix, x, y, visited, pre_x, pre_y):
        if x < 0 or x >= len(matrix) or y < 0 or y >= len(matrix[0]):
            return False
        if (x, y) in visited and (visited[(x, y)] <= visited[(pre_x, pre_y)] + matrix[x][y]):
            return False
        return True

    # Attempt2: DP: f: min path sum.
    # NOT WOKRING FOR [[0,0,0,1,1],[0,1,0,0,0],[0,1,1,1,1], [0,1,1,1,1]]
    # f[i][j] = matrix[i][j] + min(f[i][j - 1], f[i][j + 1], f[i - 1][j], f[i + 1][j])
    # we can do two pass DP.
    # Time: O(n^2) space: O(n^2)
    # def minPathSumII(self, matrix):
    #     if not matrix or not matrix[0]:
    #         return 0
    #     m, n = len(matrix), len(matrix[0])
    #     f = [[sys.maxsize] * (n + 2) for _ in range(m + 2)]
    #     f[-1][1] = f[-2][0] = 0
    #     for i in range(1, m + 1):
    #         for j in range(n, 0, -1):
    #             f[i][j] = min(f[i][j], matrix[i - 1][j - 1] + min(f[i - 1][j], f[i][j + 1]))
    #     print(f)
    #     for i in range(m, 0, -1):
    #         for j in range(1, n + 1):
    #             f[i][j] = matrix[i - 1][j - 1] + min(f[i][j - 1], f[i + 1][j])
    #     print(f)
    #     return f[1][-2]

    # APP4: bfs


import json

import requests
from django.conf import settings

class CalumaClient:
    def __init__(
        self,
        token,
        endpoint,
    ):
        self.token = token
        self.endpoint = endpoint

    def execute(self, query, variables=None, add_headers=None):
        return self._send(query, json.dumps(variables), add_headers=add_headers)

    def _send(self, query, variables, add_headers=None):
        data = {"query": query, "variables": variables}
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": self.token,
        }

        if add_headers:
            headers.update(add_headers)

        response = requests.post(
            self.endpoint,
            json=data,
            headers=headers,
            verify=settings.CALUMA_VERIFY_SSL,
            timeout=15,
        )
        response.raise_for_status()
        return response.json()

    def get_data(self, gql_file, variables, add_headers=None):
        with gql_file.open("r") as f:
            query = f.read()
        return self.execute(query, variables, add_headers=add_headers)


from django.db import models
import os
from twilio.rest import Client
# Create your models here.
class SMS(models.Model):
    mysms = models.CharField(max_length=200)
    def save(self, *args, **kwargs):
        account_sid = 'Your Account SID'
        auth_token = 'Your Auth Token'
        client = Client(account_sid, auth_token)
        message = client.messages.create(
                            body={self.mysms},
                            from_='Twilio Phone Number',
                            to   ='Phone Number on which sms send'
                            )
        print(message.sid)
        return super().save(*args, **kwargs)


import random
from typing import Tuple, List
from datetime import date, timedelta, datetime

from django.core.management.base import BaseCommand
from django.db.utils import IntegrityError
from numpy.random import choice
from russian_names import RussianNames

from core.models import Well, WellState, WellExtraction, Field, Layer

class Command(BaseCommand):

    def __init__(self):
        super().__init__()
        self.purpose_values = {"добывающая": "Добыча",
                               "нагнетательная": "Нагнетание",
                               "специальная": ["Пьезометрическая", "Оценочная", "Разведочная", "Наблюдатетельная"],
                               "вспомогательная": ["Водозаборная", "Поглощающая"]}

    def get_dates_of_drilling(self) -> Tuple[date, date, date]:
        start_date = date(2000, 1, 1)
        available_range = (date(datetime.now().year - 1, 12, 31) - start_date).days
        start_offset = random.randint(0, available_range - 1800)
        start_date_of_drilling = start_date + timedelta(days=start_offset)
        completion_offset = random.randint(90, 1700)
        completion_date_of_drilling = start_date_of_drilling + timedelta(days=completion_offset)
        service_offset = random.randint(0, 90)
        service_date = completion_date_of_drilling + timedelta(days=service_offset)
        return start_date_of_drilling, completion_date_of_drilling, service_date

    def get_purpose_and_nature_of_work(self) -> Tuple[str, str]:
        purpose = random.choice(list(self.purpose_values.keys()))
        nature_of_work_values = self.purpose_values[purpose]
        if type(nature_of_work_values) is list:
            nature_of_work = random.choice(nature_of_work_values)
        else:
            nature_of_work: str = nature_of_work_values
        return purpose, nature_of_work

    def create_wells(self, field: Field, layer: Layer, letter: str) -> List[Well]:
        wells = []
        for i in range(random.randint(10, 60)):
            params = dict(
                name=f"{random.randint(10, 2000)}{letter}",
                # todo пока вероятность не работает
                purpose=choice(["добывающая", "нагнетательная", "специальная", "вспомогательная"],
                               p=[0.7, 0.1, 0.1, 0.1]),
                well_type=choice(["многозабойная", "горизонтальная", "наклонно-направленная"], p=[0.25, 0.5, 0.25]),
                operator=RussianNames().get_person(),
                license_block="Снежный",
                mining_method=random.choice(["фонтанный", "компрессорный", "насосный"]),
                field=field,
                x_coordinate=field.x_coordinate + random.uniform(-0.07, 0.07),
                y_coordinate=field.y_coordinate + random.uniform(-0.07, 0.07)
            )
            params["profile"] = random.choice(["A", "Б", "В", "Г"]) if params["well_type"] == "наклонно-направленная" else "-"
            params["sank_amount"] = random.randint(1, 4) if params["well_type"] == "многозабойная" else 0
            params["start_date_of_drilling"], params["completion_date_of_drilling"], params[
                "service_date"] = self.get_dates_of_drilling()
            params["purpose"], params["nature_of_work"] = self.get_purpose_and_nature_of_work()
            well = Well(**params)
            try:
                well.save()
                well.layers.set([layer])
                well.save()
                wells.append(well)
            except IntegrityError:
                print(f"Скважина с именем {well.name} уже существует")
        return wells

    def create_well_extraction_data(self, well: Well) -> None:
        oil_output_t = 0
        gas_output_m3 = 0
        liquid_output_m3 = 0

        for year in range(well.service_date.year, datetime.now().year):
            oil_output_t_inc = random.uniform(0, 5000)
            liquid_output_m3_inc = random.uniform(0, 7000)
            gas_output_m3_inc = random.uniform(0, 600)
            oil_output_t += oil_output_t_inc
            liquid_output_m3 += liquid_output_m3_inc
            gas_output_m3 += gas_output_m3_inc

            WellExtraction.objects.create(
                year=year,
                oil_output_t=oil_output_t,
                oil_output_m3=oil_output_t / 865 * 1000,
                liquid_output_t=liquid_output_m3 / 1000 * 997,
                liquid_output_m3=liquid_output_m3,
                gas_output_m3=gas_output_m3,
                water_injection=random.uniform(0, 250),
                gas_injection=random.uniform(30000, 200000),
                well=well,
                oil_rate=oil_output_t_inc / 365,
                liquid_rate=liquid_output_m3_inc / 365,
                gas_rate=gas_output_m3_inc / 365,
                bottom_hole_pressure=well.layers.first().layer_pressure - random.uniform(1, 3.5)
            )

    def handle(self, *args, **options):
        fields = Field.objects.all()
        for field in fields:
            for layer in field.layers.all():
                letter = random.choice(["P", "I", "J", "N", "U"])
                wells = self.create_wells(field=field, layer=layer, letter=letter)
                for well in wells:
                    self.create_well_extraction_data(well)


import math
import numpy as np
import matplotlib
matplotlib.use('SVG')

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

a = 0.
b = 1.

f = lambda x: 5. *x
u = lambda x: -5. * x**3 / 6. + 5. * x / 6. + 0. * x * (1- x) / 2 + (b - a) * x + a

x0 = 0.
x1 = 1.
xs = np.linspace(x0, x1, 100)
ax.plot(xs, u(xs), linewidth=2, label = '$u(x)$')

ax.plot(xs, f(xs), linestyle='dashed', label = '$f(x)$')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_bounds(x0, x1)
ax.spines['bottom'].set_position('zero')
plt.tick_params(
    axis='y',
    which='both',
    left='on',
    right='off',
    labelleft='on')
ax.xaxis.set_ticks_position('bottom')

ax.set_xlim((x0, x1))
m = np.min(u(xs))
M = np.max(u(xs))
h = 0.1 * (M - m)
ax.set_ylim((m - h, M + h))
ax.set_xlabel('$x$')
ax.xaxis.set_label_coords(1.0, -0.025)
ax.set_ylabel('$y$', rotation=0)
ax.yaxis.set_label_coords(-0.025, 1.0)

ax.legend(frameon=False, loc='upper right')

plt.savefig('../img/simple_poisson.svg')
# plt.show()


from collections import deque

def dls(start, goal, graph, limit):
    '''
    Finds the path using DLS
    '''
    path = []
    explored = set()

    frontier = deque()  # Stack
    frontier.append(start)
    depth = { start: 0 }
    for node in graph:
        for nxt in graph[node]:
            depth[nxt] = depth.get(node, 0) + 1

    while frontier:
        current = frontier.pop()
        path.append(current)
        if current == goal:
            break
        explored.add(current)
        if depth[current] > limit - 1:
            raise Exception(f'Cutoff: Depth limit: {limit} reached')
        for next in graph.get(current, [])[::-1]:
            if next not in explored:
                frontier.append(next)
    else:
        raise ValueError(f'Failure: No path from {start} to {goal}')
    return ' -> '.join(path)

if __name__ == '__main__':
    graph = {
        "A": ["B", "C", "D"],
        "B": ["E", "F"],
        "C": ["G", "H"],
        "D": ["I", "J"]
    }
    start, goal = 'A', 'G'
    print('DLS traversal: ', dls(start, goal, graph, limit=1))


from zope.cachedescriptors.property import Lazy
from zope.interface import implements

from cybertools.organize.interfaces import IWorkItems
from loops.common import AdapterBase, adapted, baseObject
#from loops.organize.task import Task
from loops.type import TypeInterfaceSourceList
from loops import util
from cco.work.interfaces import IProject, ITask

#from cco.storage.loops import common

TypeInterfaceSourceList.typeInterfaces += (IProject, ITask)

#class TaskBase(common.AdapterBase):
class TaskBase(AdapterBase):

    _contextAttributes = list(ITask)

    #start = end = None

    defaultStates = ['done', 'done_x', 'finished', 'finished_x']

    @property
    def actualEffort(self):
        result = 0.0
        for t in self.getAllTasks():
            for wi in t.getWorkItems():
                result += wi.effort
        return result

    def getSubTasks(self):
        if self.__is_dummy__:
            return []
        result = []
        for c in baseObject(self).getChildren():
            obj = adapted(c)
            if IProject.providedBy(obj) or ITask.providedBy(obj):
                result.append(obj)
        return result

    def getAllTasks(self):
        if self.__is_dummy__:
            return []
        result = set([self])
        for t1 in self.getSubTasks():
            if t1 not in result:
                for t2 in t1.getAllTasks():
                    if t2 not in result:
                        result.add(t2)
        return result

    @Lazy
    def workItems(self):
        rm = self.getLoopsRoot().getRecordManager()
        return IWorkItems(rm['work'])

    def addWorkItem(self, party, action='plan', **kw):
        wi = self.workItems.add(util.getUidForObject(baseObject(self)), party)
        wi.doAction(action, party, **kw)

    def getWorkItems(self, crit={}):
        kw = dict(task=util.getUidForObject(baseObject(self)),
                  state=crit.get('states') or self.defaultStates)
        return self.workItems.query(**kw)

class Project(TaskBase):
    """ Adapter for concepts of a project type
        with additional fields for planning/controlling.
    """

    implements(IProject)

    _adapterAttributes = AdapterBase._adapterAttributes + (
            'estimatedEffort', 'chargedEffort', 'actualEffort',)
    _contextAttributes = list(IProject)

    @property
    def estimatedEffort(self):
        return sum(self.tofloat(t.estimatedEffort or 0.0)
                    for t in self.getSubTasks())

    @property
    def chargedEffort(self):
        return sum(self.tofloat(t.chargedEffort or 0.0)
                    for t in self.getSubTasks())

    @staticmethod
    def tofloat(v):
        if isinstance(v, basestring):
            v = v.replace(',', '.')
        try:
            return float(v)
        except ValueError:
            return 0.0

class Task(TaskBase):
    """ Adapter for concepts of a task type
        with additional fields for planning/controlling.
    """

    implements(ITask)

    #estimatedEffort = chargedEffort = 0.0

    _adapterAttributes = AdapterBase._adapterAttributes + ('actualEffort',)
    _contextAttributes = list(ITask)


from django.conf.urls import patterns, url
from apps.editor import views

urlpatterns = patterns('',
	url(r'^$', views.Index, name = 'index'),
	url(r'^newproject/$', views.GetNewProject, name = 'newproject'),
	url(r'^savecode/$', views.SaveCode, name = 'savecode'),
	url(r'^altername/$', views.AlterName, name = 'altername'),
	url(r'^vote/$', views.Vote, name = 'vote')
)


''' @file task_hardware.py
    @brief Task to assign motors and encoders to hardware pins, checking for user to disable faults, and setting duty cycle to shared value
    @details Sets motors/encoders to their repective pins and channel numbers then enables the driver. A controller is instantiated to be
    used to control duty based on a current and reference velocity. Tasks constantly updates shared values and checks for flags executed
    in task user.
    @author Christian Clephan
    @author John Bennett
    @date November 13, 2021
'''

import pyb
import utime
import closedloop
import math
import encoder2

# Motor Pins
## @brief Sets up first pin for motor 1
pinB4 = pyb.Pin(pyb.Pin.cpu.B4)
## @brief Sets up second pin for motor 1
pinB5 = pyb.Pin(pyb.Pin.cpu.B5)
## @brief Sets up first pin for motor 2
pinB0 = pyb.Pin(pyb.Pin.cpu.B0)
## @brief Sets up second pin for motor 2
pinB1 = pyb.Pin(pyb.Pin.cpu.B1)

## Encoder Pins
## @brief Sets up first pin for encoder 1
pinB6 = pyb.Pin (pyb.Pin.cpu.B6)
## @brief Sets up second pin for encoder 1
pinB7 = pyb.Pin (pyb.Pin.cpu.B7)
## @brief Sets up first pin for encoder 2
pinC6 = pyb.Pin (pyb.Pin.cpu.C6)
## @brief Sets up second pin for encoder 2
pinC7 = pyb.Pin (pyb.Pin.cpu.C7)

## Motor Shares Index referances
## @brief Index reference for encoder number
ID = 0
## @brief Index reference for current position (rad)
POSITION = 1
## @brief Index reference for current velocity (rad/s)
VELOCITY = 2
## @brief Index reference for reference (previous) position (rad)
REF_POSITION = 3
## @brief Index reference for reference (previous) velocity (rad/s)
REF_VELOCITY = 4
## @brief Index reference for zero flag
IS_ZERO = 5
## @brief Index reference for disable fault flag
DIS_FAULT = 6
## @brief Index reference for PID controller
PID = 7
## @brief Index reference for current duty (% PWM)
DUTY = 8
## @brief Index reference for checking if there is a fault
IS_FAULT = 9

## @brief Ratio of radians to ticks on encoder
ticks_to_rad = (2*math.pi/4000)
class Task_Hardware:
    ''' @brief                  Encoder and motor task methods.
        @details                Contains logic to be used with hardware based on what is desired from commands sent by
                                task user.
    '''

    def __init__(self, period,MotorShare, motor_drv):

        '''
        @brief              Constructs an hardware task object
        @details            Instantiates period, a variable changing for every period, motor object
        @param              Period at which motor updates defined by user in main.
        @param              MotorShare is a share object that contains all relevent info about the motor
        @param              motor_drv is the DRV8847 driver
        '''

        ## @brief Defines period as what is called in main for period parameter
        self.period = period*1000
        ## @brief Time adjusts once clock reaches the period value plus the current time
        self.next_time = period*1000 + utime.ticks_us()
         ## @brief Time time of last run
        self.last_time = utime.ticks_us()

        ## @brief Shares all relevavant motor info
        # [Encoder number (int), Current Position (ticks), Current delta (ticks/period), duty(int), Zero (boolean), Fault(boolean)]
        self.MotorShare = MotorShare

        ## @brief Instantiates motor driver object
        self.motor_drv = motor_drv

        if self.MotorShare.read(ID) == 1:
            ##  @brief Creates motor object from motor function in DRV8847 driver with specified chanel and pins
            self.motor = self.motor_drv.motor(1,pinB4,pinB5)
            ## @brief Creates encoder object with functionallity described in encoder driver file. Parameters for object dictate encoder pins and timer.
            self.encoder = encoder2.Encoder(pinB6,pinB7,4)
        elif self.MotorShare.read(ID) == 2:
            self.motor = self.motor_drv.motor(3,pinB0,pinB1)
            self.encoder = encoder2.Encoder(pinC6,pinC7,8)

        #Enable motor driver
        self.motor_drv.enable()

        ## @brief Instantiates controller object that reads PID initial values and sets duty limits to -100 and 100.
        self.Controller = closedloop.ClosedLoop(self.MotorShare.read(PID), [-100,100])

    def run(self):
        '''
        @brief      Updates shared values of current/reference position and velocity. Detects for UI flags and if PID gains change.
        @details    Constantly updates motor position and velocity and executes logic for flags sent from task_user such as zeroing
                    position or reseting velocity and PID gains when a fault is disabled.
        '''

        # If the current time passes next time (time to update) then next update is utilized to obtain encoder position and delta
        if (utime.ticks_us() >= self.next_time):
            # Update motor share values with new current position, velocity, and set duty to controller output that takes in a
            # reference velocity, velocity, and time difference.

            self.nextUpdate()

            # If zero command is True then encoder position is set to 0
            if self.MotorShare.read(IS_ZERO):
                self.encoder.set_position(0)
                self.MotorShare.write(IS_ZERO,False)

            if self.motor_drv.fault_status():
                self.MotorShare.write(IS_FAULT, True)

            # If the disable fault flag is true: reference velocity and PID are reset and the driver is re-enabled.
            if (self.MotorShare.read(DIS_FAULT)):
                self.MotorShare.write(REF_VELOCITY, 0)
                self.MotorShare.write(PID,[0,0,0])
                self.motor_drv.enable()
                self.MotorShare.write(IS_FAULT, False)
                self.MotorShare.write(DIS_FAULT,False)

            # If there's a difference in PID values then change the PID to what is new.
            if (self.MotorShare.read(PID) != self.Controller.get_PID()):
                self.Controller.set_PID(self.MotorShare.read(PID))

    def nextUpdate(self):
        '''
        @brief      Updates encoder position, velocity, and time then sets duty to what is calculated in controller update method.
        @details    Uses encoder driver to update position/velocity from which the values are written into the MotorShare list
                    and the period is updated. Duty is determined by controller update method, which takes in reference/current
                    velocity and a time difference.
        '''
        ## @brief Time difference between runs
        tdif = utime.ticks_diff(utime.ticks_us(), self.last_time)
        self.encoder.update()
        self.next_time += self.period
        self.last_time = utime.ticks_us()

        self.MotorShare.write(POSITION,self.encoder.get_position()*ticks_to_rad)
        self.MotorShare.write(VELOCITY,self.encoder.get_delta()*ticks_to_rad/((tdif)/1000000))

        ## @brief Motor duty value obtained from controller update method.
        duty = self.Controller.update(self.MotorShare.read(REF_VELOCITY), self.MotorShare.read(VELOCITY),tdif)
        self.MotorShare.write(DUTY, duty)
        self.motor.set_duty(duty)

Mechatronics I/Lab4/The Real Code/task_hardware.py


import smtplib

receiver_email = input("Enter the receiver's email\n")
content = input("Enter the content\n")

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587) # 2nd parameter is the port number
    server.ehlo()
    server.starttls() # this will start the session
    server.login('sender_email@gmail.com', '12345') # 2nd parameter is the password
    server.sendmail('sender_email@gmail.com', to, content)
    server.close() # this will close the connection

sendEmail(receiver_email, content)