import logging
import time
from abc import ABC, abstractmethod
from logging import Logger
from typing import Any, Optional

from robot_interface.models.exceptions.robot_exceptions import (
    RobotRetrieveInspectionException,
)
from roslibpy import Message, Ros
from roslibpy import Topic as RosTopic

from isar_turtlebot.settings import settings

class TopicInterface(ABC):
    @abstractmethod
    def publish(self, message: Any) -> None:
        pass

    @abstractmethod
    def get_value(self) -> Optional[Any]:
        pass

class ImageTopicInterface(ABC):
    @abstractmethod
    def get_image(self) -> bytes:
        pass

class Topic(TopicInterface):
    def __init__(
        self,
        client: Ros,
        name: str,
        message_type: str,
        throttle_rate: int = 0,
        queue_size: int = 100,
        queue_length: int = 0,
        log_callbacks: bool = False,
    ) -> None:
        self.name: str = name
        self.topic: RosTopic = RosTopic(
            ros=client,
            name=name,
            message_type=message_type,
            throttle_rate=throttle_rate,
            queue_size=queue_size,
            queue_length=queue_length,
        )

        self.log_callbacks: bool = log_callbacks
        if self.log_callbacks:
            self.logger: Logger = logging.getLogger("turtlebot_bridge")

        self.value: Optional[Any] = None

        self.subscribe()

    def publish(self, message: Any) -> None:
        self.topic.publish(Message(message))

    def get_value(self) -> Optional[Any]:
        return self.value

    def on_message(self, message: dict) -> None:
        self.value = message
        if self.log_callbacks:
            self.logger.debug(f"Updated value for topic {self.name}")

    def subscribe(self) -> None:
        self.topic.subscribe(self.on_message)

class ImageTopic(ImageTopicInterface):
    def __init__(
        self,
        client: Ros,
        name: str,
        message_type: str,
        throttle_rate: int = 0,
        queue_size: int = 100,
        queue_length: int = 0,
        log_callbacks: bool = False,
        get_image_timeout: float = settings.GET_IMAGE_TIMEOUT,
    ) -> None:
        self.name: str = name
        self.topic: RosTopic = RosTopic(
            ros=client,
            name=name,
            message_type=message_type,
            throttle_rate=throttle_rate,
            queue_size=queue_size,
            queue_length=queue_length,
        )
        self.log_callbacks: bool = log_callbacks
        if self.log_callbacks:
            self.logger: Logger = logging.getLogger("turtlebot_bridge")

        self.image: Optional[bytes] = None
        self.take_image: bool = False
        self.get_image_timeout: float = get_image_timeout

        self.subscribe()

    def publish(self, message: Any) -> None:
        self.topic.publish(Message(message))

    def subscribe(self) -> None:
        self.topic.subscribe(self.on_image)

    def on_image(self, message: dict) -> None:
        if self.take_image:
            self.image = message["data"].encode("ascii")
        else:
            self.image = None

        if self.log_callbacks:
            self.logger.debug(f"Updated value for topic {self.name}")

    def get_image(self) -> Optional[bytes]:
        self.take_image = True
        start_time = time.time()
        while not self.image:
            time.sleep(0.1)
            execution_time: float = time.time() - start_time
            if execution_time > self.get_image_timeout:
                error_description: str = "Timed our while fetching the image"
                self.logger.error(error_description)
                raise RobotRetrieveInspectionException(
                    error_description=error_description
                )

        self.take_image = False
        return self.image


from heapq import *

"""
    You're given a list of n integers arr[0..(n-1)].
    You must compute a list output[0..(n-1)] such that, for each index i (between 0 and n-1, inclusive), output[i] is equal to the product of the three largest elements out of arr[0..i] (or equal to -1 if i < 2, as arr[0..i] then includes fewer than three elements).
    Note that the three largest elements used to form any product may have the same values as one another, but they must be at different indices in arr.

    Signature
    int[] findMaxProduct(int[] arr)

    Input
    n is in the range [1, 100,000].
    Each value arr[i] is in the range [1, 1,000].

    Output
    Return a list of n integers output[0..(n-1)], as described above.

    Example 1
    n = 5
    arr = [1, 2, 3, 4, 5]
    output = [-1, -1, 6, 24, 60]
    The 3rd element of output is 3*2*1 = 6, the 4th is 4*3*2 = 24, and the 5th is 5*4*3 = 60.

    Example 2
    n = 5
    arr = [2, 1, 2, 1, 2]
    output = [-1, -1, 4, 4, 8]
    The 3rd element of output is 2*2*1 = 4, the 4th is 2*2*1 = 4, and the 5th is 2*2*2 = 8.
"""

def findMaxProduct(arr):
    n = len(arr)
    res = n * [-1]
    maxheap = []
    for i in range(n):
        heappush(maxheap, -arr[i])
        if i >= 2:
            a = -heappop(maxheap)
            b = -heappop(maxheap)
            c = -maxheap[0]
            res[i] = a * b * c
            heappush(maxheap, -a)
            heappush(maxheap, -b)
    return res


from OpenGL.GL import (
    glBindTexture,
    GL_TEXTURE_2D,
    glTexImage2D,
    GL_RGBA,
    GL_UNSIGNED_BYTE,
    glGenTextures,
    glTexParameteri,
    GL_TEXTURE_MIN_FILTER,
    GL_NEAREST,
    GL_CLAMP_TO_EDGE,
    GL_TEXTURE_MAG_FILTER,
    GL_TEXTURE_WRAP_S,
    GL_TEXTURE_WRAP_T,
)
from typing import Generator, Any, Tuple, Dict, Optional
import struct
import hashlib
import os
import json
from PIL import Image
import numpy
import glob
import logging

from minecraft_model_reader.api.resource_pack.base import BaseResourcePackManager
from minecraft_model_reader import BlockMesh
import PyMCTranslate
from amulet.api.block import Block

from amulet_map_editor.api.opengl import textureatlas

log = logging.getLogger(__name__)

class OpenGLResourcePack:
    """This class will take a minecraft_model_reader resource pack and
    load all of the textures into a texture atlas."""

    _translator: PyMCTranslate.Version
    _block_models: Dict[Block, BlockMesh]
    _texture_bounds: Dict[Any, Tuple[float, float, float, float]]
    _image: Optional[numpy.ndarray]
    _image_width: int
    _image_height: int
    _gl_textures: Dict[str, int]

    def __init__(
        self, resource_pack: BaseResourcePackManager, translator: PyMCTranslate.Version
    ):
        self._resource_pack = resource_pack
        self._translator = translator
        self._block_models: Dict[Block, BlockMesh] = {}

        self._texture_bounds: Dict[str, Tuple[float, float, float, float]] = {}
        self._image: Optional[Image.Image] = None
        self._image_width: int = 0
        self._image_height: int = 0

        self._gl_textures: Dict[str, int] = {}

    def get_atlas_id(self, context_id: str) -> int:
        """Get the opengl texture id of the atlas for a given context."""
        if context_id not in self._gl_textures:
            if self._image is None:
                raise Exception(
                    "OpenGLResourcePack.setup() needs to be run before accessing a texture."
                )
            self._setup_texture(context_id)
        return self._gl_textures[context_id]

    def get_texture_path(self, namespace: Optional[str], relative_path: str):
        """Get the absolute path of the image from the relative components.
        Useful for getting the id of textures for hard coded textures not connected to a resource pack.
        """
        return self._resource_pack.get_texture_path(namespace, relative_path)

    def texture_bounds(self, texture_path: str) -> Tuple[float, float, float, float]:
        """Get the bounding box of a given texture path."""
        if texture_path in self._texture_bounds:
            return self._texture_bounds[texture_path]
        else:
            return self._texture_bounds[self._resource_pack.missing_no]

    @property
    def translator(self) -> PyMCTranslate.Version:
        """The translator used to convert the universal blocks into the required version for the resource pack."""
        return self._translator

    def setup(self) -> Generator[float, None, None]:
        """Create and bind the atlas texture."""
        if self._image is None:
            cache_id = struct.unpack(
                "H",
                hashlib.sha1(
                    "".join(self._resource_pack.pack_paths).encode("utf-8")
                ).digest()[:2],
            )[0]

            atlas: Image.Image

            if not self._resource_pack.pack_paths:
                log.warning("There are no resource packs to load.")

            mod_time = max(
                (
                    os.stat(path).st_mtime
                    for pack in self._resource_pack.pack_paths
                    for path in glob.glob(
                        os.path.join(glob.escape(pack), "**", "*.*"), recursive=True
                    )
                ),
                default=0,
            )

            cache_dir = os.path.join(os.environ["CACHE_DIR"], "resource_packs", "atlas")
            img_path = os.path.join(cache_dir, f"{cache_id}.png")
            bounds_path = os.path.join(cache_dir, f"{cache_id}.json")
            try:
                with open(bounds_path) as f:
                    cache_mod_time, bounds = json.load(f)
                if mod_time != cache_mod_time:
                    raise Exception(
                        "The resource packs have changed since last merging."
                    )
                atlas = Image.open(img_path)
            except:
                atlas_iter = textureatlas.create_atlas_iter(
                    self._resource_pack.textures
                )
                try:
                    while True:
                        yield next(atlas_iter)
                except StopIteration as e:
                    (
                        atlas,
                        bounds,
                    ) = e.value
                    os.makedirs(cache_dir, exist_ok=True)
                    atlas.save(img_path)
                    with open(bounds_path, "w") as f:
                        json.dump((mod_time, bounds), f)

            self._image_width, self._image_height = atlas.size
            self._image = numpy.array(atlas, numpy.uint8).ravel()
            self._texture_bounds = bounds

    def _setup_texture(self, context_id: str):
        """Set up the texture for a given context"""
        gl_texture = self._gl_textures[context_id] = glGenTextures(
            1
        )  # Create the texture location
        glBindTexture(GL_TEXTURE_2D, gl_texture)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)

        glBindTexture(GL_TEXTURE_2D, gl_texture)
        glTexImage2D(
            GL_TEXTURE_2D,
            0,
            GL_RGBA,
            self._image_width,
            self._image_height,
            0,
            GL_RGBA,
            GL_UNSIGNED_BYTE,
            self._image,
        )
        glBindTexture(GL_TEXTURE_2D, 0)
        log.info("Finished setting up texture atlas in OpenGL")

    def get_block_model(self, universal_block: Block) -> BlockMesh:
        """Get the BlockMesh class for a given universal Block.
        The Block will be translated to the version format using the
        previously specified translator."""
        if universal_block not in self._block_models:
            version_block = self._translator.block.from_universal(
                universal_block.base_block
            )[0]
            if universal_block.extra_blocks:
                for block_ in universal_block.extra_blocks:
                    version_block += self._translator.block.from_universal(block_)[0]

            self._block_models[universal_block] = self._resource_pack.get_block_model(
                version_block
            )

        return self._block_models[universal_block]


"""
LAMBDA FUNCTION:
it is funciton without  a name
"""
f=lambda x,y:x+y
print(f(1,1))

"""

lambda is always used with map function
map has two argument 1st one is a function and 2nd one is the sequence
map(function,seq)

"""

Celsius=[39.5,36.5,37.3,37.8]
Fahrenhiet=list(map(lambda x:(float(9)/5)*x +32,Celsius))
print(Fahrenhiet)

c=list(map(lambda x:(float(5)/9)*(x-32),Fahrenhiet))
print(c)

a=[1,2,3,4]
b=[17,12,11,10]

print(list(map(lambda x,y:x+y,a,b)))


#importing libraries and init program
import pygame
import sys
import os
from pygame.locals import *
pygame.init()

import random

#changes cwd to the project folder
os.chdir('..')

#fps value
fps = 30
frame_per_sec = pygame.time.Clock()

#colors
green = (0, 100, 0)
blue = (0, 153, 255)
white = (255, 255, 255)
red = (255, 0, 0)
black = (0, 0, 0)
yellow = (230, 184, 0)

#display w caption
display_surf = pygame.display.set_mode((1920,1080))
display_surf.fill(green)
pygame.display.set_caption("Blackjack")

