from collections import defaultdict

def parse_right(item):
    return item.split(',')[0]

def build_graph(entry_list):
    graph = defaultdict(list)
    for entry in entry_list:
        left = entry[0]
        if len(entry) > 3:
            for i, item in enumerate(entry[3:]):
                graph[left].append(parse_right(item))
    return graph

def build_weight(entry_list):
    weight = {}
    for entry in entry_list:
        left = entry[0]
        w = int(entry[1][1:-1])
        weight[left] = w
    return weight

def get_tree_w(graph, root, weight):
    if root is None:
        return 0
    w = weight[root]
    for next in graph[root]:
        w += get_tree_w(graph, next, weight)
    return w

def build_rev(graph):
    rev = {}
    for key in graph:
        for val in graph[key]:
            rev[val] = key
    return rev

def get_leaves(graph):
    resp = []
    for key, neighs in graph.items():
        for neigh in neighs:
            if neigh not in graph:
                resp.append(neigh)
    return resp

def get_unbalanced_parent(graph, weight):
    rev_graph = build_rev(graph)
    leaves = get_leaves(graph)
    q = leaves
    visited = set()
    while q:
        cur = q.pop()
        visited.add(cur)
        parent = rev_graph[cur]
        child_vals = set()
        for child in graph[parent]:
            if not child_vals:
                child_vals.add(get_tree_w(graph, child, weight))
            else:
                child_w = get_tree_w(graph, child, weight)
                if child_w not in child_vals:
                    return parent

        if parent not in visited:
            q.insert(0, parent)

def get_unbalanced_child(graph, weight, parent):
    seen = defaultdict(list)
    for child in graph[parent]:
        seen[get_tree_w(graph, child, weight)].append(child)

    expected = 0
    cur = 0
    for value, l in seen.items():
        if len(l) == 1:
            cur = value
        else:
            expected = value

    diff = expected - cur

    return seen[cur], weight[seen[cur][0]] + diff

def get_new_weight(entry_list):
    root = get_root(entry_list)
    graph = build_graph(entry_list)
    weight = build_weight(entry_list)

    unbalanced_parent = get_unbalanced_parent(graph, weight)
    unbalanced_child, new_w = get_unbalanced_child(graph, weight, unbalanced_parent)
    return new_w

def get_root(entry_list):
    total = []
    is_right_rule = set()
    for entry in entry_list:
        total.append(entry[0])
        if len(entry) > 3:
            for i, item in enumerate(entry[3:]):
                is_right_rule.add(parse_right(item))
    for item in total:
        if item not in is_right_rule:
            return item
    return None

def main():
    entry = []
    while True:
        line = input()
        if line == '':
            break
        entry.append(line.split())
    resp = get_new_weight(entry)
    print(resp)

if __name__ == '__main__':
    main()


def computepay(h, r):
    try:
        h = float(hrs)
        r = float(rate)
    except:
        print("Error!!! Enter numeric input")
        quit()
    if h < 40:
        grosspay = (h * r)
        return(grosspay)
    else:
        grosspay = (h * r)
        extra = ((h -40) * (r * 0.5))
        grosspay = grosspay + extra
        return(grosspay)

hrs = input("Enter Hours: ")
rate = input("Enter Rate: ")
p = computepay(hrs, rate)
print("Pay", p)


"""The LRU caching scheme is to remove the least recently used frame
when the cache is full and a new page is referenced which is not there in cache"""

from functools import lru_cache

"""
    LRU
    Least Recently Used Cache
"""

@lru_cache(maxsize = 1000)
def fibonacci(n):
    #check that the input is a positive integer
    if type(n) != int:
        raise TypeError("n must be a positive int")
    if n < 1:
        raise ValueError("n must be a positive int")

    #compute the Nth term
    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return fibonacci(n-1) + fibonacci(n-2)

for n in range(1, 1001):
    print(n, ":", fibonacci(n))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('tests', '0005_auto_20160127_0719'),
    ]

    operations = [
        migrations.CreateModel(
            name='test_results',
            fields=[
                ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)),
                ('test_case_id', models.IntegerField()),
                ('test_time_id', models.IntegerField()),
                ('test_result', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='test_times',
            fields=[
                ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)),
                ('test_time', models.TextField()),
            ],
        ),
        migrations.DeleteModel(
            name='Test',
        ),
        migrations.AlterField(
            model_name='test_cases',
            name='test_case',
            field=models.TextField(),
        ),
    ]


import pickle as pickle
import os
import pandas as pd
import torch
import re

class RE_Dataset(torch.utils.data.Dataset):
    """ Dataset 구성을 위한 class."""

    def __init__(self, pair_dataset, labels):
        self.pair_dataset = pair_dataset
        self.labels = labels

    def __getitem__(self, idx):
        item = {key: val[idx].clone().detach() for key, val in self.pair_dataset.items()}
        item["labels"] = torch.tensor(self.labels[idx])
        return item

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

def get_word_new(sentence):
    # ?는 non-greedy matching
    result = re.search(r"'word': '(.+?)'", sentence)
    if result == None:
        result = re.search(r"'word': \"(.+?)\"", sentence)
    result = result.group(1).strip("\"")
    match = re.search(r"\B'\b|\b'\B", result[:-1])
    if match:
        pass
    else:
        result = result.strip("'")
    # result = "'" + result + "'"
    return result

def preprocessing_dataset(dataset):
    """ 처음 불러온 csv 파일을 원하는 형태의 DataFrame으로 변경 시켜줍니다."""
    subject_entity = []
    object_entity = []
    for i, j in zip(dataset["subject_entity"], dataset["object_entity"]):
        i = get_word_new(i)
        j = get_word_new(j)

        subject_entity.append(i)
        object_entity.append(j)
    out_dataset = pd.DataFrame(
        {"id": dataset["id"],
         "sentence": dataset["sentence"],
         "subject_entity": subject_entity,
         "object_entity": object_entity,
         "label": dataset["label"],
        }
    )
    return out_dataset

def preprocessing_dataset_large_class(dataset):
    """ 처음 불러온 csv 파일을 원하는 형태의 DataFrame으로 변경 시켜줍니다."""
    subject_entity = []
    object_entity = []
    for i, j in zip(dataset["subject_entity"], dataset["object_entity"]):
        i = i[1:-1].split(",")[0].split(":")[1]
        j = j[1:-1].split(",")[0].split(":")[1]

        subject_entity.append(i)
        object_entity.append(j)
    out_dataset = pd.DataFrame(
        {"id": dataset["id"],
         "sentence": dataset["sentence"],
         "subject_entity": subject_entity,
         "object_entity": object_entity,
         "label": dataset["label"][0],
        }
    )
    return out_dataset

def load_data(dataset_dir):
    """ csv 파일을 경로에 맞게 불러 옵니다. """
    pd_dataset = pd.read_csv(dataset_dir)
    dataset = preprocessing_dataset(pd_dataset)

    return dataset

def load_data_large_class(dataset_dir):
    """
    csv 파일을 경로에 맞게 불러 옵니다.
    이후, label은 no_relation의 "n", per:~의 "p", org:~의 "o"만 따와 대분류로 설정해줍니다.
    """
    pd_dataset = pd.read_csv(dataset_dir)
    dataset = preprocessing_dataset_large_class(pd_dataset)

    return dataset

def tokenized_dataset(dataset, tokenizer):
    """ tokenizer에 따라 sentence를 tokenizing 합니다."""
    concat_entity = []
    for e01, e02 in zip(dataset["subject_entity"], dataset["object_entity"]):
        temp = ""
        temp = e01 + "[SEP]" + e02
        concat_entity.append(temp)
    tokenized_sentences = tokenizer(
        concat_entity, list(dataset["sentence"]), return_tensors="pt", padding=True, truncation=True, max_length=256, add_special_tokens=True,
    )

    return tokenized_sentences


import numpy as np
from pylab import imshow, show
from math import log

# Constants
n = 2000
width = 2
height = 2
iterations = 1000

if __name__ == "__main__":
    n_rows, n_cols = int(n / 2), int(n)

    real_axis = np.linspace(-0.5 - width / 2, -0.5 + width / 2, num=n_cols)
    imaginary_axis = np.linspace(height / 2, 0, num=n_rows)

    complex_grid = np.zeros((n_rows, n_cols), dtype=np.complex)
    real, imag = np.meshgrid(real_axis, imaginary_axis)
    complex_grid.real = real
    complex_grid.imag = imag

    mandelbrot_top = np.zeros((n_rows,n_cols), dtype=np.float)

    z_grid = np.zeros_like(complex_grid)
    to_do = np.ones((n_rows, n_cols), dtype=bool)

    for iteration in range(iterations):
        z_grid[to_do] = z_grid[to_do]**2 + complex_grid[to_do]
        mask = np.logical_and((z_grid.real**2 + z_grid.imag**2) > 4, to_do)
        mandelbrot_top[mask] = log(iteration + 1)
        to_do = np.logical_and(to_do, np.logical_not(mask))

    mandelbrot_bottom = np.flipud(mandelbrot_top)[1:,:]

    imshow(np.vstack((mandelbrot_top, mandelbrot_bottom)), aspect=1)
    show()


# just call the function to see their action
# basic Rucrrsion function
# ----------------------------------------
# def recursivefun(parameters):
#     if exit from condition satisfied:
#         return some Value
#     else:
#         recursivefun(modifed parameter)
# -----------------------------------------

def count(doll):
    if doll == 1:
        print('last doll')
    else:
        print(doll)
        count(doll-1)
# Factorials using recursion

def factorials(num):
    assert num >= 0 and int(
        num) == num, 'Please the number should be an +VE Integer'
    if num in {0, 1}:
        return 1
    else:
        return num * factorials(num-1)

# Fabonacci numbers in recursion
# 'num' represents the element in faboncci series

def fabonacci(num):
    assert num >= 0 and int(
        num) == num, 'Please the number should be an +VE Integer'
    if num in [0, 1]:
        return num
    else:
        return fabonacci(num-1) + fabonacci(num-2)

# sum of digits of a postive integer using recursion

def sum(num):
    assert num >= 0 and int(
        num) == num, 'Please the number should be an +VE Integer'
    if num == 0:
        return 0
    else:
        return int(num % 10) + sum(int(num/10))

# Power of number using recursion

def poweOf(base,exp):
    assert exp >= 0 and int(
        exp) == exp, 'Please the exponet number should be an +VE Integer'
    if exp == 0:
        return 1
    if exp ==1:
        return base
    return base * poweOf(base,exp-1)

# finding GCD(Greatest common Divisor) of two numbers using recursion
#  using Euclidean algorithm

def gcd(num, num2):
    assert int(num) ==num and int(num2) == num2, 'The numbers must be integer only'
    if num<0:
        num= -1*num
    if num2 < 0:
        num2=-1*num2
    if num2==0:
        return num
    else:
        return gcd(num2, num % num2)

# convert a number from Decimal to Binary using recursion

def binary(num):
    assert int(num) ==num, 'The numbers must be integer only'
    if num == 0:
        return 0
    else:
        return (num % 2) + 10 * binary(int(num/2))


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
import random
import seaborn as sns; sns.set()
from dateutil.relativedelta import relativedelta

from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error

from especial_functions import augmentation_reduction

def exploiting_words(data):
    items_vector = list(data.item_name.unique())
    items_vector = pd.DataFrame({'item_name': items_vector})
    items_vector['lenstr'] = items_vector.item_name.str.len() ## this can be a feature
    items_vector['NWords'] = items_vector.item_name.str.split().str.len()
    items_vector['ItemWord0'] = items_vector.item_name.str.split().str.get(0)
    items_vector['ItemWord_1'] = items_vector.item_name.str.split().str.get(-1)

    def my_tokengen(data, columnx):
        unique_words = list()
        for string in  list(data[columnx].values):
            for word in string.split():
                unique_words.append(word)
        unique_words = set(unique_words)
        unique_words = list(unique_words)
        unique_words.sort()
        number = [idx[0] +1 for idx in enumerate(unique_words)]
        map_word = {x:y for x,y in zip(unique_words, number)}

        data[columnx] = data[columnx].map(map_word)
        return data

    items_vector = my_tokengen(items_vector, 'ItemWord0')
    items_vector = my_tokengen(items_vector, 'ItemWord_1')
    items_vector = items_vector.merge(data[['item_name','item_id']], on = 'item_name', how = 'left').drop(columns = 'item_name')

    return {'item_name_explo':items_vector}

