import os
from collections import defaultdict

def pretty_print(img_dict: dict):
	mini = min(img_dict.keys(), key=lambda x: x[0])[0]
	maxi = max(img_dict.keys(), key=lambda x: x[0])[0]
	minj = min(img_dict.keys(), key=lambda x: x[1])[1]
	maxj = max(img_dict.keys(), key=lambda x: x[1])[1]
	for i in range(mini, maxi + 1):
		for j in range(minj, maxj + 1):
			print(f"{'#' if img_dict[(i,j)]==1 else '.'}", end='')
		print()

cwd = os.path.dirname(os.path.abspath(__file__))
with open(f"{cwd}/input.txt") as f:
	enhance_str = f.readline().strip()
	enhance = [1 if c == '#' else 0 for c in enhance_str]
	img_str = [l for l in f.read().strip().splitlines()]
img_dict = defaultdict(int)
img_dict_odd = defaultdict(lambda: 1)
for i, l in enumerate(img_str):
	for j, c in enumerate(l):
		if c == '#':
			img_dict[(i, j)] = 1
			img_dict_odd[(i, j)] = 1
		else:
			img_dict[(i, j)] = 0
			img_dict_odd[(i, j)] = 0

for n in range(50):
	if n == 2:
		print(f"p1: {sum(img_dict.values())}")
	mini = min(img_dict.keys(), key=lambda x: x[0])[0]
	maxi = max(img_dict.keys(), key=lambda x: x[0])[0]
	minj = min(img_dict.keys(), key=lambda x: x[1])[1]
	maxj = max(img_dict.keys(), key=lambda x: x[1])[1]
	updates = dict()
	for i in range(mini - 1, maxi + 2):
		for j in range(minj - 1, maxj + 2):
			binary_str = []
			for i2 in range(-1, 2):
				for j2 in range(-1, 2):
					if enhance[0] == 1 and n % 2 != 0:
						binary_str.append(str(img_dict_odd[(i + i2, j + j2)]))
					else:
						binary_str.append(str(img_dict[(i + i2, j + j2)]))
			binary = int(''.join(binary_str), 2)
			updates[(i, j)] = enhance[binary]
	for k, v in updates.items():
		img_dict[k] = v
		img_dict_odd[k] = v

print(f"p2: {sum(img_dict.values())}")


from aocutils import get_lines

def problem1():
    lines = get_lines(3)
    bits = len(lines[0])
    nums = [int(num, 2) for num in lines]
    gamma = 0
    for i in range(bits - 1, -1, -1):
        gamma = (gamma << 1) + int(sum([(num >> i) % 2 for num in nums]) > (len(nums) / 2))
    return gamma * (~gamma & (1 << bits) - 1)

def problem2():
    lines = get_lines(3)
    bits = len(lines[0])
    o2 = [int(num, 2) for num in lines]
    co2 = [int(num, 2) for num in lines]
    i = bits - 1
    while len(o2) > 1:
        most = int(sum([(num >> i) % 2 for num in o2]) >= (len(o2) / 2))
        o2 = [num for num in o2 if (num >> i) % 2 ^ most]
        i -= 1
    i = bits - 1
    while len(co2) > 1:
        least = int(sum([(num >> i) % 2 for num in co2]) < (len(co2) / 2))
        co2 = [num for num in co2 if (num >> i) % 2 ^ least]
        i -= 1
    return o2[0] * co2[0]


import numpy as np
from numba import njit

# @njit
def main():
    n = int(input())

    min_r, min_c = 1e10, 1e10
    max_r, max_c = -1, -1

    r_list = []
    c_list = []
    r_append = r_list.append
    c_append = c_list.append
    for _ in range(n):
        c, r = [int(v) for v in input().split()]
        if c < min_c:
            min_c = c
        if max_c < c:
            max_c = c
        if r < min_r:
            min_r = r
        if max_r < r:
            max_r = r
        r_append(r)
        c_append(c)

    # 必要ない範囲（0のみの所）は除外する
    width = max_c - min_c + 1
    height = max_r - min_r + 1
    grid_data = np.zeros((height, width))
    for list_id in range(n):
        r = r_list[list_id]
        c = c_list[list_id]

        grid_data[r - min_r, c - min_c] = 1

    print(grid_data)

    for r in range(height):
        check_row = np.sum(grid_data[r])
        if check_row < 2:
            grid_data[r] = 0

    print(grid_data)

    for c in range(width):
        check_col = np.sum(grid_data[:, c])
        if check_col < 2:
            grid_data[:, c] = 0

    print(grid_data)

    # 座標圧縮して余白を消したほうが良さそう。

    # exit()

    row_width_list = [None] * height
    for r in range(height):
        check_row = 0
        min_c = height * 2
        max_c = -1
        for c in range(width):
            if grid_data[r, c] == 1:
                check_row = check_row + 1
                if c < min_c:
                    min_c = c
                if max_c < c:
                    max_c = c

        if check_row >= 2:
            row_width_list[r] = (min_c, max_c)

    print(row_width_list)

    pre_row_width = None
    split_id_list = []
    for r_id, row_width in enumerate(row_width_list):
        if pre_row_width != row_width:
            split_id_list.append(r_id)
        pre_row_width = row_width

    print(split_id_list)

if __name__ == "__main__":
    main()


import smtplib
import email.mime.multipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import tkinter
from tkinter import *
import tkinter.messagebox as box
from tkinter import ttk

global ephone,eage,eaddress,ename

#===================================================Send Email=======================================

def SendEmail():
    v1 = ephone.get()
    v2 = ename.get()
    v3 = eaddress.get()
    v4 = eage.get()
    if (ephone.get()!="" and ename.get()!="" and eaddress.get()!="" and eage.get!="" and v1.isdigit()==True and
            v2.isalpha()==True and v4.isdigit()==True):
        if (len(v1)<=12 or len(v1)==10 and len(v1!=11)):
        #Create Email Details
            msgMultiPart=email.mime.multipart.MIMEMultipart()
            msgMultiPart["subject"]="Appointment Notification"
            msgMultiPart["From"]="nvnpunia001@gmail.com"
            msgMultiPart["To"]=etxtTo.get()
            #Create Body may be plain or html
            body="Dear Sir I want a appointment, My name is "+ename.get()+"\n"+ "My age is "+eage.get()+"\n"+"My Phone Number is "+ephone.get()+"\n"+"I m from "+eaddress.get()
            msgMultiPart.attach(MIMEText(body,'plain'))

            smtpobj=smtplib.SMTP(host="smtp.gmail.com",port=587)

            smtpobj.starttls()
            smtpobj.login("nvnpunia001@gmail.com","8222050457")
            smtpobj.sendmail("nvnpunia001@gmail.com",etxtTo.get(),msgMultiPart.as_string())
            box.showinfo("Info","Email send successfully")
            root.destroy()
            print("Sucess")
        else:
            box.showerror("Error","Please enter the valid phone number")
    else:
        box.showerror("Warning","Please fill all the required entry in correct way")
#=========================================Back function for doctor list================================

def back():
    root.destroy()
    import Nav4_Doctorlist_1 as dc_1
    dc_1.doctor_appointment("please wait, Opening list of best doctors for breast cancer treatment")

#=================================================================================================================

def GMIL():
    global root
    global To
    global etxtTo,e,ename,eaddress,eage,ephone
    root=Tk()
    root.title("Gmail")
    root.config(bg="pink")
    root.state('z')

    #=================================================Frame============================================================

#    Tops0 = Frame(root, width=1380, height=1000, bg="white", bd=0, relief="raise")
#    Tops0.place(x=0, y=0)
    Tops = Frame(root, width=1400, height=90, bg="blue", relief="raise")
    Tops.pack(side=TOP)

    #======================================================Variable==================================================

    To=StringVar()
    Name=StringVar()
    Age=StringVar()
    Phone=StringVar()
    Address=StringVar()

    #=========================================================Labels========================================================

    lblFrom = Label(Tops, text="From", font=('aria', 16, 'bold'),bg="blue", fg="black", bd=20).grid(row=0, column=0)
    lblTo = Label(Tops, text="To", font=('aria', 16, 'bold'),height=2,bg="blue", fg="black", bd=20).grid(row=1, column=0)
    lblFrom1 = Label(Tops, text="nvnpunia001@gmail.com", font=('aria', 16, 'bold'),bg="blue" ,bd=16, width=30, justify='left')
    lblFrom1.grid(row=0, column=1)

    lblName = Label(Tops, text="Name", font=('aria', 16, 'bold'), bg="blue", fg="black", bd=20).grid(row=2, column=0)
    lblFrom = Label(Tops, text="Age", font=('aria', 16, 'bold'), bg="blue", fg="black", bd=20).grid(row=3, column=0)
    lblFrom = Label(Tops, text="Phone No.", font=('aria', 16, 'bold'), bg="blue", fg="black", bd=20).grid(row=4, column=0)
    lblFrom = Label(Tops, text="Address", font=('aria', 16, 'bold'), bg="blue", fg="black", bd=20).grid(row=5, column=0)

    #======================================================Text Part=======================================================
    etxtTo = Entry(Tops,textvariable=To, font=('aria', 16, 'bold'), width=30, justify='left')
    etxtTo.grid(row=1, column=1)
    ename = Entry(Tops, textvariable=Name, font=('aria', 16, 'bold'), width=30, justify='left')
    ename.grid(pady=20,row=2, column=1)
    eage = Entry(Tops, textvariable=Age, font=('aria', 16, 'bold'), width=30, justify='left')
    eage.grid(pady=20,row=3, column=1)
    ephone = Entry(Tops, textvariable=Phone, font=('aria', 16, 'bold'), width=30, justify='left')
    ephone.grid(pady=20,row=4, column=1)
    ephone.insert(0,"91")
    eaddress = Entry(Tops, textvariable=Address, font=('aria', 16, 'bold'), width=30, justify='left')
    eaddress.grid(pady=20,row=5, column=1)

    #=======================================================Button=======================================================

    btnSendMail = ttk.Button(Tops, text='Send Mail',width=15,command=SendEmail)
    btnSendMail.grid(row=6, column=1)
    btnback=ttk.Button(Tops,text="Back",width=15,command=back)
    btnback.grid(row=6,column=2)
    root.mainloop()
if __name__=="__main__":
    GMIL()


import math

import pygame

from DrawHandlers import MachineDrawHandler2, SelectionDrawHandler, BackgroundDrawHandler2, MachineHologramDrawHandler
from RateHandlers import FrameRateHandler
from InputHandler import InputHandler
from RCGame import ResourceConsumerGame, GenericMachine
from RCScreenGUI import RCScreenGUI