#deck
deck = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
#bust booleans
player_bust = False
dealer_bust = False
#stand booleans
player_stand = False
#quit boolean
quit = False
#deck values
player_deck = 0
dealer_deck = 0
#lists
player_list = []
dealer_list = []
#dealer positions
dealer_x = 740
dealer_y = 122
#player positions
player_x = 740
player_y = 662

#function to hit
def hit(person_deck, person_list, person, person_x, person_y):
    card = deck[random.randint(0,12)]
    if isinstance(card, str) and card!= "A":
        card_value = 10
        if "A" in person_list and (person_deck +10 > 21):
            card_value = 0
        person_list.append(card)
        image = display_card(card)
        display_surf.blit(image, (person_x, person_y))
        return card_value
    elif card == "A":
        if (person_deck + 11 > 21):
            person_list.append(card)
            hard_hand(person_list)
            card_value = 1
            image = display_card(card)
            display_surf.blit(image, (person_x, person_y))
            return card_value
        else:
            person_list.append(card)
            card_value = 11
            image = display_card(card)
            display_surf.blit(image, (person_x, person_y))
            return card_value
    else:
        person_list.append(card)
        if "A" in person_list and (person_deck + card > 21):
            hard_hand(person_list)
            card_value = (card - 10)
        else:
            card_value = card
        image = display_card(card)
        display_surf.blit(image, (person_x, person_y))
        return card

#changes the list once it changes to a hard hand
def hard_hand(person_list):
    for i in range(0, len(person_list)):
        if person_list[i] == "A":
            person_list[i] = "a"

#makes the card to image
def display_card(card):
    if card == 2:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '2.jpg'))
        return image
    elif card == 3:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '3.jpg'))
        return image
    elif card == 4:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '4.jpg'))
        return image
    elif card == 5:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '5.jpg'))
        return image
    elif card == 6:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '6.jpg'))
        return image
    elif card == 7:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '7.jpg'))
        return image
    elif card == 8:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '8.jpg'))
        return image
    elif card == 9:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '9.jpg'))
        return image
    elif card == 10:
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', '10.jpg'))
        return image
    elif card == "J":
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', 'J.jpg'))
        return image
    elif card == "Q":
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', 'Q.jpq'))
        return image
    elif card == "K":
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', 'K.jpg'))
        return image
    elif card == "A":
        image = pygame.image.load(os.path.join(os.getcwd(), 'Assets', 'A.jpg'))
        return image

class button():
    def __init__(self, color, x, y, width, height, text):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win):
        pygame.draw.rect(win, black, (self.x-2, self.y-2, self.width+4, self.height+4), 0)
        #draws button to screen
        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)
        font = pygame.font.SysFont("trebuchet ms", 40)
        text = font.render(self.text, 1, (0,0,0))
        win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))

def is_clicked(x, y, width, height):
    if (pygame.mouse.get_pos()[0] >= x and pygame.mouse.get_pos()[0] <= (x + width)) and (pygame.mouse.get_pos()[1] >= y and pygame.mouse.get_pos()[1] <= (y + height)):
        return True

hit_button = button(blue, 806, 510, 130, 60, "HIT")
hit_button.draw(display_surf)

stand_button = button(yellow, 982, 510, 130, 60, "STAND")
stand_button.draw(display_surf)

exit_button = button(red, 60, 60, 60, 60, "X")
exit_button.draw(display_surf)

#Deal dealer's deck
image = pygame.image.load(r'C:\Users\charl\source\repos\blackjack3.0\Assets\template.jpg')
display_surf.blit(image, (dealer_x, dealer_y))
dealer_x += 240
dealer_deck += hit(dealer_deck, dealer_list, "dealer", dealer_x, dealer_y)
dealer_x +=240

#deal player's deck
for i in range(2):
    player_deck += hit(player_deck, player_list, "player", player_x, player_y)
    player_x += 240

while True:
    pygame.display.update()
    for event in pygame.event.get():
        #checks to see if the exit button was clicked
        #if event.type == QUIT:
        #    quit = True
        #    break
        #checks to see if the mouse clicked the hit button
        if pygame.mouse.get_pressed() == (1, 0, 0):
            if is_clicked(806, 510, 130, 60):
                #player hit
                player_deck += hit(player_deck, player_list, "player", player_x, player_y)
                player_x += 240
                if player_deck > 21:
                    pygame.display.update()
                    player_bust = True
                    break
        if pygame.mouse.get_pressed() == (1, 0, 0):
            if is_clicked(60, 60, 60, 60):
                quit = True
                #pygame.quit()
                break
        if pygame.mouse.get_pressed() == (1, 0, 0):
            if is_clicked(982, 510, 130, 60):
                player_stand = True
                break
    frame_per_sec.tick(fps)
    if quit == True:
        break
    if player_stand == True:
        break
    if player_bust == True:
        break

#dealer's turn
if quit == False:
    if player_bust == False:
        dealer_x -= 480
        dealer_deck += hit(dealer_deck, dealer_list, "dealer", dealer_x, dealer_y)
        dealer_x += 480
        while True:
            pygame.display.update()
            if dealer_deck < 17:
                dealer_deck += hit(dealer_deck, dealer_list, "dealer", dealer_x, dealer_y)
                dealer_x += 240
                pygame.time.delay(1000)
                if dealer_deck > 21:
                    pygame.display.update()
                    dealer_bust = True
                    break
            if dealer_deck == 17 and "A" in dealer_list:
                dealer_deck += hit(dealer_deck, dealer_list, "dealer", dealer_x, dealer_y)
                dealer_x += 240
                break
            if dealer_deck >= 17:
                break
            frame_per_sec.tick(fps)

#evaluates who won and creates a banner to say who won
if player_bust == True:
    end_button = button(red, 740, 464, 440, 152, "BUST")
    end_button.draw(display_surf)
elif dealer_bust == True:
    end_button = button(yellow, 740, 464, 440, 152, "DEALER BUSTED")
    end_button.draw(display_surf)
elif dealer_deck > player_deck and dealer_bust == False:
    end_button = button(red, 740, 464, 440, 152, "DEALER WINS")
    end_button.draw(display_surf)
elif player_deck > dealer_deck and player_bust == False:
    end_button = button(yellow, 740, 464, 440, 152, "PLAYER WINS")
    end_button.draw(display_surf)
elif player_deck == dealer_deck:
    end_button = button(white, 740, 464, 440, 152, "STAND")
    end_button.draw(display_surf)

#adds the end banner and checks to see if clicks exit button
if quit == False:
    while True:
        pygame.display.update()
        for event in pygame.event.get():
            #checks to see if the exit button was clicked
            if event.type == QUIT:
                quit = True
                break
            if pygame.mouse.get_pressed() == (1, 0, 0):
                if is_clicked(60, 60, 60, 60):
                    pygame.quit()
                    quit = True
                    break
        if quit == True:
            break
        frame_per_sec.tick(fps)


def read_file(filename):
	lines = []
	with open(filename, 'r', encoding='utf-8-sig') as f:
		for line in f:
			lines.append(line.strip())
	return lines
def convert(lines):
	new = []
	person = None
	allen_word_count = 0
	allen_sticker_count = 0
	allen_image_count = 0
	viki_word_count = 0.
	viki_sticker_count = 0
	viki_image_count = 0
	for line in lines:
		s = line.split(' ')
		time = s[0]
		name = s[1]
		if name == 'Allen':
			if '貼圖' in s[2:]:
				allen_sticker_count += 1
			elif '圖片' in s[2:]:
				allen_image_count += 1
			else:
				for word in s[2:]:
					allen_word_count += len(word)

		elif name == 'Viki':
			if '貼圖' in s[2:]:
				viki_sticker_count += 1
			elif '圖片' in s[2:]:
				viki_image_count += 1
			else:
				for word in s[2:]:
					viki_word_count += len(word)
	print('allen說了', allen_word_count, '字')
	print('傳了', allen_sticker_count, '張貼圖')
	print('傳了', allen_image_count, '張圖片')
	print('viki說了', viki_word_count, '字')
	print('傳了', viki_sticker_count, '張貼圖')
	print('傳了', viki_image_count, '張圖片')

		#print(s)

	return new
def write_file(filename,lines):
	with open(filename, 'w', encoding='utf-8') as d:
		for line in lines:
			d.write(line + '\n')
def main():
	filename = '-LINE-Viki.txt'
	lines = read_file('-LINE-Viki.txt')
	lines = convert(lines)
	#write_file(filename,lines)
main()


# -*- coding: utf-8 -*-
import openpyxl
import os
import copy
import csv

all_file = os.listdir()
all_program = []
all_computers = []
clear_list = []
ignor_list = []

#  функция загркузки xlsx файла
def load_xlsx(file):
    xls = file.split('.')[-1]
    if xls == 'xlsx':
        wb = openpyxl.load_workbook(file)
        sheet = wb['Лист1']
        return sheet

# ищем все программы по всех файлах и составляем список всех программ
for file in all_file:
    sheet = load_xlsx(file)
    if sheet is not None:
        for i in range(1, 200):
            prog_name = sheet.cell(row=i, column=1).value
            if prog_name is None:
                break
            if not prog_name in all_program:
                all_program.append(prog_name)

# пишем список всех программ в текстовый файл
if os.path.isfile('all_prog.txt') is not True:
    with open('all_prog.txt', 'a', encoding='utf-8') as f_obj:
        for proga in all_program:
            string = f'{proga}\n'
            f_obj.write(string)

# Подгружаем в память список игнорируемых программ
with open('ignor_list.txt', 'r', encoding='utf-8') as ignor:
    for proga in ignor:
        proga = proga.split('\n')[0]
        ignor_list.append(proga)

# чистим список с программами
for ignor in ignor_list:
    if ignor in all_program:
        index = all_program.index(ignor)
        all_program.pop(index)

# сортируем список по алфавиту
all_program.sort()
all_program.insert(0, 'Комп')

# генерис список, который потом будем заоплнять программами в будущей таблице
clear_list = [x*0 for x in range(len(all_program))]

# сверяем программы из каждого файла со списком всех программ
for file in all_file:
    sheet = load_xlsx(file)
    if sheet is not None:
        buffer = copy.deepcopy(clear_list)
        for i in range(1, 200):
            prog_name = sheet.cell(row=i, column=1).value
            if prog_name is None:
                break
            for index, count in enumerate(all_program):
                if prog_name == count or buffer[index] == 1:
                    buffer[index] = 1
                else:
                    buffer[index] = 0
        buffer[0] = file
        all_computers.append(buffer)
        buffer = clear_list

# записываем результат в отчет в формате csv
result = "result.csv"
data = [[1, 1, 1], [2,2, 2], [3, 3, 3]]
with open(result, "w", newline='') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for index, comp in enumerate(all_computers):
        if index == 0:
            writer.writerow(all_program)
        writer.writerow(comp)


from enum import Enum
from abc import ABC, abstractmethod

from uncertainty.utypes import *

class IncubatorState(Enum):
    Heating = 1
    CoolingDown = 2

class ActiveObject:

    @abstractmethod
    def action(self):
        pass

class Clock:

    def __init__(self):
        self.now : float = 0.0
        self.timeStep : float = 3
        self.activeObjects : list[ActiveObject] = []

    def tick(self):
        self.now = self.now + self.timeStep
        for o in filter(lambda p : not isinstance(p, Controller), self.activeObjects):
            o.action()

        for o in filter(lambda p : isinstance(p, Controller), self.activeObjects):
            o.action()

    def run(self, n:int):
        for i in range(n):
            self.tick()

    def addObject(self, activeObject):
        if isinstance(activeObject, ActiveObject):
            self.activeObjects.append(activeObject)

