import pandas as pd
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
#%% Reading the obtained results for different representation and sampling methods
undersampling= pd.read_csv('Pred_Infos_undersampling.csv')
oversampling= pd.read_csv('Pred_Info_oversampling.csv')
physical= pd.read_csv('Pred_Info_oversampling_physical.csv')
ph_undersampling= pd.read_csv('Pred_Info_undersampling_physical.csv')

physical_over=pd.DataFrame()
physical_over['Score']=pd.to_numeric(physical.iloc[4,1::2])
physical_over['Embedding'] = 'Physical_Features'
physical_over['Sampling']= 'R-Over-sampling'

physical_smote= pd.DataFrame()
physical_smote['Score']=pd.to_numeric(physical.iloc[4,2::2])
physical_smote['Embedding'] = 'Physical_Features'
physical_smote['Sampling']= 'SMOTE'

physical_under=pd.DataFrame()
physical_under['Score']=pd.to_numeric(ph_undersampling.iloc[4,1:])
physical_under['Embedding'] = 'Physical_Features'
physical_under['Sampling']=  ' Undersampling'
#%%
undersampling_oh= list(undersampling.iloc[4,1::3])
undersampling_unirep=list(undersampling.iloc[4,2::3])
undersampling_esm= list(undersampling.iloc[4,3::3])

oversampling_ro_oh=list(oversampling.iloc[4,1::6])
oversampling_ro_unirep=list(oversampling.iloc[4,2::6])
oversampling_ro_esm= list(oversampling.iloc[4,3::6])

oversampling_smo_oh=list(oversampling.iloc[4,4::6])
oversampling_smo_unirep=list(oversampling.iloc[4,5::6])
oversampling_smo_esm= list(oversampling.iloc[4,6::6])

#%% plot 1 making comparison between each embedding performance for undersampling vs oversampling

OH_under= pd.DataFrame()
OH_under['Score']= pd.to_numeric(undersampling.iloc[4,1::3])
OH_under['Embedding'] = 'OneHot'
OH_under['Sampling']= 'Under-sampling'
OH_under_n= OH_under[(np.abs(stats.zscore(OH_under['Score'])) < 3)|(np.abs(stats.zscore(OH_under['Score'])) > -3)]

OH_over= pd.DataFrame()
OH_over['Score']= pd.to_numeric(oversampling.iloc[4,1::6])
OH_over['Embedding'] = 'OneHot'
OH_over['Sampling']= 'R-Over-sampling'
OH_over_n= OH_over[(np.abs(stats.zscore(OH_over['Score'])) < 3)|(np.abs(stats.zscore(OH_over['Score'])) >-3)]

OH_smote= pd.DataFrame()
OH_smote['Score']= pd.to_numeric(oversampling.iloc[4,4::6])
OH_smote['Embedding'] = 'OneHot'
OH_smote['Sampling']= 'SMOTE'
OH_smote_n= OH_smote[(np.abs(stats.zscore(OH_smote['Score'])) < 3)|(np.abs(stats.zscore(OH_smote['Score'])) >-3)]

Unirep_under= pd.DataFrame()
Unirep_under['Score']= pd.to_numeric(undersampling.iloc[4,2::3])
Unirep_under['Embedding'] = 'UniRep'
Unirep_under['Sampling']= 'Under-sampling'
Unirep_under_n= Unirep_under[(np.abs(stats.zscore(Unirep_under['Score'])) < 3)|(np.abs(stats.zscore(Unirep_under['Score'])) > -3)]

Unirep_over= pd.DataFrame()
Unirep_over['Score']= pd.to_numeric(oversampling.iloc[4,2::6])
Unirep_over['Embedding'] = 'UniRep'
Unirep_over['Sampling']= 'R-Over-sampling'
Unirep_over_n= Unirep_over[(np.abs(stats.zscore(Unirep_over['Score'])) < 3)|(np.abs(stats.zscore(Unirep_over['Score']))>-3)]

Unirep_smote= pd.DataFrame()
Unirep_smote['Score']= pd.to_numeric(oversampling.iloc[4,5::6])
Unirep_smote['Embedding'] = 'UniRep'
Unirep_smote['Sampling']= 'SMOTE'
Unirep_smote_n= Unirep_smote[(np.abs(stats.zscore(Unirep_smote['Score'])) < 3)|(np.abs(stats.zscore(Unirep_smote['Score'])) >-3)]

ESM_under= pd.DataFrame()
ESM_under['Score']= pd.to_numeric(undersampling.iloc[4,3::3])
ESM_under['Embedding'] = 'ESM'
ESM_under['Sampling']= 'Under-sampling'
ESM_under_n= ESM_under[(np.abs(stats.zscore(ESM_under['Score'])) < 3)|(np.abs(stats.zscore(ESM_under['Score'])) >-3)]

ESM_over= pd.DataFrame()
ESM_over['Score']= pd.to_numeric(oversampling.iloc[4,3::6])
ESM_over['Embedding'] = 'ESM'
ESM_over['Sampling']= 'R-Over-sampling'
ESM_over=ESM_over.drop(index='RandomOverSampler()UniRep_Embedding6')
ESM_over_n= ESM_over[(np.abs(stats.zscore(ESM_over['Score'])) < 3)|(np.abs(stats.zscore(ESM_over['Score'])) > -3)]

ESM_smote= pd.DataFrame()
ESM_smote['Score']= pd.to_numeric(oversampling.iloc[4,6::6])
ESM_smote['Embedding'] = 'ESM'
ESM_smote['Sampling']= 'SMOTE'
ESM_smote_n= ESM_smote[(np.abs(stats.zscore(ESM_smote['Score'])) < 3)| (np.abs(stats.zscore(ESM_smote['Score'])) >-3)]

physical_over=pd.DataFrame()
physical_over['Score']=pd.to_numeric(physical.iloc[4,1::2])
physical_over['Embedding'] = 'Physical_Features'
physical_over['Sampling']= 'R-Over-sampling'

physical_smote= pd.DataFrame()
physical_smote['Score']=pd.to_numeric(physical.iloc[4,2::2])
physical_smote['Embedding'] = 'Physical_Features'
physical_smote['Sampling']= 'SMOTE'
#%%
df_all_n= pd.concat([OH_under_n, OH_over_n, OH_smote_n, Unirep_under_n, Unirep_over_n, Unirep_smote_n, ESM_under_n, ESM_over_n, ESM_smote_n])
df_all= pd.concat([OH_under, OH_over, OH_smote, Unirep_under, Unirep_over, Unirep_smote, ESM_under, ESM_over, ESM_smote, physical_smote, physical_over])
df_all_nn= df_all[(np.abs(stats.zscore(df_all['Score'])) < 3)| (np.abs(stats.zscore(df_all['Score'])) >-3)]

df_alll= pd.concat([ OH_over, Unirep_over, ESM_under,  physical_smote])

#%% Sampling vs sampling

OH_under_vs_over= stats.ttest_ind(OH_under['Score'], OH_over['Score'])
OH_under_vs_smote= stats.ttest_ind(OH_under['Score'], OH_smote['Score'])
OH_over_vs_smote= stats.ttest_ind(OH_over['Score'], OH_smote['Score'])

Unirep_under_vs_over= stats.ttest_ind(Unirep_under['Score'], Unirep_over['Score'])
Unirep_under_vs_smote= stats.ttest_ind(Unirep_under['Score'], Unirep_smote['Score'])
Unirep_over_vs_smote= stats.ttest_ind(Unirep_over['Score'], Unirep_smote['Score'])

ESM_under_vs_over= stats.ttest_ind(ESM_under['Score'], ESM_over['Score'])
ESM_under_vs_smote= stats.ttest_ind(ESM_under['Score'], ESM_smote['Score'])
ESM_over_vs_smote= stats.ttest_ind(ESM_over['Score'], ESM_smote['Score'])

#%% T test Representation vs representation given same sampling method

Under_OH_Unirep= stats.ttest_ind(OH_under['Score'], Unirep_under['Score'])
Under_OH_ESM=stats.ttest_ind(OH_under['Score'], ESM_under['Score'])
Under_ESM_Unirep=stats.ttest_ind(ESM_under['Score'], Unirep_under['Score'])

Over_OH_Unirep= stats.ttest_ind(OH_over['Score'], Unirep_over['Score'])
Over_OH_ESM=stats.ttest_ind(OH_over['Score'], ESM_over['Score'])
Over_ESM_Unirep=stats.ttest_ind(ESM_over['Score'], Unirep_over['Score'])

smote_OH_Unirep= stats.ttest_ind(OH_smote['Score'], Unirep_smote['Score'])
smote_OH_ESM=stats.ttest_ind(OH_smote['Score'], ESM_smote['Score'])
smote_ESM_Unirep=stats.ttest_ind(ESM_smote['Score'], Unirep_smote['Score'])


from enum import Enum
import enums

class Carta:
	def __init__(self, numero, color, efecto):
		if not isinstance(color, enums.Color):
			raise TypeError("Color no existente")
		if numero is not None and not isinstance(numero, int):
			raise ValueError("Número erróneo.")
		self.numero = numero
		self.color = color
		self.efecto = efecto

	def __str__(self):
		texto = ""
		if not self.numero and self.color is enums.Color.sin_color:
			texto = "Comodin: {}".format(self.efecto)
		elif self.numero is None:
			texto = "{} - {}".format(self.color, self.efecto)
		else:
			texto = "{} - {}".format(self.color, self.numero)

		return texto

	def aplicar_color(self, color):
		self.color = color


import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.convolutional import MaxPooling1D, Conv1D
from keras.layers import Dense, BatchNormalization, Activation, Dropout
from keras.optimizers import Adam, SGD
from keras.layers import Flatten, RepeatVector
from achieve_params import Flags

def base_model(trainX, trainY, input_dim=1, output_dim=7, type='easy'):
    """
    output = activation(BN(Wx+b))
    :param trainX:
    :param trainY:
    :param input_dim:
    :param output_dim:
    :param type:
    :return:
    """
    keras.backend.clear_session()
    if type == 'easy':
        model = Sequential()
        model.add(LSTM(units=Flags.unit, input_dim=input_dim))
        model.add(BatchNormalization(momentum=0.99))
        model.add(Activation('linear'))
        model.add(Dense(1))
        model.compile(loss='mae', optimizer=Adam(lr=0.002, beta_1=0.9))
        history = model.fit(trainX, trainY, nb_epoch=Flags.epoch, batch_size=Flags.batch_size,
                            verbose=1, validation_split=Flags.validation_split)
    elif type == 'hard':
        model = Sequential()
        model.add(Conv1D(filters=32, kernel_size=1, activation='linear', input_shape=(1, 7)))
        model.add(MaxPooling1D(pool_size=1))
        model.add(Flatten())
        model.add(RepeatVector(1))
        model.add(LSTM(Flags.unit, activation='linear', return_sequences=True))
        model.add(LSTM(50, activation='linear', return_sequences=False))
        model.add(Dropout(Flags.dropout))
        model.add(Flatten())
        model.add(Dense(output_dim))
        model.add(BatchNormalization(momentum=0.99))
        model.compile(loss='mae', optimizer=Adam(lr=0.002, beta_1=0.9))
        history = model.fit(trainX, trainY, nb_epoch=Flags.epoch, batch_size=Flags.batch_size,
                            verbose=1, validation_split=Flags.validation_split)
    return model, history


import asyncio
import os
from time import sleep
from aion.microservice import main_decorator, Options
from aion.kanban import Kanban
from aion.logger import lprint, lprint_exception

from .yaskawa import command

SERVICE_NAME = "control-yaskawa-robot-r-kube"
ADDRESS = "192.168.X.X"
PORT = 10040
JSON_PATH = os.path.join(
    "/var/lib/aion/Data/control-yaskawa-robot-r_1/command_list.json")
