'''

 5) Foi feita uma pesquisa entre os habitantes de uma região.
 Foram coletados os dados de idade, sexo (1/2 – masculino/feminino) e salário.
 Faça um programa que calcule e mostre:
a) A média dos salários do grupo;
b) A maior e a menor idade do grupo;
c) A quantidade de mulheres na região;
d) A idade e o sexo da pessoa que possui o menor salário;
Finalize a entrada de dados ao ser digitada uma idade negativa.

'''

i = 0
s = 0
sa = 0
contsa = 0
totsa = 0
m = 0
f = 0
menorsa = 99999999999999
menorid = 99999999999999
maiorid = 0
idademenorsa = 0
sexomenorsa = 0

while i >= 0:
    print("Digite sua idade:")
    i = int(input())

    if i >= 0:
        if maiorid < i:
            maiorid = i
        if menorid > i:
            menorid = i
    else:
        print("Não existe idade negativa")

    print("Digite seu sexo:")
    print("1 - masculino")
    print("2 - feminino:")
    s = int(input())
    if s == 1:
        m = m + 1
    if s == 2:
        f = f + 1
    print("Digite seu salário:")
    sa = float(input())
    totsa = totsa + sa
    contsa = contsa + 1

    if menorsa > sa:
        menorsa = sa
        idademenorsa = i
        sexomenorsa = s

med1 = totsa/contsa

print("A média dos salários do grupo é:", med1)
print("A maior idade é:", maiorid, "anos")
print("A menor idade é:", menorid, "anos")
print("A quantidade de mulheres na região é:", f, "mulheres")
print("A idade da pessoa com menor salário é:", idademenorsa, "anos")

if sexomenorsa == 1:
    print("O sexo da pessoa com menor salário é masculino" )
elif sexomenorsa == 2:
    print("O sexo da pessoa com menor salário é feminino" )


# 337. 打家劫舍 III
# 在上次打劫完一条街道之后和一圈房屋后，小偷又发现了一个新的可行窃的地区。这个地区只有一个入口，我们称之为“根”。 除了“根”之外，每栋房子有且只有一个“父“房子与之相连。一番侦察之后，聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫，房屋将自动报警。
# 计算在不触动警报的情况下，小偷一晚能够盗取的最高金额。

# 类似 198，状态转移方程需要修改一下
# dp(root) = x 表示对 根为 root 的二叉树进行行动所得的最大金额
# 对于 root，要么偷要么不偷
# 如果偷，则所得为 root.val + dp(root.left.left) + dp(root.left.right) + dp(root.right.left) + dp(root.right.right)
# 如果不偷，则所得为 dp(root.left) + dp(root.right)
# base case 就是 dp(None) = 0

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

class Solution:
    def __init__(self) -> None:
        self.cache = {}

    def dp(self, root):
        if root is None:
            return 0
        if root in self.cache:
            return self.cache[root]
        # 偷
        do = root.val
        if root.left:
            do = do + self.dp(root.left.left) + self.dp(root.left.right)
        if root.right:
            do = do + self.dp(root.right.left) + self.dp(root.right.right)
        # 不偷
        not_do = self.dp(root.left) + self.dp(root.right)
        r = max(do, not_do)
        self.cache[root] = r
        return r

    def rob(self, root: TreeNode) -> int:
        return self.dp(root)


import basf2 as b2
from L1trigger import add_trigger_simulation
################
import sys  # get argv
argvs = sys.argv  # get arg
argc = len(argvs)  # of arg
if argc != 3:
    sys.exit("ztsim02.py> # of arg is strange. Exit.")
if argc == 3:
    f_in_root = argvs[1]
    f_out_root = argvs[2]
# print
# print 'f_in_root  = %s' % f_in_root
# print 'f_out_root = %s\n' % f_out_root

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

b2.set_log_level(b2.LogLevel.ERROR)
# set_log_level(LogLevel.INFO)
# set_log_level(LogLevel.DEBUG)
# use_local_database('./trg_ecl/database.txt')

gearbox = b2.register_module('Gearbox')

# input
rootinput1 = b2.register_module('RootInput')
rootinput1.param('inputFileName', f_in_root)

# output
rootoutput = b2.register_module('RootOutput')
rootoutput.param('outputFileName', f_out_root)

# import random
progress = b2.register_module('Progress')

# Create paths
main = b2.create_path()

main.add_module(rootinput1)

main.add_module(progress)
main.add_module(gearbox)

add_trigger_simulation(main, component=["ECL"])

main.add_module(rootoutput, branchNames=["TRGECLTrgs", "TRGECLHits", "TRGECLClusters"])

# main
b2.process(main)
###
###
###
print(b2.statistics)
# ===<END>


import unittest
import pandas as pd
import numpy as np
import warnings
from spac.data_utils import combine_dfs

class TestCombineDFs(unittest.TestCase):

    def test_empty_input_list(self):
        expected_error_msg = "Input list is empty, please check."
        # Test when the input list is empty, it should raise a ValueError.
        with self.assertRaises(ValueError) as context:
            combine_dfs([])
            actual_error_message = str(context.exception)
            self.assertTrue(expected_error_msg in actual_error_message)

    def test_non_list_input(self):
        # Test when the input is not a list, it should raise a ValueError.
        expected_error_msg = "Input is not a list, please check."
        with self.assertRaises(ValueError) as context:
            combine_dfs("not_a_list")
            actual_warning = str(context.warning)
            self.assertTrue(expected_error_msg in actual_warning)

    def test_schema_warning_and_uneven_merge(self):
        # Test when the schemas of DataFrames are different,
        # it should print a warning.
        df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
        df2 = pd.DataFrame({'A': [1, 2], 'C': [5, 6]})

        expected_warning = "Schema of DataFrame 2 " + \
            "is different from the primary DataFrame."

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            combined_df = combine_dfs([df1, df2])

            # Check if a UserWarning is issued
            self.assertTrue(
                any(
                    issubclass(item.category, UserWarning) for item in w
                    )
                )

            # Check if the expected warning message
            # matches the actual warning message

            actual_warning = str(w[0].message)
            self.assertEqual(expected_warning, actual_warning)

            expected_df = pd.DataFrame(
                    {
                        'A': [1, 2, 1, 2],
                        'B': [3, 4, np.nan, np.nan],
                        'C': [np.nan, np.nan, 5, 6]
                    }
                )

            self.assertTrue(expected_df.equals(combined_df))

    def test_correct_input(self):
        # Test when the input is correct,
        # it should return the combined DataFrame.
        df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
        df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
        expected_df = pd.DataFrame({'A': [1, 2, 5, 6], 'B': [3, 4, 7, 8]})

        combined_df = combine_dfs([df1, df2])
        self.assertTrue(expected_df.equals(combined_df))

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


import torch
import torch.utils.data as data
from PIL import Image
import os
import math
import functools
import json
import copy
from scipy.ndimage import filters
import numpy as np

from utils import load_value_file

def cnnlstm(clip, sample_duration):

    h,w = np.array(clip[0]).shape
    #print("fsdf".format(img.size()))

    ret_img = np.zeros((1, h, w))
    ret_clip = []
    #clip = [img.convert('LA') for img in clip]
    #print(sample_duration)
    for i in range(1, sample_duration - 1):
        #print(np.array(clip[i]).shape)
        ret_clip.append(Image.fromarray(np.bitwise_and(np.array(clip[i]) - np.array(clip[i - 1])),
                        (np.array(clip[i + 1]) - np.array(clip[i]))))

    return torch.from_numpy(ret_img).float()

def cal_gradient(clip, sample_duration):

    h,w = np.array(clip[0]).shape
    #print("fsdf".format(img.size()))

    ret_img = np.zeros((3, h, w))

    #clip = [img.convert('LA') for img in clip]
    #print(sample_duration)
    for i in range(1, sample_duration):
        #print(np.array(clip[i]).shape)
        ret_img[0,:,:] = ret_img[0,:,:] + (np.array(clip[i]) - np.array(clip[i - 1]))

    img = Image.fromarray(ret_img[:,:,0])
    filters.sobel(img, 1, ret_img[:, :, 1])
    filters.sobel(img, 0, ret_img[:, :, 2])

    #print(type(ret_img))
    #img = Image.fromarray(ret_img)

    return torch.from_numpy(ret_img).float()

def pil_loader(path):
    #print("pil_loader called")
    # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
    with open(path, 'rb') as f:
        with Image.open(f) as img:
            #return img.convert('RGB')
            ## MCCNN
            return img.convert('L')

def accimage_loader(path):
    #print("accimage loader called")
    try:
        import accimage
        return accimage.Image(path)
    except IOError:
        # Potentially a decoding problem, fall back to PIL.Image
        return pil_loader(path)

def get_default_image_loader():
    from torchvision import get_image_backend
    if get_image_backend() == 'accimage':
        return accimage_loader
    else:
        return pil_loader

def video_loader(video_dir_path, frame_indices, image_loader):
    video = []
    pth = video_dir_path.split('/')
    pth = pth[-1].split('_')
    #print(video_dir_path)
    for i in frame_indices:
        image_path = os.path.join(video_dir_path, 'image_{:2d}.jpg'.format(i - 1))
        #print(image_path)
        if os.path.exists(image_path):
            video.append(image_loader(image_path))
        else:
            return video

    return video

def get_default_video_loader():
    #print("get default video loader called")
    image_loader = get_default_image_loader()
    return functools.partial(video_loader, image_loader=image_loader)

def load_annotation_data(data_file_path):
    with open(data_file_path, 'r') as data_file:
        return json.load(data_file)

def get_class_labels(data):
    class_labels_map = {}
    index = 0
    for class_label in data['labels']:
        class_labels_map[class_label] = index
        index += 1
    return class_labels_map

def get_video_names_and_annotations(data, subset):
    video_names = []
    annotations = []

    for key, value in data['database'].items():
        this_subset = value['subset']
        if this_subset == subset:
            label = value['annotations']['label']
            video_names.append('{}/{}'.format(label, key))
            annotations.append(value['annotations'])

    # video_names contains:
    # [ApplyEyeMakeup/v_ApplyEyeMakeup_g08_c01, ApplyLipstick/v_ApplyLipstick_g17_c05, ...]
    # annotations contains:
    # [{'label':'ApplyMakeup'}, {'label':'ApplyLipstick'}, ...]

    return video_names, annotations

def make_dataset(root_path, annotation_path, subset, n_samples_for_each_video,
                 sample_duration):
    data = load_annotation_data(annotation_path)
    video_names, annotations = get_video_names_and_annotations(data, subset)
    class_to_idx = get_class_labels(data)
    idx_to_class = {}
    for name, label in class_to_idx.items():
        idx_to_class[label] = name

    dataset = []
    for i in range(len(video_names)):
        if i % 1000 == 0:
            print('dataset loading [{}/{}]'.format(i, len(video_names)))

        video_path = os.path.join(root_path, video_names[i])
        if not os.path.exists(video_path):
            continue

        n_frames_file_path = os.path.join(video_path, 'n_frames')
        n_frames = int(load_value_file(n_frames_file_path))
        if n_frames <= 0:
            continue

        begin_t = 1
        end_t = n_frames
        sample = {
            'video': video_path,
            'segment': [begin_t, end_t],
            'n_frames': n_frames,
            'video_id': video_names[i].split('/')[1]
        }
        if len(annotations) != 0:
            sample['label'] = class_to_idx[annotations[i]['label']]
        else:
            sample['label'] = -1

        # n_sample_for_each_video = number of samples to create from a video
        # sample_duration = number of frames in each sample

        if n_samples_for_each_video == 1:
            sample['frame_indices'] = list(range(1, n_frames + 1))
            dataset.append(sample)
        # we are done here, else part is not important as of now
        else:
            if n_samples_for_each_video > 1:
                step = max(1,
                           math.ceil((n_frames - 1 - sample_duration) /
                                     (n_samples_for_each_video - 1)))
            else:
                step = sample_duration
            for j in range(1, n_frames, step):
                sample_j = copy.deepcopy(sample)
                sample_j['frame_indices'] = list(
                    range(j, min(n_frames + 1, j + sample_duration)))
                dataset.append(sample_j)

    return dataset, idx_to_class

