def plot_decision_surface(x_train, x_today, y_today, classifier, scaler, date):

    #Plot of the decision surface obtained through the classifier used
    #INPUTS: x_train = training set of spreads
    #        x_today =
    #        y_today =
    #        classifier = classifier used for the training
    #                     (between svclassifier and xgbclassifier)
    #        scaler = standard scaler to normalize new data following
    #                 normalization used for training

    import matplotlib.pyplot as plt
    import numpy as np

    # first drop all countries with na spreads or CCC rating
    idx_na = x_today[x_today.isna().any(axis=1)].index  # save index were imp rating will be overwritten
    x_today_wo_na = x_today.drop(idx_na)
    y_today_wo_na = y_today.drop(idx_na)
    idx_ccc = y_today_wo_na[~y_today_wo_na['RATING_SP'].isin([1, 2, 3, 4, 5])].index  # select were  rating is CCC
    x_today_wo_na = x_today_wo_na.drop(idx_ccc)
    y_today_wo_na = y_today_wo_na.drop(idx_ccc)

    # adapt to scaling
    x_today_wo_na = scaler.transform(x_today_wo_na)

    # plot
    h = .02  # step size in the mesh
    x_min, x_max = x_train[:, 1].min() - 1e-2, x_train[:, 1].max() + 1e-2  # Bond Spread
    y_min, y_max = x_train[:, 0].min() - 1e-2, x_train[:, 0].max() + 1e-2  # CDS
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    z = classifier.predict(np.c_[xx.ravel(), yy.ravel()])
    z = z.reshape(xx.shape)
    plt.contourf(xx, yy, z, cmap=plt.cm.coolwarm, alpha=0.8)

    col = np.array(y_today_wo_na.RATING_SP)
    markers = ["o", "^", "s", "*", "h"]
    label = ["AAA", "$A A$", "$A$", "$B B B$", "$B B$"]
    colors = ['mediumblue', 'royalblue', 'lightsteelblue', 'salmon', 'firebrick']
    for i, c in enumerate(np.unique(col)):
        plt.scatter(x_today_wo_na[:, 1][col == c], x_today_wo_na[:, 0][col == c], color=colors[c - 1],
                    cmap=plt.cm.coolwarm, marker=markers[i], s=144, label=label[i])
    plt.legend()
    plt.xlabel('Bond Spreads')
    plt.ylabel('CDS')
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title('Decision Surface ' + str(date)[:10])
    plt.show()

    return


import matplotlib
import numpy as np
import torch
import matplotlib.pyplot as plt
import torch.nn as nn

from main import create_training_sample, plot, state_loss, state_step

matplotlib.use('TkAgg')

def is_positive(x: torch.tensor):
    return torch.clamp(x, 0, 1)

def conway_layer(x: torch.tensor):
    surround_sum = torch.roll(x, 1, 2) + torch.roll(x, -1, 2) + torch.roll(x, 1, 3) + torch.roll(x, -1, 3) +\
        torch.roll(x, (-1, -1), (2, 3)) + torch.roll(x, (1, -1), (2, 3)) + torch.roll(x, (-1, 1), (2, 3)) + torch.roll(x, (1, 1), (2, 3))

    return is_positive(surround_sum + x - 2) - is_positive(surround_sum - 3)

def custom_gradient_conway_loss(x0: torch.Tensor, target: torch.Tensor, delta: int):
    """

    input roll pattern:

    00      01      02

    10      11      12

    20      21      22

    """
    x0_21 = torch.roll(x0, 1, 2)
    x0_01 = torch.roll(x0, -1, 2)
    x0_12 = torch.roll(x0, 1, 3)
    x0_10 = torch.roll(x0, -1, 3)
    x0_00 = torch.roll(x0, (-1, -1), (2, 3))
    x0_20 = torch.roll(x0, (1, -1), (2, 3))
    x0_02 = torch.roll(x0, (-1, 1), (2, 3))
    x0_22 = torch.roll(x0, (1, 1), (2, 3))

    # step one delta
    surround_sum = x0_21 + x0_01 + x0_12 + x0_10 + x0_00 + x0_20 + x0_02 + x0_22
    x1 = is_positive(surround_sum + x0 - 2) - is_positive(surround_sum - 3)

    # step multiple deltas
    if delta > 1:
        end, gradient1, loss = custom_gradient_conway_loss(x1, target, delta - 1)
    else:
        gradient1 = target - x1

    # masks
    mask_x0_1 = x0
    mask_x0_0 = -x0 + 1
    pos_gradient1 = torch.clamp_min(gradient1, 0)
    neg_gradient1 = torch.clamp_max(gradient1, 0)
    mask_surround_sum_is_2 = is_positive(surround_sum - 1) - is_positive(surround_sum - 2)
    mask_surround_sum_below_3 = is_positive(-surround_sum + 3)
    mask_surround_sum_above_3 = is_positive(surround_sum - 3)

    # randomness (-1 or 1)
    random_gradient_direction = torch.sign(torch.rand(x0.size()) - 1.1)

    # ------------------
    # calculate gradient
    # ------------------

    # gradient negative
    center_gradient = neg_gradient1 * mask_surround_sum_is_2
    surround_gradient = neg_gradient1 * random_gradient_direction

    # gradient positive - below 3
    center_gradient += pos_gradient1 * mask_surround_sum_below_3
    surround_gradient += pos_gradient1 * mask_surround_sum_below_3

    # gradient positive - above 3
    surround_gradient -= pos_gradient1 * mask_surround_sum_above_3

    # sum up the gradients
    sg_21 = torch.roll(surround_gradient, 1, 2)
    sg_01 = torch.roll(surround_gradient, -1, 2)
    sg_12 = torch.roll(surround_gradient, 1, 3)
    sg_10 = torch.roll(surround_gradient, -1, 3)
    sg_00 = torch.roll(surround_gradient, (-1, -1), (2, 3))
    sg_20 = torch.roll(surround_gradient, (1, -1), (2, 3))
    sg_02 = torch.roll(surround_gradient, (-1, 1), (2, 3))
    sg_22 = torch.roll(surround_gradient, (1, 1), (2, 3))
    gradient0 = center_gradient + sg_21 + sg_01 + sg_12 + sg_10 + sg_00 + sg_20 + sg_02 + sg_22

    # keep only valid direction gradients
    gradient0 = mask_x0_0 * torch.clamp_min(gradient0, 0) + mask_x0_1 * torch.clamp_max(gradient0, 0)

    if delta > 1:
        return end, gradient0, loss
    else:
        return x1, gradient0, torch.sum(torch.abs(gradient1))

class ConvRegressionModule(nn.Module):
    def __init__(self, input_shape=(1, 1, 25, 25)):
        super().__init__()
        self.inputs = torch.from_numpy(np.random.uniform(0.4, 0.6, input_shape)).float()
        self.inputs_para = nn.Parameter(self.inputs, True)
        self.register_parameter(name="bias", param=nn.Parameter(self.inputs, True))

    def forward(self, num_iterations):
        out = conway_layer(self.inputs_para)
        for i in range(num_iterations - 1):
            out = conway_layer(out)

        return out

    def get_current_boards(self):
        out = (np.array(self.inputs.tolist()) >= 0.5).astype(np.int)
        return out[:, 0, :, :]

    def step_clamp(self):
        self.inputs.data.clamp(0, 1)

def plot_solver_state(input_mask: torch.Tensor,
                      target: torch.Tensor,
                      analytic_start_state: torch.Tensor,
                      output: torch.Tensor,
                      gradient: torch.Tensor):
    input_mask = np.array(input_mask.tolist())[0, 0]
    target = np.array(target.tolist())[0, 0]
    analytic_start_state = np.array(analytic_start_state.tolist())[0, 0]
    output = np.array(output.tolist())[0, 0]
    gradient = np.array(gradient.tolist())[0, 0]

    plt.clf()
    plt.subplot(2, 3, 1)
    plt.title("input")
    plt.imshow(input_mask, vmin=0.0, vmax=1.0)

    plt.subplot(2, 3, 2)
    plt.title("gradients")
    plt.imshow(gradient)

    plt.subplot(2, 3, 3)
    plt.title("input (analytic)")
    plt.imshow(analytic_start_state, vmin=0.0, vmax=1.0)

    plt.subplot(2, 2, 3)
    plt.title("target")
    plt.imshow(target, vmin=0.0, vmax=1.0)

    plt.subplot(2, 2, 4)
    plt.title("current output")
    plt.imshow(output, vmin=0.0, vmax=1.0)
    plt.show(block=False)

def main():
    DELTA = 5
    STEPS = 700

    sample = create_training_sample(delta=DELTA)
    batch_target = np.expand_dims(np.expand_dims(sample['end'], 0), 3)
    batch_sample_start = np.expand_dims(np.expand_dims(sample['end'], 0), 3)
    batch_target_torch = torch.from_numpy(batch_target.transpose((0, 3, 1, 2))).float()
    batch_sample_start_torch = torch.from_numpy(batch_sample_start.transpose((0, 3, 1, 2))).float()

    analytic_start_state = torch.rand(batch_sample_start_torch.size()) * 0.1
    # analytic_start_state = batch_target_torch
    # plot(sample['start'])
    # plot(sample['end'])

    max_pool = nn.MaxPool2d((25, 25), return_indices=True)
    max_unpool = nn.MaxUnpool2d((25, 25))
    unpool_value = torch.ones((1, 1, 1, 1)).float()

    for step in range(STEPS):
        masked = torch.sign(analytic_start_state - 0.5) * 0.5 + 0.5

        output, gradient, loss = custom_gradient_conway_loss(masked, batch_target_torch, DELTA)
        print(loss.item())
        plot_solver_state(masked, batch_target_torch, analytic_start_state, output, gradient)

        max, indices = max_pool(torch.abs(gradient))
        biggest_gradient = torch.sign(gradient * max_unpool(unpool_value, indices))
        analytic_start_state += biggest_gradient

        # analytic_start_state = torch.clamp(analytic_start_state + gradient * 3 / (torch.sum(torch.abs(gradient)) + 0.00001), 0., 1.0)
        plt.pause(0.01)

    print()

    exit()

    net = ConvRegressionModule(batch_target_torch.size())
    mse = torch.nn.MSELoss(reduction="sum")
    sgd = torch.optim.SGD(net.parameters(), 0.01)

    prediction = net.get_current_boards()
    pred_end = np.array(prediction.tolist())[0]
    plt.imshow(pred_end)
    plt.show()
    for step in range(STEPS):
        net.zero_grad()
        loss = mse(net(DELTA), batch_target_torch)
        loss.backward()
        print(loss.item())
        sgd.step()
        net.step_clamp()

    prediction = net.get_current_boards()
    pred_end = np.array(prediction.tolist())[0]
    for d in range(DELTA):
        pred_end = state_step(pred_end)

    print(state_loss(sample['end'], pred_end) * 25 * 25)

