# import essentials
import time
import random
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler

# set the seed for reproducability
seed = 69
random.seed = seed
np.random.seed(seed)

# get data
data = pd.read_csv('../input/high_diamond_ranked_10min.csv')

# data cleaning time!

# Heat map to show which features correlate with y
corrmat = data.corr()
plt.subplots(figsize=(12,9))
sns.heatmap(corrmat, vmax=0.9, square=True)

# many features are linearly dependent on one another. Gotta drop.

# redGoldDiff is -1 * blueGoldDiff
# blueTotalGold is NOT dropped because it is not a
# linear combination of cs and kills for game-specific reasons
# check if blueFirstBlood and redFirstBlood are opposites
nokills = pd.DataFrame(data['blueFirstBlood'] + data['redFirstBlood'] == 0)
print('\nno kill games:', str(pd.DataFrame.sum(nokills).values[0]) + '\n')
# so if blueFirstBlood is false, redFirstBlood is true and vice-versa
# so drop redFirstBlood

# total experience is not a zero-sum game, so leave redTotalExperience in
# same with dragons, kills, wards placed/destroyed
# but red and blue deaths are almost opposites (not completely opposites since executes can occur
# so get rid of deaths
# also get rid of red total gold and exp, since blue gold - difference = red gold
# blueEliteMonsters = blueDragons + blueHeralds
dropset = ['redGoldDiff', 'redFirstBlood', 'blueDeaths', 'redDeaths',
           'redExperienceDiff', 'redTotalGold', 'redTotalExperience',
           'blueEliteMonsters', 'redEliteMonsters', 'gameId']

outcomes = data.pop('blueWins')
data = data.drop(columns=dropset)

# adding features time!
def square_feats(_columns, _data):
    for col in _columns :
        _data[col + '_2'] = _data[col] ** 2
    return _data

square_cols = [
    'blueWardsPlaced', 'redWardsPlaced', 'blueWardsDestroyed',
    'redWardsDestroyed', 'blueExperienceDiff'
    ]
data = square_feats(square_cols, data)

# check that all the variables are in
print(str(data.dtypes) + '\n')

# observe our dataset
print(data.describe())

# create the train and test sets
from sklearn.model_selection import \
    train_test_split, cross_val_predict, cross_val_score
from sklearn.model_selection import KFold

X_train, X_test, y_train, y_test = train_test_split(
    data, outcomes, test_size=0.20,
        random_state=seed, shuffle=True, stratify=outcomes)

# scale our data
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)

# define how we will output scores to the screen:
def score_method(_y_actual :np.array, _y_pred :np.array) :
    errors = np.abs(_y_actual - _y_pred)
    _score = np.sum(errors) / _y_actual.shape[0]
    return 1 - _score

def score_models(_models :dict, _X=X_train, _y=y_train) :
    t_0 = time.time()
    kfold = KFold(n_splits=5, shuffle=False)
    output = list()
    for name, model in _models.items() :
        predictions = cross_val_predict(model, _X, _y, cv=kfold, n_jobs=-1)
        _t_1 = time.time() - t_0
        _pred_score = score_method(y_train,predictions)
        _score = cross_val_score(model, _X, _y, cv=kfold, n_jobs=-1, scoring='roc_auc')
        output.append([name,_pred_score,_t_1])
        print('\n{} ROC Score: {:.4f}, ({:.4f})'
              .format(name, _score.mean(), _score.std()))
        print('{} accuracy: {:.4f}\nTime elapsed: {:.1f}s'
              .format(name,_pred_score,_t_1))
        model.fit(X_train,y_train)
        test_eval = model.score(X_test,y_test)
        print('{} accuracy on the test set: {:.4f}\nVariance: {:.4f}'
              .format(name, test_eval, _score.mean() - _pred_score))
    return output

# regression tiiime
from sklearn.linear_model import ElasticNet, Lasso, \
    BayesianRidge, LassoLarsIC, LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier

# create empty model dictionary that will contain the model under its name
models = {}

# define our models and add them to our model dictionary
logit = make_pipeline(RobustScaler(),
                      LogisticRegression(random_state=seed, max_iter=1000,n_jobs=-1))
models['Logit'] = logit

lasso = make_pipeline(RobustScaler(),
                      Lasso(alpha=.0005, random_state=seed))
models['Lasso'] = lasso

eNet = make_pipeline(RobustScaler(),
                     ElasticNet(alpha=.0005, l1_ratio=.9, random_state=seed))
models['ENet'] = eNet

rforest = RandomForestClassifier(max_depth=5,n_estimators=64)
models['Random Forest'] = rforest

svm = SVC(kernel='rbf',random_state=seed)
models['Basic SVM'] = svm

bayesian_ridge = BayesianRidge()
models['Bayesian Ridge'] = bayesian_ridge

lasso_lars_ic = LassoLarsIC(max_iter=15)
models['LassoLarsIC'] = lasso_lars_ic

score_models(models)

# Let's build our own stacking classifier
from sklearn.base import BaseEstimator, RegressorMixin, \
    TransformerMixin, clone
from sklearn.model_selection import cross_val_predict

print('--------------------------------------')
print('\nBuilding a stacking classifier...\n')

kfold = KFold(n_splits=5, shuffle=True, random_state=seed)

class StackedClassifier(BaseEstimator, RegressorMixin,
                      TransformerMixin):
    def __init__(self, models, final_estimator):
        self.models = models
        self.cloned_models = \
            [clone(x) for x in self.models]
        self.final_estimator = clone(final_estimator)

    # clone original models to fit data into
    def fit(self, X, y):
        # train clones
        predictions = np.column_stack([
            cross_val_predict(model,X,y,cv=kfold,n_jobs=-1,method='predict_proba')
            for model in self.cloned_models
        ])
        for model in self.cloned_models : model.fit(X,y)
        self.final_estimator.fit(predictions, y)
        return self

    # Now execute predictions for cloned models
    def predict(self, X):
        base_predictions = np.column_stack([
            model.predict(X) for
            model in self.cloned_models
        ])
        final_predictions = self.final_estimator.predict(base_predictions)
        return final_predictions

# instantiate our stacking regressor
stacked_classifier = StackedClassifier(
    [model for model in models.values()],
    LogisticRegression(penalty='l2',random_state=seed))

# fit and score our model
stacked_classifier.fit(X_train,y_train)
predictions = stacked_classifier.predict(X_test)

score = score_method(y_test, predictions)
print('\n\nStacked Classifier performance: {}'.format(score))

# now let's try a prepackadged stacking classifier
from sklearn.ensemble import StackingClassifier
from sklearn.svm import LinearSVC

estimators = [
    ('rf', RandomForestClassifier(n_estimators=128,
                                  random_state=seed)),
    ('svr', make_pipeline(LinearSVC(random_state=seed,
                                    max_iter=30000))),
    ('logit', make_pipeline(StandardScaler(),
                            LogisticRegression(max_iter=1000,n_jobs=-1,
                                               random_state=seed))),
    ('Random Forest', RandomForestClassifier(max_depth=5,n_estimators=64)),
    ('SVC',SVC(kernel='rbf',random_state=seed)),
]

print('\nNow evaluating prepackadged Stacking Classifier...')

score = score_method(y_test, predictions)
print('\n\nStacked Classifier performance: {}'.format(score))

quit()
# looks like our Logit model performs best. Let's see if a neural net does any better

#import tensorflow
import tensorflow as tf
from tensorflow.keras import layers

# make tensorflow a little quieter
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

def score_neural_net(_neural_net :tf.keras.models.Sequential,
                     X_data=X_train, y_data=y_train) :
    n_folds = 5
    kfold = KFold(n_splits=n_folds)
    _score = np.zeros(n_folds)
    for i, (train_index, test_index) in enumerate(kfold.split(X_data)) :
        _X_train,_X_test = X_data[train_index], X_data[test_index]
        _y_train,_y_test = y_data[train_index], y_data[test_index]
        _neural_net.fit(_X_train, _y_train)
        pred = _neural_net.predict(_X_test)
        _score[i] = score_method(_y_test, pred)
    return _score

def build_neural_net() :
    _neural_net = tf.keras.models.Sequential([
        layers.Dense(64,activation='relu'),
        layers.Dense(64,activation='sigmoid'),
        layers.Dense(1,activation='sigmoid')
    ])

    _neural_net.compile(
        optimizer='rmsprop',
        loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
    metrics=['accuracy'])

    return _neural_net

neural_net = build_neural_net()

print('\nFitting Neural Net...')
neural_net.fit(X_train,y_train,epochs=10)

# add a predictions layer
neural_net.add(
    layers.Lambda(
        lambda x: tf.math.round(x)
    )
)

neural_net.predict(X_test)

print('\nEvaluating model...')
neural_net.evaluate(X_test,y_test)

stacking_clf = StackingClassifier(
    estimators=estimators, final_estimator=
    LogisticRegression(max_iter=10000,random_state=seed),
    n_jobs=-1, verbose=1
)

# evaluate our final model
stacking_clf.fit(X_train,y_train)
score = stacking_clf.score(X_test,y_test)
print('\nStacking Classifier Score on the test set: {:.4f}'
      .format(score))


import argparse
from socket import gethostbyname
import proxy_server
import utility

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('ip')
    parser.add_argument('port')
    args = parser.parse_args()

    while True:
        print('Config:')
        print('1: Add to Blackist')
        print('2: Start Server')
        c = int(input('Choice: '))
        if c == 2:
            break
        elif c == 1:
            while True:
                blacklist_file = open('blacklist.txt', 'a')
                try:
                    addr = input('Enter website host name [empty line to exit]: ')
                    if not addr:
                        break
                    hostname = utility.extract_hostname(addr)
                    ip = gethostbyname(hostname)
                    blacklist_file.write(f'{addr}\n')
                except Exception as e:
                    print(e)
                blacklist_file.close()

    ps = proxy_server.proxy_server()
    ps.start(args.ip, int(args.port))


from pathlib import Path
import pandas as pd

# clean up artificats of the translation API

path = Path("data/dev/europarl_dev.csv")

data = pd.read_csv(path, index_col=0, header = 0)