class RCScreen(object):
    # class to handle the overall window, interaction and rendering of a ResourceConsumerGame object
    def __init__(self, rcg: ResourceConsumerGame, callback_outgoing_queue_func):
        self.rcg = rcg
        self.callback_outgoing = callback_outgoing_queue_func

        self.input_handler = InputHandler()

        pygame.init()

        # set up window
        self.window_size = (1000, 750)
        self.clock = pygame.time.Clock()

        self.screen = pygame.display.set_mode(self.window_size)
        self.screen.fill((0, 100, 100))  # base colour
        pygame.display.set_caption("resource consumer screen")

        # set up surfaces
        self.bg_surface = pygame.Surface(self.window_size)
        self.machine_surface = pygame.Surface(self.window_size, pygame.SRCALPHA)  # per pixel alpha
        self.hud_surface = pygame.Surface(self.window_size, pygame.SRCALPHA)  # per pixel alpha
        self.selection_surface = pygame.Surface(self.window_size, pygame.SRCALPHA)  # per pixel alpha

        # set up GUI and placements
        self.gui = RCScreenGUI(self.rcg, self.set_selected_machine)
        self.selected_machine = None  # used for the gui to callback to
        self.selected_rotation = 0

        # set up selection
        self.selection = {"down": [None, None], "cur": [None, None]}

        # zoom and camera position limits and speeds
        self.tile_size_min = 10
        self.tile_size_max = 75
        self.offsets_max = (1000, 1000)  # (x, y) pairs or (h, v) pairs
        self.offsets_min = (-1000, -1000)  # (x, y) pairs or (h, v) pairs
        # can be changed to be smooth/have acceleration
        self.offset_move_speed = 10  # n pixels change per frame
        self.tile_size_zoom_speed = 2  # n pixels change per frame

        # set up base zoom and camera position
        self.tile_size = 50
        self.offsets = [0, 0]

        # run flag for main
        self.run = False

        self.background_draw_handler = BackgroundDrawHandler2(self.rcg.game_map.size,
                                                              self.rcg.game_map.background_map,
                                                              self.rcg.game_map.background_addition_map,
                                                              (self.tile_size, self.tile_size))
        self.machine_draw_handler = MachineDrawHandler2(self.rcg.placed_objects, (self.tile_size, self.tile_size))
        self.selection_draw_handler = SelectionDrawHandler((self.tile_size, self.tile_size))
        self.block_hologram_draw_handler = MachineHologramDrawHandler((self.tile_size, self.tile_size))

    def draw(self):
        # draw a single frame of the game

        # reset the surfaces to blank
        self.bg_surface.fill((0, 0, 0))
        self.machine_surface.fill((0, 0, 0, 0))  # alpha value of 0 needed
        self.selection_surface.fill((0, 0, 0, 0))
        # self.hud_surface.fill((0, 0, 0, 0))  # don't need to re-draw hud on every frame

        # draw the background
        self.background_draw_handler.draw_background(self.bg_surface, self.offsets, (self.tile_size, self.tile_size))

        # draw the machines
        # MachineDrawHandler
        # for machine in self.rcg.placed_objects:
        #     machine.draw_handler.draw(self.machine_surface, self.offsets, (self.tile_size, self.tile_size))
        # MachineDrawHandler2
        self.machine_draw_handler.draw_machines(self.machine_surface, self.offsets, (self.tile_size, self.tile_size))
        # draw the selection
        self.selection_draw_handler.draw(self.selection_surface,
                                         self.offsets,
                                         (self.tile_size, self.tile_size),
                                         self.selection)

        # draw the gui
        self.gui.draw(self.hud_surface)

        # draw the block hologram
        self.block_hologram_draw_handler.draw(self.selection_surface,
                                              (self.tile_size, self.tile_size),
                                              pygame.mouse.get_pos(),
                                              self.selected_machine,
                                              self.selected_rotation)

        # Update screen surface
        self.screen.blit(self.bg_surface, (0, 0))
        self.screen.blit(self.machine_surface, (0, 0))
        self.screen.blit(self.selection_surface, (0, 0))
        self.screen.blit(self.hud_surface, (0, 0))
        pygame.display.flip()

    def adjust_camera_offset(self, direction):
        # takes direction tuple, (x, y) or (h, v) of either -1, 0, 1 and moves one time in that direction

        # handle horizontal
        if direction[0] != 0:
            if direction[0] > 0:
                self.offsets[0] = min(self.offsets[0] + self.offset_move_speed, self.offsets_max[0])
            elif direction[0] < 0:
                self.offsets[0] = max(self.offsets[0] - self.offset_move_speed, self.offsets_min[0])
        # handle vertical
        if direction[1] != 0:
            if direction[1] > 0:
                self.offsets[1] = min(self.offsets[1] + self.offset_move_speed, self.offsets_max[1])
            elif direction[1] < 0:
                self.offsets[1] = max(self.offsets[1] - self.offset_move_speed, self.offsets_min[1])

    def adjust_camera_zoom(self, direction):
        # takes direction value, either -1, 0, 1 and zooms one time in that direction
        if direction != 0:  # for later, if this is called every tick with a smooth camera
            if direction > 0:
                self.tile_size = min(self.tile_size + self.tile_size_zoom_speed, self.tile_size_max)
            elif direction < 0:
                self.tile_size = max(self.tile_size - self.tile_size_zoom_speed, self.tile_size_min)

    def handle_events(self):
        # uses the input_handler to record the key states
        # updates the input_handler with input changes
        # handles the inputs given by the input handler

        # Get and process events, including keypress and mouse position
        mouse_pos = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.run = False  # handle exit flag
            elif event.type == pygame.KEYDOWN:
                self.input_handler.kb_input_start(event.key)
            elif event.type == pygame.KEYUP:
                self.input_handler.kb_input_stop(event.key)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                for m_button, pressed in enumerate(pygame.mouse.get_pressed()):
                    if pressed == 1:
                        self.input_handler.m_down(m_button, mouse_pos, self.px_to_game_tile(mouse_pos))
            elif event.type == pygame.MOUSEBUTTONUP:
                for m_button, pressed in enumerate(pygame.mouse.get_pressed()):
                    if pressed == 0:
                        self.input_handler.m_up(m_button, mouse_pos, self.px_to_game_tile(mouse_pos))

        # handle inputHandler inputs, this can be moved into the input_handler
        kb_inputs, m_inputs = self.input_handler.get_inputs()

        # handle keyboard
        camera_offset_adjust = [0, 0]
        camera_zoom_adjust = 0
        if kb_inputs.get("pan_left"):
            camera_offset_adjust[0] += 1
        if kb_inputs.get("pan_right"):
            camera_offset_adjust[0] -= 1
        if kb_inputs.get("pan_up"):
            camera_offset_adjust[1] += 1
        if kb_inputs.get("pan_down"):
            camera_offset_adjust[1] -= 1
        if kb_inputs.get("zoom_in"):
            camera_zoom_adjust += 1
        if kb_inputs.get("zoom_out"):
            camera_zoom_adjust -= 1

        if kb_inputs.get("rotate"):
            self.selected_rotation = (self.selected_rotation + 1) % 4
            self.input_handler.kb_set_input("rotate", False)
            print("ROT", self.selected_rotation)

        # apply the camera offset and zoom changes
        self.adjust_camera_offset(camera_offset_adjust)
        self.adjust_camera_zoom(camera_zoom_adjust)

        # handle mouse
        # left click place
        if m_inputs[0]["up_pos"] != [None, None]:
            if self.selected_machine is not None:  # check if a building is selected
                if self.is_on_map(m_inputs[0]["up_pos"][1]):
                    # need to check if on gui and ignore if so
                    if m_inputs[0]["down_pos"][1] == m_inputs[0]["up_pos"][1]:  # compare the game pos
                        print("place building at", m_inputs[0]["up_pos"][1], self.selected_machine)

                        machine = self.selected_machine(list(m_inputs[0]["up_pos"][1]), self.selected_rotation)
                        if self.rcg.can_build_machine(machine):
                            # add to the staging callback queue so the client can send to server
                            self.callback_outgoing("placements", machine.to_json_serialisable())

        # right click drag selection
        if m_inputs[2]["down_pos"] != [None, None]:
            self.selection["down"] = m_inputs[2]["down_pos"]
            self.selection["cur"] = [mouse_pos, self.px_to_game_tile(mouse_pos)]
        else:
            # on no selection - default to [None, None]
            self.selection["down"] = [None, None]
            self.selection["cur"] = [None, None]

        # on right click release, send selection to client to send to server for dismantling
        if m_inputs[2]["up_pos"] != [None, None]:
            tile_selection = {"start": self.selection["down"][1], "end": self.selection["cur"][1]}
            print(tile_selection)
            self.callback_outgoing("removal_sel", tile_selection)

        # update the gui with the mouse position and mouse input handler
        self.gui.update(mouse_pos, m_inputs)

    def is_on_map(self, game_pos):
        # game pos is tuple (x, y) of already converted px_to_game_tile() result for a position
        # checks if this position is within the map
        map_size = self.rcg.game_map.size
        if 0 <= game_pos[0] < map_size[0] and 0 <= game_pos[1] < map_size[1]:
            return True
        else:
            return False

    def px_to_game_tile(self, pixel_pos):
        # pixel_pos is a tuple (x, y) of a pixel position
        # converts the pixel_pos to the game_pos tuple (x, y) for the correct game tile

        tile_x = math.floor((pixel_pos[0] - self.offsets[0]) / self.tile_size)
        tile_y = math.floor((pixel_pos[1] - self.offsets[1]) / self.tile_size)

        return tile_x, tile_y

    def set_selected_machine(self, machine):
        # setter for setting the currently selected machine - used by the RCScreenGUI for callback
        assert issubclass(machine, GenericMachine)  # using issubclass() because not inited

        # handle un-selecting a machine
        if self.selected_machine == machine:
            self.selected_machine = None
        else:
            self.selected_machine = machine

    async def main(self):
        # main loop for handling every frame of the screen
        framerate_handler = FrameRateHandler(30)

        self.run = True
        while self.run:
            framerate_handler.period_start()  # start the framerate_handler's frame
            # use input_handler and method to apply all the needed inputs/actions
            self.handle_events()

            # entire draw routine
            self.draw()

            # dynamically await using the framerate_handler
            await framerate_handler.period_end()


#global
"""a=34
b=65

def production():
    #local
    a=30
    b=30
    print("Mul:",a*b)

production()
print("Sum:",a+b)"""

# -------------- Global Keywords ---------------
a=12
print("A:",a)

def getA():
    global a
    a=68
    print("A:",a)

getA()


import asyncio
import logging
from datetime import datetime, timezone
from queue import Queue
from threading import Thread
from typing import Dict, Optional

from aws_embedded_metrics.logger.metrics_logger import MetricsLogger
from aws_embedded_metrics.unit import Unit
from shapely.affinity import translate
from shapely.geometry import Polygon

from aws.osml.model_runner.app_config import MetricLabels
from aws.osml.model_runner.common import GeojsonDetectionField
from aws.osml.model_runner.database import FeatureTable
from aws.osml.model_runner.inference import Detector
from aws.osml.model_runner.tile_worker import FeatureRefinery

class TileWorker(Thread):
    def __init__(
        self,
        in_queue: Queue,
        feature_detector: Detector,
        feature_refinery: Optional[FeatureRefinery],
        feature_table: FeatureTable,
        metrics: MetricsLogger,
    ) -> None:
        super().__init__()
        self.in_queue = in_queue
        self.feature_detector = feature_detector
        self.feature_refinery = feature_refinery
        self.feature_table = feature_table
        self.metrics = metrics

    def run(self) -> None:
        thread_event_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(thread_event_loop)
        while True:
            image_info: Dict = self.in_queue.get()

            if image_info is None:
                logging.info("All images processed. Stopping tile worker.")
                logging.info(
                    "Feature Detector Stats: {} requests with {} errors".format(
                        self.feature_detector.request_count, self.feature_detector.error_count
                    )
                )
                break

            try:
                logging.info("Invoking Feature Detector Endpoint")
                with open(image_info["image_path"], mode="rb") as payload:
                    feature_collection = self.feature_detector.find_features(payload)

                # Convert the features to reference the full image
                features = []
                ulx = image_info["region"][0][1]
                uly = image_info["region"][0][0]
                if isinstance(feature_collection, dict) and "features" in feature_collection:
                    logging.info("SM Model returned {} features".format(len(feature_collection["features"])))
                    for feature in feature_collection["features"]:
                        # model returned a mask
                        scaled_polygon = None
                        if GeojsonDetectionField.GEOM in feature["properties"]:
                            polygon = Polygon(feature["properties"][GeojsonDetectionField.GEOM])
                            scaled_polygon = translate(polygon, xoff=ulx, yoff=uly)
                            feature["properties"][GeojsonDetectionField.GEOM] = list(scaled_polygon.exterior.coords)
                        # model returned a bounding box
                        if GeojsonDetectionField.BOUNDS in feature["properties"]:
                            tile_bbox = feature["properties"][GeojsonDetectionField.BOUNDS]
                            scaled_bbox = translate(
                                Polygon(FeatureRefinery.imcoords_bbox_to_polygon(tile_bbox)), xoff=ulx, yoff=uly
                            )
                            feature["properties"][GeojsonDetectionField.BOUNDS] = scaled_bbox.bounds
                        elif scaled_polygon is not None:
                            feature["properties"][GeojsonDetectionField.BOUNDS] = scaled_polygon.bounds
                        else:
                            logging.warning(f"There isn't a valid detection shape for feature: {feature}")
                        feature["properties"]["image_id"] = image_info["image_id"]
                        feature["properties"]["inferenceTime"] = datetime.now(tz=timezone.utc).isoformat()
                        FeatureRefinery.feature_property_transformation(feature)
                        features.append(feature)

                logging.info("# Features Created: {}".format(len(features)))
                if len(features) > 0:
                    if self.feature_refinery is not None:
                        # Create a geometry for each feature in the result. The geographic coordinates of these
                        # features are computed using the sensor model provided in the image metadata
                        self.feature_refinery.refine_features_for_tile(features)
                        logging.info(f"Created Geographic Coordinates for {len(features)} features")

                    self.feature_table.add_features(features)
            except Exception as e:
                logging.error("Failed to process region tile!")
                logging.exception(e)
                if self.metrics:
                    self.metrics.put_metric(MetricLabels.TILE_PROCESSING_ERROR, 1, str(Unit.COUNT.value))
                    self.metrics.put_metric(MetricLabels.TILE_CREATION_FAILURE, 1, str(Unit.COUNT.value))
            finally:
                self.in_queue.task_done()

        try:
            thread_event_loop.stop()
            thread_event_loop.close()
        except Exception as e:
            logging.warning("Failed to stop and close the thread event loop")
            logging.exception(e)