TRIGGER_PATH = os.path.join(
    "/var/lib/aion/Data/control-yaskawa-robot-r_1/trigger_list.json")

@main_decorator(SERVICE_NAME)
def main(opt: Options):
    conn = opt.get_conn()
    num = opt.get_number()

    kanban = conn.set_kanban(SERVICE_NAME, num)
    address = os.environ[f"ROBOT_IP_{num:02d}"]
    lprint(f"robot address: {address}")

    loop = asyncio.get_event_loop()
    y = command.YaskawaRobotCommunicator(
        JSON_PATH, address, PORT, loop, __file__, TRIGGER_PATH
    )
    y.start_to_send(conn)


import sys
import re
import os
import shutil
import subprocess

"""Copy Special exercise

"""

# +++your code here+++
# Write functions and modify main() to call them
def get_special_paths(dir):
    result = []
    filenames = os.listdir(dir)
    for filename in filenames:
        match = re.search(r'__\w+__', filename)
        if match:
            result.append(os.path.abspath(os.path.join(dir, filename)))
    return result

def copy_to(paths, dir):
    for path in paths:
        shutil.copy(path, dir)

def zip_to(paths, zippath):
    cmd = 'zip -j ' + zippath + ' ' + ' '.join(paths)
    print("Command I'm going to do:", cmd)
    (status, output) = subprocess.getstatusoutput(cmd)
    if status:
        sys.stderr.write(output + '\n')
        sys.exit(1)
    print(output)

def main():
    # This basic command line argument parsing code is provided.
    # Add code to call your functions below.

    # Make a list of command line arguments, omitting the [0] element
    # which is the script itself.
    args = sys.argv[1:]
    if not args:
        print("usage: [--todir dir][--tozip zipfile] dir [dir ...]")
        sys.exit(1)

    # todir and tozip are either set from command line
    # or left as the empty string.
    # The args array is left just containing the dirs.
    todir = ''
    if args[0] == '--todir':
        todir = args[1]
        del args[0:2]

    tozip = ''
    if args[0] == '--tozip':
        tozip = args[1]
        del args[0:2]

    if len(args) == 0:
        print("error: must specify one or more dirs")
        sys.exit(1)

    # +++your code here+++
    # Call your functions
    paths = []
    for dirname in args:
        paths += get_special_paths(dirname)

    if todir:
        os.makedirs(todir, exist_ok=True)
        copy_to(paths, todir)
    elif tozip:
        zip_to(paths, tozip)
    else:
        print('\n'.join(paths))

if __name__ == "__main__":
    main()


import discord_bot_tools as dt
import datetime, os, asyncio

async def log_all_messages(client):
    """
    Arguments:
        client: A discord.py Client Object

    Returns:
        Logs messages from all private channels, servers, everything it can see.
    """
    print("Logging All Messages for %s..." % client.user.name)

    """
    Then loop through the connected channels from expected smallest amount to largest amount:
        1. Private Messages
        2. Servers -> Server Channels
    """
    await log_all_private_messages(client)
    await log_all_server_messages(client)

    print("Completed Logging All Messages for %s." % client.user.name)

async def all_messages(client):
    """
    Arguments:
        client: A discord.py Client Object

    Returns:
        Exactly like our log_all_messages function, except this function is a generator.
        It loops through all messages belonging to the client object, be them in
            private channels, private group messages, servers, or whatever.

        I could write a version of these for every single other log_ function,
            but I really don't want to yet.
    """
    #Get our two lists
    channels = [channel for channel in client.get_all_channels()]
    private_channels = [private_channel for private_channel in client.private_channels]

    #Get all our messages as one list
    channels.extend(private_channels)

    #Loop through all channels and messages
    for channel in channels:
        try:
            async for msg in client.logs_from(channel, limit=100100100100):
                yield msg
        except:
            pass

async def log_all_server_messages(client):
    """
    Arguments:
        client: A discord.py Client Object

    Returns:
        Logs messages from all servers and channels in these servers.
    """
    print("Logging All Server Messages for %s from %i Servers..." % (client.user.name, len([server for server in client.servers])))

    await log_channel_messages(client, client.get_all_channels())

    print("Completed Logging All Server Messages for %s." % client.user.name)

async def log_all_private_messages(client):
    """
    Arguments:
        client: A discord.py Client Object

    Returns:
        Logs messages from all private messages and private group messages.
    """
    print("Logging All Private Messages for %s from %i Private Channels..." % (client.user.name, len([private_channel for private_channel in client.private_channels])))

    await log_private_messages(client, client.private_channels)

    print("Completed Logging All Private Messages for %s." % client.user.name)

async def log_server_messages(client, server_iterable):
    """
    Arguments:
        client: A discord.py Client Object
        server_iterable: An iterable of servers, where all the servers are either strings or discord.py Server objects.
            Can be of any length > 0
    Returns:
        Will loop through every server in the server_iterable, and log messages from all channels in each server.
        Will call the appropriate function depending on if each server is a string or discord.py Server object.
        Will overwrite existing logs for this server, if it is found, using the usual message format.
    """
    servers = [server for server in server_iterable]
    for server in servers:
        if isinstance(server, str):
            print("Logging Server Messages from %s for %s." % (server, client.user.name))
            await log_server_str_messages(client, server)
            print("Completed Logging Server Messages from %s for %s." % (server, client.user.name))
        else:
            print("Logging Server Messages from %s for %s." % (server.name, client.user.name))
            await log_server_obj_messages(client, server)
            print("Completed Logging Server Messages from %s for %s." % (server.name, client.user.name))

async def log_server_obj_messages(client, server):
    """
    Arguments:
        client: A discord.py Client Object
        server: A server OBJECT, from discord.py.
            Do not confuse with log_server_str_messages, as this only works when the server is an object.

    Returns:
        All messages from the server object, including all channels of the server.
        Will overwrite existing logs for this server.
        This is very useful when you want to ensure you get from a specific server,
            whereas log_server_str_messages can only search for the first server matching
            the name given, and use that. However, this function has the cost of it not being
            obvious what the server is when printing it, since it is a discord object
    """
    await log_channel_messages(client, server.channels)

async def log_server_str_messages(client, server_str):
    """
    Arguments:
        client: A discord.py Client Object
        server_str: A server STRING.
            Do not confuse with log_server_obj_messages, as this only works when the server is a string.

    Returns:
        Searches for servers matching the string passed in, and uses the first result if found.
        If found, logs all messages from the server object, including all channels of the server.
        Will overwrite existing logs for this server.
        This is very useful when you don't want to use an object, however you know the name
            and it's hopefully a unique name. While not as specific as the object, it is easier to use.
    """

    """
    We already have our query, just need our strings to search through.
    This is easily obtained by getting the names of all the servers our client is connected to.
    """
    servers = [server for server in client.servers]
    server_names = [server.name for server in servers]

    #idxs is plural of i because otherwise we would be saying "is"
    search_result_idxs = dt.search_strings(server_str, server_names)

    #If we have results
    if len(search_result_idxs) > 0:
        #Get first result and reference our server object with it.
        first_search_result_i = search_result_idxs[0]
        server_obj = servers[first_search_result_i]

        #Then log messages from this object
        await log_server_obj_messages(client, server_obj)

async def log_channel_messages(client, channel_iterable):
    """
    Arguments:
        client: A discord.py Client Object
        channel_iterable: An iterable of channels, where all the channels are either strings or discord.py Channel objects.
            Can be of any length > 0

    Returns:
            Will check the first element in the iterable and call the appropriate sub-function.
                If string -> log_channel_str_messages()
                If object -> log_channel_obj_messages()
            Will overwrite existing logs for all channels, if they are found, using the usual message format.
    """
    channels = [channel for channel in channel_iterable]
    for channel in channels:
        #print("DEBUG: Logging Channel messages from {}".format(channel))
        if isinstance(channel, str):
            await log_channel_str_messages(client, channel)
        else:
            await log_channel_obj_messages(client, channel)

async def log_channel_obj_messages(client, channel):
    """
    Arguments:
        client: A discord.py Client Object
        channel: A channel OBJECT from discord.py .

    Returns:
        Logs messages from channel using the usual format.
        Will use server attribute to determine the server directory.

        NOTE: NO LONGER SORTS, as this involved holding all messages for a channel in ram.
            Since channels can have millions of messages, this became infeasible.

    """
    log_fname = channel.name + ".log"
    log_fpath = dt.get_valid_filename(client.user.name) + os.sep + "Servers" + os.sep + dt.get_valid_filename(channel.server.name) + os.sep + dt.get_valid_filename(log_fname)

    #print("DEBUG: Channel Object")
    with open(log_fpath, "w") as f:
        try:
            async for msg in client.logs_from(channel, limit=100100100100):
                #print("DEBUG: Message: {}".format(dt.get_global_msg_str(msg).strip()))
                f.write(dt.get_msg_str(msg))
        except:
            pass

async def log_channel_str_messages(client, channel_str):
    """
    Arguments:
        client: A discord.py Client Object
        channel_str: A channel STRING.
            Do not confuse with log_channel_obj_messages, as this only works when the channel is a string.

    Returns:
        Searches for channels matching the string passed in, and uses the first result if found.
        If found, logs all messages from the channel object.
        Will overwrite existing logs for this channel.
        This is very useful when you don't want to use an object, however you know the name
            and it's hopefully a unique name. While not as specific as the object, it is easier to use.
    """

    """
    We already have our query, just need our strings to search through.
    This is easily obtained by getting the names of all the channels our client is connected to.
    """
    channels = [channel for channel in client.get_all_channels()]
    channel_names = [channel.name for channel in channels]

    #idxs is plural of i because otherwise we would be saying "is"
    search_result_idxs = dt.search_strings(channel_str, channel_names)

    #print("DEBUG: Channel String")
    #If we have results
    if len(search_result_idxs) > 0:
        #Get first result and reference our channel object with it.
        first_search_result_i = search_result_idxs[0]
        channel_obj = channels[first_search_result_i]

        #Then log messages from this object
        await log_channel_obj_messages(client, channel_obj)

async def log_private_messages(client, private_channel_iterable):
    """
    Arguments:
        client: A discord.py Client Object
        private_channel_iterable: An iterable of private messages / channels, where all the channels are either strings or discord.py private channel objects.
            Can be of any length > 0

    Returns:
            Will check the first element in the list and call the appropriate sub-function.
                If string -> log_channel_str_messages()
                If object -> log_channel_obj_messages()
            Will overwrite existing logs for all channels, if they are found, using the usual message format.
    """
    private_channels = [private_channel for private_channel in private_channel_iterable]
    for private_channel in private_channels:
        if isinstance(private_channel, str):
            await log_str_private_messages(client, private_channel)
        else:
            await log_obj_private_messages(client, private_channel)

async def log_obj_private_messages(client, private_channel):
    """
    Arguments:
        client: A discord.py Client Object
        private_channel: A PrivateChannel OBJECT from discord.py .

    Returns:
        Logs messages from PrivateChannel object using the usual format.
        Will use their recipient count to determine if it is a group private message or not.
    """
    if len(private_channel.recipients) == 1:
        #One user message
        log_fname = private_channel.user.name + ".log"
        log_fpath = dt.get_valid_filename(client.user.name) + os.sep + "Private_Messages" + os.sep + dt.get_valid_filename(log_fname)
    else:
        #Group Message
        log_fname = '-'.join([user.name for user in private_channel.recipients]) + "-" + dt.get_date_str(private_channel.created_at) + ".log"
        log_fpath = dt.get_valid_filename(client.user.name) + os.sep + "Private_Group_Messages" + os.sep + dt.get_valid_filename(log_fname)

    with open(log_fpath, "w") as f:
        log = []
        try:
            async for msg in client.logs_from(private_channel, limit=100100100100):
                log.append(msg)
        except:
            pass
        log = dt.sort_log(log)
        for msg in log:
            f.write(dt.get_msg_str(msg))