class Incubator(ActiveObject):
    def __init__(self):
        super().__init__()
        self.cAir : ufloat #  mass of object inside box * capacity of air inside box
        self.gBox : ufloat #  link the difference between the room temperature and the air temperature inside the box with the energy flowing to the box
        self.voltage : ufloat = ufloat(0, 0.05)
        self.onVoltage : ufloat = ufloat(18, 0.05)
        self.current : ufloat = ufloat(4, 0.05)
        self.tBair : ufloat = ufloat(22.8125, 0.05) #  temperature inside box
        self.tRoom : ufloat = ufloat(20, 0.05) #  temperature of the room
        self.currentState : IncubatorState = IncubatorState.CoolingDown
        self.numericalPrecision : ufloat = ufloat(0, 0.05)

    @abstractmethod
    def calculateTemperature(self, timeIncrement : ufloat) -> ufloat:
        pass

class Incubator2P(Incubator):
    def init(self):
        super().__init__()
        self.cAir = ufloat(616.56, 0.05)
        self.gBox = ufloat(0.65, 0.05)

    def calculateTemperature(self, timeIncrement : ufloat) -> ufloat:
            (1/self.cAir)*(self.voltage * self.current * timeIncrement - self.gBox * (self.tBair - self.tRoom))

    def action(self):
            self.tBair : self.tBair + self.clock.timeStep*self.calculateTemperature(self.clock.timeStep)

class Incubator4P(Incubator):
    def __init__(self, clock):
        super().__init__()
        self.tHeater : ufloat = ufloat(25,0.05)
        self.cAir: ufloat = ufloat(486.12, 0.05)
        self.gBox: ufloat = ufloat(0.856, 0.05)
        self.cHeater: ufloat = ufloat(33.65, 0.05)
        self.gHeater: ufloat = ufloat(0.87, 0.05)
        self.clock: Clock = clock

    def caculateHeaterTemperature(self, timeIncrement : ufloat) -> ufloat:
        return (1/self.cHeater) * (self.voltage * self.current * timeIncrement - self.gHeater * (self.tHeater - self.tBair))

    def calculateTemperature(self, timeIncrement : ufloat) -> ufloat:
        return (1/self.cAir) * (self.gHeater * (self.tHeater-self.tBair) - self.gBox * (self.tBair - self.tRoom))

    def action(self):
        self.tHeater = self.tHeater + self.clock.timeStep * self.caculateHeaterTemperature(self.clock.timeStep)
        self.tBair = self.tBair + self.clock.timeStep * self.calculateTemperature(self.clock.timeStep)

class Controller(ActiveObject):
    def __init__(self, clock, incubator):
        super().__init__()
        self.desiredTemp : ufloat = ufloat(28, 0.05)
        self.lowerBound : ufloat = ufloat(3, 0.05)
        self.tolerance : float = 0.99999
        self.incubator: Incubator = incubator
        self.clock: Clock = clock

    def action(self):
        if self.incubator.currentState == IncubatorState.Heating and (self.incubator.tBair >= self.desiredTemp).confidence > self.tolerance:
            self.incubator.currentState = IncubatorState.CoolingDown
            self.incubator.voltage = ufloat(0, 0.05)
        elif (self.incubator.currentState == IncubatorState.CoolingDown) and ((self.incubator.tBair <= (self.desiredTemp - self.lowerBound)).confidence > self.tolerance):
            self.incubator.currentState = IncubatorState.Heating
            self.incubator.voltage = self.incubator.onVoltage

        print(str(self.clock.now) + '\t| ' + str(self.incubator.tBair.value) + '\t| ' + str(self.incubator.tBair.uncertainty))

if __name__ == "__main__":
    clock = Clock()
    incubator4p = Incubator4P(clock)
    controller = Controller(clock, incubator4p)

    clock.addObject(incubator4p)
    clock.addObject(controller)

    print("Time\t| Temperature\t\t| Uncertainty")
    print("------------------------------------------------------")
    clock.run(15)


from event import Event
import boto3
import os

if os.environ.get('AWS_EXECUTION_ENV'):
    from aws_xray_sdk.core import xray_recorder
    from aws_xray_sdk.core import patch_all

    patch_all()

ssm = boto3.client('ssm',region_name='us-east-2')

signature_public_key_parameter = ssm.get_parameter(
    Name='/external/accounts/dev/sso_signature_public_key',
    WithDecryption=True
)
encryption_private_key_parameter = ssm.get_parameter(
    Name='/external/accounts/dev/sso_encryption_private_key',
    WithDecryption=True
)
sso_cookie_name_parameter = ssm.get_parameter(
    Name='/external/accounts/dev/sso_cookie_name',
    WithDecryption=True
)

from oxauth import Strategy2

strategy = Strategy2(
    signature_public_key=signature_public_key_parameter['Parameter']['Value'],
    signature_algorithm="RS256",
    encryption_private_key=encryption_private_key_parameter['Parameter']['Value'],
    encryption_algorithm="A256GCM",
    encryption_method="dir"
)

class Output:
    def __init__(self):
        self.set_user_uuid(None)

    def set_user_uuid(self, value):
        self.__user_uuid = value

    def set_country_code(self, value):
        self.__country_code = value

    def to_dict(self):
        return {
            'general': {
                'user_uuid': self.__user_uuid or 'not logged in',
                'country_code': self.__country_code
            },
            'reading_progress': {
                'a_book_uuid': 'a_page_uuid'
            },
            'accounts': {
                'faculty_status': 'confirmed_faculty (dummy value for now)'
            },
            'diagnostics': {
                'region': os.environ.get('AWS_REGION'),
                'hostname': os.environ.get('HOSTNAME'),
                'lambda_event_body': os.environ.get('AWS_LAMBDA_EVENT_BODY'),
                'aws_execution_env': os.environ.get('AWS_EXECUTION_ENV'),
                'lambda_task_root': os.environ.get('LAMBDA_TASK_ROOT'),
            }
        }

def lambda_handler(event, context):
    event = Event(event)
    request = event.request()

    sso_cookie = request.parsedCookies().get(sso_cookie_name_parameter['Parameter']['Value'])

    output = Output()

    if sso_cookie != None:
        payload = strategy.decrypt(sso_cookie)
        output.set_user_uuid(payload.user_uuid)

    output.set_country_code(request.country_code())

    return render_diagnostic(output.to_dict())

def render_diagnostic(something):
    content = f"""
        <html>
            <head>
                <meta name="robots" content="noindex">
                <title>Me Spike diagnostics</title>
            </head>
            <body>
                {something}
            </body>
        </html>
        """

    response = {
        'status': '200',
        'headers': {
            'x-robots-tag': [{
                'key': 'X-Robots-Tag',
                'value': 'noindex'
            }]
        },
        'body': content
    }

    return response


#!/usr/bin/env python
#coding:utf-8
import pika,time

credentials = pika.PlainCredentials('admin', 'admin')
#链接rabbit服务器（localhost是本机，如果是其他服务器请修改为ip地址）
connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='192.168.1.210', port=5672, credentials=credentials, virtual_host='/'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(" [x] 发送消息：  当前时间是： %s" % now)
connection.close()


import time
from typing import List, Type, Union

from acme.jax import savers as acme_savers
from chex import dataclass

from mava.callbacks import Callback
from mava.components import Component
from mava.components.updating.parameter_server import ParameterServer
from mava.core_jax import SystemParameterServer
from mava.utils.checkpointing_utils import update_to_best_net
from mava.wrappers import SaveableWrapper

"""Checkpointer component for Mava systems."""

@dataclass
class CheckpointerConfig:
    checkpoint_minute_interval: float = 5
    restore_best_net: Union[str, None] = None

class Checkpointer(Component):
    def __init__(
        self,
        config: CheckpointerConfig = CheckpointerConfig(),
    ):
        """Component for checkpointing system variables."""
        self.config = config

    def on_parameter_server_init(self, server: SystemParameterServer) -> None:
        """Create the system checkpointer.

        Args:
            server: SystemParameterServer.

        Returns:
            None.
        """
        saveable_parameters = SaveableWrapper(server.store.parameters)
        old_trainer_steps = server.store.parameters["trainer_steps"].copy()
        server.store.system_checkpointer = acme_savers.Checkpointer(
            object_to_save=saveable_parameters,  # must be type saveable
            directory=server.store.experiment_path,
            add_uid=False,
            time_delta_minutes=0,
        )

        # Check if the checkpointer restored the network parameters
        # and if the user wants the network with the best performance.
        if (old_trainer_steps != server.store.parameters["trainer_steps"]) and (
            self.config.restore_best_net is not None
        ):
            update_to_best_net(server, self.config.restore_best_net)

        server.store.last_checkpoint_time = time.time()
        server.store.checkpoint_minute_interval = self.config.checkpoint_minute_interval

    def on_parameter_server_run_loop_checkpoint(
        self, server: SystemParameterServer
    ) -> None:
        """Intermittently checkpoint the server parameters.

        Args:
            server: SystemParameterServer.

        Returns:
            None.
        """
        if (
            time.time() - server.store.last_checkpoint_time
            > self.config.checkpoint_minute_interval * 60 + 1
        ):
            server.store.system_checkpointer.save()
            server.store.last_checkpoint_time = time.time()

    @staticmethod
    def name() -> str:
        """Static method that returns component name."""
        return "checkpointer"

    @staticmethod
    def required_components() -> List[Type[Callback]]:
        """List of other Components required in the system for this Component to function.

        ParameterServer required to set up server.store.parameters
        and server.store.experiment_path.

        Returns:
            List of required component classes.
        """
        return [ParameterServer]


import numpy as np

from pysrc.GeoMathKit import GeoMathKit

class Harmonic:
    """
    Harmonic analysis and synthesis: Ordinary 2D integration for computing Spherical Harmonic coefficients
    """

    def __init__(self, lat, lon, PnmMatrix, Nmax: int):
        self.lat, self.lon = GeoMathKit.getCoLatLoninRad(lat, lon)
        self.nlat, self.nlon = len(lat), len(lon)
        self.PnmMatrix = PnmMatrix

        m = np.arange(Nmax + 1)
        self.g = m[:, None] @ self.lon[None, :]

        self.factor1 = np.ones((self.nlat, Nmax + 1))
        self.factor1[:, 0] += 1
        self.factor1 = 1 / (self.factor1 * self.nlon)

        self.factor2 = np.ones((Nmax + 1, Nmax + 1))
        self.factor2[:, 0] += 1
        self.factor2 *= np.pi / (2 * self.nlat)
        pass

    def analysis(self, Inners: list):
        Inners = np.array(Inners)

        g = self.g.T
        co = np.cos(g)
        so = np.sin(g)

        Am = np.einsum('pij,jm->pim', Inners, co, optimize='greedy') * self.factor1
        Bm = np.einsum('pij,jm->pim', Inners, so, optimize='greedy') * self.factor1

        Cnms = np.einsum('pim,ilm,i->plm', Am, self.PnmMatrix, np.sin(self.lat), optimize='greedy') * self.factor2
        Snms = np.einsum('pim,ilm,i->plm', Bm, self.PnmMatrix, np.sin(self.lat), optimize='greedy') * self.factor2
        return Cnms, Snms

    def synthesis(self, Cnms: list, Snms: list):
        assert len(Cnms) == len(Snms)
        Cnms = np.array(Cnms)
        Snms = np.array(Snms)

        Am = np.einsum('ijk,ljk->ilk', Cnms, self.PnmMatrix)
        Bm = np.einsum('ijk,ljk->ilk', Snms, self.PnmMatrix)

        co = np.cos(self.g)
        so = np.sin(self.g)

        Fout = Am @ co + Bm @ so

        return Fout