"""grid"""
import math
import numpy as np

def make_grid(_input, nrow=8, padding=2):
    """make_grid"""
    low = np.min(_input)
    high = np.max(_input)
    _input = np.clip(_input, a_min=low, a_max=high)
    _input = _input - low
    _max = high - low
    if _max < 1e-5:
        _input = _input / 1e-5
    else:
        _input = _input / _max

    if _input.shape[0] == 1:
        return np.squeeze(_input)

    nmaps = _input.shape[0]
    if nrow < nmaps:
        xmaps = nrow
    else:
        xmaps = nmaps
    ymaps = int(math.ceil(float(nmaps) / xmaps))
    height, width = int(_input.shape[2] + padding), int(_input.shape[3] + padding)
    num_channels = _input.shape[1]

    grip = np.zeros((num_channels, height * ymaps + padding, width * xmaps + padding))

    k = 0
    for y in range(ymaps):
        for x in range(xmaps):
            if k >= nmaps:
                break
            grip[:, y * height + padding : y * height + height, :] \
                [:, :, x * width + padding : x * width + width] = _input[k]
            k = k + 1
    return grip

def permute(_input):
    """permute"""
    _input = _input * 255
    _input = np.clip(_input, a_min=0, a_max=255)
    _input = _input.astype(np.uint8)
    _input = np.transpose(_input, (1, 2, 0))

    return _input


'''

visited : 방문했다면 True, 아니라면 False
노드가 1000일때 간선이 500개까지 받아지고 꽤나 많이 받아질 수 있기에 연결list를 사용하여 풀이진행.

for문으로 node를 돌면서 visited가 False일때 bfs를 동작시키고 counting 변수값을 증가 시킴.
'''

import sys
from collections import deque
input = sys.stdin.readline
two_input = lambda : map(int, input().split())

n,m = two_input()

linked_list = [[0]*(n+1) for _ in range(n+1)]
visited = [False]*(n+1)
for _ in range(m):
    a,b = two_input()
    linked_list[a][b]=1
    linked_list[b][a]=1

count = 0

def bfs(start):

    global count
    count += 1

    queue = deque([])
    queue.append(start)
    visited[start] = True

    while(queue):
        current = queue.popleft()
        linked_node = linked_list[current]

        for node in range(1,len(linked_node)):
            if linked_node[node] == 1 and visited[node]==False:
                visited[node]=True
                queue.append(node)

for node in range(1, n+1):
    if visited[node]==False:
        bfs(node)

print(count)


"""Test DocugamiLoader."""
from pathlib import Path

import pytest

from langchain_community.document_loaders import DocugamiLoader

DOCUGAMI_XML_PATH = Path(__file__).parent / "test_data" / "docugami-example.xml"

@pytest.mark.requires("dgml_utils")
def test_docugami_loader_local() -> None:
    """Test DocugamiLoader."""
    loader = DocugamiLoader(file_paths=[DOCUGAMI_XML_PATH])
    docs = loader.load()

    assert len(docs) == 25

    assert "/docset:DisclosingParty" in docs[1].metadata["xpath"]
    assert "h1" in docs[1].metadata["structure"]
    assert "DisclosingParty" in docs[1].metadata["tag"]
    assert docs[1].page_content.startswith("Disclosing")

def test_docugami_initialization() -> None:
    """Test correct initialization in remote mode."""
    DocugamiLoader(access_token="test", docset_id="123")


"""Scikit utilities."""

import numpy as np

def tree_used_features(tree):
    """Get indices of the features used by a given decision tree."""

    left = tree.tree_.children_left
    right = tree.tree_.children_right
    features = tree.tree_.feature

    ret = set()

    def recurse(left, right, node):
        """Up the tree you go."""

        ret.add(features[node])
        if left[node] != -1:
            recurse(left, right, left[node])
        if right[node] != -1:
            recurse(left, right, right[node])

    recurse(left, right, 0)

    return list(ret)

def get_code(tree, feature_names, target_names,
             spacer_base="    "):
    """Produce psuedo-code for decision tree.

    Args
    ----
    tree -- scikit-leant DescisionTree.
    feature_names -- list of feature names.
    target_names -- list of target (class) names.
    spacer_base -- used for spacing code (default: "    ").

    Notes
    -----
    based on http://stackoverflow.com/a/30104792.
    """

    left = tree.tree_.children_left
    right = tree.tree_.children_right
    threshold = tree.tree_.threshold
    features = [feature_names[i] for i in tree.tree_.feature]
    value = tree.tree_.value

    def recurse(children, threshold, features, node, depth):
        """Up the tree you go."""

        (left, right) = children

        spacer = spacer_base * depth
        if threshold[node] != -2:
            print(spacer + "if ( " + features[node] + " <= " +
                  str(threshold[node]) + " ) {")
            if left[node] != -1:
                recurse((left, right), threshold, features,
                        left[node], depth+1)
            print(spacer + "}\n" + spacer + "else {")
            if right[node] != -1:
                recurse((left, right), threshold, features,
                        right[node], depth+1)
            print(spacer + "}")
        else:
            target = value[node]
            for idx, val in zip(np.nonzero(target)[1],
                                target[np.nonzero(target)]):
                target_name = target_names[idx]
                target_count = int(val)
                print(spacer + "return " + str(target_name) +
                      " ( " + str(target_count) + " examples )")

    recurse((left, right), threshold, features, 0, 0)


"""
2020-4-20
yfc
把类设置为迭代器iterator，可用for in 遍历
类中有 __iter__(self)，__next__(self)两个函数，则该类具有了迭代器的属性
"""
class A():
    def __init__(self):
        self.cur = 0
        self.data = ['<Python>','<C++>','<Java>','<C#>']

    def __iter__(self):
        """
        向系统说明这是一个可迭代对象
        """
        return self

    def __next__(self):
        """
        提供迭代算法
        """
        if self.cur >= len(self.data):
            # raise显示引发异常，执行后，后续语句不再执行;StopIteration迭代不再执行
            raise StopIteration()
        r = self.data[self.cur]
        self.cur +=1
        return r

language = A()
# 迭代器的使用具有一次性，不能多次使用for in遍历
for i in language:
    print(i)


import pickle
from datetime import date, datetime, timedelta
from typing import Any, List, Tuple

import numpy as np
import pandas as pd

from wikipedia_cleanup.predictor import CachedPredictor

