# -*- coding: utf-8 -*-

from sklearn.metrics import *
from sklearn.model_selection import learning_curve
from sklearn.model_selection import GridSearchCV
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from cie.common import logger
# use TkAgg backend
matplotlib.use("TkAgg")

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['savefig.dpi'] = 200
plt.rcParams['figure.dpi'] = 200

tuning_folder = './output/tuning/'
if not os.path.exists(tuning_folder):
    os.makedirs(tuning_folder)

logger = logger.get_logger(name=logger.get_name(__file__))

def grid_search_tuning(estimator, x_train, y_train, x_test, y_test, param_grid=None, cv=5,
                       scores={"acc": ("accuracy", None)}, features_names=None, regressor=False, fit_params=None, do_plot=False):
    """
    参数grid search交叉tuning
    :param estimator: 模型评估器
    :param x_train: 训练数据特征
    :param y_train: 训练数据标签
    :param x_test: 测试数据特征
    :param y_test: 测试数据标签
    :param param_grid: 参数字典
    :param cv: cv类型
    :param scores: dict: key为别名， value为tuple(sklearn支持的score方法，score函数），对于分类问题，score函数可以设置为None;
    目前只支持单一score
    :param features_names: 特征名字列表
    :param regressor: 是否为回归，默认为False
    :return: best_estimator: 最好的estimator。
    """
    results = dict()
    for score in scores:
        logger.info("# 超参数tuning: %s" % score)
        score_new = scores[score][0]
        score_func = scores[score][1]
        if scores[score] in ['f1', 'precision', 'recall']:
            score_new = '%s_macro' % score_new
        logger.info(f"param_grid: {param_grid}")
        if regressor:
            gs = GridSearchCV(estimator, param_grid, cv=cv, fit_params=fit_params, scoring=score_new)
        else:
            gs = GridSearchCV(estimator, param_grid, cv=cv, fit_params=fit_params,
                              scoring={score: score_new}, refit=score, return_train_score=True)
            # gs = GridSearchCV(estimator, param_grid, cv=cv, scoring=score_new, class_weight=class_weight)
        gs.fit(x_train, y_train)

        if regressor:
            best_index_ = gs.cv_results_["rank_test_score"].argmax()
            best_params_ = gs.cv_results_["params"][best_index_]
            logger.info(f"交叉验证集上最好的参数：{best_params_}")
        else:
            logger.info(f"交叉验证集上最好的参数：{gs.best_params_}")
        logger.info("交叉验证集上的各个参数表现：")
        if regressor:
            means = gs.cv_results_['mean_test_score']
            stds = gs.cv_results_['std_test_score']
        else:
            means = gs.cv_results_['mean_test_' + score]
            stds = gs.cv_results_['std_test_' + score]
        for mean, std, params in zip(means, stds, gs.cv_results_['params']):
            logger.info("mean: %0.3f, std: (+/-%0.03f) for %r"
                  % (mean, std * 2, params))
        if y_test is not None:
            y_true, y_pred = y_test, gs.predict(x_test)
            if regressor:
                logger.info("回归评估 %s: %.3f" % (score, score_func(y_true, y_pred)))
            else:
                logger.info("测试集上的分类效果报告:")
                logger.info(classification_report(y_true, y_pred))
        results.update(gs.cv_results_)
        best_estimator = gs.best_estimator_

    if do_plot:
        X_axis = results['params']
        plt.figure(figsize=(13, 13))
        plt.title("GridSearchCV evaluating using multiple scorers simultaneously",
                  fontsize=16)

        plt.xlabel("Parameter")
        plt.ylabel("Score")

        ax = plt.gca()
        # if not regressor:
        #     ax.set_ylim(0.01, 1.01)

        # Get the regular numpy array from the MaskedArray

        colormap = plt.cm.get_cmap(lut=len(scores) + 1)
        colors = [colormap(i) for i in range(len(scores))]
        for scorer, color in zip(sorted(scores), colors):
            for sample, style in (('train', '--'), ('test', '-')):
                if regressor:
                    sample_score_mean = results['mean_%s_score' % sample]
                    sample_score_std = results['std_%s_score' % sample]
                else:
                    sample_score_mean = results['mean_%s_%s' % (sample, scorer)]
                    sample_score_std = results['std_%s_%s' % (sample, scorer)]
                ax.fill_between(X_axis, sample_score_mean - sample_score_std,
                                sample_score_mean + sample_score_std,
                                alpha=0.1 if sample == 'test' else 0, color=color)
                ax.plot(X_axis, sample_score_mean, style, color=color,
                        alpha=1 if sample == 'test' else 0.7,
                        label="%s (%s)" % (scorer, sample))
            # if regressor:
            #     best_index = np.nonzero(results['rank_test_score'] == len(results['rank_test_score']))[0][0]
            #     best_score = results['mean_test_score'][best_index]
            # else:
            best_index = np.nonzero(results['rank_test_%s' % scorer] == 1)[0][0]
            best_score = results['mean_test_%s' % scorer][best_index]

            # Plot a dotted vertical line at the best score for that scorer marked by x
            ax.plot([X_axis[best_index], ] * 2, [0, best_score],
                    linestyle='-.', color=color, marker='x', markeredgewidth=3, ms=8)

            # Annotate the best score for that scorer
            ax.annotate("%0.2f" % best_score,
                        (X_axis[best_index], best_score + 0.005))
        plt.xticks(rotation=75)
        plt.subplots_adjust(bottom=.3)
        plt.legend(loc="best")
        plt.grid('off')
        plt.show()

        # 分析feature importance
        if features_names is not None:
            feat_imp = pd.Series(best_estimator.fit(x_train, y_train).feature_importances_, features_names).sort_values(
                ascending=False)
        else:
            feat_imp = pd.Series(best_estimator.fit(x_train, y_train).feature_importances_).sort_values(ascending=False)
        feat_imp.plot(kind='bar', title='Feature Importance')
        plt.ylabel('Feature Importance Score')
        plt.show()

    return best_estimator

def plot_learning_curve(estimator, title, X, y, ylim=None, scoring=None, cv=None,
                        n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):
    """
    Generate a simple plot of the test and training learning curve.

    Parameters
    ----------
    estimator : object type that implements the "fit" and "predict" methods
        An object of that type which is cloned for each validation.

    title : string
        Title for the chart.

    X : array-like, shape (n_samples, n_features)
        Training vector, where n_samples is the number of samples and
        n_features is the number of features.

    y : array-like, shape (n_samples) or (n_samples, n_features), optional
        Target relative to X for classification or regression;
        None for unsupervised learning.

    ylim : tuple, shape (ymin, ymax), optional
        Defines minimum and maximum yvalues plotted.
    scoring : string, callable or None, optional, default: None
        A string (see model evaluation documentation) or
        a scorer callable object / function with signature
        ``scorer(estimator, X, y)``.
    cv : int, cross-validation generator or an iterable, optional
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:
          - None, to use the default 3-fold cross-validation,
          - integer, to specify the number of folds.
          - :term:`CV splitter`,
          - An iterable yielding (train, test) splits as arrays of indices.

        For integer/None inputs, if ``y`` is binary or multiclass,
        :class:`StratifiedKFold` used. If the estimator is not a classifier
        or if ``y`` is neither binary nor multiclass, :class:`KFold` is used.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validators that can be used here.

    n_jobs : int or None, optional (default=None)
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    train_sizes : array-like, shape (n_ticks,), dtype float or int
        Relative or absolute numbers of training examples that will be used to
        generate the learning curve. If the dtype is float, it is regarded as a
        fraction of the maximum size of the training set (that is determined
        by the selected validation method), i.e. it has to be within (0, 1].
        Otherwise it is interpreted as absolute sizes of the training sets.
        Note that for classification the number of samples usually have to
        be big enough to contain at least one sample from each class.
        (default: np.linspace(0.1, 1.0, 5))
    """
    plt.figure()
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, scoring=scoring, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="Cross-validation score")

    plt.legend(loc="best")
    return plt

def plot_roc(model, X, y):
    """
    Plot ROC curve of 'model' on X and y.

    Parameters
    ----------
    model: fitted model
    X : array-like, shape [n_samples, n_feature]
    y: the label,must be binary(i.e.

    Returns
    -------
    ROC curve
    """
    # plot setting
    plt.style.use("ggplot")
    f = plt.subplot()
    f.set_title('ROC Curve (%s)' % model.__class__.__name__, {'fontsize': 20})
    f.set_xlabel('fpr', {'fontsize': 20})
    f.set_ylabel('tpr', {'fontsize': 20})

    proba = model.predict_proba(X)[:, 1]
    fpr, tpr, thr = roc_curve(y, proba)
    line, = f.plot(fpr, tpr)

    f.legend(line, model.__class__.__name__, loc='lower right', fontsize='large')

def _round(x):
    if isinstance(x, float):
        return np.round(x, 3)
    else:
        return x

def classific_report(model, X, y):
    """
    classification performance of 'model' on X and y.

    Parameters
    ----------
    model: fitted model
    X : array-like, shape [n_samples, n_feature]
    y: the label,must be binary(i.e.

    Returns
    -------
    the values of main evaluation metrics with respect to 'model'
    """
    print(model.__class__.__name__)

    pred = model.predict(X)
    print('%d个特征' % X.shape[1])
    acc = model.score(X, y)
    print('准确率', acc)

    confusionMatrix = confusion_matrix(y, pred)
    print(confusionMatrix)

    if len(np.unique(y)) == 2:
        proba = model.predict_proba(X)[:, 1]
        auc = roc_auc_score(y, proba)
        print('AUC', auc)

    sensitivity = confusionMatrix[0, 0] / confusionMatrix.sum(axis=0)[0]
    specificity = confusionMatrix[1, 1] / confusionMatrix.sum(axis=0)[1]
    print('敏感度: %.3f, 特异度: %.3f' % (sensitivity, specificity))

    performance = [model.__class__.__name__, acc, sensitivity, specificity]
    performance = list(map(_round, performance))
    return performance

def regression_report(model, X, y):
    """
    regression performance of 'model' on X and y.

    Parameters
    ----------
    model: fitted model
    X : array-like, shape [n_samples, n_feature]
    y: the label,must be binary(i.e.

    Returns
    -------
    the values of main evaluation metrics with respect to 'model'
    """
    print(model.__class__.__name__)
    performance = []
    pred = model.predict(X)
    mae = mean_absolute_error(y, pred)
    mse = mean_squared_error(y, pred)
    evs = explained_variance_score(y, pred)
    r2 = r2_score(y, pred)
    performance = [model.__class__.__name__, mae, mse, evs, r2]
    performance = list(map(_round, performance))
    return performance


import sys
from itertools import combinations

sys.stdin = open('1767.txt', 'r')

