from __future__ import print_function
import Tile
import numpy as np
import collections

'''
Encoding:
0: player->hand,
1: player->fixed_hand
2: player->disposed_tiles

3+2i: neighbor[i]->fixed_hand
3+2i+1: neighbor[i]->disposed_tiles
'''
def dnn_encode_state(player, neighbors):
	state = np.zeros((9, 34, 1))
	for tile in player.hand:
		state[0, Tile.convert_tile_index(tile), :] += 1

	players = [player] + list(neighbors)
	for i in range(len(players)):
		p = players[i]
		for _, _, tiles in p.fixed_hand:
			for tile in tiles:
				state[1 + 2*i, Tile.convert_tile_index(tile), :] += 1

		for tile in p.get_discarded_tiles():
			state[2 + 2*i, Tile.convert_tile_index(tile), :] += 1
	return state

def extended_dnn_encode_state(player, neighbors, new_tile = None, cpk_tile = None):
	state = np.zeros((10, 34, 1))
	for tile in player.hand:
		state[0, Tile.convert_tile_index(tile), :] += 1

	if new_tile is not None:
		state[0, Tile.convert_tile_index(new_tile), :] += 1

	if cpk_tile is not None:
		state[9, Tile.convert_tile_index(cpk_tile), :] += 1

	players = [player] + list(neighbors)
	for i in range(len(players)):
		p = players[i]
		for _, _, tiles in p.fixed_hand:
			for tile in tiles:
				state[1 + 2*i, Tile.convert_tile_index(tile), :] += 1

		for tile in p.get_discarded_tiles():
			state[2 + 2*i, Tile.convert_tile_index(tile), :] += 1

	return state

def get_input_list(title, options):
	i = 0
	options_str = ""
	for option in options:
		options_str += "%d. %s\n"%(i, option)
		i += 1
	print("%s\n%s"%(title, options_str), end = "")
	while True:
		result = input("Enter your choice [%d - %d]: "%(0, len(options) - 1))
		try:
			result = int(result)
			if result < 0 or result >= len(options):
				raise ValueError
			return result
		except ValueError:
			print("Input must be an integer within the range, try again")

def get_input_range(title, lower_bound, upper_bound, lb_inclusive = True, ub_inclusive = True):
	range_str, lb_sign, ub_sign = "", "", ""
	if lb_inclusive:
		lb_sign = "["
	else:
		lb_sign = "("

	if ub_inclusive:
		ub_sign = "]"
	else:
		ub_sign = ")"

	range_str = "%s%d,%d%s"%(lb_sign, lower_bound, upper_bound, ub_sign)

	while True:
		result = input("%s %s: "%(title, range_str))
		try:
			result = int(result)
			if result < lower_bound or result > upper_bound:
				raise ValueError
			if not lb_inclusive and result == lower_bound:
				raise ValueError
			if not ub_inclusive and result == upper_bound:
				raise ValueError
			return result
		except ValueError:
			print("Input must be an integer within the range, try again")

def map_increment(map, index, increment = 1, remove_zero = False):
	if index is None:
		raise Exception("Index cannot be None")

	result = map.get(index, 0) + increment
	map[index] = result

	if remove_zero and result == 0:
		del map[index]

	return map

def map_retrieve(map, index, default_val = 0):
	if index is None:
		return default_val

	if not isinstance(index, collections.Hashable):
		index = str(index)

	return map.get(index, default_val)

def print_hand(hand, end = "\n"):
	meld_type, is_secret, tiles = None, None, None
	for meld in hand:
		if type(meld) == Tile.Tile:
			print(meld.symbol, end = "")
		else:
			if len(meld) == 3:
				meld_type, is_secret, tiles = meld
			elif len(meld) == 2:
				meld_type, tiles = meld
				is_secret = False
			else:
				raise Exception("unexpected structure of hand")
			for tile in tiles:
				print(tile.symbol, end = "")
			print(" ", end = "")
	print("", end = end)

def softmax(x):
	e_x = np.exp(x - np.max(x))
	return e_x / e_x.sum(axis=0)

def random_choice(objs, p):
	s = 0
	target = np.random.uniform()
	n_item = len(p) if type(p) is list else p.shape[0]
	for i in range(n_item):
		s += p[i]
		if s >= target:
			return objs[i]
	return objs[n_item - 1]

def print_game_board(player_name, fixed_hand, hand, neighbors, game, new_tile = None, print_stolen_tiles = False):
		line_format_left = u"|{next:<20s}|{opposite:<20s}|{prev:<20s}|"
		line_format_right = u"|{next:>20s}|{opposite:>20s}|{prev:>20s}|"
		line_merged_format_left = u"|{msg:<62s}|"
		line_merged_format_right = u"|{msg:>62s}|"

		horizontal_line = line_merged_format_left.format(msg = '-'*62)

		print("Wake up %s!"%player_name)

		print(horizontal_line)
		print(line_merged_format_right.format(msg = "Game of %s wind [%d]"%(game.game_wind, game.deck_size)))
		print(horizontal_line)
		print(line_format_left.format(next = "Next Player", opposite = "Opposite Player", prev = "Previous Player"))
		print(line_format_left.format(next = "(%s)"%neighbors[0].name, opposite = "(%s)"%neighbors[1].name, prev = "(%s)"%neighbors[2].name))
		print(horizontal_line)

		fixed_hands_strs = []
		hand_sizes = []
		disposed_tiles_symbols = []
		filter_state = None if print_stolen_tiles else "unstolen"

		for neighbor in neighbors:
			fixed_hand_str = ""
			for meld_type, is_secret, tiles in neighbor.fixed_hand:
				if is_secret:
					fixed_hand_str += Tile.tile_back_symbol + tiles[0].symbol + tiles[0].symbol + Tile.tile_back_symbol
				else:
					fixed_hand_str += "".join([tile.symbol for tile in tiles])
			fixed_hands_strs.append(fixed_hand_str)
			hand_sizes.append(neighbor.hand_size)

			disposed_tiles = neighbor.get_discarded_tiles(filter_state)
			disposed_tiles_symbols.append(''.join([tile.symbol for tile in disposed_tiles]))

		print(line_format_left.format(next = fixed_hands_strs[0], opposite = fixed_hands_strs[1], prev = fixed_hands_strs[2]))
		print(line_format_right.format(next = "%s -%d"%(Tile.tile_back_symbol*hand_sizes[0], hand_sizes[0]), opposite =  "%s -%d"%(Tile.tile_back_symbol*hand_sizes[1], hand_sizes[1]), prev =  "%s -%d"%(Tile.tile_back_symbol*hand_sizes[2], hand_sizes[2])))

		print(horizontal_line)
		is_continue_print = True

		while is_continue_print:
			print(line_format_left.format(next = disposed_tiles_symbols[0][0:20], opposite = disposed_tiles_symbols[1][0:20], prev = disposed_tiles_symbols[2][0:20]))
			is_continue_print = False
			for i in range(3):
				disposed_tiles_symbols[i] = disposed_tiles_symbols[i][20:]
				if len(disposed_tiles_symbols[i]) > 0:
					is_continue_print = True

		print(horizontal_line)
		print(line_merged_format_left.format(msg = "%s's tiles:"%(player_name)))
		fixed_hand_str = ""
		for meld_type, is_secret, tiles in fixed_hand:
			if is_secret:
				fixed_hand_str += "".join([Tile.tile_back_symbol, tiles[0].symbol, tiles[0].symbol, Tile.tile_back_symbol])
			else:
				fixed_hand_str += "".join([tile.symbol for tile in tiles])
		print(line_merged_format_left.format(msg = fixed_hand_str))

		line_1, line_2 = "", ""
		i = 0
		for tile in hand:
			line_1 += "%s  "%(tile.symbol)
			line_2 += "{digit:<3s}".format(digit = str(i))
			i += 1
		print(line_merged_format_right.format(msg = line_1))
		print(line_merged_format_right.format(msg = line_2))

		if new_tile is not None:
			print(line_merged_format_right.format(msg = "%d: %s  "%(i, new_tile.symbol)))
		print(horizontal_line)

def generate_TG_boad(player_name, fixed_hand, hand, neighbors, game, new_tile = None, print_stolen_tiles = False):
	line_format_left = u"|{msg:<25s}|\n"
	line_format_right = u"|{msg:>25s}|\n"
	horizontal_line = line_format_left.format(msg = '-'*25)

	result = line_format_left.format(msg = "Game of %s wind [%d]"%(game.game_wind, game.deck_size))

	for i in range(len(neighbors)):
		neighbor = neighbors[i]
		identifier = "%s"%neighbor.name
		if i == 0:
			identifier += " (next)"
		elif i == 2:
			identifier += " (prev)"

		fixed_hand_strs = []
		for meld_type, is_secret, tiles in neighbor.fixed_hand:
			meld_str = ""
			if is_secret:
				meld_str += Tile.tile_back_symbol + tiles[0].symbol + tiles[0].symbol + Tile.tile_back_symbol
			else:
				meld_str += "".join([tile.symbol for tile in tiles])
			fixed_hand_strs.append(meld_str)

		result += line_format_left.format(msg = identifier)
		result += line_format_left.format(msg = " ".join(fixed_hand_strs))
		result += line_format_right.format(msg = "%s [%d]"%(Tile.tile_back_symbol*neighbor.hand_size, neighbor.hand_size))
		result += horizontal_line

	result += line_format_left.format(msg = "Tiles disposed")
	disposed_tiles = game.disposed_tiles
	while True:
		result += line_format_left.format(msg = "".join([tile.symbol for tile in disposed_tiles[0:25]]))
		disposed_tiles = disposed_tiles[25:]
		if len(disposed_tiles) == 0:
			break

	result += horizontal_line

	fixed_hand_strs, hand_str = [], ""
	for meld_type, is_secret, tiles in fixed_hand:
		meld_str = ""
		if is_secret:
			meld_str += Tile.tile_back_symbol + tiles[0].symbol + tiles[0].symbol + Tile.tile_back_symbol
		else:
			meld_str += "".join([tile.symbol for tile in tiles])
		fixed_hand_strs.append(meld_str)

	for tile in hand:
		hand_str += tile.symbol
	if new_tile is not None:
		hand_str += " - "+new_tile.symbol+" "

	result += line_format_left.format(msg = "Your tiles")
	result += line_format_left.format(msg = " ".join(fixed_hand_strs))
	result += line_format_right.format(msg = hand_str)

	print(result)
	return result


from random import randint
from telegram import Update, Bot
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler, ConversationHandler

bot = Bot(token='5594488827:AAG1tLzTOpSE1_tEABaf43GT3uf0iukcGdI')
updater = Updater(token='5594488827:AAG1tLzTOpSE1_tEABaf43GT3uf0iukcGdI', use_context=True)
dispatcher = updater.dispatcher

global num_candy1, num_candy2, num_candy3
print ('\nИгра кто последний заберет конфеты, тот -  выиграл!\n')

from random import randint

def command_start(update, context):
    context.bot.send_message(update.effective_chat.id, 'Привет, я бот хочешь сыграть в игру? Кто последний заберет конфеты - тот выиграл. ')
    context.bot.send_message(update.effective_chat.id, 'Выбери исходное кол конфет: /kol "кол"')

print ('\nИгра кто последний заберет конфеты, тот -  выиграл!\n')

def command_input1(update, context):
    global num_candy1
    num_candy1 = context.args
    print (f'исходное кол кофет {num_candy1}')
    context.bot.send_message(update.effective_chat.id, 'введите максимальное кол конфет, которое можно брать: /max "кол"')

def command_input2(update, context):
    global num_candy2, num_candy_ost, num_candy_take, count, turn, curr_player_turn, num_candy3
    num_candy2 = context.args
    print (f'максимальное кол конфет {num_candy2}')