class BaselineMinPrecision(CachedPredictor):
    def __init__(
        self,
        use_cache: bool = True,
    ) -> None:
        super().__init__(use_cache)
        self.classifier: dict = {}

    def get_relevant_ids(self, identifier: Tuple) -> List[Tuple]:
        return []

    def get_relevant_attributes(self) -> List[str]:
        return ["value_valid_from"]

    def _load_cache_file(self, file_object: Any) -> bool:
        self.classifier = pickle.load(file_object)
        return True

    def _get_cache_object(self) -> Any:
        return self.classifier

    def _fit_classifier(
        self, train_data: pd.DataFrame, last_day: datetime, keys: List[str]
    ) -> None:

        bins = pd.date_range(
            last_day - timedelta(364),
            last_day,
        )
        total_days = len(bins)
        bins = pd.cut(
            train_data["value_valid_from"].astype(np.datetime64), bins, labels=False
        )
        train_data["bins"] = bins
        train_data = train_data[train_data["bins"].notna()]
        train_data["bins"] = train_data["bins"].astype(int)

        def _create_time_series(a, duration):
            series = np.zeros(duration)
            uniques, counts = np.unique(a, return_counts=True)

            series[uniques] = counts
            return series

        def _aggregate_labels(labels: np.ndarray, n: int) -> np.ndarray:
            if n == 1:
                return labels
            if 365 % n != 0:
                cut_labels = labels[:, : -(365 % n)]
            else:
                cut_labels = labels
            cut_labels = cut_labels.reshape((labels.shape[0], -1, n))
            return np.any(cut_labels, axis=2)

        train_data_grp = train_data.groupby(["key"])["bins"].apply(
            _create_time_series, duration=total_days
        )
        x = np.vstack(train_data_grp.to_numpy())

        self.classifier[1] = set(train_data_grp.index[x.sum(axis=1) >= 365 * 0.85])
        self.classifier[7] = set(
            train_data_grp.index[_aggregate_labels(x, 7).sum(axis=1) >= 365 // 7 * 0.85]
        )
        self.classifier[30] = set(
            train_data_grp.index[
                _aggregate_labels(x, 30).sum(axis=1) >= 365 // 30 * 0.85
            ]
        )
        self.classifier[365] = set(
            train_data_grp.index[_aggregate_labels(x, 365).sum(axis=1) >= 1]
        )

    def predict_timeframe(
        self,
        data_key: np.ndarray,
        additional_data: np.ndarray,
        columns: List[str],
        first_day_to_predict: date,
        timeframe: int,
    ) -> Any:  # can be bool for actual predictions or float for confidence scores
        key_col = columns.index("key")
        if len(data_key) == 0:
            return False
        current_key = data_key[0, key_col]
        return current_key in self.classifier[timeframe]


import gzip
import json
import logging
import os
import time

import boa
from airflow.hooks.S3_hook import S3Hook
from airflow.hooks.base_hook import BaseHook
from airflow.models import BaseOperator, Variable
from google_plugin.hooks.google_hook import GoogleHook

from six import BytesIO

class GoogleSheetsToS3Operator(BaseOperator):
    """
    Google Sheets To S3 Operator

    :param google_conn_id:    The Google connection id.
    :type google_conn_id:     string
    :param sheet_id:          The id for associated report.
    :type sheet_id:           string
    :param sheet_names:       The name for the relevent sheets in the report.
    :type sheet_names:        string/array
    :param range:             The range of of cells containing the relevant data.
                              This must be the same for all sheets if multiple
                              are being pulled together.
                              Example: Sheet1!A2:E80
    :type range:              string
    :param include_schema:    If set to true, infer the schema of the data and
                              output to S3 as a separate file
    :type include_schema:     boolean
    :param s3_conn_id:        The s3 connection id.
    :type s3_conn_id:         string
    :param s3_key:            The S3 key to be used to store the
                              retrieved data.
    :type s3_key:             string
    """

    template_fields = ('s3_key',)

    def __init__(self,
                 google_conn_id,
                 sheet_id,
                 s3_conn_id,
                 s3_key,
                 compression_bound,
                 include_schema=False,
                 sheet_names=[],
                 range=None,
                 output_format='json',
                 *args,
                 **kwargs):
        super().__init__(*args, **kwargs)

        self.google_conn_id = google_conn_id
        self.sheet_id = sheet_id
        self.sheet_names = sheet_names
        self.s3_conn_id = s3_conn_id
        self.s3_key = s3_key
        self.include_schema = include_schema
        self.range = range
        self.output_format = output_format.lower()
        self.compression_bound = compression_bound
        if self.output_format not in ('json'):
            raise Exception('Acceptable output formats are: json.')

        if self.sheet_names and not isinstance(self.sheet_names, (str, list, tuple)):
            raise Exception('Please specify the sheet names as a string or list.')

    def execute(self, context):
        g_conn = GoogleHook(self.google_conn_id)

        if isinstance(self.sheet_names, str) and ',' in self.sheet_names:
            sheet_names = self.sheet_names.split(',')
        else:
            sheet_names = self.sheet_names

        sheets_object = g_conn.get_service_object('sheets', 'v4')
        logging.info('Retrieved Sheets Object')

        response = sheets_object.spreadsheets().get(spreadsheetId=self.sheet_id,
                                                    includeGridData=True).execute()

        title = response.get('properties').get('title')
        sheets = response.get('sheets')

        final_output = dict()

        total_sheets = []
        for sheet in sheets:
            name = sheet.get('properties').get('title')
            name = boa.constrict(name)
            total_sheets.append(name)

            if self.sheet_names:
                if name not in sheet_names:
                    logging.info('{} is not found in available sheet names.'.format(name))
                    continue

            table_name = name
            data = sheet.get('data')[0].get('rowData')
            output = []

            for row in data:
                row_data = []
                values = row.get('values')
                for value in values:
                    ev = value.get('effectiveValue')
                    if ev is None:
                        row_data.append(None)
                    else:
                        for v in ev.values():
                            row_data.append(v)

                output.append(row_data)

            if self.output_format == 'json':
                headers = output.pop(0)
                output = [dict(zip(headers, row)) for row in output]

            final_output[table_name] = output

        s3 = S3Hook(self.s3_conn_id)

        for sheet in final_output:
            output_data = final_output.get(sheet)

            file_name, file_extension = os.path.splitext(self.s3_key)

            output_name = ''.join([file_name, '_', sheet, file_extension])

            if self.include_schema is True:
                schema_name = ''.join([file_name, '_', sheet, '_schema', file_extension])

            self.output_manager(s3, output_name, output_data, context, sheet, schema_name)

        dag_id = context['ti'].dag_id

        var_key = '_'.join([dag_id, self.sheet_id])
        Variable.set(key=var_key, value=json.dumps(total_sheets))
        time.sleep(10)

        return boa.constrict(title)

    def output_manager(self, s3, output_name, output_data, context, sheet_name, schema_name=None):
        self.s3_bucket = BaseHook.get_connection(self.s3_conn_id).host
        if self.output_format == 'json':
            output = '\n'.join([json.dumps({boa.constrict(str(k)): v
                                            for k, v in record.items()})
                                for record in output_data])

            enc_output = str.encode(output, 'utf-8')

            # if file is more than bound then apply gzip compression
            if len(enc_output) / 1024 / 1024 >= self.compression_bound:
                logging.info("File is more than {}MB, gzip compression will be applied".format(self.compression_bound))
                output = gzip.compress(enc_output, compresslevel=5)
                self.xcom_push(context, key='is_compressed_{}'.format(sheet_name), value="compressed")
                self.load_bytes(s3,
                                bytes_data=output,
                                key=output_name,
                                bucket_name=self.s3_bucket,
                                replace=True
                                )
            else:
                logging.info("File is less than {}MB, compression will not be applied".format(self.compression_bound))
                self.xcom_push(context, key='is_compressed_{}'.format(sheet_name), value="non-compressed")
                s3.load_string(
                    string_data=output,
                    key=output_name,
                    bucket_name=self.s3_bucket,
                    replace=True
                )

            if self.include_schema is True:
                output_keys = output_data[0].keys()
                schema = [{'name': boa.constrict(a),
                           'type': 'varchar(512)'} for a in output_keys if a is not None]
                schema = {'columns': schema}

                s3.load_string(
                    string_data=json.dumps(schema),
                    key=schema_name,
                    bucket_name=self.s3_bucket,
                    replace=True
                )

            logging.info('Successfully output of "{}" to S3.'.format(output_name))

        # TODO -- Add support for csv output

        # elif self.output_format == 'csv':
        #     with NamedTemporaryFile("w") as f:
        #         writer = csv.writer(f)
        #         writer.writerows(output_data)
        #         s3.load_file(
        #             filename=f.name,
        #             key=output_name,
        #             bucket_name=self.s3_bucket,
        #             replace=True
        #         )
        #
        #     if self.include_schema is True:
        #         pass

    # TODO: remove when airflow version is upgraded to 1.10
    def load_bytes(self, s3,
                   bytes_data,
                   key,
                   bucket_name=None,
                   replace=False):
        if not bucket_name:
            (bucket_name, key) = s3.parse_s3_url(key)

        if not replace and s3.check_for_key(key, bucket_name):
            raise ValueError("The key {key} already exists.".format(key=key))

        filelike_buffer = BytesIO(bytes_data)

        client = s3.get_conn()
        client.upload_fileobj(filelike_buffer, bucket_name, key, ExtraArgs={})


import numpy as np
from keras.datasets import mnist
import random

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from sklearn import preprocessing
import keras
import tensorflow as tf
from keras.datasets import mnist
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Input, Reshape, multiply
from keras.layers import BatchNormalization, Activation, ZeroPadding2D, Embedding
from keras.layers.convolutional import UpSampling2D
from keras.layers import Conv2D, MaxPooling2D,LeakyReLU,Conv2DTranspose
from keras.layers import Input, Lambda, concatenate, Add, Concatenate
from keras import backend as K

from keras.optimizers import Adam, RMSprop

from privacy_net.utils.module import u_tail
from privacy_net.utils.module import y_tail
from privacy_net.utils.module import InstanceNormalization2D
from privacy_net.utils.module import residual_block
from privacy_net.models.privacy_net_model import privacyNet

plt.rcParams['font.size'] = 8
plt.rcParams['figure.figsize'] = (8,8)

def save_some(im_list,name):
    im_list = np.squeeze(im_list)
    num_list = len(im_list)
    plt.figure(figsize=(3 * num_list, 4))
    for i, array in enumerate(im_list):
        plt.subplot(1, len(im_list), i + 1)
        plt.imshow(((array + 1) * 127.5).astype(np.uint8), cmap='gray')
        plt.axis('off')
    plt.savefig(name)

def generator(img):
    #     def tileAttr(x):
    #         x = tf.expand_dims(x, axis = 1)
    #         x = tf.expand_dims(x, axis = 2)
    #         return tf.tile(x, [1, size, size, 1])

    #     y = Concatenate()([img, Lambda(tileAttr)(attr)])

    y = Conv2D(32, 5, padding="same", kernel_initializer='he_normal')(img)
    y = InstanceNormalization2D()(y)
    y = Activation('relu')(y)

    y = Conv2D(64, 3, strides=2, padding="same", kernel_initializer='he_normal')(y)
    y = InstanceNormalization2D()(y)
    y = Activation('relu')(y)

    y = Conv2D(128, 3, strides=2, padding="same", kernel_initializer='he_normal')(y)
    y = InstanceNormalization2D()(y)
    y = Activation('relu')(y)

    y = residual_block(y, 128, 3)
    y = residual_block(y, 128, 3)
    y = residual_block(y, 128, 3)
    y = residual_block(y, 128, 3)

    y = Conv2DTranspose(64, 3, strides=2, padding='same', kernel_initializer='he_normal')(y)
    y = InstanceNormalization2D()(y)
    y = Activation('relu')(y)

    y = Conv2DTranspose(32, 3, strides=2, padding='same', kernel_initializer='he_normal')(y)
    y = InstanceNormalization2D()(y)
    y = Activation('relu')(y)

    y = Conv2D(1, 5, strides=1, padding='same', kernel_initializer='he_normal')(y)
    y = Activation('tanh')(y)
    return y

def discriminator(img, u_size, y_size, u_feat_dims=None, y_feat_dims=None, activation='tanh'):

    y = Conv2D(32, kernel_size=3, strides=2, padding='same', kernel_initializer='he_normal')(img)
    y = LeakyReLU(alpha=0.2)(y)  # 14 14 32
    y = Dropout(0.25)(y)

    y = Conv2D(64, kernel_size=3, strides=2, padding='same', kernel_initializer='he_normal')(y)
    y = ZeroPadding2D(padding=((0, 1), (0, 1)))(y)
    y = BatchNormalization(momentum=0.8)(y)
    y = LeakyReLU(alpha=0.2)(y)  # 8 8 64
    y = Dropout(0.25)(y)

    y = Conv2D(128, kernel_size=3, strides=2, padding='same', kernel_initializer='he_normal')(y)
    y = BatchNormalization(momentum=0.8)(y)
    y = LeakyReLU(alpha=0.2)(y)  # 4 4 128
    y = Dropout(0.25)(y)

    y = Conv2D(256, kernel_size=3, strides=1, padding='same', kernel_initializer='he_normal')(y)
    y = BatchNormalization(momentum=0.8)(y)
    y = LeakyReLU(alpha=0.2)(y)  # 4 4 256
    y = Dropout(0.25)(y)

    y = Conv2D(512, kernel_size=3, strides=2, padding='same', kernel_initializer='he_normal')(y)
    y = BatchNormalization(momentum=0.8)(y)
    y = LeakyReLU(alpha=0.2)(y)  # 2 2 512
    y = Dropout(0.25)(y)

    pred_f_u = []
    if not u_feat_dims:
        u_feat_dims = [2 for _ in range(u_size)]

    pred_f_y = []
    if not y_feat_dims:
        y_feat_dims = [2 for _ in range(y_size)]

    for i in range(u_size):
        temp_u = Conv2D(u_feat_dims[i], kernel_size=2, strides=1, kernel_initializer='he_normal',
                        activation=activation)(y)
        temp_u = Flatten()(temp_u)
        pred_f_u.append(temp_u)

    for i in range(y_size):
        temp_y = Conv2D(y_feat_dims[i], kernel_size=2, strides=1, kernel_initializer='he_normal',
                        activation=activation)(y)
        temp_y = Flatten()(temp_y)
        pred_f_y.append(temp_y)

    return pred_f_u,pred_f_y

def generatorV2(img):

    trans_x = Conv2D(32, kernel_size=3,
                         padding='same',
                         activation='relu')(img)
    trans_x = Conv2D(64, kernel_size=3,
                         padding='same',
                         activation='relu')(trans_x)
    trans_x = Conv2D(1, 5, strides=1, padding='same', kernel_initializer='he_normal')(trans_x)
    trans_x = Activation('tanh')(trans_x)
    return trans_x

def generatorV3(img):
    def mean_layer(x):
        x = tf.reduce_mean(x, axis=3)
        return tf.expand_dims(x, -1)
    trans_x = Conv2D(32, kernel_size=3,
                         padding='same',
                         activation='relu')(img)
    trans_x = Conv2D(64, kernel_size=3,
                         padding='same',
                         activation='tanh')(trans_x)
    trans_x = Lambda(mean_layer)(trans_x)
    return trans_x

def generatorV4(img):
    def mean_layer(x):
        x = tf.reduce_mean(x, axis=3)
        return tf.expand_dims(x, -1)
    trans_x = Conv2D(96, kernel_size=3,
                         padding='same',
                         activation='tanh')(img)
    trans_x = Lambda(mean_layer)(trans_x)
    return trans_x

class reversedMNISTGenerator():
    def __init__(self, batch_size=16):

        self.input_shape = (28, 28, 1)
        self.batch_size = batch_size
        (self.x_train, self.digit_train), (self.x_test, self.digit_test) = mnist.load_data()
        self.x_train = np.expand_dims(self.x_train, axis=-1)
        self.x_test = np.expand_dims(self.x_test, axis=-1)

        self.x_train = np.concatenate((self.x_train,255-self.x_train),axis=0)
        self.x_test = np.concatenate((self.x_test,255-self.x_test),axis=0)
        self.digit_train = np.concatenate((self.digit_train,self.digit_train),axis=0)
        self.digit_test = np.concatenate((self.digit_test,self.digit_test),axis=0)

        self.train_size = self.x_train.shape[0]
        self.test_size = self.x_test.shape[0]

        self.u_train, self.u_test = self.load_public_label()
        self.y_train, self.y_test = self.load_sensitive_label()

        self.steps_per_epoch = self.default_training_steps
        self.test_steps = self.default_testing_steps

        self.cur_train_step = 0
        self.cur_test_step = 0
        self.train_ind_list = np.array([i for i in range(self.train_size)])
        self.test_ind_list = np.array([i for i in range(self.test_size)])
        random.seed(1234)
        random.shuffle(self.train_ind_list)
        random.shuffle(self.test_ind_list)

    # property is a getter
    @property
    def default_training_steps(self):
        # make sure train with full batch size which means each epoch less than batch size images being used.
        return int(np.floor(self.train_size / self.batch_size))

    @property
    def default_testing_steps(self):
        # make sure train with full batch size which means each epoch less than batch size images being used.
        return int(np.floor(self.test_size / self.batch_size))

    def load_public_label(self):
        # prepare utility labels
#         u_train = np.zeros_like(self.digit_train)
#         u_test = np.zeros_like(self.digit_test)

#         u_train[self.digit_train % 2 == 1] = 1
#         u_test[self.digit_test % 2 == 1] = 1

        return self.digit_train, self.digit_test

    def load_sensitive_label(self):
        # prepare privacy labels
        y_train = np.zeros_like(self.digit_train)
        y_test = np.zeros_like(self.digit_test)

        y_train[int(self.train_size/2):] = 1
        y_test[int(self.test_size/2):] = 1
        return y_train, y_test

    def nextTrain(self):
        while True:

            # set self.cur_train_ind
            # cur_train_ind has indices of batch_sizes, this indices correpond to the image ids
            self.fetchCurrentTrainInd()
            train_x = self.x_train[self.cur_train_ind]
            train_x = train_x / 127.5 - 1

            train_u = np.zeros((self.batch_size, 10))
            for i in range(self.batch_size):
                train_u[i][self.u_train[self.cur_train_ind[i]]] = 1
            train_y = np.zeros((self.batch_size, 2))
            for i in range(self.batch_size):
                train_y[i][self.y_train[self.cur_train_ind[i]]] = 1

            inputs = {'input_x': train_x, 'input_y': [train_y], 'input_u': [train_u]}
            output = np.zeros((self.batch_size, 1))
            self.cur_train_step += 1
            yield inputs, output

    def fetchCurrentTrainInd(self):
        # this function find cur_train_ind for each step
        # it read batch_size's image_ids, starting from cur_train_step(batch_size,augment_ratio)

        # if self.cur_train_step%self.augment_ratio != 0:
        #     return

        # when epoch end it will shuffle image_ids and reset cur_train_step, namely, read from the start
        if self.cur_train_step >= self.steps_per_epoch:
            random.shuffle(self.train_ind_list)
            # print("shuffling")
            self.cur_train_step = 0

        cur_train_start = int(self.cur_train_step) * self.batch_size
        cur_train_end = cur_train_start + self.batch_size
        if cur_train_end > self.train_size:
            cur_train_end = self.train_size
        self.cur_train_ind = self.train_ind_list[np.arange(cur_train_start, cur_train_end).astype(int)]

    def nextVal(self):
        while True:
            if self.cur_test_step == self.test_steps:
                self.cur_test_step = 0
                random.shuffle(self.test_ind_list)
            cur_test_start = int(self.cur_test_step) * self.batch_size
            cur_test_end = cur_test_start + self.batch_size
            if cur_test_end > self.test_size:
                cur_test_end = self.test_size
            self.cur_test_ind = self.test_ind_list[np.arange(cur_test_start, cur_test_end)]

            test_x = self.x_test[self.cur_test_ind]
            test_x = test_x / 127.5 - 1

            test_u = np.zeros((self.batch_size, 10))
            for i in range(self.batch_size):
                test_u[i][self.u_test[self.cur_test_ind[i]]] = 1
            test_y = np.zeros((self.batch_size, 2))
            for i in range(self.batch_size):
                test_y[i][self.y_test[self.cur_test_ind[i]]] = 1

            self.cur_test_step += 1
            inputs = {'input_x': test_x, 'input_y': [test_y], 'input_u': [test_u]}
            output = np.zeros((self.batch_size, 1))
            yield inputs, output

class privacyNetV4(privacyNet):

    def __init__(self, u_input_dims=[2, 2, 2, 2], y_input_dims=[2], u_feat_dims=[2, 2, 2, 2], y_feat_dims=[2],mode=0,
                 **kwargs):
        self.u_input_dims = u_input_dims
        self.y_input_dims = y_input_dims
        self.u_feat_dims = u_feat_dims
        self.y_feat_dims = y_feat_dims
        self.mode = mode # 0->generatorV2 1->generatorV3 2->generatorV4
        super(privacyNetV4, self).__init__(**kwargs)

    def build_model(self):

        """Build Discriminator and Generator and Transformer, seperately.
        This method requires no inputs and returns nothing.
        self.d_model, self.g_model, self.transform_tail_models are goals for this method.
        NOTE: The following 'Output's and 'Input's are used for introducing model specs.

        # D model arguments:
            - d_model: Discriminator part.
        Input:
            - attr_y_input: list of Input Tensors. sensitive labels, Y.
            - attr_u_input(Optional): list, of Input Tensors. public labels, U.
            - img_input: Input Tensor, shared with g_model. raw images, X.
        Output:
            - loss_y_output: list, H-score between imgs and sensitive labels. H_score.
            - loss_u_output: list, H-score between imgs and public labels. Might be None. H_score
            - pred_real: predictions of real images. prob.
            - pred_f_y: list,feature of Y. y(X).
            - pred_f_u: list,feature of U. u(X).

        # G model:
            - g_model: Generator part.
        Input:
            - img_input: Input Tensor, shared with d_model. raw images, X.
        Output:
            - img_output: transformed images. transformed images, Z.

        # T models:
            - transform_tail_models: list of T models.
        Input:
            - transform_y_input: list of input of third networks in order to filter
                                 sensitive information. y(Z)
        Output:
            - transform_y_tail: list. h(y(Z))

        """
        ################## Part I ######################
        ## start building D model
        self.img_input = Input(self.image_size)
        self.attr_y_input = []  # placeholder for every sensitive labels
        self.attr_u_input = []  # placeholder for every public labels

        for i in range(self.y_size):
            self.attr_y_input.append(Input((self.y_input_dims[i],)))
        for j in range(self.u_size):
            self.attr_u_input.append(Input((self.u_input_dims[j],)))

        self.pred_f_u, _ = discriminator(self.img_input,
                                                     self.u_size,
                                                     0,
                                                     self.u_feat_dims,
                                                     activation=self.activation)
        _, self.pred_f_y = discriminator(self.img_input,
                                                     0,
                                                     self.y_size,
                                                     self.y_feat_dims,
                                                     activation=self.activation)
        # All tail networks are separated
        self.attr_y_tail = []  # holding tails network for sensitive_attrs
        self.attr_u_tail = []  # holding tails network for public_attrs

        for i in range(self.y_size):
            self.attr_y_tail.append(y_tail(self.attr_y_input[i],
                                           self.y_feat_dims[i],
                                           activation=self.activation))

        for j in range(self.u_size):
            self.attr_u_tail.append(u_tail(self.attr_u_input[j],
                                           self.u_feat_dims[j],
                                           activation=self.activation))

        self.loss_y_output = []  # containing sensitive H-score
        self.loss_u_output = []  # containing public H-score

        for i in range(self.y_size):
            self.loss_y_output.append(Lambda(self.neg_hscore)([self.pred_f_y[i], self.attr_y_tail[i]]))

        for j in range(self.u_size):
            self.loss_u_output.append(Lambda(self.neg_hscore)([self.pred_f_u[j], self.attr_u_tail[j]]))

        self.d_model = Model(inputs=[self.img_input] + self.attr_u_input + self.attr_y_input,
                             outputs= self.loss_u_output + self.loss_y_output
                                     + self.pred_f_u + self.pred_f_y)
        if self.d_model_dir:
            self.d_model.load_weights(self.d_model_dir)  # load pretrained model if avialable
        ## end building D model
        self.d_model.summary()

        ################## Part II ######################
        ## start building G model
        if self.mode == 0:
            self.img_output = generatorV2(self.img_input)  # pass image into generator
        elif self.mode == 1:
            self.img_output = generatorV3(self.img_input)  # pass image into generator
        elif self.mode == 2:
            self.img_output = generatorV4(self.img_input)  # pass image into generator
        else:
            self.img_output = generator(self.img_input)  # pass image into generator

        self.g_model = Model(inputs=[self.img_input], outputs=[self.img_output])

        if self.g_model_dir:
            self.g_model.load_weights(self.g_model_dir)  # load pretrained model if avialable
        ## end building G model
        self.g_model.summary()

    def build_loss(self):
        """Build Discriminator and Generator and Transformer loss, itegrating G,D,T into privacy_net model.
        This project uses three steps training, D->T->G. Thus, three losses are introduced accordingly.

        # Network Arguments:

            - img_a: Input Tensor. Raw images.
            - attr_y: list, Input Tensors. Sensitive labels.
            - attr_u: list, Input Tensors. Public labels.
            - img_a_trans: Output Tensor of G. Transformed images.
            - pred_real(local): List, Output tensor of D. On raw images.
            Details: pred_real
            |0       |1:1+u_size   |1+u_size:1+u_size+y_size|1+u_size+y_size:1+u_size*2+y_size|1+u_size*2+y_size:1+u_size*2+y_size*2|
            |pred_dis|loss_u_hscore|      loss_y_hscore     |           u(X)                  |               y(X)                  |
            - pred_trans(local): List, Output tensor of D. On transformed images.
            Details: pred_trans
            |0       |1:1+u_size   |1+u_size:1+u_size+y_size|1+u_size+y_size:1+u_size*2+y_size|1+u_size*2+y_size:1+u_size*2+y_size*2|
            |pred_dis|loss_u_hscore|      loss_y_hscore     |           u(Z)                  |               y(Z)                  |
            - h_z(local): list, Output Tensors of T. h(y(Z)).
        """

        # Same implementation with neg_hscore, in case of mixing up with Lambda layer.
        def neg_hscore_loss(x):
            """
            neg hscore loss implementation
            """
            f = x[0]
            g = x[1]
            f0 = f - K.mean(f, axis=0)
            g0 = g - K.mean(g, axis=0)
            corr = tf.reduce_mean(tf.reduce_sum(tf.multiply(f0, g0), 1))
            cov_f = K.dot(K.transpose(f0), f0) / K.cast(K.shape(f0)[0] - 1, dtype='float32')
            cov_g = K.dot(K.transpose(g0), g0) / K.cast(K.shape(g0)[0] - 1, dtype='float32')
            return - corr + tf.trace(K.dot(cov_f, cov_g)) / 2

        ########### Part 0 ################
        ## Connecting three models
        self.img_a = Input(shape=self.image_size)  # Raw images tensor.

        self.attr_y = []  # sensitive_label tensor.
        self.attr_u = []  # public_label tensor.
        for i in range(self.y_size):
            self.attr_y.append(Input((self.y_input_dims[i],)))
        for j in range(self.u_size):
            self.attr_u.append(Input((self.u_input_dims[j],)))

        self.img_a_trans = self.g_model(self.img_a)  # Transformed image Tensor.
        pred_trans = self.d_model([self.img_a_trans] + self.attr_u + self.attr_y)  # D output tensor.

        ## end Connecting three models

        ############## Part I #################
        ## build D loss
        # compute u_loss in total
        for i in range(self.u_size):
            if i == 0:
                d_loss_u_total = pred_trans[i]
            else:
                d_loss_u_total += pred_trans[i]

        # compute y_loss in total
        for j in range(self.u_size, self.u_size + self.y_size):
            if j == self.u_size:
                d_loss_y_total = pred_trans[j]
            else:
                d_loss_y_total += pred_trans[j]

        # d_loss = u_loss+y_loss+loss_real+loss_fake+loss_gp
        if self.u_size == 0:
            self.d_loss = (1. / self.y_size) * self.gamma * d_loss_y_total
        else:
            self.d_loss = (1 / self.u_size) * d_loss_u_total + (1. / self.y_size) * self.gamma * d_loss_y_total
        ## end build D loss

        ############## Part II #################
        ## build G

        g_loss_y_total = d_loss_y_total
        g_loss_u_total = d_loss_u_total

        if self.u_size == 0:
            self.g_loss = - (1. / self.y_size) * self.gamma * g_loss_y_total
        else:
            self.g_loss = (1. / self.u_size) * g_loss_u_total - (1. / self.y_size) * self.gamma * g_loss_y_total
        ## end build G loss

        # save list for detail printing.
        self.d_loss_list_print = []
        if self.u_size > 0:
            self.d_loss_list_print.append(d_loss_u_total)
        self.d_loss_list_print.append(d_loss_y_total)

        self.g_loss_list_print = []
        if self.u_size > 0:
            self.g_loss_list_print.append(g_loss_u_total)
        self.g_loss_list_print.append(g_loss_y_total)

    def build_optimizer(self):

        self.g_training_updates = Adam(lr=self.lr, decay=5e-9, beta_1=self.b1, beta_2=self.b2).get_updates(
            self.g_model.trainable_weights, [], self.g_loss)
        self.g_train = K.function([self.img_a] + self.attr_u + self.attr_y, self.g_loss_list_print, self.g_training_updates)

        self.d_training_updates = Adam(lr=self.lr, decay=5e-9, beta_1=self.b1, beta_2=self.b2).get_updates(
            self.d_model.trainable_weights, [], self.d_loss)
        self.d_train = K.function([self.img_a] + self.attr_u + self.attr_y, self.d_loss_list_print,
                                  self.d_training_updates)
    def build_output(self):
        pass

    def train(self):
        dict_val, _ = next(self.celeba_generator.nextVal())
        sample_input_x = dict_val['input_x']
        save_some(sample_input_x[:10], os.path.join(self.log_dir, 'original_image'))
        loss_g = []
        loss_d = []
        for j in range(self.start_epoch, self.num_epochs):
            # clean up loss logs on epoch begin, loss list different when u_size = 0
            for i in range(self.celeba_generator.steps_per_epoch):
                dict_input, output = next(self.celeba_generator.nextTrain())
#                 output = output.reshape(self.batch_size)
                input_x = dict_input['input_x']
                input_y = dict_input['input_y']
                input_u = dict_input['input_u']
                input_y_batch = []
                input_u_batch = []
                for ind_1 in range(self.y_size):
                    input_y_batch.append(input_y[ind_1])
                for ind_2 in range(self.u_size):
                    input_u_batch.append(input_u[ind_2])
                for _ in range(self.d_ites):
                    errD = self.d_train([input_x] + input_u_batch + input_y_batch)
                errT = []
                for _ in range(self.g_ites):
                    errG = self.g_train([input_x] + input_u_batch + input_y_batch)

                if i % 100 == 0:
                    if self.u_size > 0:
                        print(
                            'epoch{}/{},batch:{}/{},loss_u D:{},loss_y D:{},loss_u G:{},loss_y G:{}'.
                                format(j, self.num_epochs, i, self.celeba_generator.steps_per_epoch,
                                       np.mean(errD[0]), np.mean(errD[1]), np.mean(errG[0]), np.mean(errG[1])))
                    else:
                        print(
                            'epoch{}/{},batch:{}/{},loss_y D:{},loss_y G:{}'.
                                format(j, self.num_epochs, i, self.celeba_generator.steps_per_epoch,
                                       np.mean(errD[0]), np.mean(errG[0]),
                                       ))

                    loss_d.append(np.mean(errD[0]))
#                     for ind_1 in range(len(d_loss_list)):
#                         loss_d[ind_1 + 1].append(np.mean(d_loss_list[ind_1]))

                    loss_g.append(np.mean(errD[1]))
#                     for ind_2 in range(len(g_loss_list)):
#                         loss_g[ind_2 + 1].append(np.mean(g_loss_list[ind_2]))

#                     loss_t.append(np.mean(errT))

                if i % 1000 == 0:
                    val_trans_x = self.g_model.predict(sample_input_x)
                    save_some(val_trans_x[:10], os.path.join(self.log_dir, 'predict_' + str(j) + '_' + str(i)))

            if (j+1) % 5 == 0:
                self.g_model.save_weights(os.path.join(self.log_dir, 'g_model_' + self.date + '_' + str(j) + '.h5'))
                self.d_model.save_weights(os.path.join(self.log_dir, 'd_model_' + self.date + '_' + str(j) + '.h5'))
        results_loss = {}
        results_loss['loss_u'] = loss_d
        results_loss['loss_y'] = loss_g
        np.save(os.path.join(self.log_dir, 'result_loss_' + self.date + '_' + str(j) + '.npy'), results_loss)

if __name__ == '__main__':
    import os
    from keras import backend as K
    from keras.backend.tensorflow_backend import set_session
    batch_size = 16
    K.set_learning_phase(False)
    set_session(tf.Session())

    for gamma in [1,10]:
        for ind_mode in range(3):
            log_dir = 'logs_mnist_mode_'+str(ind_mode)+'_gamma_'+str(gamma)
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)
            mnist_generator = reversedMNISTGenerator()
            privacy_net = privacyNetV4(log_dir=log_dir,
			                           g_model_dir=None,
			                           d_model_dir=None,
			                           start_epoch=0,
			                           batch_size=batch_size,
			                           image_size=(28, 28, 1),
			                           data_generator = mnist_generator,
			                           u_input_dims=[10],
			                           u_feat_dims=[10],
			                           y_feat_dims=[2],
			                           u_size = 1,
			                           mode=ind_mode,
			                           epochs=10, lambda_cls=1,
			                           gamma=gamma, activation='tanh',t_ites =1)
            privacy_net.train()


