# -*- coding: utf-8 -*-
# Question 4
# Author: Weining Qu (wq2155)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from evaluation import *

def NBClassifier(data, target):
    Y = data[target].values
    X_all = data[[col for col in data.columns if col != target]]

    # Categorize data by target class
    X_byclass = {}
    Y_byclass = {}
    phi = {}
    for i in np.unique(Y):
        X_byclass[i] = X_all[Y == i]
        Y_byclass[i] = Y[Y == i]
        phi[i] = (len(Y_byclass[i])+1)/ (len(Y)+2)

    # Calculate count probabilities of features
    prob_X = {}
    for i in np.unique(Y):
        prob_X[i] = {}
        for j in range(X_all.shape[1]):
            X_j = X_byclass[i].iloc[:,j]
            prob_X[i][j] = X_j.value_counts()/len(X_j)

        # Model "age" feature as continuous variable following Gaussian distribution
        prob_X[i][1] = [np.mean(X_byclass[i].iloc[:, 1]), np.var(X_byclass[i].iloc[:, 1])]
    return phi, prob_X

def NBpredict(testX, phi, prob_X):
    def GaussianProb(x, mean, var):
        # (np.exp(-(x-mean)**2/(2*var)))*(1/np.sqrt(2*np.pi*var))
        gaussian_prob = np.exp(-(x-mean)**2/(2*var)) * (1/np.sqrt(2*np.pi*var))
        return gaussian_prob

    predY = []
    predY_prob = []
    for i in range(testX.shape[0]):
        X_i = testX.iloc[i,:].values
        Cond_pos = 1
        for s in range(len(X_i)):
            if (s != 1) and (X_i[s] in prob_X[1][s].index.tolist()):
                Cond_pos = Cond_pos * prob_X[1][s][X_i[s]]
            else:  # "age"
                Cond_pos = Cond_pos * GaussianProb(X_i[s],prob_X[1][s][0], prob_X[1][s][1])
        prob_pos = phi[1] * Cond_pos

        Cond_neg = 1
        for s in range(len(X_i)):
            if (s != 1) and (X_i[s] in prob_X[0][s].index.tolist()):
                Cond_neg = Cond_neg * prob_X[0][s][X_i[s]]
            else:  # "age"
                Cond_neg = Cond_neg * GaussianProb(X_i[s], prob_X[1][s][0], prob_X[1][s][1])
        prob_neg = phi[0] * Cond_neg

        if prob_pos >= prob_neg:
            predY.append(1)
            predY_prob.append(1-prob_pos)
        else:
            predY.append(0)
            predY_prob.append(prob_neg)
    predY = np.array(predY)
    predY_prob = np.array(predY_prob)

    return predY, predY_prob

################ Evaluation ###########################################################
def Accuracy(pred, true):
    return sum(pred == true) / len(pred)

def Test_trainsize(traindata, testdata, target):
    accu_pair = []
    for s in range(1,11):
        N = int(traindata.shape[0] * s/10)
        tr_part = traindata.iloc[:N,:]
        # print(tr_part)
        phi, prob_X = NBClassifier(tr_part, target)
        testX = testdata[[col for col in testdata.columns if col != target]]
        testY = testdata[target]
        predY, predprobY = NBpredict(testX, phi, prob_X)
        accuracy_test = Accuracy(predY, testY)
        accu_pair.append((N, accuracy_test))
    x, y = zip(*accu_pair)
    y_max = np.argmax(y)
    plt.figure()
    plt.plot(x,y)
    plt.scatter(x[y_max],y[y_max], c='red')
    plt.xlabel("Training sample size")
    plt.ylabel("Accuracy")
    plt.title("Naive Bayes")
    plt.savefig("./Fig/NB_trainsizetest.png")
    plt.show()

    return accu_pair

if __name__ == "__main__":
    traindata = pd.read_csv("propublicaTrain.csv", sep=',')
    testdata = pd.read_csv("propublicaTest.csv", sep=',')
    target = 'two_year_recid'

    phi, prob_X = NBClassifier(traindata, target)
    testX = testdata[[col for col in testdata.columns if col != target]]
    testY = testdata[target]

    predY, predprobY = NBpredict(testX, phi, prob_X)
    accuracy_test = Accuracy(predY, testY)
    print("Testdata accuracy: {:.4f}".format(accuracy_test))

    plot_roc(testY, predprobY, "NB")  # ROC Curve and AUC

    accu_diffsize = Test_trainsize(traindata, testdata, target)  # Test training sample size effect

    ############## Fairness analysis ################################################################
    df = pd.concat([testX['race'], pd.Series(predY), testY], axis=1)
    df.columns = ['race', 'ypred', 'ytrue']
    # Demographic parity
    df_race0 = df[df['race'] == 0]
    df_race1 = df[df['race'] == 1]
    p_race0_0 = (df_race0.shape[0] - df_race0['ypred'].sum()) / df_race0.shape[0]
    p_race0_1 = df_race0['ypred'].sum() / df_race0.shape[0]
    p_race1_0 = (df_race1.shape[0] - df_race1['ypred'].sum()) / df_race1.shape[0]
    p_race1_1 = df_race1['ypred'].sum() / df_race1.shape[0]

    # Equalized Odds (EO)
    df_race0_y0 = df_race0[df_race0['ytrue'] == 0]
    eo_race0_00 = (df_race0_y0.shape[0] - df_race0_y0['ypred'].sum()) / df_race0_y0.shape[0]
    df_race0_y1 = df_race0[df_race0['ytrue'] == 1]
    eo_race0_11 = df_race0_y1['ypred'].sum() / df_race0_y1.shape[0]
    df_race1_y0 = df_race1[df_race1['ytrue'] == 0]
    eo_race1_00 = (df_race1_y0.shape[0] - df_race1_y0['ypred'].sum()) / df_race1_y0.shape[0]
    df_race1_y1 = df_race1[df_race1['ytrue'] == 1]
    eo_race1_11 = df_race1_y1['ypred'].sum() / df_race1_y1.shape[0]

    # Predictive Parity (PP)
    df_race0_hy0 = df_race0[df_race0['ypred'] == 0]
    pp_race0_00 = (df_race0_hy0.shape[0] - df_race0_hy0['ytrue'].sum()) / df_race0_hy0.shape[0]
    df_race0_hy1 = df_race0[df_race0['ypred'] == 1]
    pp_race0_11 = df_race0_hy1['ytrue'].sum() / df_race0_hy1.shape[0]
    df_race1_hy0 = df_race1[df_race1['ypred'] == 0]
    pp_race1_00 = (df_race1_hy0.shape[0] - df_race1_hy0['ytrue'].sum()) / df_race1_hy0.shape[0]
    df_race1_hy1 = df_race1[df_race1['ypred'] == 1]
    pp_race1_11 = df_race1_y1['ytrue'].sum() / df_race1_y1.shape[0]


import torch
from transformers import BertTokenizer, BertForMaskedLM
from opencc import OpenCC

from utils.pinyin import get_sim_pronunciation

cc = OpenCC('s2t')