"""
    Created by howie.hu at 2022-05-12.
    Description: 基于Ruia爬虫框架的微信公众号爬虫
        原始数据来源于：https://mp.data258.com/mp/search?type=category&key=老胡的储物柜&sort=
        ! 注意，该目标网站有比较严厉的反爬措施，单IP只能访问15次，此功能需要代理池
        - 运行: 根目录执行，其中环境文件pro.env根据实际情况选择即可
        - 命令: PIPENV_DOTENV_LOCATION=./dev.env pipenv run python src/collector/wechat/data258_ruia_start.py
        - 结果示例：
        {
            "doc_date": "2022-01-09 21:20:00",
            "doc_image": "wx_fmt=jpeg",
            "doc_name": "我的周刊（第021期）",
            "doc_ts": 1641734400,
            "doc_link": "",
            "doc_source_meta_list": [
                "howie_locker",
                "编程、兴趣、生活"
            ],
            "doc_des": "奇文共欣赏，疑义相与析",
            "doc_core_html": "hello world",
            "doc_type": "article",
            "doc_author": "howie6879",
            "doc_source_name": "老胡的储物柜",
            "doc_id": "3b6b3dd93b58164f0f60403b06ef689a",
            "doc_source": "liuli_wechat",
            "doc_source_account_nick": "howie_locker",
            "doc_source_account_intro": "编程、兴趣、生活",
            "doc_content": "hello world",
            "doc_keywords": ""
        }
    Changelog: all notable changes to this file will be documented
"""
import asyncio
import re

from urllib.parse import urljoin

import execjs

from ruia import Response, Spider
from ruia_ua import middleware as ua_middleware

from src.collector.utils import load_data_to_articlles
from src.collector.wechat.items import (
    Data258WechatItem,
    Data258WechatListItem,
    WechatItem,
)
from src.processor import html_to_text_h2t
from src.utils.log import LOGGER
from src.utils.tools import md5_encryption

def exec_js_data258(html: str) -> str:
    """返回js执行结果"""
    t_list = re.findall(r"setTimeout\(function\(\){(.*?);},", html)
    mp_res_list = []
    for i in t_list:
        js_text = """
        window = {};
        location = {
        href: null,
        };
        """
        js_text += re.compile(r"\}\);(.*?)</script>", re.S).search(html)[1]
        js_text += i
        js = execjs.compile(js_text)
        res = js.eval("location")["href"]
        if "www.data258.com" in res:
            break
        else:
            mp_res_list.append(res)

    return mp_res_list[-1] if mp_res_list else None

class Data258WechatSpider(Spider):
    """微信文章爬虫"""

    name = "Data258WechatSpider"
    request_config = {"RETRIES": 3, "DELAY": 3, "TIMEOUT": 10}
    concurrency = 1
    base_url = "https://mp.data258.com/"
    wechat_name = ""
    # aiohttp config
    aiohttp_kwargs = {}

    async def parse(self, response: Response):
        """解析公众号原始链接数据"""
        html = await response.text()
        async for item in Data258WechatItem.get_items(html=html):
            if item.wechat_name == self.wechat_name:
                url = urljoin(self.base_url, item.wehcat_href)
                yield self.request(
                    url=url,
                    callback=self.parse_wechat_articles,
                )
                break

    async def parse_wechat_articles(self, response: Response):
        """解析公众号详情页面，提取历史文章"""
        html = await response.text()

        async for item in Data258WechatListItem.get_items(html=html):
            url = urljoin(self.base_url, item.w_article_href)
            yield self.request(
                url=url,
                headers={"Host": "mp.data258.com", "Referer": response.url},
                callback=self.parse_wechat_url,
                metadata={"wechat_title": item.w_article_title},
            )

    async def parse_wechat_url(self, response: Response):
        """解析公众号文章原始链接"""
        html = await response.text()
        if "今日浏览次数已达上限" in html:
            LOGGER.error(f"微信真实链接提取失败(IP 限制)：{response.metadata['wechat_title']} ")
        else:
            real_wechat_url = await asyncio.coroutine(exec_js_data258)(html)
            if real_wechat_url:
                yield self.request(
                    url=real_wechat_url,
                    callback=self.parse_wechat,
                )
            else:
                LOGGER.error(f"微信真实链接提取失败(js解密)：{response.metadata['wechat_title']} ")

    async def parse_wechat(self, response: Response):
        """解析公众号元数据"""
        html = await response.text()
        wechat_item: WechatItem = await WechatItem.get_item(html=html)
        wechat_data = {
            **wechat_item.results,
            **{
                "doc_id": md5_encryption(f"{wechat_item.doc_name}_{self.wechat_name}"),
                "doc_keywords": "",
                "doc_source_name": self.wechat_name,
                "doc_link": response.url,
                "doc_source": wechat_item.doc_source,
                "doc_source_account_nick": wechat_item.doc_source_account_nick,
                "doc_source_account_intro": wechat_item.doc_source_account_intro,
                "doc_content": html_to_text_h2t(html),
                "doc_html": "",
            },
        }
        await asyncio.coroutine(load_data_to_articlles)(input_data=wechat_data)

def run(collect_config: dict):
    """微信公众号文章抓取爬虫

    Args:
        collect_config (dict, optional): 采集器配置
    """
    s_nums = 0
    wechat_list = collect_config["wechat_list"]
    delta_time = collect_config.get("delta_time", 3)
    for wechat_name in wechat_list:
        Data258WechatSpider.wechat_name = wechat_name
        Data258WechatSpider.request_config = {
            "RETRIES": 3,
            "DELAY": delta_time,
            "TIMEOUT": 5,
        }
        t_url = (
            f"https://mp.data258.com/mp/search?type=category&key={wechat_name}&sort="
        )
        Data258WechatSpider.start_urls = [t_url]
        try:
            Data258WechatSpider.start(middleware=ua_middleware)
            s_nums += 1
        except Exception as e:
            err_msg = f"😿 公众号->{wechat_name} 文章更新失败! 错误信息: {e}"
            LOGGER.error(err_msg)

    msg = f"🤗 微信公众号文章更新完毕({s_nums}/{len(wechat_list)})!"
    LOGGER.info(msg)

if __name__ == "__main__":
    t_collect_config = {"wechat_list": ["老胡的储物柜"], "delta_time": 5}
    run(t_collect_config)
    # wechat_name = "老胡的储物柜"
    # t_url = f"https://mp.data258.com/mp/search?type=category&key={wechat_name}&sort="
    # Data258WechatSpider.start_urls = [t_url]
    # Data258WechatSpider.wechat_name = wechat_name
    # Data258WechatSpider.start(middleware=ua_middleware)


import json
from openpyxl import load_workbook
from datetime import datetime

workbook = load_workbook(filename="Marksheet.xlsx", data_only=True)
sheet = workbook.active

grades = []
descriptor_levels = {
    1: "Not Achieved",
    2: "Elementary Achievement",
    3: "Moderate Achievement",
    4: "Adequate Achievement",
    5: "Substantial Achievement",
    6: "Meritorious Achievement",
    7: "Outstanding Achievement"
}

english_avg_mark = 0
xhosa_avg_mark = 0
life_skill_avg_mark = 0
social_science_avg_mark = 0
math_avg_mark = 0
natural_science_avg_mark = 0

def get_level(mark):
    if 0 <= mark <= 29:
        return 1
    elif 30 <= mark <= 39:
        return 2
    elif 40 <= mark <= 49:
        return 3
    elif 50 <= mark <= 59:
        return 4
    elif 60 <= mark <= 69:
        return 5
    elif 70 <= mark <= 79:
        return 6
    elif 80 <= mark <= 100:
        return 7

for item in sheet.iter_rows(min_row=49,
                           max_row=49,
                           min_col=4,
                           max_col=9,
                           values_only=True):
    english_avg_mark = item[0]
    xhosa_avg_mark = item[1]
    math_avg_mark = item[2]
    life_skill_avg_mark = item[3]
    natural_science_avg_mark = item[4]
    social_science_avg_mark = item[5]

for row in sheet.iter_rows(min_row=2,
                           max_row=47,
                           min_col=1,
                           max_col=12,
                           values_only=True):
    grade = {
        "full_name": row[0] + ", " + row[1],
        "english_mark": str(row[3]),
        "xhosa_mark": str(row[4]),
        "math_mark": str(row[5]),
        "life_skill_mark": str(row[6]),
        "natural_science_mark": str(row[7]),
        "social_science_mark": str(row[8]),
        "total_mark": str(row[9]),
        "avg_mark": str(round(row[10])),
        "passed": row[11],
        "english_level": str(get_level(row[3])),
        "xhosa_level": str(get_level(row[4])),
        "math_level": str(get_level(row[5])),
        "life_skill_level": str(get_level(row[6])),
        "natural_science_level": str(get_level(row[7])),
        "social_science_level": str(get_level(row[8])),
        "english_description": descriptor_levels.get(get_level(row[3]),""),
        "xhosa_description": descriptor_levels.get(get_level(row[4]),""),
        "math_description": descriptor_levels.get(get_level(row[5]),""),
        "life_skill_description": descriptor_levels.get(get_level(row[6]),""),
        "natural_science_description": descriptor_levels.get(get_level(row[7]),""),
        "social_science_description":descriptor_levels.get(get_level(row[8]),""),
        "english_avg_mark": str(round(english_avg_mark)),
        "xhosa_avg_mark": str(round(xhosa_avg_mark)),
        "math_avg_mark": str(round(math_avg_mark)),
        "life_skill_avg_mark": str(round(life_skill_avg_mark)),
        "natural_science_avg_mark": str(round(natural_science_avg_mark)),
        "social_science_avg_mark": str(round(social_science_avg_mark)),
    }

    grades.append(grade)

print(grades)
print(json.dumps(grades))


def fechou_loop(inicial, atual):
    if atual >= len(caderneta) or atual < 0: return ''
    if caderneta[atual]['indice'] == inicial:
        return caderneta[atual]['nome']
    return fechou_loop(inicial, caderneta[atual]['indice'])

ganhador = ''
caderneta = []

for inicio in range(int(input())):
    nome, idx = input().split()
    caderneta += [{'nome': nome, 'indice': int(idx)-1}]
    if not ganhador:
        ganhador = fechou_loop(inicio,inicio)

print(ganhador)

"""
num_jogadas = int(input())
registro_jogadas = []
jogador = {}
for _ in range(num_jogadas):
    jogador['nome'], jogador['proximo'] = input().split()
    registro_jogadas.append(jogador.copy())
for j in registro_jogadas:
    if j['proximo'] == str(num_jogadas):
def getNome():

    getNome(j['proximo'])"""


import time
import numpy as np
import random
from PIL import Image, ImageOps, ImageFilter

import torch
import torch.optim as optim
import torch.nn as nn
import torch.utils.data as data
import torchvision.transforms as transforms

from utils.logger import AverageMeter
from utils import utils

