from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalMaxPooling1D
from keras_preprocessing.text import Tokenizer

# set parameters:
num_words = 10
embedded_dims = 5
maxlen = 5
batch_size = 100
filters = 10
kernel_size = 2
hidden_dims = 2
epochs = 20

# create data that represents it taking longer to travel home from work, than to travel to
docs = ['home daycare work', 'home daycare work', 'work daycare home', 'work daycare home', 'home work', 'work home', 'home work', 'work home']
docs_eos = list(map(lambda x: '<go> ' + x, docs))
docs_eos = list(map(lambda x: x + ' <eos>', docs_eos))
y = [35, 34, 47, 46, 18,  23, 19, 26]

# set up the word tokenizer
# TO DO adda a stemmer some home
t = Tokenizer(num_words=10,  oov_token='<oov>')
t.fit_on_texts(docs_eos)

# extract a work sequence
x_seqs = t.texts_to_sequences(docs_eos)

# padding seqs
x_padded = sequence.pad_sequences(x_seqs, maxlen=maxlen)

# initialized the model
model = Sequential()

# our vocab indices into embedding_dims dimensions
model.add(Embedding(num_words,
                    embedded_dims,
                    input_length=maxlen))

# word group filters of size filter_length:
model.add(Conv1D(filters,
                 kernel_size,
                 padding='valid',
                 activation='relu',
                 strides=1))
# we use max pooling:
model.add(GlobalMaxPooling1D())

# We project onto a single unit output layer, and squash it with a sigmoid:
model.add(Dense(1))
model.add(Activation('linear'))

model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['mae'])
model.fit(x_padded, y,
          epochs=epochs)
print('completed')

def predict(docs, maxlen=maxlen):
    docs_eos = list(map(lambda x: '<go> ' + x, docs))
    docs_eos = list(map(lambda x: x + ' <eos>', docs_eos))
    docs_seq = t.texts_to_sequences(docs_eos)
    x_padded = sequence.pad_sequences(docs_seq, maxlen=maxlen)
    return model.predict(x_padded)

test_data = ['home daycare work', 'work daycare home']

print(predict(test_data))


from train_network import create_one_hot_encoding, encode_labels, create_labels
from keras.models import load_model, Sequential
import os
import pickle
import numpy as np
import tensorflow as tf

input_width = 128
input_height = 128

if __name__ == "__main__":
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.25)
    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

    label_dict, emotions_list = create_labels()
    one_hot_encoding = create_one_hot_encoding(emotions_list)
    encoded_labels = encode_labels(label_dict, one_hot_encoding, emotions_list)

    with open('./image_data_dict/images_test.dictionary', 'rb') as image_dict_file:
        validate_image_dict = pickle.load(image_dict_file)
        amount_images = len(validate_image_dict.keys())
        x_train = np.empty(shape=(amount_images, input_width, input_height, 1), dtype=int)
        y_train = np.empty(shape=(amount_images, 8), dtype=int)
        index = 0
        for image_name, image_data in validate_image_dict.items():
            if image_name in encoded_labels.keys() and image_data.shape[0] == input_width:
                x_train[index] = image_data
                y_train[index] = (encoded_labels[image_name])
                index += 1

    model_path = "model"
    model_name = "facial_model.h5"
    path = os.path.join(model_path, model_name)
    model = load_model(path)
    model.fit(x_train, y_train, batch_size=32, epochs=1, validation_split=.1, verbose=2)


import pathlib
from setuptools import setup, find_packages

PACKAGE_ROOT = pathlib.Path(__file__).resolve().parent

def list_reqs(fname='requirements.txt'):
    with open(fname) as f:
        return f.read().splitlines()

with open('README.md') as f:
    readme = f.read().strip()

with open(PACKAGE_ROOT / 'funding_model' / 'VERSION') as f:
    _version = f.read().strip()

setup(name='funding-model',
      version=_version,
      packages=find_packages(exclude=('tests', 'docs')),
      install_requires=list_reqs(),
      python_requires='>=3.7.0',
      author='Ali Naji',
      url="https://github.com/ali-naji",
      license='MIT',
      author_email='anaji7@gatech.edu',
      description="Classification model to predict whether a kickstarter project will be successfully funded",
      long_description=readme,
      package_data={'funding_model': ['VERSION']},
      classifiers=['License :: OSI Approved :: MIT License',
                   'Programming Language :: Python',
                   'Programming Language:: Python:: 3.7',
                   'Programming Language:: Python:: 3.8',
                   'Programming Language:: Python:: 3.9']
      )


## write an example agent and show that it does stuff
import numpy as np
import torch
import matplotlib.pyplot as plt

def get_action(agent, s):
    action, logprob, value = agent.get_action(s)
    return action

def agent_test(env, agent):
    maxsteps = 100
    for step in range(maxsteps):
        s = torch.Tensor(np.expand_dims(env.get_observation(), axis=0))

        action = get_action(agent, s)

        s_prime, r, done, __ = env.step(action)

        env.render()

        if step == maxsteps - 1 or done:
            plt.pause(2)
            plt.close()

        if done:
            break


import torch
import numpy as np
import utils.data_format_utils as df_utils
from data_processing.camera_pipeline import apply_gains, apply_ccm, apply_smoothstep, gamma_compression

class SimplePostProcess:
    def __init__(self, gains=True, ccm=True, gamma=True, smoothstep=True, return_np=False):
        self.gains = gains
        self.ccm = ccm
        self.gamma = gamma
        self.smoothstep = smoothstep
        self.return_np = return_np

    def process(self, image, meta_info):
        return process_linear_image_rgb(image, meta_info, self.gains, self.ccm, self.gamma,
                                        self.smoothstep, self.return_np)

def process_linear_image_rgb(image, meta_info, gains=True, ccm=True, gamma=True, smoothstep=True, return_np=False):
    if gains:
        image = apply_gains(image, meta_info['rgb_gain'], meta_info['red_gain'], meta_info['blue_gain'])

    if ccm:
        image = apply_ccm(image, meta_info['cam2rgb'])

    if meta_info['gamma'] and gamma:
        image = gamma_compression(image)

    if meta_info['smoothstep'] and smoothstep:
        image = apply_smoothstep(image)

    image = image.clamp(0.0, 1.0)

    if return_np:
        image = df_utils.torch_to_npimage(image)
    return image

class BurstSRPostProcess:
    def __init__(self, no_white_balance=False, gamma=True, smoothstep=True, return_np=False):
        self.no_white_balance = no_white_balance
        self.gamma = gamma
        self.smoothstep = smoothstep
        self.return_np = return_np

    def process(self, image, meta_info, external_norm_factor=None):
        return process_burstsr_image_rgb(image, meta_info, external_norm_factor=external_norm_factor,
                                         no_white_balance=self.no_white_balance, gamma=self.gamma,
                                         smoothstep=self.smoothstep, return_np=self.return_np)

def process_burstsr_image_rgb(im, meta_info, return_np=False, external_norm_factor=None, gamma=True, smoothstep=True,
                              no_white_balance=False):
    im = im * meta_info.get('norm_factor', 1.0)

    if not meta_info.get('black_level_subtracted', False):
        im = (im - torch.tensor(meta_info['black_level'])[[0, 1, -1]].view(3, 1, 1).to(im.device))

    if not meta_info.get('while_balance_applied', False) and not no_white_balance:
        im = im * (meta_info['cam_wb'][[0, 1, -1]].view(3, 1, 1) / meta_info['cam_wb'][1]).to(im.device)

    im_out = im

    if external_norm_factor is None:
        im_out = im_out / im_out.max()
    else:
        im_out = im_out / external_norm_factor

    im_out = im_out.clamp(0.0, 1.0)

    if gamma:
        im_out = im_out ** (1.0 / 2.2)

    if smoothstep:
        # Smooth curve
        im_out = 3 * im_out ** 2 - 2 * im_out ** 3

    if return_np:
        im_out = im_out.permute(1, 2, 0).cpu().numpy() * 255.0
        im_out = im_out.astype(np.uint8)

    return im_out


from keras.preprocessing.text import Tokenizer
import nltk
from nltk.tokenize import word_tokenize
import numpy as np
import re
from keras.utils import to_categorical
import pandas as pd
import pickle
from matplotlib import style
from collections import deque
import matplotlib.pyplot as plt

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Embedding
from keras.preprocessing.sequence import pad_sequences
from keras.optimizers import Adam
from keras import backend as K

import tensorflow as tf

import gym
import gym_chess
import random
import chess
import chess.engine
from gym_chess.alphazero import BoardEncoding

from difflib import SequenceMatcher

path = r'C:\Users\Octavio\Desktop\Projetos Python\Chess-RL\games.csv'
df = pd.read_csv(path)
df = df.dropna(subset=['moves'])
df = df[(df['winner'] == 'white') & (df['victory_status'] == 'mate')].reset_index()

class DQNAgent:
    def __init__(self, state_size, action_size):
        self.state_size = state_size
        self.action_size = action_size
        self.memory = deque(maxlen=5000)
        self.gamma = 0.999    # discount rate #0.95
        self.epsilon = 1.0  # exploration rate
        self.epsilon_min = 0.01
        self.epsilon_decay = 0.9 #0.99
        self.learning_rate = 1e-5 #0.001
        self.model = self._build_model()
        self.target_model = self._build_model()
        self.update_target_model()

    """Huber loss for Q Learning
    References: https://en.wikipedia.org/wiki/Huber_loss
                https://www.tensorflow.org/api_docs/python/tf/losses/huber_loss
    """

    def _huber_loss(self, y_true, y_pred, clip_delta=1.0):
        error = y_true - y_pred
        cond  = K.abs(error) <= clip_delta

        squared_loss = 0.5 * K.square(error)
        quadratic_loss = 0.5 * K.square(clip_delta) + clip_delta * (K.abs(error) - clip_delta)

        return K.mean(tf.where(cond, squared_loss, quadratic_loss))

    def _build_model(self):
        # Neural Net for Deep-Q learning Model
        model = Sequential()
        model.add(Dense(5, input_dim=self.state_size, activation='relu')) #24
        model.add(Dense(5, activation='relu')) #24
        model.add(Dense(self.action_size, activation='linear'))
        model.compile(loss=self._huber_loss,
                      optimizer=Adam(lr=self.learning_rate),
                      metrics=['accuracy'])
        return model

    def update_target_model(self):
        # copy weights from model to target_model
        self.target_model.set_weights(self.model.get_weights())

    def remember(self, state, action, reward, next_state, done):
        self.memory.append((state, action, reward, next_state, done))

    def act(self, state):
        ##With probability e select a random action at
        if np.random.rand() <= self.epsilon:
            return random.randrange(self.action_size)
        ##otherwise select at = maxa Q∗(φ(st), a; θ)
        act_values = self.model.predict(state)
        return np.argmax(act_values[0])

    def replay(self, batch_size): # train
        ##Sample random minibatch of transitions (φj , aj , rj , φj+1) from D
        minibatch = random.sample(self.memory, batch_size)
        #print(minibatch[0])
        ##Set yj = rj for terminal φj+1 or (rj + γ maxa0 Q(φj+1, a0; θ)) for non-terminal φj+1
        for state, action, reward, next_state, done in minibatch:
            target = self.model.predict(state)
            if done:
                target[0][action] = reward
            else:
                a = self.model.predict(next_state)[0]
                #a = self.target_model.predict(next_state)[0]
                max_future_q = np.amax(a)
                target[0][action] = reward + self.gamma * max_future_q
                # target[0][action] = reward + self.gamma * t[np.argmax(a)]

            ##Perform a gradient descent step on (yj − Q(φj , aj ; θ))^2
            history = self.model.fit(state, target, epochs=5, verbose=0)

        if self.epsilon > self.epsilon_min:
            self.epsilon *= self.epsilon_decay

        return history

    def load(self, name):
        self.model.load_weights(name)

    def save(self, name):
        self.model.save_weights(name)