class Corrector():
    def __init__(self):
        self.tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
        self.model = BertForMaskedLM.from_pretrained('bert-base-chinese')
        self.model.eval()

    def predict_mask(self, sentence, error_id):
        text = '[CLS] '+' '.join(sentence)+' [SEP]'
        tokenized_text = self.tokenizer.tokenize(text)
        tokenized_text[error_id] = '[MASK]'

        indexed_tokens = self.tokenizer.convert_tokens_to_ids(tokenized_text)
        segments_ids = [0 for _ in range(len(sentence) + 2)]

        tokens_tensor = torch.tensor([indexed_tokens])
        segments_tensors = torch.tensor([segments_ids])

        with torch.no_grad():
            predictions = self.model(tokens_tensor, segments_tensors)[0]

        predicted_index = torch.topk(predictions[0, error_id], 5)[1].cpu().numpy()
        list_mask_items = []
        for i in predicted_index:
            predicted_token = self.tokenizer.convert_ids_to_tokens([i])[0]
            list_mask_items.append(predicted_token)

        return list_mask_items

    def correct_with_bert(self, sentence):
        correct_result = []
        for i, char in enumerate(sentence):
            org_char_pinyin = get_sim_pronunciation(char)
            list_maybe_right = self.predict_mask(sentence, i + 1)
            for c in list_maybe_right:
                if get_sim_pronunciation(c) == org_char_pinyin:
                    if cc.convert(c) != char:
                        correct_result.append([i, c])
                    break

        return correct_result


import imp
from os import environ, path

from openpyxl import load_workbook  # pylint: disable=W7936

from odoo.modules import get_module_resource
from odoo.tools import file_open

pyfile = get_module_resource(
    "l10n_eu_product_adr", "scripts", "import_adr_multilang_xlsx.py"
)
name, ext = path.splitext(path.basename(pyfile))
fp, pathname = file_open(pyfile, pathinfo=True)
mod = imp.load_module(name, fp, pathname, (".py", "r", imp.PY_SOURCE))
get_xml_id = mod.get_xml_id

env = self.env  # noqa
skiprows = 3
columns = {
    1: "nl_NL",
    3: "de_DE",
    4: "fr_FR",
}

def activate_languages():
    installed = []
    for code in columns.values():
        mods = env["ir.module.module"].search([("state", "=", "installed")])
        lang = (
            env["res.lang"]
            .with_context(active_test=False)
            .search([("code", "=", code)])
        )
        if not lang:
            raise ValueError("Language with code %s not found in Odoo" % code)
        if not lang.active:
            lang.active = True
            installed.append(code)
    if installed:
        mods._update_translations(filter_lang=installed)

def import_adr_translations():
    if not environ.get("ADR_FILE"):
        raise ValueError(
            "Please define the location of the Excel sheet in the environment "
            "variable ADR_FILE"
        )
    sheet = load_workbook(environ["ADR_FILE"]).active
    mod.populate_key_types(sheet)
    count = 0
    for row in sheet.iter_rows(values_only=True):
        count += 1
        if count <= skiprows:
            continue
        if row[0] is None:  # Emtpy rows
            continue
        xml_id = get_xml_id(row)
        record = env.ref("l10n_eu_product_adr.%s" % xml_id)
        for index, lang in columns.items():
            if row[index]:
                translation = row[index].strip().replace("\n", "")
                record.with_context(lang=lang).write({"name": translation})

activate_languages()
import_adr_translations()
env.cr.commit()


# -*- coding:utf-8 -*-
# 获取历史数据

import tushare as ts
import os
import datetime

#将八位数字的日期转换为yyyy-mm-dd
def TransfDate(d):
    year = int(d/10000)
    month = int((d - year*10000)/100)
    day = int((d - year*10000 - month*100))
    date = format("%4d-%02d-%02d" % (year, month, day))
    return date

#上面函数的逆操作，将日期转化为数字
def TransfDate2(s):
    year = int(s[0:4])
    month = int(s[5:7])
    day = int(s[8:11])
    date = year*10000+month*100+day
    return date

# 将日期转换为datetime.date
def TransfDate2Datetime(s):
    year = int(s[0:4])
    month = int(s[5:7])
    day = int(s[8:11])
    date = datetime.date(year, month, day)
    return date

# 获取历史数据
def GetHistoryData(Code, BeginTime, EndTime):
    df = ts.get_k_data(Code, index = False,  start = TransfDate(BeginTime), end = TransfDate(EndTime))
    return df

# 更新数据
def updateData(endTime):
    beginTime = 20130515
    if endTime <= beginTime:
        print("结束时间必须大于20130515，程序将结束。")
        os.exit(1)
        return
    etf300 = GetHistoryData("510300", beginTime, endTime)
    etfnas = GetHistoryData("513100", beginTime, endTime)
    #保存文件
    etf300.to_csv("df_300_hist.csv")
    etfnas.to_csv("df_nas_hist.csv")

if __name__ == "__main__":
    updateData(20190510)
    print("历史数据获取成功")
    #date = TransfDate2Datetime("2010-01-10")
#    print(date, dir(date))


class Solution:
    def trap(self, height: List[int]) -> int:
        n = len(height)
        max_left = [0] * n
        max_right = [0] * n
        for i in range(n):
            if i==0:
                max_right[0] = height[-1]
                max_left[0] = height[0]
            else:
                max_left[i] = max(height[:i+1])
                max_right[-i] = max(height[-i:])
        print(max_left)
        print(max_right)
        print(height)
        res = 0
        for i, v in enumerate(height):
            res += max(min(max_left[i], max_right[i]) - v, 0)
        return res


import os
import gzip
import shutil
import struct
import numpy as np
from six.moves import urllib

DATA_SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def downloadMNIST(filename):
	"""
	download dataset from Yann's website
	:param filename: dataset name
	:param path: dataset working directory
	:return: none
	"""
	work_path = os.path.join(BASE_DIR,'datasets')
	if not os.path.exists(work_path):
		os.mkdir(work_path)
	filepath = os.path.join(work_path,filename)
	if not os.path.exists(filepath):
		filepath, _ = urllib.request.urlretrieve(DATA_SOURCE_URL+filename,filepath)
		stat_info 	= os.stat(filepath)
		print('Dataset downloaded, ',filename,stat_info.st_size, 'bytes. ',end='')
	filename = filename.replace('.gz','')
	if not os.path.exists(os.path.join(work_path,filename)):
		with gzip.open(filepath,'rb') as f_in:
			with open(os.path.join(work_path,filename),'wb') as f_out:
				shutil.copyfileobj(f_in,f_out)
				print('Dataset unzipped. ')

def loadMNIST(dataset="training", num_image=1):
	"""
	# loads data from MNIST datasets
	:param dataset:train or test
	:param num_image: ubyte file, either image or label
	:return:numpy matrix
	"""
	if dataset == "training":
		image_file = os.path.join(BASE_DIR, "datasets/train-images-idx3-ubyte")
		label_file = os.path.join(BASE_DIR, "datasets/train-labels-idx1-ubyte")
	if dataset == "test":
		image_file = os.path.join(BASE_DIR, "datasets/t10k-images-idx3-ubyte")
		label_file = os.path.join(BASE_DIR, "datasets/t10k-labels-idx1-ubyte")
	with open(image_file, 'br') as fd:  # b for binary, r for read only
		struct.unpack('>BBBB', fd.read(4))
		dataset_image_num, num_col, num_row = struct.unpack('>III', fd.read(12))
		image_buf = fd.read(num_image * num_col * num_row)
		image_data = np.frombuffer(image_buf, dtype=np.uint8).astype(np.float32)
		image_data = image_data.reshape(num_image, num_col, num_row)
	with open(label_file, 'br') as fd:
		magic = fd.read(4)
		struct.unpack('>BBBB', magic)
		struct.unpack('>I', fd.read(4))
		label_buf = fd.read(num_image)
		label_data = np.frombuffer(label_buf, dtype=np.uint8).astype(np.int32)
	return image_data, label_data


import pdb
import argparse
import numpy as np
from tqdm import tqdm

import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
from torch.optim.lr_scheduler import MultiStepLR

from torchvision.utils import make_grid
from torchvision import datasets, transforms

from util.misc import CSVLogger
from util.cutout import Cutout
from util.cutout_intensity import Cutout_intensity
from util.Cutout_Shape import Cutout_Shape
from util.cutout_intensity_shapes import Cutout_intensity_shapes

