import argparse
import os
import time
import torch
from torch import nn
import torch.nn.parallel
import torch.optim as optim
from einops import rearrange

from src.evaluation.test_episode_io import load_episode, get_saved_episode_dir

import sys
path = os.path.abspath('../few-shot-video-classification')  # include the tsl repository
sys.path.append(path)
from tsl_fsv import weights_init, CLASSIFIER
from utils import setup_logger, AverageMeter, count_acc, euclidean_metric

""" The methods are adapted from
https://github.com/xianyongqin/few-shot-video-classification/tsl_fsv r2+1d precomputed episodes.
"""

def parse_command_line():
    """ Parses the command line.

    :return: command line parameters
    """
    parser = argparse.ArgumentParser()

    # GENERAL
    parser.add_argument(
        '--manual_seed', default=1, type=int, help='Manually set random seed')
    parser.add_argument('--dataset', type=str)
    parser.add_argument(
        '--batch_size', default=32, type=int, help='Batch size for computing the embeddings')
    parser.add_argument(
        '--n_threads', default=4, type=int, help='Number of threads for multi-thread loading')
    parser.add_argument('--shot', type=int, default=1)
    parser.add_argument('--query', type=int, default=5)
    parser.add_argument('--test_way', type=int, default=5)
    parser.add_argument('--nepisode', type=int, default=500)
    parser.add_argument('--nepoch', default=5, type=int, help='Number of total epochs to run')
    parser.add_argument(
        '--lr', default=0.001, type=float,
        help='Initial learning rate (divided by 10 while training by lr scheduler)')
    parser.add_argument('--emb_dim', default=512, type=int, help='Temporal duration of inputs')
    parser.add_argument(
        '--n_val_samples', default=3, type=int, help='Number of validation clips for each video')
    parser.add_argument(
        '--result_dir', type=str, default=None, help='root directory where to save the results.')

    cmd_args = parser.parse_args()
    return cmd_args

def main_classifier_based_from_episodes():
    """ Runs the classifier-based approach on pre-saved episodes. First, loads episodes.
    For each episode, train a new classifier using the support examples, and
    evaluate the query examples with this classifier.
    """
    main_start_time = time.time()
    cmd_args = parse_command_line()

    if not os.path.exists(cmd_args.result_dir):
        os.makedirs(cmd_args.result_dir)

    # Setup logging system
    logger = setup_logger(
        "validation",
        cmd_args.result_dir,
        0,
        f'results_{cmd_args.manual_seed}_{cmd_args.shot}shots.txt'
    )
    logger.debug(cmd_args)

    torch.backends.cudnn.benchmark = True
    torch.manual_seed(cmd_args.manual_seed)

    episode_time = AverageMeter()
    accuracies = AverageMeter()
    full_episode_time = AverageMeter()

    start_sample = time.time()
    for i_episode in range(1, cmd_args.nepisode + 1):
        start_time = time.time()
        end_time = time.time()
        acc = meta_test_episode(cmd_args, i_episode)
        accuracies.update(acc)
        episode_time.update(time.time() - end_time)
        full_episode_time.update(time.time() - start_time)

        logger.info('Episode: {0}\t'
              'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
              'Full Time {full_time.val:.3f} ({full_time.avg:.3f})\t'
              'Acc {acc.val:.3f} ({acc.avg:.3f})'.format(
                  i_episode,
                  batch_time=episode_time,
                  full_time=full_episode_time,
                  acc=accuracies))
        # raise Exception("debug")

    main_end_time = time.time()
    print(f"total time  {main_end_time - main_start_time}")
    print(f"time only episodes {main_end_time - start_sample}")

def meta_test_episode(cmd_args, episode_id):
    """ Trains a classifier on the support examples.

    :param cmd_args: command line parameters
    :param episode_id: episode id between 1 and 10000
    :return: accuracy value
    """
    # initialize a new classifier
    classifier = CLASSIFIER(cmd_args.emb_dim, cmd_args.test_way)
    classifier.apply(weights_init)
    criterion = nn.NLLLoss()
    classifier.cuda()
    criterion.cuda()
    optimizer = optim.Adam(classifier.parameters(), lr=cmd_args.lr, betas=(0.5, 0.999))

    # loads the episode
    support_features, support_labels, target_features, target_labels = load_episode_and_format(
        cmd_args, episode_id)

    # trains the classifier
    for _ in range(cmd_args.nepoch):
        train_epoch_from_features(
            classifier, criterion, optimizer, support_features, support_labels)

    # evaluates
    acc = val_epoch_from_features(classifier, target_features, target_labels, cmd_args)
    return acc

def load_episode_and_format(cmd_args, episode_id):
    """ Trains a classifier on the support examples.

    :param cmd_args: command line parameters
    :param episode_id: episode id between 1 and 10000
    :return: R2+1D features of the support examples
    :return: labels of the support examples
    :return: R2+1D features of the target/query examples
    :return: labels of the target/query examples
    """
    cmd_args.test_episode_dir = "/mnt/personal/bertrjul/debug_github/episodes/"

    saved_episodes_dir = get_saved_episode_dir(
        cmd_args.test_episode_dir, cmd_args.dataset, cmd_args.test_way, cmd_args.shot)

    support_features, support_labels, target_features, target_labels = load_episode(
        saved_episodes_dir, episode_id)

    support_features = rearrange(support_features, "a b c -> (a b) c")
    support_labels = support_labels.type(torch.LongTensor)
    support_labels = support_labels.to(support_features.device)
    support_labels = torch.repeat_interleave(support_labels, cmd_args.n_val_samples)

    target_features = rearrange(target_features, "a b c -> (a b) c")
    target_labels = target_labels.type(torch.LongTensor)
    target_labels = target_labels.to(target_features.device)
    return support_features, support_labels, target_features, target_labels

def train_epoch_from_features(classifier, criterion, optimizer, support_features, support_labels):
    """ Trains a classifier on the support examples.

    :param classifier: classifier to be trained
    :param criterion:
    :param optimizer:
    :param support_features: R2+1D features of the support examples
    :param support_labels: labels of the support examples
    """
    classifier.train()
    optimizer.zero_grad()
    output = classifier(support_features)
    loss = criterion(output, support_labels)
    loss.backward()
    optimizer.step()

def val_epoch_from_features(classifier, target_features, target_labels, args):
    """Classifies the target/query examples using the classifier.

    :param classifier: classifier
    :param target_features: R2+1D features of the target/query examples
    :param target_labels: labels of the target/query examples
    :param args: command line parameters
    :return: accuracy value
    """
    classifier.eval()
    with torch.no_grad():
        clip_logits = torch.exp(classifier(target_features))
        logits = clip_logits.reshape(args.query * args.test_way, args.n_val_samples, -1).mean(dim=1)
        acc, pred = count_acc(logits, target_labels)
    return acc

if __name__ == '__main__':
    torch.multiprocessing.set_start_method('spawn')
    main_classifier_based_from_episodes()


T = int(input())
for testcase in range(1,T+1):
    charge = int(input())
    money = [50000,10000,5000,1000,500,100,50,10]
    index = 0
    lst = []
    while index <= 7:
        cnt = charge//money[index]
        lst.append(cnt)
        charge-= cnt * money[index]
        index += 1
    result = ' '.join(map(str,lst))
    print(f'#{testcase}')
    print(result)


import faker
import random

categories = ["junior", "senior", "retired", "trainee"]

f = faker.Faker()

for i in range(10):
    r = random.randint(0, 3)
    print(f.last_name(), f.first_name(), f.email(), f.job(),
          f.credit_card_number(), categories[r], f.date())

for i in range(10):
    print(f.isbn10(), f.sentence(), f.last_name(), f.first_name())


def solution(s):
    stack = []

    for i in range(len(s)):
        if len(stack) == 0: # stack이 비어있으면, 문자열 넣어줘
            stack.append(s[i])

        else: # stack이 비어있지 않으면, 확인해줘야겠지
            if stack[-1] == s[i]: # stack 맨 위에 있는 알파벳이랑 지금 넣으려는 애랑 같으면
                stack.pop() # pop 해주고 넘어가
                continue
            else:
                stack.append(s[i])

    # stack이 비어있으면 성공, 아니면 실패
    return 1 if len(stack) == 0 else 0

프로그래머스/lv2/12973. 짝지어 제거하기/짝지어 제거하기.py


import time

from selenium.webdriver.common.action_chains import ActionChains

from selenium.webdriver.common.by import By

class JobPost:
    def __init__(self, driver):
        self.driver = driver
        self.good_job = {}

    def loop_two_window(self):

        count = 0

        count_try = 60

        while True:

            count += 1

            if count > count_try:
                print(f'Не открылось окно')
                return False

            try:
                count_windows = len(self.driver.window_handles)

                if count_windows > 1:
                    return True

                time.sleep(1)

                continue
            except:
                continue

    def get_rows(self):
        _rows = self.driver.find_elements(by=By.XPATH,
                                          value=f"//*[contains(@class, 'Overlay-wrapper')]//*[contains(@id, 'task')]")

        return _rows

    def loop_get_rows(self):

        count = 0

        count_try = 5

        while True:

            count += 1

            if count > count_try:
                print(f'Не смог получить строчки')
                return False

            try:
                _rows = self.get_rows()

                if _rows != []:
                    return _rows

                time.sleep(2)

                continue
            except:
                continue

    def click_look(self):
        try:
            self.driver.find_elements(by=By.XPATH,
                                      value=f"//*[contains(@class, 'contextContainer')]//button")[0].click()
        except:
            return False

        return True

    def click_show_rows(self):

        count = 0

        count_try = 60

        while True:

            count += 1

            if count > count_try:
                print(f'Не смог получить строчки')
                return False

            try:
                self.driver.find_elements(by=By.XPATH,
                                          value=f"//*[contains(@class, 'infoWrapper')]//button")[0].click()

                return True
            except:
                time.sleep(1)
                continue

    def show_row(self, row):

        try:
            elem_button = row.find_element(by=By.XPATH,
                                           value=f".//button")
        except:
            return False

        try:
            elem_button.click()
        except:
            pass

        try:
            ActionChains(self.driver).move_to_element(elem_button).perform()
        except:
            pass

        time.sleep(2)

        return True

    def get_keys_text_by_row(self, row):
        try:
            keys_ = row.find_element(by=By.XPATH,
                                     value=f".//*[contains(@class, 'TaskAnswerView-text')]").text
        except:
            return ''

        return keys_

    def get_value_by_radiobox(self, row):
        try:
            elements = row.find_element(by=By.XPATH,
                                        value=f".//span[contains(@class, 'Mui-checked')]//following-sibling::label").text
        except:
            return ''

        return elements

    def get_value_by_bonus(self, row):
        try:
            elements = row.find_element(by=By.XPATH,
                                        value=f".//*[contains(@class, 'MuiOutlinedInput')]"
                                              f"/input").get_attribute(
                'value')

        except:
            return ''

        return elements

    def get_value_by_show_rows(self, row):
        try:
            elements = row.find_element(by=By.XPATH,
                                        value=f".//*[contains(@class, 'MuiOutlinedInput')]"
                                              f"//*[contains(@class, 'MuiTypography')]").text

        except:
            return ''

        return elements

    def get_value_by_obe_to_one(self, row):
        try:
            elem_button = row.find_elements(by=By.XPATH,
                                            value=f".//*[contains(@class, 'MuiPaper-elevation')]")

            ActionChains(self.driver).move_to_element(elem_button[-1]).perform()

        except:
            return ''

        return row.screenshot_as_base64

    def get_type_row(self, row):
        try:
            elements = row.find_element(by=By.XPATH,
                                        value=f".//p[contains(@class, 'MuiTypography')]").text
        except:
            return ""

        return elements

    def get_response_row(self, row):
        # TODO функция определения типа ответа
        type_row = self.get_type_row(row)

        if type_row == 'Одиночный выбор':
            value = self.get_value_by_radiobox(row)
        elif type_row == 'Выпадающий список':
            value = self.get_value_by_show_rows(row)
        elif type_row == 'Один к одному':
            value = self.get_value_by_obe_to_one(row)
        elif type_row == 'Ввод числа':
            value = self.get_value_by_bonus(row)
        elif type_row == 'Одиночный ввод':
            value = self.get_value_by_bonus(row)
        else:
            # print(f'Не задан шаблон работы с типом строки: "{type_row}" - сохраняю как картинку')
            value = self.get_value_by_obe_to_one(row)

        return value

    def iter_rows(self, list_rows):

        for count, row in enumerate(list_rows):
            res_show = self.show_row(row)

            if not res_show:
                print(f'Строка {count + 1} не раскрылась')
                continue

            _keys = self.get_keys_text_by_row(row)

            _value = self.get_response_row(row)

            if _value == '':
                continue

            self.good_job[_keys] = _value

        return True

    def start_job_post(self, _req):

        print(f'Зашёл в материал по запросу "{_req}"')

        res_click = self.click_look()

        res_loop = self.loop_two_window()

        if not res_click:
            return False

        self.driver.switch_to.window(self.driver.window_handles[1])

        res_click = self.click_show_rows()

        list_rows = self.loop_get_rows()

        if not list_rows:
            return False

        print(f'Обрабатываю строчки с "{_req}"')

        res_iter = self.iter_rows(list_rows)

        self.driver.close()

        self.driver.switch_to.window(self.driver.window_handles[0])

        return self.good_job


