class Room:
    room_cost = 0

    def __init__(self, name: str, budget: float, members_count: int):
        self.family_name = name
        self.budget = budget
        self.members_count = members_count
        self.children = []
        self.expenses = 0

    @property
    def expenses(self):
        return self.__expenses

    @expenses.setter
    def expenses(self, value):
        if value < 0:
            raise ValueError("Expenses cannot be negative")
        self.__expenses = value

    def calculate_expenses(self, *args):
        for sublist in args:
            self.expenses += sum(x.get_monthly_expense() for x in sublist)

    @property
    def monthly_total_consumption(self):
        return self.expenses + self.room_cost

    def __repr__(self) -> str:
        output = [f'{self.family_name} with {self.members_count} members. '\
                f'Budget: {self.budget:.2f}$, Expenses: {self.expenses:.2f}$']

        total_room_children_expenses = 0
        for i, child in enumerate(self.children, 1):
            monthly_child_expenses = child.get_monthly_expense()
            total_room_children_expenses += monthly_child_expenses
            output.append(f'--- Child {i} monthly cost: {monthly_child_expenses:.2f}$')

        output.append(f'--- Appliances monthly cost: {(self.expenses - total_room_children_expenses):.2f}$')

        return '\n'.join(output)


m = int(input())
win = [0,0]

tie = True
for i in range(3*m):
    rps = input().split()
    if rps == ['R','P']:
        win[1] += 1
    elif rps == ['P','R']:
        win[0] += 1
    elif rps == ['P','S']:
        win[1] += 1
    elif rps == ['S','P']:
        win[0] += 1
    elif rps == ['S','R']:
        win[1] += 1
    elif rps == ['R','S']:
        win[0] += 1
    if win[0] >= m:
        tie = False
        print(win[0],win[1])
        print("Player 1 wins")
        break
    elif win[1] >= m:
        tie = False
        print(win[0],win[1])
        print("Player 2 wins")
        break
if tie:
    print(win[0],win[1])
    print("Tie")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/3/13 20:27

#import some necessary librairies

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt  # Matlab-style plotting
import seaborn as sns
color = sns.color_palette()
sns.set_style('darkgrid')
import warnings
def ignore_warn(*args, **kwargs):
    pass
warnings.warn = ignore_warn #ignore annoying warning (from sklearn and seaborn)
from scipy import stats
from scipy.stats import norm, skew #for some statistics
pd.set_option('display.float_format', lambda x: '{:.3f}'.format(x)) #Limiting floats output to 3 decimal points
from subprocess import check_output
# print(check_output(["ls", "../input"]).decode("utf8")) #check the files available in the directory

train = pd.read_csv('../input/train.csv')
test = pd.read_csv('../input/test.csv')
# print(train.head(5))

print("The train data size before dropping Id feature is : {} ".format(train.shape))
print("The test data size before dropping Id feature is : {} ".format(test.shape))

train.drop("Id", axis = 1, inplace = True)
test.drop("Id", axis = 1, inplace = True)

print("\nThe train data size after dropping Id feature is : {} ".format(train.shape))
print("The test data size after dropping Id feature is : {} ".format(test.shape))

# fig, ax = plt.subplots()
# ax.scatter(x = train['GrLivArea'], y = train['SalePrice'])
# plt.ylabel('SalePrice', fontsize=13)
# plt.xlabel('GrLivArea', fontsize=13)
# plt.show()

# var = 'GrLivArea'
# # data = pd.concat([train['SalePrice'],train[var]],1)
# f, ax = plt.subplots()
# plt.scatter(x=train['GrLivArea'],y=train['SalePrice'])
# plt.show()

print(train.shape)
train = train.drop(train[(train['GrLivArea'] > 4000) & (train['SalePrice'] < 300000)].index)
print(train.shape)

# 观察SalePrcie数据分布
# sns.distplot(train['SalePrice'] , fit=norm)
#
# # Get the fitted parameters used by the function
# (mu, sigma) = norm.fit(train['SalePrice'])
# print( '\n mu = {:.2f} and sigma = {:.2f}\n'.format(mu, sigma))
#
# #Now plot the distribution
# plt.legend(['Normal dist. ($\mu=$ {:.2f} and $\sigma=$ {:.2f} )'.format(mu, sigma)],loc='best')
# plt.ylabel('Frequency')
# plt.title('SalePrice distribution')
#
# #Get also the QQ-plot
# fig = plt.figure()
# res = stats.probplot(train['SalePrice'], plot=plt)
# plt.show()

# 进行log变换
train['SalePrice'] = np.log(train['SalePrice'])
# sns.distplot(train['SalePrice'],fit=norm)
# (mu,sigma) = norm.fit(train['SalePrice'])
# print('the $\mu$ = {:.2f} \n the $\sigma$ = {:.2f}'.format(mu,sigma))
# plt.legend(['Norm distribution( $\mu$ = {:.2f} , $\sigma$ = {:.2f})'.format(mu,sigma)],loc='best')
# plt.ylabel('Frequency')
# plt.xlabel('SalePrice')
# plt.title('SalePrice distribution')
# fig = plt.figure()
# stats.probplot(train['SalePrice'],plot=plt)
# plt.show()

all_data = pd.concat([train,test],ignore_index=True)
ntrain = train.shape[0]
ntest = test.shape[0]
y_train = train.SalePrice.values
all_data.drop('SalePrice',1,inplace=True)
print(all_data.shape)

# 处理缺失数据
all_data_na = (all_data.isnull().sum() / len(all_data)) *100
all_data_na = all_data_na.drop(all_data_na[all_data_na == 0].index).sort_values(ascending=False)[:30]
missing_data = pd.DataFrame({'Missing Ratio':all_data_na})
# print(missing_data.head(20))

# 画数据丢失率
# sns.barplot(all_data_na.index,all_data_na.values)
# plt.xticks(rotation=90)
# plt.title('data missing percent')
# plt.show()

# 画数据相关性图
corrmat = train.corr()
# plt.subplots(figsize=(12,9))
# sns.heatmap(corrmat,vmax=0.9,square=True)
# plt.xticks(rotation=90)
# plt.yticks(rotation=360)
# plt.show()

# print(np.abs(corrmat['SalePrice']).sort_values())
var = ['PoolQC','MiscFeature','Alley','Fence','FireplaceQu','GarageType', 'GarageFinish', 'GarageQual', 'GarageCond',
       'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2','MSSubClass', 'MasVnrType']
# all_data['PoolQC'] = all_data['PoolQC'].fillna('None')
for v in var:
    all_data[v] = all_data[v].fillna('None')
# print('为null的值',max(all_data[var].isnull().sum()))

all_data['LotFrontage'] = all_data.groupby('Neighborhood')['LotFrontage'].transform(lambda x:x.fillna(x.median()))
var = ['GarageYrBlt', 'GarageArea', 'GarageCars','BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF',
       'BsmtFullBath', 'BsmtHalfBath','MasVnrArea']
for v in var:
    all_data[v] = all_data[v].fillna(0)

var = ['Electrical','MSZoning','KitchenQual','Exterior1st','Exterior2nd','SaleType']
for v in var:
    all_data[v] = all_data[v].fillna(all_data[v].mode()[0])

# print(all_data['Utilities'].value_counts())
all_data.drop('Utilities',1,inplace=True)

all_data["Functional"] = all_data["Functional"].fillna("Typ")
print(max(all_data.isnull().sum()))

#MSSubClass=The building class
all_data['MSSubClass'] = all_data['MSSubClass'].astype(str)

#Changing OverallCond into a categorical variable
all_data['OverallCond'] = all_data['OverallCond'].astype(str)

#Year and month sold are transformed into categorical features.
all_data['YrSold'] = all_data['YrSold'].astype(str)
all_data['MoSold'] = all_data['MoSold'].astype(str)

from sklearn.preprocessing import LabelEncoder

# my1 = pd.get_dummies(all_data).to_csv('my1.csv')
columns = ('FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual', 'GarageCond',
        'ExterQual', 'ExterCond','HeatingQC', 'PoolQC', 'KitchenQual', 'BsmtFinType1',
        'BsmtFinType2', 'Functional', 'Fence', 'BsmtExposure', 'GarageFinish', 'LandSlope',
        'LotShape', 'PavedDrive', 'Street', 'Alley', 'CentralAir', 'MSSubClass', 'OverallCond',
        'YrSold', 'MoSold')
# columns = all_data.columns.values
# print(type(all_data['Street'].values))
for column in columns:
    lb_make = LabelEncoder()
    all_data[column] = lb_make.fit_transform(all_data[column].values)
print('Shape all_data: {}'.format(all_data.shape))

all_data['TotalSF'] = all_data['TotalBsmtSF'] + all_data['1stFlrSF'] + all_data['2ndFlrSF']

# 算一下数据斜度
numeric_feats = all_data.dtypes[all_data.dtypes != "object"].index
skewed_feats = all_data[numeric_feats].apply(skew).sort_values(ascending=False)
print("\nSkew in numerical features: \n")
skewness = pd.DataFrame({'Skew' :skewed_feats})

# 进行box-cox变换
skewness = skewness[abs(skewness)>0.75]
# print('斜度大于0.75的有{}个'.format(skewness.shape[0]))

from scipy.special import boxcox1p
skewed_features = skewness.index
lam = 0.15
for feat in skewed_features:
    #all_data[feat] += 1
    all_data[feat] = boxcox1p(all_data[feat], lam)

all_data = pd.get_dummies(all_data)
print(all_data.shape)

# 建立模型

from sklearn.linear_model import ElasticNet, Lasso,  BayesianRidge, LassoLarsIC
from sklearn.ensemble import RandomForestRegressor,  GradientBoostingRegressor
from sklearn.kernel_ridge import KernelRidge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.metrics import mean_squared_error
import xgboost as xgb
import lightgbm as lgb

train = all_data[:ntrain]
test = all_data[ntrain:]
# 交叉验证
n_folds = 5
def rmsle_cv(model):
    kf = KFold(n_folds, shuffle=True, random_state=42)
    rmse = np.sqrt(-cross_val_score(model, train.values, y_train, scoring='neg_mean_squared_error',cv=kf))
    return rmse

# 基本模型
# LASSO Regression :拉索回归
lasso = make_pipeline(RobustScaler(), Lasso(alpha =0.0005, random_state=1))

#Elastic Net Regression :弹性网络回归
ENet = make_pipeline(RobustScaler(), ElasticNet(alpha=0.0005, l1_ratio=.9, random_state=3))

# Kernel Ridge Regression :内核岭回归
KRR = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,
                                   max_depth=4, max_features='sqrt',
                                   min_samples_leaf=15, min_samples_split=10,
                                   loss='huber', random_state =5)

#Gradient Boosting Regression : :
GBoost = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,
                                   max_depth=4, max_features='sqrt',
                                   min_samples_leaf=15, min_samples_split=10,
                                   loss='huber', random_state =5)

#XGBoost :
model_xgb = xgb.XGBRegressor(colsample_bytree=0.4603, gamma=0.0468,
                             learning_rate=0.05, max_depth=3,
                             min_child_weight=1.7817, n_estimators=2200,
                             reg_alpha=0.4640, reg_lambda=0.8571,
                             subsample=0.5213, silent=1,
                             random_state =7, nthread = -1)

#LightGBM :
model_lgb = lgb.LGBMRegressor(objective='regression',num_leaves=5,
                              learning_rate=0.05, n_estimators=720,
                              max_bin = 55, bagging_fraction = 0.8,
                              bagging_freq = 5, feature_fraction = 0.2319,
                              feature_fraction_seed=9, bagging_seed=9,
                              min_data_in_leaf =6, min_sum_hessian_in_leaf = 11)

# 单个模型的结果
# score = rmsle_cv(lasso)
# print("\nLasso score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# score = rmsle_cv(ENet)
# print("ElasticNet score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# score = rmsle_cv(KRR)
# print("Kernel Ridge score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# score = rmsle_cv(GBoost)
# print("Gradient Boosting score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# score = rmsle_cv(model_xgb)
# print("Xgboost score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# score = rmsle_cv(model_lgb)
# print("LGBM score: {:.4f} ({:.4f})\n" .format(score.mean(), score.std()))