from model.resnet import ResNet18

import matplotlib.pyplot as plt

model_options = ['resnet18']
dataset_options = ['cifar10']
cutout_options = ['None', 'Cutout', 'Cutout_intesity', 'Cutout_Shape', 'Cutout_intensity_shapes']
shape_options = ['square', 'circle', 'triangle']

parser = argparse.ArgumentParser(description='CNN')
parser.add_argument('--dataset', '-d', default='cifar10',
                    choices=dataset_options)
parser.add_argument('--model', '-a', default='resnet18',
                    choices=model_options)
parser.add_argument('--batch_size', type=int, default=128,
                    help='input batch size for training (default: 128)')
parser.add_argument('--epochs', type=int, default=200,
                    help='number of epochs to train (default: 20)')
parser.add_argument('--learning_rate', type=float, default=0.1,
                    help='learning rate')
parser.add_argument('--data_augmentation', action='store_true', default=False,
                    help='augment data by flipping and cropping')
parser.add_argument('--cutout', default='None', choices=cutout_options,
                    help='apply cutout')
parser.add_argument('--shape', default='square', choices=shape_options,
                    help='shape of the cutout')
parser.add_argument('--n_holes', type=int, default=1,
                    help='number of holes to cut out from image')
parser.add_argument('--length', type=int, default=16,
                    help='length of the holes')
parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='enables CUDA training')
parser.add_argument('--seed', type=int, default=0,
                    help='random seed (default: 1)')

args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
cudnn.benchmark = True  # Should make training should go faster for large models

torch.manual_seed(args.seed)
if args.cuda:
    torch.cuda.manual_seed(args.seed)

test_id = args.dataset + '_' + args.model

print(args)

# Image Preprocessing
normalize = transforms.Normalize(mean=[x / 255.0 for x in [125.3, 123.0, 113.9]],
                                 std=[x / 255.0 for x in [63.0, 62.1, 66.7]])

train_transform = transforms.Compose([])
if args.data_augmentation:
    train_transform.transforms.append(transforms.RandomCrop(32, padding=4))
    train_transform.transforms.append(transforms.RandomHorizontalFlip())

    # those who got the best acc are RandomRotation (0.414 ) and ColorJitter (0.378) for one epoch:

    # train_transform.transforms.append(transforms.RandomVerticalFlip())
    # train_transform.transforms.append(transforms.Grayscale(3))
    # train_transform.transforms.append(transforms.RandomRotation(10)) good acc for 1 epoch
    # train_transform.transforms.append(transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1))

train_transform.transforms.append(transforms.ToTensor())
train_transform.transforms.append(normalize)

if args.cutout == 'Cutout':
    train_transform.transforms.append(Cutout(n_holes=args.n_holes, length=args.length, shape=args.shape))
if args.cutout == 'Cutout_intesity':
    train_transform.transforms.append(Cutout_intensity(n_holes=args.n_holes, length=args.length, shape=args.shape))
if args.cutout == 'Cutout_Shape':
    train_transform.transforms.append(Cutout_Shape(n_holes=args.n_holes, length=args.length, shape=args.shape))
if args.cutout == 'Cutout_intensity_shapes':
    train_transform.transforms.append(
        Cutout_intensity_shapes(n_holes=args.n_holes, length=args.length, shape=args.shape))

test_transform = transforms.Compose([
    transforms.ToTensor(),
    normalize])

# for the 'cifar10' dataset:
num_classes = 10
train_dataset = datasets.CIFAR10(root='data/',
                                 train=True,
                                 transform=train_transform,
                                 download=True)

test_dataset = datasets.CIFAR10(root='data/',
                                train=False,
                                transform=test_transform,
                                download=True)

# Data Loader (Input Pipeline)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=args.batch_size,
                                           shuffle=True,
                                           pin_memory=True,
                                           num_workers=2)

# Print the size of the training dataset after augmentation
print("Size of training dataset after augmentation:", len(train_loader.dataset))

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=args.batch_size,
                                          shuffle=False,
                                          pin_memory=True,
                                          num_workers=2)

# Print the size of the test dataset
print("Size of test dataset:", len(test_loader.dataset))

# imply the 'resnet18':
cnn = ResNet18(num_classes=num_classes)

cnn = cnn.cuda()
criterion = nn.CrossEntropyLoss().cuda()
##################### !!!!!!!!!!!!!!1 can shift arguments ######
cnn_optimizer = torch.optim.SGD(cnn.parameters(), lr=args.learning_rate,
                                momentum=0.9, nesterov=True, weight_decay=5e-4)

scheduler = MultiStepLR(cnn_optimizer, milestones=[60, 120, 160], gamma=0.2)

filename = 'logs/' + test_id + '.csv'
csv_logger = CSVLogger(args=args, fieldnames=['epoch', 'train_acc', 'test_acc'], filename=filename)

def test(loader):
    cnn.eval()  # Change model to 'eval' mode (BN uses moving mean/var).
    correct = 0.
    total = 0.
    for images, labels in loader:
        images = images.cuda()
        labels = labels.cuda()

        with torch.no_grad():
            pred = cnn(images)

        pred = torch.max(pred.data, 1)[1]
        total += labels.size(0)
        correct += (pred == labels).sum().item()

    val_acc = correct / total
    cnn.train()

    return val_acc

for epoch in range(args.epochs):

    xentropy_loss_avg = 0.
    correct = 0.
    total = 0.

    progress_bar = tqdm(train_loader)

    for i, (images, labels) in enumerate(progress_bar):
        progress_bar.set_description('Epoch ' + str(epoch))

        images = images.cuda()
        labels = labels.cuda()

        cnn.zero_grad()
        pred = cnn(images)

        xentropy_loss = criterion(pred, labels)
        xentropy_loss.backward()
        cnn_optimizer.step()

        xentropy_loss_avg += xentropy_loss.item()

        # Calculate running average of accuracy
        pred = torch.max(pred.data, 1)[1]
        total += labels.size(0)
        correct += (pred == labels.data).sum().item()
        accuracy = correct / total

        progress_bar.set_postfix(
            xentropy='%.3f' % (xentropy_loss_avg / (i + 1)),
            acc='%.3f' % accuracy)

        # Visualize the first image in the batch after normalization
        if i == 44 and epoch == 0:
            image = images[0].cpu().numpy()
            image = np.transpose(image, (1, 2, 0))  # Transpose (C, H, W) to (H, W, C)
            image = image * [x / 255.0 for x in [63.0, 62.1, 66.7]] + [x / 255.0 for x in [125.3, 123.0, 113.9]]
            image = np.clip(image, 0, 1)  # Clip values to [0, 1] range

            plt.imshow(image)
            plt.title(f"Epoch: {epoch}, Label: {labels[0]}")
            plt.axis('off')

            # Save the image instead of displaying it interactively
            plt.savefig(f"image_epoch_{epoch}_label_{labels[0]}.png")
            plt.close()  # Close the plot to free up memory

    test_acc = test(test_loader)
    tqdm.write('test_acc: %.3f' % (test_acc))

    scheduler.step(epoch)  # Use this line for PyTorch <1.4
    # scheduler.step()     # Use this line for PyTorch >=1.4

    row = {'epoch': str(epoch), 'train_acc': str(accuracy), 'test_acc': str(test_acc)}
    csv_logger.writerow(row)

torch.save(cnn.state_dict(), 'checkpoints/' + test_id + '.pt')
csv_logger.close()


testing = False

import shared

if testing:
    text = shared.read_input("input_test")
    print(f"Instructions: {text}")
else:
    text = shared.read_input("input")