# def command_input3(update, context):
#     global num_candy3
#     num_candy3 = context.args
#     print (f'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')

    num_candy_ost = int (num_candy1[0])
    num_candy_take= int (num_candy2[0])

    from random import randint

    count = 0
    curr_player_turn = 0
    flag = True
    flag1 = 0

    print (f"Кол конфет в кучке: {num_candy_ost}, можно взять от 1 до {num_candy_take} конф.\n")
    context.bot.send_message(update.effective_chat.id, f"Кол конфет в кучке: {num_candy1}, можно взять от 1 до {num_candy2} конф.")

    while True:
        count += 1
        if num_candy_ost <= num_candy_take:
            print (f"Ход №{count} БОТ взял {num_candy_ost} конф., БОТ ПОБЕДИЛ!!!\n")
            context.bot.send_message(update.effective_chat.id, f"Ход №{count} БОТ: взял {num_candy_ost} конф., БОТ ПОБЕДИЛ!!!")
            break
    # 1 - ый ход
        if count == 1 :
            turn = randint(1, num_candy_take)
            flag = False
            num_candy_ost -= turn
            print (f"Ход №{count} БОТ взял {turn} конф. В кучке {num_candy_ost} конф.")
            context.bot.send_message(update.effective_chat.id, f"Ход №{count} БОТ взял {turn} конф. В кучке {num_candy_ost} конф.")
    # ходы последующие
        else:
            if num_candy_ost % (num_candy_take + 1) != 0:
                flag = True
                if flag1 == 0:                                                               #флаг - перелом игры, компьютер поменял стратегию игры
                    print ("---ВЫ ОШИБЛИСЬ! БОТ МЕНЯЕТ СТРАТЕГИЮ, НАЧИНАЕТ ВЫИГРЫВАТЬ----\n")
                    context.bot.send_message(update.effective_chat.id, "---ВЫ ОШИБЛИСЬ! БОТ МЕНЯЕТ СТРАТЕГИЮ, НАЧИНАЕТ ВЫИГРЫВАТЬ----")
                    flag1 += 1
            turn = num_candy_ost % (num_candy_take + 1) if flag == True else randint(1, num_candy_take)
            num_candy_ost -= turn
            flag1 = False
            print (f"Ход №{count} БОТ взял {turn} конф. В кучке {num_candy_ost} конф.")
            context.bot.send_message(update.effective_chat.id, f"Ход №{count}  БОТ взял {turn} конф. В кучке {num_candy_ost} конф.")

        count += 1
        if (flag == True):
            print (f"Введите количество конф. ")
            context.bot.send_message(update.effective_chat.id, f"Введите количество конф. ")
        else:
            print (f"Введите количество конф. Чтобы выиграть надо взять: {num_candy_ost % (num_candy_take + 1)} конф.")
            context.bot.send_message(update.effective_chat.id, f"Введите количество конф. Чтобы выиграть надо взять: {num_candy_ost % (num_candy_take + 1)} конф.")

        curr_player_turn = int(input())   # ВВОД ПОЛЬЗОВАТЕЛЯ

        while curr_player_turn < 1 or  curr_player_turn > num_candy_take:
            print (f'Количество конфет должно быть от 1 до {num_candy_take}  повторите ввод: ')
            context.bot.send_message(update.effective_chat.id, f'Количество конфет должно быть от 1 до {num_candy_take}  повторите ввод: ')

            curr_player_turn = int(input())   # ВВОД ПОЛЬЗОВАТЕЛЯ

        num_candy_ost -= curr_player_turn

        if num_candy_ost == 0:
            print ("ВЫ ПОБЕДИЛИ!")
            context.bot.send_message(update.effective_chat.id, "ВЫ ПОБЕДИЛИ!")
            break
        else:
            print (f" Ход №{count} Вы взяли: {curr_player_turn}  конф. В кучке {num_candy_ost} конф. \n")
            context.bot.send_message(update.effective_chat.id, f" Ход №{count} Вы взяли: {curr_player_turn}  конф. В кучке {num_candy_ost} конф.")

updater.dispatcher.add_handler(CommandHandler('start', command_start))
updater.dispatcher.add_handler(CommandHandler('kol', command_input1))
updater.dispatcher.add_handler(CommandHandler('max', command_input2))
#updater.dispatcher.add_handler(CommandHandler('vvod', command_input3))

print ('server start')
updater.start_polling()
updater.idle()


ipAddress = input("Please enter an IP address: ")

ipAddress += "."
x = 1
y = 0
character = ""

for character in ipAddress:
    if character == '.':
        print("segment {} contains {} characters".format(x,y))
        x += 1
        y = 0
    else:
        y += 1


import torch
import numpy as np

def image_batch_transformation(batch, transformation):
    perturbed = []
    for k in range(batch.shape[0]):
        image_k = batch[k, :, :].cpu().detach().numpy()
        perturbed.append(transformation(image=image_k)['image'])
    perturbed = torch.FloatTensor(perturbed).unsqueeze(1).to(batch.device)
    return perturbed

def image_color_batch_transformation(batch, transformation):
    perturbed = []
    for k in range(batch.shape[0]):
        image_k = batch[k, :, :].cpu().detach().numpy()
        image_k = np.moveaxis(image_k, [0, 1, 2], [2, 0, 1])
        image_k = transformation(image=image_k)['image']
        image_k = np.moveaxis(image_k, [2, 0, 1], [0, 1, 2])
        perturbed.append(image_k)
    perturbed = torch.FloatTensor(perturbed).to(batch.device)
    return perturbed


"""
Model performance.
"""
import os
import sys
import time
import resource
import argparse
import warnings
from datetime import datetime
warnings.simplefilter(action='ignore', category=UserWarning)  # lgb compiler warning

import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.base import clone

here = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, here + '/../')  # for utility
sys.path.insert(0, here + '/../../')  # for libliner
import util

def get_model(args, cat_indices=None):
    """
    Return the appropriate classifier.
    """
    if args.model in ['cb', 'lgb', 'xgb']:
        clf = util.get_model(args.model,
                             n_estimators=args.n_estimators,
                             max_depth=args.max_depth,
                             random_state=args.rs,
                             cat_indices=cat_indices)
        params = {'n_estimators': [10, 25, 50, 100, 250], 'max_depth': [3, 5, 7]}

    elif args.model == 'rf':
        clf = util.get_model(args.model,
                             n_estimators=args.n_estimators,
                             max_depth=args.max_depth,
                             random_state=args.rs)
        params = {'n_estimators': [10, 25, 50, 100, 250], 'max_depth': [3, 5, 7],
                  'class_weight': [None, 'balanced']}

    elif args.model == 'dt':
        clf = DecisionTreeClassifier(random_state=args.rs)
        params = {'criterion': ['gini', 'entropy'], 'splitter': ['best', 'random'],
                  'max_depth': [3, 5, 10, None]}

    elif args.model == 'lr':
        clf = Pipeline(steps=[
            ('ss', StandardScaler()),
            ('lr', LogisticRegression(penalty=args.penalty, C=args.C, solver='liblinear', random_state=args.rs))
        ])
        params = {'lr__penalty': ['l1', 'l2'], 'lr__C': [1e-2, 1e-1, 1e0]}

    elif args.model == 'svm_linear':
        clf = Pipeline(steps=[
            ('ss', StandardScaler()),
            ('svm', LinearSVC(dual=False, penalty=args.penalty, C=args.C, random_state=args.rs))
        ])
        params = {'svm__penalty': ['l1', 'l2'], 'svm__C': [1e-2, 1e-1, 1e0]}

    elif args.model == 'svm_rbf':
        clf = Pipeline(steps=[
            ('ss', StandardScaler()),
            ('svm', SVC(gamma='auto', C=args.C, kernel=args.kernel, random_state=args.rs))
        ])
        params = {'svm__C': [1e-2, 1e-1, 1e0]}

    elif args.model == 'knn':
        clf = KNeighborsClassifier(weights=args.weights, n_neighbors=args.n_neighbors)
        params = {'n_neighbors': [3, 5, 7, 9, 11, 13, 15, 31, 45, 61]}

    else:
        raise ValueError('model uknown: {}'.format(args.model))

    return clf, params

def experiment(args, logger, out_dir, seed):
    """
    Main method comparing performance of tree ensembles and svm models.
    """

    # start experiment timer
    begin = time.time()

    # get data
    data = util.get_data(args.dataset,
                         data_dir=args.data_dir,
                         preprocessing=args.preprocessing)
    X_train, X_test, y_train, y_test, feature, cat_indices = data

    logger.info('no. train: {:,}'.format(X_train.shape[0]))
    logger.info('no. test: {:,}'.format(X_test.shape[0]))
    logger.info('no. features: {:,}'.format(X_train.shape[1]))

    # tune on a fraction of the training data
    if not args.no_tune:

        if args.tune_frac < 1.0:
            sss = StratifiedShuffleSplit(n_splits=1, test_size=2,
                                         train_size=args.tune_frac,
                                         random_state=args.rs)
            tune_indices, _ = list(sss.split(X_train, y_train))[0]
            X_train_sub, y_train_sub = X_train[tune_indices], y_train[tune_indices]
            logger.info('tune instances: {:,}'.format(X_train_sub.shape[0]))

        else:
            X_train_sub, y_train_sub = X_train, y_train
    else:
        X_train_sub, y_train_sub = X_train, y_train

    # get model
    model, param_grid = get_model(args, cat_indices=cat_indices)
    logger.info('\nmodel: {}, param_grid: {}'.format(args.model, param_grid))

    # tune the model
    start = time.time()
    if not args.no_tune:
        skf = StratifiedKFold(n_splits=args.cv, shuffle=True, random_state=args.rs)
        gs = GridSearchCV(model, param_grid, scoring=args.scoring, cv=skf, verbose=args.verbose)
        gs = gs.fit(X_train_sub, y_train_sub)

        cols = ['mean_fit_time', 'mean_test_score', 'rank_test_score']
        cols += ['param_{}'.format(param) for param in param_grid.keys()]

        df = pd.DataFrame(gs.cv_results_)
        logger.info('gridsearch results:')
        logger.info(df[cols].sort_values('rank_test_score'))

        model = clone(gs.best_estimator_)
        logger.info('best params: {}'.format(gs.best_params_))

    tune_time = time.time() - start
    logger.info('tune time: {:.3f}s'.format(tune_time))

    # train model
    start = time.time()
    model = model.fit(X_train, y_train)
    train_time = time.time() - start
    logger.info('train time: {:.3f}s'.format(train_time))

    # evaluate
    auc, acc, ap, ll = util.performance(model, X_test, y_test, logger, name=args.model)

    # save results
    result = {}
    result['model'] = args.model
    result['auc'] = auc
    result['acc'] = acc
    result['ap'] = ap
    result['ll'] = ll
    result['tune_time'] = tune_time
    result['train_time'] = train_time
    result['max_rss'] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    result['tune_frac'] = args.tune_frac
    if args.model in ['cb', 'rf']:
        result['n_estimators'] = gs.best_params_['n_estimators']
        result['max_depth'] = gs.best_params_['max_depth']
    np.save(os.path.join(out_dir, 'results.npy'), result)

    # Macs show this in bytes, unix machines show this in KB
    logger.info('max_rss: {:,}'.format(result['max_rss']))
    logger.info('total time: {:.3f}s'.format(time.time() - begin))
    logger.info('saving results to {}...'.format(os.path.join(out_dir, 'results.npy')))