if __name__ == "__main__":
    main()


import os
import sys
import copy
import torch
import itertools

from model import *
from utilities import *

class SudokuSolver:
    def __init__(self, modelPath, recurrentIterations=10):
        self.sudokuChecker = SudokuChecker()
        self.plotter = SudokuPlotter()
        self.__loadModel(modelPath, recurrentIterations)

    def __loadModel(self, modelPath, recurrentIterations):

        self.model = SudokuNet(recurrentIterations=recurrentIterations)
        self.model.load_state_dict(torch.load(modelPath, map_location=torch.device('cpu')))
        self.model.to(torch.device('cpu'))
        self.model.eval()

    @staticmethod
    def __prepareSudokuTensor(sudoku):
        sudokuTensor = torch.zeros((1,81))
        for rowIndex, row in enumerate(sudoku):
            for columnIndex, value in enumerate(row):
                sudokuTensor[0, rowIndex*9 + columnIndex] = int(value)
        return sudokuTensor.long()

    def __solveSudokuInOneStep(self, sudoku):
        sudokuTensor = self.__prepareSudokuTensor(sudoku)
        _, outputSudokuTensor = self.model(sudokuTensor)
        solutionTensor = torch.argmax(outputSudokuTensor,-1)
        solutionTensor += 1
        mask = torch.where(sudokuTensor==0)
        sudokuTensor[mask]+=solutionTensor[mask]
        self.plotter.plotMatrix(sudokuTensor)
        return sudokuTensor

    def __solveSudokuStepByStep(self, sudoku):
        sudokuTensor = self.__prepareSudokuTensor(sudoku)
        step=1
        while torch.sum(sudokuTensor==0)>0:
            _, outputSudokuTensor = self.model(sudokuTensor)
            decisionProbabilities, solutionTensor = torch.max(outputSudokuTensor,2)
            _, mask = torch.where(sudokuTensor>0)
            decisionProbabilities[0,mask] = float('-inf')
            mostLikelyCell = torch.argmax(decisionProbabilities)
            sudokuTensor[0,mostLikelyCell] = solutionTensor[0,mostLikelyCell]+1
            print('Step: {}'.format(step))
            print('Filled Row {}, Column {}'.format(mostLikelyCell//9+1,mostLikelyCell%9+1))
            self.plotter.plotMatrix(sudokuTensor)
            step+=1

        return sudokuTensor

    def __getSudokuSolution(self, sudoku, fast):

        with torch.no_grad():
            if fast:
                solvedSudoku = self.__solveSudokuInOneStep(sudoku)
            else:
                solvedSudoku = self.__solveSudokuStepByStep(sudoku)
        return solvedSudoku

    def __evaluateSudoku(self, sudokuTensor, fast):

        speed = 'Fast' if fast else 'Slow'
        sudokuMatrix = copy.copy(sudokuTensor).view(9,9).tolist()
        if self.sudokuChecker.checkSudoku(sudokuMatrix):
            print('{} Sudoku Is Correct\n'.format(speed))
            return True
        else:
            print('{} Sudoku Is UnCorrect\n'.format(speed))
            return False

    def solveSudoku(self, sudoku, fast=False):
        solvedSudokuTensor = self.__getSudokuSolution(sudoku, fast)
        self.__evaluateSudoku(solvedSudokuTensor, fast)

    def solveSudokus(self, sudokus, fast=False):
        accuracyCount = 0.
        for sudoku in sudokus:
            solvedSudokuTensor = self.__getSudokuSolution(sudoku, fast)
            if self.__evaluateSudoku(solvedSudokuTensor, fast):
                accuracyCount += 1
        print('Sudokus Solved: {}%'.format(accuracyCount*100/len(sudokus)))

def readSudokusFromTest(sudokuPath):

    listOfInputSudokus = list()
    with open(sudokuPath) as inputFile:
        sudokus = inputFile.read().split('\n\n')
        for sudoku in sudokus:
            sudokuAsList = list()
            lines = sudoku.split('\n')
            for line in lines:
                sudokuAsList.append(''.join(line.strip().split()))
            listOfInputSudokus.append(sudokuAsList)

    return listOfInputSudokus

if __name__ == '__main__':

    sudokuSolver = SudokuSolver(sys.argv[1])
    sudokus = readSudokusFromTextFile(sys.argv[2])
    sudokuSolver.solveSudokus(sudokus, fast=True)


import os
import asciidrawer as ass

def _character_checker(s: str) -> str:
    """Checks if given characters are ascii and destroys the duplicates

    Parameters:
    s (str): String of characters to pass further

    Returns:
    chars str: string of given symbols without duplicates

   """
    if type(s) != str:
        raise TypeError("given argument should be \'str\' type")
    if not s.isascii():
        raise ValueError("given string \"{}\" contains non-ASCII characters".format(s))
    chars = []
    for char in s:
        if char not in chars:
            chars.append(char)
    ret = ""
    for i in chars:
        ret += str(i)
    return ret

def _check_cfg_values(path_from: str, grid_x: int, grid_y: int):
    """Throws exceptions

        Parameters:
        path_from (str): path to the file from which to create ASCII art
        grid_x (int): x length of the output ASCII art
        grid_y (int): y length of the output ASCII art
        use_y (bool): use grid_y to determine size of the output

    """
    if not os.path.isfile(path_from):
        raise OSError("file \"{}\" does not exist".format(path_from))
    if grid_x <= 0 or grid_x >= 200:
        raise ValueError("x size of the grid should be between 1 and 200")
    if grid_y <= 0 or grid_y >= 200:
        raise ValueError("y size of the grid should be between 1 and 200")

def draw_ascii(path_from, symbols, grid_x, grid_y, normalize=True):
    """Draws image

        Parameters:
        path_from (str): path to the file from which to create ASCII art
        grid_x (int): x length of the output ASCII art
        grid_y (int): y length of the output ASCII art
        normalize (bool): normalize image to improve contrast

    """
    symbols_filtered = _character_checker(symbols)
    _check_cfg_values(path_from, grid_x, grid_y)
    return ass.draw(path_from, symbols_filtered, grid_x, grid_y, normalize)


#!/usr/bin/python2
# -*- coding: utf-8 -*-

import sys

sys.path.append('base')
sys.path.append('utilities')

from RobotStateBase import RobotStateBase
from Constants import *

class EnemyCapture(RobotStateBase):

	def __init__(self, playerType, orchRpcAPI):
		RobotStateBase.__init__(self, playerType, orchRpcAPI)

	def createResponseMessage(self):
		return{
			'player_id': self.playerType.value,
			'calls': {'min_distance_from_opponent':1},
			'depth': self.escapeRouteSearchDepth,
			'strategy':'optimal',
			'strategy_area': 4,
			'state': 'EnemyCapture'
		}

The ROBers - Patra/Strategy1/pacmanApp/output/robotStates/EnemyCapture.py


import cv2
import numpy as np
import os
from random import shuffle
from tqdm import tqdm
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
matplotlib.use('tkagg')

train_data = './trainingData/train'
test_data = './trainingData/test'

def one_hot_label(img):
    ohl = None
    label = img.split('.')[0]
    if label == 'eyes':
        ohl = np.array([1, 0])
    elif label == 'nose':
        ohl = np.array([0, 1])
    return ohl

def train_data_with_label():
    train_imgs = []
    for i in tqdm(os.listdir(train_data)):
        path = os.path.join(train_data, i)
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (64, 64))
        train_imgs.append([np.array(img), one_hot_label(i)])
    shuffle(train_imgs)
    return train_imgs

def test_data_with_label():
    test_imgs = []
    for i in tqdm(os.listdir(test_data)):
        path = os.path.join(test_data, i)
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (64, 64))
        test_imgs.append([np.array(img), one_hot_label(i)])
    return test_imgs

training_images = train_data_with_label()
testing_images = test_data_with_label()

tr_img_data = np.array([i[0] for i in training_images]).reshape(-1,64,64,1)
tr_lbl_data = np.array([i[1] for i in training_images])

tst_img_data = np.array([i[0] for i in testing_images]).reshape(-1,64,64,1)
tst_lbl_data = np.array([i[1] for i in testing_images])

model = Sequential()
model.add(InputLayer(input_shape = [64, 64, 1]))

model.add(Conv2D(filters = 32, kernel_size = 5, strides = 1, padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = 5, padding = 'same'))

model.add(Conv2D(filters = 50, kernel_size = 5, strides = 1, padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = 5, padding = 'same'))

model.add(Conv2D(filters = 80, kernel_size = 5, strides = 1, padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = 5, padding = 'same'))

model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, activation = 'relu'))
model.add(Dropout(rate = 0.5))
model.add(Dense(2, activation = 'softmax'))

model.compile(optimizer = Adam(lr = 1e-3), loss = 'categorical_crossentropy', metrics = ['accuracy'])
model.fit(x = tr_img_data, y = tr_lbl_data, epochs = 50, batch_size = 128)
model.save('./models/eyesNose.h5')
model.summary()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 09:33:54 2020

