import pandas as pd
import numpy as np

from dataclasses import dataclass
from datetime import datetime
from typing import List, Optional, Union

from .transactions import BankTransaction, BrokerageTransaction, CardTransaction
from .interface import CsvInterface

class BaseAccount:
    """ individual account for accounts"""

    def __init__(self, interface: CsvInterface, institution: str) -> None:
        self.interface = interface
        self.institution = institution
        self.transactions = []
        self.positions = []
        self._balance_sheet = None

    def _account_type(self) -> str:
        return self.__class__.__name__

    def _fetch(self):
        txn_lists = self.interface.parse()
        for txn_per_file in txn_lists:
            for txn in txn_per_file['transactions']:
                yield txn_per_file['file_path'], txn_per_file['file_date'], txn

    def to_dataframe(self) -> pd.DataFrame:
        return pd.DataFrame.from_records(
            txn.to_dict() for txn in self.transactions
        ).sort_values(by='date')

    def _get_transactions(self,
                         start_date=datetime(1990, 1, 1),
                         end_date=datetime.today(),
                         format='pandas'
                         ) -> List[Union[BankTransaction, BrokerageTransaction]]:

        txns =  [
            txn for txn in self.transactions
            if (txn.date >= start_date) and (txn.date <= end_date)
        ]

        if format == 'pandas':
            return pd.DataFrame.from_records(
                txn.to_dict() for txn in txns
                )
        else:
            return txns

class BankAccount(BaseAccount):
    def fetch(self, ignore_error=True):
        for file_name, file_date, txn in self._fetch():
            try:
                self.transactions.append(
                    BankTransaction(
                        txn['date'],
                        txn['merchant'],
                        txn['amount'],
                        txn['balance']
                    )
                )
            except:
                if ignore_error:
                    pass
                else:
                    raise ValueError

    def get_transactions(self, type="all", start_date="1990-01-01", end_date="2099-01-01"):
        if self._balance_sheet is None:
            self._balance_sheet = self.to_dataframe()

        if type == 'all':
            balance = self._balance_sheet.query("(date>=@start_date) & (date<=@end_date)")
        elif type == 'income':
            balance = self._balance_sheet.query("(date>=@start_date) & (date<=@end_date) & (amount>0)")
        elif type == 'spending':
            balance = self._balance_sheet.query("(date>=@start_date) & (date<=@end_date) & (amount<0)")
        elif type == 'balance':
            balance = self._balance_sheet
        else:
            raise ValueError('Unknown type!')
        return balance

    def get_spending(self, freq='M', start_date="1990-01-01", end_date="2099-01-01"):
        balance = self.get_transactions(type='spending', start_date=start_date, end_date=end_date)
        return balance.groupby(by=balance['date'].dt.to_period(freq))['amount'].sum().rename('spending')

    def get_income(self, freq='M', start_date="1990-01-01", end_date="2099-01-01"):
        balance = self.get_transactions(type='income', start_date=start_date, end_date=end_date)
        return balance.groupby(by=balance['date'].dt.to_period(freq))['amount'].sum().rename('income')

    def get_cashflow(self, freq='M', start_date="1990-01-01", end_date="2099-01-01"):
        balance = self.get_transactions(type='all', start_date=start_date, end_date=end_date)
        return balance.groupby(by=balance['date'].dt.to_period(freq))['amount'].sum().rename('cashflow')

    def get_balance(self, freq="M", start_date="1990-01-01", end_date="2099-01-01"):
        balance = self.get_transactions(type='balance', start_date=start_date, end_date=end_date)
        balance = balance.set_index('date').asof(pd.date_range(start=start_date, end=end_date, freq=freq))['balance']
        balance.index = balance.index.to_period(freq)
        return balance

class CardAccount(BaseAccount):
    def fetch(self, ignore_error=True):
        for file_name, file_date, txn in self._fetch():
            try:
                self.transactions.append(
                    CardTransaction(
                        txn['date'],
                        txn['merchant'],
                        txn['category'],
                        txn['type'],
                        txn['amount']
                    )
                )
            except:
                if ignore_error:
                    pass
                else:
                    raise ValueError

    def get_transactions(self, start_date="1990-01-01", end_date="2099-01-01", exclude_type='Payment'):
        if self._balance_sheet is None:
            self._balance_sheet = self.to_dataframe()
        balance = self._balance_sheet.query(f"(date>=@start_date) & (date<=@end_date) & (type!='{exclude_type}')")
        return balance

    def get_spending(self, freq='M', start_date="1990-01-01", end_date="2099-01-01", by_category=True):
        balance = self.get_transactions(start_date=start_date, end_date=end_date).copy()
        balance[freq] = balance['date'].dt.to_period(freq)
        if by_category:
            return balance.groupby(by=[freq, 'category'])['amount'].sum().rename('spending')
        else:
            return balance.groupby(by=freq)['amount'].sum().rename('spending')

class BrokerageAccount(BaseAccount):
    def fetch(self, ignore_error=True):
        for file_path, file_date, txn in self._fetch():
            try:
                self.transactions.append(
                    (
                        BrokerageTransaction(
                            txn.get('date', file_date),
                            txn['symbol'],
                            txn['quantity'],
                            txn['cost']
                        )
                    )
                )
            except:
                if ignore_error:
                    pass
                else:
                    raise ValueError

    def get_cost(self, start_date="1990-01-01", end_date="2099-01-01"):
        if self._balance_sheet is None:
            self._balance_sheet = self.to_dataframe()
        balance = self._balance_sheet.query("(date>=@start_date) & (date<=@end_date)")
        return np.around(balance['cost'].sum(), 2)


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 20:12:36 2019

@brief:create subgraph

@author: 冯准生
"""

import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd    #pandas,强大的数据处理能力
import random
import community
#处理数据简洁，两行代码搞定
sourse_data=pd.read_csv("netscience.txt",sep=' ')  #Dataframe
list=sourse_data.values.tolist()
#生成开始原图
G=nx.Graph()
G.add_edges_from(list)
############# 处理图 #############
train_set=[]
test_set=[]
for edge in list:
    if random.randint(0,100)<10:
        test_set.append(edge)
    else:
        train_set.append(edge)
##################################
#生成训练集图和测试集图
G_train=nx.Graph()
G_train.add_edges_from(train_set)
G_test=nx.Graph()
G_test.add_edges_from(test_set)
#图的属性输出
degree_sequence = sorted([d for n, d in G_train.degree()], reverse=True)
print("nodes:",G_train.number_of_nodes())
print("edges:",G_train.number_of_edges(),end='\n')
print("Degree sequence", degree_sequence)
#图划分
part=community.best_partition(G)
mod=community.modularity(part,G)
print(part)
print(mod)
"""
#画图
plt.figure(figsize=[90,60])  #matplotlib画布的宽和高
pos=nx.spring_layout(G)      #布局
#分别画点、边、结点标签

nx.draw_networkx_nodes(G, pos, node_size=400,node_color='g')
nx.draw_networkx_edges(G_train, pos, alpha=0.6,edge_color='g')
nx.draw_networkx_edges(G_test,pos,alpha=0.6,edge_color='r')
nx.draw_networkx_labels(G,pos,lables=G.nodes,font_color='r')

values = [part.get(node) for node in G.nodes()]
nx.draw(G, pos, node_color = values, node_size=400, with_labels=True)