class Barlow_Online:

	def __init__(self, te_query, te_gallery, model, checkpoint, img_transforms, args, device):

		self.te_query = te_query
		self.te_gallery = te_gallery
		self.model = model
		self.checkpoint = checkpoint

		self.transform, self.transform_prime = Transform_BT()
		self._eval_transform = img_transforms['eval']
		self.args = args
		self.device = device

		# normalization layer for the representations z1 and z2
		self.bn_layer = nn.BatchNorm1d(args.semantic_emb_size, affine=False).to(self.device)
		self.backbone_params = list(self.model.base_model.parameters())[:-2]
		self.classifier_params = self.model.base_model.last_linear.parameters()

		self.opt_net = optim.SGD(self.backbone_params, momentum=0, weight_decay=0, lr=self.args.lr_net)
		self.opt_clf = optim.SGD(list(self.classifier_params) + list(self.bn_layer.parameters()), momentum=self.args.momentum,
								 weight_decay=5e-4, nesterov=bool(self.args.nesterov), lr=self.args.lr_clf)

		self.bt_loss = AverageMeter()

	def adapt_single_sample(self, img):

		if self.args.online=='std':
			# print('000')
			self.model.load_state_dict(self.checkpoint['model_state_dict'])

		self.model.train()

		img_domain = img.split('/')[-3]
		if img_domain=='sketch' or img_domain=='quickdraw':
			sample = ImageOps.invert(Image.open(img)).convert(mode='RGB')
		else:
			sample = Image.open(img).convert(mode='RGB')

		for _ in range(self.args.num_iter):
			x1 = [self.transform(sample) for _ in range(self.args.batch_size_train)]
			x2 = [self.transform_prime(sample) for _ in range(self.args.batch_size_train)]

			im1 = torch.stack(x1)
			im2 = torch.stack(x2)

			im1 = im1.float().to(self.device)
			im2 = im2.float().to(self.device)

			self.opt_net.zero_grad()
			self.opt_clf.zero_grad()

			_, im_feat1 = self.model(im1)
			_, im_feat2 = self.model(im2)

			z1 = self.model.base_model.last_linear(im_feat1)
			z2 = self.model.base_model.last_linear(im_feat2)

			# z1 = projector(z1)
			# z2 = projector(z2)

			# empirical cross-correlation matrix
			# c = torch.t(z1) @ z2
			c = torch.t(self.bn_layer(z1)) @ self.bn_layer(z2)
			c.div_(self.args.batch_size_train)

			on_diag = torch.diagonal(c).add_(-1).pow_(2).sum()
			off_diag = off_diagonal(c).pow_(2).sum()
			loss = on_diag + self.args.lambd * off_diag
			loss.backward()

			self.opt_net.step()
			self.opt_clf.step()

			self.bt_loss.update(loss.item(), im1.size(0))

	def test_single_sample(self, img):

		self.model.eval()

		img_domain = img.split('/')[-3]
		img_clss = img.split('/')[-2]

		if img_domain=='sketch' or img_domain=='quickdraw':
			sample = ImageOps.invert(Image.open(img)).convert(mode='RGB')
		else:
			sample = Image.open(img).convert(mode='RGB')

		with torch.no_grad():
			inputs = self._eval_transform(sample).unsqueeze(0).to(self.device)

			_, im_feat = self.model(inputs)
			im_em = self.model.base_model.last_linear(im_feat)

		return im_em.cpu().data.numpy(), np.expand_dims(np.array(img_clss), axis=0)

	def save_model(self, path_cp, model_save_name):

		utils.save_checkpoint({
							'iter':self.args.num_iter,
							'model_state_dict':self.model.state_dict(),
							}, directory=path_cp, save_name=model_save_name, last_chkpt='')

	def train(self):

		# Start counting time
		start = time.time()

		np.random.shuffle(self.te_query['te'])

		print('\nQuery set size: ', len(self.te_query['te']))
		for i in range(len(self.te_query['te'])):

			self.adapt_single_sample(self.te_query['te'][i])
			sk_em, cls_sk = self.test_single_sample(self.te_query['te'][i])

			# Accumulate sketch embedding
			if i == 0:
				self.acc_sk_em = sk_em
				self.acc_cls_sk = cls_sk
			else:
				self.acc_sk_em = np.concatenate((self.acc_sk_em, sk_em), axis=0)
				self.acc_cls_sk = np.concatenate((self.acc_cls_sk, cls_sk), axis=0)

			if (i+1) % self.args.log_interval == 0:
				print('[Train] [{0}/{1}]\t'
					  'BT loss: {rn.val:.4f} ({rn.avg:.4f})\t'
					  .format(i+1, len(self.te_query['te']), rn=self.bt_loss))

			# if (i+1)==50:
			# 	break

		if self.args.include_gallery:
			np.random.shuffle(self.te_gallery['te_unseen_cls'])

		print('\nGallery set size: ', len(self.te_gallery['te_unseen_cls']))
		for i in range(len(self.te_gallery['te_unseen_cls'])):

			if self.args.include_gallery:
				self.adapt_single_sample(self.te_gallery['te_unseen_cls'][i])

			im_em, cls_im = self.test_single_sample(self.te_gallery['te_unseen_cls'][i])

			# Accumulate image embedding
			if i == 0:
				self.acc_im_em = im_em
				self.acc_cls_im = cls_im
			else:
				self.acc_im_em = np.concatenate((self.acc_im_em, im_em), axis=0)
				self.acc_cls_im = np.concatenate((self.acc_cls_im, cls_im), axis=0)

			if (i+1) % self.args.log_interval == 0:
				print('[Train] [{0}/{1}]\t'
					  'BT loss: {rn.val:.4f} ({rn.avg:.4f})\t'
					  .format(i+1, len(self.te_gallery['te_unseen_cls']), rn=self.bt_loss))

			# if (i+1)==50:
			# 	break

		if self.args.dataset=='DomainNet':
			print('\nSeen gallery set size: ', len(self.te_gallery['te_seen_cls']))
			for i in range(len(self.te_gallery['te_seen_cls'])):

				im_seen_em, cls_seen_im = self.test_single_sample(self.te_gallery['te_seen_cls'][i])

				# Accumulate image embedding
				if i == 0:
					acc_im_seen_em = im_seen_em
					acc_cls_seen_im = cls_seen_im
				else:
					acc_im_seen_em = np.concatenate((acc_im_seen_em, im_seen_em), axis=0)
					acc_cls_seen_im = np.concatenate((acc_cls_seen_im, cls_seen_im), axis=0)

				# if (i+1)==50:
				# 	break

			self.acc_im_em_gzs = np.concatenate((self.acc_im_em, acc_im_seen_em), axis=0)
			self.acc_cls_im_gzs = np.concatenate((self.acc_cls_im, acc_cls_seen_im), axis=0)

			print('\nSeen + Unseen Gallery Emb Dim:{}'.format(self.acc_im_em_gzs.shape))

		print('\nQuery Emb Dim:{}; Gallery Emb Dim:{}.'.format(self.acc_sk_em.shape, self.acc_im_em.shape))

		end = time.time()
		elapsed = end-start
		print(f"Time Taken:{elapsed//60:.0f}m{elapsed%60:.0f}s.\n")

def barlow_ttt(loader, model, args):

	# normalization layer for the representations z1 and z2
	bn_layer = nn.BatchNorm1d(args.semantic_emb_size, affine=False).cuda()

	backbone_params = list(model.base_model.parameters())[:-2]
	classifier_params = model.base_model.last_linear.parameters()

	opt_net = optim.SGD(backbone_params, momentum=0, weight_decay=0, lr=args.lr_net)
	opt_clf = optim.SGD(list(classifier_params) + list(bn_layer.parameters()), momentum=0.9, weight_decay=5e-4, nesterov=True, lr=args.lr_clf)

	model.train()
	bt_loss = AverageMeter()

	for epoch in range(args.epochs):

		# Start counting time
		start = time.time()

		for i, (im1, im2, _) in enumerate(loader):

			im1 = im1.float().cuda()
			im2 = im2.float().cuda()

			opt_net.zero_grad()
			opt_clf.zero_grad()

			_, im_feat1 = model(im1)
			_, im_feat2 = model(im2)

			z1 = model.base_model.last_linear(im_feat1)
			z2 = model.base_model.last_linear(im_feat2)

			# z1 = projector(z1)
			# z2 = projector(z2)

			# empirical cross-correlation matrix
			# c = torch.t(z1) @ z2
			c = torch.t(bn_layer(z1)) @ bn_layer(z2)
			c.div_(args.batch_size)

			on_diag = torch.diagonal(c).add_(-1).pow_(2).sum()
			off_diag = off_diagonal(c).pow_(2).sum()
			loss = on_diag + args.lambd*off_diag
			loss.backward()

			opt_net.step()
			opt_clf.step()

			bt_loss.update(loss.item(), im1.size(0))

			if (i+1) % args.log_interval == 0:
				print('[Train] Epoch: [{0}][{1}/{2}]\t'
					  'BT loss: {bt.val:.4f} ({bt.avg:.4f})\t'
					  .format(epoch+1, i+1, len(loader), bt=bt_loss))

		end = time.time()
		elapsed = end-start
		print(f"Time Taken:{elapsed//60:.0f}m{elapsed%60:.0f}s.\n")

	return model

class BarlowDataset(data.Dataset):
	def __init__(self, fls, transform, transform_prime):

		self.fls = fls
		self.clss = np.array([f.split('/')[-2] for f in fls])
		self.domains = np.array([f.split('/')[-3] for f in fls])
		self.transform = transform
		self.transform_prime = transform_prime

	def __getitem__(self, item):

		sample_domain = self.domains[item]
		if sample_domain=='sketch' or sample_domain=='quickdraw':
			sample = ImageOps.invert(Image.open(self.fls[item])).convert(mode='RGB')
		else:
			sample = Image.open(self.fls[item]).convert(mode='RGB')
		# sample = Image.open(self.fls[item]).convert(mode='RGB')

		clss = self.clss[item]

		x1 = self.transform(sample)
		x2 = self.transform_prime(sample)

		return x1, x2, clss

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

def off_diagonal(x):
	# return a flattened view of the off-diagonal elements of a square matrix
	n, m = x.shape
	assert n == m
	return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()

class GaussianBlur(object):
	def __init__(self, p):
		self.p = p

	def __call__(self, img):
		if random.random() < self.p:
			sigma = random.random() * 1.9 + 0.1
			return img.filter(ImageFilter.GaussianBlur(sigma))
		else:
			return img

class Solarization(object):
	def __init__(self, p):
		self.p = p

	def __call__(self, img):
		if random.random() < self.p:
			return ImageOps.solarize(img)
		else:
			return img

def Transform_BT():

	# Imagenet standards
	im_mean = [0.485, 0.456, 0.406]
	im_std = [0.229, 0.224, 0.225]

	transform = transforms.Compose([
		transforms.RandomResizedCrop(224, interpolation=Image.BICUBIC),
		transforms.RandomHorizontalFlip(p=0.5),
		transforms.RandomApply([transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)], p=0.8),
		transforms.RandomGrayscale(p=0.2),
		GaussianBlur(p=1.0),
		Solarization(p=0.0),
		transforms.ToTensor(),
		transforms.Normalize(im_mean, im_std)
	])

	transform_prime = transforms.Compose([
		transforms.RandomResizedCrop(224, interpolation=Image.BICUBIC),
		transforms.RandomHorizontalFlip(p=0.5),
		transforms.RandomApply([transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)], p=0.8),
		transforms.RandomGrayscale(p=0.2),
		GaussianBlur(p=0.1),
		Solarization(p=0.2),
		transforms.ToTensor(),
		transforms.Normalize(im_mean, im_std)
	])

	return transform, transform_prime


from rest_framework import status, mixins
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from devices.models import Device
from devices.serializers import DeviceSerializer
from .authentication import CsrfExemptSessionAuthentication, SiriAuthentication, WebhookAuthentication
from .serializers import SiriSerializer, WebhookSerializer
from .utils import update_device_status

class SiriAPIView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, SiriAuthentication)

    def post(self, request):
        serializer = SiriSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.validated_data
            device_name = data.get("device_name")
            if device_name:
                device = Device.objects.filter(name=device_name, active=True).first()
                if device:
                    update_device_status(device.unique_id, data["state"])
                    return Response(serializer.data, status=status.HTTP_200_OK)

            else:
                devices = Device.objects.filter(active=True)
                if devices:
                    for device in devices:
                        update_device_status(device.unique_id, data["state"])

                    return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get_queryset(self):
        return Device.objects.all()

class WebhookAPIView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, WebhookAuthentication)

    def post(self, request):
        serializer = WebhookSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.validated_data
            device = Device.objects.filter(unique_id=data["unique_id"]).first()
            if device:
                active = data.get("active")
                state = data.get("state")
                auto = data.get("auto")
                if active is not None:
                    device.active = active
                if state is not None:
                    device.state = state
                if auto is not None:
                    device.auto = auto
                device.save()
                return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get_queryset(self):
        return Device.objects.all()

class ListDevicesViewSet(
    mixins.ListModelMixin,
    GenericViewSet,
):
    authentication_classes = (CsrfExemptSessionAuthentication, WebhookAuthentication)
    serializer_class = DeviceSerializer
    queryset = Device.objects.all()

    def get_queryset(self):
        return Device.objects.filter(active=True)


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

import sys

import numpy as np
import pandas as pd

from data_processing import _in_list, colorit, split_wrd, unsqueeze_numlist
from exam import *

sys.path.insert(0, '..')