class GRIT(data.Dataset):

    def __init__(self,
                 root_path,
                 annotation_path,
                 subset,
                 sample_duration,
                 n_samples_for_each_video=1,
                 spatial_transform=None,
                 temporal_transform=None,
                 target_transform=None,
                 get_loader=get_default_video_loader):
        self.data, self.class_names = make_dataset(
            root_path, annotation_path, subset, n_samples_for_each_video,
            sample_duration)

        self.spatial_transform = spatial_transform
        self.temporal_transform = temporal_transform
        self.target_transform = target_transform
        self.loader = get_loader()
        self.sample_duration = sample_duration

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            tuple: (image, target) where target is class_index of the target class.
        """
        path = self.data[index]['video']

        frame_indices = self.data[index]['frame_indices']
        #print(path)
        #print(frame_indices)
        if self.temporal_transform is not None:
            frame_indices = self.temporal_transform(frame_indices)
        clip = self.loader(path, frame_indices)

        if self.spatial_transform is not None:
            #print(self.spatial_transform)
            self.spatial_transform.randomize_parameters()
            clip = [self.spatial_transform(img) for img in clip]

        ######### important
        ######### inject gradient info in channels
        #clip = cal_gradient(clip, self.sample_duration)
        ###MCCNN
        # clip = torch.unsqueeze(clip, 0).permute(1, 0, 2, 3)
        #########
        # torch.stack concatenate vector entries in a new tensor along new(0) dimension
        #print(clip.size)

        ### CNNLSTM
        clip = cnnlstm(clip, self.sample_duration)

        clip = torch.stack(clip, 0).permute(1, 0, 2, 3)

        target = self.data[index]
        if self.target_transform is not None:
            target = self.target_transform(target)

        # returns:
        # clip: an array of images
        # target: dictionary containing sample info

        return clip, target

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


from telethon import TelegramClient, events, errors
from decouple import config

if __name__ == '__main__':
	try:
		# Console Title
		print('▄▄   ▄▄ ▄▄▄ ▄▄    ▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄')
		print('█  █ █  █   █  █  █ █       █   █       █   █       █   ▄  █')
		print('█  █▄█  █   █   █▄█ █   ▄▄▄▄█   █    ▄▄▄█   █    ▄▄▄█  █ █ █')
		print('█       █   █       █  █  ▄▄█   █   █▄▄▄█   █   █▄▄▄█   █▄▄█▄')
		print('█▄     ▄█   █  ▄    █  █ █  █   █    ▄▄▄█   █    ▄▄▄█    ▄▄  █')
		print('  █   █ █   █ █ █   █  █▄▄█ █   █   █   █   █   █▄▄▄█   █  █ █')
		print('  █▄▄▄█ █▄▄▄█▄█  █▄▄█▄▄▄▄▄▄▄█▄▄▄█▄▄▄█   █▄▄▄█▄▄▄▄▄▄▄█▄▄▄█  █▄█')

		# Getting config from .env file
		DEBUG_MODE = config('debug_mode')
		api_id = config('api_id')
		api_hash = config('api_hash')
		user_phone_number = config('phonenum_to_watch')

		# Starting the telegram client
		print('\nStarting Telegram Session...')
		client = TelegramClient('Yingifier_Session', api_id, api_hash)
		client.start()
		print('Waiting for message to yingify... (press ctrl+c to close)')

		# Event watcher waiting for when the user to send a message to any channel/chat
		@client.on(events.NewMessage(outgoing=True))
		async def new_message_handler(event):
			# Extracting the message variables from the event
			message_obj = event.message
			message_id = message_obj.id
			message_text = message_obj.message
			peer_id = message_obj.peer_id
			entity_id = ''
			if hasattr(peer_id, 'user_id'):
				entity_id = peer_id.user_id

			if hasattr(peer_id, 'channel_id'):
				entity_id = peer_id.channel_id

			if DEBUG_MODE is True:
				print(message_obj)
				print('Message ID: {}, Message Text: {}, Entity ID: {}'.format(message_id, message_text, entity_id))

			# Translating the message to Yinglish
			new_message_text = message_text.replace('th', 'zh')

			# Replacing the captured method with the new string
			try:
				await client.edit_message(entity=entity_id, message=message_id, text=new_message_text)
				print('\tEditing: "{}"'.format(message_text))
			except errors.MessageNotModifiedError:
				pass

		with client:
			client.loop.run_forever()

	except KeyboardInterrupt:
		print('\nDisconnecting from Telegram and closing Yingifier')
		client.disconnect()


import paho.mqtt.client as paho
import json

# MQTT related constants
MQTT_BROKER_HOST = "localhost"
MQTT_BROKER_PORT = 1883
MQTT_KEEPALIVE = 60
MQTT_TOPIC_NAME = "AnalyticsData"
MQTT_TOPIC_ENTER_NAME = "enter_event"
MQTT_TOPIC_EXIT_NAME = "exit_event"
MQTT_BROKER_ADDRESS = MQTT_BROKER_HOST + ":" + str(MQTT_BROKER_PORT)

enterExitCount = 0

def on_connect(client, userdata, message, rc):
    print("Connected to mqtt broker")
    f = open("AnalyticsData.txt", "w")
    f.close()
    client.subscribe(MQTT_TOPIC_NAME)

def on_subscribe(client, userdata, message, qos):
    print("Subscribed to topic")

def on_message(client, userdata, message):
    if message.topic == MQTT_TOPIC_NAME:
        f = open("AnalyticsData.txt", "a")
        f.write(str(message.payload.decode("utf-8")) + "\n")
        f.close()

mqttClient = paho.Client()
mqttClient.on_message = on_message
mqttClient.on_connect = on_connect
mqttClient.on_subscribe = on_subscribe
try:
    mqttClient.connect(MQTT_BROKER_HOST, MQTT_BROKER_PORT, MQTT_KEEPALIVE)
    mqttClient.loop_forever()
except:
    print("WARNING: Enter Exit Service could not connect to mqtt broker, no enter exit messages will be produced")


from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from LiveData.views import (LiveDataDetailAPIView,
                            LiveDataListAPIView,
                            LiveDataUpdateAPIView,
                            LiveDataDeleteAPIView)

app_name = 'LiveData'
urlpatterns = [
    url(r'edit/(?P<pk>\d+)$', LiveDataUpdateAPIView.as_view(), name='update'),
    url(r'detail/(?P<pk>\d+)$', LiveDataDetailAPIView.as_view(), name='detail'),
    url(r'delete/(?P<pk>\d+)$', LiveDataDeleteAPIView.as_view(), name='delete'),
    url(r'list/$', LiveDataListAPIView.as_view(), name='list'),
]


from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from math import *
import sys
print("Imports successful!")

def display():
    glFlush();
    glColor3f(0,0.5,0.5);
    drawTriangle()
    glMatrixMode(GL_MODELVIEW);
    glTranslatef(200.0,100.0,0.0);
    glColor3f(0.5,0.0,1.0);
    drawTriangle()
    glutSwapBuffers()
    return

def drawTriangle():
    glBegin(GL_TRIANGLES);
    glVertex2f(200,200);
    glVertex2f(600,200);
    glVertex2f(400,400);
    glEnd();

glutInit()
glutInitDisplayMode(GLUT_SINGLE  | GLUT_RGB)
glutInitWindowSize(800, 600)
glutInitWindowPosition(0, 0)
wind = glutCreateWindow("TRANSLATION")
#glutIdleFunc(display)
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, .5, 1.0);
glPointSize(4.0);
gluOrtho2D(0, 800,0, 800);
glutDisplayFunc(display)
glutMainLoop()


import os, config, time, requests, sys, json, logging, torch, utils
import numpy as np
from PIL import Image
import pandas as pd
import argparse
#from utils import LoadDataset
from requests.exceptions import HTTPError, ConnectTimeout
from glob import glob
#from load_dataset import load_test_caltech_256
from torchvision.utils import save_image

def load_dataset(args, dataset_path, savePath_idx):
	return load_test_caltech_256(config.input_dim, dataset_path, args.split_ratio, savePath_idx, config.model_id_dict[args.model_name])

def main(args):
	#Number of side branches that exists in the early-exit DNNs
	#nr_branches_model_list = np.arange(config.nr_min_branches, config.nr_max_branches+1)

	p_tar_list = [0.8, 0.81, 0.82, 0.83, 0.84, 0.85]
	dataset_path = config.dataset_path_dict["caltech256"]

	logPath = os.path.join(config.DIR_NAME, "logTest_%s.log"%(args.model_name))

	logging.basicConfig(level=logging.DEBUG, filename=logPath, filemode="a+", format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

	#This line defines the number of side branches processed at the edge
	nr_branch_edge = np.arange(3, config.n_branches+1)

	logging.debug("Sending Configuration")

	utils.sendModelConf(config.urlConfModelEdge, config.n_branches, args.dataset_name, args.model_name, args.location)
	#utils.sendModelConf(config.urlConfModelCloud, config.n_branches, args.dataset_name, args.model_name, args.location)

	logging.debug("Finish Configuration")

	#test_loader = load_dataset(args, dataset_path, save_indices_path)
	#inferenceTimeExperiment(test_loader, p_tar_list, nr_branch_edge, logPath)

if (__name__ == "__main__"):
	# Input Arguments. Hyperparameters configuration
	parser = argparse.ArgumentParser(description="Evaluating early-exits DNNs perfomance in terms of missed deadline probability.")

	parser.add_argument('--dataset_name', type=str, default=config.dataset_name,
		choices=["caltech256"], help='Dataset name (default: Caltech-256)')

	parser.add_argument('--model_name', type=str, default=config.model_name,
		choices=["mobilenet", "resnet18", "resnet152", "vgg16"], help='DNN model name (default: MobileNet)')

	parser.add_argument('--split_ratio', type=float, default=config.split_ratio, help='Split Ratio')

	parser.add_argument('--location', type=str, choices=["ohio", "sp"], help='Location of Cloud Server')

	args = parser.parse_args()

	main(args)


import numpy as np
import VkInline as vki
import FeiRaysInline as fri
from PIL import Image

width = 640
height = 480

film = fri.Film(width, height)

kernel = vki.Computer(['film'],
'''
void main()
{
    int x = int(gl_GlobalInvocationID.x);
    int y = int(gl_GlobalInvocationID.y);
    if (x >= film.width || y>=film.height) return;

    float u = (float(x)+0.5)/float(film.width);
    float v = (float(y)+0.5)/float(film.height);

    Spectrum color;
    from_rgb(color, vec3(u, v, 0.0));
    incr_pixel(film, x, y, color);
}
''')

blockSize = (8,8)
gridSize = (int((width+7)/8), int((height+7)/8))
kernel.launch(gridSize, blockSize, [film])
film.inc_times_exposure()

img_out = film.download_srgb()
Image.fromarray(img_out, 'RGBA').save('output.png')


#Thresholding:- It's a process of binarising the image. That is comparing the each pixel with a threshold value and if pixel < threshold then that pixel is considered
#as 0, if it is > then it will be considered either as 1 or 255.

import cv2 as cv
import numpy as np

img = cv.imread('images\lady.jpg')

cv.imshow('Lady', img)

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

cv.imshow('LadyGray', gray)

# Two types of thresholding.

# Method:- 1 Simple Thresholding

threshold, thresh = cv.threshold(gray, 150, 255, cv.THRESH_BINARY)

print(threshold)

cv.imshow('Thresholded Image', thresh)

#Inverse Threshold

threshold, thresh_inv = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV)

print(threshold)

cv.imshow('Inverse Thresholded Image', thresh_inv)

#In the simple threshold technique, the threshold value is user defined, hence this type of threshold may work for some cases and may not work for some other cases.

# Hence, in the adaptive threshold technique the algorithm it self finds the appropriate threshold value.

# Method:- 2 Adaptive Thresholding.

adaptive_threshold = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 3)

#Here 11 is the kernal size to find  the mean, so it is 11x11, and the 3 is just an integer which will be subtracted from the mean. In place of MEAN we can also use GUASSIAN.

cv.imshow('Adaptive Threshold Image', adaptive_threshold)

cv.waitKey(0)


SPECIAL_SECTIONS = ['INTRODUCTION', 'CONCLUSION', 'PERSPECTIVES']
UNIQUENESS_METHODS = ['first_occurrence', 'unique_only']

def is_box_section(title):
    """
    Box sections have specific titles: "Box N | Title goes here".
    This function determines whether title belongs to a box section.
    """
    if '|' not in title:
        return False
    return 'Box' in title.split('|')[0]

def flatten_clustering_impl(clustering, max_level, current_level):
    """
    Recursive traversal of multi-level dict-like clustering.
    Clusters on level larger than `max_level` are merged.
    """
    current_level_elements = []
    clusters = []
    num_clusters = 0

    for el in clustering:
        if isinstance(el, dict):
            inner_clusters, num_inner_clusters = flatten_clustering_impl(el['references'],
                                                                         max_level, current_level + 1)
            if max_level <= current_level:
                current_level_elements.extend(inner_clusters)
            else:
                if num_inner_clusters == 1:
                    clusters.append(inner_clusters)
                else:
                    clusters.extend(inner_clusters)
                num_clusters += num_inner_clusters
        else:
            current_level_elements.append(el)

    if max_level <= current_level or not clusters:
        return current_level_elements, 1
    else:
        if current_level_elements:
            clusters.insert(0, current_level_elements)
            num_clusters += 1
        if num_clusters == 1:
            return clusters[0], num_clusters
        else:
            return clusters, num_clusters

def flatten_clustering(clustering, max_level,
                       include_special_sections,
                       include_box_sections):
    """
    Builds a flat version of multi-level clustering sliced at `max_level`.
    max_level is 1-based.
    """
    flat_clustering = []
    for section in clustering:
        is_special_section = section['title'] in SPECIAL_SECTIONS
        if not include_special_sections and is_special_section:
            continue
        if not include_box_sections and is_box_section(section['title']):
            continue
        clusters, num_clusters = flatten_clustering_impl(section['references'], max_level, 1)
        if num_clusters == 1:
            flat_clustering.append(clusters)
        else:
            flat_clustering.extend(clusters)
    return flat_clustering

def unique_ids_clustering(clustering, method):
    """
    Ensures that each paper is assigned only to one cluster by one of the methods:
     * 'first_occurence' - paper is assigned to the first cluster
     * 'unique_only' - only papers belonging to one cluster are taken into account
    """
    id_cluster = {}
    for i, cluster in enumerate(clustering):
        for pmid in cluster:
            if pmid not in id_cluster:
                id_cluster[pmid] = []
            id_cluster[pmid].append(i)
    if method == 'first_occurrence':
        return {str(k): v[0] for k, v in id_cluster.items()}
    elif method == 'unique_only':
        return {str(k): v[0] for k, v in id_cluster.items() if len(set(v)) == 1}

def preprocess_clustering(clustering, max_level,
                          include_special_sections=False,
                          include_box_sections=True,
                          uniqueness_method=None):
    """
    Convert raw multi-level clustering to a flat clustering with unique ids.
    max_level is 1-based.
    """
    flat_clustering = flatten_clustering(clustering, max_level,
                                         include_special_sections,
                                         include_box_sections)

    if uniqueness_method:
        if uniqueness_method not in UNIQUENESS_METHODS:
            raise ValueError('Unrecognized uniqueness method')
        return unique_ids_clustering(flat_clustering, uniqueness_method)

    return flat_clustering

def get_clustering_level(clustering):
    """
    Returns the numbers of levels in the clustering.
    Intended to be used as an upper bound for 1-based `max_level` in clustering preprocessing.
    """
    levels = []
    for el in clustering:
        if isinstance(el, dict):
            levels.append(get_clustering_level(el['references']))
    if not levels:
        return 1
    else:
        return max(levels) + 1


"""myresume URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.contrib.auth import views
from myapp import views