plt.show()
"""


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from time import sleep

chrome_motor = 'chromedriver.exe'
driver = webdriver.Chrome(executable_path=chrome_motor)
driver.get('https://www.google.com/')
action = ActionChains(driver)

inputer = ['definicao piada', 'definicao mapa astral', 'definicao xerecard', 'definicao masturbacao']

def pesquisador(dados):
    elemento_pesquisa = '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input'
    driver.get('https://www.google.com/')
    for dado in dados:
        driver.find_element(By.XPATH, elemento_pesquisa).click()
        driver.find_element(By.XPATH, elemento_pesquisa).send_keys(dado)
        sleep(3)
        driver.find_element(By.XPATH, elemento_pesquisa).send_keys(Keys.ENTER)
        print('enter enviado')
        elementos = driver.find_elements(By.XPATH, '/html/body/div[7]/div/div[10]/div/div[2]/div[2]/div/div/div[1]/div/div/div/div/div/div/div/span/div/div/div[3]/div/div[3]/div/div/ol/li[1]/div/div/div[1]/div[2]/div/div/div/span')
        print('elementos encontrados')
        print(elementos)
        for element in elementos:
            sleep(2)
            with open('loglist.txt', 'w') as texto:
                print('texto aberto')
                texto.write(f'-' * len(element.text))
                texto.write(f'\n{element.text}')
                texto.write(f'\n')
                print('texto copiado')
                continue
        else:
            elemento_pesquisa = '/html/body/div[4]/div[2]/form/div[1]/div[1]/div[2]/div/div[2]/input'
            driver.find_element(By.XPATH, elemento_pesquisa).click()
            action.key_down(Keys.CONTROL).send_keys('A').key_up(Keys.BACK_SPACE).perform()
            driver.find_element(By.XPATH, elemento_pesquisa).click()
            continue

pesquisador(inputer)


from gi.repository import Gtk

# Load application-wide definitions
import get_iplayer_downloader

#NOTE Import module, not symbol names inside a module, to avoid circular import
import get_iplayer_downloader.ui.main_window

class HelpDialogWrapper(object):

    def __init__(self, parent):
        self.parent = parent

        self._init_dialog()

    def _init_dialog(self):
        self.dialog = Gtk.MessageDialog(self.parent, 0,
                                        Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE,
                                        "Keyboard Shortcuts", title="help - " + get_iplayer_downloader.PROGRAM_NAME)
        self.dialog.format_secondary_text(" ")
        self.dialog.set_default_response(Gtk.ResponseType.CLOSE)

        content_area = self.dialog.get_content_area()
        #content_area.set_size_request(800, 400)

        KEYBOARD_SHORTCUTS = [["Shortcut", "Command", "Description"],
                              [" ", None, None],
                              ["alt+enter", "Properties", get_iplayer_downloader.ui.main_window.TOOLTIP_VIEW_PROPERTIES],
                              ["ctrl+c", "Clear", get_iplayer_downloader.ui.main_window.TOOLTIP_TOOLS_CLEAR],
                              ["ctrl+d", "Download", get_iplayer_downloader.ui.main_window.TOOLTIP_TOOLS_DOWNLOAD],
                              ["ctrl+f", "Find", get_iplayer_downloader.ui.main_window.TOOLTIP_SEARCH_GO_TO_FIND],
                              ["ctrl+m", "Similar", get_iplayer_downloader.ui.main_window.TOOLTIP_SEARCH_LOCATE_SIMILAR],
                              ["ctrl+l", "Log", get_iplayer_downloader.ui.main_window.TOOLTIP_VIEW_LOG],
                              ["ctrl+p", "Play", get_iplayer_downloader.ui.main_window.TOOLTIP_VIEW_PLAYER],
                              ["ctrl+q", "Queue", get_iplayer_downloader.ui.main_window.TOOLTIP_OPTION_PVR_QUEUE],
                              ["ctrl+r", "Refresh", get_iplayer_downloader.ui.main_window.TOOLTIP_TOOLS_REFRESH],
                              ["ctrl+s, ctrl+shift+s", "Since", get_iplayer_downloader.ui.main_window.TOOLTIP_SEARCH_ROTATE_SINCE],
                              ["ctrl+t", "Type", get_iplayer_downloader.ui.main_window.TOOLTIP_SEARCH_ROTATE_PROG_TYPE],
                              [" ", None, None],
                              ["ctrl+1", "Type", None],
                              ["ctrl+2", "Category", None],
                              ["ctrl+3", "Channel", None],
                              #["ctrl+4, ctrl+shift+4", "Since", None],
                              ["ctrl+4, ctrl+5", "Since", None],
                              [" ", None, None],
                              ["f1", "Help", None],
                              [" ", None, None],
                              ["down-arrow", None, "Go from tool bar to episode list"],
                              ["space or enter", None, "Toggle selection in the episode list"]]

        grid = Gtk.Grid(orientation=Gtk.Orientation.VERTICAL, halign=Gtk.Align.CENTER)
        for i, keyboard_shortcut in enumerate(KEYBOARD_SHORTCUTS):
            for j, label_text in enumerate(keyboard_shortcut):
                if label_text:
                    label = Gtk.Label(label_text, valign=Gtk.Align.START, halign=Gtk.Align.START,
                                      margin_start=16, margin_end=16,
                                      hexpand_set=True, hexpand=True)
                    #label.set_padding(WIDGET_BORDER_WIDTH, 0)
                    grid.attach(label, j, i, 1, 1)
        content_area.add(grid)

        #self.dialog.show_all()
        grid.show_all()

    def run(self):
        self.dialog.run()

    def destroy(self):
        #if self.dialog is not None:
        self.dialog.destroy()


import connexion

from swagger_server.models.article import Article  # noqa: E501
from swagger_server.models.body import Body  # noqa: E501
from swagger_server import config
import sqlite3

def dict_factory(cursor, row):
    """Для удобного вывода словаря из базы"""
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

def add_article(body):  # noqa: E501
    """Создать новую статью

     # noqa: E501

    :param body: Нужно отправить текст статьи и логин пользователя который её написал
    :type body: dict | bytes

    :rtype: None
    """
    if connexion.request.is_json:
        body = Body.from_dict(connexion.request.get_json())  # noqa: E501

        conn = sqlite3.connect(config.database)
        conn.row_factory = dict_factory
        cursor = conn.cursor()

        # получаем данные для модели ордера
        author = body.author
        text = body.text

        # регистрируем ордер в базе данных
        cursor.execute(f"""INSERT INTO article('text','user_id')
                          VALUES ('{text}', '{author}')
                          """)

        cursor.execute(f"""SELECT * FROM article WHERE id = (SELECT MAX(id) FROM article)
                          """)

        article = cursor.fetchone()

        conn.commit()  # сохраняем изменения

    return article

def get_article(id):  # noqa: E501
    """Получить статью

    По id статьи можно получить более подробную информацию о ней # noqa: E501

    :param id: Уникальный id статьи
    :type id: int

    :rtype: Article
    """
    return 'do some magic!'


# 3) Построить график (можно использовать __excel__) функции
# __f(n) = T1 / Tn__,
# где __Tn__ - время работы функции
# перемножения матриц с использованием __n__ подпроцессов.
import csv
import multiprocessing as mp
import time
from math import ceil
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter

def minor_tick(x, pos):
    if not x % 1.0:
        return ""
    return "%.2f" % x

def time_decorator(func):
    def wrapper(*args, **kwargs):
        if __name__ == "__main__":
            start_time = time.time()
        res = func(*args, **kwargs)
        if __name__ == "__main__":
            res2 = time.time() - start_time
            print(res2)
        return res, res2
    return wrapper

def work(coord):
    global matrix_1
    global matrix_2
    global m
    result = 0
    for i in range(m):
        result += matrix_1[coord[0]][i] * matrix_2[i][coord[1]]
    return result

matrix_1 = []
matrix_2 = []
with open("matrix_1.csv", encoding='utf-8') as r_file:
    file_reader = csv.reader(r_file, delimiter = ";")
    for row in file_reader:
        matrix_1.append(list(map(int, row)))
with open("matrix_2.csv", encoding='utf-8') as l_file:
    file_reader = csv.reader(l_file, delimiter = ";")
    for row in file_reader:
        matrix_2.append(list(map(int, row)))
# matrix_1 = [[1, 2], [2, 1]]
# matrix_2 = [[9], [1]]
n = len(matrix_1)
m = len(matrix_1[0])
p = len(matrix_2[0])

@time_decorator
def main_function(proc):
    global n, p
    if __name__ == "__main__":
        pond = mp.Pool(proc)
        res = pond.map(work, ((i, j) for i in range(n) for j in range(p)))
        for i in range(n):
            print([res[i*p + j] for j in range(p)])

def print_cool(time_list):
    np.random.seed(19680801)

    X = [time_list[i][0] for i in range(len(time_list))]
    Y1 = [time_list[i][1] for i in range(len(time_list))]
    print(X, Y1)

    fig = plt.figure(figsize=(16, 16))
    ax = fig.add_subplot(1, 1, 1, aspect=1)

    ax.xaxis.set_major_locator(MultipleLocator(1.000))
    ax.yaxis.set_major_locator(MultipleLocator(1.000))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))
    ax.yaxis.set_minor_formatter(FuncFormatter(minor_tick))

    ax.set_xlim(0, len(X)+1)
    ax.set_ylim(ceil(min(Y1))-1, ceil(max(Y1)))

    ax.tick_params(which='major', width=1.0)
    ax.tick_params(which='major', length=10)
    ax.tick_params(which='minor', width=1.0, labelsize=10)
    ax.tick_params(which='minor', length=5, labelsize=10, labelcolor='0.25')

    ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)

    ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10)

    ax.set_title("Скорость от количества задействованных проессов", fontsize=20, verticalalignment='bottom')
    ax.set_xlabel("n")
    ax.set_ylabel("T_1 / T_n")

    plt.show()

if __name__ == "__main__":
    time_list=[]
    main_function(mp.cpu_count() - 1)
    for i in range(mp.cpu_count() - 1):
        time_list.append([i+1, main_function(i+1)[1]])
    for i in range(len(time_list)):
        time_list[-i-1][1] = time_list[0][1] / time_list[-i-1][1]
    print(time_list)
    print_cool(time_list)


import discord
from discord.ext import commands
from discord import ActivityType, Activity
import asyncio
import os
from datetime import datetime
import gvars

bot = commands.Bot(command_prefix=["mm!    ","mm!   ","mm!  ","mm! ","mm!","micro ","Micro "] ,description="Micro Bot")
bot.launch_time = datetime.utcnow()

@bot.command()
async def uptime(ctx):
    '''Micro's uptime'''
    delta_uptime = datetime.utcnow() - bot.launch_time
    hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
    minutes, seconds = divmod(remainder, 60)
    days, hours = divmod(hours, 24)
    await ctx.send(f"Micro is online since {days}d, {hours}h, {minutes}m, {seconds}s")

@bot.command()
async def hello(ctx):
    '''says hello to you'''
    await ctx.send("Hello {0}".format(ctx.message.author.mention))

@bot.command()
async def ping(ctx):
    '''Pong! check whether Micro is breathing or not'''
    resp = await ctx.send('Pong! Loading...')
    diff = resp.created_at - ctx.message.created_at
    await resp.edit(content=f':champagne: Cheers! That took {1000 * diff.total_seconds():.1f}ms.')

@bot.command()
async def serverinfo(ctx):
    '''current server info '''
    em=discord.Embed(colour=discord.Colour(0xf1c40f))
    em.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url)
    em.set_thumbnail(url=ctx.guild.icon_url)
    em.add_field(name="**Owner**", value=ctx.guild.owner.name)
    em.add_field(name="**Server Created on**", value=ctx.guild.created_at)
    em.add_field(name="**Member Count**", value=ctx.guild.member_count)
    em.add_field(name="**Server Emojis**", value=str(len(ctx.guild.emojis)))
    em.add_field(name="**You joined on **",value=str(ctx.author.joined_at))
    roles=ctx.guild.roles
    rolestr=''
    for role in roles:
        rolestr += role.name+','
    em.add_field(name="**Roles**" ,value=rolestr)
    await ctx.send(embed=em)

@bot.command()
async def emojis(ctx):
    """Display the current server's local emojis"""
    emojistr=''
    emojis=ctx.guild.emojis
    if len(emojis) == 0 :
        emojistr='No Emojis available'
    else:
        for emote in emojis:
            emojistr +=' '+str(emote)+' '
    await ctx.send(emojistr)