dx = (-1, 1, 0, 0)
dy = (0, 0, -1, 1)

def dfs(n, combi, visit_k_origin, k=0, acc=0):
    global result

    if k == n:
        if acc < result:
            result = acc

        return

    for i in range(4):
        flag = False
        cnt = 0
        visit_k = [visit_k_origin[i][:] for i in range(N)]
        new_x = not_connect[combi[k]][0] + dx[i]
        new_y = not_connect[combi[k]][1] + dy[i]

        if not (0 <= new_x < N and 0 <= new_y < N):
            continue

        while 0 <= new_x < N and 0 <= new_y < N:
            if visit_k[new_x][new_y] != 0:
                flag = True
                break

            cnt += 1
            visit_k[new_x][new_y] = 2
            new_x += dx[i]
            new_y += dy[i]

        if flag:
            continue

        dfs(n, combi, visit_k, k+1, acc+cnt)

T = int(input())
for test_case in range(1, T+1):
    N = int(input())
    matrix = [list(map(int, input().split())) for _ in range(N)]

    not_connect = []
    for i in range(1, N-1):
        for j in range(1, N-1):
            if matrix[i][j] == 1:
                not_connect.append((i, j))

    connect = []
    for i in [0, N-1]:
        for j in range(N):
            if matrix[i][j] == 1:
                connect.append((i, j))

    for j in [0, N-1]:
        for i in range(1, N-1):
            if matrix[i][j] == 1:
                connect.append((i, j))

    l = len(not_connect)
    for n in range(l, -1, -1):
        result = 0xffffff
        for combi in combinations(range(l), n):
            visit_0_origin = [matrix[i][:] for i in range(N)]
            dfs(n, combi, visit_0_origin)

        if result != 0xffffff:
            break

    print('#{} {}'.format(test_case, result))


# -*- coding: utf-8 -*-
"""
AGS Gateway app factory
"""

import logging
import logging.config
import os

from flask import Flask, render_template

def create_app(config='config.py', **kwargs):
    app = Flask(__name__)
    app.config.from_pyfile(config)
    app.config.update(kwargs)

    configure_logger(app)

    register_blueprints(app)
    register_context_processors(app)
    register_error_handlers(app)
    register_extensions(app)

    return app

def configure_logger(app):
    app.logger
    logging.config.dictConfig(app.config.get('LOGGING', {}))

def register_blueprints(app):

    from app.main import main
    app.register_blueprint(main)

    from app.oidc_provider import oidc_provider
    app.register_blueprint(oidc_provider)

    from app.broker import broker
    app.register_blueprint(broker)

def register_context_processors(app):

    def base_context_processor():
        return {
            'asset_path': '/static/govuk_template/assets/',
        }

    app.context_processor(base_context_processor)

def register_error_handlers(app):

    error_handlers = {
        '404.html': [404],
        # avoid flask 0.11 bug with 402 and 407
        '4xx.html': [401, 405, 406, 408, 409],
        '5xx.html': [500, 501, 502, 503, 504, 505]}

    def make_handler(code, template):
        template = os.path.join('errors', template)

        def handler(e):
            return render_template(template, code=code), code

        return handler

    for template, codes in error_handlers.items():
        for code in codes:
            app.register_error_handler(code, make_handler(code, template))

def register_extensions(app):

    from app.assets import env
    env.init_app(app)

    from app.oidc_provider import init_oidc_provider
    app.provider = init_oidc_provider(app)

    from app.oidc_client import OIDCClient
    OIDCClient(app)


import random
import string

print("H A N G M A N")

while True:

    print('Type "play" to play the game, "exit" to quit:', end=" ")
    play = input()

    if play == "exit":
        break
    elif play == "play":
        word_list = ['python', 'java', 'kotlin', 'javascript']
        random_word = random.choice(word_list)
        correct_guess = (len(random_word)) * "-"  # All the characters you have guessed correctly
        guessed_list = []  # All the words you have guess (correct or incorrect both)

        def get_input(correct_guess, guessed_list):
            while True:
                print()
                print(correct_guess)
                print("Input a letter:", end=" ")
                answer = input()
                if len(answer) != 1:
                    print("You should input a single letter")
                elif answer not in string.ascii_lowercase:
                    print("It is not an ASCII lowercase letter")
                elif answer in guessed_list:
                    print("You already typed this letter")
                else:
                    return answer

        count = 8
        while count > 0:
            letter = get_input(correct_guess, guessed_list)
            if letter in random_word:
                new_word = ""  # To make changes in correct_guess word in current loop
                if letter in correct_guess:  # or letter in guessed_list:
                    print("You already typed this letter")
                for i in range(len(random_word)):
                    if letter == random_word[i]:
                        new_word = new_word + letter  # Add letter for correct_guess word
                    elif correct_guess[i] != "-":
                        new_word = new_word + correct_guess[
                            i]  # Update new_word if character already present in correct_guess word
                    else:
                        new_word = new_word + "-"
                correct_guess = new_word  # Assign all changes from this loop in correct_guess word

                if "-" not in correct_guess:
                    print("You guessed the word!")
                    print("You survived!")
                    break

            elif letter not in random_word:
                print("No such letter in the word")
                count -= 1

            if letter not in guessed_list:
                guessed_list.append(letter)

        if "-" in correct_guess:
            print("You are hanged!\n")
            exit()


import random, time, copy
from termcolor import cprint,colored
import style
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

# import stdarray

#place bomb in random places in the grid, if random lands on an previous bomb, it loops again
def placeBomb(grid):
    while True:
        if not grid[random.randint(0, len(grid) - 1)][random.randint(0, len(grid[0]) - 1)] == '*':
            grid[random.randint(0, len(grid) - 1)][random.randint(0, len(grid[0]) - 1)] = '*'
            return

#adds to the grid numbers which represent the number of bombs in adjacent spaces
def updateValues(row_n, col, grid):
    #Row above.
    if row_n - 1 > -1:
        row = grid[row_n - 1]
        if col - 1 > -1:
            if not row[col - 1] == '*':
                row[col - 1] += 1
        if not row[col] == '*':
            row[col] += 1
        if len(grid[0]) > col + 1:
            if not row[col + 1] == '*':
                row[col + 1] += 1
    #Same row.
    row = grid[row_n]
    if col - 1 > -1:
        if not row[col - 1] == '*':
            row[col - 1] += 1
    if len(grid[0]) > col + 1:
        if not row[col + 1] == '*':
            row[col + 1] += 1
    #Row below.
    if len(grid) > row_n + 1:
        row = grid[row_n + 1]
        if col - 1 > -1:
            if not row[col - 1] == '*':
                row[col - 1] += 1
        if not row[col] == '*':
            row[col] += 1
        if len(grid[0]) > col + 1:
            if not row[col + 1] == '*':
                row[col + 1] += 1

def checkZeros(shown_grid, solution_grid, row, col):
    oldGrid = copy.deepcopy(shown_grid)

    zeroProcedure(row, col, shown_grid, solution_grid)

    while oldGrid != shown_grid:
        oldGrid = copy.deepcopy(shown_grid)
        for row in range(len(shown_grid)):
            for col in range(len(shown_grid[0])):
                if shown_grid[row][col] == 0:
                    zeroProcedure(row, col, shown_grid, solution_grid)
        if oldGrid == shown_grid:
            return

def zeroProcedure(row_n, col_n, shown_grid, solution_grid):
    #Row above
    if row_n-1 > -1:
        row = shown_grid[row_n-1]
        if col_n-1 > -1:
            row[col_n-1] = solution_grid[row_n -1 ][col_n -1]
        row[col_n] = solution_grid[row_n - 1][col_n]
        if len(shown_grid[0]) > col_n + 1:
            row[col_n+1] = solution_grid[row_n - 1][col_n + 1]
    #Same row
    row = shown_grid[row_n]
    if col_n - 1 > -1:
        row[col_n-1] = solution_grid[row_n][col_n -1]
    if len(shown_grid[0]) > col_n+1:
        row[col_n+1] = solution_grid[row_n][col_n + 1]
    #Row below
    if len(shown_grid) > row_n+1:
        row = shown_grid[row_n+1]
        if col_n-1 > -1:
            row[col_n-1] = solution_grid[row_n + 1][col_n - 1]
        row[col_n] = solution_grid[row_n + 1][col_n]
        if len(shown_grid[0]) > col_n+1:
            row[col_n+1] = solution_grid[row_n + 1][col_n + 1]

def playAgain(start_time):
    print('Time: ' + str(round(time.time() - start_time)) + 's')
    while True:
        playBla = input('Play again? (Y/N): ').lower()
        if playBla == 'y':
            return 1
        if playBla != 'n':
            cprint('Choice not supported, please type (Y/N)!', 'red')
            continue
        cprint('Thank you for playing!', 'yellow')
        quit()

def play(solution_grid, shown_grid, mines):
    start_time = time.time()
    while True:
        style.printGrid(shown_grid)
        row, col = choose(solution_grid, shown_grid)

        if solution_grid[row][col] == '*' and shown_grid[row][col] != '⚐':
            style.printGrid(solution_grid)
            print(f"You DEAD {colored('Looser!', 'red', 'on_cyan')}")
            if playAgain(start_time) == 1:
                return 1
        if shown_grid[row][col] != '⚐':
            shown_grid[row][col] = solution_grid[row][col]
        if solution_grid[row][col] == 0 and shown_grid[row][col] != '⚐':
            checkZeros(shown_grid, solution_grid, row, col)

        squaresLeft = 0
        for row in shown_grid:
            squaresLeft += row.count(' ') + row.count('⚐')

        if squaresLeft == mines:
            style.printGrid(solution_grid)
            print('You win!')
            if playAgain(start_time) == 1:
                return 1

def choose(solution_grid, shown_grid):
    letters = [chr(i) for i in range(97, 97 + len(shown_grid[0]))]
    numbers = [str(i) for i in range(len(shown_grid))]

    #Loop in case of invalid entry.
    while True:
        chosen = input('Choose a cell (eg. B2) or place a marker (eg. mB2): ').lower()
        if len(chosen) == 3 and chosen[0] == 'm' and chosen[1] in letters and chosen[2] in numbers:
            if shown_grid[int(chosen[2])][ord(chosen[1])-97] != ' ':
                print('You cannot put a marker on an already shown cell')
                continue
            shown_grid[int(chosen[2])][ord(chosen[1])-97] = '⚐'
            return (int(chosen[2]), ord(chosen[1])-97)
        elif len(chosen) == 2 and chosen[0] in letters and chosen[1] in numbers:
            return (int(chosen[1]), ord(chosen[0])-97)

