import cv2
import tensorflow as tf
import numpy as np
from moviepy.video.io import ImageSequenceClip
import os

model = tf.keras.models.load_model('U-Net.h5', compile=False)
os.makedir('frames')

def vidGen(vid_path):
    video = cv2.VideoCapture(vid_path)
    success = 1
    fps = video.get(cv2.CAP_PROP_FPS)
    width  = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    count = 0
    img_files = []
    while success:
        count+=1
        success, image = video.read()
        if success:
            image_shape = image.shape
            image = transform(image)
            img_files.append(segmentFn(image, image_shape, count))

    video.release()
    image_folder = 'frames'
    clip = ImageSequenceClip.ImageSequenceClip(img_files,fps=fps)
    clip.write_videofile('output_video.mp4')

def transform(image):
    image = cv2.resize(image,dsize=(256,256))
    image = image.astype('float32')
    image /= 255.0
    return image

def apply_mask(img_pot, mask_pot):
    img = img_pot*255
    m = mask_pot[:,:,1]
    m = m>=0
    m = m.astype('int32')
    img[:,:,2] = cv2.add(img_pot[:,:,2], mask_pot[:,:,1]*255)
    return img

def segmentFn(image, image_shape, count):
    img_arr = np.array([image])
    mask = model.predict(img_arr)
    seg_img = apply_mask(image, mask[0])
    seg_img = cv2.resize(seg_img, dsize=(image_shape[1],image_shape[0]))
    cv2.imwrite('frames/Frame' + str(count) + '.jpg', seg_img)
    return 'frames/Frame' + str(count) + '.jpg'

if __name__=='__main__':
    vidGen('input_video.mp4')


import discord
from discord.ext import commands
from yuki import color as ykColor
import yuki

import time
import aiohttp
import random

import json
from base64 import b64decode

class Utilities:
    def __init__(self, bot):
        self.bot = bot

        self.ping_emoji = u"\U0001F3D3"
        # self.ping_emoji = "\N{TABLE TENNIS PADDLE AND BALL}"
        self.answers = (
            "Very doubtful",
            "Most likely no",
            "Perhaps",
            "Definitely no",
            "Not sure",
            "No",
            "NO - It may cause disease contraction",
            "Nope",
            "Don't even think about it",
            "Don't count on it",

            "It is uncertain",
            "Ask again later",

            "Yes",
            "Of course!",
            "Perhaps",
            "My sources say yes"
        )

    @commands.command(aliases = [u"\U0001f3d3"])
    async def ping(self, ctx):
        """Outputs the bot's ping."""

        t1 = time.perf_counter()
        await ctx.trigger_typing() # Tell Discord that the bot is typing.
        t2 = time.perf_counter()
        time_delta = abs(round((t1 - t2) * 1000, 2)) # Calculate the time.

        await ctx.send(content = f"{self.ping_emoji} Pong! That took **{time_delta} ms**.")

    """@commands.command(aliases = [u"\U0001f3d3"])
    async def ping(self, ctx):
        Outputs the bot's ping.

        start = time.perf_counter()
        message = await ctx.send(f"_{self.pingEmoji}_")
        end = time.perf_counter()
        duration = (end - start) * 1000

        output = "{} Pong! That took **{:.2f} ms**.".format(self.pingEmoji, duration)
        await message.edit(content = output)"""

    @commands.command()
    async def poll(self, ctx, question: str = "What game should we play?", *options: str):
        """Starts a simple poll."""

        # ABCDEFGHI
        letters = (
            u"\U0001F1E6", u"\U0001F1E7", u"\U0001F1E8", u"\U0001F1E9",
            u"\U0001F1EA", u"\U0001F1EB", u"\U0001F1EC", u"\U0001F1ED",
            u"\U0001F1EE"
        )

        mem = ctx.message.author
        if ctx.guild:
            embed_color = mem.top_role.color
        else:
            embed_color = ykColor

        options = ("Fortnite", "PUBG") if options == () else options

        embed = discord.Embed(title = question, color = embed_color)
        embed.set_author(name = str(mem), icon_url = mem.avatar_url)

        for i, option in enumerate(options):
            embed.add_field(name = letters[i], value = option, inline = True)

        msg = await ctx.send(embed = embed)
        for i, option in enumerate(options):
            await msg.add_reaction(letters[i])

    """@commands.command(pass_context = True)
    async def reddit(self, ctx, *, subreddit: str = "examplesubreddit"):
        subreddit = ''.join(subreddit).lower().replace(" ", "_")
        async with aiohttp.ClientSession() as cs:
            async with cs.get(f"https://api.reddit.com/r/{subreddit}/random") as r:
                data = await r.json()

                embed = discord.Embed(title = "T", color = ykColor) # str(data[1]["data"]["children"][0]["data"]["body"])
                embed.set_image(url = data[0]["data"]["children"][0]["data"]["url"])
                embed.set_footer(text = subreddit)

                await ctx.send(embed = embed)"""

    @commands.command(aliases = ["meow", "kitten", "purr", u"\U0001f431", u"\U0001f408"])
    async def cat(self, ctx):
        """Outputs a random cat."""

        async with ctx.typing():
            async with aiohttp.ClientSession() as cs:
                async with cs.get("http://aws.random.cat/meow") as r:
                    data = await r.json()

                    embed = discord.Embed(title = u"Meow \U0001F431", color = ykColor)
                    embed.set_image(url = data["file"])
                    embed.set_footer(text = "http://random.cat/")

                    await ctx.send(embed = embed)

    @commands.command(aliases = ["bark", "puppy", u"\U0001f436", u"\U0001f415"])
    async def dog(self, ctx):
        """Outputs a random dog."""

        async with ctx.typing():
            async with aiohttp.ClientSession() as cs:
                async with cs.get("https://dog.ceo/api/breeds/image/random") as r:
                    data = await r.json()

                    embed = discord.Embed(title = u"Bark \U0001F436", color = ykColor)
                    embed.set_image(url = data["message"])
                    embed.set_footer(text = "https://dog.ceo/dog-api/")

                    await ctx.send(embed = embed)

    @commands.command(aliases = ["choice"])
    async def choose(self, ctx, *, options: commands.clean_content):
        """Chooses an option from a list of options."""

        options_list = ''.join(options).split(',')
        options_list = [option.strip() for option in options_list]
        # fOptionsList = [f"**{option}**" for option in options_list]

        output = "\N{THINKING FACE} From ``{}`` I choose **{}**".format(
            ", ".join(options_list),
            random.choice(options_list)
        )
        await ctx.send(output)

    @commands.command()
    async def shuffle(self, ctx, *, list: commands.clean_content):
        """Shuffles a list of things."""

        shuffled_list = ''.join(list).split(',')
        shuffled_list = [thing.strip() for thing in shuffled_list]
        random.shuffle(shuffled_list)

        output = "``{}`` \N{BLACK RIGHTWARDS ARROW} ``{}``".format(
            list,
            ", ".join(shuffled_list)
        )
        await ctx.send(output)

    @commands.command()
    async def sort(self, ctx, *, list: commands.clean_content):
        """Sorts a list of things in alphabetic order."""

        sorted_list = ''.join(list).split(',')
        sorted_list = [thing.strip() for thing in sorted_list]
        sorted_list.sort()

        output = "``{}`` \N{BLACK RIGHTWARDS ARROW} ``{}``".format(
            list,
            ", ".join(sorted_list)
        )
        await ctx.send(output)

    @commands.command()
    async def quote(self, ctx):
        """Outputs a random quote."""

        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://talaikis.com/api/quotes/random/") as r:
                data = await r.json()

                embed = discord.Embed(title = data["author"], description = data["quote"], color = ykColor)
                embed.set_footer(text = "https://talaikis.com/api/")

                await ctx.send(embed = embed)

    @commands.command(aliases = ["die", u"\U0001F3B2"])
    async def dice(self, ctx):
        """Rolls a dice."""

        a = random.randint(1, 6)
        b = '!' if a == 6 else '.'

        file = discord.File(f"assets/dice/{a}.png", filename = "dice.png")
        embed = discord.Embed(title = u"\U0001F3B2" + f" You rolled a {a}{b}", color = discord.Color.blurple())
        embed.set_image(url = "attachment://dice.png")

        await ctx.send(embed = embed, file = file)

    @commands.command(aliases = ["skin"])
    async def mcskin(self, ctx, username: str = "Steve"):
        """Gets a Minecraft skin."""

        async with ctx.typing():
            async with aiohttp.ClientSession() as cs:
                async with cs.get(f"https://api.mojang.com/users/profiles/minecraft/{username}") as r:
                    try:
                        data = await r.json()
                    except:
                        await yuki.send_error("Minecraft user doesn't exist!", ctx)
                        return

                    uuid = data["id"]
                    name = data["name"]

                async with cs.get(f"https://sessionserver.mojang.com/session/minecraft/profile/{uuid}") as r:
                    data1 = await r.json()

                    value = data1["properties"][0]["value"]
                    skinURL = json.loads(b64decode(value))["textures"]["SKIN"]["url"]

            embed = discord.Embed(title = f"{name}'s Skin", color = ykColor)
            embed.set_image(url = skinURL)

            await ctx.send(embed = embed)

    @commands.command(aliases = ["bc", "bcp", "bitcoinprice"])
    async def bitcoin(self, ctx):
        """Outputs the current Bitcoin price."""

        bc_logo = "https://raw.githubusercontent.com/roslinpl/bitcoin.it-promotional_graphics/master/bitcoinLogo1000.png"

        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://api.coindesk.com/v1/bpi/currentprice.json") as r:
                data = json.loads(await r.content.read())

        usd = data["bpi"]["USD"]["rate"]
        gbp = data["bpi"]["GBP"]["rate"]
        eur = data["bpi"]["EUR"]["rate"]

        embed = discord.Embed(title = "", color = 0xf7931a)
        embed.set_author(
            name = "Current Bitcoin Price",
            url = "https://www.coindesk.com/price/",
            icon_url = bc_logo
        )

        embed.add_field(name = "United States Dollar", value = f"$ {usd}")
        embed.add_field(name = "British Pound Sterling", value = f"£ {gbp}")
        embed.add_field(name = "Euro", value = f"€ {eur}")
        embed.set_footer(text = "Powered by CoinDesk")

        await ctx.send(embed = embed)

    @commands.command(name = "8ball", aliases = ["ask", u"\U0001f3b1"])
    async def ask(self, ctx, *, text: str):
        """Ask the 8-ball questions."""

        if ''.join(text).endswith('?'):
            answer = random.choice(self.answers)
        else:
            answer = "Ask me something next time"

        embed = discord.Embed(color = ykColor)
        embed.set_author(name = "8-ball") # "https://image.ibb.co/drgwj8/8ball.png"
        embed.set_thumbnail(url = "https://image.ibb.co/drgwj8/8ball.png")
        embed.add_field(name = u"\U00002753 Question", value = ''.join(text), inline = False)
        embed.add_field(name = u"\U0001f3b1 Answer", value = answer, inline = True)
        embed.set_footer(text = "Put a ? for it to count as a question!")

        # await ctx.send(u"\U0001F3B1" + f" The 8-ball said ``{answer}``")
        await ctx.send(embed = embed)

    @commands.command(aliases = ["pm"])
    async def dm(self, ctx, user: discord.User = None, *, text: str):
        """DMs text to the user."""

        # await member.send(''.join(text))
        msg_author = ctx.author

        embed = discord.Embed(
            title = "",
            description = ''.join(text),
            color = ykColor
        )
        embed.set_author(
            name = str(msg_author),
            icon_url = msg_author.avatar_url
        )
        embed.set_footer(text = f"User ID: {msg_author.id}")

        await user.send(embed = embed)
        await ctx.message.add_reaction(u"\u2705")
        # else:
        #     await ctx.message.add_reaction(self.bot.get_emoji(465215264439664650))

    @commands.command(aliases = ["plus", "\U00002795"])
    async def sum(self, ctx, *numbers: float):
        """Adds numbers together."""

        numbers = (3, 6) if numbers == () else numbers

        """
        nums = []
        for num in numbers:
            if num % 1 == 0: # If it ends with .0
                nums.append(int(num))
            else:
                nums.append(num)
        """

        # Get rid of .0
        nums = [int(num) if num % 1 == 0 else num for num in numbers]
        # Make every number a bold string
        f_numbers = [f"**{num}**" for num in nums]

        output = "{} = __**{}**__".format(" + ".join(f_numbers), sum(nums))

        await ctx.send(output)

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