@bot.command()
async def feedback(ctx,*,message : str):
    '''Give your feedback on Micro'''
    tchannel=bot.get_guild(446649726578720778).get_channel(450297549006307329)
    server=ctx.guild.name
    channel=ctx.channel
    em_title='{0} on "{1}->{2}" said:'.format(ctx.author,server,channel)
    em=discord.Embed(title=em_title, description=message,colour=discord.Colour(0x992d22))
    await tchannel.send(embed=em)
@bot.command()
async def rolelist(ctx,*,role_name):
    '''Displays the members with specified role.
    To avoid unnecessary mentions, this command only takes name, mention wouldn`t work.'''
    for role in ctx.guild.roles:
        if role.name.lower() == role_name.lower() :
            member_list = role.members
            em=discord.Embed(title='Member(s) with {0} role in this server'.format(role.name))
            em.colour = role.colour
            emoji= ':diamond_shape_with_a_dot_inside:'
            members=''
            for member in member_list:
                members += emoji+member.name+'\n'
            if len(members)> 2048:
                await ctx.send("Sorry! {0} names can`t fit here".format(str(len(member_list))))
                return
            em.description = members
            em.set_footer(text="Requested by {0}".format(ctx.author.name))
            await ctx.send(embed=em)
            return
    msg=await ctx.send("Enter a valid role.\n Make sure that you enter **name** of the role but don`t mention it.")
    await asyncio.sleep(4)
    msg.delete()
    return

##################################################################

@bot.event
async def on_ready():
    extensions=('REPL','Admin','Events')
    for i in extensions:
        try:
            bot.load_extension(f"cogs.{i}")
        except Exception as e:
            await bot.get_channel(449863094290612224).send(f"Error Loading {i}\n ```py {str(e)}```")
    print("I'm ready!")
    await bot.get_channel(449863094290612224).send(f"Bot reawakened at {datetime.now(): %B %d, %Y at %H:%M:%S GMT}")

messages = [
    (discord.ActivityType.watching, 'Doraemon |mm!help'),
    (discord.ActivityType.watching, 'Phineas and Ferb|mm!help'),
    (discord.ActivityType.watching, 'Timon and Pumba |mm!help'),
    (discord.ActivityType.listening, 'mm!help'),
    (discord.ActivityType.playing, 'with Uday...|mm!help'),

]

async def presence_task():
    index = -1
    while True:
        await bot.wait_until_ready()
        index = (index + 1) % len(messages)
        next_type, next_msg = messages[index]
        await bot.change_presence(activity=discord.Activity(name=next_msg, type=next_type))
        await asyncio.sleep(10)

bot.loop.create_task(presence_task())

bot.run(os.getenv('TOKEN'))


import argparse

__author__ = 'Ahmed G. Ali'

def fix_idf(file_path):
    f = open(file_path, 'r')
    lines = f.readlines()
    f.close()
    write_lines = []
    for i in range(len(lines)):
        line = lines[i].strip().split('\t')
        write_line = []
        if line[0] == 'Term Source Name' or line[0] == '"Term Source Name"':
            line.append('ArrayExpress')
        if line[0] == 'Term Source File' or line[0] == '"Term Source File"':
            line.append('http://www.ebi.ac.uk/arrayexpress/')

        for part in line:
            if part.endswith('"'):
                part = part.replace('"', '')
            write_line.append(part)

        write_lines.append('\t'.join(write_line))
    f = open(file_path, 'w')
    f.write('\n'.join(write_lines))
    f.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Fixes Export IDF.')
    parser.add_argument('file_path', metavar='PATH_TO_FILE.idf', type=str,
                        help='''The path to the IDF file''')
    args = parser.parse_args()
    fix_idf(args.file_path)


#!/bin/python3

import math
import os
import random
import re
import sys

from collections import defaultdict

#
# Complete the 'mostActive' function below.
#
# The function is expected to return a STRING_ARRAY.
# The function accepts STRING_ARRAY customers as parameter.
#

def mostActive(customers):
    # Write your code here
    default_dict = defaultdict(int)
    for customer in customers:
        default_dict[customer] +=1
    return sorted([c for c, count in default_dict.items() if count / len(customers)>= 0.05])

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    customers_count = int(input().strip())

    customers = []

    for _ in range(customers_count):
        customers_item = input()
        customers.append(customers_item)

    result = mostActive(customers)

    fptr.write('\n'.join(result))
    fptr.write('\n')

    fptr.close()

Skills Certification Test/Problem Solving (Basic)/Active Traders.py


import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as shc
import pandas as pd
import librerias.decoratos as dc
import numpy as np
from sklearn.cluster import AgglomerativeClustering

@dc.timing
def group_data(linkage, num_clusters):
    cluster = AgglomerativeClustering(n_clusters=num_clusters, affinity='euclidean', linkage=linkage)
    data = pd.read_csv('clusteringFiles/data_all_books_scaled.csv', index_col=0)
    cluster.fit_predict(data)
    print(cluster.labels_)
    plt.figure(figsize=(13, 9))
    plt.title(f"Data clustered with {linkage} ")
    plt.scatter(data.iloc[:,0], data.iloc[:,1], c=cluster.labels_, cmap='rainbow')
    plt.savefig(f'clustered-{linkage}.png', dpi=1200)
    print(f'clustered-{linkage}.png created')

# Numero de cluster obtenidos al dibujar una horizontal en los dendograms
group_data('ward', 10)
group_data('complete', 10)
group_data('average', 10)


#! python3
# -*- coding:utf-8 -*-
from google.cloud.vision import types
from google.cloud import vision
import sys
import io
import os
import re
import cv2
import MeCab

# Imports the Google Cloud client library

def detect_label(path, debug=True):
    # check args that image path exists
    if path == None:
        print("please input target image file on first argument.")
        sys.exit(0)

    # Instantiates a client
    client = vision.ImageAnnotatorClient()

    # The name of the image file to annotate
    file_name = os.path.abspath(path)

    # Loads the image into memory
    with io.open(file_name, 'rb') as image_file:
        content = image_file.read()

    image = types.Image(content=content)

    # Performs label detection on the image file
    response = client.label_detection(image=image)
    labels = response.label_annotations

    if debug == True:
        print('Labels:')
        for label in labels:
            print(label.description)

    if response.error.message:
        raise Exception(
            '{}\nFor more info on error messages, check: '
            'https://cloud.google.com/apis/design/errors'.format(
                response.error.message))

    return labels

def detect_text(path, debug=True):
    # check args that image path exists
    if path == None:
        print("please input target image file on first argument.")
        sys.exit(0)

    """Detects text in the file."""
    from google.cloud import vision
    import io
    client = vision.ImageAnnotatorClient()

    with io.open(path, 'rb') as image_file:
        content = image_file.read()

    image = vision.types.Image(content=content)

    response = client.text_detection(image=image)
    texts = response.text_annotations

    if debug == True:
        print('Texts:')
        for text in texts:
            print('\n"{}"'.format(text.description))

            vertices = (['({},{})'.format(vertex.x, vertex.y)
                         for vertex in text.bounding_poly.vertices])

            print('bounds: {}'.format(','.join(vertices)))

    if response.error.message:
        raise Exception(
            '{}\nFor more info on error messages, check: '
            'https://cloud.google.com/apis/design/errors'.format(
                response.error.message))

    return texts

def detect_document(path, debug=True):
    """Detects document features in an image."""
    from google.cloud import vision
    import io
    client = vision.ImageAnnotatorClient()

    with io.open(path, 'rb') as image_file:
        content = image_file.read()

    image = vision.types.Image(content=content)

    response = client.document_text_detection(image=image)

    if debug == True:
        for page in response.full_text_annotation.pages:
            for block in page.blocks:
                print('\nBlock confidence: {}\n'.format(block.confidence))

                for paragraph in block.paragraphs:
                    print('Paragraph confidence: {}'.format(
                        paragraph.confidence))

                    for word in paragraph.words:
                        word_text = ''.join([
                            symbol.text for symbol in word.symbols
                        ])
                        print('Word text: {} (confidence: {})'.format(
                            word_text, word.confidence))

                        for symbol in word.symbols:
                            print('\tSymbol: {} (confidence: {})'.format(
                                symbol.text, symbol.confidence))

def localize_objects(path, debug=True):
    """Localize objects in the local image.
    Args:
    path: The path to the local file.
    """
    from google.cloud import vision
    client = vision.ImageAnnotatorClient()

    with open(path, 'rb') as image_file:
        content = image_file.read()
    image = vision.types.Image(content=content)

    objects = client.object_localization(
        image=image).localized_object_annotations

    if debug == True:
        print('Number of objects found: {}'.format(len(objects)))
        for object_ in objects:
            print('\n{} (confidence: {})'.format(object_.name, object_.score))
            print('Normalized bounding polygon vertices: ')
            for vertex in object_.bounding_poly.normalized_vertices:
                print(' - ({}, {})'.format(vertex.x, vertex.y))

    return objects

func_list = {}
func_list.setdefault('label', detect_label)
func_list.setdefault('text', detect_text)
func_list.setdefault('document', detect_document)
func_list.setdefault('objects', localize_objects)