def main(args):

    # define output directory
    out_dir = os.path.join(args.out_dir,
                           args.dataset,
                           args.model,
                           args.preprocessing,
                           'rs_{}'.format(args.rs))

    # create outut directory and clear any previous contents
    os.makedirs(out_dir, exist_ok=True)
    util.clear_dir(out_dir)

    # create logger
    logger = util.get_logger(os.path.join(out_dir, 'log.txt'))
    logger.info(args)
    logger.info('\ntimestamp: {}'.format(datetime.now()))

    # write everything printed to stdout to this log file
    logfile, stdout, stderr = util.stdout_stderr_to_log(os.path.join(out_dir, 'log+.txt'))

    # run experiment
    experiment(args, logger, out_dir, seed=args.rs)

    # restore original stdout and stderr settings
    util.reset_stdout_stderr(logfile, stdout, stderr)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    # I/O settings
    parser.add_argument('--dataset', type=str, default='churn', help='dataset to explain.')
    parser.add_argument('--data_dir', type=str, default='data', help='data directory.')
    parser.add_argument('--preprocessing', type=str, default='standard', help='preprocessing directory.')
    parser.add_argument('--out_dir', type=str, default='output/performance/', help='output directory.')

    # Experiment settings
    parser.add_argument('--rs', type=int, default=1, help='random state.')
    parser.add_argument('--model', type=str, default='cb', help='model to use.')
    parser.add_argument('--no_tune', action='store_true', default=False, help='do not tune the model.')
    parser.add_argument('--cv', type=int, default=5, help='number of cross-val folds.')
    parser.add_argument('--scoring', type=str, default='accuracy', help='scoring metric.')
    parser.add_argument('--tune_frac', type=float, default=1.0, help='fraction of train data to use for tuning.')

    # tree hyperparameters
    parser.add_argument('--n_estimators', type=int, default=100, help='Number of trees.')
    parser.add_argument('--max_depth', type=int, default=3, help='Maximum depth in tree ensemble.')

    # LR and SVM hyperparameters
    parser.add_argument('--penalty', type=str, default='l2', help='linear model penalty type.')
    parser.add_argument('--C', type=float, default=0.1, help='linear model penalty.')
    parser.add_argument('--kernel', type=str, default='rbf', help='linear model kernel.')

    # knn hyperparameters
    parser.add_argument('--weights', type=str, default='uniform', help='knn weights.')
    parser.add_argument('--n_neighbors', type=int, default=3, help='number of k nearest neighbors.')

    # Extra settings
    parser.add_argument('--verbose', default=2, type=int, help='verbosity level.')

    args = parser.parse_args()
    main(args)


import dis
import os
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import sys
import fastai
from fastai.vision import *
from fastai.callbacks import *
import torch.nn.functional as F
import plot
from adversarial import run_wgan
from adversarial import run_waae

def instance_bce_with_logits(logits, labels):
    assert logits.dim() == 2

    loss = nn.functional.binary_cross_entropy_with_logits(logits, labels)
    loss *= labels.size(1)
    return loss

def compute_score_with_logits(logits, **targets):
    labels,_=targets
    logits = torch.max(logits, 1)[1].data # argmax
    one_hots = torch.zeros(*labels.size()).cuda()
    one_hots.scatter_(1, logits.view(-1, 1), 1)
    scores = (one_hots * labels)
    return scores

class LossCallback(Callback):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def on_epoch_begin(self, **kwargs):
        self.loss_reconstruction, self.total = 0, 1e-8

    def on_epoch_end(self, last_metrics, **kwargs):
        return add_metrics(last_metrics, self.loss_reconstruction / self.total)

    def __call__(self, item):
        self.loss_reconstruction += item
        self.total += 1

class LossModel(LossCallback):
    def __init__(self, name="model loss"):
        super().__init__(name)

class LossReconstruction(LossCallback):
    def __init__(self, name="reconstruction loss"):
        super().__init__(name)

class LossGenerator(LossCallback):
    def __init__(self, name="generator loss"):
        super().__init__(name)

class LossDiscriminator(LossCallback):
    def __init__(self, name="discriminator loss"):
        super().__init__(name)

class GC(LearnerCallback):
    def __init__(self,learn, params, clip):
        super(GC, self).__init__(learn)
        self.params=params
        self.clip=clip

    def on_backward_end(self, **kwargs):
        nn.utils.clip_grad_norm_(self.params, self.clip)

class Precision(Callback):

    def on_epoch_begin(self, **kwargs):
        self.correct, self.total = 0, 0

    def on_batch_end(self, last_output, last_target, **kwargs):
        logits, _ = last_output
        v, a = last_target

        logits = torch.max(logits, 1)[1].data  # argmax
        one_hots = torch.zeros(*a.size()).cuda()
        one_hots.scatter_(1, logits.view(-1, 1), 1)
        scores = (one_hots * a)

        self.correct += scores.sum()
        self.total += a.size(0)

    def on_epoch_end(self, last_metrics, **kwargs):
        return add_metrics(last_metrics, self.correct / self.total)

class TotalLoss(nn.Module):
    def __init__(self, reconstruction, adv_mode, g, d, d_lr, gamma_r, gamma_a, loss_m, loss_r, loss_g, loss_d, penality,
                 critic,
                 adv):
        super().__init__()
        self.gamma_r = gamma_r
        self.gamma_a = gamma_a
        self.reconstruction = reconstruction
        self.adv = adv

        self.loss_m = loss_m
        self.loss_r = loss_r
        self.loss_g = loss_g
        self.loss_d = loss_d

        if reconstruction:
            self.G = g
            self.D = d
            self.adv_mode = adv_mode
            if adv_mode == "wgan":
                self.run_adv = run_wgan
            else:
                self.run_adv = run_waae

            self.optimizer_D = torch.optim.Adamax(self.D.parameters(), lr=d_lr, betas=(0.5, 0.999))
            self.critic = critic
            self.penality = penality

    def forward(self, input, v, a):
        logits, h = input

        loss_rec = 0
        g_loss = 0
        if self.reconstruction and self.D.training:
            #adv loss
            if self.adv:
                g_loss, d_loss, g_rec, v = self.run_adv(self.G, self.D, self.optimizer_D, self.penality, self.critic, h,
                                                        v)
                self.loss_g(g_loss.data)
                if d_loss:
                    self.loss_d(d_loss.data)
            else:
                v = v.permute(0, 2, 1).view(h.size(0), -1, 6, 6)
                g_rec = self.G(h)

            #rec loss
            if self.adv_mode == "waae":
                loss_rec = F.mse_loss(g_rec, v)
                self.loss_r(loss_rec.data)

        #model loss
        loss_model = instance_bce_with_logits(logits, a)
        self.loss_m(loss_model.data)
        return loss_model + self.gamma_r * loss_rec + self.gamma_a * g_loss

class SaveModel(LearnerCallback):
    def __init__(self, learn, output):
        super(SaveModel, self).__init__(learn)
        self.best_accuracy_score = 0.0
        self.output = output
        self.model = learn

    def on_epoch_end(self, last_metrics, **kwargs):
        #last_metrics = val_loss, metric1, metric2,...
        accuracy_score = last_metrics[1]
        if accuracy_score > self.best_accuracy_score:
            old = os.path.join(self.output, 'model_%.4f.pth' % float(self.best_accuracy_score))
            if os.path.exists(old):
                os.remove(old)
            ret = self.model.save('model_%.4f' % float(accuracy_score), return_path=True)
            self.best_accuracy_score = accuracy_score

    def on_train_end(self,**kwargs):
        for p in ["plot_lr","plot_losses","plot_metrics"]:
            f = getattr(plot,p)
            fig, ax = f(self.learn.recorder)
            out = os.path.join(self.output,p)
            pickle.dump(ax, open(out, 'wb+'))
            fig.savefig(out)

        with open("all_scores.txt", "a+") as f:
            f.write('%s-%.4f \n'%(self.output,self.best_accuracy_score))

def train(model, train_loader, eval_loader, num_epochs, batch_size, output, reconstruction, lr,
          gamma_r,
          gamma_a,
          size,
          early_stop,
          dropout_hid,
          adv_mode,
          penality,
          critic,
          adv,
          ckpt,
          logger):

    logger.write("batch_size %s, "
                 "reconstruction %s, "
                 "gamma_r %s, "
                 "gamma_a %s, "
                 "size %s, "
                 "dropout_hid %s, "
                 "adv_mode %s, "
                 "penality %s, "
                 "critic %s, "
                 "ad %s, "
                 % (str(batch_size), reconstruction, str(gamma_r), str(gamma_a), str(size), str(dropout_hid),
                    adv_mode,
                    str(penality),
                    str(critic),
                    str(adv),
                    ))

    generator, discriminator = None, None,
    #define main model
    model_group = [model.w_emb,
                model.q_emb,
                model.v_att,
                model.q_net,
                model.v_net,
                model.classifier]
    generator_group = []
    if reconstruction:
        #define adversarial, include generator on main model
        discriminator = model.D
        generator = model.G
        generator_group = [model.G]

    #Loss
    lmod = LossModel()
    lrec = LossReconstruction()
    ladvg = LossGenerator()
    ladvd = LossDiscriminator()
    total_loss = TotalLoss(reconstruction, adv_mode, generator, discriminator, lr/10, gamma_r, gamma_a,
                           lmod,
                           lrec,
                           ladvg,
                           ladvd,
                           penality,
                           critic,
                           adv,
                           )

    #Learner
    learn = Learner(DataBunch(train_dl=train_loader,
                              valid_dl=eval_loader),
                    model=model,
                    wd=0.0,
                    metrics=[Precision(), lmod, lrec, ladvg, ladvd],
                    loss_func=total_loss,
                    model_dir=output,
                    opt_func=torch.optim.Adamax,
                    layer_groups=model_group+generator_group)

    if ckpt is not None:
        print("Loading", str(ckpt))
        learn.load(ckpt)

    #Callback
    p_gc = []
    for m in model_group:
        p_gc += list(m.parameters())
    gp = GC(learn, p_gc, 0.25)
    sm = SaveModel(learn, output=output)
    es = EarlyStoppingCallback(learn=learn, monitor='precision', min_delta=0.0001, patience=early_stop)

    print("LR is",lr)

    #Go
    learn.fit(num_epochs, lr, callbacks=[gp,sm,es])

def evaluate(model, eval_loader, output, ckpt):
    lmod = LossModel()
    lrec = LossReconstruction()
    ladvg = LossGenerator()
    ladvd = LossDiscriminator()
    total_loss = TotalLoss(True, False, model.G, model.D, 10/10, 0, 0.,
                           lmod,
                           lrec,
                           ladvg,
                           ladvd,
                           0.,
                           0.,
                           0.,
                           )

    learn = Learner(DataBunch(train_dl=eval_loader,
                              valid_dl=eval_loader),
                    model=model,
                    wd=0.0,
                    metrics=[Precision(), lmod, lrec],
                    loss_func=total_loss,
                    model_dir=output,
                    )
    learn.load(ckpt)

    print(learn.validate()[1])


import math
g,y0 = 9.81,0
def trajectory(xdata,speed,angle):
	lis = list(())
	angle = math.radians(angle)
	fx = 0
	for x in xdata:
		fx = x*math.tan(angle) - (1/(2*speed**2))*(g*x**2)/(math.cos(angle))**2 + y0
		if fx >= 0:
			lis.append(fx)
	return lis


# lavadoras/urls.py
from django.urls import path
from .views import LavadoraListView, LavadoraCreateView, LavadoraUpdateView, LavadoraDeleteView

urlpatterns = [
    path('', LavadoraListView.as_view(), name='lavadoras-list'),
    path('crear/', LavadoraCreateView.as_view(), name='lavadora-create'),
    path('editar/<int:pk>/', LavadoraUpdateView.as_view(), name='lavadora-update'),
    path('eliminar/<int:pk>/', LavadoraDeleteView.as_view(), name='lavadora-delete'),
]


from flask import Flask, render_template, request,redirect,url_for,session
import random
from utils.learning import *
import json
import requests

app = Flask(__name__)
app.secret_key = 'password'
IMDB_KEY = "3df29fd2"
BASEURL = "http://www.omdbapi.com/?i=tt"
movie_list = []

def get_request_url(movid):
	return BASEURL + movid + "&apikey=" + IMDB_KEY

def decode_movie_json(url):
	response = requests.get(url)
	response = response.json()
	return dict(response)