def cleaning_shop_categs(shops, categories):
    shops[['shop_comp1','shop_comp2']] = shops.shop_name.str.split(' "',expand=True,)
    shops['shop_comp1'] = shops.shop_comp1.replace({r'\([^)]*\)' : ''}, regex=True)
    shops['shop_comp1'] = shops['shop_comp1'].str.split(' ').str[0]

    shops['shop_comp2'] = shops.shop_comp2.replace({r'\([^)]*\)' : ''}, regex=True)
    shops['shop_comp2'] = shops.shop_comp2.replace({'"' :''}, regex=True)

    categories[['categ_comp1','categ_comp2']] = categories.item_category_name.str.split(" - ",expand=True,)
    categories['categ_comp1'] = categories.categ_comp1.replace({r'\([^)]*\)' : ''}, regex=True)
    categories['categ_comp2'] = categories.categ_comp2.replace({r'\([^)]*\)' : ''}, regex=True)

    return shops, categories

def indexing_shop_categs(data, column):
    my_map = dict()
    for index, value in enumerate(data[column].unique()):
        my_map[value] = index
    data[f'map_{column}'] = data[column].map(my_map)
    return data

def merge_basic(train_data, test_data, test_how = 'inner'):
    train_merge = train_data.merge(items, on = 'item_id', how = 'left')\
        .merge(categories, on = 'item_category_id', how = 'left')\
        .merge(shops, on = 'shop_id', how = 'left')\
        .merge(test_data, on = ['shop_id','item_id'], how = test_how)\

    train_merge['SaleDate'] = pd.to_datetime(train_merge['date'], format = '%d.%m.%Y')

    return train_merge

def convert_bronze(data, train = False, test_order = 34):
    if train:
        data['date'] = pd.to_datetime(data['date'], format = '%d.%m.%Y')

    data['SaleDateMY'] = data['date'].dt.to_period('M').dt.to_timestamp()
    data['item_cnt_day'] = data['item_cnt_day'].clip(0,20)

    data = data.groupby(['SaleDateMY', 'date_block_num', 'shop_id', 'item_id'],
                                ).agg( Sale = ('item_cnt_day', 'sum'),
                                   item_price = ('item_price', 'mean'))
    data = data.reset_index().rename(columns = {'SaleDateMY':'Date'})

    data['min_date'] = data.groupby(['shop_id', 'item_id'])['Date'].transform('min')

    ### completing with 0 items with 0 in no dates

    map_aggg = data[['Date','item_id','shop_id','min_date','Sale']]\
        .pivot_table(index = ['item_id','shop_id','min_date'], columns = ['Date'], values = 'Sale', aggfunc = 'count').reset_index()
    map_aggg = map_aggg.melt(id_vars=['item_id','shop_id','min_date'], value_vars = map_aggg.columns[2:],  var_name='Date', value_name='Nothing')
    map_aggg = map_aggg[map_aggg.Date >= map_aggg.min_date]
    map_aggg = map_aggg[['item_id','shop_id','Date']]

    group_data = map_aggg.merge(data, on = ['item_id','shop_id','Date'], how = 'left').fillna(0)
    group_data['Sale'] = group_data['Sale'].clip(0,20)

    del map_aggg

    if train:
        ### get a map of the dates
        date_list =[group_data.Date.min()]
        date = group_data.Date.min()
        max_date = group_data.Date.max()
        while date <= max_date:
            date = date_list[-1] + relativedelta(months=1)
            date_list.append(date)
        order_list = range(1,len(date_list)+1)
        date_map = pd.DataFrame({'Date':date_list, 'Order':order_list})
        group_data = group_data.merge(date_map, on = 'Date', how = 'left')
    group_data = group_data.drop(columns = ['date_block_num', 'min_date'])
    return group_data

def merge_basic(train_data, items, items_feature ,categories, shops):
    train_merge = train_data.merge(items, on = 'item_id', how = 'left')
    train_merge = train_merge.merge(items_feature, on = 'item_id', how = 'left')
    train_merge = train_merge.merge(categories, on = 'item_category_id', how = 'left')
    train_merge = train_merge.merge(shops, on = 'shop_id', how = 'left')

    return train_merge

def supagg(data):
    data['lit'] = data.groupby(['item_id'])['shop_id'].transform('nunique')
    agge = data.groupby(['item_id','shop_id']).agg(lit = ('lit','max')).reset_index()
    return agge

def  reduce_sample(data, frac, single = False ):
    if single:
        data = data.groupby(['item_id','shop_id']).agg(lit = ('lit','max')).reset_index().sample(frac = frac, random_state = 123)
    else:
        data = data.sample(frac = frac, random_state = 123)
        data = data[['item_id','shop_id','lit']]
    return data

def get_val_window(data, date, items_to_drop_all):
    val_window_1 = data[data.Date == date ]
    already_found = val_window_1.shopitem.unique()

    val_window_2 = data[ (data.Date != date) & (data.shopitem.isin(items_to_drop_all)) ]
    val_window_2['Order'] = val_window_2.groupby(['shop_id','item_id']).cumcount() + 1
    val_window_2 = val_window_2[val_window_2.Order == 1]
    val_window_2['Date'] = date
    val_window_2 = val_window_2[~val_window_2.shopitem.isin(already_found)]
    val_window_2['Sale'] = 0
    print(len(val_window_1),len(val_window_2))
    val_window = pd.concat([val_window_1,val_window_2])
    return val_window

def inversed_scale(scaler, data, target_name, y_pred = np.array([])):
    data_new = data.copy()
    if y_pred.any():
        data_new[target_name] = y_pred

    unscaled_data = scaler.inverse_transform(data_new)
    unscaled_data = pd.DataFrame(unscaled_data, columns = data_new.columns)
    return unscaled_data

def consolidation_prediction(data, prediction ):
    pdf_plot = data.copy()
    #pdf_plot['PredictedVar'] = prediction
    pdf_plot['PredSale'] = prediction
    #pdf_plot['RealValueVar'] = pdf_plot.L0M_L1M
    #pdf_plot = pdf_plot.assign(PredSale = pdf_plot.PredictedVar + pdf_plot.SaleL1M)
    pdf_plot = pdf_plot[['Date','shop_id','item_id','Sale','PredSale']]
    return pdf_plot

def plot_prediction(dfplot):
    fig, axs = plt.subplots(nrows=1, ncols=1, figsize=(10,8))

    ax = sns.scatterplot(ax = axs, x="Sale", y="PredSale", data=dfplot)

    x0, x1 = axs.get_xlim()
    y0, y1 = axs.get_ylim()
    lims = [max(x0, y0), min(x1, y1)]
    axs.plot(lims, lims, '-r')

    axs.set(xlabel='Real Sale', ylabel='Predicted Sale', title='Scatter plot of variation predictions')

def preparing_to_predict(val_data, train_data):
    val_data_go = val_data.copy()
    val_data_go['date_block_num'] = np.nan
    val_data_go['shopitem'] = val_data_go['shop_id'].astype('str') + '-' + val_data_go['item_id'].astype('str')
    val_data_go = val_data_go[train_data.columns]
    items = val_data_go.shopitem.unique()
    result_data = pd.concat([train_data[train_data.shopitem.isin(items)],val_data_go])
    return result_data

def plot_metrics(data):
    resultdict = {'Date':list(), 'RMSE':list()}
    for datex in data.Date.unique():
        df = data[data.Date == datex]
        rmse = (mean_squared_error(df.Sale, df.PredSale))**(1/2)
        resultdict['Date'].append(datex)
        resultdict['RMSE'].append(rmse)
    result = pd.DataFrame(resultdict)
    return result
#########################################################
### The following functions follow a fixed sstructure ###
#########################################################

"""test_dates = [datetime.datetime(2014, 11, 1), datetime.datetime(2015, 4, 1), datetime.datetime(2015, 5, 1), datetime.datetime(2015, 6, 1), datetime.datetime(2015, 7, 1), datetime.datetime(2015, 8, 1),
datetime.datetime(2015, 9, 1), datetime.datetime(2015, 10, 1),]

to_drop_columns = ['Date']
ids_columns = ['item_category_id',
       'ItemIdPart1','ItemIdPart2', 'CategIdItem3A', 'CategIdItem3B'] #'item_id'
numericals = [ 'Quarter', 'OrderGot', 'countItemPossitives',
       'countItemZero', 'L1maxLev1Item', 'L2maxLev1Item', 'L3maxLev1Item',
       'L4maxLev1Item', 'L5maxLev1Item', 'lenstr', 'NWords',
       'Word0', 'Word_1', 'L1maxLev1Shop', 'meanLaggedVars',
       'item_id_mean_LastMonth', 'item_id_max_LastMonth',
       'item_id_mean_LastOrder', 'item_id_max_LastOrder', 'meanL1Price',
       'SpaceOrder'] + ids_columns

categoricals = ['SpaceOrderActivator', 'CategoryL1Item']
my_features = to_drop_columns + numericals + categoricals
my_target = 'Sale'

my_columns_to_drops = ['Quarter','CategoryL1Item_C', 'CategoryL1Item_A', 'CategoryL1Item_D',
       'SpaceOrderActivator_A', 'CategIdItem3B', 'ItemIdPart1',
       'CategIdItem3A']

categoricals_features = ['SpaceOrderActivator_A', 'SpaceOrderActivator_B',
                         'CategoryL1Item_A','CategoryL1Item_B','CategoryL1Item_C','CategoryL1Item_D']

if len(categoricals) != 0:
    final_features = categoricals_features +  numericals
else:
    final_features = numericals
final_features = [x for x in final_features if x not in my_columns_to_drops]

"""

def My_ML_prediction_on_test( data_dict , dates_vector, model, features_dict, zero_vector, frac = 0.80):

    numericals = features_dict['numericals']
    categoricals = features_dict['categoricals']
    my_columns_to_drops = features_dict['features_to_drop']
    my_target = features_dict['my_target']

    data_result = list()

    for datex in dates_vector:
        datex_str = datex.strftime('%Y-%m-%d')
        #### reading files
        train_selection = data_dict['Train Data'][datex_str]
        val_selection = data_dict['Validation Data'][datex_str]
        train_augmented = augmentation_reduction(train_selection, fracs = zero_vector)

        train_scaled, my_scaler = scaler(train_augmented, numericals, my_target, scaler=None, drop_columns = my_columns_to_drops)
        #train_scaled = train_augmented[ numericals + [my_target] ]
        if len(categoricals) != 0:
            train_dummies = pd.get_dummies(train_augmented[categoricals])
            train_scaled = pd.concat([train_dummies,train_scaled],axis = 1)

        if len(categoricals) != 0:
            final_features = list(train_dummies.columns) +  numericals
        else:
            final_features = numericals
        final_features = [x for x in final_features if x not in my_columns_to_drops]

        train_scaled_sampled = train_scaled.sample(frac = frac, random_state = 12489)

        ### ML train
        X_train = train_scaled_sampled[final_features]
        Y_train = train_scaled_sampled[my_target]
        model.fit(X_train, Y_train)

        ### Test data prepa
        val_scaled = scaler(val_selection, numericals, my_target, scaler=my_scaler,drop_columns = my_columns_to_drops )

        if len(categoricals) != 0:
            val_dummies = pd.get_dummies(val_selection[categoricals])
            val_scaled_full = pd.concat([val_dummies,val_scaled],axis = 1)
        else:
            val_scaled_full = val_scaled

        X_val = val_scaled_full[final_features]

        ## Prediction
        Y_pred = model.predict(X_val)

        ## Saving Result
        predicted_val = inversed_scale(scaler = my_scaler, data = val_scaled, target_name = my_target, y_pred = Y_pred)
        my_lm_plot = consolidation_prediction(data = val_selection, prediction = predicted_val.Sale.values)
        data_result.append(my_lm_plot)
        #print(f'the prediction over the {datex} data is done')

    return pd.concat(data_result)