# class AveragingModels(BaseEstimator, RegressorMixin, TransformerMixin):
#     def __init__(self, models):
#         self.models = models
#     def fit(self,X,y):
#         self.models_ = [clone(x) for x in self.models]
#
#         for model in self.models_:
#             model.fit(X,y)
#         return self
#
#     def predict(self,X):
#         predictions = np.column_stack([model.predict(X) for model in self.models_])
#         return np.mean(predictions, axis=1)

    # def score(self, X, y, sample_weight=None):
    #     return np.mean(self.predict(X))

# averaged_models = AveragingModels(models = (ENet, GBoost, KRR, lasso))
# score = rmsle_cv(averaged_models)
# print(score.mean(),score.std())

class StackingAveragedModels(BaseEstimator, RegressorMixin, TransformerMixin):
    def __init__(self, base_models, meta_model, n_folds=5):
        self.base_models = base_models
        self.meta_model = meta_model
        self.n_folds = n_folds

    # We again fit the data on clones of the original models
    def fit(self, X, y):
        self.base_models_ = [[]] * len(self.base_models)
        self.meta_model_ = clone(self.meta_model)
        kfold = KFold(n_splits=self.n_folds, shuffle=True, random_state=156)

        # Train cloned base models then create out-of-fold predictions
        # that are needed to train the cloned meta-model
        out_of_fold_predictions = np.zeros((X.shape[0], len(self.base_models)))
        for i, model in enumerate(self.base_models):
            for train_index, holdout_index in kfold.split(X, y):
                instance = clone(model)
                self.base_models_[i].append(instance)
                instance.fit(X[train_index], y[train_index])
                y_pred = instance.predict(X[holdout_index])
                out_of_fold_predictions[holdout_index, i] = y_pred

        # Now train the cloned  meta-model using the out-of-fold predictions as new feature
        self.meta_model_.fit(out_of_fold_predictions, y)
        return self

    # Do the predictions of all base models on the test data and use the averaged predictions as
    # meta-features for the final prediction which is done by the meta-model
    def predict(self, X):
        # d = len(self.base_models_)
        # for base_models in self.base_models_:
        #     a = [model.predict(X) for model in base_models]
        #     c = len(base_models)
        #     for model in base_models:
        #         b = model.predict(X)
        #         pass
        meta_features = np.column_stack([np.column_stack([model.predict(X) for model in base_models]).mean(axis=1)
                                         for base_models in self.base_models_])
        return self.meta_model_.predict(meta_features)

stacked_averaged_models = StackingAveragedModels(base_models = (ENet, GBoost, KRR, GBoost, model_xgb, model_lgb),
                                                 meta_model = lasso)

score = rmsle_cv(stacked_averaged_models)
stacked_averaged_models.fit(train.values,y_train)
final_result = stacked_averaged_models.predict(train.values)
final_result = pd.DataFrame({'final_result':final_result})
final_result.to_csv('result.csv')
print("Stacking Averaged models score: {:.4f} ({:.4f})".format(score.mean(), score.std()))