# Part 1
text.sort()
text.insert(0,0)
text.append(text[-1] + 3)
if testing:
    print(f"Sorted: {text}")
diff = [0] * 4
for i in range(1,len(text)):
    x = text[i] - text[i-1]
    assert x <= 3
    diff[x] += 1
print(f"[Part 1] {diff[1]*diff[3]}")

# Part 2
res = [1]
for i in range(1, len(text)):
    count = 0
    for j in range(i):
        if text[i] - text[j] <= 3:
            count += res[j]
    res.append(count)
print(f"[Part 2] {res[-1]}")

# Display the time this took to run
shared.printTimeElapsed()


def find_sum(nums):
    positive_sum = 0
    negative_sum = 0
    for number in nums:
        if number > 0:
            positive_sum += number
        else:
            negative_sum += number

    strong = "The negatives are stronger than the positives" if abs(negative_sum) > abs(positive_sum) \
        else "The positives are stronger than the negatives"

    return negative_sum, positive_sum, strong

numbers_line = [int(x) for x in input().split()]

print(*find_sum(numbers_line), sep="\n")

# Input: 1 2 -3 -4 65 -98 12 57 -84
# Output:
# -189
# 137
# The negatives are stronger than the positives


import argparse
import numpy as np
import torch
import time
import pickle
import os
import matplotlib.pyplot as plt

from attacks.action import softmax_attack, random_attack, guassian_attack
from trainer.maddpg.maddpg import MADDPGAgentTrainer
from trainer.maddpg.maddpg_infer import MADDPGInferAgentTrainer
from trainer.maddpg.maddpg_merge import MADDPGMergeAgentTrainer
from utils.common import save_state, restore_state, latest_checkpoint, generate_checkpoint_path, get_device

# torch.manual_seed(0)

def mkdir(dirs):
    for directory in dirs:
        dirs = directory.split('/')
        _dirs = '.'
        for _dir in dirs:
            _dirs = os.path.join(_dirs, _dir)
            if not os.path.exists(_dirs):
                os.mkdir(_dirs)

def parse_args():
    parser = argparse.ArgumentParser(
        "Reinforce Learning for Multi-Agent Environments")

    # Environment
    parser.add_argument("--scenario", type=str, default="simple", help="name of the scenario script")
    parser.add_argument("--max-episode-len", type=int, default=25, help="maximum episode length")
    parser.add_argument("--num-episodes", type=int, default=60000, help="number of episodes")
    # parser.add_argument("--num-adversaries", type=int, default=0, help="number of adversaries")
    parser.add_argument("--policy", type=str, default="maddpg", help="policy for agents")
    parser.add_argument("--num-agents", type=int, default=3, help="number of agents")

    # Core training parameters
    parser.add_argument("--lr", type=float, default=1e-2, help="learning rate for Adam optimizer")
    parser.add_argument("--gamma", type=float, default=0.95, help="discount factor")
    parser.add_argument("--batch-size", type=int, default=1024, help="number of episodes to optimize at the same time")
    parser.add_argument("--num-units", type=int, default=64, help="number of units in the mlp")
    parser.add_argument("--grad-norm-clip", type=float, default=0.5, help="max norm for clip gradients")
    parser.add_argument('--use-gpu', action='store_true', default=False)
    parser.add_argument('--gpu-id', type=int, default=0, help='id of gpu')
    parser.add_argument('--buffer-size', type=int, default=1e6, help='size of replay buffer')
    parser.add_argument('--depth', type=int, default=3, help='depth of MLP')
    parser.add_argument('--update-gap', type=int, default=100, help='amount of samples for online fashion')
    parser.add_argument('--beta', type=float, default=1e-2, help='factor for online fashion')

    # Checkpointing
    parser.add_argument("--exp-name", type=str, default="test", help="name of the experiment")
    parser.add_argument("--save-dir", type=str, default="./save_dir/", help="directory in which training state and model should be saved")
    parser.add_argument("--save-rate", type=int, default=1000, help="save model once every time this many episodes are completed")
    parser.add_argument("--load-dir", type=str, default="", help="directory in which training state and model are loaded")
    parser.add_argument("--summary-dir", type=str, default="", help="directory in which the summary of tranining process should be saved")
    parser.add_argument("--plot", action="store_true", default=False)
    parser.add_argument('--run_index', type=int, default=0, help="index of which run")

    # Evaluation
    parser.add_argument("--restore", action="store_true", default=False)
    parser.add_argument("--display", action="store_true", default=False)
    parser.add_argument("--benchmark", action="store_true", default=False)
    parser.add_argument("--benchmark-iters", type=int, default=100000, help="number of iterations run for benchmarking")
    parser.add_argument("--benchmark-dir", type=str, default="./benchmark_files/", help="directory where benchmark data is saved")
    parser.add_argument("--plots-dir", type=str, default="./learning_curves/", help="directory where plot data is saved")
    return parser.parse_args()

def make_env(scenario_name, arglist, benchmark=False):
    from multiagent.environment import MultiAgentEnv
    import multiagent.scenarios as scenarios

    # load scenario from script
    # scenario = scenarios.load(scenario_name + ".py").Scenario()
    from scenarios.spread import Scenario
    # from scenarios.spread_policy_reg import Scenario
    scenario = Scenario()

    # create world
    world = scenario.make_world()

    # create multiagent environment
    if benchmark:
        env = MultiAgentEnv(world, scenario.reset_world, scenario.reward,
                            scenario.observation, scenario.benchmark_data)
    else:
        env = MultiAgentEnv(world, scenario.reset_world,
                            scenario.reward, scenario.observation)

    return env

def get_trainers(env, num_adversaries, obs_shape_n, arglist):
    trainers = []
    if arglist.policy == 'maddpg':
        trainer = MADDPGAgentTrainer
    elif arglist.policy == 'maddpg_pi':
        trainer = MADDPGInferAgentTrainer
    elif arglist.policy == 'maddpg_si':
        trainer = MADDPGMergeAgentTrainer
    else:
        trainer = MADDPGAgentTrainer
    for i in range(num_adversaries):
        trainer_instance = train()
        trainers.append(trainer_instance)
    for i in range(num_adversaries, env.n):
        trainer_instance = trainer("agent_%d" % i, obs_shape_n, env.action_space,
                                   i, arglist, local_q=(arglist.policy == 'ddpg'))
        trainers.append(trainer_instance)
    return trainers