CHAP = 'Which chapter to choose(empty to enter search mode)\n'\
        '\t1\t绪论\n'\
        '\t2\t细胞的基本功能\n'\
        '\t3\t血液\n'\
        '\t4\t循环系统\n'\
        '\t5\t呼吸系统\n'\
        '\t6\t消化系统\n'\
        '\t7\t能量代谢与体温调节\n'\
        '\t8\t泌尿系统\n'\
        '\t9\t感觉器官\n'\
        '\t10\t神经系统的功能\n'\
        '\t11\t内分泌与生殖系统\n'

class BeginPhysioQuestForm(BeginQuestForm):
    def selchap(self, qf):
        # chapter
        kind = InteractiveAnswer(
            CHAP + ':',
            accept_empty=True,
            serializer=lambda x: [int(i) for i in split_wrd(x, list(', ，、'))],
            verify=unsqueeze_numlist('1-11')).get()

        if kind:
            qf = QuestForm(
                [i for i in qf if _in_list(i.args['Chapter'], kind)])
        else:  # include
            kind = InteractiveAnswer(
                'Which chapter to include?(empty to include all): ',
                accept_empty=True,
                serializer=lambda x: split_wrd(x, list(', ，、'))).get()
            if kind:
                qf = QuestForm(
                    [i for i in qf if _in_list(str(i.q + i.sel), kind)])
        return qf

    def raise_q(self, quest, **kwargs):
        if quest.ta is None:
            print(colorit("No True Answer", "red"))
        super(BeginPhysioQuestForm, self).raise_q(quest, **kwargs)

    def raise_ta(self, quest, **kwargs):
        return

    def check_ans(self, ans, quest, **kwargs):
        if not isinstance(quest.ta, list) or (isinstance(quest.ta[0], float)
                                              and np.isnan(quest.ta[0])):
            self.qf[kwargs['qid']].ta = ans
            return False

        print('True Answer:', ''.join(quest.ta))
        if ans == 'pass':
            print(colorit('Roger!', 'magenta'))
            return 'pass'
        elif set(list(split_wrd(ans.upper(), list(', ，、'), ''))) == set(
                list(''.join(quest.ta))):
            print(colorit('Same!', 'green'))
            return True
        else:
            print(colorit('NotTheSame!', 'lightred'))
            return False

    def raise_sel(self, quest, **kwargs):
        if quest.sel:
            for sel, no in zip(quest.sel, 'ABCDE'):
                print(no + '.', sel)

def main():
    t = QuestFormExcelLoader(
        qcol='题干',
        selcol=['选项' + i for i in 'ABCDE'],
        tacol='Answer',
        argcol={'Chapter': '章节'})
    BeginPhysioQuestForm(
        t.load('Data.xlsx'),
        input_manner=InteractiveAnswer("Your Answer:"),
        no_filter=t.is_cached,
        storage='l|wo').start()

if __name__ == '__main__':
    main()


"""
Name: Taha Andac
ID : 75785
Section : 03"""

def display_menu():

    """Displays a menu for the choice of a user and returns that choice."""

    print("g or G for key generation")
    print("e or E for encrytion")
    print("d or D for decryption")
    print("x or X to exit")

    option = input("Please enter your choice: ")

    while option != 'g' and option != 'G'and option != 'e' and option != 'E' and option != 'd' and option != 'D' and option != 'x' and option != 'X':

        print('\n   ***Invalid option***   \n ')

        print("g or G for key generation")
        print("e or E for encrytion")
        print("d or D for decryption")
        print("x or X to exit")

        option = input("Please enter your choice: ")
    else:
        if option == 'g' or option == 'G':
            option = 'G'
        elif option == 'e' or option == 'E':
            option = 'E'
        elif option == 'd' or option == 'D':
            option = 'D'
        else:
            option = 'X'

        return option


# ch7/example1.py

import multiprocessing

class ReductionConsumer(multiprocessing.Process):

    def __init__(self, task_queue, result_queue):
        multiprocessing.Process.__init__(self)
        self.task_queue = task_queue
        self.result_queue = result_queue

    def run(self):
        pname = self.name
        print('Using process %s...' % pname)

        while True:
            num1 = self.task_queue.get()
            if num1 is None:
                print('Exiting process %s.' % pname)
                self.task_queue.task_done()
                break

            self.task_queue.task_done()
            num2 = self.task_queue.get()
            if num2 is None:
                print('Reaching the end with process %s and number %i.' % (pname, num1))
                self.task_queue.task_done()
                self.result_queue.put(num1)
                break

            print('Running process %s on numbers %i and %i.' % (pname, num1, num2))
            self.task_queue.task_done()
            self.result_queue.put(num1 + num2)

def reduce_sum(array):
    tasks = multiprocessing.JoinableQueue()
    results = multiprocessing.JoinableQueue()
    result_size = len(array)

    n_consumers = multiprocessing.cpu_count()

    for item in array:
        results.put(item)

    while result_size > 1:
        tasks = results
        results = multiprocessing.JoinableQueue()

        consumers = [ReductionConsumer(tasks, results) for i in range(n_consumers)]
        for consumer in consumers:
            consumer.start()

        for i in range(n_consumers):
            tasks.put(None)

        tasks.join()
        result_size = result_size // 2 + (result_size % 2)
        #print('-' * 40)

    return results.get()

my_array = [i for i in range(20)]

result = reduce_sum(my_array)
print('Final result: %i.' % result)


from collections import OrderedDict

"""
    On Amazon Prime Day, non-critical requests for a transaction system are routed through a throttling gateway
    to ensure that the network is not choked by non-essential requests.

    The gateway has the following limits:
    - The number of transactions in any given second cannot exceed 3.
    - The number of transactions in any given 10 second period cannot exceed 20.
    - A ten-second period includes all requests arriving from any time max(1, T-9) to T (inclusive of both) for any valid time T.
    - The number of transactions in any given minute cannot exceed 60. Similar to above, 1 minute is from max(1, T-59) to T.
    - Any request that exceeds any of the above limits will be dropped by the gateway.
    - Given the times at which different requests arrive sorted ascending, write an algorithm to find how many requests will be dropped.

    Input:
    num: an integer representing the number of requests;
    requestTime: a list of integers representing the times of various requests.

    Output:
    Return an integer representing the total number of dropped requests.

    Note:
    Even if a request is dropped it is still considered for future calculations.
    Although, if a request is to be dropped due to multiple violations, it is still counted only once.

    Constraints:
    1 <= num <= 10^6
    1 <= requestTime[i] <= 10^9
    0 <= i < num

    Example
    Input:
    num = 27
    requestTime = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7,7,7,7, 11, 11, 11, 11]

    Output:
    7

    Explanation:

     0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5  6  7  8  9  0  1  2   3   4   5   6
    [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 11, 11, 11, 11]
              ^                                                  ^  ^  ^       ^  ^   ^
              1                                                  2  3  4       5  6   7

    reasons:
    1. At most 3 requests are allowed in one second. Then No request will be dropped till 6 as all comes at an allowed rate of 3 requests per second and the 10-second clause is also not violated.
    2. At most 20 requests are allowed in ten seconds.
    3. At most 20 requests are allowed in ten seconds.
    4. At most 20 requests are allowed in ten seconds.
    5. Dropped. At most 20 requests are allowed in ten seconds.
    6. Dropped. At most 20 requests are allowed in ten seconds.
    7. Dropped. At most 20 requests are allowed in ten seconds.
"""

def f(n, requestTime):
    dropped = 0
    for i in range(3, len(requestTime)):
        if requestTime[i] == requestTime[i-3]:
            dropped += 1
            continue
        if i > 19 and requestTime[i] - requestTime[i-20] < 10:
            dropped += 1
            continue
        if i > 59 and requestTime[i] - requestTime[i-60] < 60:
            dropped += 1
            continue
    return dropped

a = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5,
     5, 5, 6, 6, 6, 7, 7, 7, 7, 11, 11, 11, 11]
print(f(0, a))


#imports
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
import re
import os
import sys

#Variables
checkurl = input("Enter URL to rate: ")
zulu = "https://zulu.zscaler.com/"
path = "C:\chromedriver.exe"
chrome = Service(path)
invalid = "invalid"
timeStr = time.strftime("%Y%m%d-%H%M%S")
from os.path import expanduser
home = expanduser("~")
line = '---------------------------------------'

#Chrome Driver Setup
#options.add_argument('window-size=1920x1080')
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument("disable-gpu")
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(service=chrome, options=options)

#Get ZULU
driver.get(zulu)

#Find URL text box and enter text
#checkurl = "test.com"
inputElement = driver.find_element(By.ID, "url")
inputElement.send_keys(checkurl)
#inputElement.send_keys("test.com")

#Find Analyze button and click
submit = driver.find_element(By.CSS_SELECTOR, '[value="Analyze"]')
submit.click()