def main():
    rows = 10
    columns = 10
    mines = 10
    choice = ''

    style.clear()
    while choice != 'P' and choice != 'I':
        print(f'''Welcome to {colored("MINESWEEPER", "red", "on_cyan")} 1.0!!
Created by {colored('Victor Hugo AIZPURUA', 'red')}
For instructions, type '{colored("I", "blue")}'
To play, type '{colored("P", "green")}'

        ''')

        choice = input("What's your choice?: ").upper()

        if choice == 'I':
            style.clear()
            cprint(open('instructions.txt', 'r').read(), 'blue')
            input('Press [enter] when ready to play. ')
        elif choice != 'P':
            style.clear()
            continue
        while True:
            solution_grid = [[0 for j in range(rows)] for i in range(columns)]
            for n in range (mines):
                placeBomb(solution_grid)
            for row in range(rows):
                for column in range(columns):
                    if solution_grid[row][column] == '*':
                        updateValues(row, column, solution_grid)

            shown_grid = [[' ' for j in range(rows)] for i in range(columns)]
            play(solution_grid, shown_grid, mines)

main()


import sqlite3

conn = sqlite3.connect("vaccitrack-backend.db")
c = conn.cursor()
# Create table - USERS
c.execute(
    """CREATE TABLE USERS
             ([username] text PRIMARY KEY,[name] text,[app_id] text, [password] text,[email_id] text, [timestamp] date)"""
)
c.execute(
    """CREATE TABLE ADMIN
             ([username] text PRIMARY KEY,[name] text,[password] text, [timestamp] date)"""
)
c.execute(
    """ INSERT INTO USERS(username,name,app_id,email_id,password,timestamp)
              VALUES('admin_user','admin',123,'admin@vaccitrack.com','admin@123',123) """
)
conn.commit()


import sys
from pyremapper.remapper import Remapper

# The input value is from 1 to -1, with 0 being centered
# Out of bounds values will be rouned to the nearest valid value
def logarithmic(value):
   import math
   # Log base 10 of 10 is 1 so input values to log should be between 1-10
   in_range_value = (abs(value) * 10) + 1
   if value < 0:
      return math.log(in_range_value, 10) * -1
   else:
      return math.log(in_range_value, 10)

def sigmoid(value):
      return (1.25 * value) / (1 + abs(value))

mapping_functions = [
   {
      'name':     'Logarithmic',
      'function': logarithmic,
   },
   {
      'name':     'Sigmoid',
      'function': sigmoid,
   },
]

if __name__ == '__main__':
   log_file = open('remapper.log', 'w')
   #sys.stdout = log_file
   #sys.stderr = log_file
   remapper = Remapper(mapping_functions = mapping_functions)
   remapper.start()
   log_file.close()


n=int(input())
s=[0]*1000
s[0]=3
cnt=1
while 1:
  s[cnt]=s[cnt-1]+cnt+3+s[cnt-1]
  if s[cnt]>n:
    break
  cnt+=1
answer=['-1','m','o','o']
def recur(now,cnt):
  if cnt==0:
    return answer[now]
  if now<=s[cnt-1]:
    return recur(now,cnt-1)
  elif now>s[cnt-1]+cnt+3:
    return recur(now-s[cnt-1]-cnt-3,cnt-1)
  else:
    if now==s[cnt-1]+1:
      return 'm'
    return 'o'
print(recur(n,cnt))


# -*- coding: utf-8 -*-
"""
fudcon.ui.frontend.utils
~~~~~~~~~~~~~~~~~~~~~~~~
Utils for frontend
"""

import hashlib
import urllib

def avatar_url(username, size=64, default='retro'):
    openid = "http://%s.id.fedoraproject.org/" % username
    return avatar_url_from_openid(openid, size, default)

def avatar_url_from_openid(openid, size=64, default='retro', dns=False):
    if dns:
        import libravatar
        return libravatar.libravatar_url(
            openid=openid,
            size=size,
            default=default,)
    else:
        query = urllib.urlencode({'s': size, 'd': default})
        hash = hashlib.sha256(openid).hexdigest()
        return "https://seccdn.libravatar.org/avatar/%s?/%s" % (hash, query)


"""ファイル操作系共通モジュール
"""
import codecs

# エンコード種類
ENCODING_UTF_8 = 'utf-8'
ENCODING_UTF_8_SIG = 'utf_8_sig'    #Signature UTF8
ENCODING_SHIFT_JIS = 'shift_jis'

# 改行コード種類
NEWLINE_UNIX = '\n'
NEWLINE_WINDOWS = '\r\n'

# エンコードエラーオプション
ENCODING_ERROR_IGNORE = 'ignore'
ENCODING_ERROR_REPLACE = 'replace'

def encode_file(from_file_path,
                to_file_path,
                from_file_encoding=ENCODING_UTF_8,
                to_file_encoding=ENCODING_SHIFT_JIS,
                to_file_newline=NEWLINE_WINDOWS,
                encoding_error_option=ENCODING_ERROR_REPLACE):
    """ファイルの文字コードを変換して出力する。

    Args:
        from_file_path (str): 変換前ファイルパス
        to_file_path (str): 変換後ファイルパス
        from_file_encoding (str): 変換前ファイルの文字コード Defaults to ENCODING_UTF_8.
        to_file_encoding (str): 変換後ファイルの文字コード Defaults to ENCODING_SHIFT_JIS.
        to_file_newline (str): 変換後ファイルの改行コード. Defaults to NEWLINE_WINDOWS.
        encoding_error_option (str): エンコードエラー発生時、"ignore"指定で無視、
                                     "replace"指定で「?」に置換する。 Defaults to ENCODING_ERROR_REPLACE.
    """
    with codecs.open(from_file_path, 'r', encoding=from_file_encoding) as from_file:
        with open(to_file_path, 'w', encoding=to_file_encoding, newline=to_file_newline) as to_file:
            if to_file_encoding == ENCODING_SHIFT_JIS or to_file_encoding == ENCODING_UTF_8_SIG:
                # 出力ファイルがShift-JIS / utf_8_sig の場合
                for row in from_file:
                    to_file.write(row.encode(to_file_encoding, encoding_error_option).decode(to_file_encoding))
            else:
                # 出力ファイルがUTF-8の場合
                for row in from_file:
                    to_file.write(row)


import pendulum
import os
from .helpers.s3_resource import S3_resource
from .helpers.fs_resource import FS_resource

datastores = {
    "S3": S3_resource,
    "filesystem": FS_resource
}

evKeys = [
    "LOCAL_DATA",
    "DATASTORE_NAME",
    "DATASTORE_PATH",
    "TMP_DIR",
    "METRO_LINES",
    "METRO_AGENCY",
    "TIMEZONE",
    "SCHEDULE_URL",
    "VEHICLE_API_URL",
    "LOG_TIMESTAMPS"
]

class Context:
    def __init__(self):
        self.config = {}

        for k in evKeys:
           self.config[k]=os.environ[k]

        self.config["METRO_LINES"] = [int(line) for line in self.config["METRO_LINES"].split(",")]
        self.datastore = datastores[self.config["DATASTORE_NAME"]](self.config["DATASTORE_PATH"])
        self.tmp = FS_resource(self.config["TMP_DIR"])

    def logger(self, stuff, datetime=pendulum.now('UTC')):
        if self.config["LOG_TIMESTAMPS"] == "TRUE":
            print(datetime, stuff, sep=",")
        else:
            print(stuff)


import heapq
import random
from typing import List

from simulator.network_simulator.constants import BITS_PER_BYTE, BYTES_PER_PACKET, EVENT_TYPE_ACK, EVENT_TYPE_SEND
from simulator.network_simulator.packet import Packet
from simulator.network_simulator.link import Link
from simulator.network_simulator.sender import SenderType

USE_LATENCY_NOISE = False
# USE_LATENCY_NOISE = True
MAX_LATENCY_NOISE = 1.01

# DEBUG = True
DEBUG = False