#Importing the necessary library
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
import reverse_geocoder as rg
import matplotlib.pyplot as plt

def main():

    app()

def app():
    # Importing the files
    path1 = "C:/Users/Moise/Documents/Data visualization/My time on earth/Data/map_data.csv"

    # Creating the DataFrames
    df1 = pd.read_csv(path1)

    st.title("My activity on land")

    # Controls How the data is displayed
    def display_preference(df):
        st.sidebar.title('Map Data')
        choice1 = st.sidebar.selectbox("Choose a year", [2017, 2018])
        df = df.loc[df['year'] == choice1]
        choice2 = st.sidebar.selectbox("Choose a month", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
        if(choice2):
            df = df.loc[df['month'] == choice2]

        if((choice1 == 2017) and (choice2 < 10)):
            st.error("The Map data starts in October of 2017.")
        elif((choice1 == 2018) and (choice2 > 5)):
            st.error("The data ends in May.")
        else:
            display_3D_Map(df, choice2)
            display_hist(df)
            select_date(df)
            trajet(df)

    # Display a 3D map for a given date
    def display_3D_Map(df, month):
        st.title(f"3D map in {current_month(month)}")
        st.pydeck_chart(pdk.Deck(
     map_style='mapbox://styles/mapbox/light-v9',
     initial_view_state=pdk.ViewState(
         latitude= 48.85,#default lon and lat
         longitude= 2.34,
         zoom=11,
         pitch=50,
     ),
     layers=[
         pdk.Layer(
            'HexagonLayer',
            data=df,
            get_position='[longitude, latitude]',
            radius=200,
            elevation_scale=10,
            elevation_range=[0, 1000],
            pickable=True,
            extruded=True,
         ),
         pdk.Layer(
             'ScatterplotLayer',
             data=df,
             get_position='[longitude, latitude]',
             get_color='[200, 30, 0, 160]',
             get_radius=200,
         ),
     ],
 ))

    # Display an histogram
    def display_hist(df):
        fig, ax = plt.subplots()
        ax.hist(df['day'], bins= 30, rwidth= 0.7)
        plt.xlabel('Days of the month')
        plt.ylabel('Frequency of position')
        st.pyplot(fig)

    # Display a position for a certain date IIII I could use/modify this function to plot mes trajets
    def select_date(df):
        st.title("My location at a precise time.")
        my_datetime = st.select_slider("Choose a time",df['time'])
        df = df.loc[df['time'] == my_datetime]
        #print(df['time'])
        for a, b in zip(df['latitude'], df['longitude']):
            #print(a, b)
            place = reverseGeocode((a, b))
            st.title(place)
            map = pd.DataFrame(
            np.array([[a,b]]),
            columns=['lat', 'lon'])
            st.map(map)
            break
    # display my positions during a time interval
    def trajet(df):
        st.title("My timeline.")
        my_datetime1 = st.select_slider("Choose a starting time",df['time'])
        my_datetime2 = st.select_slider("Choose an ending time",df['time'])
        df = df.loc[(df['time'] > my_datetime1) & (df['time'] < my_datetime2)]
        lon = []
        lat = []
        for a, b in zip(df['latitude'], df['longitude']):
            lat.append(a)
            lon.append(b)
        dic = { 'lat':lat, 'lon':lon}
        timeline = pd.DataFrame(dic)
        st.map(timeline)

    # Find a location from the coordinates
    def reverseGeocode(coordinates):
        result = rg.search(coordinates)
        # result is a list containing ordered dictionary.
        return (result[0]['name'])

    # This should allow me to display a month, but it doesn' work
    def current_month(month):
        if(month == 1):
            return 'January'
        elif(month == 2):
            return 'February'
        elif(month == 3):
            return 'March'
        elif(month == 4):
            return 'April'
        elif(month == 5):
            return 'May'
        elif(month == 6):
            return 'Jun'
        elif(month == 7):
            return 'July'
        elif(month == 8):
            return 'August'
        elif(month == 9):
            return 'September'
        elif(month == 10):
            return 'October'
        elif(month == 11):
            return 'November'
        elif(month == 12):
            return 'December'

    display_preference(df1)

if __name__ == "__main__":
    main()


#!/usr/bin/env python
# coding=utf-8

s = input()
t = 'hello'
t_i = 0
for i in range(len(s)):
    if t_i >= 5:
        break
    if s[i] == t[t_i]:
        t_i += 1
if t_i >= 5:
    print('YES')
else:
    print('NO')


#! Calculate the average value
# Task:
# Now, let's use our knowledge of sets and help Mickey.
# Ms. Gabriel Williams is a botany professor at District College.
# One day, she asked her student Mickey to compute the average of all
# the plants with distinct heights in her greenhouse.
#
# Input Format:
# The first line contains the integer, N, the total number of plants.
# The second line contains the N space separated heights of the plants.
#
# Output Format:
# Output the average height value on a single line.
#
# Sample Input:
# 10
# 161 182 161 154 176 170 167 171 170 174
# Sample Output:
# 169.375
#
# Explanation:
# Here, set ([154, 161, 167, 170, 171, 174, 176, 178, 182])
# is the set containing the distinct heights.
# Using the sum() and len() functions, we can compute the average.

arr = list(map(int, input().split()))
print(arr)
new_arr = set(arr)
a = sum(new_arr)
b = len(new_arr)
average = a/b
print('%.3f' % average)


def two_sum_first_approach(nums, target):
    for i in range(0, len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return [-1, -1]

def two_sum_second_approach(nums, target):
    hashmap = {}
    for i in range(0, len(nums)):
        if (target - nums[i]) in hashmap:
            return [hashmap[target - nums[i]], i]
        else:
            hashmap[nums[i]] = i
    return [-1, -1]

nums1 = [2, 7, 11, 15]
target1 = 9
print(two_sum_first_approach(nums1, target1))
print(two_sum_second_approach(nums1, target1))

nums2 = [3, 2, 4]
target2 = 6
print(two_sum_first_approach(nums2, target2))
print(two_sum_second_approach(nums2, target2))

nums3 = [3, 3]
target3 = 6
print(two_sum_first_approach(nums3, target3))
print(two_sum_second_approach(nums3, target3))


"""This file is provided as a starting template for writing your own unit
tests to run and debug your minimax and alphabeta agents locally.  The test
cases used by the project assistant are not public.
"""

import unittest

import isolation
from sample_players import (RandomPlayer, open_move_score,
							improved_score, center_score)
from game_agent import (MinimaxPlayer, AlphaBetaPlayer, custom_score,
						custom_score_2, custom_score_3)

from importlib import reload

class IsolationTest(unittest.TestCase):
	"""Unit tests for isolation agents"""

	def setUp(self):
		self.player2 = RandomPlayer()
		self.player1 = AlphaBetaPlayer(score_fn=custom_score)
		self.game = isolation.Board(self.player1, self.player2)

	def test(self):
		winner, history, outcome = self.game.play()
		print("\nWinner: {}\nOutcome: {}".format(winner, outcome))
		print(self.game.to_string())
		print("Move history:\n{!s}".format(history))

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


n = int(input())
loc = [0]*n
cnt = 0

def check(cur, i):
  for idx in range(cur):
    #겹치는 것이 있는지 확인
    if loc[idx] == i or abs(loc[idx]-i) == abs(idx-cur):
      return False
  return True

def DFS(cur):

  global cnt

  if cur == n:
    cnt += 1
    return
  for idx in range(n):
    #해당 위치에 퀸을 놓음
    loc[cur] = idx
    if check(cur, idx):
      DFS(cur+1)

DFS(0)
print(cnt)


import os
import json
from urllib import request
import boto3
import logging
import create_message
from check_registration import get_user_name

# ロガー作成
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# DBインスタンス作成
dynamodb = boto3.resource('dynamodb')

# テーブルの定義
user_table = dynamodb.Table('intern-groupa-user')
group_table = dynamodb.Table('intern-groupa-group')

############## 以下に処理を記述 ##############

text_list = [
    "第1ステップ",
    "第2ステップ",
    "第3ステップ",
    "第4ステップ",
    "第5ステップ",
]

progress_list = [
    "20%",
    "40%",
    "60%",
    "80%",
    "100%",
]

contents_list = [
    "入力画面の右端にある笑顔😊のマークを押す",
    "送りたいスタンプを選択する",
    "そのスタンプを押す。",
    "プレビューが表示されるので、ちゃんと送りたいものか、確認する。",
    "もう一度押して送信完了"
]

def check_playing_start(event):
    event_text = event['events'][0]['message']['text']
    if event_text == '始めます':
        # 返信内容は仮
        messages = [
            {
                "type":"text",
                "text":"ミッションを開始します"
            },
            {
            	"type": "flex",
            	"altText": "mission message",
            	"contents": create_message.create_mission_message("ミッション1", 1, "https://renote.jp/files/blobs/proxy/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBcFZTIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--f38b550ff470c8ca991c91d62ac5974ffa33561b/20150529_780425.jpg", "😊スタンプを送ってみよう😊")
            },
            {
                "type": "flex",
                "altText": "mission procedure",
                "contents": create_message.create_procedure_message(text_list, progress_list, contents_list)
            }
        ]

        #playingをTrueに変更して開始
        group_id = event['events'][0]['source']['groupId']
        group_table.update_item(
            Key={'id': group_id},
            UpdateExpression="set playing=:m",
            ExpressionAttributeValues={
                ':m': True
            }
        )
        return messages

    else:
        # 返信内容は仮
        messages = [
            {
                "type":"text",
                "text":"ミッションを開始するには「始めます」とコメントしてください"
            }
        ]
    return messages


import pytest
import time
from selenium import webdriver
from PageObjectModules.LoginPage import Login
from PageObjectModules.SettingsPage import Settings
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import InvalidSessionIdException
import random

class Test_004_Settings:

    ProjName = "projectsk"
    ProjDesc = "protest"
    SaveAs = "look"
    switchGroup = "Leaktest1"
    projectname = "tsk"
    projdesc = "something blue "

    def test_projectscreen(self, user_login):
        self.driver = user_login
        self.driver.implicitly_wait(2)
        self.pj = Settings(self.driver)
        self.pj.Project()

        # Validation of Project in Side Menu Bar
        expected_element = ['Project']
        data_base_element = self.driver.find_elements(By.XPATH, "//*[@id='three']")

        for idx, base_element in enumerate(data_base_element):
            print(idx, base_element.text)
            assert (expected_element[idx] == base_element.text)

    @pytest.mark.sanity()
    def test_new_project(self, user_login):
        self.driver = user_login
        self.pj = Settings(self.driver)
        self.pj.Project()
        self.pj.clicknew()

        rand_project_name = ''.join((random.choice('aeiourtnslcrp')for i in range (5)))

        self.pj.setpn(rand_project_name)
        self.pj.setpd(self.ProjDesc)
        self.pj.ClickDevMang()
        self.pj.selectSysGrp()
        self.pj.clickSave()

        time.sleep(2)
        assert 'Updated Successfully.' in self.driver.page_source

    def test_general_prop(self, user_login):
        self.driver = user_login
        self.pj = Settings(self.driver)
        time.sleep(2)
        self.pj.Project()

        # Validation of General Properties in Settings Page
        expected_el = ['Project Name']
        time.sleep(2)
        data_base_el = self.driver.find_elements(By.XPATH, "//*[@id='collapseOne']/div/div[1]/div/div/div[1]")

        for idx, base_el in enumerate(data_base_el):
            print(idx, base_el.text)
            assert (expected_el[idx] == base_el.text)

        expected_el = ['Description']
        time.sleep(2)
        data_base_el = self.driver.find_elements(By.XPATH, "//*[@id='collapseOne']/div/div[1]/div/div/div[3]/div/h5")

        for idx, base_el in enumerate(data_base_el):
            print(idx, base_el.text)
            assert (expected_el[idx] == base_el.text)

    def test_project_edit(self, user_login):
        self.driver = user_login
        self.pj = Settings(self.driver)
        self.pj.Project()
        # self.pj.clickcheck()
        time.sleep(1)
        self.pj.clickedit()

        self.driver.find_element(By.XPATH, "//*[@id='ProjName']").clear()
        self.driver.find_element(By.XPATH, "//*[@id='ProjName']").send_keys("ppt")

        self.driver.find_element(By.XPATH, "//*[@id='Projdesc']").clear()
        self.driver.find_element(By.XPATH, "//*[@id='Projdesc']").send_keys("new project")

        self.pj.clickSave()
        time.sleep(2)
        assert 'Updated Successfully.' in self.driver.page_source

    def test_delete_project(self, user_login):
        self.driver = user_login
        self.pj = Settings(self.driver)
        self.pj.Project()
        # self.pj.clickcheck()
        self.pj.deleteproj()
        self.pj.popupdeleteproj()
        time.sleep(2)
        assert 'Deleted Successfully.' in self.driver.page_source

    def test_multiple_delete(self, user_login):
        self.driver = user_login
        self.pj = Settings(self.driver)
        self.pj.Project()
        self.pj.clickmultipledelete()
        time.sleep(2)


import os

import pandas as pd
import torch
import torchvision.transforms.functional as F
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from torchvision.io import read_image
from transformers import AutoImageProcessor, Dinov2Model

class TensorDataset(Dataset):
    def __init__(self, annotations_file, tensor_dir, transform=None, target_transform=None):
        self.tensor_labels = pd.read_csv(annotations_file)
        self.tensor_dir = tensor_dir
        self.transform = transform
        self.target_transform = target_transform

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

    def __getitem__(self, idx):
        tensor_path = os.path.join(self.tensor_dir, 'gallery_tensors_dino_v2/' + self.tensor_labels.iloc[idx, 1].split('/')[1])
        tensor = torch.load(tensor_path)
        label = self.tensor_labels.iloc[idx, 2]
        image_path = self.tensor_labels.iloc[idx, 3]
        if self.transform:
            tensor = self.transform(tensor)
        if self.target_transform:
            label = self.target_transform(label)
        return tensor, label, image_path

class DeploymentModel_DINO_v2:
    __instance = None

    @staticmethod
    def getInstance():
        """ Static access method. """
        if DeploymentModel_DINO_v2.__instance is None:
            DeploymentModel_DINO_v2()
        return DeploymentModel_DINO_v2.__instance

    def __init__(self):
        if DeploymentModel_DINO_v2.__instance is not None:
            raise Exception("This class is a singleton!")
        else:
            DeploymentModel_DINO_v2.__instance = self
            model_ckpt = "facebook/dinov2-giant"
            self.image_processor = AutoImageProcessor.from_pretrained(model_ckpt,
                                                                 do_normalize=True,
                                                                 do_center_crop=True,
                                                                 do_rescale=True,
                                                                 do_resize=True,
                                                                 size={'shortest_edge': 384},
                                                                 crop_size={'height': 384, 'width': 384})
            model = Dinov2Model.from_pretrained(model_ckpt)
            model = model.to('cuda')
            self.model = model

            self.gallery_tensor_dict = {}
            self.gallery_label_dict = {}
            self.gallery_img_path_dict = {}

            self.load_gallery_embeddings()

    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(DeploymentModel_DINO_v2, cls).__new__(cls)
        return cls.instance

    def img_transform(self, image):
        images = F.resize(image, (384, 384), antialias=True)
        images = self.image_processor(images, return_tensors="pt")
        return images['pixel_values']

    def load_gallery_embeddings(self):
        tensor_dataset = TensorDataset("/home/group15/VPR/visual-product-recognition-2/Deployment/Streamlit_Web_App/gallery_tensors_dino_v2/gallery_tensors_dino_v2.csv",
                                       "/home/group15/VPR/visual-product-recognition-2/Deployment/Streamlit_Web_App")
        tensor_dataloader = DataLoader(tensor_dataset, batch_size=1, shuffle=True)

        for idx, data in enumerate(tensor_dataloader):
            tensors, labels, image_paths = data
            self.gallery_tensor_dict[idx] = tensors
            self.gallery_label_dict[idx] = labels
            self.gallery_img_path_dict[idx] = image_paths

    def get_query_embedding(self, image_path, x, y, w, h):
        query_image = read_image(image_path)
        query_image = F.crop(F.to_pil_image(query_image), y, x, h, w)
        preprocessed_query_image = self.img_transform(query_image).to('cuda')
        with torch.no_grad():
            output = self.model(preprocessed_query_image)
            embedding = output.last_hidden_state[:, 0].cpu()
        return embedding

    def get_matching_gallery_images(self, query_tensor):
        tensor_dict = self.gallery_tensor_dict
        img_path_dict = self.gallery_img_path_dict

        query_tensor_ = query_tensor.to('cuda')

        euclidean = None
        for k in range(len(tensor_dict)):
            query_tensor = query_tensor_.repeat(tensor_dict[k].shape[0], 1)
            gallery_tensors = tensor_dict[k].to('cuda')
            if euclidean is None:
                euclidean = torch.nn.functional.pairwise_distance(gallery_tensors, query_tensor, p=2)
            else:
                euclidean = torch.cat(
                    (euclidean, torch.nn.functional.pairwise_distance(gallery_tensors, query_tensor, p=2)), dim=0)

        euclidean_, euclidean_indices = torch.sort(euclidean)
        euclidean_indices = euclidean_indices.cpu().tolist()

        similar_images = []
        for i in range(len(euclidean_indices)):
            similar_images.append(img_path_dict[euclidean_indices[i]][0])

        return similar_images


import argparse

from packaging import version
import azure.cognitiveservices.vision.face as faceAPI
if version.parse(faceAPI.__version__) <= version.parse('0.3.0'):
    from azure.cognitiveservices.vision.face.face_client import FaceClient  # The main interface to access Azure face API
else:
    from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials  # To hold the subscription key

from mlhub.pkg import (
    azkey,
    is_url,
)

from utils import (
    SERVICE,
    azface_detect,
    get_abspath,
    get_face_api_key_endpoint,
    option_parser,
    print_detection_results,
)

# ----------------------------------------------------------------------
# Parse command line arguments
# ----------------------------------------------------------------------

parser = argparse.ArgumentParser(
    prog='detect',
    parents=[option_parser],
    description='Detect faces in an image.'
)

parser.add_argument(
    'path',
    type=str,
    help='path or URL of a photo where faces will be detected')

args = parser.parse_args()

# ----------------------------------------------------------------------
# Setup
# ----------------------------------------------------------------------

img_url = args.path if is_url(args.path) else get_abspath(args.path)
face_attrs = ['age', 'gender', 'glasses', 'emotion', 'occlusion']
subscription_key, endpoint = args.key, args.endpoint

# ----------------------------------------------------------------------
# Call face API to detect and describe faces
# ----------------------------------------------------------------------

if not subscription_key or not endpoint:  # Request subscription key and endpoint from user.
    subscription_key, endpoint = get_face_api_key_endpoint(*azkey(args.key_file, SERVICE, verbose=False))

credentials = CognitiveServicesCredentials(subscription_key)  # Set credentials
client = FaceClient(endpoint, credentials)  # Setup Azure face API client
faces = azface_detect(client, img_url, return_face_attributes=face_attrs)
print_detection_results(faces)


from datetime import date
gênero = str(input('Digite ao lado seu gênero (Feminino ou Masculino): \033[4;33m')).strip().capitalize()

if 'F' in gênero:
    print('\033[m\033[1;35mDesculpe! O alistamento é so para pessoas do sexo masculino\033[m')

elif 'M' in gênero:
    anoAtual = date.today().year
    anoDeNascimento = int(input('\033[mDigite aqui o ano do seu nascimento: '))
    idade = anoAtual - anoDeNascimento

    if idade == 18:
        print('Já está na hora de se alistar')
    elif idade > 18:
        diferençaEntreIdadeAtualE18Anos = idade - 18
        print(f'Já passou {diferençaEntreIdadeAtualE18Anos} anos do ano que você deveria se alistar')
        print(f'Seu alistamento foi, ou deveria ser em {anoAtual - diferençaEntreIdadeAtualE18Anos}')
    else:
        diferençaEntreIdadeAtualE18Anos = 18 - idade
        print('Ainda falta {} anos para o seu alistamento'.format(diferençaEntreIdadeAtualE18Anos))
        print('Seu alistamento será em {}'.format(anoAtual + diferençaEntreIdadeAtualE18Anos))
else:
    print('\033[m\033[1;31mAcho que você digitou seu gênero errado... Tente novamente digitando "Masculino" ou "Feminino"!\033[m')

cursoEmVídeo/Mundo 2/Aula 12 (If and else)/Desafio 039.py


import os.path as os
from input import Err

def press(data):
    print('Real file size',len(data))
    complete=[]
    data = data.replace('\\','\\\\')

    #data = [data]
    for i in [10,9,8,7,6,5,4]:
        print('File size now',len(data),'bytes')

        for j in range(len(data)-i):
            top = data[j:j+i]
            count = 0
            loop = 0

            for p in range(len(data)-i):
                if loop:
                    loop-=1
                    continue
                if data[p:p+i] == top:
                    loop = i
                    count +=1
                    if count == 5:
                        data= data.replace(top,'\\'+str(len(complete))+'.')
                        complete.append(top)
                        break

    print('Compressed file size',len(data))
    print('writting your file.')

    return (complete,data)

def compress(f,ff,is_file,replace):
    f2=f
    loc = os.dirname(f)
    with open(ff,'r' if is_file else 'rb') as c :
        inf=str(c.read())
        if os.exists(f+'.cmp'):
            if not replace:
                return Err('replace : False\ncompressed location already exist')

    with open(f+'.cmp',"w") as c2:
        c2.write(str(int(is_file))+'\n')
        c,d = press(inf)
        c2.write(str(f)+'\n')
        c2.write(str(c)+'\n')
        c2.write(str(d))
        c2.close()

    return Err() #no argument, error not occured.


from django.shortcuts import render
from django.views.generic import View
from pure_pagination import PageNotAnInteger,Paginator
from django.http import JsonResponse
from django.db.models import Q

from .models import Course
from operation.models import UserCollect,UserCourse,CourseComment
from organizations.models import CourseOrg,Teacher
from util.mixin_util import LoginRequiredMixin

class CourseView(View):
    def get(self, request):
        all_courses = Course.objects.all()
        hot_courses = Course.objects.order_by('-click')[:3]

        # 课程全局搜索
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_courses = Course.objects.filter(Q(name__contains=search_keywords)|
                                                  Q(desc__contains=search_keywords)|
                                                  Q(detail__contains=search_keywords))

        sort = request.GET.get('sort', '')
        if sort:
            if sort == 'students':
                all_courses = all_courses.order_by('-students_num')
            elif sort == 'hot':
                all_courses = all_courses.order_by('-click')

        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        p = Paginator(all_courses, 3, request=request)
        all_courses = p.page(page)
        return render(request, 'course-list.html',
                      {
                        "all_courses" : all_courses,
                        "hot_courses" : hot_courses,
                        "sort" : sort,
                      })

class CourseDetailView(View):
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        course.click += 1
        course.save()
        hasfav_course = False
        hasfav_org = False
        if request.user.is_authenticated:
            if UserCollect.objects.filter(user=request.user, fav_id=int(course_id), fav_type=1):
                hasfav_course = True
            if UserCollect.objects.filter(user=request.user, fav_id=int(course.course_org.id), fav_type=2):
                hasfav_org = True
        tag =  course.tag
        if tag:
            related_courses = Course.objects.filter(~Q(id=int(course_id)), tag=tag)[:2]
        else:
            related_courses = []

        return render(request, 'course-detail.html',
                      {
                          "course" : course,
                          "related_courses" : related_courses,
                          "hasfav_course" : hasfav_course,
                          "hasfav_org" : hasfav_org,
                      })

class AddFavorView(View):
    '''
    用户收藏，取消收藏
    '''
    def post(self, request):
        fav_id = request.POST.get('fav_id', 0)
        fav_type = request.POST.get('fav_type', 0)

        if not request.user.is_authenticated:
            return JsonResponse({"status": "fail", "msg": "用户未登录"})
        records = UserCollect.objects.filter(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type))

        if records:
            '''
            取消收藏
            '''
            records.delete()
            if fav_type == '1':
                course = Course.objects.get(id=fav_id)
                course.favor -= 1
                if course.favor <= 0:
                    course.favor = 0
                course.save()
            elif fav_type == '2':
                course_org = CourseOrg.objects.get(id=fav_id)
                course_org.favor -= 1
                if course_org.favor <= 0:
                    course_org.favor = 0
                course_org.save()
            elif fav_type == '3':
                teacher = Teacher.objects.get(id=fav_id)
                teacher.favor -= 1
                if teacher.favor <= 0:
                    teacher.favor = 0
                teacher.save()
            return JsonResponse({"status": "success", "msg": "收藏"})
        else:
            '''
            收藏
            '''
            if int(fav_id) > 0 and int(fav_type) in [1,2,3]:
                collect = UserCollect()
                collect.user = request.user
                collect.fav_type = int(fav_type)
                collect.fav_id = int(fav_id)
                collect.save()
                if fav_type == '1':
                    course = Course.objects.get(id=fav_id)
                    course.favor += 1
                    course.save()
                elif fav_type == '2':
                    course_org = CourseOrg.objects.get(id=fav_id)
                    course_org.favor += 1
                    course_org.save()
                elif fav_type == '3':
                    teacher = Teacher.objects.get(id=fav_id)
                    teacher.favor += 1
                    teacher.save()
                return JsonResponse({"status": "success", "msg": "已收藏"})
            else:
                return JsonResponse({"status": "fail", "msg": "收藏出错"})

class CourseVideoView(LoginRequiredMixin, View):
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        #
        # if not request.user.is_authenticated:
        #     return render(request, 'login.html')

        usercourse = UserCourse.objects.filter(user=request.user, course=course)
        if not usercourse:
            course.students_num += 1
            course.save()
            usercourse = UserCourse(user=request.user, course=course)
            usercourse.save()

        courseuser = UserCourse.objects.filter(course=course)
        #取出该课程所有用户id
        course_user_ids = [user.id for user in courseuser]
        #取出所有课程id
        all_usercourses = UserCourse.objects.filter(user_id__in=course_user_ids)
        all_courseid = [user_course.course.id for user_course in all_usercourses]
        #有关课程
        related_courses = Course.objects.filter(id__in=all_courseid).order_by("-click")[:5]
        if not related_courses:
            related_courses = []
        return render(request, 'course-video.html',
                      {
                          "course" : course,
                          "related_courses" : related_courses,
                      })

class CourseCommentView(LoginRequiredMixin, View):
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        course_comment = course.coursecomments.all()
        return render(request, 'course-comment.html',
                      {
                          "course" : course,
                          "course_comment" : course_comment,
                      })

class AddCommentView(View):
    def post(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({"status" : "fail", "msg" : "用户未登录"})

        course_id = request.POST.get('course_id', 0)
        comments = request.POST.get('comments', '')
        if int(course_id) > 0 and comments:
            course = Course.objects.get(id=course_id)
            course_comment = CourseComment(user=request.user, course=course, comments=comments)
            course_comment.save()
            return JsonResponse({"status": "success", "msg" : "添加失败"})
        else:
            return JsonResponse({"status": "success", "msg" : "添加失败"})


n = int(input("Number of parentheses:"))
print('\n', end='')

def initial_value():
    return -1

def first(x):
    return 0

def next_elem(x, n):
    if x[-1] == 1:
        return None
    return x[-1] + 1

def consistent(x, n):
    zeros = x.count(0)
    return len(x) - zeros <= zeros <= n // 2

def is_solution(x, n):
    return len(x) == n

def output_solution(x):
    l = ("(" if e == 0 else ")" for e in x)
    print("".join(l))

def back_rec(x, n):
    el = first(x)
    x.append(el)
    while el is not None:
        if consistent(x, n):
            if is_solution(x, n):
                output_solution(x)
            else:
                back_rec(x[:], n)
        el = next_elem(x, n)
        x[-1] = el

def back_iter(n):
    x = [initial_value()]
    while len(x) > 0:
        el = next_elem(x, n)
        while el is not None:
            x[-1] = el
            if consistent(x, n):
                if is_solution(x, n):
                    output_solution(x)
                else:
                    x.append(initial_value())
                    break
            el = next_elem(x, n)
        if el is None: x = x[:-1]

if __name__ == "__main__":
    option = input("Input either 'rec' for recursive or 'iter' for iterative: ")
    if option == 'rec':
        back_rec([], n)
    elif option == 'iter':
        back_iter(n)
    else:
        print("Invalid option chosen! Exiting...")


from base64 import b64encode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes

key = get_random_bytes(16)  # Genera una llave aleatoria de 16 bytes.

with open('key.txt', 'wb') as a_file:
    a_file.write(key)

print('Ingrese el texto a encriptar: ', end="")
plaintext = input().encode()

cipher = AES.new(key, AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))

ct = b64encode(ciphertext).decode('utf-8')

print('El texto encriptado es: ', end="")
print(ct)

with open('cipher_text.txt', 'wb') as b_file:
    b_file.write(cipher.iv)
    b_file.write(ciphertext)


from random import randint
import os
# x->ratat
# O-> neatins de nimic
# 1-> nava
# *->distrus
# in aux tin navele
# in board tin focurile
def createTable(size):
    boardGame=[]
    for i in range(0,size):
        line=["O"]*size
        boardGame.append(line)

    return boardGame

def customPrint(boardGame):
    ch=" "
    for line in boardGame:
        print (ch.join(line))

def makeCross(auxBoard):
    center_line=randint(1,len(auxBoard)-2)
    center_row=randint(1,len(auxBoard)-2)
    if auxBoard[center_line][center_row]!="1" and auxBoard[center_line][center_row+1]!="1" and auxBoard[center_line][center_row-1]!="1" and \
        auxBoard[center_line+1][center_row]!="1" and auxBoard[center_line-1][center_row]!="1" :

        auxBoard[center_line][center_row]="1"
        auxBoard[center_line][center_row-1]="1"
        auxBoard[center_line][center_row+1]="1"
        auxBoard[center_line-1][center_row]="1"
        auxBoard[center_line+1][center_row]="1"

def checkWin(boardGame,auxBoardGame):
    for line in range(0,len(boardGame)):
        for col in range(0,len(boardGame)):
            if auxBoardGame[line][col]=="1" and boardGame[line][col]=="O":
                return 0
    return 1

def maineGame(boardGame,auxBoardGame):

     for i in range(0,20):
         clear = lambda: os.system('cls')
         clear()
         print ("Turn %d" % (i+1))
         customPrint(boardGame)
         guess_row = int(input("Guess Row: "))
         guess_col = int(input("Guess Col: "))

         if guess_col<len(boardGame) and guess_row<len(boardGame):
             if(auxBoardGame[guess_row][guess_col]=="1"):
                 boardGame[guess_row][guess_col]="*"
                 if checkWin(boardGame,auxBoardGame)==1:
                     return 1
             else:
                 boardGame[guess_row][guess_col]="X"
         else:
             print ("Out of board game..")
         customPrint(boardGame)
     return 0

def main(boardGame,auxBoardGame):
     if maineGame(boardGame,auxBoardGame)==1:
        print("Congr! You win!")
     else:
         print ("Out of turns")

boardGame=createTable(6)
auxboard=createTable(6)
makeCross(auxboard)
makeCross(auxboard)
maineGame(boardGame,auxboard)
main(boardGame,auxBoardGame)


class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        # 1->2->3->4->5
        # 3->4->5
        if not head or not head.next:
            return True
        slow = fast = head
        while slow and fast:
            slow = slow.next
            fast = fast.next.next if fast.next is not None else fast.next
        # Reverse slow as head
        prev = None
        while slow:
            tmp = slow.next
            slow.next = prev
            prev = slow
            slow = tmp
        while head and prev:
            if head.val != prev.val:
                return False
            head = head.next
            prev = prev.next
        return True


from typing import List, Optional, Tuple

import pytest

from dbgen.core.node.extract import Extract

def run_extract(extract: Extract) -> Tuple[List[dict], Optional[int]]:
    outputs = []
    with extract:
        extract_generator = extract.extract()
        length = extract.length()
        for extracted_val in extract_generator:
            outputs.append({extract.hash: extract.process_row(extracted_val)})
    return outputs, length

def test_basic_extract():
    """Test the Base Extract."""
    extract = Extract()
    outputs, length = run_extract(extract)
    assert length is None
    assert len(outputs) == 1
    assert outputs[0] == {extract.hash: {}}

class BaseCustomExtract(Extract[str]):
    outputs: List[str] = ['char']
    string: str

    def length(self):
        return len(self.string)

    def extract(self):
        yield from self.string

class CustomExtract(BaseCustomExtract):
    _status: str = 'initialized'

    def setup(self):
        self._status = 'setup'

    def teardown(self):
        self._status = 'finished'

    def extract(self):
        assert self._status == 'setup'
        return super().extract()

class ErrorCustomExtract(CustomExtract):
    def extract(self):
        raise ValueError('Error')

def test_basic_custom_extract():
    """Test that a custom extract has the correct length and extract methods."""

    string = 'abcd'
    extract = BaseCustomExtract(string='abcd')
    outputs, length = run_extract(extract)
    assert length == len(string)
    assert len(outputs) == len(string)
    assert outputs == [{extract.hash: {'char': char}} for char in string]

def test_custom_setup_teardown():
    """Test that a custom extract's setup and teardown methods are correctly called in order."""

    string = 'abcd'
    extract = CustomExtract(string='abcd')
    assert extract._status == 'initialized'
    outputs, length = run_extract(extract)
    assert length == len(string)
    assert len(outputs) == len(string)
    assert outputs == [{extract.hash: {'char': char}} for char in string]
    assert extract._status == 'finished'

def test_teardown_called_during_exception():
    extract = ErrorCustomExtract(string='abcd')
    assert extract._status == 'initialized'
    with pytest.raises(ValueError):
        run_extract(extract)
    assert extract._status == 'finished'

class BadTupleExtract(Extract[tuple]):
    outputs: List[str] = ['tuple']

    def extract(self):
        yield (1, 2, 3)

class GoodTupleExtract(Extract[tuple]):
    outputs: List[str] = ['tuple']

    def extract(self):
        yield ((1, 2, 3),)

class ListExtract(Extract[list]):
    outputs: List[str] = ['list']

    def extract(self):
        yield [1, 2, 3]

def test_bad_tuple_return():
    """Test that error is raised when a N-length tuple is returned for a 1-length output extract"""
    with pytest.raises(ValueError, match='Expected 1 output from extract '):
        extract = BadTupleExtract()
        run_extract(extract)

def test_good_return():
    """Test that lists and tuples can be returned as 1 output"""
    extract = GoodTupleExtract()
    outputs, _ = run_extract(extract)
    assert outputs == [{extract.hash: {'tuple': (1, 2, 3)}}]

    extract = ListExtract()
    outputs, _ = run_extract(extract)
    assert outputs == [{extract.hash: {'list': [1, 2, 3]}}]


import os
import json

from time import sleep
from io import BytesIO
from PIL import Image, ImageDraw
from tqdm import tqdm
from base64 import b64encode
from threading import Thread, Lock

from .labeling import label_image
from .segmentation import segment_image
from .region_detection import get_image_regions

from scripts.status import get_status
from scripts.common import step_list

def img_to_base64(img,scale=1):
	buffer = BytesIO()
	if scale > 1:
		img = img.resize((int(img.width/scale),int(img.height/scale)), Image.LANCZOS)
	img = img.convert('RGB')
	img.save(buffer, "jpeg")
	buffer.seek(0)
	encoded = b64encode(buffer.read()).decode('utf-8')
	return f"data:image/jpeg;base64,{encoded}"

def get_image_crop_preview(image_path,boxes):
	img = Image.open(image_path)
	draw = ImageDraw.Draw(img)
	for box in boxes:
		d = (box[0],box[2],box[1],box[3])
		draw.rectangle(d,outline="red",width=4)
	return img

def box_to_crop_data(box):
	size = min(box[1]-box[0],box[3]-box[2])
	data = {
		"x": box[0],
		"y": box[2],
		"width": size,
		"height": size,
		"rotate": 0,
		"scaleX": 1,
		"scaleY": 1
	}
	return data

def get_image_autocrop(image_path,threshold,min_size,scale):
	# print(f"autocrop {image_path} [{threshold},{min_size},{scale}]")
	boxes = get_image_regions(segment_image(image_path),threshold,min_size,scale)
	preview = get_image_crop_preview(image_path,boxes)
	return boxes, preview

class Autocrop(Thread):
	def __init__(self, image_data, threshold, min_size, scale):
		Thread.__init__(self)
		self.threshold = threshold
		self.min_size = min_size
		self.scale = scale
		self.lock = Lock()
		self.preview = None
		image_data = [x for x in image_data if not (x.get("auto") and x.get("duplicate"))]
		self.image_data = image_data
		target = [image_data.index(x) for x in image_data if x.get("auto") or x.get("status") == "raw"]
		self.tqdm = tqdm(target,unit="img")
	def run(self):
		new = []
		for i in self.tqdm:
			img = self.image_data[i]
			img_path = os.path.join(step_list[0],img.get("filename"))
			boxes, preview = get_image_autocrop(img_path, self.threshold, self.min_size, self.scale)
			if not boxes or len(boxes) == 0:
				continue
			self.image_data[i]["auto"] = True
			self.image_data[i]["crop_data"] = box_to_crop_data(boxes[0])
			if len(boxes) > 1:
				for b in boxes[1:]:
					n = dict(self.image_data[i])
					n["crop_data"] = box_to_crop_data(b)
					n["duplicate"] = True
					new.append(n)
			with self.lock:
				self.preview = img_to_base64(preview, 2)
		self.image_data = sorted(self.image_data+new, key=lambda x: x["filename"])
		sleep(0.5) # last img
		return
	def get_status(self):
		with self.lock:
			data = {
				"run": self.is_alive(),
				"max": self.tqdm.total,
				"current": self.tqdm.n,
				"preview": self.preview,
			}
		return data

def get_image_tags(tagger, image_path, threshold=0.35):
	rating = ["general", "sensitive", "questionable", "explicit"] # remove / filter these
	tags = label_image(image_path, tagger)
	tags = {name.replace("_"," "):conf for name, conf in tags.items() if conf >= threshold and name not in rating}
	return tags

class Autotagger(Thread):
	def __init__(self, images, overwrite, threshold, taggers=None, multi_conf=None, multi_mode=None):
		Thread.__init__(self)
		self.overwrite = overwrite
		self.threshold = threshold
		self.multi_conf = multi_conf
		self.multi_mode = multi_mode
		self.lock = Lock()
		self.caption = None
		self.preview = None
		for i in images: i.txt = os.path.splitext(i.get_step_path(3))[0]+".json"
		if not overwrite:
			images = [x for x in images if not os.path.isfile(x.txt)]

		image_runs = []
		taggers = ["wd-v1-4-vit-tagger-v2"] if not taggers else taggers # fallback
		for t in taggers:
			image_runs += [(t,i) for i in images]
		self.tqdm = tqdm(image_runs, unit="img")

	def run(self):
		if not os.path.isdir(step_list[3]):
			os.mkdir(step_list[3])

		captions = {}
		json_path_list = []
		for tagger, img in self.tqdm:
			json_file = os.path.splitext(img.get_step_path(3))[0]+".json"
			json_path = os.path.split(json_file)[0]
			if json_path not in json_path_list: # don't recheck each time
				if not os.path.isdir(json_path):
					os.mkdir(json_path)
				json_path_list.append(json_path)

			if os.path.isfile(json_file) and not self.overwrite:
				with open(json_file) as f:
					data = json.load(f)
				caption = {"Empty caption":1.0} if "caption" not in data.keys() else data["caption"]
				caption["Already tagged"] = 1.0
				caption = dict(sorted(caption.items(), key=lambda item: item[1], reverse=True))
			else:
				caption = get_image_tags(tagger, img.path, 0.15) # low threshold here, filter later
				if json_file not in captions.keys():
					captions[json_file] = []
				captions[json_file].append(caption)

			with self.lock:
				self.caption = caption
				self.preview = img_to_base64(Image.open(img.path),2)

		# write output
		for json_file, caption in captions.items():
				if len(caption) == 1: # single tagger mode
					caption = caption[0]
				else: # multi tagger mode
					# intersect or union
					allowed_tags = []
					for c in caption:
						for i in c.keys():
							if i not in allowed_tags:
								allowed_tags.append(i)
					if self.multi_mode == "intersect":
						for k in allowed_tags:
							for c in caption:
								if k not in c.keys():
									allowed_tags.remove(k)
									break
					# sum captions
					out = {}
					for c in caption:
						for tag, conf in c.items():
							if tag not in allowed_tags:
								continue
							if tag not in out.keys():
								out[tag] = 0
							out[tag] += conf
					# max 1.0 or avg
					cl = len(caption)
					caption = {}
					for tag, conf in out.items():
						caption[tag] = conf/cl if self.multi_conf == "avg" else min(conf, 1.0)

				caption = {tag:conf for tag, conf in caption.items() if conf >= self.threshold}
				caption = dict(sorted(caption.items(), key=lambda item: item[1], reverse=True))
				with open(json_file, "w") as f:
					f.write(json.dumps({"caption":caption}, indent=2))

		sleep(1) # last img/return
		return

	def get_status(self):
		with self.lock:
			data = {
				"run": self.is_alive(),
				"max": self.tqdm.total,
				"current": self.tqdm.n,
				"caption": self.caption,
				"preview": self.preview,
			}
		return data


#import yt.mods as yt
import yt
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import glob

__all__ = ['sfrFromParticles']

def sfrFromParticles(ds, data, selection = None, times = None, t_o = None):
    """
    Given a dataset, computes the star formation rate as a
    function of time
    """

    nstars = np.size( data['particle_mass'] )

    if selection is None:
        selection = np.array( [True]*nstars )

    particle_mass = data['birth_mass'][selection].value * yt.units.Msun
    creation_time = data['creation_time'][selection].to('Myr')
    currentTime   = ds.current_time.to('Myr')

    # set start time of array
    if t_o is None:
        t_o = np.min(creation_time)
    else:
        if not hasattr(t_o, 'value'):
            t_o = t_o * yt.units.Myr
        else:
            t_o = t_o.to('Myr')

    if times is None:
        bin_spacing = 10.0 * yt.units.Myr
        times = np.arange(t_o - bin_spacing*2.0, currentTime + bin_spacing, bin_spacing)*yt.units.Myr
    elif np.size(times) == 1:
        bin_spacing = times
        if not hasattr(bin_spacing, 'value'):
            bin_spacing = bin_spacing * yt.units.Myr
        else:
            bin_spacing = bin_spacing.to('Myr')

        t_f = currentTime + bin_spacing

        times = np.arange(t_o - bin_spacing*2.0, t_f, bin_spacing)
        if not hasattr(times, 'value'):
            times = times * yt.units.Myr

    sfr   = np.zeros(np.size(times)-1)

    times = times.to('yr')

    for i in np.arange(np.size(times)-1):
        dt = times[i+1] - times[i]
        dm = np.sum(particle_mass[creation_time <= times[i+1]]) -\
             np.sum(particle_mass[creation_time <= times[i]])

        sfr[i] = dm / dt

    return times, sfr

if __name__=='__main__':
    log = True

    ds_list = np.sort( glob.glob('./DD????/DD????'))

    ds   = yt.load(ds_list[-1])
    data = ds.all_data()

    dt = 10.0*yt.units.Myr

    times = np.arange(0.0*yt.units.Myr, ds.current_time.to('Myr')+dt, dt)
    times = times*yt.units.Myr

    times, sfr = sfrFromParticles(ds, data, times = times)
    fig, ax = plt.subplots(figsize=(8,8))

    center = 0.5 * (times[1:]+times[:-1])

    if log:
        ax.plot(center/1.0E6, sfr, color = 'black', lw = 3)
        ax.semilogy()
    else:
        ax.step(times[:-1]/1.0E6, sfr*1.0E4, color = 'black', lw = 3, where='pre')

    ax.set_xlabel('Time (Myr)')

    ax.set_ylabel(r'SFR (10$^{-4}$ M$_{\odot}$/yr)')

    if log:
        ax.set_ylim(1.0E-5, 1.0E-2)
    else:

        ax.set_ylim(0.0, np.max(sfr)*1.1*1.0E4)
    ax.minorticks_on()
    plt.savefig('sfr.png')


import sys
_module = sys.modules[__name__]
del sys
abstract_game = _module
breakout = _module
cartpole = _module
connect4 = _module
gomoku = _module
gridworld = _module
lunarlander = _module
tictactoe = _module
twentyone = _module
models = _module
muzero = _module
replay_buffer = _module
self_play = _module
shared_storage = _module
trainer = _module

from _paritybench_helpers import _mock_config, patch_functional
from unittest.mock import mock_open, MagicMock
from torch.autograd import Function
from torch.nn import Module
import abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings
import numpy as np
from torch import Tensor
patch_functional()
open = mock_open()
yaml = logging = sys = argparse = MagicMock()
ArgumentParser = argparse.ArgumentParser
_global_config = args = argv = cfg = config = params = _mock_config()
argparse.ArgumentParser.return_value.parse_args.return_value = _global_config
yaml.load.return_value = _global_config
sys.argv = _global_config
__version__ = '1.0.0'
xrange = range
wraps = functools.wraps

import numpy

import torch

import math

from random import randint

from abc import ABC

from abc import abstractmethod

import copy

import time

from torch.utils.tensorboard import SummaryWriter

import collections

class AbstractNetwork(ABC, torch.nn.Module):

    def __init__(self):
        super().__init__()
        pass

    @abstractmethod
    def initial_inference(self, observation):
        pass

    @abstractmethod
    def recurrent_inference(self, encoded_state, action):
        pass

    def get_weights(self):
        return {key: value.cpu() for key, value in self.state_dict().items()}

    def set_weights(self, weights):
        self.load_state_dict(weights)

class FullyConnectedNetwork(torch.nn.Module):

    def __init__(self, input_size, layer_sizes, output_size, activation=None):
        super().__init__()
        size_list = [input_size] + layer_sizes
        layers = []
        if 1 < len(size_list):
            for i in range(len(size_list) - 1):
                layers.extend([torch.nn.Linear(size_list[i], size_list[i + 1]), torch.nn.LeakyReLU()])
        layers.append(torch.nn.Linear(size_list[-1], output_size))
        if activation:
            layers.append(activation)
        self.layers = torch.nn.ModuleList(layers)

    def forward(self, x):
        for layer in self.layers:
            x = layer(x)
        return x

class MuZeroFullyConnectedNetwork(AbstractNetwork):

    def __init__(self, observation_shape, stacked_observations, action_space_size, encoding_size, fc_reward_layers, fc_value_layers, fc_policy_layers, fc_representation_layers, fc_dynamics_layers, support_size):
        super().__init__()
        self.action_space_size = action_space_size
        self.full_support_size = 2 * support_size + 1
        self.representation_network = FullyConnectedNetwork(observation_shape[0] * observation_shape[1] * observation_shape[2] * (stacked_observations + 1) + stacked_observations * observation_shape[1] * observation_shape[2], fc_representation_layers, encoding_size)
        self.dynamics_encoded_state_network = FullyConnectedNetwork(encoding_size + self.action_space_size, fc_dynamics_layers, encoding_size)
        self.dynamics_reward_network = FullyConnectedNetwork(encoding_size, fc_reward_layers, self.full_support_size)
        self.prediction_policy_network = FullyConnectedNetwork(encoding_size, fc_policy_layers, self.action_space_size)
        self.prediction_value_network = FullyConnectedNetwork(encoding_size, fc_value_layers, self.full_support_size)

    def prediction(self, encoded_state):
        policy_logits = self.prediction_policy_network(encoded_state)
        value = self.prediction_value_network(encoded_state)
        return policy_logits, value

    def representation(self, observation):
        encoded_state = self.representation_network(observation.view(observation.shape[0], -1))
        min_encoded_state = encoded_state.min(1, keepdim=True)[0]
        max_encoded_state = encoded_state.max(1, keepdim=True)[0]
        scale_encoded_state = max_encoded_state - min_encoded_state
        scale_encoded_state[scale_encoded_state < 1e-05] += 1e-05
        encoded_state_normalized = (encoded_state - min_encoded_state) / scale_encoded_state
        return encoded_state_normalized

    def dynamics(self, encoded_state, action):
        action_one_hot = torch.zeros((action.shape[0], self.action_space_size)).float()
        action_one_hot.scatter_(1, action.long(), 1.0)
        x = torch.cat((encoded_state, action_one_hot), dim=1)
        next_encoded_state = self.dynamics_encoded_state_network(x)
        reward = self.dynamics_reward_network(next_encoded_state)
        min_next_encoded_state = next_encoded_state.min(1, keepdim=True)[0]
        max_next_encoded_state = next_encoded_state.max(1, keepdim=True)[0]
        scale_next_encoded_state = max_next_encoded_state - min_next_encoded_state
        scale_next_encoded_state[scale_next_encoded_state < 1e-05] += 1e-05
        next_encoded_state_normalized = (next_encoded_state - min_next_encoded_state) / scale_next_encoded_state
        return next_encoded_state_normalized, reward

    def initial_inference(self, observation):
        encoded_state = self.representation(observation)
        policy_logits, value = self.prediction(encoded_state)
        reward = torch.zeros(1, self.full_support_size).scatter(1, torch.tensor([[self.full_support_size // 2]]).long(), 1.0).repeat(len(observation), 1)
        return value, reward, policy_logits, encoded_state

    def recurrent_inference(self, encoded_state, action):
        next_encoded_state, reward = self.dynamics(encoded_state, action)
        policy_logits, value = self.prediction(next_encoded_state)
        return value, reward, policy_logits, next_encoded_state

def conv3x3(in_channels, out_channels, stride=1):
    return torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)

class ResidualBlock(torch.nn.Module):

    def __init__(self, num_channels, stride=1):
        super().__init__()
        self.conv1 = conv3x3(num_channels, num_channels, stride)
        self.bn1 = torch.nn.BatchNorm2d(num_channels)
        self.conv2 = conv3x3(num_channels, num_channels)
        self.bn2 = torch.nn.BatchNorm2d(num_channels)

    def forward(self, x):
        out = self.conv1(x)
        out = self.bn1(out)
        out = torch.nn.functional.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        out += x
        out = torch.nn.functional.relu(out)
        return out

class DownSample(torch.nn.Module):

    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.conv1 = torch.nn.Conv2d(in_channels, out_channels // 2, kernel_size=3, stride=2, padding=1, bias=False)
        self.resblocks1 = torch.nn.ModuleList([ResidualBlock(out_channels // 2) for _ in range(2)])
        self.conv2 = torch.nn.Conv2d(out_channels // 2, out_channels, kernel_size=3, stride=2, padding=1, bias=False)
        self.resblocks2 = torch.nn.ModuleList([ResidualBlock(out_channels) for _ in range(3)])
        self.pooling1 = torch.nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
        self.resblocks3 = torch.nn.ModuleList([ResidualBlock(out_channels) for _ in range(3)])
        self.pooling2 = torch.nn.AvgPool2d(kernel_size=3, stride=2, padding=1)

    def forward(self, x):
        out = self.conv1(x)
        for block in self.resblocks1:
            out = block(out)
        out = self.conv2(out)
        for block in self.resblocks2:
            out = block(out)
        out = self.pooling1(out)
        for block in self.resblocks3:
            out = block(out)
        out = self.pooling2(out)
        return out

class RepresentationNetwork(torch.nn.Module):

    def __init__(self, observation_shape, stacked_observations, num_blocks, num_channels, downsample):
        super().__init__()
        self.use_downsample = downsample
        if self.use_downsample:
            self.downsample = DownSample(observation_shape[0] * (stacked_observations + 1) + stacked_observations, num_channels)
        self.conv = conv3x3(observation_shape[0] * (stacked_observations + 1) + stacked_observations, num_channels)
        self.bn = torch.nn.BatchNorm2d(num_channels)
        self.resblocks = torch.nn.ModuleList([ResidualBlock(num_channels) for _ in range(num_blocks)])

    def forward(self, x):
        if self.use_downsample:
            out = self.downsample(x)
        else:
            out = self.conv(x)
            out = self.bn(out)
            out = torch.nn.functional.relu(out)
        for block in self.resblocks:
            out = block(out)
        return out

class DynamicsNetwork(torch.nn.Module):

    def __init__(self, num_blocks, num_channels, reduced_channels_reward, fc_reward_layers, full_support_size, block_output_size_reward):
        super().__init__()
        self.conv = conv3x3(num_channels, num_channels - 1)
        self.bn = torch.nn.BatchNorm2d(num_channels - 1)
        self.resblocks = torch.nn.ModuleList([ResidualBlock(num_channels - 1) for _ in range(num_blocks)])
        self.conv1x1_reward = torch.nn.Conv2d(num_channels - 1, reduced_channels_reward, 1)
        self.block_output_size_reward = block_output_size_reward
        self.fc = FullyConnectedNetwork(self.block_output_size_reward, fc_reward_layers, full_support_size)

    def forward(self, x):
        out = self.conv(x)
        out = self.bn(out)
        out = torch.nn.functional.relu(out)
        for block in self.resblocks:
            out = block(out)
        state = out
        out = self.conv1x1_reward(out)
        out = out.view(-1, self.block_output_size_reward)
        reward = self.fc(out)
        return state, reward

class PredictionNetwork(torch.nn.Module):

    def __init__(self, action_space_size, num_blocks, num_channels, reduced_channels_value, reduced_channels_policy, fc_value_layers, fc_policy_layers, full_support_size, block_output_size_value, block_output_size_policy):
        super().__init__()
        self.resblocks = torch.nn.ModuleList([ResidualBlock(num_channels) for _ in range(num_blocks)])
        self.conv1x1_value = torch.nn.Conv2d(num_channels, reduced_channels_value, 1)
        self.conv1x1_policy = torch.nn.Conv2d(num_channels, reduced_channels_policy, 1)
        self.block_output_size_value = block_output_size_value
        self.block_output_size_policy = block_output_size_policy
        self.fc_value = FullyConnectedNetwork(self.block_output_size_value, fc_value_layers, full_support_size)
        self.fc_policy = FullyConnectedNetwork(self.block_output_size_policy, fc_policy_layers, action_space_size)

    def forward(self, x):
        out = x
        for block in self.resblocks:
            out = block(out)
        value = self.conv1x1_value(out)
        policy = self.conv1x1_policy(out)
        value = value.view(-1, self.block_output_size_value)
        policy = policy.view(-1, self.block_output_size_policy)
        value = self.fc_value(value)
        policy = self.fc_policy(policy)
        return policy, value

class MuZeroResidualNetwork(AbstractNetwork):

    def __init__(self, observation_shape, stacked_observations, action_space_size, num_blocks, num_channels, reduced_channels_reward, reduced_channels_value, reduced_channels_policy, fc_reward_layers, fc_value_layers, fc_policy_layers, support_size, downsample):
        super().__init__()
        self.action_space_size = action_space_size
        self.full_support_size = 2 * support_size + 1
        block_output_size_reward = reduced_channels_reward * (observation_shape[1] // 16) * (observation_shape[2] // 16) if downsample else reduced_channels_reward * observation_shape[1] * observation_shape[2]
        block_output_size_value = reduced_channels_value * (observation_shape[1] // 16) * (observation_shape[2] // 16) if downsample else reduced_channels_value * observation_shape[1] * observation_shape[2]
        block_output_size_policy = reduced_channels_policy * (observation_shape[1] // 16) * (observation_shape[2] // 16) if downsample else reduced_channels_policy * observation_shape[1] * observation_shape[2]
        self.representation_network = RepresentationNetwork(observation_shape, stacked_observations, num_blocks, num_channels, downsample)
        self.dynamics_network = DynamicsNetwork(num_blocks, num_channels + 1, reduced_channels_reward, fc_reward_layers, self.full_support_size, block_output_size_reward)
        self.prediction_network = PredictionNetwork(action_space_size, num_blocks, num_channels, reduced_channels_value, reduced_channels_policy, fc_value_layers, fc_policy_layers, self.full_support_size, block_output_size_value, block_output_size_policy)

    def prediction(self, encoded_state):
        policy, value = self.prediction_network(encoded_state)
        return policy, value

    def representation(self, observation):
        encoded_state = self.representation_network(observation)
        min_encoded_state = encoded_state.view(-1, encoded_state.shape[1], encoded_state.shape[2] * encoded_state.shape[3]).min(2, keepdim=True)[0].unsqueeze(-1)
        max_encoded_state = encoded_state.view(-1, encoded_state.shape[1], encoded_state.shape[2] * encoded_state.shape[3]).max(2, keepdim=True)[0].unsqueeze(-1)
        scale_encoded_state = max_encoded_state - min_encoded_state
        scale_encoded_state[scale_encoded_state < 1e-05] += 1e-05
        encoded_state_normalized = (encoded_state - min_encoded_state) / scale_encoded_state
        return encoded_state_normalized

    def dynamics(self, encoded_state, action):
        action_one_hot = torch.ones((encoded_state.shape[0], 1, encoded_state.shape[2], encoded_state.shape[3])).float()
        action_one_hot = action[:, :, (None), (None)] * action_one_hot / self.action_space_size
        x = torch.cat((encoded_state, action_one_hot), dim=1)
        next_encoded_state, reward = self.dynamics_network(x)
        min_next_encoded_state = next_encoded_state.view(-1, next_encoded_state.shape[1], next_encoded_state.shape[2] * next_encoded_state.shape[3]).min(2, keepdim=True)[0].unsqueeze(-1)
        max_next_encoded_state = next_encoded_state.view(-1, next_encoded_state.shape[1], next_encoded_state.shape[2] * next_encoded_state.shape[3]).max(2, keepdim=True)[0].unsqueeze(-1)
        scale_next_encoded_state = max_next_encoded_state - min_next_encoded_state
        scale_next_encoded_state[scale_next_encoded_state < 1e-05] += 1e-05
        next_encoded_state_normalized = (next_encoded_state - min_next_encoded_state) / scale_next_encoded_state
        return next_encoded_state_normalized, reward

    def initial_inference(self, observation):
        encoded_state = self.representation(observation)
        policy_logits, value = self.prediction(encoded_state)
        reward = torch.zeros(1, self.full_support_size).scatter(1, torch.tensor([[self.full_support_size // 2]]).long(), 1.0).repeat(len(observation), 1)
        return value, reward, policy_logits, encoded_state

    def recurrent_inference(self, encoded_state, action):
        next_encoded_state, reward = self.dynamics(encoded_state, action)
        policy_logits, value = self.prediction(next_encoded_state)
        return value, reward, policy_logits, next_encoded_state

import torch
from torch.nn import MSELoss, ReLU
from _paritybench_helpers import _mock_config, _mock_layer, _paritybench_base, _fails_compile

TESTCASES = [
    # (nn.Module, init_args, forward_args, jit_compiles)
    (DownSample,
     lambda: ([], {'in_channels': 4, 'out_channels': 4}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (RepresentationNetwork,
     lambda: ([], {'observation_shape': [4, 4], 'stacked_observations': 4, 'num_blocks': 4, 'num_channels': 4, 'downsample': 4}),
     lambda: ([torch.rand([4, 24, 64, 64])], {}),
     True),
    (ResidualBlock,
     lambda: ([], {'num_channels': 4}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
]

class Test_werner_duvaud_muzero_general(_paritybench_base):
    def test_000(self):
        self._check(*TESTCASES[0])

    def test_001(self):
        self._check(*TESTCASES[1])

    def test_002(self):
        self._check(*TESTCASES[2])


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

class IGAN(nn.Module):
    def __init__(self, realnvp, deq, nc, img_size, cond_label_size):
        super().__init__()
        self.model = realnvp
        self.deq = deq
        self.nc = nc
        self.img_size = img_size
        self.cond_label_size = cond_label_size

    def forward(self, z, y=None):
        N = len(z)
        labels = None
        if not y is None:
            labels = torch.zeros(N, self.cond_label_size).to(z.device)
            labels[:,y] = 1

        x, _ = self.model.inverse(z, labels)
        x = self.deq.inverse(x).view(-1, self.nc, self.img_size, self.img_size)
        return x

    def inverse(self, x, y=None):
        N = len(x)
        x = self.deq(x)
        x = x.view(x.shape[0], -1)
        if not y is None:
            labels = torch.zeros(N, self.cond_label_size).to(x.device)
            labels[:,y] = 1
        z, _ = self.model(x, labels)
        return z

    def log_prob(self, x, y=None):
        N = len(x)
        x = self.deq(x)
        x = x.view(N, -1)
        if not y is None:
            labels = torch.zeros(N, self.cond_label_size).to(x.device)
            labels[:,y] = 1
        return self.model.log_prob(x, labels)/(self.nc * self.img_size * self.img_size)


from airflow import DAG
from airflow.sensors.http_sensor import HttpSensor
from airflow.utils.dates import days_ago

dag = DAG('dag', schedule_interval='@daily', start_date=days_ago(1))

def response_check(response):
  number = response.json()
  if number == 5:
      return True
  else:
      return False

sensor = HttpSensor(
    task_id='http_sensor',
    http_conn_id='get_random_number',
    endpoint='/integers/?num=1&min=1&max=5&col=1&base=10&format=plain',
    response_check=response_check,
    timeout=60,
    poke_interval=10,
    dag=dag)


from django.contrib.auth.models import Group
from bank_app.models import Account, Transaction, User, UserType, UserProfile
from django.db.models import Sum, F, Count
from django.shortcuts import render, reverse, get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from decimal import Decimal
from django.core.exceptions import ValidationError

def form_make_loan_payment(request):
    accounts = Account.objects.filter(
        user_id=request.user, account_type="standard")
    loans = Account.objects.filter(user_id=request.user, account_type="loan")
    context = {
        'accounts': accounts,
        'loans': loans
    }

    if request.method == "POST":
        standard_account_number = request.POST['standard_account_number']
        loan_account_number = request.POST['loan_account_number']
        amount = request.POST['amount']
        standard_account = get_object_or_404(
            Account, account_number=standard_account_number)
        loan_account = get_object_or_404(
            Account, account_number=loan_account_number)
        try:
            transaction = Transaction()
            transaction.transfer(
                standard_account, loan_account, "loan payment", Decimal(amount), is_loan=False)
            messages.success(request, "Loan payment successful.")
            return HttpResponseRedirect(reverse('customer_app:view_my_accounts'))
        except ValidationError as err:
            messages.warning(
                request, err.messages)
            return render(request, 'customer_app/form_make_loan_payment.html', context)
    else:
        return render(request, 'customer_app/form_make_loan_payment.html', context)

def form_take_a_loan(request):

    accounts = Account.objects.filter(
        user_id=request.user, account_type="standard")

    context = {
        'accounts': accounts
    }

    if request.method == "POST":
        try:
            number_account_to = request.POST['account']
            amount = request.POST['amount']
            account_to = get_object_or_404(
                Account, account_number=number_account_to)
            request.user.userprofile.take_loan(account_to, amount)
            messages.success(request, "Successfully added a new loan.")
            return HttpResponseRedirect(reverse('customer_app:view_my_accounts'))
        except ValidationError as err:
            messages.warning(
                request, err.messages)
            return render(request, 'customer_app/form_take_a_loan.html', context)
    else:
        return render(request, 'customer_app/form_take_a_loan.html', context)

def form_transfer_money(request):
    accounts = Account.objects.filter(
        user_id=request.user, account_type="standard")
    context = {
        'accounts': accounts
    }

    if request.method == "POST":
        standard_account_number = request.POST['standard_account_number']
        receiver_account_number = request.POST['receiver_account_number']
        bank_code = request.POST['bank_code']
        standard_account = get_object_or_404(
            Account, account_number=standard_account_number)
        if(bank_code == "10"):
            print("internal")
            receiver_account = get_object_or_404(
                Account, account_number=receiver_account_number)
        else:
            print("external")
            receiver_account = get_object_or_404(
                Account, account_number=28694578)

        description = request.POST['description']
        amount = request.POST['amount']
        try:
            transaction = Transaction()
            transaction.transfer(
                standard_account, receiver_account, description, Decimal(amount), is_loan=False)
            messages.success(request, "Transfer successful.")
            channel_layer = get_channel_layer()
            # Pass any data based on your requirement
            data = "You have just received money from " + standard_account.user_id.username
            # Trigger message sent to group
            print(receiver_account.user_id.pk)
            async_to_sync(channel_layer.group_send)(
                # Group Name, Should always be string
                str(receiver_account.user_id.pk),
                {
                    "type": "notifyAboutTransfer",   # Custom Function written in the consumers.py
                    "text": data,
                },
            )
            return HttpResponseRedirect(reverse('customer_app:view_my_accounts'))
        except ValidationError as err:
            messages.warning(
                request, err.messages)
            return render(request, 'customer_app/form_transfer_money.html', context)

    else:
        return render(request, 'customer_app/form_transfer_money.html', context)

def view_account_details(request, account_id):
    account = Account.objects.filter(id=str(account_id))
    accountTransactions = Transaction.objects.select_related().filter(
        account_id=str(account_id))
    accountBalance = Account.objects.filter(user_id=request.user, id=account_id).annotate(
        ammount=Sum('transaction__ammount'))
    context = {
        'account': account,
        'accountBalance': accountBalance,
        'accountTransactions': accountTransactions
    }

    return render(request, 'customer_app/view_account_details.html', context)

def view_my_accounts(request):
    bankAccounts = Account.objects.filter(user_id=request.user).annotate(
        ammount=Sum('transaction__ammount'))
    context = {
        'bankAccounts': bankAccounts

    }
    # print(request.user)
    return render(request, 'customer_app/view_my_accounts.html', context)

def view_profile(request):
    customer = User.objects.filter(username=request.user)
    phone_number = UserProfile.objects.get(user=request.user).phone_number
    user_rank = UserProfile.objects.get(user=request.user).user_type.text
    context = {
        'customer': customer,
        'phone_number': phone_number,
        'user_rank': user_rank
    }
    return render(request, 'customer_app/view_profile.html', context)

def access_denied(request):
    return render(request, 'customer_app/access_denied.html')


class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        result=[]
        for i in range(2**len(nums)):
            temp=[]
            i1=i
            for j in range(len(nums)):
                if i1%2==1:
                    temp.append(nums[j])
                i1=i1//2
            result.append(temp)
        return result


# tf 1.14版本以上
import tensorflow as tf

in_path = "/home/fengshijia/mars(1).pb"
out_path = "/home/fengshijia/mars(1).tflite"

input_tensor_name = ["images"]
input_tensor_shape = {"images":[1,128,64,3]}

#classes_tensor_name = ['lambda_1/box', 'lambda_1/scores', 'lambda_1/class']
classes_tensor_name = ["features"]

converter = tf.lite.TFLiteConverter.from_frozen_graph(in_path,
                                            input_tensor_name, classes_tensor_name,
                                            input_shapes = input_tensor_shape)
#input_shapes = input_tensor_shape

#converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS,tf.lite.OpsSet.SELECT_TF_OPS]
tflite_model = converter.convert()

with open(out_path, "wb") as f:
    f.write(tflite_model)


import os
from typing import Iterator
import pytest
import tempfile

import dlt
from dlt.common.runners import Venv
from dlt.common.schema.schema import Schema
from dlt.common.utils import uniq_id
from dlt.helpers.dbt import create_venv
from dlt.helpers.dbt.exceptions import DBTProcessingError, PrerequisitesException

from tests.load.pipeline.utils import select_data
from tests.utils import ACTIVE_SQL_DESTINATIONS
from tests.load.pipeline.utils import destinations_configs, DestinationTestConfiguration

# uncomment add motherduck tests
# NOTE: the tests are passing but we disable them due to frequent ATTACH DATABASE timeouts
# ACTIVE_DESTINATIONS += ["motherduck"]

@pytest.fixture(scope="module")
def dbt_venv() -> Iterator[Venv]:
    # context manager will delete venv at the end
    # yield Venv.restore_current()
    with create_venv(tempfile.mkdtemp(), list(ACTIVE_SQL_DESTINATIONS)) as venv:
        yield venv

@pytest.mark.parametrize("destination_config", destinations_configs(default_sql_configs=True), ids=lambda x: x.name)
def test_run_jaffle_package(destination_config: DestinationTestConfiguration, dbt_venv: Venv) -> None:
    if destination_config.destination == "athena":
        pytest.skip("dbt-athena requires database to be created and we don't do it in case of Jaffle")
    pipeline = destination_config.setup_pipeline("jaffle_jaffle", full_refresh=True)
    # get runner, pass the env from fixture
    dbt = dlt.dbt.package(pipeline, "https://github.com/dbt-labs/jaffle_shop.git", venv=dbt_venv)
    # no default schema
    assert pipeline.default_schema_name is None
    # inject default schema otherwise dataset is not deleted
    pipeline._inject_schema(Schema("default"))
    # run the package (clone/pull repo, deps, seed, source tests, run)
    models = dbt.run_all()
    # all models were executed
    assert len(models) == 5
    assert all(r.status == "success" for r in models)
    # test the models
    tests = dbt.test()
    assert len(tests) == 20
    assert all(r.status == "pass" for r in tests)

    # get and display dataframe with customers
    customers = select_data(pipeline, "SELECT * FROM customers")
    assert len(customers) == 100
    orders = select_data(pipeline, "SELECT * FROM orders")
    assert len(orders) == 99

@pytest.mark.parametrize("destination_config", destinations_configs(default_sql_configs=True), ids=lambda x: x.name)
def test_run_chess_dbt(destination_config: DestinationTestConfiguration, dbt_venv: Venv) -> None:
    from docs.examples.chess.chess import chess
    if not destination_config.supports_dbt:
        pytest.skip("dbt is not supported for this destination configuration")

    # provide chess url via environ
    os.environ["CHESS_URL"] = "https://api.chess.com/pub/"

    pipeline = destination_config.setup_pipeline("chess_games", dataset_name="chess_dbt_test", full_refresh=True)
    assert pipeline.default_schema_name is None
    # get the runner for the "dbt_transform" package
    transforms = dlt.dbt.package(pipeline, "docs/examples/chess/dbt_transform", venv=dbt_venv)
    assert pipeline.default_schema_name is None
    # there's no data so the source tests will fail
    with pytest.raises(PrerequisitesException):
        transforms.run_all(source_tests_selector="source:*")
    # load data
    info = pipeline.run(chess(max_players=5, month=9))
    print(info)
    assert pipeline.schema_names == ["chess"]
    # run all the steps (deps -> seed -> source tests -> run)
    # request all the source tests
    transforms.run_all(source_tests_selector="source:*")
    # run all the tests
    transforms.test()
    load_ids = select_data(pipeline, "SELECT load_id, schema_name, status FROM _dlt_loads ORDER BY status")
    assert len(load_ids) == 2
    view_player_games = select_data(pipeline, "SELECT * FROM view_player_games ORDER BY username, uuid")
    assert len(view_player_games) > 0
    # run again
    transforms.run()
    # no new load ids - no new data in view table
    new_load_ids = select_data(pipeline, "SELECT load_id, schema_name, status FROM _dlt_loads ORDER BY status")
    new_view_player_games = select_data(pipeline, "SELECT * FROM view_player_games ORDER BY username, uuid")
    assert load_ids == new_load_ids
    assert view_player_games == new_view_player_games

@pytest.mark.parametrize("destination_config", destinations_configs(default_sql_configs=True), ids=lambda x: x.name)
def test_run_chess_dbt_to_other_dataset(destination_config: DestinationTestConfiguration, dbt_venv: Venv) -> None:
    from docs.examples.chess.chess import chess
    if not destination_config.supports_dbt:
        pytest.skip("dbt is not supported for this destination configuration")

    # provide chess url via environ
    os.environ["CHESS_URL"] = "https://api.chess.com/pub/"

    pipeline = destination_config.setup_pipeline("chess_games", dataset_name="chess_dbt_test", full_refresh=True)
    # load each schema in separate dataset
    pipeline.config.use_single_dataset = False
    # assert pipeline.default_schema_name is None
    # get the runner for the "dbt_transform" package
    transforms = dlt.dbt.package(pipeline, "docs/examples/chess/dbt_transform", venv=dbt_venv)
    # assert pipeline.default_schema_name is None
    # load data
    info = pipeline.run(chess(max_players=5, month=9))
    print(info)
    assert pipeline.schema_names == ["chess"]
    # store transformations in alternative dataset
    test_suffix = "alt"
    # inject the schema for test_suffix. due to use_single_dataset = False, we are able to create a sql client for it and the dataset
    # will clean up automatically
    pipeline._inject_schema(Schema(test_suffix))
    transforms.run_all(destination_dataset_name=info.dataset_name + "_" + test_suffix)
    # run all the tests on original dataset which will fail
    with pytest.raises(DBTProcessingError):
        transforms.test()
    # run tests on destination dataset where transformations actually are
    transforms.test(destination_dataset_name=info.dataset_name + "_" + test_suffix)
    # get load ids from the source dataset
    load_ids = select_data(pipeline, "SELECT load_id, schema_name, status FROM _dlt_loads ORDER BY status")
    assert len(load_ids) == 1
    # status is 0, no more entries
    assert load_ids[0][2] == 0
    # get from destination dataset
    load_ids = select_data(pipeline, "SELECT load_id, schema_name, status FROM _dlt_loads ORDER BY status", schema_name=test_suffix)
    # TODO: the package is not finished, both results should be here
    assert len(load_ids) == 1
    # status is 1, no more entries
    assert load_ids[0][2] == 1


import cv2
import numpy as np
from matplotlib import pyplot as plt
import subprocess

FILE = r"C:\Users\coff-\OneDrive\デスクトップ\Hack\水着1.jpg"
CASCADE = r"C:\Users\coff-\OneDrive\デスクトップ\Hack\haarcascades\haarcascade_frontalface_alt.xml"

img = cv2.imread(FILE)
#画像の高さ
height = img.shape[0]
#画像の幅
width = img.shape[1]
# 画像サイズを取得
print(f"height:{height}, width:{width}")

cv2.putText(img,
            "Hello Python",
            org=(200, 50),
            fontFace=cv2.FONT_HERSHEY_DUPLEX,
            fontScale=1.5,
            color=(0, 255, 0),
            thickness=2,
            lineType=cv2.LINE_AA)

color = ("b", "g", "r")
for i, col in enumerate(color):
    histr = cv2.calcHist(images=[img], channels=[i],
     mask=None, histSize=[256], ranges=[0, 256])
    plt.plot(histr, color=col)
    plt.xlim([0, 256])
plt.show()

# 画像をトリミング
#trim = img[200: 500, 300: 600]
#cv2.imwrite(r"C:\Users\coff-\OneDrive\デスクトップ\Hack\trim.jpg", trim)

#resize = cv2.resize(img, dsize=(200, 200))
#resize = cv2.resize(img, dsize=None, fx=1, fy=0.5)

# 画像処理のノイズ除去のため一旦グレースケールに変更
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#グレースケールの表示
#cv2.imshow('img', gray)
#cv2.waitKey(0)

#学習済みモデルの読み込み
cascade = cv2.CascadeClassifier(CASCADE)
# 顔の検出
# minSizeで最小検出サイズを指定（今回は20*20以下は探さない）
face = cascade.detectMultiScale(gray, minSize = (20, 20))

# 白黒に変換
#ret, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY_INV)
#cv2.imwrite(r"C:\Users\coff-\OneDrive\デスクトップ\Hack\change1.png", thresh)

# 輪郭検出
#img, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#cv2.drawContours(img, contours, -1, (0, 0, 255), 10)
#cv2.imwrite(r"C:\Users\coff-\OneDrive\デスクトップ\Hack\change2.png", img)

# 円を検出
#circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=0.8, minDist=50, param1=100, param2=60, minRadius=0, maxRadius=0)
# numpyを用いて描画できる形に変換
#circles = np.uint16(np.around(circles))

# 円が見つかるかで条件分岐
#if len(circles):
    #for circle in circles[0, :]:
    # 円周を描画
        #cv2.circle(img, (circle[0], circle[1]), circle[2], (0, 0, 255), 10)

    # 中心点を描画
        #cv2.circle(img, (circle[0], circle[1]), 2, (0, 0, 255), 5)

    #cv2.imshow('img', img)
    #cv2.waitKey(0)

#else:
    #print('見つかりませんでした')

# 顔が見つかるかで条件分岐
if len(face):
    for (x,y,w,h) in face:
        # 顔が見つかった場合赤い四角で囲う
        print('見つけました')
        cv2.rectangle(img, (x,y), (x+w, y+h), (0, 0, 255), thickness=3)
    cv2.imshow('img', img)
    cv2.waitKey(0)

# 顔が見つからなかった場合
else:
    print('見つかりませんでした')

#cv2.imshow('imshow_test', gray)
#cv2.waitKey(0) #待機時間、ミリ秒指定、0の場合はボタンが押されるまで待機
#cv2.destroyWindows()
#cv2.waitKey(1) #待機時間、ミリ秒指定、0の場合はボタンが押されるまで待機


from tkinter import *
from tkinter import ttk

ventana = Tk()
ventana.title("Calculadora2")
ventana.configure(bg="#F3C7AA")
ventana.configure(cursor="pencil")
ventana.geometry('460x150')
style = ttk.Style()
style.configure("Transparent.TLabel", background=ventana["bg"])

def count_up():
    current_value = int(num.get())
    new_value = current_value + 1
    num.config(state=NORMAL)
    num.delete(0, END)
    num.insert(0, new_value)
    num.config(state="readonly")

def count_down():
    current_value = int(num.get())
    new_value = current_value - 1
    num.config(state=NORMAL)
    num.delete(0, END)
    num.insert(0, new_value)
    num.config(state="readonly")

def reset_counter():
    num.config(state=NORMAL)
    num.delete(0, END)
    num.insert(0, 0)
    num.config(state="readonly")

cont = ttk.Label(ventana, text="Contador", width=10, style="Transparent.TLabel")
cont.grid(row=1, column=1, padx=10, pady=50)

num = ttk.Entry(ventana, width=15)
num.insert(END, "0")
num.grid(row=1, column=2)
num.config(state="readonly")

countup = Button(ventana, text="CountUp", width=10, command=count_up).grid(row=1, column=3, pady=(10, 0), padx=(10, 10), sticky=W+E)
countdown = Button(ventana, text="CountDown", width=10, command=count_down).grid(row=1, column=4, pady=(10, 0), padx=(0, 10), sticky=W+E)
rest = Button(ventana, text="Rest", width=10, command=reset_counter).grid(row=1, column=5, pady=(10, 0), padx=(0, 10), sticky=W+E)

ventana.mainloop()