#add Variable to Clipboard
def clipped(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

#Logging output to Desktop
def logging():
	with open(home+'\\Desktop\\log.txt', "a") as external_file:
		add_text = timeStr, checkurl, score, isSafe, myURL
		print(add_text, file=external_file)
		external_file.close()

#Printing output to console
def printoutput():
	print(line)
	print("---------Zulu URL Risk Analyzer--------")
	print(line)
	print(timeStr, checkurl, score, isSafe, myURL)
	print(line)
	clipped(myURL)
	print("Reprot URL copied to Clipboard")
	print("Log entry created, "+home+'\\Desktop\\log.txt')
	print(line)

#validate page and fetch Reputation Score using logging()/printoutput()/restart()
while True:
	InvalidURL = driver.current_url
	if  invalid in InvalidURL or zulu == InvalidURL:
		driver.quit()
		print(line)
		print("Invalid URL - " + checkurl)
		print(line)
		print("Please make sure that you supplied valid url. (only ipv4 and FQDN)")
		print(line)
		os.execv(sys.executable, ['python'] + sys.argv)
		break
	else:
		rep = driver.find_element(By.ID, "rep-status").text
	if rep == "Completed":
		score = driver.find_element(By.ID, "rep-score").text
		score = re.sub('/100', '', score)
		#intScore = int(score)
		if int(score) >= 60:
			isSafe = "Fail"
		else:
			isSafe = "Pass"
		myURL = driver.current_url
		logging()
		printoutput()
		driver.quit()
		os.execv(sys.executable, ['python'] + sys.argv)
		break
	else:
		print("Analyzing...")
		time.sleep(2)


import argparse
import json
import os
import sys
from typing import Dict, Any

import WDL

_output_mapping = [
    (WDL.Type.File(),
     "file"),
    (WDL.Type.Array(
        WDL.Type.File(), nonempty=True),
     "files"),
    (WDL.Type.Pair(
        WDL.Type.File(),
        WDL.Type.Map(
            (WDL.Type.String(), WDL.Type.String()))),
     "file-with-labels"),
    (WDL.Type.Pair(
        WDL.Type.Array(
            WDL.Type.File(), nonempty=True),
        WDL.Type.Map(
            (WDL.Type.String(),
             WDL.Type.String()))),
     "files-with-labels"),
    (WDL.Type.Array(
        WDL.Type.Pair(
            WDL.Type.File(),
            WDL.Type.Map(
                (WDL.Type.String(),
                 WDL.Type.String()))), nonempty=True),
     "files-with-labels"),
    (WDL.Type.Boolean(),
     "quality-control"),
    (WDL.Type.File(
        optional=True),
     "optional-file"),
    (WDL.Type.Array(WDL.Type.File(), optional=True, nonempty=True),
     "optional-files"),
    (WDL.Type.Array(WDL.Type.File(), optional=True, nonempty=False),
     "optional-files"),
    (WDL.Type.Array(
        WDL.Type.File(),
        nonempty=False),
     "optional-files"),
    (WDL.Type.Pair(
        WDL.Type.File(),
        WDL.Type.Map(
            (WDL.Type.String(),
             WDL.Type.String())),
        optional=True),
     "optional-file-with-labels"),
    (WDL.Type.Pair(
        WDL.Type.Array(WDL.Type.File(), nonempty=True),
        WDL.Type.Map(
            (WDL.Type.String(),
             WDL.Type.String())),
        optional=True),
     "optional-files-with-labels"),
    (WDL.Type.Boolean(
        optional=True),
     "optional-quality-control"),
]

def _map_input(wdl_type: WDL.Type.Base, structures: Dict[str, Any]):
    if wdl_type.optional:
        return {
            "is": "optional",
            "inner": _map_inner_input(
                wdl_type,
                structures)}
    else:
        return _map_inner_input(wdl_type, structures)

def _map_inner_input(wdl_type: WDL.Type.Base, structures: Dict[str, Any]):
    if isinstance(wdl_type, WDL.Type.Array):
        (inner,) = wdl_type.parameters
        return {"is": "list", "inner": _map_input(inner, structures)}
    elif isinstance(wdl_type, WDL.Type.Pair):
        (left_type, right_type) = wdl_type.parameters
        return {
            "is": "pair", "left": _map_input(
                left_type, structures), "right": _map_input(
                right_type, structures)}
    elif isinstance(wdl_type, WDL.Type.StructInstance):
        return {"is": "object", "fields": structures[wdl_type.type_name]}
    elif isinstance(wdl_type, WDL.Type.Map):
        (key_type, value_type) = wdl_type.parameters
        return {
            "is": "dictionary", "key": _map_input(
                key_type, structures), "value": _map_input(
                value_type, structures)}
    elif isinstance(wdl_type, WDL.Type.Boolean):
        return "boolean"
    elif isinstance(wdl_type, WDL.Type.Directory):
        return "directory"
    elif isinstance(wdl_type, WDL.Type.File):
        return "file"
    elif isinstance(wdl_type, WDL.Type.Float):
        return "floating"
    elif isinstance(wdl_type, WDL.Type.Int):
        return "integer"
    elif isinstance(wdl_type, WDL.Type.String):
        return "string"
    raise ValueError(f"No conversion for {wdl_type}")

def _map_output(wdl_type: WDL.Type.Base, allow_complex: bool,
                structures: WDL.Env.Bindings[WDL.StructTypeDef]):
    for (vidarr_wdl_type, vidarr_type) in _output_mapping:
        if wdl_type == vidarr_wdl_type:
            return vidarr_type
    if allow_complex and isinstance(wdl_type, WDL.Type.Array):
        (inner,) = wdl_type.parameters
        if isinstance(inner, WDL.Type.StructInstance):
            keys = {}
            outputs = {}
            for (member_name,
                 member_type) in structures[inner.type_name].members.items():
                if member_type == WDL.Type.Int():
                    keys[member_name] = "INTEGER"
                elif member_type == WDL.Type.String():
                    keys[member_name] = "STRING"
                else:
                    outputs[member_name] = _map_output(
                        member_type, False, structures)
            return {"is": "list", "keys": keys, "outputs": outputs}
    raise ValueError(
        f"Vidarr cannot process output type {wdl_type} in output.")

def parse(wdl_file_path: str) -> Dict[str, Any]:
    """
    Read a WDL file and convert it into a Vidarr workflow definition

    :param wdl_file_path: the path to the WDL file; this must be a path on disk in case the WDL file imports other files
    :return: the Vidarr configuration object
    """
    return convert(WDL.load(wdl_file_path))

def convert(doc: WDL.Document) -> Dict[str, Any]:
    """
    Convert a parsed WDL file into a Vidarr workflow definition
    :param doc:  the parsed WDL file
    :return: the Vidarr configuration object
    """
    workflow_name = doc.workflow.name
    structures = {}
    unprocessed_structs = [s for s in doc.struct_typedefs]
    while unprocessed_structs:
        structs_needing_unprocessed = []
        for structure in unprocessed_structs:
            try:
                structures[structure.name] = {member_name: _map_input(member_type, structures) for (
                    member_name, member_type) in structure.value.members.items()}
            except KeyError:
                structs_needing_unprocessed.append(structure)
        assert len(structs_needing_unprocessed) < len(unprocessed_structs)
        unprocessed_structs = structs_needing_unprocessed

    workflow_inputs = {}

    def read_output(output: WDL.Decl):
        output_metadata = doc.workflow.meta.get(
            "output_meta", {}).get(
            output.name, {})
        if isinstance(
                output_metadata,
                dict) and "vidarr_type" in output_metadata:
            return output_metadata["vidarr_type"]
        else:
            return _map_output(
                output.type, True, doc.struct_typedefs)

    for wf_input in (doc.workflow.available_inputs or []):
        meta = doc.workflow.parameter_meta.get(wf_input.name)

        if meta and isinstance(meta, dict) and "vidarr_type" in meta:
            vidarr_type = meta["vidarr_type"]
        else:
            vidarr_type = _map_input(wf_input.value.type, structures)

        # Optional should be processed after retry because it should be okay to omit a retriable value and use a
        # singular default.
        if meta and isinstance(meta, dict) and meta.get("vidarr_retry", False):
            vidarr_type = {"is": "retry", "inner": vidarr_type}

        if wf_input.value.expr:
            vidarr_type = {"is": "optional", "inner": vidarr_type}

        workflow_inputs[doc.workflow.name + "." + wf_input.name] = vidarr_type

    workflow = {
        'language': 'WDL_' + str(
            doc.wdl_version).replace(
            ".",
            "_"),
        'outputs': {
            workflow_name + "." + output.name:
                read_output(output)
            for output in doc.workflow.outputs},
        'parameters': workflow_inputs,
        'workflow': doc.source_text,
        'accessoryFiles': {
            imported.uri: imported.doc.source_text for imported in doc.imports}}
    return workflow

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        "-i",
        "--input-wdl-path",
        required=True,
        help="Source wdl path")
    parser.add_argument(
        "-o",
        "--output-path",
        required=False,
        help="Output a file with contents of the workflow parameter dict")
    args = parser.parse_args()

    if args.output_path:
        workflow = parse(args.input_wdl_path)
        parent_dir = os.path.dirname(args.output_path)
        if parent_dir:
            os.makedirs(parent_dir, exist_ok=True)
        with open(args.output_path, "w") as output_file:
            json.dump(workflow, output_file)
    else:
        json.dump(
            parse(
                args.input_wdl_path),
            sys.stdout,
            indent=4,
            sort_keys=True)

if __name__ == "__main__":
    main()


import datetime
import time
import sys

# parse user-defined parameters
input_log_file = sys.argv[1]
input_tex_file = sys.argv[2]
output_tex_file = sys.argv[3]

NUM_INTERVALS = 10
MAX_TIME = float(sys.argv[4])

# define some constants
BATCH_PROC_TASK = '@batch_proc_task'
REGULARIZING_TASK = '@regularizing_task'
NORMALIZING_TASK = '@normalizing_task'
MERGING_TASK = '@merging_task'
MERGING_INCREMENTS_TASK = '@merging_increments_task'

GLOBAL_START = 'Log file created at:'
START_BATCH_PROC = 'Processor: start processing batch'
COMPLETE_BATCH_PROC = 'Processor: complete processing batch'
START_REGULARIZING = 'MasterComponent: start regularizing'
COMPLETE_REGULARIZING = 'MasterComponent: complete regularizing'
START_NORMALIZING = 'MasterComponent: start normalizing'
COMPLETE_NORMALIZING = 'MasterComponent: complete normalizing'
START_MERGING = 'MasterComponent: start merging models'
COMPLETE_MERGING = 'MasterComponent: complete merging models'
START_MERGING_INCREMENTS = 'MasterComponent: start merging processor increments'
COMPLETE_MERGING_INCREMENTS = 'MasterComponent: complete merging processor increments'

START_TASK_TYPE = {
    START_BATCH_PROC: BATCH_PROC_TASK,
    START_REGULARIZING: REGULARIZING_TASK,
    START_NORMALIZING: NORMALIZING_TASK,
    START_MERGING: MERGING_TASK,
    START_MERGING_INCREMENTS: MERGING_INCREMENTS_TASK,
}

COMPLETE_TASK_TYPE = {
    COMPLETE_BATCH_PROC: BATCH_PROC_TASK,
    COMPLETE_REGULARIZING: REGULARIZING_TASK,
    COMPLETE_NORMALIZING: NORMALIZING_TASK,
    COMPLETE_MERGING: MERGING_TASK,
    COMPLETE_MERGING_INCREMENTS: MERGING_INCREMENTS_TASK,
}

class Task(object):
    def __init__(self, task_type=None, start_time=None, complete_time=None, batch_name=None, model_name=None, model_index=None, rhs=None):
        self.task_type = task_type
        self.start_time = start_time
        self.complete_time = complete_time
        self.batch_name = batch_name
        self.model_name = model_name
        self.model_index = model_index

        if rhs is not None:
            self.task_type = rhs.task_type
            self.start_time = rhs.start_time
            self.complete_time = rhs.complete_time
            self.batch_name = rhs.batch_name
            self.model_name = rhs.model_name
            self.model_index = rhs.model_index

    def __str__(self):
        return '{0}\n {1}\n {2}\n {3}\n {4}\n {5}\n'.format(self.task_type, self.start_time, self.complete_time,
                                                      self.batch_name, self.model_name, self.model_index)

def parse_log(log_file_name):

    def _make_comparator(less_than):
        def compare(x, y):
            if less_than(x, y):
                return -1
            elif less_than(y, x):
                return 1
            else:
                return 0
        return compare

    def _read_global_start_time(line):
        line_list = line.split()

        month, day = int(line_list[4][5: 7]), int(line_list[4][8: ])
        hour, minute, second = int(line_list[5][0: 2]), int(line_list[5][3: 5]), int(line_list[5][6: ])

        return time.mktime(datetime.datetime(year=2000, month=month, day=day, hour=hour,
                                             minute=minute, second=second).timetuple())

    def _read_task_info(line, global_start_time, read_batch):
        line_list = line.split()

        process_name = line_list[2]
        month, day, hour = int(line_list[0][1: 3]), int(line_list[0][3: ]), int(line_list[1][0: 2])
        minute, second, m_second = int(line_list[1][3: 5]), int(line_list[1][6: 8]), float('0.{}'.format(line_list[1][9: ]))

        current_time = time.mktime(datetime.datetime(year=2000, month=month, day=day, hour=hour,
                                                     minute=minute, second=second).timetuple()) + m_second
        batch_name = None
        if read_batch:
            batch_name = line_list[8]

        model_name = None
        if len(line_list) == 12:
            model_name = line_list[11]

        return process_name, current_time - global_start_time, batch_name, model_name

    max_time_stamp = -1
    min_time_stamp = None
    models_list = []
    main_thread_name = None
    use_merger = False
    process_info = {}  # dict, key --- process name, value --- list of tasks
    with open(log_file_name, 'r') as fin:
        incomplete_tasks = {}
        global_start_time = None
        for line in fin:
            if GLOBAL_START in line:
                global_start_time = _read_global_start_time(line)

            else:
                for task_name, task_type in START_TASK_TYPE.iteritems():
                    if task_name in line:
                        read_batch = (task_type == BATCH_PROC_TASK)

                        if task_type == MERGING_INCREMENTS_TASK:
                            use_merger = True

                        process_name, start_time, batch_name, model_name = _read_task_info(line,
                                                                                global_start_time,
                                                                                read_batch=read_batch)
                        task_name = '{0}-{1}'.format(task_type, process_name)

                        if min_time_stamp is None:
                            min_time_stamp = start_time

                        model_index = None
                        if model_name is not None and (len(models_list) == 0 or model_name != models_list[-1]):
                            models_list.append(model_name)

                        model_index = len(models_list) - 1
                        incomplete_tasks[task_name] = Task(task_type, start_time, -1, batch_name, model_name, model_index)
                        break

                for task_name, task_type in COMPLETE_TASK_TYPE.iteritems():
                    if task_name in line:
                        read_batch = (task_type == BATCH_PROC_TASK)
                        process_name, complete_time, batch_name, model_name = _read_task_info(line,
                                                                                global_start_time,
                                                                                read_batch=read_batch)
                        task_name = '{0}-{1}'.format(task_type, process_name)
                        main_thread_name = process_name  # this would be 'main' in the last task

                        if (task_name not in incomplete_tasks) or\
                             (read_batch and incomplete_tasks[task_name].batch_name != batch_name and\
                                             incomplete_tasks[task_name].model_name != model_name) or\
                              (complete_time < incomplete_tasks[task_name].start_time):
                            raise IOError('Given log-file is incorrect')

                        incomplete_tasks[task_name].complete_time = complete_time

                        if complete_time > max_time_stamp:
                            max_time_stamp = complete_time

                        if process_name not in process_info:
                            process_info[process_name] = []

                        process_info[process_name].append(Task(rhs=incomplete_tasks[task_name]))
                        del incomplete_tasks[task_name]
                        break

    for process_name in process_info.keys():
        process_info[process_name].sort(cmp=_make_comparator(lambda x, y: x.start_time > y.start_time), reverse=True)

    return process_info, models_list, max_time_stamp, min_time_stamp, main_thread_name, use_merger