# 单日
# key = 'K%Z6DnmLwd9BQek+61%4,-30925.87'
# data = "Z99Z"
# 多日
# 简单映射,映射表前一半字符对应后一半字符，把 data 的数据
key = "I4+2SzpFxAOLPnU.3-2497+%,86051"
data = 'U22UAU2p2AU4PU'
# n = {}
# s = []
# for i in range(len(key) // 2):
#     n[key[i]] = key[len(key) // 2 + i]
# for j in range(len(data)):
#     s.append(n[data[j]])
# print(s)
# print(list(map(int,''.join(s).split(','))))
m = list(key)
# print(m)
d = dict(zip(m[:len(m)//2],m[len(m)//2::]))
print(m[:len(m)//2])
print(m[len(m)//2::])
# print(d)
# print(list(map(lambda x:d[x],data)))
print(''.join(map(lambda x:d[x],data)).split(','))
str_list =  ''.join(map(lambda x: d[x], data)).split(',')
data_list = []
for s in str_list:
    data_list.append(int(s))
print(data_list)


import os
import os.path
import numpy as np

IMG_EXTENSIONS = [
    '.jpg', '.JPG', '.jpeg', '.JPEG',
    '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]

def is_image_file(filename):
    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)

def make_dataset(path_files, dir=''):
    if path_files.find('.txt') != -1:
        paths, size = make_dataset_txt(path_files, dir)
    elif path_files.find('.csv') != -1:
        paths, size = make_dataset_csv(path_files, dir)
    elif path_files.find('.lst') != -1:
        paths, size = make_dataset_lst(path_files, dir)
    else:
        paths, size = make_dataset_dir(path_files)

    return paths, size

def make_dataset_txt(files, dir):
    """
    :param path_files: the path of txt file that store the image paths
    :return: image paths and sizes
    """
    img_paths = []

    with open(files) as f:
        paths = f.readlines()

    for path in paths:
        path = path.strip()
        img_paths.append(dir + path)

    return img_paths, len(img_paths)

def make_dataset_dir(dir):
    """
    :param dir: directory paths that store the image
    :return: image paths and sizes
    """
    img_paths = []

    assert os.path.isdir(dir), '%s is not a valid directory' % dir

    for root, _, fnames in os.walk(dir):
        for fname in sorted(fnames):
            if is_image_file(fname):
                path = os.path.join(root, fname)
                img_paths.append(path)

    return img_paths, len(img_paths)

def make_dataset_csv(files, dir):
    """
    :param path_files: the path of txt file that store the image paths
    :return: image paths and sizes
    """
    img_paths = []

    with open(files) as f:
        for line in f:
            val = line.strip().split(",")
            #img_paths.append((val[0], np.float32(val[1]), np.float32(val[2]), np.float32(val[3])))
            #print(os.path.join(dir, val[0]))
            img_paths.append((os.path.join(dir, val[0]), np.float32(val[1:])))

    return img_paths, len(img_paths)

def make_dataset_lst(files, dir):
    """
    :param path_files: the path of txt file that store the image paths
    :return: image paths and sizes
    """
    img_paths = []

    with open(files) as f:
        paths = f.readlines()

    for path in paths:
        path = path.strip().split(',')
        img_paths.append(list(map(lambda s: dir + s, path)))

    return img_paths, len(img_paths)


import unittest
from microservices import postgres_mode as pm
from microservices.xml_handler import XmlReport as XHXmlReport
from microservices.xml_handler import XmlRequest
from bs4 import BeautifulSoup

class XHUnitTestXmlReport(XHXmlReport):
    def __init__(self):
        pass

class TestManager(unittest.TestCase):

    def setUp(self):
        order_id = 1
        self.manager = TestManager()

        sql = ("INSERT INTO "
               "concurent_site.main_order "
               f"VALUES ({order_id}, 0, 0, 2, 1, 3) ")

        pm.custom_request_to_database_without_return(sql)

        sql = ("INSERT INTO "
               "concurent_site.main_request "
               f"VALUES "
               f"(1, 'Lasik', 0, 0, 0, 0, 0, 0, 0, 0, 'in work', 0, 0, 0, 0, 0, '', 0, 0, 255, {order_id}), "
               f"(2, 'Коррекция зрения', 0, 0, 0, 0, 0, 0, 0, 0, 'in work', 0, 0, 0, 0, 0, '', 0, 0, 255, {order_id}),"
               f"(3, 'ФРК', 0, 0, 0, 0, 0, 0, 0, 0, 'in work', 0, 0, 0, 0, 0, '', 0, 0, 255, {order_id}),"
               f"(4, 'Smile', 0, 0, 0, 0, 0, 0, 0, 0, 'in work', 0, 0, 0, 0, 0, '', 0, 0, 255, {order_id})")

        pm.custom_request_to_database_without_return(sql)

        file = open("text_files_for_tests/first_xml_answer", "r")
        xml = file.read()
        file.close()

        sql = ("INSERT INTO "
               "concurent_site.main_requestqueue "
               f"VALUES (DEFAULT, FALSE, 255, 1)")

        pm.custom_request_to_database_without_return(sql)

        sql = ("INSERT INTO "
               "concurent_site.main_handledxml "
               f"VALUES "
               f"(DEFAULT, '{xml}', 'in work', 0, 0, 0, 0, 255, 1),"
               f"(DEFAULT, '{xml}', 'in work', 0, 0, 0, 0, 255, 2),"
               f"(DEFAULT, '{xml}', 'in work', -1, 1, 0, 0, 255, 3),"
               f"(DEFAULT, '{xml}', 'in work', 0, 4, 0, 0, 255, 4)")

        pm.custom_request_to_database_without_return(sql)

        file = open("text_files_for_tests/second_xml_answer", "r")
        xml = file.read()
        file.close()

        sql = ("INSERT INTO "
               "concurent_site.main_requestqueue "
               f"VALUES (DEFAULT, FALSE, 255, 2)")

        pm.custom_request_to_database_without_return(sql)

        sql = ("INSERT INTO "
               "concurent_site.main_domain "
               "VALUES "
               "('test-domain-one.ru', 8, 400, 800, 'complete', 0),"
               "('test-domain-two.ru', 12, 600, 1200, 'pending', 1),"
               "('test-domain-three.ru', 45, 100500, 1000000, 'fake', 2)")

        pm.custom_request_to_database_without_return(sql)

    def tearDown(self):
        SCHEMA = 'concurent_site'
        test_domains = ('test-domain-one.ru', 'test-domain-two.ru', 'test-domain-three.ru')
        sql = (f'DELETE FROM {SCHEMA}.main_order; '
               f'DELETE FROM {SCHEMA}.main_handledxml; '
               f'DELETE FROM {SCHEMA}.main_requestqueue; '
               f'DELETE FROM {SCHEMA}.main_request; '
               f'DELETE FROM {SCHEMA}.main_domain WHERE name in {test_domains};')

        pm.custom_request_to_database_without_return(sql)

    def test_setup_insertion_main_order(self):
        sql = "SELECT id FROM concurent_site.main_order;"
        database_return = pm.custom_request_to_database_with_return(sql, 'one')
        id = database_return[0]

        self.assertEqual(id, 1)

    def test_setup_insertion_main_request(self):
        sql = "SELECT id, text FROM concurent_site.main_request;"
        database_return = pm.custom_request_to_database_with_return(sql)

        first_request = database_return[0]
        second_request = database_return[1]

        self.assertEqual(first_request[0], 1)
        self.assertEqual(first_request[1], 'Lasik')
        self.assertEqual(second_request[0], 2)
        self.assertEqual(second_request[1], 'Коррекция зрения')

    def test_setup_insertion_main_requestqueue(self):
        sql = "SELECT request_id FROM concurent_site.main_requestqueue;"
        database_return = pm.custom_request_to_database_with_return(sql)

        first_request = database_return[0]
        second_request = database_return[1]

        self.assertEqual(first_request[0], 1)
        self.assertEqual(second_request[0], 2)

    def test_setup_insertion_main_handledxml(self):
        sql = "SELECT request_id FROM concurent_site.main_handledxml;"
        database_return = pm.custom_request_to_database_with_return(sql)

        first_request = database_return[0]
        second_request = database_return[1]

        self.assertEqual(first_request[0], 1)
        self.assertEqual(second_request[0], 2)

    def test_get_requests_from_queue(self):
        handler_object = XHUnitTestXmlReport()
        handler_object.requests = list()
        handler_object.get_requests_from_queue()

        request = handler_object.requests[0]
        self.assertEqual('Lasik', request.text)

        request = handler_object.requests[1]
        self.assertEqual('Коррекция зрения', request.text)

    def test_get_requests_for_recheck(self):
        handler_object = XHUnitTestXmlReport()
        handler_object.requests = list()
        handler_object.get_requests_for_recheck()

        request = handler_object.requests[0]
        self.assertEqual('ФРК', request.text)

    def test_add_url_to_dataset(self):
        request_datasets = (XmlRequest(text='Lasik', region_id=255),
                            XmlRequest(text='ФРК', region_id=10))

        handler_object = XHUnitTestXmlReport()
        handler_object.requests = request_datasets
        handler_object.add_url_to_dataset()

        self.assertEqual(
            'http://xmlriver.com/search_yandex/xml?user=1391&key=893df7feb2a0f02343085ea6bc9e5424056aa945&query=Lasik',
            handler_object.requests[0].xml_url)
        self.assertEqual(
            'http://xmlriver.com/search_yandex/xml?user=1391&key=893df7feb2a0f02343085ea6bc9e5424056aa945&query=ФРК&lr=10',
            handler_object.requests[1].xml_url)

    def test_get_ads_block(self):
        file = open("text_files_for_tests/first_xml_answer", "r")
        xml = file.read()
        file.close()

        xml = BeautifulSoup(xml, 'html.parser')
        handler_object = XHUnitTestXmlReport()
        _, ads_count = handler_object.get_ads_block(xml, 'topads')
        self.assertEqual(4, ads_count)

        handler_object = XHUnitTestXmlReport()
        _, ads_count = handler_object.get_ads_block(xml, 'bottomads')
        self.assertEqual(5, ads_count)

    def test_get_real_ads_count(self):
        handler_object = XHUnitTestXmlReport()
        overcaped_bottom_ads_count, bottom_ads_count, top_ads_count = handler_object.get_real_ads_count(9)
        self.assertEqual(5, bottom_ads_count)
        self.assertEqual(4, top_ads_count)
        self.assertEqual(4, overcaped_bottom_ads_count)

    def test_count_ads(self):
        file = open("text_files_for_tests/first_xml_answer", "r")
        xml = file.read()
        file.close()

        handler_object = XHUnitTestXmlReport()
        overcaped_ads_count, top_ads_count, bottom_ads_count, bottom_ads_block = handler_object.count_ads(xml)
        self.assertEqual(0, overcaped_ads_count)
        self.assertEqual(4, top_ads_count)
        self.assertEqual(5, bottom_ads_count)

        file = open("text_files_for_tests/first_xml_answer_with_overcap", "r")
        xml = file.read()
        file.close()

        handler_object = XHUnitTestXmlReport()
        overcaped_ads_count, top_ads_count, bottom_ads_count, bottom_ads_block = handler_object.count_ads(xml)
        self.assertEqual(4, overcaped_ads_count)
        self.assertEqual(4, top_ads_count)
        self.assertEqual(5, bottom_ads_count)

    def test_validate_quotes_for_sql(self):
        handler_object = XHUnitTestXmlReport()
        string = "Д'Артаньян"
        string_for_sql = handler_object.validate_quotes_for_sql(string)
        self.assertEqual("Д''Артаньян", string_for_sql)

    def test_edit_xml_answer_text(self):
        file = open("text_files_for_tests/first_xml_answer_with_overcap", "r")
        xml = file.read()
        file.close()
        soup = BeautifulSoup(xml, 'html.parser')

        handler_object = XHUnitTestXmlReport()
        bottom_ads_block, _ = handler_object.get_ads_block(soup, 'bottomads')
        edited_xml_text = handler_object.edit_xml_answer_text(4, bottom_ads_block, xml)

        soup = BeautifulSoup(edited_xml_text, 'html.parser')
        top_ads = soup.find('topads')
        top_ads_count = len(top_ads.find_all('query'))
        bottom_ads = soup.find('bottomads')
        bottom_ads_count = len(bottom_ads.find_all('query'))

        self.assertEqual(9, edited_xml_text.count('<query>'))
        self.assertEqual(4, top_ads_count)
        self.assertEqual(5, bottom_ads_count)

        file = open("text_files_for_tests/second_xml_answer_with_overcap", "r")
        xml = file.read()
        file.close()
        soup = BeautifulSoup(xml, 'html.parser')

        handler_object = XHUnitTestXmlReport()
        bottom_ads_block, _ = handler_object.get_ads_block(soup, 'bottomads')
        edited_xml_text = handler_object.edit_xml_answer_text(2, bottom_ads_block, xml)

        soup = BeautifulSoup(edited_xml_text, 'html.parser')
        top_ads = soup.find('topads')
        top_ads_count = len(top_ads.find_all('query'))
        bottom_ads = soup.find('bottomads')
        bottom_ads_count = len(bottom_ads.find_all('query'))

        self.assertEqual(7, edited_xml_text.count('<query>'))
        self.assertEqual(2, top_ads_count)
        self.assertEqual(5, bottom_ads_count)

        file = open("text_files_for_tests/third_xml_answer_with_overcap", "r")
        xml = file.read()
        file.close()
        soup = BeautifulSoup(xml, 'html.parser')

        handler_object = XHUnitTestXmlReport()
        bottom_ads_block, _ = handler_object.get_ads_block(soup, 'bottomads')
        edited_xml_text = handler_object.edit_xml_answer_text(0, bottom_ads_block, xml)

        soup = BeautifulSoup(edited_xml_text, 'html.parser')
        top_ads = soup.find('topads')
        top_ads_count = len(top_ads.find_all('query'))
        bottom_ads = soup.find('bottomads')
        bottom_ads_count = len(bottom_ads.find_all('query'))

        self.assertEqual(5, edited_xml_text.count('<query>'))
        self.assertEqual(0, top_ads_count)
        self.assertEqual(5, bottom_ads_count)

    def test_get_refresh_timer_and_reruns_count(self):
        handler_object = XHUnitTestXmlReport()
        reruns_count, refresh_timer = handler_object.get_refresh_timer_and_reruns_count(4, 5)
        self.assertEqual(4, reruns_count)
        self.assertEqual(0, refresh_timer)

        reruns_count, refresh_timer = handler_object.get_refresh_timer_and_reruns_count(4, 4)
        self.assertEqual(1, reruns_count)
        self.assertEqual(10, refresh_timer)

        self.assertRaises(ValueError, handler_object.get_refresh_timer_and_reruns_count, 14, 5)

    def test_is_rerun(self):

        handler_object = XHUnitTestXmlReport()
        request = XmlRequest(reruns_count=0)
        is_rerun = handler_object.check_is_rerun(request)
        self.assertEqual(None, is_rerun)

        request = XmlRequest(reruns_count=2)
        is_rerun = handler_object.check_is_rerun(request)
        self.assertEqual(True, is_rerun)

    def test_found_more_ads_then_before(self):

        handler_object = XHUnitTestXmlReport()
        request = XmlRequest(top_ads_count=4, bottom_ads_count=5)
        found_more = handler_object.check_found_more_ads_then_before(request, 4, 5)
        self.assertEqual(None, found_more)

        handler_object = XHUnitTestXmlReport()
        request = XmlRequest(top_ads_count=4, bottom_ads_count=5)
        found_more = handler_object.check_found_more_ads_then_before(request, 3, 4)
        self.assertEqual(None, found_more)

        handler_object = XHUnitTestXmlReport()
        request = XmlRequest(top_ads_count=0, bottom_ads_count=5)
        found_more = handler_object.check_found_more_ads_then_before(request, 1, 5)
        self.assertEqual(True, found_more)

    def test_finalize_dataset(self):
        handler_object = XHUnitTestXmlReport()
        request = XmlRequest()
        handler_object.finalize_dataset(request, 'hello', 10, 1, 5, 4)
        self.assertEqual('hello', request.validated_text)
        self.assertEqual('in work', request.status)
        self.assertEqual(10, request.refresh_timer)
        self.assertEqual(1, request.reruns_count)
        self.assertEqual(4, request.top_ads_count)
        self.assertEqual(5, request.bottom_ads_count)


import os, sys
from pathlib import Path

apps = []

if m.is_android:
    m.link_glob(DOTFILES/"config/termux", "~/.termux")
else:
    apps += [
        "xorg",
        "river",
        "hypr",
        "awesome",
        "qtile",

        "sxhkd",
        "picom",
        "zathura",
        "taskwarrior",
        "sxiv",
        "tig",
        # "i3",
        # "rofi",
        # "bspwm",
        # "polybar",
        # "alacritty",
    ]

    for i in {2, 4}:
        origin = DOTFILES / f"config/gtk-{i}.0"
        if origin.is_dir():
            m.link_glob(origin, f"~/.config/gtk-{i}.0")

apps += [
    "irb",
    "inputrc",
    "dircolors",
    "mimeapps.list",
    "pulsemixer.cfg",
    "ripgreprc",
    "dots",
    "lf",
    # "broot",
]

for app in apps:
    m.link_conf(app, f"~/.config/{app}")

m.link_conf("gdbinit", f"~/.gdbinit")
m.link_conf("prettierrc.json", f"~/.pretierrc.json")
m.link_conf("profile", "~/.profile")
m.link_conf("guile/guilerc", "~/.guile")
m.link_conf("bash/bashrc", "~/.bashrc")
m.link_conf("profile", "~/.zprofile")
m.link_conf("zsh/zshrc", "~/.config/zsh/.zshrc")
m.link_conf("zsh/zlogout", "~/.config/zsh/.zlogout")
m.link_conf("git/gitconfig", "~/.gitconfig")
m.link_conf("git/gitignore", "~/.gitignore")
m.link_conf("cargo-config.toml", "~/.cache/cargo/config.toml")
m.link_conf("pylintrc", "~/.pylintrc")
m.link_conf("tmux.conf", "~/.tmux.conf")
m.link_conf("icons_default.theme", "~/.icons/default/index.theme")
m.link_conf("radium/keybindings.conf", "~/.radium/keybindings.conf")
m.link_conf("waybar/config", "~/.config/waybar/config")

m.link_glob(DOTFILES / "config/qutebrowser", "~/.config/qutebrowser")
# m.link_glob(DOTFILES / "config/furnace", "~/.config/furnace") # new backup system is incompatible with this
m.link_glob(DOTFILES / "config/nvim", "~/.config/nvim")
m.link_glob(DOTFILES / "config/emacs", "~/.emacs.d")
m.link_glob(DOTFILES / "desktop", "~/.local/share/applications")
# m.link_glob(DOTFILES / "config/kak", "~/.config/kak")
# m.link_glob(DOTFILES / "config/vscode", "~/.config/Code/User")

XDG_CACHE_HOME = Path(os.environ["XDG_CACHE_HOME"])
DOTS_CACHE = XDG_CACHE_HOME / "dots"

print("Downloading/updating repos...", file=sys.stderr)

(DOTS_CACHE / "repos").mkdir(parents=True, exist_ok=True)
REPOS = {
    "FlatColor": "https://github.com/YohananDiamond/FlatColor",
}
for (name, url) in REPOS.items():
    print(f"Current repo: {name} ({url})", file=sys.stderr)
    p = DOTS_CACHE / "repos" / name
    if p.exists():
        # os.system(f"cd {repr(str(p))} && git pull")
        pass
    else:
        os.system(f"git clone {repr(url)} {repr(str(p))}")

Path("~/.themes").expanduser().mkdir(parents=True, exist_ok=True)
m.link_glob(DOTS_CACHE / "repos/FlatColor", "~/.themes/FlatColor")

print("Generating config...", file=sys.stderr, end="")

# general config
os.system(DOTFILES / "scripts/gen-config")

print(" done!", file=sys.stderr)


# Example 1-1 in Electric Machinery Fundamentals

import numpy as np

N = 200 # turns
curr =  1 # amps
mu_r = 2500 # relative permeability
mu_o = np.pi * 4e-7 # permeability of vacuum
f = N*curr # magnetomotive force
mu = mu_r * mu_o # total permeability
A_1 = 15e-2 * 10e-2 # m^2
l_1 = (5 + 30 + 15 + 30 + 15 + 30 + 5)*1e-2 # m
print("l1 = " + str(l_1))
A_2 = 10e-2 * 10e-2 # m^2
l_2 = (7.5 + 30 + 7.5)*1e-2 # m
reluctance_1 = l_1 / (A_1 * mu)
print("r1 = " + str(reluctance_1))
reluctance_2 = l_2 / (A_2 * mu)
print("r2 = " + str(reluctance_2))
reluctance_total = reluctance_1 + reluctance_2
# f = φr
flux = f/reluctance_total
print("flux = " + str(flux))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import sys
import os

strset=('name', 'padding', 'data_format')
class NormalizeLayer(object):
    '''
    '''
    def __init__(self, conf_opt):
        self.name = 'NormalizeLayer'
        self.input_dim = 0
        self.target_rms = 1.0
        self.axis = -1
        self.epsilon = 1.3552527156068805425e-20 # 2^-66
        self.dtype = tf.float32
        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])

        self.scale = self.target_rms * self.target_rms * self.input_dim
        self.scale = pow(self.scale, 1/2)

    def __call__(self, input_feats):
        with tf.name_scope(self.name, "Normalize", [input_feats]) as name:
            #axis = deprecated_argument_lookup("axis", self.axis, "dim", None)
            input_feats = tf.convert_to_tensor(input_feats, dtype=self.dtype, name="input_feats")
            square_sum = tf.reduce_sum(
                    tf.square(input_feats), self.axis, keepdims=True)
            x_inv_norm = tf.rsqrt(tf.maximum(square_sum, self.epsilon))
            x_inv_norm = tf.multiply(x_inv_norm, self.scale)

            return tf.multiply(input_feats, x_inv_norm, name=name)

    def GetOutputDim(self):
        return self.input_dim

class ReluLayer(object):
    '''
    '''
    def __init__(self, conf_opt):
        self.name = 'ReluLayer'
        self.input_dim = 0
        self.output_dim = 0
        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])

        assert self.input_dim == self.output_dim

    def __call__(self, input_feats):
        return tf.nn.relu(input_feats, self.name)

    def GetOutputDim(self):
        return self.output_dim

class SpliceLayer(object):
    '''
    '''
    def __init__(self, conf_opt):
        self.splice = [-1,0,1]
        self.input_dim = 0
        self.name = 'SpliceLayer'
        self.time_major = True
        self.splice_padding = False
        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])
        assert self.splice[0] <= 0
        assert self.splice[-1] >= 0
        if self.time_major is True:
            self.time = 0
        else:
            self.time = 1

    #t1 = [[1, 2, 3], [4, 5, 6]]
    #t2 = [[7, 8, 9], [10, 11, 12]]
    #tf.concat([t1, t2], 0)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
    #tf.concat([t1, t2], 1)  # [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
    # padding
    def SpliceFeats(self, input_feats):
        output = None
        start_nframe = 0
        end_nframe = 0
        for i in self.splice:
            if i < 0:
                start = input_feats[:1]
                start_end = input_feats[:i]
                while i < 0:
                    start_end = tf.concat([start, start_end], self.time)
                    i += 1
                concat_input = start_end
                start_nframe += 1
            elif i == 0:
                concat_input = input_feats
            elif i > 0:
                end = input_feats[-1:]
                end_start = input_feats[i:]
                while i > 0:
                    end_start = tf.concat([end_start, end], self.time)
                    i -= 1
                concat_input = end_start
                end_nframe += 1

            if output is None:
                output = concat_input
            else:
                output = tf.concat([output, concat_input], -1)

        #first = input_feats[:1]
        #end = input_feats[-1:]
        #f = input_feats[:-1]
        #b = input_feats[1:]
        #fi = tf.concat([first, f],0)
        #bi = tf.concat([b, end], 0)
        #out = tf.concat([fi, input_feats, bi],-1)
        return output
        #return output[start_nframe:-end_nframe]

    # b=tf.pad(input_feats,[[1,1],[0,0],[0,0]],"SYMMETRIC")
    def __call__(self, input_feats):
        '''
        in advance at head and tail add frames,
        so extract need features
        '''
        # no padding
        if self.splice_padding is False:
            output = None
            start_nframe = -1 * self.splice[0]
            end_nframe = self.splice[-1]
            for i in self.splice:
                #if i < 0:
                start = start_nframe + i
                end = end_nframe - i
                if end == 0:
                    concat_input = input_feats[start:]
                else:
                    concat_input = input_feats[start:-1*end]

                #concat_input = input_feats[start:-1*end]
                #elif i == 0:
                #    concat_input = input_feats[start_nframe:-1*end_nframe]
                #elif i > 0:
                #    start = start_nframe + i
                #    end = end_nframe-i

                if output is None:
                    output = concat_input
                else:
                    output = tf.concat([output, concat_input], -1)
            return output

        else:
            # padding
            return self.SpliceFeats(input_feats)

    def GetOutputDim(self):
        return len(self.splice) * self.input_dim

class AffineTransformLayer(object):
    '''
    '''
    def __init__(self, conf_opt, dtype = tf.float32,
            initializer = tf.contrib.layers.xavier_initializer(tf.float32),
            trainable = True,
            name = 'AffineTransformLayer'):
        self.name = name
        self.input_dim = None
        self.output_dim = None
        self.dtype = tf.float32
        self.initializer = tf.contrib.layers.xavier_initializer(tf.float32)
        self.trainable = True
        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])
        if name != 'AffineTransformLayer':
            self.name = name
        assert self.input_dim != None
        assert self.output_dim != None

        with tf.variable_scope(self.name):
            self.weights = tf.get_variable(self.name+'_w',
                    shape = [self.input_dim, self.output_dim],
                    dtype = self.dtype,
                    initializer = self.initializer,
                    trainable = self.trainable)

            self.bias = tf.get_variable(self.name+'_b',
                    shape = [self.output_dim],
                    dtype = self.dtype,
                    initializer = self.initializer,
                    trainable = self.trainable)

    def __call__(self, input_feats):
        input_feats = tf.reshape(input_feats, [-1, self.input_dim])
        return tf.matmul(input_feats, self.weights) + self.bias

    def GetInputDim(self):
        return self.input_dim

    def GetOutputDim(self):
        return self.output_dim