if __name__ == '__main__':
    runFunc = func_list.get(sys.argv[2], None)
    if runFunc != None:
        # draw bounds
        img = cv2.imread(sys.argv[1])

        if sys.argv[2] == 'label':
            labels = runFunc(sys.argv[1])
            for label in labels:
                print("description:" + label.description + "  score:" + str(label.score))

        if sys.argv[2] == 'text':
            texts = runFunc(sys.argv[1], bool(int(sys.argv[4])))

            tagger = MeCab.Tagger()
            tagger.parse('')
            searches = None
            if len(sys.argv) > 4:
                searches = [re.compile(sys.argv[3])]
                node = tagger.parseToNode(sys.argv[3])
                while node:
                    if "BOS" not in node.feature and "EOS" not in node.feature and \
                       node.feature.split(",")[0] not in ["助詞", "助動詞"]:
                        searches.append(re.compile(node.surface))
                    node = node.next

            for i, text in enumerate(texts):
                # restricting draw text include search words.
                if searches is not None:
                    hasWords = False
                    for b in searches:
                        if b.search(text.description) is not None:
                            hasWords = True
                            break
                    if hasWords == False:
                        if i == 0:
                            break
                        else:
                            continue

                # draw rect
                vertices = []
                [vertices.append((verticex.x, verticex.y)) for verticex in text.bounding_poly.vertices]
                cv2.rectangle(img, (vertices[0][0], vertices[0][1]), (vertices[2][0], vertices[2][1]), (0, 255, 0), 6)

            fname = os.path.dirname(os.path.abspath(sys.argv[1])) + os.path.sep + "after_bounds.jpg"
            cv2.imwrite(fname, img)

        if sys.argv[2] == 'objects':
            objects = runFunc(sys.argv[1], bool(int(sys.argv[3])))

            for object_ in objects:
                # draw rect
                vertices = []
                [vertices.append((vertex.x, vertex.y)) for vertex in object_.bounding_poly.normalized_vertices]
                x = int(vertices[0][0] * img.shape[1])
                y = int(vertices[0][1] * img.shape[0])
                width = int(vertices[2][0] * img.shape[1])
                height = int(vertices[2][1] * img.shape[1])

                cv2.rectangle(img, (x, y), (width, height), (0, 255, 0), 6)

            fname = os.path.dirname(os.path.abspath(sys.argv[1])) + os.path.sep + "after_bounds.jpg"
            cv2.imwrite(fname, img)


import streamlit as st
import pickle
import pandas as pd

movies_dict=pickle.load(open('movies_dict.pkl','rb'))
moviesnew=pd.DataFrame(movies_dict)
similarity=pickle.load(open('similarity.pkl','rb'))

def recommend(movie):
    movie_index=moviesnew[moviesnew['title']==movie].index[0]
    distances=similarity[movie_index]
    movie_list=sorted(list(enumerate(distances)),reverse=True,key=lambda x:x[1])[1:6]

    recommended_movies=[]
    for i in movie_list:
        recommended_movies.append(moviesnew['title'][i[0]])
    return recommended_movies

st.title('Movie Recommender System')

movie_name=st.selectbox("Select Movie",moviesnew['title'].values)

if(st.button('Recommend')):
    recommendations=recommend(movie_name)
    for i in recommendations:
        st.write(i)


# coding: utf-8
import xlwings as xw
app = xw.App(visible=True, add_book=False)
xb = app.books.open(r'C:\Users\leshuangjiang\Desktop\配件.xlsx')
app.screen_updating = False
sht = xb.sheets[0].active
sht = xb.sheets[0]
sht.activate
sht = xb.sheets[1].activate
sht
app.screen_updating = True
lst = sht.range('a1:f25').value
sht = xb.sheets[1]
lst = sht.range('a1:f25').value
lst
for i in lst:
    print(i)

for i in lst:
    for y in i:
        print(y)

get_ipython().magic('save -f d:\\excel.py 1-17')


import csv
from matplotlib import pyplot as plt

filename = 'csv/sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    highs = []
    for row in reader:
        high = int(row[1])
        highs.append(high)

    print(highs)

x_value = [i for i in range(1, 32)]

fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(x_value, highs, c='red')

plt.title("Daily high temperatures, July 2014", fontsize=24)
plt.xlabel('', fontsize=16)
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)

plt.show()


import time

import driver as driver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
#from selenium.webdriver.support import expected_conditions as EC
list = []
list2 = []
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://rahulshettyacademy.com/seleniumPractise/")
driver.find_element_by_css_selector("input.search-keyword").send_keys("ber")
driver.implicitly_wait(10)
time.sleep(4)
count = len(driver.find_elements_by_xpath("//div[@class='products']/div"))
assert count == 3
buttons =driver.find_elements_by_xpath("//div[@class='product-action']/button")

for button in buttons:
    list.append(button.find_element_by_xpath("parent::div/parent::div/h4").text)
    button.click()

print(list)

driver.find_element_by_css_selector("img[alt='Cart']").click()
driver.find_element_by_xpath("//button[text()='PROCEED TO CHECKOUT']").click()

veggies = driver.find_elements_by_css_selector("p.product-name")
print(len(veggies))
for veg in veggies :
    list2.append(veg.text)

print(list2)

assert list[0] == list2[0]
assert list[1] == list2[1]
assert list[2] == list2[2]

originalAmount = driver.find_element_by_css_selector(".discountAmt").text
driver.find_element_by_class_name("promoCode").send_keys("rahulshettyacademy")
driver.find_element_by_css_selector(".promoBtn").click()
print(driver.find_element_by_css_selector("span.promoInfo").text)
discountAmount = driver.find_element_by_css_selector(".discountAmt").text

assert float(discountAmount) < float(originalAmount)

amounts = driver.find_elements_by_xpath("//tr/td[5]/p")
sum1 = 0
for amount in amounts:
    sum1 = sum1 + int(amount.text)

print(sum1)

totalAmount = int(driver.find_element_by_class_name("totAmt").text)

assert sum1 == totalAmount


'''
'''
import dash_bootstrap_components as dbc
import logging
from dash import dcc, html
from dotanalysis_control.dta import (get_available_players, get_dota_player, get_dota_team,
                                     heroes_dict)

################ Logging information
logger = logging.getLogger(__name__)

style_center = {
    "width":"1700px",
    "max-width":"1700px",
    "display":"inline-block",
    "margin-left":"auto",
    "margin-right":"auto"
}
style_update = {
    "width":"700px",
    "max-width":"700px",
    "display":"inline-block",
    "margin-left":"auto",
    "margin-right":"auto"
}
style_logo = {
    "width":"100px",
    "max-width":"100px",
}
style_register_box = {
    "width":"800px",
    "margin-left":"auto",
    "margin-right":"auto"
}

def players_table():
    t_header = ["Player", "Last Updated"]
    players_table_header = [
        html.Thead(html.Tr([html.Th(h) for h in t_header]))
    ]
    rows = []
    dota_players = get_available_players()
    if dota_players == ["EMPTY"]:
        return []
    for player in dota_players:
        dota_player = get_dota_player(player)
        rows.append(html.Tr([
            html.Td(dcc.Link(player, href="/players/"+player)),
            html.Td(dota_player.data_info["Last Updated"]),
        ]))
    players_table_body = [html.Tbody(rows)]
    players_table = dbc.Table(players_table_header + players_table_body,
        bordered=True,
        dark=True,
        hover=True,
        responsive=True,
        striped=True,)
    return players_table

def get_players_data(dota_team):
    dota_team_obj = get_dota_team(dota_team)

    most_played_heroes_list = dota_team_obj.get_most_played_heroes_df(heroes_dict)
    player_data = [[], [], [], [], []]
    for idx, player in enumerate(dota_team):
        player_data[idx].append(dcc.Markdown(f"#### {player}"))

    for idx, mph_df in enumerate(most_played_heroes_list):
        most_played_heroes_tables = dbc.Table.from_dataframe(mph_df,
                                                             dark=True,
                                                             striped=True,
                                                             bordered=True,
                                                             hover=True)
        player_data[idx].append(most_played_heroes_tables)

    return player_data

def get_team_info(dota_team):
    dota_team_obj = get_dota_team(dota_team)
    wins = sum([result["win"] for result in dota_team_obj.matches])
    losses = len(dota_team_obj.matches) - wins
    team_info = ["Wins: "+str(wins), html.Br(), "Losses: "+str(losses), html.Br()]
    radiant_winrate, radiant_matches = dota_team_obj.get_team_radiant_winrate_matches()
    radiant_winrate = "{:10.2f}".format(radiant_winrate)
    dire_winrate, dire_matches = dota_team_obj.get_team_dire_winrate_matches()
    dire_winrate = "{:10.2f}".format(dire_winrate)
    team_info.append("Radiant Winrate: "+str(radiant_winrate)+"%, Matches: "+str(radiant_matches))
    team_info.append(html.Br())
    team_info.append("Dire Winrate: "+str(dire_winrate)+"%, Matches: "+str(dire_matches))
    team_info.append(html.Br())
    return team_info

def get_monthly_matches_data(dota_team, date):
    monthly_matches_data = []
    if dota_team:
        dota_team_obj = get_dota_team(dota_team)
        team_matches_month_df = dota_team_obj.get_monthly_matches_df(date)

        if not team_matches_month_df.empty:
            month = date.strftime("%B")
            monthly_matches_data.append(
                dcc.Markdown(f"#### Monthly matches - {month} {str(date.year)}")
            )
            team_matches_month_table = dbc.Table.from_dataframe(
                                    team_matches_month_df,
                                    dark=True, striped=True, bordered=True, hover=True)

            # thead = team_matches_month_table.children[0].children
            tbody = team_matches_month_table.children[1].children

            for tr_row in tbody:
                td = tr_row.children[0].children
                match_id_link = "https://www.opendota.com/matches/"+str(td)
                tr_row.children[0].children = dcc.Link(match_id_link, href=match_id_link)

            monthly_matches_data.append(team_matches_month_table)
            return monthly_matches_data

    return []


from typing import Tuple
import numpy as np
import pandas as pd

from aeromaps.models.base import AeromapsModel