# import heapq

# N,M = map(int,input().split())
# G = []
# indegree = [0 for _ in range(N)] # 各ノードへの入次数を管理する。

# for _ in range(N):
#     G.append([])

# for _ in range(M):
#     A,B = map(int,input().split()) # AからBへ有向辺
#     G[A-1].append(B-1)
#     indegree[B-1] += 1

# heap = [] # 入次数が0のノードを保存する。辞書順で一番最初のものを出力する必要があり,idxの小さいものから取得する必要があるため、heapで管理

# for node in range(N):
#     if indegree[node] == 0:
#         heapq.heappush(heap, node)

# visited = [False for _ in range(N)]

# ans = []

# while len(heap) > 0:
#     cur_node = heapq.heappop(heap)

#     # if visited[cur_node]:#ノードを再訪している場合は、閉路が存在してしまっているため、
#     #     break
#     ans.append(cur_node)
#     # visited[cur_node] = True
#     for node_next_to in G[cur_node]:
#         indegree[node_next_to] -= 1
#         if indegree[node_next_to] == 0:
#             heapq.heappush(heap, node_next_to)

# if len(ans) != N:
#     print(-1)
#     exit(0)

# for i in range(N):
#     print(ans[i]+1,end=" ")

# import heapq

# N, M = map(int, input().split())
# route = [[] for _ in range(N+1)]
# in_deg = [0 for _ in range(N+1)]
# heap = []
# ans = []