def random_ten():
	sample = random.sample(list(movies.keys()), 12)
	l = [(i, links[i][imdb_id]) for i in sample]
	return l

def get_movie_data(movies):
	movie_data = []
	for movie in movies:
		imdb = movie[1]
		url = get_request_url(imdb)
		movie_data.append(decode_movie_json(url))
	return movie_data

def get_ratings(feedback):
	rated_feedback = []
	total = 0
	for i in range(0, len(feedback)):
		if((i % 5) == 0 and (i > 0)):
			rated_feedback.append(total)
			total = 0
		if(feedback[i] == "true"):
			total+=1
	rated_feedback.append(total)
	return rated_feedback

def rated_feedback_to_user(feedback):
	user = []
	for i in range(0, len(feedback)):
		dic = {}
		dic[rating] = feedback[i]
		dic[movie_id] = movie_list[i][0]
		user.append(dic)
	return user

@app.route("/", methods = ['GET', 'POST'])
def mainpage():
	global movie_list
	movie_list=random_ten()
	movie_data=get_movie_data(movie_list)
	return render_template("index.html", movies=movie_data)

@app.route("/suggestions", methods = ['GET', 'POST'])
def suggest():
	feedback = request.args.get('feedback')
	feedback = feedback.split(",")
	feedback = get_ratings(feedback)
	user = rated_feedback_to_user(feedback)
	user_id = add_user(user)
	movie_recs = get_movie_recs(predict(user_id,k=10))
	already_shown = [i[0] for i in movie_list]
	movie_recs = [i for i in movie_recs if not i in already_shown]
	movie_recs = movie_recs[:12]
	movie_recs = [(i, links[i][imdb_id]) for i in movie_recs]
	movie_recs = get_movie_data(movie_recs)
	return render_template("recs.html", movies=movie_recs)

@app.route("/test", methods = ['GET', 'POST'])
def test():
	return render_template("test.html")

if __name__=="__main__":
    app.run("localhost", 5000, debug = True)


import pandas as pd
import numpy as np
from urllib import urlretrieve

### retrieve and store data from urls
es_url = 'http://www.stoxx.com/download/historical_values/hbrbcpe.txt'
vs_url = 'http://www.stoxx.com/download/historical_values/h_vstoxx.txt'

cols = ['SX5P', 'SX5E','SXXP','SXXE','SXXF','SXXA','DK5F','DKXF']

es = pd.read_csv(es_url, index_col=0,parse_dates=True,sep=':', dayfirst=True,header=None,skiprows=4,names=cols)

es.tail()

vs = pd.read_csv('./data/vs.txt', index_col=0,header=2,parse_dates=True,sep=',',dayfirst=True)

vs.info()


# Given an input array of integers and a specific target, return two indices that add up to the target
class soln:
    def twoSum(self, nums: list[int], target: int):
        prevMap = {}  # val:index #HashMap
        for i, n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
                return [prevMap[diff], i]
            prevMap[n] = i  # Pass in the current value and the key
        return

    # Recall
    # Given an input array and a target, return a list of indices of two numbers that add up to the target
    class Soln2:
        def twoSum(self, nums: list[int], target: int) -> list[int]:
            map = {} #value : index
            for index, value in enumerate(nums):  # Iterate through the list and get the index and the value
                difference = target - value
                if difference in map:
                    return [map.get(difference,0),index]
                else:
                    map[value] = index
            return []

#Given an integer array  nums and a target k
#Return indices of two numbers that add up to k
class SolutionTwoS:
    def twoSum(self,nums:list[int],k:int)->list[int]:
        prevMap = {}#val -> index
        for i,n in enumerate(nums):
            diff = k - n
            if diff in prevMap:
                return  [prevMap[diff], i]
            prevMap[n] = i

    def twoSum2(self,nums:list[int],k:int):
        hashMap = {}
        for key,value in enumerate(nums):
            diff = k - value
            if diff in hashMap:
                return  [hashMap[diff],key]
            hashMap[value] = key

class SolutionTwoSu:
    def twoSum(self,nums:list[int],target:int):
        prevMap = {}
        for index,value in enumerate(nums):
            #Get th
            difference = target - value
            if difference in prevMap:
                return  [prevMap[difference],value]
            prevMap[value] = index

class SolutionTwoSum:
    def twoSum(self,nums:list[int],target:int)->list[int]:
        prevMap = {}
        for i,n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
                return  [prevMap[diff], i]
            prevMap[n] = i

class twoSum:
    def twoSum(self,nums:list[int],target:int):
        prevMap = {}
        for i,n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
                return  [prevMap[diff],i]
            prevMap[n] = i

class last:
    def twoSum(self,nums:list[int],target:int):
        prevMap = {}#value and index
        for i,n in enumerate(nums):
            diff = target - n
            if n in prevMap:
                return  [prevMap[diff],i]
            prevMap[n] = i


import os.path

from CropModels import *
from CropDataset import Apple_leaf_dataset, normalize_torch, normalize_05, normalize_dataset, preprocess, \
    preprocess_hflip, \
    preprocess_with_augmentation
import pandas as pd
import torch.nn as nn
from tensorboardX import SummaryWriter
import torch
from torch.cuda.amp import autocast
from torch.autograd import Variable
from torch.cuda.amp import GradScaler

import datetime
from utils import RunningMean, split_dataset_pytorch
import utils
from tqdm import tqdm

random_seed = 42
torch.manual_seed(random_seed)
scaler = GradScaler()

torch.backends.cudnn.benchmark = True

model_dict = {
    'resnet18': resnet18_finetune,
    'resnet34': resnet34_finetune,
    'resnet50': resnet50_finetune,
    'resnet101': resnet101_finetune,
    'resnet152': resnet152_finetune,
    'densenet121': densenet121_finetune,
    'densenet161': densenet161_finetune,
    'densenet201': densenet201_finetune,
    'xception': xception_finetune,
    'inceotionv4': inceptionv4_finetune,
    'inceptionv2': inceptionresnetv2_finetune,
    'nasnet': nasnet_finetune,
    'nasnetmobile': nasnetmobile,
    'mobilenet': mobilenetv3_finetune,
    'googlenet': googlenetv2_finetune,
    'shufflenet': shufflenetv2_finetune
}

def train(epochNum, model_name='resnet18'):
    # 初始化tensorboad
    date = str(datetime.date.today())
    # 创建 /log/日期/InceptionResnet的组织形式  不同模型需要修改不同名称
    writer = SummaryWriter('./log/' + date + '/' + model_name + '/')
    #
    NB_CLASS = 5
    BATCH_SIZE = 128
    IMAGE_SIZE = 224  # 不同模型修改不同的Size
    IMAGE_ROOT = './apple_leaf_disease'
    validation_split = .2

    dataset = Apple_leaf_dataset(img_root=IMAGE_ROOT, transform=preprocess(normalize=normalize_torch,
                                                                           image_size=IMAGE_SIZE))

    train_dataloader, val_dataloader = split_dataset_pytorch(dataset, batch_size=BATCH_SIZE, validation_split=validation_split, random_seed=random_seed)

    model = model_dict[model_name](num_classes=NB_CLASS).cuda()

    criterion = nn.CrossEntropyLoss().cuda()
    lx, px = utils.predict(model, val_dataloader)
    min_loss = criterion(px, lx).item()
    print('min_loss is :%f' % (min_loss))
    min_acc = 0.80
    patience = 0
    # momentum = 0.0
    lr = 1e-4
    optimizer_warming = torch.optim.Adam(model.fresh_params(), lr=lr, amsgrad=True, weight_decay=1e-4)
    optimizer_training = torch.optim.Adam(model.parameters(), lr=lr)
    scheduler_warming = torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer_training, milestones=[20, 30, 40], gamma=0.1)
    for epoch in range(epochNum):
        print('Epoch {}/{}'.format(epoch, epochNum - 1))
        print('-' * 10)

        if patience == 2:
            patience = 0
            model.load_state_dict(torch.load('save_model/' + model_name + "/loss_best/" + date + '_loss_best.pth')['state_dict'])
            lr = lr / 10
            print('loss has increased lr divide 10 lr now is :%f' % (lr))
        if epoch < 10:  # 第一轮首先训练全连接层
            optimizer = optimizer_warming
            scheduler = None
        else:
            optimizer = optimizer_training
            scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer, milestones=[17, 27, 27], gamma=0.1)

        running_loss = RunningMean()
        running_corrects = RunningMean()

        train_bar = tqdm(train_dataloader)
        train_bar.desc = "train_step"
        for batch_idx, (inputs, labels) in enumerate(train_bar):
            model.train(True)
            optimizer.zero_grad()
            with autocast():
                n_batchsize = inputs.size(0)
                inputs = Variable(inputs).cuda()
                labels = Variable(labels).cuda()
                outputs = model(inputs)
                _, preds = torch.max(outputs.data, 1)
                if isinstance(outputs, tuple):
                    loss = sum((criterion(o, labels)) for o in outputs)
                else:
                    loss = criterion(outputs, labels)
            running_loss.update(loss.item(), 1)
            running_corrects.update(torch.sum(preds == labels.data).data, n_batchsize)
            # 梯度放大
            scaler.scale(loss).backward()
            scaler.step(optimizer)
            scaler.update()
            if scheduler is not None:
                scheduler.step()

        #
        # val
        #
        lx, px = utils.predict(model, val_dataloader)
        log_loss = criterion(Variable(px), Variable(lx))
        log_loss = log_loss.item()
        _, preds = torch.max(px, dim=1)
        accuracy = torch.mean((preds == lx).float())
        writer.add_scalar('Val/Acc', accuracy, int((epoch + 1) * len(train_dataloader)))
        writer.add_scalar('Val/Loss', log_loss, int((epoch + 1) * len(train_dataloader)))
        print('[epoch:%d]: val_loss:%f,val_acc:%f,' % (epoch, log_loss, accuracy))

        #
        # save model
        #
        if log_loss < min_loss:
            if not os.path.isdir('./save_model/' + model_name + '/loss_best'):
                os.makedirs('./save_model/' + model_name + '/loss_best')
            torch.save({
                'epoch': epoch + 1,
                'state_dict': model.state_dict(),
                'optimizer': optimizer.state_dict(),
                'val_loss': log_loss,
                'val_correct': accuracy}, 'save_model/' + model_name + '/loss_best/' + date + '_loss_best.pth')
            patience = 0
            min_loss = log_loss
            print('save new model loss,now loss is ', min_loss)
        else:
            patience += 1
        if accuracy > min_acc:
            if not os.path.isdir('./save_model/' + model_name + '/acc_best'):
                os.makedirs('./save_model/' + model_name + '/acc_best')
            torch.save({'epoch': epoch + 1,
                        'state_dict': model.state_dict(),
                        'optimizer': optimizer.state_dict(),
                        'val_loss': log_loss,
                        'val_correct': accuracy}, 'save_model/' + model_name + '/acc_best/' + date + '_acc_best.pth')
            min_acc = accuracy
            print('save new model acc,now acc is ', min_acc)

if __name__ == '__main__':
    # model_list = ['resnet34', 'resnet50', 'resnet101', 'resnet152', 'densenet121', 'densenet161', 'densenet201',
    #               'xception', 'inceotionv4', 'inceptionv2', 'nasnet', 'nasnetmobile', 'mobilenet', 'googlenet',
    #               'shufflenet']
    # for model_name in model_list:
    #     train(100, model_name)
    train(100, "googlenet")