class ERF(AeromapsModel):
    def __init__(self, name="effective_radiative_forcing", *args, **kwargs):
        super().__init__(name, *args, **kwargs)

    def compute(
        self,
        soot_emissions: pd.Series = pd.Series(dtype="float64"),
        co2_emissions: pd.Series = pd.Series(dtype="float64"),
        h2o_emissions: pd.Series = pd.Series(dtype="float64"),
        nox_emissions: pd.Series = pd.Series(dtype="float64"),
        sulfur_emissions: pd.Series = pd.Series(dtype="float64"),
        direct_co2_erf_2018_reference: float = 0.0,
        kerosene_emission_factor_2019: float = 0.0,
        erf_coefficient_soot: float = 0.0,
        erf_coefficient_co2: float = 0.0,
        erf_coefficient_contrails: float = 0.0,
        erf_coefficient_h2o: float = 0.0,
        erf_coefficient_nox: float = 0.0,
        erf_coefficient_sulfur: float = 0.0,
        total_aircraft_distance: pd.Series = pd.Series(dtype="float64"),
        operations_contrails_gain: pd.Series = pd.Series(dtype="float64"),
    ) -> Tuple[
        pd.Series,
        pd.Series,
        pd.Series,
        pd.Series,
        pd.Series,
        pd.Series,
        pd.Series,
        pd.Series,
        pd.Series,
    ]:
        """ERF calculation for the different climate impacts of aviation."""

        # CO2
        self.df["annual_co2_erf"] = co2_emissions * erf_coefficient_co2 / 1000

        # To improve
        reference_year = 2018
        co2_erf_2018_reference = (
            direct_co2_erf_2018_reference * kerosene_emission_factor_2019 / 73.2
        )

        self.df.loc[reference_year, "co2_erf"] = co2_erf_2018_reference
        for k in range(self.historic_start_year, reference_year):
            self.df.loc[self.historic_start_year + reference_year - 1 - k, "co2_erf"] = (
                self.df.loc[self.historic_start_year + reference_year - k, "co2_erf"]
                - self.df.loc[self.historic_start_year + reference_year - 1 - k, "annual_co2_erf"]
            )
        for k in range(reference_year + 1, self.end_year + 1):
            self.df.loc[k, "co2_erf"] = (
                self.df.loc[k - 1, "co2_erf"] + self.df.loc[k, "annual_co2_erf"]
            )

        annual_co2_erf = self.df["annual_co2_erf"]
        co2_erf = self.df["co2_erf"]

        # Contrails
        self.df["contrails_erf"] = (
            total_aircraft_distance
            * erf_coefficient_contrails
            * (1 - operations_contrails_gain / 100)
        )
        contrails_erf = self.df["contrails_erf"]

        # Others
        self.df["soot_erf"] = soot_emissions * erf_coefficient_soot
        self.df["h2o_erf"] = h2o_emissions * erf_coefficient_h2o
        self.df["nox_erf"] = nox_emissions * erf_coefficient_nox
        self.df["sulfur_erf"] = sulfur_emissions * erf_coefficient_sulfur
        soot_erf = self.df["soot_erf"]
        h2o_erf = self.df["h2o_erf"]
        nox_erf = self.df["nox_erf"]
        sulfur_erf = self.df["sulfur_erf"]

        # Total
        self.df["aerosol_erf"] = soot_erf + sulfur_erf
        self.df["total_erf"] = co2_erf + contrails_erf + h2o_erf + nox_erf + soot_erf + sulfur_erf
        aerosol_erf = self.df["aerosol_erf"]
        total_erf = self.df["total_erf"]

        return (
            annual_co2_erf,
            co2_erf,
            contrails_erf,
            soot_erf,
            h2o_erf,
            nox_erf,
            sulfur_erf,
            aerosol_erf,
            total_erf,
        )

class DetailedERF(AeromapsModel):
    def __init__(self, name="detailed_erf", *args, **kwargs):
        super().__init__(name, *args, **kwargs)

    def compute(
        self,
        co2_erf: pd.Series = pd.Series(dtype="float64"),
        contrails_erf: pd.Series = pd.Series(dtype="float64"),
        h2o_erf: pd.Series = pd.Series(dtype="float64"),
        nox_erf: pd.Series = pd.Series(dtype="float64"),
    ) -> Tuple[pd.Series, pd.Series, pd.Series]:
        """ERF calculation for helping plot display."""

        self.df["co2_h2o_erf"] = co2_erf + h2o_erf
        self.df["co2_h2o_nox_erf"] = co2_erf + h2o_erf + nox_erf
        self.df["co2_h2o_nox_contrails_erf"] = co2_erf + h2o_erf + nox_erf + contrails_erf

        co2_h2o_erf = self.df["co2_h2o_erf"]
        co2_h2o_nox_erf = self.df["co2_h2o_nox_erf"]
        co2_h2o_nox_contrails_erf = self.df["co2_h2o_nox_contrails_erf"]

        return co2_h2o_erf, co2_h2o_nox_erf, co2_h2o_nox_contrails_erf


# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 18:36:02 2019