import tensorflow as tf
import pathlib
import os
data_dir = pathlib.Path(os.path.abspath('webs/static/ImageToTrain'))

#Tạo tập dữ liệu
batch_size =3
img_height=224
img_width=224

#Chỉ dùng 80% hình ahr để đào tạo và 20% hình ảnh để xác thực
train_ds=tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="training",
    seed=123,
    image_size=(img_height,img_width),
    batch_size=batch_size
)
val_ds=tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size
)
class_names=train_ds.class_names


from .utils import timestamps_collection, validate_publication_date, calculate_difference, timestamps_to_format, categorize_in_time_buckets

def calculate_historical_distance(iterable_of_nafs,
                                    event_date,
                                    time_buckets,
                                    xlsx_path=None,
                                    output_folder=None,
                                    start_from_scratch=True):
    '''
    provides the spread of historical distance in days for a corpus of reference texts
    :param path_to_nafs: path to a directory containing a collection of naf files
    :param event_date: the date of the event (YY-MM-DD)
    :param filename: name.type for the output table
    :type iterable_of_nafs: list
    :type event_date: datetime.datetime
    '''
    timestamps = timestamps_collection(collection=iterable_of_nafs)
    known_timestamps, unknown_timestamps = validate_publication_date(event_date=event_date,
                                                                    timestamps=timestamps)
    known_distance = calculate_difference(list_of_timestamps=known_timestamps,
                                                event_date=event_date)
    known_distance_time_buckets = categorize_in_time_buckets(known_distance=known_distance,
                                                            time_buckets=time_buckets)
    df = timestamps_to_format(known_timestamps=known_distance_time_buckets,
                            unknown_timestamps=unknown_timestamps,
                            xlsx_path=xlsx_path,
                            output_folder=output_folder,
                            start_from_scratch=start_from_scratch)
    return df


#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import matplotlib.pyplot as plt
import numpy as np

# def plotData(x, y):
#     """The following function plots the previously pulled data"""
#     try:
#         plt.plot(x,y,linewidth=0.5)
#         plt.title('Radiation Counts', fontsize=18)
#         plt.xlabel('Channel', fontsize=15)
#         plt.ylabel('Counts', fontsize=15)

#         # storename  = datetime.now().time().strftime('%H%M%S%f')

#         # plt.savefig('Test_Data/'+str(storename)+'.png')

#         plt.show(block = False)

#     except Exception:
#         print('error in file plot')

# def callback(data):
#     channels = []
#     counts = []
#     measurements = data.data.split("%")
#     for i in range(0, len(measurements) - 1):
#         single_data =  measurements[i].split("#")
#         print(single_data)
#         channels.append(float(single_data[0]))
#         counts.append(float(single_data[1]))

#     # plotData(np.array(channels), np.array(counts))
#     plt.plot(np.array(channels),np.array(counts),linewidth=0.5)

# def plotter():

#     plt.title('Radiation Counts', fontsize=18)
#     plt.xlabel('Channel', fontsize=15)
#     plt.ylabel('Counts', fontsize=15)
#     plt.show()

#     rospy.init_node('plotter', anonymous=True)

#     rospy.Subscriber("radiation_sensor", String, callback)

#     # spin() simply keeps python from exiting until this node is stopped
#     rospy.spin()

class RadiationSensorPlotter:
    def __init__(self):
        # self.measurements = []
        self.channels = []
        self.counts = []
        self.fig, self.ax = plt.subplots()

    def radiation_sensor_callback(self, msg):
        # Split the string into a list of measurements
        self.channels = []
        self.counts = []
        measurements = msg.data.split("%")
        for i in range(0, len(measurements) - 1):
            single_data =  measurements[i].split("#")
            # print(single_data)
            self.channels.append(float(single_data[0]))
            self.counts.append(float(single_data[1]) * 0.499)

        # Update the measurements and plot the new data
        self.ax.clear()
        # self.ax.plot(self.channels,self.counts,linewidth=0.5)
        self.ax.bar(self.channels,self.counts)
        self.ax.set_xlim(0,2000)
        self.ax.set_xlabel('Energy (keV)', fontsize=15)
        self.ax.set_ylabel('Counts', fontsize=15)
        self.ax.set_title('Radiation Counts', fontsize=18)

        # Draw the plot
        self.fig.canvas.draw()

    def run(self):
        rospy.init_node('radiation_sensor_plotter')

        # Subscribe to the radiation_sensor topic
        rospy.Subscriber('radiation_sensor', String, self.radiation_sensor_callback)

        plt.show()

if __name__ == '__main__':
    node = RadiationSensorPlotter()
    node.run()


# @Version : Python3.6
# @Time    : 2018/9/10 17:34
# @Author  : zhcf1ess
# @Site    :
# @File    : 估计线性模型.py
# @Software: PyCharm

import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

def dnorm(mean, variance, size=1):
    if isinstance(size, int):
        size = size
    return mean + np.sqrt(variance) * np.random.randn(size)

np.random.seed(1234)

N = 100
X = np.c_[dnorm(0, 0.4, size=N), dnorm(0, 0.6, size=N), dnorm(0, 0.2, size=N)]

eps = dnorm(0, 0.1, size=N)

beta = [0.1, 0.3, 0.5]

y = np.dot(X, beta) + eps

# print(X[:5])
# print("============================================")
# print(y[:5])

# sm.add_constant(X)  添加一个截距到矩阵
# X_model = sm.add_constant(X)
# print(X_model)
model = sm.OLS(y, X)
result = model.fit()
# print(result.params)
# print(result.summary())
data = pd.DataFrame(X, columns=['col0', 'col1', 'col2'])
data['y'] = y
# print(data[:5])
results = smf.ols('y ~  col0  +  col1  +  col2', data=data).fit()
# print(results.params)
# print(results.tvalues)
print(result.predict(data[:5]))

notebook/第 13 章  Python 建模库介绍模库/13.3  statsmodels/估计线性模型.py


import time

import cv2

def load_images(images_path_list, size=None, gray=True, print_data=False):
    """
    for each image: resize image and convert to gray scale
    :param print_data: print duration data (default is false)
    :param gray: convert to gray or not
    :param size: size of image - image will be sized: (size x size)
    :param images_path_list: images list (full path) to load
    :return: image list
    """

    start = time.time()

    ims = []
    for image_path in images_path_list:
        im = load_image(image_path, size, gray, print_data)
        if im is not None:
            ims.append(im)

    if print_data:
        print('> Loading images took: %.2f seconds' % (time.time() - start))

    return ims

def load_image(image_path, size=None, gray=True, print_data=False):
    """
    load image: resize image and convert to gray scale
    :param print_data: print duration data (default is false)
    :param gray: convert to gray or not
    :param size: size of image - image will be sized: (size x size)
    :param image_path: images list (full path) to load
    :return: image
    """

    start = time.time()
    im = None
    try:
        if gray:
            im = cv2.imread(image_path, 0)
        else:
            im = cv2.imread(image_path)
        im = my_resize(im, size, size)
    except Exception as e:
        print('Error while reading image!Path= %s\nError= %s' % (image_path, str(e)))

    if print_data:
        print('Loading image took: %.2f seconds' % (time.time() - start))

    return im

def my_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    """
    Resize image
    :param image: the image
    :param width: new width
    :param height: new height
    :param inter: cv2 interpolation
    :return: the resized image
    """

    if width is None or height is None:
        return image

    # resize the image
    resized = cv2.resize(image, (width, height), interpolation=inter)

    # return the resized image
    return resized


import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

tarpath = r"5.27/maker.liquidation.surplus.20220403.csv"

def read():
        tarFile = pd.read_csv(tarpath)
        return tarFile

def dataProcess():
    target: pd.Series = read()
    features: list = [pd.to_datetime(target.deal_time, format='%m/%d/%Y %H:%M:%S').dt.strftime("%Y-%m-%d"),
                      pd.to_datetime(target.kick_time, format='%m/%d/%Y %H:%M:%S').dt.strftime("%Y-%m-%d"),
                      pd.to_datetime(target.tend_time, format='%m/%d/%Y %H:%M:%S').dt.strftime("%Y-%m-%d")]
    return target.bid_price_unit_of_mkr, features

def plotdrawing_Days():
    Pbid, features = dataProcess()
    features = pd.DataFrame(features).T
    frequency = [features[item].value_counts().sort_index() for item in features]
    x = frequency[0].index.values.tolist()
    x = [pd.to_datetime(items, format="%Y-%m-%d") for items in x]
    x1 = frequency[1].index.values.tolist()
    x1 = [pd.to_datetime(items, format="%Y-%m-%d") for items in x1]
    x2 = frequency[2].index.values.tolist()
    x2 = [pd.to_datetime(items, format="%Y-%m-%d") for items in x2]
    frequency = [features[item].value_counts().sort_index().to_numpy().astype(int) for item in features]
    plt.figure(figsize=(10, 10))
    plt.plot(x, frequency[0], color='lightcoral')
    plt.plot(x1, frequency[1], color="royalblue")
    plt.plot(x2, frequency[2], color="forestgreen")
    plt.legend(["Kick", "Tend", "Deal"])
    print(frequency)
    plt.show()

def plotDraw_Months():
    Pbid, features = dataProcess()
    features = [pd.to_datetime(item, format="%Y-%m-%d").dt.strftime("%y-%m") for item in features]
    # ---------------for pbid----merged with kick_time----------------------------
    Pbid = pd.concat([Pbid, features[1]], axis=1)
    Pbid.set_index("kick_time", drop=True, inplace=True)
    result = Pbid.groupby(level=0).sum()
    # -----Hence we get sum of price every month(only suit for kick time) -------------------------
    features = pd.DataFrame(features).T
    frequency = [features[item].value_counts().sort_index() for item in features]
    # x = frequency[0].index.values.tolist()
    x1Index = frequency[1].index.values.tolist()
    # x2 = frequency[2].index.values.tolist()
    width = 0.2
    x = [item - width for item in range(len(frequency[1]))]
    x1 = [item for item in range(len(frequency[1]))]
    x2 = [item + width for item in range(len(frequency[1]))]
    frequency = [features[item].value_counts().sort_index().to_numpy().astype(int) for item in features]
    # just show the trend
    avg = result["bid_price_unit_of_mkr"].div(frequency[1]) * 20
    fig, ax = plt.subplots()
    # fig(figsize=(10, 10))
    ax.bar(x, frequency[0], width, color='tomato')
    ax.bar(x1, frequency[1], width, color="slateblue")
    ax.bar(x2, frequency[2], width, color="forestgreen")
    ax.plot(x1Index, avg, color="darkorange", marker="o", linestyle="dashed")
    plt.legend(["Avg Monthly Price", "Deal", "Kick", "Tend"])
    plt.show()