urlpatterns = [
    url(r'^$',views.index,name='index'),
    url(r'^admin/', admin.site.urls),
    # url(r'^myapp/',include('myapp.urls')),
    url(r'^about/',views.about,name='about'),
    url(r'^profile_picture/',views.profile_picture,name='profile_picture'),
    url(r'^education/',views.education,name='education'),
    url(r'^technical_skills/',views.technical_skills,name='technical_skills'),
    url(r'^research/',views.research,name='research'),
    url(r'^strengths/',views.strengths,name='strengths'),
    url(r'^certifications_workshops/',views.certifications_workshops,name='certifications_workshops'),
    url(r'^project_experience/',views.project_experience,name='project_experience'),
    url(r'^achievements/',views.achievements,name='achievements'),
    url(r'^extracurricular_activities/',views.extracurricular_activities,name='extracurricular_activities'),
    url(r'^hobbies/',views.hobbies,name='hobbies'),
    url(r'^personal_details/',views.personal_details,name='personal_details'),

]


import scrapy
import pandas as pd
from scrapy import Request
import re

class GlassdoorTextSpider(scrapy.Spider):
    name = 'glassdoor_text'

    def start_requests(self):
        # for item in pd.read_csv(f"data_{self.topic}/glassdoor_raw.csv", converters={"link": lambda x: str(x)}):

        for index, row in pd.read_csv(f"data_{self.cat}/glassdoor/glassdoor_raw.csv").iterrows():
            yield Request(
                url=row['link'],
                dont_filter=True,
                callback=self.parse_text,
                cb_kwargs=dict(link=row['link'], job_id=row['job_id']))

    def parse_text(self, response, link, job_id):
        text = self.cleanhtml("".join(response.css(
            "#JobDescriptionContainer").css(".desc").getall()))
        yield {"text": text, "job_id": job_id, "link": link}

    def cleanhtml(self, raw_html):
        cleanr = re.compile('<.*?>')
        cleantext = re.sub(cleanr, '', raw_html)
        cleantext = cleantext.replace("\n", "")
        cleantext = cleantext.replace("\t", "")
        cleantext = cleantext.replace("\r", "")
        return cleantext.strip()


# import the sys module, that tells us that we can use all functions defined in the sys module.
import sys

# the fuction input display the text string that is passed to it as arguments between the ( and ) signs. it then asks for a value.
text_of_first_number=input("enter the first number: ")

# lets read the operation
oper = input("operation: ")

# read the string value of the second variable.
text_of_second_number=input("enter the second number: ")

# now in python you can't add two text string values, you need to convert the text to a number. lets do it for the first number
first_number=float(text_of_first_number)
# lets covert the second text string to a number
# please note: if you try to convert a text with letters, and not a number then this will give you an error.
second_number = float(text_of_second_number)

# now something new: check that this is an allowed operation
# the keyword if says that we are checking if a condition is fulfilled.
# the sign == says that the value of the left hand side is compared with the right hand side.
# here we look up the value of the variable oper and compare it with the string constanct *
# if both are equal then we run the statement: result = first_number * second_number
# if that is not true then we do everything that is written after the else: line

if oper == "*":

    # What is run if the condition is true: see that the line is indented.
    # That's a feature of the python programming language ;-(
    # it tells us that this statement is run only if the condition oper == "*" is true.
    result = first_number * second_number
else:
    if oper == "/":
        result = first_number / second_number
    else:
        if oper == "+":
            result = first_number + second_number
        else:
            if oper == "-":
                result = first_number - second_number
            else:
                # if the variable oper is not equal to any of the handled operations, then print an error message
                print("error: illegal operand!")
                # exit the program. (we are calling the function exit from the sys module)
                # please note that we have the name of the module sys, followed by a . sign, then the name of the function followed by ()
                # every function call has the argument passed within ( and ) - just like with the print function
                sys.exit(1)

# onces all the checks are finished: return to the top level indentation level (that's a feature of pythob ;-(
# it says that the  statement does not belong to the previous if statement.
# if you have a space in front of the next print statement then you get the error "unindent does not match any outer indentation level"
print("the result:")
print(result)

# exercise: write a program that combines the two exercise programs of the previous lesson, by displaying a list of choices.
# the first choice is to compute the square of the circle, the second one is to compute the square of a rectangle.
# run the respective programs upon doing this choise.


import random
import sys
import pygame
import numpy
from snake import Snake
from foodspawner import FoodSpawner
from fileio import FileIO

baseFramerate = 500
size = 500
fIO = FileIO()

def gameover(quitGame=False, score = 0, framerate = 0):
	pygame.quit()
	fIO.printScore(score,framerate)
	if quitGame == True:
		sys.exit(0)
	init(baseFramerate)

def userInput(snake):
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			gameover(True)
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_RIGHT:
				snake.changeDirTo("R")

			if event.key == pygame.K_LEFT:
				snake.changeDirTo("L")

			if event.key == pygame.K_DOWN:
				snake.changeDirTo("D")

			if event.key == pygame.K_UP:
				snake.changeDirTo("U")

def compInput(snake, foodpos):
	# Quit key event
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			gameover(True)

	moved = False

	# Avoid walls
	if snake.getDir() != "U" and snake.getDir() != "D":
		if snake.getX()+10 >= size and moved==False:
			if snake.getY() <= size/2:
				snake.changeDirTo("D")
				moved = True
			else:
				snake.changeDirTo("U")
				moved = True
		if snake.getX()-10 < 0 and moved==False:
			if snake.getY() <= size/2:
				snake.changeDirTo("D")
				moved = True
			else:
				snake.changeDirTo("U")
				moved = True
	if snake.getDir() != "L" and snake.getDir() != "R":
		if snake.getY()+10 >= size and moved==False:
			if snake.getX() <= size/2:
				snake.changeDirTo("R")
				moved = True
			else:
				snake.changeDirTo("L")
				moved = True
		if snake.getY()-10 < 0 and moved==False:
			if snake.getX() <= size/2:
				moved = True
				snake.changeDirTo("R")
			else:
				moved = True
				snake.changeDirTo("L")

	# Avoid bodyparts

	if snake.getDir() == "L" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getX()-10 == bodyParts[0] and snake.getY() == bodyParts[1] and moved==False:

				if snake.checkPos(snake.getX()-10,snake.getY()-10):
					if snake.checkPos(snake.getX(),snake.getY()+10):
						snake.changeDirTo("U")
					else:
						snake.changeDirTo("D")
				else:
					snake.changeDirTo("U")
				moved=True

	if snake.getDir() == "R" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getX()+10 == bodyParts[0] and snake.getY() == bodyParts[1]  and moved==False:
				if snake.checkPos(snake.getX()+10,snake.getY()-10):
					snake.changeDirTo("D")
				else:
					snake.changeDirTo("U")
				moved=True

	if snake.getDir() == "U" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getY()-10 == bodyParts[1] and snake.getX() == bodyParts[0]  and moved==False:
				if snake.checkPos(snake.getX()+10, snake.getY()-10):
					if snake.checkPos(snake.getX()-10,snake.getY()):
						snake.changeDirTo("R")
					else:
						snake.changeDirTo("L")
				else:
					snake.changeDirTo("R")
				moved=True
	if snake.getDir() == "D" and moved==False:
		for bodyParts in snake.getBody()[1:]:
			if snake.getY()+10 == bodyParts[1] and snake.getX() == bodyParts[0]  and moved==False:
				if snake.checkPos(snake.getX()+10, snake.getY()+10):
					snake.changeDirTo("L")
				else:
					snake.changeDirTo("R")
				moved=True

	# Look for food
	if  moved==False:
		if snake.getX() < foodpos[0] :
			snake.changeDirTo("R")
			moved = True
		elif snake.getX() > foodpos[0]:
			snake.changeDirTo("L")
			moved = True
		else:
			if snake.getY() < foodpos[1] :
				snake.changeDirTo("D")
				moved=True
			else:
				snake.changeDirTo("U")
				moved=True