def scaler(dataset, features, target, scaler=None, drop_columns = []):
    if scaler:
        features = [x for x in features if x not in drop_columns]
        df = dataset[features + [target]]
        df_scaled = scaler.transform(df)
        dataset_scaled = pd.DataFrame(df_scaled, columns = df.columns, index = df.index)
        return dataset_scaled

    else:
        features = [x for x in features if x not in drop_columns]
        df  = dataset[features + [target]]
        scaler = MinMaxScaler()
        scaler.fit(df)

        dataset_scaled = scaler.transform(df)
        dataset_scaled = pd.DataFrame(dataset_scaled, columns = df.columns, index = df.index)
        return dataset_scaled, scaler

def consolidated_metrics_MSE(data):
    labels = list()
    RMSEs = list()
    for i in range(len(data['machine label'])):
        label = data['machine label'][i]
        result_detail = data['machine result'][i]
        pred = result_detail['Sale']
        real = result_detail['PredSale']
        rmse = mean_squared_error(real,pred)**(1/2)
        labels.append(label)
        RMSEs.append(rmse)

    return pd.DataFrame({'machine':labels,'RMSE': RMSEs}).sort_values('RMSE')

def consolidated_plot_metrics(data):
    list_dfplot = list()
    for i in range(len(data['machine label'])):
        label = data['machine label'][i]
        result_detail = data['machine result'][i]
        df_plot = plot_metrics(result_detail)
        df_plot['machine'] = label
        list_dfplot.append(df_plot)

    return pd.concat(list_dfplot)

def get_splited_data(dates_vector):
    train_data = dict()
    validation_data = dict()

    for datex in dates_vector:
        datex_str = datex.strftime('%Y-%m-%d')
        train_selection = pd.read_csv(f'generated_datasets/data_{datex_str}/train_selection.csv')
        val_selection = pd.read_csv(f'generated_datasets/data_{datex_str}/val_selection.csv')

        train_data[datex_str] = train_selection
        validation_data[datex_str] = val_selection
        print(datex_str)
    return { 'Train Data' : train_data,
            'Validation Data': validation_data}


from pytest import mark
import os

@mark.smoke
@mark.folder_structure
@mark.data_folder_structure
class DataFolderTests:
    @staticmethod
    def test_data_folder_structure(app_constants, get_test_data_folder):
        """
        Check the structure of the Data folder and its inner folders.
        """
        # count folders/files in Data folder
        number_of_files = len(os.listdir(app_constants.PROJECT + get_test_data_folder["folderPath"]))

        # expected folders/files count in Data folder
        expected_file_count = len(get_test_data_folder["FolderStructure"])

        # compare number of files with expected number of files
        assert number_of_files == expected_file_count

    @staticmethod
    def test_data_folder_content(app_constants, get_test_data_folder):
        """
        Check the content of the Data folder and its inner folders.
        """
        # get the folder content
        files = os.listdir(app_constants.PROJECT + get_test_data_folder["folderPath"])

        # compare folder content with the expected files
        assert all(file in files for file in get_test_data_folder["FolderStructure"])


from django.urls import path
from . import views

app_name = 'news'
urlpatterns = [
    path('', views.post_list_view, name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',
         views.post_detail_view, name='post_detail'),
    path('tag/<slug:tag_slug>/', views.post_list_view, name='post_list_by_tag'),
    # path('news/search/', views.post_search, name='post_search'),
]


import cv2
import numpy as np

cv2.namedWindow("car_affine", cv2.WINDOW_NORMAL)
cv2.resizeWindow("car_affine", (1125, 633))

img = cv2.imread("img/car.jpg")
move = cv2.warpAffine(img, np.float32([[1, 0, 10], [0, 1, 20]]), (1125, 633))  # 平移
M_rotate = cv2.getRotationMatrix2D((1125, 633), 10, 1)
rotate = cv2.warpAffine(move, M_rotate, (1125, 633))  # 旋转
M_incline = cv2.getAffineTransform(src=np.float32([[0, 0], [1125, 0], [0, 633]]), dst=np.float32([[10, 0], [1135, 0], [0, 633]]))  # 倾斜
affine_all = cv2.warpAffine(rotate, M_incline, (1125, 633))

while True:
    cv2.imshow("car_affine", affine_all)
    cv2.imwrite("img/car_affine.jpg", affine_all)
    key = cv2.waitKey(0)
    if key == ord("q"):
        break


class Solution(object):
    def canFinish(self, numCourses: int, prerequisites) -> bool:
        """
        :type numCourses: int 课程门数
        :type prerequisites: List[List[int]] 课程与课程之间的关系
        :rtype: bool
        """
        # 课程的长度
        if len(prerequisites) == 0: return True
        # 深度优先遍历，判断结点是否访问过
        # 这里要设置 3 个状态
        # 0 就对应 False ，表示结点没有访问过
        # 1 就对应 True ，表示结点已经访问过，在深度优先遍历结束以后才置为 1
        # 2 表示当前正在遍历的结点，如果在深度优先遍历的过程中，
        # 有遇到状态为 2 的结点，就表示这个图中存在环
        visited = [0 for _ in range(numCourses)]

        inverse_adj = [set() for _ in range(numCourses)]
        for first, second in prerequisites:
            inverse_adj[second].add(first)

        for i in range(numCourses):
            # 在遍历的过程中，如果发现有环，就退出
            if self.__dfs(i, inverse_adj, visited):
                return False
        return True

    def __dfs(self, vertex, inverse_adj, visited):
        # 返回是否有环 是：True
        # 2 表示这个结点正在访问
        if visited[vertex] == 2:
            # 表示遇到环
            return True
        if visited[vertex] == 1:
            return False

        visited[vertex] = 2
        for precursor in inverse_adj[vertex]:
            # 如果有环，就返回 True 表示有环
            if self.__dfs(precursor, inverse_adj, visited):
                return True

        # 1 表示访问结束
        # 先把 vertex 这个结点的所有前驱结点都输出之后，再输出自己
        visited[vertex] = 1
        return False

有向图是否有环-dfs.py

有向图是否有环-dfs.py


from selenium import webdriver
from selenium.webdriver.support.select import Select
import pandas as pd
import numpy as np
import os
from selenium.webdriver.common.action_chains import ActionChains

DRIVER_PATH =r'C:\\Users\\geeth\\Downloads\\chromedriver_win32\\chromedriver.exe'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.get('https://www.espn.in/nhl/team/schedule/_/name/ana')

element_year = driver.find_element_by_xpath('/html/body/div[1]/div/div/div/div[4]/div[2]/div[5]/div/div[1]/section/div/section/div[2]/div[1]/select[1]')
element_calendar = driver.find_element_by_xpath('/html/body/div[1]/div/div/div/div[4]/div[2]/div[5]/div/div[1]/section/div/section/div[2]/button')
element_teams = driver.find_element_by_xpath('/html/body/div[1]/div/div/div/div[4]/div[2]/div[5]/div/div[1]/section/div/section/div[1]/div/select[1]')

sel_year=Select(element_year)
#sel_calendar=Select(element_calendar)
sel_teams=Select(element_teams)

options_year=sel_year.options
options_teams=sel_teams.options

# for index3 in range(0,)
# d= driver.find_element_by_xpath("/html/body/div[1]/div/div/div/div[4]/div[2]/div[5]/div/div[1]/section/div/section/div[2]/button")
# d.click()

for index1 in range(0,len(options_teams)):
  team=options_teams[index1].text

  path='C:/Users/geeth/Desktop/new/'
  path = os.path.join(path,team)
  os.mkdir(path)

  for index2 in range(0,len(options_year)):

    year=options_year[index2].text
    # path1 = os.path.join(path,year)
    # os.mkdir(path1)

    all_tables=pd.read_html(driver.page_source)
    df=all_tables[0]
    df.to_csv('C:/Users/geeth/Desktop/new/'+team+'/'+year+'.csv')


#inheritance
#can be called parent-child, superclass-subclass
class A: #super class
    def fun1(self):
        print('fun1 started.....')

    def fun2(self):
        print('fun2 started....')

class B(A): #sub class
    def fun3(self):
        print('fun3 started....')
    def fun4(self):
        print('fun4 started....')

class C(B):
    def fun5(self):
        print('fun5 started.....')

a1=A()
a1.fun1()

b1=B()
b1.fun3()
b1.fun2()#can use method  of A

c1=C()
c1.fun1()#can use method of A and B

#inheritance constructor
class X:
    def __init__(self):
        print("Init of X")

class Y(X):
    def __init__(self):
        super().__init__() #super is reffering to superclass
        print("Init of Y")

y=Y() #if it has no init, it will call init of parent class X

#polymorphism: objects behave differently depending on the situation
# 1)Duck Typing:
class Add:
    def execute(self):
        print('Adding, A+B')

class Subtract:
    def execute(self):
        print('Subtracting, A-B')

class Laptop:
    def operate(self,operation):
        operation.execute()

operation1=Add()
operation2=Subtract()

lap1=Laptop()
lap1.operate(operation1)
lap1.operate(operation2) #for different input, the code function will perform different functions

# 2)Operator Overloading:
n1,n2=5,6
print(n1+n2)
print(int.__add__(n1,n2)) #for '+' __add__ is called, for '*' __mul__ is called
print(n1) #for 'print' it is actually print(n1.__str__())

class Student:
    def __init__(self,m1,m2):
        self.m1=m1
        self.m2=m2

    def __add__(self,other): #overload normal '+' with own function
        m1=self.m1+other.m1 #self=s1, other=s2; m1=s1.m1+s2.m1
        m2=self.m2+other.m2
        s3=Student(m1,m2) #create new object s3
        return s3

    def __gt__(self,other): #overload '>' with own function
        r1=self.m1+self.m2
        r2=other.m1+other.m2
        if r1>r2:
            return True
        else:
            return False

    def __str__(self): #overload print with own method
        return '{} {}' .format(self.m1, self.m2)

s1=Student(55,66)
s2=Student(10,30)

total=s1+s2 # '+' changed Student.__add__(s1,s2)
print(total.m1)

if s1>s2: # '>' changed Student.__gt__(s1,s2)
    print("s1 wins")
else:
    print("s2 wins")

print(s1) # 'print' changed Student.__str__(s1)


from tkinter import *
from downloader import *

SAVE_LOCATION = r"C:\Users\REYNA ROYCE\Desktop"
BG_COLOR = '#181818'
FG_COLOR = '#ffffff'
BT_BG = '#373737'
BT_FG = '#828282'

class Setup:
    def sent_file(self):
        try:
            file_url = fr'{self.file_entry.get()}'
            file_path = self.path_entry.get()
            obj = Download(file_url, file_path)
            if len(self.path_entry.get()) != 0:
                obj.download_file()
                self.message.config(text=f"'{obj.video_title}' downloaded.")
            else:
                self.message.config(text=f"Enter the location to save.")
        except:
            self.message.config(text="Oops! Something went wrong.Try again")

    def clear_content(self):
        self.file_entry.delete(0, END)
        self.path_entry.delete(0, END)
        self.message.config(text="")

    def __init__(self):
        self.window = Tk()
        self.window.title("YouTube Video Downloader")
        self.window.geometry('550x550')
        self.window.config(padx=60, pady=10, bg=BG_COLOR)

        self.image_canvas = Canvas(width=350, height=300, bg=BG_COLOR, highlightthickness=0)
        img = PhotoImage(file='image/yt_logo.png')
        self.image_canvas.create_image(150, 150, image=img)
        self.image_canvas.grid(row=1, column=2, columnspan=2)

        self.file_label = Label(text="Video URL", font=('Open Sans Condensed', 10, 'bold'), bg=BG_COLOR, fg=FG_COLOR)
        self.file_label.grid(row=2, column=1)

        self.file_entry = Entry(width=45, bg='#202020', fg='white')
        self.file_entry.grid(row=2, column=2, padx=30)

        self.path_label = Label(text="Location", font=('Open Sans Condensed', 10, 'bold'), bg=BG_COLOR, fg=FG_COLOR)
        self.path_label.grid(row=3, column=1, pady=20)

        self.path_entry = Entry(width=45, bg='#202020', fg='white')
        self.path_entry.insert(0, SAVE_LOCATION)
        self.path_entry.grid(row=3, column=2, padx=30, pady=20)

        self.download_bt = Button(text="Download", font=('Open Sans Condensed', 10, 'bold'), bg=BT_BG, fg=BT_FG
                                  , command=self.sent_file)
        self.download_bt.grid(row=5, column=1, columnspan=2, pady=5)

        self.clear_bt = Button(text="Clear", font=('Open Sans Condensed', 10, 'bold'), width=8, bg=BT_BG, fg=BT_FG
                               , command=self.clear_content)
        self.clear_bt.grid(row=6, column=1, columnspan=2, pady=15)

        self.message = Label(text="", font=('Open Sans Condensed', 10, 'bold'),
                             bg=BG_COLOR, fg=FG_COLOR, wraplength=400)
        self.message.grid(row=7, column=1, columnspan=2)

        self.window.mainloop()