def run(arglist):
    # prepare save dir
    # print(arglist.save_dir)

    arglist.device = get_device(arglist.use_gpu, arglist.gpu_id)

    # save params of arglist
    arglist_dict = vars(arglist)
    with open(os.path.join(arglist.save_dir, 'params.txt'), 'w', encoding='utf-8') as f:
        keys = list(arglist_dict.keys())
        keys.sort()
        for k in keys:
            f.write(k + ':\n\t' + str(arglist_dict[k]) + '\n')

    # Create Environment
    env = make_env(arglist.scenario, arglist, arglist.benchmark)

    # create agent trainers
    obs_shape_n = [env.observation_space[i].shape for i in range(env.n)]
    # num_adversaries = min(env.n, arglist.num_adversaries)
    num_adversaries = 0
    trainers = get_trainers(env, num_adversaries, obs_shape_n, arglist)
    print('Policy:{}'.format(arglist.policy))

    # Prepare necessary data recorders
    mean_episode_rewards = []
    episode_rewards = [0.0]                         # sum of rewards for all agents
    final_ep_rewards = []                           # sum of rewards for training curve
    final_ep_ag_rewards = []                        # agent rewards for training curve
    agent_rewards = [[0.0] for _ in range(env.n)]   # individual agent reward
    agent_info = [[[]]]                             # placeholder for benchmarking info

    # Run experiments
    print('Start iterations...')
    obs_n = env.reset()
    episode_step = 0    # amount of steps inside one episode
    num_episodes = 0    # amount of episodes
    train_step = 0      # amount of training steps
    t_start = time.time()

    # Load previous results if necessary
    if arglist.load_dir == '':
        arglist.load_dir = arglist.save_dir
    if arglist.display or arglist.restore or arglist.benchmark:
        print('Loading previous states...')
        path, latest_index = latest_checkpoint(arglist.load_dir)
        restore_state(trainers, path, map_location=arglist.device)
        num_episodes = latest_index
    if arglist.display or arglist.benchmark:
        for agent in trainers:
            agent.eval()
    else:
        for agent in trainers:
            agent.train()
            # agent.sync_target_nets()

    while True:
        # Get action
        action_n = [agent.action(obs) for agent, obs in zip(trainers, obs_n)]

        # Evolution of the environment
        new_obs_n, reward_n, done_n, info_n = env.step(action_n)

        episode_step += 1
        done = all(done_n)
        terminal = (episode_step >= arglist.max_episode_len)

        # Collect experience for replay buffer
        for i, agent in enumerate(trainers):
            agent.experience(obs_n[i], action_n[i], reward_n[i],
                             new_obs_n[i], done_n[i], terminal)
        obs_n = new_obs_n

        for i, reward in enumerate(reward_n):
            episode_rewards[-1] += reward
            agent_rewards[i][-1] += reward

        if done or terminal:
            num_episodes += 1
            obs_n = env.reset()
            episode_step = 0
            episode_rewards.append(0.0)
            for a in agent_rewards:
                a.append(0.0)
            agent_info.append([[]])

        # Increment global train step counter
        train_step += 1

        # # for benchmarking learned policies
        # if arglist.benchmark:
        #     for i, info in enumerate(info_n):
        #         agent_info[-1][i].append(info_n['n'])
        #     if train_step > arglist.benchmark_iters and (done or terminal):
        #         file_name = arglist.benchmark_dir + arglist.exp_name + '.pkl'
        #         print('Finished benchmarking, now saving...')
        #         with open(file_name, 'wb') as f:
        #             pickle.dump(agent_info[:-1],f)
        #         break3, q-value: -115.43821716308594, p-loss:115.20866394042969, time: 134.907
        #     continue

        # For displaying learned policies
        if arglist.display:
            time.sleep(0.1)
            env.render()
            continue

        # Update parameters of all trainers if not in display or benchmark mode
        info = None
        for agent in trainers:
            agent.preupdate()   # reset sample index of replay buffer
        for agent in trainers:
            info = agent.update(trainers, train_step)

        # Save mode, display training output
        if terminal and ( num_episodes % arglist.save_rate == 0):
            path = generate_checkpoint_path(arglist.save_dir, num_episodes)
            save_state(trainers, path)

            _steps = train_step
            _episodes = num_episodes
            _mean_episode_reward = np.mean(episode_rewards[-arglist.save_rate:])
            mean_episode_rewards.append(_mean_episode_reward)
            q_value = info['q-value']
            p_loss = info['p_loss']
            _time = round(time.time() - t_start, 3)
            if num_adversaries == 0:
                print("steps: {}, epsiodes: {}, mean episode reward: {:.4f}, q-value: {:.4f}, p-loss:{}, time: {}".format(
                    _steps, _episodes, _mean_episode_reward, q_value, p_loss, _time))
            else:
                _agent_episode_reward = [np.mean(reward[-arglist.save_rate:]) for reward in agent_rewards]
                print("steps: {}, epsiodes: {}, mean episode reward: {}, agent episode reward: {}, q-value: {}, p-loss:{}, time: {}".format(
                    _steps, _episodes, _mean_episode_reward,_agent_episode_reward, q_value, p_loss, _time
                ))
            t_start = time.time()
            # Keep track of final episode reward
            final_ep_rewards.append(_mean_episode_reward)
            for reward in agent_rewards:
                final_ep_ag_rewards.append(np.mean(reward[-arglist.save_rate:]))

            # Save final episode reward for plotting training curve later
            if num_episodes >= arglist.num_episodes:
                np.savetxt(os.path.join(arglist.save_dir, 'episode_reward.txt'), episode_rewards[arglist.save_rate:-1], fmt='%.1f')
                plt.plot(list(range(1, len(episode_rewards) - arglist.save_rate)), episode_rewards[arglist.save_rate:-1])
                plt.savefig(os.path.join(arglist.save_dir, 'episode_reward.png'))
                np.savetxt(os.path.join(arglist.save_dir, 'mean_episode_rewards.txt'), mean_episode_rewards, fmt='%.1f')
                plt.clf()
                plt.plot(list(range(1, len(mean_episode_rewards) + 1)), mean_episode_rewards)
                plt.savefig(os.path.join(arglist.save_dir, 'mean_episode_rewards.png'))
                # reward_file_name = arglist.plots_dir + arglist.exp_name + '_rewards.pkl'
                # with open(reward_file_name, 'wb') as f:
                #     pickle.dump(final_ep_rewards, f)

                # ag_rewards_file_name = arglist.plots_dir + arglist.exp_name + '_agrewards.pkl'
                # with open(ag_rewards_file_name, 'wb') as f:
                #     pickle.dump(final_ep_ag_rewards, f)
                print('...Finished tottal of {} episodes'.format(len(episode_rewards)))
                break

if __name__ == "__main__":
    for i in range(5):
        np.random.seed(seed=i)
        arglist = parse_args()
        arglist.run_index = i
        save_dir = './save_dir/{}/agent_{}/run_{}/'.format(arglist.policy, arglist.num_agents, arglist.run_index)
        mkdir([save_dir,])
        arglist.save_dir = save_dir
        run(arglist)


import requests
from checklib import *

PORT = 10000

class CheckMachine:

    def __init__(self, checker):
        self.checker = checker

    def ping(self):
        r = requests.get(f'http://{self.checker.host}:{PORT}/ping/', timeout=2)
        self.checker.check_response(r, 'Check failed')

    def put_flag(self, flag, vuln):
        new_id = rnd_string(10)
        r = requests.post(
            f'http://{self.checker.host}:{PORT}/put/',
            json={
                'id': new_id,
                'vuln': vuln,
                'flag': flag,
            },
            timeout=2,
        )
        self.checker.check_response(r, 'Could not put flag')

        return new_id

    def get_flag(self, flag_id, vuln):
        r = requests.get(
            f'http://{self.checker.host}:{PORT}/get/',
            params={
                'id': flag_id,
                'vuln': vuln,
            },
            timeout=2,
        )
        self.checker.check_response(r, 'Could not get flag')
        data = self.checker.get_json(r, 'Invalid response from /get/')
        self.checker.assert_in(
            'flag', data,
            'Could not get flag',
            status=Status.CORRUPT,
        )
        return data['flag']


import urllib
from django.db import models
from django.contrib.postgres.fields import JSONField
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.utils.translation import gettext_lazy as _

from base import mods
from base.models import Auth, Key

import zipfile

class Question(models.Model):
    desc = models.TextField()
    is_yes_no_question = models.BooleanField(default=False)

    def save(self):
        super().save()

        if self.is_yes_no_question:
            if self.options.all().count()>=1:
                self.options.all().delete()

            question_yes = QuestionOption(option = 'Yes', number = 0, question = self)
            question_yes.save()

            question_no = QuestionOption(option = 'No', number = 1, question = self)
            question_no.save()

    def __str__(self):
        return self.desc