async def log_str_private_messages(client, private_channel_str):
    """
    Arguments:
        client: A discord.py Client Object
        private_channel_str: A private channel STRING.
        Do not confuse with log_obj_private_messages, as this only works when the private channel is a string.

    Returns:
        Searches for private channels matching the string passed in, and uses the first result if found.
        If found, logs all messages from the private channel object.
        Will overwrite existing logs for this private channel.
        This is very useful when you don't want to use an object, however you know the name
            and it's hopefully a unique name. While not as specific as the object, it is easier to use.
        When searching, will use only the name of the users. If it is a group message, it will not use a given name - instead using the users in the group message.
            If you have multiple group messages with the same users, then I suggest using that object or simply logging all private messages instead.
    """

    """
    We already have our query, just need our strings to search through.
    This is easily obtained by getting the names of all the private channels our client is connected to.
    We get these names in a similar way to how we get them for their log filenames in log_obj_private_messages(),
        but without the filename, file extension, filepath, and date. We use recipients to tell if it is a group or private message.
    """
    private_channels = [private_channel for private_channel in client.private_channels]
    private_channel_names = []
    for private_channel in private_channels:
        if len(private_channel.recipients) == 1:
            #One user message
            private_channel_name = private_channel.user.name
        else:
            #Group Message
            private_channel_name = '-'.join([user.name for user in private_channel.recipients])

        #Add to list of names
        private_channel_names.append(private_channel_name)

    #idxs is plural of i because otherwise we would be saying "is"
    search_result_idxs = dt.search_strings(private_channel_str, private_channel_names)

    #If we have results
    if len(search_result_idxs) > 0:
        #Get first result and reference our private channel object with it.
        first_search_result_i = search_result_idxs[0]
        private_channel_obj = private_channels[first_search_result_i]

        #Then log messages from this object
        await log_obj_private_messages(client, private_channel_obj)


from django.urls import path, include
#from .views import ArticleApiView
from .views import ArticleCreateApiView, ArticleListApiView, \
    ArticleUpdateApiView, CommentListApiView, CommentCreateApiView, \
    CommentUpdateApiView

app_name = "news"

urlpatterns = [
    # path('articles/', ArticleApiView.as_view()),
    # path('articles/<int:pk>', ArticleApiView.as_view()),
    path('articles/create/', ArticleCreateApiView.as_view()),
    path('articles/', ArticleListApiView.as_view()),
    path('articles/update/<int:pk>', ArticleUpdateApiView.as_view()),
    path('comments/', CommentListApiView.as_view()),
    path('comments/create', CommentCreateApiView.as_view()),
    path('comments/update/<int:pk>', CommentUpdateApiView.as_view()),
]


#!/usr/bin/env python

from mimetypes import guess_type
from sys import stderr
from sys import stdout
from collections import defaultdict
import argparse
import gzip

def sort_variant(scf, line_to_sort):
    if scf2chr[scf] == 'A':
        variant_file_A.write(line_to_sort)
    elif scf2chr[scf] == 'X':
        variant_file_X.write(line_to_sort)
    else:
        variant_file_other.write(line_to_sort)

parser = argparse.ArgumentParser(description='Sorting variants by chromosomal assignment')
parser.add_argument('vcf_file', help='The vcf file to be sorted')
parser.add_argument('asignment_table', help='tsv file with header that contain "scf" and "chr" columns')
parser.add_argument('-o', '-output', help='pattern used to generate new vcf files (with _<Chr>.vcf suffix)', default = 'sorted_variants')

args = parser.parse_args()

encoding = guess_type(args.vcf_file)[1]
_open = partial(gzip.open, mode='rt') if encoding == 'gzip' else open

stderr.write("Sorting " + args.vcf_file + " vcf file using " + args.asignment_table + " asignment table.")

scf2chr = defaultdict(lambda: 'other')

# args.asignment_table='data/Afus1/asm/asm_01_spades_filt_reads/scaffold_lengths_and_covs.tsv'
with open(args.asignment_table) as asn_tab:
    header = asn_tab.readline().rstrip('\n').split('\t')
    scf_col = [i for i,h in enumerate(header) if h == 'scf'][0]
    chr_col = [i for i,h in enumerate(header) if h == 'chr'][0]
    # if there is no scf/chr, it prints an obscure error
    for line in asn_tab:
        scf_info_vec = line.rstrip('\n').split('\t')
        # this could be more general
        if scf_info_vec[chr_col] in ['A', 'X']:
            scf2chr[scf_info_vec[scf_col]] = scf_info_vec[chr_col]

### sort header
# args.o = 'data/resequencing/SNP_calls/freebayes_filtered_sorted'
variant_file_A = open(args.o + "_A.vcf", "w")
variant_file_X = open(args.o + "_X.vcf", "w")
variant_file_other = open(args.o + "_other.vcf", "w")

# args.vcf_file='data/resequencing/SNP_calls/freebayes_all_samples_filt.vcf'
with _open(args.vcf_file) as vcf_file:
    header_line = vcf_file.readline()
    while header_line.startswith("#"):
        if header_line.startswith('##contig'):
            scf=header_line.split('ID=')[1].split(',')[0]
            # lines that should be sorted to individual headers
            sort_variant(scf, header_line)
        else:
            # lines that should be present in all vcf headers
            variant_file_A.write(header_line)
            variant_file_X.write(header_line)
            variant_file_other.write(header_line)
        header_line = vcf_file.readline()

    variant = header_line
    scf = variant.rstrip('\n').split('\t')[0]
    sort_variant(scf, variant)

    for variant in vcf_file:
        scf = variant.rstrip('\n').split('\t')[0]
        sort_variant(scf, variant)

variant_file_A.close()
variant_file_X.close()
variant_file_other.close()


# Day 4: Rock, Paper, Scissor

import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

# Lijst met mogelijkheden:
RPS = [rock, paper, scissors]

# Hier wordt de keuze van de speler verwerkt:
player = int(input("What do you choose? Type 0 for Rock, 1 for paper or 2 for scissors.\n"))
if player <= 2:
    print("You chose\n" + RPS[int(player)])
else:
    print("You typed an invalid number, pls try again")

# Hier wordt een willekeurige keuze van de computer bepaald:
computer = random.randint(0, 2)
if player <= 2:
    print("Computer chose\n" + RPS[int(computer)])

# Getal wordt string
player = int(player)
computer = int(computer)

# Hier wordt besloten wie er wint:
if player == 0 and computer == 0:
    print("Draw")
elif player == 0 and computer == 1:
    print("You lose")
elif player == 0 and computer == 2:
    print("You win")

if player == 1 and computer == 0:
    print("You win")
elif player == 1 and computer == 1:
    print("Draw")
elif player == 1 and computer == 2:
    print("You lose")

if player == 2 and computer == 0:
    print("You lose")
elif player == 2 and computer == 1:
    print("You win")
elif player == 2 and computer == 2:
    print("Draw")

Day 4; Rock, Paper, Scissors/Day 4; Rock, Paper, Scissors.py


BUFFS = {
    "weapon":{
        "all":[
            "Anti-Material 3",
            "Anti-Material 2",
            "Attack up 3",
            "Attack up 2",
            "Construction Speed up lv3",
            "Construction Speed up lv2",
            "Ambush Attack up lv3",
            "Ambush Attack up lv2",
            "Warrior Slayer",
            "Cleric Slayer",
            "Mage Slayer",
            "Fire Enchant Effect",
            "Ice Enchant Effect",
            "Lightning Enchant Effect",
            "Wind Enchant Effect",
            "Anti-Guard Attack up lv3",
            "Anti-Guard Attack up lv2",
            "Stun Crusher",
            "Freeze Crusher",
            "KO Crusher",
            "Shock Crusher",
            "KO Effect up lv3",
            "Stun Effect up lv3",
            "Stun Effect up lv2",
            "Smash Effect up lv3",
            "Smash Effect up v2",
            "Attack Reach up",
            "Fast Attack",
            "Longer Rush",
            "Super Spinning blade",
            "Weight reliever"
        ],
        "warrior-exclusive":[
            "Dash Attack Power-Up",
            "Charge attack +",
            "Spinning blade +",
            "Rush +"
        ],
        "mage-exclusive":[
            "Farther Thunderbolt",
            "Farther Fireball",
            "Farther Ice",
            "Wind Enchant +",
            "Ice Enchant +",
            "Lightning Enchant +",
            "Fire Enchant +"
        ],
        "cleric-exclusive":[
            "Sanctuary",
            "Resurect +",
            "Dispel +"
        ]
    },

    "shield":[
        "Get hit & Gain AP 3",
        "Get hit & Gain AP 2",
        "Fast Guard Attack",
        "Guard move Speed up",
        "Uppercut powerup 3",
        "Uppercut powerup 2",
        "Guard Power 3",
        "Guard Power 2",
        "AntiMagic Guard 3",
        "AntiMagic Guard 2",
        "Guard HPrecovery 3",
        "Guard HPrecovery 2",
        "Guard Attack 3",
        "Guard Attack 2",
        "Spartan Uppercut"
    ],

    "armor": {
        "all": [
            "Ice Resistance up lv3",
            "Ice Resistance up lv2",
            "Wind Resistance up lv3",
            "Wind Resistance up lv2",
            "Lightning Resistance up lv3",
            "Lightning Resistance up lv2",
            "Fire Resistance up lv3",
            "Fire Resistance up lv2",
            "Anti-Warrior Aid",
            "Anti-Mage Aid",
            "Anti-Cleric Aid",
            "Mobility Speed up lv3",
            "Mobility Speed up lv2",
            "Defense up lv3",
            "Defense up lv2",
            "Magic Defense up lv3",
            "Magic Defense up lv2",
            "Ambush Reliever up lv3",
            "Ambush Reliever up lv2",
            "Intensify Defense",
            "Stun Rate Down up lv3",
            "Stun Rate Down up lv2",
            "KO Rate Down up lv3",
            "KO Rate Down up lv2",
            "Smash Resist up lv3",
            "Smash Resist up lv2",
            "Custom Sacred Armor",
            "Canon Durability up lv3",
            "Canon Durability up lv2",
            "Anti Tactical Power up lv3",
            "Anti Tactical Power up lv2"
        ],
        "warrior-exclusive": [
            'Rush +',
            'Cheer +',
            'Iron Phalanx +'
        ],
        "mage-exclusive": [
            'Meteor Storm +',
            'Tornado +',
            'Lightning Strike +'
        ],
        "cleric-exclusive": [
            'Sacred Song +',
            'Happy Miracle +',
            'Transport +',
        ]
    },

    "helmet": {
        "all": [
            "Max HP up 3",
            "Max HP up 2",
            "Max AP up 3",
            "Max AP up 2",
            "Hp Recovery 3",
            "Hp Recovery 2",
            "AP Recovery 3",
            "AP Recovery 2",
            "HP & AP Limit 3",
            "HP & AP Limit 2",
            "HP & AP Recov 3",
            "HP & AP Recov 2",
            "Reduce Status Effect",
            'Intensify HP'
        ],
        "warrior-exclusive": [
            "Shield Charge",
            'Rocket man +',
            'Super Guard +'
        ],
        "mage-exclusive": [
            'Fast Blizzard',
            'Blizzard +',
            'Napalm +'
        ],
        "cleric-exclusive": [
            'Fast Resurrect',
            "Wide Dispel"
            'Sacred Armor +'
        ]
    },

    "acc":[
        "Shorten Cooldown 3",
        "Shorten Cooldown 2",
        "Conserve AP 3",
        "Conserve AP 2",
        "Tactical Power 3",
        "Tactical Power 2",
        "Canon Shots up 3",
        "Canon Shots up 2",
        "Parameter Boost 3",
        "Parameter Boost 2",
        "Happy Dance 3",
        "Happy Dance 2",
        "Happy Dance 1",
        "Start From lv 2",
        "Conserve Shot AP 3",
        "Conserve Shot AP 2"
    ]
}