"""
Задание 6. В программе генерируется случайное целое число от 0 до 100.
Пользователь должен его отгадать не более чем за 10 попыток. После каждой
неудачной попытки должно сообщаться больше или меньше введенное пользователем
число, чем то, что загадано. Если за 10 попыток число не отгадано,
то вывести загаданное число.
Решите через рекурсию. В задании нельзя применять циклы.
"""

number = 67

print('Дружище! я загадал число, попробуй угадать!')

# while True:
#     # решение при помощи цикла
#     count = 10
#     if count > 0:
#         user_number = int(input('Введите число: '))
#         if number == user_number:
#             print(f'Ты угадал! Это число {number}')
#         elif user_number > number:
#             print(
#                 f'Твое число {user_number} больше загаданного, количество '
#                 f'попыток {count - 1}')
#         else:
#             print(
#                 f'Твое число {user_number} меньше загаданного, количество '
#                 f'попыток {count - 1}')
#         count -= 1
#     else:
#         print('Ты проиграл!')
#         break

# решение рекурсией:
def func(number, count=10):
    if count < 0:
        print(f"Число не отгадано. Загаданное число: {number}")
        return number
    user_number = int(input('Введите число: '))
    if user_number == number:
        print(f'Ты угадал! Это число {number}')
        return user_number
    elif user_number > number:
        print(
            f'Твое число {user_number} больше загаданного, количество '
            f'попыток {count - 1}')
        return func(number, count - 1)
    else:
        print(
            f'Твое число {user_number} меньше загаданного, количество '
            f'попыток {count - 1}')
        return func(number, count - 1)

func(number)


import webfont_exporter

def get_output(dict_icons, file_path, font_family):
    if file_path.find("style.css") > 0:
        output_path = file_path[0:len(file_path) - 9]
    else:
        output_path = file_path

    if output_path[len(output_path) - 1] != "\\" or output_path[len(output_path) - 1] != "/":
        if output_path.find("/") > 0:
            output_path += "/"
        else:
            output_path += "\\"

    output_file_android = open(output_path + "android_layout.xml", "w", encoding="UTF-8")

    layout_open = "<ScrollView\nandroid:layout_width=\"match_parent\"\nandroid:layout_height=\"match_parent\"\nandroid:orientation=\"vertical\"\nxmlns:android=\"http://schemas.android.com/apk/res/android\">\n<LinearLayout\nandroid:layout_width=\"match_parent\"\nandroid:layout_height=\"wrap_content\"\nandroid:orientation=\"vertical\" >\n "
    layout_close = "</LinearLayout>\n</ScrollView>"
    output = ""
    temp = ""
    count = 0
    for i in dict_icons.keys():
        count += 1
        temp += "<TextView\nandroid:id = \"@+id/" + i + "\"\nandroid:layout_width = \"20dp\"\nandroid:layout_height = " \
                                                        "\"20dp\"\nandroid:gravity = \"center_vertical\"\nandroid:text = \"@string/" + i + "\"\nandroid:fontFamily =" \
                                                                                " \"" + font_family + "\" />\n"
        if count % 20 == 0 or count == len(dict_icons.keys()):
            output += "<LinearLayout\nandroid:layout_width=\"match_parent\"\nandroid:layout_height=\"wrap_content\"\nandroid:orientation=\"horizontal\" >\n " + temp + "</LinearLayout>\n"
            temp = ""
    output_file_android.write(layout_open + output + layout_close)

    output_file_android.close()

def get_layout_and_fonts():
    inp = str(input("Please enter a filepath of style.css of webfont(ex: C:\\Users\\can\\Desktop): "))
    path = inp
    inp = str(input("Please enter webfont fontFamily (ttf) name (ex: @font/groupama_icons): "))
    font_family = inp
    dict_icon = webfont_exporter.get_icon_names(path)
    webfont_exporter.get_output(dict_icon, path)
    get_output(dict_icon, path, font_family)
    return path


from direct.distributed.DistributedObject import DistributedObject
from direct.directnotify.DirectNotifyGlobal import directNotify

class TTCodeRedemptionMgr(DistributedObject):
    neverDisable = 1
    notify = directNotify.newCategory('TTCodeRedemptionMgr')

    def __init__(self, cr):
        DistributedObject.__init__(self, cr)

    def announceGenerate(self):
        DistributedObject.announceGenerate(self)
        base.codeRedemptionMgr = self
        self._contextGen = SerialMaskedGen(4294967295)
        self._context2callback = {}

    def delete(self):
        if hasattr(base, 'codeRedemptionMgr'):
            if base.codeRedemptionMgr is self:
                del base.codeRedemptionMgr
        self._context2callback = None
        self._contextGen = None
        DistributedObject.delete(self)
        return

    def redeemCode(self, code, callback):
        context = next(self._contextGen)
        self._context2callback[context] = callback
        self.notify.debug('redeemCode(%s, %s)' % (context, code))
        self.sendUpdate('redeemCode', [context, code])

    def redeemCodeResult(self, context, result, awardMgrResult):
        self.notify.debug('redeemCodeResult(%s, %s, %s)' % (context, result, awardMgrResult))
        callback = self._context2callback.pop(context)
        callback(result, awardMgrResult)


# Type or paste your code in this area
# Type or paste your code in this area
n=int(input())
# O을 n*n만큼 그리기
graph=[["O"]*n for _ in range(n)]
m=int(input())
# X 표 그리기
for i in range(m):
    a,b=map(int,input().split())
    graph[a][b]="X"

# 지도 리스트를 string으로 변경해주는 것
for i in graph:
    a=""
    for j in i:
        a+=j
    print(a)

# 초기 좌표 초기화
x,y=0,0
while True:
    if(y+1==n):
        if(x+1==n):
            print("finish")
            break
        # 아래로 이동
        elif(graph[x+1][y]=="O"):
            print("Down")
            x,y=x+1,y
        elif(graph[x+1][y]=="X"):
            print("error")
            break
    elif(x+1==n):
        if(y+1==n):
            print("finish")
            break
        # 옆으로 이동
        elif(graph[x][y+1]=="O"):
            print("Right")
            x,y=x,y+1
        elif(graph[x][y+1]=="X"):
            print("error")
            break
    elif x>=0 and x<n and y>=0 and y<n:
        # 오른쪽으로 이동
        if (graph[x][y+1]=="O"):
            print("Right")
            x,y=x,y+1
        # 오른쪽이 막히면?
        elif (graph[x][y+1]=="X"):
            # 아래로 이동
            if(graph[x+1][y]=="O"):
                print("Down")
                x,y=x+1,y
            # 아래도 막혀있으면
            elif (graph[x+1][y]=="X"):
                print("error")
                break


import time
import os
import re
import pyautogui
import telegram_send
import pyperclip

from platform import platform
from modules.constants import p, c, locate_and_click, Entry, open_network, \
    ImageNotFoundError, enter_maintenance
from modules.filereader import read_excel

if "Windows" in platform():
    from pywinauto.keyboard import send_keys
else:
    def send_keys(t): return pyautogui.write(t, interval=0.05)

# So here's how the bot is going to need to work
# Step 1: Read the Excel sheet
# Do this by opening every page in the spreadsheet using pandas
# and then read row by row to assemble a list of entries

xls = os.path.exists(c("stock.xls"))
xlsx = os.path.exists(c("stock.xlsx"))

if not xls and not xlsx:
    pyautogui.alert(
        "Please save the stock spreadsheet in the folder bot_data "
        "with the name stock.xls or stock.xlsx, and try again."
    )
    exit()

name = "stock.xls" if xls else "stock.xlsx"
try:
    entries = read_excel(c(name))
except ValueError as e:
    pyautogui.alert(str(e))
    exit()

if not entries:
    pyautogui.alert("No entries found in the spreadsheet.")
    exit()

print(entries)

# Step 2: Read the Word document containing the sign data to extract notes.
# Do this by opening the Word document and then reading the text
# using textract, then read the notes by splitting on double newlines
# and add each note to the entry with the corresponding index number
# Also, check that the prices match up

def locate_price(sentence: str) -> str:
    for word in sentence.split():
        if "$" in word:
            return word[word.index("$") + 1:]

    return ""

if not os.path.exists(c("signs.txt")):
    pyautogui.alert(
        "Please copy the signs information "
        "and save it in the folder bot_data/ as signs.txt."
    )
    exit()

try:
    with open(c("signs.txt"), 'r') as f:
        signs = f.read().strip().split("\n\n")
except UnicodeDecodeError as e:
    if "codec can't decode byte 0x93" in str(e):
        with open(c("signs.txt"), 'r', encoding="latin-1") as f:
            signs = f.read().strip()

        signs = signs.replace("0x93", '"').replace('?', '" ')
        signs = signs.split("\n\n")
    else:
        pyautogui.alert(
            "The signs file looks weird... I can't read it! :("
        )
        raise e

signs_map = {}
for s in signs:
    lines = s.splitlines()
    i = re.search(r"\d+", lines[0]).group(0)
    t = '\n'.join(lines[1:])
    signs_map[i] = t.split("   ")[0].strip()

requested = set()
for entry in entries:
    if entry.index in signs_map:
        # Check that the price is contained in the text
        if entry.price not in signs_map[entry.index].replace(',', ''):
            print(f"Price mismatch for {entry.index}")
            guess = locate_price(signs_map[entry.index])
            if guess != "":
                res = pyautogui.confirm(
                    f"Price mismatch for {entry.index} with "
                    f'sign text "{signs_map[entry.index]}". '
                    f"Is the price {guess}? "
                    "Click OK to accept, "
                    "or Cancel to keep the existing price. "
                    "If you would like to enter in a new price, "
                    'click "New Price".',
                    buttons=["OK", "Cancel", "New Price"],
                )

                if res == "New Price":
                    new_price = pyautogui.prompt("Please enter the new price:")
                    if new_price is None:
                        pass

                    entry.price = new_price.replace(',', '')

                elif res == "OK":
                    entry.price = guess.replace(',', '')

                else:
                    exit()

            else:
                # This probably shouldn't be happening, but we can check it
                res = pyautogui.confirm(
                    f"The sign for {entry.index} does not contain a price. "
                    "Please check the sign and enter in the price manually."
                    "Click OK to continue, or Cancel to stop the program.",
                )

                if res == "Cancel":
                    exit()

        entry.notes = signs_map[entry.index]

    elif entry.index not in requested:
        print(f"No sign data for {entry.index}")
        res = pyautogui.confirm(
            text=f"No sign data for {entry.index}. Continue?",
            title="CougarBot"
        )

        if res == "Cancel":
            exit()

        requested.add(entry.index)
        continue

print(entries[0])

# Step 3: Loop through the entries and insert the data into the system,
# checking during insertion that the index number does not already exist
# either by looking for greyed out text or checking the find menu