class QuestionOption(models.Model):
    question = models.ForeignKey(Question, related_name='options', on_delete=models.CASCADE)
    number = models.PositiveIntegerField(blank=True, null=True)
    option = models.TextField()

    def save(self):
        if not self.number:
            self.number = self.question.options.count() + 2
        return super().save()

    def __str__(self):
        return '{} ({})'.format(self.option, self.number)

class Voting(models.Model):
    name = models.CharField(max_length=200)
    desc = models.TextField(blank=True, null=True)
    question = models.ForeignKey(Question, related_name='voting', null=True, on_delete=models.CASCADE)

    start_date = models.DateTimeField(blank=True, null=True)
    end_date = models.DateTimeField(blank=True, null=True)

    pub_key = models.OneToOneField(Key, related_name='voting', blank=True, null=True, on_delete=models.SET_NULL)
    auths = models.ManyToManyField(Auth, related_name='votings')

    tally = JSONField(blank=True, null=True)
    postproc = JSONField(blank=True, null=True)

    TYPES = (
        ('Importante', 'Importante'),
        ('Informativa', 'Informativa'),
        ('Urgente', 'Urgente'),
        ('Prueba', 'Prueba'),
    )
    category = models.CharField(max_length=1000, choices=TYPES, blank=True)

    #url = models.CharField(max_length=40)
    url = models.CharField(max_length=40, help_text=u"http://localhost:8000/booth/",null=True)

    def clean_fields(self, exclude=None):
        super(Voting, self).clean_fields(exclude)

        url = urllib.parse.quote_plus(self.url.encode('utf-8'))

        if Voting.objects.filter(url=url).exists():
            raise ValidationError({'url': "The url already exists."})

    def save(self, *args, **kwargs):
        #self.url = urllib.parse.quote_plus(self.url.encode('utf-8'))
        try:
            Voting.objects.get(name=self.name)
        except:
            encode_url = urllib.parse.quote_plus(self.url.encode('utf-8'))
            self.url = encode_url
        print("self.url", self.url)
        super(Voting, self).save(*args, **kwargs)

    def create_pubkey(self):
        if self.pub_key or not self.auths.count():
            return

        auth = self.auths.first()
        data = {
            "voting": self.id,
            "auths": [ {"name": a.name, "url": a.url} for a in self.auths.all() ],
        }
        key = mods.post('mixnet', baseurl=auth.url, json=data)
        pk = Key(p=key["p"], g=key["g"], y=key["y"])
        pk.save()
        self.pub_key = pk
        self.save()

    def get_votes(self, token=''):
        # gettings votes from store
        votes = mods.get('store', params={'voting_id': self.id}, HTTP_AUTHORIZATION='Token ' + token)
        # anon votes
        return [[i['a'], i['b']] for i in votes]

    def tally_votes(self, token=''):
        '''
        The tally is a shuffle and then a decrypt
        '''

        votes = self.get_votes(token)

        auth = self.auths.first()
        shuffle_url = "/shuffle/{}/".format(self.id)
        decrypt_url = "/decrypt/{}/".format(self.id)
        auths = [{"name": a.name, "url": a.url} for a in self.auths.all()]

        # first, we do the shuffle
        data = { "msgs": votes }
        response = mods.post('mixnet', entry_point=shuffle_url, baseurl=auth.url, json=data,
                response=True)
        if response.status_code != 200:
            # TODO: manage error
            pass

        # then, we can decrypt that
        data = {"msgs": response.json()}
        response = mods.post('mixnet', entry_point=decrypt_url, baseurl=auth.url, json=data,
                response=True)

        if response.status_code != 200:
            # TODO: manage error
            pass

        self.tally = response.json()
        self.save()

        self.do_postproc()

    def do_postproc(self):
        tally = self.tally
        options = self.question.options.all()

        opts = []
        for opt in options:
            if isinstance(tally, list):
                votes = tally.count(opt.number)
            else:
                votes = 0
            opts.append({
                'option': opt.option,
                'number': opt.number,
                'votes': votes
            })

        data = { 'type': 'IDENTITY', 'options': opts }
        postp = mods.post('postproc', json=data)

        self.postproc = postp
        self.save()

        archivo = open("tallydeVoting"+str((self.id))+".txt","w")
        archivo.write("\n Hola Mundo\n")
        archivo.write(str((opts)))
        archivo.close()

        zip_file=zipfile.ZipFile("tally.zip", mode="w")
        zip_file.write("tallydeVoting"+str((self.id))+".txt")
        zip_file.close()
        return zip_file

    def __str__(self):
        return self.name


from torchvision.utils import save_image

from utils.prepare_images import *

lr = "./benchmark/miku_small.png"
pre_trained = "model_results/DCSCN_model_387epos.pt"
model = DCSCN(color_channel=3,
              up_scale=2,
              feature_layers=12,
              first_feature_filters=196,
              last_feature_filters=48,
              reconstruction_filters=128,
              up_sampler_filters=32)
model.load_state_dict(torch.load(pre_trained, map_location='cpu'))

img = Image.open(lr).convert("RGB")
img_up = img.resize((2 * img.size[0], 2 * img.size[1]), Image.BILINEAR)
img = to_tensor(img).unsqueeze(0)
img_up = to_tensor(img_up).unsqueeze(0)

if torch.cuda.is_available():
    model = model.cuda()
    img = img.cuda()
    img_up = img_up.cuda()

out = model((img, img_up))
save_image(out, './benchmark/miku_dcscn.png')


import os
import json
import boto3
import logging
import argparse
import requests

logger = logging.getLogger(__name__)
api_client = boto3.client('apigatewayv2')

def get_api_url(api_name):
    list_apis = api_client.get_apis()['Items']
    filtered_apis = [api for api in list_apis if api["Name"] == api_name]
    api_url = filtered_apis[0]['ApiEndpoint']
    return api_url

def test_api(name, url, payload):
    try:
        r = requests.post(url, json=payload)
        r.raise_for_status()  # if status !=200 raise exception
        return {
            'api_name': name,
            'api_url': url,
            'success': True
        }
    except requests.exceptions.HTTPError as err:
        raise SystemExit(err)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--log-level", type=str, default=os.environ.get("LOGLEVEL", "INFO").upper())
    parser.add_argument("--import-build-config", type=str, required=True)
    parser.add_argument("--export-test-results", type=str, required=True)
    args, _ = parser.parse_known_args()

    # Configure logging to output the line number and message
    log_format = "%(levelname)s: [%(filename)s:%(lineno)s] %(message)s"
    logging.basicConfig(format=log_format, level=args.log_level)

    # Load the build config
    with open(args.import_build_config, "r") as f:
        config = json.load(f)

    # Get the api name from sagemaker project name
    api_name = "{}-{}".format(config["Parameters"]["SageMakerProjectName"], config["Parameters"]["StageName"])

    api_url = get_api_url(api_name)

    # send a test data point to the api and verifying the response status code
    test_payload = {
        "length": -0.158164,
        "diameter": -0.280982,
        "height": -0.227545,
        "whole_weight": -0.352298,
        "shucked_weight": -0.596421,
        "viscera_weight": -0.019102,
        "shell_weight": -0.135293,
        "sex_M": 0.0,
        "sex_F": 0.0,
        "sex_I": 1.0
    }

    results = test_api(api_name, api_url, test_payload)

    # Print results and write to file
    logger.debug(json.dumps(results, indent=4))
    with open(args.export_test_results, "w") as f:
        json.dump(results, f, indent=4)


from collections import namedtuple
import random
import math
import numpy as np
from matplotlib import pyplot as plt

scale = 100
width = 500
height = 500
octaves = 10
persistence = 0.5
lacunarity = 1.6

noise = np.zeros(shape=(width, height))
Vector2D = namedtuple("Vector2", ["x", "y"])

seed = 0

def lerp(left, right, amount):
    return (1 - amount) * left + amount * right