class Affine2TransformLayer(object):
    '''
    '''
    def __init__(self, conf_opt, dtype = tf.float32,
            initializer = tf.contrib.layers.xavier_initializer(tf.float32),
            trainable = True):
        self.name = 'AffineTransformLayer'
        self.input_dim = None
        self.output_dim = None
        self.dtype = tf.float32
        self.initializer = tf.contrib.layers.xavier_initializer(tf.float32)
        self.trainable = True
        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])
        assert self.input_dim != None
        assert self.output_dim != None
        self.affine1 = AffineTransformLayer(conf_opt, name=self.name+'_1')
        self.affine2 = AffineTransformLayer(conf_opt, name=self.name+'_2')

    def __call__(self, input_feats):
        input_feats = tf.reshape(input_feats, [-1, self.input_dim])
        output1 = self.affine1(input_feats)
        output2 = self.affine2(input_feats)
        return [output1, output2]

    def GetInputDim(self):
        return self.input_dim

    def GetOutputDim(self):
        return self.output_dim

class TdnnLayer(object):
    '''
    '''
    def __init__(self, conf_opt):
        self.name = 'TdnnLayer'
        self.input_dim = 0
        self.output_dim = 0
        self.time_major = True
        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])

        self.layers = []
        # SpliceLayer
        conf_opt['name'] = self.name + 'splice'
        self.layers.append(SpliceLayer(conf_opt))
        # AffineTransformLayer
        conf_opt['input_dim'] = str(self.layers[-1].GetOutputDim())
        conf_opt['name'] = self.name + 'affine'
        self.layers.append(AffineTransformLayer(conf_opt))
        # ReluLayer
        conf_opt['input_dim'] = str(self.layers[-1].GetOutputDim())
        conf_opt['name'] = self.name + 'relu'
        self.layers.append(ReluLayer(conf_opt))
        # NormalizeLayer
        conf_opt['name'] = self.name + 'normalize'
        self.layers.append(NormalizeLayer(conf_opt))

    def __call__(self, input_feats):
        output = [input_feats]
        for layer in self.layers:
            if type(layer) is ReluLayer:
                output.append(tf.nn.relu(output[-1]))
                #layer(output[-1])
            else:
                output.append(layer(output[-1]))
        return output[-1]

    def GetOutputDim(self):
        return self.output_dim

    def GetInputDim(self):
        return self.input_dim

class LstmLayer(object):
    '''
    layer_flag = BLstmLayer; name = lstmlayer1; lstm_cell = 1024; use_peepholes = True; cell_clip = 5.0; initializer = None; num_proj = 512; self.proj_clip = 1.0; forget_bias = 0.0; initializer = tf.contrib.layers.xavier_initializer(tf.float32); activation = None; dtype = tf.float32; reuse = tf.get_variable_scope().reuse; state_is_tuple = True;
    '''
    def __init__(self, conf_opt, prefix=None):
        self.lstm_cell = None
        self.use_peepholes = False
        self.cell_clip = 50.0
        self.num_proj = None
        self.proj_clip = None # advise 1.0
        self.forget_bias = 0.0
        self.state_is_tuple = True
        self.name = None
        self.reuse = None
        self.keep_prob = 1.0
        self.initializer = tf.contrib.layers.xavier_initializer(tf.float32)
        self.activation = None # default tanh
        self.dtype = tf.float32
        self.reuse = tf.get_variable_scope().reuse
        for key in self.__dict__:
            if prefix != None:
                opt_key = prefix+key
            else:
                opt_key = key
            if opt_key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[opt_key]
                else:
                    self.__dict__[key] = eval(conf_opt[opt_key])

        assert self.lstm_cell != None
#        self.lstm_cell = int(self.lstm_cell)
#        if self.use_peepholes == 'False':
#            self.use_peepholes = False
#        else:
#            self.use_peepholes = True

#        self.cell_clip = float(self.cell_clip)
#        if self.num_proj != None:
#            self.num_proj = int(self.num_proj)
#        if self.proj_clip != None:
#            self.proj_clip = float(self.proj_clip)
#        self.forget_bias = float(self.forget_bias)
#        if self.state_is_tuple == 'False':
#            self.state_is_tuple = False
#        else:
#            self.state_is_tuple = True
#        self.keep_prob = float(self.keep_prob)

    def __call__(self):
        cell = tf.contrib.rnn.LSTMCell(self.lstm_cell,
                use_peepholes = self.use_peepholes,
                cell_clip = self.cell_clip,
                initializer = self.initializer,
                num_proj = self.num_proj,
                proj_clip = self.proj_clip,
                forget_bias = self.forget_bias,
                state_is_tuple = self.state_is_tuple,
                activation = self.activation,
                reuse = self.reuse,
                name = self.name,
                dtype = self.dtype)
        if self.keep_prob < 1.0:
            cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob = self.keep_prob)
        return cell

    def GetOutputDim(self):
        if self.num_proj == None:
            return self.lstm_cell
        else:
            return self.num_proj

    def Name(self):
        return self.name

class LcBLstmLayer(object):
    '''
    layer_flag = BLstmLayer; name = lcablstmlayer1; fw_lstm_cell = 1024; fw_use_peepholes = True; fw_cell_clip = 5.0; fw_num_proj = 512; fw_proj_clip = 1.0; fw_forget_bias = 0.0; fw_keep_prob = 1.0; bw_lstm_cell = 1024; bw_use_peepholes = True; bw_cell_clip = 5.0; bw_num_proj = 512; bw_proj_clip = 1.0; bw_forget_bias = 0.0; bw_keep_prob = 1.0; latency_controlled=None; state_is_tuple = True; dtype = tf.float32; initializer = tf.contrib.layers.xavier_initializer(tf.float32); activation = None; dtype = tf.float32; reuse = tf.get_variable_scope().reuse;
    '''
    def __init__(self, conf_opt):
        self.conf = conf_opt

    def __call__(self):
        lstm_fw_cell = LstmLayer(self.conf, prefix = 'fw_')
        lstm_bw_cell = LstmLayer(self.conf, prefix = 'bw_')
        return (lstm_fw_cell(), lstm_bw_cell())

    def GetOutputDim(self):
        if self.conf['fw_num_proj'] == None:
            return int(self.conf['fw_lstm_cell']) + int(self.conf['bw_lstm_cell'])
        else:
            return int(self.conf['fw_num_proj']) + int(self.conf['bw_num_proj'])

    def Name(self):
        return self.conf['name']

    def GetLatencyControlled(self):
        return eval(self.conf['latency_controlled'])

class BLstmLayer(object):
    '''
    layer_flag = BLstmLayer; name = blstmlayer1; fw_lstm_cell = 1024; fw_use_peepholes = True; fw_cell_clip = 5.0; fw_num_proj = 512; fw_proj_clip = 1.0; fw_forget_bias = 0.0; fw_keep_prob = 1.0; bw_lstm_cell = 1024; bw_use_peepholes = True; bw_cell_clip = 5.0; bw_num_proj = 512; bw_proj_clip = 1.0; bw_forget_bias = 0.0; bw_keep_prob = 1.0; state_is_tuple = True; dtype = tf.float32; initializer = tf.contrib.layers.xavier_initializer(tf.float32); activation = None; dtype = tf.float32; reuse = tf.get_variable_scope().reuse;
    '''
    def __init__(self, conf_opt):
        self.conf = conf_opt

    def __call__(self):
        lstm_fw_cell = LstmLayer(self.conf, prefix = 'fw_')
        lstm_bw_cell = LstmLayer(self.conf, prefix = 'bw_')
        return (lstm_fw_cell(), lstm_bw_cell())

    def GetOutputDim(self):
        if self.conf['fw_num_proj'] == None:
            return int(self.conf['fw_lstm_cell']) + int(self.conf['bw_lstm_cell'])
        else:
            return int(self.conf['fw_num_proj']) + int(self.conf['bw_num_proj'])

    def Name(self):
        return self.conf['name']