def mochila (casos, nMaxDinero):
    # Calculo de beneficio / gasto
    for i in range(len(casos)):
        casos[i].append(casos[i][2] / casos[i][1])
    # Ordeno array por el calculo anterior
    casos.sort(key=elem3, reverse=True)
    sol = [0] * len(casos)
    costeAcum = 0
    benAcum = 0
    i = 0
    while costeAcum < nMaxDinero:
        if costeAcum + casos[i][1] <= nMaxDinero:
            costeAcum += casos[i][1]
            benAcum += casos[i][2]
            sol[casos[i][0]] = 1
            i += 1
        else:
            sol[casos[i][0]] = (nMaxDinero - costeAcum) / casos[i][1]
            benAcum += (casos[i][2] * sol[casos[i][0]]).__round__()
            costeAcum = nMaxDinero

    return [sol, benAcum]

def elem3(casos):
    return casos[3]

entrada1 = input().split()
nCasos = int(entrada1[0])
nMaxDinero = int(entrada1[1])
casos = []
for i in range(nCasos):
    entr = input().split()
    casos.append([i, int(entr[0]), int(entr[1])])

[sol, ben] = mochila(casos, nMaxDinero)
for i in range(nCasos):
    if sol[i] != 0:
        print(i, "", end="")

print()
print(ben)


class CampCleanup:

    def __init__(self, assignment_pairs_filename: str):
        with open(assignment_pairs_filename, 'r') as f:
            assignment_pairs = f.read().splitlines()
        self._pairs_list = [[list(map(int, pair.split('-'))) for pair in two_pair.split(',')]
                            for two_pair in assignment_pairs]

    def count_full_containment(self) -> int:
        return [self._have_fully_contained(*two_pair) for two_pair in self._pairs_list].count(True)

    def count_partial_containment(self) -> int:
        return [self._have_partial_containment(*two_pair) for two_pair in self._pairs_list].count(True)

    @staticmethod
    def _have_fully_contained(range_1: [int, int], range_2: [int, int]) -> bool:
        sorted_ranges = sorted([range_1, range_2], key=lambda x: x[0])
        if sorted_ranges[0][0] == sorted_ranges[1][0] or sorted_ranges[0][1] >= sorted_ranges[1][1]:
            return True
        else:
            return False

    @staticmethod
    def _have_partial_containment(range_1: [int, int], range_2: [int, int]) -> bool:
        sorted_ranges = sorted([range_1, range_2], key=lambda x: x[0])
        return True if sorted_ranges[0][1] >= sorted_ranges[1][0] else False

if __name__ == '__main__':
    camp_cleanup = CampCleanup('assignment_pairs.txt')
    print(f'Sum of pairs that have full containment: {camp_cleanup.count_full_containment()}')
    print(f'Sum of pairs that have partial containment: {camp_cleanup.count_partial_containment()}')


import sys
sys.stdin = open('bj1912.txt','r')

N=int(input())
L=[int(x)for x in input().split()]
DP=[0]*N
DP[0]=L[0]
R=-10**9
for i in range(1,N):
    DP[i]=max(DP[i-1]+L[i],L[i])
    R=max(R,DP[i])
print(max(R,DP[0]))


# Linear search using recusion

def linersearch(arr, index, target):
    if index == len(arr) - 1:
        return False
    return arr[index] == target or linersearch(arr, index+1, target)

arr = [2,3,5,7,3]
# print(linersearch(arr, 0, 5))

def findIndex(arr, target, index):
    if index >= len(arr) - 1:
        return False
    if arr[index] == target:
        return index
    return findIndex(arr, target, index+1)

arr = [2,3,5,7,3]
# print(findIndex(arr, 0, 5))

# Find index of all the occurrences
ans = []
def findAllIndex(arr, target, index):
    if index >= len(arr) - 1:
        return False
    if arr[index] == target:
        ans.append(index)
    return findAllIndex(arr, target, index + 1)

# arr = [1,2,3,4,5,4,2]
# print(findAllIndex(arr, 7, 0))
# print(ans)

def findAllIndex1(arr, target, index):
    ans = []
    if index == len(arr):
        return ans
    if arr[index] == target:
        ans.append(index)
    ans += findAllIndex1(arr, target, index + 1)
    return ans

arr = [1,2,3,4,5,4,2]
print(findAllIndex1(arr, 4, 0))


import sys
input=sys.stdin.readline

#top down 형식으로 맨 위부터 노드를 하나씩 만들어줘서 leaf까지 도달하자
#재귀적 특징으로 나아감
#이진탐색트리의 특징을 생각한다면 이는 필연적/당연적임
def init(node, start, end):
    if start==end:
        tree[node]=leaf[start]
        return tree[node]
    else:
        tree[node]=init(node*2,start, (start+end)//2 )+ init(node*2+1, (start+end)//2+1, end)
        return tree[node]
#[start, end]는 지금 node가 어디를 포함하는 건지
#[left, right]는 우리가 목표하는 곳.!
def subSum(node, start, end, left, right):
    if left > end or right < start: return 0 #말도 안되는 것이 입력으로 들어옴
    if left <= start and end <= right: return tree[node] #and인 거 잘 보자. 우리가 딱 구하고자 하는 것임!
    return subSum(node*2, start, (start+end)//2, left, right) + subSum(node*2+1, (start+end)//2+1, end,left, right)

def update(node, start, end, index, diff):
    if index < start or index > end: #해당 노드를 따라 밑으로 한 칸 내려갔을 때 해당하는 쪽이 아닐 경우
        return
    tree[node]+=diff
    if start != end:
        #이제 자식 노드들도 diff만큼 더해주기 위해서 재귀적호출을 해주는 부ㅜㅂㄴ
        update(node*2, start, (start+end)//2, index, diff)
        update(node*2+1, (start+end)//2+1, end, index, diff)

n,m,k=map(int,input().split())
leaf=[]
tree=[0]*3000000

for _ in range(n):leaf.append(int(input().rstrip()))

init(1,0,n-1) #노드 맨위를 1로 해서 만들어 나가기!!

for _ in range(m+k):
    a,b,c=map(int,input().rstrip().split())
    if a==1:
        b=b-1
        diff=c-leaf[b] # 6-3=3 바꾸려는 것의 차이를 구한다.
        leaf[b]=c #그 leaf노드를 바꿔준다.
        update(1,0,n-1,b,diff)
    elif a==2:
        print(subSum(1,0,n-1,b-1,c-1))


from logging import exception
from time import time
import pyautogui
import cv2
import numpy as np
import timeit
import mss
import prueba
from PIL import Image

cv2.namedWindow("Live", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Live", 1024, 1024)
monitor = {'top': 40, 'left': 0, 'width': 1024, 'height': 1024}
mss1 = mss.mss()
m1=prueba.SCNN()

def getWindow():
    data = np.array([])
    while True:
        t1 = timeit.default_timer()
        #frame = pyautogui.screenshot(region=(0, 0, 300, 400))
        frame = mss1.grab(monitor)
        input = np.array(frame)
        frame = Image.fromarray(input).convert('RGB').resize((512,512))
        t2 = timeit.default_timer()
        out = m1.segment(frame)
        t3 = timeit.default_timer()
        out = np.array(out.convert('RGB'))
        try:
            cv2.imshow('Live',out)
        except:
            pass
        t4 = timeit.default_timer()
        if int(t2) - int(t1) == 1:
            data = np.append(data, 1/(t3-t1))
            print('time(ms): ', t2-t1,t3-t2,t4-t3,t4-t1, '\nfps: ', 1/(t3-t1), '\nmean: ', np.mean(data))
        # Stop recording when we press 'q'
        if cv2.waitKey(1) == ord('q'):
            break

# Destroy all windows
if __name__ == '__main__':
    getWindow()
    cv2.destroyAllWindows()


import numpy as np
import jax
import jax.numpy as jnp
from functools import partial

from free_hamiltonian import H_free
from logpsi import log_psi
from metropolis import random_init, make_E, make_QGT, make_QGT_ED, make_loss
from sampler import Gaussian_fn

def optimize_sigma():
    batch = 1000
    t = 1.
    U = 6.
    Lsite = 2
    N = int(Lsite/2)
    hfree = H_free(Lsite, N, t)
    psi = hfree.get_psi0()

    states_init = random_init(batch, Lsite)

    batch_g = 200
    nthermal = 100
    beta = 2.5

    opt_nstep = 500
    learning_rate = 1e-2

    mu = 0.3

    make_psi_ratio, make_logpsi, grad_g_logpsi = log_psi(psi, Lsite, N)
    #states = sample_states(make_psi_ratio, g, states_init, nthermal)

    import optax

    optimizer = optax.adam(learning_rate = learning_rate)
    param = jax.random.uniform( key = jax.random.PRNGKey(42), minval = 0.001, maxval = 1. )
    opt_state = optimizer.init(param)

    key = jax.random.PRNGKey(42)

    def step(param, opt_state, key):
        loss_fn = make_loss(beta, psi, Lsite, N, t, U, nthermal, log_psi, Gaussian_fn, batch_g, mu, key)

        grad, loss, E_mean = loss_fn(states_init, param)
        updates, opt_state = optimizer.update(grad, opt_state, param)
        param = optax.apply_updates(param, updates)
        return param, opt_state, grad, loss, E_mean

    for i in range(opt_nstep):
        key_old, key = jax.random.split(key, 2)

        param, opt_state, grad, loss, E_mean = step(param, opt_state, key)
        print('istep, sigma, grad, loss, E_mean:')
        print(i, param, grad, loss, E_mean)
        print('\n')

# run =============================================================

optimize_sigma()


from django.views.generic import  DetailView
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.utils import timezone

from champsquarebackend.core.loading import get_model, get_class

AnswerPaper = get_model('quiz', 'AnswerPaper')
VideoRecord = get_model('monitoring', 'VideoRecord')

class SaveVideoRecordView(DetailView):
    """
        save video record details
    """
    def get(self, request, *args, **kwargs):
        answer_paper_id = request.GET.get('paper_id', None)
        video_record_type = request.GET.get('video_record_type', None)
        record_id = request.GET.get('record_id', None)
        answer_paper = AnswerPaper.objects.get(id=answer_paper_id)
        name = answer_paper.participant.user.email
        file_name = VideoRecord.create_mjr_video_file_name(record_id, video_record_type)

        video_record = VideoRecord(answerpaper=answer_paper, name=name,
                                   type=video_record_type,
                                   record_id=record_id, file_name=file_name)
        video_record.save()
        video_record.create_record_file()
        if video_record_type == 'webcam':
            answer_paper.set_status('webcam_permssion_granted')
        elif video_record_type == 'screen':
            answer_paper.set_status('screen_sharing_permission_granted')
        date = {
            'success': True
        }
        return JsonResponse(date)


import os
from app import app
from flask import Flask, render_template, request, url_for, redirect, send_from_directory
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = os.path.join(app.root_path, 'image')
ALLOWED_EXTENSIONS = set(['pdf','png','jpg','jpeg','gif'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'picture' not in request.files:
            flash('No file')
            return redirect(request.url)

        file = request.files['picture']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))

    return render_template('index.html')

@app.route('/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


import jieba
import re

#去除描述信息中无用的被告，原告，姓名和日期等信息

jieba.setLogLevel('WARN')

class normalizer:
    def __init__(self, stopword_filepath):
        '''
        :param stopword_filepath: 停用词表路径
        :return:
        '''
        self.raw_json_list = []
        self.cut_list = []

        self.data_out = None
        self.stopword_filepath = stopword_filepath

        self.time_sub_pattern = [
                        r'([\d一二三四五六七八九十零]+年|[\d一二三四五六七八九十]+月|周+[\d一二三四五六日末]|[\d一二三四五六七八九十零]+(日|号)|[\d一二三四五六七八九十零]+时|\d+分)+',
        ]
        self.time_sub_replacer = [
            '',
        ]

        self.person_sub_pattern = [
            r'被告人(.)某',
            r'原告(.)称',
            r'证人(.)某',
            r'(.)某',
        ]
        self.person_sub_replacer = [
            '',
            '',
            '',
            '',
        ]

        self.money_sub_pattern = [
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右)*十(余|多|几)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右|几)*百(余|多)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右|几)*千(余|多)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右|几)*万(余|多)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右)*十(余|多)*万(余|多)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右)*百(余|多)*万(余|多)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(余|多|左右)*千(余|多)*万(余|多)*元(人民币)*',
            r'(人民币)*[几一二两三四五六七八九]*(\d+(\.)?\d*)*(十|百|千)*(余|多|左右)*亿(余|多)*元(人民币)*',
        ]
        self.money_sub_replacer = [
            'm1', #<1000
            'm1',
            'm1',
            'm2',  #<10000
            'm3',  #<100000
            'm4',  #<1000000
            'm5',  #<10000000
            'm6',
            'm7',
        ]

        # self.penalty_sub_pattern = [
        #
        # ]
        # self.penalty_sub_replacer = [
        #
        # ]

        self.stopwordlist = self.read_data_to_list(self.stopword_filepath)

    def read_data_to_list(self, filepath):
        rslt_list = []

        with open(filepath, 'r', encoding='utf8') as fin:
            line = fin.readline()
            while line:
                line = line.strip()
                if line != "":
                    rslt_list.append(line)
                line = fin.readline()

        return rslt_list

    def seg_one_text(self, one_text, filterd_word_len):
        rslt_list = []
        text = one_text
        text = text.replace("\r", "")
        text = text.replace("\n", "")
        for i in range(len(self.time_sub_pattern)):
            text = re.sub(self.time_sub_pattern[i], self.time_sub_replacer[i], text)
        for j in range(len(self.person_sub_pattern)):
            text = re.sub(self.person_sub_pattern[j], self.person_sub_replacer[j], text)
        for k in range(len(self.money_sub_pattern)):
            text = re.sub(self.money_sub_pattern[k], self.money_sub_replacer[k], text)

        tmp_cut_list = [word for word in jieba.lcut(text) if len(word) >= filterd_word_len]
        ###test
        # print(tmp_cut_list)
        for word in tmp_cut_list:

            if word in self.stopwordlist:
                continue
            if re.match(r'^\d+(\.)?\d*$', word) is not None:
                number = float(word)
                if (number < 1000 and number >= 0):
                    rslt_list.append('m1')
                elif (number < 10000 and number >= 1000):
                    rslt_list.append('m2')
                elif (number < 100000 and number >= 10000):
                    rslt_list.append('m3')
                elif (number < 1000000 and number >= 100000):
                    rslt_list.append('m4')
                elif (number < 10000000 and number >= 1000000):
                    rslt_list.append('m5')
                elif (number < 100000000):
                    rslt_list.append('m6')
                elif (number >= 100000000):
                    rslt_list.append('m7')
                continue

            # re.match(r'^(.*?)(县|市|乡|镇|州|村|区|省)$', word)
            elif (re.match(r'^(.*?)(县)$', word) is not None):
                # rslt_list.append('县')
                continue
            elif (re.match(r'^(.*?)(市)$', word) is not None):
                # rslt_list.append('市')
                continue
            elif (re.match(r'^(.*?)(乡)$', word) is not None):
                # rslt_list.append('乡')
                continue
            elif (re.match(r'^(.*?)(镇)$', word) is not None):
                # rslt_list.append('镇')
                continue
            elif (re.match(r'^(.*?)(州)$', word) is not None):
                # rslt_list.append('州')
                continue
            elif (re.match(r'^(.*?)(村)$', word) is not None):
                # rslt_list.append('村')
                continue
            elif (re.match(r'^(.*?)(区)$', word) is not None):
                # rslt_list.append('区')
                continue
            elif (re.match(r'^(.*?)(省)$', word) is not None):
                # rslt_list.append('省')
                continue
            if word != '':
                rslt_list.append(word)
        return rslt_list