class Network:
    """Network model"""

    def __init__(self, senders: List[SenderType], links: List[Link],
                 record_pkt_log: bool = False):
        self.q = []
        self.cur_time = 0.0
        self.senders = senders
        self.links = links
        self.record_pkt_log = record_pkt_log
        self.pkt_log = []
        self.extra_delays = []  # time used to put packet onto the network
        self.queue_initial_packets()

    def queue_initial_packets(self):
        for sender in self.senders:
            sender.register_network(self)
            sender.reset_obs()

            sender.schedule_send(True)

    def add_packet(self, pkt: Packet) -> None:
        """Add a packet to the packet event queue."""
        heapq.heappush(self.q, pkt)

    def reset(self) -> None:
        self.cur_time = 0.0
        self.q = []
        for link in self.links:
            link.reset()
        for sender in self.senders:
            sender.reset()
        self.queue_initial_packets()
        self.pkt_log = []
        self.extra_delays = []  # time used to put packet onto the network

    def get_cur_time(self) -> float:
        """Return current network time."""
        return self.cur_time

    def run(self, dur: float):
        """Run the network with specified duration."""
        for sender in self.senders:
            sender.reset_obs()
        end_time = min(self.cur_time + dur, self.links[0].trace.timestamps[-1])
        self.extra_delays = []  # time used to put packet onto the network
        while True:
            pkt = self.q[0]
            # pkt.debug_print()
            # use got_data here to make sure aurora receives at least a pkt ack
            # in MI at the beginning of the connection. got_data does not
            # affect other congestion controls
            # if pkt.sender.got_data and pkt.ts >= end_time and pkt.event_type == EVENT_TYPE_SEND:
            if pkt.sender.stop_run(pkt, end_time):
                end_time = pkt.ts
                self.cur_time = end_time
                break
            pkt = heapq.heappop(self.q)

            self.cur_time = pkt.ts
            push_new_event = False

            # if len(self.q) == 0:
            #     self.add_packet(Packet(self.get_cur_time() + 0.001, pkt.sender, 0, 0))
            # if pkt.pkt_size == 0:
            #     continue
            # debug_print("Got %d event %s, to link %d, latency %f at time %f, "
            #             "next_hop %d, dropped %s, event_q length %f, "
            #             "sender rate %f, duration: %f, queue_size: %f, "
            #             "rto: %f, cwnd: %f, ssthresh: %f, sender rto %f, "
            #             "pkt in flight %d, wait time %d" % (
            #                 event_id, event_type, next_hop, cur_latency,
            #                 event_time, next_hop, dropped, len(self.q),
            #                 sender.rate, dur, self.links[0].queue_size,
            #                 rto, sender.cwnd, sender.ssthresh, sender.rto,
            #                 int(sender.bytes_in_flight/BYTES_PER_PACKET),
            #                 sender.pkt_loss_wait_time))
            if pkt.event_type == EVENT_TYPE_ACK:
                sender = pkt.sender
                if pkt.next_hop == len(self.links):
                    # if cur_latency > 1.0:
                    #     sender.timeout(cur_latency)
                    # sender.on_packet_lost(cur_latency)
                    # if sender.rto >= 0 and pkt.cur_latency > sender.rto and sender.pkt_loss_wait_time <= 0:
                    #     sender.timeout()
                    #     pkt.drop()
                    if pkt.dropped:
                        sender.on_packet_lost(pkt)
                        if self.record_pkt_log:
                            self.pkt_log.append(
                                [self.cur_time, pkt.pkt_id, 'lost',
                                 pkt.pkt_size, pkt.cur_latency, pkt.queue_delay,
                                 self.links[0].pkt_in_queue,
                                 sender.pacing_rate * BITS_PER_BYTE,
                                 self.links[0].get_bandwidth(self.cur_time) * BYTES_PER_PACKET * BITS_PER_BYTE,
                                 sender.cwnd, sender.rto])
                    else:
                        sender.on_packet_acked(pkt)
                        if self.record_pkt_log:
                            self.pkt_log.append(
                                [self.cur_time, pkt.pkt_id, 'acked',
                                 pkt.pkt_size, pkt.cur_latency,
                                 pkt.queue_delay, self.links[0].pkt_in_queue,
                                 sender.pacing_rate * BITS_PER_BYTE,
                                 self.links[0].get_bandwidth(self.cur_time) * BYTES_PER_PACKET * BITS_PER_BYTE])
                else:  # in acklink
                    # comment out to save disk usage
                    # if self.record_pkt_log:
                    #     self.pkt_log.append(
                    #         [self.cur_time, pkt.pkt_id, 'arrived',
                    #          pkt.pkt_size, pkt.cur_latency, pkt.queue_delay,
                    #          self.links[0].pkt_in_queue,
                    #          sender.pacing_rate * BITS_PER_BYTE,
                    #          self.links[0].get_bandwidth(self.cur_time) * BYTES_PER_PACKET * BITS_PER_BYTE,
                    #          sender.cwnd, sender.rto])
                    link_prop_latency = self.links[pkt.next_hop].get_cur_propagation_latency(
                        self.cur_time)
                    # link_latency *= self.env.current_trace.get_delay_noise_replay(self.cur_time)
                    # if USE_LATENCY_NOISE:
                    # link_latency *= random.uniform(1.0, MAX_LATENCY_NOISE)
                    # TODO: add delay noise of acklink
                    pkt.add_propagation_delay(link_prop_latency)
                    #
                    # rand = random.uniform(0, 1)
                    # if rand > 0.75:
                    #     noise = abs(random.uniform(0.0, 200) / 1000)
                    #     pkt.add_propagation_delay(noise)
                    pkt.next_hop += 1
                    push_new_event = True
            elif pkt.event_type == EVENT_TYPE_SEND:  # in datalink
                sender = pkt.sender
                if pkt.next_hop == 0:
                    if sender.on_packet_sent(pkt):
                        if self.record_pkt_log:
                            self.pkt_log.append(
                                [self.cur_time, pkt.pkt_id, 'sent',
                                 pkt.pkt_size, pkt.cur_latency,
                                 pkt.queue_delay, self.links[0].pkt_in_queue,
                                 sender.pacing_rate * BITS_PER_BYTE,
                                 self.links[0].get_bandwidth(self.cur_time) * BYTES_PER_PACKET * BITS_PER_BYTE,])
                        push_new_event = True
                    else:
                        continue
                else:
                    push_new_event = True

                if pkt.next_hop == sender.dest:
                    pkt.event_type = EVENT_TYPE_ACK

                # print(pkt.next_hop, pkt.pkt_id, q_delay, self.links[pkt.next_hop].pkt_in_queue)
                # if USE_LATENCY_NOISE:
                # link_latency *= random.uniform(1.0, MAX_LATENCY_NOISE)
                # link_latency += self.env.current_trace.get_delay_noise(
                #     self.cur_time, self.links[pkt.next_hop].get_bandwidth(self.cur_time)) / 1000
                # link_latency *= self.env.current_trace.get_delay_noise_replay(self.cur_time)
                # rand = random.uniform(0, 1)
                # if rand > 0.9:
                #     noise = random.uniform(0.0, self.links[pkt.next_hop].trace.delay_noise) / 1000
                #     pkt.add_propagation_delay(noise)
                # pkt.add_transmission_delay(1 / self.links[0].get_bandwidth(self.cur_time))
                if not self.links[pkt.next_hop].packet_enters_link(self.cur_time):
                    pkt.drop()
                link_prop_latency, q_delay = self.links[pkt.next_hop].get_cur_latency(
                    self.cur_time)
                pkt.add_propagation_delay(link_prop_latency)
                pkt.add_queue_delay(q_delay)
                self.extra_delays.append(
                    1 / self.links[pkt.next_hop].get_bandwidth(self.cur_time))
                pkt.next_hop += 1
                # if not pkt.dropped:
                #     sender.queue_delay_samples.append(new_event_queue_delay)

            if push_new_event:
                heapq.heappush(self.q, pkt)
        return


import my_io
import io

# ugliest code ever writter, probably

input = my_io.get_clipboard_contents()

uniques = set()

lines = input.splitlines()

template = lines[0]

for c in template:
    uniques.add(c)

rules = dict()

for i in range(2, len(lines)):

    (key, value) = lines[i].split(' -> ')
    rules[key] = value

    (k1, k2) = key
    uniques.add(k1)
    uniques.add(k2)
    uniques.add(value)

replacements = dict()

# generate replacements from 0-10 steps

for key in rules:

    replacement = rules[key]

    seq = key

    reps = 21 * [None]

    reps[0] = seq

    for i in range(1, 11):

        next_index = 0

        while next_index < len(seq) - 1:

            pair = seq[next_index:next_index + 2]
            replacement = rules[pair]

            if pair in rules:
                seq = seq[:next_index + 1] + \
                    replacement + seq[next_index + 1:]
                next_index += 2
            else:
                next_index += 1

        reps[i] = seq

    replacements[key] = reps

# generate replacements for 20 steps

for key in rules:

    reps = replacements[key]

    seq = reps[10]

    buff = io.StringIO()

    for j in range(0, len(seq) - 1):

        pair = seq[j:j+2]
        rep = replacements[pair][10]

        buff.write(rep[:len(rep)-1])

    buff.write(rep[-1:])

    reps[20] = buff.getvalue()

template20 = ''

for i in range(0, len(template) - 1):

    pair = template[i:i+2]
    rep = replacements[pair][20]

    template20 += rep[:len(rep) - 1]
template20 += rep[-1:]

hits = dict()

hits_dict = dict()

for key in rules:

    hits_dict[key] = dict()

    for k in uniques:
        hits_dict[key][k] = 0

    rep = replacements[key][20]

    for i in range(0, len(rep) - 1):

        c = rep[i]
        hits_dict[key][c] += 1

hits = dict()

for k in uniques:
    hits[k] = 0

for i in range(0, len(template20) - 1):

    pair = template20[i: i+2]
    hits20 = hits_dict[pair]

    for k in uniques:
        hits[k] += hits20[k]

hits[template20[len(template20) - 1]] += 1

print(hits)


#!/usr/bin/python
# This code will provide a python function that will return an ordered
# list of distinct rotation systems for an n flower given n as an input.

# Need to make all the rotations 0 based. First vertex is labeled 0
# and first edge is labeled 0.

# This function rotates a list to the left by n thus, term n becomes
# term 0, term m becomes term m - n and term 0 becomes term len - n.
def rotate(inputList,n):
	List1 = inputList[0:n];
	List2 = inputList[n:len(inputList)];
	List2.extend(List1);
	return List2;

# Temporarily defined variable to see the number of each genus for
# each flower.
totalCount = 0;
ourGenus = 2;

# We begin by writing a function to place a rotation system in proper
# form. We define "proper form" in such a way that two rotation systems
# on a flower are equivalent iff their proper form representations are
# identical.

def makeProper(inputList):
	temp = min(inputList);
	# mins will be an array holding all minimum indexes of inputList
	mins = [];
	for i in range(0,len(inputList)):
		if (inputList[i] == temp):
			mins.append(i);
	# proper form has the smallest interval in the front thus any
	# rotation of the rotation system with one of the mins at the
	# beginning may be the proper form.
	properForm = inputList;
	for i in range(0,len(mins)):
		temp2 = rotate(inputList,mins[i]);
		for j in range(0,len(temp2)):
			if (properForm[j] > temp2[j]):
				properForm = temp2;
				break;
			if (properForm[j] < temp2[j]):
				break;
	# print properForm;
	return properForm;

# The following function converts a rotation system to a gap sequence
# representation.
def rottogap(inputList):
	temp = [0]*len(inputList);
	for i in range(0,len(inputList)):
		if (temp[i] == 0):
			for j in range(i+1,len(inputList)):
				if (inputList[j] == inputList[i]):
					temp2 = j - i;
					break;
			temp[i] = temp2;
			temp[i+temp2] = len(inputList) - temp2;
	# print temp;
	return temp;

# The following function converts a gap sequence representation to a
# rotation system.
def gaptorot(inputList):
	temp = [0]*len(inputList);
	current = 1;
	for i in range(0,len(inputList)):
		if (temp[i] == 0):
			temp[i] = current;
			temp[i+inputList[i]] = current;
			current = current+1;
	# print temp;
	return temp;

# Transforms a rotation to a reduced gap sequence representation.
def rottoredgap(inputList):
	newList = inputList[:];
	temp = [];
	for i in range(0,len(newList)):
		if (newList[i] != -1):
			for j in range(i+1,len(newList)):
				if (newList[j] == newList[i]):
					temp.append(j - i);
					newList[j] = -1;
					newList[i] = -1;
					break;
	# print temp;
	return temp;

# Transforms a gap representation of a rotation system to a reduced gap
# representation.
def gaptoredgap(inputList):
	newList = inputList[:];
	temp = [];
	for i in range(0,len(newList)):
		if (newList[i] != 0):
			temp.append(newList[i]);
			newList[i + newList[i]] = 0;
			newList[i] = 0;
	# print temp;
	return temp;

# Transforms a reduced gap to a rotation system
def redgaptorot(inputList):
	rotation = [0]*(len(inputList)*2);
	current = 0;
	index = 1;
	for i in range(0, len(inputList)):
		while (rotation[current] != 0):
			current += 1;
		rotation[current] = index;
		rotation[current+inputList[i]] = index;
		index += 1;
	# print rotation;
	return rotation;

# Transforms a reduced gap sequence to a gap sequence
def redgaptogap(inputList):
	gap = [0]*(len(inputList)*2);
	current = 0;
	for i in range(0,len(inputList)):
		while (gap[current] != 0):
			current += 1;
		gap[current] = inputList[i];
		gap[current + gap[current]] = 2*len(inputList) - gap[current];
	# print gap;
	return gap;