@author: Shantanu
"""

import tensorflow as tf
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

import matplotlib.pyplot as plt

image_index = 7777
print(y_train[image_index])
plt.imshow(x_train[image_index], cmap='Greys')

x_train.shape

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])

from tensorflow import keras
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D

model = keras.Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layers
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10,activation=tf.nn.softmax))

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=10)

model.save("mnist.h5")

model2 = keras.models.load_model("mnist.h5")

model2.evaluate(x_test, y_test)

import matplotlib.pyplot as plt
from PIL import Image
import PIL.ImageOps
import numpy as np

img=Image.open('digit.png').convert('L')
img.thumbnail((28, 28), Image.ANTIALIAS)
img1 = PIL.ImageOps.invert(img)
img2 =  np.array(img1)

plt.imshow(img2, cmap=plt.cm.binary, interpolation="nearest")
plt.show()

print(model2.predict_classes(img2.reshape(1, 28, 28, 1))[0])


from django.db import models
from LMS.leavemgt.models import Leave_req
import uuid
from account.models import CustomUser
from django.urls import reverse

# Create your models here.
class Approved(models.Model):
    emp_id = models.ForeignKey('Employee', on_delete=models.CASCADE)
    dept_name = models.ForeignKey('Dept', on_delete=models.CASCADE)
    hod_comment = models.TextField(verbose_name='hod comment')
    hr_comment = models.TextField(verbose_name='hr comment')
    hod_approved = models.BooleanField(default=False)
    hr_approved = models.BooleanField(default=False)

class Emp_leave_hist(models.Model):
    leave_req = models.ForeignKey(Leave_req, on_delete=models.CASCADE)
    start_date = models.DateField()
    end_date = models.DateField()
    active = models.BooleanField(default=False)

class Employee(models.Model):
    user = models.OneToOneField(CustomUser,on_delete=models.CASCADE)
    emp_id = models.CharField(verbose_name='employee id', max_length=10, unique=True, default=uuid.uuid4, editable=False)
    staff_id = models.CharField(max_length=10, unique=True)
    f_name = models.CharField(verbose_name='First name', max_length=30)
    l_name = models.CharField(verbose_name='Last name', max_length=30)
    SEX = (
        ('M', 'Male'),
        ('F', 'Female')
    )
    sex = models.CharField(max_length=1, choices=SEX)
    dept_unit = models.CharField(verbose_name='Department Unit', max_length=30)
    home_addr = models.CharField(verbose_name='Home address', max_length=100)
    designation = models.CharField(verbose_name='Designation', max_length=30)
    phone_num = models.IntegerField(verbose_name='Phone Number',default='0')
    email_addr = models.CharField(verbose_name='Email address', max_length=100)

    def create_profile(self,created,**kwargs):
        if created:
            employee = Employee.objects.create(**kwargs)

    def get_absolute_url(self):
        return reverse(employee.views.EmployeeDetailView, args=[(self.id)])

    def __str__(self):
        return '%s %s' % (self.f_name, self.staff_id)

class Dept(models.Model):
    dept_name = models.CharField(verbose_name='Department name', max_length=100)

class Hod(models.Model):
    hod_name = models.CharField(verbose_name='Hod Name', unique=True, max_length=50)
    dept_name = models.ForeignKey('Dept', on_delete=models.CASCADE)

class Superuser(models.Model):
    name = models.CharField(verbose_name='Super_user', max_length=50)
    dept = models.CharField(verbose_name='HR Department', max_length=20)

    def __str__(self):
        return '%s' % (self.name)


import py, pytest
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../src')

from floor import Floor

def test_initialization():
    try:
        floor = Floor()
    except:
        pytest.fail("Failed to initialize Lift object")

floor = Floor(4, (5,5,5))

def test_floor_queue():
    assert floor.queue == (5,5,5)

def test_floor_number():
    assert floor.number == 4


from typing import Tuple

from ground.hints import Scalar
from hypothesis import given
from hypothesis.strategies import DataObject

from hypothesis_geometry.hints import Strategy
from hypothesis_geometry.planar import boxes
from tests import strategies
from tests.utils import (ScalarsLimitsType,
                         box_has_coordinates_in_range,
                         box_has_coordinates_types,
                         is_box)

@given(strategies.scalars_strategies)
def test_basic(coordinates: Strategy[Scalar]) -> None:
    result = boxes(coordinates)

    assert isinstance(result, Strategy)

@given(strategies.data,
       strategies.scalars_strategy_with_limit_and_type_pairs)
def test_properties(data: DataObject,
                    coordinates_limits_type_pair: Tuple[ScalarsLimitsType,
                                                        ScalarsLimitsType]
                    ) -> None:
    (x_coordinates_limits_type,
     y_coordinates_limits_type) = coordinates_limits_type_pair
    ((x_coordinates, (min_x_value, max_x_value)),
     x_type) = x_coordinates_limits_type
    ((y_coordinates, (min_y_value, max_y_value)),
     y_type) = y_coordinates_limits_type

    strategy = boxes(x_coordinates, y_coordinates)

    result = data.draw(strategy)

    assert is_box(result)
    assert box_has_coordinates_types(result,
                                     x_type=x_type,
                                     y_type=y_type)
    assert box_has_coordinates_in_range(result,
                                        min_x_value=min_x_value,
                                        max_x_value=max_x_value,
                                        min_y_value=min_y_value,
                                        max_y_value=max_y_value)
    assert result.min_x < result.max_x
    assert result.min_y < result.max_y

@given(strategies.data,
       strategies.scalars_strategies_with_limits_and_types)
def test_same_coordinates(data: DataObject,
                          coordinates_limits_type: ScalarsLimitsType
                          ) -> None:
    (coordinates, (min_value, max_value)), type_ = coordinates_limits_type

    strategy = boxes(coordinates)

    result = data.draw(strategy)

    assert is_box(result)
    assert box_has_coordinates_types(result,
                                     x_type=type_,
                                     y_type=type_)
    assert box_has_coordinates_in_range(result,
                                        min_x_value=min_value,
                                        max_x_value=max_value,
                                        min_y_value=min_value,
                                        max_y_value=max_value)
    assert result.min_x < result.max_x
    assert result.min_y < result.max_y


# (c) Nelen & Schuurmans.  GPL licensed, see LICENSE.rst.
# -*- coding: utf-8 -*-

"""Helper functions for opening tiles of the AHN and LGN."""

# Python 3 is coming
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division

import os

import gdal

from . import utils
from .conf import settings

def get_tile_filename(datadir, ahn_name):
    """Return bytestring path to the needed tile. datadir is
    'data_ahn' or 'data_lgn'."""
    return os.path.join(
        settings.LIZARD_DAMAGE_DATA_ROOT, datadir, ahn_name[1:4],
        ahn_name + '.tif').encode('utf8')

def get_tile_dataset(datadir, ahn_name):
    return gdal.Open(get_tile_filename(datadir, ahn_name))

def get_ahn_dataset(ahn_name, logger=None):
    ds = get_tile_dataset('data_ahn', ahn_name)
    if ds is None and logger:
        logger.warning('No height data for {}'.format(ahn_name))
    return ds

def get_lgn_dataset(ahn_name, logger=None):
    ds = get_tile_dataset('data_lgn', ahn_name)
    if ds is None and logger:
        logger.warning('No landuse data for {}'.format(ahn_name))
    return ds

def get_datasets_for_tile(
    ahn_name,
    alternative_heights_dataset=None,
    alternative_landuse_dataset=None,
        logger=None):
    """
    Return datasets (waterlevel, height, landuse).

    Input:
        ahn_name: ahn subunit name

        If an alternative_heights_dataset or
        alternative_landuse_dataset is given, use that. But first we
        do retrieve the standard ahn/lgn datasets, and reproject the
        alternatives to have the same dimensions.

    Output:
        ds_ahn, ds_lgn, orig_ds_lgn

        Of these, the first two should be used for computations (they
        may contain data from custom uploaded height/landuse
        datasets), the last is guaranteed to be from the normal
        AHN/LGN (to be used for caching purposes, don't put custom
        stuff in the tile cache).

        This is less relevant for the height dataset as the cache slug
        for that has min and max value in it, so different datasets
        are likely (but not certain) to miss each other in the cache.
    """
    ds_ahn = get_ahn_dataset(ahn_name)
    orig_ds_lgn = ds_lgn = get_lgn_dataset(ahn_name)

    if ds_lgn and alternative_landuse_dataset is not None:
        logger.info('Reproject alternative dataset to same dimensions as LGN')
        ds_lgn = utils.reproject(alternative_landuse_dataset, ds_lgn)

    if ds_ahn and alternative_heights_dataset is not None:
        logger.info('Reproject alternative dataset to same dimensions as AHN')
        ds_ahn = utils.reproject(alternative_heights_dataset, ds_ahn)

    return ds_ahn, ds_lgn, orig_ds_lgn


import cv2
import numpy as np

MAX_FEATURES = 10000
GOOD_MATCH_PERCENT = 0.45
BLURCAR = 585

class TemplateTracker():
    def __init__(self, template, bbox):
        self.template = template
        self.bbox = bbox
        self.orb = cv2.ORB_create(int(MAX_FEATURES/10))
        self.template_keypoints, self.template_desc = self.orb.detectAndCompute(template, None)
        print(self.template_keypoints)
        self.matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMINGLUT)

    def warped_bbox(self, h):
        points = [(self.bbox[0],self.bbox[1]), (self.bbox[0]+self.bbox[2],self.bbox[1]), (self.bbox[0]+self.bbox[2],self.bbox[1]+self.bbox[3]), (self.bbox[0],self.bbox[1]+self.bbox[3])]

        for i, p in enumerate(points):
            px = (h[0][0]*p[0] + h[0][1]*p[1] + h[0][2]) / ((h[2][0]*p[0] + h[2][1]*p[1] + h[2][2]))
            py = (h[1][0]*p[0] + h[1][1]*p[1] + h[1][2]) / ((h[2][0]*p[0] + h[2][1]*p[1] + h[2][2]))
            points[i] = (round(px),round(py))

        return points

    def get_best_template_match_bbox(self, frame):
        orb = cv2.ORB_create(MAX_FEATURES)
        keypoints, descriptors = orb.detectAndCompute(frame, None)

        matches = self.matcher.match(self.template_desc, descriptors, None)
        matches.sort(key=lambda x: x.distance, reverse=False)

        good_matches = matches[:int(len(matches) * GOOD_MATCH_PERCENT)]
        print(len(good_matches))

        points1 = np.zeros((len(good_matches), 2), dtype=np.float32)
        points2 = np.zeros((len(good_matches), 2), dtype=np.float32)

        shift = np.array([self.bbox[0],self.bbox[1]])
        for i, match in enumerate(good_matches):
            points1[i, :] = self.template_keypoints[match.queryIdx].pt + np.array([self.bbox[0],self.bbox[1]])
            points2[i, :] = keypoints[match.trainIdx].pt

        h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)

        # imMatches = cv2.drawMatches(self.template, self.template_keypoints, frame, keypoints, good_matches, None)
        # cv2.imshow("match", imMatches)
        # cv2.waitKey(2000)

        return self.warped_bbox(h)

bboxes = []
with open('A2/BlurCar2/groundtruth_rect.txt') as gt:
    all_lines = gt.readlines()
    for line in all_lines:
        nums = line.split('\t')
        bboxes.append((int(nums[0]), int(nums[1]), int(nums[2]), int(nums[3])))

first_frame = cv2.imread('A2/BlurCar2/img/0001.jpg')
first_frame = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY)
tt = TemplateTracker(first_frame[bboxes[0][1]:bboxes[0][1]+bboxes[0][3],bboxes[0][0]:bboxes[0][0]+bboxes[0][2]], bboxes[0])

for i in range(2, BLURCAR+1):
    print(i)
    frame = cv2.imread('A2/BlurCar2/img/' + str(i).zfill(4) + '.jpg')
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    best_match = tt.get_best_template_match_bbox(frame)
    print(best_match)
    print(bboxes[i-1])
    frame = cv2.line(frame, best_match[0], best_match[1], (255,0,0), 2)
    frame = cv2.line(frame, best_match[1], best_match[2], (255,0,0), 2)
    frame = cv2.line(frame, best_match[2], best_match[3], (255,0,0), 2)
    frame = cv2.line(frame, best_match[3], best_match[0], (255,0,0), 2)
    cv2.imwrite('A2/BlurCar2/output/' + str(i).zfill(4) + '.jpg', frame)


from gpiozero import RGBLED
from signal import pause
import time

led = RGBLED(red=22, green=10, blue=9)

led.red = 1

start_time = time.time()
step_time = 0.1

def timer(x):
    previous_time = start_time - 0.1
    current_time = time.time()
    if current_time > previous_time:
        previous_time = previous_time + step_time
        return x - 0.01
    return x

while True:
    if led.red > 0.02:
        led.red = timer(led.red)
        print(led.red)
    else:
        led.red = 1
        print("reset led")


"""
Validates that the viewing frustum lies inside the [-1, 1]^3 cube
"""

import argparse
from src.training.rendering import validate_frustum

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-r', '--radius', type=float, help='Camera distance from the origin')
    parser.add_argument('-n', '--near', type=float, help='Position of the near plane')
    parser.add_argument('-f', '--far', type=float, help='Position of the far plane')
    parser.add_argument('--fov', type=float, help='Field of view (in degrees)')
    parser.add_argument('--scale', type=float, default=1.0, help='The additional scaling of the [-1, 1] cube (if any)')
    parser.add_argument('--step', type=float, default=1e-2, help='Step size when sampling the points')
    parser.add_argument('--device', type=str, default='cpu', help='`cpu` or `cuda` device?')
    args = parser.parse_args()

    is_valid = validate_frustum(
        radius=args.radius,
        near=args.near,
        far=args.far,
        fov=args.fov,
        scale=args.scale,
        step=args.step,
        device=args.device,
        verbose=True,
    )
    print('Valid?', is_valid)


"""laymei URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path, include
from django.views.generic import TemplateView
# 이 아래부분 미디어 파일 디벨롭모드에서 쓰기 위해 필요
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    re_path(r'^dayoverall/', include('dayoverall.urls')),
    re_path(r'^daywork/', include('daywork.urls')),
    re_path(r'^daylove/', include('daylove.urls')),
    re_path(r'^daymoney/', include('daymoney.urls')),
    re_path(r'^dayrelationships/', include('dayrelationships.urls')),
    re_path(r'^dayemotion/', include('dayemotion.urls')),
    re_path(r'^post/', include('post.urls')),
    re_path(r'^celeb/', include('celebrity.urls')),
    re_path(r'^', include('website.urls')),
]

# 이 아래 부분 미디어 파일 디벨롭 모드에서 쓰기 위해 필요

if settings.DEBUG:
    import debug_toolbar

    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += [
        re_path(r'^__debug__/', include(debug_toolbar.urls)),
        re_path(r'^admin/', admin.site.urls),
    ]
'''
    url(r'^accounts/', include('dayoverall.urls', namespace='accounts')),
    url(r'base_test/$', TemplateView.as_view(template_name='base_test.html')),
'''