#!/usr/bin/env python
import octomap
import numpy as np
import scipy
import cc3d
from plot import *
from pytransform3d.plot_utils import plot_sphere, plot_box
from polytope import *
from transform import *

def cluster_indices(assignment):
    indices = []

    for i, j in enumerate(assignment):
        while True:
            try:
                indices[j - 1].append(i)
                break
            except:
                indices += [[]]
    return indices

class Objects:
    """Class that manages the occupied voxels as which the objects to be grasped are represented"""

    def __init__(self, space, *args, **kwargs):
        """Initialize with space containing points and map or points"""
        self.space = space

        if args and type(args[0]) == str:
            self.set_map(*args, **kwargs)

        else:
            self.set_points(*args, **kwargs)

    def set_map(self, name="map", limit=None):
        """Obtain occupied voxel coordinates from map file"""
        path = map_file(name)
        objects = octomap.OcTree(1)
        objects.readBinary(bytearray(path, "utf-8"))
        resolution = objects.getResolution()
        points = []

        for leaf in objects.begin_leafs_bbx(*self.space.get_bounds()):
            if limit is not None and len(points) >= limit:
                break

            if objects.isNodeOccupied(leaf):
                point = [leaf.getX(), leaf.getY(), leaf.getZ()]
                # point = [list(leaf.getCoordinate())]

                if type(self.space) is Rectangle or self.space.inside(point):
                    points.append(point)

        self.set_points(points, resolution)

    def set_points(self, points=[], resolution=0.01):
        """Set occupied voxel coordinates"""
        self.points = np.array(points)
        self.n_p = len(self.points)
        if self.n_p:
            print("Number of points:", self.n_p)

        # Diameter of voxel
        self.d_v = resolution
        self.cluster(False)

    def center(self, type=0, tight=False):
        """Points in source frame or centered by substracting their mean"""
        if type and self.n_p:
            if type == 1:
                self.points_mean = self.space.get_center()

            else:
                self.points_mean = np.mean(self.points, axis=0)

            self.points_centered = self.points - self.points_mean
            self.radius = self.space.radius

        else:
            self.points_mean = np.zeros(3)
            self.points_centered = self.points
            self.radius = self.space.dmax

        if tight and self.n_p:
            # Distance of farthest points to origin
            self.radius = np.max(np.linalg.norm(self.points_centered, axis=1))

        self.T = Transform(t=self.points_mean)

        return self.points_centered

    def get_pdist(self):
        if not hasattr(self, "pdist") or self.pdist is None:
            self.pdist = scipy.spatial.distance.pdist(self.points_centered)

        return self.pdist

    def distances(self, tight):
        if self.n_p:
            if tight:
                # Distances between each point and other points
                self.d_pp = scipy.spatial.distance.squareform(self.get_pdist())

                # Greatest distance between each point and other points
                self.d_ppmax = np.max(self.d_pp, axis=0)

                # Greatest distance between two points
                self.d_pmax = np.max(self.d_ppmax)

            else:
                self.d_pmax = self.space.diameter
                self.d_ppmax = np.repeat(self.d_pmax, self.n_p)

    def cluster(self, type=2):
        """Cluster the points into objects"""
        if type == 1:
            self.flat()

        elif type == 2:
            self.connected()

        else:
            self.objects = [list(range(self.n_p))]

        self.n_P = len(self.objects)
        self.n_Pp = [len(object) for object in self.objects]
        self.n_Ppmax = max(self.n_Pp + [0])

        if self.n_p and type:
            print("Points per object:", self.n_Pp)

    def flat(self, s=3):
        linkage = scipy.cluster.hierarchy.linkage(self.get_pdist())
        fcluster = scipy.cluster.hierarchy.fcluster(
            linkage, s * np.sqrt(3) * self.d_v, "distance"
        )
        self.objects = cluster_indices(fcluster)

    def connected(self):
        voxel = np.floor_divide(self.points, self.d_v).astype(int)
        voxel -= voxel.min(axis=0)
        grid = np.full((voxel.max(axis=0) + 1), None)

        for i, v in enumerate(voxel):
            grid[tuple(v)] = i

        labels, self.n_P = cc3d.connected_components(grid != None, return_N=True)
        self.objects = [[] for _ in range(self.n_P)]

        for i, v in enumerate(voxel):
            self.objects[labels[tuple(v)] - 1].append(i)

    def plot_space(self, *args, **kwargs):
        self.space.plot(*args, **kwargs)

    def plot_frame(self, *args, **kwargs):
        self.T.plot(*args, **kwargs, dir=1)

    def plot(self, ax=None, T=None, marker=0):
        if self.n_p:
            show = not ax

            if show:
                ax = Plot.init(self)

            points = self.points

            if T is not None:
                points = T.transform(points)

            for object in self.objects:
                object_points = points[object]

                ax.scatter(*object_points.T)

                if marker == 1:
                    self.cubes(ax, object_points, self.d_v)

                elif marker == 2:
                    self.spheres(ax, object_points, self.d_v)

            if show:
                plt.show()

    def spheres(self, ax, positions, diameter, color="blue"):
        for position in positions:
            plot_sphere(
                ax=ax,
                radius=diameter / 2,
                p=position,
                ax_s=1,
                wireframe=False,
                n_steps=20,
                alpha=1.0,
                color=color,
            )

    def cubes(self, positions, l, color="blue"):
        e = (
            np.array(
                [
                    [[0, l, 0], [0, 0, 0], [l, 0, 0], [l, l, 0]],
                    [[0, 0, 0], [0, 0, l], [l, 0, l], [l, 0, 0]],
                    [[l, 0, l], [l, 0, 0], [l, l, 0], [l, l, l]],
                    [[0, 0, l], [0, 0, 0], [0, l, 0], [0, l, l]],
                    [[0, l, 0], [0, l, l], [l, l, l], [l, l, 0]],
                    [[0, l, l], [0, 0, l], [l, 0, l], [l, l, l]],
                ]
            )
            - l / 2
        )

        for position in positions:
            self.ax.add_collection3d(
                Poly3DCollection(e + position, facecolor=color, alpha=0.5)
            )

    def cubes(self, positions, l, color="blue"):
        plot_box(
            ax=self.ax,
            size=np.full((3), self.diameter),
            A2B=np.eye(4),
            ax_s=1,
            wireframe=True,
            color="k",
            alpha=1.0,
        )

if __name__ == "__main__":
    objects = Objects(source)
    name = "cuboid/0.025x0.1x0.1"
    limit = None
    objects.set_map(name, limit)
    objects.plot()


import matplotlib.pyplot as plt
import os

def plot_col_graph(x, y, titulo_x, titulo_y, plot_title, size, name, representar='N'):
    '''
    Función que genera un gráfico de barras a partir de los parámetros de entrada

    :param x: datos eje x
    :param y: datos eje y
    :param titulo_x: título eje x
    :param titulo_y: título eje y
    :param plot_title: título del gráfico
    :param size: tamaño del gráfico. Por ejemplo: size = (20, 10)
    :param name: nombre del fichero png generado
    :param representar: parámetro que nos indica si queremos devolver el gráfico
            por pantalla o no. Puede tomar los valores 'Y' o 'N'
    :return: fig: se retorna un gráfico para que en caso que el parámetro representar
            sea 'Y' se pueda presentar el gráfico por pantalla
    '''
    plt.style.use('ggplot')  # Utilizaremos el tema ggplot

    # Definimos el tamaño en función del parámetro de entrada
    fig = plt.figure(figsize=size)
    # Añadimos datos en el eje x y en el eje y
    plt.bar(x, y)

    # Añadimos informaición en los ejes
    plt.xticks(range(len(x)), x, fontsize=8, rotation=90)
    plt.xlabel(titulo_x, fontsize=18)
    plt.ylabel(titulo_y, fontsize=18)
    plt.title(plot_title, fontsize=30)

    # Guardo la imagen en la carpeta img con el nombre indicado
    data_folder = '../img/'
    full_path = os.path.join(data_folder, name)
    plt.savefig(full_path, dpi=100)

    # Analizo el parámetro de entrada para estudiar si representamos la gráfica
    if representar == 'N':
        plt.close(fig)
    else:
        plt.show()
        plt.close(fig)

    return fig