def init(framerate):
	global size
	window = pygame.display.set_mode((size, size))
	pygame.display.set_caption("SNAKE")
	fps = pygame.time.Clock()

	score = 0

	snake = Snake(size)
	food = FoodSpawner(size)

	highscore = "\t Highscore: "+str(fIO.getHighScore())

	while True:
		# userInput(snake)

		foodpos = food.spawnFood()
		compInput(snake,foodpos)

		if(snake.move(foodpos) == 1):
			score += 1
			if(score%5 == 0 and score > 0):
				framerate += 1
			if(foodpos == snake.position):
    				food.setFoodOnScreen(False)

		window.fill(pygame.Color(0, 0, int(abs(numpy.sin(score)*50))))
		for pos in snake.getBody():
			pygame.draw.rect(window, pygame.Color(0, 255, 0), pygame.Rect(pos[0], pos[1], 10,10))
		pygame.draw.rect(window, pygame.Color(255, 0, 0), pygame.Rect(foodpos[0], foodpos[1], 10, 10))

		if snake.checkCollision() == 1:
			gameover(False, score, framerate)
		pygame.display.set_caption("Snake | Score:"+str(score)+highscore+"\t speed:"+str(framerate))
		pygame.display.flip()
		fps.tick(framerate)

init(baseFramerate)


from higher_lower_data import data
from random import randint

data_size = len(data)
is_game_end = False
choice_A = data[randint(0, data_size - 1)]
choice_B = data[randint(0, data_size - 1)]
user_score = 0

def comparison_result(a, b):
    if a["follower_count"] > b["follower_count"]:
        return "A"
    else:
        return "B"

def game():
    global choice_A, choice_B, user_score, is_game_end
    while choice_A == choice_B:
        choice_B = data[randint(0, data_size - 1)]
    print(f"Compare A: {choice_A['name']}, {choice_A['description']}, from {choice_A['country']}")
    print("vs")
    print(f"Against B: {choice_B['name']}, {choice_B['description']}, from {choice_B['country']}")
    user_choice = input("Who has more followers? Type 'A' or 'B': ")
    if user_choice != comparison_result(choice_A, choice_B):
        print(f"Sorry, that's wrong! Final score is: {user_score}")
        is_game_end = True
    else:
        print("That's correct!!! ")
        choice_A = choice_B
        choice_B = data[randint(0, data_size - 1)]
        user_score += 1

while not is_game_end:
    game()


# Making emoji's with dictionaries
message = input(">")
words = message.split(' ') # this will go through a string and apply a character specified, in this case a space, and return a list
print(words) # the output will be: ['Good', 'morning', 'sunshine']

# here is the emoji dictionary
message = input(">")
words = message.split(' ')
emojis = {
    ":)": "🙂",
    ":(": "🙁"
}
output = ""
for word in words:
    output += emojis.get(word, word) + " "
print(output)
# this program may not work if emoji's are not implemented in python


import copy
import logging

import torch
from pytorch_metric_learning.distances import LpDistance
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import get_linear_schedule_with_warmup

from src.data_utils import InstanceDataset
from src.utils import get_evaluate_fpr

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s -   %(message)s',
                    datefmt='%m/%d/%Y %H:%M:%S',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

distance_metric = LpDistance(power=2)

def test_meta(args, device, model, target_task):
    label2id = target_task['type2id']
    support_dataset = InstanceDataset(target_task, domain="support")
    query_dataset = InstanceDataset(target_task, domain="query")
    support_dataloader = DataLoader(support_dataset, batch_size=args.inner_batch_size,
                                    collate_fn=support_dataset.collate,
                                    shuffle=False, drop_last=False,
                                    num_workers=16 if device == 'cuda' else 0)
    query_dataloader = DataLoader(query_dataset, batch_size=args.inner_batch_size,
                                  collate_fn=query_dataset.collate,
                                  shuffle=False, drop_last=False,
                                  num_workers=16 if device == 'cuda' else 0)

    # Test
    O_id = label2id["O"]
    optimizer, scheduler = set_optimizer(args, model, train_steps=len(support_dataloader), get_scheduler=False)

    # TODO: inner train on support set
    best_support_loss = 1e99
    for support_epoch in range(args.inner_identify_loops):
        for batch in support_dataloader:
            support_loss = 0.
            batch_support_input_ids, batch_support_input_mask, \
            batch_support_segment_ids, batch_support_label_ids = (i.to(device) for i in batch[:4])
            batch_support_spans = batch[-1]

            step_loss, _, _ = model.forward_(batch_support_input_ids, batch_support_input_mask,
                                             batch_support_segment_ids, batch_support_label_ids,
                                             batch_support_spans, O_id,
                                             post_avg_by_class=args.post_avg_by_class,
                                             prior_avg_by_class=args.prior_avg_by_class)

            support_loss += step_loss.item()
            optimizer.zero_grad()
            step_loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.25)
            optimizer.step()
            if scheduler:
                scheduler.step()
        if support_loss <= best_support_loss:
            best_support_loss = support_loss
        else:
            logger.info(f"This Dev process use {support_epoch + 1} support epochs, final loss {best_support_loss:.3f}")
            break

    support_entity_vectors, support_entity_ids = None, None
    # TODO: get prototype vectors
    for batch in support_dataloader:
        batch_support_input_ids, batch_support_input_mask, \
        batch_support_segment_ids, batch_support_label_ids = (i.to(device) for i in batch[:4])
        batch_support_spans = batch[-1]
        with torch.no_grad():
            _, entity_vectors, entity_ids = model.forward_(batch_support_input_ids, batch_support_input_mask,
                                                           batch_support_segment_ids, batch_support_label_ids,
                                                           batch_support_spans, O_id,
                                                           post_avg_by_class=args.post_avg_by_class,
                                                           prior_avg_by_class=args.prior_avg_by_class,
                                                           only_retur_protos=True)

        # 汇总
        if support_entity_vectors == None:
            support_entity_vectors = entity_vectors.to('cpu')
            support_entity_ids = entity_ids.to('cpu')
        else:
            support_entity_vectors = torch.vstack((support_entity_vectors, entity_vectors.to('cpu')))
            support_entity_ids = torch.hstack((support_entity_ids, entity_ids.to('cpu')))

    _, _, proto_entity_vectors, proto_entity_ids = \
        model.get_proto_vectors(O_id, support_entity_vectors, support_entity_ids,
                                args.prior_avg_by_class, args.post_avg_by_class)

    # TODO: get tag prediction on query set
    for batch in query_dataloader:
        batch_query_input_ids, batch_query_input_mask, \
        batch_query_segment_ids, batch_query_label_ids = (i.to(device) for i in batch[:4])
        batch_query_spans = batch[-1]
        with torch.no_grad():
            _, entity_vectors, golden_entity_ids = model.forward_(batch_query_input_ids, batch_query_input_mask,
                                                                  batch_query_segment_ids, batch_query_label_ids,
                                                                  batch_query_spans, O_id,
                                                                  post_avg_by_class=args.post_avg_by_class,
                                                                  prior_avg_by_class=args.prior_avg_by_class,
                                                                  only_retur_protos=True)

        hidden_size = entity_vectors.shape[-1]

        # prior: 先判断是不是 entity
        is_entity_prob = model.entity_classifier(entity_vectors).reshape(-1).to('cpu')

        # 然后判断实体类型
        pred_vectors = distance_metric(entity_vectors.view(-1, hidden_size).to('cpu'), proto_entity_vectors)
        pred_ids = proto_entity_ids[torch.argmin(pred_vectors, dim=-1)]  # b_s, seq_len, seq_len, 1
        # 非实体设置为 O-tag
        pred_ids[is_entity_prob > 0] = O_id

    prior_f1, prior_precision, prior_recall, ent_f1, ent_precision, ent_recall \
        = get_evaluate_fpr(pred_ids, golden_entity_ids, O_id=O_id)
    return prior_f1, prior_precision, prior_recall, ent_f1, ent_precision, ent_recall