@author: vargthon
"""
from lib.collector import Collector
from lib.normalizer import Normalizer
import pandas as pd
import numpy as np
import pickle
from sklearn.linear_model import LinearRegression
from datetime import datetime
from lib.linearmodel import LinearModel
from lib.repository.linearmodelrepository import LinearModelRepository
from lib.period import Period
class ProductLearning():

    def __init__(self):
        self.collector = Collector()
        self.normalize = Normalizer()

    def load_linear(self, company, product, period):
        repository = LinearModelRepository()
        model = repository.load_valid(product,company, period.value)
        if len(model.params) > 0:
            model = model
            product = model.product
            company = model.company
        else:
            model = self.fit_linear_product(product,company)
            model.company = {"cod": company}
            model.product = {"cod": product}
            repository.save(model)

        return model

    def fit_linear_product(self, codigoProduto, codigoFilial, features=[],target=None, training_date_from=datetime.now().timestamp(),
        training_date_to=datetime.now().timestamp(), period=Period.MONTHLY):
        company = {"cod": codigoFilial}
        df = self.collector.colector_mes(codigoProduto, codigoFilial)
        df = self.normalize.normalizar(df)
        model = LinearModel()
        if df.size > 0:
            product = {
                   "cod": df.loc[0,"KEY:PRODUTO:CODIGO"]
                }
        real_params = []
        for col in df.columns:
            column = col.split(":")
            if len(column) > 0:
                if column[0] == 'PARAMS':
                    real_params.append(col)
                if column[0] == 'CALENDAR' and column[1] != 'DATE':
                    real_params.append(col)
                if column[0] == 'EVENT':
                    real_params.append(col)
        X = df[real_params].values
        y = df['METRIC:QTD'].values
        if df.size != 0:
            model.fit(X,y)
            model.params = real_params
            model.training_date_from = training_date_from
            model.training_date_to = training_date_to
            model.period = period
            #self.model = self.regression#pickle.dumps(self.regression)

        return model


Import('RTT_ROOT')
Import('rtconfig')
from building import *

cwd = GetCurrentDir()
src = Glob('*.c')

CPPPATH = [cwd, cwd + '/include']
libs  = ['speex_arm968_gcc']
libpath  = [cwd]

group = DefineGroup('speex', src, depend = [''], CPPPATH = CPPPATH, LIBS = libs, LIBPATH = libpath)

Return('group')


import argparse
import importlib
import json
import logging
import os
import pkgutil
import sys  # noqa: F401
import tempfile
from unittest.mock import patch

import configargparse
import humanfriendly
import lookout

from lookout.core import slogging
from lookout.core.data_requests import DataService
from lookout.core.event_listener import EventListener
from lookout.core.manager import AnalyzerManager
from lookout.core.package import package_cmdline_entry
from lookout.core.sqla_model_repository import SQLAlchemyModelRepository

class ArgumentDefaultsHelpFormatterNoNone(argparse.ArgumentDefaultsHelpFormatter):
    """
    Pretty formatter of help message for arguments. \
    It adds default value to the end if it is not None.
    """

    def _get_help_string(self, action):
        if action.default is None:
            return action.help
        return super()._get_help_string(action)

def list_analyzers(args: argparse.Namespace):
    """
    Print the list of the analyzers inside the `lookout` package.

    :param args: Not used - parsed command line arguments.
    :return: None
    """
    first = True
    queue = [tuple(c) + ("lookout.",) for c in pkgutil.iter_modules(lookout.__path__)]
    while queue:
        importer, name, ispkg, prefix = queue.pop(0)

        if not ispkg or name == "core":
            continue

        m = importer.find_module(name).load_module(name)
        if getattr(m, "__meta__", False):
            queue.extend(tuple(c) + (prefix + name + ".",)
                         for c in pkgutil.iter_modules(m.__path__))
            continue

        try:
            cls = m.analyzer_class
        except AttributeError:
            continue
        if first:
            first = False
        else:
            print()
        print(prefix + name)
        print("\t%s" % cls.version)
        print("\t" + cls.description)

def run_analyzers(args: argparse.Namespace):
    """
    Launch the service with the specified analyzers. Blocks until a KeyboardInterrupt.

    :param args: Parsed command line arguments.
    :return: None
    """
    log = logging.getLogger("run")
    model_repository = create_model_repo_from_args(args)
    log.info("Created %s", model_repository)
    if args.request_server == "auto":
        data_request_address = "%s:10301" % args.server.split(":")[0]
    else:
        data_request_address = args.request_server
    data_service = DataService(data_request_address)
    log.info("Created %s", data_service)
    sys.path.append(os.getcwd())
    manager = AnalyzerManager(
        analyzers=[importlib.import_module(a).analyzer_class for a in args.analyzer],
        model_repository=model_repository,
        data_service=data_service,
    )
    sys.path = sys.path[:-1]
    log.info("Created %s", manager)
    listener = EventListener(address=args.server, handlers=manager, n_workers=args.workers)
    log.info("Created %s", listener)
    listener.start()
    log.info("Listening %s", args.server)
    listener.block()
    model_repository.shutdown()
    data_service.shutdown()

def init_repo(args: argparse.Namespace):
    """
    Initialize the model repository.

    :param args: Parsed command line arguments.
    :return: None
    """
    repo = create_model_repo_from_args(args)
    repo.init()

def run_analyzer_tool(args: argparse.Namespace) -> None:
    """
    Invoke the tooling of an analyzer.

    :param args: Parsed command line arguments.
    :return: None
    """
    with patch("sys.argv", [args.analyzer] + args.args):
        importlib.import_module(args.analyzer).run_cmdline_tool()

def create_model_repo_from_args(args: argparse.Namespace) -> SQLAlchemyModelRepository:
    """
    Get SQLAlchemyModelRepository from command line arguments.

    :param args: `argparse` parsed arguments.
    :return: Constructed instance of SQLAlchemyModelRepository.
    """
    return SQLAlchemyModelRepository(
        db_endpoint=args.db, fs_root=args.fs,
        max_cache_mem=humanfriendly.parse_size(args.cache_size),
        ttl=int(humanfriendly.parse_timespan(args.cache_ttl)),
        engine_kwargs=args.db_kwargs)

def add_model_repository_args(parser):
    """
    Add command line flags specific to the model repository.

    :param parser: `argparse` parser where to add new flags.
    """
    parser.add("-d", "--db", required=True, help="Model repository database address.")
    parser.add("-f", "--fs", required=True, help="Model repository file system root.")
    parser.add("--cache-size", default="1G",
               help="Model repository cache size - accepts human-readable values like 200M, 2G.")
    parser.add("--cache-ttl", default="6h",
               help="Model repository cache time-to-live (TTL) - accepts human-readable "
                    "values like 30min, 4h, 1d.")
    parser.add("--db-kwargs", type=json.loads, default={},
               help="Additional keyword arguments to SQLAlchemy database engine.")

def add_analyzer_arg(parser):
    """
    Add the variable count argument to specify analyzers.

    :param parser: `argparse` parser where to add new flags.
    """
    parser.add("analyzer", nargs="+",
               help="Fully qualified package name with an analyzer. Current directory is "
                    "included into PYTHONPATH.")

def create_parser() -> configargparse.ArgParser:
    """
    Initialize the command line argument parser.
    """
    parser = configargparse.ArgParser(default_config_files=[
        "/etc/lookout/analyzer.conf", "~/.config/lookout/analyzer.conf"],
        formatter_class=ArgumentDefaultsHelpFormatterNoNone,
        auto_env_var_prefix="lookout_")
    slogging.add_logging_args(parser)
    subparsers = parser.add_subparsers(help="Commands", dest="command")

    def add_parser(name, help):
        return subparsers.add_parser(
            name, help=help, formatter_class=ArgumentDefaultsHelpFormatterNoNone)

    list_parser = add_parser("list", "Print globally available analyzers.")
    list_parser.set_defaults(handler=list_analyzers)

    run_parser = add_parser(
        "run", "Launch a new service with the specified (one or more) analyzers.")
    run_parser.set_defaults(handler=run_analyzers)
    add_analyzer_arg(run_parser)
    run_parser.add("-c", "--config", is_config_file=True,
                   help="Path to the configuration file with option defaults.")
    run_parser.add("-s", "--server", required=True,
                   help="Lookout server address, e.g. localhost:1234.")
    run_parser.add("-w", "--workers", type=int, default=1,
                   help="Number of threads which process Lookout events.")
    add_model_repository_args(run_parser)
    run_parser.add_argument("--request-server", default="auto",
                            help="Address of the data retrieval service. \"same\" means --server.")

    init_parser = add_parser("init", "Initialize the model repository.")
    init_parser.set_defaults(handler=init_repo)
    add_model_repository_args(init_parser)

    tool_parser = add_parser("tool", "Invoke the tooling of a given analyzer.")
    tool_parser.set_defaults(handler=run_analyzer_tool)
    tool_parser.add("analyzer", help="Fully qualified package name with an analyzer.")
    tool_parser.add("args", nargs=argparse.REMAINDER)

    package_parser = add_parser(
        "package",
        "Package several analyzers to a Docker container and write a sample Docker Compose config "
        "for Lookout.")
    package_parser.set_defaults(handler=package_cmdline_entry)
    add_analyzer_arg(package_parser)
    package_parser.add("-w", "--workdir", help="Generate files in this directory.",
                       default=tempfile.mkdtemp(prefix="lookout_package_"))
    package_parser.add("--requirements", help="Path to a custom requirements.txt")
    package_parser.add("-r", "--repo", help="GitHub repository name to watch. "
                                            "Example: \"src-d/lookout\".",
                       required=True)
    package_parser.add("-u", "--user", help="GitHub user name which will send review comments.",
                       required=True)
    paturl = "https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/"  # noqa
    package_parser.add("-t", "--token", help="GitHub token for -u/--user. See " + paturl,
                       required=True)
    package_parser.add("-y", "--yes", help="Run the commands in the end.",
                       action="store_true")
    package_parser.add("-n", "--no", help="Do not run the commands in the end.",
                       action="store_true")
    return parser


from dockerspawner import DockerSpawner
from traitlets import default
from tornado import gen
import jupyterhub
import requests

SERVER = 'http://localhost:5005'

def default_format_volume_name(template, spawner):
    return template.format(username=spawner.user.name,
                           user_ID=spawner.user.name.split('+')[0],
                           project_name=spawner.user.name.split('+')[1])

class MyDockerSpawner(DockerSpawner):
    tb_port = '6006'

    @property
    def extra_create_kwargs(self):
        return {"ports": {'%i/tcp' % self.port: None, '6006/tcp': None}}

    @property
    def extra_host_config(self):
        return {"port_bindings": {self.port: (self.host_ip,),
                                  '6006': (self.host_ip,)}}

    @default('format_volume_name')
    def _get_default_format_volume_name(self):
        return default_format_volume_name

    @gen.coroutine
    def get_tb_port(self):
        tb_resp = yield self.docker('port', self.container_id, self.tb_port)
        port = int(tb_resp[0]['HostPort'])
        return port

    @staticmethod
    def update_project_tb_port(project_name, tb_port):
        """
        update tb port when docker restarted
        :param tb_port:
        :param project_name:
        :return: dict of res json
        """
        print('update project tb_port: ', project_name, tb_port)
        return requests.put(f'{SERVER}/project/projects/{project_name}?by=name'
                            , json={'tb_port': str(tb_port)})

    @staticmethod
    def insert_envs(project_name):
        """
        add env to jupyterlab
        :param tb_port:
        :param project_name:
        :return: dict of res json
        """
        return requests.put(f'{SERVER}/apps/insert_envs/{project_name}')

    @gen.coroutine
    def start(self, image=None, extra_create_kwargs=None,
              extra_start_kwargs=None, extra_host_config=None):
        """Start the single-user server in a docker container. You can override
        the default parameters passed to `create_container` through the
        `extra_create_kwargs` dictionary and passed to `start` through the
        `extra_start_kwargs` dictionary.  You can also override the
        'host_config' parameter passed to `create_container` through the
        `extra_host_config` dictionary.

        Per-instance `extra_create_kwargs`, `extra_start_kwargs`, and
        `extra_host_config` take precedence over their global counterparts.

        """
        container = yield self.get_container()
        if container and self.remove_containers:
            self.log.warning(
                "Removing container that should have been cleaned up: %s (id: %s)",
                self.container_name, self.container_id[:7])
            # remove the container, as well as any associated volumes
            yield self.docker('remove_container', self.container_id, v=True)
            container = None

        if container is None:
            image = image or self.image
            if self._user_set_cmd:
                cmd = self.cmd
            else:
                image_info = yield self.docker('inspect_image', image)
                cmd = image_info['Config']['Cmd']
            cmd = cmd + self.get_args()

            # build the dictionary of keyword arguments for create_container
            create_kwargs = dict(
                image=image,
                environment=self.get_env(),
                volumes=self.volume_mount_points,
                name=self.container_name,
                command=cmd,
            )

            # ensure internal port is exposed
            create_kwargs['ports'] = {'%i/tcp' % self.port: None}

            create_kwargs.update(self.extra_create_kwargs)
            if extra_create_kwargs:
                create_kwargs.update(extra_create_kwargs)

            # build the dictionary of keyword arguments for host_config
            host_config = dict(binds=self.volume_binds, links=self.links)

            if hasattr(self, 'mem_limit') and self.mem_limit is not None:
                # If jupyterhub version > 0.7, mem_limit is a traitlet that can
                # be directly configured. If so, use it to set mem_limit.
                # this will still be overriden by extra_host_config
                host_config['mem_limit'] = self.mem_limit

            if not self.use_internal_ip:
                host_config['port_bindings'] = {self.port: (self.host_ip,)}
            host_config.update(self.extra_host_config)
            host_config.setdefault('network_mode', self.network_name)

            if extra_host_config:
                host_config.update(extra_host_config)

            self.log.debug("Starting host with config: %s", host_config)

            host_config = self.client.create_host_config(**host_config)
            create_kwargs.setdefault('host_config', {}).update(host_config)

            # create the container
            resp = yield self.docker('create_container', **create_kwargs)
            self.container_id = resp['Id']
            self.log.info(
                "Created container '%s' (id: %s) from image %s",
                self.container_name, self.container_id[:7], image)

        else:
            self.log.info(
                "Found existing container '%s' (id: %s)",
                self.container_name, self.container_id[:7])
            # Handle re-using API token.
            # Get the API token from the environment variables
            # of the running container:
            for line in container['Config']['Env']:
                if line.startswith(
                        ('JPY_API_TOKEN=', 'JUPYTERHUB_API_TOKEN=')):
                    self.api_token = line.split('=', 1)[1]
                    break

        # TODO: handle unpause
        self.log.info(
            "Starting container '%s' (id: %s)",
            self.container_name, self.container_id[:7])

        # build the dictionary of keyword arguments for start
        start_kwargs = {}
        start_kwargs.update(self.extra_start_kwargs)
        if extra_start_kwargs:
            start_kwargs.update(extra_start_kwargs)

        # start the container
        yield self.docker('start', self.container_id, **start_kwargs)

        ip, port = yield self.get_ip_and_port()
        if jupyterhub.version_info < (0, 7):
            # store on user for pre-jupyterhub-0.7:
            self.user.server.ip = ip
            self.user.server.port = port
        tb_port = yield self.get_tb_port()
        # update tb_port and module env to exist app
        self.update_project_tb_port(self.user.name, tb_port)
        self.insert_envs(self.user.name)
        # jupyterhub 0.7 prefers returning ip, port:
        return ip, port


import asyncio
import base64
import cv2
import numpy as np
import websockets
import AI_function_img_pose_add
import AI_function_img_face

async def handler(websocket):
    data = await websocket.recv()
    if data == 'face':
      while True:
          data = await websocket.recv()
          img = cv2.imdecode(np.frombuffer(base64.b64decode(data.split(',')[1]), np.uint8), cv2.IMREAD_COLOR)
          result = AI_function_img_face.handle(img)
          if result != None and len(result) > 0:
            await websocket.send(result)
    elif data == 'pose':
      while True:
          data = await websocket.recv()
          img = cv2.imdecode(np.frombuffer(base64.b64decode(data.split(',')[1]), np.uint8), cv2.IMREAD_COLOR)
          result = AI_function_img_pose_add.handle(img)
          if result != None and len(result) > 0:
            await websocket.send(result)

async def main():
    async with websockets.serve(handler, "172.31.11.131", 9999):
      await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())


from core.utils         import getDateTimeObjGotEbayStr, getShrinkItemURL

from ebayinfo           import getEbayShippingChoiceCode

from pyPks.Utils.Config import getBoolOffYesNoTrueFalse

d = dict

# null = True, blank = True fields in model MUST be marked bOptional here!
dItemFoundFields = d(
    iItemNumb       = d( t = ( 'itemId',),
                         f = int ),
    cTitle          = d( t = ( 'title',) ),
    cSubTitle       = d( t = ( 'subtitle', ),
                         bOptional = True ),
    cLocation       = d( t = ( 'location',) ),
    cCountry        = d( t = ( 'country',) ),
    cMarket         = d( t = ( 'globalId',) ),
    iEbaySiteID     = d( t = ( 'iEbaySiteID',), # must use cMarket to look this up
                         bCalculate = True ),
    cGalleryURL     = d( t = ( 'galleryURL',), bOptional = True ),
    cEbayItemURL    = d( t = ( 'viewItemURL',),
                         f = getShrinkItemURL ),
    tTimeBeg        = d( t = ( 'listingInfo','startTime'),
                         f = getDateTimeObjGotEbayStr ),
    tTimeEnd        = d( t = ( 'listingInfo','endTime'),
                         f = getDateTimeObjGotEbayStr ),
    bBestOfferable  = d( t = ( 'listingInfo','bestOfferEnabled'),
                         f = getBoolOffYesNoTrueFalse ),
    bBuyItNowable   = d( t = ( 'listingInfo','buyItNowAvailable'),
                         f = getBoolOffYesNoTrueFalse ),
    lBuyItNowPrice  = d( t = ( 'listingInfo',
                               'buyItNowPrice','__value__'),
                         f = float,
                         bOptional = True ),
    dBuyItNowPrice  = d( t = ( 'listingInfo',
                               'convertedBuyItNowPrice','__value__'),
                         f = float,
                         bOptional = True ),
    cListingType    = d( t = ( 'listingInfo','listingType') ),
    lLocalCurrency  = d( t = ( 'sellingStatus','currentPrice','@currencyId') ),
    lCurrentPrice   = d( t = ( 'sellingStatus','currentPrice','__value__'),
                         f = float ),
    dCurrentPrice   = d( t = ( 'sellingStatus',
                               'convertedCurrentPrice','__value__'),
                         f = float ),
    iShippingType   = d( t = ( 'shippingInfo', 'shippingType'),
                         f = getEbayShippingChoiceCode ),
    iHandlingTime   = d( t = ( 'shippingInfo', 'handlingTime'),
                         f = int,
                         bOptional = True ),
    iCategoryID     = d( t = ( 'primaryCategory','categoryId'),
                         f = int ),
    cCategory       = d( t = ( 'primaryCategory','categoryName') ),

    iCatHeirarchy   = d( t = ( 'iCatHeirarchy',), # not from ebay, calculated
                         bCalculate = True ),
    i2ndCategoryID  = d( t = ( 'secondaryCategory','categoryId'),
                         f = int,
                         bOptional = True ),
    c2ndCategory    = d( t = ( 'secondaryCategory','categoryName'),
                         bOptional = True ),
    i2ndCatHeirarchy= d( t = ( 'i2ndCatHeirarchy',), # not from ebay, calculated
                         bCalculate = True ),
    iConditionID    = d( t = ( 'condition','conditionId'),
                         f = int,
                         bOptional = True ),
    cCondition      = d( t = ( 'condition','conditionDisplayName'),
                         bOptional = True ),
    cSellingState   = d( t = ( 'sellingStatus','sellingState') ) )

dUserItemFoundUploadFields = d(
    iItemNumb       = d( t = ( 'itemId',),
                         f = int ),
    tTimeEnd        = d( t = ( 'listingInfo','endTime'),
                         f = getDateTimeObjGotEbayStr ),
    iSearch         = d( t = () ),
    iUser           = d( t = () ),
    tCreate         = d( t = () ), # why does this not work for tCreate?
    bAuction        = d( t = (), bCalculate = True ) )


# Escribimos el nombre de las reservas en un fichero de texto
guests = open("guests.txt", "w")
initial_guests = ["Bob", "Andrea", "Manuel", "Polly", "Khalid"]

for i in initial_guests:
    guests.write(i + "\n")

guests.close()

# Leemos el contenido por consola
with open("guests.txt") as guests:
    for line in guests:
        print(line)
# Agregamos 3 reservas nuevas
new_guests = ["Sam", "Danielle", "Jacob"]

# Abirmos el archivo y añadimos las nuevas reservas
with open("guests.txt", "w") as guests:
    for i in new_guests:
        guests.write(i + "\n")

guests.close()

# Vemos de nuevo las reservas
with open("guests.txt") as guests:
    for line in guests:
        print(line)

# Registramos las salidas
checked_out = ["Andrea", "Manuel", "Khalid"]
temp_list = []

# Agregamos la lista temporal elimando los espacios en blanco
with open("guests.txt", "r") as guests:
    for g in guests:
        temp_list.append(g.strip())

# Eliminamos los nombres de la lista check-out
with open("guests.txt", "w") as guests:
    for name in temp_list:
        if name not in checked_out:
            guests.write(name + "\n")

# Vemos de nuevo las reservas
with open("guests.txt") as guests:
    for line in guests:
        print(line)

# Verificamos si Bob y Andrea han hecho check-in
guests_to_check = ['Bob', 'Andrea']
checked_in = []

with open("guests.txt", "r") as guests:
    for g in guests:
        checked_in.append(g.strip())
    for check in guests_to_check:
        if check in checked_in:
            print("{} is checked in".format(check))
        else:
            print("{} is not checked in".format(check))

Module -2 Using Python to Interact with the Operating System/Week -2 Managing Files With Python/Read Writing Files/laboratory/hotel/hotel.py


# import sys
# sys.stdin = open("swea_1989_input.txt", "r")

n = int(input())

for i in range(1, n+1):
    word = input()
    k = int(len(word)/2+1)
    l = int(len(word)/2)
    magimak = int(len(word))

    if len(word) % 2 == 1:
        if word[0:k] == word[magimak:k-2:-1]:
            print(f'#{i} 1')
        else:
            print(f'#{i} 0')
    elif len(word) % 2 == 0:
        if word[0:l] == word[magimak:l-1:-1]:
            print(f'#{i} 1')
        else:
            print(f'#{i} 0')


import json
import os

path='C:\\Users\\ECE-ML\\Desktop\\sample data\\'

class keypoint:
    def __init__(self, path):
        self.path = path

    def get_jsonfile_path(self):
        keypoint_dirs = []
        all_label_jsonfile = []
        for dir in os.listdir(self.path):
            keypoint_dir = os.path.join(self.path, dir)
            keypoint_dirs.append(keypoint_dir)  # get keypoint path
        for path_keypoint_dir in keypoint_dirs:  # all of the keypoint path
            same_label_jsonfile = []
            for json_file in os.listdir(path_keypoint_dir):  # all the file in path
                json_file_dir = os.path.join(path_keypoint_dir, json_file)  # join the path and name of file
                same_label_jsonfile.append(json_file_dir)
            all_label_jsonfile.append(same_label_jsonfile)
        return all_label_jsonfile
        # print(json_file_dir)
        # C:\Users\ECE-ML\Desktop\video_json_word\000000\P01_01_00_0_color.json

    def get_x_y(self, keypoint):
        allvideo_coordinate = []
        for onelabel_folder in self.get_jsonfile_path():
            onelabel_allvideo_coordinate = []
            for onejsonfile in onelabel_folder:
                video_frame_coordinate = []
                with open(onejsonfile, 'r') as f:
                    data = json.load(f)  # all frames data in one video
                    for num_frame in range(1, len(data), 1):
                        # frame number in one video
                        frame_coordinate = []
                        frame_data = data[num_frame]
                        data_body = frame_data[keypoint]
                        data_body_list = data_body[0]
                        for data_x_y_num in range(len(data_body_list)):  # one frame x and y
                            data_keypoint = data_body_list[data_x_y_num]
                            data_x_y = tuple((data_keypoint[0], data_keypoint[1]))
                            frame_coordinate.append(data_x_y)
                        video_frame_coordinate.append(frame_coordinate)
                onelabel_allvideo_coordinate.append(video_frame_coordinate)
            allvideo_coordinate.append(onelabel_allvideo_coordinate)
        return allvideo_coordinate
    def left_hand_keypoint(self):
        return self.get_x_y('Left hand keypoint')

    def right_hand_keypoint(self):
        return self.get_x_y('right hand keypoint')

    def body_keypoint(self):
        return self.get_x_y('body keypoint')

    def Face_keypoint(self):
        return self.get_x_y('Face keypoint')


import argparse
import os
import re
import sys
import time

# Command line arguments
parser=argparse.ArgumentParser(description='Calculate the shortest path between all pairs of vertices in a graph')
parser.add_argument('--algorithm',default='a',\
    help='Algorithm: Select the algorithm to run, default is all. (a)ll, (b)ellman-ford only or (f)loyd-warshall only')
parser.add_argument('-v','--verbose',action='store_true')
parser.add_argument('--profile',action='store_true')
parser.add_argument('filename',metavar='<filename>',help='Input file containing graph')

graphRE=re.compile("(\\d+)\\s(\\d+)")
edgeRE=re.compile("(\\d+)\\s(\\d+)\\s(-?\\d+)")

vertices=[]
edges=[]

def BellmanFord(G):
    pathPairs=[]
    # TODO: Fill in your Bellman-Ford algorithm here
    temp = edges
    for i in range(len(vertices)):
        temp[i][i] = 0

    for Lp in range(len(vertices)):
        dist = []
        for i in range(len(vertices)):
            dist.append(float("inf"))
        dist[Lp] = 0
        for i in range(len(vertices) - 1):
            for j in range(len(dist)):
                for k in range(len(dist)):
                    if dist[j] != float("inf") and float(dist[k]) > float(dist[j]) + float(temp[j][k]):
                        dist[k] = int(dist[j]) + int(temp[j][k])
                        dist[k] = str(dist[k])

        for x in range(len(dist)):
            for y in range(len(dist)):
                if float(dist[y]) > float(dist[x]) + float(temp[x][y]):
                    print("N/A")
        pathPairs.append(dist)

    for i in pathPairs:
        print(i)

    print('BellmanFord algorithm is complete')
    # The pathPairs list will contain the 2D array of shortest paths between all pairs of vertices
    # [[w(1,1),w(1,2),...]
    #  [w(2,1),w(2,2),...]
    #  [w(3,1),w(3,2),...]
    #   ...]
    return pathPairs

def FloydWarshall(G):
    pathPairs=[]
    # TODO: Fill in your Floyd-Warshall algorithm here
    dist = []
    Lp = []
    for i in edges:
        k = []
        for j in i:
            if j != float("inf"):
                k.append(int(j))
            elif j == float("inf"):
                k.append(float("inf"))
        Lp.append(k)
    for a in range(len(vertices)):
        c = []
        for b in range(len(vertices)):
            c.append(float("inf"))
        dist.append(c)
    for i in range(len(dist)):
        for j in range(len(dist)):
            if i == j:
                dist[i][j] = 0
            elif Lp[i][j] != float("inf"):
                dist[i][j] = Lp[i][j]

    for x in range(len(vertices)):
        for y in range(len(vertices)):
            for z in range(len(vertices)):
                if dist[y][z] > dist[y][x] + dist[x][z]:
                    dist[y][z] = dist[y][x] + dist[x][z]
    pathPairs = dist

    for i in pathPairs:
        print(i)

    print('FloydWarshall algorithm is complete')
    # The pathPairs list will contain the 2D array of shortest paths between all pairs of vertices
    # [[w(1,1),w(1,2),...]
    #  [w(2,1),w(2,2),...]
    #  [w(3,1),w(3,2),...]
    #   ...]
    return pathPairs

def readFile(filename):
    global vertices
    global edges
    # File format:
    # <# vertices> <# edges>
    # <s> <t> <weight>
    # ...
    inFile=open(filename,'r')
    line1=inFile.readline()
    graphMatch=graphRE.match(line1)
    if not graphMatch:
        print(line1+" not properly formatted")
        quit(1)
    vertices=list(range(int(graphMatch.group(1))))
    edges=[]
    for i in range(len(vertices)):
        row=[]
        for j in range(len(vertices)):
            row.append(float("inf"))
        edges.append(row)
    for line in inFile.readlines():
        line = line.strip()
        edgeMatch=edgeRE.match(line)
        if edgeMatch:
            source=edgeMatch.group(1)
            sink=edgeMatch.group(2)
            if int(source) > len(vertices) or int(sink) > len(vertices):
                print("Attempting to insert an edge between "+source+" and "+sink+" in a graph with "+vertices+" vertices")
                quit(1)
            weight=edgeMatch.group(3)
            edges[int(source)-1][int(sink)-1]=weight
    G = (vertices,edges)
    return (vertices,edges)

def matrixEquality(a,b):
    if len(a) == 0 or len(b) == 0 or len(a) != len(b): return False
    if len(a[0]) != len(b[0]): return False
    for i,row in enumerate(a):
        for j,value in enumerate(b):
            if a[i][j] != b[i][j]:
                return False
    return True

def main(filename,algorithm):
    G=readFile(filename)
    pathPairs = []
    # G is a tuple containing a list of the vertices, and a list of the edges
    # in the format ((source,sink),weight)
    if algorithm == 'b' or algorithm == 'B':
        # TODO: Insert timing code here
        start_time = time.time()
        pathPairs = BellmanFord(G)
        print("<<%s seconds>>" % (time.time() - start_time))
    if algorithm == 'f' or algorithm == 'F':
        # TODO: Insert timing code here
        start_time = time.time()
        pathPairs = FloydWarshall(G)
        print("<<%s seconds>>" % (time.time() - start_time))
    if algorithm == 'a':
        print('running both')
        start_time = time.time()
        pathPairsBellman = BellmanFord(G)
        print("<<%s seconds>>" % (time.time() - start_time))
        start_time = time.time()
        pathPairsFloyd = FloydWarshall(G)
        print("<<%s seconds>>" % (time.time() - start_time))
        pathPairs = pathPairsBellman
        if matrixEquality(pathPairsBellman,pathPairsFloyd):
            print('Floyd-Warshall and Bellman-Ford did not produce the same result')
    with open(os.path.splitext(filename)[0]+'_shortestPaths.txt','w') as f:
        for row in pathPairs:
            for weight in row:
                f.write(str(weight)+' ')
            f.write('\n')

if __name__ == '__main__':
    args=parser.parse_args()
    main(args.filename,args.algorithm)


"""
Income Data Sorter By State and County

    Open_file():
        Open file for reading, prompt until successful
    Get_County_State():
        Extract county and state from string
    Read_File():
        Loop through file, make tuple list (state, county, median_income)

    State_Average_Income():
        Find income average for counties in state
    Top_Counties_By_Income():
        Find top ten income counties in decreasing order
    Bottom_Counties_By_Income():
        Find the bottom ten income counties in decreasing order
    Top_States_By_Income():
        Find top ten income states in decreasing order
    Bottom_States_By_Income():
        Find bottom ten income counties decreasing order
    Counties_In_State():
        Find tuple list with counties, incomes sorted alphabetically

    Display_Options():
        Display menu of options for program, take option input

    Main():
        Open_file()
        Read_File()
        User Input Loop
            Display_Options()
            Option Decision Tree
                1- State_Average_Income()
                2- Top_Counties_By_Income()
                3- Bottom_Counties_By_Income()
                4- Top_States_By_Income()
                5- Bottom_States_By_Income()
                6- Counties_In_State()