def create_model(vocabulary_size, seq_len):
    model = Sequential()
    model.add(Embedding(vocabulary_size, seq_len, input_length=seq_len))
    model.add(LSTM(10,return_sequences=True))
    model.add(LSTM(10))
    model.add(Dense(10,activation='relu'))
    model.add(Dense(vocabulary_size, activation='softmax'))
    # compiling the network
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

    return model

#load
t_len = 10
model_name = f"chessML_len{t_len}.h5"
token_name = f"tokenizer_len{t_len}.pkl"

with open(token_name, 'rb') as handle:
    tokenizer = pickle.load(handle)

stats = pd.read_csv('train_data_log.csv')
vocabulary_size = stats['vocabulary_size'][0]
seq_len = stats['seq_len'][0]

model = create_model(vocabulary_size, seq_len)
model.load_weights(model_name)

def predict(seq_len,model, tokenizer,board, debug = False):
    next_moves = []
    input_text = board
    encoded_text = tokenizer.texts_to_sequences([input_text])[0]
    pad_encoded = pad_sequences([encoded_text], maxlen=seq_len, truncating='pre')
    #print(encoded_text, pad_encoded)

    for i in (model.predict(pad_encoded)[0]).argsort()[-3:][::-1]:
      pred_word = tokenizer.index_word[i]
      next_moves.append(pred_word)
      if debug:
          print("Next word suggestion:",pred_word)

    return next_moves

#predict(seq_len,model, tokenizer)

def make_matrix(board): #type(board) == chess.Board()
    pgn = board.epd()
    foo = []  #Final board
    pieces = pgn.split(" ", 1)[0]
    rows = pieces.split("/")

    mapped = {
        'P': 1,     # White Pawn
        'p': -1,    # Black Pawn
        'N': 2,     # White Knight
        'n': -2,    # Black Knight
        'B': 3,     # White Bishop
        'b': -3,    # Black Bishop
        'R': 4,     # White Rook
        'r': -4,    # Black Rook
        'Q': 5,     # White Queen
        'q': -5,    # Black Queen
        'K': 6,     # White King
        'k': -6     # Black King
        }

    for row in rows:
        foo2 = []  #This is the row I make
        for thing in row:
            if thing.isdigit():
                for i in range(0, int(thing)):
                    foo2.append(0)
            else:
                foo2.append(mapped[thing])
        foo.append(foo2)
    return foo

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

def act(cnt,df,seq_len, model, tokenizer, obs, legal_moves, opening: str=None, idx_open: int=0, debug = False, choice = 2):
    #start
    if cnt == 0:
        if opening == None:
            #random opening
            idx = random.choice([x for x in range(0,len(df['moves']))])
            moves = df['moves'][idx].split()
            move = moves[0]
        else:
            moves = df[df['opening_name'] == opening]['moves'].iloc[idx_open].split()
            move = moves[0]

        return move

    else:
        if choice == 0:
            if opening != None:
                if (cnt <= int(df[df['opening_name'] == opening]['opening_ply'].iloc[idx_open])):
                    moves = df[df['opening_name'] == opening]['moves'].iloc[idx_open].split()
                    move = moves[cnt]
                    return move
                else:
                    for idx,line in enumerate(df[df['opening_name'] == opening]['moves']):
                        op_idx = int(df[df['opening_name'] == opening]['opening_ply'].iloc[idx])
                        moves = line.split()[cnt:]
                        if len(moves) >= 3:
                            move = moves[2]
                            #print("teste: ", move)
                            if move in legal_moves:
                                print("teste certo: ", move)
                                return move
                        else:
                            return legal_moves[0]

        elif choice == 1:
            df2 = df.copy()
            df2['similarities'] = df2['moves'].apply(lambda x: similar(x.split(), obs))
            df2 = df2.sort_values(by=['similarities'], ascending = False)
            #moves = moves[cnt-1:]
            for i in range(0,len(df2['moves'])):
                moves = df2['moves'][i].split()
                if debug:
                    print("Similarity of , ", df2['similarities'][i] * 100, "%")
                    print(obs[-1])
                if obs[-1] in moves:
                    try:
                        if debug:
                            #similarity
                            print("Next move: ",moves[moves.index(obs[-1]) + 1])
                            print("game: ",moves[moves.index(obs[-1])-2:moves.index(obs[-1])+2])
                        move = moves[moves.index(obs[-1]) + 1]
                        if move in legal_moves:
                            break
                    except:
                        #ML predict
                        #print("Machine Learning")
                        board = ' '.join([str(elem) for elem in obs])
                        next_moves = predict(seq_len,model, tokenizer, board)
                        move = next_moves
                        move = [x.capitalize() if len(x) > 2 else x for x in move]
                        for i in move:
                            if i in legal_moves:
                                move = i
                                break
                else:
                    #ML predict
                    #print("Machine Learning")
                    board = ' '.join([str(elem) for elem in obs])
                    next_moves = predict(seq_len,model, tokenizer, board)
                    move = next_moves
                    move = [x.capitalize() if len(x) > 2 else x for x in move]
                    for i in move:
                        if i in legal_moves:
                            move = i
                            return move

                    move = random.choice(legal_moves)
                    return move

        elif choice == 2:
            result = engine.play(state, chess.engine.Limit(time=0.1))
            move = state.san(result.move)
            return move

episode_rewards = []
epsilon_time = []
moving_avg = []
action_time = []
choices_time = []
EPISODES = 64
SHOW_EVERY = 2

if __name__ == "__main__":

    env = gym.make('Chess-v0')
    print(env.render())

    state_size = 64
    action_size = 3
    agent = DQNAgent(state_size, action_size)
    try:
        agent.load("chess-ddqn.h5")
    except:
        pass

    batch_size = 64 #256
    move =""

    for e in range(EPISODES):
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        epsilon_time.append(agent.epsilon)
        if e % SHOW_EVERY == 0:
                print(f"on # {e}, epsilon: {agent.epsilon}")
                print(f"{SHOW_EVERY} ep mean {np.mean(episode_rewards[-SHOW_EVERY:])}")

        episode_reward = 0
        scores_eps = []
        done = False
        state = env.reset()
        cnt = 0
        obs = []
        mode = "for two"

        history_moves = []

        while not done:

            board_txt = state.fen().split()[0]
            board_encoded = ''.join(str(ord(c)) for c in board_txt)
            #obs = [board_encoded]
            obs = make_matrix(state)
            #obs = BoardEncoding(env, history_length=4).action_space

            print(done)
            print(state.is_game_over())
            if state.is_checkmate():
                result = "White" if reward > 0 else "Black"
                print(f"CHECKMATE! for {result}")
                done = True
                break
            elif state.is_stalemate() or state.is_insufficient_material() or state.is_game_over() or state.can_claim_threefold_repetition() or state.can_claim_fifty_moves() or state.can_claim_draw() or state.is_fivefold_repetition() or state.is_seventyfive_moves():
                done = True
                break
            #elif "#" in move:
            #    done = True

            if done:
                    print(env.render(mode='unicode'))
                    agent.update_target_model()
                    print("episode: {}/{}, score: {}, e: {:.2}".format(e, EPISODES, reward, agent.epsilon))
                    print(f"episode: {e}, reward: {episode_reward}")
                    break

            if e == EPISODES-1:
                action_time.append(action)

            if mode == 'alone':
                legal_moves = [state.san(x) for x in env.legal_moves]
                #choose action
                if cnt % 2 == 0: #white
                    #print("White turn")
                    opp = 'Scandinavian Defense: Mieses-Kotroc Variation'
                    if cnt == 2:
                        if move == 'd5':
                            opp = 'Scandinavian Defense: Mieses-Kotroc Variation' #e4 d5
                        elif move == 'e5':
                            opp = 'Scotch Game' #e4 e5

                    choice = agent.act(np.reshape(obs, [1, 64]))
                    print(agent.model.predict(np.reshape(obs, [1, 64])))
                    choices_time.append(choice)

                    move = act(cnt,df,seq_len, model,tokenizer,obs,legal_moves,opp,choice)
                    old_obs = obs.copy()
                    action = state.push_san(move)

                    next_state,reward,done,_ = env.step(action)

                    info = engine.analyse(state, chess.engine.Limit(time=0.1))
                    mate = info["score"].white().mate()
                    score = info["score"].white().score()
                    score = score if score != None else 0
                    print("Action: ",choice ," Score:", score, " Mate in: ", mate)

                    scores_eps.append(score)
                    #reward = score if score != None else 0
                    reward = np.average(scores_eps)

                    board_txt = next_state.fen().split()[0]
                    board_encoded = ''.join(str(ord(c)) for c in board_txt)
                    #obs = [board_encoded]
                    obs = make_matrix(state)

                    agent.remember(np.reshape(old_obs, [1, 64]), choice, reward, np.reshape(obs, [1, 64]), done)
                    state = next_state

                    episode_reward = reward

                else: #black
                    #print("Black turn")
                    move = act(cnt,df,seq_len, model,tokenizer,obs,legal_moves,choice=2)
                    action = state.push_san(move)
                    #take action
                    state,reward,done,_ = env.step(action)

                #append action
                history_moves.append(move)

                ##Sample random minibatch of transitions (φj , aj , rj , φj+1) from D
                if len(agent.memory) > batch_size:
                    #print("train")
                    ##Set yj = rj for terminal φj+1 or (rj + γ maxa0 Q(φj+1, a0; θ)) for non-terminal φj+1
                    history = agent.replay(batch_size)
                    print(history.history['acc'])

            elif mode == "for two":
                if cnt % 2 == 0:
                    print("PC turn")
                    legal_moves = [state.san(x) for x in env.legal_moves]
                    #choose action
                    opp = 'Scandinavian Defense: Mieses-Kotroc Variation'
                    if cnt == 2:
                        if move == 'd5':
                            opp = 'Scandinavian Defense: Mieses-Kotroc Variation' #e4 d5
                        elif move == 'e5':
                            opp = 'Scotch Game' #e4 e5

                    choice = agent.act(np.reshape(obs, [1, 64]))
                    print(agent.model.predict(np.reshape(obs, [1, 64])))
                    choices_time.append(choice)

                    move = act(cnt,df,seq_len, model,tokenizer,obs,legal_moves,opp,choice)
                    old_obs = obs.copy()
                    action = state.push_san(move)

                    next_state,reward,done,_ = env.step(action)

                    info = engine.analyse(state, chess.engine.Limit(time=0.1))
                    mate = info["score"].white().mate()
                    score = info["score"].white().score()
                    score = score if score != None else 0
                    print("Action: ",choice ," Score:", score, " Mate in: ", mate)

                    scores_eps.append(score)
                    #reward = score if score != None else 0
                    reward = np.average(scores_eps)

                    board_txt = next_state.fen().split()[0]
                    board_encoded = ''.join(str(ord(c)) for c in board_txt)
                    #obs = [board_encoded]
                    obs = make_matrix(state)

                    agent.remember(np.reshape(old_obs, [1, 64]), choice, reward, np.reshape(obs, [1, 64]), done)
                    state = next_state

                    episode_reward = reward

                    #append action
                    history_moves.append(move)

                    ##Sample random minibatch of transitions (φj , aj , rj , φj+1) from D
                    if len(agent.memory) > batch_size:
                        #print("train")
                        ##Set yj = rj for terminal φj+1 or (rj + γ maxa0 Q(φj+1, a0; θ)) for non-terminal φj+1
                        history = agent.replay(batch_size)
                        print(history.history['acc'])

                    print(f"PC Move {move}")
                else:
                    print("Human turn")
                    valid = False
                    while not valid:
                        move = input("Choose a move: ")
                        obs.append(move)
                        try:
                            action = state.push_san(move)
                            valid = True
                        except:
                            valid = False
                            obs.pop()
                            print("Wrong move, choosing other move")
                    #take action
                    state,reward,done,_ = env.step(action)

            #print(env.render(mode='unicode'))
            cnt += 1
            #print(" ")

        # if e % 10 == 0:
        if e % 2 == 0:
            agent.save("chess-ddqn.h5")

        env.close()
        engine.quit()
        episode_rewards.append(episode_reward)

    moving_avg = np.convolve(episode_rewards, np.ones((SHOW_EVERY,)) / SHOW_EVERY, mode = "valid")
    plt.subplot(221)
    #plt.plot([i for i in range(len(episode_rewards))], episode_rewards)
    plt.plot([i for i in range(len(moving_avg))], moving_avg)
    plt.ylabel(f"reward {SHOW_EVERY}ma")
    plt.xlabel("episode #")
    plt.title("Episode rewards Mov Avg")

    plt.subplot(222)
    plt.plot([i for i in range(len(episode_rewards))], episode_rewards)
    #plt.plot([i for i in range(len(epsilon_time))], epsilon_time)
    plt.title("Episode rewards")

    plt.subplot(223)
    plt.plot([i for i in range(len(epsilon_time))], epsilon_time)
    plt.title("Epsilon")

    plt.subplot(224)
    plt.plot([i for i in range(len(choices_time))], choices_time)
    plt.title("Choices")

    plt.show()