def train_meta(args, label2id, train_task, model, device):
    """
    task_dataloader is ccomposed of three part:
        support tasks
        query tasks
        label map shared

    This function is composed of:
        inner train on support set ( negative sample for O-tag)
        get prototype vectors of support set ( negative sample for O-tag)
        get loss on query set ( full sample for candidate span)
    """

    support_dataset = InstanceDataset(train_task, domain="support")
    query_dataset = InstanceDataset(train_task, domain="query")
    support_dataloader = DataLoader(support_dataset, batch_size=args.inner_batch_size,
                                    collate_fn=support_dataset.collate,
                                    shuffle=False, drop_last=False,
                                    num_workers=16 if device == 'cuda' else 0)
    query_dataloader = DataLoader(query_dataset, batch_size=args.inner_batch_size,
                                  collate_fn=query_dataset.collate,
                                  shuffle=False, drop_last=False,
                                  num_workers=16 if device == 'cuda' else 0)

    O_id = label2id["O"]

    # TODO: inner train for entity identify
    optimizer, scheduler = set_optimizer(args, model, train_steps=len(support_dataloader), get_scheduler=False)

    for i in range(args.inner_identify_loops):  # 每个 task 训练多少轮

        # TODO: 每一轮都更新模型
        for support_batch, query_batch in zip(support_dataloader, query_dataloader):
            # TODO：存在问题，不应该用 batch level 进行 forward_，
            #  这样 不保证forward_内部包含所有vector

            batch_support_input_ids, batch_support_input_mask, \
            batch_support_segment_ids, batch_support_label_ids = (i.to(device) for i in support_batch[:4])
            batch_support_spans = support_batch[-1]

            batch_query_input_ids, batch_query_input_mask, \
            batch_query_segment_ids, batch_query_label_ids = (i.to(device) for i in query_batch[:4])
            batch_query_spans = query_batch[-1]

            s_step_loss, _, _ = model.forward_(batch_support_input_ids, batch_support_input_mask,
                                               batch_support_segment_ids, batch_support_label_ids,
                                               batch_support_spans, O_id,
                                               post_avg_by_class=args.post_avg_by_class,
                                               prior_avg_by_class=args.prior_avg_by_class)

            q_step_loss, _, _ = model.forward_(batch_query_input_ids, batch_query_input_mask,
                                               batch_query_segment_ids, batch_query_label_ids,
                                               batch_query_spans, O_id,
                                               post_avg_by_class=args.post_avg_by_class,
                                               prior_avg_by_class=args.prior_avg_by_class)

            one_step_loss = s_step_loss + q_step_loss

            optimizer.zero_grad()
            one_step_loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.25)
            optimizer.step()
            if scheduler:
                scheduler.step()

    # TODO: get model params for identify update
    _, identify_updated_params = get_names_and_params(model)
    identify_updated_params = copy.deepcopy(identify_updated_params)
    logger.info(f"\t\tidentify loss: {one_step_loss.item():.3f}")
    return identify_updated_params, None

    support_entity_vectors, support_entity_ids = None, None
    # TODO: get prototype vectors
    for batch in support_dataloader:
        batch_support_input_ids, batch_support_input_mask, \
        batch_support_segment_ids, batch_support_label_ids = (i.to(device) for i in batch[:4])
        batch_support_spans = batch[-1]
        entity_vectors, entity_ids = model.get_entities_and_ids(batch_support_input_ids,
                                                                batch_support_input_mask,
                                                                batch_support_segment_ids,
                                                                batch_support_spans, O_id)

        # 汇总
        if support_entity_vectors == None:
            support_entity_vectors = entity_vectors
            support_entity_ids = entity_ids
        else:
            support_entity_vectors = torch.vstack((support_entity_vectors, entity_vectors))
            support_entity_ids = torch.hstack((support_entity_ids, entity_ids))

    _, _, proto_entity_vectors, proto_entity_ids = \
        model.get_proto_vectors(O_id, support_entity_vectors, support_entity_ids,
                                args.prior_avg_by_class, args.post_avg_by_class)

    proto_entity_vectors = proto_entity_vectors.detach()  # 尝试 2，见下文
    # TODO: get loss for entity classification
    optimizer, scheduler = set_optimizer(args, model, train_steps=len(support_dataloader), get_scheduler=False)

    for i in range(args.inner_classify_loops):
        for batch in query_dataloader:
            batch_query_input_ids, batch_query_input_mask, \
            batch_query_segment_ids, batch_query_label_ids = (i.to(device) for i in batch[:4])
            batch_query_spans = batch[-1]

            # 序列方式
            q_entity_vectors, q_entity_ids = model.get_entities_and_ids(batch_query_input_ids,
                                                                        batch_query_input_mask,
                                                                        batch_query_segment_ids,
                                                                        batch_query_spans, O_id)

            # get loss of Entity classification
            if args.use_prior:
                entity_pros = model.entity_classifier(q_entity_vectors)
                is_entity_pros = entity_pros[q_entity_ids != O_id]
            else:
                is_entity_pros = None

            is_ent_vectors = q_entity_vectors[q_entity_ids != O_id]
            is_ent_ids = q_entity_ids[q_entity_ids != O_id]
            is_ent_dis = distance_metric(is_ent_vectors, proto_entity_vectors)
            is_ent_loss = model.get_loss(is_ent_ids, is_ent_dis, proto_entity_ids, is_entity_pros)

            # update
            optimizer.zero_grad()
            is_ent_loss.backward(retain_graph=True)
            """
            出现 BUG，计算图被破坏，因为 backward() 调用之后，图就被释放了。 proto_entity_vectors 无法回传了。

                尝试 1 # retain_graph=True 因为第一次 loop 后 proto_entity_vectors 的计算图被破坏了

                又出现错误 one of the variables needed for gradient computation has been modified by an inplace operation
                是因为首次更新后 模型改变了，所以 `proto_entity_vectors` 不能回传了

                尝试 2 ，时间快的做法： # 直接对 proto_entity_vectors 进行 detach
                尝试 3 ，每次重新得到 proto_entity_vectors
            """
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.25)
            optimizer.step()

    # TODO: get model params for classifier update
    _, classify_updated_params = get_names_and_params(model)
    classify_updated_params = copy.deepcopy(classify_updated_params)
    return identify_updated_params, classify_updated_params

def load_gradients(model, names, grads, norm=1):
    model_params = model.state_dict(keep_vars=True)
    for n, g in zip(names, grads):
        if model_params[n].grad is None:
            continue
        model_params[n].grad.data.add_(g.data / norm)  # accumulate normed grad

def update_weight(model, names, all_tasks_grad, step_len=1.):
    model_params = model.state_dict(keep_vars=True)
    norm = float(len(all_tasks_grad))
    for task_grad in all_tasks_grad:  # each task
        for n, g in zip(names, task_grad):
            if model_params[n].grad is None:
                continue
        model_params[n].data.add_(step_len * g / norm)

def load_weights(model, names, params):
    model_params = model.state_dict()
    for n, p in zip(names, params):
        model_params[n].data.copy_(p.data)

def get_names_and_params(model):
    names = [n for n, p in model.named_parameters() if p.requires_grad]
    params = [p for p in model.parameters() if p.requires_grad]
    return names, params

def set_optimizer(args, model, train_steps=None, get_scheduler=False):
    if not args.froze_encoder:
        # encoder 的 named_parameters()
        encoder_param_optimizer = list(model.encoder.named_parameters())

    # classifier/dense 的 named_parameters()
    dense_para_optimizer = list(model.head.named_parameters()) \
                           + list(model.tail.named_parameters()) \
                           + list(model.entity_classifier.named_parameters())

    # 筛选 pooler
    if not args.froze_encoder:
        encoder_param_optimizer = [n for n in encoder_param_optimizer if 'pooler' not in n[0]]
    dense_para_optimizer = [n for n in dense_para_optimizer if 'pooler' not in n[0]]

    no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
    optimizer_grouped_parameters = []
    if not args.froze_encoder:
        optimizer_grouped_parameters += [
            {'params': [p for n, p in encoder_param_optimizer if not any(nd in n for nd in no_decay)],
             'weight_decay': 0.01,
             'lr': args.encoder_lr},
            {'params': [p for n, p in encoder_param_optimizer if any(nd in n for nd in no_decay)],
             'weight_decay': 0.0,
             'lr': args.encoder_lr}
        ]
    optimizer_grouped_parameters += [
        {'params': [p for n, p in dense_para_optimizer if not any(nd in n for nd in no_decay)],
         'weight_decay': 0.01,
         'lr': args.downsize_lr
         },
        {'params': [p for n, p in dense_para_optimizer if any(nd in n for nd in no_decay)],
         'weight_decay': 0.0,
         'lr': args.downsize_lr}
    ]

    optimizer = AdamW(optimizer_grouped_parameters, lr=args.encoder_lr, eps=1e-8)

    scheduler = None
    if get_scheduler:
        scheduler = get_linear_schedule_with_warmup(
            optimizer, num_warmup_steps=int(0.01 * train_steps), num_training_steps=train_steps
        )
        logger.info(f"num_warmup_steps: {int(0.1 * train_steps)}")
    return optimizer, scheduler

def froze_model(args, model):
    # Froze model's PLM
    if args.froze_encoder:
        model.encoder.requires_grad = False
        for p in model.encoder.parameters():
            p.requires_grad = False

    # Embedding and Pooling freezing
    no_grad_param_names = ["embeddings", "pooler"]
    logger.info("The frozen parameters are:")
    for name, param in model.named_parameters():
        if any(no_grad_pn in name for no_grad_pn in no_grad_param_names):
            param.requires_grad = False

    return model


import numpy as np

#j = np.complex(1j)

Y = np.zeros((2,2))

Y[0,0] = 1
Y[0,1] = 5
Y[1,1] = 100
Y[1,0] = 5

print(np.linalg.inv(Y)*75)


# Comment it before submitting
# class Node:
#     def __init__(self, value, next_item=None):
#         self.value = value
#         self.next_item = next_item

def solution(node, elem):
    idx = 0
    while node and node.value != elem:
        node = node.next_item
        idx = idx + 1
    if node:
        return idx
    else:
        return -1

def test():
    node3 = Node("node3", None)
    node2 = Node("node2", node3)
    node1 = Node("node1", node2)
    node0 = Node("node0", node1)
    idx = solution(node0, "node22")
    # result is idx == 2

2.D. Заботливая мама.py


import argparse
import asyncio
import datetime
import json
import logging
import re

import websockets
from pygtail import Pygtail
from websockets import WebSocketServerProtocol

INTERVAL = 1
logging.basicConfig(level=logging.INFO)

class Server:
    def __init__(self, log_file, interface, port):
        self.log_file = log_file
        self.interface = interface
        self.port = port
        self.clients = set()
        self.ON_LINE = set()

    async def register(self, ws: WebSocketServerProtocol) -> None:
        self.clients.add(ws)
        logging.info(f'{ws.remote_address} connects.')
        jobj = json.dumps(list(self.ON_LINE))
        await ws.send(str(jobj))

    async def unregister(self, ws: WebSocketServerProtocol) -> None:
        self.clients.remove(ws)
        logging.info(f'{ws.remote_address} disconnects.')

    async def send_to_clients(self, message: str) -> None:
        if self.clients:
            await asyncio.wait([client.send(message) for client in self.clients])

    async def ws_handler(self, ws: WebSocketServerProtocol, url: str) -> None:
        await self.register(ws)
        try:
            await self.distribute(ws)
        except websockets.exceptions.ConnectionClosedError:
            pass
        finally:
            await self.unregister(ws)

    async def distribute(self, ws: WebSocketServerProtocol) -> None:
        async for message in ws:
            logging.info(f'I got the message: {message}')
            await self.send_to_clients(message)

    async def start(self) -> None:
        start_server = websockets.serve(self.ws_handler, self.interface, self.port)
        self.server = await start_server

    def stop(self) -> None:
        if self.server != None:
            self.server.close()

    async def monitor_log(self) -> None:
        joinedRegEx = re.compile("^.*: (.*) joined the game$")
        leftRegEx = re.compile("^.*: (.*) left the game$")
        pygtail = Pygtail(self.log_file, paranoid=True)
        while True:
            try:
                for line in pygtail:
                    x = joinedRegEx.search(line)
                    if x != None:
                        self.ON_LINE.add(x.group(1))
                    x = leftRegEx.search(line)
                    if x != None:
                        self.ON_LINE.discard(x.group(1))
                    jobj = json.dumps(list(self.ON_LINE))
                    now = datetime.datetime.now() + datetime.timedelta(hours=5)
                    print(str(jobj) + "  " + now.strftime('%H:%M:%S on %A, %B the %dth, %Y'))
                    await self.send_to_clients(str(jobj))
                await asyncio.sleep(INTERVAL)
            except OSError:
                await asyncio.sleep(INTERVAL)

ap = argparse.ArgumentParser()
ap.add_argument("-l", "--log", required=True, help="path to the log file")
ap.add_argument("-i", "--interface", default="0.0.0.0", help="network interface")
ap.add_argument("-p", "--port", default=4000, help="port to use for websocket")
args = ap.parse_args()

log_file = args.log
interface = args.interface
port = args.port
try:
    server = Server(log_file, interface, port)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(server.start(), server.monitor_log()))
    loop.run_forever()
except KeyboardInterrupt:
    server.stop()


import random
import time
from tkinter import *

root = Tk()
root.geometry("500x500+450+100")
root.title("Taş Kağıt Makas v0.1")
color="#C500FF"
background = Label(width=500, height=500, bg=color)
background.place(x=0, y=0)
root.iconbitmap("logo.ico")
root.resizable(width=False, height=False)

list1 = ["taş", "kağıt","makas"]

skorsiz = 0

skorrakip = 0