plotDraw_Months()
#plotdrawing_Days()


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

class BasicConv2d(nn.Module):
    def __init__(self, n_channels, out_channels, kernel_size, stride=1, padding=0):
        super(BasicConv2d, self).__init__()
        self.bc = nn.Sequential(
            nn.Conv2d(n_channels, out_channels, kernel_size, stride, padding),
            nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True),
            nn.ReLU(inplace=True),
        )

    def forward(self, x):
        x = self.bc(x)
        return x

class Attention(nn.Module):
    """input_channels, out_channels"""

    def __init__(self, in_channels, out_channels):
        super(Attention,self).__init__()

        sub_channels = int(out_channels / 4)
        self.q = BasicConv2d(in_channels, sub_channels, 1)
        self.k = BasicConv2d(in_channels, sub_channels, 1)
        self.v = BasicConv2d(in_channels, out_channels, 3 , padding=1)
        self.psi = nn.Sequential(
            nn.ReLU(inplace=True),
            BasicConv2d(sub_channels, 1, 1),
            nn.Sigmoid()
        )

    def forward(self, x):
        q = self.q(x)
        k = self.k(x)
        v = self.v(x)
        psi = self.psi(q*k)
        out=psi*v

        return out

class DoubleConv(nn.Module):
    """(convolution => [BN] => ReLU) * 2"""

    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.double_conv = nn.Sequential(
            Attention(in_channels, out_channels),
            Attention(out_channels, out_channels)
        )

    def forward(self, x):
        return self.double_conv(x)

class Multiscale(nn.Module):
    def __init__(self, in_channels):
        super(Multiscale, self).__init__()
        sub_channels= int(in_channels/4)
        self.s0 = nn.Sequential(
            nn.Conv2d(in_channels, sub_channels, kernel_size=1, padding=0),
            nn.BatchNorm2d(sub_channels), nn.ReLU(inplace=True))
        self.s1 = nn.Sequential(
            nn.Conv2d(in_channels, sub_channels, kernel_size=3, padding=1),
            nn.BatchNorm2d(sub_channels), nn.ReLU(inplace=True))
        self.s2 = nn.Sequential(
            nn.Conv2d(in_channels, sub_channels, kernel_size=3, padding=3, dilation=3),
            nn.BatchNorm2d(sub_channels), nn.ReLU(inplace=True))
        self.s3 = nn.Sequential(
            nn.MaxPool2d(3, stride=1, padding=1),
            nn.Conv2d(in_channels, sub_channels, kernel_size=1, padding=0),
            nn.BatchNorm2d(sub_channels), nn.ReLU(inplace=True))

    def forward(self, x):
        s0=self.s0(x)
        s1=self.s1(x)
        s2=self.s2(x)
        s3=self.s3(x)
        cats=torch.cat((s0,s1,s2,s3),dim=1)

        return cats

class Down(nn.Module):
    """Downscaling with maxpool then double conv"""

    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.maxpool_conv = nn.Sequential(
            nn.MaxPool2d(2),
            DoubleConv(in_channels, out_channels)
        )

    def forward(self, x):
        return self.maxpool_conv(x)

class Up(nn.Module):
    """Upscaling then double conv"""

    def __init__(self, in_channels, out_channels, bilinear=False):
        super().__init__()

        # if bilinear, use the normal convolutions to reduce the number of channels
        if bilinear:
            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
        else:
            self.up = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2)
        self.ms = Multiscale(out_channels)
        self.conv = DoubleConv(in_channels, out_channels)

    def forward(self, x1, x2):
        x1 = self.up(x1)
        # input is CHW
        diffY = x2.size()[2] - x1.size()[2]
        diffX = x2.size()[3] - x1.size()[3]

        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
                        diffY // 2, diffY - diffY // 2])
        ms = self.ms(x2)
        x = torch.cat([ms, x1], dim=1)
        return self.conv(x)

