import os
import random
import shutil
from shutil import copy2
from tqdm import tqdm

def spilt_datasets(data_root, trainDir, validDir):
    trainfiles = os.listdir(data_root)
    num_train = len(trainfiles)
    print("num_train: " + str(num_train))
    index_list = list(range(num_train))
    # print(index_list)
    random.shuffle(index_list)
    num = 0
    # trainDir = '../data/2023/extra_train/images'
    # validDir = '../data/2023/extra_val/images'
    for i in index_list:
        fileName = os.path.join(data_root, trainfiles[i])
        if num < num_train * 0.8:
            print(str(fileName))
            copy2(fileName, trainDir)
        else:
            copy2(fileName, validDir)
        num += 1

def cp_labels(lable_root, trainDir, validDir):
    # lable_root = '../data/2023/extra/labels'

    # trainDir = '../data/2023/extra_train/images'
    trainfiles = os.listdir(trainDir)

    # validDir = '../data/2023/extra_val/images'
    valfiles = os.listdir(validDir)

    for i in tqdm(trainfiles):
        fileName = os.path.join(lable_root, i)
        fileName = fileName.replace('.png', '.txt')
        copy2(fileName, '/workspace/pycharm_project/mmrotate/data/fair1m_ss/train/annfiles')

    for j in tqdm(valfiles):
        fileName = os.path.join(lable_root, j)
        fileName = fileName.replace('.png', '.txt')
        copy2(fileName, '/workspace/pycharm_project/mmrotate/data/fair1m_ss/val/annfiles')

def main():
    data_root = '/workspace/pycharm_project/mmrotate/data/fair1m_ss/trainval/images/'
    trainDir = '/workspace/pycharm_project/mmrotate/data/fair1m_ss/train/images/'
    validDir = '/workspace/pycharm_project/mmrotate/data/fair1m_ss/val/images/'
    # spilt_datasets(data_root, trainDir, validDir)

    lable_root = '/workspace/pycharm_project/mmrotate/data/fair1m_ss/trainval/annfiles/'
    cp_labels(lable_root, trainDir, validDir)

if __name__ == '__main__':
    main()


import matplotlib.pyplot as plt
import pandas as pd
import requests

df = pd.read_csv("experiment.csv", skiprows=1, header=None)

df.columns = ["time", "dose", "altitude"]

latitude = -33.51 #(S)  [-90, 90] degrees N is +ve
longitude = 147.24 #(E)  [-180, 180] degrees E is +ve
year = '2015'
month = '7'
day = '19'

def get_api_data(particle, api):
    url = "http://cosmicrays.amentum.space/" + api + "/ambient_dose"
    values = []
    for alt in df['altitude'] :

        parameters = {
            "altitude" : alt, #km
            "latitude" : -33.51, #degrees (N)
            "longitude" : 147.24, #degrees (E)
            "year" : 2015,
            "month" : 7,
            "day" : 19,
            "utc" : 10,
            "particle" : particle
            }
        if particle == "gamma" and api == "cari7":
            parameters["particle"] = "photon"
        response = requests.get(url, params=parameters)

        dose_rate = response.json()

        dose_rate_val = dose_rate['dose rate']['value']

        values.append(dose_rate_val)
    return values

fig = plt.figure()

axes = fig.add_subplot(111)

axes.plot(
    df['time'], df['dose'],
    label="Experiment", linestyle="None", marker="x")

values = get_api_data("gamma", "parma")
axes.plot(
    df['time'], values,
    label="PARMA_g", linestyle="None", marker="x", color="red")

values = get_api_data("total", "parma")
axes.plot(
    df['time'], values,
    label="PARMA_t", linestyle="None", marker="+", color="red")

values = get_api_data("gamma", "cari7")
axes.plot(
    df['time'], values,
    label="CARI-7_g", linestyle="None", marker="x", color="blue")

values = get_api_data("total", "cari7")
axes.plot(
    df['time'], values,
    label="CARI-7_t", linestyle="None", marker="+", color="blue")

axes.set_xlim(left=0)
axes.set_ylim(bottom=0)
axes.set_xlabel("Time, s")
axes.set_ylabel("Doses, uSv")

plt.legend(loc="upper left")
#plt.show()

plt.savefig("lineplot.png")


import json
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, fbeta_score

