import numpy as np
from scipy import linalg
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from min2net.utils import butter_bandpass_filter
# Note that we modify CSP function using MNE-Python package (version 0.20).
# Reference:
# - https://github.com/mne-tools/mne-python
# - A. Gramfort, M. Luessi, E. Larson, D. Engemann, D. Strohmeier, C. Brodbeck, R. Goj, M. Jas, T. Brooks, L. Parkkonen, and M. Ha ̈ma ̈la ̈inen, “Meg and eeg data analysis with mne-python,” Frontiers in Neuroscience, vol. 7, p. 267, 2013.
# Sources:
# - Common Spatial Pattern revisited by Riemannian geometry
# - Model based generalization analysis of common spatial pattern in brain computer interfaces

class SpectralSpatialMapping():
    def __init__(self,
                bands,
                smp_freq,
                num_class=2,
                order=5,
                n_components=10,
                n_pick_bands=20):
        self.bands = bands
        self.smp_freq = smp_freq
        self.n_components = n_components
        self.n_pick_bands = n_pick_bands
        self.cov_type = 'epoch'
        self.classes = None
        self.order = order
        self.n_classes = num_class
        if self.n_classes == 2:
            self.component_order = 'alternate'
        else:
            self.component_order = 'mutual_info'
        self.norm_trace = False

    def __covariance(self, X):
        # covariance = np.dot(X, X.T)/X.shape[0]
        # return covariance
        return np.dot(X,X.T)/np.trace(np.dot(X,X.T))

    # spatialFilter returns the spatial filter for mean covariance matrices on each class
    def __get_spatial_filter(self, covs, sample_weights):
        eigen_vectors, eigen_values = self.__decompose_covs(covs, sample_weights)
        # CSP requires the eigenvalues and eigenvector be sorted in descending order
        sorted_index = self.__order_components(covs, sample_weights, eigen_vectors, eigen_values)
        eigen_vectors = eigen_vectors[:, sorted_index]
        sp_filters = eigen_vectors.T
        pick_filters = sp_filters[:self.n_components]
        return pick_filters, sp_filters

    def __decompose_covs(self, covs, sample_weights):
        n_classes = len(covs)
        if n_classes == 2:
            eigen_values, eigen_vectors = linalg.eigh(covs[0], covs.sum(0))
        else:
            # The multiclass case is adapted from
            # http://github.com/alexandrebarachant/pyRiemann
            eigen_vectors, D = self.__ajd_pham(covs)
            eigen_vectors = self.__normalize_eigenvectors(eigen_vectors.T, covs, sample_weights)
            eigen_values = None
        return eigen_vectors, eigen_values

    def __calculate_covariance_matrices(self, data, y_class):
        '''The data is in the form of samples x channels x sampled_time_points'''
        if len(data.shape) != 3:
            raise Exception('Dimension is not match!')
        n_samples, n_channels, n_points = data.shape

        if self.cov_type == 'concat':
            cov_estimator = self.__concat_cov
        elif self.cov_type == 'epoch':
            cov_estimator = self.__epoch_cov

        covs = []
        sample_weights = []
        self.classes = np.unique(y_class)
        n_classes = len(self.classes)
        # print('The numbers of class used are {} and type of class {}'.format(n_classes, self.classes))
        for id_class in self.classes:
            cov, weight = cov_estimator(data[y_class == id_class])
            if self.norm_trace:
                cov /= np.trace(cov)
            covs.append(cov)
            sample_weights.append(weight)
        return np.stack(covs), np.array(sample_weights)

    def __concat_cov(self, X_class):
        '''The data is in the form of samples x channels x sampled_time_points'''
        '''Concatenate epochs before computing the covariance.'''
        n_samples, n_channels, n_points = X_class.shape
        X_class = np.transpose(X_class, [1, 0, 2])
        X_class = X_class.reshape(n_channels, -1)
        cov = self.__covariance(X_class)
        # The covariace with norm trace is used to provide better results
        # cov = np.cov(X_class)
        weight = X_class.shape[0]
        return cov, weight

    def __epoch_cov(self, X_class):
        '''The data is in the form of samples x channels x sampled_time_points'''
        '''Mean of per-epoch covariances.'''
        cov = sum(self.__covariance(data) for data in X_class)
        cov /= len(X_class)
        weight = len(X_class)
        return cov, weight

    def __compute_mutual_info(self, covs, sample_weights, eigen_vectors):
        class_probas = sample_weights / sample_weights.sum()

        mutual_info = []
        for jj in range(eigen_vectors.shape[1]):
            aa, bb = 0, 0
            for (cov, prob) in zip(covs, class_probas):
                tmp = np.dot(np.dot(eigen_vectors[:, jj].T, cov),
                             eigen_vectors[:, jj])
                aa += prob * np.log(np.sqrt(tmp))
                bb += prob * (tmp ** 2 - 1)
            mi = - (aa + (3.0 / 16) * (bb ** 2))
            mutual_info.append(mi)

        return mutual_info

    def __normalize_eigenvectors(self, eigen_vectors, covs, sample_weights):
        # Here we apply an euclidean mean. See pyRiemann for other metrics
        mean_cov = np.average(covs, axis=0, weights=sample_weights)

        for ii in range(eigen_vectors.shape[1]):
            tmp = np.dot(np.dot(eigen_vectors[:, ii].T, mean_cov),
                         eigen_vectors[:, ii])
            eigen_vectors[:, ii] /= np.sqrt(tmp)
        return eigen_vectors

    def __order_components(self, covs, sample_weights, eigen_vectors, eigen_values):
        if self.component_order == 'mutual_info' and self.n_classes > 2:
            mutual_info = self.__compute_mutual_info(covs, sample_weights, eigen_vectors)
            ix = np.argsort(mutual_info)[::-1]
        elif self.component_order == 'mutual_info' and self.n_classes == 2:
            ix = np.argsort(np.abs(eigen_values - 0.5))[::-1]
        elif self.component_order == 'alternate' and self.n_classes == 2:
            i = np.argsort(eigen_values)
            ix = np.empty_like(i)
            ix[1::2] = i[:len(i) // 2]
            ix[0::2] = i[len(i) // 2:][::-1]
        return ix

    def __ajd_pham(self, X, eps=1e-6, max_iter=15):
        '''Approximate joint diagonalization based on Pham's algorithm.
        This is a direct implementation of the PHAM's AJD algorithm [1].
        Parameters
        ----------
        X : ndarray, shape (n_epochs, n_channels, n_channels)
            A set of covariance matrices to diagonalize.
        eps : float, default 1e-6
            The tolerance for stopping criterion.
        max_iter : int, default 1000
            The maximum number of iteration to reach convergence.
        Returns
        -------
        V : ndarray, shape (n_channels, n_channels)
            The diagonalizer.
        D : ndarray, shape (n_epochs, n_channels, n_channels)
            The set of quasi diagonal matrices.
        References
        ----------
        .. [1] Pham, Dinh Tuan. 'Joint approximate diagonalization of positive
               definite Hermitian matrices.' SIAM Journal on Matrix Analysis and
               Applications 22, no. 4 (2001): 1136-1152.
        '''
        # Adapted from http://github.com/alexandrebarachant/pyRiemann
        n_epochs = X.shape[0]

        # Reshape input matrix
        A = np.concatenate(X, axis=0).T

        # Init variables
        n_times, n_m = A.shape
        V = np.eye(n_times)
        epsilon = n_times * (n_times - 1) * eps

        for it in range(max_iter):
            decr = 0
            for ii in range(1, n_times):
                for jj in range(ii):
                    Ii = np.arange(ii, n_m, n_times)
                    Ij = np.arange(jj, n_m, n_times)

                    c1 = A[ii, Ii]
                    c2 = A[jj, Ij]

                    g12 = np.mean(A[ii, Ij] / c1)
                    g21 = np.mean(A[ii, Ij] / c2)

                    omega21 = np.mean(c1 / c2)
                    omega12 = np.mean(c2 / c1)
                    omega = np.sqrt(omega12 * omega21)

                    tmp = np.sqrt(omega21 / omega12)
                    tmp1 = (tmp * g12 + g21) / (omega + 1)
                    tmp2 = (tmp * g12 - g21) / max(omega - 1, 1e-9)

                    h12 = tmp1 + tmp2
                    h21 = np.conj((tmp1 - tmp2) / tmp)

                    decr += n_epochs * (g12 * np.conj(h12) + g21 * h21) / 2.0

                    tmp = 1 + 1.j * 0.5 * np.imag(h12 * h21)
                    tmp = np.real(tmp + np.sqrt(tmp ** 2 - h12 * h21))
                    tau = np.array([[1, -h12 / tmp], [-h21 / tmp, 1]])

                    A[[ii, jj], :] = np.dot(tau, A[[ii, jj], :])
                    tmp = np.c_[A[:, Ii], A[:, Ij]]
                    tmp = np.reshape(tmp, (n_times * n_epochs, 2), order='F')
                    tmp = np.dot(tmp, tau.T)

                    tmp = np.reshape(tmp, (n_times, n_epochs * 2), order='F')
                    A[:, Ii] = tmp[:, :n_epochs]
                    A[:, Ij] = tmp[:, n_epochs:]
                    V[[ii, jj], :] = np.dot(tau, V[[ii, jj], :])
            if decr < epsilon:
                break
        D = np.reshape(A, (n_times, -1, n_times)).transpose(1, 0, 2)
        return V, D

    def __get_log_var_feats(self, spatial_filt, data):
        data_dot = np.dot(spatial_filt, data) # spatially filtered signals
        data_var = np.var(data_dot)
        # We use log(var) instead of averaging
        data_log = np.log(data_var)
        return data_log

    def get_transformed_feats(self, spatial_filt, data):
        data_dot = np.dot(spatial_filt, data) # spatially filtered signals
        data_cov = self.__covariance(data_dot)
        return data_cov

    def spatial_spectral_with_valset(self, X_tr, y_tr, X_val, X_te):
        if len(X_tr.shape) != 3:
            raise Exception('Dimension is not match!')

        # Empty array for getting the transformed features in each frequency band
        X_tr_transformed_var = np.zeros((len(self.bands), X_tr.shape[0]))

        # Empty array for getting the covariance matrix
        X_tr_transformed_cov = np.zeros((len(self.bands), X_tr.shape[0], X_tr.shape[1], X_tr.shape[1]))
        X_val_transformed_cov = np.zeros((len(self.bands), X_val.shape[0], X_val.shape[1], X_val.shape[1]))
        X_te_transformed_cov = np.zeros((len(self.bands), X_te.shape[0], X_te.shape[1], X_te.shape[1]))

        for id_band, freq_band in enumerate(self.bands):
            print('The process is holding on ID {} and Freq Interval {}'.format(id_band, freq_band))

            X_tr_filtered = butter_bandpass_filter(X_tr, freq_band[0], freq_band[1], self.smp_freq, self.order)
            X_val_filtered = butter_bandpass_filter(X_val, freq_band[0], freq_band[1], self.smp_freq, self.order)
            X_te_filtered = butter_bandpass_filter(X_te, freq_band[0], freq_band[1], self.smp_freq, self.order)

            # Calculating covariance only on training set
            covs, sample_weights =  self.__calculate_covariance_matrices(X_tr_filtered, y_tr)
            spf_sel, spf_org = self.__get_spatial_filter(covs, sample_weights)

            # Calculate the variance of spatially filtered signals and then compute the logarithm in each single EEG trial
            for sample_tr in range(X_tr_filtered.shape[0]):
                X_tr_transformed_var[id_band, sample_tr] = self.__get_log_var_feats(spf_sel, X_tr_filtered[sample_tr,:,:])
                X_tr_transformed_cov[id_band, sample_tr,:,:] = self.get_transformed_feats(spf_org, X_tr_filtered[sample_tr,:,:])

            for sample_val in range(X_val_filtered.shape[0]):
                X_val_transformed_cov[id_band, sample_val,:,:] = self.get_transformed_feats(spf_org, X_val_filtered[sample_val,:,:])

            for sample_te in range(X_te_filtered.shape[0]):
                X_te_transformed_cov[id_band, sample_te,:,:] = self.get_transformed_feats(spf_org, X_te_filtered[sample_te,:,:])

        # Prepare the most suited form of data for rearanging all frequency bands
        X_tr_transformed_var_sw = np.swapaxes(X_tr_transformed_var,0,1)

        # Rearrange all frequency bands from the largest MI value to smallest MI value and pick k frequency bands by considering the most k largest MI values.
        # This procedure considered only traning set obtaning the order of k frequnecy bands that provide the largest MI value.
        selector = SelectKBest(score_func=mutual_info_classif, k=self.n_pick_bands)
        X_tr_picked_band = selector.fit_transform(X_tr_transformed_var_sw, y_tr)
        des_order_list = selector.get_support(indices=True)

        # Display the selected subbands
        for idx_band in des_order_list:
            print('band_name:', self.bands[idx_band] ,'---', 'Index_is:', idx_band)

        X_tr_se_band = np.take(np.swapaxes(X_tr_transformed_cov,0,1), des_order_list, axis=1)
        X_val_se_band = np.take(np.swapaxes(X_val_transformed_cov,0,1), des_order_list, axis=1)
        X_te_se_band = np.take(np.swapaxes(X_te_transformed_cov,0,1), des_order_list, axis=1)
        # All data are in the form of (n_samples,n_subbands,n_components,n_components)
        return X_tr_se_band, X_val_se_band, X_te_se_band


from flask import Flask
from temp.Tests_ex.web_9.tasks.no1_1.data import db_session
from temp.Tests_ex.web_9.tasks.no1_1.data.users import User
from temp.Tests_ex.web_9.tasks.no1_1.data.jobs import Jobs

app = Flask(__name__)
app.config['SECRET_KEY'] = 'yandexlyceum_secret_key'

def main():
    db_session.global_init("db/mars_explorer_1.sqlite")
    # app.run()

    session = db_session.create_session()
    # dictionary of job_id and len of collaboration
    collaborations = {x.id: len(x.collaborators.split())
                      for x in session.query(Jobs).all()}

    max_size = max(collaborations.values())
    # job_id if len collaboration is max
    ids = [x for x in collaborations if collaborations[x] == max_size]

    # teamleader id if job id in ids
    temp = [x.team_leader for x in session.query(Jobs).all() if x.id in ids]

    # result
    teamleaders = session.query(User).filter(User.id.in_(temp)).all()

    for member in teamleaders:
        print(member.name, member.surname)

if __name__ == '__main__':
    main()


import torch

def load_dataset(dataset_name):
    from maskrcnn_benchmark.data.build import build_dataset, import_file

    paths_catalog = import_file(
        "maskrcnn_benchmark.config.paths_catalog", cfg.PATHS_CATALOG, True
    )
    DatasetCatalog = paths_catalog.DatasetCatalog

    dataset = build_dataset((dataset_name, ), transforms=None, dataset_catalog=DatasetCatalog, is_train=False)[0]
    return dataset

if __name__ == '__main__':
    import os, os.path as osp
    import argparse

    from maskrcnn_benchmark.config import cfg
    # from maskrcnn_benchmark.data.datasets import coco
    from maskrcnn_benchmark.engine.inference import evaluate

    parser = argparse.ArgumentParser(
        description="Evaluate predictions from predictions.pth file, COCO format. The predictions.pth"
                    "file is the output of tools/test_net.py. This is usually stored in "
                    "<cfg.OUTPUT_DIR>/inference/<test_dataset>/predictions.pth"
    )
    parser.add_argument(
        "-cfg",
        "--config_file",
        required=True,
        help="path to config file",
        type=str,
    )
    parser.add_argument(
        "-td",
        "--test_dataset",
        help="Name of test dataset, MUST be listed in paths_catalog.py > DatasetCatalog > DATASETS",
        required=True,
        type=str,
    )
    parser.add_argument(
        "-f",
        "--folder",
        help="Folder where predictions.pth is stored. Defaults to <cfg.OUTPUT_DIR>/inference/<test_dataset>",
        default="",
        type=str,
    )

    args = parser.parse_args()

    # inputs
    config_file = args.config_file
    TEST_dataset = args.test_dataset

    # load config
    cfg.merge_from_file(config_file)

    predictions_folder = args.folder
    if len(args.folder) == 0:
        predictions_folder = "%s/inference/%s"%(cfg.OUTPUT_DIR, TEST_dataset)
    predictions_file = osp.join(predictions_folder, "predictions.pth")
    assert osp.exists(predictions_file)

    output_folder = predictions_folder

    # load predictions
    predictions = torch.load(predictions_file)

    # load dataset
    dataset = load_dataset(TEST_dataset)

    include_per_class_results = True
    box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY
    iou_types = ("bbox",)
    if cfg.MODEL.MASK_ON:
        iou_types = iou_types + ("segm",)

    extra_args = dict(
        box_only=box_only,
        iou_types=iou_types,
        expected_results=cfg.TEST.EXPECTED_RESULTS,
        expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,
        include_per_class_results=include_per_class_results
    )

    result = evaluate(dataset=dataset,
                    predictions=predictions,
                    output_folder=output_folder,
                    **extra_args)


import cv2
import numpy as np

def fCanny(frame):
    img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    canny = cv2.Canny(img, 100, 200)
    canny = cv2.cvtColor(canny, cv2.COLOR_BGR2RGB)
    return canny

cap = cv2.VideoCapture('IFMA Campus Caxias.mp4')

while cap.isOpened():
    check, frame = cap.read()
    frame = cv2.resize(frame, (500, 400))
    if check == True:

        output = fCanny(frame)
        cv2.imshow("Canny", output)

        k = cv2.waitKey(20) & 0xFF
        if k == ord('q'):
            break

    else: break

cap.release()
cv2.destroyAllWindows()


# from google.cloud import translate_v2
# translate_client = translate_v2.Client()
import os

# export GOOGLE_APPLICATION_CREDENTIALS="/Users/mtdp/Downloads/tough-bearing-263013-dca7f13b193a.json"

# def translate(text):
#     # Translates some text into Russian
#     translation = translate_client.translate(text, target_language='en')

#     result = translation['translatedText']
#     # 标题，描述，内容以5个#分割
#     res = result.split('#####')
#     print(res)
#     return res

# translate('很好')

def start():
    for files in os.listdir('./articles/61186032861/'):
        print(files)

start()


from usuarios import acciones

hazEl = acciones.Acciones()

hazEl.primetaAcciones()

accion = input("Que quiere hacer?: ")

if accion == "registro" or accion == "r":
    hazEl.registro()

elif accion == "login" or accion == "l":
    hazEl.login()


# List Comprehension
# https://www.w3schools.com/python/python_lists_comprehension.asp

print("Lista de numeros del 1 al 10 multiplicados por 2")
# Forma cotidiana
numbers = []
for element in range(1, 11):
  numbers.append(element * 2)

print(numbers)

# Usando List Comprehension
numbers_v2 = [element * 2 for element in range(1, 11)]
print(numbers_v2)

print("Lista de numeros pares del 1 al 10 multiplicados por 2")
# Forma cotidiana
numbers = []
for i in range(1, 11):
  if i % 2 == 0:
    numbers.append(i * 2)

print(numbers)

# Usando List Comprehension
numbers_v2 = [i * 2 for i in range(1, 11) if i % 2 == 0]
print(numbers_v2)

# Reto
# https://www.hackerrank.com/challenges/list-comprehensions/problem


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from config import get_config
from scipy.stats.mstats import gmean
import matplotlib.ticker as ticker
import math

args = get_config()
correct = pd.read_csv("results//results_true.csv").values[:,2]

# Automatic Solvers
global automatic
automatic = ["Clp", "FICO_Xpress", "GuRoBi", "IBM_CPLEX", "HiGHS", "Mosek", "Tulip"]

# Barrier Solvers - No Crossover
global barrier
barrier = ["FICO_Xpress", "GuRoBi", "IBM_CPLEX", "Mosek", "Tulip"]

# Barrier Solver - Crossover
global c_barrier
c_barrier = ["FICO_Xpress", "GuRoBi", "IBM_CPLEX", "Mosek"]

# Primal Simplex Solvers
global p_simplex
p_simplex = ["Clp", "FICO_Xpress", "GuRoBi", "IBM_CPLEX", "Mosek"]

# Primal Simplex Solvers
global d_simplex
d_simplex = ["Clp", "FICO_Xpress", "GuRoBi", "IBM_CPLEX", "HiGHS", "Mosek"]

global modes
modes = ["Automatic", "Barrier", "Cross_Barrier", "Simplex_dual", "Simplex_primal"]

global labels
labels = {"A": "Automatic", "B": "Interior-Point Method without Crossover","CB": "Interior-Point Method with Crossover",
          "PS": "Primal Simplex", "DS": "Dual Simplex",}

def str2bool(v):
  return v.lower() in ("yes", "true", "t","1")

def matrix_processing (x):

    for index, row in x.iterrows():
        if np.isclose(row["Obj_Value"],correct[index],rtol=1e-02):
            pass
        elif row["Status"] == "Time Limit":
            pass
        else:
            x.loc[index,'Status']= "Fail"

    x = x.drop([0])
    rows = x.values.shape[0]
    report = x["Status"].value_counts()
    optimal = report["Optimal"]/rows

    try:
        time_limit = report["Time Limit"]/rows
    except:
        time_limit = 0

    try:
        fails = report["Fail"]/rows
    except:
        fails = 0

    for i in metrics:
        x.loc[(x.Status == 'Time Limit'),i]= np.inf
        x.loc[(x.Status == 'Fail'),i]= np.inf
        x.loc[(x.Solver_Time == 0),i]= 0.0001
    report = [optimal,time_limit,fails]
    return x,report

def num_status(df):
    b = df.values[:,1]
    for i in range(0,df.shape[0]):
        if b[i] == "Optimal":
            b[i] = 0
        elif b[i] == "Time Limit":
           b[i] = 1
        else:
           b[i] = 2
    df['num_status'] = b
    return df

def assert_opt(df1,df2):
    b = df1.values[:,-1]
    a = df1.values[:,2]
    a = np.array(a, dtype=float)
    for i in range(0,df1.shape[0]):
        if np.isclose(a[i],df2[i],rtol=1e-02):
            pass
        elif b[i] !=0:
            pass
        else:
            b[i] = 2
    df1['num_status'] = b
    return df1

def metric_col(df,metric):

    b = list(range(0,df.shape[0]))
    m = df[metric].values
    for i in range(0,df.shape[0]):
        if df.values[i,-1] == 0:
            b[i] = int(math.ceil(m[i]))
        elif df.values[i,-1] == 1:
            b[i] = 't'
        else:
            b[i] = 'f'

    return b,m

def solved(df,solver):

    try:
        time_limit = df[solver].value_counts().t
    except:
        time_limit = 0

    try:
        fails = df[solver].value_counts().f
    except:
        fails = 0

    opt = df.shape[0] - time_limit - fails

    return [opt, time_limit, fails]

metrics = ["Solver_Time","Julia_Time","Iterations"]

if args.metric in metrics:

    if args.info == "table":

        tot = np.ones((correct.shape[0]-1,1))
        count = 1
        for i in range(args.loops):

            modes = ['Automatic','Barrier','Cross_Barrier','Simplex_dual','Simplex_primal']
            if args.table_mode in modes:

                # Clp
                if args.table_mode != "Barrier" and args.table_mode != "Cross_Barrier":
                    clp = pd.read_csv(f"results//{args.table_mode.lower()}//{args.table_mode}_Clp.csv")
                    clp = num_status(clp)
                    clp = (assert_opt(clp,correct))
                    clp_col = (metric_col(clp,args.metric))[0]
                    clp_it = (metric_col(clp,args.metric))[1]

                # FICO Xpress
                xpress = pd.read_csv(f"results//{args.table_mode.lower()}//{args.table_mode}_FICO_Xpress.csv")
                xpress = num_status(xpress)
                xpress = (assert_opt(xpress,correct))
                xpress_col  = (metric_col(xpress,args.metric))[0]
                xpress_it = (metric_col(xpress,args.metric))[1]

                # GuRoBi
                gurobi = pd.read_csv(f"results//{args.table_mode.lower()}//{args.table_mode}_GuRoBi.csv")
                gurobi = num_status(gurobi)
                gurobi = (assert_opt(gurobi,correct))
                gurobi_col  = (metric_col(gurobi,args.metric))[0]
                gurobi_it = (metric_col(gurobi,args.metric))[1]

                # IBM_CPLEX
                cplex = pd.read_csv(f"results//{args.table_mode.lower()}//{args.table_mode}_IBM_CPLEX.csv")
                cplex = num_status(cplex)
                cplex = (assert_opt(cplex,correct))
                cplex_col  = (metric_col(cplex,args.metric))[0]
                cplex_it = (metric_col(cplex,args.metric))[1]

                # HiGHS
                if args.table_mode != "Barrier" and args.table_mode != "Cross_Barrier" and args.table_mode != "Simplex_primal":
                    highs = pd.read_csv(f"results//{args.table_mode.lower()}//{args.table_mode}_HiGHS.csv")
                    highs = num_status(highs)
                    highs = (assert_opt(highs,correct))
                    highs_col  = (metric_col(highs,args.metric))[0]
                    highs_it = (metric_col(highs,args.metric))[1]

                # Mosek
                mosek = pd.read_csv(f"results//{args.table_mode.lower()}//{args.table_mode}_Mosek.csv")
                mosek = num_status(mosek)
                mosek = (assert_opt(mosek,correct))
                mosek_col = (metric_col(mosek,args.metric))[0]
                mosek_it = (metric_col(mosek,args.metric))[1]

                # Tulip
                if args.table_mode != "Simplex_dual" and args.table_mode != "Cross_Barrier" and args.table_mode != "Simplex_primal":
                    tulip = pd.read_csv(f"results//{args.table_mode.lower()}//{args.table_mode}_Tulip.csv")
                    tulip = num_status(tulip)
                    tulip = (assert_opt(tulip,correct))
                    tulip_col = (metric_col(tulip,args.metric))[0]
                    tulip_it = (metric_col(tulip,args.metric))[1]

                # Cumulative Table
                res_table = pd.DataFrame()
                it_table = pd.DataFrame()

                res_table["Problems"] = gurobi["Problem"]
                it_table["Problems"] = gurobi["Problem"]

                if args.table_mode != "Barrier" and args.table_mode != "Cross_Barrier":
                    res_table["Clp"] = clp_col
                    it_table["Clp"] = clp_it

                res_table["FICO_Xpress"] = xpress_col
                it_table["FICO_Xpress"] = xpress_it
                res_table["GuRoBi"] = gurobi_col
                it_table["GuRoBi"] = gurobi_it
                res_table["IBM_CPLEX"] = cplex_col
                it_table["IBM_CPLEX"] = cplex_it

                if args.table_mode != "Barrier" and args.table_mode != "Cross_Barrier" and args.table_mode != "Simplex_primal":
                    res_table["HiGHS"] = highs_col
                    it_table["HiGHS"] = highs_it

                res_table["Mosek"] = mosek_col
                it_table["Mosek"] = mosek_it

                if args.table_mode != "Simplex_dual" and args.table_mode != "Cross_Barrier" and args.table_mode != "Simplex_primal":
                    res_table["Tulip"] = tulip_col
                    it_table["Tulip"] = tulip_it

                res_table = res_table.drop([0])
                it_table = it_table.drop([0])

                # Status Table
                status = pd.DataFrame()
                status['status'] = ["Optimal","Time Limit","Fail"]

                if args.table_mode != "Barrier" and args.table_mode != "Cross_Barrier":
                    status["Clp"] = solved(res_table,'Clp')

                status["FICO_Xpress"] = solved(res_table,'FICO_Xpress')
                status["GuRoBi"] = solved(res_table,'GuRoBi')
                status["IBM_CPLEX"] = solved(res_table,'IBM_CPLEX')

                if args.table_mode != "Barrier" and args.table_mode != "Cross_Barrier" and args.table_mode != "Simplex_primal":
                    status["HiGHS"] = solved(res_table,'HiGHS')

                status["Mosek"] = solved(res_table,'Mosek')

                if args.table_mode != "Simplex_dual" and args.table_mode != "Cross_Barrier" and args.table_mode != "Simplex_primal":
                    status["Tulip"] = solved(res_table,'Tulip')

                # Geometric Mean

                if args.metric =="Solver_Time":
                    res_mod = res_table.replace(["t","f"], 1800)
                elif args.metric =="Julia_Time":
                    res_mod = res_table.replace("f", 1800)
                    res_mod = res_mod.replace("t", -1)
                else:
                    res_mod = it_table

                if args.metric =="Julia_Time":
                    res_mod = pd.concat([res_mod, it_table]).max(level=0)

                mod_np = res_mod.values[:,1:]
                ones = np.ones((mod_np.shape[0],mod_np.shape[1]))
                mod = (np.maximum(ones,mod_np+10))
                mod = np.array(mod,dtype=float)
                mod = np.log(mod)/res_mod.shape[0]
                unsc_geom_mean = np.exp((np.sum(mod,axis=0)))-10
                sc_geom_mean = unsc_geom_mean/np.min(unsc_geom_mean)
                geom= np.vstack((unsc_geom_mean,sc_geom_mean))

                # Cumulative Status tables
                g = pd.DataFrame()
                g["status"] = ["Unscaled Geometric Mean","Scaled Geometric Mean"]

                if args.table_mode == 'Automatic':
                    g["Clp"] = geom[:,0]
                    g["FICO_Xpress"] = geom[:,1]
                    g["GuRoBi"] = geom[:,2]
                    g["IBM_CPLEX"] = geom[:,3]
                    g["HiGHS"] = geom[:,4]
                    g["Mosek"] = geom[:,5]
                    g["Tulip"] = geom[:,6]

                elif args.table_mode == 'Barrier':
                    g["FICO_Xpress"] = geom[:,0]
                    g["GuRoBi"] = geom[:,1]
                    g["IBM_CPLEX"] = geom[:,2]
                    g["Mosek"] = geom[:,3]
                    g["Tulip"] = geom[:,4]

                elif args.table_mode == 'Cross_Barrier':
                    g["FICO_Xpress"] = geom[:,0]
                    g["GuRoBi"] = geom[:,1]
                    g["IBM_CPLEX"] = geom[:,2]
                    g["Mosek"] = geom[:,3]

                elif args.table_mode == 'Simplex_dual':
                    g["Clp"] = geom[:,0]
                    g["FICO_Xpress"] = geom[:,1]
                    g["GuRoBi"] = geom[:,2]
                    g["IBM_CPLEX"] = geom[:,3]
                    g["HiGHS"] = geom[:,4]
                    g["Mosek"] = geom[:,5]

                elif args.table_mode == 'Simplex_primal':
                    g["Clp"] = geom[:,0]
                    g["FICO_Xpress"] = geom[:,1]
                    g["GuRoBi"] = geom[:,2]
                    g["IBM_CPLEX"] = geom[:,3]
                    g["Mosek"] = geom[:,4]

                status = pd.concat([g, status], sort=False)

                status.to_csv(f'tables//{args.table_mode}_{args.metric}_stats.csv', index=False)
                print(status)
                res_table.to_csv(f'tables//{args.table_mode}_{args.metric}_results.csv', index=False)
                print(res_table)
                tot=np.hstack([tot,res_mod.values[:,1:]])

                if count < args.loops:
                    print(f"State mode for loop {i+1}. Choices : ( Automatic, Barrier , Cross_Barrier , Simplex_dual , Simplex_primal")
                    mode = input()
                    args.table_mode = mode

                if count == args.loops and count!= 1:
                    tot = tot[:,1:]
                    minims = (np.argmin(tot, axis=1))
                    best_alg = []
                    for i in minims:
                        if i < 11:
                            best_alg.append("any_simplex")
                        else:
                            best_alg.append("IPM")
                    print(best_alg.count("any_simplex"))
                    print(minims)
                    print(tot)
                    break

                count+=1

            else:
                print("Wrong keyword for table mode. Check help. Exiting")

    elif args.info == "profile":

        if args.profile_mode == "by_Solver":

            print("State solver to be assessed. Choices : ( Clp , FICO_Xpress , GuRoBi , IBM_CPLEX , HiGHS , Mosek , Tulip ")

            while True:

                x = input()

                if x in automatic:
                    break
                else:
                    print("Wrong Input - Try Again")

            count = 0
            available = []
            if x in automatic:
                count += 1
                available.append("A")

            if x in barrier:
                count += 1
                available.append("B")

            if x in c_barrier:
                count += 1
                available.append("CB")

            if x in p_simplex:
                count += 1
                available.append("PS")

            if x in d_simplex:
                count += 1
                available.append("DS")

            solver = x
            print(f"State number of algorithms for comparison. Maximum algorithms for {solver} are {count}.")

            while True:

                x = input()

                try:
                    if int(x) > count:
                        print("More algorithms than supported: Try again")
                    elif int(x)<=1:
                        print("At least two algorithms must be selected.")
                    else:
                        break
                except:
                    print("Input must be numerical.")
                    pass

            if int(x) == count:
                print("All algorithms were selected.")
                selected = available
            else:

                print(f"Select {x} algorithms. Available algorithms are:")

                if solver in automatic:
                    print("Automatic: keyword 'A'")

                if solver in barrier:
                    print("Barrier - No Crossover: keyword  'B'")

                if solver in c_barrier:
                    print("Barrier - With Crossover: keyword 'CB'")

                if solver in p_simplex:
                    print("Primal Simplex: keyword  'PS'")

                if solver in d_simplex:
                    print("Dual Simplex: keyword  'DS'")

                selected = []
                for i in range (0,int(x)):

                    while True:
                        print(f"Algorithm no.{i+1}")
                        print("Type keywords of algorithms that to be examined.")
                        y = input()

                        if y in available and y not in selected:
                            selected.append(y)
                            break
                        else:
                            print("Wrong Input. Keyword was wrong, already selected or not available.")

            matrix = np.zeros([35,])
            success = np.zeros([3,])

            if "A" in selected:

                automatic = pd.read_csv(f"results\\automatic\\Automatic_{solver}.csv")
                automatic_res = matrix_processing(automatic)[0][args.metric]
                automatic_rep = matrix_processing(automatic)[1]
                matrix = np.vstack((matrix,automatic_res))
                success = np.vstack((success,automatic_rep))

            if "B" in selected:
                barrier = pd.read_csv(f"results\\barrier\\Barrier_{solver}.csv")
                barrier_res = matrix_processing(barrier)[0][args.metric]
                barrier_rep = matrix_processing(barrier)[1]
                matrix = np.vstack((matrix,barrier_res))
                success = np.vstack((success,barrier_rep))

            if "CB" in selected:
                cross_barrier = pd.read_csv(f"results\\cross_barrier\\Cross_Barrier_{solver}.csv")
                cross_barrier_res = matrix_processing(cross_barrier)[0][args.metric]
                cross_barrier_rep = matrix_processing(cross_barrier)[1]
                matrix = np.vstack((matrix,cross_barrier_res))
                success = np.vstack((success,cross_barrier_rep))

            if "DS" in selected:
                d_simplex = pd.read_csv(f"results\\simplex_dual\\Simplex_dual_{solver}.csv")
                d_simplex_res = matrix_processing(d_simplex)[0][args.metric]
                d_simplex_rep = matrix_processing(d_simplex)[1]
                matrix = np.vstack((matrix,d_simplex_res))
                success = np.vstack((success,d_simplex_rep))

            if "PS" in selected:
                p_simplex = pd.read_csv(f"results\\simplex_primal\\Simplex_primal_{solver}.csv")
                p_simplex_res = matrix_processing(p_simplex)[0][args.metric]
                p_simplex_rep = matrix_processing(p_simplex)[1]
                matrix = np.vstack((matrix,p_simplex_res))
                success = np.vstack((success,p_simplex_rep))

            matrix = matrix.T[:,1:]
            success = 100*success[1:,:]

            best_in_row = (np.amin(matrix,1))

            ratio = np.zeros((matrix.shape[0],matrix.shape[1]))
            for i in range(0,matrix.shape[0]):
                for j in range(0,matrix.shape[1]):
                    ratio[i][j] = matrix[i][j]/best_in_row[i]

            t = np.arange(1,float(args.tau),float(args.tau)/3000)

            prob_t = np.zeros((ratio.shape[0],ratio.shape[1],t.shape[0]))
            prob_s = np.zeros((ratio.shape[1],t.shape[0]))
            for j in range(0,ratio.shape[1]):
                for k in range(0,t.shape[0]):
                    for i in range(0,ratio.shape[0]):
                        if ratio[i][j]<=t[k]:
                            prob_t[i][j][k] = 1
                    prob_s[j][k] = np.sum(prob_t[:,j,k])/ratio.shape[0]

            fig, ax = plt.subplots()
            ax.grid()

            selected = sorted(selected, key=str.lower)
            ax.plot(t, (prob_s[0,:]),label=labels[selected[0]])
            ax.plot(t, (prob_s[1,:]),label=labels[selected[1]])

            if len(selected) >=3:
                ax.plot(t, (prob_s[2,:]),label=labels[selected[2]])

            if len(selected) >=4:
                ax.plot(t,  (prob_s[3,:]),label=labels[selected[3]])

            if len(selected) >=5:
                ax.plot(t, (prob_s[4,:]),label=labels[selected[4]])

            if str2bool(args.log_scale):
                ax.set_xscale('log')
                plt.xscale('log',base=2)
                ax.xaxis.set_major_formatter(ticker.ScalarFormatter())

            if solver == "IBM_CPLEX":
                solver = "CPLEX"

            if solver == "FICO_Xpress":
                solver = "Xpress"

            if args.metric != "Iterations":
                x = args.metric.split("_")

                ax.set(xlabel='tau', ylabel='Fraction of problems',
                    title=f"Performance Profile of {solver} - Measure {x[0]} {x[1]}")

                plt.legend(framealpha=1)
                plt.show()
            else:

                ax.set(xlabel='tau', ylabel='Fraction of problems',
                    title=f"Performance Profile of {solver} - Measure {args.metric}")
                plt.legend(framealpha=1)
                plt.show()

        elif args.profile_mode == "by_Mode":

            print("State mode to be assessed. Choices : ( Automatic, Barrier , Cross_Barrier , Simplex_dual , Simplex_primal")

            while True:

                x = input()

                if x in modes:
                    break
                else:
                    print("Wrong Input - Try Again")

            if x == "Automatic":
                available = automatic

            elif x == "Barrier":
                available = barrier

            elif x == "Cross_Barrier":
                available = c_barrier

            elif x == "Simplex_dual":
                available = d_simplex

            elif x == "Simplex_primal":
                available = p_simplex

            count = len(available)
            mode = x
            print(f"State number of solvers for comparison. Maximum solver for {mode} are {count}.")

            while True:

                x = input()

                try:
                    if int(x) > count:
                        print("More solvers than supported: Try again")
                    elif int(x)<=1:
                        print("At least two solvers must be selected.")
                    else:
                        break
                except:
                    print("Input must be numerical.")
                    pass

            if int(x) == count:
                print("All solvers were selected.")
                selected = available
            else:

                print(f"Select {x} solvers. Available solvers are:")

                for i in available:
                    print(i)

                selected = []
                for i in range (0,int(x)):

                    while True:
                        print(f"Algorithm no.{i+1}")
                        print("Type name of algorithm as stated above.")
                        y = input()

                        if y in available and y not in selected:
                            selected.append(y)
                            break
                        else:
                            print("Wrong Input. Keyword was wrong, already selected or not available.")

            matrix = np.zeros([35,])
            success = np.zeros([3,])

            if "Clp" in selected:

                clp = pd.read_csv(f"results\\{mode.lower()}\\{mode}_Clp.csv")
                clp_res = matrix_processing(clp)[0][args.metric]
                clp_rep = matrix_processing(clp)[1]
                matrix = np.vstack((matrix,clp_res))
                success = np.vstack((success,clp_rep))

            if "FICO_Xpress" in selected:

                fico_xpress = pd.read_csv(f"results\\{mode.lower()}\\{mode}_FICO_Xpress.csv")
                fico_xpress_res = matrix_processing(fico_xpress)[0][args.metric]
                fico_xpress_rep = matrix_processing(fico_xpress)[1]
                matrix = np.vstack((matrix,fico_xpress_res))
                success = np.vstack((success,fico_xpress_rep))

            if "GuRoBi" in selected:

                gurobi = pd.read_csv(f"results\\{mode.lower()}\\{mode}_GuRoBi.csv")
                gurobi_res = matrix_processing(gurobi)[0][args.metric]
                gurobi_rep = matrix_processing(gurobi)[1]
                matrix = np.vstack((matrix,gurobi_res))
                success = np.vstack((success,gurobi_rep))

            if "HiGHS" in selected:

                highs = pd.read_csv(f"results\\{mode.lower()}\\{mode}_HiGHS.csv")
                highs_res = matrix_processing(highs)[0][args.metric]
                highs_rep = matrix_processing(highs)[1]
                matrix = np.vstack((matrix,highs_res))
                success = np.vstack((success,highs_rep))

            if "IBM_CPLEX" in selected:

                ibm_cplex = pd.read_csv(f"results\\{mode.lower()}\\{mode}_IBM_CPLEX.csv")
                ibm_cplex_res = matrix_processing(ibm_cplex)[0][args.metric]
                ibm_cplex_rep = matrix_processing(ibm_cplex)[1]
                matrix = np.vstack((matrix,ibm_cplex_res))
                success = np.vstack((success,ibm_cplex_rep))

            if "Mosek" in selected:

                mosek = pd.read_csv(f"results\\{mode.lower()}\\{mode}_Mosek.csv")
                mosek_res = matrix_processing(mosek)[0][args.metric]
                mosek_rep = matrix_processing(mosek)[1]
                matrix = np.vstack((matrix,mosek_res))
                success = np.vstack((success,mosek_rep))

            if "Tulip" in selected:

                tulip = pd.read_csv(f"results\\{mode.lower()}\\{mode}_Tulip.csv")
                tulip_res = matrix_processing(tulip)[0][args.metric]
                tulip_rep = matrix_processing(tulip)[1]
                matrix = np.vstack((matrix,tulip_res))
                success = np.vstack((success,tulip_rep))

            matrix = matrix.T[:,1:]
            success = 100*success[1:,:]

            best_in_row = (np.amin(matrix,1))

            ratio = np.zeros((matrix.shape[0],matrix.shape[1]))
            for i in range(0,matrix.shape[0]):
                for j in range(0,matrix.shape[1]):
                    ratio[i][j] = matrix[i][j]/best_in_row[i]

            t = np.arange(1,float(args.tau),float(args.tau)/3000)

            prob_t = np.zeros((ratio.shape[0],ratio.shape[1],t.shape[0]))
            prob_s = np.zeros((ratio.shape[1],t.shape[0]))
            for j in range(0,ratio.shape[1]):
                for k in range(0,t.shape[0]):
                    for i in range(0,ratio.shape[0]):
                        if ratio[i][j]<=t[k]:
                            prob_t[i][j][k] = 1
                    prob_s[j][k] = np.sum(prob_t[:,j,k])/ratio.shape[0]

            fig, ax = plt.subplots()
            ax.grid()

            selected = sorted(selected, key=str.lower)

            for n, i in enumerate(selected):
                if i == "FICO_Xpress":
                    selected[n] = "Xpress"
                if i == "IBM_CPLEX":
                    selected[n] = "CPLEX"

            ax.plot(t, prob_s[0,:],label=selected[0])
            ax.plot((t), prob_s[1,:],label=selected[1])

            if len(selected) >=3:
                ax.plot((t), prob_s[2,:],label=selected[2])

            if len(selected) >=4:
                ax.plot((t),  prob_s[3,:],label=selected[3])

            if len(selected) >=5:
                ax.plot((t), prob_s[4,:],label=selected[4])

            if len(selected) >=6:
                ax.plot((t),  prob_s[5,:],label=selected[5])

            if len(selected) >=7:
                ax.plot((t), prob_s[6,:],label=selected[6])

            if str2bool(args.log_scale):
                ax.set_xscale('log')
                plt.xscale('log',base=2)

                ax.xaxis.set_major_formatter(ticker.ScalarFormatter())

            if mode == "Simplex_dual":
                mode = "Dual Simplex"

            if mode == "Simplex_primal":
                mode = "Primal Simplex"

            if mode == "Cross_Barrier":
                mode = "Interior-Point Method with Crossover"

            if mode == "Barrier":
                mode = "Interior-Point Method without Crossover"

            if args.metric != "Iterations":
                x = args.metric.split("_")

                ax.set(xlabel='tau', ylabel='Fraction of problems',
                    title=f"Performance Profile of {mode} - Measure {x[0]} {x[1]}")

                plt.legend(framealpha=1)
                plt.show()
            else:

                ax.set(xlabel='tau', ylabel='Fraction of problems',
                    title=f"Performance Profile of {mode} - Measure {args.metric}")

                plt.legend(framealpha=1)
                plt.show()

        else:
            print("Wrong Profile Mode. Check help. Exiting")

    elif args.info == "chart":

        modes = ['Automatic','Barrier','Cross_Barrier','Simplex_dual','Simplex_primal']
        if args.chart_mode in modes:

            # Clp
            if args.chart_mode != "Barrier" and args.chart_mode != "Cross_Barrier":
                clp = pd.read_csv(f"results//{args.chart_mode.lower()}//{args.chart_mode}_Clp.csv")
                clp = num_status(clp)
                clp = (assert_opt(clp,correct))
                clp_col = (metric_col(clp,args.metric))[0]
                clp_it = (metric_col(clp,args.metric))[1]

            # FICO Xpress
            xpress = pd.read_csv(f"results//{args.chart_mode.lower()}//{args.chart_mode}_FICO_Xpress.csv")
            xpress = num_status(xpress)
            xpress = (assert_opt(xpress,correct))
            xpress_col  = (metric_col(xpress,args.metric))[0]
            xpress_it = (metric_col(xpress,args.metric))[1]

            # GuRoBi
            gurobi = pd.read_csv(f"results//{args.chart_mode.lower()}//{args.chart_mode}_GuRoBi.csv")
            gurobi = num_status(gurobi)
            gurobi = (assert_opt(gurobi,correct))
            gurobi_col  = (metric_col(gurobi,args.metric))[0]
            gurobi_it = (metric_col(gurobi,args.metric))[1]

            # IBM_CPLEX
            cplex = pd.read_csv(f"results//{args.chart_mode.lower()}//{args.chart_mode}_IBM_CPLEX.csv")
            cplex = num_status(cplex)
            cplex = (assert_opt(cplex,correct))
            cplex_col  = (metric_col(cplex,args.metric))[0]
            cplex_it = (metric_col(cplex,args.metric))[1]

            # HiGHS
            if args.chart_mode != "Barrier" and args.chart_mode != "Cross_Barrier" and args.chart_mode != "Simplex_primal":
                highs = pd.read_csv(f"results//{args.chart_mode.lower()}//{args.chart_mode}_HiGHS.csv")
                highs = num_status(highs)
                highs = (assert_opt(highs,correct))
                highs_col  = (metric_col(highs,args.metric))[0]
                highs_it = (metric_col(highs,args.metric))[1]

            # Mosek
            mosek = pd.read_csv(f"results//{args.chart_mode.lower()}//{args.chart_mode}_Mosek.csv")
            mosek = num_status(mosek)
            mosek = (assert_opt(mosek,correct))
            mosek_col = (metric_col(mosek,args.metric))[0]
            mosek_it = (metric_col(mosek,args.metric))[1]

            # Tulip
            if args.chart_mode != "Simplex_dual" and args.chart_mode != "Cross_Barrier" and args.chart_mode != "Simplex_primal":
                tulip = pd.read_csv(f"results//{args.chart_mode.lower()}//{args.chart_mode}_Tulip.csv")
                tulip = num_status(tulip)
                tulip = (assert_opt(tulip,correct))
                tulip_col = (metric_col(tulip,args.metric))[0]
                tulip_it = (metric_col(tulip,args.metric))[1]

            # Cumulative Table
            res_table = pd.DataFrame()
            it_table = pd.DataFrame()

            res_table["Problems"] = gurobi["Problem"]
            it_table["Problems"] = gurobi["Problem"]

            if args.chart_mode != "Barrier" and args.chart_mode != "Cross_Barrier":
                res_table["Clp"] = clp_col
                it_table["Clp"] = clp_it

            res_table["FICO_Xpress"] = xpress_col
            it_table["FICO_Xpress"] = xpress_it
            res_table["GuRoBi"] = gurobi_col
            it_table["GuRoBi"] = gurobi_it
            res_table["IBM_CPLEX"] = cplex_col
            it_table["IBM_CPLEX"] = cplex_it

            if args.chart_mode != "Barrier" and args.chart_mode != "Cross_Barrier" and args.chart_mode != "Simplex_primal":
                res_table["HiGHS"] = highs_col
                it_table["HiGHS"] = highs_it

            res_table["Mosek"] = mosek_col
            it_table["Mosek"] = mosek_it

            if args.chart_mode != "Simplex_dual" and args.chart_mode != "Cross_Barrier" and args.chart_mode != "Simplex_primal":
                res_table["Tulip"] = tulip_col
                it_table["Tulip"] = tulip_it

            res_table = res_table.drop([0])
            it_table = it_table.drop([0])

            if args.metric!="Iterations":
                res_mod = res_table.replace(["t","f","i",'e'], 1800)
            else:
                res_mod = it_table

            res_mod['Gmean'] = gmean(res_mod.iloc[:,1:],axis=1)

            best = (res_mod.min(axis=1))

            avg = (res_mod['Gmean'].values)

            print(f"State solver for comparison to the baseline.")

            while True:
                x = input()

                if x in res_mod.columns[1:]:
                    break
                else:
                    print(f"Solver not available in this mode or wrong entry. Try again.")

            examined = res_mod[x].values

            t = np.arange(res_mod.values.shape[0])
            fig, ax = plt.subplots()
            ax.plot(t, best,label="Best")
            ax.plot(t, examined,label=f"{x}")
            ax.plot(t, avg,label="Average (Geometric Mean) ")

            ax.grid()
            ax.set_xticks(t)
            ax.set_xticklabels(res_table['Problems'],fontsize = 7,rotation = 60)

            if args.chart_mode == "Automatic":
                mode = "Automatic"

            if args.chart_mode == "Simplex_dual":
                mode = "Dual Simplex"

            if args.chart_mode == "Simplex_primal":
                mode = "Primal Simplex"

            if args.chart_mode == "Cross_Barrier":
                mode = "Interior-Point Method with Crossover"

            if args.chart_mode == "Barrier":
                mode = "Interior-Point Method without Crossover"

            if args.metric != "Iterations":
                x = args.metric.split("_")

                ax.set(xlabel='Problem', ylabel=f'{x[0]} {x[1]}',
                title=f'Graph Chart of {mode} - Measure {x[0]} {x[1]}')

            else:

                ax.set(xlabel='Problem', ylabel=f'{args.metric}',
                title=f'Graph Chart of {args.chart_mode} - Measure {args.metric}')

            plt.legend(framealpha=1)
            plt.show()

    else:
        print("Wrong Information. Check help. Exiting")

else:
    print("Wrong Metric. Check help. Exiting")


import click
from flask import Blueprint

from pcapi.core import search
import pcapi.core.offers.api as offers_api
from pcapi.scripts.algolia_indexing.indexing import batch_indexing_offers_in_algolia_from_database

blueprint = Blueprint(__name__, __name__)

@blueprint.cli.command("process_offers")
def process_offers():
    search.index_offers_in_queue(stop_only_when_empty=True)

@blueprint.cli.command("process_offers_by_venue")
def process_offers_by_venue():
    search.index_offers_of_venues_in_queue()

@blueprint.cli.command("process_offers_from_database")
@click.option("--clear", help="Clear search index", type=bool, default=False)
@click.option("-ep", "--ending-page", help="Ending page for indexing offers", type=int, default=None)
@click.option("-l", "--limit", help="Number of offers per page", type=int, default=10_000)
@click.option("-sp", "--starting-page", help="Starting page for indexing offers", type=int, default=0)
def process_offers_from_database(
    clear: bool,
    ending_page: int,
    limit: int,
    starting_page: int,
):
    if clear:
        search.unindex_all_offers()
    batch_indexing_offers_in_algolia_from_database(ending_page=ending_page, limit=limit, starting_page=starting_page)

@blueprint.cli.command("process_expired_offers")
@click.option("-a", "--all", help="Bypass the two days limit to delete all expired offers", default=False)
def process_expired_offers(all_offers: bool):
    offers_api.unindex_expired_offers(process_all_expired=all_offers)


from django.test import SimpleTestCase
from django.urls import reverse,resolve
from Users.views import register, userissues

class TestUrls(SimpleTestCase):

    def test_register_url_is_resolved(self):
        url = reverse('register')
        self.assertEquals(resolve(url).func,register)

    def test_userissues_url_is_resolved(self):
        url = reverse('user-issues')
        self.assertEquals(resolve(url).func,userissues)


#Problem 1. Sort With Quicksort.
# Please build a function called "quicksort" that uses recursion to define the quicksort algorithm for a list of any length.
# Build a main script that reads in the list provided, "numbers.txt", and runs it through your quicksort algorithm.
# The main script should return the finished sorted list as "sorted.txt"
# All 3 files "In_class_assignment_5.py", "numbers.txt", and "sorted.txt" should all be added to your github repository and submitted as a github link.

'''Info on Quicksort Algorithm:
The Quicksort algorithm is an efficient sorting algorithm developed by British computer scientist Tony Hoare in 1959.

Quicksort is a divide-and-conquer algorithm. Suppose you have a list of objects to sort. You start by choosing an item in the list, called the *pivot item*.
This can be any item in the list. You then partition the list into two sublists based on the pivot item and recursively sort the sublists.

The steps of the algorithm are as follows:

1. Choose the pivot item.
2. Partition the list into two sublists:
        Those items that are less than the pivot item
        Those items that are greater than the pivot item
3. Quicksort the sublists recursively.
4. Each partitioning produces smaller sublists, so the algorithm is reductive.

The base cases occur when the sublists are either empty or have one element, as these are inherently sorted.
 '''

"""
Sources:
    https://www.geeksforgeeks.org/quick-sort/
    https://www.youtube.com/watch?v=kFeXwkgnQ9U&ab_channel=DerrickSherrill
"""
def quicksort(numbers_in_a_list):
    less = [] #Empty sublsits to sort integers less than or greater than pivot item.
    greater = []
    if len(numbers_in_a_list) <= 1: #Base case occurs here when sublists are either 1 or 0.
        return numbers_in_a_list
    else:
        pivot = numbers_in_a_list.pop() #Removes element from list.
    for number in numbers_in_a_list: #Appends number into correct corresponding sublist.
        if number < pivot:
            less.append(number)
        else:
            greater.append(number)
    return quicksort(less) + [pivot] + quicksort(greater) #Returns one large list containing all elements from both sublists including pivot in the middle.

def main():
    with open("numbers.txt") as fin: #Opens numbers.txt file, takes in as string, converts string to list.
        string_list = fin.read()
        empty_list = string_list.split(",")
    sorted_list = quicksort(empty_list) #Creates new list, sorted_list, by running empty_list through quicksort function.
    with open("sorted.txt", "w") as fout: #Creates new file sorted.txt and writes in sorted_list.
        fout.write(str(sorted_list))
    return quicksort(sorted_list)

if __name__ == "__main__":
    main()


import os
import h5py
import pyBigWig
import numpy as np
import tqdm
import click

def fetch_bigwig_paths(base_path, tf_name, tf_cont_mapping_path):
    """
    Reads in the set of BigWig paths corresponding to TF-ChIPseq profiles and
    control profiles. These BigWigs should be generated by
    `generate_ENCODE_profile_labels.sh`. This function performs error-checking
    to ensure that the proper files are there under `base_path`.
    Arguments:
        `base_path`: path containing the BigWig profiles
        `tf_name`: name of the TF (i.e. the profiles for the TF-ChIPseq runs
            should start with this name)
        `tf_cont_mapping_path`: path to TSV mapping TF-ChIPseq experiment IDs
            to their matched control ChIPseq experiment IDs
    Returns a list of pairs, where each pair is the BigWig tracks for the
    negative and positive strands (in that order). The first half of this
    list-of-pairs is for the TF-ChIPseq profiles, and the second half are the
    corresponding control profiles. The BigWigs are ordered such that the
    TF-ChIPseq experiment IDs are in sorted order, and the control experiment
    IDs are in a parallel matched order.
    """
    tf_cont_mapping = {}
    with open(tf_cont_mapping_path, "r") as f:
        for line in f:
            tokens = line.strip().split("\t")
            tf_cont_mapping[tokens[0]] = tokens[1]  # Map TF ID to control ID

    bigwig_list = [
        item for item in os.listdir(base_path) if item.endswith(".bw")
    ]

    # Read in names, organizing into
    # tf_name/control : experiment/cell line : strand
    bigwig_dict = {}
    for name in bigwig_list:
        tokens = name[:-3].split("_")
        assert len(tokens) == 4, \
            "Found BigWig of improperly formatted name: %s" % name
        cond = tokens[0]
        expid_cline = (tokens[1], tokens[2])
        strand = tokens[3]
        assert cond in (tf_name, "control"), \
            "Found BigWig not of type %s or control" % tf_name
        assert strand in ("neg", "pos"), "Found BigWig of strand other than pos/neg"

        if cond not in bigwig_dict:
            bigwig_dict[cond] = {}
        if expid_cline not in bigwig_dict[cond]:
            bigwig_dict[cond][expid_cline] = {}
        assert strand not in bigwig_dict[cond][expid_cline], \
            "Found duplicate BigWig for %s, %s, %s" % \
            (cond, expid_cline, strand)
        bigwig_dict[cond][expid_cline][strand] = os.path.join(base_path, name)

    # Verify that the expected conditions, experiments/cell lines, and strands
    # are all present
    assert sorted(bigwig_dict.keys()) == sorted([tf_name, "control"]), \
        "Did not find tracks for both %s and control" % tf_name

    tf_clines = sorted([pair[1] for pair in bigwig_dict[tf_name].keys()])
    cont_clines = sorted([pair[1] for pair in bigwig_dict["control"].keys()])
    assert tf_clines == cont_clines, \
        "Did not have same cell lines for %s and control" %  tf_name

    for cond, cond_dict in bigwig_dict.items():
        for expid_cline, expid_cline_dict in cond_dict.items():
            assert sorted(expid_cline_dict.keys()) == ["neg", "pos"], \
                "Did not find both strands for %s, %s" % (cond, expid_cline)

    # Reformat dictionary into list of pairs
    paths = []
    tf_expids = []
    for expid_cline in sorted(bigwig_dict[tf_name].keys(), key=lambda p: p[0]):
        expid = expid_cline[0]
        assert expid in tf_cont_mapping.keys(), \
            "Did not find %s as TF-ChIPseq experiment in mapping" % expid
        strand_dict = bigwig_dict[tf_name][expid_cline]
        paths.append([strand_dict["neg"], strand_dict["pos"]])
        tf_expids.append(expid)
    assert len(tf_expids) == len(set(tf_expids)), \
        "Found duplicate TF-ChIPseq experiment IDs"
    for tf_expid in tf_expids:
        try:
            cont_expid = tf_cont_mapping[tf_expid]
        except KeyError:
            raise ValueError("Did not find mapped control for %s" % tf_expid)
        expid_cline = [
            key for key in bigwig_dict["control"] if key[0] == cont_expid
        ]
        assert len(expid_cline) == 1, \
            "Did not find exactly 1 experiment for mapped control %s" % \
            cont_expid
        strand_dict = bigwig_dict["control"][expid_cline[0]]
        paths.append([strand_dict["neg"], strand_dict["pos"]])

    return paths

def create_hdf5(
    bigwig_paths, chrom_sizes_path, out_path, chunk_size, batch_size=100
):
    """
    Creates an HDF5 file containing all BigWig tracks.
    Arguments:
        `bigwig_paths`: a list of pairs of paths, as returned by
            `fetch_bigwig_paths`
        `chrom_sizes_path`: path to canonical chromosome sizes
        `out_path`: where to write the HDF5
        `chunk_size`: chunk size to use in HDF5 along the chromosome size
            dimension; this is recommended to be the expected size of the
            queries made
        `batch_size`: number of chunks to write at a time
    This creates an HDF5 file, containing a dataset for each chromosome. Each
    dataset will be a large array of shape L x 2T x 2, where L is the length of
    the chromosome, T is the number of tasks (i.e. T experiment/cell lines, one
    for each TF and one for matched control), 2 is for both strands. The HDF5
    will also contain a dataset which has the paths to the corresponding source
    BigWigs, stored as a 2T x 2 array of paths.
    """
    bigwig_readers = [
        [pyBigWig.open(path1), pyBigWig.open(path2)]
        for path1, path2 in bigwig_paths
    ]

    # Read in chromosome sizes
    with open(chrom_sizes_path, "r") as f:
        chrom_sizes = {}
        for line in f:
            tokens = line.strip().split("\t")
            chrom_sizes[tokens[0]] = int(tokens[1])

    # Convert batch size to be in terms of rows, not number of chunks
    batch_size = batch_size * chunk_size

    with h5py.File(out_path, "w") as f:
        # Store source paths
        f.create_dataset("bigwig_paths", data=np.array(bigwig_paths, dtype="S"))
        for chrom in sorted(chrom_sizes.keys()):
            chrom_size = chrom_sizes[chrom]
            num_batches = int(np.ceil(chrom_size / batch_size))
            chrom_dset = f.create_dataset(
                chrom, (chrom_size, len(bigwig_paths), 2), dtype="f",
                compression="gzip", chunks=(chunk_size, len(bigwig_paths), 2)
            )
            for i in tqdm.trange(num_batches, desc=chrom):
                start = i * batch_size
                end = min(chrom_size, (i + 1) * batch_size)

                values = np.stack([
                    np.stack([
                        np.nan_to_num(reader1.values(chrom, start, end)),
                        np.nan_to_num(reader2.values(chrom, start, end))
                    ], axis=1) for reader1, reader2 in bigwig_readers
                ], axis=1)

                chrom_dset[start : end] = values

@click.command()
@click.option(
    "--tf-name", "-t", required=True,
    help="Name of TF, needs to match prefix of TF-ChIPseq BigWig files"
)
@click.option(
    "--base-path", "-b", default=None,
    help="Path to directory containing BigWigs; defaults to /users/amtseng/att_priors/data/interim/ENCODE_TFChIP/profile/{tf_name}/"
)
@click.option(
    "--tf-cont-mapping-path", "-m", default=None,
    help="Path to mapping between TF-ChIPseq and control ChIPseq experiment IDs; defaults to /users/amtseng/att_priors/data/raw/ENCODE_TFChIP/{tf_name}/tf_cont_mapping.tsv"
)
@click.option(
    "--chrom-sizes-path", "-c",
    default="/users/amtseng/genomes/hg38.canon.chrom.sizes",
    help="Path to canonical chromosome sizes"
)
@click.option(
    "--out-path", "-o", default=None,
    help="Destination for new HDF5; defaults to /users/amtseng/att_priors/data/processed/ENCODE_TFChIP/profile/labels/{tf_name}/{tf_name}_profiles.h5"
)
@click.option(
    "--chunk-size", "-s", default=1500,
    help="Chunk size along chromosome length dimension for HDF5"
)
def main(
    tf_name, base_path, tf_cont_mapping_path, chrom_sizes_path, out_path,
    chunk_size
):
    """
    Converts TF-ChIPseq and control ChIPseq profile BigWigs into an HDF5 file.
    HDF5 has separate datasets for each chromosome. Each chromosome's dataset
    is stored as an L x 2T x 2 array, where L is the size of the chromosome,
    T is the number of matched experiments (i.e. tasks), and 2 is for each
    strand. The dataset under the key `bigwig_paths` stores the paths for the
    source BigWigs.
    """
    if not base_path:
        base_path = "/users/amtseng/att_priors/data/interim/ENCODE_TFChIP/profile/%s" % tf_name
    if not tf_cont_mapping_path:
        tf_cont_mapping_path = \
            "/users/amtseng/att_priors/data/raw/ENCODE_TFChIP/%s/tf_cont_mapping.tsv" % tf_name
    if not out_path:
        out_path = \
            "/users/amtseng/att_priors/data/processed/ENCODE_TFChIP/profile/labels/%s/%s_profiles.h5" % (tf_name, tf_name)

    bigwig_paths = fetch_bigwig_paths(base_path, tf_name, tf_cont_mapping_path)
    print("Found %d matched experiments/tasks" % (len(bigwig_paths) // 2))
    create_hdf5(bigwig_paths, chrom_sizes_path, out_path, chunk_size)

if __name__ == "__main__":
    main()


import json
from account.bl.user import User
from libservice.base.entity import Entity
from account.api.session_schema import SessionResourceSchema
from libservice.base.meta_info import MetaResource
from libservice.base.service import ServiceException
from falcon.status_codes import (HTTP_200, HTTP_201)

class SessionResource(object):
    """
    :description:
        User session management

    :title:
        Account and Session
    """
    def __init__(self):
        self._token_payload = None
        self.input_body_POST = SessionResourceSchema.get_request_schema("POST")
        MetaResource.add_meta_resource(__class__.__name__, "POST", self.input_body_POST)

    def on_post(self, req, resp):
        """
        :description:
            Login to user session

        :title:
            Login

        :input_body::

            {
                "type": "object",
                "properties": {
                    "email": {
                        "type": "string",
                        "description": "The user’s registered account email address"
                    },
                    "password": {
                        "type": "string",
                        "description": "The user’s password"
                    }
                },
                "required": ["email", "password"]
            }

        :output_body::

            {
                "type": "object",
                "properties": {
                    "auth_token": {
                        "type": "string",
                        "description": "The user authentication token"
                    }
                },
                "required": ["auth_token"]
            }

        """

        # Extract the 'body' from the request
        entity = Entity(req.context['body'])

        # Make sure the entity has all required fields
        entity.add_member('login', entity['email'])

        if entity['email'] == "":
            i = 0
        else:
            i = 0

        # Process the request
        auth_token, self._token_payload = User.generate_token_from_credential(entity['login'], entity['password'])

        if not auth_token:
            raise ServiceException('USER_INVALID_CREDENTIALS_TOKEN', "Invalid credentials", "Token generation failed")

        # Fill the response
        resp.status = HTTP_200
        resp.body = json.dumps({'auth_token': auth_token})


import include
import item_list
from hero import PC_HERO

item_type_dict = {
    "key":"Klucz",
    "weapon":"Broń",
    "armor":"Zbroja",
    "miscelanous":"Różne",
    "food":"Żywność",
    "book":"Słowo Pisane"
}

def showinv():
    item_ids = []
    item_names = []
    while True:
        include.printimportanttext("EKWIPUNEK")
        print("OBOLE: " + str(PC_HERO.gold))
        if hasattr(PC_HERO,"armor"):
            print("Używana zbroja: " + PC_HERO.armor.name)
        else:
            print("Używana zbroja: BRAK")
        if hasattr(PC_HERO,"weapon"):
            print("Używana broń: " + PC_HERO.weapon.name)
        else:
            print("Używana broń: BRAK")

        print("\nTORBA: ")
        for item in PC_HERO.inventory:
            print(item.name + " -- " + item_type_dict[item.type])

            item_ids.append(item)
            item_names.append(item.name)
        char_items = dict(zip(item_names, item_ids))
        print("Wpisz przedmiot którego chcesz użyć. Jeśli chcesz wrócić wpisz POWRÓT")
        command = input()
        action = command.split(' ', 1)[0].lower()
        if action in include.destroy_set:
            command = include.stringify(command.split(' ', 1)[1:])

        #print(action)
        #print(command)
        if command in char_items:
            command = char_items[command]
            if action in include.destroy_set:
                if hasattr(command,"used"):
                    print("Nie możesz wyrzucić itemu którego właśnie używasz!")
                else:
                    destroy_item(PC_HERO,command)
                    input()
            elif command.type == "weapon":
                print(command.desc)
                print("Obrażenia: " + str(command.dmg))
                if hasattr(command,"used"):
                    print("Używasz tej broni")
                    yes_no_bool = input("Odłożyć? ")
                    if yes_no_bool.lower() in include.yes_set:
                        delattr(PC_HERO.weapon,"used")
                else:
                    if hasattr(PC_HERO,"weapon"):
                        print("Obecna broń: " + str(PC_HERO.weapon.dmg))
                    else:
                        print("Obecna broń: BRAK")
                    yes_no_bool = input("Użyć? ")
                    if yes_no_bool.lower() in include.yes_set:
                        if hasattr(PC_HERO,"weapon"):
                            delattr(PC_HERO.weapon,"used")
                        PC_HERO.weapon = command
                        PC_HERO.weapon.used = 1

            elif command.type == "armor":
                print(command.desc)
                print("Ochrona: " + str(command.armor))
                if hasattr(command,"used"):
                    print("Używasz tej zbroi")
                    yes_no_bool = input("Odłożyć? ")
                    if yes_no_bool.lower() in include.yes_set:
                        delattr(PC_HERO.armor,"used")
                else:
                    if hasattr(PC_HERO,"armor"):
                        print("Obecna zbroja: " + str(PC_HERO.armor.armor))
                    else:
                        print("Obecna zbroja: BRAK")
                    yes_no_bool = input("Użyć? ")
                    if yes_no_bool.lower() in include.yes_set:
                        if hasattr(PC_HERO,"armor"):
                            delattr(PC_HERO.armor,"used")
                        PC_HERO.armor = command
                        PC_HERO.armor.used = 1
            elif hasattr(command,"eateffect"):
                command.eateffect(PC_HERO,command)
            else:
                print(command.desc)
        elif command.lower() in include.back_set:
            break

def add_to_inventory(character,item):
    character.inventory.append(item)
    print("Otrzymano przedmiot: " + item.name)
    if hasattr(item,"effect"):
        item.effect()

def add_gold(character,amount):
    character.gold += amount
    print("Zdobywasz " + str(amount) + " Obole")

def remove_gold(character,amount):
    character.gold -= amount
    print("Tracisz " + str(amount) + " Obole")

def destroy_item(character,item):
    character.inventory.remove(item)
    print("Wyrzucono przedmiot: " + item.name)


import asyncio
import logging
from typing import Iterator, Union

import grpc
from django.conf import settings
from pydantic import Field

from llmstack.common.blocks.base.schema import BaseSchema
from llmstack.common.runner.proto import runner_pb2, runner_pb2_grpc
from llmstack.connections.models import (
    Connection,
    ConnectionActivationInput,
    ConnectionActivationOutput,
    ConnectionStatus,
    ConnectionType,
)
from llmstack.connections.types import ConnectionTypeInterface

logger = logging.getLogger(__name__)

class WebLoginBaseConfiguration(BaseSchema):
    _storage_state: str = Field(
        description='Storage state', widget='textarea', hidden=True)

class WebLoginConfiguration(WebLoginBaseConfiguration):
    start_url: str = Field(description='URL to login to',
                           default='https://google.com')

class WebLogin(ConnectionTypeInterface[WebLoginConfiguration]):
    @staticmethod
    def name() -> str:
        return 'Web Login'

    @staticmethod
    def provider_slug() -> str:
        return 'promptly'

    @staticmethod
    def slug() -> str:
        return 'web_login'

    @staticmethod
    def description() -> str:
        return 'Login to a website'

    @staticmethod
    def type() -> ConnectionType:
        return ConnectionType.BROWSER_LOGIN

    def input(self, activation_input: ConnectionActivationInput) -> None:
        if activation_input.data == 'terminate':
            self._is_terminated = True

    async def _request_iterator(self, connection, timeout):
        session_data = connection.configuration['_storage_state'] if '_storage_state' in connection.configuration and connection.configuration['_storage_state'] else ''
        yield runner_pb2.RemoteBrowserRequest(init_data=runner_pb2.BrowserInitData(url=connection.configuration['start_url'],
                                                                                terminate_url_pattern='',
                                                                                session_data=session_data,
                                                                                timeout=timeout, persist_session=True))

        # Sleep till timeout or self._is_terminated is True
        time_elapsed = 0
        while not self._is_terminated and time_elapsed < timeout:
            await asyncio.sleep(0.1)
            time_elapsed += 0.1

        yield runner_pb2.RemoteBrowserRequest(input=runner_pb2.BrowserInput(type=runner_pb2.TERMINATE))

    async def _read_browser_output(self, connection, remote_browser_stream):
        while not self._is_terminated:
            try:
                # Read the next message from the stream
                output = await remote_browser_stream.read()
                if output.state is not runner_pb2.RemoteBrowserState.RUNNING:
                    self._is_terminated = True
                    if output.session.session_data:
                        connection.configuration['_storage_state'] = output.session.session_data
                        connection.status = ConnectionStatus.ACTIVE
                    else:
                        connection.status = ConnectionStatus.FAILED
                    break
            except grpc.aio.AioRpcError as e:
                # Handle the case where the stream has been closed by the server
                if e.code() == grpc.StatusCode.CANCELLED:
                    # Stream has been cancelled, likely no more messages to read
                    logger.info('Stream was cancelled, no more messages.')
                    break
                else:
                    # An actual error occurred, log or re-raise
                    logger.error(
                        f'RPC error occurred: {e.code()} - {e.details()}')
                    raise
            except asyncio.CancelledError:
                # The task was cancelled, so exit the loop
                logger.info('Task was cancelled, exiting read loop.')
                break
            except TimeoutError:
                pass

            await asyncio.sleep(0.01)

        return connection

    async def activate(self, connection) -> Iterator[Union[Connection, dict]]:
        self.channel = grpc.aio.insecure_channel(
            f'{settings.RUNNER_HOST}:{settings.RUNNER_PORT}')
        stub = runner_pb2_grpc.RunnerStub(self.channel)
        self._input_index = 0
        self._input_instructions = []
        self._is_terminated = False
        timeout = 120

        self.remote_browser_stream = stub.GetRemoteBrowser(
            self._request_iterator(connection, timeout))

        first_message = await self.remote_browser_stream.read()

        ws_url = first_message.session.ws_url

        yield ConnectionActivationOutput(data={'ws_url': ws_url, 'timeout': timeout})

        # Consume the stream in a separate task and return the connection
        connection = await self._read_browser_output(connection, self.remote_browser_stream)

        await self.channel.close()
        yield connection


#!/usr/bin/python
# -*- coding: utf8 -*-

"""
H. Asorey
Cálculo del campo gravitatorio tridimensional para un objeto central utilizando una clase propia de vectores. Debería usarse numpy pero se trata de un ejemplo para aprender a trabajar con clases en python
"""
import math

####################### mi clase vector

class vector:
    def __init__(self,lista):
        self.x=[]
        for xi in lista:
          self.x.append(float(xi))
        self.dim=len(self.x)
        self.mod=math.sqrt(self.prod_escalar(self))

    def prod_escalar(self,a):
        if (self.dim == a.dim):
            pesc=0.
            for i in range(0,self.dim):
                pesc += (self.x[i] * a.x[i])
            return pesc
        else:
            print ("El productor escalar se define para vectores de la misma dimension")
            return None

###################### Operaciones entre vectores

def suma(a, b):
    suma=[]
    if (a.dim == b.dim):
       for i in range(0,a.dim):
          suma.append(a.x[i]+b.x[i])
       return vector(suma)
    else:
       return None

def resta(a, b):
    resta=[]
    if (a.dim == b.dim):
       for i in range(0,a.dim):
          resta.append(a.x[i]-b.x[i])
       return vector(resta)
    else:
       return None

def vector_escalar(a, num):
    escalar=[]
    for i in range(0,a.dim):
      escalar.append(num*a.x[i])
    return vector(escalar)

################ Unidades
## Hay que pasar todo a unidades del SI
## Usamos múltiplos comunes (1km = 1000m; 1 dia=86400 s; etc)

kg = 1.
s = 1.
m = 1.
G = 6.67e-11 * m**3 / (kg * s**2)

## algunas definiciones útiles
km = 1000. * m
ua = 1.5e8 * km
# masa solar
ms = 1.989e30 * kg
# masa tierra
mt = 5.972e24 * kg
# masa júpiter
mj = 1.898e27 * kg

# la masa de prueba
mp = 1. * kg

## las masas de campo
## son las que producen el campo gravitatorio
## por ejemplo, dos estrellas con masas solares separadas por 1 UA centradas en el eje x
m1 = 1. * ms
r1=vector([0.5*ua, 0, 0])

m2 = 1. * ms
r2=vector([-0.5*ua, 0, 0])

# auxiliares
# r es el vector posición donde calculo el campo
r=vector([0, 0, 0])

# dimensiones de la grilla cartesiana.
# base es la unidad base para la grilla cartesiana.
base = 1. * ua
# res es la cantidad de puntos por unidad de base. Por ejemplo 10 significa que tomará 10 puntos por unidad base, en dr
res=1/2.
# límite es el máximo (y mínimo) de la grilla en bases. La grilla será un cubo de 2*lim*base de lado
lim = 3.

# paso
dr = base / res

# recorro el espacio
for x in range(int(-lim*res),int((lim*res)+1)):
  for y in range(int(-lim*res),int((lim*res)+1)):
    for z in range(int(-lim*res),int((lim*res)+1)):
      # estoy mirando el punto r
      r=vector([x * dr, y * dr, z * dr])
      # calculo los vectores de r respecto a cada estrella
      d1=resta(r, r1)
      d2=resta(r, r2)

      # si ninguno es 0 (no estoy en la estrella donde el campo diverge), calculo:
      if (d1.mod and d2.mod):
        # Fuerza debida a la estrella 1, va distancia cubo xq uso el vector y no el versor
        F1_mod = -G * m1 * mp / d1.mod**3
        # La fuerza tiene dirección de d1 y módulo F1
        F1 = vector_escalar(d1, F1_mod)
        # Fuerza debida a la estrella 2, va distancia cubo xq uso el vector y no el versor
        F2_mod = -G * m2 * mp / d2.mod**3
        F2 = vector_escalar(d2, F2_mod)

        # Superposición -> suma vectorial de las fuerzas
        F=suma(F1, F2)

        # ahora las energías potenciales gravitatorias
        U1 = -G * m1 *mp / d1.mod
        U2 = -G * m2 *mp / d2.mod
        U=U1+U2

        # pone el vector en el vector r para dibujar en cada punto
        Faux = suma (r, F)

        # imprimo los resultados: posición, fuerza, módulo y energía para este punto y vuelvo.
        # Al terminar sale
        for i in range (0, r.dim):
          print (r.x[i], end=',')
        for i in range (0, r.dim):
          print (Faux.x[i], end=',')
        print (F.mod, end=',')
        print (U)


import itertools
from itertools import product, chain, combinations
from sympy.combinatorics import Permutation

class Sigma:

    ALL_SIGMA = {}
    ALL_PERMS = {}
    MEMO = {}

    def __init__(self, tuples):
        self.dom = set()
        self.rng = set()
        self.id = True
        self.tuple_inverse = list()
        self.length = len(tuples)
        self.tuple_form = list()
        self.keys = []
        self.values = []
        for pair in tuples:
            if (pair[0] is None) or (pair[1] is None):
                continue
            if pair[0] != pair[1]:
                self.id = False
            self.tuple_form.append(pair)
            self.keys.append(pair[0])
            self.values.append(pair[1])
            self.tuple_inverse.append((pair[1], pair[0]))
            self.dom.add(pair[0])
            self.rng.add(pair[1])

        self.hs = hash(frozenset(self.tuple_form))

    def len(self):
        return len(self.tuple_form)

    def __str__(self):
        if len(self.tuple_form) == 0:
            return "{}"
        return str(self.tuple_form).replace("\'", "")

    def __contains__(self, item):
        return item in self.keys

    def __add__(self, other: "Sigma"):
        new_tuples = set()
        for t in self.tuple_form:
            key, value = t
            if value in other:
                new_tuples.add((key, other[value]))
        return Sigma(new_tuples)

    def __eq__(self, other: "Sigma"):
        return set(self.tuple_form) == set(other.tuple_form)

    def __le__(self, other: "Sigma"):
        return self.tuple_form.issubset(other.tuple_form)

    def __getitem__(self, key):
        try:
            index = self.keys.index(key)
        except IndexError:
            raise IndexError("Error - key {} non-existent.".format(key))
        return self.values[index]

    def __hash__(self):
        return self.hs

    def in_dom(self, s):
        return s in self.dom

    def in_rng(self, s):
        return s in self.rng

    def dom_sub(self, s: set):
        return s - self.dom

    def rng_sub(self, s: set):
        return s - self.rng

    def reverse(self):
        return Sigma(self.tuple_inverse)

    def __copy__(self):
        return Sigma(self.tuple_form)

    def invert(self):
        return Sigma(self.tuple_inverse)

    def is_id(self):
        return self.id

    def get_tuple_form(self):
        return self.tuple_form

    def harpoon(self, q1, q2, RA) -> "Sigma":
        s1, s2 = RA.s_map[q1], RA.s_map[q2]
        new_tuples = set()
        for current_tuple in self.tuple_form:
            if (current_tuple[0] in s1) and (current_tuple[1] in s2):
                new_tuples.add(current_tuple)
        return Sigma(new_tuples)

    def generate_temp_sigma(self, key, value) -> "Sigma":
        keys = list(self.keys)
        values = list(self.values)
        if key not in keys:
            values.append(None)
            keys.append(key)
        i1 = keys.index(key)
        if value not in values:
            keys.append(None)
            values.append(value)
        i2 = values.index(value)
        values[i2] = None
        values[i1] = value
        # try:
        #     assert len(keys) == len(values)
        # except AssertionError:
        #     print(keys, key)
        #     print(values, value)
        #     exit(5)
        while None in keys:
            index = keys.index(None)
            keys.pop(index)
            values.pop(index)
        while None in values:
            index = values.index(None)
            keys.pop(index)
            values.pop(index)
        tuples = set(zip(keys, values))
        return Sigma(tuples)

    @classmethod
    def eliminate(cls, l1: list, l2: list, s: set) -> None:
        i = 0
        while i < len(l1):
            if l1[i] is None:
                i += 1
                continue
            if l1[i] not in s:
                del l1[i]
                del l2[i]
            else:
                i += 1

    @classmethod
    def generate_sigmas(cls, s1, s2):
        f1 = frozenset(s1)
        f2 = frozenset(s2)
        if (f1, f2) not in Sigma.ALL_SIGMA:
            all_sigmas = set()
            if len(s1) >= len(s2):
                length = len(s2)
                zip_set = s1
            else:
                length = len(s1)
                zip_set = s2
            f_temp = frozenset(zip_set)
            if not (f_temp, length) in Sigma.ALL_PERMS:
                Sigma.ALL_PERMS[(f_temp, length)] = set(itertools.permutations(zip_set, length))
            if len(s1) >= len(s2):
                perm = [list(zip(x, s2)) for x in Sigma.ALL_PERMS[(f_temp, length)]]
            else:
                perm = [list(zip(s1, x)) for x in Sigma.ALL_PERMS[(f_temp, length)]]
            for p in perm:
                new_sig = Sigma(set(p))
                if new_sig not in all_sigmas:
                    all_sigmas.add(new_sig)
                # sets = powerset(p)
                # for s in sets:
                #     new_sig = Sigma(set(s))
                #     if new_sig not in all_sigmas:
                #         all_sigmas.add(new_sig)
            Sigma.ALL_SIGMA[(f1, f2)] = frozenset(all_sigmas)
        return Sigma.ALL_SIGMA[(f1, f2)]

def unique_permutations(the_list: list):
    l_list = range(len(the_list) - 1, -1, -1)
    k_list = l_list[1:]
    the_list = sorted(the_list)
    while True:
        yield the_list
        found = False
        for k in k_list:
            if the_list[k] < the_list[k+1]:
                found = True
                break
        if not found:
            return
        val = the_list[k]
        for i in l_list:
            if val < the_list[i]:
                break
        the_list[k], the_list[i] = the_list[i], the_list[k]
        the_list[k + 1:] = the_list[-1:k:-1]

def powerset(iterable):
    s = list(iterable)
    return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1))


#!/usr/bin/env python3

import argparse
import logging
import os
import textwrap
from functools import partial
from multiprocessing import Pool

import matplotlib
import pandas as pd
from rich.logging import RichHandler
from rich.progress import Progress

from your.utils.misc import YourArgparseFormatter
from your.utils.plotter import plot_h5

os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE"
matplotlib.use("Agg")

def mapper(save, detrend_ft, publication, mad_filter, out_dir, h5_file):
    # maps the variables so the function will be imap friendly
    plot_h5(
        h5_file=h5_file,
        save=save,
        detrend_ft=detrend_ft,
        publication=publication,
        mad_filter=mad_filter,
        outdir=out_dir,
    )

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        prog="your_h5plotter.py",
        description="Plot candidate h5 files.",
        formatter_class=YourArgparseFormatter,
        epilog=textwrap.dedent(
            """\
            This script can be used to plot and save the candidate HDF5 format files generated by your_candmaker.py or by the Candidate class.
            """
        ),
    )
    parser.add_argument("-v", "--verbose", help="Be verbose", action="store_true")
    parser.add_argument(
        "-f", "--files", help="h5 files to be plotted", nargs="+", required=False
    )
    parser.add_argument(
        "-c", "--results_csv", help="Plot positives in results.csv", required=False
    )
    parser.add_argument(
        "--publish", help="Make publication quality plots", action="store_true"
    )
    parser.add_argument(
        "--no_detrend_ft", help="Detrend the frequency-time plot", action="store_false"
    )
    parser.add_argument(
        "--no_save", help="Do not save the plot", action="store_false", default=True
    )
    parser.add_argument(
        "-o",
        "--out_dir",
        help="Directory to save pngs (default: h5 dir)",
        type=str,
        default=None,
        required=False,
    )
    parser.add_argument(
        "-mad",
        "--mad_filter",
        help="Median Absolute Deviation spectal clipper, default 3 sigma",
        nargs="?",
        const=3.0,
        default=False,
    )
    parser.add_argument(
        "-n",
        "--nproc",
        help="Number of processors to use in parallel (default: 4)",
        type=int,
        default=4,
        required=False,
    )
    parser.add_argument(
        "--no_progress",
        help="Do not show the tqdm bar",
        action="store_true",
    )
    parser.add_argument(
        "--no_log_file", help="Do not write a log file", action="store_true"
    )

    values = parser.parse_args()
    logging_format = (
        "%(asctime)s - %(funcName)s -%(name)s - %(levelname)s - %(message)s"
    )

    if values.verbose:
        logging.basicConfig(
            level=logging.DEBUG,
            format=logging_format,
            handlers=[RichHandler(rich_tracebacks=True)],
        )

    else:
        logging.basicConfig(
            level=logging.INFO,
            format=logging_format,
            handlers=[RichHandler(rich_tracebacks=True)],
        )

    matplotlib_logger = logging.getLogger("matplotlib")
    matplotlib_logger.setLevel(logging.INFO)

    if values.files:
        h5_files = values.files
    elif values.results_csv:
        df = pd.read_csv(values.results_csv)
        h5_files = list(df["candidate"][df["label"] == 1])
    else:
        raise ValueError(f"Need either --files or --results_csv argument.")

    with Pool(processes=values.nproc) as p:
        max_ = len(h5_files)
        func = partial(
            mapper,
            values.no_save,
            values.no_detrend_ft,
            values.publish,
            values.mad_filter,
            values.out_dir,
        )

        with Progress() as progress:
            if values.no_progress:
                task = progress.add_task("[green]Writing...", total=max_, visible=False)
            else:
                task = progress.add_task("[green]Writing...", total=max_)
            for i, _ in enumerate(p.imap_unordered(func, h5_files, chunksize=2)):
                progress.update(task, advance=1)


import logging
import config
from cube_session import CubeSession

class CubeParser(object):

    def __init__(self):
        self.logger = logging.getLogger(config.logger_name)

    def parse_current_result(self, id, full_json, is_current):
        results = full_json["results"]

        if is_current:
            if len(results) == 0:
                self.logger.error("No results found for %s.", id)
                return None
            elif len(results) > 1:
                self.logger.warning("Too many results found. Using only first.")

        zipped = dict(zip(full_json["field_list"], results[0]))
        zipped['id'] = id

        return zipped

    def get_devices(self, session):
        response = session.get("%s/devices/" % config.RES)
        result = response.json()
        # print(response.headers)
        # print(result)
        return result

    def get_data(self):
        session = CubeSession.get_session()
        result = self.get_devices(session)
        parsed_datas = []
        if result["ok"]:
            for device in result["devices"]:
                cube_data_response = session.get('%s/devices/%s/current' % (config.RES, device["uid"]))
                parsed = self.parse_current_result(device["uid"], cube_data_response.json(), True)
                if parsed:
                    parsed_datas.append(parsed)
        else:
            self.logger.error("Failed to get devices %s", str(result))

        return parsed_datas

if __name__ == '__main__':
    CubeParser().get_data()


# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

H, W = LI()
c = []
for i in range(10):
    c.append(LI())

A = []
for i in range(H):
    A = A + LI()

for k in range(10):
    for i in range(10):
        for j in range(10):
            c[i][j] = min(c[i][j], c[i][k] + c[k][j])

ans = 0
for a in A:
    if a != -1:
        ans += c[a][1]

print(ans)