import json
import json
import os
import shutil
import time
from io import BytesIO
from pprint import pprint

import PyPDF2
import pandas as pd
from PIL import Image, ImageDraw, ImageFont
from PyPDF2 import PdfReader, PdfWriter
from PyQt5.QtWidgets import QMessageBox
from loguru import logger
from peewee import fn
from reportlab.lib.pagesizes import A4, A3, landscape
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas

from created_one_pdf import created_pdfs
from db import Article, Orders, Statistic, files_base_postgresql, orders_base_postgresql, remove_russian_letters, \
    push_number
from utils import ProgressBar, df_in_xlsx

pdfmetrics.registerFont(TTFont('Arial', 'arial.ttf'))
Image.MAX_IMAGE_PIXELS = None

def add_header_and_footer_to_pdf(pdf_file, footer_text, A3_flag):
    """Надписи сверху пдф файла и снизу"""
    # Open the original PDF and extract its content
    with open(pdf_file, "rb") as pdf:
        pdf_content = BytesIO(pdf.read())
    if A3_flag:
        with open('Настройки\\Параметры значков_A3.json', 'r') as file:
            config = json.load(file)
        pagesize = A3
        size = 8
    else:
        with open('Настройки\\Параметры значков.json', 'r') as file:
            config = json.load(file)
        pagesize = A4
        size = 10

    x2, y2 = config['pdf down']['x'], config['pdf down']['y']
    # Load pages from the original PDF and add header and footer to each page
    reader = PdfReader(pdf_content)
    writer = PdfWriter()

    for page_num in range(len(reader.pages)):
        try:
            page = reader.pages[page_num]

            # Create a canvas for the page
            packet = BytesIO()
            can = canvas.Canvas(packet, pagesize=pagesize)

            # Add the header text (centered) to the canvas
            can.setFont("Arial", size=size)
            if A3_flag:
                can.drawCentredString(x2, y2, f"{footer_text} - Стр.{page_num + 1}")
            else:
                can.drawCentredString(x2, y2, f"{footer_text} - Стр.{page_num + 1}")
            can.save()
            packet.seek(0)
            new_pdf = PdfReader(packet)
            page.merge_page(new_pdf.pages[0])

            writer.add_page(page)
        except Exception as ex:
            logger.error(ex)
    with open(pdf_file, "wb") as output_pdf:
        writer.write(output_pdf)