"""

# Import Library
import csv
from operator import itemgetter

# Constants
STATES = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
          "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
          "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
          "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
          "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"]

def open_file(ch):
    """File name hardcoded here for demo purposes"""
    """Opens file for reading, prompts until successful"""

    # User Input Loop
    # while True:
    #     # Reading file
    #     if ch == "r":
    #         try:
    #             file_str = input('Input a file: ')
    #             file_pointer = open(file_str, 'r')
    #             break
    #         except IOError:
    #             print('Invalid filename, please try again.')
    file_pointer = open("data.csv", 'r')
    return file_pointer

def get_county_state(s):
    """Extract county and state from string"""

    # Split the line, extract state and county
    format_list = s.split(",")
    state = format_list[1]
    county = format_list[0]

    # Remove leading and trailing spaces
    state = state.strip()
    county = county.strip()

    return county, state

def read_file(fp):
    """ Loop through file, make tuple list (state, county, median_income)"""

    # Skip Header
    fp.readline()

    # Read file, extract columns 1 and 10, put into place name and income lists
    name_list = []
    income_list = []
    reader = csv.reader(fp)

    for line_list in reader:
        name_list.append(line_list[1])

        # Remove Commas from income
        if line_list[10] != "":
            format_list = line_list[10].split(",")
            format_str = "".join(format_list)
            income_list.append(int(format_str))
        else:
            income_list.append(line_list[10])

    # Separate state and county, match up place with income
    stats_list = []
    income_count = 0

    for name in name_list:
        # Call the get_county_state to separate the county and state
        county, state = get_county_state(name)
        stats_tuple = state, county, income_list[income_count]

        # If there is no value for income, ignore that county
        if stats_tuple[2] != "":
            stats_list.append(stats_tuple)

        income_count += 1

    # Return a list of tuples (state, county, median_income)
    # in decreasing order of median_income
    return sorted(stats_list, key=itemgetter(2), reverse=True)

def state_average_income(state, master_list):
    """Find median income average for counties in state"""

    # Check for incorrect spelling
    if state not in STATES:
        return None

    # Add up incomes
    total = 0
    count = 0
    for county_tuple in master_list:
        if county_tuple[0] == state:
            total += county_tuple[2]
            count += 1

    # Check for wrong state
    if count == 0:
        return None

    avg = total/count

    return round(avg, 2)

def top_counties_by_income(master_list):
    """Find top ten counties by median income in decreasing order"""

    income_order_list = sorted(master_list, key=itemgetter(2), reverse=True)
    top_ten_list = income_order_list[0:10]

    return top_ten_list

def bottom_counties_by_income(master_list):
    """Find the bottom ten counties by median incomes in decreasing order"""

    income_order_list = sorted(master_list, key=itemgetter(2), reverse=True)
    bottom_ten_list = income_order_list[-10:]

    return bottom_ten_list

def top_states_by_income(master_list):
    """Find top ten states by average median incomes in decreasing order"""

    # Call state_average_income for each state, sort
    avg_list = []
    for state in STATES:
        # Make list of each state and average income in tuples
        stats_list = [state, state_average_income(state, master_list)]

        # Check if income value is empty
        try:
            float(stats_list[1])
            avg_list.append(stats_list)
        except TypeError:
            continue

    # Return tuple list where each tuple is (state, average_median_income)
    avg_list = sorted(avg_list, key=itemgetter(1), reverse=True)
    return avg_list[0:10]

def bottom_states_by_income(master_list):
    """Find bottom ten counties by median incomes in decreasing order"""

    # Call state_average_income for each state, sort
    avg_list = []
    for state in STATES:
        # Make list of each state and average income in tuples
        stats_list = [state, state_average_income(state, master_list)]

        # Check if income value is empty
        try:
            float(stats_list[1])
            avg_list.append(stats_list)
        except TypeError:
            continue

    # Return tuple list where each tuple is (state, average_median_income)
    avg_list = sorted(avg_list, key=itemgetter(1))
    return avg_list[:10]

def counties_in_state(state, master_list):
    """Find tuple list with counties, median incomes sorted alphabetically"""

    # Find counties in state, extract name and income
    county_list = []
    for in_tuple in master_list:
        # Check if county is in state
        if in_tuple[0] == state:
            stats_list = tuple([in_tuple[1], in_tuple[2]])
            county_list.append(stats_list)

    # Return a list of tuples (county, median_income)
    county_tuple = sorted(county_list, key=itemgetter(0))
    return county_tuple

def display_options():
    """Display menu of options for program, take option input"""

    OPTIONS = """\nMenu
    1: Average median household income in a state
    2: Highest median household income counties
    3: Lowest median household income counties
    4: Highest average median household income states
    5: Lowest average median household income states
    6: List counties' median household income in a state\n"""

    print(OPTIONS)

    option = input('Choose an option, q to quit: ')

    return option