DOCTYPE = "!DOCTYPE"
html = "html"
head = "head"
body = "body"
div = "div"
a = "a"
b = "b"
button = "button"
form = "form"
input = "input"
abbr = "abbr"
address = "address"
area = "area"
article = "article"
aside = "aside"
audio = "audio"
base = "base"
bdi = "bdi"
bdo = "bdo"
blockquote = "blockquote"
br = "br"
canvas = "canvas"
caption = "caption"
cite = "cite"
code = "caption"
col = "col"
colgroup = "colgroup"
data = "data"
datalist = "datalist"
dd = "dd"
Del = "del"
details = "details"
dfn = "dfn"
dialog = "dialog"
dl = "dl"
dt = "dt"
em = "em"
embed = "embed"
fieldset = "fieldset"
figcaption = "figcaption"
figure = "figure"
footer = "footer"
h1, h2, h3, h4, h5, h6 = ("h1", "h2", "h3", "h4", "h5", "h6")
header = "header"
hr = "hr"
i = "i"
iframe = "iframe"
img = "img"
ins = "ins"
kbd = "kbd"
label = "label"
legend = "legend"
li = "li"
link = "link"
main = "main"
map = "map"
mark = "mark"
meta = "meta"
meter = "meter"
nav = "nav"
noscript = "noscript"
object = "object"
ol = "ol"
optgroup = "optgroup"
option = "option"
output = "output"
p = "p"
param = "param"
picture = "picture"
pre = "pre"
progress = "progress"
q = "q"
rp = "rp"
rt = "rt"
ruby = "ruby"
s = "s"
samp = "samp"
script = "script"
section = "section"
select = "select"
small = "small"
source = "source"
span = "span"
strong = "strong"
style = "style"
sub = "sub"
summary = "summary"
sup = "sup"
svg = "svg"
table = "script"
tbody = "tbody"
td = "td"
template = "template"
textarea = "textarea"
tfoot = "tfoot"
th = "th"
thead = "thead"
time = "time"
title = "title"
tr = "tr"
track = "track"
u = "u"
ul = "ul"
var = "var"
video = "video"
wbr = "wbr"
fragment = 'fragment'
UNSAFEHTML = 'UNSAFEHTML'


__all__ = ["boxplot"]

from typing import Union, List, Tuple

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

from .utils import is_rgb
from .utils import is_series
from .utils import is_dataframe
from .utils import process_axes
from .utils import create_subplots
from .utils import make_cols_from_cmap

def boxplot(
        data:Union[np.ndarray, List[np.ndarray]],
        line_color:Union[str, List[str]] = None,
        line_width = None,
        fill_color:Union[str, List[str]] = None,
        labels:Union[str, List[str]] = None,
        share_axes:bool = True,
        figsize:tuple = None,
        ax:plt.Axes = None,
        ax_kws:dict = None,
        show:bool = True,
        **box_kws,
)->Tuple[Union[plt.Axes, List[plt.Axes]], Union[List[dict], dict]]:
    """
    Draws the box and whiker plot

    parameters
    ----------
    data :
        array like (list, numpy array, pandas dataframe/series) or list of
        array likes. If list of array likes, the length of arrays in the list
        can be different.
    line_color :
        name of color/colors/cmap for lines/boundaries of box
    line_width :
        width of the box lines.
    fill_color :
        name of color/colors/cmap to fill the boxes. It can be any valid
         matplotlib color or cmap.
    labels : str/list (default=None)
        used for ticklabels of x-axes
    share_axes : bool (default=True)
        whether to draw all the histograms on one axes or not
    figsize : tuple (default=None)
        figure size as tuple (width, height)
    ax : plt.Axes, optional (default=None)
        matploltib axes on which to draw the plot
    ax_kws : dict (default=None)
        keyword arguments of :py:func:`easy_mpl.utils.process_axes`
    show : bool (default=show)
        whether to show the plot or not
    **box_kws :
        any additional keyword argument for :obj:`matplotlib.axes.Axes.boxplot`

    Returns
    -------
    tuple
        a tuple of two
            - plt.Axes or list of :obj:`matplotlib.axes`
            - a dictionary or list of dictionaries which consists of boxes,
              medians, whiskers, fliers

    Examples
    ---------
    >>> from easy_mpl import boxplot
    >>> boxplot(np.random.random((100, 5)))
    we can also provide arrays of different lengths
    >>> boxplot([np.random.random(100), np.random.random(90)])
    the color can be given as either color name or colormap
    >>> boxplot(np.random.random((100, 3)), fill_color=['pink', 'lightblue', 'lightgreen'])
    >>> boxplot(np.random.random((100, 3)), fill_color="viridis")

    See :ref:`sphx_glr_auto_examples_boxplot.py` for more examples

    """

    if ax is None:
        ax = plt.gca()

    _box_kws = {}

    data, labels = _unpack_data(data, labels, share_axes)

    if share_axes:
        nplots = 1
    else:
        nplots = len(labels)

    if box_kws is None:
        box_kws = dict()

    _box_kws.update(box_kws)

    f, axes = create_subplots(nplots, ax=ax, figsize=figsize)

    if isinstance(axes, np.ndarray):
        axes = axes.flatten().tolist()
    elif isinstance(axes, plt.Axes):
        axes = [axes]

    nboxes = len(labels)
    if len(labels)==1:
        nboxes = len(labels[0])
    fill_colors = _unpack_colors(fill_color, nboxes, share_axes)
    line_colors = _unpack_colors(line_color, nboxes, share_axes)
    line_widths = _unpack_linewidth(line_width, nboxes, share_axes)

    box_outs = []
    for (idx, name), x, ax in zip(enumerate(labels), data, axes):

        # in version 3.2.. giving DataFrame to ax.boxplot makes boxes for each row
        # in version 3.3.. giving DataFrame to ax.boxplot tries to make boxp for first row (columns)
        if is_dataframe(x) and matplotlib.__version__ < "3.3.0":
            x = x.values

        box_out = ax.boxplot(x, **_box_kws)
        box_outs.append(box_out)

        _set_box_props(fill_colors[idx], line_colors[idx],
                       line_widths[idx], box_out)

        _set_ticklabels(ax, share_axes, name, _box_kws)

        if ax_kws:
            process_axes(ax, **ax_kws)

    if show:
        plt.show()

    if len(box_outs)==1:
        box_outs = box_outs[0]

    if len(axes)==1:
        axes = axes[0]

    return axes, box_outs

def _set_ticklabels(ax, share_axes, name, box_kws):

    if name is not None:
        kws = dict()

        if share_axes:
            if box_kws.get('vert', True):
                ax.set_xticklabels(name)
            else:
                ax.set_yticklabels(name)
        else:
            if isinstance(name, (str, int)):
                if box_kws.get('vert', True):
                    ax.set_xticklabels([name])
                else:
                    ax.set_yticklabels([name], rotation=90, va='center')
            elif isinstance(name, list):
                if box_kws.get('vert', True):
                    ax.set_xticklabels(name)
                else:
                    ax.set_yticklabels(name, rotation=90, va='center')

        if share_axes and len(name) > 7:
            kws['rotation'] = 90
            ax.xaxis.set_tick_params(rotation=90)

    return

def _unpack_linewidth(line_width, nboxes, share_axes):
    if isinstance(line_width, (float, int)):
        line_widths = [[line_width] for _ in range(nboxes)]
    elif line_width is None:
        line_widths = [[None] for _ in range(nboxes)]

    if share_axes:
       line_widths = [[line_width[0] for line_width in line_widths]]

    return line_widths

def _unpack_colors(color, nboxes, share_axes)->list:
    if isinstance(color, str):
        if color in plt.colormaps():
            colors = make_cols_from_cmap(color, nboxes)
            colors = [[color] for color in colors]
        else:
            colors = [[color] for _ in range(nboxes)]
    elif is_rgb(color):
        colors = [[color] for _ in range(nboxes)]
    elif hasattr(color, '__len__'):
        assert len(color) == nboxes, f"{len(color)} colors for {nboxes} boxes?"
        colors = [[clr] for clr in color]
    elif color is None:
        colors = [[None] for _ in range(nboxes)]
    else:
        raise ValueError(f"{color} is not recognized as valid color")

    if share_axes:
       colors = [[color[0] for color in colors]]

    return colors

def _set_box_props(fill_color:list,
                   line_color:list,
                   line_width:list,
                   box_out):

    for idx, patch in enumerate(box_out['boxes']):
        if hasattr(patch, 'set_facecolor'):
            if fill_color[idx] is not None:
                patch.set_facecolor(fill_color[idx])
        elif hasattr(patch, 'set_markerfacecolor'):
            if fill_color[idx] is not None:
                patch.set_markerfacecolor(fill_color[idx])

        if hasattr(patch, 'set_color') and line_color[idx] is not None:
            patch.set_color(line_color[idx])

        if hasattr(patch, 'set_linewidth') and line_width[idx] is not None:
            patch.set_linewidth(line_width[idx])

    return

def _unpack_data(x, labels, share_axes:bool)->Tuple[list, list]:

    if isinstance(x, np.ndarray):
        if len(x) == x.size:
            X = [x]
            names = [[None]]
        else:
            if share_axes:
                X = [x]
                names = [[f"{i}" for i in range(x.shape[1])]]
            else:
                X = [x[:, i] for i in range(x.shape[1])]
                names = [f"{i}" for i in range(x.shape[1])]

    elif is_dataframe(x):
        if share_axes:
            names = [x.columns.tolist()]
            X = [x]
        else:
            X = []
            for col in x.columns:
                X.append(x[col].values)
            names = x.columns.tolist()

    elif is_series(x):
        X = [x.values]
        names = [[x.name]]

    elif isinstance(x, (list, tuple)) and isinstance(x[0], (list, tuple, np.ndarray)):
        assert all([len(array)==array.size for array in x]), f"""
        All arrays must be one dimensional."""
        X = [np.array(x_).reshape(-1,) for x_ in x]
        names = [None] * len(X)
        if share_axes:
            X = [X]
            names = [names]

    elif isinstance(x, (list, tuple)) and is_series(x[0]):  # list of series
        if share_axes:
            X = [x]
        else:
            X = x
        names = [x_.name for x_ in x]

    elif isinstance(x, (list, tuple)) and not is_dataframe(x[0]):
        X = [x]
        names = [None]
    else:
        raise ValueError(f"unrecognized type of x {type(x)}")

    if labels is not None:
        if isinstance(labels, str):
            labels = [labels]
        if share_axes:
            labels = [labels]
        #assert len(labels) == len(names), f"{len(names)} does not match data"
        names = labels

    return X, names


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        self.l1Check = True
        self.l1_l = []
        temp = l1
        while (self.l1Check):
            self.l1_l.append(temp.val)
            if (temp.next == None):
                self.l1Check = False
            else:
                temp = temp.next
        self.l2Check = True
        self.l2_l = []
        temp = l2
        while(self.l2Check):
            self.l2_l.append(temp.val)
            if (temp.next == None):
                self.l2Check = False
            else:
                temp = temp.next
        temp = []
        for i in range(len(self.l1_l)):
            temp.append(str(self.l1_l[len(self.l1_l) - 1 - i]))
        self.l1_l = temp
        temp = []
        for i in range(len(self.l2_l)):
            temp.append(str(self.l2_l[len(self.l2_l) - 1 - i]))
        self.l2_l = temp
        self.l1_l = int("".join(self.l1_l))
        self.l2_l = int("".join(self.l2_l))
        self.rtr = self.l1_l + self.l2_l
        self.rtr = str(self.rtr)
        a = self.getLinkedList(self.rtr)
        return a

    def getLinkedList(self, item):
        for i in range(len(item)):
            if i == 0:
                self.temp = ListNode(int(item[i]))
            else:
                a = ListNode(int(item[i]))
                a.next = self.temp
                self.temp = a
        return self.temp