from django.http import HttpResponse
from django.shortcuts import render
from gestionPedidos.models import Articulos
from django.core.mail import send_mail
from django.conf import settings
from gestionPedidos.forms import FormularioContacto

# Create your views here.

def busqueda_productos(request):
    return render(request, "busqueda_productos.html")

def buscar(request):
    if request.GET["prd"]:
        #mensaje = "Artículo buscado: %r" %request.GET["prd"]
        producto = request.GET["prd"]

        if len(producto) > 20:
            mensaje = "texto de búsqueda demasiado largo"
        else:
            articulos = Articulos.objects.filter(nombre__icontains = producto)
            return render(request, "resultados_busqueda.html", {"articulos":articulos, "query": producto})
    else:
        mensaje = "mete algo capullo"
    return HttpResponse("<h1>" + mensaje + "</h1>")

def contacto(request):
    # version anterior a usar API Forms
    # if request.method == "POST":
    #     subject = request.POST["asunto"]
    #     message = request.POST["mensaje"] + " " + request.POST["email"]
    #     email_from = settings.EMAIL_HOST_USER
    #     recipient_list = ["direccion@destino.com"]
    #     send_mail(subject, message, email_from, recipient_list)
    #     return render(request, "gracias.html")
    # return render(request, "contacto.html")

    # version de API Forms
    if request.method == "POST":
        miFormulario = FormularioContacto(request.POST)
        if miFormulario.is_valid():
            infForm = miFormulario.cleaned_data
            send_mail(infForm['asunto'], infForm['mensaje'], infForm.get('email',''), ['direccion@administrador.es'])
            return render(request, "gracias.html")
    else:
        miFormulario = FormularioContacto() #esto es para que al cargar el formulario antes de meter los datos lo cargue vacío

    #ahora hay que mandarle construir el formulario en html (ya casi lo hace él sólo con print)
    return render(request, "formulario_contacto.html", {"form": miFormulario})


import os

import numpy as np
import torch as th

from . import utils

class ShapenetDataset(th.utils.data.Dataset):
    def __init__(self, root, canvas_size,  val=False, jitter=True):
        self.jitter = jitter
        self.root = root
        self.canvas_size = canvas_size
        self.files = sorted([f for f in os.listdir(self.root) if os.path.isdir(os.path.join(self.root, f))])
        np.random.shuffle(self.files)
        cutoff = int(0.9*len(self.files))
        if val:
            self.files = self.files[cutoff:]
        else:
            self.files = self.files[:cutoff]

    def __repr__(self):
        return "ShapenetDataset | {} entries".format(len(self))

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

    def __getitem__(self, idx):
        fname = self.files[idx]
        distance_fields = th.from_numpy(np.load(os.path.join(self.root, fname, 'df.npy')).astype(np.float32)) ** 2
        alignment_fields = th.from_numpy(np.load(os.path.join(self.root, fname, 'af.npy')).astype(np.float32))

        if self.jitter:
            x, y, z = np.random.randint(distance_fields.size(0)-self.canvas_size+1, size=3)
            distance_fields = distance_fields[x:x+self.canvas_size,y:y+self.canvas_size,z:z+self.canvas_size]
            alignment_fields = \
                alignment_fields[x:x+self.canvas_size,y:y+self.canvas_size,z:z+self.canvas_size]
        else:
            distance_fields = distance_fields[5:-5,5:-5,5:-5]
            alignment_fields = alignment_fields[5:-5,5:-5,5:-5]

        occupancy_fields = utils.compute_occupancy_fields(distance_fields)

        return {
            'fname': fname,
            'distance_fields': distance_fields,
            'alignment_fields': alignment_fields,
            'occupancy_fields': occupancy_fields,
        }


import json
from time import sleep
from typing import List

from mbientlab.metawear import MetaWear, libmetawear, FnVoid_VoidP_DataP, parse_value
from mbientlab.warble import WarbleException

from ENVIRONMENT_VARIABLES import DEBUG_STREAM_ACC, BATCH_STORE
from models.Point import Point
from services import logger
from services.logger import start_debug, end_debug
# from services.reset import reset
from storage.influxdb_store import DatabaseStore

class State:
    strage: DatabaseStore
    def __init__(self, device, strage):
        self.device = device
        self.samples = 0
        self.callback = FnVoid_VoidP_DataP(self.data_handler)
        self.data = []
        self.strage = strage

    def data_handler(self, ctx, data):
        raw_point = parse_value(data)
        point = Point(raw_point.x, raw_point.y, raw_point.z, self.device.address)
        if BATCH_STORE:
            self.data.append(point)
        else:
            self.strage.store([point])
        self.samples += 1

class StreamAcc:
    strage: DatabaseStore
    device_list: List[State]

    def __init__(self, strage: DatabaseStore):

        self.strage = strage

    def init_device(self, device):
        print(f"Configuring device: {device.device.address}")
        # reset(device.device)
        libmetawear.mbl_mw_settings_set_connection_parameters(device.device.board, 7.5, 7.5, 0, 6000)
        sleep(1.5)

        libmetawear.mbl_mw_acc_set_odr(device.device.board, 25.0)
        libmetawear.mbl_mw_acc_set_range(device.device.board, 8.0)
        libmetawear.mbl_mw_acc_write_acceleration_config(device.device.board)

    def init_multidevices(self, devices_mac_list):
        self.device_list = []
        for device_mac in devices_mac_list:
            device = MetaWear(device_mac)
            try:
                device.connect()
            except WarbleException:
                logger.error(f"connect error: {device_mac}")
            print("Connected to " + device.address)
            state_device = State(device, self.strage)
            self.device_list.append(state_device)
            self.init_device(state_device)
            sleep(5.5)

    def start_test(self, time_tests):
        for device in self.device_list:
            logger.info_log(f"Start device: {device.device.address}")
            signal = libmetawear.mbl_mw_acc_get_acceleration_data_signal(device.device.board)
            libmetawear.mbl_mw_datasignal_subscribe(signal, None, device.callback)

            libmetawear.mbl_mw_acc_enable_acceleration_sampling(device.device.board)
            libmetawear.mbl_mw_acc_start(device.device.board)
            sleep(5.0)

        sleep(time_tests)

        for device in self.device_list:
            libmetawear.mbl_mw_acc_stop(device.device.board)
            libmetawear.mbl_mw_acc_disable_acceleration_sampling(device.device.board)

            signal = libmetawear.mbl_mw_acc_get_acceleration_data_signal(device.device.board)
            libmetawear.mbl_mw_datasignal_unsubscribe(signal)
            libmetawear.mbl_mw_debug_disconnect(device.device.board)
            logger.info_log(f"Stop device: {device.device.address}")

        if DEBUG_STREAM_ACC:
            start_debug()
            for s in self.device_list:
                if BATCH_STORE:
                    self.strage.store(s.data)
                print("%s -> %d" % (s.device.address, s.samples))
            end_debug()


import requests
from pystyle import Colorate, Colors, Center
from os import system
from time import sleep

boucle1 = True

header_final = """
─╔╗─────────╔╗────     ───────╔╗─╔╗───────╔╗─
╔╝║╔═╗╔╗─╔═╗║╚╗╔═╗     ╔╦╦╗╔═╗║╚╗║╚╗╔═╗╔═╗║╠╗
║╬║║╩╣║╚╗║╩╣║╔╣║╩╣     ║║║║║╩╣║╬║║║║║╬║║╬║║═╣
╚═╝╚═╝╚═╝╚═╝╚═╝╚═╝     ╚══╝╚═╝╚═╝╚╩╝╚═╝╚═╝╚╩╝

"""

while boucle1:
    system('clear')
    print(Colorate.Diagonal(Colors.purple_to_blue, Center.XCenter(header_final)))
    print(Colorate.Horizontal(Colors.purple_to_blue, "[?] ลิ้งเว็บฮุค↓"))
    webhook_url = input("")
    if webhook_url.startswith("https://discord.com/api/webhooks/"):
        try:
            system('clear')
            requests.delete(webhook_url.rstrip())
            print(Colorate.Diagonal(Colors.purple_to_blue, Center.XCenter(header_final)))
            print(Colorate.Horizontal(Colors.purple_to_blue, "ลบแล้วจ้า"))
            sleep(5)
        except:
            system('clear')
            print(Colorate.Diagonal(Colors.purple_to_blue, Center.XCenter(header_final)))
            print(Colorate.Horizontal(Colors.yellow_to_red, "[!] ผิดพลาด"))
            sleep(2)
    else:
            system('clear')
            print(Colorate.Diagonal(Colors.purple_to_blue, Center.XCenter(header_final)))
            print(Colorate.Horizontal(Colors.yellow_to_red, "[!] ผิดพลาด"))
            sleep(2)


from functools import reduce
from itertools import cycle
from operator import mul

import numpy as np

from utils import array_to_string, read_input, str_to_array

OPPOSITE_HDG = {"n": "s", "e": "w", "s": "n", "w": "e"}

class Tile:
    def __init__(self, id, array):
        self.id = id
        self.arr = array

    def __repr__(self):
        return f"Tile {self.id}\n{array_to_string(self.arr)}"

    def rotate(self):
        self.arr = np.rot90(self.arr)

    def flip(self):
        self.arr = np.flip(self.arr, axis=1)

    def get_edges(self):
        return {
            "n": "".join(map(chr, self.arr[0, :])),
            "s": "".join(map(chr, self.arr[-1, :])),
            "w": "".join(map(chr, self.arr[:, 0])),
            "e": "".join(map(chr, self.arr[:, -1])),
        }

def create_tiles_dict(raw_in):
    tiles_dict = {}

    for line in raw_in:
        a, b = line.split("\n", maxsplit=1)
        a = int(a[5:-1])
        b = str_to_array(b.split())
        tiles_dict[a] = Tile(a, b)

    return tiles_dict