import numpy as np
import gym
import scipy
import scipy.signal
import matplotlib.pyplot as plt
from functools import partial

def discretize_val(val, min_val, max_val, num_states):
    """
	Discretizes a single float
	if val < min_val, it gets a discrete value of 0
	if val >= max_val, it gets a discrete value of num_states-1

	Args:
	    val (float): value to discretize
	    min_val (float): lower bound of discretization
	    max_val (float): upper bound of discretization
	    num_states (int): number of discrete states

	Returns:
	    float: discrete value
	"""
    state = int(num_states * (val - min_val) / (max_val - min_val))
    if state >= num_states:
        state = num_states - 1
    if state < 0:
        state = 0
    return state

def observationToState(num_states, lower_bounds, upper_bounds, obs):
    """
	Turns an observation into a discrete state

	Args:
	    num_states (list): list of number of states for each dimension of observation
	    lower_bounds (list): list of lowerbounds for discretization
	    upper_bounds (list): list of upperbounds for discretization
	    obs (list): observation in R^N to discretize

	Returns:
	    int: discrete state
	"""
    state_idx = []
    for ob, lower, upper, num in zip(obs, lower_bounds, upper_bounds, num_states):
        state_idx.append(discretize_val(ob, lower, upper, num))

    return np.ravel_multi_index(state_idx, num_states)

def EpsilonGreedyPolicy(Q, eps, state):
    sample = np.random.random_sample()

    num_actions = Q.shape[1]

    if sample > eps:
        max_val = Q[state, :].max()
        max_indices = np.where(np.abs(Q[state, :] - max_val) < 1e-5)[0]
        rand_idx = np.random.randint(len(max_indices))
        max_action = max_indices[rand_idx]

        return max_action
    else:
        return np.random.randint(num_actions)

# Initialize policy
def initPi(Q, eps):
    pi = partial(EpsilonGreedyPolicy, Q, eps)
    return pi

def UpdatePi(Q, eps):
    pi = partial(EpsilonGreedyPolicy, Q, eps)
    return pi

def initQ(stateLength, numberOfActions):
    Q = np.zeros((stateLength, numberOfActions))
    return Q

def initReturns(stateLength, numberOfActions):
    returns = {}
    for i, value in enumerate(Q):
        returns[i,0] = []
        returns[i,1] = []
    return returns

def play(env, policy,stateMapping, display):
    obs = env.reset()
    # prev_screen = env.render(mode='rgb_array')
    # plt.imshow(prev_screen)
    rewards = []
    actions = []
    states = []
    totalRewards = 0
    while True:
        state = stateMapping(obs)
        action = policy(state)
        actions.append(action)
        states.append(state)

        obs, reward, done, info = env.step(action)
        if display == True:
            screen = env.render(mode='rgb_array')
            plt.imshow(screen)
        totalRewards += reward
        rewards.append(reward)
        if done == True:
            #print(obs)
            break

        #print(totalRewards)
    return states, actions, rewards

env = gym.make('CartPole-v0')

eps = 0.05
gamma = 1
numberOfActions = env.action_space.n
numberOfStates = [10, 8, 10, 8]
lowerBounds = [-2.4, -9999, -0.21, -9999]
upperBounds = [2.4, 9999, 0.21, 9999]
stateMapping = partial(observationToState, numberOfStates, lowerBounds, upperBounds)
stateLength = np.prod(np.array(numberOfStates))
Q = initQ(stateLength, numberOfActions)
returns = initReturns(stateLength, numberOfActions)
policy = initPi(Q, eps)
rewardList = []
avg = 0
for i in range(20000):
    if i%100 == 0 and i != 0:
        print("i = " + str(i) + ", and average reward over past 100 episode " + str(avg/ 100))
        avg = 0
        states, actions, rewards = play(env, policy, stateMapping, False)
    else:
        states, actions, rewards = play(env, policy,stateMapping,False)

    seen = set()
    G = 0
    for i, (state, action, reward) in enumerate(zip(reversed(states), reversed(actions), reversed(rewards))):
        if i == 0:
            G = G * gamma
        else:
            G = G * gamma + rewards[i - 1]
        if state in seen:
            continue

        seen.add(state)
        returns[state,action].append(G)

        Q[state, action] = sum(returns[state,action])/ len(returns[state,action])
        policy = UpdatePi(Q,eps)
    avg += sum(rewards)
    rewardList.append(sum(rewards))
plt.plot(rewardList)
plt.show()
eps = 0
policy = UpdatePi(Q, eps)
avg = 0
for i in range(100):
    states, actions, rewards = play(env, policy, stateMapping, False)
    avg += sum(rewards)
print(avg)
play(env, policy,stateMapping, True)


from flask import Flask, request, Markup, render_template, flash
import json

app = Flask(__name__)

@app.route('/')
def render_home():
    return render_template('home.html')

@app.route('/about')
def render_about():
    return render_template('about.html')

@app.route('/Likes')
def render_Likes():
    return render_template('likes.html')

@app.route('/popularity')
def render_popularity():
    return render_template('mvp.html', options = options())

def options():
    with open('super_bowl_ads.json') as Ads:
        Ads_data = json.load(Ads)
#the drop down menu and also gets year
    year = []
    for y in Ads_data:
        if y['Year'] not in year:
           year.append(y['Year'])

    a = ""
    for y in year:
        a = a + Markup('<option value = "'+ str(y) + '">'+ str(y) + '</option>')
    return a

@app.route('/popularity_response')
def render_popularity_response():
    with open('super_bowl_ads.json') as Ads:
        Ads_data = json.load(Ads)
#gets year for html drop down menu
    Year = ""
    if 'year' in request.args:
        Year = request.args['year']
        brand = {}
        for a in Ads_data:
            if str(a['Year']) == Year:
                if a['Brand'] in brand:
                    brand[a['Brand']] = brand[a['Brand']] + a['Data']['Viewership']['Views']
                else:
                    brand[a['Brand']] = a['Data']['Viewership']['Views']
#Gets the most viewed brand
    print(brand)
    MostViewed = "Budweiser"
    for r in brand:
        if brand[r] > brand[MostViewed]:
            MostViewed = r
    return render_template('mvp_display.html', Year = Year, mostViewed = MostViewed, Views=brand[MostViewed], options = options())

@app.route('/category')
def render_category():
#Gets the year
    year = []
    with open('super_bowl_ads.json') as Ads:
        Ads_data = json.load(Ads)
    for y in Ads_data:
        if y['Year'] not in year:
           year.append(y['Year'])
    a = ""
    for y in year:
        a = a + Markup('<option value = "'+ str(y) + '">'+ str(y) + '</option>')
    return render_template('category.html', options = a)

@app.route('/category_response')
def render_category_response():
    with open('advertisements.json') as Ads:
        Ads_data = json.load(Ads)

    category = most_pop_cat(request.args['year'],Ads_data)
    return render_template('category_display.html', Year = request.args['year'], mostUsed = category[0], used = category[1], options = options())

def most_pop_cat(year, data):
#Finds the most populay category based on the users choice of year
    cat = {"funny":0, "show_product_quickly":0, "patriotic":0, "celebrity":0,"danger":0,"animals":0,"use_sex":0}
    for ad in data:
        if str(ad['year']) == year:

            if ad["funny"] == "TRUE":
                cat['funny'] = cat['funny'] + 1

            if ad["show_product_quickly"] == "TRUE":
                cat['show_product_quickly'] = cat['show_product_quickly'] + 1

            if ad["patriotic"] == "TRUE":
                cat['patriotic'] = cat['patriotic'] + 1

            if ad["celebrity"] == "TRUE":
                cat['celebrity'] = cat['celebrity'] + 1

            if ad["danger"] == "TRUE":
                cat['danger'] = cat['danger'] + 1

            if ad["animals"] == "TRUE":
                cat['animals'] = cat['animals'] + 1

            if ad["use_sex"] == "TRUE":
                cat['use_sex'] = cat['use_sex'] + 1

    MyCat={'funny': "Comedy",
    'show_product_quickly': "Showing the Product",
    'patriotic': "Patriotic",
    'celebrity':"Celebrity",
    'danger': "Danger",
    'animals': "Animals",
    'use_sex': "Sexual appeal"}

#finds the highest nuber for category used
    print(cat)
    category = []
    highest = 0
    for c in cat:
        if cat[c] == highest:
            category.append(c)

        if cat[c] > highest:
            highest = cat[c]
            category = []
            category.append(c)

    print(highest)
    print(category)
    CT = ""
    for c in category:
       CT = CT + Markup(MyCat[c] + ",")
    return [CT[:-1], highest]

if __name__ == '__main__':
    app.run(debug=True)

  # for c in ad['Data']['Content']:
                #if ad['Data']['Content'][c] == True:
                   # if c in cat:
                      #  cat[c] = cat[c] + 1
                  #  else:
                      #  cat[c] = 1


"""Command line functions for training dictionaries with pronunciation probabilities"""
from __future__ import annotations

from pathlib import Path

import rich_click as click

from montreal_forced_aligner import config
from montreal_forced_aligner.alignment.pretrained import DictionaryTrainer
from montreal_forced_aligner.command_line.utils import (
    common_options,
    validate_acoustic_model,
    validate_dictionary,
)

__all__ = ["train_dictionary_cli"]

@click.command(
    name="train_dictionary",
    context_settings=dict(
        ignore_unknown_options=True,
        allow_extra_args=True,
        allow_interspersed_args=True,
    ),
    short_help="Calculate pronunciation probabilities",
)
@click.argument(
    "corpus_directory",
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
)
@click.argument("dictionary_path", type=click.UNPROCESSED, callback=validate_dictionary)
@click.argument("acoustic_model_path", type=click.UNPROCESSED, callback=validate_acoustic_model)
@click.argument(
    "output_directory", type=click.Path(file_okay=False, dir_okay=True, path_type=Path)
)
@click.option(
    "--config_path",
    "-c",
    help="Path to config file to use for training.",
    type=click.Path(exists=True, file_okay=True, dir_okay=False, path_type=Path),
)
@click.option(
    "--silence_probabilities",
    is_flag=True,
    help="Flag for saving silence information for pronunciations.",
    default=False,
)
@click.option(
    "--speaker_characters",
    "-s",
    help="Number of characters of file names to use for determining speaker, "
    "default is to use directory names.",
    type=str,
    default="0",
)
@click.option(
    "--audio_directory",
    "-a",
    help="Audio directory root to use for finding audio files.",
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
)
@common_options
@click.help_option("-h", "--help")
@click.pass_context
def train_dictionary_cli(context, **kwargs) -> None:
    """
    Calculate pronunciation probabilities for a dictionary based on alignment results in a corpus.
    """
    if kwargs.get("profile", None) is not None:
        config.profile = kwargs.pop("profile")
    config.update_configuration(kwargs)
    config_path = kwargs.get("config_path", None)
    acoustic_model_path = kwargs["acoustic_model_path"]
    corpus_directory = kwargs["corpus_directory"].absolute()
    dictionary_path = kwargs["dictionary_path"]
    output_directory = kwargs["output_directory"]
    trainer = DictionaryTrainer(
        acoustic_model_path=acoustic_model_path,
        corpus_directory=corpus_directory,
        dictionary_path=dictionary_path,
        **DictionaryTrainer.parse_parameters(config_path, context.params, context.args),
    )

    try:
        trainer.align()
        trainer.export_lexicons(output_directory)
    except Exception:
        trainer.dirty = True
        raise
    finally:
        trainer.cleanup()