# for _ in range(M):
#     a, b = map(int, input().split())
#     route[a].append(b)
#     in_deg[b] += 1

# for i in range(1, len(in_deg)):
#     if in_deg[i] == 0:
#         heapq.heappush(heap, i)

# # print(route)
# # print(in_deg)
# # print(heap)

# while heap:
#     num = heapq.heappop(heap)
#     ans.append(num)
#     if route[num]:
#         for i in route[num]:
#             in_deg[i] -= 1
#             if in_deg[i] == 0:
#                 heapq.heappush(heap, i)

# if len(ans) == N:
#     print(*ans)
# else:
#     print('-1')

# 先に現れる数字の中で、最小のものから取っていく
# 入次数が０の数字の中で最小のものを選んでいく
# 入次数が０の数字からでている有向辺の行き先の入次数を１減らす。
import heapq

N, M = map(int, input().split())
destination = [[] for _ in range(N+1)]
in_degree = [0] * (N+1)
hq = []
ans = []

for _ in range(M):
    A, B = map(int, input().split())
    destination[A].append(B)
    in_degree[B] += 1

for v in range(1, N+1):
    if in_degree[v] == 0:
        heapq.heappush(hq, v)

while hq:
    min_num = heapq.heappop(hq)
    ans.append(min_num)
    for j in destination[min_num]:
        in_degree[j] -= 1
        if in_degree[j] == 0:
            heapq.heappush(hq, j)

if len(ans) == N:
    print(*ans)
else:
    print(-1)


from tkinter import *
import random
import tkinter.messagebox as tmsg

root = Tk()

def play():
    random_number = random.randint(1, 6)
    number.config(text=f"Number is : {random_number}")
    if random_number == 6:
        tmsg.showinfo("Congratulations", "You Won !!")

number = Label(root)
number.pack(pady=10)

play = Button(root, text="Play", command=play)
play.pack(padx=50)
root.mainloop()


from main_functions import create_db_connection, create_server_connection, read_query, execute_query
from years_logic import add_years, add_35_years_or_not

# CONNECTIONS
connection = create_db_connection("localhost", "root", "", "kula_old_data")

# NEW CONNECTION TO NEW DATABASE
connection_kula = create_db_connection("localhost", "root", "", "kula_new")

# GETTING DATA
c_configuration_read = "SELECT * FROM c_configuration"
c_configuration_table_data = read_query(connection_kula, c_configuration_read)

for config in c_configuration_table_data:

    created_at = config[6]
    updated_at = config[7]
    deleted_at = config[9]

    if updated_at is None and created_at is not None:
        updated_at = created_at

    end_date = add_35_years_or_not(deleted_at, created_at, updated_at)

    migrate = f"UPDATE c_configuration SET c_end_date = '{end_date}' WHERE row_id = {config[0]};"
    execute_query(connection_kula, migrate)


from utils.RAMN_ISOTP_Handler   import *