def main():
    print("\nMedian Income Data")

    # Call open_file to open an input file for reading
    fp = open_file("r")

    # Call read_file to read the desired data into a “master” list of tuples.
    master_list = read_file(fp)

    # Display menu of options, prompt for input, execute options
    # Loop until the input is "q"
    option = ""
    while option != "q":
        option = display_options()

        # Check if quitting or numerical input
        if option.isalpha():
            pass
        else:
            option = int(option)

        # Option Decision Tree
        if option == 1:

            # Prompt user for 2-letter code until valid
            while True:
                state = input('Please enter a 2-letter state code: ').upper()

                # Checks for spelling, calls state_average_income
                if state in STATES:
                    income = state_average_income(state, master_list)
                    break
                else:
                    print('Please input a valid state')

            # Display income
            print('\nAverage median income in {:2s}: ${:<10,.2f}'
                  .format(state, income))

        elif option == 2:

            # Call top_counties_by_income to determine the top 10
            display_list = top_counties_by_income(master_list)

            # Display Header Lines
            print('\nTop 10 Counties by Median Household Income (2018)')
            print('{:<10}{:<30s}{:10s}'
                  .format('State', 'County', 'Median Household Income'))

            # Display Data
            for e in display_list:
                print('{:<10}{:<30s}${:<10,d}'.format(e[0], e[1], e[2]))

        elif option == 3:

            # Call bottom_counties_by_income
            display_list = bottom_counties_by_income(master_list)

            # Display Header Lines
            print('\nBottom 10 Counties by Median Household Income (2018)')
            print('{:<10}{:<30s}{:10s}'
                  .format('State', 'County', 'Median Household Income'))

            # Display Data
            for e in display_list:
                print('{:<10}{:<30s}${:<10,d}'.format(e[0], e[1], e[2]))

        elif option == 4:

            # Call top_states_by_income
            display_list = top_states_by_income(master_list)

            # Display Header Lines
            print('\nTop 10 States by Average Median Household Income (2018)')
            print('{:<10}{:<10s}'.format('State', 'Median Household Income'))

            # Display Data
            for e in display_list:
                print('{:<10}${:<10,.2f}'.format(e[0], e[1]))

        elif option == 5:

            # Call bottom_states_by_income
            display_list = bottom_states_by_income(master_list)

            # Display Header Lines
            print('\nBottom 10 States by\
                  Average Median Household Income (2018)')
            print('{:<10}{:<10s}'.format('State', 'Median Household Income'))

            # Display Data
            for e in display_list:
                print('{:<10}${:<10,.2f}'.format(e[0], e[1]))

        elif option == 6:

            # Prompt user for 2-letter code until valid
            while True:
                state = input('Please enter a 2-letter state code: ').upper()

                if state in STATES:
                    income = state_average_income(state, master_list)
                    break
                else:
                    print('Please input a valid state')

            # Find counties in state
            display_list = counties_in_state(state, master_list)

            # Display Data
            if len(display_list) > 0:
                print('\nThere are {} counties in {}:'
                      .format(len(display_list), state))
                print('{:<30s}{:<10}'
                      .format('County', 'Median Household Income'))
            else:
                print('\nThere are 0 counties in {}'.format(state))

            for e in display_list:
                print('{:<30s}${:<10,d}'.format(e[0], e[1]))

        elif option == "q":
            # Pause before break
            pass

        else:
            # Error for wrong input
            print('Invalid choice, please try again')