class Cnn2d(object):
    def __init__(self, conf_opt):
        self.height = 11
        self.width = 71
        self.in_channels = 1
        self.filter_height = 11
        self.filter_width = 9
        self.out_channels = 128
        self.height_strides = 1
        self.width_strides = 2
        self.padding = 'VALID'
        self.data_format = 'NHWC'
        self.dilations = [1, 1, 1, 1]
        self.name = 'cnn2d'
        self.initializer = tf.contrib.layers.xavier_initializer(tf.float32)
        self.dtype = tf.float32
        self.trainable = True

        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])

        self.cnn_filter = [self.filter_height, self.filter_width, self.in_channels, self.out_channels]
        self.strides = [1, self.height_strides, self.width_strides, 1]

        with tf.variable_scope(self.name):
            self.kernel = tf.get_variable(self.name+'_w',
                    shape = self.cnn_filter,
                    dtype = self.dtype,
                    initializer = self.initializer,
                    trainable = self.trainable)

    def __call__(self, input_feats):
        return tf.nn.conv2d(input_feats, self.kernel,
                strides = self.strides, padding = self.padding,
                use_cudnn_on_gpu=True,
                data_format=self.data_format, dilations = self.dilations, name = self.name)

    def GetOutputDim(self):
        return [int((self.height - self.filter_height + 1)/self.height_strides), int((self.width - self.filter_width + 1)/self.width_strides), self.out_channels]

class MaxPool2d(object):
    '''
    inputdim is [height, width, channels]
    '''
    def __init__(self, conf_opt):
        self.pool_height = 1
        self.pool_width = 4
        self.height_strides = 1
        self.width_strides = 4
        self.padding = 'valid'
        self.data_format = 'channels_last'
        self.name = 'maxpool2d'
        self.inputheight = 1
        self.inputwidth = 32
        self.inputchannels = 128

        for key in self.__dict__:
            if key in conf_opt.keys():
                if key in strset:
                    self.__dict__[key] = conf_opt[key]
                else:
                    self.__dict__[key] = eval(conf_opt[key])
        self.inputdim = [self.inputheight, self.inputwidth, self.inputchannels]
        self.pool_size = [self.pool_height, self.pool_width]
        self.strides = [self.height_strides, self.width_strides]
        return
    # input_feats it's [batch, height, width, channels]
    def __call__(self, input_feats):
        return tf.layers.max_pooling2d(input_feats, pool_size = self.pool_size,
                strides = self.strides,
                padding = self.padding,
                data_format = self.data_format,
                name = self.name)

    def GetOutputDim(self):
        outputheight = int((self.inputheight - self.pool_height)/self.height_strides + 1)
        outputwidth = int((self.inputwidth - self.pool_width)/self.width_strides + 1)
        outputchannels = self.inputchannels
        return [outputheight, outputwidth, outputchannels]

# enum layer
g_layer_dict={'NormalizeLayer':NormalizeLayer,
        'ReluLayer':ReluLayer,
        'SpliceLayer':SpliceLayer,
        'AffineTransformLayer':AffineTransformLayer,
        'Affine2TransformLayer':Affine2TransformLayer,
        'TdnnLayer':TdnnLayer,
        'LstmLayer':LstmLayer,
        'LcBLstmLayer':LcBLstmLayer,
        'BLstmLayer':BLstmLayer,
        'Cnn2d':Cnn2d,
        'MaxPool2d':MaxPool2d
        }


import wget
# wget.download("https://raw.githubusercontent.com/pesikj/python-012021/master/zadani/5/temperature.csv")
import pandas
import pytemperature

teploty = pandas.read_csv("temperature.csv")

# na stupně Celsia
teploty["AvgTemperatureC"] = pytemperature.f2c(teploty["AvgTemperature"])

# teploty 13.11
dany_den = teploty[teploty["Day"] == 13]

# vyřaď -99
teploty = teploty[teploty["AvgTemperature"] != -99]

# seřadit od největší
teploty = teploty.sort_values(by="AvgTemperatureC", ascending=False)

#  měst s nejvyšší a  s nejnižší teplotou
print(teploty[["City", "AvgTemperatureC"]].head())
print(teploty[["City", "AvgTemperatureC"]].tail())


from config.dbconfig import pg_config
import psycopg2
class RequestDAO:
    global list
    list = set()
    def __init__(self):

        connection_url = "dbname=%s user=%s password=%s host=127.0.0.1" % (pg_config['dbname'],
                                                            pg_config['user'],
                                                            pg_config['passwd'])
        self.conn = psycopg2._connect(connection_url)

    def addrequest(self,date,quantity,adress):
        print(date,quantity,adress)
        list.add((date,quantity,adress))
        return list

    def searchrequested(self, name):
        cursor = self.conn.cursor()
        query = "SELECT  rname,rtype,quantity,rqaddress,rqdate FROM resources as r inner join requested as rq on r.rid=rq.rid inner join request as req on req.rqid=rq.rqid where rname like %s order by rname"
        cursor.execute(query, (name,))
        result = []
        for row in cursor:
            result.append(row)
        return result

    def getrequest(self):
        cursor = self.conn.cursor()
        query = "select rqaddress,quantity,rqdate from request"
        cursor.execute(query)
        result = []
        for row in cursor:
            result.append(row)
        return result

    def searchrequest(self, request):
        cursor = self.conn.cursor()
        query = "select rqaddress,quantity,rqdate from request where rqid= %s "
        cursor.execute(query, (request,))
        result = []
        for row in cursor:
            result.append(row)
        return result

    def getRequestbyCoid(self, request):
        cursor = self.conn.cursor()
        query = "SELECT  firstname,lastname,quantity,rqaddress,rqdate FROM consumer as c inner join makes as mk on c.coid=mk.coid inner join request as req on req.rqid=mk.rqid where c.coid=%s"
        cursor.execute(query, (request,))
        result = []
        for row in cursor:
            result.append(row)
        return result

    def insertrequest(self, rqaddress,quantity,rqdate):
        cursor = self.conn.cursor()
        query = "insert into request(rqaddress,quantity,rqdate) values (%s, %s, %s) returning rqid;"
        cursor.execute(query, (rqaddress,quantity,rqdate,))
        pid = cursor.fetchone()[0]
        self.conn.commit()
        return pid

    def insertmakes(self, pid,coid):
        cursor = self.conn.cursor()
        query = "insert into makes(rqid,coid) values (%s, %s) returning mkid;"
        cursor.execute(query, (pid,coid))
        pid = cursor.fetchone()[0]
        self.conn.commit()
        return pid

    def insertrequested(self, pid,rid,quantity):
        cursor = self.conn.cursor()
        query = "insert into requested(rid,rqid,quantity) values (%s, %s,%s) returning rqdid;"
        cursor.execute(query, (rid,pid,quantity))
        pid = cursor.fetchone()[0]
        self.conn.commit()
        return pid

    def dailyResourcesinNeed(self,date):
        cursor = self.conn.cursor()
        query = "SELECT resources.rname, sum(request.quantity), request.rqdate FROM public.request, public.requested,public.resources WHERE request.rqid = requested.rqid AND requested.rid = resources.rid and request.rqdate = %s group by resources.rname, request.rqdate;"
        cursor.execute(query, (date,))
        result = []
        for row in cursor:
            result.append(row)
        return result

    def weeklyResourcesinNeed(self, date):
        cursor = self.conn.cursor()
        date1 = date.split("-")
        year = int(date1[0])
        month = int(date1[1])
        day = int(date1[2])
        print(year + month + day)
        if month == 1 or month == 3  or month == 5  or month == 7 or month == 8  or month == 10  or month == 12:
            if day+7 > 31:
                if month+1 >12:
                    year = year+1
                    month = "01"
                else:
                    month = month+1
            else:
                day = int(date1[2]) + 7
        else:
            if month == 4 or month == 6 or month == 9 or month == 11:
                if day + 7 > 30:
                    if month + 1 > 12:
                        year = year + 1
                        month = "01"
                    else:
                        month = month + 1
                else:
                    day = int(date1[2]) + 7
            else:
                if month == 2:
                    if day + 7 > 28:
                        if month + 1 > 12:
                            year = year + 1
                            month = "01"
                        else:
                            month = month + 1
                    else:
                        day = int(date1[2]) + 7

            year = str(year)
            if month < 10:
                month = "0" + str(month)
            else:
                month = str(month)

            if day < 10:
                day = "0" + str(day)
            else:
                day = str(day)

        date2 = year + "-" + month + "-" + day
        print(year +"-" +month+"-" + day)

        query = "SELECT rqdate as Week1stDate, resources.rname, sum(request.quantity) FROM public.request, public.requested,public.resources WHERE request.rqid = requested.rqid AND requested.rid = resources.rid and request.rqdate between %s and %s group by  request.rqdate, resources.rname;"
        cursor.execute(query, (date,date2,))
        result = []
        for row in cursor:
            result.append(row)
        return result


import numpy as np
import wave
import os
import sys
import scipy
import matplotlib.pyplot as plt
BLOCK_SIZE_MS = 20

def main():
	filename = sys.argv[1]

	sample_rate = rd.getframerate()
	n_samples = rd.getnframes()

	block_size = BLOCK_SIZE_MS*sample_rate/1000
	split_array = np.array([[]])
	for i in np.xrange(0,n_samples,block_size):
		f = rd.readframes(2*n_samples)
		pdb.set_trace()
		split_array = np.concatenate((split_array,f),axis=0)

	rd.close()

if __name__ == "__main__":
	main()


# -*- coding: utf-8 -*-
"""
Created on Fri Apr  9 22:11:49 2021

@author: pmspr
"""
# import packages
import os
import numpy as np

# Set the local paths for data
path = r'C:\Users\pmspr\Documents\HS\MS\Sem 4\EECS 730\Bioinformatics\Project 3\Docs'
f1 = os.path.join(path, 'file1.fasta') # Change the file name accordingly.
f2 = os.path.join(path, 'file2.fasta') # Change the file name accordingly.
seq = []
#Read file1.fasta
with open(f1) as fl1:
    for line in fl1:
        if(line[0].strip() != '>'):
            seq.append(line.strip())

#Read file2.fasta
with open(f2) as fl2:
    for line in fl2:
        if(line[0].strip() != '>'):
            seq.append(line.strip())

print('Sequence 1 - {}'.format(seq[0]))
print('Sequence 2 - {}'.format(seq[1]))

# Determine the lengths
ls0 = len(seq[0]); ncols = ls0 + 1
ls1 = len(seq[1]); nrows = ls1 + 1

# Create numpy arrays from the strings
s0_arr = np.array(['*' for i in range(0, ncols)], dtype=np.object)
s0_arr[1:] = [seq[0][i] for i in range(0, ls0)]
#print(s0_arr)

s1_arr = np.array(['*' for i in range(0, nrows)], dtype=np.object)
s1_arr[1:] = [seq[1][i] for i in range(0, ls1)]
#print(s1_arr)

# Define the scoring parameters
match_score = 1.0
mismatch_score = -2.0
gap_open = -5
gap_extn = -1

# Define the upper layer matrix and initialize
# Initialize first column = gap_open + row_index * gap_extn
upp_arr = np.zeros(shape=(nrows,ncols),dtype=np.int64)
upp_arr[0,0] = -1000
upp_arr[1:,0] = np.array([gap_open + i*gap_extn for i in range(1,nrows)],dtype=np.int64)
#print(upp_arr)

# Define the left layer matrix and initialize
# Initialize first row = gap_open + col_index * gap_extn
lft_arr = np.zeros(shape=(nrows,ncols),dtype=np.int64)
lft_arr[0,0] = -1000
lft_arr[0,1:] = np.array([gap_open + i*gap_extn for i in range(1,ncols)],dtype=np.int64)
#print(lft_arr)

# Define the diagonal layer matrix and initialize
# Initialize first column, row = 0
dig_arr = np.zeros(shape=(nrows,ncols),dtype=np.int64)
dig_arr[0,0] = -1000
#print(dig_arr)