# The following function is the first tricky function employed for the
# overall purpose of finding all rotation systems seperating a given
# genus surface. The input of this function is an integer that is 2*n
# where n is the number of leaves of the flower graph under consideration.
# The function below will traverse the tree of all possible rotation
# systems of the n flower and print them out. What makes this function so
# tricky is it has both iterative and recursive components. Also, we are
# able to prune the tree with our code which also serves to obfuscate the
# code. The search is of rotation systems in reduced gap form because
# this form provides us with initially the smallest number of
# possibilities. Nevertheless some of the rotation systems returned are
# repeats.
class AllRots(object):
    def __init__(*arg):
        self = arg[0]
        self.genus = ourGenus
        if arg[1]:
            flowerNum = arg[1];
        if arg[2]:
            self.genus = arg[2];
        self.current = [0]*flowerNum;
        self.current[0] = 1;
        self.totalCount = 0;
        self.flowerNum = flowerNum;
        self.genusCalc = [0]*4*flowerNum;
        self.minSorted = [];
        for j in range(0, (flowerNum + 1)/2):
   	    # This is going to be a smallest to largest gap
	    # depth first search. So we will initialize the
	    # rotation vector as such.
            self.current[0] = 1 + j*2;
            level = 1;
            self.number = j + 1;
            rotation = [0]*2*flowerNum;
            rotation[0] = 1;
            rotation[self.current[0]] = 1;
            spot = 0;
            self.findAllRedGap(rotation,spot,level);
	# Now we will define a recursive subfunction. We will want
	# rotation, and spot to update recursively,
	# but number, current, and level to update iteratively.
        def findAllRedGap(self,rotation, spot,level):
            newrot = rotation[:];
            if (level == len(self.current)):
                # We are done, we print the results. To be
                # replaced with our main logic.
                #print self.current;
                finalTemp = redgaptogap(self.current);
                if (self.getGenus(finalTemp) == self.genus):
                    self.totalCount += 1;
                    self.minSorted.append(makeProper(finalTemp));
                    return;
            # Here we will attempt to increment the current level
            temp = self.current[0];
            while (newrot[spot] != 0):
                spot += 1;
            while ((temp <= self.flowerNum*2 - self.current[0])and(spot + temp < len(newrot))and(newrot[spot+temp] != 0)):
                temp += 2;
            if (temp + spot < len(newrot)):
                newrot[spot] = 1;
                newrot[spot + temp] = 1;
                self.number = 1;
                self.current[level] = temp;
                level += 1;
                self.findAllRedGap(newrot,spot,level);
            else :
                return;
            for i in range(0,len(self.current) - level):
                # Here we will attempt to increment number
                if (level + self.number - 1 == len(self.current)):
                    self.number = 1;
                    return;
                temp = self.current[level - 1] + 2;
                self.number += 1;
                newrot[spot + self.current[level - 1]] = 0;
            while (spot + temp < len(newrot))and(newrot[spot + temp] != 0):
                temp += 2;
                if (spot + temp < len(newrot)):
                    self.current[level - 1] = temp;
                    newrot[spot + temp] = 1;
                    self.findAllRedGap(newrot,spot,level);
                else:
                    return;

    # converts a Gap sequence to a long in base 2*flowernumber. This is to
    # facilitate the sorting mechanism. We will try this for now, if this doesn't
    # work, we will make our very own indexed list data structure.
    # Sorts the results and removes duplicates
    def sortResults(self):
        newResults = [];
        self.minSorted = sorted(self.minSorted);
        for i in range(0,len(self.minSorted)):
            if (i == len(self.minSorted) - 1) or (cmp(self.minSorted[i],self.minSorted[i+1]) != 0):
                newResults.append(self.minSorted[i]);
            self.minSorted = newResults;

    def getGenus(self, gapSeq):
        genus = 0;
        current = 1;
        for k in range(0,self.flowerNum*4):
            if ( k % 2 == 0):
                self.genusCalc[k] = gapSeq[k/2];
            else :
                self.genusCalc[k] = 0;
            while current < 4*self.flowerNum:
                cycle = current;
                while self.genusCalc[cycle] == 0:
                    self.genusCalc[cycle] = 1;
                    cycle = (cycle + (self.genusCalc[(cycle+1)%(4*self.flowerNum)]+1)*2)%(4*self.flowerNum);
                genus += 1;
                while (current < 4*self.flowerNum) and (self.genusCalc[current] != 0):
                    current += 2;
        return (self.flowerNum - 1 + genus)/2 -1;

input = [0,2,3,0,5,3,2,4,4,5];
print("Proper");
makeProper(input);
print("rotation to gap");
rottogap(input);
print("rotation to reduced gap");
rottoredgap(input);
print("rotation to gap to reduced gap");
gaptoredgap(rottogap(input));
print("rotation to gap to proper to rotation");
gaptorot(makeProper(rottogap(input)));
print("rotation to reduced gap to rotation");
redgaptorot(rottoredgap(input));
print("rotation to reduced gap to gap to rotation");
gaptorot(redgaptogap(rottoredgap(input)));
print("Starting chaos:");
#myFlower = AllRots(12);
#myFlower.sortResults();
#print len(myFlower.minSorted);


import json
from typing import Dict, List, Tuple
import re

from chatbot.system_messages.system import (
    function_res_agent,
    base_system_message,
    )
from chatbot.agents.function_mapper import FunctionMapper
from chatbot.agents.function_call_agent import FunctionCallAgent
from chatbot.agents.base_agent import RegularAgent
from chatbot.agents.function_response_agent import function_response_agent
from chatbot.agents.anthropic_base import AnthropicAgent

function_mapper = FunctionMapper()
fc = FunctionCallAgent()
ra = RegularAgent()
aa = AnthropicAgent()
function_call_agent = fc.call
regular_agent = ra.call
anthropic_agent = aa.call

def get_command(prompt):
    """Extract command from prompt if it exists"""
    match = re.search(r"/\w+", prompt)
    if match:
        return match.group(0)
    return None

def call_function(function_name, function_args):
    if function_name not in function_mapper.function_map:
        raise Exception(f"Function {function_name} not found.")
    if function_args is None:
        return function_mapper.function_map[function_name]()
    return function_mapper.function_map[function_name](*function_args.values())

def run_conversation(prompt: str, conversation: List[Dict[str, str]]) -> Tuple[str, List[Dict[str, str]], int, float]:
    agents = function_mapper.agents
    command = get_command(prompt)
    if command in agents:
        agent_properties = agents[command]
        prompt = prompt[agent_properties["command_length"]:].strip()
        if agent_properties["is_function"]:
            print(agent_properties["name"])
            response = function_call_agent(
                prompt=prompt,
                conversation=conversation,
                system_message=agent_properties["agent"].system_message,
                function_params=agent_properties["agent"].function_params,
                temperature=agent_properties["agent"].temperature,
                top_p=agent_properties["agent"].top_p,
                frequency_penalty=agent_properties["agent"].frequency_penalty,
                model=agent_properties["agent"].model,
            )
            message = response[0]

        else:
            print(agent_properties["name"])
            response = regular_agent(
                prompt=prompt,
                conversation=conversation,
                system_message=agent_properties["system_message"],
                stream=True,
            )
            return response

    elif command == "/claude":
        print('Anthropic')
        prompt = prompt[len(command):].strip()
        response = anthropic_agent(
            prompt=prompt,
            conversation=conversation,
            stream=True
            )
        return response
    else:
        print('Personal Assistant')
        response = regular_agent(
            prompt=prompt,
            conversation=conversation,
            system_message=base_system_message,
            stream=True
            )
        return response

    if message.get("function_call"):
        function_name = message["function_call"]["name"]
        function_args = json.loads(message["function_call"]["arguments"])
        print(f"Function name: {function_name}")
        print(f"Function arguments: {function_args}")

        function_response = call_function(function_name, function_args)
        if function_name in function_mapper.functions_that_append_to_conversation:
            print(f"Function response: {function_response}")
            conversation.append({
                "role": "assistant",
                "content": function_response,  # directly add function response to the conversation
            })
            return function_response
        else:
            print(f"Function response: {function_response}")
            second_response = function_response_agent(
                prompt=prompt,
                system_message=function_res_agent,
                function_name=function_name,
                function_response=function_response,
                message=message,
                stream=True
                )
            return second_response


'''
    This file is part of RandomGameGenerator.

    RandomGameGenerator is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    RandomGameGenerator is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with RandomGameGenerator.  If not, see <http://www.gnu.org/licenses/>.
'''

from os import path as ospath

from libraries.rggQt import QDockWidget, QWidget, QGridLayout, Qt, QPushButton, QTextEdit, QLabel
from libraries.rggSystem import signal
from libraries.rggDialogs import banDialog
from libraries.rggConstants import BASE_STRING, SAVE_DIR

class scratchPadWidget(QDockWidget):
	"""A mutually-editable shared text widget."""

	def __init__(self, mainWindow):
		"""Initializes the user list."""
		super(QDockWidget, self).__init__(mainWindow)
		self.setWindowTitle(self.tr("Scratch Pad"))
		self.widget = QWidget(mainWindow)
		self.textArea = QTextEdit(mainWindow)
		self.currentEditingLabel = QLabel("No one is editing.")
		self.getLockButton = QPushButton("Edit")
		self.releaseLockButton = QPushButton("Confirm")
		#self.saveToFileButton = QPushButton("Save...")
		#self.loadButton = QPushButton("Load")
		self.layout = QGridLayout()
		self.layout.addWidget(self.currentEditingLabel, 0, 0, 1, 2)
		self.layout.addWidget(self.textArea, 1, 0, 1, 2)
		self.layout.addWidget(self.getLockButton, 2, 0)
		self.layout.addWidget(self.releaseLockButton, 2, 1)
		self.releaseLockButton.pressed.connect(self._releaseLock)
		self.getLockButton.pressed.connect(self._getLock)
		self.widget.setLayout(self.layout)
		self.setWidget(self.widget)
		self.setObjectName("Scratch Pad Widget")
		self.hasLock = False
		self.updateButtonStatus()
		try:
			with open(ospath.join(SAVE_DIR, "scratchpad.txt"), 'r') as autosave:
				self.textArea.setText(autosave.read())
		except:
			pass
		mainWindow.addDockWidget(Qt.BottomDockWidgetArea, self)

	@property
	def currentText(self):
		return self.textArea.toPlainText()

	def updateButtonStatus(self):
		self.getLockButton.setEnabled(not self.hasLock)
		self.textArea.setReadOnly(not self.hasLock)
		self.releaseLockButton.setEnabled(self.hasLock)

	def _getLock(self):
		self.getScratchPadLock.emit()

	def _releaseLock(self):
		self.updateScratchPad.emit()
		self.releaseScratchPadLock.emit()

	def getLock(self):
		self.hasLock = True
		self.updateButtonStatus()

	def releaseLock(self, name):
		self.hasLock = False
		if name:
			self.currentEditingLabel.setText("%s is editing." % name)
		else:
			self.currentEditingLabel.setText("No one is editing.")
		self.updateButtonStatus()

	def updateText(self, txt):
		if len(txt) > 100000:
			print("Excessively long scratchpad data received. Might be an attack or just a bug.")
			return
		self.textArea.setText(txt)
		try:
			with open(ospath.join(SAVE_DIR, "scratchpad.txt"), 'w') as autosave:
				autosave.write(txt)
		except:
			pass

	getScratchPadLock = signal(doc=
		"""Called to request lock for scratch pad."""
	)

	releaseScratchPadLock = signal(doc=
		"""Called to indicate relinquishment of scratch pad lock."""
	)

	updateScratchPad = signal(doc=
		"""Called to request that the scratchpad be updated."""
	)