from os import getenv
import requests
import random
from googletrans import Translator

class assistir_filme():
    token = getenv(key="CHAVE_API_FILMES")
    dict_genero = {"terror":27, "acao":28, "comedia":35, "drama":18, "ficcao_cientifica":878,
               "fantasia":14, "familia":10751, "aventura":12, "misterio":9648, "suspense":53,
               "crime":80, "cinemaTv":10770, "romance":10749}

    def numero_aleatorio(self, limite_range=501):
        numero_aleatorio = random.randrange(1, limite_range)
        return numero_aleatorio

    def chunks(self, lista):
        for i in range(0, len(lista), 4):
            yield lista[i:i + 4]

    def lista_aleatoria(self, lista):
        lista = list(self.chunks(lista))
        count_list = len(lista)
        numero = random.randrange(0, count_list +1)
        try:
            list_aleatoria = lista[numero]
        except:
            numero = numero - 1
            list_aleatoria = lista[numero]
        return list_aleatoria

    def requisicao(self, url):
        requisicao = requests.get(url)
        json = requisicao.json()
        return json

    def listar_filmes_rate_genero(self, rate, genero):
        while True:
            lista_filmes = []
            genero_id = self.dict_genero[f"{genero}"]
            url_geral = "https://api.themoviedb.org/3/discover/movie?" \
                        f"api_key={self.token}&" \
                        "include_adult=false&" \
                        "include_video=false&" \
                        f"page={self.numero_aleatorio()}&" \
                        f"vote_average.gte={rate}&" \
                        f"with_genres={genero_id}"
            filmes = self.requisicao(url_geral)
            filmes = filmes['results']
            if not filmes:
                continue
            else:
                for movie in filmes:
                    id = movie['id']
                    lista_filmes.append(id)
                return lista_filmes

    def listar_filmes_genero(self, genero):
        while True:
            lista_filmes = []
            genero_id = self.dict_genero[f"{genero}"]
            url_geral = "https://api.themoviedb.org/3/discover/movie?" \
                        f"api_key={self.token}&" \
                        "include_adult=false&" \
                        "include_video=false&" \
                        f"page={self.numero_aleatorio()}&" \
                        f"with_genres={genero_id}"
            filmes = self.requisicao(url_geral)
            filmes = filmes['results']
            if not filmes:
                continue
            else:
                for movie in filmes:
                    id = movie['id']
                    lista_filmes.append(id)
                return lista_filmes

    def listar_filmes_rate(self, rate, max_rate=10):
        contador_de_tentativas = 0
        while True:
            if rate >=0 and rate <=4:
                max_rate = 4
            if rate >= 5 and rate <= 7:
                max_rate = 7
            if rate >= 8 and rate <= 10:
                max_rate = 10

            lista_filmes = []
            url_geral = "https://api.themoviedb.org/3/discover/movie?" \
                        f"api_key={self.token}&" \
                        "include_adult=false&" \
                        "include_video=false&" \
                        f"page={self.numero_aleatorio()}&" \
                        f"vote_average.gte={rate}&" \
                        f"vote_average.lte={max_rate}"
            filmes = self.requisicao(url_geral)
            filmes = filmes['results']
            if not filmes:
                contador_de_tentativas += 1
                if contador_de_tentativas == 20:
                    url_geral = f'https://api.themoviedb.org/3/discover/movie?' \
                                f'api_key={self.token}&' \
                                f'include_adult=false&' \
                                f'include_video=false&page={self.numero_aleatorio(limite_range=max_rate)}&' \
                                f'vote_average.gte={rate}&' \
                                f'vote_average.lte={max_rate}'
                    filmes = self.requisicao(url_geral)
                    filmes = filmes['results']
                    if not filmes:
                        continue
                    for movie in filmes:
                        id = movie['id']
                        lista_filmes.append(id)
                    return lista_filmes
                continue
            else:
                for movie in filmes:
                    id = movie['id']
                    lista_filmes.append(id)
                return lista_filmes

    def listar_filmes(self):
        while True:
            lista_filmes = []
            url_geral = "https://api.themoviedb.org/3/discover/movie?" \
                        f"api_key={self.token}&" \
                        "include_adult=false&" \
                        "include_video=false&" \
                        f"page={self.numero_aleatorio()}"
            filmes = self.requisicao(url_geral)
            filmes = filmes['results']
            if not filmes:
                continue
            else:
                for movie in filmes:
                    id = movie['id']
                    lista_filmes.append(id)
                return lista_filmes

    def rodar(self, lista_filmes):
        i = True
        while i:
            try:
                count_movies = len(lista_filmes)
                random_id = random.randrange(0, count_movies + 1)
                id_filme = lista_filmes[random_id]

                url_filme = f"https://api.themoviedb.org/3/movie/{id_filme}?" \
                            f"api_key={self.token}"
                filme = self.requisicao(url_filme)
                imagem = filme['poster_path']
                id = filme['id']
                url_id = 'https://www.themoviedb.org/movie/'+str(id)
                nome = filme['original_title']
                sinopse = filme['overview']
                translator = Translator()
                sinopse = translator.translate(text=sinopse, dest='pt')
                nome_pt = translator.translate(text=nome, dest='pt')
                if not sinopse:
                    sinopse = "Não encontrado"
                votos = filme['vote_average']
                saida = f'****** SEU FILME É ******\nNome: {nome_pt.text} ({nome})\nSinopse: {sinopse.text}\nMédia de votos: {votos}'
                i = False
                return [saida, url_id, imagem]
            except Exception as e:
                print("Algo deu errado, finalizando !")


import pytest
from selenium.webdriver import FirefoxProfile
from seleniumrequests import Firefox

def pytest_addoption(parser):
    parser.addoption("--browser", default="chrome", help="Browsers : Chrome or Firefox")
    parser.addoption("--env", default="qa", help="Environments : qa or uat")

@pytest.fixture
def env(request):
    return request.config.getoption("--env")

@pytest.fixture
def browser(request):
    return request.config.getoption("--browser")

@pytest.fixture
def driver_init(request, browser):
    from selenium.webdriver import Chrome
    from selenium.webdriver.chrome.options import Options

    # if browser(request) == "chrome":
    if browser == "chrome":
        options = Options()
        options.add_argument("--incognito")
        # options.add_argument('--headless')
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        request.instance.driver = Chrome(executable_path="D:/github/automationpractice/fe/chromedriver.exe", options=options)
        request.instance.driver.maximize_window()
        request.addfinalizer(request.instance.driver.quit)

    # if browser(request) == "firefox":
    if browser == "firefox":
        fp = FirefoxProfile()
        request.instance.driver = Firefox(executable_path="D:/github/automationpractice/fe/geckodriver.exe", firefox_profile=fp)
        request.addfinalizer(request.instance.driver.quit)

@pytest.fixture
def chrome_init():
    from selenium.webdriver import Chrome
    from selenium.webdriver.chrome.options import Options
    chrome_opt = Options()
    chrome_opt.add_argument("--incognito")
    chrome_opt.add_argument("user-agent=qaauto")
    driver = Chrome(executable_path="../chromedriver.exe", options=chrome_opt)
    yield driver
    driver.quit()

@pytest.fixture
def firefox_init(request):
    from selenium.webdriver import Firefox
    from selenium.webdriver import FirefoxProfile
    fp = FirefoxProfile()
    request.instance.driver = Firefox(executable_path=r'/usr/local/bin/geckodriver', firefox_profile=fp)
    request.addfinalizer(request.instance.driver.quit)


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 23 10:50:50 2022

@author: ChrisZeThird