from collections import deque

dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

def startDirection(i, j):
    q = deque()
    count = 1
    graph[i][j] = 0
    for k in range(4):
        nx = i + dx[k]
        ny = j + dy[k]
        if 0 <= nx < len(graph) and 0 <= ny < len(graph):
            if graph[nx][ny] == 1:
                q.append((nx, ny))
                count += 1
                graph[nx][ny] = 0
    return q, count

def direction(q, i, j):
    count = 0
    for k in range(4):
        nx = i + dx[k]
        ny = j + dy[k]
        if 0 <= nx < len(graph) and 0 <= ny < len(graph):
            if graph[nx][ny] == 1:
                q.append((nx, ny))
                count += 1
                graph[nx][ny] = 0
    return q, count

def BFS(i, j):
    q, count = startDirection(i, j)

    while q:
        x, y = q.popleft()
        q_state, count_state = direction(q, x, y)
        q = q_state
        count += count_state
    return count

def cadastralSurvey(pMap):
    '''
    디지털월드의 국토의 모양이 주어졌을 때, 섬의 갯수 (int) 와 각 섬의 크기들 (list)을 반환하세요.
    '''
    N = len(pMap)
    result = 0
    count_result = []
    for i in range(N):
        for j in range(N):
            if graph[i][j] == 1:
                count_result.append(BFS(i, j))
                result += 1
    count_result.sort()
    return (result, count_result)

def main():
    N = int(input())
    global graph
    graph = [0 for _ in range(N)]
    graph = [list(map(int, input())) for _ in range(N)]
    print(cadastralSurvey(graph))

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
"""
Takes all your GitHub pages repos and builds their static sites.
"""

import os
import os.path
import shutil
from subprocess import check_call, check_output, DEVNULL

PATH = 'https://github.com/{username}/{reponame}'
HELPTEXT = """usage: {} [SUBCOMMAND]
Build and rebuild GitHub pages sites.  Typical usage is to run with no
arguments, which runs the "dwim" sub-command.

dwim - Automatically guess the operations necessary to completely build your
       site.  Will tell you what it's doing as it goes. (this is default)
init - Initialize the site by pulling and running the first build.
pull - Pull every repository (but do not build anything).
rebuild - Rebuild the entire site (without pulling first).
build - Pull each repository and rebuild if it updated.
deploy - Push to S3 (this will never be done by dwim)
help - Display this help text.
"""

def run(args, **kwargs):
    check_call(args, stdout=DEVNULL, stderr=DEVNULL, **kwargs)

class GhpRepo(object):
    """A class representing a git repository with GitHub pages enabled.

    Has a remote URL, a local directory, and a "build" directory, where the
    actual generated site will be placed. Also, most repositories are on branch
    gh-pages, but some (like *.github.io) are on master, so this accepts a
    branch argument.

    This class allows you to clone, build, update, and rebuild a repo fairly
    easily.  Of course, it just shells out to git and jekyll.

    """

    def __init__(self, name, url, local, output, branch='gh-pages'):
        """Create the class instance.

        This doesn't necessarily clone the repo or build it - in fact, the repo
        may already exist locally.

        """
        self.name = name
        self.url = url
        self.local = local
        self.output = output
        self.branch = branch

    def should_build(self):
        return not os.path.exists(os.path.join(self.local, '.nojekyll'))

    def checkout(self):
        """Check out the repository."""
        print("Cloning {}".format(self.name))
        run(['git', 'clone', '-b', self.branch, self.url, self.local])

    def current_commit(self):
        """Return the SHA of the current commit."""
        os.chdir(self.local)
        return check_output(['git', 'rev-parse', 'HEAD'])

    def pull(self):
        """Pull from the default remote tracking branch, hopefully.

        Return True if updated, false otherwise.
        """
        os.chdir(self.local)
        old_revision = self.current_commit()
        run(['git', 'pull'])
        return self.current_commit() != old_revision

    def build(self):
        """Run the build command (jekyll) or just copy files if .nojekyll exists."""
        os.chdir(self.local)
        if self.should_build():
            print('=> {}: build via Jekyll'.format(self.name))
            run(['jekyll', 'build', '-d', self.output])
        else:
            print('=> {}: build via copy'.format(self.name))
            if os.path.exists(self.output):
                shutil.rmtree(self.output)
            ignore = shutil.ignore_patterns(
                # may have to include lots of stuff in here
                '.git',
                '.gitignore',
                '.nojekyll'
            )
            shutil.copytree(self.local, self.output, ignore=ignore)
        print('   DONE'.format(self.name))

    def update_and_build(self):
        """Pull, and if the repo has changed, rebuild.

        Return True if the repo updated.  Return False otherwise.
        """
        if self.pull():
            print('=> {}: was out of date'.format(self.name))
            self.build()
            return True
        return False

class GhpBuilder(object):
    """This class represents a collection of GitHub pages repositories to deploy.

    Construct an instance of this object to build your complete GitHub pages
    website for later deployment.

    """

    def __init__(self, username, repos, directory=os.getcwd()):
        directory = os.path.abspath(directory)
        self.username = username
        self.directory = directory
        self.work = os.path.join(directory, 'work')
        self.site = os.path.join(directory, 'site')
        self.repos = []
        self.main = None
        for name, branch, path in repos:
            url = PATH.format(username=username, reponame=name)
            localwork = os.path.join(self.work, name)
            localbuild = os.path.join(self.site, path)
            if path == '':  # this is the "main site"
                self.main = GhpRepo(name, url, localwork, localbuild, branch)
            else:
                self.repos.append(GhpRepo(name, url, localwork, localbuild, branch))

    def _initial_checkout(self):
        """Create workdir and clone repos for the first time."""
        os.makedirs(self.work, exist_ok=True)
        if self.main:
            self.main.checkout()
        for repo in self.repos:
            repo.checkout()

    def rebuild(self):
        """Build all repos, assuming they are already cloned."""
        os.makedirs(self.site, exist_ok=True)
        if self.main:
            self.main.build()
        for repo in self.repos:
            repo.build()

    def init(self):
        """Check out and build for the first time."""
        print("Initializing the site!")
        self._initial_checkout()
        self.rebuild()

    def pull(self):
        """Pull all repositories without updating."""
        updated = False
        if self.main and self.main.pull():
            print('=> {}: updated'.format(self.main.name))
            updated = True
        for repo in self.repos:
            if repo.pull():
                print('=> {}: updated'.format(repo.name))
                updated = True
        if updated:
            print('You have pulled but not built.  Your site/ directory will')
            print('only be up-to-date when you run "rebuild".')

    def _update_main(self):
        """Update the main repository, and possibly subdirectories.

        Since the main site resides in the root, when it is regenerated, the
        subdirectories are clobbered! To address this, whenever the main repo
        is rebuilt, all other repos are forced to rebuild.

        """
        if self.main and self.main.update_and_build():
            print('Rebuilding other repos since they may have been clobbered.')
            for repo in self.repos:
                repo.build()
            print('Continuing to update other repos...')

    def build(self):
        """Normal build."""
        self._update_main()
        for repo in self.repos:
            repo.update_and_build()

    def dwim(self):
        """Do what I mean mode!

        This tries to infer what operation should be done based on the state of
        the directories.  The goal here is always a completely built site.

        """
        if not os.path.exists(self.work):
            print('Detected that the work directory does not exist.')
            print('Initializing ...')
            self.init()
        elif not os.path.exists(self.site):
            print('Detected that the site directory does not exist, but your repos are cloned.')
            print('Rebuilding ...')
            self.rebuild()
        else:
            print('Updating your existing site.')
            self.build()

    def deploy(self):
        check_call(["s3_website", "push"])

def help():
    print(HELPTEXT.format(sys.argv[0]))

if __name__ == '__main__':
    import sys
    sys.path.insert(0, os.getcwd())
    from config import USERNAME, REPOS
    builder = GhpBuilder(USERNAME, REPOS)
    commands = {
        'init': builder.init,
        'build': builder.build,
        'rebuild': builder.rebuild,
        'dwim': builder.dwim,
        'pull': builder.pull,
        'deploy': builder.deploy,
        'push': builder.deploy,
        'help': help,
    }
    if len(sys.argv) <= 1:
        cmd = 'dwim'
    else:
        cmd = sys.argv[1]
    func = commands.get(cmd)
    if func:
        func()
    else:
        help()


"""
1. use 'of' function to create observable
2. use 'pipe' function to add a series operators to the observable
3. subscribe observable
"""

from rx import range, operators as op

def onError(x):
    raise Exception ("data error")
observable1 = range(1,11)
observable2 = observable1.pipe(
   op.filter(lambda s: s%2==0),
   lambda x: onError(x),
   op.reduce(lambda x0, x1: x0 + x1)
)
observable2.subscribe(lambda x: print("Sum of Even numbers is {0}".format(x))) # 1st step: default on_next

observable2.subscribe(
    on_next = lambda i: print("Sum: {0}".format(i)),
    on_error = lambda e: print("Error : {0}".format(e)),
    on_completed = lambda: print("Done!"),
)


import subprocess
from sys import stderr
import os
from datetime import datetime

path = input('Copy and past the directory ')

now = datetime.now()
date_time = now.strftime("%Y-%m-%d at %H:%M:%S")
start_message = f'+++ As of {date_time} ocrDetective suspects these files do not contain OCR +++'

suspects = []
suspects.append(start_message)