def webAppKeyboard(update):
    # список ID пользователей, которым разрешен доступ к клавиатуре
    allowed_users = [1005942370, 987654321]

    # проверяем, является ли пользователь авторизованным
    if update.effective_user.id not in allowed_users:
        return None

    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)

    webAppBim = types.WebAppInfo("https://games.mihailgok.ru")
    webAppEdm = types.WebAppInfo("https://games.mihailgok.ru")
    webAppCloud = types.WebAppInfo("https://www.emiia.ru/osm/indoor9.html#18.31/55.977272/37.17427/62.4/45")
    webAppData = types.WebAppInfo("https://games.mihailgok.ru")
    one_butt = types.KeyboardButton(text="ТИМ (BIM)", web_app=webAppBim)
    two_butt = types.KeyboardButton(text="ЭДО (EDM)", web_app=webAppEdm)
    three_butt = types.KeyboardButton(text="CLOUD EMIIA.AI", web_app=webAppCloud)
    four_butt = types.KeyboardButton(text="DATA ANALYSIS", web_app=webAppData)
    keyboard.add(one_butt, two_butt)
    keyboard.add(three_butt, four_butt)

    return keyboard


f = open('dayso.inp','r')
f2 = open('dayso,out','w')
dayso = f.read()
dayso = dayso.split()
mang = []
for i in range(len(dayso)):
    mang.append(int(dayso[i]))
a = mang[0]
b = mang[1]
c = mang[2]
m = mang[3]
max = a*b
if (a*c >max):
    max=a*c
if (b*c >max):
    max=b*c
f2.write(str(max%m))


def authenticate_user(connection, username, password):
    query = """SELECT COUNT (*)
               FROM Users U
               WHERE U.username=%s AND
                    U.password=%s
               ;"""
    result = connection.execute(query, [username, password])
    user_count = result.first()
    return user_count['count'] > 0

def get_user(connection, username):
    query = """SELECT U.username
               FROM Users U
               WHERE U.username=%s
               ;"""
    result = connection.execute(query, [username])
    return result.first()

def add_user(connection, username, password, email):
    query = """INSERT INTO
               Users (username, password, email)
               VALUES (%s, %s, %s)
               ;"""
    connection.execute(query, [username, password, email])

def get_reviews_by_user(connection, username):
    query = """SELECT R1.time_written, R1.content, R1.rating, R2.neighborhood
               FROM Review R1 INNER JOIN Reviewed_By R2
                       ON R1.username=R2.username AND
                       R1.time_written=R2.time_written
               WHERE R1.username=%s
               ORDER BY R1.time_written DESC
               ;"""
    result = connection.execute(query, [username])
    return result.fetchall()

def get_reviews_by_neighborhood(connection, neighborhood):
    query = """SELECT R1.username, R1.time_written, R1.content, R1.rating
               FROM Review R1 INNER JOIN Reviewed_By R2
                   ON R1.username=R2.username AND
                   R1.time_written=R2.time_written
               WHERE R2.neighborhood=%s
               ORDER BY R1.time_written DESC
               ;"""
    result = connection.execute(query, [neighborhood])
    return result.fetchall()

def get_favorites(connection, username):
    query = """SELECT L.neighborhood, L.borough
               FROM Favorites F INNER JOIN Located_In L
                   ON F.neighborhood=L.neighborhood
               WHERE F.username=%s
               ;"""
    result = connection.execute(query, [username])
    return result.fetchall()

def add_favorite(connection, username, neighborhood):
    query = """INSERT INTO
               Favorites (username, neighborhood)
               VALUES (%s, %s)
               ;"""
    connection.execute(query, [username, neighborhood.title()])

def is_favorite(connection, username, neighborhood):
    query = """SELECT * FROM Favorites F
               WHERE F.username=%s AND F.neighborhood=%s
               ;"""
    result = connection.execute(query, [username, neighborhood])
    return result.first() is not None

def add_favorite(connection, username, neighborhood):
    query = """INSERT INTO
               Favorites (username, neighborhood)
               VALUES (%s, %s)
               ;"""
    connection.execute(query, [username, neighborhood])

def remove_favorite(connection, username, neighborhood):
    query = """DELETE FROM Favorites F
               WHERE F.username=%s AND F.neighborhood=%s
               ;"""
    connection.execute(query, [username, neighborhood])

def add_review(connection, neighborhood, username, review_data):
    rating, time_written, content = review_data['rating'], \
        review_data['time_written'], review_data['content']
    query = """INSERT INTO
               Review (time_written, content, rating, username)
               VALUES (%s, %s, %s, %s)
               ;"""
    connection.execute(query, [time_written, content, rating, username])

    query = """INSERT INTO
               Reviewed_By (username, time_written, neighborhood)
               VALUES (%s, %s, %s)
               ;"""
    connection.execute(query, [username, time_written, neighborhood.title()])

def get_borough_info(connection, borough):
    query = """SELECT B.year_incorporated, B.county_name
               FROM Borough B
               WHERE LOWER(B.name)=LOWER(%s)
               ;"""
    result = connection.execute(query, [borough])
    return result.first()

def get_borough_name_by_neighborhood(connection, neighborhood):
    query = """SELECT L.borough
               FROM Located_In L
               WHERE L.neighborhood=%s
               ;"""
    result = connection.execute(query, [neighborhood])
    return result.first()

def get_borough_names(connection):
    query = """SELECT B.name
               FROM Borough B
               ;"""
    result = connection.execute(query)
    return result.fetchall()

def get_neighborhood_names(connection, borough):
    query = """SELECT L.neighborhood
               FROM Located_In L
               WHERE LOWER(L.borough)=LOWER(%s)
               ;"""
    result = connection.execute(query, [borough])
    return result.fetchall()

def get_neighborhood_info(connection, neighborhood):
    query = """SELECT N.population, N.mean_income
               FROM Neighborhood N
               WHERE LOWER(N.name)=LOWER(%s)
               ;"""
    result = connection.execute(query, [neighborhood]).first()

    if result is None:
        return None

    neighborhood_info = {}
    neighborhood_info['population'] = result['population']
    neighborhood_info['mean_income'] = result['mean_income']
    neighborhood_info['subways'] = []

    query = """SELECT S1.subway, S2.color, S2.is_express
               FROM Neighborhood N INNER JOIN Serves S1
                       ON N.name=S1.neighborhood
                   INNER JOIN Subway S2
                       ON S2.name=S1.subway
               WHERE LOWER(N.name)=LOWER(%s)
               ;"""
    result = connection.execute(query, [neighborhood]).fetchall()
    for row in result:
        neighborhood_info['subways'].append(row)

    return neighborhood_info

def get_parks(connection, neighborhood):
    query = """SELECT P1.place_id, P2.name, P3.acres, P3.is_public,
                   P3.dogs_allowed
               FROM Placed_In P1 INNER JOIN Place_Of_Interest P2
                       ON P1.place_id=P2.id
                   INNER JOIN Park P3
                       ON P2.id=P3.id
               WHERE LOWER(P1.neighborhood)=LOWER(%s)
               ;"""
    result = connection.execute(query, [neighborhood])
    return result.fetchall()

def get_schools(connection, neighborhood):
    query = """SELECT P1.place_id, P2.name, S.mean_cost, S.school_type
               FROM Placed_In P1 INNER JOIN Place_Of_Interest P2
                       ON P1.place_id=P2.id
                   INNER JOIN School S
                       ON P2.id=S.id
               WHERE LOWER(P1.neighborhood)=LOWER(%s)
               ;"""
    result = connection.execute(query, [neighborhood])
    return result.fetchall()

def get_restaurants(connection, neighborhood):
    query = """SELECT P1.place_id, P2.name, R.restaurant_type, R.cost_rating,
                   R.alcohol_served
               FROM Placed_In P1 INNER JOIN Place_Of_Interest P2
                       ON P1.place_id=P2.id
                   INNER JOIN Restaurant R
                       ON P2.id=R.id
               WHERE LOWER(P1.neighborhood)=LOWER(%s)
               ;"""
    result = connection.execute(query, [neighborhood])
    return result.fetchall()


import face_recognition
import os

TEST_FACES = "test_faces"

true_positives = 0
false_positives = 0

image = face_recognition.load_image_file(f"image_0001.jpg")
realID = face_recognition.face_encodings(image)[0]
print(type(realID))
tolerance = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
for value in tolerance:
    print("tolerance: " + str(value))
    for filename in os.listdir(TEST_FACES):
        image = face_recognition.load_image_file(f"{TEST_FACES}/{filename}")
        if len(face_recognition.face_encodings(image, model="cnn")) != 0:
            face = face_recognition.face_encodings(image, model="cnn")[0]
            results = face_recognition.compare_faces([realID], face, value)
        else:
            continue

        if True in results:
            if "real" in filename:
                true_positives += 1
            else:
                false_positives += 1
            print("Access Granted" + " " + filename)
        else:
            print("Access Denied" + " " + filename)
    print("true: " + str(true_positives) + '\n' + "false: " + str(false_positives))
    true_positives = 0
    false_positives = 0


from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages

from ..models import Question
from ..forms import QuestionForm