# Define the diagonal layer matrix and initialize
# Initialize first column = gap_open + row_index * gap_extn
# Initialize first row = gap_open + col_index * gap_extn
sub_arr = np.zeros(shape=(nrows,ncols),dtype=np.int64)
sub_arr[0,1:] = np.array([gap_open + i*gap_extn for i in range(1,ncols)],dtype=np.int64)
sub_arr[1:,0] = np.array([gap_open + i*gap_extn for i in range(1,nrows)],dtype=np.int64)
#print(sub_arr)

# Define trace back matrix
# Initialize first column = 'u'
# Initialize first row = 'l'
trace_arr = np.array([['x' for i in range(0,ncols)]for j in range(0,nrows)], dtype=np.object)
trace_arr[0,1:] = np.array(['l' for i in range(0,ls0)],dtype=np.object)
trace_arr[1:,0] = np.array(['u' for i in range(0,ls1)],dtype=np.object)

# Fill the intermediate arrays
neighbors = np.array([0,0], dtype=np.int64)
fneigh = np.array([0,0,0], dtype=np.int64)
for i in range(1,nrows):
    for j in range(1,ncols):

        # Fill upper matrix
        neighbors = [0,0]
        neighbors[0] = sub_arr[i,j-1] + gap_open + gap_extn
        neighbors[1] = upp_arr[i,j-1] + gap_extn
        upp_arr[i,j] = np.amax(neighbors)

        # Fill left matrix
        neighbors = [0,0]
        neighbors[0] = sub_arr[i-1,j] + gap_open + gap_extn
        neighbors[1] = lft_arr[i-1,j] + gap_extn
        lft_arr[i,j] = np.amax(neighbors)

        # fill diagonal matrix
        if(s1_arr[i] == s0_arr[j]):
            dig_arr[i,j] = sub_arr[i-1,j-1] + match_score
        if(s1_arr[i] != s0_arr[j]):
            dig_arr[i,j] = sub_arr[i-1,j-1] + mismatch_score

        # fill traceback matrix
        fneigh = [0,0,0]
        fneigh = np.array([dig_arr[i,j],upp_arr[i,j],lft_arr[i,j]],dtype=np.int64)
        sub_arr[i,j] = np.amax(fneigh)
        if(np.argmax(fneigh) == 0):
            trace_arr[i,j] = 'd'
        if(np.argmax(fneigh) == 1):
            trace_arr[i,j] = 'l'
        if(np.argmax(fneigh) == 2):
            trace_arr[i,j] = 'u'

print('Upper layer Matrix:')
print(upp_arr)
print()

print('Left layer Matrix:')
print(lft_arr)
print()

print('Diagonal layer Matrix:')
print(dig_arr)
print()

print('Substitution Matrix:')
print(sub_arr)
print()

print('Trace back Matrix:')
print(trace_arr)

# Determine the alignment using traceback matrix
i = trace_arr.shape[0] - 1
j = trace_arr.shape[1] - 1
a0 = []; a1 = []; a2 = [];
score = 0;ugap_ind = 0; lgap_ind = 0;

# Traverse from right bottom to the top left to create the alignment
while(trace_arr[i,j] != 'x'):
    if(trace_arr[i,j] == 'd'):
        a0.append(s0_arr[j])
        a1.append(s1_arr[i])
        if(s0_arr[j] == s1_arr[i]):
            a2.append('|')
            score = score + match_score

        if(s0_arr[j] != s1_arr[i]):
            a2.append('*')
            score = score + mismatch_score
        i = i-1;j=j-1;
    if(trace_arr[i,j] == 'l'):
        a0.append(s0_arr[j])
        a1.append('-')
        a2.append(' ')
        lgap_ind = lgap_ind + 1
        score = score + gap_open + lgap_ind*gap_extn
        i=i;j=j-1;
    if(trace_arr[i,j] == 'u'):
        a0.append('-')
        a1.append(s1_arr[i])
        a2.append(' ')
        ugap_ind = ugap_ind + 1
        score = score + gap_open + ugap_ind*gap_extn
        i=i-1;j=j;

as0 = ''.join(a0[::-1]); as1 = ''.join(a1[::-1]); as2 = ''.join(a2[::-1])

# print the output to the console
print()
print('Global Alignment without Affine gap with score = {}:'.format(score))
print(as0)
print(as2)
print(as1)


class Solution:
    def missingElement(self, nums: List[int], k: int) -> int:
        start = nums[0]
        left, right = 0, len(nums) - 1
        while left <= right:
            mid = left + (right - left) // 2
            num_missing = nums[mid] - mid - start
            if num_missing < k:
                left = mid + 1
            else:
                right = mid - 1
        return (nums[right - 1] + k) - (nums[right - 1] - right - start)

## Time Complexity: O(log N)
## Time Complexity: O(1)

Binary Search/1060. Missing Element in Sorted Array.py


from django.shortcuts import render
from django.http import HttpResponse
import os
# Create your views here.

import csv
import json

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(BASE_DIR)
def index(request,):
	Budget = request.GET['Budget']
	path_to_file = BASE_DIR +'/data/Detail_Of_Places.csv'
	with open(path_to_file,'rt')as f:
		data = csv.reader(f)
		context = {
		'list_of_places': []
		}
		count =0
		for row in data:
			if(count == 0):
				count =1
				continue
			if(row[4]==''):

				row[4] = 0.0
			# print(type(int(float(row[4]))))
			# print(row[4])

			if(float(row[4])<= float(Budget)):
				context['list_of_places'].append({
					"nameOfPlace" : row[1],
					"linkOfImage" : row[2],
					"description" : row[3],
					"budget"	  : row[4]
					})

	return HttpResponse(json.dumps(context),content_type="application/json")


# BOJ 2606 바이러스
# BFS - queue
# list, deque

ans = 0 # 바이러스에 감염된 컴퓨터의 수

n, m = int(input()), int(input()) # 컴퓨터 수, 연결 수

arr = [[False]*(n+1) for _ in range(n+1)] # edge 정보 저장

for i in range(m):
    c1, c2 = map(int, input().split())
    arr[c1][c2] = True # connected
    arr[c2][c1] = True

# BFS
que = []
visited = [False]*(n+1)
que.append(1) # start node = 1

while que:
    cur = que.pop(0)
    if not visited[cur]:
        ans+=1
        visited[cur] = True

    for i in range(1, n+1):
        if arr[cur][i] and not visited[i]:
            que.append(i)

print(ans-1)


# -*- coding: utf-8 -*-
# @Time    : 2019/1/17 0017 下午 8:53
# @Author  : Youpeng Li
# @Site    :
# @File    : hasSubtree.py
# @Software: PyCharm

'''
题目：输入两棵二叉树A，B，判断B是不是A的子结构。（ps：我们约定空树不是任意一个树的子结构）

分析:首先判断根节点是不是相同，如果根节点相同，那么进入判断是否相同的函数；
如果不相同，接着递归判断左边子树与B是不是相同；
如果还不相同，接着递归判断右边子树与B是不是相同。
'''

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def hasSubtree(self, pRoot1: 'TreeNode', pRoot2: 'TreeNode') -> 'TreeNode':
        result = False
        if pRoot1 != None and pRoot2 != None:
            # 判断根节点
            if pRoot1.val == pRoot2.val:
                result = self.same(pRoot1, pRoot2)
            # 判断左子树
            if not result:
                result = self.hasSubtree(pRoot1.left, pRoot2)
            # 判断右子树
            if not result:
                result = self.hasSubtree(pRoot1.right, pRoot2)
        return result

    def same(self, pRoot1: 'TreeNode', pRoot2: 'TreeNode') -> 'bool':
        if pRoot2 == None:
            return True
        if pRoot1 == None:
            return False
        if pRoot1.val != pRoot2.val:
            return False
        return self.same(pRoot1.left, pRoot2.left) and self.same(pRoot1.right, pRoot2.right)

if __name__ == "__main__":
    '''
                  _______8_______                   ___8___
                 /               \                 /       \
            ____8____             7               9         2
           /         \
          9         __2__
                   /     \
                  4       7
    '''
    t1 = TreeNode(8)
    t2 = TreeNode(8)
    t3 = TreeNode(7)
    t4 = TreeNode(9)
    t5 = TreeNode(2)
    t6 = TreeNode(4)
    t7 = TreeNode(7)

    t1.left = t2
    t1.right = t3

    t2.left = t4
    t2.right = t5

    t5.left = t6
    t5.right = t7

    pRoot1 = t1

    t11 = TreeNode(8)
    t12 = TreeNode(9)
    t13 = TreeNode(2)

    t11.left = t12
    t11.right = t13

    pRoot2 = t11

    a = Solution()
    res = a.hasSubtree(pRoot1, pRoot2)
    print(res)


import probabilities as pr
import random, copy, re

features = {}
actions = {}
prob_size_sequence = 0

class tree:

	def __init__(self, root=None):
		self.root=root

	def add_root(self,label=None):
		self.root=node(label)
		return self.root

	def __str__(self):
		res = str(self.root)
		length = len(res)+1
		if self.root:
			if self.root.children:
				res+=':\n'
				for value in self.root.children:
					res += ' '*(len(str(self.root))+1) + str(value) + "--->" + self.__rec_print(self.root.children[value], length+len(str(value))+4)
		return res

	def __rec_print(self, node, length):
		res = str(node)
		if node.children:
			res+=':\n'
			for value in node.children:
				res += ' '*(length+len(str(node))+1) + str(value) + "--->" + self.__rec_print(node.children[value], length+len(str(node))+4)
		elif node.action_value != None:
			res+=': ' + str(node.action_value) + '\n'
		else:
			res+='\n'
		return res

	def create_random_tree(self):
		global features, actions, prob_size_sequence
		num_features = len(features)
		prior_prob_f = 0.90
		copy_features = copy.deepcopy(features)
		copy_actions = copy.deepcopy(actions)
		root = self.add_root(random.choices(list(features), k=1)[0])
		values = copy.deepcopy(features[str(root)])
		original_size = len(values)
		del copy_features[str(root)]
		while values:
			value = values[0]

			#compute prob. size of the sequence
			res_prob_seq = pr.binomial(len(values)-1, prob_size_sequence)
			size_seq = random.choices([n+1 for n in range(len(values))], weights=[float(x) for x in res_prob_seq], k=1)[0]
			if len(values)-size_seq < 2:
				size_seq=len(values)

			#compute prob. of a feature or of an action
			prob_f_a = pr.p_feat_action(num_features, prior_prob_f, prior_prob_f)
			res_f_a = random.choices(["f","a"], weights=[float(x) for x in prob_f_a], k=1)[0]

			if res_f_a=="a" or not copy_features: #if action is the outcome or there are no features
				action = random.choices(list(copy_actions), k=1)[0]
				action_value = random.choices(copy_actions[action])[0]
				copy_actions[action].remove(action_value)
				if not copy_actions[action]:
					del copy_actions[action]
				ind_val = values.index(value)
				while size_seq:
					root.children[values[ind_val]].add_label(action, action_value)
					ind_val+=1
					size_seq-=1

			else: #if feature is the outcome
				feature = random.choices(list(copy_features), k=1)[0]
				ind_val = values.index(value)
				while size_seq:
					root.children[values[ind_val]].add_label(feature)
					self.__rec_create_random_tree(root.children[values[ind_val]], copy.deepcopy(copy_features), actions, prior_prob_f, prob_f_a[0], num_features)
					ind_val+=1
					size_seq-=1
			values = values[ind_val:]

	def __rec_create_random_tree(self, node, features, actions, prior_prob_f, prob_f, num_features):
		global prob_size_sequence
		copy_actions = copy.deepcopy(actions)
		values = copy.deepcopy(features[str(node)])
		original_size = len(values)
		del features[str(node)]
		while values:
			value = values[0]

			#compute prob. size of the sequence
			res_prob_seq = pr.binomial(len(values)-1, prob_size_sequence)
			size_seq = random.choices([n+1 for n in range(len(values))], weights=[float(x) for x in res_prob_seq], k=1)[0]
			if len(values)-size_seq < 2:
				size_seq=len(values)

			#compute prob. of a feature or of an action
			prob_f_a = pr.p_feat_action(num_features, prior_prob_f, prob_f)
			res_f_a = random.choices(["f","a"], weights=[float(x) for x in prob_f_a], k=1)[0]

			if res_f_a=="a" or not features: #if action is the outcome or there are no features
				action = random.choices(list(copy_actions), k=1)[0]
				action_value = random.choices(copy_actions[action])[0]
				copy_actions[action].remove(action_value)
				if not copy_actions[action]:
					del copy_actions[action]
				ind_val = values.index(value)
				while size_seq:
					node.children[values[ind_val]].add_label(action, action_value)
					ind_val+=1
					size_seq-=1

			else: #if feature is the outcome
				feature = random.choices(list(features), k=1)[0]
				ind_val = values.index(value)
				while size_seq:
					node.children[values[ind_val]].add_label(feature)
					self.__rec_create_random_tree(node.children[values[ind_val]], copy.deepcopy(features), actions, prior_prob_f, prob_f, num_features)
					ind_val+=1
					size_seq-=1
			values = values[ind_val:]

	def final_tree(self):
		root = self.root
		if root.label == None:
			return
		for child in root.children:
			self.__rec_final_tree(root.children[child])

	def __rec_final_tree(self, node):
		if node.label == None:
			if len(node.most_likely.split(";")) == 2: #feature
				node.add_label(node.most_likely.split(";")[0])
			else:
				action = node.most_likely.split(":")
				action_value = action[1]
				node.add_label(action[0], int(action_value))
		elif node.action_value == None:
			for child in node.children:
				self.__rec_final_tree(node.children[child])