Special thanks to ConfusedReptile#6830 on discord for their help on the animation setup.
"""
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import matplotlib.animation as animation

""" Rules of the Game of Life """

def update(grid):

    # Copy grid since we require 8 neighbors for calculation and we go cell by cell
    newGrid = grid.copy()
    N,_ = np.shape(grid)
    for i in range(N):
        for j in range(N):
            total = grid[i%N, (j-1)%N] + grid[i%N, (j+1)%N] + grid[(i-1)%N, j%N] + grid[(i+1)%N, j%N] + grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] + grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N]

            # Applies Conway's rules
            if grid[i, j]  == 1:
                if (total < 2) or (total > 3):
                    newGrid[i, j] = 0
            else:
                if total == 3:
                    newGrid[i, j] = 1

    # Updated data
    global data
    data = newGrid
    # Updated image
    global img
    img.set_data(data)

""" Setting initial distribution """

# Size of the grid
N = 30

# Make an empty data set
data = np.zeros((N, N))

""" Figure setup """

global fig
fig = plt.figure()
global ax
ax = fig.subplots()
plt.subplots_adjust(right = 0.25)

# Draw a grid layout to see the cell more clearly
for x in range(N + 1):
    ax.axhline(x, lw=2, color='w', zorder=5)
    ax.axvline(x, lw=2, color='w', zorder=5)

# Turn off the axis labels
ax.axis('off')
plt.tight_layout(pad=4)

# Plot the initial empty distribution
global img
img = ax.imshow(data, cmap='gray', extent=[0, N, 0, N], vmin=0, vmax=1)

""" Buttons positioning """

# Reset button placement
axes_exit = plt.axes([0.755, 0.2, 0.1, 0.075])
exit_button = Button(axes_exit, 'Exit',color='lightcoral', hovercolor='firebrick')

# Reset grid button placement
axes_reset = plt.axes([0.7, 0.4, 0.1, 0.075])
reset_button = Button(axes_reset, 'Reset',color='sandybrown', hovercolor='orangered')

# Random distribution button placement
axes_random = plt.axes([0.81, 0.4, 0.1, 0.075])
random_button = Button(axes_random, 'Randomize', color='lightblue', hovercolor='darkblue')

# Start animation button placement
axes_start = plt.axes([0.7, 0.6, 0.1, 0.075])
start_button = Button(axes_start, 'Start',color='palegreen', hovercolor='lime')

# Pause animation button placement
axes_pause = plt.axes([0.81, 0.6, 0.1, 0.075])
pause_button = Button(axes_pause, 'Pause',color='navajowhite', hovercolor='gold')

""" Defining button press events """

# Allow the user to select cells to setup the initial configuration
def turn_on(event):
    gx = event.xdata # x coordinate of the mouse
    gy = event.ydata # y coordinate of the mouse

    # mouse coordinate (x,y) correspond to array indexes [i,j] with i = N-1 - y and j = x
    i = N - 1 - int(gy)
    j = int(gx)
    if data[i,j] == 0:
        data[i,j] = 1 # on click, turns cell on
    else:
        data[i,j] = 0 # on click, turns cell off if it was on already
    global img
    img.set_data(data) # update the imshow

    fig.canvas.draw_idle()

# Lets the user exit the figure
def escape(event):
    plt.close()

# On click, reset the plot with all zeros array
def reset(event):
    global data
    data = np.zeros((N,N)) # reset the array to all zeros

    global img
    img.set_data(data)
    fig.canvas.draw_idle()

# Start the animation of the game
def _update(frame):
    update(data)

def start_anim(event):
    global ani
    ani = animation.FuncAnimation(fig, _update, interval=200, save_count=50)
    # ani.save('animation3.gif')

def pause_anim(event):
    global ani
    ani.pause()

def random_distribution(event):
    global data
    data = np.random.randint(2, size=(N,N))

    global img
    img.set_data(data)
    fig.canvas.draw_idle()

""" Associate buttons with respective function """

# Connect buttons to functions
start_button.on_clicked(start_anim) # start the animation on click
pause_button.on_clicked(pause_anim)

reset_button.on_clicked(reset)
random_button.on_clicked(random_distribution)

exit_button.on_clicked(escape)

# Connect buttons to figure
fig.canvas.mpl_connect('button_press_event', turn_on) # connect cells management to figure


from __future__ import print_function

import tensorflow as tf
from tensorflow.contrib import rnn
import process
import numpy as np
from dataset_text_series import TextSeriesDataFileList
import sys
import os
import numpy as np
# Import MNIST data
#from tensorflow.examples.tutorials.mnist import input_data
#mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

class RNNTraining:
    def __init__(self,
        learning_rate = 0.0001,
        num_steps = 1000,
        batch_size = 128,
        valid_size = 500,
        display_step = 100,
        save_iter = 100,
        datafile = "",
        train_valid_file = "",
        dictfile = "",
        model_dir = "",
        restore_file = "",
        process_type = "train",
        predict_output="",
        series_len = 1000,
        num_hidden = 128,
        normalize_data = False,
        neurons = [256, 256]):
        self.learning_rate = learning_rate
        self.num_steps = num_steps
        self.batch_size = batch_size
        self.display_step = display_step
        self.save_iter = save_iter
        self.datafile = datafile
        self.dictfile = dictfile
        self.model_dir = model_dir
        self.restore_file = restore_file
        self.process_type = process_type
        self.predict_output = predict_output
        self.neurons = neurons
        self.valid_size = valid_size
        self.series_len = series_len
        self.num_hidden = num_hidden
        self.normalize_data = normalize_data

    def run(self):
        wdict = process.open_dict(self.dictfile)
        num_input = self.series_len
        timesteps = 1
        num_classes = 2

        # tf Graph input
        X = tf.placeholder("float", [None, timesteps, num_input])
        Y = tf.placeholder("float", [None, num_classes])

        # Define weights
        weights = {
            'out': tf.Variable(tf.random_normal([self.num_hidden, num_classes]))
        }
        biases = {
            'out': tf.Variable(tf.random_normal([num_classes]))
        }

        def RNN(x, weights, biases):

            # Prepare data shape to match `rnn` function requirements
            # Current data input shape: (batch_size, timesteps, n_input)
            # Required shape: 'timesteps' tensors list of shape (batch_size, n_input)

            # Unstack to get a list of 'timesteps' tensors of shape (batch_size, n_input)
            x = tf.unstack(x, timesteps, 1)

            # Define a lstm cell with tensorflow
            lstm_cell = rnn.BasicLSTMCell(self.num_hidden, forget_bias=1.0)

            # Get lstm cell output
            outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)

            # Linear activation, using rnn inner loop last output
            return tf.matmul(outputs[-1], weights['out']) + biases['out']

        logits = RNN(X, weights, biases)
        prediction = tf.nn.softmax(logits)

        # Define loss and optimizer
        loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
            logits=logits, labels=Y))
        optimizer = tf.train.GradientDescentOptimizer(learning_rate= self.learning_rate)
        train_op = optimizer.minimize(loss_op)

        # Evaluate model (with test logits, for dropout to be disabled)
        class_pred = tf.argmax(prediction, 1)
        correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

        # Initialize the variables (i.e. assign their default value)
        init = tf.global_variables_initializer()
        graph_location = self.model_dir
        if self.process_type == "train":
            print('Saving graph to: %s' % graph_location)
            merged = tf.summary.merge_all()
            train_writer = tf.summary.FileWriter(graph_location)
            train_writer.add_graph(tf.get_default_graph())

        # Start training
        with tf.Session() as sess:

            # Run the initializer
            sess.run(init)
            saver = tf.train.Saver()
            if self.restore_file != "" :
                saver.restore(sess, self.restore_file)

            if self.process_type == "train":
                tf.train.write_graph(sess.graph_def, graph_location, "graph.pbtxt", True) #proto
                textdata = TextSeriesDataFileList([self.datafile], wdict, self.batch_size, self.series_len, self.normalize_data)
                valid_x, valid_y = textdata.get_valid_set(self.valid_size)
                valid_y = tf.one_hot(valid_y, num_classes).eval()
                valid_x = valid_x.astype(np.float).reshape((valid_x.shape[0],1,self.series_len))

                for step in range(1, self.num_steps + 1):
                    batch_x, batch_y = textdata.get_next_batch() #mnist.train.next_batch(batch_size)
                    batch_y = tf.one_hot(batch_y, num_classes).eval()
                    batch_x = batch_x.astype(np.float).reshape((batch_x.shape[0],1,self.series_len))
                    #batch_x, batch_y = mnist.train.next_batch(batch_size)
                    # Reshape data to get 28 seq of 28 elements
                    #batch_x = batch_x.reshape((batch_size, timesteps, num_input))
                    # Run optimization op (backprop)
                    sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
                    if step % self.display_step == 0 or step == 1:
                        # Calculate batch loss and accuracy
                        loss, acc = sess.run([loss_op, accuracy], feed_dict={X: valid_x,
                                                                            Y: valid_y})
                        print("Step " + str(step) + ", Minibatch Loss= " + \
                            "{:.4f}".format(loss) + ", Training Accuracy= " + \
                            "{:.3f}".format(acc))

                    if step % self.save_iter == 0:
                        save_path = saver.save(sess, graph_location + "/"+"model"+str(step)+".ckpt")
                        print("Model saved in file: %s" % save_path)

                print("Optimization Finished!")

            if self.process_type == "predict" :
                textdata = TextSeriesDataFileList([self.datafile], wdict, self.batch_size, self.series_len, self.normalize_data, False)
                f = open(self.predict_output, "w")
                while True:
                    batch_x, batch_y = textdata.get_next_batch() #mnist.train.next_batch(batch_size)
                    if batch_x is None or len(batch_x) == 0:
                        break
                    batch_x = batch_x.astype(np.float).reshape((batch_x.shape[0],1,self.series_len))
                    pred_ = sess.run(class_pred, feed_dict={X: batch_x})
                    print("Classification: ", pred_)
                    for i in pred_:
                        f.write(str(i) +"\n")
                f.close()

            if self.process_type == "eval" :
                textdata = TextSeriesDataFileList([self.datafile], wdict, self.batch_size, self.series_len, self.normalize_data, False)
                result = np.zeros((num_classes, num_classes))
                while True:
                    batch_x, batch_y = textdata.get_next_batch() #mnist.train.next_batch(batch_size)
                    if batch_x is None  or len(batch_x) == 0:
                        print("Exit")
                        break
                    yplus = batch_y
                    batch_y = tf.one_hot(batch_y, num_classes).eval()
                    batch_x = batch_x.astype(np.float).reshape((batch_x.shape[0],1,self.series_len))
                    pred_, acc_ = sess.run([class_pred, accuracy], feed_dict={X: batch_x, Y: batch_y})

                    print("Classification: ", len(pred_), pred_)
                    print("Testing Accuracy:", acc_)
                    result = process.compare_result(yplus, pred_, result)
                    print(result)
                print(result)
                print("Accuracy:",(result[0][0] + result[1][1]) / (result[0][0] + result[1][1] + result[0][1] + result[1][0]))


# -*- coding: UTF-8 -*-
# @Project: Progress
# @File: Net
# @Author: Henry Ng
# @Date: 2021/12/08 15:02

import os
from tensorflow.keras.preprocessing import image

import numpy as np
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.models import Model
import tensorflow as tf
from config import Config
import sys
sys.path.append('/')
from pypeline.Validation import Validation
from pypeline.VGG import VGG
from pypeline.XCeption import XCeption
from pypeline.Resnet import Resnet
from Debug import Debug

class Net(object):
    def __init__(self, k: int, frozen_layer: int = Config.frozen_layer_vgg16, net_name: str = Config.name_vgg16):
        self.K = k
        self.image_width = 300
        self.image_height = 300
        self.nb_epoch = 100
        self.batch_size = 32
        self.frozen_layer = frozen_layer
        self.label = {}
        self.net_name = net_name

    @staticmethod
    def save_history(history, result_file):
        loss = history.history['loss']
        acc = history.history['accuracy']
        # val_loss = history.history['val_loss']
        val_acc = history.history['val_accuracy']
        nb_epoch = len(acc)

        with open(result_file, "w") as fp:
            fp.write("epoch\tloss\tacc\tval_loss\tval_acc\n")
            for i in range(nb_epoch):
                # fp.write("%d\t%f\t%f\t%f\t%f\n" % (i, loss[min(i, len(loss) - 1)], acc[min(i, len(acc) - 1)], val_loss[min(i, len(val_loss) - 1)], val_acc[min(i, len(val_acc) - 1)]))
                fp.write("%d\t%f\t%f\t%f\n" % (i, loss[min(i, len(loss) - 1)], acc[min(i, len(acc) - 1)], val_acc[min(i, len(val_acc) - 1)]))

    def create_model(self) -> tf.keras.models.Model:
        shape = (self.image_width, self.image_height, 3)
        model = Model()
        if Config.name_vgg16 == self.net_name:
            return VGG(shape=shape, frozen_layer=self.frozen_layer).model()
        elif Config.name_resnet == self.net_name:
            return Resnet(shape=shape, frozen_layer=self.frozen_layer).model()
        elif Config.name_xception == self.net_name:
            return XCeption(shape=shape, frozen_layer=self.frozen_layer).model()
        return model

    def generate_train(self, batch_size: int = 32, target_size: (int, int) = (256, 256)):
        head_data_path = Config.path(Config.slic_result_path, self.K, Config.name_train)

        train_datagen = image.ImageDataGenerator(rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
        train_generator = train_datagen.flow_from_directory(
            head_data_path,
            target_size=target_size,
            batch_size=batch_size,
            class_mode='binary')
        self.label = train_generator.class_indices  # {'fake': 0, 'real': 1}
        return train_generator

    def generate_validation(self, batch_size: int = 32, target_size: (int, int) = (256, 256)):
        head_data_path = Config.path(Config.slic_result_path, self.K, Config.name_validation)
        real_path = Config.path(head_data_path, Config.name_real)
        fake_path = Config.path(head_data_path, Config.name_fake)
        real_list = Config.get_child_folder(real_path)  # 存储真图片的文件夹 每张图片一个文件夹
        fake_list = Config.get_child_folder(fake_path)
        image_list = real_list + fake_list  # 所有图片的子文件夹
        boundary = len(real_list)
        max_len = len(image_list)

        steps = 0
        finish_flag = False
        while True:
            x_list = []  # 存储图片的数组，每次返回后清零 （len/batch, 20, 300, 300, 3）
            y_list = []
            for i in range(steps, min(steps + batch_size, max_len)):
                tmp_list = []  # （20, 300, 300, 3)
                for pic in Config.get_image_file_list(image_list[i]):  # 遍历每一个子文件夹（20）
                    tmp_list.append(np.array(image.load_img(
                        path=pic,
                        target_size=target_size
                    )))
                x_list.append(np.array(tmp_list))  # （20, 300, 300, 3)
                y_list.append(self.label[Config.name_real] if i < boundary else self.label[Config.name_fake])  # 1

            steps += batch_size
            if steps >= max_len:
                steps = 0
                finish_flag = True
            # (n, 20, 300, 300, 3)  (n, 1)
            yield np.array(x_list), np.array(y_list), finish_flag
            finish_flag = False

    def fit(self, model: tf.keras.models.Model) -> tf.keras.models.Model:
        check = Config.path_exist(Config.path(Config.checkpoint_path, str(self.K), self.net_name))
        checkpoint_path = check + '/cp-{epoch:04d}.ckpt'
        checkpoint_dir = os.path.dirname(checkpoint_path)

        cp_callback = ModelCheckpoint(
            filepath=checkpoint_path,
            monitor='accuracy',
            save_best_only=True,
            model='auto',
            save_weights_only=True,
            save_freq=1
        )
        reduce_lr = ReduceLROnPlateau(
            monitor='accuracy',
            factor=0.1,
            patience=2,
        )
        train = self.generate_train(
                batch_size=self.batch_size,
                target_size=(self.image_width, self.image_height)
            )
        validation = Validation(
                    validation_gen=self.generate_validation(
                        batch_size=self.batch_size,
                        target_size=(self.image_width, self.image_height)
                    ),
                    label=self.label,  # {'fake': 0, 'real': 1}
                    status='{} slice with {} Net'.format(self.K, self.net_name)
                )
        initial_epoch = 0
        if os.path.exists(check):
            latest = tf.train.latest_checkpoint(checkpoint_dir)
            if latest:
                model.load_weights(latest)
                tmp_len = len(checkpoint_dir) + 4  # 路径长度
                initial_epoch = int(latest[tmp_len:tmp_len + 4]) - 1
        model.fit_generator(
            generator=train,
            epochs=self.nb_epoch,
            # steps_per_epoch=nb_train_samples,
            # validation_data=validation_generator,
            # validation_steps=nb_validation_samples
            callbacks=[
                cp_callback,
                reduce_lr,
                validation
            ],
            initial_epoch=initial_epoch
        )
        return model

    def save(self, model: tf.keras.models.Model):
        model.save_weights(Config.path_exist(Config.model_path) + '{}_{}_fine-tuning.h5'.format(self.K, self.net_name))
        self.save_history(model.history, Config.path_exist(Config.history_path) + '{}_{}_history.txt'.format(self.K, self.net_name))

    def run(self):
        if not os.path.isfile(Config.path_exist(Config.model_path) + '{}_{}_fine-tuning.h5'.format(self.K, self.net_name)):
            Debug.info("Net_Processing: {} net is running with {} slices".format(self.net_name, self.K))
            model = self.create_model()
            self.save(self.fit(model))
        else:
            Debug.info('{} net exists, skipping...'.format(self.net_name))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Make a existing local or ephemeral hidden service available over TLS for non-Tor users
"""