def enter_stock(entry: Entry, first=False) -> bool:
    """
    Enter the data from an entry into the Cougar Mountain system.

    Returns True if the entry was successfully entered, False otherwise.
    """

    # Enter the stock number
    if first:
        for _ in range(5):
            try:
                locate_and_click(p("number.png"))
                break
            except pyautogui.ImageNotFoundException as e:
                time.sleep(0.5)

        else:
            raise e

    time.sleep(0.5)
    send_keys(entry.code + "{TAB}", pause=0.1)
    tabs = 5
    on_hand = pyautogui.locateOnScreen(p("on_hand.png"))
    if on_hand is None:
        first = False
        tabs -= 1

    # Enter the location and description
    if first:
        tabs -= 2
        send_keys(entry.location + "{TAB 2}I1{TAB %d}" % tabs)
    else:
        send_keys(entry.location + "{TAB %d}" % tabs)

    # Now try to find the notes box. If it is not on screen,
    # then there must be a duplicate
    time.sleep(1)
    dup = pyautogui.locateOnScreen(p("notes.png"))
    if dup is None:
        # Duplicate detected.
        locate_and_click(p("cancel.png"))
        enter_maintenance()
        return False

    pyperclip.copy(entry.description)
    send_keys("^v")
    consign_grey = pyautogui.locateOnScreen(p("consignment_grey.png"))
    if entry.cnor.strip() not in ["nan", ''] and consign_grey is not None:
        send_keys("{TAB}" + entry.cnor, pause=0.1)
        try:
            locate_and_click(p("serialized.png"))
        except ImageNotFoundError:
            # Looks like this consignment item is already in the system
            locate_and_click(p("cancel.png"))
            locate_and_click(p("no.png"))
            locate_and_click(p("file.png"))
            locate_and_click(p("main_menu.png"))
            enter_maintenance()
            return False

        locate_and_click(p("consignment.png"), pos='r')
        send_keys("{TAB 2}" + entry.cost)
    elif entry.cnor in ["nan", '']:
        send_keys("{TAB}{BACK}")

    locate_and_click(p("breaklist.png"), pos="br", stretch=3)
    send_keys(entry.price + "{TAB}")

    # lc = pyautogui.locateOnScreen(p("last_cost.png"))
    # pyautogui.click(lc.left + lc.width + 2, lc.top + 0.5 * lc.height)
    locate_and_click(p("last_cost.png"), pos='r', stretch=2)
    send_keys(entry.cost + "{TAB}")

    locate_and_click(p("sales.png"))
    locate_and_click(p("storing.png"), pos='r', stretch=2)
    send_keys(entry.price + "{TAB}")

    locate_and_click(p("notes.png"))
    pyperclip.copy(entry.notes)
    send_keys("^v")

    locate_and_click(p("save.png"))
    time.sleep(2)

    with open("finished.txt", 'a') as f:
        f.write(entry.code + "\n")

    return True

if not os.path.exists("finished.txt"):
    with open("finished.txt", "w") as f:
        f.write("")

try:
    open_network()
    enter_maintenance()
    with open("finished.txt", "r") as f:
        finished = f.readlines()

    already_entered = []
    first = True
    for i, entry in enumerate(entries):
        if entry.code not in finished:
            if not enter_stock(entry, first=first):
                already_entered.append(entry)
                first = True
            else:
                first = False

except ImageNotFoundError as e:
    pyautogui.alert(f"Could not find {e}!")
    exit()

# Step 4: Send a Telegram message to Mom when the program is done
codes = '\n'.join([e.code for e in already_entered])
message = (
    f"Finished entering {len(entries) - len(already_entered)} entries"
    f" into Cougar Mountain. {len(already_entered)} duplicates found:"
    f"\n{codes}"
)
telegram_send.send(messages=[message])

# Step 5: Profit


import re
import requests
from bs4 import BeautifulSoup
import dateparser
import pandas as pd
import vaxutils

def main():

    url = "https://www.folkhalsomyndigheten.se/smittskydd-beredskap/utbrott/aktuella-utbrott/covid-19/vaccination-mot-covid-19/statistik-over-vaccinerade-mot-covid-19/"
    soup = BeautifulSoup(requests.get(url).content, "html.parser")

    table = soup.find(id="content-primary").find("table")
    df = pd.read_html(str(table))[0]
    assert len(df) == 1

    total_vaccinations = df["Alla vacciner"].values[0]
    total_vaccinations = vaxutils.clean_count(total_vaccinations)

    date = soup.find(id="content-primary").find("h2").text
    date = re.search(r"\d+\s\w+\s+202\d", date).group(0)
    date = str(dateparser.parse(date, languages=["sv"]).date())

    vaxutils.increment(
        location="Sweden",
        total_vaccinations=total_vaccinations,
        date=date,
        source_url=url,
        vaccine="Pfizer/BioNTech"
    )

if __name__ == '__main__':
    main()


from nextcord.ext import commands
from .role_view import RoleView
from config import IT_ROLE_ID