#Class that handles KWP communication for one ECU
class RAMN_KWP_Handler:
    def __init__(self,ramn,tp,txid,rxid,name="Unknown"):
        self.ramn = ramn
        self.txid=txid
        self.rxid=rxid
        self.tp = tp
        self.ramn = ramn
        self.name = name

    #Send a Raw payload over KWP
    def sendRawData(self,toSend,timeout=RAMN_Utils.DEFAULT_TIMEOUT,recvAnswer=True):
        if isinstance(toSend,list):
            toSend = bytes(toSend)
        if len(toSend) > 0xFFF:
            log("Requested a payload which size is too big: {}".format(len(toSend)),LOG_ERROR)
            return None

        log("SEND: " + ''.join("{:02x}".format(i) for i in toSend),LOG_DEBUG)

        self.tp.sendFrame(toSend, self.txid, self.rxid)
        tstart = time.time()
        while timeout == 0 or (time.time() - tstart < timeout):

            payload = self.tp.update(recvAnswer,timeout)
            if recvAnswer:
                if payload != None:
                    log("RECV: " + ''.join("{:02x}".format(i) for i in payload),LOG_DEBUG)
                    return payload
            else:
                if self.tp.isTxOver():
                    return []
            return None

    #Send a KWP command with specified parameters
    def sendCommand(self, commandID, params=[],timeout=RAMN_Utils.DEFAULT_TIMEOUT, recvAnswer=True):
        r = self.sendRawData([commandID] + params,timeout, recvAnswer)
        if recvAnswer:
            if r == None:
                log("Timeout",LOG_ERROR)
                return 'b'
            elif len(r) == 0:
                log("Received Empty Data",LOG_ERROR)
                return b''
            elif r[0] == commandID + 0x40:
                return list(r[1:])
            elif r[0] == 0x7F: #negative command
                log("Received Negative RESPONSE: " + hex(r[2]) + " for COMMAND " + hex(r[1]) + " ",LOG_ERROR)
            else: log("Unexpected KWP RESPONSE: " + hex(r[0]),LOG_ERROR)
            return None
        return []

    #Sends a tester present command and wait for answer
    def testerPresent(self):
        if self.sendCommand(0x3E,[0x01]) != None :
            log("ECU responsed to Tester Present (TX:0x{:03x} RX:0x{:03x})".format(self.txid,self.rxid),LOG_DATA)
            return True
        else:
            log("ECU did not respond to Tester Present",LOG_ERROR)
            return False

    #Goes to specified diagnostic session
    def diagnosticSessionControl(self, session):
        return self.sendCommand(0x10,[session])

    #Request that ECU stops sending periodic messages
    def disablePeriodicSending(self):
        return self.sendCommand(0x28,[0x01])

    #Request that ECU resumes sending periodic messages
    def enablePeriodicSending(self):
        return self.sendCommand(0x29,[0x01])


import os

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

def strip_invalid_chars(name: str):
    chars = ['\\', '/', ':', '|', "*", '?', '<', '>', '"']

    for c in chars:

        if c == ':' or c == '/':
            rep = '-'
        else:
            rep = ''

        name = name.replace(c, rep)

    return name


# 75. Sort Colors
# Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
# We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

from typing import List

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i, j = 0, len(nums) - 1
        m = 0
        while i < j and m <= j:
            while nums[i] == 0 and i < j:
                i += 1
            while nums[j] == 2 and i < j:
                j -= 1
            if m < i:
                m = i
            while m <= j:
                if nums[m] == 0:
                    nums[i], nums[m] = nums[m], nums[i]
                    i += 1
                    break
                if nums[m] == 2:
                    nums[j], nums[m] = nums[m], nums[j]
                    j -= 1
                    break
                m += 1