import os
import sys
import time
import logging
import argparse
import subprocess
from multiprocessing import Process
import ssl

from flask import Flask, send_from_directory
from stem.control import Controller

handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(fmt="%(asctime)s [%(levelname)s]: %(message)s"))

logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

app = Flask(__name__)

def make_directory(path):
    if not os.path.exists(path):
        os.makedirs(path)

@app.route("/")
def index():
    return "It works"

@app.route("/<path:filename>")
def serve_challenge_response(filename):
    """Serve files from the web root directory"""
    return send_from_directory(app.config["web_root"], filename)

def request_cert(domain, web_root, data_dir, testing=False):
    """Run cerbot in background to issue a new cert"""
    cmd = [
        "certbot", "certonly", "--webroot", "-d", domain, "--register-unsafely-without-email",
        "--work-dir", data_dir, "--config-dir", data_dir, "--logs-dir", data_dir, "--agree-tos",
        "-w", web_root, "--keep",
    ]
    if testing:
        cmd.append("--test-cert")

    logger.debug("Running: {}".format(" ".join(cmd)))
    return subprocess.check_output(cmd, stderr=subprocess.STDOUT)

def create_server_thread(*args, **kwargs):
    return Process(target=app.run, kwargs=kwargs)

def server_with_letsencrypt_keys(port, cert_path):
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.load_cert_chain(os.path.join(cert_path, "fullchain.pem"),
                            os.path.join(cert_path, "privkey.pem"))
    return create_server_thread(port=port, ssl_context=context)

def start_ephemeral_onion(ports):
    """
    Start ephemeral onion address and wait for publication.

    The ports argument should be a dictionary mapping public to local ports
    """
    with Controller.from_port() as controller:
        controller.authenticate()
        return controller.create_ephemeral_hidden_service(ports, await_publication=True,
                                                          detached=True)

def parse_cmd_args():
    """Parses and returns command line arguments."""
    parser = argparse.ArgumentParser(description="%s start a Flask web server and request"
                                     "a LetsEncrypt cert for your onion address." % sys.argv[0])

    parser.add_argument("--onion_address", type=str, default=None,
                        help="Local onion service address. If not provided an ephemeral onion "
                        "service will be started.")

    parser.add_argument("--proxy-host", type=str, default="oniongate.com",
                        help="Service running the OnionGateway TLS proxy (default: '%(default)s').")

    parser.add_argument("--http-port", type=int, default=8080,
                        help="Local destination port for HTTP request to the Tor "
                        "onion service (default: '%(default)s').")

    parser.add_argument("--tls-port", "-p", type=int, default=8443,
                        help="Local destination port for TLS connections to the Tor "
                        "onion service (default: '%(default)s').")

    parser.add_argument("--letsencrypt-data-dir", "-d", type=str, default="letsencrypt_data",
                        help="Directory to store LetsEncrypt keys, logs and other data "
                        "(default: '%(default)s').")

    parser.add_argument("--web-root", "-w", type=str, default="webroot",
                        help="Directory to store LetsEncrypt challenges (default: '%(default)s').")

    parser.add_argument("--test-run", action="store_true",
                        help="Use the LetsEncrypt staging server when requesting the cert.")

    # parser.add_argument("--challenge-path", type=str, default="/.well-known/acme-challenge/",
    #                     help="The path where LetsEncrypt challenges are served "
    #                     "(default: '%(default)s').")

    return parser.parse_args()

def main():
    args = parse_cmd_args()

    make_directory(args.web_root)
    app.config["web_root"] = args.web_root

    # Start an ephemeral onion if no onion address is provided.
    if not args.onion_address:
        logger.info("Starting ephemeral onion service, this may take a minute...")
        response = start_ephemeral_onion({80: args.http_port, 443: args.tls_port})
        onion_address = response.service_id
        logger.info("Started ephemeral onion service {}".format(onion_address))

    else:
        onion_address = args.onion_address

    if onion_address.endswith(".onion"):
        onion_address = onion_address[:-6]

    # Determine public domain from onion address and proxy host
    domain = ".".join([onion_address, args.proxy_host])

    # Start a local Flask server to serve the LetsEncrypt challenge response
    # The `adhoc` ssl_context mode creates a temporary self-signed cert and private key
    logger.info("Starting Flask server with self-signed certs for domain {}".format(domain))
    server = create_server_thread(port=args.tls_port, ssl_context="adhoc")
    server.start()
    time.sleep(5)

    try:
        logger.info("Starting LetsEncrypt cert request")
        certbot_response = request_cert(domain, args.web_root, args.letsencrypt_data_dir,
                                        args.test_run)
        logger.debug("Certbot output:\n{}".format(certbot_response.decode("utf-8")))

    except subprocess.CalledProcessError as e:
        logger.warning("LetsEncrypt cert issuance failed:\n{}".format(e.output.decode("utf-8")))
        server.terminate()
        sys.exit(1)

    # Stop running Flask server and restart with the new certs
    logger.info("Successfully got a LetsEncrypt cert for https://{}".format(domain))
    server.terminate()
    server.join()

    logger.info("Starting Flask server with the LetsEncrypt certificate")
    cert_path = os.path.join(args.letsencrypt_data_dir, "live", domain)
    server = server_with_letsencrypt_keys(port=args.tls_port, cert_path=cert_path)
    server.daemon = True
    server.start()

    # Start the HTTP server for direct connections to the onion address
    app.run(port=args.http_port)

if __name__ == "__main__":
    main()


import math
import matplotlib.pyplot as plt

dataset = [
    [i * (2 / 5) for i in range(6)],
    [math.atan(i * (2 / 5)) for i in range(6)]
]

class SplineStruct:
    def __init__(self, a, b, c, d, x):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.x = x

def spline_create(x, y, n):
    splines = [SplineStruct(0, 0, 0, 0, 0) for _ in range(0, n)]
    for i in range(0, n):
        splines[i].x = x[i]
        splines[i].a = y[i]

    splines[0].c = splines[n - 1].c = 0.0

    alpha = [0.0 for _ in range(0, n - 1)]
    beta = [0.0 for _ in range(0, n - 1)]

    for i in range(1, n - 1):
        hi = x[i] - x[i - 1]
        hi1 = x[i + 1] - x[i]
        A = hi
        C = 2.0 * (hi + hi1)
        B = hi1
        F = 6.0 * ((y[i + 1] - y[i]) / hi1 - (y[i] - y[i - 1]) / hi)
        z = (A * alpha[i - 1] + C)
        alpha[i] = -B / z
        beta[i] = (F - A * beta[i - 1]) / z

    for i in range(n - 2, 0, -1):
        splines[i].c = alpha[i] * splines[i + 1].c + beta[i]

    for i in range(n - 1, 0, -1):
        hi = x[i] - x[i - 1]
        splines[i].d = (splines[i].c - splines[i - 1].c) / hi
        splines[i].b = hi * (2.0 * splines[i].c + splines[i - 1].c) / 6.0 + (y[i] - y[i - 1]) / hi
    return splines

def interpolate(splines, x):
    if not splines:
        return None

    n = len(splines)
    s = SplineStruct(0, 0, 0, 0, 0)

    if x <= splines[0].x:
        s = splines[0]
    elif x >= splines[n - 1].x:
        s = splines[n - 1]
    else:
        i = 0
        j = n - 1
        while i + 1 < j:
            k = i + (j - i) // 2
            if x <= splines[k].x:
                j = k
            else:
                i = k
        s = splines[j]

    dx = x - s.x
    return s.a + (s.b + (s.c / 2.0 + s.d * dx / 6.0) * dx) * dx

spline = spline_create(dataset[0], dataset[1], 6)

print("Сплайн в точке x = 0.75: ", interpolate(spline, 0.75))
print("Значение функции tg(x) в точке x = 0.75: ", math.atan(0.75))
print("Погрешность: {:0.9f}".format(abs(interpolate(spline, 0.75) - math.atan(0.75))))

splinesx = []
for i in dataset[0]:
    splinesx.append(interpolate(spline, i))

plt.plot(dataset[0], dataset[1])
plt.scatter(dataset[0], splinesx)
plt.show()


#!/usr/bin/env python3
# https://thingsmatic.com/2017/03/02/influxdb-and-grafana-for-sensor-time-series/
import paho.mqtt.client as mqtt
import datetime
import time
import json
from influxdb import InfluxDBClient
from config import *

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("fronius/#")

def on_message(client, userdata, msg):
    print("Received a message on topic: " + msg.topic)
    # Use utc as timestamp
    receiveTime = datetime.datetime.utcnow()

    m_decode=str(msg.payload.decode("utf-8","ignore"))
#    print ("\ndata m_decode-type ",type(m_decode))
    if m_decode != 'TimeOut':   # To avoid the connector to chrash on timeouts on the publisher
      if m_decode[0]=='[':
        message = json.loads(m_decode)
#        print("Message: ",message)
        dbclient.write_points(message)
#        print("Finished writing to InfluxDB")
      else:
        print ("No DATA!!!!!!!!!!!!!!!")   # This seems to happen on start.
    else:
      print('>>>>>>>>  TIMEOUT!!!!!  <<<<<<<<<<<')