class Buttons(commands.Cog, name= "Button Roles"):
    def __init__ (self, bot: commands.Bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        self.bot.add_view(RoleView())
        print ("Buttons roles are ready")

    @commands.command()
    @commands.has_role(IT_ROLE_ID)
    async def buttons(self, ctx: commands.Context):
        await ctx.send("Click a button", view=RoleView())

def setup(bot: commands.Bot):
    bot.add_cog(Buttons(bot))


#!/usr/bin/env python

#=======================================================================================================================
# PyClone
# Author : Andrew Roth
#=======================================================================================================================
import pyclone.run as run

import argparse

def main():
    parser = argparse.ArgumentParser(prog='PyClone')

    parser.add_argument('--version', action='version', version='PyClone-0.13.1')

    subparsers = parser.add_subparsers()

#----------------------------------------------------------------------------------------------------------------------
    setup_analysis_parser = subparsers.add_parser(
        'setup_analysis',
        help='''Setup a config file and mutations files for a PyClone analysis.'''
    )

    _setup_setup_analysis_parser(setup_analysis_parser)

#----------------------------------------------------------------------------------------------------------------------
    run_analysis_parser = subparsers.add_parser(
        'run_analysis',
        help='''Run an MCMC sampler to sample from the posterior of the PyClone model.'''
    )

    _setup_run_analysis_parser(run_analysis_parser)

#----------------------------------------------------------------------------------------------------------------------
    analysis_pipeline_parser = subparsers.add_parser(
        'run_analysis_pipeline',
        help='''Run a full PyClone analysis.'''
    )

    _setup_analysis_pipeline_parser(analysis_pipeline_parser)

#----------------------------------------------------------------------------------------------------------------------
    build_prior_parser = subparsers.add_parser(
        'build_mutations_file',
        help='''Build a YAML format file with mutation data and states prior to be used for PyClone analysis.'''
    )

    _setup_build_prior_parser(build_prior_parser)

#----------------------------------------------------------------------------------------------------------------------
    plot_clusters_parser = subparsers.add_parser(
        'plot_clusters',
        help='''Plot features of the clusters.'''
    )

    _setup_cluster_plot_parser(plot_clusters_parser)

#----------------------------------------------------------------------------------------------------------------------
    plot_loci_parser = subparsers.add_parser(
        'plot_loci',
        help='''Plot features of the loci.'''
    )

    _setup_loci_plot_parser(plot_loci_parser)

#----------------------------------------------------------------------------------------------------------------------
    build_table_parser = subparsers.add_parser(
        'build_table',
        help='''Build results table which contains cluster ids and (mean) cellular prevalence estimates.''')

    _setup_build_table_parser(build_table_parser)

#----------------------------------------------------------------------------------------------------------------------
    args = parser.parse_args()

    args.func(args)

def _setup_run_analysis_parser(parser):

    _add_config_file_args(parser)

    _add_seed_args(parser)

    parser.set_defaults(func=run.run_analysis)

def _setup_setup_analysis_parser(parser):

    parser.add_argument(
        '--in_files',
        nargs='+',
        required=True,
        help='''Space delimited list of tsv format files with copy number and allele count information. See
        build_mutations_file command for information.'''
    )

    parser.add_argument(
        '--working_dir',
        required=True,
        help='''Path of directory where analysis pipeline files will be placed.'''
    )

    parser.add_argument(
        '--tumour_contents',
        nargs='+',
        type=float,
        default=None,
        help='''Space delimited list of tumour contents. Should match the order of --in_files. If not given tumour
        content is assumed to 1.0 in all samples.'''
    )

    parser.add_argument(
        '--samples',
        nargs='+', default=None, help='''Space delimited list of sample names. Should be in the same order as
        --in_files. If not set sample name will be inferred from file names and ordering in plots will be arbitrary.''')

    parser.add_argument(
        '--config_extras_file',
        required=False,
        help='''Path to configuration file with extra parameters used for analysis.'''
    )

    parser.add_argument(
        '--density',
        choices=['pyclone_binomial', 'pyclone_beta_binomial'],
        default='pyclone_beta_binomial',
        help='''Emission density for the model. Default is pyclone_beta_binomial.'''
    )

    _add_init_method_args(parser)

    parser.add_argument(
        '--num_iters',
        default=10000,
        type=int,
        help='''Number of iterations of the MCMC sampler to perform. Default is 10,000.'''
    )

    _add_prior_args(parser)

    parser.set_defaults(func=run.setup_analysis)

def _setup_analysis_pipeline_parser(parser):

    _setup_setup_analysis_parser(parser)

    _add_post_process_args(parser)

    _add_seed_args(parser)

    parser.add_argument(
        '--plot_file_format',
        default='pdf',
        choices=['pdf', 'svg'],
        help='''File format for plots. Default is pdf.'''
    )

    _add_max_clusters_args(parser)

    _add_mesh_size_args(parser)

    _add_min_cluster_size_args(parser)

    parser.set_defaults(func=run.run_analysis_pipeline)

def _setup_build_prior_parser(parser):

    parser.add_argument(
        '--in_file',
        required=True,
        help='''Path to tab separated input file. The input file should have header and the following columns:
        mutation_id, ref_counts, var_counts, normal_cn, minor_cn, major_cn. Any additional columns will be ignored.
        See examples for format.'''
    )

    parser.add_argument(
        '--out_file',
        required=True,
        help='''Path where YAML formatted PyClone input file will be written.'''
    )

    _add_prior_args(parser)

    parser.set_defaults(func=run.build_mutations_file)

def _setup_build_table_parser(parser):

    _add_config_file_args(parser)

    parser.add_argument(
        '--out_file',
        required=True,
        help='''Path where table will be written in tsv format.'''
    )

    parser.add_argument(
        '--table_type',
        choices=['cluster', 'loci', 'old_style'],
        required=True,
        help='''Build a table of results. Choices are: `cluster` for cluster specific information; `loci` for loci
        specific information; `old_style` matches the 0.12.x PyClone output.'''
    )

    _add_max_clusters_args(parser)

    _add_mesh_size_args(parser)

    _add_post_process_args(parser)

    parser.set_defaults(func=run.build_table)

def _setup_cluster_plot_parser(parser):

    _add_config_file_args(parser)

    _add_plot_out_file_args(parser)

    parser.add_argument(
        '--plot_type',
        choices=['density', 'parallel_coordinates', 'scatter'],
        default='density',
        required=True,
        help='''Determines which style of plot will be done.'''
    )

    _add_post_process_args(parser)

    _add_max_clusters_args(parser)

    _add_mesh_size_args(parser)

    _add_min_cluster_size_args(parser)

    parser.add_argument(
        '--samples',
        default=None,
        nargs='+',
        help='''Samples to plot and order to plot them in.'''
    )

    parser.set_defaults(func=run.cluster_plot)

def _setup_loci_plot_parser(parser):

    _add_config_file_args(parser)

    _add_plot_out_file_args(parser)

    parser.add_argument(
        '--plot_type',
        choices=[
            'density',
            'parallel_coordinates',
            'scatter',
            'similarity_matrix',
            'vaf_parallel_coordinates',
            'vaf_scatter'
        ],
        default='density',
        required=True,
        help='''Determines which style of plot will be done.'''
    )

    _add_post_process_args(parser)

    _add_min_cluster_size_args(parser)

    _add_max_clusters_args(parser)

    parser.add_argument(
        '--samples',
        default=None,
        nargs='+',
        help='''Samples to plot and order to plot them in.'''
    )

    parser.set_defaults(func=run.loci_plot)

#=======================================================================================================================
# Common args
#=======================================================================================================================

def _add_config_file_args(parser):

    parser.add_argument(
        '--config_file',
        required=True,
        help='''Path to configuration file used for analysis.'''
    )

def _add_plot_out_file_args(parser):

    parser.add_argument(
        '--plot_file',
        required=True,
        help='Path to file where plot will be saved. Format can be controlled by changing file extension.'
    )

def _add_seed_args(parser):

    parser.add_argument(
        '--seed',
        default=None,
        type=int,
        help='''Set random seed so results can be reproduced. By default a random seed is chosen.'''
    )

def _add_prior_args(parser):

    parser.add_argument(
        '--prior',
        choices=['major_copy_number', 'parental_copy_number', 'total_copy_number'],
        default='major_copy_number',
        help='''Method used to set the possible genotypes. See online help for description. Default is major_copy_number.'''
    )

def _add_post_process_args(parser):

    parser.add_argument(
        '--burnin',
        default=0,
        type=int,
        help='''Number of samples to discard as burning for the MCMC chain. Default is 0.'''
    )

    parser.add_argument(
        '--thin',
        default=1,
        type=int,
        help='''Number of samples to thin MCMC trace. For example if thin=10 every tenth sample after burning will be
        used for inference. Default is 1.'''
    )

def _add_min_cluster_size_args(parser):
    parser.add_argument(
        '--min_cluster_size',
        default=0,
        type=int,
        help='''Clusters with fewer mutations than this value will not be plotted.'''
    )

def _add_mesh_size_args(parser):
    parser.add_argument(
        '--mesh_size',
        default=101,
        type=int,
        help='''Number of points to use for approximating the cluster posteriors. Default is 101.'''
    )

def _add_init_method_args(parser):
    parser.add_argument(
        '--init_method', choices=['connected', 'disconnected'], default='disconnected',
        help='''How to initialise the DP clustering algorithm. `connected` places all data points in one cluster,
        preferred for large datasets. `disconnected places each data point in a separate cluster. Default
        `disconnected`.'''
    )

def _add_max_clusters_args(parser):
    parser.add_argument(
        '--max_clusters', default=None, type=int,
        help='''Maximum number of clusters to consider for post-processing. Note this does not affect the DP sampling
        only the final post-processing steps to get hard cluster assignments.'''
    )

if __name__ == '__main__':
    main()


import sys
import inspect
import os
import datetime
import traceback

this_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
if this_dir not in sys.path:
    sys.path.append(this_dir)

import menu_tools as tools

# constants
_error_print_periodicity = 2.0  # As seconds
_error_signatures_stack_size = 32
# variables
_prev_error_signatures = [""] * _error_signatures_stack_size
_prev_error_index = 0
_prev_time = datetime.datetime.now()
_accumulated_dt = 0.0

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# ////////   P R I V A T E   F U N C T I O N S   ////////
# - - - - - - - - - - - - - - - - - - - - - - - - - - -
# region [ COLLAPSE / EXPAND ]
def _try_print(signature, title, func_name, line_num, filename, comment, suggestion, call_stack):
    if _signatures_stack_has_signature(signature) is False:
        # New error ==> PRINT
        _insert_error_signature(signature)
        print(_create_print_message(title, func_name, line_num, filename, comment, suggestion, call_stack))
        # Reset time-variables here to avoid inconsistent printing
        globals()['_prev_time'] = datetime.datetime.now()
        globals()['_accumulated_dt'] = 0
    else:
        # Error already reported ==> adjust time-variables
        curr_time = datetime.datetime.now()
        dt = curr_time - globals()['_prev_time']
        globals()['_accumulated_dt'] += dt.total_seconds()
        globals()['_prev_time'] = curr_time
        # Timer has passed 'print periodicity' ==> PRINT
        if globals()['_accumulated_dt'] > globals()['_error_print_periodicity']:
            _insert_error_signature(signature)
            print(_create_print_message(title, func_name, line_num, filename, comment, suggestion, call_stack))
            # Reset accumulated time
            globals()['_accumulated_dt'] = 0

def _create_print_message(title, func_name, line_num, filename, comment, suggestion, call_stack):
    result = ""
    result += ("\n" + title[:7] + "\t|FUNCTION NAME: " + func_name)
    result += (" (line " + line_num + " in '" + filename + "')")
    if comment != "":
        result += "\n"
        result += "-" * len(title[:7])
        result += ("\t|COMMENT:" + "\t" + comment)
    if suggestion != "":
        result += ("\n\t|SUGGESTION: " + "\t" + suggestion)
    if call_stack != "":
        result += ("\n" + call_stack)
    return result

def _signatures_stack_has_signature(signature):
    if signature in globals()['_prev_error_signatures']:
        return True
    return False

def _insert_error_signature(signature):
    curr_error_index = globals()['_prev_error_index'] + 1
    if curr_error_index == globals()['_error_signatures_stack_size']:
        curr_error_index = 0
    globals()['_prev_error_signatures'][curr_error_index] = signature
    globals()['_prev_error_index'] = curr_error_index

def _traceback_list_to_array(traceback_list):
    return_array = [[0]*4 for i in range(len(traceback_list))]
    for i in range(len(traceback_list)):
        temp_string = traceback_list[i]
        # Filepath
        temp_string = temp_string.split("\"", 2)
        return_array[i][1] = temp_string[1]
        # Line number
        temp_string = temp_string[2].split("line ", 1)[1].split(",", 1)
        return_array[i][2] = temp_string[0]
        # Function name
        temp_string = temp_string[1].split("in ", 1)[1].split("\n", 1)
        return_array[i][3] = temp_string[0]
        # The actual line of code
        return_array[i][0] = temp_string[1].lstrip()
    return return_array

def _get_call_stack_as_str(call_stack_2d_array, prune_depth, reverse_order=False):
    prune_depth = tools.clamp(prune_depth, 0, len(call_stack_2d_array))
    return_str = "\tCALL STACK:"
    if (prune_depth == len(call_stack_2d_array)):
        return ""  # E A R L Y   E X I T
    else:
        total_depth = len(call_stack_2d_array)
        curr_depth = 0
        # Remove 'prune_depth' number of entries, bot -> top
        for i in range(total_depth - prune_depth):
            if reverse_order:
                index = total_depth-i-1
            else:
                index = i
            return_str += ("\n\t\t")
            if (i != 0):
                return_str += (" "*(curr_depth-1) + "\\" + " ")
            return_str += call_stack_2d_array[index][3]
            return_str += " (line "
            return_str += str(call_stack_2d_array[index][2])
            return_str += " in "
            return_str += os.path.basename(call_stack_2d_array[index][1])
            return_str += ")"
            curr_depth += 1
    return return_str

def _get_call_stack_exception_last_layer():
    return_array = [0]*4
    traceback_as_2d_array = _traceback_list_to_array(traceback.extract_tb(sys.exc_info()[2]).format())
    last_index = len(traceback_as_2d_array) - 1
    for i in range(4):
        return_array[i] = traceback_as_2d_array[last_index][i]
    return return_array

def _get_call_stack_exception(prune_depth=0):
    traceback_as_2d_array = _traceback_list_to_array(traceback.extract_tb(sys.exc_info()[2]).format())
    return _get_call_stack_as_str(traceback_as_2d_array, prune_depth)
# endregion

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# ////////   E X P O R T E D   F U N C T I O N S   ////////
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# region [ COLLAPSE / EXPAND ]
def get_this_method_name():
    return inspect.stack()[1][3]

def get_parent_method_name():
    try:
        inspect.stack()[2][3]
    except IndexError as e:
        try_print_except(str(e), "The parent method wasn't found. Perhaps the function calling this passed as a lambda?")
        return "Parent method not found!"
    return inspect.stack()[2][3]

def get_this_method_line_num():
    return inspect.stack()[1][2]

def get_parent_method_line_num():
    try:
        inspect.stack()[2][2]
    except IndexError as e:
        try_print_except(str(e), "The parent method wasn't found. Perhaps the function calling this was passed as a lambda?")
        return "Parent method not found!"
    return inspect.stack()[2][2]

def get_this_method_filename():
    return inspect.stack()[1][1]

def get_parent_method_filename():
    try:
        inspect.stack()[2][2]
    except IndexError as e:
        try_print_except(str(e), "The parent method wasn't found. Perhaps the function calling this was passed as a lambda?")
        return "Parent method not found!"
    return inspect.stack()[2][1]

def try_print_except(comment="", suggestion="", only_filename=False):
    # Append the exception type to the comment
    comment = str(sys.exc_info()[0]).split("'", 2)[1] + " - " + comment
    call_stack_bot_layer_info = _get_call_stack_exception_last_layer()
    func_name = call_stack_bot_layer_info[3]
    line_num = call_stack_bot_layer_info[2]
    if only_filename:
        filename = call_stack_bot_layer_info[1].rsplit("\\", 1)[1]
    else:
        filename = call_stack_bot_layer_info[1]
    call_stack = _get_call_stack_exception()
    signature = func_name + line_num
    _try_print(signature, "EXCEPT", func_name, line_num, filename, comment, suggestion, call_stack)

def force_print_except(comment="", suggestion="", only_filename=False):
    # Append the exception type to the comment
    comment = str(sys.exc_info()[0]).split("'", 2)[1] + " - " + comment
    call_stack_bot_layer_info = _get_call_stack_exception_last_layer()
    func_name = call_stack_bot_layer_info[3]
    line_num = call_stack_bot_layer_info[2]
    if only_filename:
        filename = call_stack_bot_layer_info[1].rsplit("\\", 1)[1]
    else:
        filename = call_stack_bot_layer_info[1]
    call_stack = _get_call_stack_exception()
    print(_create_print_message("EXCEPT", func_name, line_num, filename, comment, suggestion, call_stack))

def try_print(title_short="MSG", comment="", suggestion="", only_filename=False):
    func_name = get_parent_method_name()
    line_num = str(get_parent_method_line_num())
    if only_filename:
        filename = get_parent_method_filename().rsplit("\\", 1)[1]
    else:
        filename = get_parent_method_filename()
    signature = func_name + line_num
    _try_print(signature, title_short, func_name, line_num, filename, comment, suggestion, "")

def force_print(title_short, comment="", suggestion="", only_filename=False):
    func_name = get_parent_method_name()
    line_num = str(get_parent_method_line_num())
    if only_filename:
        filename = get_parent_method_filename().rsplit("\\", 1)[1]
    else:
        filename = get_parent_method_filename()
    print(_create_print_message(title_short, func_name, line_num, filename, comment, suggestion, ""))
# endregion


import scipy.stats as stats
import pandas as pd

def fixed_data_index():
    #データ確認
    df_historical = pd.read_csv('m_quote_fix.csv', encoding="shift-jis")
    # ここで、手動でカラム名'data'と付けた

    #カラム'data'をインデックスに設定
    df_i = df_historical.rename(columns={'':'data'})
    return df_i

def main():
    df_historical = fixed_data_index()

    #原系列のShapiro-Wilk検定
    print(stats.shapiro(df_historical.USD.values))

    df_diff1 = df_historical.USD.diff().dropna()

    #1次階差系列のShapiro-Wilk検定
    print(stats.shapiro(df_diff1.values))

if __name__ == '__main__':
    main()


import re

text = ""

with open("guys", "+r") as f:
    text = f.read()

results = re.finditer(r"[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]", text)

other_results = [x.group(1)  for x in results]

print(other_results)


import argparse
import youtube_transcript_api

def get_transcript(url):
    try:
        # From the URL, fetch the video ID
        video_id = url.split("v=")[1]

        # Fetch the transcript using the YouTube transcript api
        transcript = youtube_transcript_api.YouTubeTranscriptApi.get_transcript(video_id)

        # Extract the text from the transcript
        text = ""
        for line in transcript:
            text += line['text'] + '\n'

        return text
    except youtube_transcript_api.CouldNotRetrieveTranscript:
        print(f"Error: Could not retrieve transcript for video {video_id}")
        return None
    except IndexError:
        print("Error: Invalid URL")
        return None

# Parse the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("url", help="the YouTube URL of the video")
args = parser.parse_args()

# Get the transcript
transcript = get_transcript(args.url)

# Write the transcript to the file
if transcript:
    with open("transcript.txt", "w") as f:
        f.write(transcript)
    print(f"Transcript for video {video_id} written to transcript.txt")
else:
    print("Transcript not written to file")


"""Methods for parsing a build request document.

The primary input for this is a List[List[str]] representing the excel
or csv sheet. This can be obtained by parsing an excel sheet, using the
google sheet API, etc.
"""
import re
from itertools import tee
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import List
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

import pandas as pd

from .cell_value import CellValue
from .exceptions import BuildRequestParsingException
from .exceptions import parsing_location
from .validate import validate_part_list

T = TypeVar("T")

# TODO: parse these keys
class Keys:
    # keys used in the build request document

    Basic_DNA_Parts = "Basic DNA Parts"
    Composite_DNA_Parts = "Composite DNA Parts"
    Collection_Name = "Collection Name"
    Part_Name = "Part Name"
    Description = "Description (Optional)"
    Sequence = "Sequence"
    Length = "length (bp)"
    Source = "Source (Optional)"
    Role = "Role"

##########################
# Utilities
##########################

def _is_nan(x: Union[str, CellValue]) -> bool:
    if x is None:
        return True
    elif x.strip().lower() == "nan":
        return True
    elif x.strip().lower() == "None":
        return True
    elif x.strip() == "":
        return True
    return False

def _dispatch_match_fxn(
    match: Union[Callable, str, re.Pattern]
) -> Callable[[str], bool]:
    """Generate a match function from a string, Callable, or regex pattern."""
    if callable(match):
        _match_fxn = match
    else:

        def _match_fxn(x):
            if isinstance(match, re.Pattern):
                return match.match(x)
            else:
                return match == x

    return _match_fxn

def match_value(match: Union[Callable, str, re.Pattern], value: str) -> bool:
    """Match a string, Callable, or regex pattern with a value."""
    fxn = _dispatch_match_fxn(match)
    return fxn(value)

def find_value(
    values,
    match: Union[Callable, str, re.Pattern],
    only_rows: Optional[List[int]] = None,
    only_cols: Optional[List[int]] = None,
) -> List[Tuple[int, int]]:
    """Return the indices [(int, int), ...] of the cells that match the
    provided matching string, function, regex pattern."""
    found = []

    for r, row in enumerate(values):
        if not only_rows or r in only_rows:
            for c, val in enumerate(row):
                if not only_cols or c in only_cols:
                    if match_value(match, str(val)):
                        found.append((r, c))
    return found

def pairwise(iterable: Iterable[T]) -> Iterable[Tuple[T, T]]:
    """s -> (s0,s1), (s1,s2), (s2, s3), ..."""
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def _partition(x: List, indices: Union[None, int]) -> List:
    """Partition a list using a list of indices."""
    for a, b in pairwise(indices):
        yield x[a:b]

def cell_is_empty(cell: str):
    return _is_nan(cell)

def row_is_empty(row: List[str]) -> bool:
    """check that a row of string values is empty."""
    return all(cell_is_empty(c) for c in row)

def remove_empties_from_row(values: List[List[str]]) -> List[List[str]]:
    """Remove empty rows."""
    return [row for row in values if not row_is_empty(row)]

def is_square(values: List[List[T]]) -> bool:
    """Check that 2D list is square."""
    row_sizes = [len(r) for r in values]
    return len(set(row_sizes)) == 1

def transpose(values: List[List[T]]) -> List[List[T]]:
    """Try to 'transpose' a list of lists."""
    num_rows = max([len(r) for r in values])
    transposed = [[] for _ in range(num_rows)]
    for r in range(num_rows):
        for row in values:
            if r < len(row):
                transposed[r].append(row[r])
    return transposed

##########################
# Extract sections of
# the build request values
##########################

def extract_meta(values: List[List[CellValue]]) -> List[List[CellValue]]:
    r1 = find_value(values, Keys.Basic_DNA_Parts)[0][0]
    return remove_empties_from_row(values[:r1])

def extract_basic_parts(values: List[List[Union[str, int]]]) -> List[List[CellValue]]:
    r1 = find_value(values, Keys.Basic_DNA_Parts)[0][0]
    r2 = find_value(values, Keys.Composite_DNA_Parts)[0][0]
    return remove_empties_from_row(values[r1:r2])

def extract_composite_parts(
    values: List[List[Union[str, int]]]
) -> List[List[CellValue]]:
    r1 = find_value(values, Keys.Composite_DNA_Parts)[0][0]
    return remove_empties_from_row(values[r1:])

########################
# Parse extracted values
########################

def values_to_json(
    values: List[List[Union[str, int]]],
    key_column: int,
    fill_empty_key_from_above: bool = False,
):
    data = {}
    for row in values:
        key = row[key_column].strip()
        if fill_empty_key_from_above and key == "":
            key = prev_key
        data.setdefault(key, list())
        data[key].append(row[key_column + 1 :])
        prev_key = key
    return data

# TODO: rename this method
def parse_composite_parts(values: List[List[Union[str, int]]]) -> List[Dict]:
    composite = extract_composite_parts(values)

    # locate indices of new "Collections"
    indices = find_value(composite, re.compile(Keys.Collection_Name))
    rows = [None] + [i[0] for i in indices] + [None]

    # partition the values on the indices
    partitioned = list(_partition(composite, rows))[1:]
    parsed_json_arr = []
    for p in partitioned:
        with parsing_location(p[0][0]):
            parsed_json_arr.append(values_to_json(p, 0, True))

    # TODO: Validate the data here. Check for incorrect keys under each heading

    def _make_part_list(parsed_json):
        with parsing_location(parsed_json["Name:"][0][0]):
            names = transpose(parsed_json["Name:"])

        if "Parts:" in parsed_json:
            # TODO: should this be covered by the jsonschema?
            # if 'Part Sequence:' in parsed_json:
            #     with parsing_location(parsed_json['Parts:'][0][0]):
            #         raise BuildRequestParsingException("Both 'Parts:' and 'Part Sequence:' cannot be "
            #                                            "defined for a composite part")
            with parsing_location(parsed_json["Parts:"][0][0]):
                parts = transpose(parsed_json["Parts:"])
            part_type = "composite part"
        # if 'Part Sequence:' in parsed_json:
        #     with parsing_location(parsed_json['Part Sequence:'][0][0]):
        #         parts = transpose(parsed_json['Part Sequence:'])
        #     part_type = 'composite part'
        with parsing_location(parsed_json["Description:"][0][0]):
            descriptions = transpose(parsed_json["Description:"])
        collection_name = parsed_json["Collection Name:"][0][0]

        parts = [[p for p in row if not _is_nan(p)] for row in parts]

        part_list = []
        for _name, _description, _parts in list(zip(names, descriptions, parts)):
            part_list.append(
                {
                    "name": _name[0],
                    "collection": collection_name,
                    "partType": part_type,
                    "description": _description[0],
                    "parts": _parts,
                }
            )
        return part_list

    part_list = []
    for p in parsed_json_arr:
        part_list += _make_part_list(p)

    # remove empty parts (again)
    part_list_old = part_list[:]
    part_list = []
    for part in part_list_old:
        if (
            _is_nan(part["name"])
            and _is_nan(part["description"])
            and part["parts"] in [[], ["nan"], ["none"], ["None"], [""]]
        ):
            continue
        else:
            part_list.append(part)

    return part_list

def _get_and_strip(d: Dict[str, str], k: str, default: T) -> Union[T, str]:
    """Get value from dictionary and strip.

    Else, return default
    """
    if k in d:
        if not isinstance(d[k], str):
            return default
        else:
            cv = CellValue(d[k].strip())
            cv.add_rc(d[k].row, d[k].col)
            return cv

def parse_basic_parts(values: List[List[Union[str, int]]]) -> List[Dict]:
    basic = extract_basic_parts(values)

    # remove empty rows
    basic = remove_empties_from_row(basic)

    part_json = pd.DataFrame(basic[2:], columns=basic[1]).T.to_dict()

    part_json_list = []
    for data in part_json.values():
        new_data = {
            "name": _get_and_strip(data, Keys.Part_Name, None),
            "collection": "basic DNA parts",
            "partType": "basic part",
            "description": _get_and_strip(data, Keys.Description, None),
            "sequence": _get_and_strip(data, Keys.Sequence, None),
        }

        length = data[Keys.Length]
        if length and not _is_nan(length):
            try:
                new_data["length"] = int(length)
            except ValueError:
                pass

        source = data[Keys.Source]
        if source and not _is_nan(source):
            new_data["source"] = source.strip()

        role = data[Keys.Role]
        if role and not _is_nan(role):
            new_data["roles"] = [role.strip()]

        part_json_list.append(new_data)
    return part_json_list

def parse_parts(values: List[List[Union[str, int]]]) -> List[Dict]:
    basic_parts = parse_basic_parts(values)
    composite_parts = parse_composite_parts(values)
    all_parts = basic_parts + composite_parts
    validate_part_list(all_parts)
    return all_parts


## create a telegram bot that has a helper function to send message on a specific chat_id

import requests
import json
import os
from dotenv import load_dotenv

load_dotenv()

token = os.getenv('TELEGRAM_TOKEN')
chat_id = os.getenv('TELEGRAM_CHAT_ID')

def send_message(message):
    ## send message to a specific chat_id
    url = f'https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={message}'
    requests.get(url)

def get_updates():
    ## get all new messages
    url = f'https://api.telegram.org/bot{token}/getUpdates'
    response = requests.get(url)
    return response.json()

if __name__ == '__main__':
    print(get_updates())
    input("Press ENTER to continue:")
    send_message('Hello World!')
    input("Press ENTER to continue:")
    print(get_updates())


#https://leetcode.com/problems/median-of-two-sorted-arrays/

from core.problem_base import *

class FindMedianSortedArrays(ProblemBase):
    def Solution(self, nums1: list[int], nums2: list[int]) -> float:
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1

        m = len(nums1)
        n = len(nums2)
        length = m + n
        partition = (length + 1) // 2
        left = 0
        right = m

        while left <= right:
            mid1 = (left + right) // 2
            mid2 = partition - mid1

            m1 = nums1[mid1 - 1] if mid1 > 0 else float("-inf")
            l1 = nums1[mid1] if mid1 < m else float("inf")

            m2 = nums2[mid2 - 1] if mid2 > 0 else float("-inf")
            l2 = nums2[mid2] if mid2 < n else float("inf")

            if m1 <= l2 and m2 <= l1:
                if length % 2 == 0:
                    return (max(m1, m2) + min(l1, l2)) / 2
                return max(m1, m2)

            if m1 > l2:
                right = mid1 - 1
            else:
                left = mid1 + 1

        return 0

if __name__ == '__main__':
    TestGen(FindMedianSortedArrays) \
        .Add(lambda tc: tc.Param("nums1", [1,2,3,4,5]).Param("nums2", [1,2,3,4,5,6,7,8]).Result(4.0)) \
        .Add(lambda tc: tc.Param("nums1", [1,2,3,4]).Param("nums2", [1,2,3,4,5,6,7,8]).Result(3.5)) \
        .Add(lambda tc: tc.Param("nums1", [1,3]).Param("nums2", [2]).Result(2.0)) \
        .Add(lambda tc: tc.Param("nums1", [1,2]).Param("nums2", [3,4]).Result(2.5)) \
        .Run()


'''
Utilities for building ntuples used in ISA.

Author: Devin N. Taylor, UW-Madison
'''
from itertools import product

import ROOT as rt
from array import array

def buildCutTree(cutlabels,**kwargs):
    eventLeafs = ['evt','run','lumi']
    eventBranchLineToProcess = "struct eventBranch_t {ULong64_t evt; Int_t run; Int_t lumi;}"
    cutBranchLineToProcess = "struct cutBranch_t {" + " ".join(["Int_t {0};".format(x) for x in cutlabels]) + "}"
    eventBranchStrForBranch = 'evt/l:run/I:lumi'
    cutBranchStrForBranch = '{0}/I:'.format(cutlabels[0]) + ':'.join(cutlabels[1:])
    if not hasattr(rt,"eventBranch_t"): rt.gROOT.ProcessLine(eventBranchLineToProcess)
    if not hasattr(rt,"cutBranch_t"): rt.gROOT.ProcessLine(cutBranchLineToProcess)
    eventBranchStruct = rt.eventBranch_t()
    cutBranchStruct = rt.cutBranch_t()
    tree = rt.TTree('cutTree','cutTree')
    tree.Branch('event',eventBranchStruct,eventBranchStrForBranch)
    tree.Branch('selections',cutBranchStruct,cutBranchStrForBranch)
    return (tree, eventBranchStruct, cutBranchStruct)

def getStruct(name,varDict):
    strToProcess = 'struct {0}'.format(name) + ' {'
    strForBranch = ''
    typeMap = {'I': 'Int_t', 'F': 'Float_t', 'l': 'ULong64_t', 'C': 'Char_t'}
    for t in ['F','I','l']:
        if t not in varDict: continue
        for v,var in enumerate(varDict[t]):
            strToProcess += '{0} {1};'.format(typeMap[t],var)
            if v==0:
                strForBranch += '{0}/{1}:'.format(var,t)
            else:
                strForBranch += '{0}:'.format(var)
    strToProcess += '};'
    strForBranch = strForBranch[:-1]
    if not hasattr(rt,name): rt.gROOT.ProcessLine(strToProcess)
    struct = getattr(rt,name)()
    return struct, strForBranch

def buildNtuple(object_definitions,states,channelName,final_states,**kwargs):
    '''
    A function to build an initial state ntuple for AnalyzerBase.py
    '''
    alternateIds = kwargs.pop('altIds',[])
    doVBF = kwargs.pop('doVBF',False)
    doMetUnc = kwargs.pop('doMetUnc',False)

    finalStateObjects = 'emtjgn'
    structureDict = {}
    structOrder = []

    # count objects
    nl = 0
    nj = 0
    np = 0
    for key in states[0]:
        val = object_definitions[key]
        for obj in val:
            if obj=='n': continue
            else:
                if obj in 'emt':
                    nl += 1
                if obj == 'j':
                    nj += 1
                if obj == 'g':
                    np += 1

    # some common things
    baseMetVars = ['met','metPhi','mT']
    metVars = []
    metVars += baseMetVars
    baseLepMetVars = ['mass','Pt','sT','dPhi']
    lepMetVars = []
    if doMetUnc:
        for s in ['JetRes','JetEn','MuonEn','ElectronEn','TauEn','UnclusteredEn','PhotonEn']:
            for d in ['Up','Down']:
                for m in baseMetVars:
                    metVars += ['{0}{1}{2}'.format(m,s,d)]
                for m in baseLepMetVars:
                    lepMetVars += ['{0}{1}{2}'.format(m,s,d)]

    lepFloats = ['Pt', 'Eta', 'Phi', 'Iso', 'Dxy', 'Dz', 'SigmaIEtaIEta', 'DEtaIn', 'DPhiIn', 'HOverE', 'OoEmOoP', 'TriggeringMVA', 'NonTriggeringMVA', 'NormalizedChi2', 'JetPt', 'JetBTag']
    for t in ['','_up','_down']:
        for l in ['Loose','Medium','Tight']:
            lepFloats += ['LepScale{0}{1}'.format(l,t)]
            if l=='Loose': continue
            lepFloats += ['LepEff{0}{1}'.format(l,t)]
            lepFloats += ['LepFake{0}{1}'.format(l,t)]
            lepFloats += ['LepFakeMC{0}{1}'.format(l,t)]
    lepInts = ['Chg', 'PassLoose', 'PassMedium', 'PassTight', 'GenIsPrompt', 'GenPdgId', 'GenPatPdgId', 'MotherGenPdgId', 'ChargeConsistent', 'ExpectedMissingInnerHits', 'PassConversionVeto', 'IsGlobalMuon', 'IsPFMuon', 'IsTrackerMuon', 'ValidMuonHits', 'MatchedStations', 'ValidPixelHits', 'TrackerLayers']

    # define selection bools
    numObjs = len(final_states[0])
    allowedObjects = ''
    for fsObj in finalStateObjects:
        for fs in final_states:
            if fsObj in fs:
                allowedObjects += fsObj
                break
    numObjTypes = len(allowedObjects)

    selectVars = {}
    selectVars['I'] = ['passTight','passLoose']
    for trig in ['DoubleMuon','DoubleEG','MuonEG','EGMuon','SingleMuon','SingleEG']:
        selectVars['I'] += ['pass{0}'.format(trig)]
    for altId in alternateIds:
        selectVars['I'] += ['pass_{0}'.format(altId)]
    selectName = 'structSelect_t'
    selectStruct, selectStrForBranch = getStruct(selectName,selectVars)

    structureDict['select'] = [selectStruct, selectStruct, selectStrForBranch]
    structOrder += ['select']

    # define common root classes
    eventVars = {}
    eventVars['I'] = ['run','lumi','nvtx','GenNUP']
    eventVars['l'] = ['evt'] # ULong64
    eventVars['F'] = ['gen_weight','charge_uncertainty','trig_prescale']
    scaleVars = ['lep_scale','lep_scale_e','lep_scale_m','pu_weight','fakerate','trig_scale']
    for v in scaleVars:
        for t in ['','_up','_down']:
            eventVars['F'] += ['{0}{1}'.format(v,t)]
    eventName = 'structEvent_t'
    eventStruct, eventStrForBranch = getStruct(eventName,eventVars)
    structOrder += ['event']
    structureDict['event'] = [eventStruct,eventStruct,eventStrForBranch]

    # add channels
    if not hasattr(rt,'structChannel_t'):
        rt.gROOT.ProcessLine(
        "struct structChannel_t {\
           Char_t  channel[9];\
        };");
    channelStruct = rt.structChannel_t()
    structureDict['channel'] = [channelStruct, rt.AddressOf(channelStruct,'channel'),'channel/C']
    structOrder += ['channel']
    genChannelStruct = rt.structChannel_t()
    structureDict['genChannel'] = [genChannelStruct, rt.AddressOf(genChannelStruct,'channel'),'channel/C']
    structOrder += ['genChannel']
    fakeChannelStruct = rt.structChannel_t()
    structureDict['fakeChannel'] = [fakeChannelStruct, rt.AddressOf(fakeChannelStruct,'channel'),'channel/C']
    structOrder += ['fakeChannel']
    if channelName=='WZ':
        fakeChannelTightWStruct = rt.structChannel_t()
        structureDict['fakeChannel_tightW'] = [fakeChannelTightWStruct, rt.AddressOf(fakeChannelTightWStruct,'channel'),'channel/C']
        structOrder += ['fakeChannel_tightW']
        fakeChannelAllMediumStruct = rt.structChannel_t()
        structureDict['fakeChannel_allMedium'] = [fakeChannelAllMediumStruct, rt.AddressOf(fakeChannelAllMediumStruct,'channel'),'channel/C']
        structOrder += ['fakeChannel_allMedium']

    # add final state structs
    fsVars = {}
    fsVars['F'] = ['mass','eta','phi','sT']
    fsVars['F'] += metVars
    fsVars['F'] += ['leadJetPt','leadJetEta','leadJetPhi','leadJetPUMVA']
    fsVars['I'] = ['jetVeto20','jetVeto30','jetVeto40']
    fsVars['I'] += ['elecVetoLoose','elecVetoTight','muonVetoLoose','muonVetoTight']
    for pt in ['20','30']:
        for l in ['Loose','Medium','Tight']:
            fsVars['I'] += ['bjetVeto{0}{1}'.format(pt,l)]
    if doVBF:
        fsVars['F'] += ['vbfMass','vbfPt','vbfPt1','vbfPt2','vbfEta1','vbfEta2']
        fsVars['I'] += ['centralJetVeto20','centralJetVeto30']
    fsName = 'structFinalState_t'
    fsStruct, fsStrForBranch = getStruct(fsName,fsVars)
    structureDict['finalstate'] = [fsStruct, fsStruct, fsStrForBranch]
    structOrder += ['finalstate']

    # add object struct
    objVars = {}
    objVars['F'] = lepFloats
    objVars['I'] = lepInts
    objName = 'structObject_t'

    if not hasattr(rt,'structObjChar_t'):
        rt.gROOT.ProcessLine(
        "struct structObjChar_t {\
           Char_t  Flv[2];\
        };");

    lepCount = 0
    jetCount = 0
    phoCount = 0
    for key in states[0]:
        val = object_definitions[key]
        for obj in val:
            if obj=='n': continue
            else:
                objStruct, objStrForBranch = getStruct(objName,objVars)
                flvStruct = rt.structObjChar_t()
                if obj in 'emt':
                    charName = 'l'
                    lepCount += 1
                    objCount = lepCount
                if obj == 'j':
                    charName = 'j'
                    jetCount += 1
                    objCount = jetCount
                if obj == 'g':
                    charName = 'g'
                    phoCount += 1
                    objCount = phoCount
                structureDict['%s%i' % (charName, objCount)] = [objStruct, objStruct, objStrForBranch]
                structureDict['%s%iFlv' % (charName, objCount)] = [flvStruct, rt.AddressOf(flvStruct,'Flv'),'Flv/C']
                structOrder += ['%s%i' % (charName, objCount)]
                structOrder += ['%s%iFlv' % (charName, objCount)]

    # define objects for each initial state
    for state in states:
        for key in state:
            val = object_definitions[key]
            stateVars = {'I':[],'F':[]}
            stateName = 'struct{0}_t'.format(key.upper())
            stateVars['F'] += ['mass','Pt','sT','dPhi']
            if 'n' not in val:
                stateVars['F'] += ['dR']
            objCount = 0
            for obj in val:
                if obj == 'n':
                    #stateVars['F'] += metVars
                    stateVars['F'] += lepMetVars
                else:
                    objCount += 1
                    for v in lepFloats:
                        stateVars['F'] += ['{0}{1}'.format(v,objCount)]
                    for v in lepInts:
                        stateVars['I'] += ['{0}{1}'.format(v,objCount)]
                    # manually add the W Z deltaRs for now
                    if key == 'w1':
                        stateVars['F'] += ['dR1_z1_1','dR1_z1_2','mll_z1_1','mll_z1_2','dR1_leadJet']
                    for altId in alternateIds:
                        stateVars['I'] += ['pass_{0}_{1}'.format(altId, objCount)]
            initialStruct, initialStrForBranch = getStruct(stateName,stateVars)
            structureDict[key] = [initialStruct, initialStruct, initialStrForBranch]
            structOrder += [key]

    if not hasattr(rt,'structInitialChar_t'):
        rt.gROOT.ProcessLine(
        "struct structInitialChar_t {\
           Char_t  Flv[3];\
        };");
    for key in object_definitions:
        initialFlvStruct = rt.structInitialChar_t()
        structureDict['%sFlv' % key] = [initialFlvStruct,rt.AddressOf(initialFlvStruct,'Flv'),'Flv/C']
        structOrder += ['%sFlv' % key]

    # now create the tree
    tree = rt.TTree(channelName,channelName)
    allBranches = {}
    for key in structOrder:
        val = structureDict[key]
        tree.Branch(key,val[1],val[2])
        allBranches[key] = val[0]

    return (tree, allBranches)


import click

def click_prompt_multiple_choice(question, choices, default=0):

    full_question = question
    for ichoice, choice in enumerate(choices):
        full_question += '\n   {0} - {1}'.format(ichoice + 1, choice)
    full_question += '\n'

    result = click.prompt(full_question, type=click.IntRange(1, len(choices)), default=default + 1)

    return choices[result - 1]


from django.conf.urls import url
from inkscape.url_utils import url_tree

from .views import DownloadRedirect, ReleaseView, PlatformList,\
                   ReleasePlatformStage, ReleasePlatformView, PlatformView

version_urls = url_tree( # pylint: disable=invalid-name
    r'^(?P<version>[\w\+\.-]+)/',
    url('^$', ReleaseView.as_view(), name="release"),
    url(r'^platforms/$', PlatformList.as_view(), name="platforms"),

    # We don't use url_tree here because .+ competes with /dl/
    url('^(?P<platform>.+)/dl/$', ReleasePlatformView.as_view(), name="download"),
    url('^(?P<platform>.+)/$', ReleasePlatformStage.as_view(), name="platform"),
)

urlpatterns = [ # pylint: disable=invalid-name
    url(r'^$', DownloadRedirect.as_view(), name="download"),
    url('^all/(?P<platform>.+)/$', PlatformView.as_view(), name="platform"),
    url_tree(
        r'^(?P<project>[\w\-\.]+)-',
        version_urls,
    ),
    version_urls,
]