process_info, models_list, max_time_stamp, min_time_stamp, main_thread_name, use_merger = parse_log(input_log_file)
for _, tasks in process_info.iteritems():
    for task in tasks:
        task.start_time -= min_time_stamp
        task.complete_time -= min_time_stamp

max_time_stamp -= min_time_stamp

# write info to latex file
coef = NUM_INTERVALS / max_time_stamp
line_len_value = 5.7 #5.4 - 0.35 * (len(process_info.keys()) - 1)  # incorrect!
with open(input_tex_file, 'r') as fin:
    with open(output_tex_file, 'w') as fout:
        for line in fin:
            if '%%%%% START_MARKER_1 %%%%%' not in line and\
               '%%%%% START_MARKER_2 %%%%%' not in line and\
               '%%%%% START_MARKER_3 %%%%%' not in line:
                fout.write(line)
            elif '%%%%% START_MARKER_1 %%%%%' in line:
                value = MAX_TIME / (10.0 * NUM_INTERVALS) * coef
                fout.write('-- ++(0,-0.1) -- ++(0,0.05)\n')
                for _ in xrange(4):
                    fout.write('-- ++({},0) ++(0,-0.02) -- ++(0,0.02)\n'.format(value))
                fout.write('-- ++({},0)  -- ++(0,-0.035) -- ++(0,0.035)\n'.format(value))
                for _ in xrange(5):
                    fout.write('-- ++({},0) ++(0,-0.02) -- ++(0,0.02)\n'.format(value))
                fout.write('-- ++(0,-0.05) -- ++(0,0.1)\n')
            elif '%%%%% START_MARKER_2 %%%%%' in line:
                iter = MAX_TIME / (1.0 * NUM_INTERVALS)
                for i in [int(iter * i) for i in xrange(NUM_INTERVALS + 1)]:
                    fout.write('\draw[dotted] (t_cur) +(0,-.1) node[above=0.05cm] {{\\tiny {}s}};\n'.format(i))
                    fout.write('\clki\n')
            else:
                fout.write('\\begin{{wave}}{{{0}}}{{10}}{{{1:.2f}}}{{{2}}}\n'.format(len(process_info.keys()), max_time_stamp, line_len_value))
                process_names_list = process_info.keys()
                process_names_list.remove(main_thread_name)
                process_names_list = [main_thread_name] + process_names_list

                for p_i, p_name in enumerate(process_names_list):
                    name_to_print = 'Main' if not use_merger else 'Merger'
                    if p_i > 0:
                        name_to_print = 'Proc-{}'.format(p_i)
                    process_str = '\\nextwave{{{}}} '.format(name_to_print)
                    process_str += '\\Wait{{ }}{{{}}}'.format(process_info[p_name][0].start_time * coef)
                    for idx, _ in enumerate(process_info[p_name]):
                        if idx != len(process_info[p_name]) - 1:
                            val_1 = (process_info[p_name][idx].complete_time - process_info[p_name][idx].start_time) * coef
                            val_2 = (process_info[p_name][idx + 1].start_time - process_info[p_name][idx].complete_time) * coef

                            if process_info[p_name][idx].task_type == BATCH_PROC_TASK:
                                process_str += '\\ProcBatch{0}[]{{{1}}} \\Wait{{ }}{{{2}}} '.format(
                                    'One' if process_info[p_name][idx].model_index % 2 else 'Two', val_1, val_2)
                            elif process_info[p_name][idx].task_type == REGULARIZING_TASK:
                                process_str += '\\Regularization[]{{{0}}} \\Wait{{ }}{{{1}}} '.format(val_1, val_2)
                            elif process_info[p_name][idx].task_type == NORMALIZING_TASK:
                                process_str += '\\Normalization[]{{{0}}} \\Wait{{ }}{{{1}}} '.format(val_1, val_2)
                            elif process_info[p_name][idx].task_type == MERGING_TASK:
                                process_str += '\\Merge[]{{{0}}} \\Wait{{ }}{{{1}}} '.format(val_1, val_2)
                            elif process_info[p_name][idx].task_type == MERGING_INCREMENTS_TASK:
                                process_str += '\\MergeInc[]{{{0}}} \\Wait{{ }}{{{1}}} '.format(val_1, val_2)
                        else:
                            val = (process_info[p_name][idx].complete_time - process_info[p_name][idx].start_time) * coef
                            if process_info[p_name][idx].task_type == BATCH_PROC_TASK:
                                process_str += '\\ProcBatch{0}[]{{{1}}} '.format(
                                    'One' if process_info[p_name][idx].model_index % 2 else 'Two', val)
                            elif process_info[p_name][idx].task_type == REGULARIZING_TASK:
                                process_str += '\\Regularization[]{{{0}}} '.format(val)
                            elif process_info[p_name][idx].task_type == NORMALIZING_TASK:
                                process_str += '\\Normalization[]{{{0}}} '.format(val)
                            elif process_info[p_name][idx].task_type == MERGING_TASK:
                                process_str += '\\Merge[]{{{0}}} '.format(val)
                            elif process_info[p_name][idx].task_type == MERGING_INCREMENTS_TASK:
                                process_str += '\\MergeInc[]{{{0}}} '.format(val)

                    fout.write('{}\n'.format(process_str))


from connection import connection
from my_parser import *

print("Connecting to server...")

try:
	conn = connection()
	create_table_queries = get_create_table_queries("create.sql")

	cur = conn.get_cursor()

	for i in range(len(create_table_queries)):
		cur.execute(create_table_queries[i])

	print("Connection complite")

	tbls_path = ["data/club.tbl", "data/coach.tbl", "data/sport.tbl",\
		"data/workout.tbl", "data/client.tbl", "data/client_workout.tbl"]

	print("Start parcing...")
	insert_into_table_queries = get_insert_into_table_queries(tbls_path)
	print("Parcing complite")

	print("Start putting...")
	for i in range(len(insert_into_table_queries)):
		cur.execute(insert_into_table_queries[i])
	print("Putting complite")

except Exception as e:
	print("Connection to server is failed")
	print(e)


''''''

'''
python中的匿名函数lambda
'''

a=lambda x,y,z:x+y+z

print(a(4,5,6))

li=[4,6,7,8]
new=map(lambda x:x*2 ,li)
for i in new:
      print(i)
''' 如果列表中的元素的值除以二没有余数，将这个值进行平方'''
fnew=map(lambda  x:x*2,  filter( lambda x:x%2==0 ,li)     )
for f in fnew:
      print(f)
      '''方式二实现：    '''
enew= ( i*2  for i in li if i%2==0   )
for e in enew:
      print(e)

      ''' python中使用三元运算:假如当前元素除以三为0，就执行前面函数体，如果不等于就执行后面'''
san=567
sanyuan=   (san*2 if san%3==0 else san+2)
print(sanyuan)
'''三元运算符和for循环一起在列表推导式使用'''

g = (x * x for x in range(10)if x%3==0 )
i=[0,1,2,3]
new=map(lambda x:x+2,i)
for i in new:
      print(i)


from collections import defaultdict
import time

def split_pair(pair):
    pair = pair.split(' -> ')
    return pair

def make_puzzle_inputs(file_path):
    with open(file_path) as file:
        input_text = file.read().splitlines()
        polymer = input_text[0]
        pair_list = input_text[2:]
        pair_list = list(map(split_pair, pair_list))
        return polymer, pair_list

def grow_polymer(polymer, pair_list, polymer_lookup_dict):
    new_polymer = ''
    updated_polymer_pair = ''
    for i, char in enumerate(polymer):
        try:
            polymer_pair = char + polymer[i + 1]
        except IndexError:
            new_polymer += char
            break
        if polymer_pair in polymer_lookup_dict.keys():
            updated_polymer_pair = polymer_lookup_dict[polymer_pair]
        else:
            for pair in pair_list:
                if pair[0] == polymer_pair:
                    updated_polymer_pair = polymer_pair[0] + pair[1]
                    polymer_lookup_dict[polymer_pair] = updated_polymer_pair
                    break
        new_polymer += updated_polymer_pair
    return new_polymer, polymer_lookup_dict

def grow_polymer_n_times(polymer, pair_list, polymer_lookup_dict, n):
    for i in range(n):
        print('NNC' in polymer)
        start_time = time.time()
        polymer, polymer_lookup_dict = grow_polymer(polymer, pair_list, polymer_lookup_dict)
        elapsed_time = time.time() - start_time
        print(f'grew polymer {i + 1} times in {round(elapsed_time, 4)} seconds')
        # occurance_dict = create_occurance_dict(polymer)
        # max_key, min_key = find_max_and_min_key(occurance_dict)
        # print(occurance_dict)
        # answer = calculate_answer(occurance_dict, min_key, max_key)
        # print(f'polymer is {len(polymer)} characters')
        # print(f'answer is {answer}')
    return polymer

def default_to_0():
    return 0

def create_occurance_dict(polymer):
    occurance_dict = defaultdict(default_to_0)
    for char in polymer:
        occurance_dict[char] = occurance_dict[char] + 1
    return dict(occurance_dict)

def find_max_and_min_key(occurance_dict):
    max_key = max(occurance_dict, key=occurance_dict.get)
    min_key = min(occurance_dict, key=occurance_dict.get)
    return max_key, min_key

def calculate_answer(occurance_dict, min_key, max_key):
    max = occurance_dict[max_key]
    min = occurance_dict[min_key]
    return max - min

polymer, pair_list = make_puzzle_inputs('example_1.txt')
polymer_lookup_dict = {}
polymer = grow_polymer_n_times(polymer, pair_list, polymer_lookup_dict, 17)
occurance_dict = create_occurance_dict(polymer)
print(occurance_dict)
max_key, min_key = find_max_and_min_key(occurance_dict)
answer = calculate_answer(occurance_dict, min_key, max_key)
print(f'answer = {answer}')


# date: 2022-03-02 17:15
# author: liucc
import os
import sys
import shutil

# this func loads test-list.txt, then copies error-predicted images to dst_dir
def cp_error_images(src_list_fp, dst_dir):
    with open(src_list_fp, 'r') as f:
        lines = f.readlines()
        lines = [line.strip() for line in lines]
    assert lines is not None, src_list_fp
    print('found %d lines in ...%s.' % (len(lines), src_list_fp[-40:]))

    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)

    for line in lines:
        # line format: correct{0/1},fp,distance,radius,margin
        spt = line.split(',')

        if int(spt[0]) == 1:
            continue

        src_fp = spt[1]
        src_dir, src_fn = os.path.split(src_fp)
        fn = '%s-%s-%s' % (os.path.basename(src_dir), spt[2], src_fn)
        dst_fp = os.path.join(dst_dir, fn)
        shutil.copyfile(src_fp, dst_fp)
    return

def fast_run(argv):
    if len(argv) < 3:
        print('Usage:\n  python %s <src_list_fp> <dst_dir>' % argv[0])
        print('make sure line format: correct{0/1},fp,distance,radius,margin')
        exit(1)
    cp_error_images(
        src_list_fp=argv[1],
        dst_dir=argv[2]
    )

if __name__ == '__main__':
    fast_run(sys.argv)