if __name__ == '__main__':
    main()


import click

from pyBrown_tools.input_RotDiff import InputDataRotDiff
from pyBrown_tools.messaging import timestamp
from pyBrown_tools.trajectories import read_trajectories, add_auxiliary_data_multibeads, \
								 compute_orientations, compute_mean_orientation_autocorrelation, \
								 save_mean_orientation_autocorrelation_to_file, \
								 compute_mean_squared_angular_displacements, \
								 save_mean_squared_angular_displacements_to_file
from pyBrown_tools.plotting import plot_msads, plot_moas

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

@click.command()
@click.argument('input_filename',
				type = click.Path( exists = True ))
def main(input_filename):

	# here the list of keywords that are required for program to work is provided
	required_keywords = ["labels", "sizes", "box_size", "input_xyz_template", "input_xyz_range"]

	# here the dict of keywords:default values is provided
	# if given keyword is absent in JSON, it is added with respective default value
	defaults = {"debug": False, "verbose": False, "probing_frequency": 1,
				"min_time": 0.0, "mode": "window", "float_type": 32}

	timestamp( 'Reading input from {} file', input_filename )
	i = InputDataRotDiff(input_filename, required_keywords, defaults)
	timestamp( 'Input data:\n{}', i )

	timestamp( 'Reading trajectories' )
	times, labels, auxiliary_data = read_trajectories(i.input_data)
	add_auxiliary_data_multibeads( i.input_data, labels, auxiliary_data )
	timestamp( 'Separating the rotational movement' )
	orientation_labels = compute_orientations( i.input_data, labels, auxiliary_data )
	del labels

	timestamp( 'Computing mean orientation autocorrelations' )
	moas = compute_mean_orientation_autocorrelation( i.input_data, orientation_labels, auxiliary_data )
	timestamp( 'Saving mean orientation autocorrelations to a file' )
	save_mean_orientation_autocorrelation_to_file(i.input_data, times, moas)

	timestamp( 'Computing mean squared angular displacements' )
	msads = compute_mean_squared_angular_displacements( i.input_data, orientation_labels, auxiliary_data )
	timestamp( 'Saving mean squared angular displacements to a file' )
	save_mean_squared_angular_displacements_to_file(i.input_data, times, msads)
	del orientation_labels

	timestamp( 'Plotting mean squared angular displacements' )
	plot_msads(i.input_data, times, msads)

	timestamp( 'Plotting mean orientation autocorrelations' )
	plot_moas(i.input_data, times, moas)

	del times
	del moas
	del msads

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

if __name__ == '__main__':

	main()


from typing import Any, List
# from entity_linking.REL import rel_wrapper
import codecs
import wikipediaapi
import time
import requests
import logging

wiki = wikipediaapi.Wikipedia('en')

API_URL = "https://rel.cs.ru.nl/api"