# -*- coding:utf-8 -*-
# Created by LuoJie at 11/23/19

from utils.config import save_wv_model_path, vocab_path
import tensorflow as tf
from utils.gpu_utils import config_gpu
from tensorflow.keras.models import Model
import tensorflow as tf
from utils.wv_loader import load_embedding_matrix, Vocab

class Encoder(tf.keras.Model):
    def __init__(self,  embedding_matrix,enc_units, batch_sz):
        super(Encoder, self).__init__()
        self.batch_sz = batch_sz
        self.enc_units = enc_units
        vocab_size, embedding_dim =  embedding_matrix.shape
        self.embedding =tf.keras.layers.Embedding(vocab_size, embedding_dim,
                                                  trainable = True)

        self.lstm = tf.keras.layers.LSTM(self.enc_units,
                                       return_sequences=True,
                                       return_state=True,
                                       recurrent_initializer='glorot_uniform')
        self.bilstm = tf.keras.layers.Bidirectional(self.lstm)
        #self.W_h = tf.keras.layers.Dense(self.enc_units*2)
        #默认是concat
    def call(self, x):
        # code
        x = self.embedding(x)
        #output shape = batch, max_enc_len, 2*hidden_dim
        output, forward_state,f_cell_state, backward_state,b_cell_state = self.bilstm(x)
        #print("cell shape is {}".format(cell_state.shape))
        hidden_state = tf.keras.layers.concatenate([forward_state, backward_state], axis=-1)
        cell_state = tf.keras.layers.concatenate([f_cell_state, b_cell_state], axis=-1)
        state = [hidden_state, cell_state]
        #enc_features shape == (batch_size*max_len, 2*enc_units)
        #enc_features = tf.reshape(output, (-1,2*self.enc_units))
        #enc_features = self.W_h(enc_features)
        #output= self.bilstm(x)

        return output, state

    # def initialize_hidden_state(self):
    #     return tf.zeros(shape = [self.batch_sz, self.enc_units])
class ReduceState(tf.keras.Model):
    def __init__(self,enc_units,):
        super(ReduceState, self).__init__()
        self.reduce_h = tf.keras.layers.Dense(enc_units, activation = tf.keras.activations.relu)
            #nn.Linear(config.hidden_dim * 2, config.hidden_dim)
        self.reduce_c = tf.keras.layers.Dense(enc_units,activation =tf.keras.activations.relu)
            #nn.Linear(config.hidden_dim * 2, config.hidden_dim)

    def call(self, state):
        # h, c dim = [ batch, 2*enc_units]
        h, c = state

        hidden_reduced_h = self.reduce_h(h)

        hidden_reduced_c = self.reduce_c(c)

        # h, c dim = [1, batch, hidden_dim]
        return hidden_reduced_h, hidden_reduced_c

def masked_attention(enc_padding_mask, score):
    """Take softmax of e then apply enc_padding_mask and re-normalize"""
    #attn_dist shape = batch_size, max_len,1
    attn_dist = tf.squeeze(score, axis=2)
    attn_dist = tf.nn.softmax(attn_dist) #shape = (batch_size, max_len)
    mask = tf.cast(enc_padding_mask, dtype=attn_dist.dtype)
    attn_dist *= mask  # apply mask
    masked_sums = tf.reduce_sum(attn_dist, axis=1)  # shape (batch_size)
    attn_dist = attn_dist / tf.reshape(masked_sums, [-1, 1])  # re-normalize
    attn_dist = tf.expand_dims(attn_dist, axis=2)
    return attn_dist #shape batch_size, max_len,1

class BahdanauAttention(tf.keras.layers.Layer):
    def __init__(self, units):
        super(BahdanauAttention, self).__init__()
        self.W_s = tf.keras.layers.Dense(2*units)
        self.W_h = tf.keras.layers.Dense(2*units)
        self.W_c = tf.keras.layers.Dense(2*units)
        self.V = tf.keras.layers.Dense(1)

    def __call__(self, dec_hidden, enc_output, enc_pad_mask, use_coverage=False, prev_coverage=None):
        """
         calculate attention and coverage from dec_hidden enc_output and prev_coverage
         one dec_hidden(word) by one dec_hidden
         dec_hidden or query is [batch_sz, enc_unit], enc_output or values is [batch_sz, max_train_x, enc_units],
         prev_coverage is [batch_sz, max_len_x, 1]
         dec_hidden is initialized as enc_hidden, prev_coverage is initialized as None
         output context_vector [batch_sz, enc_units] attention_weights & coverage [batch_sz, max_len_x, 1]
         """
        # hidden shape == (batch_size, hidden size)
        # hidden_with_time_axis shape == (batch_size, 1, hidden size)
        # we are doing this to perform addition to calculate the score
        #dec_hidden  shape = (batch_size, 2*dec_units)
        hidden_with_time_axis = tf.expand_dims(dec_hidden, 1)

        if use_coverage and prev_coverage is not None:
            # Multiply coverage vector by w_c to get coverage_features.
            # self.W_s(values) [batch_sz, max_len, units] self.W_h(hidden_with_time_axis) [batch_sz, 1, 2*units]
            # self.W_c(prev_coverage) [batch_sz, max_len, 2*units]  score [batch_sz, max_len, 1]
            score = self.V(tf.nn.tanh(self.W_s(enc_output) + self.W_h(hidden_with_time_axis) + self.W_c(prev_coverage)))
            # attention_weights shape (batch_size, max_len, 1)

            # attention_weights shape== (batch_size, max_length, 1)
            #mask = tf.cast(enc_pad_mask, dtype=score.dtype)

            ##attention_weights = tf.nn.softmax(score, axis=1)
            attention_weights = masked_attention(enc_pad_mask, score)
            coverage = attention_weights + prev_coverage
        else:
            # score shape == (batch_size, max_length, 1)
            # we get 1 at the last axis because we are applying score to self.V
            # the shape of the tensor before applying self.V is (batch_size, max_length, units)
            # 计算注意力权重值
            score = self.V(tf.nn.tanh(
                self.W_s(enc_output) + self.W_h(hidden_with_time_axis)))

            # mask = tf.cast(enc_pad_mask, dtype=score.dtype)
            # masked_score = tf.squeeze(score, axis=-1) * mask
            # masked_score = tf.expand_dims(masked_score, axis=2)
            # attention_weights = tf.nn.softmax(masked_score, axis=1

            attention_weights = masked_attention(enc_pad_mask, score)
            if use_coverage:
                coverage = attention_weights
            else:
                coverage = []

        # # 使用注意力权重*编码器输出作为返回值，将来会作为解码器的输入
        # context_vector shape after sum == (batch_size, 2*hidden_dim)
        context_vector = attention_weights * enc_output
        context_vector = tf.reduce_sum(context_vector, axis=1)
        attention_weights = tf.squeeze(attention_weights, -1) #转换为 batch_size, max_len

        return context_vector, attention_weights, coverage
class Decoder(tf.keras.Model):
    def __init__(self, embedding_matrix, dec_units, attn_units, batch_sz, ):
        super(Decoder, self).__init__()
        self.batch_sz = batch_sz
        self.dec_units = dec_units
        vocab_size, embedding_dim = embedding_matrix.shape
        self.attention = BahdanauAttention(attn_units)
        self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim, weights=[embedding_matrix],
                                                   trainable=True)

        self.lstm = tf.keras.layers.LSTM(dec_units,
                                       return_sequences=True,
                                       # whether to return the last output sequence, or the full sequence
                                       return_state=True,  # whether to return the last state in additon to output
                                       recurrent_initializer='glorot_uniform')
        self.x_context = tf.keras.layers.Dense(embedding_dim)
        self.fc1 = tf.keras.layers.Dense(dec_units)
        self.fc2 = tf.keras.layers.Dense(vocab_size, activation=tf.keras.activations.softmax)
    def __call__(self, dec_input, hidden_state, enc_output,enc_pad_mask,
                context_vector_last, use_coverage,prev_coverage):
        #hidden_state 输入lstm的hidden_state
        #context_vector 上下文词向量 batch_size,enc_units*2

        x = self.embedding(dec_input)  # x的结果shape  =(batch_size, 1,embedding_dim)
        # 与 attention合并
        x = tf.concat([tf.expand_dims(context_vector_last, axis=1), x],
                      axis=-1)  # shape= (batch_size, 1, 2*enc_hidden_size+ embedding_dim)
        x = self.x_context(x) #重新映射为 embeding_dim

        output, hidden_state, cell_state = self.lstm(x,initial_state=hidden_state)

        # dec_state shape = 2* (batch_size,1*dec_units)
        dec_state  = [hidden_state, cell_state]
        #求本轮context_vector

        dec_state_concat = tf.concat([hidden_state, cell_state], axis =-1)
        context_vector, attentions, coverage_ret = self.attention(dec_state_concat,
                                                                  enc_output,
                                                                  enc_pad_mask,
                                                                  use_coverage,
                                                                  prev_coverage)
        #print("context vector shape", context_vector.shape)

        output = tf.reshape(output, (-1, output.shape[2]))  #batch_size, dec_units
       # 按照作者做法再与context_vector 合并  可加快训练速度
        output = tf.concat([output, context_vector], axis = -1)  #batch_size, dec_hidden_size +2*enc_units
        output = self.fc1(output)
        prediction = self.fc2(output)
        #prediction 维度 batch_size,vocab_size

        return x, prediction, dec_state,context_vector,attentions,coverage_ret