class node:

	def __init__(self, label=None, parent=None):
		global features, actions
		self.u=0
		self.label=label
		self.children={}
		self.action_value=None
		self.parent = parent
		self.most_likely = None

		if self.label != None and self.action_value == None: #if is a feature, for each value add children nodes
			self.__add_children()

	def __add_children(self): #create children nodes of the feature
		for value in features[self.label]:
			self.children[value] = node(None, self)

	def add_label(self, label, action_value=None): #assign the label to the node, if is a feature create the children nodes
		self.label = label
		if action_value:
			self.action_value=action_value
		else:
			self.__add_children()

	def __str__(self):
		return str(self.label)

	def count_nodes_subtree(self):
		res = 1
		for value in self.children:
			res+=self.children[value].count_nodes_subtree()
		return res

	def count_actions_subtree(self):
		res = 0
		if self.label != None and self.action_value != None:
			res+=1
		else:
			if self.children:
				for child in self.children:
					res+=self.children[child].count_actions_subtree()
		return res

def create_features(numb, minim, maxim):
	global features
	prob = pr.binomial(maxim-minim+1, 0.50)
	sizes = [x for x in range(minim,maxim+1)]
	for n in range(numb):
		prob = pr.binomial(maxim-minim, 0.50)
		size = random.choices(sizes, weights=[float(x) for x in prob], k=1)[0]
		features[f"feature{n+1}"] = [x+1 for x in range(size)]
	return features

def create_actions(numb, minim, maxim):
	global actions
	prob = pr.binomial(maxim-minim+1, 0.50)
	sizes = [x for x in range(minim,maxim+1)]
	for n in range(numb):
		prob = pr.binomial(maxim-minim, 0.50)
		size = random.choices(sizes, weights=[float(x) for x in prob], k=1)[0]
		actions[f"action{n+1}"] = [x+1 for x in range(size)]
	return actions

def count_different_nodes(first, second):
	res = 0
	if str(first.root) != str(second.root):
		res+=first.root.count_nodes_subtree()
	else:
		for value in first.root.children:
			res+=rec_count_different_nodes(first.root.children[value], second.root.children[value])
	return res

def rec_count_different_nodes(first, second):
	res = 0
	if first.label != second.label:
		res+=first.count_nodes_subtree()
	else:
		if first.children: #if they are features
			for value in first.children:
				res+=rec_count_different_nodes(first.children[value], second.children[value])
	return res


from grid import ColoredGrid
from wilsons import Wilsons