def entity_link(text):

    if text is None:
        return []

    res = requests.post(API_URL, json={
            "text": text,
            "spans": []
        }).json()

    res = [(x[3]) for x in res]
    return res

def get_wiki_text(wiki_title):
    page = wiki.page(wiki_title)

    if page.exists():
        return page.text
    else:
        return None

# Reading Comprehension Model
class AllenNLPRoBERTa():
    def __init__(self):
        from allennlp.predictors.predictor import Predictor
        import allennlp_models.rc
        self.predictor = Predictor.from_path("https://storage.googleapis.com/allennlp-public-models/transformer-qa.2021-02-11.tar.gz")

    def predict(self, question:str, context:str) -> str:
        try:
            results = self.predictor.predict(question, context)
            if results['best_span'][0] == -1:
                return None
            # return results
            return results['best_span_str'], results['best_span_probs'], results['best_span_scores']
        except:
            return None

# Wikipedia text splitter
filtered_sections = set(['References', 'Sources', 'Further reading', 'External links', 'See also'])

def get_text_by_section(section, out:List[str]) -> None:
    if section.title in filtered_sections:
        return

    if len(section.sections) == 0:
        out.append(section.text)
    else:
        for s in section.sections:
            get_text_by_section(s, out)

def flatten(t:List[List[Any]]) -> List[Any]:
    return [item for sublist in t for item in sublist]

def split_article(wiki_title:str, max_tokens:int=-1) -> List[str]:
    page = wiki.page(wiki_title)

    # print(page.sections)
    all_text = []
    get_text_by_section(page, all_text)

    # This does not actually guarantee text is split into less than max_tokens lol
    if max_tokens > 0:
        def split_long_texts(text):
            if len(text.split()) > max_tokens:
                return text.split('\n')
            return [text]
        all_text = flatten([split_long_texts(text) for text in all_text])

    return all_text

if __name__ == '__main__':

    logging.getLogger('allennlp.common.params').disabled = True
    logging.getLogger('allennlp.nn.initializers').disabled = True
    logging.getLogger('allennlp.modules.token_embedders.embedding').setLevel(logging.INFO)
    logging.getLogger('urllib3.connectionpool').disabled = True

    prompt = """
    Robert Walker argued that failing to take this action would lead to an overflow of Northern insane asylums and British intervention.
    Juan Almonte resigned his diplomatic post in indignation over this event.
    Isaac Van Zandt began discussing this plan with Abel Upshur before Upshur died.
    Anson Jones proposed this plan, which reduced his own power but reserved the weaker side the right to split
    into five parts in the future. Five years after it, a payment of 10 million dollars helped the area at issue repay debts.
    The Regulator-Moderator war was calmed just before this deal was struck.
    The question of whether the Nueces River became a southern border in this transaction led to war later in James K Polk's presidency.
    For 10 points, name this deal that ended the independent Lone Star Republic.
    """

    sentences = prompt.split(".")
    model = AllenNLPRoBERTa()

    for sent in sentences:
        entities = entity_link(sent)
        print(entities)
        for e in entities:
            sections = split_article(e)
            for section in sections:
                prediction = model.predict(sent, section)
                if prediction:
                    data = {
                        # 'label': question['page'],
                        'model_output': prediction[0],
                        'model_output_probs': prediction[1],
                        'model_output_score': prediction[2],
                    }
                    print(data)


"""
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the
elements in both subsets is equal or false otherwise.

Example 1:

Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:

Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
"""

"""

This problem is essentially let us to find whether there are several numbers in a set which are able to sum to a
specific value (in this problem, the value is sum/2).

Actually, this is a 0/1 knapsack problem, for each number, we can pick it or not. Let us assume dp[i][j] means whether
the specific sum j can be gotten from the first i numbers. If we can pick such a series of numbers from 0-i whose sum
is j, dp[i][j] is true, otherwise it is false.

Base case: dp[0][0] is true; (zero number consists of sum 0 is true)

Transition function: For each number, if we don't pick it, dp[i][j] = dp[i-1][j], which means if the first i-1 elements
has made it to j, dp[i][j] would also make it to j (we can just ignore nums[i]).
If we pick nums[i]. dp[i][j] = dp[i-1][j-nums[i]], which represents that j is composed of the current value nums[i]
and the remaining composed of other previous numbers.
Thus, the transition function is dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i]]

public boolean canPartition(int[] nums) {
    int sum = 0;

    for (int num : nums) {
        sum += num;
    }

    if ((sum & 1) == 1) {
        return false;
    }
    sum /= 2;

    int n = nums.length;
    boolean[][] dp = new boolean[n+1][sum+1];
    for (int i = 0; i < dp.length; i++) {
        Arrays.fill(dp[i], false);
    }

    dp[0][0] = true;

    for (int i = 1; i < n+1; i++) {
        dp[i][0] = true;
    }
    for (int j = 1; j < sum+1; j++) {
        dp[0][j] = false;
    }

    for (int i = 1; i < n+1; i++) {
        for (int j = 1; j < sum+1; j++) {
            dp[i][j] = dp[i-1][j];
            if (j >= nums[i-1]) {
                dp[i][j] = (dp[i][j] || dp[i-1][j-nums[i-1]]);
            }
        }
    }

    return dp[n][sum];
}
"""