def get_seed(a, b):
    rng = random.Random(-a)
    a_new = rng.randrange(0, 10000000)
    rng = random.Random(b)
    b_new = rng.randrange(0, 10000000)
    return a_new + b_new + seed

def get_noise_value(x, y):
    x_min = int(x)
    y_min = int(y)
    x_max = x_min + 1
    y_max = y_min + 1

    rng = random.Random(get_seed(x_min, y_min))
    g0 = Vector2D(rng.random() * 2 - 1, rng.random() * 2 - 1)
    rng = random.Random(get_seed(x_max, y_min))
    g1 = Vector2D(rng.random() * 2 - 1, rng.random() * 2 - 1)
    rng = random.Random(get_seed(x_min, y_max))
    g2 = Vector2D(rng.random() * 2 - 1, rng.random() * 2 - 1)
    rng = random.Random(get_seed(x_max, y_max))
    g3 = Vector2D(rng.random() * 2 - 1, rng.random() * 2 - 1)

    p0 = Vector2D(x - x_min, y - y_min)
    p1 = Vector2D(x - x_max, y - y_min)
    p2 = Vector2D(x - x_min, y - y_max)
    p3 = Vector2D(x - x_max, y - y_max)

    d0 = dot(p0.x, p0.y, g0.x, g0.y)
    d1 = dot(p1.x, p1.y, g1.x, g1.y)
    d2 = dot(p2.x, p2.y, g2.x, g2.y)
    d3 = dot(p3.x, p3.y, g3.x, g3.y)

    x_fade = fade(x - x_min)
    y_fade = fade(y - y_min)

    lerp1 = lerp(d0, d1, x_fade)
    lerp2 = lerp(d2, d3, x_fade)

    return lerp(lerp1, lerp2, y_fade)

def dot(x1, y1, x2, y2):
    return x1 * x2 + y1 * y2

def fade(t):
    return 6*math.pow(t, 5) - 15 * math.pow(t, 4) + 10*math.pow(t, 3)

rnd = random.Random(seed)
offsets = []
for i in range(octaves):
    offsets.append(Vector2D(rnd.randrange(0, 10000), rnd.randrange(0, 10000)))

for y in range(height):
    for x in range(width):
        amplitude = 1
        frequency = 1
        noiseValue = 0
        for i in range(octaves):
            sampleX = x / scale * frequency + offsets[i].x
            sampleY = y / scale * frequency + offsets[i].y
            rawNoise = get_noise_value(sampleX, sampleY)
            noiseValue += rawNoise * amplitude
            amplitude *= persistence
            frequency *= lacunarity
        noise[x][y] = noiseValue

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.imshow(noise, cmap='gray')
ax.axis('off')
fig.savefig("out.png")
fig.show()


# @Project:AID1810
# @Author:biabu
# @Date:18-12-24 下午5:44
# @File_name:12_信号量.py
# @IDE:PyCharm

import os
import time
from multiprocessing import Semaphore,Process

def f1():
    print("%d 想要执行事件" % os.getpid())
    # 获取一个信号量,信号量计数器减一
    # 减为０时，剩余事件任务被阻塞
    sem.acquire()
    print("%d 拿到信号量开始执行" % os.getpid())
    time.sleep(1)
    # 释放一个信号量，信号量计数器加一
    # 每当信号量加一，被阻塞的任务事件则释放
    sem.release()

if __name__ == '__main__':
    # 创建信号量
    sem = Semaphore(3)
    # 定义空列表，存放所有进程对象
    pList = []
    for i in range(10):
        p = Process(target = f1)
        pList.append(p)
        p.start()

    for p in pList:
        p.join()


file1=input("Enter The File Name with Extension::")
with open(file1,'a') as f:
    write=input("Enter The Strings For Appending::\n")
    f.write(write)
print("Writing Completed ")

file2=input("Enter The File Name with Extension For Open::")
with open(file2,'r') as f:
    print("After Writing The Content Availble The Updated Contents")
    print(f.read())

File-Handling Programs/5__Read a String From User and Append into The File.py


'''
사탕게임
> P
n*n에 4가지 사탕을 채워넣고 인접한 두 칸을 선택하여 교환했을 때 가장 긴 연속 부분 수열 찾기

kp
1. 인접한 두 칸을 교환하는 방법
    - 상/하/좌/우 교환할 수 있지만 n*n 행렬 모든 요소 반복한다면
    - 오른쪽(i+1 != n) / 아래(j+1 != n) 만 교환 그리고 다시 교환(제자리로)
    -> 오른쪽 교환 [i][j], [i][j+1] = [i][j+1], [i][j]
    -> 아래와 교환 [i][j], [i+1][j] = [i+1][j], [i][j]
2. 가장 긴 연속 부분(행/열) 찾는 방법
    - 모든 교환의 경우에 체크해야함
    - 함수로 만들어 놓으면 편리함
    - n*n에 대해 행/열 체크
    -> 행 체크 cnt = 1, if [i] == [i-1] cnt += 1  then ret = max(ret, cnt)
'''

def check(board: list):
    global ans, N

    for i in range(N):
        # 행 기준 체크
        cnt = 1
        for j in range(1, N):
            if board[i][j] == board[i][j-1]:
                cnt += 1
                ans = max(ans, cnt)
            else:
                cnt = 1
        # 열 기준 체크
        cnt = 1
        for j in range(1, N):
            if board[j][i] == board[j-1][i]:
                cnt += 1
                ans = max(ans, cnt)
            else:
                cnt = 1

N = int(input())
board = [list(map(str, input())) for _ in range(N)]
ans = 0

for i in range(N):
    for j in range(N):
        if j + 1 == N:
            continue
        board[i][j], board[i][j+1] = board[i][j+1], board[i][j]
        check(board)
        board[i][j], board[i][j+1] = board[i][j+1], board[i][j]

    # for j in range(N):
        board[j][i], board[j+1][i] = board[j+1][i], board[j][i]
        check(board)
        board[j][i], board[j+1][i] = board[j+1][i], board[j][i]

print(ans)


from pint import UnitRegistry
from eppy import modeleditor
from eppy.modeleditor import IDF

# Context: Design assistance projects.
# Function: Create and Assign a ZoneInfiltration:DesignFlowRate and set it to the ZoneList specified
# Important Notes:
#				- Zone Types (via ZoneList objects) must be defined before calling this function
# Arg. Values:
#				- ZoneType: Any Zone Type available in the model.
#				- ScheduleName: Any available schedule.
#				- Method: ACH or CFMperExtWallArea
#				- InfFlow : Any > 0.

def CreateAndAssignInfiltration(idf_file,*args):
	# Define the Unit Registery used for unit conversion
	ureg = UnitRegistry()

	# Object and variables initialization
	ZoneType = args[0][0]
	ScheduleName = args[0][1]
	Method = args[0][2]
	InfFlow = args[0][3]

	# Create the new ZoneInfiltration:DesignFlowRate object based on the specified input and assign it to the specified ZoneType
	NewInfObject = idf_file.newidfobject("ZONEINFILTRATION:DESIGNFLOWRATE")
	NewInfObject.Name = "Infiltration " + ZoneType
	NewInfObject.Zone_or_ZoneList_Name = ZoneType
	NewInfObject.Schedule_Name = ScheduleName

	if Method == "ACH":
		NewInfObject.Design_Flow_Rate_Calculation_Method = "AirChanges/Hour"
		NewInfObject.Air_Changes_per_Hour = InfFlow
	elif Method == "CFMperExtWallArea":
		NewInfObject.Design_Flow_Rate_Calculation_Method = "Flow/ExteriorWallArea"
		InfFlow = float(InfFlow)
		InfFlowIP = InfFlow*(ureg.foot**3/ureg.minute)/ureg.foot**2
		InfFlowSI = InfFlowIP.to((ureg.meter**3/ureg.second)/ureg.meter**2)
		NewInfObject.Flow_per_Exterior_Surface_Area = InfFlowSI.magnitude

	# DOE-2	infiltration methodology
	NewInfObject.Constant_Term_Coefficient = 0
	NewInfObject.Velocity_Term_Coefficient = 0.244