def Rock():
    global skorrakip
    global skorsiz
    v = random.choice(list1)
    if v == "taş":
        label3["text"] = v
        label4["text"] = "Kazanan : Berabere"
    elif v == "kağıt":
        label3["text"] = v
        label4["text"] = "Kazanan : Rakip"
        skorrakip = skorrakip+1
        label6["text"] = "Rakip : {0}".format(skorrakip)
    elif v == "makas":
        label3["text"] = v
        label4["text"] = "Kazanan : Siz"
        skorsiz = skorsiz+1
        label5["text"]="Siz : {0}".format(skorsiz)

def Paper():
    global skorrakip
    global skorsiz
    v = random.choice(list1)
    if v == "kağıt":
        label3["text"] = v
        label4["text"] = "Kazanan : Berabere"
    elif v == "makas":
        label3["text"] = v
        label4["text"] = "Kazanan : Rakip"
        skorrakip = skorrakip+1
        label6["text"] = "Rakip : {0}".format(skorrakip)
    elif v == "taş":
        label3["text"] = v
        label4["text"] = "Kazanan : Siz"
        skorsiz = skorsiz+1
        label5["text"]="Siz : {0}".format(skorsiz)

def Scissors():
    global skorrakip
    global skorsiz
    v = random.choice(list1)
    if v == "makas":
        label3["text"] = v
        label4["text"] = "Kazanan : Berabere"
    elif v == "taş":
        label3["text"] = v
        label4["text"] = "Kazanan : Rakip"
        skorrakip = skorrakip+1
        label6["text"] = "Rakip : {0}".format(skorrakip)
    elif v == "kağıt":
        label3["text"] = v
        label4["text"] = "Kazanan : Siz"
        skorsiz = skorsiz+1
        label5["text"]="Siz : {0}".format(skorsiz)

def Again():
    global skorrakip
    global skorsiz
    skorrakip = 0
    skorsiz = 0
    label3["text"] = "Seçiyor..."
    label4["text"] = "Kazanan : "
    label5["text"] = "Siz : 0"
    label6["text"] = "Rakip : 0"

label1 = Label(text="Taş Kağıt Makas", bg=color, font="Arial 24")
label1.place(x=130, y=10)

label2 = Label(bg="Black", width=1000, height=1)
label2.place(x=0, y=225)

label3 = Label(text="Rakip", bg=color, font="Arial 24", fg="Yellow")
label3.place(x=200, y=60)

label3 = Label(text="Seçiyor...", bg=color, font="Arial 24", fg="#00FFE0")
label3.place(x=200, y=110)

label4 = Label(text="Kazanan : ", bg=color, font="Arial 24", fg="#36FF00")
label4.place(x=175, y=214)

label5 = Label(text="Siz : 0", bg=color, font="Arial 12", fg="blue")
label5.place(x=10, y=460)

label6 = Label(text="Rakip : 0", bg=color, font="Arial 12", fg="blue")
label6.place(x=420, y=460)

buton0 = Button(text="Tekar Başla", bg="white", fg="black", font="Arial 18", command=Again)
buton0.place(x=175, y=265)

buton1 = Button(text="Taş", bg="yellow", fg="black", font="Arial 32", command=Rock)
buton1.place(x=30, y=330)

buton2 = Button(text="Kağıt", bg="yellow", fg="black", font="Arial 32", command=Paper)
buton2.place(x=150, y=330)

buton3 = Button(text="Makas", bg="yellow", fg="black", font="Arial 32", command=Scissors)
buton3.place(x=300, y=330)

root.mainloop()


import datetime
import logging
import os
import pprint
import dateutil.parser
import datetime
import time
import re
import requests

import azure.functions as func

from azure.identity import DefaultAzureCredential
import azure.mgmt.resource as azr

## To run in development set the following environment variables:
#   AZURE_CLIENT_ID
#   AZURE_CLIENT_SECRET
#   AZURE_TENANT_ID

## Optionally supply :
#   subscriptions           Comma separated list of subscription IDs
#   max_rg_age              Max age of a RG that doesn't have an expiry date
#   datadog_api_key         Datadog API key for sending events
#

regex = re.compile(r'((?P<days>\d+?)d)?((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?')
defaultRgAge = "7d"

def main(mytimer: func.TimerRequest) -> None:
    maxRgAge = os.getenv("max_rg_age", defaultRgAge)

    datadog_event( {
      'alert_type': 'info',
      'source_type_name': 'AZURE',
      'text': "ci-clean starting",
      'title': 'ci-clean starting'
    })

    ## Default Azure SDK is very verbose..
    azLogger = logging.getLogger("azure")
    azLogger.setLevel(logging.WARN)

    ## Get creds from the environment or MSI
    credentials = DefaultAzureCredential()

    ## Get subscription list from environment, or use all subs in the tenant
    subscriptionIds = os.getenv("subscriptions")
    if subscriptionIds is None:
        logging.info("Querying for all subscription IDs")
        subscriptionIds = list_subscriptions(credentials)
    else:
        logging.info("Using provided list")
        subscriptionIds = [x.strip()  for x in subscriptionIds.split(",")]

    ## Iterate the subscriptions
    tasks = []
    for sub in subscriptionIds:
        logging.info("Cleaning subscription %s" % sub)

        ## Find RGs that we need to remove
        allRgs = list_resource_groups(credentials, sub)
        toClean = filter_resource_groups(allRgs, maxRgAge)

        for rg in toClean:
            task = clean_rg(credentials, sub, rg)
            if task:
                tasks.append(task)

    ## Wait for tasks to complete
    while len(tasks) > 0:
        time.sleep(10)
        tasks[:] = [x for x in tasks if not x.done()]
        logging.info("Still waiting for %d RG deletions", len(tasks))

    logging.info("Delete tasks have completed")

    datadog_event( {
      'alert_type': 'info',
      'source_type_name': 'AZURE',
      'text': "ci-clean complete",
      'title': 'ci-clean complete'
    })

def clean_rg(credentials, subscriptionId, rg):
    logging.info("Cleaning RG %s/%s" % (subscriptionId, rg))
    datadog_event( {
      'alert_type': 'info',
      'source_type_name': 'AZURE',
      'text': "Deleting resource group %s" % rg["Name"],
      'title': 'Azure RG Cleanup',
      'payload': rg,
      'tags': rg['Tags']
    })

    with azr.ResourceManagementClient(credentials, subscriptionId) as rg_client:
        try:
            return rg_client.resource_groups.begin_delete(rg["Name"])

        except Exception as e:
            logging.error("encountered: {0}".format(str(e)))

def filter_resource_groups(allRGs, maxRgAge):
    toClean = []

    for rg in allRGs:
        if is_rg_permenant(rg) == False  and  is_rg_expired(rg, maxRgAge):
                toClean.append(rg)

    return toClean

def is_rg_permenant(rg):
    if "durability" in rg["Tags"]:
        res = rg["Tags"]["durability"] == "permenant"
        logging.info("RG %s is%spermenant" % (rg["Name"], " " if res else " not "))
        return

    logging.info("RG %s does not have a durability tag" % rg["Name"])
    return False

def is_rg_expired(rg, maxRgAge):
    createdOn = None
    expiresOn = None

    maxDelta = parse_time(maxRgAge)
    now = datetime.datetime.now(datetime.timezone.utc)

    if "createdate" in rg["Tags"]:
        createdOn = dateutil.parser.parse(rg["Tags"]["createdate"])

    if "expiredate" in rg["Tags"]:
        expiresOn = dateutil.parser.parse(rg["Tags"]["expiredate"])

    if expiresOn != None:
        if now > expiresOn:
            logging.info("RG %s has expired" % rg["Name"])
            return True
        else:
            logging.info("RG %s has not yet expired" % rg["Name"])
            return False

    if createdOn != None:
        if now > (createdOn + maxDelta):
            logging.info("RG %s is older than max lifetime (%s)" % (rg["Name"], maxDelta))
            return True
        else:
            logging.info("RG %s is not yet older than max lifetime (%s)" % (rg["Name"], maxDelta))
            return False

    logging.warn("RG %s is missing 'expiredate' and 'createdate' tags, ignoring" % rg["Name"])

    return False

def process_rg_instance(group):
    """
    Get the relevant pieces of information from a ResourceGroup instance.
    """
    return {
        "Name": group.name,
        "Id": group.id,
        "Location": group.location,
        "Tags": group.tags,
        "Properties": group.properties.provisioning_state if group.properties and group.properties.provisioning_state else None
    }

def list_resource_groups(credentials, subscriptionId):
    list_of_resource_groups = []

    with azr.ResourceManagementClient(credentials, subscriptionId) as rg_client:
        try:
            for i in rg_client.resource_groups.list():
                list_of_resource_groups.append(process_rg_instance(i))

        except Exception as e:
            logging.error("encountered: {0}".format(str(e)))

    return list_of_resource_groups

def list_subscriptions(credentials):
    list_of_subscriptions = []

    with azr.SubscriptionClient(credentials) as s_client:
        try:
            for s in s_client.subscriptions.list():
                list_of_subscriptions.append(s.subscription_id)

        except Exception as e:
            logging.error("encountered: {0}".format(str(e)))

    return list_of_subscriptions

def parse_time(time_str):
    parts = regex.match(time_str)
    if not parts:
        return

    parts = parts.groupdict()
    time_params = {}

    for name, param in parts.items():
        if param:
            time_params[name] = int(param)

    return datetime.timedelta(**time_params)

def datadog_event(data):
    key = os.getenv("datadog_api_key", None)
    if not key:
        return

    url = "https://api.datadoghq.com/api/v1/events"
    headers = {
        'DD-API-KEY': key
    }

    resp = requests.post(url, json=data, headers=headers)
    logging.info("Datadog response: %s" % resp.content)