with open('Evaluation.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    true = data['label']
    pred =  data['predict']

def eval(true, pred):
    ave = ['macro', 'micro']
    precision = []
    recall = []
    fbeta = []
    f1 = []
    acc = accuracy_score(true, pred)
    for i in ave:
        precision.append(precision_score(true, pred, average=i))
        recall.append(recall_score(true, pred, average=i))
        f1.append(f1_score(true, pred, average=i))
    return acc, precision, recall, f1

conf_mat = confusion_matrix(true, pred)
evaluation = eval(true, pred)
save_file_name = '2019711752_윤민형_EVAL'
with open('./'+save_file_name+'.txt', 'w', encoding='utf-8', newline='') as writer_text:
    writer_text.writelines('Confusion martix' + '\n')
    for i in conf_mat:
        for j in i:
            writer_text.writelines(str(j) + '\t')
        writer_text.writelines('\n')
    writer_text.writelines('\n')
    writer_text.writelines('Accuracy : ' + str(evaluation[0]*100) +'%' + '\n')
    writer_text.writelines('\n')
    list = ['precision', 'recall', 'f1-score']
    for idx, k in enumerate(range(len(evaluation[1:]))):
        writer_text.writelines('Macro average ' + str(list[idx]) +' : '
                               + str(evaluation[k+1][0]*100) +'%' + '\n')
        writer_text.writelines('Micro averate ' + str(list[idx]) +' : '
                               + str(evaluation[k+1][1]*100) +'%'+ '\n\n')
    #writer_text.close()
    print("[저장 완료]")


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 17:52:12 2021

@author: Anand
"""

#%%writefile app1.py

import pickle
import streamlit as st
import pandas as pd
import numpy as np

# loading the trained model
pickle_in = open('model.pkl', 'rb')
classifier = pickle.load(pickle_in)

@st.cache()

# defining the function which will make the prediction using the data which the user inputs
# Variables input to this function are from user, we will convert them in order to feed the model
def prediction(dom,season,yr,mnth,holiday,weekday,workingday,weather,temp,hum,windspeed,casual_reg):
    weekday_dict = {'Monday':1,'Tuesday':2,'Wednesday':3,'Thursday':4, 'Friday':5,'Saturday':6, 'Sunday':0}
    weather_dict = {'Clear, Few clouds, Partly cloudy, Partly cloudy':1,
                    'Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist':2,
                    'Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered clouds':3,
                    'Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog':4}
    season_dict = {'Spring':1,'Summer':2,'Fall':3, 'Winter':4}

    if season in season_dict:
        season = season_dict[season]
#Converting input of weekday to numerical value
    if weekday in weekday_dict:
        weekday = weekday_dict[weekday]

#Converting input of weekday to numerical value
    if weather in weather_dict:
        weathersit = weather_dict[weather]

    # Making predictions
    prediction = classifier.predict(
        np.array([[dom,season,yr,mnth,holiday,weekday,workingday,weathersit,temp,hum,windspeed,casual_reg]]))

#    if prediction == 0:
#        pred = 'Not Default'
#    else:
#        pred = 'Default'
    return int(prediction)

# this is the main function in which we define our webpage
def main():
    # front end elements of the web page
    html_temp = """

Bank Loan Prediction

    """

    # display the front end aspect
    st.markdown(html_temp, unsafe_allow_html = True)

    # following lines create boxes in which user can enter data required to make prediction
    dom = st.selectbox("Day of the Month", range(1,32))
    season = st.selectbox("Season of the Year",['Spring','Summer','Fall','Winter'],index = 0)
    yr = st.selectbox("Year", [0,1], help = '0: 2011, 1:2012')
    mnth = st.selectbox("Month" , range(1,13))
    holiday = st.selectbox("Whether or not it is Holiday",[0,1], help = 'If day is neither weekend nor holiday is 1, otherwise is 0')
    weekday = st.selectbox("Day of the week" , ['Monday','Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday'])
    workingday = st.selectbox("Whether or not it is Workingday" , [0,1], help = 'If day is neither weekend nor holiday is 1, otherwise is 0')
    weather = st.selectbox("How is the Weather", ['Clear, Few clouds, Partly cloudy, Partly cloudy',
                                                    'Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist',
                                                    'Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered clouds',
                                                    'Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog'])
    temp = st.number_input("Temperature")
    hum = st.number_input("Humidity")
    windspeed = st.number_input("Windspeed")
    casual_reg = st.number_input("Ratio of casual to registered customers")
    result =""

    # when 'Predict' is clicked, make the prediction and store it
    if st.button("Predict"):
        result = prediction(dom,season,yr,mnth,holiday,weekday,workingday,weather,temp,hum,windspeed,casual_reg)
        st.success('The count of bikes rented is {}'.format(result))
        #print(result)

if __name__=='__main__':
    main()


from binaryheap import BinaryHeap

from test_graph import test_graph, s

def mst_prim(g, s):
    s.key = 0
    s.parent = s
    q = BinaryHeap(list(g))
    #tree = BinaryHeap([])
    tree = []
    while len(q.keys_list) > 0:
        u = q.delete_min_heap()
        u.judge_location = False
        #tree.insert_into_heap(u)
        tree.append(u)
        for v in u.adjacent.keys():
            if v.judge_location and u.adjacent[v] < v.key:
                v.parent = u
                q.decrease_key(v.id_heap, u.adjacent[v])
    return tree

#test_tree = mst_prim(test_graph, s)

#print([(node.name, node.parent.name, node.key) for node in test_tree])


from collections import Counter
import numpy as np

# Creating Board
def create_board(r,c):
    b = np.zeros((r,c))
    b = b.astype(int)
    return b

# Logic for piece Droping
def drop_piece(r, b, col, player_piece):
    i = r-1
    while i>=0:
        if b[0][col] != 0:
            print("Invalid entry! Try another column")
            break
        else:
            if b[i][col] == 0:
                b[i][col] = player_piece
                break
            else:
                i -= 1
    print(b)

# Rows & Cols winning
def checkRows(x, no_of_connecting_piece, turn):
    for row in x:
        d = Counter(row)
        player1 = 1
        player2 = 2
        if turn == 0 and d[player1] >= no_of_connecting_piece:
            return 1
        elif turn == 1 and d[player2] >= no_of_connecting_piece:
            return 2
    return 0

def checkDiagonals(x):
    pass

# Winning Conditions
def win_conditions(b, no_of_connecting_piece, turn):
    for x in [b, np.transpose(b)]:
        result = checkRows(x, no_of_connecting_piece, turn)
        if result:
            return result
    return checkDiagonals(b)

# Main program
print("Hello Guys Let's play the game Connect Four")
row = int(input("No of rows : "))
column = int(input("No of cols : "))
piece = int(input("No of connected piece required for winning : "))

game_over = False
board = create_board(row,column)
turn = 0

print(board)

while not game_over:
    if turn==0:
        selected_col = int(input("Player 1 - "))
        drop_piece(row, board, selected_col, 1)

    else:
        selected_col = int(input("Player 2 - "))
        drop_piece(row, board, selected_col, 2)

    results = win_conditions(board, piece, turn)
    if results==1 or results==2:
        print(f"Player {results} wins")
        break

    turn += 1
    turn = turn%2


from moviepy.editor import VideoFileClip
import moviepy.video.fx.all as vfx
import os
import gc

n_sessions = 5
var_aux = 0
aux = 0

#for i in range(0,n_sessions):
i = 1
cont = 1
print("Session",i+1)
dir_videos = 'D:/IEMOCAP_full_release/IEMOCAP/Video'
dir_videos_s = dir_videos+'/Session'+str(i+1)
files = os.listdir(dir_videos_s)
dir_videos_cropped = 'D:/IEMOCAP_full_release/IEMOCAP/Video_cropped_2/Session'+str(i+1)
#os.mkdir(dir_videos_cropped)
for j in range(len(files)):
    gc.collect()
    if  j == 2:
        dir_video_s = dir_videos_s+'/'+files[j+var_aux]
        clip = VideoFileClip(dir_video_s)
        # 450,650
        new_clip_2 = vfx.crop(clip, x1=450,x2=645,y1=0,y2=280)
        video_cropped_2 = dir_videos_cropped+'/2_'+files[j+var_aux][:-3] + 'mp4'
        new_clip_2.write_videofile(video_cropped_2,fps=29.97,audio=False)
        new_clip_2.close()
        clip.close()


#
# @lc app=leetcode.cn id=49 lang=python3
#
# [49] 字母异位词分组
#

# @lc code=start
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        ans = []
        d = {}
        idx = 0
        for s in strs:
            l = list(s)
            l.sort()
            s_sorted = str(l)
            if s_sorted in d:
                ans[d[s_sorted]].append(s)
            else:
                ans.append([s])
                d[s_sorted] = idx
                idx += 1

        return ans
# @lc code=end

49.字母异位词分组.py

49.字母异位词分组.py


from datetime import datetime

from sqlalchemy import (Boolean, DateTime, String, Column, ForeignKey,
                        PrimaryKeyConstraint)
from sqlalchemy.orm import relation, backref, deferred

from aquilon.aqdb.model import (Base, HardwareEntity, HostLifecycle, Grn,
                                OperatingSystem, CompileableMixin)

from aquilon.aqdb.column_types import AqStr

_TN = 'host'
_HOSTGRN = 'host_grn_map'

class Host(CompileableMixin, Base):
    """ The Host class captures the configuration profile of a machine.

        Putting a physical machine into a chassis and powering it up leaves it
        in a state with a few more attributes not filled in: what Branch
        configures this host? If Ownership is captured, this is the place for
        it.

        Post DNS changes the class name "Host", and it's current existence may
        not make much sense. In the interest of keeping the scope of changes
        somewhat limited (compared to how much else is changing), the class is
        being left in this intermediate state, for the time being. The full
        expression of the changes would be to call the class "MachineProfile",
        and remove any machine specific information. This would provide a more
        normalized schema, rather than individual machines having all of the
        rows below, which potentially would need to be nullable.
    """

    __tablename__ = _TN
    _instance_label = 'fqdn'

    hardware_entity_id = Column(ForeignKey(HardwareEntity.id), primary_key=True)

    lifecycle_id = Column(ForeignKey(HostLifecycle.id), nullable=False)

    operating_system_id = Column(ForeignKey(OperatingSystem.id), nullable=False)

    owner_eon_id = Column(ForeignKey(Grn.eon_id, name='%s_owner_grn_fk' % _TN),
                          nullable=True)

    # something to retain the advertised status of the host
    advertise_status = Column(Boolean, nullable=False, default=False)

    creation_date = deferred(Column(DateTime, default=datetime.now,
                                    nullable=False))

    comments = deferred(Column(String(255), nullable=True))

    # This is a one-to-one relation, so we need uselist=False on the backref
    hardware_entity = relation(HardwareEntity, innerjoin=True,
                               backref=backref('host', uselist=False,
                                               cascade='all, delete-orphan'))

    status = relation(HostLifecycle, innerjoin=True)
    operating_system = relation(OperatingSystem, innerjoin=True)
    owner_grn = relation(Grn)

    @property
    def fqdn(self):
        return self.hardware_entity.fqdn

    # see cluster.py
    @property
    def virtual_machines(self):
        mach = []
        if self.resholder:
            for res in self.resholder.resources:
                # TODO: support virtual machines inside resource groups?
                if res.resource_type == "virtual_machine":
                    mach.append(res.machine)
        return mach

    def all_objects(self):
        yield self

    @property
    def effective_owner_grn(self):
        if self.owner_grn:
            return self.owner_grn
        else:
            return self.personality_stage.owner_grn

    @property
    def required_services(self):
        # Order matters in case the same key is present in both
        rqs = {dbsrv: None for dbsrv in self.operating_system.required_services}
        rqs.update(super(Host, self).required_services)
        return rqs

class HostGrnMap(Base):
    __tablename__ = _HOSTGRN

    host_id = Column(ForeignKey(Host.hardware_entity_id, ondelete="CASCADE"),
                     nullable=False)

    eon_id = Column(ForeignKey(Grn.eon_id), nullable=False)

    target = Column(AqStr(32), nullable=False)

    grn = relation(Grn, lazy=False, innerjoin=True)

    __table_args__ = (PrimaryKeyConstraint(host_id, eon_id, target),)

Host.grns = relation(HostGrnMap, cascade='all, delete-orphan',
                     passive_deletes=True)


#!/usr/bin/env python

tn_pairs = "/home/users/wooma/tn_pairs.txt"
fh = open(tn_pairs, "r")

switch_file = "/home/users/wooma/HLA_switching.txt"
switch_fh = open(switch_file, "w")
switch_fh.write("Subject_ID\tNormal\tTumor\n")

for line in fh:
	line = line.strip("\n").split("\t")
	if line[0] != "Subject_ID":
		subject = line[0]
		normal = line[1]
		tumor = line[2]
		if normal != "NA" and tumor != "SRR2588549":
			normal_opt = "/mnt/lustre1/CompBio/data/immunotherapy/HLA_typing/" + normal + "_result.tsv"
			normal_fh = open(normal_opt, "r")
			normal_fh.readline()
			line = normal_fh.readline().strip("\n").split("\t")
			norm_OptA1 = line[1]
			norm_OptA2 = line[2]
			norm_OptB1 = line[3]
			norm_OptB2 = line[4]
			norm_OptC1 = line[5]
			norm_OptC2 = line[6]
			normal_fh.close()
			tumor_opt = "/mnt/lustre1/CompBio/data/immunotherapy/HLA_typing/" + tumor + "_result.tsv"
			tumor_fh = open(tumor_opt, "r")
			tumor_fh.readline()
			line = tumor_fh.readline().strip("\n").split("\t")
			tum_OptA1 = line[1]
			tum_OptA2 = line[2]
			tum_OptB1 = line[3]
			tum_OptB2 = line[4]
			tum_OptC1 = line[5]
			tum_OptC2 = line[6]
			tumor_fh.close()
			match = True
			if norm_OptA1 != tum_OptA1 and norm_OptA1 != tum_OptA2:
				match = False
			if norm_OptA2 != tum_OptA1 and norm_OptA2 != tum_OptA2:
				match = False
			if norm_OptB1 != tum_OptB1 and norm_OptB1 != tum_OptB2:
				match = False
			if norm_OptB2 != tum_OptB1 and norm_OptB2 != tum_OptB2:
				match = False
			if norm_OptC1 != tum_OptC1 and norm_OptC1 != tum_OptC2:
				match = False
			if norm_OptC2 != tum_OptC1 and norm_OptC2 != tum_OptC2:
				match = False
			if match == False:
				switch_line = subject + "\t" + normal + "\t" + tumor + "\n"
				switch_fh.write(switch_line)

switch_fh.close()


import os
import sys
sys.path.append('hyungju/code/fenglab')
import json
import glob
import copy
import pathlib
import scipy.io
import scipy.ndimage
import natsort
import itertools
import lap
import cv2
import pandas as pd
import re
import math
import numpy as np
import ants
import shutil
import fnmatch

from zimg import *
from utils import io
from utils import img_util
from utils import nim_roi
from utils import region_annotation
from utils.logger import setup_logger
from tempfile import mktemp

def build_template(
    initial_template=None,
    image_list=None,
    iterations=3,
    gradient_step=0.2,
    blending_weight=0.75,
    weights=None,
    **kwargs
):
    """
    Estimate an optimal template from an input image_list
    ANTsR function: N/A
    Arguments
    ---------
    initial_template : ANTsImage
        initialization for the template building
    image_list : ANTsImages
        images from which to estimate template
    iterations : integer
        number of template building iterations
    gradient_step : scalar
        for shape update gradient
    blending_weight : scalar
        weight for image blending
    weights : vector
        weight for each input image
    kwargs : keyword args
        extra arguments passed to ants registration
    Returns
    -------
    ANTsImage
    Example
    -------
    >>> import ants
    >>> image = ants.image_read( ants.get_ants_data('r16') )
    >>> image2 = ants.image_read( ants.get_ants_data('r27') )
    >>> image3 = ants.image_read( ants.get_ants_data('r85') )
    >>> timage = ants.build_template( image_list = ( image, image2, image3 ) ).resample_image( (45,45))
    >>> timagew = ants.build_template( image_list = ( image, image2, image3 ), weights = (5,1,1) )
    """
    if "type_of_transform" not in kwargs:
        type_of_transform = "SyN"
    else:
        type_of_transform = kwargs.pop("type_of_transform")

    if weights is None:
        weights = np.repeat(1.0 / len(image_list), len(image_list))
    weights = [x / sum(weights) for x in weights]
    if initial_template is None:
        initial_template = image_list[0] * 0
        for i in range(len(image_list)):
            temp = image_list[i] * weights[i]
            temp = resample_image_to_target(temp, initial_template)
            initial_template = initial_template + temp

    xavg = initial_template.clone()
    for i in range(iterations):
        for k in range(len(image_list)):
            w1 = registration(
                xavg, image_list[k], type_of_transform=type_of_transform, **kwargs
            )
            if k == 0:
                wavg = iio.image_read(w1["fwdtransforms"][0]) * weights[k]
                xavgNew = w1["warpedmovout"] * weights[k]
            else:
                wavg = wavg + iio.image_read(w1["fwdtransforms"][0]) * weights[k]
                xavgNew = xavgNew + w1["warpedmovout"] * weights[k]
        print(wavg.abs().mean())
        wscl = (-1.0) * gradient_step
        wavg = wavg * wscl
        wavgfn = mktemp(suffix=".nii.gz")
        iio.image_write(wavg, wavgfn)
        xavg = apply_transforms(xavgNew, xavgNew, wavgfn)
        if blending_weight is not None:
            xavg = xavg * blending_weight + utils.iMath(xavg, "Sharpen") * (
                1.0 - blending_weight
            )

    return xavg

if __name__ == "__main__":

    folder = '/home/hyungjujeon/hyungju/data/aligned_volumes'
    (_, _, filenames) = next(os.walk(os.path.join(folder)))
    r = re.compile('.*tiff')
    filenames = list(filter(r.match, filenames))
    ch_list = []
    ants_image_list = [[]]*len(filenames)*2
    weights = np.repeat(1.0 / len(filenames), len(ch_list))

    for idx in range(len(filenames)):
        temp = ZImg(os.path.join(folder, filenames[idx]))
        img_data = temp.data[0][1,:,:,:].copy()
        temp = ants.from_numpy(np.moveaxis(img_data.astype('float32'), [0, 1], [-1, -2]))
        # temp = ants.image_read(os.path.join(folder, filenames[idx]))
        temp.set_spacing((10,10,100))
        # split_image = ants.split_channels(temp)
        ants_image_list[2*idx] = temp.resample_image((25,25,25))
        ants_image_list[2*idx+1] = ants.reflect_image(temp.resample_image((25,25,25)),0)

        image_ch = re.split("[_ .]",filenames[idx])[1:-1]
        for ch in image_ch:
            ch = ch.lower()
            if ch not in ch_list:
                ch_list.append(ch)
    weights = np.repeat(1.0 / len(ants_image_list), len(ch_list))

    # ants_template = build_template(image_list = ants_image_list)
    iterations = 30
    gradient_step = 0.2
    blending_weight = 0.5

    initial_name = os.path.join(folder, f'template_22.nii.gz')
    initial_template = ants.image_read(initial_name)
    initial_template.set_spacing((25, 25, 25))

    type_of_transform = "SyNAggro"
    # initial_template = ants_image_list[0] * 0
    # for i in range(len(ants_image_list)):
    #     temp = ants_image_list[i] * weights[0]
    #     temp = ants.resample_image_to_target(temp, initial_template)
    #     initial_template = initial_template + temp

    xavg = initial_template.clone()
    for i in range(1,iterations):
        for k in range(len(ants_image_list)):
            w1 = ants.registration(
                xavg, ants_image_list[k], type_of_transform=type_of_transform, verbose=False
            )
            if k == 0:
                wavg = ants.image_read(w1["fwdtransforms"][0]) * weights[0]
                xavgNew = w1["warpedmovout"] * weights[0]
            else:
                wavg = wavg + ants.image_read(w1["fwdtransforms"][0]) * weights[0]
                xavgNew = xavgNew + w1["warpedmovout"] * weights[0]
            fwdfn = os.path.join(folder, f'list_{k}_tform_0.nii.gz')
            shutil.copyfile(w1["fwdtransforms"][0], fwdfn)
            fwdfn = os.path.join(folder, f'list_{k}_tform_1.mat')
            shutil.copyfile(w1["fwdtransforms"][1], fwdfn)

        print(wavg.abs().mean())
        wscl = (-1.0) * gradient_step
        wavg = wavg * wscl
        wavgfn = mktemp(suffix=".nii.gz", dir=os.path.join(folder, 'temp'))
        ants.image_write(wavg, wavgfn)
        xavg = ants.apply_transforms(xavgNew, xavgNew, wavgfn)
        if blending_weight is not None:
            xavg = xavg * blending_weight + ants.iMath(xavg, "Sharpen") * (
                1.0 - blending_weight
            )
        os.remove(wavgfn)
        xavgfn = os.path.join(folder, f'template_{i}.nii.gz')
        ants.image_write(xavg, xavgfn)


from typing import List
import copy
import numpy as np
import scipy.stats
import augtxt.typo
import augtxt.order
import augtxt.punct
import re

fn_dict = {
    'typo.swap_consecutive': augtxt.typo.swap_consecutive,
    'typo.pressed_twice': augtxt.typo.pressed_twice,
    'typo.drop_char': augtxt.typo.drop_char,
    'typo.drop_n_next_twice': augtxt.typo.drop_n_next_twice,
    'typo.pressed_shiftalt': augtxt.typo.pressed_shiftalt,
}

def random_args(cfg_: dict):
    """ randomly pick alternative args """
    cfg = copy.copy(cfg_)
    for k, v in cfg.items():
        if isinstance(v, (list, tuple)):
            j = scipy.stats.randint.rvs(0, len(v))
            cfg[k] = v[j]
    return cfg

def wordtypo(original: str, settings: List[dict]) -> str:
    """Apply different augmentation functions to one word

    Parameters:
    -----------
    original : str

    settings : List[dict]

    Return:
    -------
    str
        The augmented variant of the input word

    Example:
    --------
        from augtxt.augmenters import wordtypo
        from collections import Counter
        import numpy as np
        np.random.seed(seed=42)

        settings = [
            {'p': 0.04, 'fn': 'typo.drop_n_next_twice',
             'args': {'loc': ['m', 'e'], 'keep_case': True}},
            {'p': 0.04, 'fn': 'typo.swap_consecutive',
             'args': {'loc': ['m', 'e'], 'keep_case': True}}]

        tokenseq = ["Dies", "ist", "ein", "Satz", "."]

        n_trials = 1000
        results = [' '.join([wordtypo(word, settings) for word in tokenseq])
                   for _ in range(n_trials)]

        Counter(results)
    """
    result = copy.copy(original)
    # loop over all augmentation methods in random order
    for i in np.random.permutation(len(settings)):
        # apply augmentation with a given probability
        if settings[i]['p'] >= scipy.stats.uniform.rvs():
            # read fn args and randomly pick alternative args
            cfg = random_args(settings[i]['args'])
            # augment the word
            result = fn_dict[settings[i]['fn']](result, **cfg)
    # next
    return result

def senttypo(original: str,
             settings: List[dict],
             exclude: List[str] = None,
             num_augmentations: int = 1,
             pmax: float = 0.1) -> List[str]:
    """ Apply different augmentation functions to at least one word or up
          a certain percentage of words in a sentence

    Parameters:
    -----------
    original : str
        The original sentence as string. If a List[str] it is assumed to be
          pretokenized.

    settings : List[dict]

    exclude : List[str]
        List of strings that are excluded from augmentation

    num_augmentations : int (default: 1)
        Number of augmentations to generate

    pmax : float (default 0.1)
        The maximum percentage of words per sentence to augment

    Return:
    -------
    List[str]
        The augmented variant of the input sentence

    Example:
    --------
        from augtxt.augmenters import senttypo
        import numpy as np
        np.random.seed(seed=42)

        settings = [
            {'weight': 1, 'fn': 'typo.drop_n_next_twice',
             'args': {'loc': ['m', 'e'], 'keep_case': True}},
            {'weight': 1, 'fn': 'typo.swap_consecutive',
             'args': {'loc': ['m', 'e'], 'keep_case': True}}]

        exclude = ["[MASK]", "[UNK]"]

        orginal = 'Die Lehrerin [MASK] einen Roman.'

        augm = senttypo(original, settings=settings, exclude=exclude, 2, 0.1)
    """
    # tokenization
    token = [t for t in re.split('[ .,;:!?]', original) if len(t) > 0]

    # number of words to augment
    num_aug = max(int(len(token) * pmax), 1)

    # which tokens are not excluded?
    if exclude is None:
        exclude = []
    indicies = np.where([t not in exclude for t in token])[0]

    if len(indicies) == 0:
        return []

    # extract settings for shuffling
    fns = [item.get("fn") for item in settings]
    configs = [item.get("args") for item in settings]
    weights = np.array([item.get("weight") for item in settings])
    p = weights / weights.sum()

    augmentations = []
    for _ in range(num_augmentations):
        augsent = copy.copy(original)
        # draw random tokens
        selected = np.random.choice(indicies, size=num_aug)
        # loop over selected tokens to augment them
        for i in selected:
            # get random augmentation function
            j = np.random.choice(range(len(p)), size=1, replace=False, p=p)[0]
            cfg = random_args(configs[j])
            # augment the choosen token
            augword = fn_dict[fns[j]](token[i], **cfg)
            # replace original word with augmented word
            augsent = augsent.replace(token[i], augword, 1)
        # save augmented sentence
        augmentations.append(augsent)
    # done
    return augmentations

fn_dict2 = {
    'order.swap_consecutive': augtxt.order.swap_consecutive,
    'order.drop_word': augtxt.order.drop_word,
    'order.write_twice': augtxt.order.write_twice,
    'order.drop_n_next_twice': augtxt.order.drop_n_next_twice
}

def sentaugm(sentence, settings, exclude=["[MASK]"]):
    """

    Example:
    --------
    from augtxt.augmenters import sentaugm
    import augtxt.keyboard_layouts as kbl
    import numpy as np

    typo_settings = [
        {'weight': 2, 'fn': 'typo.drop_n_next_twice',
        'args': {'loc': 'u', 'keep_case': True}},
        {'weight': 2, 'fn': 'typo.swap_consecutive',
        'args': {'loc': 'u', 'keep_case': True}},
        {'weight': 1, 'fn': 'typo.pressed_twice',
        'args': {'loc': 'u', 'keep_case': True}},
        {'weight': 1, 'fn': 'typo.drop_char',
        'args': {'loc': 'u', 'keep_case': True}},
        {'weight': 1, 'fn': 'typo.pressed_shiftalt',
        'args': {'loc': ['b', 'm']}, 'keymap': kbl.qwertz_de}
    ]

    order_settings = [
        {'weight': 3, 'fn': 'order.swap_consecutive'},
        {'weight': 2, 'fn': 'order.drop_word'},
        {'weight': 1, 'fn': 'order.write_twice'},
        {'weight': 1, 'fn': 'order.drop_n_next_twice'},
    ]

    settings = {
        "typo": {"num_augmentations": 6,
                 "settings": typo_settings, "pmax": 0.1},
        "punct": {"num_augmentations": 3},
        "order": {"num_augmentations": 6, "settings": order_settings}
    }

    np.random.seed(seed=42)
    exclude = ["[MASK]", "[UNK]"]
    sentence = 'Die Lehrerin [MASK] einen Roman.'
    augs = sentaugm(sentence, settings, exclude)
    """
    augs = []
    req_num = sum([v.get("num_augmentations") for _, v in settings.items()])
    for _ in range(2):
        # typographical errors
        if settings.get("typo"):
            augs.extend(augtxt.augmenters.senttypo(
                sentence, exclude=exclude, **settings.get("typo")))

        # interpunctation errors
        if settings.get("punct"):
            cfg = settings.get("punct")
            if cfg.get("num_augmentations", 0) > 0:
                augs.append(augtxt.punct.remove_syntaxinfo(sentence))
            if cfg.get("num_augmentations", 0) > 1:
                for _ in range(1, cfg.get("num_augmentations", 0)):
                    augs.append(augtxt.punct.merge_words(sentence, num_aug=1))

        # word order errors
        if settings.get("order"):
            cfg = settings.get("order")
            weights = np.array([item.get('weight') for item
                                in cfg.get("settings")])
            p = weights / weights.sum()
            idx = np.random.choice(range(len(p)),
                                   size=cfg.get("num_augmentations"),
                                   replace=True, p=p)
            for i in idx:
                fname = cfg.get("settings")[i].get('fn')
                augs.append(fn_dict2[fname](
                    sentence, exclude=exclude, num_aug=1))
        # done?
        if len(set(augs)) >= req_num:
            break
    # filter duplicates
    augs = list(set(augs))
    # chop excess
    return augs[:req_num]


"""16. Generați cel mai mare număr perfect mai mic decât un număr dat. Daca nu exista un astfel de
număr, tipăriți un mesaj. Un număr este perfect daca este egal cu suma divizorilor proprii. Ex. 6 este
un număr perfect (6=1+2+3)."""

import math
def perfect(x):
    suma = 0
    for div in range(1, math.ceil(x/2) + 1):
        if x%div == 0:
            suma = suma + div
    if suma == x:
        return 1
    return 0

n = int(input())
n = n - 1
if n < 6:
    print("nu exista")
else:
    while perfect(n) == 0:
        n = n - 1
    print(n)

Year 1/Semester 1/FP/labs/lab 02/ex16 perfect number.py


# Tính tổng của N số nguyên nhập vào
print("Chương trình tính tổng N số nguyên:")
n=int(input("N = "))
mylist=[]
for i in range(n):
    val=int(input("Nhập số nguyên : "))
    mylist.append(val)
S=0
for i in mylist:
    S+=i
print("S =",S)


"""Age Calculator."""

EARTHYEARINSECOND = 31557600.0

PLANETORBITALPERIOD = {
  'earth': 1.0,
  'mercury': 0.2408467,
  'venus': 0.61519726,
  'mars': 1.8808158,
  'jupiter': 11.862615,
  'saturn': 29.447498,
  'uranus': 84.016846,
  'neptune': 164.79132
}

class SpaceAge:
    """Calculate age for different planets."""
    def __init__(self, seconds):
        """Initialize new age calculator."""
        self.seconds = seconds
        for planet in PLANETORBITALPERIOD:
            self.add_method(planet)

    def _on_planet(self, planet):
        """Return age in planet year."""
        return round(self.seconds / EARTHYEARINSECOND / PLANETORBITALPERIOD[planet], 2)

    def add_method(self, planet):
        """Add method to return age in planet years."""
        function = lambda: self._on_planet(planet)
        function.__name__ = f'on_{planet}'
        function.__doc__ = f'Return age in {planet} years.'
        self.__setattr__(function.__name__, function)


"""
ORDER AND CART MANAGEMENT

Orders are sets of items ordered by a customer
An ordered item has four components:
 - a name
 - a quantity (the number of such items bought)
 - a unit price (in pence)
 - a unit weight (in pounds)
Those are represented by a tuple.

NOTE: You can safely assume that all orders have all the required fields
(name, quantity, unit-price and unit-weight) so no validation needs to be made.

DO NOT MODIFY CONSTANTS
"""

ORDER_SAMPLE_1 = {("lamp", 2, 2399, 2), ("chair", 4, 3199, 10), ("table", 1, 5599, 85)}
ORDER_SAMPLE_2 = {("sofa", 1, 18399, 140), ("bookshelf", 2, 4799, 40)}

CATALOGUE = {("table", 9999, 20), ("chair", 2999, 5), ("lamp", 1999, 10)}

def delivery_charges(order):
    """
    Compute the delivery charges for an order. The company charges a flat £50
    fee plus £20 for each 100lbs (additional weight under 100lbs is ignored).

    E.g., delivery_charges({("desk", 1, 11999, 160)}) is 7000 (pence)
    E.g., delivery_charges({("desk", 2, 11999, 160)}) is 11000 (pence)
    E.g., delivery_charges({("lamp", 1, 2399, 2)}) is 5000 (pence)
    E.g., delivery_charges({("lamp", 50, 2399, 2)}) is 7000 (pence)

    :param order: order to process. See samples for examples.
    :return: delivery fee in pence
    :rtype: float | int
    """
    def extract_deliverycharge(quantity, weight):
        total_weight = quantity * weight
        flat_fee = 50
        if total_weight < 100:
            total_fee = flat_fee *100.00
            print(total_fee)
            return total_fee
        else:

            total_fee = (((total_weight//100)*20) + flat_fee)*100
            print(total_fee)
            return total_fee

    total_delivery = 0
    for item in order:
        name =item[0]
        quantity = item[1]
        price =item[2]
        weight =item[3]

        total_delivery += extract_deliverycharge(quantity, weight)
        # total_delivery += total_fee
    print(total_delivery)

delivery_charges(order=ORDER_SAMPLE_2)


class Solution(object):
    def minSubArrayLen(self, target, nums):
        """
        :type target: int
        :type nums: List[int]
        :rtype: int
        """
        i,j=0,0
        mn=float("inf")
        sm=nums[0]
        while True:
            if sm>=target:
                mn= min(j-i+1,mn)
                sm-=nums[i]
                i+=1
            else:
                j+=1
                if j<len(nums):
                    sm+=nums[j]
                else:
                    break
        return mn if mn!=float("inf") else 0

a=[12,28,83,4,25,26,25,2,25,25,25,12]
# a=[2,3,1,2,4,3]
t=700
s=Solution()

l=s.minSubArrayLen(t,a)
print(l)


import pytest

import pandas as pd

from simba_ml.simulation import generators
from simba_ml.simulation import noisers
from simba_ml.simulation import system_model
from simba_ml.simulation.species import Species
from simba_ml.simulation import distributions
from simba_ml.simulation import kinetic_parameters as kinetic_parameters_module

def test_generator_returns_correct_result_when_no_noiser_is_provided():
    sm = get_converging_system_model()
    generator = generators.PertubationGenerator(sm)

    actual = generator.generate_signals(2)
    expected = pd.DataFrame(
        [
            {
                "unnoised_species_y": 1.0,
                "unnoised_kinetic_parameter_sledge": 0.0,
                "unnoised_steady_state_y": 1.0,
                "noised_species_y": 1.0,
                "noised_kinetic_parameter_sledge": 0.0,
                "noised_steady_state_y": 1.0,
            },
            {
                "unnoised_species_y": 1.0,
                "unnoised_kinetic_parameter_sledge": 0.0,
                "unnoised_steady_state_y": 1.0,
                "noised_species_y": 1.0,
                "noised_kinetic_parameter_sledge": 0.0,
                "noised_steady_state_y": 1.0,
            },
        ]
    )
    assert actual.equals(expected)

class DummyNoiser(noisers.Noiser):
    """The dummy noiser is used to test if the noiser is called."""

    def __init__(self):
        self.called = False

    def noisify(self, signal):
        self.called = True
        return signal

def test_generator_returns_correct_result_when_noisers_are_provided():
    sm = get_converging_system_model()
    kinetic_parameters_noiser = DummyNoiser()
    species_noiser = noisers.AdditiveNoiser(distributions.Constant(2.0))
    generator = generators.PertubationGenerator(
        sm,
        kinetic_parameters_noiser=kinetic_parameters_noiser,
        species_start_values_noiser=species_noiser,
    )

    actual = generator.generate_signals(2)
    expected = pd.DataFrame(
        [
            {
                "unnoised_species_y": 1.0,
                "unnoised_kinetic_parameter_sledge": 0.0,
                "unnoised_steady_state_y": 1.0,
                "noised_species_y": 3.0,
                "noised_kinetic_parameter_sledge": 0.0,
                "noised_steady_state_y": 3.0,
            },
            {
                "unnoised_species_y": 1.0,
                "unnoised_kinetic_parameter_sledge": 0.0,
                "unnoised_steady_state_y": 1.0,
                "noised_species_y": 3.0,
                "noised_kinetic_parameter_sledge": 0.0,
                "noised_steady_state_y": 3.0,
            },
        ]
    )

    assert actual.equals(expected)
    assert kinetic_parameters_noiser.called

def test_generator_raises_error_if_there_is_no_steady_state():
    sm = get_non_converging_system_model()
    generator = generators.PertubationGenerator(sm)

    with pytest.raises(ValueError):
        generator.generate_signals(2)

def test_generator_raises_error_if_there_is_no_steady_state_after_noising():
    sm = get_converging_system_model()
    generator = generators.PertubationGenerator(
        sm,
        kinetic_parameters_noiser=noisers.AdditiveNoiser(distributions.Constant(1.0)),
    )

    with pytest.raises(ValueError):
        generator.generate_signals(2)

def test_is_similar_thows_exception_if_series_have_different_length():
    sm = get_converging_system_model()
    generator = generators.PertubationGenerator(sm)
    s1 = pd.Series([1, 2, 3])
    s2 = pd.Series([1, 2, 3, 4])
    with pytest.raises(ValueError):
        generator._is_similar(s1, s2)  # pylint: disable=protected-access

def test_raises_error_if_non_constant_kinetic_parameter_is_provided():
    sm = get_converging_system_model()
    sm.kinetic_parameters[
        "sledge"
    ] = kinetic_parameters_module.DictBasedKineticParameter({0: 0.0, 10: 0.0})
    generator = generators.PertubationGenerator(sm)

    with pytest.raises(TypeError):
        generator.generate_signals(2)

def get_converging_system_model():
    name = "Converging System Model"
    timestamps = distributions.Constant(100)

    specieses = [Species("y", distributions.Constant(1.0))]

    args = {
        "sledge": kinetic_parameters_module.ConstantKineticParameter(
            distributions.Constant(0.0)
        )
    }

    def deriv(_t, _y, arguments):
        return arguments["sledge"]

    sm = system_model.SystemModel(
        name, specieses, args, deriv=deriv, timestamps=timestamps
    )
    return sm

def get_non_converging_system_model():
    name = "Non Converging System Model"
    timestamps = distributions.Constant(100)

    specieses = [Species("y", distributions.Constant(1.0))]

    args = {
        "sledge": kinetic_parameters_module.ConstantKineticParameter(
            distributions.Constant(1.0)
        )
    }

    def deriv(_t, _y, arguments):
        return arguments["sledge"]

    sm = system_model.SystemModel(
        name, specieses, args, deriv=deriv, timestamps=timestamps
    )
    return sm


def solution(answers):
    answer = []

    mh1 = [1, 2, 3, 4, 5]
    mh2 = [2, 1, 2, 3, 2, 4, 2, 5]
    mh3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]

    count = [0, 0, 0]

    for i in range(len(answers)):
        if answers[i] == mh1[i % len(mh1)]:
            count[0] += 1
        if answers[i] == mh2[i % len(mh2)]:
            count[1] += 1
        if answers[i] == mh3[i % len(mh3)]:
            count[2] += 1

    for j in range(3):
        if count[j] == max(count):
            answer.append(j + 1)

    return answer


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import random

from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators import text_problems
from tensor2tensor.data_generators import translate
from tensor2tensor.data_generators import wiki_lm
from tensor2tensor.utils import registry

_ENRO_TRAIN_DATASETS = [
    [
        "http://www.statmt.org/europarl/v7/ro-en.tgz",
        ("europarl-v7.ro-en.en", "europarl-v7.ro-en.ro")
    ],
    [
        "http://opus.nlpl.eu/download.php?f=SETIMES/v2/moses/en-ro.txt.zip",
        ("SETIMES.en-ro.en", "SETIMES.en-ro.ro")
    ]
]
_ENRO_TEST_DATASETS = [
    [
        ("http://data.statmt.org/wmt16/translation-task/"
         "dev-romanian-updated.tgz"),
        ("dev/newsdev2016-roen-ref.en.sgm", "dev/newsdev2016-roen-src.ro.sgm")
    ],
]

@registry.register_problem
class TranslateEnroWmt8k(translate.TranslateProblem):
  """Problem spec for WMT En-Ro translation."""

  @property
  def approx_vocab_size(self):
    return 2**13  # 8192

  def source_data_files(self, dataset_split):
    train = dataset_split == problem.DatasetSplit.TRAIN
    return _ENRO_TRAIN_DATASETS if train else _ENRO_TEST_DATASETS

@registry.register_problem
class TranslateEnroWmt32k(TranslateEnroWmt8k):

  @property
  def approx_vocab_size(self):
    return 2**15  # 32768

@registry.register_problem
class TranslateEnroWmtCharacters(TranslateEnroWmt8k):
  """Problem spec for WMT En-Ro translation."""

  @property
  def vocab_type(self):
    return text_problems.VocabType.CHARACTER

@registry.register_problem
class TranslateEnroWmtMulti64k(TranslateEnroWmt8k):
  """Translation with muli-lingual vocabulary."""

  @property
  def use_vocab_from_other_problem(self):
    return wiki_lm.LanguagemodelDeEnFrRoWiki64k()

@registry.register_problem
class TranslateEnroWmtMultiSmall64k(TranslateEnroWmt8k):
  """Translation with muli-lingual vocabulary, small (6K) training data."""

  @property
  def dataset_splits(self):
    """Splits of data to produce and number of output shards for each."""
    return [{
        "split": problem.DatasetSplit.TRAIN,
        "shards": 16,  # It's a small dataset, TPUs like at least a few shards.
    }, {
        "split": problem.DatasetSplit.EVAL,
        "shards": 1,
    }]

  @property
  def use_vocab_from_other_problem(self):
    return wiki_lm.LanguagemodelDeEnFrRoWiki64k()

  @property
  def how_many_examples_to_sample(self):
    return 6000

  def generate_samples(self, data_dir, tmp_dir, dataset_split):
    """Generate just the first 6k samples for training."""
    # If not training, do the same as before.
    if dataset_split != problem.DatasetSplit.TRAIN:
      for x in super(TranslateEnroWmtMultiSmall64k, self).generate_samples(
          data_dir, tmp_dir, dataset_split):
        yield x
      raise StopIteration
    # Now we assume we're training.
    counter = 0
    # The size of this data-set in total is around 614K, we want to sample so
    # that in expectation we take the requested number of samples in 1 go.
    sample_prob = self.how_many_examples_to_sample / float(614000)
    # Let's sample.
    for x in super(TranslateEnroWmtMultiSmall64k, self).generate_samples(
        data_dir, tmp_dir, dataset_split):
      if random.random() > sample_prob:
        continue
      counter += 1
      if counter > self.how_many_examples_to_sample:
        raise StopIteration
      yield x
    # We do it again if we don't have enough samples.
    if counter < self.how_many_examples_to_sample:
      for x in super(TranslateEnroWmtMultiSmall64k, self).generate_samples(
          data_dir, tmp_dir, dataset_split):
        if random.random() > sample_prob:
          continue
        counter += 1
        if counter > self.how_many_examples_to_sample:
          raise StopIteration
        yield x

@registry.register_problem
class TranslateEnroWmtMultiTiny64k(TranslateEnroWmtMultiSmall64k):
  """Translation with muli-lingual vocabulary, tiny (600) training data."""

  @property
  def how_many_examples_to_sample(self):
    return 600

@registry.register_problem
class TranslateEnroWmtMultiTiny64kPacked1k(TranslateEnroWmtMultiTiny64k):
  """Translation with muli-lingual vocabulary."""

  @property
  def packed_length(self):
    return 1024

  @property
  def num_training_examples(self):
    return 32

  @property
  def inputs_prefix(self):
    return "translate English Romanian "

  @property
  def targets_prefix(self):
    return "translate Romanian English "


# Импортируем библиотеку
import math

# Задаем координаты X, Y, Z
x = 10
y = 10
z = 0

# Вычисляем длину вектора
lvec = math.sqrt(x * x + y * y + z * z)

# Выводим длину вектора
print('Length = ', lvec)


decoration = "----------------------------------"

def data_entry():
	all_grades = []

	for i in range(3):
		student_grades = []

		for j in range(3):
			grade = float(input(f"Write the grade {j + 1} of the student {i + 1}: "))
			student_grades.append(grade)

		print(decoration)

		all_grades.append(student_grades)

	return all_grades

def student_average(student_grades):
	return round(sum(student_grades) / len(student_grades), 1)

def subject_averages(all_grades):
	averages = [0, 0, 0]

	for i in range(3):
		my_sum = 0

		for grades in all_grades:
			my_sum += grades[i]

		averages[i] = round(my_sum / 3, 1)

	return averages

# ------------------------------------- - ------------------------------------ #

all_grades = data_entry()
print(all_grades)
print("\t	 Stu.1  " + " Stu.2  " + " Stu.3  ")

for i, grades in enumerate(all_grades):
	print(f"{i + 1} Subject     {grades[0]}     {grades[1]}     {grades[2]}")

print(decoration)

for i, grades in enumerate(all_grades):
	average = student_average(grades)
	print(f"{i + 1} student average: {average}")

print(decoration)

for i, average in enumerate(subject_averages(all_grades)):
	print(f"{i + 1} subject average: {average}")

print(decoration)


from db import SessionLocal
from models import Client

# Función para obtener una sesión de base de datos
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

## Funcion que busca cliente por dni
def get_client_by_dni(dni: str):
    db = next(get_db())
    client = db.query(Client).filter(Client.dni == dni).first()
    if client == None:
        return None
    else:
            return client.__dict__

## Funcion que verifica el estado de BlackList recibiendo el cliente completo
def check_blacklist(client):
    blacklist = client.get("blacklist")
    print(blacklist)
    if blacklist == "True":
        return True
    else:
        return False


from rest_framework.serializers import ModelSerializer, StringRelatedField
from .models import Bom

class BomSerializer(ModelSerializer):
    item_id = StringRelatedField()
    workstation_id = StringRelatedField()
    class Meta:
        model = Bom
        fields = ('pk', 'item_id', 'workstation_id', 'production_rate')
        # lookup_field = 'ws_plant'


# simulation_tool.py
'''
本文件是写的界面与部分界面的设置
'''
from UI.simulation_exe_Form import Ui_Form  # 用designer设计的界面类
from PyQt5 import QtCore, QtGui, QtWidgets  # Qt的核心部件
from matplotlib import pyplot as plt  # 输出网络连接图需要的模块
import networkx as nx  # 输出网络连接图需要的模块
import pylab  # 输出网络连接图需要的模块

import sys  # 需要的部分内容
import os  # 需要的部分内容
import traceback
from time import sleep  # 测试可能需要的东西
from datetime import datetime  # 基本的仿真时间
from random import seed
seed(9527)

import xml.dom.minidom  # 系统使用的xml操作类
from xml.dom.minidom import parseString  # 用于转换符合xml文件标准的字符串为dom对象

import external_func  # 自己编写的外部函数模块
from external_func.read_file import read_xml_to_module  # 单独引用一下读取模块中的总和函数
from external_func.__scripts import read_scripts, run_script  # 单独引用一下脚本模块中读取与运行的函数

import members  # 自己编写的成员模块
from members.read_file import read_network, read_member, read_component_methods  # 读取网络与成员所需的函数

import pattren  # 自己编写的格局模块
from pattren.read_file import read_pattern  # 读取格局所需的函数

from other_tools import read_xml, write_xml, copy_file  # 读取与生成xml文件的方法
from record_maker import save_member_round_record, save_global_attribute_record  # 生成每一轮仿真纵览信息和所有成员的细节信息

inherited = bool()  # 仿真继承标志位

class MyThread(QtCore.QThread):
    _signal = QtCore.pyqtSignal(int)

    def __init__(self, generation_upper, global_dict):
        super(MyThread, self).__init__()
        self.current_generation = 0
        self.generation_upper = generation_upper
        self.global_dict = global_dict
        self.flag = False

    def run(self):
        while self.current_generation < self.generation_upper:
            if self.flag:
                self.current_generation += 1
                if inherited:
                    pass
                else:
                    load_old(self.global_dict)
                run_script(self.global_dict, self.current_generation)
                print("in Thread, current_generation:{}".format(self.current_generation))
                external_func.round_method(self.global_dict)
                for global_attr_func in external_func.global_attribute_func_ptrs:
                    global_attr_func(self.global_dict)
                self._signal.emit(self.current_generation)
                sleep(0.001)
            else:
                continue

def load_old(global_dict):
    external_func.global_attribute_dict = external_func.old_global_attribute_dict.copy()
    for k, v in external_func.global_attribute_dict.items():
        global_dict[v['aName']] = v['val']
    read_member(members.member_dom)
    read_network(members.member_dom)

class uf_Form(QtWidgets.QWidget, Ui_Form):

    def __init__(self, global_dict):
        super(uf_Form, self).__init__()
        # 加载UI
        self.MyThread = MyThread(0, global_dict)
        self.global_dict = global_dict
        self.setupUi(self)
        # 对UI中的部分控件进行设置
        self.setupUiAgain()
        # 加载本界面需要的一些资源
        self.setupResoure()
        # 设置所有的信号
        self.set_all_signal()
        # 设置所有的槽函数
        self.set_all_slot()
        # 设置不可更改窗口大小
        self.setFixedSize(self.width(), self.height())
        self.current_generation = 0
        self.flag = "waiting"
        self.start_moment = None
        self.end_moment = 0

    def set_all_slot(self):
        """
        设置所有的槽函数
        :return: no return
        """
        # 添加行按钮槽函数
        self.add_script_button.clicked.connect(self.slot_btn_add_oneRow)
        # 删除行按钮槽函数
        self.delete_script_button.clicked.connect(self.slot_btn_delete_oneRow)
        # 加载脚本按钮槽函数
        self.load_script_button.clicked.connect(self.slot_btn_load_script)
        # 重新设置脚本按钮槽函数
        self.reset_script_button.clicked.connect(self.slot_btn_reset_script)
        # 设置成员文件路径按钮槽函数
        self.members_filedialog_btn.clicked.connect(self.slot_btn_set_members_path)
        # 设置仿真定义文件路径按钮槽函数
        self.record_filedialog_btn.clicked.connect(self.slot_btn_set_record_path)
        # 设置表格脚本函数路径双击槽函数
        self.script_table_widget.itemDoubleClicked.connect(self.slot_btn_load_script_file_path)
        # 设置存储路径函数
        self.def_xml_filedialog_btn.clicked.connect(self.slot_btn_set_definition_path)
        # 设置轮方法槽函数
        self.start_btn.clicked.connect(self.emit_round_method)
        # 设置暂停槽函数
        self.pause_btn.clicked.connect(self.slot_btn_pause)
        # 设置终止槽函数
        self.stop_btn.clicked.connect(self.slot_terminate_simulation)
        # 设置显示网络函数
        self.show_nw_btn.clicked.connect(self.slot_btn_show_network)
        # 设置测试用按钮
        self.testButton.clicked.connect(self.slot_test_button)
        self.testButton.hide()
        ...

    def set_all_signal(self):
        self.MyThread._signal.connect(self.slot_return_from)
        # self.MyThread.finished.connect(a)
        ...

    def setupResoure(self):
        """
        设置窗口需要的各种资源
        :return: no return
        """
        # 播放按钮的图标
        self.start_btn_icon = QtGui.QIcon(r'.\UI\播放按钮.ico')
        # 暂停按钮的图标
        self.pause_btn_icon = QtGui.QIcon(r'.\UI\暂停.ico')
        # 停止按钮的图标
        self.stop_btn_icon = QtGui.QIcon(r'.\UI\停止.ico')
        # 初始化设置，将播放按钮图标设置为启动仿真的按钮
        self.start_btn.setIcon(self.start_btn_icon)
        self.pause_btn.setIcon(self.pause_btn_icon)
        # 初始化设置，将停止按钮的图标设置为停止仿真的按钮
        self.stop_btn.setIcon(self.stop_btn_icon)

    def setupUiAgain(self):
        """
        设置窗口中各种元素的编辑于排版
        :return:
        """
        # 脚本注册表的所有内容均靠左对齐
        self.script_table_widget.horizontalHeaderItem(0).setTextAlignment(QtCore.Qt.AlignLeft)
        self.script_table_widget.horizontalHeaderItem(1).setTextAlignment(QtCore.Qt.AlignLeft)
        self.script_table_widget.horizontalHeaderItem(2).setTextAlignment(QtCore.Qt.AlignLeft)
        # 设置脚本注册表三列的宽度
        self.script_table_widget.setColumnWidth(0, 100)
        self.script_table_widget.setColumnWidth(1, 200)
        self.script_table_widget.setColumnWidth(2, 538)
        # 设置脚本注册表行标可视
        self.script_table_widget.verticalHeader().setVisible(True)
        self.pause_btn.setEnabled(False)
        # 设置日期编辑栏获取当前日期
        self.modify_dateEdit.setDate(QtCore.QDate.currentDate())
        # self.script_table_widget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)

    def all_fill(self):
        """
        判断脚本注册表内容是否填满。
        :return: bool
        """
        # 获取行列数值
        rows_num = self.script_table_widget.rowCount()
        columns_num = self.script_table_widget.columnCount()
        # 双层循环判断对比
        for row in range(rows_num):
            for col in range(columns_num):
                # 如果循环的当前表格对应的item的内容为空，则返回False，表示未填满
                if self.script_table_widget.item(row, col).text() is "":
                    return False
        # 均通过判断，说明表格已经被填满，具备保存逻辑
        return True

    def slot_btn_load_script_file_path(self):
        """
        槽函数，用来保存已经注册的所有脚本函数为XML文件。
        :return:
        """
        # 判断当前表格可编辑，则表示未保存已有内容
        if self.add_script_button.isEnabled() and self.delete_script_button.isEnabled():
            # 获取单圈选中的表格里item对象
            item = self.script_table_widget.selectedItems()[0]
            # 双层循环嵌套遍历表格
            for row in range(self.script_table_widget.rowCount()):
                for col in range(self.script_table_widget.columnCount()):
                    # 判断选中的表格里item是否为第二列，即需要设置脚本函数所在文件路径的列且内容为空
                    if item == self.script_table_widget.item(row, col) and col == 2 and item.text() == "":
                        # 打开文件对话框，选择.py文件
                        py_scripts_path = QtWidgets.QFileDialog.getOpenFileName(self, "选择脚本py文件", "./",
                                                                                "XML Files (*.py);;All Files (*)")
                        # 当成功选择了一个文件时，设置路径
                        if py_scripts_path[0] is not "":
                            item.setText(py_scripts_path[0])
                        # 服务信息更新显示
                        self.service_msg_log_text.append(
                            str(datetime.now()) + ': ' + 'Read script from: ' + py_scripts_path[0])
                        return

    def slot_btn_load_script(self):
        """
        保存已经设置的脚本信息为xml文件槽函数
        :return:
        """
        # 设置将表格中的内容按列保存为xml
        if self.all_fill() and self.save_scripts_to_xml():
            # 设置脚本表格不可编辑
            self.script_table_widget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
            self.add_script_button.setEnabled(False)
            self.delete_script_button.setEnabled(False)
            # 一点提示信息
            self.script_setting_widget_status_label.setText("Script loaded.")
            QtWidgets.QMessageBox.information(self, 'Success', 'Scripts save succeed.')
            read_scripts(xml_dom=read_xml(external_func.scripts_file_path))
        else:
            QtWidgets.QMessageBox.warning(self, 'failure', 'Scripts save failed.\n Please check the form.')

    def slot_btn_reset_script(self):
        """
        重新设定脚本列表
        :return: no return
        """
        # 设置脚本表格可双击编辑
        self.script_table_widget.setEditTriggers(QtWidgets.QAbstractItemView.DoubleClicked)
        # 一点提示信息
        QtWidgets.QMessageBox.information(self, 'Reset', 'You can reset Scripts now.')
        # 设置添加按钮与删除按钮可用
        self.add_script_button.setEnabled(True)
        self.delete_script_button.setEnabled(True)
        # 更改一下标签状态
        self.script_setting_widget_status_label.setText("Script setting. ")

    def slot_btn_add_oneRow(self):
        """
        表格加一行槽函数
        :return: no return
        """
        # 首先获取一下行列数
        rows_num = self.script_table_widget.rowCount()
        columns_num = self.script_table_widget.columnCount()
        # 表格行数+1
        self.script_table_widget.setRowCount(self.script_table_widget.rowCount() + 1)
        # 对新添加的一行，每一列赋一个新的item
        for col in range(columns_num):
            item_data = QtWidgets.QTableWidgetItem("")
            self.script_table_widget.setItem(rows_num, col, item_data)

    def slot_btn_delete_oneRow(self):
        """
        删除脚本表一行
        :return: no return
        """
        # 表格数-1，已有的item会自动删除
        self.script_table_widget.setRowCount(self.script_table_widget.rowCount() - 1)

    def slot_btn_set_definition_path(self):
        """
        设置仿真定义文件路径
        :return: no return
        """
        try:
            xml_definition_path = QtWidgets.QFileDialog.getOpenFileName(self, "选择仿真定义xml文件", "./",
                                                                        "XML Files (*.xml);;All Files (*)")
            if xml_definition_path[0] == '' and xml_definition_path[0] == '':
                return
            self.def_xml_path_edit.setText(xml_definition_path[0])
            definition_dom = read_xml(xml_definition_path[0])
            external_func.external_func_file_path = xml_definition_path[0]
            read_xml_to_module(definition_dom, self.global_dict)
            external_func.round_method_dict['attributes']['num'] = 16549
            member_path_label = definition_dom.getElementsByTagName("memberModelFilePath")[0]
            self.members_xml_path_edit.setText(member_path_label.firstChild.data)
            def_id_label = definition_dom.getElementsByTagName("simulationExecutionMetaModel")[0]
            self.definition_ID_edit.setText(def_id_label.firstChild.data)
            member_meta_label = definition_dom.getElementsByTagName("memberMetaModelFilePath")[0]
            self.meta_member_ID_edit.setText(member_meta_label.firstChild.data)
            generation_label = definition_dom.getElementsByTagName("simulationRoundNumber")[0]
            self.generation_Edit.setText(generation_label.firstChild.data)
            self.MyThread.generation_upper = int(generation_label.firstChild.data)
            inherited_label = definition_dom.getElementsByTagName("inherited")[0]
            global inherited
            if int(inherited_label.firstChild.data):  # 如果继承数据
                self.inherited_Edit.setText("True")
                inherited = True
            else:
                self.inherited_Edit.setText("False")
                inherited = False
                self.step_size_Edit.setText("1")  # 如果不继承，则说明每一轮仿真都是从最初始状态开始的，那么步长将不存在意义
                self.step_size_Edit.setEnabled(False)
            # 根据这个路径来读取成员
            member_dom = read_xml(self.members_xml_path_edit.text())
            # 服务信息更新显示
            self.service_msg_log_text.append(
                str(datetime.now()) + ': ' + 'Read member from: ' + self.members_xml_path_edit.text())
            # 解析成员
            # global net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c
            # net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c = net_work_read(member_dom)
            # global primitives, advisers, monitorMembers, collectives
            # primitives, advisers, monitorMembers, collectives = member_read(member_dom)
            # 读取一下各个成员的数目与基本信息，并在界面上显示
            id_role_dict, member_number, p_number, c_number, a_number, m_number = format_members_id_role(member_dom)
            read_member(member_dom)
            read_network(member_dom)
            read_pattern(member_dom)
            read_component_methods(member_dom)

            members.member_dom = member_dom
            members.member_file_path = self.members_xml_path_edit.text()
            members.member_num = member_number
            self.reset_member_tableWidget(member_number, id_role_dict)
            self.primitive_num_edit.setText(str(p_number))
            self.adviser_num_edit.setText(str(a_number))
            self.monitor_num_edit.setText(str(m_number))
            self.collective_num_edit.setText(str(c_number))
            self.service_msg_log_text.append(
                str(datetime.now()) + ': ' + "Primitive:{}|Adviser:{}|Monitor:{}|Collective:{}".format(
                    p_number, a_number, m_number, c_number
                ))

            self.service_msg_log_text.append(
                str(datetime.now()) + ': ' + 'Read definition from: ' + member_path_label.firstChild.data)
        except Exception:
            raise
            # QtWidgets.QMessageBox.critical(self, "error", traceback.print_exc())
            # self.def_xml_path_edit.clear()
            # self.service_msg_log_text.append(str(datetime.now()) + ': ' + 'Setting definition file error. ')

    def slot_btn_set_members_path(self):
        """
        读取所有成员的路径的槽函数
        :return: no return
        """
        try:
            # 打开文件对话框
            xml_members_path = QtWidgets.QFileDialog.getOpenFileName(self, "选择仿真成员xml文件", "./",
                                                                     "XML Files (*.xml);;All Files (*)")
            self.members_xml_path_edit.setText(xml_members_path[0])
            # 根据这个路径来读取成员
            member_dom = read_xml(self.members_xml_path_edit.text())
            members.member_file_path = self.members_xml_path_edit.text()
            # 服务信息更新显示
            self.service_msg_log_text.append(
                str(datetime.now()) + ': ' + 'Read member from: ' + self.members_xml_path_edit.text())
            # 解析成员
            # global net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c
            # net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c = net_work_read(member_dom)
            # global primitives, advisers, monitorMembers, collectives
            # primitives, advisers, monitorMembers, collectives = member_read(member_dom)
            # 读取一下文件中的成员基本信息与数目，并在界面上刷新显示
            id_role_dict, member_number, p_number, c_number, a_number, m_number = format_members_id_role(member_dom)
            read_member(member_dom)
            read_network(member_dom)
            read_pattern(member_dom)
            read_component_methods(member_dom)

            members.member_dom = member_dom
            members.member_file_path = self.members_xml_path_edit.text()
            members.member_num = member_number
            self.reset_member_tableWidget(member_number, id_role_dict)
            self.primitive_num_edit.setText(str(p_number))
            self.adviser_num_edit.setText(str(a_number))
            self.monitor_num_edit.setText(str(m_number))
            self.collective_num_edit.setText(str(c_number))
            self.service_msg_log_text.append(
                str(datetime.now()) + ': ' + "Primitive:{}|Adviser:{}|Monitor:{}|Collective:{}".format(
                    p_number, a_number, m_number, c_number
                ))
        except:
            QtWidgets.QMessageBox.critical(self, "Error", traceback.print_exc())
            self.members_xml_path_edit.clear()
            self.service_msg_log_text.append(str(datetime.now()) + ': ' + 'Setting member XML file error. ')
            raise

    def slot_btn_pause(self):
        self.flag = "waiting"
        self.start_btn.setEnabled(True)
        self.pause_btn.setEnabled(False)
        self.MyThread.flag = False
        self.MyThread.wait()

    def slot_return_from(self, current):
        # 一个迭代的仿真结束了，需要判断一下仿真是否需要继承数据。
        self.current_generation = current
        # print("in widget, current_generation:{}".format(self.current_generation))
        self.exe_progress_bar.setValue(self.current_generation / external_func.round_number * 100)
        if current == external_func.round_number:
            self.slot_btn_pause()
            self.end_moment = datetime.now()
            self.service_msg_log_text.append(str(self.end_moment) + ": Simulation task completed.")
            record_dom = read_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml")
            record_dom_root = record_dom.getElementsByTagName("Result")[0]
            record_dom_root.setAttribute("EndMoment", str(self.end_moment))
            record_dom_root.setAttribute("TimeConsuming", str(self.end_moment - self.start_moment))
            write_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml", record_dom)
        if current % int(self.step_size_Edit.text()) == 0:
            self.MyThread.flag = False
            save_member_round_record(self.record_dir_path_edit.text(), current, self.global_dict,
                                     len(self.generation_Edit.text()))
            save_global_attribute_record(self.record_dir_path_edit.text(), current, self.global_dict)
            self.MyThread.flag = True

    def slot_btn_show_network(self):
        for i in range(members.network_list.__len__()):
            edge_labels = dict([((u, v,), format(d['strength'], '.2f'))
                                for u, v, d in members.network_list[i].edges(data=True)])
            plt.figure(members.network_list[i].graph['ID'])
            plt.title(members.network_list[i].graph['ID']+' network')
            pos = nx.spring_layout(members.network_list[i])
            nx.draw_networkx_edge_labels(members.network_list[i], pos, edge_labels=edge_labels)
            nx.draw(members.network_list[i], pos=pos, node_size=200, with_labels=True, font_weight='bold',
                    edge_cmap=plt.cm.Reds,font_size =9, font_color='g',node_color = 'c', edge_color = 'r')
            # plt.get_current_fig_manager().window.state('zoomed')
        pylab.show()

    def save_scripts_to_xml(self):
        """
        保存脚本列表设置到xml文件中，保存成功为True，失败为False。
        :return:bool
        """
        # 设置保存路径，为本项目下的external_file文件夹

        save_path = "external_module_file"
        # 设置文件名
        file_name = "script.xml"
        # 保存表格中的内容
        doc = xml.dom.minidom.Document()
        SCRIPTS = doc.createElement('Scripts')
        doc.appendChild(SCRIPTS)
        for row in range(self.script_table_widget.rowCount()):
            SCRIPT = doc.createElement('Script')
            SCRIPT.setAttribute("id", str(row))
            for col in range(self.script_table_widget.columnCount()):
                # 在第一列，需要判断输入的迭代数是否合法
                if col == 0:
                    the_round = self.script_table_widget.item(row, col).text()
                    try:
                        # 需要判断一下在round列中的输入是不是int且不大于回合数设置
                        if int(the_round) < int(self.generation_Edit.text()):
                            SCRIPT.setAttribute("round", the_round)
                        else:
                            QtWidgets.QMessageBox.critical(self, "error",
                                                           "in row: {}\nOver generation.".format(str(row + 1)))
                            return False
                    except ValueError:
                        QtWidgets.QMessageBox.critical(self, "error",
                                                       "in row: {}\nRound number error.".format(str(row + 1)))
                        return False
                # 第二列，单纯保存一下名字就可以了
                elif col == 1:
                    the_name = self.script_table_widget.item(row, col).text()
                    SCRIPT.setAttribute("funcName", the_name)
                # 第三列，需要分离出文件名与文件所在路径
                elif col == 2:
                    the_path = self.script_table_widget.item(row, col).text()
                    module_name = the_path.split('/')[-1].split('.')[0]
                    SCRIPT.setAttribute("moduleName", module_name)
                    script_path = '/'.join(the_path.split('/')[0:-1])
                    SCRIPT.setAttribute("path", script_path)
                # 其他未知错误
                else:
                    QtWidgets.QMessageBox.critical(self, "error",
                                                   "in row: {}\nRound number error.".format(str(row + 1)))
            SCRIPTS.appendChild(SCRIPT)
        # 保存
        write_xml(save_path + '/' + file_name, doc)
        self.service_msg_log_text.append(str(datetime.now()) + ': ' + "Setting scripts succeed." + "({})".format(
            str(self.script_table_widget.rowCount())))
        return True

    def reset_member_tableWidget(self, length, id_role_dict):
        """
        重新设置成员表格信息
        :param length: 成员数
        :param id_role_dict: 成员信息字典
        :return:
        """
        self.member_tableWidget.setRowCount(length)
        item = self.member_tableWidget.horizontalHeaderItem(0)
        item.setText(QtCore.QCoreApplication.translate("Form", "Member"))
        item = self.member_tableWidget.horizontalHeaderItem(1)
        item.setText(QtCore.QCoreApplication.translate("Form", "Role"))
        self.member_tableWidget.setHorizontalHeaderItem(1, item)
        temp_arrow = 0
        for id, role in zip(id_role_dict['id'], id_role_dict['role']):
            id_item, role_item = QtWidgets.QTableWidgetItem(), QtWidgets.QTableWidgetItem()
            id_item.setText(QtCore.QCoreApplication.translate("Form", id))
            role_item.setText(QtCore.QCoreApplication.translate("Form", role))
            self.member_tableWidget.setItem(temp_arrow, 0, id_item)
            self.member_tableWidget.setItem(temp_arrow, 1, role_item)
            temp_arrow += 1

    def slot_btn_set_record_path(self):
        """
        设置仿真结果路径保存的槽函数
        :return: no return
        """
        dir_record_path = QtWidgets.QFileDialog.getExistingDirectory(self, "选择仿真记录文件夹", os.getcwd())
        now = datetime.now()
        str_now = now.strftime("%Y-%m-%d %H-%M-%S")
        if dir_record_path == "":
            self.service_msg_log_text.append(str_now + ': ' + 'Unselect record save path.')
        else:
            self.record_dir_path_edit.setText(
                dir_record_path + "/" + str_now
            )
            self.service_msg_log_text.append(
                str(datetime.now()) + ': ' + 'Set record dictionary to: ' + dir_record_path)
            if not os.path.exists(self.record_dir_path_edit.text()):
                os.mkdir(self.record_dir_path_edit.text())
            # 需要有一个清空当前文件夹内容的操作
            # 需要初始化生成一个xml基础文件
            res = "<%s>""</%s>" % ("Result", "Result")
            record_dom = parseString(res)
            root = record_dom.getElementsByTagName("Result")[0]
            first_record_node = record_dom.createElement("Record")
            for v in external_func.global_attribute_dict.values():
                first_record_node.setAttribute(v['aName'], str(self.global_dict[v['aName']]))
            first_record_node.setAttribute("round", str(self.current_generation))
            root.appendChild(first_record_node)
            write_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml", record_dom)

    def start_check(self):
        if self.members_xml_path_edit.text() is "" or \
                self.def_xml_path_edit.text() is "" or \
                self.record_dir_path_edit.text() is "" or \
                self.version_edit.text() is "" or \
                self.step_size_Edit.text() is "" or \
                self.ex_ID_edit.text() is "" or \
                self.step_size_Edit.text() is "":
            return False
        else:
            record_dom = read_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml")
            record_dom_root = record_dom.getElementsByTagName("Result")[0]
            record_dom_root.setAttribute("ID", self.ex_ID_edit.text())
            record_dom_root.setAttribute("version", self.version_edit.text())
            record_dom_root.setAttribute("MetaMemberID", self.meta_member_ID_edit.text())
            record_dom_root.setAttribute("DefinitionID", self.definition_ID_edit.text())
            record_dom_root.setAttribute("RecordStepSize", self.step_size_Edit.text())
            record_dom_root.setAttribute("Inherited", str(eval(self.inherited_Edit.text())))
            record_dom_root.setAttribute("Datetime", self.modify_dateEdit.text())
            self.start_moment = datetime.now()
            record_dom_root.setAttribute("StartMoment", str(self.start_moment))
            write_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml", record_dom)
            return True

    def emit_round_method(self):
        if self.flag == "waiting" and self.start_check():
            self.flag = "running"
            self.start_btn.setEnabled(False)
            self.pause_btn.setEnabled(True)
            self.MyThread.flag = True
            save_member_round_record(self.record_dir_path_edit.text(), 0, self.global_dict,
                                     len(self.generation_Edit.text()))
            # 添加一个把脚本保存到仿真记录路径下的代码
            copy_file("external_file_for_cEvolution/script.xml", self.record_dir_path_edit.text() + '/')
            self.MyThread.start()
            self.service_msg_log_text.append(str(self.start_moment) + ": Simulation task started.")

    def slot_test_button(self):
        # 任何可能用来测试的功能
        save_global_attribute_record(self.record_dir_path_edit.text(), 0, self.global_dict)
        pass

    def slot_terminate_simulation(self):
        # 加一步状态检测
        if self.flag == "running":
            # 加一步询问
            reply = QtWidgets.QMessageBox.question(self, "Terminate Simulation",
                                                   "Are you sure you want to teminate this simulation?",
                                                   QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)

            if reply == QtWidgets.QMessageBox.Yes:
                self.MyThread.terminate()
                self.end_moment = datetime.now()
                self.service_msg_log_text.append(str(self.end_moment) + ": Simulation task terminated.")
                record_dom = read_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml")
                record_dom_root = record_dom.getElementsByTagName("Result")[0]
                record_dom_root.setAttribute("EndMoment", str(self.end_moment))
                record_dom_root.setAttribute("TimeConsuming", str(self.end_moment - self.start_moment))
                write_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml", record_dom)
                self.current_generation = 0
                self.flag = "waiting"
                self.start_btn.setEnabled(True)
                self.pause_btn.setEnabled(False)
                self.MyThread.flag = False
                self.MyThread.current_generation = 0
                self.start_moment = None
                self.end_moment = None

def format_members_id_role(xml_dom: xml.dom.minidom.Document):
    """
    格式化成员的id与角色，本函数仅用于获取仿真成员xml文件中的部分简单信息包含成员id，成员角色，各类成员的数量
    :param xml_dom: xml文件的dom对象
    :return: key为id与role的dict，成员总个数，primitive成员的数量，collective成员的数量，adviser成员的数量，monitor成员的数量
    """
    root = xml_dom.documentElement  # 获取dom对象的根
    # 初始化id_role字典
    id_role_dict = {
        'id': list(),
        'role': list()
    }
    member_info_labels = root.getElementsByTagName('memberInfo')  # 获取memberInfo标签
    primitive_number = len(root.getElementsByTagName('primitiveInfo'))  # 获取primitiveInfo标签
    collective_number = len(root.getElementsByTagName('collectiveInfo'))  # 获取collectiveInfo标签
    adviser_number = len(root.getElementsByTagName('adviserInfo'))  # 获取adviserInfo标签
    monitorMember_number = len(root.getElementsByTagName('monitorMemberInfo'))  # 获取monitorMemberInfo标签
    for one_member_info_label in member_info_labels:
        id_role_dict['id'].append(one_member_info_label.getAttribute('成员ID'))
        id_role_dict['role'].append(one_member_info_label.getAttribute('成员类型'))
    return id_role_dict, len(
        member_info_labels), primitive_number, collective_number, adviser_number, monitorMember_number

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = uf_Form(globals())
    window.setWindowTitle('众智网络仿真执行工具软件')
    window.show()
    exit(app.exec_())


# calculating the amount of debt when paying a bill in a restaurant.

def is_float_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

def get_bill():
    while True:
        bill=input("Enter, using a comma, how much money each guest contributed to pay the bill within a cent:").split(',')
        flag_correct = True
        sum = 0
        for k,value in enumerate(bill):
            if is_float_number(value) and float(value) >= 0:
                bill[k] = round(float(value),2)
                sum += bill[k]
            else:
                flag_correct = False
                break
        if flag_correct:
            return bill, sum, len(bill)
        else:
            print("Incorrect value.")

bill, sum, number_of_guests = get_bill()
pay_per_one=round(sum/number_of_guests,2)

# checking the possibility to split the bill equally
mistake = round(pay_per_one*number_of_guests - sum,2)
if mistake != 0:
    print(f"To make it possible to calculate, we will change the amount of money for the first guest ({mistake}).")
    sum =  round(pay_per_one*number_of_guests,2)
    bill[0] += mistake

# displaying general information about the bill in a restaurant
print(f"The total amount: {sum}. The amount per person: {pay_per_one}. Contribution of everyone: {bill}. ")

# creating a list of amounts of money that have lent or borrowed
contribution_of_everyone = [round(x-pay_per_one,2) for x in bill]

debtors_list = []
creditors_list = []

for k,value in enumerate(contribution_of_everyone):
    if value < 0:
        debtors_list.append([k+1,-value])
    elif value > 0:
        creditors_list.append([k+1,value])

if len(debtors_list) != 0:
    # calculating the amount of debt, add information in debtors_list about how much money and from whom the debtor borrowed
    # create variable to iterate for debtors_list
    k1=0
    for k,value in enumerate(creditors_list):
        while value[1] > 0:
            if debtors_list[k1][1] != 0 and debtors_list[k1][1] <= value[1]:
                balance = round(value[1] - debtors_list[k1][1],2)
                debtors_list[k1].append([creditors_list[k][0],debtors_list[k1][1]])
                creditors_list[k][1], debtors_list[k1][1] = balance, 0
                k1 += 1
            elif debtors_list[k1][1] != 0 and debtors_list[k1][1] > value[1]:
                debtors_list[k1].append([creditors_list[k][0], value[1]])
                debt = round(debtors_list[k1][1] - value[1],2)
                creditors_list[k][1], debtors_list[k1][1] = 0, debt

    # displaying a list of debtors
    for debtor in debtors_list:
        s=[]
        k=2
        number_of_debtor = len(debtor)
        while k < number_of_debtor:
            s.append(f"{debtor[k][0]} guest - {debtor[k][1]}$")
            k += 1
        s=", ".join(s)
        print(f"{debtor[0]} guest owes: {s}.")
else:
    print("No one owes nothing to nobody.")


"""
Attempt at "translating" the NCL function pattern_corr to Python.
See http://www.ncl.ucar.edu/Support/talk_archives/2011/att-2603/tst_pattern_cor2.ncl
"""

# imports
import numpy as np

def pattern_corr(x, y, w=None, opt=0):

    """
    Function for calculating the Pearson product-moment coefficient of linear correlation between two variables that are
    respectively the values of the same variables at corresponding locations on two different maps. The function is
    mostly adapted from the NCL function of the same name. See:
        https://www.ncl.ucar.edu/Document/Functions/Contributed/pattern_cor.shtml

    Parameters:
        :param x: 2d- or 3d-Numpy array with last dimensions [..., lat, lon].
        :param y: 2d- or 3d-Numpy array. Must have same shape as x.
        :param w: Optional. Numpy array of weights. Must have same shape as x and y. Defaults to None.
        :param opt: Integer. opt=0 means a centered pattern correlations will be performed, i.e., the field means of x
                    and y will be subtracted first. opt=1 means an uncentered pattern correlations will be performed,
                    i.e., the field means of x and y will NOT be subtracted. Defaults to 0.
    """

    # if no weights are given set the weights array to an array with the same shape as x and y but containing only values
    # of 1 so that the average is calculated correctly below
    if w is None:
        w = np.ones(np.shape(x))
    # end if

    # x and y must have same dimensions
    if np.ndim(x) != np.ndim(y):
        raise Exception("Error: Dimensions of x and y do not match!")
    # end if

    # if the arrays are 3d make sure the means are only taken for the last two dimensions
    ax = 0
    if np.ndim(x) == 3:
        ax = 1
    # end if

    # centered correlation
    if opt == 0:
        x_avg_area = np.sum(x * w, axis=(0+ax, 1+ax)) / np.sum(w, axis=(0+ax, 1+ax))
        y_avg_area = np.sum(y * w, axis=(0+ax, 1+ax)) / np.sum(w, axis=(0+ax, 1+ax))

        if np.ndim(x) == 3:
            x_anom = x[:, :, :] - x_avg_area[:, None, None]
            y_anom = y[:, :, :] - y_avg_area[:, None, None]
        else:
            x_anom = x - x_avg_area
            y_anom = y - y_avg_area
        # end if else

        xy_cov = np.sum(w * x_anom * y_anom, axis=(0+ax, 1+ax))
        x_anom2 = np.sum(w * x_anom**2, axis=(0+ax, 1+ax))
        y_anom2 = np.sum(w * y_anom**2, axis=(0+ax, 1+ax))

    # uncentered correlation
    elif opt == 1:
        xy_cov = np.sum(w * x * y, axis=(0+ax, 1+ax))
        x_anom2 = np.sum(w * x**2, axis=(0+ax, 1+ax))
        y_anom2 = np.sum(w * y**2, axis=(0+ax, 1+ax))
    # end if elif

    if np.any(x_anom2 > 0) & np.any(y_anom2 > 0):
        r = xy_cov / (np.sqrt(x_anom2) * np.sqrt(y_anom2))
        return r
    else:
        raise Exception("Error: Sum of squares < 0, division by zero.")
    # end if else

# end function pattern_corr


import os, sys
lib_path = os.path.abspath(os.path.join('..'))
sys.path.append(lib_path)

from util import hex_to_base_n, permutation_from_hex

symbols33 = '0123456789abcdefghijklmnopqrstuvw'
symbols16 = '0123456789abcdef'
hex64 = '8d98fb67850b4fd740330f2e5067595962c61ac86a3358ba5a4de55e66ff5704'

base16 = hex_to_base_n(hex64, symbols16)
base16.reverse()
assert(hex64 == ''.join(base16))

base33 = hex_to_base_n(hex64, symbols33)

permutation = permutation_from_hex(hex64, symbols33, False)

assert(base33 == permutation[0])

uniq_results, reset_x = permutation_from_hex(hex64, symbols16, True, 33)
uniq_results.reverse()
print(''.join(uniq_results))


from __future__ import annotations

import random
from dataclasses import dataclass

import torch
from torch import Tensor, nn

def apply_rgb_gain(image: Tensor, rgb_gain: float, red_gain: float, blue_gain: float) -> Tensor:
    """Applies gains to an image."""
    assert image.dim() == 3
    channels = image.shape[0]
    assert channels == 3 or channels == 4
    middle = [1.0] * (channels // 2)

    gains = torch.tensor([red_gain, *middle, blue_gain], dtype=image.dtype, device=image.device) * rgb_gain
    gains = gains.view(-1, 1, 1)

    return (image * gains).clamp(0.0, 1.0)

def invert_rgb_gain(image: Tensor, rgb_gain: float, red_gain: float, blue_gain: float) -> Tensor:
    """Inverts gains while safely handling saturated pixels."""
    assert image.dim() == 3
    assert image.shape[0] == 3

    gains = (
        torch.tensor(
            [1.0 / red_gain, 1.0, 1.0 / blue_gain],
            dtype=image.dtype,
            device=image.device,
        )
        / rgb_gain
    )
    gains = gains.view(-1, 1, 1)

    # Prevents dimming of saturated pixels by smoothly masking gains near white.
    gray = image.mean(dim=0, keepdim=True)
    inflection = 0.9
    mask = ((gray - inflection) / (1.0 - inflection)).clamp(0.0) ** 2.0

    safe_gains = torch.max(input=mask + (1.0 - mask) * gains, other=gains)  # type: ignore
    return image * safe_gains

def random_rgb_gain(
    rgb_gain_mu: float = 0.8,
    rgb_gain_sigma: float = 0.1,
    red_gain_min: float = 1.9,
    red_gain_max: float = 2.4,
    blue_gain_min: float = 1.5,
    blue_gain_max: float = 1.9,
) -> tuple[float, float, float]:
    """Generates random gains for brightening and white balance."""
    rgb_gain = 1.0 / random.gauss(rgb_gain_mu, rgb_gain_sigma)
    red_gain = random.uniform(red_gain_min, red_gain_max)
    blue_gain = random.uniform(blue_gain_min, blue_gain_max)
    return rgb_gain, red_gain, blue_gain

@dataclass(eq=False)
class RgbGain(nn.Module):
    """Container for gains.
    RGB gain represents brightening.
    Red and blue gains represent white balance.
    """

    rgb_gain: float
    red_gain: float
    blue_gain: float

    def __post_init__(self) -> None:
        super().__init__()

    @staticmethod
    def random(
        rgb_gain_mu: float = 0.8,
        rgb_gain_sigma: float = 0.1,
        red_gain_min: float = 1.9,
        red_gain_max: float = 2.4,
        blue_gain_min: float = 1.5,
        blue_gain_max: float = 1.9,
    ) -> RgbGain:
        return RgbGain(
            *random_rgb_gain(
                rgb_gain_mu,
                rgb_gain_sigma,
                red_gain_min,
                red_gain_max,
                blue_gain_min,
                blue_gain_max,
            )
        )

    def forward(self, image: Tensor) -> Tensor:  # type: ignore
        """Applies gains to an image."""
        return apply_rgb_gain(image, self.rgb_gain, self.red_gain, self.blue_gain)

    def invert_rgb_gain(self, image: Tensor) -> Tensor:
        """Inverts gains while safely handling saturated pixels."""
        return invert_rgb_gain(image, self.rgb_gain, self.red_gain, self.blue_gain)


import random
class Solution:
    def pickIndex(self,nums):
        total = sum(nums)
        rndm = random.uniform(0,1)

        for i,val in enumerate(nums):
            nums[i] = val/total
            if rndm < sum(nums[:i+1]):
                return i

        #rnd = random.uniform(0,1)
        #for i in range(len(nums)):
         #   if rnd < sum(nums[:i+1]):
          #      return i

nums = [1,2,3]
mySol = Solution()
print(mySol.pickIndex(nums))


#!/usr/bin/env python3

from PIL import Image
from PIL import ImageFilter
from random import randint
import numpy, blend_modes # For overlay blending
import glob, os, sys

from tools import openttd_palettise, palette_image, openttd_palette_image, check_update_needed, blend_overlay

if os.path.isdir("pygen") == False: os.mkdir("pygen")

verbose = True
scale = int(sys.argv[1])
tile_size = scale * 64

mode = sys.argv[2]

if mode == "normal":
  # Terrain sprites to use
  terrain_list = {
    "arctic_grass_gridline": os.path.join("pygen", "arctic_groundtiles_gridline_32bpp.png"),
    "arctic_snow_gridline": os.path.join("pygen", "arctic_groundtiles_snow_gridline_32bpp.png"),
    "tropical_grass_gridline": os.path.join("pygen", "tropical_groundtiles_gridline_32bpp.png"),
    "tropical_desert_gridline": os.path.join("pygen", "tropical_groundtiles_desert_gridline_32bpp.png"),
    "temperate_grass_gridline": os.path.join("pygen", "temperate_groundtiles_gridline_32bpp.png"),
    "general_concrete": "general_concretetiles_32bpp.png",
    "arctic_grass_nogridline": os.path.join("pygen", "arctic_groundtiles_nogridline_32bpp.png"),
    "arctic_snow_nogridline": os.path.join("pygen", "arctic_groundtiles_snow_nogridline_32bpp.png"),
    "tropical_grass_nogridline": os.path.join("pygen", "tropical_groundtiles_nogridline_32bpp.png"),
    "tropical_desert_nogridline": os.path.join("pygen", "tropical_groundtiles_desert_nogridline_32bpp.png"),
    "temperate_grass_nogridline": os.path.join("pygen", "temperate_groundtiles_nogridline_32bpp.png")
  }
  shoreline_overlay_path = "shorelines_overlaynormal.png"
elif mode == "toyland":
  terrain_list = {
    "toyland_grass_gridline": os.path.join("pygen", "toyland_shoretiles_gridline_32bpp.png"),
    "toyland_grass_nogridline": os.path.join("pygen", "toyland_shoretiles_nogridline_32bpp.png")
  }
  shoreline_overlay_path = "shorelines_toyland_overlaynormal.png"

print("Running in scale "+str(scale)+" (tile size "+str(tile_size)+")")
for terrain_key in terrain_list:
  print("  "+terrain_key)
  terrain_image_path = terrain_list[terrain_key]
  shoreline_shading_path = "shorelines_overlayshading.png"
  output_main_path = os.path.join("pygen", terrain_key+"_shoretiles_palmask.png")
  output_palmask_path = os.path.join("pygen", terrain_key+"_shoretiles_32bpp.png")
  if check_update_needed([terrain_image_path, shoreline_overlay_path, shoreline_shading_path], output_main_path):
    terrain_image = Image.open(terrain_list[terrain_key]).convert("RGB")
    shore_image = Image.open(shoreline_overlay_path)
    shore_image = openttd_palettise(shore_image)
    width, height = shore_image.size
    target_image = terrain_image.crop((0, 0, width, height))
    # Save shore_image as palmask image
    shore_image.save(os.path.join("pygen", terrain_key+"_shoretiles_palmask.png"))
    # Overlay shading, if it exists
    target_image = target_image.convert("RGBA")
    if os.path.isfile("shorelines_overlayshading.png") and mode == "normal":
      print("shorelines_overlayshading.png")
      shoreline_shading = Image.open("shorelines_overlayshading.png").convert("RGBA")
      target_image = blend_overlay(target_image, shoreline_shading, 192/255)
    # Overlay shore_image onto target_image using blue as transparent
    v = [255] * 256
    v[0] = 0
    mask_palimg = palette_image(v, v, v)
    shore_mask = shore_image.copy()
    shore_mask.putpalette(mask_palimg.getpalette())
    shore_mask = shore_mask.convert("L")
    target_image.paste(shore_image, (0, 0), shore_mask)
    # Save
    target_image.save(os.path.join("pygen", terrain_key+"_shoretiles_32bpp.png"))


from discord.ext import commands
from user_data import UserData
import json
import discord

class CopyWatchlist(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(aliases=["copy", "copywatchlist"], pass_context=True, description="Copies the watchlist of the "
                                                                                "given user"
                                                                                "and makes it your own!")
    async def copy_watchlist(self, ctx, *, user_input):
        username = str(ctx.author)
        user = UserData.create_user_instance_by_name(username)
        other_user = UserData.create_user_instance_by_name(user_input)

        if username == user_input:
            return

        with open(other_user.get_full_path_for_edit(), "r+") as f:
            data = json.load(f)
            watchlist = data["Watchlist"][0]

            if len(watchlist) == 0:
                await ctx.channel.send(f"{other_user.username} doesn't have a watchlist! Be sure to enter their name "
                                       f"correctly along with their # ID.")
                return

            new_watchlist = watchlist

        with open(user.get_full_path_for_edit(), "r+") as f:
            data = json.load(f)
            data["Watchlist"][0] = new_watchlist

            await user.update_watchlist(data)
            await ctx.message.add_reaction("👍")

def setup(client):
    client.add_cog(CopyWatchlist(client))


import discord
from main import Client
from discord.ext.commands import Cog, MissingRole, CommandOnCooldown
import time

class ErrorHandler(Cog):

    def __init__(self, bot: Client):
        self.bot = bot

    @Cog.listener()
    async def on_command_error(self, ctx, error):
        if isinstance(error, MissingRole):
            embed1 = discord.Embed(title="Error", description="Missing Permission!", colour=discord.Colour.red())
            await ctx.send(embed=embed1)

        if isinstance(error, CommandOnCooldown):
            embed = discord.Embed(title="Error", description='Can\'t ping. Try again in <t:{}:R>'.format(int(time.time() + error.retry_after)),
                                  colour=discord.Colour.red())
            await ctx.send(embed=embed, delete_after=60)

async def setup(bot: Client):
    await bot.add_cog(
        ErrorHandler(bot),
        guilds=[discord.Object(id=1040220674226139206)]
    )


from typing import Callable, Optional, Type

import mesa

class RandomActivationByTypeFiltered(mesa.time.RandomActivationByType):
    """
    A scheduler that overrides the get_type_count method to allow for filtering
    of agents by a function before counting.

    Example:
    >>> scheduler = RandomActivationByTypeFiltered(model)
    >>> scheduler.get_type_count(AgentA, lambda agent: agent.some_attribute > 10)
    """

    def get_type_count(
        self,
        type_class: Type[mesa.Agent],
        filter_func: Optional[Callable[[mesa.Agent], bool]] = None,
    ) -> int:
        """
        Returns the current number of agents of certain type in the queue
        that satisfy the filter function.
        """
        count = 0
        for agent in self.agents_by_type[type_class].values():
            if filter_func is None or filter_func(agent):
                count += 1
        return count