if __name__ == '__main':
	CreateAndAssignInfiltration(idf_file,*args)


Host = ['Host','id']
Experiment = ['Event', 'experimentID', 'experimentDay','repetition']
Environment = ['level1', 'level2', 'level3']
Pathogen = ['name','index']
Sample = ['SampleType', 'index', 'experimentDay', 'experimentHour', 'result']
Gene = ['name']
BodyMass = ['BodyMass', 'index']
Measure = ['hasNumericalValue']
Measurement = ['M', 'index']
SpecificViableCount = ['Quantity', 'index']
Inoculation =['Inoculation','index']
VolumetricViableCount = ['Dose','index']
Antibiotic = ['Antibiotic','name']
PathogenResistance = ['Resistance','index']
DiagnosticTest = ['testName']
Treatment = ['Treatment', 'index']
Observation =  ['Observation', 'index']
ObservationType = ['name']
Movement = ['Movement','index']

linked_classes = {'Measurement': ['Experiment'],'Inoculation':['Experiment'], 'Treatment':['Experiment'], 'Observation':['Experiment'], 'Movement':['Expirement']}


from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views.generic.edit import DeleteView
from django.views.generic.list import ListView
from django.views.generic.base import TemplateView
from .models import Escala

from django.contrib import messages
from .forms import EscalaModelForm
from medico.models import Medico
from posto.models import Posto
from folga.models import Folga
from datetime import datetime, date

# Create your views here.
class HomeView(TemplateView):
    template_name = 'escala/home_page.html'

class ListEscalaView(ListView):
    model = Escala
    template_name = 'escala/index.html'

def create_escala(request):
    formulario = EscalaModelForm(request.POST)

    if request.method == 'POST':

        if formulario.is_valid():
            medico = request.POST.get('medico')
            posto = request.POST.get('posto_de_trabalho')
            data = request.POST.get('data')

            # de string pra date
            data_escala = datetime.strptime(data, '%d/%m/%Y').date()
            # data de hoje
            hoje = date.today()

            # Verificando dia da escala.
            if data_escala >= hoje:
                try:
                    # analisando se o médico está ativo
                    medico_qs = Medico.objects.get(id=medico)
                    medico_status = medico_qs.ativo

                    # analisando se não está em escala
                    medico_escala_qs = Escala.objects.filter(medico_id=medico)

                    # analisando se não está de folga
                    folga_qs = Folga.objects.filter(medico_id=medico, dia_de_folga=data_escala)
                    medico_disponivel = False

                    if len(folga_qs) > 0:
                        if folga_qs[0].dia_de_folga != data_escala:
                            medico_disponivel = True
                        else:
                            messages.error(request, 'Não é possível, pois a data da escala do médico é igual da folga.')
                    else:
                        medico_disponivel = True

                    # analisando se o posto está ativo
                    posto_qs = Posto.objects.get(id=posto)
                    posto_status = posto_qs.ativo

                    if medico_status and len(medico_escala_qs) == 0 and medico_disponivel and posto_status:
                        # salvando dados
                        formulario.save()

                        # redirecionando
                        return redirect('escala:escala')

                    else:
                        messages.error(request, 'Verifique se posto de trabalho e médico estão ativos / aptos.')

                except Exception as e:
                    messages.error(request, f'Opa, houve um erro: {e}...')

            else:
                messages.error(request, 'Esta data já passou.')

        else:
            messages.error(request, 'Houve algum erro, tente novamente.')

    else:
        formulario = EscalaModelForm()

    context = {
        'form': formulario
    }

    return render(request, 'escala/escala_form.html', context)

def update_escala(request, pk):
    escala = Escala.objects.get(pk=pk)
    formulario = EscalaModelForm(instance=escala)

    if request.method == 'POST':
        formulario = EscalaModelForm(request.POST, instance=escala)

        if formulario.is_valid():
            medico = request.POST.get('medico')
            posto = request.POST.get('posto_de_trabalho')
            data = request.POST.get('data')

            # de string pra date
            data_escala = datetime.strptime(data, '%d/%m/%Y').date()
            # data de hoje
            hoje = date.today()

            # Verificando dia da escala.
            if data_escala >= hoje:
                try:
                    # analisando se o médico está ativo
                    medico_qs = Medico.objects.get(id=medico)
                    medico_status = medico_qs.ativo
                    medico_disponivel = False

                    # analisando escala do médico
                    medico_escala_qs = Escala.objects.filter(medico_id=medico)

                    if len(medico_escala_qs) > 0:
                        if medico_escala_qs[0].data != data_escala:
                            medico_disponivel = True
                        else:
                            messages.error(request, 'Coloque uma data diferente da atual.')
                    else:
                        medico_disponivel = True

                    # analisando se não está de folga
                    folga_qs = Folga.objects.filter(medico_id=medico, dia_de_folga=data_escala)

                    if len(folga_qs) > 0:
                        if folga_qs[0].dia_de_folga != data_escala:
                            medico_disponivel = True
                        else:
                            messages.error(request, 'Não é possível, pois a data da escala do médico é igual da folga.')
                    else:
                        medico_disponivel = True

                    # analisando se o posto está ativo
                    posto_qs = Posto.objects.get(id=posto)
                    posto_status = posto_qs.ativo

                    if medico_status and medico_disponivel and posto_status:
                        # salvando dados
                        formulario.save()

                        # redirecionando
                        return redirect('escala:escala')

                    else:
                        messages.error(request, 'Verifique se posto de trabalho e médico estão ativos / aptos.')

                except Exception:
                    messages.error(request, 'Opa, houve um erro...')

            else:
                messages.error(request, 'Esta data já passou.')

        else:
            messages.error(request, 'Houve algum erro, tente novamente.')

    context = {
        'form': formulario
    }

    return render(request, 'escala/escala_form.html', context)

class DeleteEscalaView(DeleteView):
    model = Escala
    template_name = 'escala/escala_delete.html'
    success_url = reverse_lazy('escala:escala')


#coding:utf-8

# __author__ = 'lc'

#类的定义
class Person:
    #类方法
    def eat(self,food):
        print('%s吃%s' % (self.name,food))
        print(self.sleep())

    def sleep(self):
        print('睡觉')

# 第一步：实例化--创建一个对象（变量名=类名（））
a = Person('xiaoming')

# 第二步：调用类中的方法（实例名.方法名()）
a.eat('rice')

b = Person()
b.eat('mantou')


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

import os
from config import Config

from flask_script import Manager, Shell

from app import create_app, db
from app.models import User, Role, Menu, City, R_User_City, R_Role_Menu, CityInfo
from flask_cors import CORS

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
CORS(app, allow_headers=['X-Token', 'Content-Type'])

# def make_shell_context():
#     return dict(app=app, db=db, User=User, Role=Role)

# manager.add_command('shell', Shell(make_context=make_shell_context))

@manager.command
def createdb():
    db.create_all()
    Role.insert_master()
    User.insert_master()
    Menu.insert_master()
    City.insert_master()
    R_User_City.insert_master()
    R_Role_Menu.insert_master()
    CityInfo.insert_master()

@manager.command
def env():
    print(os.getenv('FLASK_CONFIG'))

if __name__ == '__main__':
    # print(app.url_map)
    manager.run()