if __name__ == '__main__':
    s = Solution()
    nums = [2, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
    s.sortColors(nums)
    print(nums)


import pendulum
from airflow import DAG
from airflow.decorators import dag, task

hosts = []

@task(multiple_outputs=True)
def parse_arguments(**kwargs):
    """
    #### Parse Arguments to the Task
    """
    global hosts
    hosts = eval(kwargs['dag_run'].conf['hosts'])

@task()
def run_task(host_ip):
    f"""
    #### Runs on {host_ip}
    """
    print(f"Running on {host_ip}")

with DAG(
    'parallel_pipeline2',
    schedule_interval=None,
    start_date=pendulum.datetime(2022, 4, 20, tz="UTC"),
    catchup=False,
    tags=['pipeline'],
) as dag:
    tasks = []
    for host in hosts:
        tasks.append(lambda: run_task(host))

    parse_arguments.set_downstream(tasks)


import re

# convert decimal to binary with at least minDigits number of bits
def DecToBin(number, minBits = 8):

	bin = ''

	while number > 0:

		j = number & 1
		bin = str(j) + bin
		number >>= 1

	while len(bin) < minBits:
		bin = '0' + bin

	return bin

# convert dotted ip address to dotted binary
def IPToBin(ip):

	ipDict = ip.split('.')
	index = 0
	binDict = { }

	for x in ipDict:

		binDict[index] = DecToBin(int(x))
		index += 1

	binIP = str(binDict[0]) + '.' + str(binDict[1]) + '.' + str(binDict[2])  + '.' + str(binDict[3])

	return binIP

# convert dotted binary to ip address
def BinToIP(binIP):

	binDict = binIP.split('.')
	index = 0
	ipDict = { }

	for x in binDict:

		ipDict[index] = int(x, 2)
		index += 1

	ip = str(ipDict[0]) + '.' + str(ipDict[1]) + '.' + str(ipDict[2]) + '.' + str(ipDict[3])

	return ip

# convert dotted ip address to long
def IPToLong(ip):

	ipDict = ip.split('.')
	long = 16777216*int(ipDict[0]) + 65536*int(ipDict[1]) + 256*int(ipDict[2]) + int(ipDict[3])
	return long

# convert long to dotted ip address
def LongToIP(long):

	ipDict = { }
	ipDict[0] = long / 16777216
	long = long - (ipDict[0] * 16777216)
	ipDict[1] = long / 65536
	long = long - (ipDict[1] * 65536)
	ipDict[2] = long / 256
	ipDict[3] = long - (ipDict[2] * 256)
	return str(ipDict[0]) + '.' + str(ipDict[1]) + '.' + str(ipDict[2]) + '.' + str(ipDict[3])

# convert dotted netmask to cidr
def NetmaskToCIDR(netmask):

	cidr = 0
	binNetmask = IPToBin(netmask)

	for x in binNetmask:
		if x == '1':
			cidr += 1

	return cidr

# convert cidr to dotted netmask
def CIDRToNetmask(cidr):

	netmask = ''

	for x in range(0,cidr):
		netmask += '1'

	netmask += '00000000000000000000000000000000'
	netmask = netmask[0:32]

	return BinToIP(netmask[0:8] + '.' + netmask[8:16] + '.' + netmask[16:24] + '.' + netmask[24:32])

# convert dotted ip and netmask to ip range
def NetmaskToRange(ip, netmask):

	baseCIDR = 32
	ipRange = { }

	netmaskCIDR = NetmaskToCIDR(netmask)
	hostCount = pow(2, (baseCIDR - netmaskCIDR))

	binIP = IPToBin(ip)
	binNetmask = IPToBin(netmask)

	longIP = IPToLong(ip)

	startAddress = ""

	index = 0

	for x in binIP:

		if x != '.':
			startAddress = startAddress + str( int(x) & int(binNetmask[index]) )
		else:
			startAddress = startAddress + '.'

		index += 1

	ipRange['startAddress'] = BinToIP(startAddress)
	ipRange['endAddress'] = LongToIP(IPToLong(ipRange['startAddress']) + hostCount - 1)

	return ipRange

def CIDRToRange(ipCIDR):

	parts = ipCIDR.split('/')
	if len(parts) == 2:
		baseIP = parts[0]
		subnet = CIDRToNetmask(int(parts[1]))
		ipRange = NetmaskToRange(baseIP, subnet)
		if ipRange:
			return ipRange

def convert_mac_to_long(value):

    if value is not None:
        new_value = value.replace('-', '')
        new_value = new_value.replace(':', '')
        if len(new_value) > 0:
                return long(new_value, 16)

def convert_long_to_mac(value):

    if value is not None:
        # 1 -- Get a hex version of the number
        basic_hex = hex(value)
        basic_hex = basic_hex.replace('0x', '')
        basic_hex = basic_hex.replace('L', '')
        basic_hex = basic_hex.zfill(12) # Add back the leading zeroes to ensure it is 12 characters long

        # 2 -- produce a string representing the MAC address with hex digits (uppercase) separated by colons

        #    2.1 -- Parse out the list of bytes
        regex = re.compile('([A-Fa-f0-9]{2,2})')
        match = regex.findall(basic_hex)

        final_string = None

        #    2.2 -- Append each byte to the final MAC address string
        if match is not None:
            for mac_byte in match:
                if final_string is None:
                    final_string = mac_byte.upper()
                else:
                    final_string =  final_string + ":" + mac_byte.upper()

        return final_string

    else:
        return None


REGION_FIELD_MAPPING = {
    'nuts3id': 'NUTS3ID',
    'nufttp': 'NUFTTP',
    'n0cd': 'N0CD',
    'n1cd': 'N1CD',
    'n2cd': 'N2CD',
    'n3cd': 'N3CD',
    'n0nme': 'N0NME',
    'n0nm': 'N0NM',
    'n1nm': 'N1NM',
    'n2nm': 'N2NM',
    'n3nm': 'N3NM',
    'n2_3cd': 'N2_3CD',
    'geom': 'POLYGON',
}


from django import forms
from django.core.validators import ValidationError
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.conf import settings
from django.forms.widgets import DateInput

from .models import Vaccine, Clinic, UserAppointBooking

class DashboardForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(DashboardForm, self).__init__(*args, **kwargs)

    class Meta:
        model = User
        widgets = {
            'username': forms.TextInput(attrs={'placeholder': 'Username'}),
            'email': forms.EmailInput(attrs={'placeholder': 'Email'}),
            'first_name': forms.TextInput(attrs={'placeholder': 'First Name'}),
            'last_name': forms.TextInput(attrs={'placeholder': 'Last Name'}),
        }
        fields = ['username', 'email', 'first_name', 'last_name']

class VaccineForm(forms.ModelForm):

    def __init__(self,  *args, **kwargs):
        # self.request = kwargs.pop('request')
        super(VaccineForm, self).__init__(*args, **kwargs)

    def clean_vaccine_for(self):
        name = self.cleaned_data.get('vaccine_for')
        try:
            match = Vaccine.objects.get(vaccine_for=name)
        except Vaccine.DoesNotExist:
            return name
        raise ValidationError(_('The Location already exist. Please update the value instead adding new.'))

    class Meta:
        model = Vaccine
        fields = ['vaccine_for', 'vaccine_name', 'quantity', 'clinic']

class ClinicForm(forms.ModelForm):

    # def __init__(self,  *args, **kwargs):
    #     self.request = kwargs.pop('request')
    #     super(ClinicForm, self).__init__(*args, **kwargs)

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get('phone_number')
        is_number = phone_number.isnumeric()

        if not is_number:
            raise ValidationError(_('The value must be a number.'))
        elif len(phone_number) != 10:
            raise ValidationError(_('The value can not be less than or greater than 10.'))
        else:
            return phone_number

    def clean_clinic_name(self):
        name = self.cleaned_data.get('clinic_name')
        try:
            match = Clinic.objects.get(clinic_name=name)
        except Clinic.DoesNotExist:
            return name
        raise ValidationError(_('The Clinic already exist. Please update the value instead adding new.'))
    class Meta:
        model = Clinic
        fields = ['clinic_name', 'address_line_one', 'address_line_two', 'postal_code', 'city', 'provinces',
        'phone_code', 'phone_number', 'website', 'opening_time', 'closing_time']

        widgets = {
                'closing_time': forms.TimeInput(format='%H:%M'),
            }

class UserAppointBookingForm(forms.ModelForm):

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get('phone_number')
        is_number = phone_number.isnumeric()
        if not is_number:
            raise ValidationError(_('The value must be a number.'))
        elif is_number != 10:
            raise ValidationError(_('The value can not be less than or greater than 10.'))
        else:
            return phone_number

    class Meta:
        widgets = {
            'DOB': DateInput()
        }
        model = UserAppointBooking
        fields = ['first_name', 'last_name', 'address_line_one', 'address_line_two', 'postal_code', 'city', 'provinces',
        'phone_code', 'phone_number', 'DOB', 'gender', 'health_card', 'which_dose', 'vaccine_name', 'choose_date']


# 题目
# 操作给定的二叉树，将其变换为源二叉树的镜像。
# 输入描述:
# 二叉树的镜像定义：源二叉树
#     	    8
#     	   /  \
#     	  6   10
#     	 / \  / \
#     	5  7 9 11
#     	镜像二叉树
#     	    8
#     	   /  \
#     	  10   6
#     	 / \  / \
#     	11 9 7  5

#思路
# 递归实现反转每个子节点

# -*- coding:utf-8 -*-
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        # A1_order_result=[]
        # self.order_traversal(A1,A1_order_result)
        if root is None:
            return
        if root.left is None and root.right is None:
            return
        temp=root.left
        root.left=root.right
        root.right=temp

        if root is not None:
            self.Mirror(root.left)
        if root is not None:
            self.Mirror(root.right)

    def order_traversal(self,root,result):
        if not root:
            return
        self.order_traversal(root.left,result)
        result.append(root.val)
        self.order_traversal(root.right,result)

if __name__=='__main__':
    A1 = TreeNode(8)
    A2 = TreeNode(6)
    A3 = TreeNode(10)
    A4 = TreeNode(5)
    A5 = TreeNode(7)
    A6 = TreeNode(9)
    A7 = TreeNode(11)
    A1.left=A2
    A1.right=A3
    A2.left=A4
    A2.right=A5
    A3.left=A6
    A3.right=A7

    temp1=[]
    solution=Solution()
    solution.order_traversal(A1,temp1)
    print(temp1)
    solution.Mirror(A1)
    solution.order_traversal(A1,temp1)
    print(temp1)

18.二叉树的镜像.py

18.二叉树的镜像.py


import re
import tweepy
import time
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import SGDClassifier

from sklearn import metrics

import matplotlib.pyplot as plt

import mysql.connector
from textblob import TextBlob

# app = Flask(__name__)

# @app.route("/")
# def index():
#     return "Hello World!"

def main():

    # tweets = pd.DataFrame(columns=['id','term','text','sent'])

    term = ''

    while True:
        term = input('Enter a search term: ')
        if term in ['exit', 'e', 'stop']:
            break
        elif term == 'stream':

            strm.append((input('Enter a term to stream: ')))

            getStream(strm[-1])
        else:
            tweets = {
                'term': [],
                'text': [],
                'sent': [],
            }

            getTweets(term, tweets)
            tweet_df = pd.DataFrame.from_dict(tweets)
            print(tweet_df.head(10))
            barChart(tweets)

            # tweet_df = pd.DataFrame(columns=['id','term','text','sent'])
            # database_option = input("Save results to database? ")
            # if database_option in ['Y', 'y', 'yes']:
            #     connectSQL(tweets, table='tweets')

            action = input('Save tweets to file? ')
            if action in ['yes', 'y', 'save']:
                saveTweets(tweets)

class tweepStreamListener(tweepy.StreamListener):

    def on_status(self, status):

        try:
            streamTextSize(status.extended_tweet['full_text'])

        except AttributeError:
            streamTextSize(status.text)

        # if not status.truncated:
        # else:

    def on_error(self, status_code):
        return super().on_error(status_code)

def streamTextSize(text):
    clean_stream = cleanTweet(text)

    # stream_tweets["id"].append(id)
    stream_tweets['term'].append(strm[-1])
    stream_tweets['text'].append(clean_stream)
    stream_tweets['sent'].append(nbSentiment(clean_stream))

def getStream(strm):
    runtime = int(input('how long should the stream run?: '))
    print('Now istening for: ' + strm)
    stream_listener = tweepStreamListener()
    stream = tweepy.Stream(auth=api.auth, listener=stream_listener)
    stream.filter(track=strm, is_async=True)
    time.sleep(runtime)

    print('Time\'s Up! Stream Connection Terminated.')
    stream.disconnect()
    #print (stream_tweets)
    stream_df = pd.DataFrame(stream_tweets)
    print(stream_df.head(10))

    barChart(stream_tweets)
    # database_option = input("Save results to database? ")
    # if database_option in ['Y', 'y', 'yes']:
    #     connectSQL(stream_tweets, table='stream')

    save_option = input('Save stream results to file? ')
    if save_option in ['Y', 'y', 'yes']:
        saveTweets(stream_tweets)

# def connectSQL(tweets, table):

#     try:
#         connection = mysql.connector.connect(
#             user="root",
#             password="",
#             host="127.0.0.1",
#             database="pytwitter"
#         )

#         cursor = connection.cursor()

#         addtoTable(connection, tweets, table)

#     except connection.Error as err:
#         print(err)

# def addtoTable(connection, tweets, table):
#     x = connection.cursor()
#     for i in range(0, len(tweets['text'])):
#         if table == 'tweets':
#             x.execute('INSERT INTO tweets (search,text,sentiment) VALUES (%s,%s,%s)', (str(
#                 tweets['term'][i]), str(tweets['text'][i]), str(tweets['sent'][i])))

#         elif table == 'stream':
#             x.execute("INSERT INTO streamtweets (search,text,sentiment) VALUES (%s,%s,%s)", (str(
#                 tweets['term'][i]), str(tweets['text'][i]), str(tweets['sent'][i])))

#     connection.commit()

def getTweets(term, tweets):
    for t in tweepy.Cursor(api.search, q='%s -filter:retweets' % term, lang='en', tweet_mode='extended').items(50):
        clean_text = str(cleanTweet(t.full_text))
        if clean_text not in tweets['text']:

            # print(clean_text)
            # tweets = tweets.append({'id': t.id, 'term': term, 'text': clean_text , 'sent': tblobSentiment(clean_text)}, ignore_index=True)

            # tweets["id"].append(t.id)
            tweets['term'].append(term)
            tweets['text'].append(clean_text)
            tweets['sent'].append(nbSentiment(clean_text))
            # tweets["like"].append(t.retweeted_status.favorite_count)
            # tweets["rtwt"].append(t.retweeted_status.retweet_count)
            # tweets["date"].append(t.created_at)
            # tweets["geo"].append(t.geo)

    return tweets

def nbTrain(dataset):
    # dataset.head()
    pass
    # X_train_counts = count_vect.fit_transform(dataset.data)
    # X_train_counts.shape

def tblobSentiment(t):  # function for checking tweet polarity
    tw_sent = TextBlob(t)
    if tw_sent.sentiment.polarity > 0:
        return 'Positive'  # positive tweets
    elif tw_sent.sentiment.polarity == 0:
        return 'Neutral'  # negative tweets
    else:
        return 'Negative'  # tweets with no strong polarity

def cleanTweet(t):
    # clean_text=re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t]) |(\w+:\/\/\S+)", " ", t).split()
    t = re.sub('@[A-Za-z0-9]+', '', t)  # removes Twitter handles/@symbol
    t = re.sub(r'(?:\@|http?\://|https?\://|www)\S+', '', t)  # removes URLs
    t = t.replace("#", "").replace("_", " ")  # remove hashtags and underscores
    t = " ".join(t.split())
    return t

def saveTweets(tweets):
    # try:
    with open(input('Enter a file name: '), 'a+', encoding='utf-8') as tdata:
        tdata.seek(0)
        if tdata.read() == '':
            tdata.write('Search, Tweet, Sentiment\n')

        rows = len(tweets['term'])
        for i in range(0, len(tweets['term'])):
            tdata.write(str(tweets['term'][i]) + ',' + str(tweets['text']
                        [i]).replace(',', ' ')+','+str(tweets['sent'][i])+'\n')

        print('Saved ' + str(rows) + ' rows.\n')

    # # tdata.write(str(tweets["term"][i])+ "," + str(tweets["text"][i]).replace(","," ")+","+str(tweets["sent"][i])+","
    # # +str(tweets["like"][i])+","+str(tweets["rtwt"][i])+"\n")
    #     else:
    #         tdata.write(str(tweets["term"][i]) + "," + str(tweets["text"]
    #                     [i]).replace(",", " ")+","+str(tweets["sent"][i])+"\n")
    tdata.close()
    # except:
    #     print("Error with save.")

def barChart(t):
    bar_data = {'pos':0, 'neg':0, 'neu':0}
    bar_sent = []
    for s in t['sent']:
        bar_sent.append(str(s))

    for i in bar_sent:
        if i == 'Positive':
            bar_data['pos'] += 1
        elif i == 'Negative':
            bar_data['neg'] += 1
        else:
            bar_data['neu'] += 1

    bkey = bar_data.keys()
    bval = bar_data.values()
    # %matplotlib inline
    plt.bar(bkey,bval)
    plt.show()

if __name__ == "__main__":
    # app.run(host="127.0.0.1", port=8080, debug=True)
    # Twitter API keys
    consumer_key = ""
    consumer_secret = ""
    access_token = ""
    access_token_secret = ""

    auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)  # authorises and enables Tweepy API

    stream_tweets = {
        # "id": [],
        "term": [],
        "text": [],
        "sent": []
    }

    strm = []

    fields = ['tweet', 'polarity']
    # findcsv = open(,'r')
    # trainingcsv = findcsv.read()
    traning_data = pd.read_csv('d:/OneDrive/LSBU/Year 3/Final Year Project/mysite/business.csv',
                               usecols=[1, 2], low_memory=True, names=fields, dtype=str)

    csv_df = pd.DataFrame(traning_data)

    print(csv_df)

    tweets_corpus = []
    for i in traning_data['tweet']:
        tweets_corpus.append(cleanTweet(i))

    vect = TfidfVectorizer(stop_words='english', ngram_range=(1, 3))
    X = vect.fit_transform(tweets_corpus)
    y = traning_data['polarity']
    mnb = MultinomialNB(fit_prior=True).fit(X, y)

    def nbSentiment(t):
        t = [t]
        X_test = vect.transform(t)
        y_pred = mnb.predict(X_test)

        t = y_pred[-1]

        # if y_pred == 'Negative':
        #     t = 'Negative'
        # elif y_pred == '4':
        #     t = 'Positive'
        # else:
        #     t = 'Neutral'

        return t

    main()


"""
Cho một xâu ký tự. Quá trình mã hóa D - R - M sẽ trải qua ba bước Chia (Divide), Xoay (Rotate) và Trộn (Merge). Ví dụ với xâu: EWPGAJRB  quá trình này sẽ diễn ra như sau:

Devide: Xâu ban đầu được chia thành 2 nửa: “EWPG” và “AJRB”.
Rotate: Với mỗi nửa, tính toán giá trị xoay của nó bằng cách tính tổng giá trị các ký tự. (A = 0; B = 1; … Z = 25).  Giá trị xoay của “EWPG” là 4 + 22 + 15 + 6 = 47. Tiến hành xoay xâu  “EWPG”  đi 47 ký tự (tính cả bước chuyển từ Z về A nếu cần) ta sẽ được xâu: “ZRKB”. Tương tự, “AJRB” được chuyển thành “BKSC”
Merge: Trong bước này, mỗi ký tự trong xâu thứ nhất sẽ được xoay theo giá trị của ký tự ở vị trí tương ứng trong xâu thứ 2. Trong ví dụ trên, chữ Z trong xâu thứ nhất sẽ xoay theo giá trị B, tức là 1 vị trí. Do đó sẽ chuyển thành chữ A. Tiếp tục thực hiện với các ký tự tiếp theo ta sẽ có kết quả là “ABCD”.
Input:
3
EWPGAJRB
BB
TPQJDRJWSQXGRRIPXFMINTELHBJA
Output:
ABCD
E
FIRSTDATAFILEV
"""
def func():
    ss=input()
    l=int(len(ss)/2)
    str=''
    str1=''
    #devide
    for i in range(l): str+=ss[i]
    for i in range(l,l*2): str1+=ss[i]
    #rotate
    x=0
    x1=0

    for i in str: x+=ord(i)-65
    for i in str1: x1+=ord(i)-65

    s=''
    s1=''
    for i in str:
        m=(ord(i)-65+x)%26
        s+= chr(m+65)
    for i in str1:
        m=(ord(i)-65+x1)%26
        s1+= chr(m+65)

    #Merge
    for i in range(l):
        m=(ord(s[i])-65 + ord(s1[i])-65)%26
        print(chr(m+65),end='')
    print()

for i in range(int(input())):func()