class Pointer(tf.keras.layers.Layer):

    def __init__(self):
        super(Pointer, self).__init__()
        self.w_s_reduce = tf.keras.layers.Dense(1)
        self.w_i_reduce = tf.keras.layers.Dense(1)
        self.w_c_reduce = tf.keras.layers.Dense(1)

    def call(self, context_vector, dec_hidden, dec_inp):
        #context_vector 为当前context_vector
        dec_hidden = tf.concat([dec_hidden[0], dec_hidden[1]], axis =-1)  #batch_size, 2*dec_units
        dec_inp = tf.squeeze(dec_inp, axis =1 ) #转换为 （batch_size, embedding_size)
        return tf.nn.sigmoid(self.w_s_reduce(dec_hidden) + self.w_c_reduce(context_vector) +
                             self.w_i_reduce(dec_inp))
    #shape= batch_size, 1

if __name__ == '__main__':
    # GPU资源配置
    config_gpu()
    # 读取vocab训练
    vocab = Vocab(vocab_path)
    # 计算vocab size
    vocab_size = vocab.count

    # 使用GenSim训练好的embedding matrix
    embedding_matrix = load_embedding_matrix()

    enc_max_len = 200
    dec_max_len = 41
    batch_size = 16
    embedding_dim = 300
    units = 128
    context_vector_last = tf.zeros(shape = (batch_size,2*units))
    # 编码器结构
    encoder = Encoder( embedding_matrix, units, batch_size)
    # encoder input
    enc_inp = tf.ones(shape=(batch_size, enc_max_len), dtype=tf.int32)
    # decoder input
    dec_inp = tf.ones(shape=(batch_size, dec_max_len), dtype=tf.int32)
    # enc pad mask
    enc_pad_mask = tf.ones(shape=(batch_size, enc_max_len), dtype=tf.int32)

    # encoder hidden
   # enc_hidden = encoder.initialize_hidden_state()

    enc_output, enc_hidden = encoder(enc_inp)
    # 打印结果
    print('Encoder output shape: (batch size, sequence length, units) {}'.format(enc_output.shape))
    print('Encoder Hidden state shape: (batch size, units) {}'.format(enc_hidden[0].shape))
    #
    reduce_state = ReduceState(units)
    enc_hidden = reduce_state(enc_hidden)
    # attention_layer = BahdanauAttention(units)
    # context_vector, attention_weights, coverage = attention_layer(enc_hidden, enc_output, enc_pad_mask)
    #
    # print("Attention context_vector shape: (batch size, units) {}".format(context_vector.shape))
    # print("Attention weights shape: (batch_size, sequence_length, 1) {}".format(attention_weights.shape))
    # print("Attention coverage: (batch_size, ) {}".format(coverage))

    decoder = Decoder( embedding_matrix, units,units, batch_size)

    dec_x, dec_out, dec_hidden, context_vector, attentions, coverage_ret= decoder(tf.random.uniform((batch_size, 1)),
                                          enc_hidden,enc_output,enc_pad_mask,
                                          context_vector_last, True, None)
    print('Decoder output shape: (batch_size, vocab size) {}'.format(dec_out.shape))
    print('Decoder dec_x shape: (batch_size, 1,embedding_dim + units) {}'.format(dec_x.shape))
    print("decoder dec_hidden shape:{}".format(dec_hidden[0].shape))
    print("context_vector shape:{}".format(context_vector.shape))
    pointer = Pointer()
    p_gen = pointer(context_vector, dec_hidden, dec_x)
    print('Pointer p_gen shape: (batch_size,1) {}'.format(p_gen.shape))


from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

import numpy as np
import pandas as pd

import sklearn.preprocessing as pro
from sklearn.preprocessing import LabelEncoder

import func as func

if __name__ == '__main__':
    # load data
    df1 = pd.read_table('.\data\Accelerometer_climb_descent_stairs\climb_stairs.txt', sep=' ', header=None)
    df2 = pd.read_table('.\data\Accelerometer_climb_descent_stairs\descend_stairs.txt', sep=' ', header=None)
    df1.columns = ['x','y','z']
    df2.columns = ['x','y','z']
    df1['ADL'] = 'climb_stairs'
    df2['ADL'] = 'descend_stairs'
    df = df1.append(df2)
    df = df.reset_index(drop=True)

    data = df.loc[:, ['x', 'y', 'z']]
    class_labels = df.loc[:, ['ADL']]
    true_labels = LabelEncoder().fit_transform(class_labels)

    min_max_scaler = pro.MinMaxScaler()  # normalization to [0,1]
    data = min_max_scaler.fit_transform(data)

    # clustering : K-means & DBSCAN
    k_means_pred = KMeans(n_clusters=2, random_state=128).fit_predict(data)

    # determine the parameters (Eps, minPts) for DBSCAN
    from sklearn.neighbors import NearestNeighbors
    nbrs = NearestNeighbors(n_neighbors=5).fit(data)
    distances, _ = nbrs.kneighbors(data)
    distanceDec = sorted(distances[:, 4], reverse=False)
    indices = range(len(distanceDec))
    plt.plot(indices, distanceDec)
    plt.show()
    dbscan_pred = DBSCAN(eps=0.11, min_samples=5).fit_predict(data)

    # compute evaluation criteria: DBI,SC,MI,NMI,AMI
    print("Class Label")
    func.cal_int_ind(data, true_labels)

    print("K-means")
    func.cal_int_ind(data, k_means_pred)
    func.cal_ext_ind(true_labels, k_means_pred)

    print("DBSCAN")
    func.cal_int_ind(data, dbscan_pred)
    func.cal_ext_ind(true_labels, dbscan_pred)

    # plot clustering result
    y_pred = pd.DataFrame(dbscan_pred)

    dt_0 = data[class_labels['ADL'] == 'climb_stairs']
    y_pred_0 = y_pred[class_labels['ADL'] == 'climb_stairs']
    dt_1 = data[class_labels['ADL'] == 'descend_stairs']
    y_pred_1 = y_pred[class_labels['ADL'] == 'descend_stairs']

    fig = plt.figure()
    ax = Axes3D(fig)

    ax.set_ylim(0, 0.9)
    ax.set_zlim(0, 0.9)
    ax.view_init(elev=40.,azim=135)

    color_0 = func.cal_col(np.array(y_pred_0))
    color_1 = func.cal_col(np.array(y_pred_1))
    ax.scatter(dt_0[:, 0], dt_0[:, 1], dt_0[:, 2], c=color_0, s=50, marker='^')
    ax.scatter(dt_1[:, 0], dt_1[:, 1], dt_1[:, 2], c=color_1, s=80, marker='.')
    #plt.legend(labels=['climb_stairs', 'descend_stairs'], loc=1, prop={'size': 15})

    ax.set_xticklabels([])  # remove the tick mark of x axis
    ax.set_yticklabels([])  # remove the tick mark of y axis
    ax.set_zticklabels([])  # remove the tick mark of z axis

    font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 20,
             }
    ax.set_xlabel('x', fontdict=font2)
    ax.set_ylabel('y', fontdict=font2)
    ax.set_zlabel('z', fontdict=font2)
    #plt.savefig('results/Accelerometer_climb_descent_stairs/DBSCAN_0.010_5.png', dpi=1024)
    plt.show()


'''
Main program to perform the ETL on the Redshift cluster
'''

import configparser
import psycopg2
from sql_queries import copy_table_queries, insert_table_queries

def load_staging_tables(cur, conn):

    '''
    FUNCTION:   load_staging_tables
    PURPOSE:    Runs SQL queries to copy staging tables from S3
    INPUT:      cur:    a specified cursor on Redshift cluster
                conn:   a specified connection to Redshift cluster
    OUTPUT:     None
    '''

    for query in copy_table_queries:
        cur.execute(query)
        conn.commit()

        print('Executing query: {}'.format(query))

def insert_tables(cur, conn):

    '''
    FUNCTION:   insert_tables
    PURPOSE:    Runs SQL queries to insert values into specified tables
    INPUT:      cur:    a specified cursor on Redshift cluster
                conn:   a specified connection to Redshift cluster
    OUTPUT:     None
    '''

    for query in insert_table_queries:
        cur.execute(query)
        conn.commit()

        print('Executing query: {}'.format(query))

def main():

    '''
    FUNCTION:   main
    PURPOSE:    Connects to a Redshift cluster and runs the specified functions to perform the ETL
    INPUT:      None
    OUTPUT:     No explicit return, prints to the console
    '''

    config = configparser.ConfigParser()
    config.read('dwh.cfg')

    conn = psycopg2.connect("host={} dbname={} user={} password={} port={}".format(*config['CLUSTER'].values()))
    cur = conn.cursor()

    print('Copying staging tables. Please wait...')
    load_staging_tables(cur, conn)
    print('Staging tables successfully loaded!')

    print('Inserting into tables. Please wait...')
    insert_tables(cur, conn)
    print('Values inserted successfully into tables!')

    cur.close()
    conn.close()

if __name__ == "__main__":
    main()


#
# @lc app=leetcode.cn id=116 lang=python3
#
# [116] 填充每个节点的下一个右侧节点指针
#

# @lc code=start
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return root

        leftmost = root
        while leftmost.left:
            head = leftmost
            while head:
                head.left.next = head.right
                if head.next:
                    head.right.next = head.next.left
                head = head.next
            leftmost = leftmost.left

        return root

# @lc code=end

116.填充每个节点的下一个右侧节点指针.py

116.填充每个节点的下一个右侧节点指针.py


from django import forms
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone

from .models import Post
from blog import *

from .forms import PostForm, ContactForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse

# Create your views here.

def post_list(request):
    posts = Post.objects.all()
    return render(request, 'blog/post_lists.html', {'posts': posts})

# POST METHOD

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

def post_create(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.publish_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form, 'pk': pk})