def find_corner_tiles(tiles_dict):
    # Corner pieces have exactly 2 sides that have a match in other tiles
    tiles = list(tiles_dict.values())
    corner_pieces = []
    for t in tiles:
        n_matches = 0
        for e in t.get_edges().values():
            edges_to_test = set.union(
                *(set(t2.get_edges().values()) for t2 in tiles if (t != t2))
            )
            edges_to_test_flipped = set(x[::-1] for x in edges_to_test)
            if (e in edges_to_test) or (e in edges_to_test_flipped):
                n_matches += 1
        if n_matches == 2:
            corner_pieces.append(t.id)
    return corner_pieces

def _find_match(tile, hdg, unsolved_tiles, tiles_dict):
    opp_hdg = OPPOSITE_HDG[hdg]
    for tile_id in unsolved_tiles:
        other = tiles_dict[tile_id]
        for _ in range(2):
            for _ in range(4):
                if tile.get_edges()[hdg] == other.get_edges()[opp_hdg]:
                    return other
                other.rotate()
            other.flip()

def piece_together(tiles_dict, corner_tiles):
    # Resources
    LOC_OFFSET = {
        "n": np.array([-1, 0]),
        "e": np.array([0, 1]),
        "s": np.array([1, 0]),
        "w": np.array([0, -1]),
    }
    hdg_iter = cycle(["e", "s", "w", "n"])

    # Init
    unsolved_tiles = set(tiles_dict)
    solution = {}
    loc = np.array([0, 0])
    hdg = next(hdg_iter)
    tile = tiles_dict[corner_tiles[0]]
    unsolved_tiles.remove(tile.id)

    # Loop and build the solution dict
    while unsolved_tiles:
        solution[tuple(loc)] = tile
        match = _find_match(tile, hdg, unsolved_tiles, tiles_dict)
        if match:
            tile = match
            unsolved_tiles.remove(tile.id)
            loc += LOC_OFFSET[hdg]

        if not match:
            hdg = next(hdg_iter)
    solution[tuple(loc)] = tile

    # Transform solution dict into a big tile
    row_idxes, col_idxes = zip(*solution.keys())
    row_min, row_max = min(row_idxes), max(row_idxes)
    col_min, col_max = min(col_idxes), max(col_idxes)
    rows = []
    for col in range(col_min, col_max + 1):
        rows.append(
            np.concatenate(
                [
                    solution[(row, col)].arr[1:-1, 1:-1]
                    for row in range(row_min, row_max + 1)
                ],
                axis=0,
            )
        )
    final = np.concatenate(rows, axis=1)

    return Tile("FINALE", final)

def _calculate_roughness(array):
    monster_ascii = [
        "                  # ",
        "#    ##    ##    ###",
        " #  #  #  #  #  #   ",
    ]
    monster_filter = (str_to_array(monster_ascii) == ord("#")).astype(int)
    m_len_y, m_len_x = monster_filter.shape

    hashes = (array == ord("#")).astype(int)

    solution = np.zeros_like(hashes)
    max_y, max_x = solution.shape
    for row in range(0, max_y - m_len_y + 1):
        for col in range(0, max_x - m_len_x + 1):
            original = hashes[row : row + m_len_y, col : col + m_len_x]
            filtered = original * monster_filter
            if np.array_equal(filtered, monster_filter):
                solution[row : row + m_len_y, col : col + m_len_x] += filtered

    roughness = np.sum((solution == 0) * hashes)
    return roughness

def determine_roughness(tiles_dict, corner_tiles):
    final = piece_together(tiles_dict, corner_tiles)

    roughnesses = []
    for _ in range(2):
        final.flip()
        for _ in range(4):
            final.rotate()
            r = _calculate_roughness(final.arr)
            roughnesses.append(r)

    return min(roughnesses)

if __name__ == "__main__":
    raw_in = read_input("inputs/day_20.txt", split_delimiter="\n\n")
    tiles_dict = create_tiles_dict(raw_in)

    corner_tiles = find_corner_tiles(tiles_dict)
    roughness = determine_roughness(tiles_dict, corner_tiles)

    print(f"Part 1 answer: {reduce(mul, corner_tiles)}")
    print(f"Part 2 answer: {roughness}")


from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from manager.managers import PersonManager

class Person(AbstractBaseUser):
    objects = PersonManager()

    MAN = 0
    WOMAN = 1

    # 北海道
    HOKKAIDO = 0
    # 東北
    TOHOKU = 10
    AOMORI = 11
    AKITA = 12
    IWATE = 13
    YAMAGATA = 14
    MIYAGI = 15
    HUKUSHIMA = 16
    # 関東
    KANTO = 20
    TOKYO = 21
    CHIBA = 22
    KANAGAWA = 23
    SAITAMA = 24
    TOCHIGI = 25
    IBARAGI = 26
    GUNMA = 27
    # 北陸・中部
    HOKURIKU = 30
    NIIGATA = 31
    NAGANO = 32
    YAMANASHI = 33
    TOYAMA = 34
    ISHIKAWA = 35
    HUKUI = 36
    GIHU = 37
    SHIZUOKA = 38
    AICHI = 39
    # 関西
    KANSAI = 40
    MIE = 41
    SHIGA = 42
    KYOTO = 43
    OSAKA = 44
    HYOGO = 45
    NARA = 46
    WAKAYAMA = 47
    # 中国
    CHUGOKU = 50
    OKAYAMA = 51
    HIROSHIMA = 52
    TOTTORI = 53
    SHIMANE = 54
    YAMAGUCHI = 55
    # 四国
    SHIKOKU = 60
    KAGAWA = 61
    TOKUSHIMA = 62
    EHIME = 63
    KOCHI = 64
    # 九州・沖縄
    KYUSHU = 70
    HUKUOKA = 71
    OITA = 72
    SAGA = 73
    NAGASAKI = 74
    KUMAMOTO = 75
    MIYAZAKI = 76
    KAGOSHIMA = 77
    OKINAWA = 78

    # アカウント名
    identifier = models.CharField(max_length=64, unique=True, blank=False)
    # 名前
    name = models.CharField(max_length=128)
    # メールアドレス
    email = models.EmailField()
    # 誕生日
    birthday = models.DateTimeField()
    # 性別
    sex = models.IntegerField(editable=False)
    # 出身地
    address_from = models.IntegerField()
    # 現住所
    current_address = models.IntegerField()

    # ログイン機能の実装に必要
    is_active = models.BooleanField(default=True)

    # hijack機能の実装に必要
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = 'identifier'

class Manager(models.Model):

    # 部署の定数
    DEP_ACCOUNTING = 0  # 経理
    DEP_SALES = 5  # 営業
    DEP_PRODUCTION = 10  # 製造
    DEP_DEVELOPMENT = 15  # 開発
    DEP_HR = 20  # 人事
    DEP_FIN = 25  # 財務
    DEP_AFFAIRS = 30  # 総務
    DEP_PLANNING = 35  # 企画
    DEP_BUSINESS = 40  # 業務
    DEP_DISTR = 45  # 流通
    DEP_IS = 50  # 情報システム

    # 人
    person = models.ForeignKey('Person')
    # 部署
    department = models.IntegerField()
    # 着任時期
    joined_at = models.DateTimeField()
    # やめた時期
    quited_at = models.DateTimeField(null=True, blank=True)

class Worker(models.Model):

    # 人
    person = models.ForeignKey('Person')
    # 着任時期
    joined_at = models.DateTimeField()
    # やめた時期
    quited_at = models.DateTimeField(null=True, blank=True)
    # 担当上司
    manager = models.ForeignKey('Manager')


import requests
import sys
import os
import time
from lxml import html

sys.path.append(os.path.join(os.path.dirname(__file__), '../..', 'key'))
import ENV

GET_URL_XPATH = """//span[@class="indexed-biz-name"]/*/@href"""

def get_headers(user_agent):
    headers = {
        "User-Agent": user_agent
    }
    return headers

def scrape(url, user_agent):
    urls = []

    try:
        for x in range(0, 21, 10):
            postfix = "&start=" + str(x)
            newurl = url + postfix
            print(">>> crawling: " + newurl)
            session_request = requests.session()
            response = session_request.get(newurl, headers=get_headers(user_agent))

            tree = html.fromstring(response.content)
            vals = tree.xpath(GET_URL_XPATH)
            if not vals:
                break

            urls.extend(vals)
            time.sleep(ENV.SLEEP_CRAWLING_IN_SECONDS)
    except Exception as err:
        print("<<< ERROR: " + str(err))

    urls = list(set(urls))

    return list(map(lambda x:x.split("?")[0], urls))


#!/usr/bin/python3

import datetime as dt
from io import StringIO
import hashlib
import re

def hash_value(val: str) -> str:
    return hashlib.md5(val.encode()).hexdigest()

def add_param(html_param: str, v: str) -> str:
    return html_param[0: len(html_param) - 1] + f"?v={v}" + "\""

if __name__ == "__main__":

    cb_value = hash_value(dt.datetime.now().isoformat())
    js_patt = re.compile(r'src=\"\/?js\/[a-z_]+\.js\"')
    css_patt = re.compile(r'href=\"\/?css\/[a-z_]+\.css\"')

    index_files = [
        "build/final-approach-2/index.html",
    ]

    for index_file in index_files:
        with open(index_file) as rh:
            html = rh.read()

        outText = StringIO()

        for line in html.split("\n"):
            js_m = js_patt.search(line)
            css_m = css_patt.search(line)
            if js_m:
                html_param = js_m.group()
                new_line = line.replace(html_param, add_param(html_param, cb_value))
                outText.write(new_line + "\n")
                print("adding version param to line " + line.replace(' ', ''))
            elif css_m:
                html_param = css_m.group()
                new_line = line.replace(html_param, add_param(html_param, cb_value))
                outText.write(new_line + "\n")
                print("adding version param to line " + line.replace(' ', ''))
            else:
                outText.write(line + "\n")

        with open(index_file, "w") as wh:
            wh.write(outText.getvalue())