print("start")

# Set up a client for InfluxDB
dbclient = InfluxDBClient(INFLUXDB_HOST, 8086, 'grafana', 'Mulan2010', 'fronius')
print("dbclient created")

# Initialize the MQTT client that should connect to the Mosquitto broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

# Wait for connect
connOK = False
while(connOK is False):
    try:
        client.connect(BROKER_HOST, BROKER_PORT, 60)
        connOK = True
    except Exception:
        connOK = False
    time.sleep(2)

print("mqtt connection established")

# Blocking loop to the Mosquitto broker
client.loop_forever()


import torch
import numpy as np
from typing import List

from nomeroff_net.tools.mcm import (modelhub, get_device_torch)

# download and append to path yolo repo
info = modelhub.download_repo_for_model("yolov5")
repo_path = info["repo_path"]

class Detector(object):
    """

    """
    @classmethod
    def get_classname(cls: object) -> str:
        return cls.__name__

    def __init__(self, numberplate_classes=None) -> None:
        self.model = None
        self.numberplate_classes = ["numberplate"]
        if numberplate_classes is not None:
            self.numberplate_classes = numberplate_classes
        self.device = get_device_torch()

    def load_model(self, weights: str, device: str = '') -> None:
        device = device or self.device
        model = torch.hub.load(repo_path, 'custom', path=weights, source="local")
        model.to(device)
        if device != 'cpu':  # half precision only supported on CUDA
            model.half()  # to FP16

        self.model = model
        self.device = device

    def load(self, path_to_model: str = "latest") -> None:
        if path_to_model == "latest":
            model_info = modelhub.download_model_by_name("yolov5")
            path_to_model = model_info["path"]
            self.numberplate_classes = model_info.get("classes", self.numberplate_classes)
        elif path_to_model.startswith("http"):
            model_info = modelhub.download_model_by_url(path_to_model, self.get_classname(), "numberplate_options")
            path_to_model = model_info["path"]
        elif path_to_model.startswith("modelhub://"):
            path_to_model = path_to_model.split("modelhub://")[1]
            model_info = modelhub.download_model_by_name(path_to_model)
            self.numberplate_classes = model_info.get("classes", self.numberplate_classes)
            path_to_model = model_info["path"]
        self.load_model(path_to_model)

    @torch.no_grad()
    def predict(self, imgs: List[np.ndarray], min_accuracy: float = 0.5) -> np.ndarray:
        model_outputs = self.model(imgs)
        model_outputs = [[[item["xmin"], item["ymin"], item["xmax"], item["ymax"], item["confidence"], item["class"]]
                         for item in img_item.to_dict(orient="records")
                         if item["confidence"] > min_accuracy]
                         for img_item in model_outputs.pandas().xyxy]
        return np.array(model_outputs)


import json

import torch
from tensorboardX import SummaryWriter

from trainer import train

def main():
    # Load the pipeline configuration file
    config_path = "config.json"
    with open(config_path, "r", encoding="utf8") as f:
        config = json.load(f)

    writer = SummaryWriter()
    use_gpu = config["use_gpu"] and torch.cuda.is_available()
    device = torch.device("cuda" if use_gpu else "cpu")

    train(config, writer, device)

if __name__ == "__main__":
    main()


from collections import namedtuple

import pytest

from tests.profiler import Profiler
from tests.helpers import read_from_file
from data_structures.week1_basic_data_structures.\
    II_tree_height.tree_height import main

func_to_test = main

Setup = namedtuple("Setup", ["correct_result", "params"])
setups = [
    Setup(5, dict(parents=[3, -1, 3, 1, 1, 1, 5, 6, 7])),
    Setup(3, dict(parents=[3, -1, 3, 1, 3, 3, 3, 3])),
    Setup(10**5 + 1, dict(parents=[-1, *list(range(10**5))])),
    Setup(4, dict(parents=[-1, *list(range(3))]))
    ]

@pytest.fixture(autouse=True)
def setup_functions():
    def _prepare_setup(setup):
        return {
            "correct_result": setup[0],
            "profiler_instance": Profiler(
                func=func_to_test, **setup[1])
        }

    yield [_prepare_setup(setup) for setup in setups]


import isbnlib
import csv
import pandas as pd
from ConvertToExcel import createExcelSheet,librarikaData
import xlsxwriter
from collections import defaultdict,OrderedDict
from ConvertExcelToCSV import Excel2CSV

df = pd.read_csv('ISBNNumbers.csv')
saved_column = df.ISBN
listOfBookDicts=[]
dd = defaultdict(list)
listAuthors=[]
finalFeatureDict=OrderedDict()
def CreateBookByISBN():
    try:
        i=0
        for isbn in saved_column.values.tolist():
            if type(isbn) is str:
                book = isbnlib.meta(isbn)
                listOfBookDicts.append(book)

        for d in listOfBookDicts: # you can list as many input dicts as you want here
            if d is not None:
                for key, value in d.items():
                    dd[key].append(value)

        for k,v in dd.items():
            for each in v:
                if(len(each)>1) and type(each)==list:
                    dd[k].remove(each)
                    dd[k].insert(i,';'.join(each) )
                    i=i+1
                elif type(each)==list:
                    dd[k].remove(each)
                    dd[k].insert(i,''.join(each))
                    i=i+1

        createOrderDict(dd,librarikaData)

        createExcelSheet(finalFeatureDict)
        Excel2CSV("BookListExcelColumn.xlsx","Sheet1")
    except Exception as ex:
        print(ex)
        pass
def createOrderDict(dd,librarikaData):
     for  specs in librarikaData :
            if specs not in dd.keys():
                finalFeatureDict[specs]=[]
            else:
                finalFeatureDict[specs]=dd[specs]

     for key in list(dd.keys()):
         if key=='ISBN-13':
            finalFeatureDict['ISBN13']=dd[key]
         if  key not in librarikaData :
            finalFeatureDict.pop(key, None)

CreateBookByISBN()


import errno
import os
import re
import subprocess

from error_codes import *
from errors      import error_info
from helpers     import geninfo_lookup

LR_CONFIG_PATH = "/etc/logrotate.d/omsagent-{0}"
OMSADMIN_PATH = "/etc/opt/microsoft/omsagent/conf/omsadmin.conf"

def hr2bytes(hr_size):
    if (hr_size.isdigit()):
        return int(hr_size)
    hr_digits = hr_size[:-1]
    hr_units = hr_size[-1]
    if (hr_digits.isdigit()):
        # kilobytes
        if (hr_units == 'k'):
            return int(hr_digits) * 1000
        # megabytes
        elif (hr_units == 'M'):
            return int(hr_digits) * 1000000
        # gigabytes
        elif (hr_units == 'G'):
            return int(hr_digits) * 1000000000
    # wrong formatting
    return None

def check_size_config(logrotate_configs):
    for k in list(logrotate_configs.keys()):
        # grab size limit if exists
        size_config = next((x for x in logrotate_configs[k] if x.startswith('size ')), None)
        if (size_config == None):
            continue
        size_limit = hr2bytes(size_config.split()[1])
        if (size_limit == None):
            error_info.append((k, LR_CONFIG_PATH))
            return ERR_LOGROTATE_SIZE

        # get current size of file
        try:
            size_curr = os.path.getsize(k)
            if (size_curr > size_limit):
                error_info.append((k, size_curr, size_limit, LR_CONFIG_PATH))
                return ERR_LOGROTATE
            else:
                return NO_ERROR

        # couldn't get current size of file
        except os.error as e:
            if (e.errno == errno.EACCES):
                error_info.append((k,))
                return ERR_SUDO_PERMS
            elif (e.errno == errno.ENOENT):
                if ('missingok' in logrotate_configs[k]):
                    continue
                else:
                    error_info.append(('log file', k))
                    return ERR_FILE_MISSING
            else:
                error_info.append((k, e.strerror))
                return ERR_FILE_ACCESS

def check_log_rotation():
    # update logrotate config path with wsid
    workspace_id = geninfo_lookup('WORKSPACE_ID')
    if (workspace_id == None):
        error_info.append(('Workspace ID', OMSADMIN_PATH))
        return ERR_INFO_MISSING

    global LR_CONFIG_PATH
    LR_CONFIG_PATH = LR_CONFIG_PATH.format(workspace_id)

    # check logrotate config file exists
    if (not os.path.isfile(LR_CONFIG_PATH)):
        error_info.append(('logrotate config file', LR_CONFIG_PATH))
        return ERR_FILE_MISSING

    # go through logrotate config file
    logrotate_configs = dict()
    with open(LR_CONFIG_PATH, 'r') as f:
        lr_lines = f.readlines()
        in_file = None
        for lr_line in lr_lines:
            lr_line = lr_line.rstrip('\n')

            # start of log rotation config
            lr_start = re.match("^(\S+) \{$", lr_line)
            if (lr_start != None):
                in_file = lr_start.groups()[0]
                logrotate_configs[in_file] = set()
                continue
            # log rotation config info
            elif (in_file != None):
                logrotate_configs[in_file].add(lr_line.lstrip())
                continue
            # end of log rotation config
            elif (lr_line == '}'):
                in_file = None
                continue

    # check size rotation working
    checked_size_config = check_size_config(logrotate_configs)
    if (checked_size_config != NO_ERROR):
        return checked_size_config

    return NO_ERROR


"""

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

countAndSay(1) = "1"
countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character.
Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

For example, the saying and conversion for digit string "3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.

Example 1:

Input: n = 1
Output: "1"
Explanation: This is the base case.
Example 2:

Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

Constraints:

1 <= n <= 30

"""

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """

        if n == 1:
            return 1

        # here is a self.recursion
        s = self.countAndSay(n-1)

        # so it will start when s = "1"
        # let's say when it starts from "21"

        count = 1
        i = 1
        res = ""
        # while i < 2+ 1:
        while i < len(s) + 1:
            # if i < 2
            if i < len(s) and s[i] == s[i-1]:
                count += 1
            else:
                # first loop: res += "12"
                # second loop: res = "1211"
                res += str(count) + str(s[i-1])
                count = 1
            i += 1

        return res

        # Any comments?


from pylab import figure, axes, pie, title, savefig
import matplotlib.pyplot as plt

#그래프 그리기
def draw_graph(x, y):
    plt.axhline(0, color='black', linewidth = 0.2)
    plt.plot(x, y, color = 'blue')
    plt.xlabel('x')
    plt.ylabel('Moment')
    plt.title('BMD')

def generate():
	xs = []
	bmds = []
	with open("data.txt", "r") as file:
		for line in file :
			(x, sfd, bmd) = map(float, line.strip().split(", "))
			xs.append(x)
			bmds.append(bmd)
	draw_graph(xs, bmds)
	savefig('output/bmd.pdf')

generate()


from flask import Flask, render_template, request
from pprint import pprint
import json

app = Flask(__name__)

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

@app.route("/", methods=["GET", "POST"])
def home():
	services = None

	if request.method == "POST":
		data = request.form.items()
		services = []

		for items in zip(*[iter(data)] * 3):
			infos = []
			for item in items:
				infos.append(item[1])
			services.append(infos)

	with open("config/prestations.json", "r") as f:
		data = json.load(f)

		if services != None:
			if len(services) != 0:
				export = []

				for service in services:
					export.append({
						"name" : service[1],
						"price" : service[0],
						"description" : service[2]
					})

				with open("config/export.json", "w") as outfile:
					json.dump({"services" : export}, outfile, indent=4, ensure_ascii=False)

		return render_template("pages/home.html", quotes=data)

@app.errorhandler(404)
def page_not_found(error):
	return render_template("pages/404.html"), 404

if __name__ == "__main__":
	app.run(debug=True, port=80)