for root, dirs, files in os.walk(path, topdown=False):
    for name in files:
        filepath = os.path.join(root, name)
        with subprocess.Popen(["pdffonts", filepath], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
            out = proc.stdout.readlines()
            out_error = proc.stderr.readlines()
            font_count = len(out)

# Subtract 2 because pdffonts includes two initial lines as a heading
        if font_count - 2 == 0:
            print(filepath)
            suspects.append(filepath)
        else:
            pass

output_txt = os.path.join(path, "suspects.txt")

print(suspects)
with open(output_txt, "w") as f:
    for suspect in suspects:
        f.write("%s\n" % suspect)


# -*- coding: utf-8 -*-
'''
FileName: get_multi_roi.py
Author: Wenyu
Date: 07/04/2019
Version: v1.0 [07/04/2019][Wenyu] obtain face, face mask, left and right eyes
                                  roi
'''

import cv2
import numpy as np

def get_multi_roi(image, landmarks):
	'''obtain face, face mask, left and right eye ROI	'''

	# get face roi
	points = [36, 39, 42, 45, 48, 54]

	center_x = 0
	center_y = 0
	for i in points:
		center_x += landmarks[0, i]
		center_y += landmarks[1, i]
		#cv2.circle(image, (landmarks[0, i], landmarks[1, i]), radius=5, color=(0, 0, 255), thickness=-1)

	center_x /= 6
	center_y /= 6

	rect_w = int((center_x - landmarks[0, 0]) * 1.5)

	top_l_x = int(center_x - rect_w)
	top_l_y = int(center_y - rect_w)
	down_r_x = int(center_x + rect_w)
	down_r_y = int(center_y + rect_w)

	if (down_r_x > image.shape[1]):
		down_r_x = image.shape[1]
	if (down_r_y > image.shape[0]):
		down_r_y = image.shape[0]
	if (top_l_x < 0):
		top_l_x = 0
	if (top_l_y < 0):
		top_l_y = 0

	face = image[top_l_y: down_r_y, top_l_x: down_r_x]

	# get face mask
	face_mask = np.zeros((image.shape[0], image.shape[1], 1), dtype=np.float32)
	cv2.fillPoly(face_mask, np.array([[(top_l_x, top_l_y), (down_r_x, top_l_y), (down_r_x, down_r_y), (top_l_x, down_r_y)]], dtype=np.int32), color=1.0)

	# get eyes roi
	eye_width = 2 * max(abs(landmarks[0, points[0]] - landmarks[0, points[1]]), abs(landmarks[0, points[2]] - landmarks[0, points[3]]))
	eye_height = 1.0 * eye_width
	eye_middle_right = ((landmarks[0, points[0]] + landmarks[0, points[1]]) / 2, (landmarks[1, points[0]] + landmarks[1, points[1]]) / 2)
	eye_middle_left = ((landmarks[0, points[2]] + landmarks[0, points[3]]) / 2, (landmarks[1, points[2]] + landmarks[1, points[3]]) / 2)
	top_l_x = abs(int(eye_middle_left[0] - eye_width / 2.0))
	top_l_y = abs(int(eye_middle_left[1] - eye_height / 2.0))
	down_r_x = abs(int(eye_middle_left[0] + eye_width / 2.0))
	down_r_y = abs(int(eye_middle_left[1] + eye_height / 2.0))

	# segment eye image
	left_eye = image[top_l_y: down_r_y, top_l_x: down_r_x]

	top_l_x = abs(int(eye_middle_right[0] - eye_width / 2.0))
	top_l_y = abs(int(eye_middle_right[1] - eye_height / 2.0))
	down_r_x = abs(int(eye_middle_right[0] + eye_width / 2.0))
	down_r_y = abs(int(eye_middle_right[1] + eye_height / 2.0))

	right_eye = image[top_l_y : down_r_y, top_l_x : down_r_x]

#	cv2.imshow('face_mask', face_mask)
#	cv2.imshow('face', face)
#	cv2.imshow('left_eye', left_eye)
#	cv2.imshow('right_eye', right_eye)

#	cv2.waitKey(1)

#	cv2.imwrite('temp/face_mask.jpg', face_mask)
#	cv2.imwrite('temp/face.jpg', face)
#	cv2.imwrite('temp/left_eye.jpg', left_eye)
#	cv2.imwrite('temp/right_eye.jpg', right_eye)

	return face, face_mask, left_eye, right_eye


import flet as ft

def main(page: ft.Page):
    lenguajes = ['Python', 'Flet', 'Flutter']
    etiquetas = []

    for e in lenguajes:
        etiquetas.append(ft.Text(e))

    row_datos = ft.Row(controls=etiquetas)

    page.add(row_datos)

    # Este era el contenido del main, formas distintas de crear controles
    """page.add(
        ft.Row(controls=[
            ft.Text("Python"),
            ft.Text("Flet"),
            ft.Text("Row")
        ])
    )"""

ft.app(target=main)


import json
import os
from Shared.errors import handle_error_response
from Shared.api import API
from Shared.auth import Authorizer

def main(event):
    payload = API.parse_payload(event)
    result = Authorizer.create_api_key(key_request=payload["body"])
    return result

@handle_error_response
def handler(event, context):
    return main(event)

if __name__ == "__main__":
    os.environ["some_env_var"] = "env_var_value"

    body = {
        "attribute1": "value1",
        "attribute2": "value2",
    }

    event = {
        'httpMethod': 'GET',
        'resource': '/example',
        'queryStringParameters': {},
        'pathParameters': {},
        'body' : json.dumps(body)
    }

    handler(event, context=None)


import datetime, pytz, sys, getopt, openai, random
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
# https://github.com/keithrozario/Klayers

top_screenshot_path = 'resources/top_half.jpg'
bottom_screenshot_path = 'resources/bottom_half.jpg'
#top_screenshot_path = 'resources/original.jpg'
screenshot_wCode_path = 'resources/mcd_screenshot_wCode.jpg'

class orderInfo:
	def __init__(self):
		self.code = "1701"
		self.name = "Julian"
		self.current_hour = 12
		self.current_minute = 0
		self.timezone_string = 'US/Pacific'
		self.items = "1 Oreo Shamrock McFlurry\n1 Big Mac"

def get_current_hour_in_12hr_format_for_timezone(timezone_str):
	global current_hour
	current_timezone = pytz.timezone(timezone_str)
	current_hour = int(datetime.datetime.now(current_timezone).strftime("%I"))

def get_current_minute():
	global current_minute
	current_minute = int(datetime.datetime.now().strftime("%M"))

def get_time_vars(order):
	current_timezone = pytz.timezone(order.timezone_string)
	order.current_hour = int(datetime.datetime.now(current_timezone).strftime("%I"))
	order.current_minute = int(datetime.datetime.now().strftime("%M"))
	return order

def create_screenshot(order):
	top_img = Image.open(top_screenshot_path)
	top_d1 = ImageDraw.Draw(top_img)
	codeandnameFont = ImageFont.truetype('resources/Heebo-Black.ttf', 94)
	yourordertextFont = ImageFont.truetype('resources/Heebo-Black.ttf', 64)
	timeFont = ImageFont.truetype('resources/HelveticaNeue-Medium.otf', 46)
	descriptionFont = ImageFont.truetype('resources/Cabin-Regular-TTF.ttf', 40)
	top_width, top_height = top_img.size

	codeandname = order.name + " #" + str(order.code)
	#d1.text( (top_width * (0.50 - len(str(order.code)) * 0.03) , (height * 0.20)), str(order.code), fill =(0, 0, 0),font=codeFont)
	top_d1.text( (top_width * (0.50 - len(codeandname) * 0.023) , (794)), codeandname,font=codeandnameFont, fill = (54, 54, 54))

	yourordertext = "(#" + str(order.code) + ")"
	top_d1.text( ((top_width * 0.357) , (1318)), yourordertext, fill =(41, 41, 41),font=yourordertextFont)

	#top_d1.text(( (top_width * 0.086), (45)), ( "0" + str(order.current_minute)), fill =(0, 0, 0),font=timeFont)
	time_text = ""
	if (order.current_hour < 10):
		time_text = "0" + str(order.current_hour)
	else:
		time_text = str(order.current_hour)

	if (order.current_minute < 10):
		time_text = time_text + ":0" + str(order.current_minute)
	else:
		time_text = time_text + ":" + str(order.current_minute)

	top_d1.text(( (top_width * 0.038), (63)), time_text, fill =(0, 0, 0),font=timeFont)

	orderitemsstring = order.items.replace('\\n', '\n')
	orderitemsarray = orderitemsstring.splitlines()
	top_d1.text( ((top_width * 0.065) , (1510)), orderitemsstring, fill =(41, 41, 41),font=descriptionFont)

	num_lines = len(order.items.splitlines())
	cropped_top_height = 1580 + (num_lines * 30)
	top_img = top_img.crop((0, 0, top_width, cropped_top_height))

	#bottom half

	bottom_img = Image.open(bottom_screenshot_path)
	bottom_d1 = ImageDraw.Draw(bottom_img)
	bottom_width, bottom_height = bottom_img.size

	paymentFont = ImageFont.truetype('resources/HelveticaNeue-Medium.otf', 38)

	totalitemscost = 0.0
	for i in orderitemsarray:
		totalitemscost += float(query_openai(i))
	paymentAmount = round(1.1 * float(totalitemscost), 2)
	print("totalitemscost: " + str(paymentAmount))

	#paymentAmountString should always have two decimal places. If it doesn't, add a 0
	paymentAmountString = str(paymentAmount)
	if (len(paymentAmountString.split(".")[1]) == 1):
		paymentAmountString = paymentAmountString + "0"

	paymentText = "$" + paymentAmountString + " with Apple Pay " + str(random.randint(1000, 9999))

	bottom_d1.text( ((bottom_width * 0.247) , (80)), paymentText, fill =(41, 41, 41),font=paymentFont)

	combined_img = Image.new('RGB', (top_width, cropped_top_height + bottom_height))
	combined_img.paste(top_img, (0, 0))
	combined_img.paste(bottom_img, (0, cropped_top_height))
	combined_img = combined_img.crop((0, 0, 1125, 2436))

	imgByteArr = BytesIO()
	combined_img.save(imgByteArr, format='PNG')
	imgByteArr = imgByteArr.getvalue()
	return imgByteArr

def check_if_api_or_cli(argv):
	try:
		opts, args = getopt.getopt(argv, "", ["code=", "name=", "items="])
	except getopt.GetoptError:
		print ( "Invalid arguments. Please use -h or --help for help." )
		sys.exit(2)
	if( len(opts) == 0 ):
		print("No arguments passed, exiting program")
		sys.exit()
	#check if run cli or run api
	print("CLI arguments passed")
	run_cli(opts)
	sys.exit()

def runfromlambda(code, name, items):
	currentOrder = orderInfo()
	currentOrder = get_time_vars(currentOrder)
	currentOrder.code = code
	currentOrder.name = name
	currentOrder.items = items
	return create_screenshot(currentOrder)

def run_cli(opts):
	currentOrder = orderInfo()
	currentOrder = get_time_vars(currentOrder)

	for opt, arg in opts:
		if opt in ("-c", "--code"): currentOrder.code = arg
		elif opt in ("-n", "--name"): currentOrder.name = arg
		elif opt in ("-i", "--items"): currentOrder.items = arg

	#save bytes-like object to file
	with open(screenshot_wCode_path, 'wb') as f:
		f.write(create_screenshot(currentOrder))
		f.close()

def query_openai(items):
	#set openai.api_key to the key from openai_key.txt
	openai.api_key = open("resources/openai_key.txt", "r").read()
	formatted_items = items.replace("\n", ", ")

	model_engine = "davinci:ft-personal-2023-03-30-21-42-15"
	prompt = formatted_items
	max_tokens = 6
	top_p = 0.2

	completions = openai.Completion.create(
	    engine=model_engine,
	    prompt=prompt,
	    max_tokens=max_tokens,
	    top_p=top_p
	)

	estimated_cost = completions.choices[0]["text"]
	estimated_cost = estimated_cost.replace("->", "").replace("\n", "").replace(" ", "").replace("Meal", "")
	# if there are periods before the first number, remove them
	while estimated_cost[0] == ".":
		estimated_cost = estimated_cost[1:]
	print("estimated_cost of " + prompt + " : " + estimated_cost)

	return estimated_cost

if __name__=="__main__":
	check_if_api_or_cli(sys.argv[1:])


#
# Base64是一种用64个字符来表示任意二进制数据的方法。

import base64

print( base64.b64encode(b'binary\x00string') )

# 由于标准的Base64编码后可能出现字符+和/，在URL中就不能直接作为参数，所以又有一种"url safe"的base64编码，其实就是把字符+和/分别变成-和_：

print( base64.b64encode(b'i\xb7\x1d\xfb\xef\xff') )

print(  base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff') )

# 由于=字符也可能出现在Base64编码中，但=用在URL、Cookie里面会造成歧义，所以，很多Base64编码后会把=去掉：
# 去掉=后怎么解码呢？因为Base64是把3个字节变为4个字节，所以，Base64编码的长度永远是4的倍数，因此，需要加上=把Base64字符串的长度变为4的倍数，就可以正常解码了。

print("====================================================================")

# struct
'''
    准确地讲，Python没有专门处理字节的数据类型。但由于b'str'可以表示字节，所以，字节数组＝二进制str。
    而在C语言中，我们可以很方便地用struct、union来处理字节，以及字节和int，float的转换。

    在Python中，比方说要把一个32位无符号整数变成字节，也就是4个长度的bytes，你得配合位运算符这么写：

    好在Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换。
'''
import struct

st = struct.pack('>I',10240099)
print( st )

'''
    pack的第一个参数是处理指令，'>I'的意思是：

    >表示字节顺序是big-endian，也就是网络序，I表示4字节无符号整数。

    后面的参数个数要和处理指令一致。
'''

# unpack把bytes变成相应的数据类型：

n = struct.unpack('>I',b'\x00\x9c@c')

print( n )

# hashlib提供了常见的摘要算法，如MD5，SHA1等等。

import hashlib

md5 = hashlib.md5()
md5.update("this is my first time , what are you saying  ?".encode("utf-8"))
print(md5.hexdigest())

'''
    MD5是最常见的摘要算法，速度很快，生成结果是固定的128 bit字节，通常用一个32位的16进制字符串表示。

    另一种常见的摘要算法是SHA1，调用SHA1和调用MD5完全类似：
'''

sha1 = hashlib.sha1()
sha1.update('how to use sha1 in '.encode('utf-8'))
sha1.update('python hashlib?'.encode('utf-8'))
print(sha1.hexdigest())

'''
    SHA1的结果是160 bit字节，通常用一个40位的16进制字符串表示。

    比SHA1更安全的算法是SHA256和SHA512，不过越安全的算法不仅越慢，而且摘要长度更长
'''

# hmac
import hmac

message = b'Hello , world'
key = b'secret'
h = hmac.new( key, message, digestmod='MD5' )
print( h.hexdigest() )
'''
    可见使用hmac和普通hash算法非常类似。hmac输出的长度和原始哈希算法的长度一致。
    需要注意传入的key和message都是bytes类型，str类型需要首先编码为bytes。
'''


"""
Type annotations for braket service client paginators.

[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_braket/paginators.html)

Usage::

    ```python
    import boto3

    from mypy_boto3_braket import BraketClient
    from mypy_boto3_braket.paginator import (
        SearchDevicesPaginator,
        SearchJobsPaginator,
        SearchQuantumTasksPaginator,
    )

    client: BraketClient = boto3.client("braket")

    search_devices_paginator: SearchDevicesPaginator = client.get_paginator("search_devices")
    search_jobs_paginator: SearchJobsPaginator = client.get_paginator("search_jobs")
    search_quantum_tasks_paginator: SearchQuantumTasksPaginator = client.get_paginator("search_quantum_tasks")
    ```
"""
from typing import Iterator, List

from botocore.paginate import Paginator as Boto3Paginator

from .type_defs import (
    PaginatorConfigTypeDef,
    SearchDevicesFilterTypeDef,
    SearchDevicesResponseTypeDef,
    SearchJobsFilterTypeDef,
    SearchJobsResponseTypeDef,
    SearchQuantumTasksFilterTypeDef,
    SearchQuantumTasksResponseTypeDef,
)

__all__ = ("SearchDevicesPaginator", "SearchJobsPaginator", "SearchQuantumTasksPaginator")

class SearchDevicesPaginator(Boto3Paginator):
    """
    [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/braket.html#Braket.Paginator.SearchDevices)
    [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_braket/paginators.html#searchdevicespaginator)
    """

    def paginate(
        self,
        *,
        filters: List["SearchDevicesFilterTypeDef"],
        PaginationConfig: PaginatorConfigTypeDef = None
    ) -> Iterator[SearchDevicesResponseTypeDef]:
        """
        [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/braket.html#Braket.Paginator.SearchDevices.paginate)
        [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_braket/paginators.html#searchdevicespaginator)
        """

class SearchJobsPaginator(Boto3Paginator):
    """
    [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/braket.html#Braket.Paginator.SearchJobs)
    [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_braket/paginators.html#searchjobspaginator)
    """

    def paginate(
        self,
        *,
        filters: List["SearchJobsFilterTypeDef"],
        PaginationConfig: PaginatorConfigTypeDef = None
    ) -> Iterator[SearchJobsResponseTypeDef]:
        """
        [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/braket.html#Braket.Paginator.SearchJobs.paginate)
        [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_braket/paginators.html#searchjobspaginator)
        """

class SearchQuantumTasksPaginator(Boto3Paginator):
    """
    [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/braket.html#Braket.Paginator.SearchQuantumTasks)
    [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_braket/paginators.html#searchquantumtaskspaginator)
    """

    def paginate(
        self,
        *,
        filters: List["SearchQuantumTasksFilterTypeDef"],
        PaginationConfig: PaginatorConfigTypeDef = None
    ) -> Iterator[SearchQuantumTasksResponseTypeDef]:
        """
        [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/braket.html#Braket.Paginator.SearchQuantumTasks.paginate)
        [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_braket/paginators.html#searchquantumtaskspaginator)
        """


import os
from sympy.physics.units import years
os.chdir("../")
from config import load_config
config=load_config.config()
import logging, logging.config
from logging import getLogger
logging.config.fileConfig('logs/logging.conf')
logger = logging.getLogger('analyzing_data')
import datetime as dt
from utils.database import bd_handler, database_functions
from utils.get_new_data import update_stock
from dateutil.relativedelta import relativedelta
from plots.plot_specific_series import  plot_specific_series
from plots import other_plots

other_plots
import pandas as pd
import numpy as np
from statsmodels.stats.diagnostic import lilliefors
import warnings
warnings.filterwarnings("ignore")
logging.getLogger('matplotlib').setLevel(logging.ERROR)
check_normality=False
if __name__=="__main__":
    bd=bd_handler.bd_handler("stocks")
    fecha_ini=dt.datetime(2017,3,1)
    fecha_end = dt.datetime(2022, 1, 1)
    stocks=["US_GOOG","US_MSFT","US_QCOM","US_TSLA","US_NFLX","US_FB","US_PYPL","US_NVDA","US_ZM","US_RPD","US_SPLK","US_BIDU","US_PDD"]
    data = database_functions.obtener_multiples_series("precios",

    "B", *stocks, bd=bd)
    data=data.loc[(data.index>fecha_ini)&(data.index<fecha_end)]
    log_returns =np.log(data)
    log_returns=log_returns.diff()
    data=data.pct_change()
    covariance = data.cov()
    covariance.index = data.columns
    covariance.columns = data.columns
    cov_inv=pd.DataFrame(np.linalg.inv(    covariance.values))
    cov_inv.index = data.columns
    cov_inv.columns = data.columns
    medias=data.mean()
    weights=np.dot(cov_inv,medias)
    weights = {i: e for i, e in zip(data.columns, np.dot(cov_inv, medias))}
    logger.info("optimize_porfolio: wights:{}".format(weights))
    if check_normality:
        for column in log_returns.columns:
            serie=log_returns[column].dropna()
            serie=(serie-serie.mean())/(serie.std())
            test=lilliefors(serie)
            logger.info("optimize_porfolio: lilliefors test {}: {}".format(column,test))
            other_plots.distribucion_univariante(serie, column)


import numpy as np
import torchvision

data = np.load('/Users/michaelgentnermac/Documents/ADL4CV/mnist_test_seq.npy')

Resize = torchvision.transforms.Resize(28)
ToPil = torchvision.transforms.ToPILImage()
ToTensor = torchvision.transforms.ToTensor()

seq_len = data.shape[0]
seqs = data.shape[1]

res = []

for i in range(seq_len):
    seq = []
    for j in range(seqs):

        img = ToPil(data[i, j, :, :])
        img = Resize(img)
        seq.append(ToTensor(img).numpy().squeeze())
    res.append(seq)
    print(i)

d_data = np.array(res)

np.save('./mnist_test_seq_28.npy', d_data)


import logging
from typing import Optional, List

import exiting
import msgconsumer
from groupid import GroupID
from moduleid import ModuleID
from msgid import MsgID
from msgs.integermsg import IntegerMsg, BiIntegerMsg
from msgs.message import Message
from msgs.requestmsg import RequestMsg
from uis.abstractreader import AbstractReader

class InputReader(AbstractReader):
    # noinspection PyShadowingBuiltins
    def __init__(self, id: ModuleID, module: msgconsumer.MsgConsumer):
        self.id = id
        self._module = module
        super().__init__()

    def _readMsg(self) -> Optional['Message']:
        line = input("READER ID " + str(self.id) + ": Enter msg:\n")
        parts = line.split()  # type: List[str]
        if len(parts) > 0:
            if parts[0] == 'E':
                exiting.exitCleanly(0)
            elif parts[0].isdigit():
                msg = self._formatMessage(parts)
                if msg is not None:
                    return msg

        logging.warning("Unknown command " + line)
        return None

    def _formatMessage(self, parts: List[str]) -> Optional['Message']:
        msgID = int(parts[0])
        if msgID == MsgID.SET_VOL.value:
            volume = int(parts[1])
            return IntegerMsg(value=volume, fromID=self.id, typeID=MsgID.SET_VOL, forID=ModuleID.VOLUME_OPERATOR)

        elif msgID == MsgID.REQ_CURRENT_VOL_INFO.value:
            return RequestMsg(self.id, typeID=MsgID.REQ_CURRENT_VOL_INFO, forID=ModuleID.VOLUME_OPERATOR)
        elif msgID == MsgID.REQ_SOURCE_STATUS.value:
            return RequestMsg(self.id, typeID=MsgID.REQ_SOURCE_STATUS, groupID=GroupID.SOURCE)
        elif msgID == MsgID.ACTIVATE_SOURCE.value:
            sourceID = int(parts[1])
            return IntegerMsg(value=sourceID, fromID=self.id, typeID=MsgID.ACTIVATE_SOURCE, groupID=GroupID.SOURCE)
        elif msgID == MsgID.REQ_NODE.value:
            sourceID = int(parts[1])
            nodeID = int(parts[2])
            fromIndex = int(parts[3])
            return BiIntegerMsg(value1=nodeID, value2=fromIndex, fromID=self.id, typeID=MsgID.REQ_NODE,
                                forID=ModuleID(sourceID))
        elif msgID == MsgID.SOURCE_PLAY_COMMAND.value:
            sourceID = int(parts[1])
            commandID = int(parts[2])
            return IntegerMsg(value=commandID, fromID=self.id, typeID=MsgID.SOURCE_PLAY_COMMAND,
                              forID=ModuleID(sourceID))

        else:
            return None

    def _processMsg(self, msg: 'Message'):
        self._module.dispatcher.distribute(msg, self.id)


import pandas as pd
from nltk.corpus import stopwords
import string
#from nltk.stem import PorterStemmer
from nltk import word_tokenize
from sklearn.preprocessing import LabelEncoder
from nltk import NaiveBayesClassifier
from nltk import classify
import _pickle as pickle

def train_model():
    df = pd.read_csv('spam.csv',encoding = 'latin-1')
    Y = df['v1']
    X = df['v2']
    lb = LabelEncoder()
    Y = lb.fit_transform(Y)

    global stop_words
    stop_words = stopwords.words('english')
    #ps = PorterStemmer()

    final = []
    for i in range(len(Y)):
        final.append((bag_words(X[i]),Y[i]))

    from sklearn.model_selection import train_test_split
    training,testing = train_test_split(final,test_size = 0.25)

    classifier = NaiveBayesClassifier.train(training)
    acc = classify.accuracy(classifier,testing)

    pickle.dump(classifier,open("ham_spam.pkl","wb"))
    return acc,classifier

def bag_words(words):
    processed = words.lower()
    processed = processed.replace(r'^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$', 'email')
    processed = processed.replace(r'^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$', 'phoneno')
    processed = processed.replace(
        r'^(http(s?)\:\/\/)*[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$',
        'website')
    processed = processed.replace(r'$|\£|\€', 'money')
    processed = processed.replace(r'\d+(\.\d+)?', 'number')
    processed = processed.replace(r'^\s+|\s+?$', '')
    processed = processed.replace(r'\s+', ' ')

    words = word_tokenize(processed)
    clean = []
    for i in words:
        if i not in stop_words or i not in string.punctuation:
            clean.append(i)
    dicton = dict([word, True] for word in clean)
    return dicton

acc,classifier = train_model()

def testing(input):

    #testing_strings = ['You won the lottery of $2000','meet me soon','log in to facebook today']

    #pred = []
    #for i in testing_strings:
    #    pred.append(classifier.classify(bag_words(i)))
    #pred
    prediction = classifier.classify(bag_words(input))
    if  prediction ==0:
        print('Ham')
    else:
        print('Spam')
train_model()
testing('call me as soon as possible')


from .. import graph, using, style
from ..util import shorten_strings, calc_bar_chart_height
from flask_babel import gettext as _l
import pygal
import re
import pandas as pd

def get_sentences_percent_with_cap_letter(message):
    sentences = []  # 1 - zdanie zaczęte wielką literą, 0 - zdanie zaczęte niewielką literą
    for s in message:
        t = [1 if len(i.strip()) > 0 and i.strip()[0].isupper() else 0 for i in list(filter(lambda i: len(i) > 0, re.split(r'[.?!]', s)))] # zdania w wiadomości
        sentences.extend(t)
    return round(sum(sentences) / len(sentences) * 100) if len(sentences) != 0 else 0

def create_chart(df, limit=None):
    if limit is not None:
        df = df.tail(limit)

    height = calc_bar_chart_height(df.name)
    chart = pygal.HorizontalBar(style=style, show_legend=False, height=height)
    chart.x_labels = shorten_strings(df.name)
    chart.add('', df.percent)
    chart.x_title = 'Percent of sentences starting with capital letter'
    chart.y_title = 'User'
    return chart

@graph(_l('Percent of sentences starting with capital letter'))
@using('messages', 'username')
def words_count_in_message(data):
    all_messages = data['messages']
    messages = all_messages[(all_messages.thread_type == 'Regular') & (all_messages.sender != data['username'])].dropna()

    names = []
    percents = []

    for conv, msgs in messages.groupby(messages.conversation):
        if msgs.content is not None and len(msgs.content) > 1:

            percent = get_sentences_percent_with_cap_letter(msgs.content)
            names.append(conv)
            percents.append(percent)

    df = pd.DataFrame({'name': names, 'percent': percents}).sort_values('percent', ascending=True)
    return create_chart(df, 25), create_chart(df)


import datetime

from protorpc import message_types
from protorpc import remote

from multitest_transport.api import base
from multitest_transport.models import config_encoder
from multitest_transport.models import messages
from multitest_transport.models import ndb_models
from multitest_transport.util import env

@base.MTT_API.api_class(resource_name='node_config', path='node_config')
class NodeConfigApi(remote.Service):
  """A handler for Node Config API."""

  @base.ApiMethod(message_types.VoidMessage, messages.NodeConfig,
                  http_method='GET', path='/node_config', name='get')
  def Get(self, request):
    """Fetches the server's node configuration."""
    node_config = ndb_models.GetNodeConfig()
    return messages.Convert(node_config, messages.NodeConfig)

  @base.ApiMethod(messages.NodeConfig, messages.NodeConfig,
                  http_method='PUT', path='/node_config', name='update')
  def Update(self, request):
    """Updates the server's node configuration.

    Body:
      Node configuration data
    """
    node_config = messages.Convert(
        request, ndb_models.NodeConfig, messages.NodeConfig)
    node_config.put()
    return messages.Convert(node_config, messages.NodeConfig)

  @base.ApiMethod(message_types.VoidMessage, messages.SimpleMessage,
                  http_method='GET', path='export', name='export')
  def ExportConfigData(self, request):
    """Exports the server's node configuration."""
    config_set = config_encoder.ConfigSet(
        node_config=ndb_models.GetNodeConfig(),
        build_channels=ndb_models.BuildChannelConfig.query().fetch(),
        device_actions=ndb_models.DeviceAction.query().fetch(),
        test_run_actions=ndb_models.TestRunAction.query().fetch(),
        tests=ndb_models.Test.query().fetch(),
        file_cleaner=ndb_models.GetFileCleanerSettings())
    header = '# MTT Configuration - %s - %s\n' % (
        env.HOSTNAME, datetime.datetime.now())
    data = config_encoder.Encode(config_set)
    return messages.SimpleMessage(value=header + data)

  @base.ApiMethod(messages.SimpleMessage, message_types.VoidMessage,
                  http_method='POST', path='import', name='import')
  def ImportConfigData(self, request):
    """Imports another server's node configuration.

    Body:
      Exported node configuration data
    """
    config_set = config_encoder.Decode(request.value)
    config_encoder.Load(config_set)
    return message_types.VoidMessage()


from bs4 import BeautifulSoup
import requests
import pandas as pd

def COVID_scrape():

    url = 'https://data.humdata.org/dataset/novel-coronavirus-2019-ncov-cases'

    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'lxml')
    scraped = soup.find_all('a', class_='resource-url-analytics')

    confirmed = scraped[0]['href']
    deaths = scraped[1]['href']
    recovered = scraped[2]['href']

    confirmed_df = pd.read_csv(confirmed)
    deaths_df = pd.read_csv(deaths)
    recovered_df = pd.read_csv(recovered)

    lastupdate = []
    for col in confirmed_df.columns:
        lastupdate.append(col)

    lastupdate = lastupdate[-1]

    return {"confirmed": confirmed_df, "deaths": deaths_df, "recovered": recovered_df, "lastupdate": lastupdate}


from datetime import datetime

current_date_and_time = datetime.now()
day_of_week = current_date_and_time.weekday()

total_price = float()
sales_tax = float()
subtotal = float(input("Please enter the subtotal: "))
buy_more = float()
discount = float()

def price_math():
    global total_price
    global sales_tax
    global subtotal
    global buy_more
    global discount
    if day_of_week == 1 or 2:
        if subtotal >= 50:
            discount = subtotal * .1
            subtotal = subtotal * .9
            print(f"Your discount: {discount:.2f}$")
        else:
            buy_more = 50 - subtotal #stretch (get the amount remainder the user needs to buy to get the discount)
            print(f'You will need to purchase ${buy_more} to get the 10% discount')
    sales_tax = subtotal * .06
    total_price = sales_tax + subtotal

price_math()
print(f'Subtotal: {subtotal}')
print(f'Sales tax amount: {sales_tax:.2f}')
print(f'Total: {total_price:.2f}$')


import sqlite3
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required

class Item(Resource):
    parser = reqparse.RequestParser() #Item class parser
    parser.add_argument("price", #requests must be in format { "price": float}
        type=float,
        required=True,
        help="FORMAT ERROR: This request must have be string : float where string == price "
    )

    @jwt_required() # jwt authentification required
    def get(self, name): # get request, looking for item called "name",
        item = self.find_by_name(name)
        if item:
            return item
        return {"message": "Item not found"}, 404

    @classmethod
    def find_by_name(cls, name): # abstracted and redifined from get
        # Does NOT require jwt_auth, so it can be used by both get and post
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "SELECT * FROM items WHERE name=?"
        result = cursor.execute(query, (name,))
        row = result.fetchone()
        connection.close()
        if row:
            return {"item": {"name": row[0], "price": row[1]}}

    def post(self, name):
        if self.find_by_name(name):
            return {'message': 'An item with name ' + name + 'already exists.'}, 400
        data = Item.parser.parse_args() # what the user will send to the post request (in good format)
        # In our case, the user sends the price as JSON, but the item name gets passed into the function
        item = {"name": name, "price": data["price"]}
        try:
            self.insert(item)
        except:
            return{"message": "An error occurred while inserting"}, 500 # internal server error

        return item, 201 #post was successful

    @classmethod
    def insert(cls, item):
        # write to database
        # abstracted just like find_by_name so that it can be used by both post and put
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "INSERT INTO items VALUES (?, ?)"
        cursor.execute(query, (item['name'], item['price']))

        connection.commit()
        connection.close()

    def delete(self, name):
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "DELETE FROM items WHERE name=?"
        cursor.execute(query, (name,))

        connection.commit()
        connection.close()

        return {"message": "Item Deleted"}

    def put(self, name):
        data = Item.parser.parse_args() # only add valid JSON requests into data

        item = self.find_by_name(name) # find item
        updated_item = {'name': name, 'price': data['price']}

        if item is None: # no item found, add item name with JSON price
            try:
                self.insert(updated_item)
            except:
                return {"message": "Error inserting item"}, 500
        else:
            try:
                self.update(updated_item) # item found, updated with JSON price
            except:
                return {"message": "Error inserting item"}, 500
        return item

    @classmethod
    def update(cls, item):
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "UPDATE items SET price=? WHERE name=?"
        cursor.execute(query, (item['price'], item['name']))

        connection.commit()
        connection.close()

class ItemList(Resource):
    def get(self):
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "SELECT * FROM items" #select all name matches
        result = cursor.execute(query)
        items = []
        for row in result:
            items.append({'name':row[0], 'price':row[1]})

        connection.close()

        return {'items': items}


from numpy import random
from typing import Any, Text, Dict, List
from typing import Any, Text, Dict, List
import datetime
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import FollowupAction
from rasa_sdk.events import SlotSet
from rasa_sdk.events import ReminderScheduled, ReminderCancelled
from rasa_sdk.executor import CollectingDispatcher

import mysql.connector

mydb = mysql.connector.connect(
        host = "localhost",
        user = "root",
        passwd="",
        database="questions"
    )

mycursor = mydb.cursor()
myresult = []
hintlist = []
finfo = []
randomnum = 0
hintmaxx = 0
hintcnt = 0
failcnt = 0
failmax = 2
count = 0
i=0

class ActionIncreaseScore(Action):

    def name(self) -> Text:
        return "action_answer"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        global randomnum, myresult, hintlist, hintmaxx, hintcnt, finfo, count, i
        ansentity=next(tracker.get_latest_entity_values("answer"), None)
        count = count + 1
        if i == 4:
            return [FollowupAction("action_send_problem_link")]

        # dispatcher.utter_message(text="Hello World!")

        return [FollowupAction("action_quiz")]

class ActionQuiz(Action):

    def name(self) -> Text:
        return "action_quiz"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        global randomnum, myresult, hintlist, hintmaxx, hintcnt, finfo,i,count
        quizentity=next(tracker.get_latest_entity_values("quiz"), None)
        queryy = 'select * from quizes'
        mycursor.execute(queryy)
        myresult = mycursor.fetchall()
        maxx = len(myresult)

        randomnum = random.randint(maxx)
        if i == 4:
            return [FollowupAction("action_send_problem_link")]

        msg = myresult[i][1]
        buttons = [{"title": myresult[i][2], "payload": myresult[i][2]}, {"title": myresult[i][3],  "payload":myresult[i][3]}, {"title": myresult[i][4], "payload": myresult[i][4]}, {"title": myresult[i][5], "payload": myresult[i][5]}]
        dispatcher.utter_button_message(msg+str(count), buttons)
        i = i+1

        return []

class ActionReactToReminder(Action):
    """Reminds the user to call someone."""

    def name(self) -> Text:
        return "action_react_to_reminder"

    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:

        #name = next(tracker.get_latest_entity_values("new"))
        dispatcher.utter_message("Opps! Unfortunately your time has ended! You final score is" + str(count) + "out of 5")

        return [FollowupAction("action_send_problem_link")]

class ActionSetReminder(Action):
    """Schedules a reminder, supplied with the last message's entities."""

    def name(self) -> Text:
        return "action_set_reminder"

    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        # dispatcher.utter_message("Here's a new question for you. Given two strings text1 and text2, return the length of their longest common subsequence.I am setting the timer to 5 seconds.")

        dispatcher.utter_message("The quiz has started and so has the timer. We challenge you to finish it withing 20 minutest. Best of luck!")
        date = datetime.datetime.now() + datetime.timedelta(seconds=7200)
        entities = tracker.latest_message.get("new")

        reminder = ReminderScheduled(
            "EXTERNAL_reminder",
            trigger_date_time=date,
            entities=entities,
            name="my_reminder",
            kill_on_user_message=False,
        )

        return [reminder]

class Actionsendmail(Action):

    def name(self) -> Text:
        return "action_send_problem_link"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        global randomnum, myresult, count

        import smtplib

        EMAIL_ADDRESS = "benjaminimp10@gmail.com"
        EMAIL_PASSWORD = ""
        recieverid = str(tracker.get_slot('mail'))

        with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()

            smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

            subject = 'RASA QUIZ SCORE'
            body = "here's the score of your RASA quiz: " + " " + str(count)

            msg = f'Subject: {subject}\n\n{body}'

            smtp.sendmail(EMAIL_ADDRESS, recieverid, msg)

        msg = "The link has been sent to your email id. Thank you for playing the Quiz. Hope you liked it."

        dispatcher.utter_message(text = msg)

        return [FollowupAction("utter_goodbye")]


from __future__ import annotations

from typing import TYPE_CHECKING

from sqlalchemy.ext.asyncio import AsyncSession

from core import tools
from utils import helpers

if TYPE_CHECKING:
    from ws import WSManager

async def check_player(
    session: AsyncSession,
    manager: WSManager,
    session_id: int,
    player_id: int,
) -> None:
    player = await helpers.get_player_by_id(session=session, player_id=player_id)

    if player.game_chips == 0 and not player.is_allin:
        await helpers.delete_player(
            manager=manager, player_id=player_id, preview_balance=player.game_chips
        )

    if player.is_allin or player.is_folded:
        await tools.store.game_session_accessor.set_next_player(
            session=session, session_id=session_id
        )


import os
import json

import torch
import torch.utils.data as data
import numpy as np

class yolo_phoc_dataset(data.Dataset):
    def __init__(self, gt_root, tensors_root, json_labels_path):
        self.gt_root = gt_root
        self.tensors_root = tensors_root
        self.labels_path = json_labels_path

        with open(json_labels_path) as f:
            self.filenames = json.load(f)
        self.keys = list(self.filenames.keys())

    def __getitem__(self, index):
        tensors_fname, masks_fname = self.filenames[self.keys[index]]

        tensors_path = os.path.join(self.tensors_root, tensors_fname)
        masks_path = os.path.join(self.tensors_root, masks_fname)
        gt_path = os.path.join(self.gt_root, self.keys[index])

        tensors = torch.from_numpy(np.load(tensors_path)).type(torch.FloatTensor)
        tensors = tensors.permute(0, 3, 1, 2)
        masks = np.load(masks_path).squeeze()
        masks = torch.from_numpy(masks.reshape(masks.shape[0], -1)).type(torch.FloatTensor)
        gt = torch.from_numpy(np.load(gt_path)).type(torch.FloatTensor)

        return tensors, masks, gt

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

def get_data_loader(gt_root, tensors_root, json_labels_path,
                    batch_size, shuffle=True, num_workers=8,):

    dataset = yolo_phoc_dataset(gt_root, tensors_root, json_labels_path)

    data_loader = data.DataLoader(dataset=dataset, batch_size=batch_size,
                                  shuffle=shuffle, num_workers=num_workers)

    return data_loader


import os
import re

import cv2 as cv

class ImageTools:
    original_dir: str
    original_dir_hr: str
    # preprocess_dir: str
    # measure_dir: str
    # net_dir: str
    # logs_dir: str
    # final_dir: str

    root_dir = "Data/Samples"
    measure_dir = "Measures"
    net_dir = 'Net'
    logs_dir = "Logs"
    final_dir = "Result"
    preprocess_dir = "Preprocess"
    preprocess_net_dir = "Preprocess_net"
    descript_dit = "Descript"

    CONTROL_NET_DIR = "Data/Final/Control/Net"
    CONTROL_MEASURE_DIR = "Data/Final/Control/Metrics"

    IMAGES_FILE_TYPE = ['.png', '.jpg']

    initial_shape: list or None

    def __init__(self, original_dir, original_dir_hr):
        self.control_metric_dir = None
        self.control_net_dir = None
        self.uuid = None
        self.initial_shape= None
        self.original_dir_hr = original_dir_hr
        self.original_dir = original_dir

        self.num_of_images = 0

    def built_structure(self, num_samples, uuid):
        self.uuid = uuid
        self.root_dir = self.create_dir(os.path.join(self.root_dir, uuid))
        self.measure_dir = self.create_dir(os.path.join(self.root_dir, self.measure_dir))
        self.logs_dir = self.create_dir(os.path.join(self.root_dir, self.logs_dir))
        self.preprocess_net_dir = self.create_dir(os.path.join(self.root_dir, self.preprocess_net_dir))
        self.net_dir = self.create_dir(os.path.join(self.root_dir, self.net_dir))
        self.preprocess_dir = self.create_dir(os.path.join(self.root_dir, self.preprocess_dir))
        self.descript_dit = self.create_dir(os.path.join(self.root_dir, self.descript_dit))
        self.final_dir = self.create_dir(os.path.join(self.root_dir, self.final_dir))

        self.control_net_dir = os.path.join(self.CONTROL_NET_DIR, os.path.split(self.original_dir)[-1])
        self.control_metric_dir = os.path.join(self.CONTROL_MEASURE_DIR, os.path.split(self.original_dir)[-1])

        for index_sample in range(num_samples):
            preprocess_dir_index_sample = os.path.join(self.preprocess_dir, str(index_sample))
            try:
                os.mkdir(preprocess_dir_index_sample)
            except FileExistsError:
                pass

        for image_name in os.listdir(self.original_dir):
            images_dir = os.path.join(self.original_dir, image_name)
            image = self.load(images_dir)
            if self.initial_shape is None:
                self.initial_shape = image.shape
            for index_sample in range(num_samples):
                sample_dir = os.path.join(self.preprocess_dir, str(index_sample))
                sample_dir = os.path.join(sample_dir, image_name)
                self.save(sample_dir, image)
        self.num_of_images = len(os.listdir(self.original_dir))

    def load(self, file_name):
        """
        raise TypeError if imagen tipy not define
        :param file_name:
        :return Image matrix:
        :raise TypeError:
        """
        file_type = os.path.splitext(file_name)[-1]
        if file_type in self.IMAGES_FILE_TYPE:
            return cv.imread(file_name)
        else:
            raise TypeError

    def save_preprocess_net_image(self, index, name, image):
        path = os.path.join(self.preprocess_net_dir, str(index))
        self.create_dir(path)
        self.save(os.path.join(path, name), image)

    def save_final(self, name, data, sub_dir=None):
        self.create_dir(self.final_dir)

        name = os.path.split(name)[-1]
        if sub_dir is None:
            final_dir = os.path.join(self.final_dir, name)
        else:
            aux_dir = os.path.join(self.final_dir, sub_dir)
            # compruebo si existe el directorio auxsiliar
            self.create_dir(aux_dir)
            final_dir = os.path.join(aux_dir, name)

        self.save(final_dir, data)

    def save(self, dir_name, data):
        file_type = os.path.splitext(dir_name)[-1]
        if file_type in self.IMAGES_FILE_TYPE:
            self._save_(dir_name, data)
        else:
            raise TypeError

    def _save_(self, path, data):
        cv.imwrite(path, data)

    def list_items_from(self, dir4list: str, regex=None) -> list:
        """
        Lista los elemntos del directorio **dir4list** filtrandola en caso de que se defina un patrn en **regex**

        :param dir4list: Directorio
        :param regex: Patron de regex
        :return: Lista finltrada.
        """
        list_items = list(map(lambda x: os.path.join(dir4list, x), os.listdir(dir4list)))
        if regex is not None:
            list_items = list(filter(lambda x: re.match(regex, x), list_items))
        return list_items

    @property
    def list_samples_dir(self) -> list:
        return self.list_items_from(self.preprocess_dir)

    @property
    def list_samples_net_dir(self) -> list:
        return self.list_items_from(self.net_dir)

    @property
    def list_samples_correct_net_dir(self) -> list:
        list_ = self.list_items_from(self.preprocess_net_dir)
        if len(list_) == 0:
            list_ = self.list_items_from(self.net_dir)
        return list_

    @property
    def exists_control_dir(self):
        return os.path.exists(self.CONTROL_NET_DIR) and len(os.listdir(self.CONTROL_NET_DIR)) > 0

    @property
    def exists_control_metrics(self):
        return os.path.exists(self.CONTROL_MEASURE_DIR) and len(os.listdir(self.CONTROL_MEASURE_DIR)) > 0

    def info(self):
        return {
            'original_dir' : self.original_dir,
            'original_dir_hr' : self.original_dir_hr,
            'preprocess_dir' : self.preprocess_dir,
            'measure_dir' : self.measure_dir,
            'net_dir' : self.net_dir,
            'logs_dir' : self.logs_dir,
            'final_dir' : self.final_dir,
            'control_net_dir' : self.CONTROL_NET_DIR,
            'control_metric_dir' : self.CONTROL_MEASURE_DIR
        }

    def create_dir(self, dir_):
        if not os.path.exists(dir_):
            os.mkdir(dir_)
        return dir_


from django.urls import path, include
from Auctions import views

urlpatterns = [

    path('', views.index, name='index'),
    path('dashboard/', views.dashboard, name = 'dashboard'),
    path('create-auction/', views.create_auction, name = 'create-auction'),
    path('auctions/<str:category>',views.display_auction , name='display-auction'),
    path('auctions/<str:category>/<int:itemset_id>',views.display_items, name='display-items'),
    path('tdashboard/',views.tdashboard),
    path('search/', views.search_by_keywords,name='search'),
    path('join/<int:auction_id>',views.join_auction,name='join'),
    path('dashboard/created-auctions/', views.view_created, name = 'view-created'),
    path('dashboard/participated-auctions/', views.view_participating, name= 'view-joined'),
    path('about/', views.about, name='about'),
    path('policies/', views.policy, name='policy'),

]


import itertools

s1 = input().rstrip()
s2 = input().rstrip()
s3 = input().rstrip()
ds = {c:i for i, c in enumerate(list(set(s1 + s2 + s3)))}
nd = len(ds)
if nd > 10:
    print('UNSOLVABLE')
    exit()

digits = tuple(map(int, tuple('0123456789')))
for x in itertools.permutations(digits, nd):
    n1 = 0
    n2 = 0
    n3 = 0
    f = False
    for i in range(len(s1)):
        n1 = n1 * 10 + x[ds[s1[i]]]
        if i == 0 and n1 == 0:
            f = True
            break
    if f:
        continue
    for i in range(len(s2)):
        n2 = n2 * 10 + x[ds[s2[i]]]
        if i == 0 and n2 == 0:
            f = True
            break
    if f:
        continue
    for i in range(len(s3)):
        n3 = n3 * 10 + x[ds[s3[i]]]
        if i == 0 and n3 == 0:
            f = True
            break
    if f:
        continue
    if n1 + n2 == n3:
        print(n1)
        print(n2)
        print(n3)
        exit()

print('UNSOLVABLE')