for n in range(4):
    grid = ColoredGrid(20, 20)
    Wilsons.on(grid)
    middle = grid[grid.rows // 2, grid.columns // 2]
    grid.set_distances(middle.distances())
    img = grid.to_png()
    img.save("./images/wilson_colored_%d.png" % n)


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

class CandidateEmail:

    Emailbutton = "//a[@id='btn-email']"
    EmailSubject = "//input[@name='subject']"
    emailIframe = "//div[@class='tox-edit-area']/iframe"
    EmailBody = "//*[@id='tinymce']"
    AddCCEmailOption = "//*[text()='Add CC Emails']"
    AddCCTextBox = "//label[text()='CC']/following-sibling::div//input"
    AddCCEmailValue = "//*[@aria-label='test+06@getbrokerkit.com']"
    CancelAndHideOption = "//a[text()='Cancel and hide']"
    AddAttachmentBtn = "//div[text()='Add Attachment']"
    SelectTemplateDropdown = "//div[text()='Select a template']"
    SelectTemplateOptions = "//*[text()='Mail with all variables']"

    def __init__(self,driver):
        self.driver = driver

    def AddCandidateStatusEmail(self,subject,body):
        print("set subject & body of email")
        self.driver.find_element_by_xpath(self.Emailbutton).click()
        time.sleep(5)
        self.driver.find_element_by_xpath(self.EmailSubject).send_keys(subject)
        time.sleep(5)
        self.driver.switch_to_frame(self.driver.find_element_by_xpath(self.emailIframe))

        self.driver.find_element_by_xpath(self.EmailBody).send_keys(body)
        self.driver.switch_to_default_content()
        time.sleep(5)

    def ClickAddCCEmailOption(self):
        print("Click on add cc email option")
        self.driver.find_element_by_xpath(self.AddCCEmailOption).click()
        time.sleep(5)

    def SetAddCCTextBox(self,CCemail):
        print("set value for cc email")
        time.sleep(2)
        self.driver.find_element_by_xpath(self.AddCCTextBox).send_keys(CCemail)
        time.sleep(2)
        self.driver.find_element_by_xpath(self.AddCCTextBox).send_keys(Keys.ENTER)

        time.sleep(2)

    def ClickAddCCEmailValue(self):
        print("Click on Add cc email value")
        self.driver.find_element_by_xpath(self.AddCCEmailValue).click()
        time.sleep(3)

    def ClickCancelAndHideOption(self):
        print("Click on cancel hide options")
        self.driver.find_element_by_xpath(self.CancelAndHideOption).click()
        time.sleep(2)

    def ClickAddAttachmentBtn(self):
        print("Click on add attachment button & upload attachment")
        self.driver.find_element_by_xpath(self.AddAttachmentBtn).click()
        time.sleep(5)

    def SetEmailTemplate(self):
        print("Set email template")
        self.driver.find_element_by_xpath(self.SelectTemplateDropdown).click()
        time.sleep(2)
        self.driver.find_element_by_xpath(self.SelectTemplateOptions).click()


#
import pandas as pd

from formula import CalcRatioPer, CalcBalance
from widget_helper import Graph

class AnalysisFinancials:
    def __init__(self):
        pass

    @staticmethod
    def get_graph_data(statement) -> Graph:
        # extract financials
        statement = statement.financials

        # Calc Profit Ratio
        cp = CalcRatioPer(statement.T['Operating Income'], statement.T['Total Revenue'])
        if cp.result.exec_continue:
            profit_ratio_1 = cp.result.result_data
        else:
            profit_ratio_1 = None

        cp = CalcRatioPer(statement.T['Net Income'], statement.T['Total Revenue'])
        if cp.result.exec_continue:
            profit_ratio_2 = cp.result.result_data
        else:
            profit_ratio_2 = None

        # generate Graph Class
        g = Graph()
        g.graph_type = 'line graph'
        g.set_title('Profit Ratio Graph')
        # line 1
        g.set_x_label('Date')
        g.set_y_label('Profit Rate')
        g.set_data_label('Operating Income')
        if profit_ratio_1 is not None:
            g.set_data(profit_ratio_1)
        # line 2
        g.set_x_label('Date')
        g.set_y_label('Profit Rate')
        g.set_data_label('Net Income')
        if profit_ratio_2 is not None:
            g.set_data(profit_ratio_2)

        return g

    @staticmethod
    def get_rank_data(collection: pd.DataFrame) -> Graph:
        # get data from collection
        total_revenue = collection.T['Total Revenue']
        operating_income = collection.T['Operating Income']
        net_income = collection.T['Net Income']

        # Calc Capital Adequacy Ratio & Current Ratio
        average_pr1 = CalcRatioPer(operating_income, total_revenue)
        average_pr2 = CalcRatioPer(net_income, total_revenue)
        average_1 = pd.Series.sort_values(average_pr1.result.result_data, ascending=False)
        average_1 = average_1.head(15)
        average_2 = pd.Series.sort_values(average_pr2.result.result_data, ascending=False)
        average_2 = average_2.head(15)

        # generate Graph Object
        g = Graph()
        g.graph_type = 'multi_bar graph'
        g.set_title('Profit Ratio Ranking Graph (Top15)')
        # bar1
        g.set_x_label('Company')
        g.set_y_label('Average %')
        g.set_data_label('By Operating Income')
        g.set_data(average_1)
        # bar2
        g.set_x_label('Company')
        g.set_y_label('Average %')
        g.set_data_label('By Net Income')
        g.set_data(average_2)

        # print(g)
        return g

class AnalysisBalanceSheet:
    def __init__(self):
        pass

    @staticmethod
    def get_graph_data(statement) -> Graph:
        statement = statement.balance_sheet

        # Calc Profit Ratio
        cp = CalcRatioPer(statement.T['Total Stockholder Equity'], statement.T['Total Assets'])  # 自己資本比率
        if cp.result.exec_continue:
            profit_ratio_1 = cp.result.result_data
        else:
            profit_ratio_1 = None

        cp = CalcRatioPer(statement.T['Total Current Assets'], statement.T['Total Current Liabilities'])  # 流動比率
        if cp.result.exec_continue:
            profit_ratio_2 = cp.result.result_data
        else:
            profit_ratio_2 = None

        # Generate Graph
        g = Graph()
        g.graph_type = 'multi_line graph'
        g.set_title('Capital Adequacy & Current Ratio Graph')
        # line 1
        g.set_x_label('Date')
        g.set_y_label('Percentage')
        g.set_data_label('Capital adequacy ratio')
        if profit_ratio_1 is not None:
            g.set_data(profit_ratio_1)
        # line 2
        g.set_x_label('Date')
        g.set_y_label('Percentage')
        g.set_data_label('Current ratio')
        if profit_ratio_2 is not None:
            g.set_data(profit_ratio_2)

        return g

    @staticmethod
    def get_rank_data(collection: pd.DataFrame) -> Graph:
        # get data from collection
        total_stockholder_equity = collection.T['Total Stockholder Equity']
        total_assets = collection.T['Total Assets']
        total_current_assets = collection.T['Total Current Assets']
        total_current_liabilities = collection.T['Total Current Liabilities']

        # Calc Capital Adequacy Ratio & Current Ratio
        average_pr1 = CalcRatioPer(total_stockholder_equity, total_assets)
        average_pr2 = CalcRatioPer(total_current_assets, total_current_liabilities)
        average_1 = pd.Series.sort_values(average_pr1.result.result_data, ascending=False)
        average_1 = average_1.head(15)
        average_2 = pd.Series.sort_values(average_pr2.result.result_data, ascending=False)
        average_2 = average_2.head(15)

        # generate Graph Object
        g = Graph()
        g.graph_type = 'multi_bar graph'
        g.set_title('Capital Adequacy Ratio Ranking Graph (Top10)')
        # bar1
        g.set_x_label('Company')
        g.set_y_label('Average %')
        g.set_data_label('Capital Adequacy Ratio')
        g.set_data(average_1)
        # bar2
        g.set_x_label('Company')
        g.set_y_label('Average %')
        g.set_data_label('Current Ratio')
        g.set_data(average_2)

        # print(g)
        return g

class AnalysisHistory:
    def __init__(self):
        pass

    @staticmethod
    def get_graph_data(statement) -> Graph:
        # extract financials
        statement = statement.history(period='1y')
        df = pd.DataFrame()
        df.insert(0, 'Open', statement['Open'])
        df.insert(1, 'Close', statement['Close'])
        df.insert(2, 'High', statement['High'])
        df.insert(3, 'Low', statement['Low'])
        df.insert(4, 'Volume', statement['Volume'])

        # Generate Graph
        g = Graph()
        g.graph_type = 'candle graph'
        g.set_title('Candle Graph')
        # line 1
        g.set_x_label('Date')
        g.set_y_label('Price')
        g.set_data_label('')
        if statement is not None:
            g.set_data(df)

        return g

    @staticmethod
    def get_rank_data(collection: pd.DataFrame) -> Graph:
        # get data from collection
        open_price = collection.T['Open']
        close_price = collection.T['Close']
        volume = collection.T['Volume']

        # Calc Capital Adequacy Ratio & Current Ratio
        balance = CalcBalance(open_price, close_price)
        calc_data = pd.DataFrame()
        calc_data.insert(0, 'Balance', balance.result.result_data)
        calc_data.insert(1, 'Volume', volume)
        calc_data = calc_data.sort_values('Balance', ascending=False)
        calc_data = calc_data.head(15)

        # generate Graph Object
        g = Graph()
        g.graph_type = 'multi_bar graph'
        g.set_title('Price Change Average Ranking Graph (Top10)')
        # bar1
        g.set_x_label('Company')
        g.set_y_label('Currency')
        g.set_data_label('Balance')
        g.set_data(calc_data['Balance'])
        # bar2
        g.set_x_label('Company')
        g.set_y_label('unit')
        g.set_data_label('Volume')
        g.set_data(calc_data['Volume'])

        # print(g)
        return g

class AnalysisCashFlow:
    def __init__(self):
        pass

    @staticmethod
    def get_graph_data(statement) -> Graph:
        # extract financials
        statement = statement.cashflow
        df = pd.DataFrame()
        df_var = statement.T['Total Cash From Operating Activities']
        df.insert(loc=0, column='Total Cash From Operating Activities', value=df_var)
        # Operating Collection
        df_var = statement.T['Total Cash From Financing Activities']
        df.insert(loc=1, column='Total Cash From Financing Activities', value=df_var)
        # Net Collection
        df_var = statement.T['Total Cashflows From Investing Activities']
        df.insert(loc=2, column='Total Cashflows From Investing Activities', value=df_var)

        # Generate Graph
        g = Graph()
        # g.graph_type = 'stacked_bar graph'
        g.graph_type = 'line graph'
        g.set_title('Line Graph')
        # line 1
        g.set_x_label('Date')
        g.set_y_label('Amount')
        g.set_data_label('Total Cash From Operating Activities')
        if statement is not None:
            g.set_data(df['Total Cash From Operating Activities'])
        # line 2
        g.set_x_label('Date')
        g.set_y_label('Amount')
        g.set_data_label('Total Cash From Financing Activities')
        if statement is not None:
            g.set_data(df['Total Cash From Financing Activities'])
        # line 3
        g.set_x_label('Date')
        g.set_y_label('Amount')
        g.set_data_label('Total Cashflows From Investing Activities')
        if statement is not None:
            g.set_data(df['Total Cashflows From Investing Activities'])

        return g


import pandas as pd
import Common_func
import os
import Modis_IO
import math
import numpy as np
import cupy as cp

root_path = Common_func.UsePlatform()
result_path = os.path.join(root_path,'results','nights')
amount_data = np.zeros((1221,2224))
band =1
im_data_list = []
im_data_list_mean =[]
im_geotrans = None
im_proj = None
for year in range(2003,2019):
    filename = os.path.join(result_path,str(year)+'.tif')
    #print (filename)
    try:
        im_data,im_geotrans,im_proj = Modis_IO.read_img(filename,band)
        im_data_list.append(im_data.flatten())
    except:
        continue

im_data_list_std = np.nanstd(im_data_list,axis=0).reshape(1221,2224)
# cupy
#im_data_list = cp.asarray(im_data_list)
#im_data_list_std = cp.std(im_data_list,axis=0).reshape(1221,2224)
Modis_IO.write_img(os.path.join(result_path,'std_night.tif'),im_proj,im_geotrans,im_data_list_std)


import hardware

async def set_rtc_time(secrets):

    import rtc
    import time
    import asyncio
    print("Setting NTP server...")
    hardware.espwifi.esp.sntp_config(True, secrets['timezone'], secrets['ntp_server'])
    # Get the time, check the year, if it is 1970 then retry every 10 seconds
    t = hardware.espwifi.esp.sntp_time
    while '1970' in t:
        print("Time not set, retrying...")
        t = hardware.espwifi.esp.sntp_time
        # print(time)
        await asyncio.sleep(10)
    # Convert the time to a string
    t = t.decode('ascii')
    print("Time received: {}".format(t))
    # Convert the time to a datetime object
    date_time = await convert_time(t)
    # Set the RTC
    boardclock = rtc.RTC()
    boardclock.datetime = time.struct_time((date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, date_time.weekday(), 0, -1))

async def convert_time(t):

    # Convert the time to a datetime object using the datetime module
    # Extract individual components
    # day_of_week = t[:3]
    month = t[4:7]
    day = int(t[8:10])
    hour = int(t[11:13])
    minute = int(t[14:16])
    second = int(t[17:19])
    year = int(t[20:])

    # Map month abbreviation to month number
    month_map = {
        'Jan': 1,
        'Feb': 2,
        'Mar': 3,
        'Apr': 4,
        'May': 5,
        'Jun': 6,
        'Jul': 7,
        'Aug': 8,
        'Sep': 9,
        'Oct': 10,
        'Nov': 11,
        'Dec': 12
    }
    month_number = month_map[month]

    # Create datetime object
    from adafruit_datetime import datetime
    date_time = datetime(year, month_number, day, hour, minute, second)

    return date_time


from layer import Layer

class Network:
    """Neural network"""

    def __init__(self, model: list):
        self.layers = [] # layers in neural network
        self.model = model
        for i in range(len(model)):
            self.layers.append(Layer(model[i].get("nodeCount"), model[i].get("type")))

        for i in range(len(model) - 1):
            self.layers[i].connect(len(self.layers[i + 1].nodes))

    def feed_forward(self):
        """Feed forward the network"""
        for i in range(len(self.model) - 1):
            self.layers[i].feed_forward(self.layers[i + 1])


'''Program that determines the valid words in a given file and prints
   statistics about the words, a table and a horizontal bar graphs
   of the lengths of the words and their occurences.
   Author: Harman Singh
   Version: 4 June 2014 '''

import os

TABLE_TITLE = " Len  Freq"
FREQ_TABLE_TEMPLATE = "{:>4}{:>6}"

GRAPH_TITLE = " Len  Freq Graph"
GRAPH_LINE_TEMPLATE = "{:>4}{:>5}% {}"

def get_filename():
    """Returns a valid filename"""
    filename = input ("Please enter filename: ")
    while not os.path.isfile(filename):
        print(filename, "not found...")
        filename = input("Please enter filename: ")
    return filename

def display_word_length_table(words, word_len_max):
    '''prints a table of the lengths of words in the word list
       and their respective frequencies.'''
    print()
    print(TABLE_TITLE)
    word_length_dict = {}

    for i in range(1, word_len_max + 1):
        word_length_dict[i] = 0

    for word in words:
        word_length_dict[len(word)] += 1

    for length, count in sorted(word_length_dict.items()):
        print(FREQ_TABLE_TEMPLATE.format(length, count))

    display_frequency_graph(word_length_dict, len(words))

def display_frequency_graph(word_length_dict, length_of_words):
    '''prints a graph of the word lengths in the list of words
       and their respective occurence as a percentage. The horizontal bars are
       displayed as multiples of: '='. '''
    print()
    print(GRAPH_TITLE)

    for length, count in sorted(word_length_dict.items()):

        relative_freq = int(count / length_of_words * 100)
        num_of_equals = relative_freq * '='
        print(GRAPH_LINE_TEMPLATE.format(length, relative_freq, num_of_equals))

def max_word_frequency(words):
    '''returns the most frequently ocuring word in the list of valid words
       from the given file'''
    word_dict = {}
    for word in words:
        word_dict[word] = word_dict.get(word, 0) + 1

    return (max(word_dict.values()))

def get_words_from_file(filename):
    '''Reads the file with given name and returns a list of valid words.
    The valid words are between the sentences:
    '*** START OF' and '*** END'. '''

    word_list = []
    is_reading = True
    infile = open(filename, 'r', encoding="utf-8")
    sentence = infile.readline()

    while not(sentence.startswith("*** START OF")):
        sentence = infile.readline()

    while is_reading:
        sentence = infile.readline()
        if sentence.startswith("*** END"):
            is_reading = False
        else:
            word_list += check_words_in_sentence(sentence)

    return word_list

def check_words_in_sentence(sentence):
    '''Checks each word in a valid sentence and returns a list of
       valid lower case words'''

    valid_words = []

    for word in sentence.split():
        word = word.strip('\n"-:\';,.').lower()
        if word.isalpha():
            valid_words.append(word)

    return valid_words
# ----------------------------------------------

def avg_length(words):
    """Returns the average length of words in the words list"""
    sum_lengths = 0
    for word in words:
        sum_lengths += len(word)
    average = sum_lengths / len(words)
    return average

def max_word_length(words):
    """Returns the length of the longest word in the list of words.
    Or 0 if there are no words in the list...
    """
    if len(words) > 0:
        max_length = len(words[0])
        for word in words:
            length = len(word)
            if length > max_length:
                max_length = length
    else:
        max_length = 0
    return max_length

def main():
    '''Main function: prompt for filename, prints statistics about
       valid words in the given file. Also, prints a table and graph
       of different lengths of the words in the file and
       their respective frequencies.'''

    filename = get_filename()
    words = get_words_from_file(filename)
    word_len_max = max_word_length(words)

    print(" {} loaded ok.".format(filename))
    print()
    print('Word summary (all words):')
    print(' Number of words = {}'.format(len(words)))
    print(' Avg word length = {:.2f}'.format(avg_length(words)))
    print(' Max word length = {}'.format(word_len_max))
    print(' Max frequency = {}'. format(max_word_frequency(words)))

    display_word_length_table(words, word_len_max)

main()


import random
import discord
import os
from discord.ext import commands

class Imgspam(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def cat(self, ctx):
        rand = random.choice(os.listdir("/root/TomodachAI/cats"))
        await ctx.send(file=discord.File("cats/" + rand))

    @commands.command()
    async def think(self, ctx):
        rand = random.choice(os.listdir("/root/TomodachAI/think"))
        await ctx.send(file=discord.File("think/" + rand))

    @commands.command()
    async def smug(self, ctx):
        rand = random.choice(os.listdir("/root/TomodachAI/smug"))
        await ctx.send(file=discord.File("smug/" + rand))

    @commands.command()
    async def dance(self, ctx):
        rand = random.choice(os.listdir("/root/TomodachAI/dance"))
        try:
            await ctx.send(file=discord.File("dance/" + rand))
        except Exception:
            await ctx.send('command aint workin boss')
            return

    @commands.command()
    async def scatter(self, ctx):
        await ctx.send(file=discord.File("/root/TomodachAI/SCATTER.mp4"))

def setup(bot):
    bot.add_cog(Imgspam(bot))


import json
import cv2
import numpy as np
from PIL import Image
from torch.utils import data as data

class ImageData(data.Dataset):
    def __init__(self, files, trans, trans2, tokenizer):
        super(ImageData, self).__init__()
        self.files = files
        self.vae_transforms = trans
        self.yolo_transforms = trans2
        self.tokenizer = tokenizer

    @staticmethod
    def load_prompt(json_path):
        with open(json_path, 'r') as json_file:
            data = json.load(json_file)
        prompt = data['title']
        return prompt

    def __getitem__(self, data_index):
        try:
            # load image
            image = Image.open(self.files[data_index]).convert("RGB")
            detector_input = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
            pixel_values = self.vae_transforms(image)
            detector_input = self.yolo_transforms(detector_input)

            # load prompt
            prompt_path = self.files[data_index].replace('.jpg', '.json')
            prompt = self.load_prompt(prompt_path)

            inputs = self.tokenizer(
                prompt, max_length=self.tokenizer.model_max_length,
                padding="do_not_pad",
                truncation=True
            )
            input_ids = inputs.input_ids

        except Exception as e:
            print(self.files[data_index], e)
            return None

        return {
            "pixel_values": pixel_values,
            "detector_input": detector_input,
            "input_ids": input_ids,
        }

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