data = data.dropna()
data['Original'] = data['Original'].apply(lambda x: str(x).strip('\n'))
data['Human'] = data['Human'].apply(lambda x: str(x).strip('\n'))
data['Automated'] = data['Automated'].apply(lambda x: str(x).replace('"', '\"').replace(''', '\'').strip('\n'))

data.to_csv(path)


t=int(input())
for i in range(0,t):
    k=int(input())
    s=input()
    ls=s.split()
    e=0
    if k<len(ls):
        t1=ls[k]
        for j in t1:
            e+=ord(j)
        print(e)
    else:
        print(-1)


# -*- coding: utf-8 -*-
# @Author: Fule
# @Date:   2020-05-20 18:03:50
# @Last Modified by:   Fule
# @Last Modified time: 2020-05-21 11:30:25

# %%
import PySimpleGUI as psg
import os
import pandas as pd
from time import strftime
from pandas import DataFrame as df
from pandas import read_excel
from pathlib import Path
from secrets import token_hex
#from pandas.plotting._matplotlib import table

pro_dir = os.path.join(os.getcwd(), 'profile')
script_dir = os.path.join(os.getcwd(), 'script')
dirlist = []
event = ''

if Path(script_dir).is_dir():
    print('目录存在')
else:
    os.makedirs(script_dir)
    print('创建目录')

#%%
# 文件名函数

def file_name(file_dir, exten):
    file_list = []
    filename_list = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            (name, extention) = os.path.splitext(file)
            if extention == exten:
                file_list.append(name)
                filename_list.append((name, file))
    return file_list, filename_list

# 替换函数

def replace_data_sing(table, template):
    with open(template) as f:
        template = f.read()
        pd_table = pd.read_excel(table)
        dict_table_index = pd_table.to_dict('index')
        for i in list(dict_table_index):
            maxlen = len(dict_table_index.keys())
            data_dict = dict_table_index[i]
            j = list(data_dict.keys())
            temp_cache = template
            for k in j:
                temp_cache = temp_cache.replace(k, str(data_dict[k]))
            yield [(i+1)/maxlen, temp_cache]

def replace_data_mult(table, template):
    with open(template) as f:
        template = f.read()
        pd_table = pd.read_excel(table)
        dict_table_index = pd_table.to_dict('index')
        for i in list(dict_table_index.keys()):
            maxlen = len(dict_table_index.keys())
            data_dict = dict_table_index[i]
            filename = str(data_dict['@filename'])
            del data_dict['@filename']
            j = list(data_dict.keys())
            temp_cache = template
            for k in j:
                temp_cache = temp_cache.replace(k, str(data_dict[k]))
            yield [(i+1)/maxlen, temp_cache,filename]

# 写入函数

def writer(data, filename):
    with open(filename, 'a+') as f:
        f.write(data)
        return filename
def exitsfile(filename):
    script_dir = os.path.join(os.getcwd(), 'script')
    filename = os.path.join(script_dir, filename)
    if Path(filename).exists():
        (name, extention) = os.path.splitext(filename)
        filename = name + '_' + str(token_hex(nbytes=2)) + extention
        return filename
    else:
        return filename

# 百分比函数

def percentage(i: int, n: int):
    print('\r{}{}%'.format(['/', '-', '\\'][i % 3] if n -
                           i else '', int(i/n*100)), end='' if n-i else '\n')

# if else简写方式
# 上面等效与
# a = '\r{}{}%'.format(['/', '-', '\\'][i % 3]
# if n-i:
#    print(a)
# else:
#    print('')
psg.theme('SystemDefault')
print_out = [
    [psg.Output(size=(85, 30))]
]
temp_input = [
             [psg.Text(text='刷新脚本模板后，单击选择')],
             [psg.Listbox(values=dirlist, size=(30, 6), key='模板列表'), ],
             [psg.Submit(button_text='刷新模板', key='flush', size=(25, 1))]
]

table_input = [
    [psg.Text(text='请选择脚本数据表格')],
    [psg.Input(key='excelname'), psg.FileBrowse(
        button_text='浏览',file_types=(('Table Files','*.xlsx'),) )],
    [psg.Text(text='如果需生成的脚本为单文件，则勾选此项')],
    [psg.Radio('单文件模式', 'mode', key='sing',default=True)],
    [psg.Text(text='如果需生成的脚本为多文件，则勾选此项')],
    [psg.Radio('多文件模式', 'mode', key='mult')],
]
script_creat = [
    [psg.Submit(button_text='生成脚本'), psg.Checkbox(
        '预览脚本，影响生成速度', key='preview')],
    [psg.Text('脚本生成进度'), psg.Text('  ', size=(5, 1), key='percentage')],
    [psg.ProgressBar(max_value=1, size=(61.5, 20), key='进度条')]
]
layout = [
    [psg.Frame('第一步', temp_input),
     psg.Frame('第二步', table_input)
     ],
    [psg.Frame('第三步', script_creat)],
    [psg.Frame('打印信息', print_out)],
    [psg.Cancel('退出')]
]
gui = psg.Window('脚本生成器(不好用也别告诉我)_v0.1').Layout(layout)

# %%
while True:
    event, var_read = gui.Read()
   # print(event,var_read)
    dirlist = file_name(pro_dir, '.pro')
    dict_template = dict(dirlist[1])
    if event == None:
        break
    elif event == '退出':
        break
    elif event == 'flush':
        gui.Element('模板列表').update(values=dirlist[0])
    elif event == '生成脚本':
        templist = gui.Element('模板列表').get()
        if templist == []:
            print('刷新模板列表后，再提交数据')
        elif var_read.get('excelname') == '':
            print('请选择数据表格')
        else:
            template = dict_template.get(templist[0])
            template = os.path.join(pro_dir, template)
            excelname = var_read.get('excelname')
            if  var_read['sing']==True:
                tablename = os.path.split(excelname)[1]
                name = os.path.splitext(tablename)[0]
                data = replace_data_sing(excelname, template)
                scriptname = name + '.txt'
                scriptname = exitsfile(scriptname)
                print(scriptname)
                try:
                    for [i, temp_cache] in data:
                        writer(temp_cache,scriptname)
                        gui.Element('percentage').update('{:.1%}'.format(i))
                        gui.Element('进度条').UpdateBar(i)
                        if var_read.get('preview') == True:
                            print(temp_cache)
                            pass
                        if i == 1:
                            print(scriptname)
                            psg.popup_ok('生成完毕！')
                            i = 0
                            gui.Element('进度条').UpdateBar(i)
                            gui.Element('percentage').update('{:.1%}'.format(i))
                except:
                    psg.popup('出错了，我也不知道为啥！！')
            elif var_read['mult']==True:
                data = replace_data_mult(tablename, template)
                try:
                    for [i, temp_cache,filename] in data:
                        writer(temp_cache,filename)
                        gui.Element('percentage').update('{:.1%}'.format(i))
                        gui.Element('进度条').UpdateBar(i)
                        if var_read.get('preview') == True:
                            print(filename)
                        else:
                            pass
                    if i == 1:
                        psg.popup_ok('生成完毕！')
                        i = 0
                        gui.Element('进度条').UpdateBar(i)
                        gui.Element('percentage').update('{:.1%}'.format(i))
                except:
                        psg.popup('出错了，我也不知道为啥！！')

gui.close() # 一定要加上这行，不然退出按钮无法使用

        # print('数据表格为')

# 2020-05-18 1:49完成脚本文件的读取，下一步计划进行表格遍历，然后根据表格读取值生成脚本
# 脚本生成两种方式：
# 1、 一个表格生成一个脚本文件；单文件方式
# 2、一个表格生成多个脚本文件；多文件方式
# %%
# def replace_data(table,template):
#    with open(template) as temp:                                    ##打开模板
#        template = temp.read()                                      ##读入模板
#        fl=pd.read_excel(table)                                     ##读入数据表，并dataframe
#        fl_test = fl.to_dict('index')                               ##以index为key转化为复合字典
#        for i in list(fl_test.keys()):                              ##遍历index值
#            data_dict=fl_test[i]                                    ##读取每行数据组成的字典
#            j = list(data_dict.keys())                              ##将每行数据组成的字典的key转化为list
#            temp_cache=template                                     ##对模板重新赋值
#            for k in j:                                             ##遍历字典key获取key的字符串
#                temp_cache=temp_cache.replace(k,str(data_dict[k]))  ##替换
#            yield [i,temp_cache]                                    ##使用迭代器yield，获取循环中的返回值，
# 2020-5-19 遗留问题：模板文件路径问题


import yaml
from types import SimpleNamespace

class DotDict(SimpleNamespace):
    def __init__(self, dictionary, **kwargs):
        super().__init__(**kwargs)
        for key, value in dictionary.items():
            if isinstance(value, dict):
                self.__setattr__(key, DotDict(value))
            else:
                self.__setattr__(key, value)

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

    def items(self):
        keys = sorted(self.__dict__)
        item_dict = {k: self.__dict__[k] for k in keys}
        return item_dict.items()

def read_config(config_path):
    with open(config_path, "r") as ymlfile:
        return DotDict(yaml.safe_load(ymlfile))


def main():
    nums = list(map(int, input().split(",")))
    count = 0

    for i in range(3, len(nums) + 1):
        for j in range(0, len(nums) + 1 - i):
            if is_arithmetic_sequence(nums[j:j + i]):
                count += 1

    print(count)

def is_arithmetic_sequence(nums):
    for i in range(0, len(nums) - 1):
        nums[i] = nums[i + 1] - nums[i]
    gap = nums[0]
    for i in range(1, len(nums) - 1):
        if nums[i] == gap:
            continue
        else:
            return False
    return True

if __name__ == "__main__":
    main()


#!/usr/bin/env python3

import sys

HIGH_VALUE = 100000
SEARCH_DEPTH = 6

EMPTY = 0
wP = 1
bP = -1
wN = 2
bN = -2
wR = 3
bR = -3
wQ = 4
bQ = -4
wK = 5
bK = -5

def evaluate_board(board) -> int:
    piece_values = [
        -10000,
        -900,
        -500,
        -300,
        -100,
        0,
        100,
        300,
        500,
        900,
        10000,
    ]
    return sum([piece_values[piece + 5] for piece in board])

def offset_moves(position, board, offsets):
    for dx, dy in offsets:
        nx, ny = position[0] + dx, position[1] + dy
        if 0 <= nx < 6 and 0 <= ny < 6:
            target = board[nx * 6 + ny]
            if target * board[position[0] * 6 + position[1]] <= 0:
                yield (nx, ny)

def get_knight_moves(position, board):
    offsets = ((2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), (-2, -1), (-1, -2))
    yield from offset_moves(position, board, offsets)

def get_king_moves(position, board):
    offsets = ((1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1))
    yield from offset_moves(position, board, offsets)

def vector_moves(position, board, vectors):
    for dx, dy in vectors:
        nx, ny = position
        while True:
            nx, ny = nx + dx, ny + dy
            if 0 <= nx < 6 and 0 <= ny < 6:
                target = board[nx * 6 + ny]
                if target == EMPTY:
                    yield (nx, ny)
                    continue
                if target * board[position[0] * 6 + position[1]] < 0:
                    yield (nx, ny)
            break

def get_rook_moves(position, board):
    vectors = ((0, 1), (1, 0), (0, -1), (-1, 0))
    yield from vector_moves(position, board, vectors)

def get_queen_moves(position, board):
    vectors = ((1, 1), (1, -1), (-1, 1), (-1, -1))
    yield from vector_moves(position, board, vectors)
    yield from get_rook_moves(position, board)

def get_pawn_moves(position, board):
    x, y = position
    dx = 1 if board[position[0] * 6 + position[1]] < 0 else -1
    if 0 <= x + dx < 6:
        if board[(x + dx) * 6 + y] == EMPTY:
            yield (x + dx, y)
        for dy in (-1, 1):
            if 0 <= y + dy < 6:
                target = board[(x + dx) * 6 + (y + dy)]
                if target * board[position[0] * 6 + position[1]] < 0:
                    yield (x + dx, y + dy)

def make_move(board, position, move):
    new_board = board.copy()
    pos_idx = position[0] * 6 + position[1]
    move_idx = move[0] * 6 + move[1]
    piece = new_board[pos_idx]

    new_board[pos_idx] = EMPTY
    new_board[move_idx] = piece

    if piece == wP and move[0] == 5:
        new_board[move_idx] = wQ
    elif piece == bP and move[0] == 0:
        new_board[move_idx] = bQ

    return new_board

def get_moves(idx, piece, board):
    x, y = idx // 6, idx % 6
    if piece in (wP, bP):
        yield from get_pawn_moves((x, y), board)
    elif piece in (wR, bR):
        yield from get_rook_moves((x, y), board)
    elif piece in (wN, bN):
        yield from get_knight_moves((x, y), board)
    elif piece in (wQ, bQ):
        yield from get_queen_moves((x, y), board)
    elif piece in (wK, bK):
        yield from get_king_moves((x, y), board)
    return

def negamax(board, depth, alpha, beta, color):
    if depth == 0 or wK not in board or bK not in board:
        return board, color * evaluate_board(board)

    best_value = -HIGH_VALUE
    best_board = board

    for idx, piece in enumerate(board):
        if (color == 1 and piece > 0) or (color == -1 and piece < 0):
            for move in get_moves(idx, piece, board):
                new_board = make_move(board, (idx // 6, idx % 6), move)
                _, move_value = negamax(new_board, depth - 1, -beta, -alpha, -color)
                move_value = -move_value
                if move_value > best_value:
                    best_value = move_value
                    best_board = new_board
                alpha = max(alpha, best_value)
                if alpha >= beta:
                    break
        if alpha >= beta:
            break

    return best_board, best_value

char_to_int_map = {
    ".": EMPTY,
    "P": wP,
    "p": bP,
    "R": wR,
    "r": bR,
    "N": wN,
    "n": bN,
    "Q": wQ,
    "q": bQ,
    "K": wK,
    "k": bK,
}

def string_to_int_board(board):
    return [char_to_int_map[piece] for piece in board]

def int_to_string_board(int_board):
    int_to_char_map = {v: k for k, v in char_to_int_map.items()}
    return "".join([int_to_char_map[piece] for piece in int_board])

if __name__ == "__main__":
    board, _ = negamax(
        string_to_int_board(sys.argv[1]),
        SEARCH_DEPTH,
        -HIGH_VALUE,
        HIGH_VALUE,
        1 if sys.argv[2] == "w" else -1,
    )

    print(int_to_string_board(board), "b" if sys.argv[2] == "w" else "w")


import base64
import json
import logging
from datetime import datetime
from urllib.request import urlopen

import requests
import werkzeug.http

from odoo import api, models
from odoo.exceptions import AccessDenied

try:
    from jose import jwt
except ImportError:
    logging.getLogger(__name__).debug("jose library not installed")

_logger = logging.getLogger(__name__)

class ResUsers(models.Model):
    _inherit = "res.users"

    @api.model
    def _auth_oauth_signin(self, provider, validation, params):
        """retrieve and sign in the user corresponding to provider and validated access token
        :param provider: oauth provider id (int)
        :param validation: result of validation of access token (dict)
        :param params: oauth parameters (dict)
        :return: user login (str)
        :raise: AccessDenied if signin failed
        This method can be overridden to add alternative signin methods.
        """
        oauth_provider = self.env["auth.oauth.provider"].browse(provider)
        if oauth_provider.g2p_oidc_id_to_use:
            oauth_uid = validation["user_id"]
            try:
                oauth_user = self.search(
                    [
                        ("oauth_uid", "=", oauth_uid),
                        ("oauth_provider_id", "=", provider),
                    ]
                )
                if not oauth_user:
                    raise AccessDenied()
                assert len(oauth_user) == 1
                oauth_user.write({"oauth_access_token": params["access_token"]})
                return oauth_user.login
            except AccessDenied:
                json.loads(params["state"])
                partner = self.generate_partner_signup(
                    oauth_provider, validation, params
                )
                new_user = self.generate_partner_user_signup(
                    partner, oauth_provider, validation, params
                )
                return new_user.login
        else:
            return super(ResUsers, self)._auth_oauth_signin(
                provider, validation, params
            )

    def generate_partner_user_signup(self, partner, oauth_provider, validation, params):
        oauth_uid = validation["user_id"]
        login_attr = oauth_provider.login_attribute_mapping_on_user_creation
        login = validation.get(login_attr, oauth_uid)
        user_creation_dict = {
            "login": login,
            "partner_id": partner.id,
            "oauth_provider_id": oauth_provider.id,
            "oauth_uid": oauth_uid,
            "oauth_access_token": params["access_token"],
            "active": True,
        }
        if oauth_provider.default_group_user_creation:
            user_creation_dict["groups_id"] = [
                (
                    4,
                    oauth_provider.default_group_user_creation.id,
                ),
            ]
        return self.env["res.users"].create(user_creation_dict)

    def generate_partner_signup(self, oauth_provider, validation, params):
        oauth_uid = validation["user_id"]
        if oauth_provider.partner_creation_call_validate_url:
            userinfo_dict = self._auth_oauth_rpc(
                oauth_provider.validation_endpoint, params["access_token"]
            )
            update_dict = oauth_provider.map_validation_response_partner_creation(
                userinfo_dict
            )
            validation.update(update_dict)
            _logger.info(
                "Userinfo JWT payload after validation call. %s",
                json.dumps(userinfo_dict),
            )
            _logger.info(
                "Update dict after validation call. %s", json.dumps(update_dict)
            )
            _logger.info(
                "Validation Dict after validation call. %s", json.dumps(validation)
            )
        try:
            g2p_reg_id = self.env["g2p.reg.id"].search(
                [
                    ("value", "=", oauth_uid),
                    ("id_type", "=", oauth_provider.g2p_id_type.id),
                    ("partner_id.is_registrant", "=", True),
                    ("partner_id.is_group", "=", False),
                ]
            )
            if not g2p_reg_id:
                raise AccessDenied()
            assert len(g2p_reg_id) == 1
            return g2p_reg_id.partner_id
        except AccessDenied:
            # Create partner from validation dictionary
            # TODO: Improve following mapping.
            name = validation.pop("name", "")
            partner_dict = {
                "given_name": name.split(" ")[0],
                "family_name": name.split(" ")[-1],
                "addl_name": " ".join(name.split(" ")[1:-1]),
                "email": validation.pop(
                    "email", "provider_%s_user_%s" % (oauth_provider.id, oauth_uid)
                ),
                "is_registrant": True,
                "is_group": False,
            }
            partner_dict["name"] = self.process_name(
                partner_dict["family_name"],
                partner_dict["given_name"],
                partner_dict["addl_name"],
            )
            partner_dict["gender"] = self.process_gender(validation.pop("gender", ""))
            partner_dict["birthdate"] = self.process_birthdate(
                validation.pop("birthdate", None),
                date_format=oauth_provider.partner_creation_date_format,
            )
            partner_dict["reg_ids"] = self.process_ids(
                oauth_provider.g2p_id_type, oauth_uid
            )
            phone_numbers, primary_phone = self.process_phones(
                validation.pop("phone", "")
            )
            if primary_phone:
                partner_dict["phone"] = primary_phone
            if phone_numbers:
                partner_dict["phone_number_ids"] = phone_numbers

            partner_dict["image_1920"] = self.process_picture(
                validation.pop("picture", None)
            )

            partner_dict.update(
                self.process_other_fields(
                    validation,
                    oauth_provider.partner_creation_validate_response_mapping,
                )
            )

            return self.env["res.partner"].create(partner_dict)

    def _auth_oauth_rpc(self, endpoint, access_token):
        # This is recreated to suit that application/jwt response type
        if (
            self.env["ir.config_parameter"]
            .sudo()
            .get_param("auth_oauth.authorization_header")
        ):
            response = requests.get(
                endpoint,
                headers={"Authorization": "Bearer %s" % access_token},
                timeout=10,
            )
        else:
            response = requests.get(
                endpoint, params={"access_token": access_token}, timeout=10
            )

        if response.ok:  # nb: could be a successful failure
            if response.headers.get("content-type"):
                # TODO: Improve the following
                if "application/jwt" in response.headers["content-type"]:
                    return jwt.decode(
                        response.text, None, options={"verify_signature": False}
                    )
                if "application/json" in response.headers["content-type"]:
                    return response.json()
        auth_challenge = werkzeug.http.parse_www_authenticate_header(
            response.headers.get("WWW-Authenticate")
        )
        if auth_challenge.type == "bearer" and "error" in auth_challenge:
            return dict(auth_challenge)

        return {"error": "invalid_request"}

    def process_gender(self, gender):
        return gender.capitalize()

    def process_birthdate(self, birthdate, date_format="%Y/%m/%d"):
        if not birthdate:
            return None
        return datetime.strptime(birthdate, date_format).date()

    def process_name(self, family_name, given_name, addl_name):
        name = ""
        if family_name:
            name += family_name + ", "
        if given_name:
            name += given_name + " "
        if addl_name:
            name += addl_name + " "
        return name.upper()

    def process_ids(self, id_type, id_value, expiry_date=None):
        return [
            (
                0,
                0,
                {
                    "id_type": id_type.id,
                    "value": id_value,
                    "expiry_date": expiry_date,
                },
            )
        ]

    def process_phones(self, phone):
        phone_numbers = []
        if phone:
            phone_numbers.append(
                (
                    0,
                    0,
                    {
                        "phone_no": phone,
                    },
                )
            )
        return phone_numbers, phone

    def process_picture(self, picture):
        image_parsed = None
        if picture:
            with urlopen(picture) as response:
                image_parsed = base64.b64encode(response.read())
        return image_parsed

    def process_other_fields(self, validation: dict, mapping: str):
        res = {}
        all_fields = [pair.split(":")[0].strip() for pair in mapping.split(" ")]
        for key in list(validation):
            if key in all_fields and key in self.env["res.partner"]._fields:
                value = validation.pop(key)
                if isinstance(value, dict) or isinstance(value, list):
                    res[key] = json.dumps(value)
                else:
                    res[key] = value
        return res


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp,
# ne_10m_admin_1_states_provinces_lakes.shp seems ok though.
import json
import os

file_dest = os.path.abspath(
    os.path.join(os.path.dirname(__file__), '../shp/countries.json'))

replacements = {
    'KOS': 'XKX',  # Kosovo
    'PN1': 'PNG',  # Papua New Guniea
    'PR1': 'PRT',  # Portugal
    'SDS': 'SSD',  # S. Sudan
    'SAH': 'ESH',  # W. Sahara
}

with open(file_dest, 'r') as f:
    topo = json.load(f)

countries = topo['objects']['units']['geometries']
for country in countries:
    if country['id'] in replacements:
        country['id'] = replacements[country['id']]

with open(file_dest, 'w') as f:
    json.dump(topo, f, separators=(',', ':'))  # save bytes to keep file small


import asyncio
import os
from datetime import datetime

# File locations
root_folder = r"<root_file_path>"
log_file = r"<log_file_path\output.txt>"

async def run():
    # Initialize the variables
    file_count = 0
    total_lines = 0
    special_count = 0
    event_count = 0

    for subdir, dirs, files in os.walk(root_folder):
        for file in files:
            file_count += 1
            msg_filename = os.path.join(subdir, file)
            num_lines = 0
            with open(msg_filename, "r") as f:
                print("File name: ", msg_filename)
                msg_str = ""
                # Check if it is a multi-line message
                for line in f:
                    num_lines += 1
                    if line.startswith("{ body: ") and ("timezone.utc) }" in line):
                        msg_str = line
                    else:
                        msg_str += line
                        if not (msg_str.startswith("{ body: ") and ("timezone.utc) }" in line)):
                            continue

                    # Process the message
                    try:
                        has_special = 0
                        if msg_str.find("\\x") > 0:
                            has_special = 1
                        special_count += has_special

                    except Exception as err:
                        print(str(err))
                        with open(log_file, "a+") as log_f:
                            log_f.write(
                                "ERROR: " + str(err) + ", File path: " + msg_filename + ", Event: " + msg_str)
                        pass

                    # Reset the message
                    msg_str = ""
                    event_count += 1

            # Log for each file
            with open(log_file, "a+") as log_f:
                output_time = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                log_f.write(output_time + " Completed processing: " + msg_filename + "\n")
            print("Number of lines in the file: ", num_lines)
            print(
                "------------------------------------------------------------------------------------------------------")
            total_lines += num_lines

    # Log for the total process
    with open(log_file, "a+") as log_f:
        log_f.write("Total num of files: " + str(file_count) + "\n")
        log_f.write("Total num of lines: " + str(total_lines) + "\n")
        log_f.write("Total num of events: " + str(event_count) + "\n")
        log_f.write("Total num of events with special characters: " + str(special_count) + "\n")

def main():
    startTime = datetime.now()
    with open(log_file, "a+") as log_f:
        log_f.write(str(startTime.strftime("%Y-%m-%d %H:%M:%S")) + " ----------SCRIPT EXECUTION STARTED----------" + "\n")
    # Start processing the files
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())
    # Finish processing the files
    with open(log_file, "a+") as log_f:
        log_f.write("Total processing time in seconds: " + str((datetime.now() - startTime)) + "\n")
        log_f.write(
            str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + " ----------SCRIPT EXECUTION ENDED ----------" + "\n")

if __name__ == "__main__":
    # This code won't run if this file is imported.
    main()


import streamlit as st
from PIL import Image, ImageDraw
import torch
import numpy as np

from streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfiguration
import av

# trick to load model once at server start
if not hasattr(st, 'classifier'):
    st.model = torch.hub.load('ultralytics/yolov5', 'yolov5s',  _verbose=False)
    # if you train your custm model "yolov5s.pt" use the following line
    # st.model = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5s.pt', _verbose=False)

# Configuration for use camera from web deployed server
RTC_CONFIGURATION = RTCConfiguration(
    {"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}
)

def hit(player, enemy, ray):
    xp, yp = player
    xe, ye = enemy
    dist = np.sqrt((xp - xe)**2 + (yp - ye)**2)
    return dist < ray

def compute_shape(arr):
    cx, cy = arr
    return [cx-10, cy-10, cx+10, cy+10]

class VideoProcessor:
    points = 0
    enemy = (256, 256)
    enemy2 = (400, 400)
    enemy_ray = 20
    player_pos = [50, 50]

    def recv(self, frame):
        img = frame.to_ndarray(format="bgr24")

        # vision processing
        flipped = img[:, ::-1, :]

        # model processing
        im_pil = Image.fromarray(flipped)
        # return av.VideoFrame.from_ndarray(np.array(im_pil, copy=False), format="bgr24")
        results = st.model(im_pil, size=226)
        # bbox_img = np.array(results.render()[0])
        # res_im_pil = Image.fromarray(bbox_img)
        res_im_pil = im_pil

        # il draw è molto lento
        draw = ImageDraw.Draw(im_pil)
        draw.text((28, 36), "Points:" +
                  str(VideoProcessor.points), fill=(255, 0, 0))

        if VideoProcessor.points >= 10:
            draw.text((res_im_pil.width//2, res_im_pil.height//2),
                      "You WIN", fill=(255, 0, 0))
        elif VideoProcessor.points < 0:
            draw.text((res_im_pil.width//2, res_im_pil.height//2),
                      "You Louse", fill=(255, 0, 0))
        else:
            draw.text(VideoProcessor.enemy, "ENEMY", fill=(255, 0, 0))
            draw.text(VideoProcessor.enemy2, "ENEMY", fill=(0, 0, 255))

            for p in results.pred[0]:
                x1, y1, x2, y2, conf, pred = list(p.numpy())
                cx,cy = np.abs(x1-x2) / 2 + min([x1, x2]), np.abs(y1-y2) / 2 + min([y1, y2])
                class_name = results.names[int(pred)]
                if class_name == 'scissors':
                    VideoProcessor.player_pos = [cx, cy]
                    break

            shape = compute_shape(VideoProcessor.player_pos)
            draw.rectangle(shape, fill ="#ffff33", outline ="red")

            if hit(VideoProcessor.player_pos, VideoProcessor.enemy, VideoProcessor.enemy_ray):
                VideoProcessor.points += 1
                VideoProcessor.enemy = list(np.random.randint(475 - 40 , size=2) +20 )
                VideoProcessor.enemy2 = list(np.random.randint(475 - 40 , size=2) +20 )
                print(VideoProcessor.enemy, VideoProcessor.enemy2)
            if hit(VideoProcessor.player_pos, VideoProcessor.enemy2, VideoProcessor.enemy_ray):
                VideoProcessor.points -=1
                VideoProcessor.enemy = list(np.random.randint(475 - 40 , size=2) +20 )
                VideoProcessor.enemy2 = list(np.random.randint(475 - 40 , size=2) +20 )
                print(VideoProcessor.enemy, VideoProcessor.enemy2)

            # if VideoProcessor.enemy[0] > x1 and VideoProcessor.enemy[0] < x2 and \
                    #         VideoProcessor.enemy[1] > y1 and VideoProcessor.enemy[1] < y2:
                    #     VideoProcessor.points += 1

        # res_im_pil.save('test.png')
        return av.VideoFrame.from_ndarray(np.array(res_im_pil, copy=False), format="bgr24")

if __name__ == '__main__':
    st.session_state['game'] = {
        'points': 0
    }

    webrtc_ctx = webrtc_streamer(
        key="WYH",
        mode=WebRtcMode.SENDRECV,
        rtc_configuration=RTC_CONFIGURATION,
        video_processor_factory=VideoProcessor,
        media_stream_constraints={"video": True, "audio": False},
        async_processing=False,
    )


import xgboost
from sklearn.metrics import confusion_matrix
import input_data
from xgboost import XGBClassifier
import numpy as np
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import KFold
import math
import os
from numpy import *
# from imblearn.over_sampling import SMOTE
# from collections import Counter
import xlwt
import warnings
warnings.filterwarnings("ignore")

def eva(pre, true):
    pre = np.reshape(pre , (-1, 1))
    matrix = confusion_matrix(true, pre, labels=[1, 0])
    TP = matrix[0][0]
    TN = matrix[1][1]
    FP = matrix[1][0]
    FN = matrix[0][1]
    SE = 1.0*  TP  / (TP + FN)
    SP = 1.0 * TN / (TN + FP)
    ACC = 1.0*(TP + TN) / (TP + TN + FP + FN)
    MCC = (TP * TN - FP * FN) / math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN))
    F1 = 2 * TP / (2 * TP + FP + FN)
    return TP, TN, FP, FN, SE, SP, ACC, MCC, F1

file_root_path = 'dataset'
file_num_path = os.listdir(file_root_path)
TP_list = []
TN_list = []
FP_list = []
FN_list = []
SE_list = []
SP_list = []
ACC_list = []
MCC_list = []
F1_list = []
AUC_list = []
setFileNames = []
Optimal_parameters = [(10, 3), (10, 3), (8, 3), (8, 1), (10, 3), (8, 1), (8, 1), (10, 1), (10, 5), (8, 1), (10, 3),
                      (8, 1), (8, 3), (8, 1), (10, 1), (10, 3), (8, 3), (10, 1)]  # max_depth	min_child_weight
for file_num in file_num_path:
    setFileNames.clear()
    train_datadir = file_root_path + '/' + str(file_num)
    csv_file_list = os.listdir(train_datadir)
    setFileNames.append(csv_file_list[1])
    setFileNames.append(csv_file_list[0])
    print(setFileNames)
    huang = input_data.read_data_sets(train_datadir, setFileNames=setFileNames, one_hot=True)
    trX, trY, k_X, k_Y, teX, teY = huang.train.images, huang.train.labels, huang.k_train.images, huang.k_train.labels, huang.test.images, \
                                   huang.test.labels
    print('(max_depth, min_child_weight): ', Optimal_parameters[int(file_num) - 1])
    max_depth_param = Optimal_parameters[int(file_num)-1][0]
    min_child_weight_param = Optimal_parameters[int(file_num)-1][1]
    model = XGBClassifier(learning_rate=0.01,  # 学习速率
                          n_estimators=1000,
                          max_depth=max_depth_param,  # 树的最大深度，这个参数的取值最好在3-10之间， 需要使用CV函数来进行调优
                          min_child_weight=min_child_weight_param,  # 决定最小叶子节点样本权重和， 这个参数用于避免过拟合，使用 CV来调整
                          gamma=0,
                          subsample=0.8,
                          colsample_bytree=0.8,
                          objective='binary:logistic',
                          nthread=4,
                          scale_pos_weight=1,
                          seed=None)
    model.fit(trX, trY)

    # pred_y = model.predict(trX)
    # TP, TN, FP, FN, SE, SP,  ACC, MCC, = eva(pred_y, trY)
    # print("train:")
    # print("TP:", TP)
    # print("TN:", TN)
    # print("FP:", FP)
    # print("FN:", FN)
    # print("SE:", SE)
    # print("SP:", SP)
    # print("ACC: ", ACC)
    # print("MCC: ", MCC)
    # print("F1: ", F1)
    # tr_auc =roc_auc_score(trY, pred_y)
    # print(tr_auc)
    # #
    model.fit(trX, trY)
    pred_y = model.predict(teX)
    TP, TN, FP, FN, SE, SP, ACC, MCC, F1 = eva(pred_y, teY)
    auc = roc_auc_score(teY, pred_y)
    TP_list.append(TP)
    TN_list.append(TN)
    FP_list.append(FP)
    FN_list.append(FN)
    SE_list.append(SE)
    SP_list.append(SP)
    ACC_list.append(ACC)
    MCC_list.append(MCC)
    F1_list.append(F1)
    AUC_list.append(auc)
tp_mean = mean(TP_list)
tn_mean = mean(TN_list)
fp_mean = mean(FP_list)
fn_mean = mean(FN_list)
se_mean = mean(SE_list)
sp_mean = mean(SP_list)
acc_mean = mean(ACC_list)
mcc_mean = mean(MCC_list)
f1_mean = mean(F1_list)
auc_mean = mean(AUC_list)
print("************************************************************")
print("test_list:")
print("TP_list:", TP_list)
print("TN_list:", TN_list)
print("FP_list:", FP_list)
print("FN_list:", FN_list)
print("SE_list:", SE_list)
print("SP_list:", SP_list)
print("ACC_list:", ACC_list)
print("MCC_list:", MCC_list)
print("F1_list:", F1_list)
print("AUC_list:", AUC_list)
print("***********************************************************")
print("test_mean:")
print("TP:", tp_mean)
print("TN:", tn_mean)
print("FP:", fp_mean)
print("FN:", fn_mean)
print("SE:", se_mean)
print("SP:", sp_mean)
print("ACC: ", acc_mean)
print("MCC: ", mcc_mean)
print("F1: ", f1_mean)
print("AUC：",auc_mean)


mat=eval(input())
friendly=int(input())
price=int(input())
distance=int(input())
id=[]
points=[]
result=[]
sum=len(mat)
for i in range(sum-1,-1,-1):
    item=mat[i]
    if item[2]<friendly or item[3]>price or item[4]>distance:
        continue
    else:
        id.append((item[0],item[1]))
        points.append(item[1])
points.sort()
points=points[::-1]
length=len(points)
for i in range(0,length):
    for item in id:
        if item[1] == points[0]:
            result.append(item[0])
            del points[0]
            ind=id.index(item)
            del id[ind]
            break
print(result)


import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os, sys

def cost(X, y, theta):
    h = np.dot(X, theta)
    cos = np.sum((h - y) * ( h - y))/(2 * len(y))
    return cos

def gradient_descent(X, y, theta, alpha, num_iters):
    m = len(y)
    costs = []
    for _ in range(num_iters):
        h = np.dot(X, theta)
        theta -= alpha * np.dot(X.T, (h - y))/m
        costs.append(cost(X, y, theta))
    return theta, costs

def linear_regression(X, y, alpha = 0.01,num_iters = 100):
    X = np.append(np.ones((X.shape[0], 1)), X, axis = 1)
    theta = np.zeros((X.shape[1], 1), dtype = np.float64)
    theta, costs = gradient_descent(X, y, theta, alpha, num_iters)
    predicted = np.dot(X, theta)
    return predicted, theta, costs

if __name__ == '__main__':
    images_dir = os.path.join(sys.path[0], 'images')
    if not os.path.exists(images_dir):
        os.makedirs(images_dir)

    X = np.array(range(25))
    y = (X ** 1.3 + np.random.normal(10, 10, X.shape[0]))
    X, y = X.reshape((-1, 1)), y.reshape((-1, 1))
    # data = np.loadtxt(os.path.join(sys.path[0], 'linear_regression_data.csv'), delimiter = ',', dtype = np.float64)
    # X, y = data[:, :-1], data[:, -1].reshape((-1, 1))

    predicted, theta, costs = linear_regression(X, y)

    sns.scatterplot(X[:, 0], y.flatten())
    plt.title('Dataset')
    plt.ylabel('Y')
    plt.xlabel('X')
    plt.savefig(os.path.join(images_dir, 'data.png'))
    plt.clf()

    sns.lineplot(range(100), costs)
    plt.title('Cost vs Number of Interations')
    plt.ylabel('Cost')
    plt.xlabel('No. of Interations')
    plt.savefig(os.path.join(images_dir, 'cost.png'))
    plt.clf()

    sns.lineplot(X[:, 0], predicted.flatten())
    sns.scatterplot(X[:, 0], y.flatten())
    for i, x in enumerate(X):
        plt.vlines(x, min(predicted[i], y[i]), max(predicted[i], y[i]))
    plt.ylabel('Y')
    plt.xlabel('X')
    plt.title('Error')
    plt.legend(('linear fit', 'data'))
    plt.savefig(os.path.join(images_dir, 'Error.png'))
    plt.clf()


from os.path import exists, expanduser
import pandas as pd
import time

class ExecExcel:
    """
    read xlsx and csv
    """
    def __init__(self, file_path):
        self.file_path = expanduser(file_path)

    def read(self, sheet='Sheet1', axis=0, index_col=None, **kwargs):
        df = pd.ExcelFile(self.file_path)
        sheets = [sheet] if sheet else df.sheet_names
        df_parse = df.parse(sheets, index_col=index_col, **kwargs)
        frame_data = pd.concat(df_parse, axis=axis)
        return ExcelResponse(frame_data, self.file_path)

    def read_csv(self, **kwargs):
        frame_data = pd.read_csv(self.file_path, **kwargs)
        return ExcelResponse(frame_data, self.file_path)

    def data_format(self, data: list, axis=0):
        """
        Write data to excel.
        :param axis:
        :param data: dict in list
        """
        fd = [pd.DataFrame(item, index=[0]) for item in data]
        frame_data = pd.concat(fd, axis=axis)
        return ExcelResponse(frame_data, self.file_path)

    def append_row(self, data: list, sheet='Sheet1', axis=0, index_col=None, **kwargs):
        if exists(self.file_path):
            df = pd.ExcelFile(self.file_path)
            sheets = [sheet] if sheet else df.sheet_names
            df_parse = df.parse(sheets, index_col=index_col, **kwargs)
            frame_data = pd.concat(df_parse, axis=axis)
        else:
            frame_data = pd.DataFrame()
        new_data = pd.concat([pd.DataFrame(item, index=[0]) for item in data], axis=axis)
        frame_data = pd.concat([frame_data, new_data], axis=axis)
        return ExcelResponse(frame_data, self.file_path)

class ExcelResponse:
    def __init__(self, frame_data, file_path: str):
        self.frame_data = frame_data
        self.file_path = file_path

    def extract_data(self, orient='records', empty=False, nana=None):
        """
        :param empty: if True show empty value
        :param orient:
        {
        orient=’records’: [{column -> value}, … , {column -> value}],
        orient=’index’  : {index -> {column -> value}},
        orient=’dict’   : {column -> {index -> value}},
        orient=’list’   : {column -> [values]} ,
        orient=’series’ : {column -> Series(values)},
        orient=’split’  : {index -> [index], columns -> [columns], data -> [values]},
        }
        :param nana: null display NaNa/None/''
        :return: dict : generator object
        """
        frame_data = self.frame_data.where(self.frame_data.notnull(), nana)
        data_load = frame_data.to_dict(orient=orient)
        if orient == 'records':
            for index, value in enumerate(data_load):
                yield {k: v for k, v in value.items()} if empty else {k: v for k, v in value.items() if v}
        else:
            for index, value in data_load.items():
                if value is dict:
                    yield index, {k: v for k, v in value.items()} if empty else {k: v for k, v in value.items() if v}
                else:
                    yield {index: value}

    def to_excel(self, sheet="Sheet1", file_path=None, index=False, **kwargs):
        """
        Write data to excel.
        :param index:
        :param file_path: save excel file name
        :param sheet: excel sheet name
        """
        file_path = file_path or self.file_path.rsplit('.')[0] + f'_{int(time.time())}.xlsx'
        self.frame_data.to_excel(file_path, index=index, sheet_name=sheet, **kwargs)


#Uses python3
import sys
import math

def minimum_distance(n, edges):
    #sort by distance
    sorted_edges = sorted(edges, key=lambda x:x[2])

    connection = []
    for j in range(n):
        connection.append(j)

    min_dist = 0
    for i in sorted_edges:
        print(connection, connection[i[1]], connection[i[0]])
        if connection[i[0]] != connection[i[1]]:
            min_dist += i[2]
            connection = list(map(lambda x: connection[i[0]] if x == connection[i[1]] else x,connection))

    return min_dist

if __name__ == '__main__':
    n_vertices = int(input())
    points = []
    for i in range(n_vertices):
        a,b = map(int, input().split())
        points.append((a,b))
    edges = []
    for i in range(n_vertices):
        #strat
        (x0, y0) = points[i]
        for j in range(i+1, n_vertices):
            (x,y) = points[j] #end
            distance = math.sqrt((x - x0) ** 2 + (y - y0) ** 2)
            edges.append((i,j, distance))
    print("{0:.9f}".format(minimum_distance(n_vertices,edges)))

Coursera_Data_Structures_and_Algorithms_Specialization/3. Algorithms on Graphs/week5_spanning_trees/connecting_points.py


def groupAnagrams(strs: list) -> list:

    def list2str(l: list) -> str:
        res = ""
        for ll in l:
            res += str(ll)
        return res

    tmp = dict()
    res = list()
    for s in strs:
        t = [0] * 26
        for ss in s:
            t[ord(ss) - ord("a")] += 1

        str_t = list2str(t)
        if str_t in tmp.keys():
            tmp[str_t].append(s)
        else:
            tmp[str_t] = [s]
    res = list(tmp.values())
    return res

def groupAnagrams2(strs: list) -> list:
    m = dict()
    for s in strs:
        tmp = "".join(sorted(s))
        if tmp not in m:
            m[tmp] = list()
        m[tmp].append(s)

    return list(m.values())

if __name__ == "__main__":
    strs = ["eat","tea","tan","ate","nat","bat"]
    print(groupAnagrams2(strs))


from flask import Blueprint, jsonify, request
from api.middleware import login_required, read_token

from api.models.db import db
from api.models.issue import Issue

issues = Blueprint('issues', 'issues')

@issues.route('/', methods=["POST"])
@login_required
def create():
  data = request.get_json()
  profile = read_token(request)
  data["profile_id"] = profile["id"]

  issue = Issue(**data)
  db.session.add(issue)
  db.session.commit()
  return jsonify(issue.serialize()), 201

@issues.route('/', methods=["GET"])
def index():
  issues = Issue.query.all()
  return jsonify([issue.serialize() for issue in issues]), 201

@issues.route('/<id>', methods=["GET"])
def show(id):
  issue = Issue.query.filter_by(id=id).first()
  issue_data = issue.serialize()
  return jsonify(issue=issue_data), 200

@issues.route('/<id>', methods=["PUT"])
@login_required
def update(id):
  data = request.get_json()
  profile = read_token(request)
  issue = Issue.query.filter_by(id=id).first()

  if issue.profile_id != profile["id"]:
    return 'Forbidden', 403

  for key in data:
    setattr(issue, key, data[key])

  db.session.commit()
  return jsonify(issue.serialize()), 200

@issues.route('/<id>', methods=["DELETE"])
@login_required
def delete(id):
  profile = read_token(request)
  issue = Issue.query.filter_by(id=id).first()

  if issue.profile_id != profile["id"]:
    return 'Forbidden', 403

  db.session.delete(issue)
  db.session.commit()
  return jsonify(message="Success"), 200


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file ostap/fitting/roofitresult.py
#  Module with decoration of some RooFit objects for efficient use in python
#  @see RooFitResult
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
# =============================================================================
"""Decoration of some RooFit objects for efficient use in python
- see RooFitResult
"""
# =============================================================================
__version__ = "$Revision$"
__author__  = "Vanya BELYAEV Ivan.Belyaev@itep.ru"
__date__    = "2011-06-07"
__all__     = (
    )
# =============================================================================
from   builtins import range
from   ostap.core.meta_info     import root_info
from   ostap.core.core          import Ostap, VE, valid_pointer, iszero, isequal
from   ostap.core.ostap_types   import string_types , integer_types
import ostap.math.linalg
import ostap.fitting.variables
import ostap.fitting.printable
from   ostap.logger.colorized   import allright, attention
from   ostap.logger.utils       import pretty_float, pretty_ve, pretty_2ve
import ROOT, math, sys
# =============================================================================
from   ostap.logger.logger import getLogger
if '__main__' ==  __name__ : logger = getLogger ( 'ostap.fitting.roofitresult' )
else                       : logger = getLogger ( __name__                     )
# =============================================================================
_new_methods_ = []

# =============================================================================
## get parameters from RooFitResult
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
def _rfr_params_ (self , float_only = True ) :
    """GetParameters from RooFitResult:
    >>> result = ...
    >>> params = results
    >>> p0     = params()['A'][0]  ## get the value
    >>> p0s    = params()['A'][1]  ## get the parameter itself
    """
    pars  = self.floatParsFinal()
    pars_ = {}
    for p in pars :
        pars_ [ p.GetName() ] = p.as_VE(), p

    ## also fixed parameters?
    if not float_only :
        fixed = self.constPars()
        for p in fixed :
            pars_ [ p.GetName() ] = p.as_VE(), p

    return pars_

# ==============================================================================
## get numerical values of all parameters as simple dictionary
#  @code
#  result = ...
#  dct = results.dct_params()
#  @endcode
def _rfr_dct_params_ ( self ) :
    """Get numerical values of all parameters as simple dictionary
    >>> result = ...
    >>> dct = results.dct_params()
    """
    pars_ = {}

    for p in self.floatParsFinal():
        pars_ [ p.GetName () ] = p.as_VE()

    for p in self.constPars() :
        pars_ [ p.GetName () ] = p.getValue()

    return pars_

# =============================================================================
## get parameter by name  from RooFitResult
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
def _rfr_param_  ( self , pname , float_only = False ) :
    """Get Parameter from RooFitResult by name
    >>> result = ...
    >>> signal = results.param('Signal')
    >>> print signal
    """
    if not isinstance ( pname , str ) :
        if   hasattr ( pname , 'GetName' ) : pname = pname.GetName ()
        elif hasattr ( pname , 'getName' ) : pname = pname.getName ()
        elif hasattr ( pname , 'name'    ) : pname = pname.   name ()
    p = self.parameters ( float_only )[ pname ]
    return p

# =============================================================================
## check if certain parameter (or index) is in RooFitResult object
#  @code
#  fit_result = ...
#  print ( 1      in fit_results )
#  print ( 'mean' in fit_results )
#  print ( 'A'    in fit_results )
#  @endcode
def _rfr_contains_ ( self , label ) :
    """Check if certain parameter (or index) is in RooFitResult object
    >>> fit_result = ...
    >>> print ( 1      in fit_results )
    >>> print ( 'mean' in fit_results )
    >>> print ( 'A'    in fit_results )
    """

    if   isinstance ( label , integer_types ) :
        return 0 <= label < len ( self.floatParsFinal() ) + len ( self.constPars () )
    elif isinstance ( label , string_types  ) :
        return label in  self.floatParsFinal() or label in self.constPars ()
    elif isinstance ( label , ROOT.RooAbsArg ) :
        return label.GetName() in self

    return False

# =============================================================================
## iterator over fit results
def _rfr_iter_ ( self ) :
    """Iterator over fit results :
    >>> fit_result = ...
    >>> for i in fit_results : print i
    """
    pars  = self.floatParsFinal()
    for p in pars  : yield p
    fixed = self.constPars     ()
    for f in fixed : yield f

# =============================================================================
## iterator over fit items
def _rfr_iteritems_ ( self , float_only = False ) :
    """Iterator over fit items:
    >>> fit_result = ...
    >>> for name,var in fit_results.iteritems() :
    ...                   print name,var.as_VE()
    """
    pars  = self.floatParsFinal()
    for p in pars  :
        yield p.GetName() , p

    if not float_only :
        fixed = self.constPars ()
        for f in fixed :
            yield f.GetName() , f

# =============================================================================
## get the correlation coefficient
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
def _rfr_corr_  ( self , var1 , var2 ) :
    """Get correlation coefficient for two parameters
    >>> result = ...
    >>> corr = results.corr('Signal', 'Background')
    >>> print corr
    """
    if isinstance ( var1 ,  str ) : var1 = self.param ( var1 )[1]
    if isinstance ( var2 ,  str ) : var2 = self.param ( var2 )[1]
    #
    if var1 in self.constPars() : return 0.0
    if var2 in self.constPars() : return 0.0
    #
    return self.correlation ( var1 , var2 )

# =============================================================================
## get the covariance (sub) matrix
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
def _rfr_cov_matrix_  ( self , var1 , var2 , *vars ) :
    """Get covariance (sub) matrix
    >>> result = ...
    >>> cov = results.cov_matrix('Signal', 'Background')
    >>> print corr
    """

    if isinstance ( var1 , str ) : var1 = self.param (   var1 ) [1]
    if isinstance ( var2 , str ) : var2 = self.param (   var2 ) [1]

    args = ROOT.RooArgList ( var1 , var2 )
    for v in vars :
        if isinstance ( v , str ) : v = self.param ( v ) [1]
        args.add ( v )

    cm = self.reducedCovarianceMatrix (  args )
    N  = cm.GetNrows()

    import ostap.math.linalg
    m  = Ostap.Math.SymMatrix ( N )()

    for i in range ( N ) :
        for j in  range ( i , N ) :
            m [i,j] = cm(i,j)

    return m

# =============================================================================
## get the covariance matrix
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
def _rfr_covmatrix_  ( self ) :
    """Get covariance ( matrix
    >>> result = ...
    >>> cov = results.covmatrix()
    >>> print corr
    """

    cm = self.covarianceMatrix ()
    N  = cm.GetNrows()

    import ostap.math.linalg
    m  = Ostap.Math.SymMatrix ( N )()

    for i in range ( N ) :
        for j in  range ( i , N ) :
            m [i,j] = cm(i,j)

    return m

# ============================================================================
## get the required results in form of SVectorWithError object
#  @code
#  fit_resuts = ...
#  res   = fit_results.results( 'A', 'B' , 'C' )
#  print res, res.cov2()
#  @endcode
#  @see Ostap::Math::SVectorWithError
def _rfr_results_( self , *vars ) :
    """Get the required results in form of SVectorWithError object
    >>> fit_resuts = ...
    >>> res   = fit_results.results( 'A', 'B' , 'C' )
    >>> print res, res.cov2()
    """

    if not vars :
        pars = self.floatParsFinal()
        vars = [ p.name  for p in pars ]
        logger.debug ( 'Use parameters %s' % vars )

    if not vars :
        return None

    elif 1 == len ( vars ) :
        return self.param ( vars [0]) [0]

    args = ROOT.RooArgList ()
    for v in vars :
        if isinstance ( v , str ) : v = self.param ( v ) [1]
        args.add ( v )

    cm = self.reducedCovarianceMatrix (  args )
    N  = cm.GetNrows()

    import ostap.math.linalg
    m  = Ostap.Math.SymMatrix ( N )()
    v  = Ostap.Math.Vector    ( N )()

    S  = Ostap.Math.SVectorWithError  ( N )

    v  = S()
    c2 = v.cov2()

    for i , a  in enumerate ( args ) :
        v [ i ] = float ( a )
        for j in range ( i , N ) :
            c2 [ i , j ] = cm ( i , j )

    return v

# ==============================================================================
## Get vector of eigenvalues for the covariance matrix
#  @code
#  result = ...
#  eigenvalues =  result.cov_eigenvalues()
#  @endcode
def _rfr_eigenvalues_ ( self , sorted = True ) :
    """Get vector of eigenvalues for the covarinace matrix
    >>> result = ...
    >>> eigenvalues =  result.cov_eigenvalues()
    """
    cm = _rfr_covmatrix_ ( self )
    return Ostap.Math.EigenSystems.eigenValues ( cm , sorted )

# =============================================================================
## get the covariance (sub) matrix
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
def _rfr_cov_  ( self , var1 , var2 ) :
    """Get covariance (sub) matrix
    >>> result = ...
    >>> cov = results.cov('Signal', 'Background')
    >>> print corr
    """
    if isinstance ( var1 ,  str ) : var1 = self.param ( var1 )[1]
    if isinstance ( var2 ,  str ) : var2 = self.param ( var2 )[1]
    #
    if var1 in self.constPars() : return 0.0
    if var2 in self.constPars() : return 0.0
    #
    r  = self.correlation ( var1 , var2 )
    #
    v1 = var1.error
    v2 = var2.error
    #
    return v1 * v2 * r

# ===============================================================================
## find a maximal correlation coefficient for the given variable
#  @code
#  result = ...
#  coefficient , variable = result.max_cor ( 'x' )
#  @endcode
def _rfr_max_cor_ ( self , v ) :
    """ Find a maximal correlation coefficient for the given variable
    >>> result = ...
    >>> coefficient , variable = result.max_cor ( 'x' )
    """

    if isinstance ( v ,  str ) : v = self.param ( v )[1]
    if v in self.constPars() : return 0 , ''

    pars = self.floatParsFinal()
    assert v in pars, 'Unknown variable %s' % v

    if 1 == len ( pars ) : return 0 , ''

    rmax = None
    pmax = None
    for p in pars :
        if v is p : continue
        r =  self.correlation ( v , p )
        assert -1 <= r <= 1 or isequal ( abs ( r ) , 1 ) ,\
               'Invalid correlation coefficient for (%s,%s):%s' % ( v.name , p.name , r )

        if ( rmax is None ) or ( pmax is None ) or abs ( r ) > abs ( rmax ) :
            rmax = r
            pmax = p.name

    return rmax , pmax

# ===============================================================================
## get fit-parameter as attribute
#  @code
#  fit_result = ...
#  sigma = fit_resul.sigma
#  @endcode
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2014-08-03
def _rfr_getattr_ ( self , att ) :
    """Get fit-parameter as attribute
    >>> r = ....
    >>> print( 'sigma is', r.sigma)
    """
    ##
    pars = self.floatParsFinal()
    for p in pars :
        if att == p.GetName() : return p
    #
    pars = self.constPars()
    for p in pars :
        if att == p.GetName() : return p

    raise AttributeError ( "RooFitResult: invalid attribute `%s'" % att )

# =============================================================================
## get fit-parameter through the key/name
#  @code
#  fit_result = ...
#  sigma = fit_result['sigma']
#  @endcode
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2014-08-03
def _rfr_getitem_ ( self , key  ) :
    """Get fit-parameter through the key/name
    >>> fit_result = ...
    >>> sigma = fit_result['sigma']
    """

    ##
    pars = self.floatParsFinal()
    for p in pars :
        if key == p.GetName() : return p
    #
    pars = self.constPars()
    for p in pars :
        if key == p.GetName() : return p

    raise KeyError ( 'RooFitResult: invalid key %s ' % key  )

# ===========================================================================
## get correct estimate of sum of two (or more) variables,
#  taking into account correlations
#  @code
#  >>> r = ...
#  >>> print r.sum( 'S' , 'B' )  ## S+B
#  @endcode
def _rfr_sum_ ( self , var1 , var2 , *vars ) :
    """Get correct estimate of sum of two or more variables,
    taking into account correlations
    >>> r = ...
    >>> print r.sum( 'S' , 'B' ) ## S+B
    """
    allvars = ( var1 , var2 ) + vars
    n       = len ( allvars )
    s  = 0.0
    c2 = 0.0
    for i in range ( n ) :
        vi = allvars [ i ]
        if isinstance ( vi , str ) : vi = self.param ( vi ) [1]
        v   = vi.value
        v   = VE ( v )
        s  += v . value ()
        vc  = v.cov2()
        if 0 >= vc or vi in self.constPars() : continue
        c2 += vc
        for j in range ( i ) :
            vj  = allvars [ j ]
            if isinstance ( vj , str ) : vj = self.param ( vj ) [1]
            if vj in self.constPars() : continue
            c2 += 2 * self.covariance ( vi , vj )

    return VE ( s , c2 )

# ===========================================================================
## get correct estimate of product of two variables,
#  taking into account correlations
#  @code
#  >>> r = ...
#  >>> print r.multiply( 'S' , 'B' ) ## S*B
#  @endcode
#  @see Gaudi:Math::multiply
def _rfr_multiply_ ( self , var1 ,  var2 , *vars ) :
    """Get correct estimate of product of two variables,
    taking into account correlations
    >>> r = ...
    >>> print r.multiply( 'S' , 'B' ) ## S*B
    """
    allvars = ( var1 , var2 ) + vars
    n       = len ( allvars )

    m  = 1.0
    c2 = 0
    for i in range ( n ) :
        vi = allvars[i]
        if isinstance ( vi , str ) : vi = self.param ( vi )[1]
        v  = vi.value
        v  = VE ( v )
        vv = v.value ()
        if iszero ( vv ) or iszero ( m ) : return  VE ( 0.0 , 0.0 )   ## RETURN HERE
        m  *= vv
        vc  = v.cov2()
        if 0 >= vc or vi in self.constPars() : continue
        c2 += vc / ( vv * vv )
        for j in range ( i  ) :
            vj  = allvars [ j ]
            if isinstance ( vj , str ) : vj = self.param( vj )[1]
            if vj in self.constPars()  : continue
            w   = vj . value
            w   = VE ( w )
            ww  = w.value()
            c2 += 2 * self.covariance ( vi , vj ) / ( vv * ww )

    return  VE ( m , c2 * m * m )

# ===========================================================================
## get correct estimate of division  of two variables,
#  taking into account correlations
#  @code
#  >>> r = ...
#  >>> print r.divide( 'S' , 'B' ) ## S/B
#  @endcode
#  @see Ostap:Math::divide
def _rfr_divide_ ( self , var1 , var2 ) :
    """Get correct estimate of division of two variables,
    taking into account correlations
    >>> r = ...
    >>> print r.divide( 'S' , 'B' ) ## S/B
    """
    if isinstance ( var1 , str ) : var1 = self.param ( var1 ) [1]
    if isinstance ( var2 , str ) : var2 = self.param ( var2 ) [1]
    _v1  = var1.value
    _v2  = var2.value
    _cor = self.corr  ( var1 , var2 )
    return Ostap.Math.divide ( _v1 , _v2 , _cor )

# ===========================================================================
## get correct estimate of subtraction of two variables,
#  taking into account correlations
#  @code
#  >>> r = ...
#  >>> print r.subtract( 'S' , 'B' ) ## S-B
#  @endcode
#  @see Ostap:Math::subtract
def _rfr_subtract_ ( self , var1 , var2 ) :
    """Get correct estimate of subtraction of two variables,
    taking into account correlations
    >>> r = ...
    >>> print r.subtract( 'S' , 'B' ) ## S-B
    """
    if isinstance ( var1 , str ) : var1 = self.param ( var1 ) [1]
    if isinstance ( var2 , str ) : var2 = self.param ( var2 ) [1]
    _v1  = var1.value
    _v2  = var2.value
    _cor = self.corr  ( var1 , var2 )
    return Ostap.Math.subtract ( _v1 , _v2 , _cor )

# ===========================================================================
## get correct estimate of fraction  of two variables,
#  taking into account correlations
#  @code
#  >>> r = ...
#  >>> print r.fraction( 'S' , 'B' ) ## S/(S+B)
#  @endcode
#  @see Gaudi:Math::divide
def _rfr_fraction_ ( self , var1 , var2 ) :
    """Get correct estimate of fraction of two variables,
    taking into account correlations
    >>> r = ...
    >>> print r.fraction( 'S' , 'B' ) ##   S/(S+B)
    """
    if isinstance ( var1 , str ) : var1 = self.param ( var1 ) [1]
    if isinstance ( var2 , str ) : var2 = self.param ( var2 ) [1]
    _av1  = abs ( var1.value.value() )
    _av2  = abs ( var2.value.value() )
    if _av1 >= _av2 : return 1 / ( 1 + self.ratio ( var2 , var1 ) )
    return 1.0 - self.fraction ( var2 , var1 )

# ===========================================================================
## get correct estimate of asymmetry of two variables (v1-v2)/(v1+v2)
#  taking into account correlations
#  @code
#  >>> r = ...
#  >>> print r.asymmetry( 'A' , 'B' ) ## (A-B)/(A+B)
#  @endcode
#  @see Gaudi:Math::divide
def _rfr_asymmetry_ ( self , var1 , var2 ) :
    """Get correct estimate of asymmetry of two variables, (v1-v2)/(v1+v2)
    taking into account correlations
    >>> r = ...
    >>> print r.asymmetry( 'A' , 'B' ) ##   (A-B)/(A+B)
    """
    if isinstance ( var1 , str ) : var1 = self.param ( var1 ) [1]
    if isinstance ( var2 , str ) : var2 = self.param ( var2 ) [1]
    ##
    _av1 = abs ( var1.value.value() )
    _av2 = abs ( var2.value.value() )
    _one = VE  ( 1 , 0 )

    if _av1 <= _av2 :
        return      self.ratio ( var1 , var2 ) . asym ( _one )
    else :
        return -1 * self.ratio ( var2 , var1 ) . asym ( _one )

# =============================================================================
## evaluate the certain  function/expression for the fit   result
# @code
# func = lambda x , y , z : x*x+y*y+z*z
# res = ... # RooFitResult object
# val = re.evaluate ( func , ( 'x' , 'y' , 'z' ) )
# @endcode
def _rfr_evaluate_ ( self , func , args , partial = () ) :
    """Evaluate the certain  function/expression for the fit   result
    >>> func = lambda x , y , z : x*x+y*y+z*z
    >>> res = ... # RooFitResult object
    >>> val = re.evaluate ( func , ( 'x' , 'y' , 'z' ) )
    """
    res   = _rfr_results_ ( self , *args )
    val   = res.value()
    cov2  = res.cov2 ()
    N     = len ( val )
    from ostap.math.derivative import EvalNVEcov
    func2 = EvalNVEcov ( func , N = N , partial = partial )
    return func2 ( args = val , cov2 = cov2 )

# =============================================================================
## print RooFitResult as a table
#  @code
#  result = ...
#  result.table()
#  @endcode
def _rfr_table_ ( rr , title = '' , prefix = '' , more_vars = {} ) :
    """ print RooFitResult  as a table
    >>> result = ...
    >>> result.table()
    """

    r = Ostap.Utils.FitResults ( rr )

    from  ostap.fitting.utils    import fit_status, cov_qual
    rows = []

    ##  1. fit status
    status = r.status()
    if status :
        row = attention ( 'Status' )  , '' , attention ( fit_status ( status ) ) , ''
        rows.append ( row )
    else :
        row = 'Status'                , '' , allright  ( fit_status ( status ) ) , ''
        rows.append ( row )

    ## 2. minumum NLL
    s , n = pretty_float ( r.minNll() )
    if n : n = '[10^%+d]' % n
    else : n = ''

    rows.append ( ( "Minimized FCN/NLL value"    , n , '  ' + s , '' ) )

    s , n = pretty_float ( r.edm () )
    if n : n = '[10^%+d]' % n
    else : n = ''

    rows.append ( ( 'Estimated distance to minimum' , n , '  ' + s , '' ) )

    cq = r.covQual()
    cn = ''
    if  -1 == cq :
        cn = cov_qual  ( cq )
    elif 3 == cq :
        cn = allright  ( cov_qual ( cq ) )
    elif cq in (  0 , 1 , 2 ) :
        cn = attention ( cov_qual ( cq ) )
    else :
        cn = cov_qual  ( cq )

    rows.append ( ( 'Covariance matrix quality'     , '' , '  ' + cn , '' ) )

    for i in  range ( r.numStatusHistory() ) :
        label =  r.statusLabelHistory ( i )
        code  =  r.statusCodeHistory  ( i )
        row   =  'Status: %s '% label   , '' ,             '%d' % code
        if not code in ( 0 , -1 ) :
            row = attention  ( row [ 0 ] ) , row [ 1 ] , '   ' + attention ( row [ 2 ] ) , ''
        else    :
            row =              row [ 0 ]   , row [ 1 ] , '   ' + allright  ( row [ 2 ] ) , ''
        rows.append ( row )

    nbadnll = r.numInvalidNLL()
    if 0 < nbadnll :
        rows.append ( ( 'Invalid FCN/NLL evaluations' , '' , '  %d' % nbadnll , '' ) )

    with_globcorr = not ( (6,24) <= root_info < (6,28) )
    with_globcorr = True or not ( (6,24) <= root_info < (6,28) )
    with_globcorr = True
    with_globcorr = not ( (6,24) <= root_info < (6,26) )

    if with_globcorr : rows = [ ( '', 'Unit', 'Value' , 'Global/max correlation [%]') ] + rows
    else             : rows = [ ( '', 'Unit', 'Value' , 'Max correlation [%]') ] + rows

    pars_all   = r.params ( float_only = False )
    pars_float = r.params ( float_only = True  )

    ## constant/fix parameters
    crows = []
    for p in pars_all :

        if p in pars_float : continue
        v , a = pars_all [ p ]

        s , n = pretty_float  ( v.value()  )

        if n : n = '[10^%+d]' % n
        else : n = ''
        row = p , n , '  ' + s + ' (fix)' , ''
        crows.append ( row )

    ## floating parameters
    max_corr = False
    frows    = []
    for p in pars_float :

        v , a = pars_float [ p ]

        if not a.hasAsymError() :
            s , n = pretty_ve  ( v )
        else :
            s , n = pretty_2ve (  a.getVal() , a.getAsymErrorHi() , a.getAsymErrorLo() )

        if n : n = '[10^%+d]' % n
        else : n = ''

        if 0 <= cq and 1 < len ( pars_float ) :

            mxr , mxv = r.max_cor    ( p )

            if with_globcorr :

                gc = -1.0
                ## gc    = r.globalCorr ( p ) if 3 == cq else -1.00
                gc    = r.global_corr ( p ) if 3 == cq else -1.00

                if 0 <= gc :  cc = '% +5.1f/(% +5.1f,%s)' % ( gc*100 , mxr*100   , mxv )
                else       :  cc = '% +5.1f : %-s'        % (          mxr * 100 , mxv )
                if 0.95 < abs ( mxr ) or 0.95 < gc : cc = attention ( cc )

            else :

                cc = '% +5.1f : %-s'  % ( mxr * 100 , mxv )
                if 0.95 < abs ( mxr ) : cc = attention ( cc )

                max_corr = True

            row = p , n , s , cc

        else :

            row = p , n , s

        frows.append ( row )

    ## more parameters
    mrows = []
    for p in sorted ( more_vars ) :

        func  = more_vars [ p ]

        v     = func ( r )

        s , n = pretty_ve  ( v )

        if n : n = '[10^%+d]' % n
        else : n = ''

        cc = 'derived'
        row = p , n , s , cc
        mrows.append ( row )

    crows.sort()
    frows.sort()

    all = rows + crows + frows + mrows

    import ostap.logger.table as T

    return T.table ( all , title = title if title else r.GetTitle() , prefix = prefix , alignment = 'llll' )

# =============================================================================
## 'easy' print of RooFitResult
#  @author Vanya BELYAEV Ivan.Belyaev@itep.ru
#  @date   2011-06-07
def _rfr_print_ ( self , opts = 'v' ) :
    """Easy print of RooFitResult
    >>> result = ...
    >>> print result
    """
    if not valid_pointer ( self ) : return 'Invalid RooFitResult'

    ## 1. try to use table print
    table = _rfr_table_ ( self )
    lmax  = -1
    from ostap.utils.basic      import terminal_size
    _ , width = terminal_size()

    from ostap.logger.colorized import decolorize
    for row in table :
        lmax = max ( lmax , len ( decolorize ( row ) ) )
        if width < lmax : break

    ## if the table is narrow enough, print it
    if 10 < lmax and lmax < width : return table

    ## otherwise use naive RooFit print
    result = self.print_multiline ( content = 1 , verbose = True )
    if sys.version_info < ( 3 , 0 ) :
        if isinstance ( result , unicode ) :
            result = result.encode ('utf-8')
    return result

# =============================================================================
## Get global correlation coefficient for the parameter
#  \f$ \rho_k = \sqrt{    1 - \left[ C_{kk} V_{kk}\right]^{-1} } \f$
#  where \f$ C \f$ is covarinace matrix and \f$ V = C^{-1}\$ is inverse
#  @code
#  resut = ...
#  result.global_corr ( 'S' )
#  @endcode
#  It should be accessible via RooFitResult::globalCorr method
#  but often it results in segfault
#  @see RooFitResult::globalCorr
def _rfr_global_corr_ ( self , par ) :
    """ Get global correlation coefficient for the parameter
    rho_k = sqrt ( 1 - 1/( C_{kk} V_{kk}) )
    - where C is covariance  matrix and V is inverse

    It should be accessible via `RooFitResult.globalCorr`method
    but often it results in segfauls
    - see `RooFitResult.globalCorr`
    """
    if  isinstance  ( par , string_types    ) :
        index = self.floatParsFinal().index ( par )
        if index < 0 :                                     return -1
    elif isinstance ( par , integer_types   ) :
        if not 0 <= par < len ( self.floatParsFinal () ) : return -1
        index = par
    elif isinstance ( par , ROOT.RooAbsArg ) :
        return _rfr_global_corr_ ( self , par.name )
    else : return -1

    ## get the covariance matrix and invert it!
    v = self.covmatrix()
    if not v.InvertChol () : return -1

    ## get the covariance matrix
    c = self.covmatrix()

    cv = c ( index , index ) * v ( index , index )

    rho2 = 1.0 - 1.0 / cv
    if rho2 < 0 : return -1.0

    return  math.sqrt ( rho2 )

# =============================================================================
##

# =============================================================================
## Symmetrized Kullback-Leibler divergency between two RooFitResult objects
#  @code
#  r1 = ...
#  r2 = ...
#  r1.kullback( r2 )
#  @endcode
def _rfr_kullback_ ( r1 , r2 ) :
    """Symmetrized Kullback-Leibler divergency between two RooFitResult objects
    >>> r1 = ...
    >>> r2 = ...
    >>> r1.kullback( r2 )
    """
    result = -999.0

    ## 1. check structure: constant parameters
    s1 = set ( p.name for p in r1.constPars() )
    s2 = set ( p.name for p in r2.constPars() )
    if s1 != s2 :
        logger.error ("Constant parameters are different!")
        return result

    ## 2. check structure: floating parameters
    s1 = set ( p.name for p in r1.floatParsFinal() )
    s2 = set ( p.name for p in r2.floatParsFinal() )
    if s1 != s2 :
        logger.error ("Floating parameters are different!")
        return result

    ## list of parameter names
    vars = tuple ( sorted ( s1 ) )

    ## 3. get the results
    results1 = r1.results ( *vars )
    results2 = r2.results ( *vars )

    ## 4. calculate the divergency
    result = results1.kullback_leibler ( results2 )
    if result <= -999  :
        logger.error ("Error from SVectorWithError::kullack_leibler")

    return result

# =============================================================================
## Run MIGRAD for RooMinimizer object
#  @code
#  pdf = ...
#  minuit = pdf.minuit()
#  minuit.migrad()
#  @endcode
#  @see RooMinimizer
def _rm_migrad_  ( self , refit = 0 , tag = "" , minos = () ) :
    """Run MIGRAD for RooMinimizer
    - see ROOT.RooMinimizer
    >>> pdf = ...
    >>> minuit = pdf.minuit()
    >>> minuit.migrad()
    """
    status = self._old_migrad_()
    if 0 != status :
        from   ostap.fitting.utils import fit_status
        message = "MIGRAD %s status %s"  % ( tag , fit_status ( status ) )
        if   isinstance ( refit , integer_types ) and 0 < refit :
            logger.error ( message +  ', refit... ')
            return _rm_migrad_ ( self ,  refit - 1 , tag )
        elif isinstance ( refit , bool          ) and     refit :
            logger.error ( message +  ', refit... ')
            return _rm_migrad_ ( self ,  False     , tag )
        logger.error ( message )
    elif minos :
        return self.minos ( *minos )

    return status

# =============================================================================
## run MINOS for set of parameters
#  @code
#  pdf = ...
#  minuit = pdf.minuit( ... )
#  minuit.migrad()
#  minuit.minos ( 'sigma' , 'mean' )
#  @endcode
def _rm_minos_ ( self , *variables ) :
    """Run MINOS for set of parameters
    >>> pdf = ...
    >>> minuit = pdf.minuit( ... )
    >>> minuit.migrad()
    >>> minuit.minos ( 'sigma' , 'mean' )
    """

    if not variables :
        status = self._old_minos_ ()
        if 0 != status :
            from   ostap.fitting.utils import fit_status
            logger.error ( "MINOS status %s"  % fit_status ( status ) )
        return status

    aset = ROOT.RooArgSet()
    res  = self.save()

    for v in variables :

        if   isinstance   ( v , string_types ) or isinstance ( v , ROOT.RooAbsReal ) :
            par = res.param ( v ) [ 1 ]
            if par : aset.add ( par )
        elif isinstance ( v , ROOT.RooAbsCollection ) or \
             isinstance ( v , list_types            ) :
            for a in v :
                if isinstance ( a , ROOT.RooAbsReal ) :
                    par = res.param ( a ) [ 1 ]
                    if par : aset.add ( par )

    del res

    if aset : status = self._old_minos_ ( aset )
    else    : status = self._old_minos_ (      )

    if 0 != status :
        from   ostap.fitting.utils import fit_status
        logger.error ( "MINOS status %s"  % fit_status ( status ) )

    return status

if not hasattr ( ROOT.RooMinimizer , '_old_migrad_' ) :
    ROOT.RooMinimizer._old_migrad_ = ROOT.RooMinimizer.migrad
    _rm_migrad_.__doc__ += '\n' + ROOT.RooMinimizer.migrad.__doc__
    ROOT.RooMinimizer.     migrad  = _rm_migrad_

if not hasattr ( ROOT.RooMinimizer , '_old_minos_' ) :
    ROOT.RooMinimizer._old_minos_  = ROOT.RooMinimizer.minos
    _rm_minos_.__doc__ += '\n' + ROOT.RooMinimizer.minos.__doc__
    ROOT.RooMinimizer.     minos   = _rm_minos_

# =============================================================================
## make 2D contours  in units of 'sigma'
#  @code
#  pdf    = ...
#  minuit = pdf.minuit( ... )
#  minuit.migrad()
#  contour = minuit.contour ( 'A' , 'B' )
#  @endcode
def _rm_contour_ ( self                   ,
                   var1                   ,
                   var2                   ,
                   npoints = 100          ,
                   *levels                ) :

    """Make 2D contours  in uniys  of 'sigma'
    >>> pdf    = ...
    >>> minuit = pdf.minuit( ... )
    >>> minuit.migrad()
    >>> contour = minuit.contour ( 'A' , 'B' )
    """

    assert isinstance ( npoints , integer_types ) and 2 < npoints ,\
           'Invalid number of points %s' % npoints

    res  = self.save ()
    if not isinstance ( var1 , ROOT.RooAbsReal ) :
        var1 = res.param ( var1 ) [ 1 ]
    if not isinstance ( var2 , ROOT.RooAbsReal ) :
        var2 = res.param ( var2 ) [ 1 ]

    n = 6 * [ 0.0 ]
    for i , l in enumerate ( levels ) :
        if len ( n ) <= i : break
        ll = float ( l )
        assert 0 <= l , 'Invalid level %s' % ll
        n [ i ] = ll

    return self._old_contour_ ( var1    , var2    ,
                                n [ 0 ] , n [ 1 ] ,
                                n [ 2 ] , n [ 3 ] ,
                                n [ 4 ] , n [ 5 ] , npoints )

if not hasattr ( ROOT.RooMinimizer , '_old_contour_' ) :
    ROOT.RooMinimizer._old_contour_ = ROOT.RooMinimizer.contour
    _rm_contour_.__doc__ += '\n' + ROOT.RooMinimizer.contour.__doc__
    ROOT.RooMinimizer. new_contour  = _rm_contour_
    ROOT.RooMinimizer. contour      = _rm_contour_

# =============================================================================
## some decoration over RooFitResult
## ROOT.RooFitResult . __repr__        = _rfr_print_
## ROOT.RooFitResult . __str__         = _rfr_print_
ROOT.RooFitResult . __repr__         = _rfr_table_
ROOT.RooFitResult . __str__          = _rfr_table_
ROOT.RooFitResult . __call__         = _rfr_param_
ROOT.RooFitResult . __getattr__      = _rfr_getattr_
ROOT.RooFitResult . __getitem__      = _rfr_getitem_
ROOT.RooFitResult . __iter__         = _rfr_iter_
ROOT.RooFitResult . __contains__     = _rfr_contains_
ROOT.RooFitResult . iteritems        = _rfr_iteritems_
ROOT.RooFitResult . dct_params       = _rfr_dct_params_
ROOT.RooFitResult . parameters       = _rfr_params_
ROOT.RooFitResult . params           = _rfr_params_
ROOT.RooFitResult . param            = _rfr_param_
ROOT.RooFitResult . parameter        = _rfr_param_
ROOT.RooFitResult . corr             = _rfr_corr_
ROOT.RooFitResult . cor              = _rfr_corr_
ROOT.RooFitResult . max_cor          = _rfr_max_cor_
ROOT.RooFitResult . max_corr         = _rfr_max_cor_
ROOT.RooFitResult . cov              = _rfr_cov_
ROOT.RooFitResult . covariance       = _rfr_cov_
ROOT.RooFitResult . cov_matrix       = _rfr_cov_matrix_
ROOT.RooFitResult . covmatrix        = _rfr_covmatrix_
ROOT.RooFitResult . parValue         = lambda s,n : s.parameter(n)[0]
ROOT.RooFitResult . sum              = _rfr_sum_
ROOT.RooFitResult . plus             = _rfr_sum_
ROOT.RooFitResult . multiply         = _rfr_multiply_
ROOT.RooFitResult . product          = _rfr_multiply_
ROOT.RooFitResult . subtract         = _rfr_subtract_
ROOT.RooFitResult . minus            = _rfr_subtract_
ROOT.RooFitResult . divide           = _rfr_divide_
ROOT.RooFitResult . ratio            = _rfr_divide_
ROOT.RooFitResult . fraction         = _rfr_fraction_
ROOT.RooFitResult . results          = _rfr_results_
ROOT.RooFitResult . evaluate         = _rfr_evaluate_
ROOT.RooFitResult . cov_eigenvalues  = _rfr_eigenvalues_
ROOT.RooFitResult . table            = _rfr_table_
ROOT.RooFitResult . global_corr      = _rfr_global_corr_
ROOT.RooFitResult . kullback         = _rfr_kullback_
ROOT.RooFitResult . kullback_leibler = _rfr_kullback_

_new_methods_ += [
    ROOT.RooFitResult . __repr__         ,
    ROOT.RooFitResult . __str__          ,
    ROOT.RooFitResult . __call__         ,
    ROOT.RooFitResult . __getattr__      ,
    ROOT.RooFitResult . __iter__         ,
    ROOT.RooFitResult . __contains__     ,
    ROOT.RooFitResult . iteritems        ,
    ROOT.RooFitResult . parameters       ,
    ROOT.RooFitResult . params           ,
    ROOT.RooFitResult . param            ,
    ROOT.RooFitResult . parameter        ,
    ROOT.RooFitResult . corr             ,
    ROOT.RooFitResult . cor              ,
    ROOT.RooFitResult . max_cor          ,
    ROOT.RooFitResult . max_corr         ,
    ROOT.RooFitResult . cov              ,
    ROOT.RooFitResult . covariance       ,
    ROOT.RooFitResult . parValue         ,
    ROOT.RooFitResult . sum              ,
    ROOT.RooFitResult . plus             ,
    ROOT.RooFitResult . multiply         ,
    ROOT.RooFitResult . product          ,
    ROOT.RooFitResult . subtract         ,
    ROOT.RooFitResult . minus            ,
    ROOT.RooFitResult . divide           ,
    ROOT.RooFitResult . ratio            ,
    ROOT.RooFitResult . fraction         ,
    ROOT.RooFitResult . results          ,
    ROOT.RooFitResult . evaluate         ,
    ROOT.RooFitResult . table            ,
    ROOT.RooFitResult . cov_eigenvalues  ,
    ROOT.RooFitResult . covmatrix        ,
    ROOT.RooFitResult . global_corr      ,
    ROOT.RooFitResult . kullback         ,
    ROOT.RooFitResult . kullback_leibler ,
    ]

# =============================================================================
_decorated_classes_ = (
    ROOT.RooFitResult ,
    ROOT.RooMinimizer ,
    )

_new_methods_ = tuple ( _new_methods_ )

# =============================================================================
if '__main__' == __name__ :

    from ostap.utils.docme import docme
    docme ( __name__ , logger = logger )

# =============================================================================
##                                                                     The END
# =============================================================================