def combine_images_to_pdf(input_files, output_pdf, size=None, progress=None, self=None, A3_flag=False):
    """Создание файла с наклейками"""
    x_offset = 20
    y_offset = 20
    big_list_skin = []
    for i in input_files:
        if i.nums_in_folder >= 40:
            big_list_skin.append(i)
    input_files = [i for i in input_files if i not in big_list_skin]
    if A3_flag:
        c = canvas.Canvas(output_pdf, pagesize=landscape(A3), pageCompression=1)
        img_width = (A4[0] - 2 * x_offset) / 3
        img_height = (A4[1] - 2 * y_offset) / 3 - 10

        x_positions = [
            x_offset, x_offset + img_width + 10, x_offset + 2 * (img_width + 10),
                      x_offset + 3 * (img_width + 10), x_offset + 4 * (img_width + 10), x_offset + 5 * (img_width + 10)
        ]
        y_positions = [
            A3[0] - y_offset, A3[0] - y_offset - img_height - 15, A3[0] - y_offset - 2 * (img_height + 15)
        ]

        total_images = len(input_files)
        images_per_page = 18  # Размещаем 18 изображений на одной странице
        num_pages = (total_images + images_per_page - 1) // images_per_page

        for page in range(num_pages):
            start_idx = page * images_per_page
            end_idx = min(start_idx + images_per_page, total_images)
            for i, img in enumerate(input_files[start_idx:end_idx]):
                x = x_positions[i % 6]
                y = y_positions[i // 6]
                c.setFont("Helvetica-Bold", 6)
                c.drawString(x, y + 1, f"#{img.num_on_list}  {img.art}")
                try:
                    logger.success(f"Добавился подложка {img.num_on_list}   {img.art}")
                    progress.update_progress()
                    c.drawImage(img.skin, x - 10, y - img_height - 5, width=img_width, height=img_height)
                except Exception as ex:
                    logger.error(f"Не удалось добавить подложку для {img.art} {ex}")
            c.showPage()

        c.save()
    else:
        c = canvas.Canvas(output_pdf, pagesize=A4)
        img_width = (A4[0] - 2 * x_offset) / 3
        img_height = (A4[1] - 2 * y_offset) / 3 - 5

        x_positions = [x_offset, x_offset + img_width + 5, x_offset + 2 * (img_width + 5)]
        y_positions = [A4[1] - y_offset, A4[1] - y_offset - img_height - 10, A4[1] - y_offset - 2 * (img_height + 10)]

        total_images = len(input_files)
        images_per_page = 9
        num_pages = (total_images + images_per_page - 1) // images_per_page

        for page in range(num_pages):
            start_idx = page * images_per_page
            end_idx = min(start_idx + images_per_page, total_images)
            for i, img in enumerate(input_files[start_idx:end_idx]):
                x = x_positions[i % 3]
                y = y_positions[i // 3]
                c.setFont("Helvetica-Bold", 8)
                c.drawString(x, y + 2, f"#{img.num_on_list}     {img.art}")
                try:
                    logger.success(f"Добавился скин {img.num_on_list}     {img.art}")
                    progress.update_progress()
                    c.drawImage(img.skin, x - 10, y - img_height, width=img_width, height=img_height)
                except Exception as ex:
                    logger.error(f"Не удалось добавить подложку для {img.art} {ex}")
            c.showPage()
        c.save()

    if big_list_skin:
        c = canvas.Canvas(f"Файлы на печать/Большие подложки {size}.pdf", pagesize=A4)
        img_width = 505
        img_height = 674
        for i, img in enumerate(big_list_skin):
            c.setFont("Helvetica-Bold", 8)
            c.drawString(30, 30, f"#{img.num_on_list}     {img.art}")
            try:
                logger.success(f"Добавился скин {img.num_on_list}     {img.art}")
                progress.update_progress()

                c.drawImage(img.skin, 40, 100, width=img_width, height=img_height)
            except Exception as ex:
                logger.error(f"Не удалось добавить подложку для {img.art} {ex}")
            c.showPage()
        c.save()
    add_header_and_footer_to_pdf(output_pdf, self.name_doc, A3_flag=A3_flag)

def write_images_art(image, text1):
    """Нанесения номера на значке"""
    width, height = image.size
    draw = ImageDraw.Draw(image)

    # Calculate the font size based on the image width
    font_size = int(width / 13)
    font = ImageFont.truetype("arial.ttf", font_size)

    # Добавляем надпись в правый верхний угол
    bbox1 = draw.textbbox((0, 0), text1, font=font)
    x1 = width - bbox1[2] - 5
    y1 = 5
    draw.text((x1, y1), text1, font=font, fill="black")

    return image

def write_images_art2(image, text, x, y):
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("arial.ttf", 40)

    draw.text((x, y), text, font=font, fill="black")

    return image

def distribute_images(queryset, size, a3_flag, self, count) -> tuple:
    if a3_flag:
        with open('Настройки\\Параметры значков_A3.json', 'r') as file:
            config = json.load(file)
    else:
        with open('Настройки\\Параметры значков.json', 'r') as file:
            config = json.load(file)
    nums = config[f'{str(size)}']['nums']
    list_arts = [[None, i.nums_in_folder, i.images, i.id] for i in queryset]
    list_arts = sorted(list_arts, key=lambda x: x[1], reverse=True)
    # Список для хранения наборов
    sets_of_orders = []

    current_set = []  # Текущий набор
    current_count = 0  # Текущее количество элементов в наборе
    while len(list_arts) > 0:
        for order in list_arts[:]:
            if order[1] > nums:
                image_list = [(i, count) for i in order[2].split(', ')]
                if (current_count + (len(image_list) % nums)) <= nums and ((len(image_list) % nums) != 0):
                    current_set.extend(image_list[-(order[1] % nums):])
                    current_count += len(image_list) % nums
                    full_lists = order[1] // nums
                    for i in range(full_lists):
                        sets_of_orders.append(image_list[nums * i:nums * i + nums])
                    push_number(order[3], count)
                    list_arts.remove(order)
                    count += 1
                elif (order[1] > nums) and current_count == 0:
                    full_lists = order[1] // nums
                    for i in range(full_lists):
                        sets_of_orders.append(image_list[nums * i:nums * i + nums])
                    if order[1] % nums != 0:
                        current_set.extend(image_list[-(order[1] % nums):])
                    push_number(order[3], count)
                    list_arts.remove(order)
                    count += 1
                else:
                    sets_of_orders.append(current_set)
                    current_set = []
                    current_count = 0
                    full_lists = order[1] // nums
                    for i in range(full_lists):
                        sets_of_orders.append(image_list[nums * i:nums * i + nums])

                    if order[1] % nums != 0:
                        current_set.extend(image_list[-(order[1] % nums):])
                        current_count += len(image_list[-(order[1] % nums):])
                    push_number(order[3], count)
                    list_arts.remove(order)
                    count += 1

            if (current_count + order[1]) <= nums:
                current_set.extend([[i, count] for i in order[2].split(', ')])
                current_count += order[1]
                list_arts.remove(order)
                push_number(order[3], count)
                count += 1
                if current_count == nums:
                    sets_of_orders.append(current_set)
                    current_set = []
                    current_count = 0
                    break
            continue
        if current_count != 0:
            sets_of_orders.append(current_set)
        if len(list_arts) == 1:
            sets_of_orders.append([[i, count] for i in list_arts[0][2].split(', ')])
            push_number(list_arts[0][3], count)
            list_arts.remove(list_arts[0])
            count += 1

        if list_arts:
            current_set = []
            current_set.extend([[i, count] for i in list_arts[0][2].split(', ')])
            current_count = list_arts[0][1]
            push_number(list_arts[0][3], count)
            list_arts.remove(list_arts[0])
            count += 1

    logger.info(f'Сумма значков: {sum([len(i) for i in sets_of_orders])}')
    # logger.info(f'Сумма значков на листах: {set([len(i) for i in sets_of_orders])}')
    logger.info(f'Количество листов: {len(sets_of_orders)}')
    if self:
        self.list_on_print += len(sets_of_orders)
    return sets_of_orders, count

def create_contact_sheet(images=None, size=None, self=None, A3_flag=False, popsocket=False):
    border_color = (0, 0, 0, 255)  # Черный цвет рамки
    border_width = 1  # Ширина рамки в пикселях
    ready_path = 'Файлы на печать'
    if A3_flag:
        a4_width = 3508
        a4_height = 4961
        with open('Настройки\\Параметры значков_A3.json', 'r') as file:
            config = json.load(file)
    else:
        a4_width = 2480
        a4_height = 3508
        with open('Настройки\\Параметры значков.json', 'r') as file:
            config = json.load(file)
    image_width_mm = config[f'{str(size)}']['diameter']
    image_height_mm = config[f'{str(size)}']['diameter']

    # Convert mm to inches (1 inch = 25.4 mm)
    mm_to_inch = 25.4
    image_width = int(image_width_mm * 300 / mm_to_inch)
    image_height = int(image_height_mm * 300 / mm_to_inch)

    if self:
        self.progress_label.setText(f"Прогресс: Создание изображений {size} mm.")
        self.progress_bar.setValue(0)
        progress = ProgressBar(len(images), self)
    for index, img in enumerate(images, start=1):
        try:
            contact_sheet = Image.new('RGBA', (a4_width, a4_height), (255, 255, 255, 0))
            draw = ImageDraw.Draw(contact_sheet)

            for i in range(config[f'{str(size)}']['ICONS_PER_COL']):
                for j in range(config[f'{str(size)}']['ICONS_PER_ROW']):
                    try:
                        image = Image.open(img[i * config[f'{str(size)}']['ICONS_PER_ROW'] + j][0].strip())
                        image = write_images_art(image,
                                                 f'#{img[i * config[f"{str(size)}"]["ICONS_PER_ROW"] + j][1]}')
                        image = image.resize((image_width, image_height), Image.LANCZOS)
                    except Exception as ex:
                        break
                    try:
                        if size == 56:
                            contact_sheet.paste(image, (j * image_width - 10, i * image_height + 10 * (i + 1)))
                            border_rect = [j * image_width - 10, i * image_height + 10 * (i + 1),
                                           (j + 1) * image_width - 10, (i + 1) * image_height + 10 * (i + 1)]
                        elif size == 25 or size == 44:
                            contact_sheet.paste(image, (j * image_width + 100, i * image_height + 10 * (i + 1)))
                            border_rect = [j * image_width + 100, i * image_height + 10 * (i + 1),
                                           (j + 1) * image_width + 100, (i + 1) * image_height + 10 * (i + 1)]
                        else:
                            contact_sheet.paste(image, (j * image_width + 10, i * image_height + 10 * (i + 1)))
                            border_rect = [j * image_width + 10, i * image_height + 10 * (i + 1),
                                           (j + 1) * image_width + 10, (i + 1) * image_height + 10 * (i + 1)]
                    except Exception as ex:
                        break
                    try:
                        circle_center = ((border_rect[0] + border_rect[2]) // 2, (border_rect[1] + border_rect[3]) // 2)
                        circle_radius = min((border_rect[2] - border_rect[0]) // 2,
                                            (border_rect[3] - border_rect[1]) // 2)
                        draw.ellipse((circle_center[0] - circle_radius, circle_center[1] - circle_radius,
                                      circle_center[0] + circle_radius, circle_center[1] + circle_radius),
                                     outline=border_color, width=border_width)
                    except Exception as ex:
                        break
            if self:
                progress.update_progress()
            if not popsocket:
                path_ready = f'{ready_path}/{size}/{index}.png'
            else:
                path_ready = f'{ready_path}/Popsockets/{index}.png'
            x = config['number on badge']['x'] - 40
            y = config['number on badge']['y']
            image = write_images_art2(contact_sheet, f"{self.name_doc} Стр.{index}", x, y)
            image.save(path_ready)
            logger.success(f'Создано изображение {index}.png')

        except Exception as ex:
            logger.error(ex)
            logger.error(img)

def merge_pdfs_stickers(queryset, output_path):
    pdf_writer = PyPDF2.PdfWriter()
    input_paths = [i.sticker for i in queryset if i.sticker]
    if not input_paths:
        return
    for index, input_path in enumerate(input_paths, start=1):
        try:
            with open(input_path, 'rb') as pdf_file:
                pdf_reader = PyPDF2.PdfReader(pdf_file)

                # Add all pages from PdfReader to PdfWriter
                for page in pdf_reader.pages:
                    pdf_writer.add_page(page)
        except Exception:
            pass
    current_output_path = f"{output_path}.pdf"
    with open(current_output_path, 'wb') as output_file:
        pdf_writer.write(output_file)
    PyPDF2.PdfWriter()

def created_good_images(all_arts, self, A3_flag=False):
    progress = None

    try:
        ready_path = 'Файлы на печать'
        Orders.drop_table()
        if not Orders.table_exists():
            Orders.create_table(safe=True)
        bad_arts_stickers = []
        try:
            shutil.rmtree(ready_path, ignore_errors=True)
            time.sleep(1)
        except:
            pass
        os.makedirs(f'{ready_path}\\25', exist_ok=True)
        os.makedirs(f'{ready_path}\\37', exist_ok=True)
        os.makedirs(f'{ready_path}\\44', exist_ok=True)
        os.makedirs(f'{ready_path}\\56', exist_ok=True)
        os.makedirs(f'{ready_path}\\Popsockets', exist_ok=True)

        for art in all_arts:
            art_clean = remove_russian_letters(art.art.upper())
            row = Article.get_or_none(fn.UPPER(Article.art) == art_clean)
            if row:
                data = [{'art': row.art,
                         'folder': row.folder,
                         'nums': row.nums,
                         'nums_in_folder': row.nums_in_folder,
                         'size': row.size,
                         'skin': row.skin,
                         'sticker': row.sticker,
                         'images': row.images,
                         'shop': row.shop,
                         }
                        ] * art.count
                Orders.bulk_create([Orders(**item) for item in data])

        # Присваивание номера записям Orders
        sorted_orders = Orders.sorted_records()
        for index, row in enumerate(sorted_orders, start=1):
            if not os.path.exists(row.folder):
                logger.error(f'Папка не найдена {row.folder}')
                row.delete_instance()
            if not row.sticker:
                bad_arts_stickers.append((row.art, row.size))

        # Запись ненайденных артикулов и с отсутсвующих стикеров в файл
        if bad_arts_stickers:
            try:
                df_bad_sticker = pd.DataFrame(bad_arts_stickers, columns=['Артикул', 'Размер'])
                df_in_xlsx(df_bad_sticker, 'Не найденные ШК в заказе')
            except Exception as ex:
                logger.error(ex)

        records = Orders.select(Orders.size).where(Orders.shop != 'Popsocket').order_by('-size').distinct()
        records = sorted([i.size for i in records])
        count = 1
        for size in records:
            queryset = Orders.select().where(Orders.size == size).where(Orders.shop != 'Popsocket')

            sets_of_orders, count = distribute_images(queryset, size, A3_flag, self, count)
            if self:
                self.progress_bar.setValue(0)
                self.progress_label.setText(f"Прогресс: Создание подложек {size} mm.")

                progress = ProgressBar(queryset.count(), self)

            try:
                logger.debug(f'Создание наклеек {size}')
                combine_images_to_pdf(queryset.order_by(Orders.num_on_list),
                                      f"{ready_path}/Наклейки {size}.pdf", size, progress, self, A3_flag)
            except Exception as ex:
                logger.error(ex)
                logger.error(f'Не удалось создать файл с наклейками {size}')

            try:
                logger.debug(f'Создание файла ШК {size}')
                merge_pdfs_stickers(queryset.order_by(Orders.num_on_list), f'Файлы на печать\\ШК {size}')
            except Exception as ex:
                logger.error(ex)
                logger.error(f'Не удалось создать файл ШК {size}, возможно не одного не найденно')

            try:
                logger.debug(f'Создание листов со значками {size}')
                create_contact_sheet(sets_of_orders, size, self, A3_flag)
            except Exception as ex:
                logger.error(ex)

        #Popsockets
        queryset = Orders.select().where(Orders.shop == 'Popsocket')
        if len(queryset) > 0:
            size = 44
            sets_of_orders, count = distribute_images(queryset, size, A3_flag, self, count)
            if self:
                self.progress_bar.setValue(0)
                self.progress_label.setText(f"Прогресс: Создание подложек Popsocket")
                progress = ProgressBar(queryset.count(), self)

            try:
                logger.debug(f'Создание наклеек Popsocket {size}')
                combine_images_to_pdf(queryset.order_by(Orders.num_on_list),
                                      f"{ready_path}\\Наклейки Popsockets.pdf", size, progress, self, A3_flag)
            except Exception as ex:
                logger.error(ex)
                logger.error(f'Не удалось создать файл с наклейками {size}')

            try:
                logger.debug(f'Создание файла ШК Popsocket')
                merge_pdfs_stickers(queryset.order_by(Orders.num_on_list), f'Файлы на печать\\ШК Popsocket')
            except Exception as ex:
                logger.error(ex)
                logger.error(f'Не удалось создать файл ШК Popsocket, возможно не одного не найденно')

            try:
                logger.debug(f'Создание листов со значками Popsocket')
                create_contact_sheet(sets_of_orders, size, self, A3_flag, popsocket=True)
            except Exception as ex:
                logger.error(ex)

        if self.create_pdf_checkbox.checkState() == 2:
            try:
                created_pdfs(self)
            except Exception as ex:
                logger.error(ex)

        lists = 0
        try:
            lists = files_base_postgresql(self)
        except Exception as ex:
            logger.error(ex)

        try:
            orders_base_postgresql(self, lists)
        except Exception as ex:
            logger.error(ex)

        self.list_on_print = 0
        QMessageBox.information(self, 'Завершено', 'Создание файлов завершено!')

        records = Orders.select()
        for record in records:
            record.lists = lists
            record.save()
            Statistic.create(art=record.art, nums=record.nums_in_folder, size=record.size)
    except Exception as ex:
        logger.error(ex)

if __name__ == '__main__':
    input_file = r'E:\Очередь на печать\49.png'
    output_file = r'E:\Очередь на печать\!1.png'
    # crop_to_content2(input_file, output_file)


from typing import Dict, Optional

from gi.repository import Gtk

from . import ViewEmpty
from .base import View
from ..model import Document

class ViewManager:

    def __init__(self, window: Gtk.ApplicationWindow, root: Gtk.Box):
        self.window = window
        self.root = root
        self.views: Dict[str, View] = {}

    def set_root_view(self, view_class: type) -> View:
        view = self._create_view(view_class)
        self.connect(self.window, view)
        self.root.add(view.container)
        self.print()
        return view

    def __getitem__(self, view_name: str) -> View:
        if view_name not in self.views:
            raise ValueError('Unknown view: ' + str(view_name))
        return self.views[view_name]

    def close(self, view_name: str) -> None:
        view = self[view_name]
        paned = view.container.get_parent()
        others = [sibling for sibling in paned.get_children() if sibling != view.container]

        if paned is self.root:
            raise ValueError('Not removing root')
        if not isinstance(paned, Gtk.Paned):
            raise ValueError('parent is no Paned but ' + str(type(paned)))
        if len(others) != 1:
            raise ValueError('more than 1 sibling')

        other = others[0]
        parent: Gtk.Container = paned.get_parent()
        paned.remove(view.container)
        paned.remove(other)
        view.container.destroy()
        self.disconnect(self.window, view)

        parent.remove(paned)
        parent.add(other)

        del self.views[view_name]
        del view
        self.print()

    def add(self, new_view_type: Optional[type] = None) -> View:
        return self.split(None, new_view_type, False)

    def split(self, split_view_name: Optional[str] = None, new_view_type: Optional[type] = None, vertical: bool = True) -> View:
        split_view_name = split_view_name or list(self.views.keys())[0]
        new_view_type = new_view_type or ViewEmpty
        view = self[split_view_name]
        parent: Gtk.Box = view.container.get_parent()
        new_pane_root = Gtk.Paned(visible=True, orientation=Gtk.Orientation(vertical))
        new_view = self._create_view(new_view_type)
        parent.remove(view.container)
        new_pane_root.pack1(view.container, True, False)
        new_pane_root.pack2(new_view.container, True, False)
        parent.add(new_pane_root)
        self.connect(self.window, new_view)
        self.print()
        return new_view

    def replace(self, replace_view: str, new_view_type: type) -> View:
        view = self[replace_view]
        parent: Gtk.Box = view.container.get_parent()
        new_view = self._create_view(new_view_type, replace_view)
        parent.remove(view.container)
        parent.add(new_view.container)
        self.views[view.name] = new_view
        view.container.destroy()
        self.connect(self.window, new_view)
        self.print()
        return new_view

    def _create_view(self, view_class: type, name: Optional[str] = None) -> View:
        name = name or self._unique_name()
        view: View = view_class(name, self.window)
        view.build()
        view.set_document(self.window.document)
        view.page_activated(self.window, self.window.current_page_id)
        self.views[name] = view
        return view

    def set_document(self, document: Document) -> None:
        for view in self.views.values():
            view.set_document(document)

    def update_ui(self) -> None:
        for view in self.views.values():
            view.update_ui()

    def _unique_name(self) -> str:
        for i in range(len(self.views.keys()), 999999):
            name = 'view_' + str(i)
            if name not in self.views:
                return name
        raise RuntimeError('Found no unique view name')

    def disconnect(self, win: Gtk.Window, view: View) -> None:
        try:
            win.disconnect_by_func(view.page_activated)
            win.disconnect_by_func(view.pages_selected)
        except Exception as e:
            print(e)

    def connect(self, win: Gtk.Window, view: View) -> None:
        win.connect('page_activated', view.page_activated)
        win.connect('pages_selected', view.pages_selected)

    def print(self) -> None:
        return
        # print(self.views)
        # print(self.print_level())

    def print_level(self, root: Gtk.Paned = None, indent: int = 0) -> str:
        current: Gtk.Container = root or self.root
        s: str = ('\t' * indent) + current.get_name()
        if isinstance(current, Gtk.Box) and current.get_name().startswith('view_'):
            view = self[current.get_name()]
            s = s + ': ' + type(view).__qualname__ + "\n"
        else:
            s = s + "\n"
            for c in current.get_children():
                if isinstance(c, Gtk.Container):
                    s = s + self.print_level(c, indent + 1)
        return s


'''
    Course: CS2302 Data Structures Fall 2019
    Author: Ismael Villalobos
    Assignment: Lab 3 Linked Lists
    Instructor: Dr. Olac Fuentes
    TA: Anindita Nath
    Last Modified: October 5th 2019
    Purpose:
'''

import math
import random

class Node(object):
    # constructor
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

# SortedList functions
class SortedList(object):
    # constructor
    def __init__(self, head=None, tail=None):
        self.head = head
        self.tail = tail

    def Print(self):
        # prints items in order using a loop
        t = self.head
        while t is not None:
            print(t.data, end=' ')
            t = t.next
        print()

    def Append(self, x):
        node = Node(x)
        current = self.head
        previous = None

        while current is not None and current.data < x:
            previous = current
            current = current.next

        if previous == None:
            self.head = node
        else:
            previous.next = node

            node.next = current

    def Insert(self, i):
        self.Append(i)

    def Delete(self, i):
        t = self.head

        if t is None:
            return None
        elif t.data == i:
            if t.next is None:
                self.head = None
            else:
                self.head = t.next
        else:
            prev = t
            while t is not None:
                if t.data == i:
                    prev.next = t.next
                prev = t
                t = t.next

    def Merge(self, M):
        x = M.head
        while x is not None:
            self.Insert(x.data)
            x = x.next

    def IndexOf(self, i):
        t = self.head
        index = 0
        while t is not None:
            if t.data == i:
                return index
            index += 1
            t = t.next
        return -1

    def Clear(self):
        self.head = None

    def Min(self):
        if self.head is None:
            return math.inf
        return self.head.data

    def Max(self):
        t = self.head
        if t is None:
            return -math.inf
        max = -math.inf
        while t is not None:
            if t.data > max:
                max = t.data
            t = t.next
        return max

    def HasDuplicates(self):
        t = self.head
        if t is None or t.next is None:
            return False
        while t is not None:
            if t.next != None:
                if t.data == t.next.data:
                    return True
            t = t.next
        return False

    def Select(self, k):
        if self.head is None:
            return math.inf
        index = 0
        t = self.head
        while t is not None:
            if index == k:
                return t.data
            index += 1
            t = t.next

L = SortedList()  # create empty list to use for main output
M = SortedList()  # list for merging

# fill list with random values between 0-50
for i in range(0, 10):
    L.Append(i)

for i in range(0, 10):
    M.Append(random.randint(0, 50))
print('Printing Items In Sorted List')
L.Print()
insertion= int(input('Enter number to insert: '))
print('Inserting',insertion)
print('List after inserting',insertion)
L.Insert(insertion)
L.Print()
deletion= int(input('Enter number to delete: '))
print('Deleting',deletion)
print('List after deleting',deletion)
L.Delete(deletion)
L.Print()

print('====================================')
print('This is L')
L.Print()
print('This is M')
M.Print()

print('This is L and M Merged')
L.Merge(M)
L.Print()
key = int(input("Enter a number to find in the list: "))
print(key, "is found at the following index:", L.IndexOf(key))
print('Clearing List')
L.Clear()
print('List Cleared')
L.Print()
print('Creating New List')
for i in range(0, 10):
    L.Append(random.randint(0, 50))
print('New List Is')
L.Print()

m = L.Min()
print('Minimum Value in List',m)
mx = L.Max()
print('Maximum Value in List',mx)

print('Checking for Duplicates')
L.Print()
dup=L.HasDuplicates()
if dup == True:
    print('List Contains Duplicates')
else:
    print('List Does Not Contain Duplicates')
K = int(input("Enter a number for k: "))
print("Value at position k:", L.Select(K))


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

# Interactive User Input
x = sp.Symbol('x')
a = float(input("Enter the value of 'a': "))
f_x = input("Enter the function f(x): ")

# Define the Function and its Differentiation
f = a * sp.sympify(f_x)
f_prime = sp.diff(f, x)

# Create Numeric Functions for Plotting
f_numeric = sp.lambdify(x, f, 'numpy')
f_prime_numeric = sp.lambdify(x, f_prime, 'numpy')

# Create Visualization
x_vals = np.linspace(-10, 10, 400)
y_vals_f = f_numeric(x_vals)
y_vals_f_prime = f_prime_numeric(x_vals)

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals_f, label='$af(x)$', color='blue')
plt.plot(x_vals, y_vals_f_prime, label='$a\\frac{df(x)}{dx}$', color='red')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Visualization of $af(x)$ and $a\\frac{df(x)}{dx}$')
plt.legend()
plt.grid()
plt.show()


"""
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]
"""

class Solution:
    def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        if m == 0: nums1[:n] = nums2
        if n == 0: return
        mainCur, cur1, cur2 = m + n - 1, m - 1, n - 1
        while cur1 >= 0 and cur2 >= 0:
            if nums1[cur1] <= nums2[cur2]:
                nums1[mainCur] = nums2[cur2]
                cur2 -=1
            else:
                nums1[mainCur] = nums1[cur1]
                cur1 -=1
            mainCur -= 1
        while cur2 >= 0:
            nums1[mainCur] = nums2[cur2]
            mainCur-=1
            cur2-=1
        print(nums1)
s = Solution()
print(s.merge([2,0],1,[1],1))

Leetcode/Leetcode - Merge Sorted Array.py


# Databricks notebook source
# MAGIC %run ../test_helpers

# COMMAND ----------

# MAGIC %run ../../notebooks/common/spark_helpers

# COMMAND ----------

# MAGIC %run ../../notebooks/generator_stages/relationship_generator

# COMMAND ----------

import random

from pyspark.sql import functions as F, types as T

# COMMAND ----------

# region Fixtures

def tidy_meta_df_fixture() -> DataFrame:
  data = [
    ["field1", "RELATIONSHIP", 1., 1., None, None],
    ["field1", "RELATIONSHIP", 2., 2., None, None],
    ["field1", "RELATIONSHIP", 3., 3., None, None],
    ["field2", "RELATIONSHIP", 4., 3., None, None],
    ["field2", "RELATIONSHIP", 5., 2., None, None],
    ["field2", "RELATIONSHIP", 6., 1., None, None],
    ["field3", "OTHER",        7., 3., None, None],
    ["field3", "OTHER",        8., 2., None, None],
    ["field3", "OTHER",        9., 1., None, None],
  ]
  schema = "FIELD_NAME: string, VALUE_TYPE: string, VALUE_NUMERIC: double, WEIGHT: double, VALUE_STRING: string, VALUE_DATE: date"
  df = spark.createDataFrame(data, schema)
  return df

# endregion

# COMMAND ----------

# region relationship_generator tests

relationship_generator_test_suite = FunctionTestSuite()

@relationship_generator_test_suite.add_test
def test_generated_values_have_expected_frequency_distribution():
  n_rows = 10000
  base_df = spark.range(n_rows)

  meta_df = tidy_meta_df_fixture()

  result_df = relationship_generator(meta_df, base_df, ["FIELD_NAME"])

  assert result_df.first() is not None, "Result did not have any rows"

  # Check size of each array
  aggregated_result_df = (
    result_df
    .groupBy("FIELD_NAME", "id")
    .agg(F.count(F.lit(1)).alias("CARDINALITY"))
    .groupBy("FIELD_NAME", "CARDINALITY")
    .agg((F.count(F.lit(1)) / n_rows).alias("FREQUENCY"))
  )

  expected_frequency_col = (
    F
    .when((F.col("FIELD_NAME") == "field1") & (F.col("CARDINALITY") == 1), 1 / 6)
    .when((F.col("FIELD_NAME") == "field1") & (F.col("CARDINALITY") == 2), 2 / 6)
    .when((F.col("FIELD_NAME") == "field1") & (F.col("CARDINALITY") == 3), 3 / 6)
    .when((F.col("FIELD_NAME") == "field2") & (F.col("CARDINALITY") == 4), 3 / 6)
    .when((F.col("FIELD_NAME") == "field2") & (F.col("CARDINALITY") == 5), 2 / 6)
    .when((F.col("FIELD_NAME") == "field2") & (F.col("CARDINALITY") == 6), 1 / 6)
  )

  aggregated_result_df = aggregated_result_df.withColumn("EXPECTED_FREQUENCY", expected_frequency_col)

  n_expected_rows = 6
  assert aggregated_result_df.limit(n_expected_rows+1).count() == n_expected_rows, "Fewer that expected rows in the aggregated result"

  assert columns_approx_equal(aggregated_result_df, "FREQUENCY", "EXPECTED_FREQUENCY", 0.1), "Some or all frequencies did not equal the expected values"

@relationship_generator_test_suite.add_test
def test_only_relationship_fields_generated():
  n_rows = 10
  base_df = spark.range(n_rows)

  meta_df = tidy_meta_df_fixture()

  result_df = relationship_generator(meta_df, base_df, ["FIELD_NAME"])

  assert result_df.first() is not None, "Result did not have any rows"

  # Check no fields other than categorical
  distinct_fields_df = result_df.select("FIELD_NAME").distinct()
  expected_relationship_fields = ["field1", "field2"]
  assert distinct_fields_df.filter(~F.col("FIELD_NAME").isin(expected_relationship_fields)).first() is None, "Non relationship fields were generated!"

@relationship_generator_test_suite.add_test
def test_zero_weight_values_not_generated():
  n_rows = 10
  base_df = spark.range(n_rows)

  meta_df = tidy_meta_df_fixture()

  meta_df = meta_df.withColumn("WEIGHT", F.lit(0.))

  result_df = relationship_generator(meta_df, base_df, ["FIELD_NAME"])

  assert result_df.first() is None, "Values generated with weight equal to zero!"

@relationship_generator_test_suite.add_test
def test_zero_values_do_not_have_rows_in_resulting_df():
  n_rows = 10
  base_df = spark.range(n_rows)

  meta_df = tidy_meta_df_fixture()

  meta_df = meta_df.withColumn("VALUE_NUMERIC", F.lit(0.))

  result_df = relationship_generator(meta_df, base_df, ["FIELD_NAME"])

  assert result_df.first() is None, "Did not expect any rows to be generated"

@relationship_generator_test_suite.add_test
def test_null_values_do_not_have_rows_in_resulting_df():
  n_rows = 10
  base_df = spark.range(n_rows)

  meta_df = tidy_meta_df_fixture()

  meta_df = meta_df.withColumn("VALUE_NUMERIC", F.lit(None).cast("double"))

  result_df = relationship_generator(meta_df, base_df, ["FIELD_NAME"])

  assert result_df.first() is None, "Did not expect any rows to be generated"

@relationship_generator_test_suite.add_test
def test_maximum_generated_cardinality_less_or_equal_output_ratio_threshold():
  # If the cardinality is higher than the outputRatioThreshold, then the pipeline could error
  # when trying to explode the relationships
  output_ratio_threshold = int(spark.conf.get("spark.databricks.queryWatchdog.outputRatioThreshold"))
  # Create metadata with cardinality above the threshold
  data = [["field1", "RELATIONSHIP", output_ratio_threshold ** 2., 1., None, None]]
  schema = "FIELD_NAME: string, VALUE_TYPE: string, VALUE_NUMERIC: double, WEIGHT: double, VALUE_STRING: string, VALUE_DATE: date"
  meta_df = spark.createDataFrame(data, schema)

  n_rows = 1
  base_df = spark.range(n_rows)

  result_df = relationship_generator(meta_df, base_df, ["FIELD_NAME"])

  assert result_df.count() == output_ratio_threshold

relationship_generator_test_suite.run()

# endregion

# COMMAND ----------


import discord

from discord.ext.commands import Cog
from discord.ext.commands import command
from discord.ext import commands
from datetime import date, datetime
from random import randint

from ..db import db

class LeavesXP(Cog):
    def __init__(self, bot):
        self.bot = bot
        self.numMessages = 0

    async def process_xp(self, message):
        try:
            xp, xpratelimit = db.record("SELECT XP, XPRateLimit FROM userXP WHERE UserID = ?", message.author.id)
        except Exception:
            db.execute("INSERT INTO userXP (UserID) VALUES (?)", message.author.id)
            print(f"{message.author} not found in database. adding to db")
            xp, xpratelimit = db.record("SELECT XP, XPRateLimit FROM userXP WHERE UserID = ?", message.author.id)

        if datetime.fromisoformat(xpratelimit) < datetime.utcnow():
            await self.add_xp(message, xp)

    async def add_xp(self, message):
        xp_to_add = randint(1, 4)

        db.execute("UPDATE userXP SET XP = XP + ?, XPRateLimit = ? WHERE UserID = ?", xp_to_add, datetime.utcnow().isoformat(), message.author.id)
        print(f'added {xp_to_add} xp to {message.author}')
        self.numMessages += 1

        if self.numMessages > 10:
            print(f'committed xp database')
            self.numMessages = 0
            db.commit()

    @Cog.listener()
    async def on_ready(self):
        await self.bot.stdout.send("Falling Leaves Online")
        print("Falling Leaves Online")
        if not self.bot.ready:
            self.bot.cogs_ready.ready_up("leavesXP")

    @Cog.listener()
    async def on_message(self, message):
        if not message.author.bot:
            await self.process_xp(message)

    @command(aliases=['bank', 'lb'])
    async def leafbank(self, ctx):
        xp = db.record("SELECT XP FROM userXP WHERE UserID = ?", ctx.message.author.id)
        await ctx.send(f'Hello {ctx.message.author.name}! You have collected {xp[0]} fallen leaves!')

    @command(aliases=['hb'])
    async def housebank(self, ctx):
        numleaves = db.record("SELECT XP FROM userXP WHERE UserID = 69")
        if (numleaves[0] >= 0):
            await ctx.send(f"Lol I've won {numleaves[0]} leaves from you scrubs")
        else:
            await ctx.send(f"Y'all have won {-numleaves[0]} leaves from me :c")

    @command()
    async def glb(self, ctx):
        pass

def setup(bot):
    bot.add_cog(LeavesXP(bot))


import numpy as np
import os
import json

import torch
import torch.nn as nn
import torch.nn.functional as F

from lib.embedding import load_full_embedding_with_vocab
from lib.train import BaseClassifier
from lib.transformer import MultiHeadedAttention, PositionwiseFeedForward, PositionalEncoding

class SelfAttentionCnnClassifier(BaseClassifier):
    def __init__(self, cuda_device=None, words_embed=None, len_vocab=0, len_embed=0,
                 out_channels=100, conv_width=5, hidden_size=200, out_size=2, dropout=0.5,
                 h=8):
        super(SelfAttentionCnnClassifier, self).__init__(cuda_device=cuda_device,
                    words_embed=words_embed, len_vocab=len_vocab, len_embed=len_embed)

        self.pos_enc = PositionalEncoding(self.len_embed, dropout)

        self.q_mha = MultiHeadedAttention(h=h, d_model=self.len_embed, dropout=dropout)
        self.q_layer_norms = nn.ModuleList([nn.LayerNorm([self.len_embed]) for _ in range(2)])

        self.a_mha = MultiHeadedAttention(h=h, d_model=self.len_embed, dropout=dropout)
        self.a_layer_norms = nn.ModuleList([nn.LayerNorm([self.len_embed]) for _ in range(2)])

        self.q_conv = nn.Conv1d(self.len_embed, out_channels, conv_width, padding=(conv_width//2))
        self.a_conv = nn.Conv1d(self.len_embed, out_channels, conv_width, padding=(conv_width//2))

        self.hidden1 = nn.Linear(out_channels * 2, hidden_size)
        self.dropout = nn.Dropout(dropout)
        self.hidden2 = nn.Linear(hidden_size, out_size)

        if self.cuda_device is not None:
            self.q_mha = self.q_mha.cuda(self.cuda_device)
            self.q_layer_norms = self.q_layer_norms.cuda(self.cuda_device)
            self.a_mha = self.a_mha.cuda(self.cuda_device)
            self.a_layer_norms = self.a_layer_norms.cuda(self.cuda_device)
            self.q_conv = self.q_conv.cuda(self.cuda_device)
            self.a_conv = self.a_conv.cuda(self.cuda_device)
            self.hidden1 = self.hidden1.cuda(self.cuda_device)
            self.dropout = self.dropout.cuda(self.cuda_device)
            self.hidden2 = self.hidden2.cuda(self.cuda_device)

        nn.init.kaiming_uniform_(self.hidden1.weight, nonlinearity='relu')

    @classmethod
    def load(cls, config_path):
        with open(config_path, 'r') as fread:
            config_dict = json.load(fread)

        path_config = config_dict['Path']
        model_config = config_dict['Model']

        words_embed, words_vocab = load_full_embedding_with_vocab(path_config['embed_dir'])

        model = cls(words_embed=words_embed, out_channels=model_config['out_channels'],
                    conv_width=model_config['conv_width'], hidden_size=model_config['hidden_size'],
                    cuda_device=model_config['cuda_device'], dropout=model_config['dropout'],
                    h=model_config['h'])

        model.load_state_dict(torch.load(os.path.join(path_config['model_dir'], 'net.pt')))
        model.eval()
        return model

    def forward(self, *input):
        if self.cuda_device is not None:
            input = [data.cuda(self.cuda_device) for data in input]

        # words: (batch size, sentence length)
        q_words, a_words = input

        # mask: (batch size, 1, sentence length)
        # if word is special pad token (so have to be ignored in multi-head attention) or not
        q_mask = (q_words != 1).unsqueeze(-2)
        a_mask = (a_words != 1).unsqueeze(-2)

        # sent_mat: (batch size, sentence length, embedding dimension)
        # we added Layer Normalization layer after embedding
        q_sent_mat = self.q_layer_norms[0](self.embed(q_words))
        a_sent_mat = self.a_layer_norms[0](self.embed(a_words))

        # mha_out: (batch size, sentence length, embedding dimension)
        # multi-head attention output
        # self.q_mha = MultiHeadedAttention(h=h, d_model=self.len_embed, dropout=dropout)
        q_mha_out = self.q_mha(q_sent_mat, a_sent_mat, a_sent_mat, a_mask)
        q_mha_out = self.q_layer_norms[1](q_mha_out + q_sent_mat)

        a_mha_out = self.a_mha(a_sent_mat, q_sent_mat, q_sent_mat, q_mask)
        a_mha_out = self.a_layer_norms[1](a_mha_out + a_sent_mat)

        # conv_out: (batch size, out channels, sentence length)
        q_conv_out = self.q_conv(q_mha_out.transpose(2,1))
        # pool out: (batch size, out_channels)
        # we used max over time pooling
        q_pool_out, _ = torch.max(q_conv_out, dim=-1)

        a_conv_out = self.a_conv(a_mha_out.transpose(2, 1))
        a_pool_out, _ = torch.max(a_conv_out, dim=-1)

        # qa_repr: (batch size, out channels * 2)
        # joined representation
        qa_repr = torch.cat([q_pool_out, a_pool_out], dim=-1)

        # hidden layer and softmax layer
        hidden1_out = self.hidden1(qa_repr)
        hidden2_out = self.hidden2(self.dropout(F.relu(hidden1_out)))

        return hidden2_out


# Title: CMPE273-Lab2
# Description: A simple calculator with add(x, y) function as a gRPC server
# By: Neil Shah

from concurrent import futures
import time

import grpc

import calculator_pb2
import calculator_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class Calculate(calculator_pb2_grpc.CalculateServicer):

    def Add(self, request, context):
        return calculator_pb2.AddReply(message="Sum of %s and %s is %s" % (str(request.a), str(request.b), str(request.a+request.b)))

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    calculator_pb2_grpc.add_CalculateServicer_to_server(Calculate(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()


import unittest

import AoC2018.three.three as three
import AoC2018.util.util as util

class ThreeTests(unittest.TestCase):

    fabric = [['.'] * 8 for i in range(8)]

    inputs = ['#1 @ 1,3: 4x4',
              '#2 @ 3,1: 4x4',
              '#3 @ 5,5: 2x2']

    answer = [
        ['.', '.', '.', '.', '.', '.', '.', '.'],
        ['.', '.', '.', '2', '2', '2', '2', '.'],
        ['.', '.', '.', '2', '2', '2', '2', '.'],
        ['.', '1', '1', 'X', 'X', '2', '2', '.'],
        ['.', '1', '1', 'X', 'X', '2', '2', '.'],
        ['.', '1', '1', '1', '1', '3', '3', '.'],
        ['.', '1', '1', '1', '1', '3', '3', '.'],
        ['.', '.', '.', '.', '.', '.', '.', '.']
    ]

    def test_apply_rectangle(self):
        for line in self.inputs:
            self.fabric = three.apply_rectangle(self.fabric, line)
        self.assertEqual(self.fabric, self.answer)

    def test_count_overlap(self):
        self.assertEqual(4, util.flatten_and_count_char(self.answer, 'X'))

    def test_check_intact(self):
        for claim in self.inputs:
            result = three.check_intact(self.answer, claim)
            if result:
                self.assertEqual(self.inputs[2], claim)

if __name__ == '__main__':
    unittest.main()


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        length = len(candidates)
        candidates.sort()
        result = []
        def DFS(s, case):
            for i in range(s, length):
                if sum(case) + candidates[i] < target:
                    case.append(candidates[i])
                    DFS(i, case)
                    case.pop()
                elif sum(case) + candidates[i] == target:
                    case.append(candidates[i])
                    result.append(case[:])
                    case.pop()
        DFS(0, [])
        return result


# 12. Faça um programa para o cálculo de uma folha de pagamento, sabendo que os descontos são do Imposto de Renda, que depende do salário bruto (conforme tabela abaixo) e 3% para o sind e que o FGTS corresponde a 11% do Salário Bruto, mas não é descontado (é a empresa que deposita). O Salário Líquido corresponde ao Salário Bruto menos os descontos. O programa deverá pedir ao usuário o valor da sua hora e a quantidade de horas trabalhadas no mês.

valor = float(input("Digite o valor da hora trabalhada: "))
hora = int(input("Digite a quantiadade de horas trabalhada: "))

sal_bruto = valor * hora
fgts = sal_bruto * 0.11
sind = sal_bruto * 0.03

if sal_bruto <= 900:
    ir = 0
elif sal_bruto <= 1500:
    ir = 5
elif sal_bruto <= 2500:
    ir = 10
else:
    ir = 20

sal_liquido = sal_bruto - ir - sind

print(f"Salário Bruto: R$ {sal_bruto:.2f}")
print(f"(-) IR ({ir*100/sal_bruto:.0f}%): R$ {ir:.2f}")
print(f"(-) sind ({sind*100/sal_bruto:.0f}%): R$ {sind:.2f}")
print(f"FGTS ({fgts*100/sal_bruto:.0f}%): R$ {fgts:.2f}")
print(f"Total de descontos: R$ {ir+sind:.2f}")
print(f"Salário Líquido: R$ {sal_liquido:.2f}")


#!/usr/bin/python3

# python3 -m pip install python3-xlib
# python3 -m pip install pyautogui

# http://blog.topspeedsnail.com/archives/5373
# sudo apt-get install python3-pip
# sudo pip3 install python3-xlib
# sudo apt-get install scrot
# sudo apt-get install python3-tk
# and sudo apt-get install python3-dev

import pyautogui

#Python脚本在每执行一个函数后暂停几秒钟，这样你就有了几秒种的控制权
pyautogui.PAUSE = 1.5

#想终止程序，只要你快速的把鼠标移动到屏幕左上角就可以了
pyautogui.FAILSAFE = True

## 取得螢幕解析度
#width, height = pyautogui.size()
#print(width,height)

## 取得目前滑鼠座標
#x, y = pyautogui.position()

## 點選右鍵
#pyautogui.click(button='right')

## click函数完成了一次鼠标点击。一次完整的点击包括两部分，按下mouseDown()和弹起mouseUp()。上面这两个函数参数和click函数一样，其实click函数只是简单的封装了mouseDown()和mouseUp()函数
#pyautogui.click(100, 100)

im = pyautogui.screenshot()
#im.getpixel((50, 200))
#pyautogui.pixelMatchesColor(50, 200, (30, 132, 153))

def test1():
	for i in range(2):
		## moveTo 移動絕對座標
		pyautogui.moveTo(100, 100, duration=0.25)
		pyautogui.moveTo(200, 100, duration=0.25)
		pyautogui.moveTo(200, 200, duration=0.25)
		pyautogui.moveTo(100, 200, duration=0.25)

	for i in range(2):
		## moveRel 相對座標
		pyautogui.moveRel(100, 0, duration=0.25)
		pyautogui.moveRel(0, 100, duration=0.25)
		pyautogui.moveRel(-100, 0, duration=0.25)
		pyautogui.moveRel(0, -100, duration=0.25)


from setuptools import setup

with open('README.md', 'r') as fp:
    long_description = fp.read()

setup(
    name = 'Scython',
    version = '0.1.1',
    description = 'A C-like alternative syntax parser/front-end for Python',
    long_description = long_description,
    long_description_content_type = 'text/markdown',
    author = 'Josiah (Gaming32) Glosson',
    author_email = 'gaming32i64@gmail.com',
    url = 'https://github.com/Gaming32/Scython',
    packages = ['scy'],
    license = 'License :: OSI Approved :: MIT License',
    entry_points = {
        'console_scripts': [
            'scy=scy.__main__:main',
        ],
    },
)


file = open("1907伪.cvs", "r", encoding="utf-8")
lines = []  # list

for line in file:
    line = line.replace("\n", "")
    lines.append(line.split(","))  # line作为列表加入lines的元素组

# print(lines)

file_new = open("1907伪总.cvs", "w+", encoding="utf-8")

# 表头添加总分字段
lines[1].append("总分")
# 添加总分
for i in range(len(lines) - 2):
    # 处理第二行以后的数据
    idx = i + 2
    sumScore = 0
    # 处理idx行的列数据
    for j in range(len(lines[idx]) - 1):
        j += 1  # 从第二列数据开始读
        if lines[idx][j].isnumeric():
            # 若为数字，则累加
            sumScore += int(lines[idx][j])
    # 总分加入列尾
    lines[idx].append(str(sumScore))

# 写入处理后数据
for line in lines:
    file_new.write(",".join(line) + "\n")

file.close()
file_new.close()


import json
import requests
from bs4 import BeautifulSoup
from Models.RequestModel import RequestModel

class Parser:

    @staticmethod
    def search(search_word):
        pass

class RadugastroyParser(Parser):

    @staticmethod
    def search(search_word):
        html = requests.get('https://radugastroy.ru/search/?module=search&action=search&searchword=' + search_word).text
        soup = BeautifulSoup(html, "html.parser")

        address = soup.find('div', {'class': 'siteFooter-address'}).text

        result = []
        for block in soup.find_all("li", {"class": "shopBlock-item"}):
            link = block.find("div", {"class": "name"}).find("a")
            name = link.text
            url = link.get('href')
            price = block.find("b", {"class": "js_shop_price"}).text

            if block.find("div", {"class": "stock js_stock inStock"}) is None:
                continue

            result.append(RequestModel(
                search_word,
                url,
                name,
                price,
                None,
                0,
                [address.strip()]
            ))

        return result

class SdvorParser(Parser):

    @staticmethod
    def search(search_word):
        cities = requests.get('https://www.sdvor.com/api/omni_order/cities/').text
        cities = json.loads(cities)

        addresses = []
        for city in cities:
            addresses.append(city['name'])

        items = {}

        for city in cities:
            html = requests.get(
                'https://www.sdvor.com/' + city['uri_name'] + '/search/?only_in_stock=true&str=' + search_word).text
            soup = BeautifulSoup(html, "html.parser")
            for block in soup.find_all("div", {"class": "w1l5ijvb p4t3w1l".split()}):
                identity = block.find('span', {'class': 'p1gaa8sl'}).text
                if identity in items:
                    continue

                link = block.find("div", {"class": "i1b5ubz7"}).find("a")
                url = 'https://www.sdvor.com/' + link.get('href')
                name = link.text

                price_elem = block.find("span", {"class": "p1hbhc78"})
                if price_elem is None:
                    continue
                price = price_elem.text.replace(' ₽', '')

                items[identity] = RequestModel(
                    search_word,
                    url,
                    name,
                    price,
                    None,
                    0,
                    addresses
                )

        result = []

        for key, value in items.items():
            result.append(value)

        return result

class Sb1Parser(Parser):

    @staticmethod
    def search(search_word):

        addresses = []

        soup2 = BeautifulSoup(requests.get('https://s-b-1.ru/contacts/').text, "html.parser")

        for city in soup2.find('table', {'class': 'contacts-stores no-border shops list'.split()}).find_all('tr'):
            if city.get("class") is not None:
                continue

            addresses.append(city.find('h4').text)

        html = requests.get('https://s-b-1.ru/catalog/?q=' + search_word).text
        soup = BeautifulSoup(html, "html.parser")

        result = []
        for block in soup.find_all("div", {"class": "item_block"}):
            title = block.find("div", {"class": "item-title"})
            name = title.find("span").text
            price = block.find("span", {"class": "price_value"}).text
            item_stock = block.find("div", {"class": "item-stock"})

            url = 'https://s-b-1.ru/' + title.find('a').get('href')

            if item_stock.find("span", {"class": "value"}).text == "Нет в наличии":
                continue

            result.append(RequestModel(
                search_word,
                url,
                name,
                price,
                None,
                0,
                addresses
            ))

        return result

parsers = [RadugastroyParser, SdvorParser, Sb1Parser]


import pytest
import tutils
import logging
from kubernetes import client, config, utils
from kubernetes.stream import stream
from kubernetes.client import configuration
from os import path
from time import sleep
import yaml

tutils.logSetup()
configuration.assert_hostname = False
tutils.configSetup()
configuration.assert_hostname = False
k8s_client = client.ApiClient()

# yaml filename must match the object name, per our convention
def nameToYaml(name):
    return "yamls/ext/{}.yaml".format(name)

def createPod(name):
    k8s_api = utils.create_from_yaml(k8s_client, nameToYaml(name))

    # check pod is ready
    def podChecker():
        s = k8s_api.read_namespaced_pod_status(name, "default")
        if s.status.phase == "Running":
            return ""
        return "Pod not ready"

    tutils.assertEventually(podChecker, 1, 60)
    # return IP
    s = k8s_api.read_namespaced_pod_status(name, "default")
    return s.status.pod_ip

# To create a CRD, create a yaml spec file named yamls/<crdname>.yaml
def createCRD(plural, name):
    crd_api = client.CustomObjectsApi(k8s_client)
    crd_name = ""
    with open(path.abspath(nameToYaml(name))) as f:
        crd_obj = yaml.load(f)
        crd_api.create_namespaced_custom_object("aci.aw", "v1", "kube-system", plural, crd_obj)
        crd_name = crd_obj['metadata']['name']

    # check contract is ready
    def crdChecker():
        resp = crd_api.get_namespaced_custom_object("aci.aw", "v1", "kube-system", plural, crd_name)
        if 'spec' in resp or 'status' in resp:
            return ""
        return "CRD {}/{} not created".format(plural, crd_name)

    tutils.assertEventually(crdChecker, 1, 60)

def replaceCRD(plural, name, new_file):
    crd_api = client.CustomObjectsApi(k8s_client)
    orig_obj = crd_api.get_namespaced_custom_object("aci.aw", "v1", "kube-system", plural, name)

    print(orig_obj)
    with open(path.abspath(nameToYaml(new_file))) as f:
        crd_obj = yaml.load(f)
        crd_obj['metadata']['resourceVersion'] = orig_obj['metadata']['resourceVersion']
        crd_api.replace_namespaced_custom_object("aci.aw", "v1", "kube-system", plural, name, crd_obj)

def deleteCRD(plural, name):
    crd_api = client.CustomObjectsApi(k8s_client)
    body = client.V1DeleteOptions()
    crd_api.delete_namespaced_custom_object("aci.aw", "v1", "kube-system", plural, name, body)

class TestExtPol(object):
    def test_policy(object):
        tutils.tcLog("Verify GW flows are present")
        tutils.checkGwFlows("11.3.0.1")
        tutils.tcLog("Setup nettools")
        tutils.setupNettools()
        tutils.tcLog("Setup contracts, epgs and external EP")
        v1 = client.CoreV1Api()
        createCRD("contracts", "tcp-53")
        createCRD("contracts", "icmp")
        createCRD("epgs", "epg-c-icmp-dns")
        createCRD("epgs", "epg-ext-icmp-dns")
        createCRD("podifs", "ep")
        # pod in epg-c
        podIP = createPod("pod-c")

        tutils.tcLog("Verify contracts are present")
        contractsToVerify = ["GbpeL24Classifier/tcp-53", "GbpeL24Classifier/icmp"]
        def contractChecker():
            resp = tutils.verifyAgentContracts(contractsToVerify, True)
            if resp == "":
                print("{} present".format(contractsToVerify))
            else:
                print(resp)

            return resp

        tutils.assertEventually(contractChecker, 1, 10)

        tutils.tcLog("Verify ep's are present")
        epIPs = [podIP, "8.8.8.0"]
        def epChecker():
            res = tutils.verifyAgentEPs(epIPs)
            if res == "":
                print("{} present".format(epIPs))
            else:
                print(res)

            return res
        tutils.assertEventually(epChecker, 1, 10)
        tutils.tcLog("Setup node routing for external access")
        tutils.setupNodeRouting("pod-c", "test-node1", "8.8.8.8")
        tutils.tcLog("Verify icmp access to external IP")
        tutils.verifyPing("pod-c", "default", "8.8.8.8")
        tutils.tcLog("Verify tcp 53 access to external IP")
        tutils.verifyTCP("pod-c", "default", "8.8.8.8", "53")

        tutils.tcLog("Change epg-c to consume only dns")
        replaceCRD("epgs", "epg-c", "epg-c-dns")
        sleep(1)
        tutils.tcLog("Verify icmp failure to external IP")
        tutils.verifyPing("pod-c", "default", "8.8.8.8", False)
        tutils.tcLog("Verify tcp 53 access to external IP")
        tutils.verifyTCP("pod-c", "default", "8.8.8.8", "53")

        tutils.tcLog("Change epg-ext to allow only icmp")
        replaceCRD("epgs", "epg-ext", "epg-ext-icmp")
        sleep(1)
        tutils.tcLog("Verify dns failure to external IP")
        tutils.verifyTCP("pod-c", "default", "8.8.8.8", "53", False)
        tutils.verifyPing("pod-c", "default", "8.8.8.8", False)

        tutils.tcLog("Change epg-ext to allow icmp and dns")
        replaceCRD("epgs", "epg-ext", "epg-ext-icmp-dns")
        tutils.tcLog("Verify tcp 53 access to external IP")
        tutils.verifyTCP("pod-c", "default", "8.8.8.8", "53")
        tutils.tcLog("Verify icmp failure to external IP")
        tutils.verifyPing("pod-c", "default", "8.8.8.8", False)

        tutils.tcLog("Change epg-c to consume nothing")
        replaceCRD("epgs", "epg-c", "epg-c-deny")
        tutils.tcLog("Verify icmp failure to external IP")
        tutils.verifyPing("pod-c", "default", "8.8.8.8", False)
        tutils.tcLog("Verify dns failure to external IP")
        tutils.verifyTCP("pod-c", "default", "8.8.8.8", "53", False)

        tutils.tcLog("Change epg-c to allow icmp and dns")
        replaceCRD("epgs", "epg-c", "epg-c-icmp-dns")
        tutils.tcLog("Verify icmp access to external IP")
        tutils.verifyPing("pod-c", "default", "8.8.8.8")
        tutils.tcLog("Verify tcp 53 access to external IP")
        tutils.verifyTCP("pod-c", "default", "8.8.8.8", "53")

        tutils.tcLog("Delete the external ep")
        deleteCRD("podifs", "extnet-dns")

        def epDelChecker():
            res = tutils.verifyAgentEPs(["8.8.8.0"])
            if res == "":
                print("still present")
                return "still present"
            return ""

        tutils.tcLog("Verify external ep removed")
        tutils.assertEventually(epDelChecker, 1, 10)
        tutils.tcLog("Verify icmp failure to external IP")
        tutils.verifyPing("pod-c", "default", "8.8.8.8", False)
        tutils.tcLog("Verify dns failure to external IP")
        tutils.verifyTCP("pod-c", "default", "8.8.8.8", "53", False)

        tutils.setupNodeRouting("pod-c", "test-node1", "8.8.8.8", True)
        tutils.deletePod("default", "pod-c")
        deleteCRD("contracts", "tcp-53")
        deleteCRD("contracts", "icmp")
        deleteCRD("epgs", "epg-c")
        deleteCRD("epgs", "epg-ext")


def partition(list, s, t):
    temp = list[s]
    while s < t:
        while s<t and temp<=list[t]:
            t -= 1
        list[s] = list[t]
        while s<t and temp>=list[s]:
            s += 1
        list[t] = list[s]
    list[s] = temp
    return s

def quicksort(list, s, t):
    if s >= t:
        return list
    else:
        i = partition(list, s, t)
        quicksort(list, s, i-1)
        quicksort(list, i+1, t)
    return list
#print(quicksort([3,2,1,4],0,3))
nums = [1,2,3,4,5]
print(nums[0:len(nums)-1])
print(nums[1:len(nums)])


# importação de bibliotecas
import pandas as pd
import seaborn as sns

# Criação do dataset com os dados do arquivo .csv
data = pd.read_csv('gasolina.csv')

# Criação do gráfico
grafico = sns.lineplot(data, x="dia", y="venda")
grafico.set(title="Preço da gasolina 1 a 10 de Julho 2021",xlabel="Dia", ylabel="Preço")

# Armazenamento da figura gerada
fig = grafico.get_figure()
fig.savefig('gasolina.png', dpi=250)


from app.users import bp as api
from app.models import User, Teacher, Student
from flask import jsonify, request
from app import db
from app.emails.templates import send_teacher_registration_email

@api.route('/users', methods=['GET'])
def get_all_users():
    return jsonify([u.json_response() for u in User.query.all()]), 200

@api.route('/users/<int:id>', methods=['GET'])
def get_user(id):
    user = User.query.get_or_404(id)
    return jsonify(user.json_response()), 200

@api.route('/teachers', methods=['GET'])
def get_all_teachers():
    return jsonify([t.json_response() for t in User.query.filter_by(isTeacher=True).all()])

@api.route('/users/teachers/register', methods=['POST'])
def init_teacher():
    data = request.get_json()

    teacher_data = {
        github: data.get('github', None),
        subject: data['subject'],
        link_to_resume: data.get('resume', None)
    }

    user_data = {
        first: data['first'],
        last: data['last'],
        email: data['email'],
        location: data['location']
    }

    user = User(**user_data)
    teacher = Teacher(**teacher_data)
    user.set_password(str(os.urandom(24))) #set random password for now that user will not be able to guess
    user.teacher = teacher
    db.session.add_all([user, teacher])

    db.session.commit()

    msg, token, status = send_teacher_registration_email(user)

    if status == 200:
        return jsonify({
          'Initial registration complete'
        }), status


# acro.py
# This program gives out an acronym

def acro():
    print("This program creates an acronym out of your inputted words!\n")
    w = input("Please enter words here: ")
    sw = w.split()

    acro = ""
    for x in sw:
        acro = acro + x[0]

    print("\nHere is your acronym: " + acro.upper())

acro()


# Script to pull the timing violations out of atomic_<app> tests.
# Those data live over in culpeo_measurements/runtime_tests

import pandas as pd
import sys
import matplotlib
import numpy as np
#matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import re
import glob
import pickle as pkl
from matplotlib.ticker import AutoMinorLocator

EVT_LEN = .5
DEADLINE = 4.0
TIME_INDEX = 9

if __name__ == "__main__":
  DEADLINE = float(sys.argv[1])
  out_name = sys.argv[2]
  num_files = len(sys.argv) - 2
  i = 3
  all_files = []
  lost_vals = [] # Fraction of total
  delay_vals = []
  while i < num_files + 2:
    all_files.append(sys.argv[i])
    i += 1
  for filename in all_files:
    #print("filename:",filename)
    try:
      df = pd.read_csv(filename, mangle_dupe_cols=True,
           dtype=np.float64, skipinitialspace=True)#skiprows=[0])
    except:
      df = pd.read_csv(filename, mangle_dupe_cols=True,
           dtype=np.float64, skipinitialspace=True,skiprows=[0])

    vals = df.values
    # Only look at time
    times = vals[:,TIME_INDEX:TIME_INDEX+2]
    times = times[times[:,1] == 1]
    times = times[:,0]
    #print(times)
    total = 1
    lost = 0
    last = times[0]
    first = times[0]
    second = times[1]
    violations = []
    for i in range(1,len(times)):
      # Assume we already have the first
      if times[i] < first + EVT_LEN:
        second = times[i]
        last = first
        total += 1
      else:
        # We're on the first
        first = times[i]
      if (first > last + DEADLINE):
        #print("Violation!",first,last,i)
        violations.append(first-last)
        lost += (first-last)/DEADLINE
    if len(violations) > 0:
      vio_avg = np.average(violations)
    else:
      vio_avg = 0
    print(len(violations),total,vio_avg,lost)
    lost_vals.append(lost/total)
    delay_vals.append(vio_avg)
    print("lost:",lost/total,"delay:",vio_avg)
  results = {'lost':np.average(lost_vals),'lost_std':np.std(lost_vals),\
  'delay':np.average(delay_vals),'delay_std':np.std(delay_vals)}
  pkl.dump(results,open(out_name,'wb'))
    #print("Total:",len(violations),"/",len(times))

    #print("Average:",np.average(violations))


from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.select import Select
import time

#any drop down not having select tag,like jquery/angular/react drop down

def selecrdrp(options_list,value):
    if not value[0]=='all':

        for ele in drop_down_list:
            print(ele.text)
            for i in range(len(value)):
                if ele.text==value[i]:
                    ele.click()
                    break

    else:
        try:
            for ele in options_list:
                ele.click()
        except Exception as e:
            print(e)

driver=webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.jqueryscript.net/demo/Drop-Down-Combo-Tree/")
driver.maximize_window()
time.sleep(2)

driver.find_element(By.ID,"justAnInputBox").click()
time.sleep(3)
drop_down_list=driver.find_elements(By.CSS_SELECTOR,"span.comboTreeItemTitle")
#value_list=['choice 1','choice 2','choice 3','choice 6 2 1']

#value_list=['choice 1']
value_list=['all']
#selecrdrp(drop_down_list,'choice 6 2 1')
selecrdrp(drop_down_list,value_list)

'''for ele in drop_down_list:
    print(ele.text)
    if ele.text=='choice 6 2 3':
        ele.click()
        break'''


#!/bin/bash/python
# Author: Ragy Haddad <ragy@deepbiometherapeutics.com>
import sys,os
import pandas as pd
import numpy as np
from tokenizer import Tokenizer
from torch.utils.data import Dataset as torchDataset
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader as torchDataLoader
from torch.nn.utils.rnn import pad_sequence
import torch
from rdkit import Chem
# Dataset functionality for custom batch loading
class Dataset:
    def __init__(self,input_table,sep='\t'):
        self.df = pd.read_csv(input_table,sep=sep)

        self.t = Tokenizer()
        if 'SMILES' in self.df.columns:
            self.smiles = self.df['SMILES']
        elif 'smiles' in self.df.columns:
            self.smiles = self.df['smiles']
        elif 'Smiles' in self.df.columns:
            self.smiles = self.df['Smiles']
        else:
            self.smiles = self.df.iloc[:,0] # Column Zero is smiles if none of the above

        self.cans = [Chem.MolToSmiles(Chem.MolFromSmiles(smi),True) for smi in self.smiles]
        self.smiles = pd.DataFrame(self.cans).iloc[:,0]
        # print(self.smiles)
        # exit()
    # Format Batch
    def format_df(self,input_df,return_labels=False,shifted_targets=True,padding=False,label_encoding=False,return_length=True):
        data = None
        if shifted_targets and label_encoding == False:
            src = [self.t.smiles_to_2d(r,padding=padding,add_start_token=True) for r in input_df]
            trg = [self.t.smiles_to_2d(r,padding=padding,add_start_token=False) for r in input_df]
        if shifted_targets and label_encoding:
            src = [self.t.smiles_to_int(r,padding=padding,add_start_token=True) for r in input_df]
            trg = [self.t.smiles_to_int(r,padding=padding,add_start_token=False) for r in input_df]
        if return_labels:
            labels = [self.t.smiles_to_int(r,padding=padding,add_start_token=False) for r in input_df] # Labels do not have starting token
            src,trg,labels = np.array(src),np.array(trg),np.array(labels)
            data = (src,trg,labels)
        else:
            src,trg = np.array(src),np.array(trg)
            data = (src,trg)
        if return_length:
            l_src = np.array([len(x) + 2 for x in input_df]) # Add 2 to lengths for sos_token and end_token
            l_trg = np.array([len(x) + 1 for x in input_df]) # Add 1 to lengths for eos_token
            data = data + (l_src,l_trg)
        return data
    # Load Batches
    def load_batches(self,batch_size,epoch_shuffle=True,padding=False,return_labels=False,label_encoding=False,shifted_targets=True,return_length=False):
        if epoch_shuffle:
            self.smiles = self.smiles.sample(frac=1)
        i = 0
        while i < len(self.df.index.values):
            smiles = self.smiles.iloc[i : i + batch_size]

            data = self.format_df(smiles,padding=padding,return_labels=return_labels,label_encoding=label_encoding,return_length=return_length)
            i += batch_size
            yield data

    def num_smiles(self):
        return len(self.smiles)


from socket import socket, AF_INET, SOCK_STREAM
#AF_INET - IP протокол
#SOCK_STREAM - TCP - гарантирует доставку
receiver = socket(AF_INET, SOCK_STREAM) #ПОЛУЧАТЕЛЬ
#'' - IP адрес, 90 - порт
receiver.bind (('0.0.0.0', 90) )
receiver.listen(1)

receiver, addr = receiver.accept()  # Готов к принятию соединения

print(f"Установлено соединение с адреса {addr}")
#recv(кол-во байт) - принимаем send
data = receiver.recv(4096)
print(f"Приемник принял данные {data.decode()}")

receiver.close()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:

    # def traverse()

    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:

        if not root:
            return []

        res = []

        queue = []
        queue.append(root)

        levelNo = 0
        while queue:
            currLevel = []
            size = len(queue)

            for i in range(size):
                currNode = queue.pop(0)
                if currNode.left is not None:
                    queue.append(currNode.left)
                if currNode.right is not None:
                    queue.append(currNode.right)
                currLevel.append(currNode.val)
            if levelNo%2 != 0: res.append(currLevel[::-1])
            else: res.append(currLevel)
            levelNo += 1

        return res


"""Dual Attention Network"""
import torch
import torch.nn as nn
import torch.nn.functional as F

from .segbase import SegBaseModel

__all__ = ['DANet', 'get_danet', 'get_danet_resnet50_citys',
           'get_danet_resnet101_citys', 'get_danet_resnet152_citys']

class DANet(SegBaseModel):
    r"""Pyramid Scene Parsing Network

    Parameters
    ----------
    nclass : int
        Number of categories for the training dataset.
    backbone : string
        Pre-trained dilated backbone network type (default:'resnet50'; 'resnet50',
        'resnet101' or 'resnet152').
    norm_layer : object
        Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`;
        for Synchronized Cross-GPU BachNormalization).
    aux : bool
        Auxiliary loss.
    Reference:
        Jun Fu, Jing Liu, Haijie Tian, Yong Li, Yongjun Bao, Zhiwei Fang,and Hanqing Lu.
        "Dual Attention Network for Scene Segmentation." *CVPR*, 2019
    """

    def __init__(self, nclass, backbone='resnet50', aux=True, pretrained_base=True, **kwargs):
        super(DANet, self).__init__(nclass, aux, backbone, pretrained_base=pretrained_base, **kwargs)
        self.head = _DAHead(2048, nclass, aux, **kwargs)

        self.__setattr__('exclusive', ['head'])

    def forward(self, x):
        size = x.size()[2:]
        _, _, c3, c4 = self.base_forward(x)
        outputs = []
        x = self.head(c4)
        x0 = F.interpolate(x[0], size, mode='bilinear', align_corners=True)
        outputs.append(x0)

        if self.aux:
            x1 = F.interpolate(x[1], size, mode='bilinear', align_corners=True)
            x2 = F.interpolate(x[2], size, mode='bilinear', align_corners=True)
            outputs.append(x1)
            outputs.append(x2)
        return outputs

class _PositionAttentionModule(nn.Module):
    """ Position attention module"""

    def __init__(self, in_channels, **kwargs):
        super(_PositionAttentionModule, self).__init__()
        self.conv_b = nn.Conv2d(in_channels, in_channels // 8, 1)
        self.conv_c = nn.Conv2d(in_channels, in_channels // 8, 1)
        self.conv_d = nn.Conv2d(in_channels, in_channels, 1)
        self.alpha = nn.Parameter(torch.zeros(1))
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, x):
        batch_size, _, height, width = x.size()
        feat_b = self.conv_b(x).view(batch_size, -1, height * width).permute(0, 2, 1)
        feat_c = self.conv_c(x).view(batch_size, -1, height * width)
        attention_s = self.softmax(torch.bmm(feat_b, feat_c))
        feat_d = self.conv_d(x).view(batch_size, -1, height * width)
        feat_e = torch.bmm(feat_d, attention_s.permute(0, 2, 1)).view(batch_size, -1, height, width)
        out = self.alpha * feat_e + x

        return out

class _ChannelAttentionModule(nn.Module):
    """Channel attention module"""

    def __init__(self, **kwargs):
        super(_ChannelAttentionModule, self).__init__()
        self.beta = nn.Parameter(torch.zeros(1))
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, x):
        batch_size, _, height, width = x.size()
        feat_a = x.view(batch_size, -1, height * width)
        feat_a_transpose = x.view(batch_size, -1, height * width).permute(0, 2, 1)
        attention = torch.bmm(feat_a, feat_a_transpose)
        attention_new = torch.max(attention, dim=-1, keepdim=True)[0].expand_as(attention) - attention
        attention = self.softmax(attention_new)

        feat_e = torch.bmm(attention, feat_a).view(batch_size, -1, height, width)
        out = self.beta * feat_e + x

        return out

class _DAHead(nn.Module):
    def __init__(self, in_channels, nclass, aux=True, norm_layer=nn.BatchNorm2d, norm_kwargs=None, **kwargs):
        super(_DAHead, self).__init__()
        self.aux = aux
        inter_channels = in_channels // 4
        self.conv_p1 = nn.Sequential(
            nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
            norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
            nn.ReLU(True)
        )
        self.conv_c1 = nn.Sequential(
            nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
            norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
            nn.ReLU(True)
        )
        self.pam = _PositionAttentionModule(inter_channels, **kwargs)
        self.cam = _ChannelAttentionModule(**kwargs)
        self.conv_p2 = nn.Sequential(
            nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),
            norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
            nn.ReLU(True)
        )
        self.conv_c2 = nn.Sequential(
            nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),
            norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
            nn.ReLU(True)
        )
        self.out = nn.Sequential(
            nn.Dropout(0.1),
            nn.Conv2d(inter_channels, nclass, 1)
        )
        if aux:
            self.conv_p3 = nn.Sequential(
                nn.Dropout(0.1),
                nn.Conv2d(inter_channels, nclass, 1)
            )
            self.conv_c3 = nn.Sequential(
                nn.Dropout(0.1),
                nn.Conv2d(inter_channels, nclass, 1)
            )

    def forward(self, x):
        feat_p = self.conv_p1(x)
        feat_p = self.pam(feat_p)
        feat_p = self.conv_p2(feat_p)

        feat_c = self.conv_c1(x)
        feat_c = self.cam(feat_c)
        feat_c = self.conv_c2(feat_c)

        feat_fusion = feat_p + feat_c

        outputs = []
        fusion_out = self.out(feat_fusion)
        outputs.append(fusion_out)
        if self.aux:
            p_out = self.conv_p3(feat_p)
            c_out = self.conv_c3(feat_c)
            outputs.append(p_out)
            outputs.append(c_out)

        return tuple(outputs)

def get_danet(dataset='citys', backbone='resnet50', pretrained=False,
              root='~/.torch/models', pretrained_base=True, **kwargs):
    r"""Dual Attention Network

    Parameters
    ----------
    dataset : str, default pascal_voc
        The dataset that model pretrained on. (pascal_voc, ade20k)
    pretrained : bool or str
        Boolean value controls whether to load the default pretrained weights for model.
        String value represents the hashtag for a certain version of pretrained weights.
    root : str, default '~/.torch/models'
        Location for keeping the model parameters.
    pretrained_base : bool or str, default True
        This will load pretrained backbone network, that was trained on ImageNet.
    Examples
    --------
    >>> model = get_danet(dataset='pascal_voc', backbone='resnet50', pretrained=False)
    >>> print(model)
    """
    acronyms = {
        'pascal_voc': 'pascal_voc',
        'pascal_aug': 'pascal_aug',
        'ade20k': 'ade',
        'coco': 'coco',
        'citys': 'citys',
    }
    from ..data.dataloader import datasets
    model = DANet(datasets[dataset].NUM_CLASS, backbone=backbone, pretrained_base=pretrained_base, **kwargs)
    if pretrained:
        from .model_store import get_model_file
        device = torch.device(kwargs['local_rank'])
        model.load_state_dict(torch.load(get_model_file('danet_%s_%s' % (backbone, acronyms[dataset]), root=root),
                              map_location=device))
    return model

def get_danet_resnet50_citys(**kwargs):
    return get_danet('citys', 'resnet50', **kwargs)

def get_danet_resnet101_citys(**kwargs):
    return get_danet('citys', 'resnet101', **kwargs)

def get_danet_resnet152_citys(**kwargs):
    return get_danet('citys', 'resnet152', **kwargs)

if __name__ == '__main__':
    img = torch.randn(2, 3, 480, 480)
    model = get_danet_resnet50_citys()
    outputs = model(img)


"""
New checks can be written in one of the sub modules of this package.
Writing new checks in existing modules they will automatically be picked
up by the script. When adding a new sub module it is important the contents
of the sub module into this one.

.. code-block:: python

    from .animation import *

All checks are sorted in order of occurrence in the source code. This can be
used to make sure certain checks are after others.
"""
import sys
import inspect
from collections import OrderedDict

from .uv import *
from .scene import *
from .rigging import *
from .shaders import *
from .textures import *
from .geometry import *
from .skinning import *
from .modelling import *
from .animation import *
from .renderStats import *
from .renderLayers import *

from .. import collections
from ..utils.qa import QualityAssurance

def getChecks():
    """
    Get all checks available in this module.

    :return: All available error checks
    :rtype: list
    """
    checks = []

    # get quality assurance checks.
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if (
            inspect.isclass(obj)
            and issubclass(obj, QualityAssurance)
            and obj.__name__ != QualityAssurance.__name__
        ):

            checks.append(obj())

    # sort checks based on location in source code.
    checks.sort(
        key=lambda x:
            inspect.getsource(
                inspect.getmodule(x)
            ).find(
                x.__class__.__name__
            )
    )

    return checks

def getChecksFromCollection(collection):
    """
    Get all check based on a collections. The collections are stored in the
    collection module, or custom collections made by the user are saved to
    disk.

    :param str collection:
    :return: Ordered dictionary of checks
    :rtype: OrderedDict
    """
    data = getChecksSplitByCategory()

    categories = getChecksCategories()
    categories = collections.getCollections().get(collection) or categories

    return OrderedDict(
        [
            (category, data.get(category))
            for category in categories
            if data.get(category)
        ]
    )

def getChecksSplitByCategory():
    """
    Get all of the checks and split them based on category as defined in the
    classes themselves.

    :return: All error checks split by category
    :rtype: dict
    """
    data = {}

    for check in getChecks():
        for category in check.categories:
            if category not in data.keys():
                data[category] = []

            data[category].append(check)

    return data

def getChecksCategories():
    """
    Get a list of all the categories used.

    :return: Category list
    :rtype: list
    """
    return getChecksSplitByCategory().keys()


from pathlib import Path
from bs4 import BeautifulSoup
import requests
import time
import asyncio
from concurrent.futures import ProcessPoolExecutor
from functools import partial

def get_term_names(start, end):
    return [str(int(i/3)) + "0" + str((int(i) % 3) + 1) for i in range(start*3, end*3)]

def get_term_subjects(term):
    return [option.get("value") for option in BeautifulSoup(requests.post(
        "https://suis.sabanciuniv.edu/prod/bwckctlg.p_disp_cat_term_date",
        {
            "call_proc_in": "bwckctlg.p_disp_dyn_ctlg",
            "cat_term_in": term
        }
    ).content, "html.parser").find("select", attrs={"name": "sel_subj"}).find_all("option")]

def get_term_catalog(term):
    return requests.post(
        "https://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses",
        {
            "term_in": term,
            "call_proc_in": "bwckctlg.p_disp_dyn_ctlg",
            "sel_crse_start": "",
            "sel_crse_end": "",
            "sel_title": "",
            "sel_levl": "",
            "sel_schd": "",
            "sel_coll": "",
            "sel_divs": "",
            "sel_dept": "",
            "sel_to_cred": "",
            "sel_from_cred": "",
            "sel_attr": "",
            "sel_subj": ["dummy"] + get_term_subjects(term),
        }).content

def get_and_save(term):
    print("starting", term)
    chrono = time.perf_counter()
    catalog = get_term_catalog(term)
    print("got", term, "in", str(time.perf_counter() - chrono), "seconds")

    path = Path(__file__).parent / "../Catalogs/Raws" / (term + ".html")
    with path.open(mode="wb+") as f:
        f.write(catalog)

        return True

async def main():
    with ProcessPoolExecutor(3) as pool:
        loop = asyncio.get_running_loop()
        runners = [loop.run_in_executor(pool, partial(get_and_save, term)) for term in get_term_names(int(input("start year: ")), int(input("end year (excluded): ")))]
        crs = asyncio.gather(*runners)

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


from typing import List

def merge_sort(arl: List, sort_type: str):
    '''
    Sortiramo listu s elemtnima tipa int ili float koristeći merge sort algoritam.

    Args:
        arl (List): Lista koju želimo sortirati.
        sort_type (str): Tip sortiranja ("asc" za uzlazno ili "desc" za silazno).

    Returns:
        List: Sortirana lista.
    '''
    assert sort_type in ["asc", "desc"], "Krivi tip sortiranja, mora biti 'asc' ili 'desc'!"

    if len(arl) == 1:
        return arl
    else:
        left, right = split_in_middle(arl)
        left = merge_sort(left, sort_type)
        right = merge_sort(right, sort_type)

    return merge(left, right, sort_type)

def merge(left: List, right: List, sort_type: str):
    '''
    Spaja dvije sortirane liste u jednu sortiranu listu.

    Args:
        left (List): Lijeva sortirana lista.
        right (List): Desna sortirana lista.
        sort_type (str): Tip sortiranja ("asc" za uzlazno ili "desc" za silazno).

    Returns:
        List: Spojene sortirane liste.
    '''
    merged = []
    lip, rip = 0, 0

    while lip < len(left) and rip < len(right):
        if sort_type == "asc":
            if left[lip] < right[rip]:
                merged.append(left[lip])
                lip += 1
            else:
                merged.append(right[rip])
                rip += 1
        else:
            if left[lip] > right[rip]:
                merged.append(left[lip])
                lip += 1
            else:
                merged.append(right[rip])
                rip += 1

    merged.extend(left[lip:])
    merged.extend(right[rip:])

    return merged

def split_in_middle(ar: List):
    '''
    Dijeli listu na dva dijela.

    Args:
        ar (List): Lista koju želimo podijeliti.

    Returns:
        Tuple: Tuple s dvije liste.
    '''
    middle = len(ar) // 2
    left = ar[:middle]
    right = ar[middle:]

    return left, right


#The goal of this project is to be able to edit and simulate a solar system. This system should be custom and creatable.
#Good luck Jake, you're going to need it...
import pygame as p
import random as r
import simclasses as s
import sys
p.init()
buttons = []

#This function creates a screen for the simulation to use.
def create_screen(width,height):
    screen_init = p.display.set_mode(size=(width,height))
    p.display.set_caption("Space Simulator")
    return screen_init

def button_pressed():
    print("Button Pressed")

def add_star():
    new_star = s.Star(game_screen)
    new_star.get_star_attributes()
    new_star.create()

def add_planet():
    new_planet = s.Planet(game_screen)
    new_planet.get_planet_attribute()
    new_planet.create()

#Here is where the simulation is run

#Initialize the screen
game_screen = create_screen(750,750)
game_screen.fill((0,0,0))

running = True
while running:
    mouse = p.mouse.get_pos()
    button1 = s.Button(game_screen,(10,600), 150, 30, button_list=buttons, on_click_function=add_star,one_press=True, text="Add Star")
    button2 = s.Button(game_screen,(10,650), 185, 30, button_list=buttons, on_click_function=add_planet,one_press=True, text="Add Planet")
    button3 = s.Button(game_screen,(10,700), 75, 30,button_list=buttons, on_click_function=quit,one_press=True,text="Quit")
    #Searchiong through events to set certain conditions
    for event in p.event.get():
        if event.type == p.QUIT: #If the x is hit on the screen, quit the program.
            running = False
        if event.type == p.MOUSEBUTTONUP:
            s.pressed = False
        if event.type == p.MOUSEBUTTONDOWN:
            pass

    #Searching through the objects to see if they are being executed
    for obj in buttons:
        obj.process()

    p.display.update()


from pycomplex.complex.cubical import *
from pycomplex.math import linalg
from pycomplex.synthetic import n_cube, n_cube_grid

def test_regular_2():
    complex = n_cube(3)
    dp = complex.dual_position

    for p in dp:
        print()
        print(p.shape)
        print(p)

def test_quad_3(show_plot):
    """Test the construction and subdivision of a domain with three connected quads"""
    vertices = np.indices((3, 3))
    vertices = vertices.reshape(2, -1).T[:-1]
    quads = [
        [[0, 1],
         [3, 4]],
        [[1, 2],
         [4, 5]],
        [[3, 4],
         [6, 7]],
    ]

    from pycomplex.complex.cubical import ComplexCubical2Euclidian2
    complex = ComplexCubical2Euclidian2(vertices=vertices, cubes=quads)

    for i in range(1):
        complex = complex.subdivide_cubical()
    complex.plot(plot_dual=True)
    show_plot()

def test_2cube_3space(show_plot):
    """Test the surface of a cube embedded in 3-space"""
    quads = n_cube(3, centering=True).boundary.as_23()
    for i in range(3):
        quads = quads.subdivide_cubical(smooth=True)

    quads = quads.transform(linalg.orthonormalize(np.random.randn(3, 3)))
    quads.plot()

    quads.subdivide_simplicial().as_3().plot_3d(plot_vertices=False, backface_culling=True, plot_dual=False)
    show_plot()

def test_cube(show_plot):
    """Test 3d cube embedded in 3-space"""
    cube = n_cube(3)
    cube = cube.transform(linalg.orthonormalize(np.random.randn(3, 3)))

    cube.plot()
    for i in range(2):
        cube = cube.subdivide_cubical()
    cube.boundary.plot(plot_dual=True)

    show_plot()

def test_triangulated_cube(show_plot):
    """This produces some funky patterns"""
    cube = n_cube(3)
    # cube = cube.transform(linalg.orthonormalize(np.random.randn(3, 3)))

    surface = cube.boundary.as_23()
    # surface = surface.subdivide(smooth=True)
    surface = surface.subdivide_simplicial().smooth()
    surface = surface.subdivide_cubical()
    # surface.plot_3d(backface_culling=True)

    # map back to quads again
    surface = surface.subdivide_cubical().smooth()

    surface = surface.subdivide_cubical().smooth()
    # surface = surface.subdivide()

    assert surface.topology.is_oriented
    surface.plot(plot_dual=False)
    show_plot()

def test_cube_grid_2(show_plot):
    """Simple test of a regular 2d grid"""
    grid = n_cube_grid((2, 3))
    grid.plot()
    show_plot()

def test_cube_grid_3(show_plot):
    """Simple test of a regular 3d grid"""
    grid = n_cube_grid((1, 2, 3))
    grid = grid.transform(linalg.orthonormalize(np.random.randn(3, 3)))
    assert grid.topology.is_oriented
    grid.plot(plot_dual=True)
    show_plot()

def test_product_2(show_plot):
    """Test creating a 2d grid as product of 2 1d grids"""
    d1 = n_cube_grid((3,))
    d2 = n_cube_grid((5,))

    grid = d1.product(d2)
    grid.plot()
    show_plot()

def test_product_2_1(show_plot):
    """Test creating a 3d grid as product of 1d and 2d grids"""
    d1 = n_cube_grid((3,))
    d2 = n_cube_grid((2, 4))

    grid = d1.product(d2)

    assert grid.topology.is_oriented
    assert grid.boundary.topology.is_oriented

    grid = grid.transform(linalg.orthonormalize(np.random.randn(3, 3)))
    grid.plot()
    show_plot()

def test_n_cube(show_plot):
    """Test cube grids and their subdivisions in a range of dimensions"""
    for n_dim in [2, 3, 4, 5, 6]:
        cube = n_cube(n_dim).subdivide_cubical()

        assert cube.topology.is_oriented
        # assert cube.topology.is_connected
        assert not cube.topology.is_closed
        # assert cube.topology.boundary.is_connected
        assert cube.topology.boundary.is_oriented
        assert cube.topology.boundary.is_closed

        np.random.seed(1)
        cube = cube.transform(linalg.orthonormalize(np.random.randn(n_dim, n_dim)))
        cube.plot(plot_dual=True)
        show_plot()

def test_transfer(show_plot):
    """Test the direct transfer matrices """
    n_dim = 2
    cube = n_cube(n_dim)
    cube = cube.transform(linalg.orthonormalize(np.random.randn(n_dim, n_dim)))

    hierarchy = [cube]
    for i in range(2):
        hierarchy.append(hierarchy[-1].subdivide_cubical())

    if True:
        # test that directionality is inherited as expected
        hierarchy[-2].plot(plot_dual=True, plot_arrow=True)
        hierarchy[-1].plot(plot_dual=True, plot_arrow=True)
        show_plot()

    DT = hierarchy[-1].topology.dual.transfer_matrices

    # little check
    for res, c, f in zip(DT, hierarchy[-2].topology.dual.n_elements, hierarchy[-1].topology.dual.n_elements):
        assert res.shape == (f, c)

def test_multigrid():
    """Test the full multigrid transfer operators"""
    # FIXME: test that null space vectors are preserved in a roundtrip
    # FIXME: not sure this makes sense outside of a regular grid context
    n_dim = 2
    cube = n_cube(n_dim)
    cube = cube.transform(linalg.orthonormalize(np.random.randn(n_dim, n_dim)))

    hierarchy = [cube]
    for i in range(2):
        hierarchy.append(hierarchy[-1].subdivide_cubical())

    T = hierarchy[-1].multigrid_transfers
    q = T[0].todense()
    print(q)
    z = T[-1].todense()
    print()


from sys import stdin
n = input()
for i in range(0, n):
	line = stdin.readline()
	a, b = [float(x) for x in stdin.readline().split()]
	computers = [int(x) for x in stdin.readline().split()]
	economics = [int(x) for x in stdin.readline().split()]
	avg_computer = sum(computers)/a
	avg_economics = sum(economics)/b
	c = 0
	for student in computers:
		if avg_economics < student < avg_computer:
			c += 1
	print(c)