# Create your views here.
@login_required(login_url='common:login')
def question_create(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.author = request.user
            question.create_date = timezone.now()
            question.save()
            return redirect('pybo:index')
    else:
        form = QuestionForm()
    context = {'form':form}
    return render(request, 'pybo/question_form.html', context)

@login_required(login_url='common:login')
def question_modify(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if request.user != question.author:
        messages.error(request, '수정 권한이 없습니다.')
        return redirect('pybo:detail', question_id=question.id)
    if request.method =="POST":
        #messages.error(request, '수정 권한이 없습니다.')
        form = QuestionForm(request.POST, instance=question)
        if form.is_valid():
            question = form.save(commit=False)
            question.author = request.user
            question.modify_date = timezone.now()
            question.save()
            return redirect('pybo:detail', question_id = question.id)
    else:
        form = QuestionForm(instance=question)
    context = {'form':form}
    return render(request,'pybo/question_form.html', context)

@login_required(login_url='common:login')
def question_delete(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if request.user != question.author:
        messages.error(request, '삭제 권한이 없습니다.')
        return redirect('pybo:detail', question_id=question.id)
    question.delete()
    return redirect('pybo:index')


# orthogonal projected torus knot
import numpy as np

l = -7.5
r = 7.5
b = -7.5
t = 7.5
n = 10.0
f = -10.0

ex, ey, ez = 0, 0, 15
nx, ny = 500, 500
xu, yu, zu = 1, 0, 0
xv, yv, zv = 0, 1, 0
xw, yw, zw = 0, 0, -1

Mcam_uvw = np.array([
    [xu, yu, zu, 0],
    [xv, yv, zv, 0],
    [xw, yw, zw, 0],
    [0,  0,  0,  1]])

Mcam_e = np.array([
    [1, 0, 0, -ex],
    [0, 1, 0, -ey],
    [0, 0, 1, -ez],
    [0, 0, 0, 1  ]])

Mcam = Mcam_uvw.dot(Mcam_e)

Morth = np.array([
    [2.0/(r-l), 0, 0, -(r+l)/(r-l)],
    [0, 2.0/(t-b), 0, -(t+b)/(t-b)],
    [0, 0, 2.0/(n-f), -(n+f)/(n-f)],
    [0, 0, 0, 1]])

Mvp = np.array([
    [nx/2.0, 0, 0, (nx-1)/2.0],
    [0, ny/2.0, 0, (ny-1)/2.0],
    [0, 0, 1, 0],
    [0, 0, 0, 1]])

M = Mvp.dot(Morth).dot(Mcam)

from math import sin, cos, pi

p,q = 3.0,7.0
step = 0.01

# convert angular coordinates
# r, theta, z to x, y, z
# take tuple, return tuple
def ang2xyz(angular):
	r, th, z = angular
	x = r*cos(th)
	y = r*sin(th)
	return x,y,z

# point list consists of tuples of (x,y,z) coordinates of the point
points = []

for t in np.arange(0, 2*pi*p, step):
	r_0 = 2 + cos(q*t/p)
	theta = t
	z = sin(q*t/p)
	points.append(ang2xyz((r_0, theta, z)))

p = []
for point in points:
    nppoint = np.array([point[0], point[1], 0, 1])
    p.append(M.dot(nppoint))

def write_ppm(mat, file_name):
    file_data = 'P3\n# %s\n' % file_name
    dimension = str(mat.shape[0]) + ' ' + str(mat.shape[1])
    max_val = '1'
    data = ''
    for i in mat:
        for j in i:
            pixel = [str(k) for k in [j] * 3]
            pixel = ' '.join(pixel)
            data += pixel + ' '
        data += '\n'
    file_data += dimension + '\n' + max_val + '\n' + data
    with open(file_name, 'w') as f:
        f.write(file_data)

mat = np.zeros( (ny, nx), dtype=np.uint8 )
for pn in p:
    x = int(pn[0])
    y = int(pn[1])
    #print x, y
    mat[y][x] = 1

write_ppm(mat, 'deneme.ppm')


import random

play_options = ['r', 'p', 's']
win_options = ['rs', 'pr', 'sp']

options_dict = {
    'r': 'Rock',
    'p': 'Papper',
    's': 'Scissor'
}

def game():
    user_wins = 0
    ai_wins = 0
    print('Lets play a game')

    while True:
        user_input = input('Enter ("end" = exit, "r" = Rock, p = "Papper", "s" = Scisors): ')
        ai_input = random.choice(['r', 'p', 's'])

        if user_input == 'end':
            print('Ending game')
            print(f'Final score: User {user_wins} - {ai_wins} AI')
            break
        elif user_input not in play_options:
            print('Invalid input')
        else:
            print(f'User: {options_dict[user_input]}, AI: {options_dict[ai_input]}')
            if (user_input == ai_input):
                print('Draw')
            elif f'{user_input}{ai_input}' in win_options:
                user_wins += 1
            else:
                ai_wins += 1
            print(f'Current score: User {user_wins} - {ai_wins} AI')

        print('------------------------------------------')

game()


""""
This is the instrument definition file for PyCat. Here we define the classes that reads instrument raw
data into a standardized data format. For most instruments this is a simple pandas Dataframe. The main
point is that the standardized data format should be the same for all instrument. That way
the analysis class can be re-used.
"""

import os
import json
import pandas as pd
import numpy as np
import datetime as dt
import xlrd
import pkg_resources

######################
# GC Instrument Class
# Here the GC instrument classes are defined. The structure builds on a parent class and subsequent sub classes.
######################

class GC_Instrument:
    ''''
    GC instrument parent class. This mainly adds som utility functions such as
    being able to add instrument configurations. Not strictly necessary currently
    but may be usefull in the future.
    '''

    def __init__(self, name='default', measurment_offset=0):
        """
        Inputs
        ------------
        name : instrument name (found in "instrument:lib/")
        measurment_offset : offset time from start of reactant gas feeding to start of GC sampling (minutes)
        """
        self.name = name  # name of the instrument
        self.instrument_config = self.fetch_instrument_config()  #  Fetches the instrument config
        self.measurment_offset = measurment_offset  # Sets the measurment offset

    def __str__(self):
        return 'Instrument Loaded: {}'.format(self.name)

    def fetch_instrument_config(self):
        """
        Fetches the instrument configurations such as response_factors etc.
        """
        stream = pkg_resources.resource_stream(__name__, 'instrument_lib\\{}.json'.format(self.name))

        try:
            return json.load(stream)
        except:
            raise Exception("Your reaction is not defined")

    def instrument_exists(self, name, directory):
        """
        check is the instrument from "name" exists in instrument_lib/
        """
        reaction_files = os.listdir(directory)
        if name + '.json' in reaction_files:
            return True
        else:
            raise Exception('Instrument does not exist')

class CoFeedRig(GC_Instrument):
    """
    The Co-Feed rig instrument. This only deals with GC data but the Cofeed rig also has MS data. See
    under MS_instruments.

    """
    def __init__(self, datafile, name='CoFeed', measurment_offset=0):
        """
        INPUTS
        -----------
        datafile : the raw data file path. (File as generated from OpenLab , .csv file)
        name : the name of the cofeed rig in instrument_lib/
        measurment_offset : offset time from start of reactant gas feeding to start of GC sampling (minutes)
        """
        # Loading reaction and instrument object
        GC_Instrument.__init__(self, name, measurment_offset)

        #Loading data
        self.datafile = datafile
        self.raw_data = self.read_gcdata()  # Processes the raw data and creates a standardized dataset.
        self.compounds = self.raw_data.columns.to_list()  # Returns a list of all integrated compounds
        self.tos = self.raw_data.index.to_list()  # Returns the "time-on-stream" data as a list.

    #####  Loading Data  #####
    def read_gcdata(self):
        """
        Method that reads the raw data from the CoFeed-rig and creates a standardized dataformat.
        """

        def convert_to_timestamp(times):
            """
            Function that convert the raw data time string to datetime timestamp.
            """
            new_times = []
            for i, val in enumerate(times):
                timestamp = val[:-3]
                date = dt.datetime.strptime(timestamp, "%Y%m%d %H%M%S")  # The format of the time string given by OpenLab.
                new_times.append(date.timestamp())

            new_times = np.array(new_times)
            new_times = (new_times - new_times[0])/3600  # Convert the times to hours.

            return np.round(new_times, 2)  # Rounding the times to 2 decimals.

        def _correct_for_responsfac(df, respons_factors):
            """
            functions that corrects the FID responds with the response factors.
            """
            for i in respons_factors:
                df[i] = df[i]/respons_factors[i]  # Divides each relevant compound with its response factor.
            return df

        compound_names = pd.read_csv(self.datafile, nrows=1, header=None).drop([0], axis=1).dropna(axis=1)  # The list of compounds
        df = pd.read_csv(self.datafile, skiprows=2, header=None, engine='python').fillna(0).drop([1, 2], axis=1)  # The raw data.
        df = df[df[0] !=0]  # Removing empty rows that does not contain any data
        df = df[:-2]  # Removing the last two rows which are information we don't need

        old_column_names = compound_names.values[0, :].tolist()
        old_column_names = [x.lower() for x in old_column_names]  # We force lower case on all compounds names.
        new_column_names = ['TOS'] + old_column_names  # Replacing column names
        df.columns = new_column_names

        df['TOS'] = convert_to_timestamp(df['TOS']) # Converting the time strings of the raw data to TOS in hours.

        if self.measurment_offset != 0:  #  If we assign a measurment offset it is added here to the TOS list.
            df['TOS'] += self.measurment_offset/60

        df = _correct_for_responsfac(df, self.instrument_config['Response_Factors'])  # Here we correct for respons factors.

        df = df.round(decimals=2)  # We round the data to two decimals
        df.set_index('TOS', inplace=True)  # We set the dataframe index to be the TOS column. This makes data processing more convenient.
        return df  # returns processed and standardized GC data.

class HighPressureRig(GC_Instrument):
    """
    The high pressure rig instrument. Analogous to the CoFeed rig instrument defined above.
    The high pressure rig has two FID detectors and therefore has two data sets that needs
    to be processed and combined. This instrument method does exactly this and returns a dataframe
    which are identical to the CoFeed rig.

    """
    def __init__(self, data, name='HPR', measurment_offset=0):
        """
        INPUTS
        ----------
        data : A tuple or list which takes the file locations for the two FID datafiles.

        """

        # Loading reaction and instrument object
        GC_Instrument.__init__(self, name, measurment_offset)

        #  Loading data
        self.datafile = data[0]
        self.datafile_MFID = data[0]  # The Mid FID data
        self.datafile_BFID = data[1]  # The Back FID data
        self.raw_data = self.read_gcdata().round(decimals=2)  # Processing the raw data
        self.compounds = self.raw_data.columns.to_list()  # The list of compounds
        self.tos = self.raw_data.index.to_list() # Returns the "time-on-stream" data as a list.

    #####  Loading Data  #####
    def read_gcdata(self):
        """
        This is the data parser function which reads in the GC data.
        """
        def to_df(df):
            """
            This functions reads each loaded pandas and cleanes up the raw data.
            ---------------------
            INPUTS
            df : pandas dataframe with loaded raw data from excel file
            OUTPUTS
            df : cleaned dataframe
            """
            row_id_start = df.index[df.iloc[:, 0] == 'Array 1'][0]  # Finding the start of the data
            row_id_end = df.index[df.iloc[:, 0] == 'Mean'][0]  #  Finding the end of the data

            df  = df.iloc[row_id_start+1:row_id_end, 1:].reset_index(drop=True)  # Select data and remove index
            df.columns=df.iloc[0, :]  # Set the column names
            df.drop(index=0, inplace=True)  # removes the first column
            df.reset_index(drop=True, inplace=True)

            cols = df.columns.to_list()  # Get current columns
            c_new = [c for c in cols if c[0:4]!='Time']  # Build column name list with the correct name (remove all Time)

            df = df[c_new]  # Select correcte columns with Area
            df = df[df['Run Time'] > 20]  #  Remove bypass injections
            df.drop(columns=['Acquisition Method Name', 'Run Time'], inplace=True) # Remove unneeded columns

            cols = df.columns.to_list()
            cc = [cols[i][5:].lower() if i < len(cols)-1 else cols[i] for i in range(len(cols)) ]  # Rename column headers with simpler names
            cc[0] = 'TOS'

            df.columns = cc  # New column header

            return df

        def join_FIDs(MFID, BFID):
            """
            Helper function that combines the data from the front and back FID.
            ---------------------
            INPUTS
            MFID : Dataframe with loaded Mid FID data
            BFID : Dataframe with loeaded Back FID data
            OUTPUTS
            df_combo : Merged dataframe containing the complete dataset
            """

            df_comb = pd.concat([MFID, BFID.iloc[:, 1:]], axis=1)
            df_comb['Total Area']= df_comb['Total Peak Area'].sum(axis=1)
            df_comb.drop(columns=['Total Peak Area'], inplace=True)
            df_comb = df_comb.reindex(index=df_comb.index[::-1]).reset_index(drop=True)

            df_comb['TOS'] = pd.to_datetime(df_comb.TOS, format="%d/%m/%Y %H:%M:%S")
            df_comb['TOS'] = np.round((df_comb['TOS'] - df_comb['TOS'][0])/np.timedelta64(1, 'h'), 2)
            df_comb.set_index('TOS', inplace=True)

            df_comb['aromatics'] = (df_comb.iloc[:, -1] - df_comb.iloc[:, :-1].sum(axis=1)).round(1)
            df_comb.drop(columns='Total Area', inplace=True)
            df_comb.fillna(0, inplace=True)
            df_comb[df_comb<0] = 0

            return df_comb

        def _correct_for_responsfac(df, respons_factors):
            """
            This function corrects the raw data for the GC respons factors
            """

            for i in respons_factors:
                df[i] = df[i]/respons_factors[i]
            return df

        wb1 = xlrd.open_workbook(self.datafile_MFID, logfile=open(os.devnull, 'w'))  #  This is needed to surpress annoying log messages
        wb2 = xlrd.open_workbook(self.datafile_BFID, logfile=open(os.devnull, 'w'))  #  This is needed to surpress annoying log messages

        df_MidFid = pd.read_excel(wb1)  # Reading the Mid FID datafile
        df_BackFid = pd.read_excel(wb2)  # Reading the Back FID datafile

        df_MFID = to_df(df_MidFid)  # Cleans the read dataframe
        df_BFID = to_df(df_BackFid)

        df_data = join_FIDs(df_MFID, df_BFID)  # Join the Mid and Back FID dataframes.

        df_data = _correct_for_responsfac(df_data, self.instrument_config['Response_Factors'])  # Correcting for respons factors.

        return df_data

###########################
# MS Instruments
###########################