class Solution:
  def canPartition(self, nums) -> bool:
    summ = sum(nums)
    if summ & 1:
      return False
    return self.knapsack_(nums, summ // 2)

  def knapsack_(self, nums, subsetSum: int) -> bool:
    n = len(nums)
    # dp[i][j] := True if j can be formed by nums[0..i)
    dp = [[False] * (subsetSum + 1) for _ in range(n + 1)]
    dp[0][0] = True

    for i in range(1, n + 1):
      num = nums[i - 1]
      for j in range(subsetSum + 1):
        if j < num:
          dp[i][j] = dp[i - 1][j]
        else:
          dp[i][j] = dp[i - 1][j] or dp[i - 1][j - num]

    return dp[n][subsetSum]

if __name__ == "__main__":
    sol = Solution()
    print(sol.canPartition(nums=[1,5,11,5]))


import argparse
from functools import lru_cache
import itertools
import random
from urllib.parse import urlparse

from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint

from autowebcompat import network
from autowebcompat import utils

SAMPLE_SIZE = 3000
BATCH_SIZE = 32
EPOCHS = 50
random.seed(42)

parser = argparse.ArgumentParser()
parser.add_argument('-n', '--network', type=str, choices=network.SUPPORTED_NETWORKS, help='Select the network to use for training')
parser.add_argument('-o', '--optimizer', type=str, choices=network.SUPPORTED_OPTIMIZERS, help='Select the optimizer to use for training')
parser.add_argument('-es', '--early_stopping', dest='early_stopping', action='store_true', help='Stop training training when validation accuracy has stopped improving.')
args = parser.parse_args()

bugs = utils.get_bugs()

utils.prepare_images()
all_images = utils.get_all_images()[:SAMPLE_SIZE]
image = utils.load_image(all_images[0])
input_shape = image.shape

TRAIN_SAMPLE = 80 * (SAMPLE_SIZE // 100)
VALIDATION_SAMPLE = 10 * (SAMPLE_SIZE // 100)
TEST_SAMPLE = SAMPLE_SIZE - (TRAIN_SAMPLE + VALIDATION_SAMPLE)

bugs_to_website = {}
for bug in bugs:
    bugs_to_website[bug['id']] = urlparse(bug['url']).netloc

@lru_cache(maxsize=len(all_images))
def site_for_image(image):
    bug = image[:image.index('_')]
    return bugs_to_website[int(bug)]

def are_same_site(image1, image2):
    return site_for_image(image1) == site_for_image(image2)

random.shuffle(all_images)
images_train, images_validation, images_test = all_images[:TRAIN_SAMPLE], all_images[TRAIN_SAMPLE:VALIDATION_SAMPLE + TRAIN_SAMPLE], all_images[SAMPLE_SIZE - TEST_SAMPLE:]

def couples_generator(images):
    # for image_couple in itertools.combinations_with_replacement(images, 2):
    for image_couple in itertools.combinations(images, 2):
        yield image_couple, 1 if are_same_site(image_couple[0], image_couple[1]) else 0

def gen_func(images):
    return utils.balance(couples_generator(images))

train_couples_len = sum(1 for e in gen_func(images_train))
validation_couples_len = sum(1 for e in gen_func(images_validation))
test_couples_len = sum(1 for e in gen_func(images_test))

print('Training with %d couples.' % train_couples_len)
print('Validation with %d couples.' % validation_couples_len)
print('Testing with %d couples.' % test_couples_len)
print(input_shape)

data_gen = utils.get_ImageDataGenerator(all_images, input_shape)
train_iterator = utils.CouplesIterator(utils.make_infinite(gen_func, images_train), input_shape, data_gen, BATCH_SIZE)
validation_iterator = utils.CouplesIterator(utils.make_infinite(gen_func, images_validation), input_shape, data_gen, BATCH_SIZE)
test_iterator = utils.CouplesIterator(utils.make_infinite(gen_func, images_test), input_shape, data_gen, BATCH_SIZE)

model = network.create(input_shape, args.network)
network.compile(model, args.optimizer)

callbacks_list = [ModelCheckpoint('best_pretrain_model.hdf5', monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')]

if args.early_stopping:
    callbacks_list.append(EarlyStopping(monitor='val_accuracy', patience=2))

model.fit_generator(train_iterator, callbacks=callbacks_list, validation_data=validation_iterator, steps_per_epoch=train_couples_len / BATCH_SIZE, validation_steps=validation_couples_len / BATCH_SIZE, epochs=EPOCHS)

score = model.evaluate_generator(test_iterator, steps=test_couples_len / BATCH_SIZE)
print(score)

asd = utils.CouplesIterator(utils.make_infinite(gen_func, images_test[:100]), input_shape, data_gen)
predict_couples_len = sum(1 for e in utils.balance(couples_generator(images_test)))
predictions = model.predict_generator(asd, steps=predict_couples_len / BATCH_SIZE)
print(predictions)
print([a[1] for a in utils.balance(couples_generator(images_test[:100]))])


#DISCLAIMER - The logic of the code on Line 18 has been taken from SteamGridDB (https://github.com/SteamGridDB/steamgriddb-manager) [MIT License].

import os, binascii, json, wget, ssl, traceback, sys
import configpath
from gameName import rspchar

def checkartworkexists(artwork_path, image):

    check_flag = 0

    for i in os.listdir(artwork_path):

        if i in image:
            check_flag = 1
            break

    if check_flag == 1:

        return True
    else:

        return False

def addartwork(appname, exe, userid, simplified_gamename):

    #As Steam does not store AppIDs of Non-Steam games in any config file, this makes it difficult to add artwork without knowing the AppID.
    #One way is to add the game, let Steam assign the AppID and then try to find the AppID using regex.
    #Fortunately, SteamGridDB (MIT License) has found a simple and efficient solution to calculate the AppID.

    #ALL CREDIT GOES TO THE STEAMGRIDDB DEVS FOR THIS IMPLEMENTATION (Line 18).
    #Here's how the it's explained in their source code -
        #To create a grid image we must compute the Steam ID, which is just crc32(target + label) + "02000000", using IEEE standard polynomials.
    appid = binascii.crc32(str.encode(exe + appname)) | 0x80000000
    print("Steam AppID for " + appname + " is " + str(appid))

    #Path to Steam grid folder
    artwork_path = os.path.expanduser("~") + '/.steam/steam/userdata/' + str(userid) + '/config/grid'

    #Artwork types
    coverart =  [str(appid) + 'p.jpg', str(appid) + 'p.png']
    backgroundart = [str(appid) + '_hero.jpg', str(appid) + '_hero.png']
    bigpictureart = [str(appid) + '.jpg', str(appid) + '.png']

    #Check if the folder exists, create if not
    grid_exists = os.path.isdir(artwork_path)

    if not grid_exists:
        os.makedirs(artwork_path)
        print("Created grid folder in ", artwork_path)

    try:

        print("Checking Artwork...")

        #GameFiles dir if non-Flatpak
        if configpath.is_flatpak == True:
            GameFiles = ""
        else:
            GameFiles = "GameFiles/"

        #Reading from file
        openscript = open(GameFiles + simplified_gamename + ".sh", 'r')
        readscript = openscript.read()
        openscript.close()

        #Avoid SSL certificate error
        ssl._create_default_https_context = ssl._create_unverified_context

        #Check if game is Epic or GOG
        if "EPIC" in readscript:

            #print("Epic")

            with open(configpath.heroiclibrarypath, encoding='utf-8') as l:
                epicinstalled = json.load(l)

            for i in epicinstalled['library']:

                gamename = rspchar(i['title'])

                if appname == gamename:

                    #Cover Art
                    if checkartworkexists(artwork_path, coverart) == False:

                        image_url = i['art_square']
                        print("Downloading Cover Art from " + image_url)
                        wget.download(image_url, out = artwork_path)
                        os.rename(artwork_path + '/' + image_url.split("/")[-1], artwork_path + '/' + coverart[0])
                    else:
                        print("Covert Art exists")

                    #Background Art
                    if checkartworkexists(artwork_path, backgroundart) == False:

                        image_url = i['art_cover']
                        print("Downloading Background Art from " + image_url)
                        wget.download(image_url, out = artwork_path)
                        os.rename(artwork_path + '/' + image_url.split("/")[-1], artwork_path + '/' + backgroundart[0])
                    else:
                        print("Background Art exists")

                    #BigPicture Art
                    if checkartworkexists(artwork_path, bigpictureart) == False:

                        image_url = i['art_cover']
                        print("Downloading BigPicture Art from " + image_url)
                        wget.download(image_url, out = artwork_path)
                        os.rename(artwork_path + '/' + image_url.split("/")[-1], artwork_path + '/' + bigpictureart[0])
                    else:
                        print("BigPicture Art exists")
        elif "GOG" in readscript:

            #print("GOG")

            with open(configpath.goglibrarypath, encoding='utf-8') as l:
                goginstalled = json.load(l)

            for i in goginstalled['games']:

                gamename = rspchar(i['title'])

                if appname == gamename:

                    #Cover Art
                    if checkartworkexists(artwork_path, coverart) == False:

                        image_url = i['art_square']
                        print("Downloading Cover Art from " + image_url)
                        wget.download(image_url, out = artwork_path)
                        extract_image_url = image_url.split("/")[-1]
                        os.rename(artwork_path + '/' + extract_image_url.split("?")[0], artwork_path + '/' + coverart[0])
                    else:
                        print("Covert Art exists")

                    #Background Art
                    if checkartworkexists(artwork_path, backgroundart) == False:

                        image_url = i['art_cover']
                        print("Downloading Background Art from " + image_url)
                        wget.download(image_url, out = artwork_path)
                        os.rename(artwork_path + '/' + image_url.split("/")[-1], artwork_path + '/' + backgroundart[0])
                    else:
                        print("Background Art exists")

                    #BigPicture Art
                    if checkartworkexists(artwork_path, bigpictureart) == False:

                        image_url = i['art_cover']
                        print("Downloading BigPicture Art from " + image_url)
                        wget.download(image_url, out = artwork_path)
                        os.rename(artwork_path + '/' + image_url.split("/")[-1], artwork_path + '/' + bigpictureart[0])
    except Exception:

        print(traceback.format_exc())
        os.system('zenity --error --title="Process Failed" --text="Failed to add artwork. Please check the log for the error and consider reporting it as an issue on Github." --width=400')
        sys.exit()


"""Finds prime numbers using sieve of eratosthenes"""

def sieve(num):
    """create a boolean array "prime[0...n]" and initialize all entries as True.
     A value in prime[i] will finally be false if i is not prime, else True"""

    prime = [True for i in range(num + 1)]
    p = 2
    while p * p <= num:
        # If prime[p] is not changed then it is a prime number
        if prime[p] is True:
            # update all multiples of p
            for i in range(p * 2, num + 1, p):
                prime[i] = False
        # print all prime numbers
        for p in range(2, num):
            if prime[p]:
                print(p)

# Driver program
# if __name__ == '__main__':
#     num = 30
#     print("The list of prime numbers below or equal to", end=" ")
#     print(num, end=" is: \n")
#     sieve(num)


from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(ChromeDriverManager().install())
path_to_extension = r'C:\Users\lera-\AppData\Local\Google\Chrome\User Data\Default\Extensions\gighmmpiobklfepjocnamgkkbiglidom\4.46.2_0'
chrome_options = Options()
chrome_options.add_argument('load-extension=' + path_to_extension)
driver.create_options()
time.sleep(10)
driver.maximize_window()
driver.implicitly_wait(5)
first_browser_tab = driver.window_handles[0]
driver.switch_to.window(first_browser_tab)
driver.get("http://demo.automationtesting.in/WebTable.html")
driver.implicitly_wait(5)
more = driver.find_element_by_link_text("More")
more.click()
bar = driver.find_element_by_link_text("JQuery ProgressBar")
bar.click()
button = WebDriverWait(driver, 10).until(
    EC.invisibility_of_element_located((By.ID, ".ui-dialog-buttonset > button")))
start_download = driver.find_element_by_id("downloadButton")
start_download.click()
some_element= WebDriverWait(driver, 10).until(
    EC.text_to_be_present_in_element((By.CSS_SELECTOR, ".ui-dialog-buttonset"), "Cancel Download"))
close_btn = driver.find_element_by_css_selector(".ui-dialog-buttonset > button")
close_btn.click()
start_download = driver.find_element_by_id("downloadButton")
start_download.click()
some_element= WebDriverWait(driver, 10).until(
    EC.text_to_be_present_in_element((By.CSS_SELECTOR, ".progress-label"), "Complete!"))
driver.quit()


#!/usr/bin/env python3
#
# cmp_pickle.py file1.pickle file2.pickle
#

import pickle
import sys
import re

from deepdiff import DeepDiff

def report(ddiff):
    for k,v in ddiff.items():
        print('#',k)
        if re.match(r'.*_added', k):
            for x in v:
                print('+', x)
        elif re.match(r'.*_removed', k):
            for x in v:
                print('-', x)
        elif re.match(r'.*_changed', k):
            for kk, vv in v.items():
                print('*', kk)
                for kkk, vvv in vv.items():
                    if re.match(r'new_', kkk):
                        print('  +', vvv)
                    else:
                        print('  -', vvv)
        else:
            print('?', k,v)

with open(sys.argv[1], "rb") as f:
    p1 = pickle.load(f)
with open(sys.argv[2], "rb") as f:
    p2 = pickle.load(f)

def setify_labels(data):
    if isinstance(data, dict):
        for k,v in data.items():
            data[k] = setify_labels(v)
        if 'labels' in data:
            data['labels'] = set(data['labels'])
    return data

p1 = setify_labels(p1)
p2 = setify_labels(p2)

ddiff = DeepDiff(p1.get('scantree'), p2.get('scantree'))

report(ddiff)


"""This script reads our requirements.txt file and removes the pinned versions"""

import re
import os
from os.path import abspath, dirname

TOP_LEVEL = abspath(dirname(dirname(dirname(__file__))))
REQUIREMENTS = os.path.join(TOP_LEVEL, 'requirements.txt')
BUILD_REQUIREMENTS = os.path.join(TOP_LEVEL, 'build_tools', 'build_requirements.txt')

def find_latest_dependencies(*requirements_files):
    """Given one or more requirements.txt files, strip off any pinned versions

    Parameters
    ----------
    *requirements_files : str
        One or more paths to requirements.txt files to parse

    Returns
    -------
    requirements : list
        List of parsed dependencies without their pinned versions
    """
    requirements = []
    for requirements_file in requirements_files:
        with open(requirements_file) as file:
            for line in file:
                requirement = line.strip()
                if line.startswith('#'):
                    continue
                match = re.match(r'^([A-Za-z\-0-9]+)', requirement)
                if match.group(0).lower() not in requirements:
                    requirements.append(match.group(0).lower())

    return requirements

requirements = find_latest_dependencies(REQUIREMENTS, BUILD_REQUIREMENTS)
# We print because this is called from a bash script and we need to return a
# space-separated list
print(' '.join(requirements))


import copy
from collections import Counter

with open('../inputs/day_14_input.txt') as f:
    lines = f.readlines()

    base = list(lines[0].strip())
    rules = {}

    for l in lines:
        if '->' in l:
            res = l.strip().split(' -> ')
            rules[res[0]] = res[1]

    steps = 40
    for i in range(steps):
        base_copy = []
        for j in range(len(base)-1):
            base_copy.append(base[j])
            if base[j] + base[j+1] in rules:
                base_copy.append(rules[base[j]+base[j+1]])
        base_copy.append(base[len(base)-1])

        base = base_copy
        #print("After step {}: {}".format(i, base))

    c = Counter(base).most_common()
    print(c[0], c[-1], c[0][1]-c[-1][1])