class OutConv(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(OutConv, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)

    def forward(self, x):
        return self.conv(x)

class MAUnet(nn.Module):
    """ Full assembly of the parts to form the complete network """

    def __init__(self, n_channels, n_classes, bilinear=False):
        super(MAUnet, self).__init__()
        self.name = 'MAUnet'
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.bilinear = bilinear

        self.inc = DoubleConv(n_channels, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        self.down4 = Down(512, 1024)
        self.up1 = Up(1024, 512, bilinear)
        self.up2 = Up(512, 256, bilinear)
        self.up3 = Up(256, 128, bilinear)
        self.up4 = Up(128, 64, bilinear)
        self.outc = OutConv(64, n_classes)

    def forward(self, x):
        x1 = self.inc(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        return logits


import numpy as np
import math
import sympy as sym
from scipy import linalg
from sympy import *

def limits_func_vec(vec, var, val):
    limits = np.array([])
    for i in range(0, len(vec)):
        limits = np.append(limits, sym.limit(vec[i], var, val))
    return limits

def deriv_func_vec(vec, var, num_of_derivs = 1, solve = False, val = None):
    if (solve == False and val == None):
        derivs = np.array([])
        for i in range(0, len(vec)):
            derivs = np.append(derivs, sym.diff(vec[i], var, num_of_derivs))
        return derivs
    else:
        derivs = np.array([])
        for i in range(0, len(vec)):
            derivs = np.append(derivs, sym.diff(vec[i], var, num_of_derivs))
        for i in range(0, len(vec)):
            derivs[i] = derivs[i].subs(var, val)
        return derivs

def integrate_func_vec(vec, var = None, start = None, end = None):
    if (start == None and end == None and var == None):
        integrals = np.array([])
        for i in range(0, len(vec)):
            integrals = np.append(integrals, sym.integrate(vec[i]))
        return integrals
    else:
        integrals = np.array([])
        for i in range(0, len(vec)):
            integrals = np.append(integrals, sym.integrate(vec[i], (var, start, end)))
        return integrals

def gradient_vector(expression):
    syms = [ symb for symb in expression.free_symbols ]
    partials = np.array([])

    for i in range (0, len(syms)):
        partials = np.append(partials, sym.diff(expression, syms[i]))

    return partials


# project started 12/02/2023

#import base64
#code = base64.b64encode(b"""

import tkinter as tk
import json
import time
import random
from items import *

# load and read player save and settings
with open("settings.json", "r") as file:
    settings = json.load(file)

with open("save.json", "r") as file:
    save = json.load(file)

# window initializer

version = "Alpha-0.3" # version of the project
name = "YGGDRASIL"
sizeWnd = "800x600" # window size
frame = tk.Tk()
frame.title(name) # window name display
frame.geometry(sizeWnd)
logged_in = False
loggingLoopId = None

# game var outside the "settings.json" file

chat_history = [] # stores the text displayed on the window
user_last_input = tk.StringVar()
start_time = time.time() # initialization time
end_time = 0

command_list = [
    {
        "name": "craft",
        "info": "Command used for crafting items, add \"custom\" after \"craft\" for creating new items \nCustom syntax: craft custom [name] [lore] [slots] [recipe], instead of spaces use _ to add several items or lore"
    }
]

# TODO:
# 1- Icon for the window
# 2- Crafting system        FINISHED
# 3- Map and map syntax
# 3.5- Goto function

# there goes the functions used through the game

def tgaPrint(msgType=int, msg=str):
    chat_history.append(msg)
    typeTag = "" # typeTag defines which kind of message will be sent
    if msgType == 0: # type 0 for system messages
        typeTag = "SYSTEM"
    if msgType == 1: # type 1 for world notifications
        typeTag = "WORLD"
    text_area.config(state="normal")
    text_area.insert(tk.END, "["+typeTag+"] "+msg+"\n") # print into the text_area the desired message
    text_area.config(state="disabled")

def append_message(Event=None):
    global user_last_input
    user_last_input.set(text_input.get())
    text_input.delete(0, tk.END)

def saveFiles():
    with open("settings.json", "w") as file:
        json.dump(settings, file)

    with open("save.json", "w") as file:
        json.dump(save, file)

def getUserInput(user_input):
    frame.update()
    frame.wait_variable(user_input)

def smooth(number):
    if number == int(number):
        return int(number)
    else:
        return int(number) + 1

def craft_item(item):
    global save
    for ingredient, required_quantity in item.recipe.items():
        if save["inventory"].get(ingredient, 0) < required_quantity:
            tgaPrint(0, "Not enough ingredients")
            return False
    for ingredient, required_quantity in item.recipe.items():
        save["inventory"][ingredient] -= required_quantity
    save["inventory"][item.name] = save["inventory"].get(item.name, 0) + item.quantity
    saveFiles()
    return True

def custom_crafting(custom_name, custom_lore, item_slots, recipe):
    chance = 0
    recipe_items = recipe.split("_")
    for item in recipe_items:
        for item_name in yggdrasil_itemList:
            if item_name.name == item:
                chance += item_name.rarity
    calc_rarity = smooth(chance / len(recipe))
    gen_chance = random.randint(0, 10000)
    new_item = ygg_item(custom_name, custom_lore, item_slots, calc_rarity, None)
    if gen_chance <= smooth(((10000-chance)/100)*100):
        save["inventory"].append(new_item.JSON_serialize())
        tgaPrint(0, "Custom item "+custom_name+" was successfully created")
    else:
        tgaPrint(0, "Custom item "+custom_name+" failed to create")
    print(smooth(((10000-chance)/100)*100), gen_chance)

# there goes the GUI elements

bottom_bar = tk.Frame(frame, bg="grey90", height=20)
bottom_bar.pack(side="bottom", fill="x")

version_display = tk.Label(bottom_bar, text=version)
version_display.config(bd=2, relief="sunken")
version_display.pack(side=tk.LEFT)

text_input = tk.Entry(frame)
text_input.config(bd=1, relief="raised")
text_input.pack(side=tk.BOTTOM, fill=tk.X)
text_input.bind("<Return>", append_message)

text_area = tk.Text(frame, state="disabled")
text_area.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
text_area.config(bg="black", fg="white", bd=1, relief="sunken")

# there goes the game logic (NOT FUNCTIONS)

tgaPrint(0, "Wellcome to YGGDRASIL")

if settings["first_time"] == "True":
    tgaPrint(0, "Log-in, type NEW to create your new game")
    getUserInput(user_last_input)
    command = ((user_last_input.get()).lower()).split(" ")

    if command[0] == "new":

        tgaPrint(0, "Please adventurer, type your name")
        getUserInput(user_last_input)
        save["name"] = user_last_input.get()
        tgaPrint(0, "Be welcome "+save["name"]+" to Yggdrasil, the almighty tree of life and creation!")
        tgaPrint(0, "In this Text Adventure Game you don't have to be a hero to play, but just yourself")
        settings["first_time"] = "False"
        saveFiles()

def gameLoop():
    getUserInput(user_last_input)
    command = ((user_last_input.get()).lower()).split(" ")

    if len(command) < 2:
        command.append("")

    print(command)

    if command[0] == "help":
        tgaPrint(0, "Print commands help, use help [command] or help list to show available commands")
        if command[1] == "list":
            tgaPrint(0, "Craft")
        elif command[1] == "craft":
            for commands in command_list:
                if commands["name"] == "craft":
                    tgaPrint(0, commands["info"])
    elif command[0] == "craft":
        if command[1] == "custom" and len(command) > 1:
            custom_crafting(command[2], command[3], command[4], command[5])
        else:
            tgaPrint(0, "crafting list")
        saveFiles()
    elif command[0] == "goto":
        tgaPrint(0, "goto")

    frame.after(500, gameLoop)

frame.after(500, gameLoop)
frame.mainloop()

#""")
#exec(base64.b64decode(code))


from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import threading
import cv2
from uiwindow import Ui_window
from hrnet.tools import pose
from mmaction2.demo import webcam_demo
from PyQt5 import QtCore
import os
class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        # 从文件中加载UI定义
        # 从 UI 定义中动态 创建一个相应的窗口对象
        flag=0
        self.ui = Ui_window()
        self.ui.setupUi(self)  #画出窗口
        styleFile = os.getcwd() + '\style.qss'
        self.setStyleSheet(str(self.LoadStyleFromQss(styleFile)))
        self.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
        # self.ui.pose.clicked.connect(self.play_video_pose) #拍照识别
        # self.ui.action.clicked.connect(self.play_video_activity)  # 动作识别

        self.ui.pose.clicked.connect(self.modechange(1))  # 拍照识别
        self.thread = None  # 创建线程

    def play_video_pose(self):  #创建线程不断调用摄像头捕捉画面
        self.thread = threading.Thread(target=self.detect)  #线程调用的是detect
        self.thread.start()
        print("线程开启")

    def play_video_activity(self):  #创建线程不断调用摄像头捕捉画面
        self.thread = threading.Thread(target=self.react)  #线程调用的是detect
        self.thread.start()
        print("线程开启")

    def LoadStyleFromQss(self, f):
        file = open(f)
        lines = file.readlines()
        file.close()
        res = ''
        for line in lines:
            res += line
        return res
    # def windowmode(self):

    # def modechange(self):

    def detect(self):
        self.cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 拿到摄像头的流
        while self.cap.isOpened():
            ret, frame = self.cap.read()
            img = pose.main(frame)

            convert_to_qt_format = QImage(img.data, img.shape[1], img.shape[0],
                                          QImage.Format_RGB888)  #转成qt格式！！！！！
            self.ui.show.setPixmap(QPixmap.fromImage(convert_to_qt_format))  #显示
        # self.cap.release()
        cv2.destroyAllWindows()

    def react(self):
        webcam_demo.main()

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助

app = QApplication([])
mainwindow = MainWindow()
mainwindow.show()
app.exec_()


import argparse

import cv2
import geojson
import numpy as np
import pandas as pd

def draw_poly(input_df, input_img, col=(0, 0, 0)):
    s = np.array(input_df)
    output_img = cv2.fillPoly(input_img, pts=np.int32([s]), color=col)
    return output_img

def split_qupath_roi(in_roi):
    with open(in_roi) as file:
        qupath_roi = geojson.load(file)

    # HE dimensions
    dim_plt = [qupath_roi["dim"]["width"], qupath_roi["dim"]["height"]]

    tma_name = qupath_roi["name"]
    cell_types = [ct.rsplit(" - ", 1)[-1] for ct in qupath_roi["featureNames"]]

    for cell_type in cell_types:
        # create numpy array with white background
        img = np.zeros((dim_plt[1], dim_plt[0], 3), dtype="uint8")
        img.fill(255)

        for i, roi in enumerate(qupath_roi["features"]):
            if roi["properties"]["classification"]["name"] == cell_type:
                if len(roi["geometry"]["coordinates"]) == 1:
                    # Polygon w/o holes
                    img = draw_poly(roi["geometry"]["coordinates"][0], img)
                else:
                    first_roi = True
                    for sub_roi in roi["geometry"]["coordinates"]:
                        # Polygon with holes
                        if not isinstance(sub_roi[0][0], list):
                            if first_roi:
                                img = draw_poly(sub_roi, img)
                                first_roi = False
                            else:
                                # holes in ROI
                                img = draw_poly(sub_roi, img, col=(255, 255, 255))
                        else:
                            # MultiPolygon with holes
                            for sub_coord in sub_roi:
                                if first_roi:
                                    img = draw_poly(sub_coord, img)
                                    first_roi = False
                                else:
                                    # holes in ROI
                                    img = draw_poly(sub_coord, img, col=(255, 255, 255))

        # get all black pixel
        coords_arr = np.column_stack(np.where(img == (0, 0, 0)))

        # remove duplicated rows
        coords_arr_xy = coords_arr[coords_arr[:, 2] == 0]

        # remove last column
        coords_arr_xy = np.delete(coords_arr_xy, 2, axis=1)

        # to pandas and rename columns to x and y
        coords_df = pd.DataFrame(coords_arr_xy, columns=['x', 'y'])

        # drop duplicates
        coords_df = coords_df.drop_duplicates(
            subset=['x', 'y'],
            keep='last').reset_index(drop=True)

        coords_df.to_csv("{}_{}.txt".format(tma_name, cell_type), sep='\t', index=False)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Split ROI coordinates of QuPath TMA annotation by cell type (classfication)")
    parser.add_argument("--qupath_roi", default=False, help="Input QuPath annotation (GeoJSON file)")
    parser.add_argument('--version', action='version', version='%(prog)s 0.1.0')
    args = parser.parse_args()

    if args.qupath_roi:
        split_qupath_roi(args.qupath_roi)


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 21:47:51 2023

@author: GolkarE
"""

import nibabel as nib
import numpy as np
import os

from dipy.data import get_sphere
from dipy.reconst import shm
from dipy.direction import peak_directions
import sys

vol= str(sys.argv[1])

#vol = '300-800'
#ext='/noflip'

#ext= '/'+str(sys.argv[1])

path = str(sys.argv[2])
# '/cbica/home/golkare/Data/Multishell3-062'

mask = str(sys.argv[3]) # mask file

lmax = int(sys.argv[4])
sphere = get_sphere(name='symmetric724')

nii = nib.load(mask)
img = nii.get_fdata()
ii= np.where(img==0)

vf_bundle_aniso = np.zeros(img.shape, dtype=np.float)
vf_bundle_iso = np.zeros(img.shape, dtype=np.float)
vf_FW = np.zeros(img.shape, dtype=np.float)
vf_HW = np.zeros(img.shape, dtype=np.float)
vf_intra= np.zeros(img.shape, dtype=np.float)
vf_extra= np.zeros(img.shape, dtype=np.float)
fods = np.zeros((img.shape[0], img.shape[1], img.shape[2], int((lmax+1)*(lmax+2)/2) ), dtype=np.float)
AI= np.zeros(img.shape, dtype=np.float)

#print('img.shape[1]',img.shape[1])

for i in range(1,img.shape[1],1):

    if (os.path.exists(path+'/'+vol + '/results/'+str(i)+'/vf_bundle_aniso.nii.gz') == False):
        continue
    print('vol:',vol,' slice i:',i)
    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_bundle_aniso.nii.gz')
    bundle_aniso = nii.get_fdata()
    vf_bundle_aniso[:,i:i+1,:]=bundle_aniso

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_bundle_iso.nii.gz')
    bundle_iso = nii.get_fdata()
    vf_bundle_iso[:,i:i+1,:]=bundle_iso

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_FW.nii.gz')
    FW = nii.get_fdata()
    vf_FW[:,i:i+1,:]=FW

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_HW.nii.gz')
    HW = nii.get_fdata()
    vf_HW[:,i:i+1,:]=HW

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_intra.nii.gz')
    intra = nii.get_fdata()
    vf_intra[:,i:i+1,:]=intra

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/vf_extra.nii.gz')
    extra = nii.get_fdata()
    vf_extra[:,i:i+1,:]=extra

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/fods.nii.gz')
    fod = nii.get_fdata()
    fods[:,i:i+1,:,:]=fod

    nii = nib.load(path+'/'+vol + '/results/' +str(i)+'/AI.nii.gz')
    ai = nii.get_fdata()
    AI[:,i:i+1,:]=ai

vf_bundle_aniso[ii] = 0
img_vf_bundle_aniso = nib.Nifti1Image(vf_bundle_aniso, nii.affine)
nib.save(img_vf_bundle_aniso,path+'/'+vol+'/results' +'/vf_bundle_aniso.nii.gz')

vf_bundle_iso[ii]=0
img_vf_bundle_iso = nib.Nifti1Image(vf_bundle_iso, nii.affine)
nib.save(img_vf_bundle_iso,path+'/'+vol+'/results/vf_bundle_iso.nii.gz')

vf_FW[ii]=0
img_vf_FW = nib.Nifti1Image(vf_FW, nii.affine)
nib.save(img_vf_FW,path+'/'+vol+'/results' +'/vf_FW.nii.gz')

vf_HW[ii]=0
img_vf_HW = nib.Nifti1Image(vf_HW, nii.affine)
nib.save(img_vf_HW,path+'/'+vol+'/results' +'/vf_HW.nii.gz')

vf_intra[ii]=0
img_vf_intra = nib.Nifti1Image(vf_intra, nii.affine)
nib.save(img_vf_intra,path+'/'+vol+'/results' +'/vf_intra.nii.gz')

vf_extra[ii]=0
img_vf_extra = nib.Nifti1Image(vf_extra, nii.affine)
nib.save(img_vf_extra,path+'/'+vol+'/results' +'/vf_extra.nii.gz')

AI[ii]=0
img_AI = nib.Nifti1Image(AI, nii.affine)
nib.save(img_AI,path+'/'+vol+'/results' +'/AI.nii.gz')

freeWater = np.where(vf_bundle_iso>.9)
listIndex = list(zip(freeWater[0],freeWater[1],freeWater[2]))
index =0
for i in listIndex:
    fods[i[0],i[1],i[2],:] = np.zeros((1, 1, 1, int((lmax+1)*(lmax+2)/2) ), dtype=np.float)
    index +=1

wmfod= np.zeros(fods.shape)
sf = shm.sh_to_sf(fods,sphere,sh_order=lmax,basis_type = 'tournier07')
for i in range(1,img.shape[0],1):
    print ( 'vol: ', vol, ' i:',i )
    for j in range(1,img.shape[1],1):
        for k in range(1,img.shape[2],1):
                ps = peak_directions(sf[i,j,k,:], sphere, relative_peak_threshold=.25)
                if (len(ps[1]) != 0 and ps[1][0]<3.5):
                    wmfod[i,j,k,:] = fods[i,j,k,:]
                if (img[i,j,k] == 0 ):
                    wmfod[i,j,k,:] = np.zeros((1, 1, 1, int((lmax+1)*(lmax+2)/2) ), dtype=np.float)

img_wmfod = nib.Nifti1Image(wmfod, nii.affine)
nib.save(img_wmfod,path+'/'+vol+'/results' +'/fods_lmax'+str(lmax)+'.nii.gz')


from tqdm import tqdm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MultiLabelBinarizer
from python_file.kaggle.predict_winner.params_map import (
    WEAPON_MAP,
    RANK_MAP,
    STAGE_AREA_MAP,
    BUKI_MAP,
)

WEAPONS = [
    "A1-weapon",
    "A2-weapon",
    "A3-weapon",
    "A4-weapon",
    "B1-weapon",
    "B2-weapon",
    "B3-weapon",
    "B4-weapon",
]

WEAPONS_A = [
    "A1-weapon",
    "A2-weapon",
    "A3-weapon",
    "A4-weapon",
]

WEAPONS_B = [
    "B1-weapon",
    "B2-weapon",
    "B3-weapon",
    "B4-weapon",
]

BUKI_RANGE_CATEGORY = {
    "charger": 1,
    "splatling": 1,
    "brush": 0,
    "slosher": 0,
    "maneuver": 0,
    "reelgun": 0,
    "brella": 0,
    "roller": 0,
    "blaster": 0,
    "shooter": 0,
}

class Common:
    def __init__(self):
        ...

    def make_feature(self, df_train, df_test):
        mlb = MultiLabelBinarizer()
        mlb.fit([set(df_train["A4-weapon"].fillna("none").unique())])
        train_num = len(df_train)
        df = pd.concat([df_train, df_test])

        # cat_cols = ["lobby-mode", "mode", "stage"]  # 武器以外のカテゴリ変数
        # for c in cat_cols:
        #     vv, obj = pd.factorize(df[c])  # vv: 数値エンコーディングされた値、obj: 列の種類(unique)
        #     df[c] = vv

        A1 = ["A1-weapon", "A2-weapon", "A3-weapon", "A4-weapon"]
        B1 = ["B1-weapon", "B2-weapon", "B3-weapon", "B4-weapon"]

        t = mlb.transform(df[A1].fillna("none")[A1].values)
        t2 = mlb.transform(df[B1].fillna("none")[B1].values)

        for i in range(t.shape[1]):
            df["A-" + mlb.classes_[i]] = t[:, i]
            df["B-" + mlb.classes_[i]] = t2[:, i]

        s = ["A", "B"]
        p = ["1", "2", "3", "4"]
        for i in s:
            for j in p:
                df[i + j + "-level"] = df[i + j + "-level"] // 10
                df[i + j + "-level"] = df[i + j + "-level"].clip(0, 30)

        return df[:train_num], df[train_num:]

    def trans_weapon(
        self, df, columns=["A1-weapon", "A2-weapon", "A3-weapon", "A4-weapon"]
    ):
        mlb = MultiLabelBinarizer()
        mlb.fit([set(df["A1-weapon"].unique())])
        MultiLabelBinarizer(classes=None, sparse_output=False)

        weapon = df.fillna("none")
        weapon_binarized = mlb.transform(weapon[columns].values)
        return pd.DataFrame(weapon_binarized, columns=mlb.classes_)

    def make_input_output(self, df, with_y=False):
        # a_weapon = trans_weapon(df, ['A1-weapon', 'A2-weapon', 'A3-weapon', 'A4-weapon'])
        a_weapon = self.trans_weapon(df, ["A2-weapon", "A3-weapon", "A4-weapon"])
        b_weapon = self.trans_weapon(
            df, ["B1-weapon", "B2-weapon", "B3-weapon", "B4-weapon"]
        )
        a_weapon = a_weapon.add_suffix("_A")
        b_weapon = b_weapon.add_suffix("_B")
        X = pd.concat([a_weapon, b_weapon], axis=1)
        if with_y:
            y = df["y"]
            return X, y
        return X

    def add_buki_ability(self, df):
        buki_map_title = [
            "get_rank",
            "buki_rank",
            "range",
            "offensive_power",
            "hitting",
            "DPS",
        ]

        dummy_a = df.loc[:, WEAPONS_A].fillna(df.mode().iloc[0])
        dummy_b = df.loc[:, WEAPONS_B].fillna(df.mode().iloc[0])
        weapons_a = pd.DataFrame()
        weapons_b = pd.DataFrame()

        for i in range(len(buki_map_title)):
            buki_map = {k: v[i] for k, v in zip(BUKI_MAP.keys(), BUKI_MAP.values())}
            for name_a, col_a in dummy_a.iteritems():
                weapons_a[f"{name_a}_{buki_map_title[i]}"] = col_a.replace(buki_map)
            for name_b, col_b in dummy_b.iteritems():
                weapons_b[f"{name_b}_{buki_map_title[i]}"] = col_b.replace(buki_map)
        df = pd.concat([weapons_a, weapons_b], axis=1)
        return df.fillna(df.mode().iloc[0])

    # 武器の勝率を計算する。
    def win_rate(self, buki_name, df):
        count = len(df[df[buki_name + "_A"] == 1]) + len(
            df[df[buki_name + "_B"] == 1]
        )  # それぞれのチームで対象ブキが出現する試合数のカウント
        win = len(df[(df[buki_name + "_A"] == 1) & (df.y == 1)]) + len(
            (df[(df[buki_name + "_B"] == 1) & (df.y == 0)])
        )  # それぞれのチームで対象ブキが出現する試合のうち各チームが勝利する試合数のカウント
        rate = win / count
        return rate, count

    # 各チームで使用している武器の勝率の平均値を算出する
    def calc_weapons_win_rate_avg(self, df, win_rate_dict):
        weapons_rate_A = [
            "A1-weapon_win_rate",
            "A2-weapon_win_rate",
            "A3-weapon_win_rate",
            "A4-weapon_win_rate",
        ]
        weapons_rate_B = [
            "B1-weapon_win_rate",
            "B2-weapon_win_rate",
            "B3-weapon_win_rate",
            "B4-weapon_win_rate",
        ]
        for col in df.columns:
            if col in WEAPONS:
                df[f"{col}_win_rate"] = df[col].map(win_rate_dict)  # 各武器の勝率を新特徴量として追加
        df["team_A_win_rate_avg"] = df.loc[:, weapons_rate_A].mean(axis="columns")
        df["team_B_win_rate_avg"] = df.loc[:, weapons_rate_B].mean(axis="columns")
        return df.drop([*weapons_rate_A, *weapons_rate_B], axis=1)  # 平均値のみ特徴量として加える。

    def calc_weapons_win_rate_avg_per_mode(self, df, win_rate_mode_df):
        for mode in df["mode"].unique():
            mode_rate_dict = (
                win_rate_mode_df.loc[:, [f"{mode}_buki", f"{mode}_win_rate"]]
                .set_index(f"{mode}_buki")
                .to_dict()
            )[f"{mode}_win_rate"]
            for col in df.columns:
                if col in WEAPONS:
                    df[f"{col}_win_rate_mode"] = df[col].map(
                        mode_rate_dict
                    )  # 各modeにおける武器の勝率を新特徴量として追加
        return df

    # 各チームにおける遠距離武器人数と近接武器人数の特徴量を追加する(各チーム人数も)。
    def add_count_range_distance(self, df, buki_range_distance_dict):
        buki_category_list = list(set(buki_range_distance_dict.values()))
        count_buki_rangeA = pd.DataFrame()
        count_buki_rangeB = pd.DataFrame()

        teamA_counts = 4 - df.loc[:, WEAPONS_A].isnull().sum(axis=1)
        teamB_counts = 4 - df.loc[:, WEAPONS_B].isnull().sum(axis=1)

        weapons_of_teamA = (
            df.loc[:, WEAPONS_A]
            .replace(buki_range_distance_dict)
            .replace(BUKI_RANGE_CATEGORY)
        ).sum(axis=1)

        count_buki_rangeA["count_long_distance_A"] = weapons_of_teamA
        count_buki_rangeA["count_short_distance_A"] = teamA_counts - weapons_of_teamA
        count_buki_rangeA["count_team_A"] = weapons_of_teamA

        weapons_of_teamB = (
            df.loc[:, WEAPONS_B]
            .replace(buki_range_distance_dict)
            .replace(BUKI_RANGE_CATEGORY)
        ).sum(axis=1)
        count_buki_rangeB["count_long_distance_B"] = weapons_of_teamB
        count_buki_rangeB["count_short_distance_B"] = teamB_counts - weapons_of_teamB
        count_buki_rangeB["count_team_B"] = weapons_of_teamB
        return pd.concat([df, count_buki_rangeA, count_buki_rangeB], axis=1)

    # 各チームのレベル平均,最大値と最小値の差を算出する。
    def calc_team_level_avg(self, df):
        A_level_list = ["A1-level", "A2-level", "A3-level", "A4-level"]
        B_level_list = ["B1-level", "B2-level", "B3-level", "B4-level"]
        df["teamA_level_avg"] = df.loc[:, A_level_list].mean(axis=1)
        df["teamB_level_avg"] = df.loc[:, B_level_list].mean(axis=1)
        df["teamA_lebel_diff"] = df.loc[:, A_level_list].max(axis="columns") - df.loc[
            :, A_level_list
        ].min(axis="columns")
        df["teamB_lebel_diff"] = df.loc[:, B_level_list].max(axis="columns") - df.loc[
            :, B_level_list
        ].min(axis="columns")
        return df

    # 各チームのランク平均を算出する。
    def calc_team_rank_avg(self, df):
        A_rank_list = ["A1-rank", "A2-rank", "A3-rank", "A4-rank"]
        B_rank_list = ["B1-rank", "B2-rank", "B3-rank", "B4-rank"]
        df["teamA_rank_avg"] = df.loc[:, A_rank_list].mean(axis=1)
        df["teamB_rank_avg"] = df.loc[:, B_rank_list].mean(axis=1)
        return df


# GrammarBot v1.0

# Import external dependencies
import discord
import logging
from yaml import load
from sys import exit as sys_exit
from os import startfile

# Import internal dependencies
from src import talk, cli

# Constants
CONFIG = "./data/config.yaml"
PERMS = 3136

# Get arguments form the command line
args = cli.parse()

# Sets up the logging system
logging.basicConfig(level=logging.INFO if args.info else logging.ERROR)
log = logging.getLogger()

# Get setup information from config
try:
    with open(CONFIG, "r") as file:
        try:
            data = load(file.read())
            token = data["token"]
            owner_id = str(data["owner_id"])
        except:
            log.error("Parsing the config.yaml file. Please make sure that it is formatted correctly.")
except:
    log.error("Reading the config.yaml file. Make sure such a file exists.")
    sys_exit()

# Initalise the client
client = discord.Client()
reload = False

# Events

@client.event
async def on_ready():
    global client, log
    print("GrammarBot is ready!")
    id = client.user.id
    print("With the id ~", id)
    print("Link to add the bot to a server")
    print(f"  https://discordapp.com/api/oauth2/authorize?client_id={id}&scope=bot&permissions={PERMS}")
    servers = client.servers
    n = len(servers)
    if n != 0:
        print("On", n, "Servers =>")
        for s in servers:
            print(" ", s.name)
    else:
        print("On no servers")
    print("="*8)
    await client.change_presence(game=discord.Game(name="with the 1%ers", type=1))

@client.event
async def on_message(message):
    msg = message.content.lower()
    ch = message.channel
    if msg.startswith("!ping"):
        await client.send_message(ch, "Pong!")
    elif msg.startswith("!read"):
        await client.send_message(ch, talk.reading())
    elif msg.startswith("!eval"):
        await client.send_message(ch, talk.eval(message.content[5:]))
    elif msg.startswith("!quit"):
        if message.author.id == owner_id:
            print("Exit command called from Discord. Exiting.")
            await client.logout()

# Run the bot
client.run(args.token if (args.token is not None) else token)
# End the bot
sys_exit()


import torch
import torchvision
import torchvision.transforms as transforms

def get_mnist(path: str = './data', batch_size: int = 64):
    transform = transforms.Compose(
        [
            transforms.ToTensor(),
        ]
    )

    trainset = torchvision.datasets.MNIST(root=path, train=True, download=True, transform=transform)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=0)

    testset = torchvision.datasets.MNIST(root=path, train=False, download=True, transform=transform)
    testloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=0)

    return trainset, trainloader, testset, testloader

def get_images_for_class(dataset, num_class):
    return dataset.data[dataset.targets == num_class]

def generate_mean_image(images):
    image_sum = torch.zeros(images[0].size())

    for image in images:
        image_sum += image
    return image_sum / len(images)

def generate_mean_image_for_class(dataset, num_class):
    images = get_images_for_class(dataset, num_class)

    return generate_mean_image(images)

def get_random_image(dataset_loader):
    dataiter = iter(dataset_loader)
    images, labels = dataiter.next()

    image = images[0].expand(1, 1, 28, 28)
    label = labels[0]

    return image, label


from django.conf.urls import include, url
from django.urls import path
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
from rest_framework import routers
from rest_framework_simplejwt import views as jwt_views

from .resources import ObtainTokenPairView, SubscriptionsViewSet, StripeWebookView

router = routers.DefaultRouter()
router.register(r'subscriptions', SubscriptionsViewSet, basename='subscriptions')

urlpatterns = [
    path('token/obtain/', ObtainTokenPairView.as_view(), name='token_create'),
    path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
    path('stripe-webhook/', StripeWebookView.as_view(), name='stripe-webhook'),
    url(r'', include(router.urls)),
]

urlpatterns += [
    url(r'schema/', SpectacularAPIView.as_view(), name="schema"),
    url(
        r'docs/',
        SpectacularSwaggerView.as_view(
            url_name="schema"
        ),
        name="swagger-ui",
    ),
]


from django.shortcuts import render, redirect
from .forms import *

def post_book_view(request):
    user = PublisherProfileModel.objects.get(user=request.user)
    task = "Post New"
    form = PostBookForm()
    if request.method == 'POST':
        form = PostBookForm(request.POST, request.FILES)
        if form.is_valid():
            new_ad = form.save(commit=False)
            new_ad.publisher = user
            form.save()
            return redirect('home')
        else:
            context = {
                'task': task,
                'form': form
            }
            return render(request, 'book_control/post-update-book.html', context)

    context = {
        'task': task,
        'form': form
    }
    return render(request, "publisher/post-update-book.html", context)


import numpy as np
import re
from scipy.optimize import linear_sum_assignment

def linear_sum():
    cost_matrix = np.array([
        [15, 40, 45],
        [20, 60, 35],
        [20, 40, 25]
    ])

    matches = linear_sum_assignment(cost_matrix)
    print('scipy API result:\n', matches)

"""Outputs
sklearn API result:
 [[0 1]
  [1 0]
  [2 2]]
scipy API result:
 (array([0, 1, 2], dtype=int64), array([1, 0, 2], dtype=int64))
"""

def testlistfor():
    a=[x for x in range(5) if x%2 ==0 ]  # [0, 1, 2, 3, 4]
    return a
def testmtricmax():
    maxnum=20
    a=np.array([[1,2,32],[3,5,6],[34,54,3]])
    a[a>maxnum]=maxnum+2
    return a
def argmin_min():
    lst1 = [1, 100, 56, 78, 0]
    lst2 = [[100, 4, 5], [3, 5, 7], [5, 0, 6]]
    print("lst列表中的最小值是:")
    print(np.min(lst1))
    print("lst1列表中最小值的索引是：")
    print(np.argmin(lst1))
    print("lst2列表中最小值的索引是：")
    print(np.argmin(lst2))
    print("lst2列表中最值，按照轴0方向：")
    print(lst2)
    print(np.min(lst2,axis=0))
def findkuohao():
    string = 'abe(ac)ad)'
    p1 = re.compile(r'[(](.*?)[)]', re.S)  # 最小匹配
    p2 = re.compile(r'[(](.*)[)]', re.S)  # 贪婪匹配
    print(re.findall(p1, string))
    print(re.findall(p2, string))

def main():
    findkuohao()

if __name__ == '__main__':
    main()


from flask import Flask, render_template, redirect, request

app = Flask(__name__)

# Quiz questions
questions = [
    {
        'id': 1,
        'question': 'Who is the leader of the Avengers?',
        'options': ['Iron Man', 'Captain America', 'Thor', 'Black Widow'],
        'answer': 'Captain America'
    },
    {
        'id': 2,
        'question': 'What is the real name of Black Widow?',
        'options': ['Natasha Romanoff', 'Wanda Maximoff', 'Carol Danvers', 'Hope van Dyne'],
        'answer': 'Natasha Romanoff'
    },
    {
        'id': 3,
        'question': 'Which Infinity Stone was embedded in Vision\'s forehead?',
        'options': ['Time Stone', 'Mind Stone', 'Soul Stone', 'Power Stone'],
        'answer': 'Mind Stone'
    }
]

# Global variables
current_question = 0
score = 0

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start')
def start_quiz():
    global current_question, score
    current_question = 0
    score = 0
    return redirect('/quiz')

@app.route('/quiz', methods=['GET', 'POST'])
def quiz():
    global current_question, score

    if request.method == 'POST':
        answer = request.form.get('answer')

        # Check if the answer is correct
        if answer == questions[current_question]['answer']:
            score += 1

        # Move to the next question
        current_question += 1

        # If all questions are answered, redirect to the result page
        if current_question >= len(questions):
            return redirect('/result')

    # Check if there are more questions available
    if current_question < len(questions):
        question = questions[current_question]
        return render_template('quiz.html', question=question)
    else:
        # If there are no more questions, redirect to the result page
        return redirect('/result')

@app.route('/result')
def result():
    global score
    return render_template('result.html', score=score, total_questions=len(questions))

if __name__ == '__main__':
    app.run(debug=True)


import uuid

from django.contrib.auth import get_user_model

from bothub.common.models import Repository
from bothub.project.models import Project, TemplateType, ProjectIntelligence
from bothub.project.usecases.exceptions import InvalidTemplateTypeData

User = get_user_model()

class TemplateTypeIntegrationUseCase:

    def integrate_template_type_in_project(self, project: Project, template_type_uuid: str, user: User) -> bool:
        if project.template_type is not None:
            raise InvalidTemplateTypeData(f"The project `{project.uuid}` already has an integrated template!")

        if template_type_uuid is None:
            raise InvalidTemplateTypeData("'template_type_uuid' cannot be empty when 'is_template' is True!")

        try:
            template_type = TemplateType.objects.get(uuid=template_type_uuid)
        except TemplateType.DoesNotExist:
            raise InvalidTemplateTypeData(f"Template Type with uuid `{template_type_uuid}` does not exists!")

        for repository_data in template_type.setup["repositories"]:
            repository_uuid = repository_data.get("uuid")

            repository = Repository.objects.get(uuid=repository_uuid)

            organization_authorization = project.organization.get_organization_authorization(user)

            if not organization_authorization.can_contribute:
                raise InvalidTemplateTypeData("The user dont have permission on that organization")

            access_token = str(repository.get_user_authorization(
                    organization_authorization.organization
                ).uuid
            )

            project_intelligence = ProjectIntelligence.objects.create(
                uuid=uuid.uuid4(),
                access_token=access_token,
                integrated_by=user,
                project=project,
                name=repository.name,
                repository=repository,
            )
            print(f"[ TemplateTypeIntegration ] - adding integration to `{project.uuid}` with access token `{project_intelligence.access_token}` and uuid `{project_intelligence.uuid}`")


from collections import deque

dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]

def rollback(b_board, rollback_queue):
    while rollback_queue:
        ny, nx, value = rollback_queue.popleft()

        b_board[ny][nx] = value

def check(n, m, b_board, a_board):
    for i in range(n):
        for j in range(m):
            if b_board[i][j] != a_board[i][j]:
                return False

    return True

def bfs(n, m, i, j, b_board, a_board, visited):
    value = b_board[i][j]

    rollback_queue = deque()
    queue = deque()

    queue.append((i, j))
    rollback_queue.append((i, j, b_board[i][j]))
    b_board[i][j] = a_board[i][j]
    visited[i][j] = True

    while queue:
        ny, nx = queue.popleft()

        for d in range(4):
            y = ny + dy[d]
            x = nx + dx[d]

            if 0 <= y < n and 0 <= x < m and b_board[y][x] == value and visited[y][x] == False:
                queue.append((y, x))
                rollback_queue.append((y, x, b_board[y][x]))
                b_board[y][x] = a_board[i][j]
                visited[y][x] = True

    result = check(n, m, b_board, a_board)
    if result == True:
        return True
    else:
        rollback(b_board, rollback_queue)
        return False

n, m = map(int, input().split())
b_board = [list(map(int, input().split())) for _ in range(n)] # before
a_board = [list(map(int, input().split())) for _ in range(n)] # after
visited = [[False] * m for _ in range(n)]

for i in range(n):
    for j in range(m):
        if visited[i][j] == False:
            result = bfs(n, m, i, j, b_board, a_board, visited)
            if result == True:
                print('YES')
                exit(0)

print('NO')


import os
from models.model import UNet
from dataset.dataset import load_data_bmp
import torch
import torch.optim as optim
from models.loss import MaxPoolLoss, PerceptualLoss
from tqdm import trange
from tqdm import tqdm
from utils import metrics
import argparse
from models.projection import projections
from tensorboardX import SummaryWriter
import numpy as np

def main(input_root, output_root, checkpoint_path, end_epoch):
    writer = SummaryWriter()
    lr = 0.0001
    batch_size = 72
    min_list = torch.zeros((100), requires_grad=False)
    max_list = torch.ones((100), requires_grad=False)
    norm_list = torch.stack((min_list, max_list, min_list, max_list), dim = 0)
    val_loss_list = []

    dir_path = os.path.join(output_root, 'overfitnew_b2')
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

    train_loader, val_loader, test_loader = load_data_bmp(batch_size=batch_size, data_dir=input_root)
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model = UNet(n_channels=3, n_classes = 4).to(device)
    model.initialize()
    model = torch.nn.DataParallel(model)
    if checkpoint_path:
        model.load_state_dict(
            torch.load(checkpoint_path)['net'])

    criterion = MaxPoolLoss()
    criterion_pl = PerceptualLoss([2,2,2], [0.6,0.3,0.1], device)
    optimizer = optim.Adam(model.parameters(), lr=lr)
    scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.99)

    for epoch in trange(0, end_epoch):
        min_max_list = torch.stack((max_list, min_list, max_list, min_list), dim = 0)
        train(model, optimizer, criterion, criterion_pl, train_loader, device, norm_list, min_max_list, dir_path, epoch)
        norm_list = min_max_list
        scheduler.step()
        val(model, criterion, val_loader, device, val_loss_list)

    loss_list = np.array(val_loss_list)
    index = loss_list.argmin()
    print('epoch %s is the best model' % (index))

    # print('==> Testing model...')
    # restore_model_path = os.path.join(
    #     dir_path, 'ckpt_%d_loss_%.5f.pth' % (index, loss_list[index]))
    # model.load_state_dict(torch.load(restore_model_path)['net'])
    # test(model, 'test', test_loader, device, flag, task, output_root=output_root)
    # writer.close()

def train(model, optimizer, criterion, criterion_pl, train_loader, device, norm_list, min_max_list, dir_path, epoch):
    model.train()
    train_loss = metrics.LossAverage()
    for batch_idx, (or_inputs, inputs, targets) in tqdm(enumerate(train_loader),total = len(train_loader)):
        optimizer.zero_grad()
        or_inputs, inputs, targets = or_inputs.to(device), inputs.to(device), targets.to(device)
        predict = model(inputs).to(device)
        norm_list = norm_list.to(device).detach()
        i = targets[:,0,:,0].cpu().numpy()
        coor_b2, coor_b3, result_b2, result_b3 = projections(or_inputs, predict, 64, 464, device)
        min1 ,max1 = torch.min(result_b2[:,0,:,:],2), torch.max(result_b2[:,0,:,:],2)
        resultn_b2 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
        min2 ,max2 = torch.min(result_b3[:,0,:,:],2), torch.max(result_b3[:,0,:,:],2)
        resultn_b3 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
        for j in range(len(i)):
            resultn_b2[j,:,:,:] = (result_b2[j,:,:,:]- norm_list[0, np.int(i[j][0])])/(norm_list[1, np.int(i[j][0])] - norm_list[0, np.int(i[j][0])])
            if min1[0].data[j, 0] < min_max_list[0, np.int(i[j][0])]:
                min_max_list[0, np.int(i[j][0])] = min1[0].data[j, 0]
            if max1[0].data[j, 0] > min_max_list[1, np.int(i[j][0])]:
                min_max_list[1, np.int(i[j][0])] = max1[0].data[j, 0]
            resultn_b3[j,:,:,:] = (result_b3[j,:,:,:]- norm_list[2, np.int(i[j][0])])/(norm_list[3, np.int(i[j][0])] - norm_list[2, np.int(i[j][0])])
            if min2[0].data[j, 0] < min_max_list[2, np.int(i[j][0])]:
                min_max_list[2, np.int(i[j][0])] = min2[0].data[j, 0]
            if max2[0].data[j, 0] > min_max_list[3, np.int(i[j][0])]:
                min_max_list[3, np.int(i[j][0])] = max2[0].data[j, 0]
        loss1 = criterion_pl(resultn_b2.view(-1, 3, 16,29), targets[:,:,:,1:465].view(-1, 3, 16,29))
        loss2 = criterion_pl(resultn_b3.view(-1, 3, 16,29), targets[:,:,:,465:929].view(-1, 3, 16,29))
        loss_b2 = criterion(resultn_b2, targets[:,:,:,1:465])
        loss_b3 = criterion(resultn_b3, targets[:,:,:,465:929])
        loss = loss_b2+0.25*loss1+0.5*(loss_b3+0.25*loss2)
        loss.backward()
        optimizer.step()
        train_loss.update(loss.item(),inputs.size(0))
    state = {
        'net': model.state_dict(),
        'loss': train_loss.avg,
        'epoch': epoch,
    }
    save_path = dir_path +'/checkpoint'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    path = os.path.join(save_path, 'ckpt_%d_loss_%.5f.pth' % (epoch, train_loss.avg))
    torch.save(state, path)

def val(model, criterion,train_loader, device, val_loss_list):
    model.eval()
    train_loss_b2 = metrics.LossAverage()
    train_loss_b3 = metrics.LossAverage()
    train_loss = metrics.LossAverage()
    min_list = torch.zeros((20), requires_grad=False)
    max_list = torch.ones((20), requires_grad=False)
    min_max_list = torch.stack((max_list, min_list, max_list, min_list), dim = 0)
    with torch.no_grad():
        for batch_idx, (or_inputs, inputs, targets) in enumerate(train_loader):
            or_inputs, inputs, targets = or_inputs.to(device), inputs.to(device), targets.to(device)
            predict = model(inputs).to(device)
            i = targets[:,0,:,0].cpu().numpy()
            coor_b2, coor_b3, result_b2, result_b3 = projections(or_inputs, predict, 64, 464, device)  ##change
            min1 ,max1 = torch.min(result_b2[:,0,:,:],2), torch.max(result_b2[:,0,:,:],2)
            resultn_b2 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
            min2 ,max2 = torch.min(result_b3[:,0,:,:],2), torch.max(result_b3[:,0,:,:],2)
            resultn_b3 = torch.zeros((inputs.size(0), 3, 1, 464), requires_grad=True).to(device)
            for j in range(len(i)):
                if min1[0].data[j, 0] < min_max_list[0, np.int(i[j][0])]:
                    min_max_list[0, np.int(i[j][0])] = min1[0].data[j, 0]
                if max1[0].data[j, 0] > min_max_list[1, np.int(i[j][0])]:
                    min_max_list[1, np.int(i[j][0])] = max1[0].data[j, 0]
                if min2[0].data[j, 0] < min_max_list[2, np.int(i[j][0])]:
                    min_max_list[2, np.int(i[j][0])] = min2[0].data[j, 0]
                if max2[0].data[j, 0] > min_max_list[3, np.int(i[j][0])]:
                    min_max_list[3, np.int(i[j][0])] = max2[0].data[j, 0]
            for j in range(len(i)):
                resultn_b2[j,:,:,:] = (result_b2[j,:,:,:]-  min_max_list[0, np.int(i[j][0])])/( min_max_list[1, np.int(i[j][0])] -  min_max_list[0, np.int(i[j][0])])
                resultn_b3[j,:,:,:] = (result_b3[j,:,:,:]-  min_max_list[2, np.int(i[j][0])])/( min_max_list[3, np.int(i[j][0])] -  min_max_list[2, np.int(i[j][0])])

            loss_b2 = criterion(resultn_b2, targets[:,:,:,1:465])
            loss_b3 = criterion(resultn_b3, targets[:,:,:,465:929])

            loss = loss_b2 + loss_b3

            train_loss_b2.update(loss_b2.item(),inputs.size(0))
            train_loss_b3.update(loss_b3.item(),inputs.size(0))
            train_loss.update(loss.item(),inputs.size(0))
            val_loss_list.append(train_loss)
        print(train_loss_b2.avg, train_loss_b3.avg)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='RUN model')
    parser.add_argument('--input_root',
                        default='/data1/rong/OCT_and_OCTA/',
                        help='input root, the source of dataset files',
                        type=str)
    parser.add_argument('--output_root',
                        default='./output',
                        help='output root, where to save models and results',
                        type=str)
    parser.add_argument('--checkpoint_path',
                        default='None',
                        help='use checkpoint or not',
                        type=str)
    parser.add_argument('--end_epoch',
                        default=200,
                        help='num of epochs of training',
                        type=int)

    args = parser.parse_args()
    input_root = args.input_root
    output_root = args.output_root
    checkpoint_path = args.checkpoint_path
    end_epoch = args.end_epoch
    main(input_root, output_root, checkpoint_path, end_epoch)


# -*- coding: utf-8 -*-
"""
estimate the stellar density, and mass.
"""
from __future__ import division, print_function
import numpy as np
import pickle

from astropy import units as u, constants as const

# Keivan value
Rstar = 0.893*u.Rsun
Rstar_err = 0.024*u.Rsun

# parameters from Table 4 of Hoyer+2013, for comparison
i_hoyer13 = 88.52*u.deg
a_by_Rs_hoyer13 = 5.463
a_by_Rs_perr_hoyer13 = 0.025
a_by_Rs_merr_hoyer13 = 0.020
P_hoyer13 = 1.33823204*u.day
hoyer_params = [i_hoyer13, a_by_Rs_hoyer13, a_by_Rs_perr_hoyer13,
                a_by_Rs_merr_hoyer13, P_hoyer13]

# get parameters from fit to phase-folded lightcurve
picklepath = ('/home/luke/Dropbox/proj/tessorbitaldecay/results/'
              'tess_lightcurve_fit_parameters/402026209/sector_2/'
              '402026209_phased_mandelagol_fit_empiricalerrs.pickle' )

d = pickle.load(open(picklepath, 'rb'))
i = d['fitinfo']['finalparams']['incl']*u.deg
i_upper = i + 0.39*u.deg

i = 88.52*u.deg # Hoyer+ 2013, table 4
i_upper = i + d['fitinfo']['finalparamerrs']['std_perrs']['incl']*u.deg
i_lower = i - d['fitinfo']['finalparamerrs']['std_merrs']['incl']*u.deg
a_by_Rs = d['fitinfo']['finalparams']['sma']
a_by_Rs_perr = d['fitinfo']['finalparamerrs']['std_perrs']['sma']
a_by_Rs_merr = d['fitinfo']['finalparamerrs']['std_merrs']['sma']
P = d['fitinfo']['finalparams']['period']*u.day

a_by_Rs = d['fitinfo']['finalparams']['sma']
a_by_Rs_perr = d['fitinfo']['finalparamerrs']['std_perrs']['sma']
a_by_Rs_merr = d['fitinfo']['finalparamerrs']['std_merrs']['sma']

Rp_by_Rs = d['fitinfo']['finalparams']['rp']
Rp_by_Rs_err = np.mean(
    [d['fitinfo']['finalparamerrs']['std_perrs']['rp'],
    d['fitinfo']['finalparamerrs']['std_merrs']['rp']
    ]
)
Rp = Rp_by_Rs * Rstar
Rp_upper = (Rp_by_Rs + Rp_by_Rs_err)*(Rstar+Rstar_err)
Rp_lower = (Rp_by_Rs - Rp_by_Rs_err)*(Rstar-Rstar_err)

my_params = [i, a_by_Rs, a_by_Rs_perr, a_by_Rs_merr, P]

paramnames = ['incl','a/Rstar','a/Rstar_perr','a/Rstar_merr','P']

# the period you adopt here does not particularly matter! the one reported in
# the transit time table does. so using my less precise TESS-only BLS period
# (1.33814, vs hoyer+13: 1.338232 d, is fine.

print('-'*42)
for hparam, mparam, pname in zip(hoyer_params, my_params, paramnames):
    print('{:s}: me: {:.5f}, hoyer+13: {:5f}\n\tme-h13: {:.5f}'.
          format(pname, mparam, hparam, mparam-hparam))
print('-'*42)
print('for selected system parameters table:')
# Rp/Rstar, incl, a/Rstar, ulinear, uquad:
params = ['rp','incl','sma','u_linear','u_quad']
precisions = [5, 2, 3, 3, 3]
for param, precision in zip(params, precisions):
    value = d['fitinfo']['finalparams'][param]
    value_perr = d['fitinfo']['finalparamerrs']['std_perrs'][param]
    value_merr = d['fitinfo']['finalparamerrs']['std_merrs'][param]
    outstr = ('{:s}: '.format(param)+
              '{1:.{0}f}'.format(precision, value)+
              ' +{1:.{0}f}'.format(precision, value_perr)+
              ' -{1:.{0}f}'.format(precision, value_merr)
    )
    print(outstr)
print('-'*42)

# eq 30 of Winn (2010).
# note k^3 = 3e-3, and the density of jupiter is about equal to the density of
# the sun, so neglect the k^3*rho_planet term.

rho_star = 3*np.pi/(const.G*P**2) * a_by_Rs**3
print(rho_star.cgs)

rho_star_upper = 3*np.pi/(const.G*P**2) * (a_by_Rs+a_by_Rs_perr)**3
print(rho_star_upper.cgs)

rho_star_lower = 3*np.pi/(const.G*P**2) * (a_by_Rs-a_by_Rs_merr)**3
print(rho_star_lower.cgs)

print(
    'rhostar = {:.3f} +({:.3f}) -({:.3f}) g/cm^3'.format(
        rho_star.cgs.value,
        (rho_star_upper-rho_star).cgs.value,
        (rho_star-rho_star_lower).cgs.value
    )
)

Mstar = (4*np.pi)/3*rho_star*Rstar**3
Mstar_lower = (4*np.pi)/3*rho_star_lower*(Rstar-Rstar_err)**3
Mstar_upper = (4*np.pi)/3*rho_star_upper*(Rstar+Rstar_err)**3

print(
    'Mstar = {:.3f} +({:.3f}) -({:.3f}) Msun'.format(
        Mstar.to(u.Msun).value,
        (Mstar_upper-Mstar).to(u.Msun).value,
        (Mstar-Mstar_lower).to(u.Msun).value,
    )
)

##########################################
# now get R_p

print(
    'Rp = {:.3f} +({:.3f}) -({:.3f}) Rjup'.format(
        Rp.to(u.Rjup).value,
        (Rp_upper-Rp).to(u.Rjup).value,
        (Rp-Rp_lower).to(u.Rjup).value,
    )
)

# semimajor axis
sma = a_by_Rs * Rstar
sma_upper = (a_by_Rs+a_by_Rs_perr) * (Rstar+Rstar_err)
sma_lower = (a_by_Rs-a_by_Rs_merr) * (Rstar-Rstar_err)

print(
    'sma = {:.4f} +({:.4f}) -({:.4f}) AU'.format(
        sma.to(u.AU).value,
        (sma_upper-sma).to(u.AU).value,
        (sma-sma_lower).to(u.AU).value,
    )
)

# now get M_p

K = 241.1 * u.m/u.s
K_perr = 2.8 * u.m/u.s
K_merr = 3.1 * u.m/u.s

sini = float(np.sin(i))
sini_upper = float(np.sin(i_upper))
sini_lower = float(np.sin(i_lower))

# assume e = 0

Mp = K * (const.G)**(-1/2) * sini**(-1) * Mstar**(1/2) * sma**(1/2)

Mp_upper = (
    (K+K_perr) * (const.G)**(-1/2) * sini_upper**(-1) *
    Mstar_upper**(1/2) * sma_upper**(1/2)
)

Mp_lower = (
    (K-K_merr) * (const.G)**(-1/2) * sini_lower**(-1) *
    Mstar_lower**(1/2) * sma_lower**(1/2)
)

print(
    'Mp = {:.3f} +({:.3f}) -({:.3f}) Mjup'.format(
        Mp.to(u.Mjup).value,
        (Mp_upper - Mp).to(u.Mjup).value,
        (Mp - Mp_lower).to(u.Mjup).value,
    )
)

# finally, Rstar/d
F_bol = 2.8e-10 * u.erg/(u.cm**2 * u.s)
F_bol_err = 0.1e-10 * u.erg/(u.cm**2 * u.s)
Teff = 5400 * u.K
Teff_err = 90 * u.K

Rstar_by_dist = (F_bol / (const.sigma_sb * Teff**4 ) )**(1/2)
Rstar_by_dist_upper = ( (F_bol+F_bol_err) / (const.sigma_sb * (Teff-Teff_err)**4 ) )**(1/2)
Rstar_by_dist_lower = ( (F_bol-F_bol_err) / (const.sigma_sb * (Teff+Teff_err)**4 ) )**(1/2)

print(
    'Rs/dist = {:.3e}, +{:.3e} -{:.3e}'.format(
        Rstar_by_dist.cgs,
        (Rstar_by_dist_upper-Rstar_by_dist).cgs,
        (Rstar_by_dist-Rstar_by_dist_lower).cgs,
    )
)

plx = 3.7145e-3 * u.arcsec
plx_offset = 82e-6 * u.arcsec
plx += plx_offset

plx_err = 0.0517e-3 * u.arcsec

dist_pc = (1/plx.value)*u.pc

Rs_calcd = (Rstar_by_dist * dist_pc).to(u.Rsun)

print(
    'dist = {:.2f}'.format(dist_pc)+
    '\nmy Rstar (but use Keivan\'s) = {:.3f}'.format(Rs_calcd)
)


# coding=utf-8
import scrapy
import re
import os
import urllib
import pymysql
import sys
from scrapy.selector import Selector
from scrapy.http import HtmlResponse, Request
from webCrawler_scrapy.items import  XrldSpiderItem

class XrldSpider(scrapy.spiders.Spider):
    name = 'xrld'
    allowed_domains = ["bnu.edu.cn"]
    start_urls = ["http://www.bnu.edu.cn/xxgk/xrld/index.htm" ]

    def parse(self, response):
        se = Selector(response)  # 创建查询对象，HtmlXPathSelector已过时
        src_a = response.xpath("//div[@class='leader_row']" )
        print("----------------------------")
        print(len(src_a))
        for i in range(len(src_a)):  # 遍历li个数
            ii = i+1
            src_list1 = response.xpath("//div[@class='leader_row'][%d]/ul/li"% ii)
            for m in range(len(src_list1)):
                mm = m+1
                item = XrldSpiderItem()
                item['zwmc'] = se.xpath("//div[@class='leader_row'][%d]/h4/text()" % ii).extract()
                item['name'] = se.xpath("//div[@class='leader_row'][%d]/ul/li[%d]/a/p/text()" % (ii,mm)).extract()
                yield item

        src_b = response.xpath("//div[@class='leader_row last-noborder']")
        print(len(src_b))
        for j in range(len(src_b)):  # 遍历li个数
            jj = j+1
            src_list2 = response.xpath("//div[@class='leader_row last-noborder'][%d]/ul/li"% jj)
            for n in range(len(src_list2)):
                nn = n+1
                item = XrldSpiderItem()
                item['zwmc'] = se.xpath("//div[@class='leader_row last-noborder'][%d]/h4/text()" % jj).extract()
                item['name'] = se.xpath("//div[@class='leader_row last-noborder'][%d]/ul/li[%d]/a/p/text()" % (jj,nn)).extract()
                yield item


#from django.shortcuts import render
#from django.http import HttpResponse
from google.cloud import storage
import os
import posixpath
import math
import requests

from PIL import Image

from flask import Flask  , jsonify
from flask import render_template
from flask import current_app

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
Static_Directory_Path = Flask.static_folder

print("PATH :" + BASE_DIR)

def download_blob(bucket_name, background_source_blob_name,  item_source_blob_name):
    """Downloads a blob from the bucket."""

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    bucketFurkan = storage_client.bucket("image-processing-module.appspot.com")

    # Construct a client side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
    # any content from Google Cloud Storage. As we don't need additional data,
    # using `Bucket.blob` is preferred here.
    BG_blob = bucket.blob(background_source_blob_name)
    BG_blob.download_to_filename("/tmp/bg_destination_file_name")

    item_blob = bucketFurkan.blob(item_source_blob_name)
    item_blob.download_to_filename("/tmp/item_destination_file_name")

    #combine_tmp_images(faceAnnotations)

    #print(
    #    "Blob {} downloaded to {}.".format(
    #        background_source_blob_name, bg_destination_file_name
    #    )
    #)

def upload_blob(bucket_name, source_file_name, destination_blob_name):

    """Uploads a file to the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The path to your file to upload
    # source_file_name = "local/path/to/file"
    # The ID of your GCS object
    # destination_blob_name = "storage-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    #blob.upload_from_filename(source_file_name)
    blob.upload_from_filename("/tmp/final_image_directory.jpg")

    print(
        "File {} uploaded to {}.".format(
            source_file_name, destination_blob_name
        )
    )

# create() combines the background image (containing faces) with items (hats, glasses etc.)
def create(disguise_request):

    upload_bucket_name = "image-processing-module.appspot.com"
    bucket_name = disguise_request['bucket_name']
    #background_source_blob_name = "input_images/The_Traitorous_Eight.jpeg"
    background_source_blob_name = disguise_request['image_file_name']
    #item_source_blob_name = "items/glasses0.png"
    item_source_blob_name = disguise_request['faces'][0]['item_file_name']

    #bg_destination_file_name = os.path.join(BASE_DIR, "tmp/static/face_images/background_image.jpg")
    #item_destination_file_name = os.path.join(BASE_DIR, "static/items/item1.png")

    final_image_directory = os.path.join(BASE_DIR, "static/output_images/final.png")
    destination_blob_name = "output_images/final_" + background_source_blob_name + ".jpeg"

    download_blob(bucket_name, background_source_blob_name,  item_source_blob_name)

    combine_tmp_images(disguise_request)

    #combine_images(item_destination_file_name , bg_destination_file_name , final_image_directory)

    upload_blob(upload_bucket_name, final_image_directory, destination_blob_name)

    return upload_bucket_name + "/" + destination_blob_name

    # send the output image url to the manager service
    #url = 'https://www.w3schools.com/python/demopage.php'
    #myobj = {'somekey': 'somevalue'}

    #x = requests.post(url, data = myobj)

    #print(x.text)

    #print(*args)
    #bg_destination_file_name = os.path.join(BASE_DIR, "imageCreator/face_images/downloadedFile.jpg")
    #path = "F:\ImageProcessingModule\ImageProcessingModule\ImageProcessingModule\imageCreator\face_images\downloadedFile.jpg"

    #html = "
IMAGE:
 "

    #return HttpResponse(html)
    #return render_template('index.html')

def combine_images(item_image_path, bg_image_path, final_image_directory):

    bg = Image.open(bg_image_path)
    item = Image.open(item_image_path)
    new_item_size = (370, 125)
    item = item.resize(new_item_size).rotate(20, expand = True)
    back_im = bg.copy()
    back_im.paste(item, (260,340) , item)
    back_im.save(final_image_directory, quality=95)

    #return null
def vector_length(v):
    return math.sqrt(v[0]*v[0] + v[1]*v[1])

def combine_tmp_images(diguise_request):

    bg = Image.open("/tmp/bg_destination_file_name")
    item = Image.open("/tmp/item_destination_file_name")

    back_im = bg.copy()

    lefteye = diguise_request['faces'][0]['detection']['lefteye']
    midpoint = diguise_request['faces'][0]['detection']['midpoint']
    rigtheye = diguise_request['faces'][0]['detection']['righteye']

    #for face in faceAnnotations:

    """lefteye = faceAnnotations[face]['lefteye']

    midpoint = faceAnnotations[face]['midpoint']
    rigtheye = faceAnnotations[face]['rigtheye']"""

    item_rotation = (rigtheye['y'] - lefteye['y'] ) / (rigtheye['x'] - lefteye['x'] )
    item_rotation = -math.degrees(math.atan(item_rotation))
    eyes_vector =  (rigtheye['x'] - lefteye['x'] , rigtheye['y'] - lefteye['y'] )  # the 2d vector from left eye to right eye

    print("eyes_vector: ")
    print(eyes_vector)

    print("item.size: ")
    print(item.size)

    coef = vector_length(eyes_vector) / vector_length(item.size)
    coef *= 2 # this constant is determined experimentally
    print("coef: ")
    print(coef)

    new_item_size = (int(item.size[0] * coef) , int(item.size[1] * coef)  )

    print("new_item_size: ")
    print(new_item_size)
    #item_rotation = 20

    #faceAnnotations.x = 260
    #faceAnnotations.y = 340
    #faceAnnotations = jsonify(faceAnnotations)

    item = item.resize(new_item_size).rotate(int(item_rotation), expand = True)

    x_coordinate = int(midpoint['x'] - item.size[0] / 2)
    y_coordinate = int(midpoint['y'] - item.size[1] / 2)

    back_im.paste(item, (x_coordinate, y_coordinate) , item)

    #back_im.show()
    back_im.save("/tmp/final_image_directory.jpg", quality=95)


import discord

from commonbot.user import UserLookup
from config import CMD_PREFIX
from forwarder import message_forwarder

async def get_userid(ul: UserLookup, mes: discord.Message, cmd: str, args: str = "") -> tuple[int | None, bool]:
    """
    Retrieves the user referenced in the given message.

    Uses an explicit user mention if available, otherwise uses the reply thread user if the command
    is in a reply thread.

    The second return value is useful in case the message needs to be stripped to access the args -
    it indicates how many words to strip:
     - True -> the user came from the message, strip two words (the command, and user reference)
     - False -> the user came from the reply thread, strip one word (the command)

    :param mes: Message to check.
    :param cmd: Command name for help output, if no user is found.
    :param args: Command args for help output, if no user is found.
    :return: The user id (or None if found), and whether the user came from the message (as opposed to from the reply thread).
    """
    # First check message
    userid = ul.parse_id(mes)
    if userid:
        return userid, True

    # If no user in the message, check if it's a reply thread
    thread_user = message_forwarder.get_userid_for_user_reply_thread(mes)
    if thread_user is not None:
        return thread_user, False

    outside_reply_thread = f"{CMD_PREFIX}{cmd} USER {args}".strip()
    inside_reply_thread = f"{CMD_PREFIX}{cmd} {args}".strip()

    # Otherwise send an error
    await mes.channel.send(f"I wasn't able to find a user anywhere based on that message. `{outside_reply_thread}` or `{inside_reply_thread}` in a reply thread")
    return None, False