def post_delete(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if post:
        post.delete()
        posts = Post.objects.all()
    return render(request, 'blog/post_lists.html', {'posts': posts})

# SEND EMAIL

def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = "Title of message"
            body = {
                'first_name': form.cleaned_data['first_name'],
                'last_name': form.cleaned_data['last_name'],
                'email_address': form.cleaned_data['email_address'],
                'message': form.cleaned_data['message']
            }
            message = '\n'.join(body.values())
            try:
                send_mail(subject, message, 'from@gmail.com',
                          ['to_help@gmail.com'])

            except BadHeaderError:
                return (HttpResponse('Find incorrect header'))
            return redirect('post_list')
    form = ContactForm()
    return render(request, 'blog/contact.html', {'form': form})


value = int(input('Введите сумму :  '))

bank = {5000: 0, 2000: 0, 1000: 0, 500: 0, 200: 0, 100: 0, 50: 0, 20: 0, 10: 0, 5: 0, 3: 0, 1: 0}

def get_money(s):
    for k, v in bank.items():
        if s == 0:
            break
        while s >= k:
            bank[k] += 1
            s -= k
    if s == 0:
        print('Ваши деньги : ', bank)
    else:
        raise ValueError

get_money(value)


# This approach mimics the method of meeting room 2.
# Idea is to first sort the trips in the order of the start times.
# 1. Push the following details of first trip into the priority queue [end_time, capacity]. Also decrement this capacity from the total capacity.
# 2. select trips and check if the end_time of the trip in priority_queue is less than/equal the start time of the current trip. If its true then remove it from the pqueue while increasing the capacity.
# If the end time is greater than start_time of the current trip then check if the additional capacity from the current trip be accomodated. If yes, then update capacity and push this trip into priority queue, else return False.
import heapq
class Solution:
    def carPooling(self, trips, capacity):
        trips = sorted(trips, key=lambda x: x[1])
        # print(trips)
        heap = []
        # heapq.heappush(heap, [trips[0][2], trips[0][0]])

        for i in range(0, len(trips)):
            c2, s2, e2 = trips[i]
            # print(heap)
            if not heap:
                if capacity < c2:
                    return False
                capacity -= c2
                heapq.heappush(heap, [e2, c2])
                # print("trip: {}, capacity: {}".format(i, capacity))
            else:
                e1, c1 = heapq.heappop(heap)
                capacity += c1
                while heap and s2 >= e1:
                    e1, c1 = heapq.heappop(heap)
                    capacity += c1

                if not heap and s2 >= e1:
                    if capacity < c2:
                        return False
                    capacity -= c2
                    heapq.heappush(heap, [e2, c2])
                else:

                    if capacity >= c1 + c2:
                        capacity -= (c1 + c2)
                        heapq.heappush(heap, [e1, c1])
                        heapq.heappush(heap, [e2, c2])
                        # print("trip: {} capacity: {}".format(i, capacity))
                    else:
                        return False

        return True

"""
1094. Car Pooling
Medium

351

17

Add to List

Share
You are driving a vehicle that has capacity empty seats initially available for passengers.  The vehicle only drives east (ie. it cannot turn around and drive west.)

Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off.  The locations are given as the number of kilometers due east from your vehicle's initial location.

Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.

Example 1:

Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:

Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:

Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:

Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
"""
data = [[2,1,5],[3,3,7]]
k = 4
print(Solution().carPooling(data, k))
data = [[2,1,5],[3,3,7]]
k = 5
print(Solution().carPooling(data, k))


# Write a program that prints part of the ASCII table of characters on the console.
# On the first line of input you will receive the char index you should start with
# and on the second line - the index of the last character you should print.
# Input	    Output
# 60        < = > ? @ A
# 65
#
# 69        E F G H I J K L M N O
# 79

first_num = int(input())
second_num = int(input())

for i in range(first_num, second_num + 1):
    print(chr(i), end=" ")

00. Basics - Data-Types, Variables/05. Print Part of the ASCII Table.py


"""
A simple little demo app for snakeware, it draws circles.

Josh Moore 2020
"""

import pygame

import random
import os

class CirclezApp:
    def __init__(self):
        pygame.init()

        # set pygame to fbdev mode
        os.putenv("SDL_FBDEV", "/dev/fb0")
        pygame.display.init()

        # get screen dimensions
        self.DIMS = (pygame.display.Info().current_w, pygame.display.Info().current_h)

        # init screen
        self.SCREEN = pygame.display.set_mode(self.DIMS, pygame.FULLSCREEN)

        # init background
        self.BG = pygame.Surface((self.DIMS))
        self.BG.fill((0, 0, 0))

        pygame.mouse.set_visible(False)
        pygame.display.update()

    def run(self):
        clock = pygame.time.Clock()

        while True:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    exit()

            pygame.draw.circle(
                self.BG,
                (
                    random.randint(0, 255),
                    random.randint(0, 255),
                    random.randint(0, 255),
                ),
                (random.randint(0, self.DIMS[0]), random.randint(0, self.DIMS[1])),
                random.randint(10, 100),
            )
            self.SCREEN.blit(self.BG, (0, 0))
            pygame.display.flip()
            clock.tick(30)


import iris.tests as tests

from . import extest_util

with extest_util.add_examples_to_path():
    import coriolis_plot

class TestCoriolisPlot(tests.GraphicsTest):
    """Test the Coriolis Plot example code."""

    def test_coriolis_plot(self):
        with extest_util.show_replaced_by_check_graphic(self):
            coriolis_plot.main()

if __name__ == "__main__":
    tests.main()


project = "{{ cookiecutter.project_name }}"
copyright = "{{ cookiecutter.year }}, {{ cookiecutter.full_name }}"
author = "{{ cookiecutter.full_name }}"
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
html_theme = "sphinx_book_theme"
html_theme_options = {
    "single_page": True,
    "use_fullscreen_button": False,
}
extensions = ["m2r2"]
source_suffix = [".rst", ".md"]


import RPi.GPIO as GPIO
import time

RED = [12]
GRN = [33]
BLU = [32]
PUR = [RED, BLU]
YEL = [RED, GRN]
MYSTERY = [BLU, GRN]
ALL = [RED, GRN, BLU]

class LED:
    def __init__(self):
        self.PINS = [*RED,*GRN,*BLU]
        GPIO.setup(self.PINS, GPIO.OUT, initial=GPIO.LOW)

    def turn_on(self, pin):
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.HIGH)

    def turn_off(self, pin):
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)

    # off_c and on_c are iterables
    def change_color(self, on_c, off_c=ALL):
        for p in off_c:
            self.turn_off(p)
        for p in on_c:
            self.turn_on(p)

    # on_c is an iterable
    def flash(self, on_c, off_c=ALL):
        self.change_color(on_c, off_c)
        time.sleep(1)
        self.change_color((), off_c=ALL)
        time.sleep(1)

    def interrupt(self):
        self.change_color((), off_c=ALL)
        GPIO.cleanup()


##Cuantas horas son 105 minutos?
print("Cuantas horas son 105 minutos?")

hora = 1
minutos = 60
cantidad = 105

## 1 hora _____ 60 min
## x hora _____ 105 min

total1 = (hora*cantidad)/minutos
print(total1)

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

##Cuantos kilometros son 20 millas ? (Si un kilometro corresponde a 0,6214 millas)
print("Cuantos kilometros son 20 millas?")
cant = 20
kilo = 1
millas = 0.6214

## 1 kilo ______ 0,6214 millas
## x      ______ 20 millas

total2 = (kilo*cant)/millas
print (total2)


from asyncio import Queue
from typing import Dict, List

from app import schemas
from app.cruds import UserAccountCRUD, MessageCRUD
from app.schemas import RegisterResponse, AuthResponse, Dialog, Message, User, CheckSessionResponse, LoginRequest, \
    RegisterRequest, BaseRequest, FindUsersRequest, GetDialogsRequest, SendMessageRequest, GetDialogMessagesRequest, \
    SendMessageResponse, GetDialogsResponse, GetDialogMessagesResponse, FindUsersResponse, LogoutResponse, \
    LogoutRequest, GetUserByIdResponse, GetUserByIdRequest

class AuthMiddleWare:

    def __init__(self, active_users: Dict[str, schemas.User]):
        self._active_users: Dict[str, schemas.User] = active_users

    def check_session(self, request: BaseRequest) -> CheckSessionResponse:
        session = request.session
        if session in self._active_users:
            return CheckSessionResponse(success=True, session=session)
        return CheckSessionResponse(success=False, session=session)

class AuthService:

    def __init__(self, user_account_crud: UserAccountCRUD,
                 active_users: Dict[str, schemas.User]):
        self._user_account_crud = user_account_crud
        self._active_users: Dict[str, schemas.User] = active_users

    def register(self, request: RegisterRequest) -> RegisterResponse:
        try:
            user = self._user_account_crud.create(request.username)
        except BaseException as e:
            response = RegisterResponse(success=False, error=str(e))
        else:
            response = RegisterResponse(user=user)
        return response

    def auth(self, request: LoginRequest) -> AuthResponse:
        username = request.username
        try:
            user = self._user_account_crud.get_by_username(username)
        except BaseException as e:
            response = AuthResponse(success=False, error=str(e))
        else:
            session = username + '_session'
            self._active_users[session] = user
            response = AuthResponse(user=user, session=session)
        return response

    def logout(self, request: LogoutRequest) -> LogoutResponse:
        try:
            session = request.session
            self._active_users.pop(session)
        except KeyError:
            return LogoutResponse(success=False, error='wrong session')
        else:
            return LogoutResponse(success=True)

class ChatService:

    def __init__(self, user_account_crud: UserAccountCRUD, message_crud: MessageCRUD, finding_limit: int = 10):
        self._user_account_crud = user_account_crud
        self._message_crud = message_crud
        self._finding_limit = finding_limit

    def get_user_by_id(self, request: GetUserByIdRequest) -> GetUserByIdResponse:
        user_id = request.user_id
        user = self._user_account_crud.get_by_id(user_id)
        return GetUserByIdResponse(user=user)

    def find_users(self, request: FindUsersRequest) -> FindUsersResponse:
        username_part = request.username_part
        found_users = self._user_account_crud.find_by_username_part(username_part, self._finding_limit)
        return FindUsersResponse(users=found_users)

    def get_dialog_messages(self, request: GetDialogMessagesRequest) -> GetDialogMessagesResponse:
        user_id = request.user_id
        with_user_id = request.with_user_id
        dialog_messages = self._message_crud.get_user_dialog(user_id, with_user_id)
        return GetDialogMessagesResponse(messages=dialog_messages)

    def get_dialogs(self, request: GetDialogsRequest) -> GetDialogsResponse:
        user_id = request.user_id
        user = self._user_account_crud.get_by_id(user_id)
        dialogs_users_ids = self._message_crud.get_user_dialogs_users_ids(user_id)
        dialogs_users = [self._user_account_crud.get_by_id(dialog_user_id) for dialog_user_id in dialogs_users_ids]
        return GetDialogsResponse(dialogs=[Dialog(user=user, with_user=dialog_user) for dialog_user in dialogs_users])

    def send_message(self, request: SendMessageRequest) -> SendMessageResponse:
        message_text: str = request.message_text
        from_user_id: int = request.from_user_id
        to_user_id: int = request.to_user_id
        message = self._message_crud.create(message_text, from_user_id, to_user_id)
        return SendMessageResponse(message=message)

class NewMessagesStorage:

    def __init__(self):
        self._new_messages: Dict[Dialog, Queue] = {}

    def add(self, dialog: Dialog, message: Message):
        pass

    def get_new_messages_count(self, dialog: Dialog) -> int:
        try:
            new_messages_count = len(self._new_messages[dialog])
        except KeyError:
            new_messages_count = 0
        return new_messages_count

    def get_new_messages(self, dialog: Dialog) -> List[Message]:
        pass