"""Support for Lektrico charging station switches."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Any

import lektricowifi

from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_FRIENDLY_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import LektricoDeviceDataUpdateCoordinator
from .const import DOMAIN

@dataclass
class LektricoSwitchEntityDescription(SwitchEntityDescription):
    """A class that describes the Lektrico switch entities."""

    @classmethod
    def get_is_on(cls, data: Any) -> int | None:
        """Return None."""
        return None

    @classmethod
    async def turn_on(cls, device: lektricowifi.Device, data: Any) -> bool | None:
        """Return None."""
        return None

    @classmethod
    async def turn_off(cls, device: lektricowifi.Device, data: Any) -> bool | None:
        """Return None."""
        return None

@dataclass
class RequireAuthSwitchEntityDescription(LektricoSwitchEntityDescription):
    """A class that describes the Lektrico RequireAuth Switch entity."""

    @classmethod
    def get_is_on(cls, data: Any) -> bool:
        """Get the RequireAuth."""
        return bool(data.require_auth)

    @classmethod
    async def turn_on(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Turn on the RequireAuth switch."""
        return bool(await device.set_auth(False))

    @classmethod
    async def turn_off(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Turn off the RequireAuth switch."""
        return bool(await device.set_auth(True))

@dataclass
class LockSwitchEntityDescription(LektricoSwitchEntityDescription):
    """A class that describes the Lektrico Lock / Unlock Switch entity."""

    @classmethod
    def get_is_on(cls, data: Any) -> bool:
        """Check if the reported state is LOCKED."""
        return str(data.charger_state) == "LOCKED"

    @classmethod
    async def turn_on(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Lock the charger."""
        return bool(await device.set_charger_locked(True))

    @classmethod
    async def turn_off(cls, device: lektricowifi.Device, data: Any) -> bool:
        """Unlock the charger."""
        return bool(await device.set_charger_locked(False))

SENSORS: tuple[LektricoSwitchEntityDescription, ...] = (
    RequireAuthSwitchEntityDescription(
        key="authentication",
        name="Authentication",
    ),
    LockSwitchEntityDescription(
        key="locked",
        name="Lock",
    ),
)

async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up Lektrico charger based on a config entry."""
    coordinator: LektricoDeviceDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

    async_add_entities(
        LektricoSwitch(
            description,
            coordinator,
            entry.data[CONF_FRIENDLY_NAME],
        )
        for description in SENSORS
    )

class LektricoSwitch(CoordinatorEntity, SwitchEntity):
    """The entity class for Lektrico charging stations switches."""

    entity_description: LektricoSwitchEntityDescription
    _attr_has_entity_name = True

    def __init__(
        self,
        description: LektricoSwitchEntityDescription,
        coordinator: LektricoDeviceDataUpdateCoordinator,
        friendly_name: str,
    ) -> None:
        """Initialize Lektrico charger."""
        super().__init__(coordinator)
        self.entity_description = description

        self._attr_unique_id = f"{coordinator.serial_number}_{description.key}"
        self._attr_device_info = DeviceInfo(
            identifiers={(DOMAIN, str(coordinator.serial_number))},
            model=f"{coordinator.device_type.upper()} {coordinator.serial_number} rev.{coordinator.board_revision}",
            name=friendly_name,
            manufacturer="Lektrico",
            sw_version=coordinator.data.fw_version,
        )

    @property
    def is_on(self) -> bool:
        """If the switch is currently on or off."""
        return bool(self.entity_description.get_is_on(self.coordinator.data))

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the switch on."""
        await self.entity_description.turn_on(
            self.coordinator.device, self.coordinator.data
        )
        # Refresh the coordinator because a switch changed a value.
        await self.coordinator.async_refresh()

    async def async_turn_off(self, **kwargs: Any) -> None:
        """Turn the switch off."""
        await self.entity_description.turn_off(
            self.coordinator.device, self.coordinator.data
        )
        # Refresh the coordinator because a switch changed a value.
        await self.coordinator.async_refresh()


from django.apps import apps
from django.core.management.base import BaseCommand, CommandParser
from impossible_travel.models import Alert, Config, Login, TaskSettings, User

class Command(BaseCommand):
    help = "Clear data on the models"

    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument("--model", nargs="?", type=str, help="Model to clear")
        return super().add_arguments(parser)

    def handle(self, *args, **options):
        if options["model"]:
            if options["model"] in ["Config", "config"]:
                choice = input(self.stdout.write("Are you sure you want to delete the Configurations model? [y/N]"))
                if choice in ["y", "Y"]:
                    Config.objects.all().delete()
                    self.stdout.write(self.style.SUCCESS("Config model is correctly emptied"))
                else:
                    self.stdout.write("Config model isn't emptied")
            else:
                try:
                    Model = apps.get_model("impossible_travel", options["model"].capitalize())
                    Model.objects.all().delete()
                    self.stdout.write(self.style.SUCCESS(f"{Model} model is correctly emptied"))
                except LookupError:
                    self.stdout.write(self.style.ERROR(f"{options['model']} model doesn't exist"))
        else:
            Alert.objects.all().delete()
            Login.objects.all().delete()
            User.objects.all().delete()
            TaskSettings.objects.all().delete()
            self.stdout.write(self.style.SUCCESS("All the models have been emptied, expect the Config model"))


SYMBOLS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

message = input("Enter the message you want to hack: ")

for key in range(len(SYMBOLS)):
    translated = ''
    for symbol in message:
        if symbol in SYMBOLS:
            num = SYMBOLS.find(symbol)
            num = (num - key) % len(SYMBOLS)
            translated = translated + SYMBOLS[num]
        else:
            translated = translated + symbol
    print(f"{key}: {translated}")


from processors.awards import AwardProcessor,Column,PLAYER_COL
from models import model_mgr
from models.vehicles import STATION

class Processor(AwardProcessor):
    '''
    Overview
    This processor keeps track of kills using turrets (ground mounted).

    Implementation
	Cache kill events where the attacker is using a turret.

    Notes
	None.
    '''

    def __init__(self):
        AwardProcessor.__init__(self, 'Tourette Syndrome',
                'Most Kills with Turrets',
                [PLAYER_COL, Column('Kills', Column.NUMBER, Column.DESC)])

    def on_kill(self, e):

        # Ignore suicides and team kills
        if not e.valid_kill:
            return

        attack_vehicle = model_mgr.get_vehicle(e.attacker.vehicle_id)
        if attack_vehicle.group == STATION:
            self.results[e.attacker] += 1


blocks = (
    ("1111"),
    ("11",
     "11"),
    ("10",
     "10",
     "11"),
    ("10",
     "11",
     "01"),
    ("111",
     "010")
)
def mirror(b):
    ans = []
    for i in range(len(b)):
        ans.append(b[i][::-1])
    return ans
def rotate(b):
    ans = ['']*len(b[0])
    for j in range(len(b[0])):
        for i in range(len(b)-1, -1, -1):
            ans[j] += b[i][j]
    return ans
def calc(a, b, x, y):
    n = len(a)
    m = len(a[0])
    s = 0
    for i in range(len(b)):
        for j in range(len(b[0])):
            if b[i][j] == '0':
                continue
            nx,ny = x+i, y+j
            if 0 <= nx < n and 0 <= ny < m:
                s += a[nx][ny]
            else:
                return -1
    return s

n,m = map(int,input().split())
a = [list(map(int,input().split())) for _ in range(n)]
ans = 0
for i in range(n):
    for j in range(m):
        for block in blocks:
            b = block[::]
            for mir in range(2):
                for rot in range(4):
                    cur = calc(a, b, i, j)
                    if cur != -1 and ans < cur:
                        ans = cur
                    b = rotate(b)
                b = mirror(b)
print(ans)

코딩테스트_기초/03_부르트포스/05_테트리미노3.py


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        solution_head = None
        solution_current_node = None
        solution_prev_node = None
        carryover = 0

        while True:
            # If both are None, break, we're done
            if l1 is None and l2 is None and not carryover:
                break

            l1_val = l1.val if l1 else 0
            l2_val = l2.val if l2 else 0

            node_sum = l1_val + l2_val + carryover
            carryover = node_sum // 10
            node_sum = node_sum % 10
            solution_current_node = ListNode(val=node_sum)

            if solution_prev_node:
                solution_prev_node.next = solution_current_node
            else:
                solution_head = solution_current_node

            solution_prev_node = solution_current_node

            # Check if l1 and l2 are not None before iterating to next node
            if l1:
                l1 = l1.next

            if l2:
                l2 = l2.next

        return solution_head


from blockClass import *
import time
class Conv(Block): # nn.conv2d
    def __init__(self, layer, parents, index, args = {}):
        '''
            "args": {
            "inputSize": [N, C_in, H, W],
            "outputSize": [N, C_out, H_out, W_out], # will be calculated
            "outputChannels": int,
            "kernelSize": [height, width],
            "stride": [height, width],
            "padding": [height, width] or str: "same", "valid",
            "dilation": [height, width],
            "groups": int,
            "bias": bool,
            "paddingMode": str, 'zeros', 'reflect', 'replicate' or 'circular'
        }
        '''
        super().__init__(layer, parents, index, args)
        if(isinstance(self.padding, str)):
            if(self.padding == "same"):
                self.outputSize = copy.copy(self.inputSize)
                self.outputSize[1] = self.outputChannels

                # work around for onnx export problem, https://github.com/pytorch/pytorch/issues/68880
                # solve is from tensorflow. https://discuss.pytorch.org/t/same-padding-equivalent-in-pytorch/85121/4
                if(self.inputSize[2] % self.stride[0] == 0):
                    padAlongHeight = max(self.kernelSize[0] - self.stride[0], 0)
                else:
                    padAlongHeight = max(self.kernelSize[0] - (self.inputSize[2] % self.stride[0]), 0)
                if(self.inputSize[3] % self.stride[1] == 0):
                    padAlongWidth = max(self.kernelSize[1] - self.stride[1], 0)
                else:
                    padAlongWidth = max(self.kernelSize[1] - (self.inputSize[3] % self.stride[1]), 0)
                self.padding = [padAlongHeight, padAlongWidth]
            elif(self.padding == "valid"):
                self.padding = [0, 0] # no padding
        if(isinstance(self.padding, list)):
            self.outputHeight = (self.inputSize[2] + (2 * self.padding[0]) - self.dilation[0] * (self.kernelSize[0] - 1) - 1 + self.stride[0]) // self.stride[0]
            self.outputWidth = (self.inputSize[3] + (2 * self.padding[1]) - self.dilation[1] * (self.kernelSize[1] - 1) - 1 + self.stride[1]) // self.stride[1]
            self.outputSize = [self.inputSize[0], self.outputChannels, self.outputHeight, self.outputWidth]
        #self.net = nn.Conv2d(self.inputSize[1], self.outputChannels, self.kernelSize, self.stride, self.padding,
        #                           self.dilation, self.groups, self.bias, self.paddingMode)
        if(isinstance(self.padding, str) and self.padding == "same"):
            assert self.outputSize == self.inputSize
        # I set to 0 now will error if pad = "same"
        self.net = nn.Conv2d(self.inputSize[1], self.outputChannels, self.kernelSize, self.stride, self.padding,
                                    self.dilation, self.groups, self.bias)
        # 這到底沙小扣
        #別人也是這樣 哈哈
    def forward(self, x):
        #print(self.index, self.inputSize, list(x.shape))
        out = self.net(x)
        #print(self.index, self.outputSize, list(out.shape))
        #assert(self.outputSize == list(out.shape))
        return out
class ConvDummy(Block): # nn.conv2d, slow!
    def __init__(self, layer, parents, index, args = {}):
        super().__init__(layer, parents, index, args)
        #self.net = nn.Conv2d(self.inputSize[1], self.outputChannels, self.kernelSize, self.stride, self.padding,
        #                     self.dilation, self.groups, self.bias, self.paddingMode)
        # Interestingly, onnx does not support padding lol
        self.net = nn.Conv2d(self.inputSize[1], self.outputChannels, self.kernelSize)
        dummy = torch.rand(self.inputSize)
        dummyOutput = self.net(dummy)
        self.outputSize = list(dummyOutput.shape)
        # 這到底沙小扣
        #別人也是這樣 哈哈
    def forward(self, x):
        return self.net(x)

class Pooling(Block):
    def __init__(self, layer, parents, index, args = {}):
        '''
            "args": {
            "inputSize": [N, C_in, H, W],
            "outputSize": [N, C_out, H_out, W_out], # will be calculated
            "mode": str, "max", "avg", "adaptiveMax", "adaptiveAvg"
            "outputSizeAdapt": [H_out, W_out], [0, 0] if mode isn't "adaptiveMax" or "adaptiveAvg"
            "kernelSize": [height, width],
            "stride": [height, width],
            "padding": [height, width], no string!
            "dilation": [height, width], [1, 1] if mode isn't max
        }
        '''
        super().__init__(layer, parents, index, args)
        # onnx does not support adaptive.... find other way to global pooling....
        if self.mode == "adaptiveMax":
            self.net = nn.AdaptiveMaxPool2d(self.outputSizeAdapt)
            self.outputSize = copy.copy(self.inputSize)
            self.outputSize[-2:] = self.outputSizeAdapt
        elif self.mode == "adaptiveAvg":
            self.net = nn.AdaptiveAvgPool2d(self.outputSizeAdapt)
            self.outputSize = copy.copy(self.inputSize)
            self.outputSize[-2:] = self.outputSizeAdapt
        else:
            if(isinstance(self.padding, list)):
                self.outputHeight = (self.inputSize[2] + (2 * self.padding[0]) - self.dilation[0] * (self.kernelSize[0] - 1) - 1 + self.stride[0]) // self.stride[0]
                self.outputWidth = (self.inputSize[3] + (2 * self.padding[1]) - self.dilation[1] * (self.kernelSize[1] - 1) - 1 + self.stride[1]) // self.stride[1]
                self.outputSize = [self.inputSize[0], self.inputSize[1], self.outputHeight, self.outputWidth]
            if self.mode == "max":
                self.net = nn.MaxPool2d(self.kernelSize, self.stride, self.padding, self.dilation)
            elif self.mode == "avg":
                # avg pool doens't have dilation for some reason
                self.net = nn.AvgPool2d(self.kernelSize, self.stride, self.padding)
    def forward(self, x):
        #print(self.index, list(x.shape), self.inputSize)
        out = self.net(x)
        #print(self.index, self.outputSize, list(out.shape))
        return self.net(x)
if __name__ == "__main__":
    # test speed, or maybe put in another place zzz
    start = time.time()
    times = 100
    print("--- Conv {} times ---".format(times))
    for i in range(times):
        con = Conv(1, 1, 1, {
                    "inputSize": [32, 10, 32, 32],
                    "outputSize": [],
                    "outputChannels": 100,
                    "kernelSize": [3, 3],
                    "stride": [1, 1],
                    "padding": "same",
                    "dilation": [1, 1],
                    "groups": 1,
                    "bias": True,
                    "paddingMode": "zeros"
                }
                )
    print("--- Calculate took %s seconds ---" % (time.time() - start))
    start = time.time()
    for i in range(times):
        conDummy = ConvDummy(1, 1, 1, {
                    "inputSize": [32, 10, 32, 32],
                    "outputSize": [],
                    "outputChannels": 100,
                    "kernelSize": [3, 3],
                    "stride": [1, 1],
                    "padding": "same",
                    "dilation": [1, 1],
                    "groups": 1,
                    "bias": True,
                    "paddingMode": "zeros"
                })
    print("--- Dummy took %s seconds ---" % (time.time() - start))


import logging

from rtctools.simulation.csv_mixin import CSVMixin
from rtctools.simulation.simulation_problem import SimulationProblem
from rtctools.util import run_simulation_problem

logger = logging.getLogger("rtctools")

class Example(CSVMixin, SimulationProblem):
    """
    A basic example for introducing users to RTC-Tools 2 Simulation
    """

    def initialize(self):
        self.set_var('P_control', 0.0)
        super().initialize()

    # Min and Max flow rate that the storage is capable of releasing
    min_release, max_release = 0.0, 8.0  # m^3/s

    # Here is an example of overriding the update() method to show how control
    # can be build into the python script
    def update(self, dt):

        # Get the time step
        if dt < 0:
            dt = self.get_time_step()

        # Get relevant model variables
        volume = self.get_var('storage.V')
        target = self.get_var('storage_V_target')

        # Calucate error in storage.V
        error = target - volume

        # Calculate the desired control
        control = -error / dt

        # Get the closest feasible setting.
        bounded_control = min(max(control, self.min_release), self.max_release)

        # Set the control variable as the control for the next step of the simulation
        self.set_var('P_control', bounded_control)

        # Call the super class so that everything else continues as normal
        super().update(dt)

# Run
run_simulation_problem(Example, log_level=logging.DEBUG)


# 20220130 - Python - While Loop
# 05 - Account Balance - judge: https://judge.softuni.org/Contests/Compete/Index/2419#4

# user input
deposit = input()

# calculations & results
balance = 0

while deposit != "NoMoreMoney":
    deposit = float(deposit)

    if deposit < 0:
        print("Invalid operation!")
        print(f"Total: {balance:.2f}")
        quit()

    balance += deposit
    print(f"Increase: {deposit:.2f}")
    deposit = input()

if deposit == "NoMoreMoney":
    print(f"Total: {balance:.2f}")


# 1. Imported Modules
# -------------------
import openpyxl

def ImportGameExcel(gameNumber, file_name):
    wb = openpyxl.load_workbook(file_name)
    ws = wb.active
    list1 = []
    number = None
    for row in ws.rows:
        if row[2].value == gameNumber:
            for cell in row:
                if cell.row not in list1:
                    list1.append((cell.row))
                    number = list1[0]
    if number is not None:
        start_row = number-3
        max_row1 = start_row + 13
        list2 = []
        list3 = []
        for i in range(start_row, max_row1):

            cell_obj1 = ws.cell(row = i, column = 2)
            cell_obj2 = ws.cell(row = i, column = 3)
            if cell_obj1.value == None:
                break
            list2.append(cell_obj1.value)
            list3.append(cell_obj2.value)
        res = {}
        for key in list2:
            for value in list3:
                res[key] = value
                list3.remove(value)
                break
        whiteMoves = []
        blackMoves = []
        for i in range(max_row1, ws.max_row):
            cell_obj1 = ws.cell(row = i, column = 3)
            cell_obj2 = ws.cell(row = i, column = 4)
            if cell_obj1.value == None or cell_obj2.value == None:
                break
            whiteMoves.append(cell_obj1.value)
            blackMoves.append(cell_obj2.value)
        allMoves = [None]*(len(whiteMoves)+len(blackMoves))
        allMoves[::2] = whiteMoves
        allMoves[1::2] = blackMoves
        if 'White' in allMoves:
            allMoves.remove('White')
        if 'Black' in allMoves:
            allMoves.remove('Black')
        list4 = []
        list4.append(res)
        list4.append(allMoves)
        return list4
    else:
        print('Game not found')

def ExportGameExcel(game, file_name):
    wb = openpyxl.load_workbook(file_name)
    ws = wb.active

    gameMeta = game[0]
    gameMoves = game[1]
    gameNumber = gameMeta['Round']
    gameNumbers = [row[2].value for row in ws.rows if row[2].value is not None]

    if gameNumber in gameNumbers:
        print(f"Round '{gameNumber}' already exists in the file")
    else:
        start_row = ws.max_row + 2
        for i, (key, value) in enumerate(gameMeta.items()):
            ws.cell(row=start_row + i, column=2).value = key
            ws.cell(row=start_row + i, column=3).value = value

        # Determine the row number to start writing at (one row after the last row with data)
        start_row = ws.max_row + 2
        ws.cell(row=start_row, column=2).value = 'Turn'
        ws.cell(row=start_row, column=3).value = 'white'
        ws.cell(row=start_row, column=4).value = 'Black'
        start_row = ws.max_row + 1
        # Loop through the list of values and write them to the Excel file
        for i in range(0, len(gameMoves), 2):
            ws.cell(row=start_row, column=2).value = i//2 + 1
            ws.cell(row=start_row, column=3).value = gameMoves[i]
            ws.cell(row=start_row, column=4).value = gameMoves[i+1] if i+1 < len(gameMoves) else ''
            # Increment the row number for the next iteration
            start_row += 1
        # Save the changes to the Excel file
        wb.save(file_name)


# coding=utf-8
import torch.utils.data as data
import sys
sys.path.append("..")
from imageio import imread
from path import Path
import random
import cv2
import time
from utils.pose_transfer import *

train_set = ['01', '02', '04', '05', '06', '08']
test_set = ['03', '07', '09']

def load_as_float(path, width, height):
    return cv2.resize(imread(path), (width, height)).astype(np.float32)

def pose12to16(mat):
    if mat.ndim == 1:
        mat = mat.reshape(3, -1)
        mat = np.vstack([mat, [0, 0, 0, 1]])
        return mat
    else:
        mat = np.vstack([mat, [0, 0, 0, 1]])
        return mat

def mat_to_6dof(mat):
    if mat.shape[0] == 3:
        mat = pose12to16(mat)
    else:
        translation = list(mat[:3,3])
        rotation = list(euler_from_matrix(mat))
        pose = rotation + translation
    return pose

def absolute2Relative(seqGT):
    sequence_length = len(seqGT)
    seqGT_mat = [pose12to16(item) for item in seqGT]
    seqGT_Rela_mat = []
    seqGT_Rela_mat.append(seqGT_mat[0])
    seqGT_Rela_Eul = []
    seqGT_Rela_Eul.append(mat_to_6dof(seqGT_mat[0]))
    for i in range(1, sequence_length):
        seqGT_Rela_Eul.append(mat_to_6dof(np.linalg.inv(seqGT_mat[i-1]) @ seqGT_mat[i]))
    seqGT_Rela_Eul = np.array(seqGT_Rela_Eul)

    return seqGT_Rela_Eul

class DataSequence(data.Dataset):

    def __init__(self,
                 root,
                 seed=None,
                 train=True,
                 sequence_length=3,
                 imu_range=[0, 0],
                 transform=None,
                 shuffle=True,
                 scene='default',
                 image_width=640,
                 image_height=480):
        np.random.seed(seed)
        random.seed(seed)
        self.root = Path(root)
        if scene == 'default':
            scene_list = train_set if train == True else test_set
        else:
            scene_list = scene
        self.scenes = [self.root/folder for folder in scene_list]
        self.transform = transform
        self.imu_range = imu_range
        self.shuffle = shuffle
        self.image_height = image_height
        self.image_width = image_width
        self.crawl_folders(sequence_length)

    def crawl_folders(self, sequence_length):
        sequence_set = []
        demi_length = (sequence_length-1)//2
        shifts = list(range(-demi_length, demi_length+1))

        for scene in self.scenes:
            imgs = sorted((scene/'left_256').files('*.jpg'))
            intrinsics = np.genfromtxt(scene/'left_256'/'cam.txt').astype(np.float32).reshape((3, 3))
            intrinsics[0, :] *= (self.image_width/832)
            intrinsics[1, :] *= (self.image_height/256)
            try:
                imus = np.load(scene/'imu/sampled_imu_{}_{}.npy'.format(self.imu_range[0],self.imu_range[1])).astype(np.float32)
            except EOFError as e:
                print("No npy files 'sampled_imu_{}_{}.npy' as commmand specified".format(self.imu_range[0],self.imu_range[1]))
            for i in range(demi_length, len(imgs)-demi_length):
                sample = {'imgs': [], 'imus': [], 'intrinsics': intrinsics}
                # put the target in the middle
                for j in shifts:
                    sample['imgs'].append(imgs[i+j])
                    sample['imus'].append(imus[i+j])
                sequence_set.append(sample)

        if self.shuffle:
            random.shuffle(sequence_set)
        self.samples = sequence_set

    def __getitem__(self, index):
        sample = self.samples[index]
        imgs = [load_as_float(img, self.image_width, self.image_height) for img in sample['imgs']]
        if self.transform is not None:
            imgs, imus, intrinsics = self.transform(imgs,  np.copy(sample['imus']),  np.copy(sample['intrinsics']))
        else:
            intrinsics = np.copy(sample['intrinsics'])
            imus = np.copy(sample['imus'])
        return imgs, imus, intrinsics, np.linalg.inv(intrinsics)

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

if __name__ == "__main__":
    start_time = time.time()
    D = DataSequence(
        sequence_length=5,
        root='/data3/Datasets/weip/Malaga/Malaga_Down/',
        imu_range=[-10, 0],
        shuffle=False,
        image_width=832,
        image_height=256,
        train=True,
    )
    img, imu, intr, inr_inv = D[390]
    print('time used {}'.format(time.time()-start_time))