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

# In[1]:

import tensorflow as tf
from tensorflow.keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

# In[27]:

class myCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        if(logs.get('val_acc') >= 0.9):
            print("\nReached 98% accuracy so cancelling training!")
            self.model.stop_training = True

# In[28]:

import numpy as np
def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.
    return results

x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)

# In[29]:

y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

# In[30]:

word_index = imdb.get_word_index()
reverse_word_index = dict(
[(value, key) for (key, value) in word_index.items()])
decoded_review = ' '.join(
[reverse_word_index.get(i - 3, '?') for i in train_data[8]])

# In[31]:

callbacks = myCallback()

# In[32]:

from  tensorflow.keras import models
from tensorflow.keras import layers
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

# In[33]:

model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])

# In[38]:

#x_val = x_train[:]
#y_val = y_train[:]
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]

# In[39]:

model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['acc'])
history = model.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data=(x_val, y_val),callbacks = [callbacks])

# In[41]:

import matplotlib.pyplot as plt
history_dict = history.history
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']
acc = history_dict['val_acc']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, loss_values, 'bo', label='Training loss')
plt.plot(epochs, val_loss_values, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

# In[42]:

model.save("myfirstmodel.h5")

# In[43]:

from numpy import loadtxt

# In[45]:

from tensorflow.keras.models import load_model

# In[46]:

model = load_model('myfirstmodel.h5')

# In[47]:

model.summary()

# In[ ]:


#coding:utf8

from flask import Flask,make_response,request

app = Flask(__name__)

@app.route('/cookie')
def set_cookie():
    response = make_response('cookie设置成功')
    response.set_cookie("name", 'zhang')
    return response

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


from django.shortcuts import render
from accounts.models import Team

# Create your views here.
def dashboard(request):
    context = {    }
    return render(request, 'accounts/dashboard.html', context)

def create_team(request):
    if request.POST:
        name = request.POST['name']
        members = request.POST['members']
        program_manager = request.POST['program_manager']

        team = Team.objects.create(name=name, members=members, program_manager=program_manager)

        team.save()

    context = {}
    return render(request, 'accounts/create-team.html', context)


import sys
import math
sys.path.insert(0, "../..")

# LEXING

math_reserved = {
    'sin': 'SIN',
    'cos': 'COS',
    'tg': 'TAN',
    'ctg': 'COT',
    'sqrt': 'SQRT',
    'log': 'LOG',
    'exp': 'EXP',
    'asin': 'ASIN',
    'acos': 'ACOS',
    'atg': 'ATAN',
    'actg': 'ACOT'
}

reserved = {
    **math_reserved,
    'if': 'IF',
    'else': 'ELSE',
    'while': 'WHILE',
    'for': 'FOR'
}

tokens = [
    'INTEGER',
    'REAL',
    'PLUS',
    'MINUS',
    'TIMES',
    'DIVIDE',
    'LPAREN',
    'RPAREN',
    'ID',
    'ASSIGN',
    'EQUALS',
    'POWER',
    'NOTEQUALS',
    'GT',
    'GTE',
    'LT',
    'LTE',
    'NOT',
    'BOOL',
    'SEMICOLON',
    'LBRACKET',
    'RBRACKET'
] + list(reserved.values())

t_PLUS = r'\+'
t_MINUS = r'\-'
t_TIMES = r'\*'
t_DIVIDE = r'\/'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_ASSIGN = r'\='
t_EQUALS = r'\=\='
t_POWER = r'\^'
t_NOTEQUALS = r'\!\='
t_GT = r'\>'
t_GTE = r'\>\='
t_LT = r'\<'
t_LTE = r'\<\='
t_NOT = r'\!'
t_SEMICOLON = r'\;'
t_LBRACKET = r'\{'
t_RBRACKET = r'\}'

def t_BOOL(t):
    r'(True|False)'
    if t.value == 'True':
        t.value = True
    else:
        t.value = False
    return t

def t_ID(t):
    r'[a-zA-Z_][a-zA-Z0-9_]*'
    t.type = reserved.get(t.value, 'ID')
    return t

def t_REAL(t):
    r'\d*\.\d+|\d+\.\d*'
    t.value = float(t.value)
    return t

def t_INTEGER(t):
    r'\d+'
    t.value = int(t.value)
    return t

t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
def build_lexer(data):
    import lex as lex
    lexer = lex.lex()
    lexer.input(data)
    return lexer

# Tokenize
def tokenize(lexer):
    lex_tokens = []
    while True:
        lex_token = lexer.token()
        if not lex_token:
            break
        lex_tokens.append((lex_token.type, lex_token.value))
    return lex_tokens

# PARSING

names = {}

precedence = (
    ('nonassoc', 'GT', 'GTE', 'LT', 'LTE', 'EQUALS', 'NOTEQUALS'),
    ('left', 'PLUS', 'MINUS'),
    ('left', 'TIMES', 'DIVIDE'),
    ('left', 'SIN', 'COS', 'TAN', 'COT', 'SQRT', 'LOG', 'EXP', 'ASIN', 'ACOS', 'ATAN', 'ACOT'),
    ('right', 'POWER'),
    ('right', 'NOT'),
    ('right', 'UMINUS')
)

def p_multiple_statement(p):
    'statement : statement SEMICOLON statement'
    p[0] = p[1] + p[3]

def p_statement_semicolon(p):
    'statement : statement SEMICOLON'
    p[0] = p[1]

def p_statement_assignment(p):
    'statement : assignment'
    p[0] = p[1]

def p_statement_expr(p):
    'statement : expression'
    p[0] = [p[1]]

def p_assignment(p):
    'assignment : ID ASSIGN expression'
    p[0] = [(p[2], p[1], p[3])]

def p_expression_binop_arithmetic(p):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression
                  | expression POWER expression'''
    p[0] = (p[2], p[1], p[3])

def p_expression_relation(p):
    'expression : relation'
    p[0] = p[1]

def p_expression_binop_logic(p):
    '''relation : expression EQUALS expression
                  | expression NOTEQUALS expression
                  | expression GT expression
                  | expression GTE expression
                  | expression LT expression
                  | expression LTE expression'''
    p[0] = (p[2], p[1], p[3])

def p_expression_function(p):
    '''expression : SIN expression
                  | COS expression
                  | TAN expression
                  | COT expression
                  | SQRT expression
                  | EXP expression
                  | LOG expression
                  | ASIN expression
                  | ACOS expression
                  | ATAN expression
                  | ACOT expression'''
    p[0] = (p[1], p[2])

def p_expression_uminus(p):
    "expression : MINUS expression %prec UMINUS"
    p[0] = ('NEGATE', p[2])

def p_expression_not(p):
    "expression : NOT expression %prec NOT"
    p[0] = (p[1], p[2])

def p_expression_group(p):
    "expression : LPAREN expression RPAREN"
    p[0] = ('GROUP', p[2])

def p_expression_integer(p):
    '''expression : INTEGER'''
    p[0] = ('INTEGER', p[1])

def p_expression_real(p):
    '''expression : REAL'''
    p[0] = ('REAL', p[1])

def p_expression_bool(p):
    '''relation : BOOL'''
    p[0] = ('BOOL', p[1])

def p_expression_id(p):
    "expression : ID"
    p[0] = ('ID', p[1])

def p_if_statement(p):
    "statement : IF LPAREN relation RPAREN LBRACKET statement RBRACKET"
    p[0] = [('IF', p[3], p[6])]

def p_if_else_statement(p):
    "statement : IF LPAREN relation RPAREN LBRACKET statement RBRACKET ELSE LBRACKET statement RBRACKET"
    p[0] = [('IFELSE', p[3], p[6], p[10])]

def p_while_statement(p):
    "statement : WHILE LPAREN relation RPAREN LBRACKET statement RBRACKET"
    p[0] = [('WHILE', p[3], p[6])]

def p_for_statement(p):
    "statement : FOR LPAREN assignment SEMICOLON relation SEMICOLON statement RPAREN LBRACKET statement RBRACKET"
    p[0] = [('FOR', p[3], p[5], p[7], p[10])]

def p_error(p):
    if p:
        print("Syntax error at '%s'" % p.value)
    else:
        print("Syntax error at EOF")

def calculate(data):
    def get_value(data):
        _, value = data
        return value

    def perform_assignment(data):
        _, name, value = data
        value = calculate(value)
        names[name] = value
        return None

    def get_assigned_value(data):
        _, name = data
        return names[name]

    def skip_grouping(data):
        _, expression = data
        return calculate(expression)

    def inverse(data):
        _, value = data
        value = calculate(value)
        return -value

    def negate(data):
        _, value = data
        value = calculate(value)
        return not value

    def addition(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left + right

    def subtraction(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left - right

    def multiplication(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left * right

    def division(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left / right

    def exponentiation(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left ** right

    def equality(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left == right

    def not_equality(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left != right

    def greater(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left > right

    def greater_or_equal(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left >= right

    def less(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left < right

    def less_or_equal(data):
        _, left, right = data
        left = calculate(left)
        right = calculate(right)
        return left <= right

    def math_function(data):
        f_name, arg = data
        arg = calculate(arg)
        if f_name == 'sin':
            return math.sin(arg)
        elif f_name == 'cos':
            return math.cos(arg)
        elif f_name == 'tg':
            return math.tan(arg)
        elif f_name == 'ctg':
            return 1/math.tan(arg)
        elif f_name == 'sqrt':
            return math.sqrt(arg)
        elif f_name == 'exp':
            return math.exp(arg)
        elif f_name == 'log':
            return math.log(arg)
        elif f_name == 'asin':
            return math.asin(arg)
        elif f_name == 'atg':
            return math.atan(arg)
        elif f_name == 'acos':
            return math.acos(arg)

    def if_statement(data):
        _, condition, if_instructions = data
        condition = calculate(condition)
        if condition:
            return calculate_statements(if_instructions)
        return None

    def if_else_statement(data):
        _, condition, if_instructions, else_instructions = data
        condition = calculate(condition)
        if condition:
            return calculate_statements(if_instructions)
        else:
            return calculate_statements(else_instructions)

    def while_statement(data):
        _, condition, instructions = data
        results = []
        while calculate(condition):
            results.append(calculate_statements(instructions))
        return results

    def for_statement(data):
        _, assignment, condition, expression, instructions = data
        results = []
        calculate_statements(assignment)
        while calculate(condition):
            results.append(calculate_statements(instructions))
            calculate_statements(expression)
        return results

    if data[0] in ('INTEGER', 'REAL', 'BOOL'):
        return get_value(data)
    elif data[0] in list(math_reserved.keys()):
        return math_function(data)
    elif data[0] == '=':
        return perform_assignment(data)
    elif data[0] == 'ID':
        return get_assigned_value(data)
    elif data[0] == 'GROUP':
        return skip_grouping(data)
    elif data[0] == '+':
        return addition(data)
    elif data[0] == '-':
        return subtraction(data)
    elif data[0] == '*':
        return multiplication(data)
    elif data[0] == '/':
        return division(data)
    elif data[0] == '^':
        return exponentiation(data)
    elif data[0] == '>':
        return greater(data)
    elif data[0] == '>=':
        return greater_or_equal(data)
    elif data[0] == '<':
        return less(data)
    elif data[0] == '<=':
        return less_or_equal(data)
    elif data[0] == '==':
        return equality(data)
    elif data[0] == '!=':
        return not_equality(data)
    elif data[0] == '!':
        return negate(data)
    elif data[0] == 'NEGATE':
        return inverse(data)
    elif data[0] == 'IF':
        return if_statement(data)
    elif data[0] == 'IFELSE':
        return if_else_statement(data)
    elif data[0] == 'WHILE':
        return while_statement(data)
    elif data[0] == 'FOR':
        return for_statement(data)

def calculate_statements(statements):
    results = []
    for statement in statements:
        results.append(calculate(statement))
    return results

import yacc as yacc

def calculator_output(data):
    lexer = build_lexer(data)
    parser = yacc.yacc()
    statements = parser.parse(data)
    return calculate_statements(statements)

import yacc as yacc

#data = 'a = sin (-143 + 12 ^ 2); a; a + 1; 1<2+1; if(1<2){2-1}'
# data = '1'
# #data = 'a = sin 0; -;1;a; if(1>2){2-1}else{69}; a=1; while(a < 10){a = a+1}; a; for(i = 0;i<5;i = i+1){i}'
# data = '!True'
#
# lexer = build_lexer(data)
# parser = yacc.yacc()
# statements = parser.parse(data)
# print(statements)
# print(calculate_statements(statements))


'''
A set of utility methods that are used in different parts of the framework.
'''

import logging

# Set of bots read from a bot tsv file
bots = None
filterBots = False
def setFilterBots(fb,botfile):
    global filterBots,bots

    if fb:
        try:
            bots = set(long(bot) for bot in open(botfile,'r'))
            filterBots = fb
            logging.info("%s Bots loaded from %s"%(len(bots),botfile))
        except:
            logging.error("Botlist (%s) could not be loaded, Bots will not be filtered"%botfile)

def isBot(u_id):
    '''
    Returns true if we filter for bots and  u_id is a known bot.

    :arg ints: Boolean, if True compares u_id as int (default is False)
    '''
    if filterBots:
        if u_id in bots:
            return True
    return False

def create_time_stamps_month(fromym='200101',toym='201012'):
    '''
    Helper data structures for time stamps
    List of all time unites, i.e. every month. yyyymm
    '''
    time_stamps = []
    # A dictionary that serves as a lookup for the index of atime stamp
    time_stamps_index = {}

    min_year = fromym[:-2]
    min_month = fromym[-2:]
    max_year = toym[:-2]
    max_month = toym[-2:]

    i = 0
    #add remaining months in the first year
    for m in range(int(min_month),13):
        ts = '%s%02d'%(min_year,m)
        time_stamps.append(ts)
        time_stamps_index[ts] = i
        i += 1
    #add intermediate years
    for y in range(int(min_year)+1,int(max_year)):
        for m in range(1,13):
            ts = '%s%02d'%(y,m)
            time_stamps.append(ts)
            time_stamps_index[ts] = i
            i += 1
    #last year
    for m in range(1,int(max_month)+1):
        ts = '%s%02d'%(max_year,m)
        time_stamps.append(ts)
        time_stamps_index[ts] = i
        i += 1

    return (time_stamps,time_stamps_index)

def create_time_stamps_day(fromymd='20010101',toymd='20101231'):
    '''
    Helper data structures for time stamps
    List of all time unites, i.e. every month. yyyymm
    '''

    import calendar

    time_stamps = []
    # A dictionary that serves as a lookup for the index of atime stamp
    time_stamps_index = {}

    min_year = int(fromymd[:4])
    min_month = int(fromymd[4:6])
    min_day = int(fromymd[6:8])
    max_year = int(toymd[:4])
    max_month = int(toymd[4:6])
    max_day = int(toymd[6:8])
    i = 0
    #add remaining months in the first year
    for m in range(min_month,13):
        # calender.monthrange returns a tuple (day of the week, number of days in the month)
        nds = calendar.monthrange(min_year,m)[1]
        for d in range(min_day,nds+1):
            ts = '%s%02d%02d'%(min_year,m,d)
            time_stamps.append(ts)
            time_stamps_index[ts] = i
            i += 1
    #add intermediate years
    for y in range(min_year+1,max_year):
        for m in range(1,13):
            # calender.monthrange returns a tuple (day of the week, number of days in the month)
            nds = calendar.monthrange(y,m)[1]
            for d in range(1,nds+1):
                ts = '%s%02d%02d'%(y,m,d)
                time_stamps.append(ts)
                time_stamps_index[ts] = i
                i += 1
    #to last month
    for m in range(1,max_month):
        nds = calendar.monthrange(max_year,m)[1]
        for d in range(1,nds+1):
            ts = '%s%02d%02d'%(max_year,m,d)
            time_stamps.append(ts)
            time_stamps_index[ts] = i
            i += 1
    #to last day
    for d in range(1,max_day+1):
        ts = '%s%02d%02d'%(max_year,max_month,d)
        time_stamps.append(ts)
        time_stamps_index[ts] = i
        i += 1

    return (time_stamps,time_stamps_index)

def computeMonthStartEndtime(ym):
    '''
    Returns the starting and end datetime object for the yyyymm passed. I.e. the first and last day of the month

    :arg ym: str, 'yyyymm' format
    :returns: tuple of datetime objects
    '''
    from datetime import datetime
    import calendar

    y = int(ym[:4])
    m = int(ym[4:])

    start = datetime(y, m, 1)
    # days in the given month
    # calender.monthrange returns a tuple (day of the week, number of days in the month)
    d = calendar.monthrange(y,m)[1]

    end = datetime(y, m, d)

    return (start,end)

def numberOfMonths(ymStart,ymEnd):
    '''Returns the number of months between the parameters.

    :arg ymStart: str, 'yyyymm' format
    :arg ymEnd: str, 'yyyymm' format
    :returns: int, number of month
    '''
    months = 0
    months += (int(ymEnd[:4])-(int(ymStart[:4])+1)) * 12
    if int(ymEnd[:4])==int(ymStart[:4]):
        #same year
        months += (int(ymEnd[4:])-int(ymStart[4:]))+1
    else:
        months += 12-int(ymStart[4:])+1
        months += int(ymEnd[4:])

    return months

def cmap_discretize(cmapName, N):
    """
    From http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations

    :arg cmap: colormap instance, eg. cm.jet.
    :arg N: Number of colors.

    :returns: a discrete colormap from the continuous colormap cmap.
    """

    try:
        from numpy import array, linspace, zeros, interp
        import matplotlib
        from matplotlib import pyplot as plt
    except:
        logging.error('matplotlib or numpy not installed')
        logging.error("cmap_discretize() returns invalid cmap; you can't plot without these packages anyways")
        return cmapName

    if cmapName is None:
        cmap = plt.cm.spectral
    else:
        cmap = plt.cm.get_cmap(cmapName)

    # try:
    #     from scipy import interpolate
    # except:
    #     logging.error('scipy not installed')
    #     logging.info("cmap_discretize() can't interpolate the colormap, returns cmap %s unchanged"%cmapName)
    #     return cmap

    cdict = cmap._segmentdata.copy()
    # N colors
    colors_i = linspace(0,1.,N)
    # N+1 indices
    indices = linspace(0,1.,N+1)
    for key in ('red','green','blue'):
        # Find the N colors
        D = array(cdict[key])

        # using scipy
        # I = interpolate.interp1d(D[:,0], D[:,1])
        # colors = I(colors_i)

        # using numpy
        colors = interp(colors_i,D[:,0], D[:,1])

        # Place these colors at the correct indices.
        A = zeros((N+1,3), float)
        A[:,0] = indices
        A[1:,1] = colors
        A[:-1,2] = colors
        # Create a tuple for the dictionary.
        L = []
        for l in A:
            L.append(tuple(l))
        cdict[key] = tuple(L)
    # Return colormap object.
    return matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)

def movingAverage(array, WINDOW=5):
    try:
        import numpy as N
    except:
        logging.warning("Moving average can't be computed (Numpy not installed)")
        return

    weightings = N.repeat(1.0, WINDOW) / WINDOW
    return N.convolve(array, weightings)[WINDOW-1:-(WINDOW-1)]


import os
import os.path as osp
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from sklearn import metrics

import torch

from dataset import create_data_loader, preprocess_df
from model import ClassificationModel
from utils import set_seeds, load_config, str2bool

def inference(model, test_loader, device, cls_last_sigmoid):
    model.eval()
    preds = []

    with torch.no_grad():
        for img, tab in tqdm(iter(test_loader)):
            img = img.float().to(device)
            tab = tab.float().to(device)

            model_pred = model(img, tab)
            if not cls_last_sigmoid:
                model_pred = torch.sigmoid(model_pred)
            model_pred = model_pred.squeeze(1).to('cpu')

            preds += model_pred.tolist()

    return preds

def get_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=42)
    parser.add_argument('--df', type=str, default='test')
    parser.add_argument('--mode', type=str, default='test') # test hard valid
    parser.add_argument('--hflip', action='store_true')
    parser.add_argument('--vflip', action='store_true')
    parser.add_argument('--ckpt_list', nargs='+') # exp0/best.pt
    parser.add_argument('--img_size', type=int, default=512)
    parser.add_argument('--resize_by_split', action='store_true')
    parser.add_argument('--transform_type', type=str, default='resize')
    parser.add_argument('--pred_thres', type=float, default=0.5)
    parser.add_argument('--remark', type=str, default='')
    args = parser.parse_args()

    if args.mode == 'valid':
        assert args.df in ['train', 'train_5fold', 'train_heuristic_5fold']
    else:
        assert args.df in ['test', 'test_heuristic']

    args.base_dir = './'
    args.data_dir = osp.join(args.base_dir, 'data')
    args.submit_dir = osp.join(args.base_dir, 'submit')
    os.makedirs(args.submit_dir, exist_ok=True)

    return args

def main(args, train_args, hflip=False, vflip=False):
    args.device = torch.device("cuda:0")

    df = pd.read_csv(osp.join(args.data_dir, f'{args.df}.csv'))
    if args.mode == 'valid':
        df = preprocess_df(df, train_args.df_ver, drop_row=True)
        df = df[df["kfold"] == train_args.fold].reset_index(drop=True)
    else:
        df = preprocess_df(df, train_args.df_ver, drop_row=False)

    test_loader = create_data_loader(
        df, 'infer', args.img_size, data_dir=args.data_dir,
        hflip=hflip, vflip=vflip, norm_type=train_args.norm_type,
        transform_type=args.transform_type, resize_by_split=args.resize_by_split,
    )

    # exp235
    # args.tab_model = 'drop40'
    model = ClassificationModel(train_args).to(args.device)
    model.load_state_dict(torch.load(osp.join(args.work_dir, args.ckpt)))

    preds = inference(model, test_loader, args.device, train_args.cls_last_sigmoid)
    if args.mode in ['valid', 'hard']:
        preds = np.where(np.array(preds) > args.pred_thres, 1, 0)
    if args.mode == 'valid':
        labels = df[df['kfold'] == train_args.fold]['N_category'].tolist()
        valid_f1 = metrics.f1_score(y_true=labels, y_pred=preds, average='macro', zero_division=1)
        print(f'hflip={bool(hflip)} vflip={bool(vflip)} valid_f1:{valid_f1:.4f}')

    return preds

if __name__ == '__main__':
    args = get_parser()

    submit_file_name = args.mode
    if args.hflip:
        submit_file_name += '_hflip'
    if args.vflip:
        submit_file_name += '_vflip'
    if args.resize_by_split:
        submit_file_name += '_resizeBySplit'
    if args.transform_type != 'resize':
        submit_file_name += f'_{args.transform_type}'
    if args.img_size != 512:
        submit_file_name += f'_img{args.img_size}'
    if args.remark != '':
        submit_file_name += f'_{args.remark}'

    # preds
    ensemble = []
    ensemble_cnt = 0
    for idx in range(len(args.ckpt_list)):
        args.exp, args.ckpt = args.ckpt_list[idx].split('/')
        args.work_dir = osp.join('work_dirs', args.exp) # work_dirs/exp0

        submit_file_name += f'_{args.exp}'
        if args.ckpt.split('.')[0] != 'best':
            submit_file_name += args.ckpt.split('.')[0]

        set_seeds(args.seed)
        train_args = load_config(osp.join(args.work_dir, 'config.yaml'))

        for hflip in range(args.hflip + 1):
            for vflip in range(args.vflip + 1):
                preds = main(args, train_args, hflip, vflip)
                ensemble.append(preds)
                ensemble_cnt += 1

    if args.mode in ['test', 'hard']:
        # ensemble
        if args.mode == 'hard':
            ensemble = np.array(ensemble)
            preds = [np.argmax(np.bincount(ensemble[:,i])) for i in range(ensemble.shape[1])]
        elif args.mode == 'test':
            if ensemble_cnt > 1:
                ensemble = np.sum(ensemble, axis=0)
            elif ensemble_cnt == 1:
                ensemble = ensemble[0]
            preds = np.where(ensemble > args.pred_thres * ensemble_cnt, 1, 0)

        # output
        submit = pd.read_csv(osp.join(args.data_dir, 'sample_submission.csv'))
        submit['N_category'] = preds
        submit_path = osp.join(args.submit_dir, f'{submit_file_name}.csv')
        submit.to_csv(submit_path, index=False)


import requests
from tests.helpers import NetworkTest
import time
CONTROLLER = '127.0.0.1'
KYTOS_API = 'http://%s:8181/api' % CONTROLLER

class TestE2ESDNTraceInvertedCircuit:
    net = None
    circuit = None
    @staticmethod
    def setup_class(cls):
        """run at the beginning for all tests"""
        cls.net = NetworkTest(CONTROLLER, topo_name='linear10')
        cls.net.start()
        cls.net.restart_kytos_clean()
        cls.net.wait_switches_connect()

    @classmethod
    def teardown_class(cls):
        print('somente na terminação')
        cls.net.stop()

    @staticmethod
    def create_evc(vlan_id, interface_a="00:00:00:00:00:00:00:01:1", interface_z="00:00:00:00:00:00:00:0a:1"):
        payload = {
            "name": "Vlan_%s" % vlan_id,
            "enabled": True,
            "dynamic_backup_path": True,
            "uni_a": {
                "interface_id": interface_a,
                "tag": {"tag_type": 1, "value": vlan_id}
            },
            "uni_z": {
                "interface_id": interface_z,
                "tag": {"tag_type": 1, "value": vlan_id}
            }
        }
        api_url = KYTOS_API + '/kytos/mef_eline/v2/evc/'
        response = requests.post(api_url, json=payload)
        assert response.status_code == 201, response.text
        data = response.json()
        return data['circuit_id']

        response = requests.get(api_url + "switches")
        switches = response.json()
        for switch in switches["switches"]:
            response = requests.post(api_url + f"switches/{switch}/enable")
            response = requests.post(api_url + f"interfaces/switch{switch}/enable")

        response = requests.get(api_url + "links")
        links = response.json()
        for link in links["links"]:
            response = requests.post(api_url + f"links/{link}/enable")

        time.sleep(10)

    @staticmethod
    def get_evc(circuit_id):
        api_url = KYTOS_API + '/kytos/mef_eline/v2/evc/'
        response = requests.get(api_url + circuit_id)
        assert response.status_code == 200, response.text
        data = response.json()
        return data

    def test_100_run_sdntrace_cp(self):
        """Run SDNTrace-CP (Control Plane)."""
        # Trace from UNI_A
        payload = {
            "trace": {
                "switch": {"dpid": "00:00:00:00:00:00:03:01", "in_port": 1},
                "eth": {"dl_type": 33024, "dl_vlan": 400}
            }
        }

        api_url = KYTOS_API + '/amlight/sdntrace_cp/v1/trace'
        response = requests.put(api_url, json=payload)
        assert response.status_code == 200, response.text
        data = response.json()
        assert "result" in data, data
        assert len(data["result"]) == 10, data

        expected = [
            (
                l['endpoint_b']['switch'],
                l['endpoint_b']['port_number'],
                l['metadata']['s_vlan']['value']
            )
            for l in self.circuit['current_path']
        ]
        expected.insert(0, ('00:00:00:00:00:00:03:1', 1, 400))

        actual = [
            (step['dpid'], step['port'], step['vlan'])
            for step in data["result"]
        ]

        assert expected == actual, f"Expected {expected}. Actual: {actual}"

        # Trace from UNI_Z
        payload = {
            "trace": {
                "switch": {"dpid": "00:00:00:00:00:00:01:1", "in_port": 1},
                "eth": {"dl_type": 33024, "dl_vlan": 400}
            }
        }
        api_url = KYTOS_API + '/amlight/sdntrace_cp/v1/trace'
        response = requests.put(api_url, json=payload)
        assert response.status_code == 200, response.text
        data = response.json()
        assert "result" in data
        assert len(data["result"]) == 10, data

        expected = [
            (
                l['endpoint_a']['switch'],
                l['endpoint_a']['port_number'],
                l['metadata']['s_vlan']['value']
            )
            for l in reversed(self.circuit['current_path'])
        ]
        expected.insert(0, ('00:00:00:00:00:00:01:1', 1, 400))

        actual = [
            (step['dpid'], step['port'], step['vlan'])
            for step in data["result"]
        ]

        assert expected == actual, f"Expected {expected}. Actual: {actual}"


from forta_agent import Finding, FindingType, FindingSeverity, Network
from src.detectors import processContract
import rlp
from datetime import datetime, timedelta
from web3 import Web3

cache = []

def calc_contract_address(address, nonce):

    address_bytes = bytes.fromhex(address[2:].lower())
    return Web3.toChecksumAddress(Web3.keccak(rlp.encode([address_bytes, nonce]))[-20:])

def handle_transaction(transaction_event):
    chain_id = 1 if transaction_event.network == Network.MAINNET else 137
    if transaction_event.to is None:
        cache.append({
            "address": calc_contract_address(transaction_event.from_, transaction_event.transaction.nonce).lower(),
            "from": transaction_event.from_,
            "timestamp": transaction_event.timestamp,
            "hash": transaction_event.transaction.hash,
            "chain_id": chain_id
        })
    return handle_cached_transactions()

def handle_cached_transactions():
    global cache
    findings = []
    while(len(cache) > 0 and datetime.now() - datetime.fromtimestamp(cache[0]["timestamp"]) > timedelta(minutes=5)):
        for alert_id, description in processContract(cache[0]["chain_id"], cache[0]["address"]):
            findings.append(Finding({
                'name': 'Suspicious Contract Code',
                'description': description,
                'alert_id': alert_id,
                'severity': FindingSeverity.Low,
                'type': FindingType.Info,
                'metadata': {
                    "transaction_hash": cache[0]["hash"],
                    "contract_address": cache[0]["address"],
                    "deployer": cache[0]["from"]
                }
            }))
        cache = cache[1:]
    return findings


import openpyxl

VOLUNTEER_NUMBER = 1
VOLUNTEER_FIRST_NAME= 2
VOLUNTEER_LAST_NAME= 3
VOLUNTEER_EMAIL = 4
VOLUNTEER_HOUR= 5
VOLUNTEER_POSITION = 6
VOLUNTEER_COMMENT = 7
VOLUNTEER_CERT_LOC = 8
class VolunteerExcelFile:
    """
    VolunteerExcelFile Class

    """

    def __init__(self, filename: str):
        """
        Constructor

        Takes in the filename or filepath
        filename: filename or path of the excel file
        workbook: the excel workbook
        worksheet: the active worksheet
        max_row: the maximum row that's been used in the excel sheet
        max_column: the maximum column that's been used in the excel sheet
        data: a dictionary that saves the data input from excel

        """

        self.__filename = filename
        self.__workbook = openpyxl.load_workbook(filename)
        self.__worksheet = self.__workbook.active
        self.__max_row = self.__worksheet.max_row
        self.__max_column = self.__worksheet.max_column
        self.__data = {}

    def get_file_name(self) -> str:
        """
        Returns the filename
        """
        return self.__filename

    def get_file_content(self) -> None:
        """
        Return the file content in a dictionary
        """
        for row in range(2, self.__max_row + 1):
            for column in range(1, self.__max_column):
                self.__data[self.__worksheet.cell(row, VOLUNTEER_FIRST_NAME).value + ' ' + self.__worksheet.cell(row, VOLUNTEER_LAST_NAME).value] = \
                    [self.__worksheet.cell(row, VOLUNTEER_NUMBER).value,
                    self.__worksheet.cell(row,VOLUNTEER_FIRST_NAME).value,
                    self.__worksheet.cell(row, VOLUNTEER_LAST_NAME).value,
                    self.__worksheet.cell(row, VOLUNTEER_EMAIL).value,
                    self.__worksheet.cell(row, VOLUNTEER_HOUR).value,
                    self.__worksheet.cell(row, VOLUNTEER_POSITION).value,
                    self.__worksheet.cell(row, VOLUNTEER_COMMENT).value]
        return self.__data

    def get_data(self) -> str:
        """
        Return the data dictionary
        """

        return self.__data


st=0
board=[]

b = input("").split(",")
Dies = list( map( int, input("").split(",") ) )

for i in b:
    c = i.split(":")
    a = [int(c[0]) , int(c[1])]
    board.append(a)

data = dict(board)

for i in Dies:
    die = i
    st =st+ die

    for i in data:
        if(i == st):
            st = data.get(i)
        else:
            st
    if(st>=100):
        break

if(st >= 100):
    print("Yes")
else:
    print("No")


t = int(input())
for l in range(t):
    n = int(input())
    c = 0
    temp = n
    ds = 0
    while temp != 0:
        # print(temp, ds)
        ds += (temp % 10)
        temp = temp//10

    # print(ds)

    if ds%10==0:
        digit = 0
    else:
        digit = 10 - ds%10

    # print(digit)
    ans = int(str(n) + str(digit))
    print(ans)


'''
The following codes are from https://github.com/d-li14/mobilenetv2.pytorch
'''

import os
import torch
import numpy as np
from torchvision import datasets
from torchvision import transforms

DATA_BACKEND_CHOICES = ['pytorch']
try:
    from nvidia.dali.plugin.pytorch import DALIClassificationIterator
    from nvidia.dali.pipeline import Pipeline
    from nvidia.dali import ops
    from nvidia.dali import types
    DATA_BACKEND_CHOICES.append('dali-gpu')
    DATA_BACKEND_CHOICES.append('dali-cpu')
except ImportError:
    print("Please install DALI from https://www.github.com/NVIDIA/DALI to run this example.")

class HybridTrainPipe(Pipeline):
    """
        Pipeline for training
    """
    def __init__(self, batch_size, num_threads, device_id, data_dir, crop, dali_cpu=False):
        '''
        Init function for training pipeline

        :param batch_size: batch size for training
        :param num_threads: number of threads to use
        :param device_id: device id
        :param data_dir: name of data directory
        :param crop: shape of cropped image
        :param dali_cpu: whether running on cpu or not
        '''
        super().__init__(batch_size, num_threads, \
                device_id, seed = 12 + device_id)
        if torch.distributed.is_initialized():
            local_rank = torch.distributed.get_rank()
            world_size = torch.distributed.get_world_size()
        else:
            local_rank = 0
            world_size = 1

        self.input = ops.FileReader(
                file_root = data_dir,
                shard_id = local_rank,
                num_shards = world_size,
                random_shuffle = True)

        self.jpegs, self.labels = self.input(name = "Reader")

        if dali_cpu:
            dali_device = "cpu"
            self.decode = ops.HostDecoderRandomCrop(device=dali_device, output_type=types.RGB,
                                                    random_aspect_ratio=[0.75, 4./3.],
                                                    random_area=[0.08, 1.0],
                                                    num_attempts=100)
        else:
            dali_device = "gpu"
            # This padding sets the size of the internal nvJPEG buffers to
            # be able to handle all images from full-sized ImageNet
            # without additional reallocations
            self.decode = ops.ImageDecoderRandomCrop(device="mixed", \
                    output_type=types.RGB, device_memory_padding=211025920, \
                    host_memory_padding=140544512,
                                                      random_aspect_ratio=[0.75, 4./3.],
                                                      random_area=[0.08, 1.0],
                                                      num_attempts=100)

        self.res = ops.Resize(device=dali_device, resize_x=crop,\
                resize_y=crop, interp_type=types.INTERP_TRIANGULAR)
        self.cmnp = ops.CropMirrorNormalize(device = "gpu",
                                            output_dtype = types.FLOAT,
                                            output_layout = types.NCHW,
                                            crop = (crop, crop),
                                            image_type = types.RGB,
                                            mean = [0.485 * 255,0.456 * 255,0.406 * 255],
                                            std = [0.229 * 255,0.224 * 255,0.225 * 255])
        self.coin = ops.CoinFlip(probability = 0.5)

    def define_graph(self):
        """
        Define graph function

        :return: (output, labels): images of data, and labels of data
        """
        rng = self.coin()
        images = self.decode(self.jpegs)
        images = self.res(images)
        output = self.cmnp(images.gpu(), mirror = rng)
        return [output, self.labels]

class HybridValPipe(Pipeline):
    """
    Pipeline for validation
    """
    def __init__(self, batch_size, num_threads, device_id, data_dir, crop, size):
        '''
        Init function for validation pipeline

        :param batch_size: batch size for training
        :param num_threads: number of threads to use
        :param device_id: device id
        :param data_dir: name of data directory
        :param crop: shape of cropped image
        :param size: size of images
        '''
        super().__init__(batch_size, num_threads,\
                device_id, seed = 12 + device_id)
        if torch.distributed.is_initialized():
            local_rank = torch.distributed.get_rank()
            world_size = torch.distributed.get_world_size()
        else:
            local_rank = 0
            world_size = 1

        self.input = ops.FileReader(
                file_root = data_dir,
                shard_id = local_rank,
                num_shards = world_size,
                random_shuffle = False)

        self.decode = ops.ImageDecoder(device = "mixed", output_type = types.RGB)
        self.res = ops.Resize(device = "gpu", resize_shorter = size)
        self.cmnp = ops.CropMirrorNormalize(device = "gpu",
                output_dtype = types.FLOAT,
                output_layout = types.NCHW,
                crop = (crop, crop),
                image_type = types.RGB,
                mean = [0.485 * 255,0.456 * 255,0.406 * 255],
                std = [0.229 * 255,0.224 * 255,0.225 * 255])

    def define_graph(self):
        """
        Define graph function

        :return: (output, labels): images of data, and labels of data
        """
        images = self.decode(self.jpegs)
        images = self.res(images)
        output = self.cmnp(images)
        return [output, self.labels]

class DALIWrapper:
    """
    Wrapper Class
    """
    def __init__(self, dalipipeline):
        """
        Init function for initialization
        """
        self.dalipipeline = dalipipeline

    def __iter__(self):
        """
        Iterator function
        """
        return DALIWrapper.gen_wrapper(self.dalipipeline)

    def gen_wrapper(self):
        """
        generate wrapper function

        :param dalipipeline: dali pipeline
        """
        for data in self.dalipipeline:
            inputs = data[0]["data"]
            targets = data[0]["label"].squeeze().cuda().long()
            yield inputs, targets
        self.dalipipeline.reset()

def get_dali_train_loader(dali_cpu=False):
    """
    DALI train loader

    :param dali_cpu: whether cpus is used
    :return: gdtl: output of gdtl function
    """
    def gdtl(data_path, batch_size, workers=5, _worker_init_fn=None):
        """
        DALI train loader function

        :param data_path: image data path
        :param batch_size: batch size in training phase
        :param workers: how much workers we use
        :param _worker_init_fn: initialize worker function

        :return: DALIWrapper(train_loader) or int(pipe.epoch_size("Reader")/(world_size*batch_size))
                : wrapper of train loader, or number of batch
        """
        if torch.distributed.is_initialized():
            local_rank = torch.distributed.get_rank()
            world_size = torch.distributed.get_world_size()
        else:
            local_rank = 0
            world_size = 1

        traindir = os.path.join(data_path, 'train')

        pipe = HybridTrainPipe(batch_size=batch_size, num_threads=workers,
                device_id = local_rank,
                data_dir = traindir, crop = 224, dali_cpu=dali_cpu)

        pipe.build()
        train_loader = DALIClassificationIterator(pipe, size \
                = int(pipe.epoch_size("Reader") / world_size))

        return DALIWrapper(train_loader), \
            int(pipe.epoch_size("Reader") / (world_size * batch_size))

    return gdtl

def get_dali_val_loader():
    """
    DALI valid loader

    :return: gdvl: output of gdvl function
    """
    def gdvl(data_path, batch_size, workers=5, _worker_init_fn=None):
        """
        DALI valid loader function

        :param data_path: image data path
        :param batch_size: batch size in validation phase
        :param workers: how much workers we use
        :param _worker_init_fn: initialize worker function
        :return: DALIWrapper(val_loader) or int(pipe.epoch_size("Reader") / (world_size*batch_size))
                : wrapper of validation loader, or number of batch
        """
        if torch.distributed.is_initialized():
            local_rank = torch.distributed.get_rank()
            world_size = torch.distributed.get_world_size()
        else:
            local_rank = 0
            world_size = 1

        valdir = os.path.join(data_path, 'val')

        pipe = HybridValPipe(batch_size=batch_size, num_threads=workers,
                device_id = local_rank,
                data_dir = valdir,
                crop = 224, size = 256)
        pipe.build()
        val_loader = DALIClassificationIterator(pipe, size \
                = int(pipe.epoch_size("Reader") / world_size), fill_last_batch=False)

        return DALIWrapper(val_loader), \
            int(pipe.epoch_size("Reader") / (world_size * batch_size))
    return gdvl

def fast_collate(batch):
    """
    collate function

    :param batch: batch images
    :return: (tensor, targets): tensor for images, and labels of images
    """
    imgs = [img[0] for img in batch]
    targets = torch.tensor([target[1] for target in batch], dtype=torch.int64)
    width = imgs[0].size[0]
    height = imgs[0].size[1]
    tensor = torch.zeros( (len(imgs), 3, height, width), dtype=torch.uint8 )
    for i, img in enumerate(imgs):
        nump_array = np.asarray(img, dtype=np.uint8)
        if nump_array.ndim < 3:
            nump_array = np.expand_dims(nump_array, axis=-1)
        nump_array = np.rollaxis(nump_array, 2)

        tensor[i] += torch.from_numpy(nump_array)

    return tensor, targets

class PrefetchedWrapper:
    """
    Prefetched Wrapper
    """
    def prefetched_loader(self,loader):
        """
        Prefetched loader function

        :param loader: loading data
        :return: (tensor, targets): tensor for images, and labels of images
        """
        mean = torch.tensor([0.485 * 255, 0.456 * 255, 0.406 * 255]).cuda().view(1,3,1,1)
        std = torch.tensor([0.229 * 255, 0.224 * 255, 0.225 * 255]).cuda().view(1,3,1,1)

        stream = torch.cuda.Stream()
        first = True

        for next_input, next_target in loader:
            with torch.cuda.stream(stream):
                next_input = next_input.cuda(non_blocking=True)
                next_target = next_target.cuda(non_blocking=True)
                next_input = next_input.float()
                next_input = next_input.sub_(mean).div_(std)

            if not first:
                yield current_input, current_target
            else:
                first = False

            torch.cuda.current_stream().wait_stream(stream)
            current_input = next_input
            current_target = next_target

        yield current_input, current_target

    def __init__(self, dataloader):
        """
        Init function

        :param dataloader: loading data
        """
        self.dataloader = dataloader
        self.epoch = 0

    def __iter__(self):
        """
        Iterator function

        :return: PrefetchedWrapper.prefetched_loader(self.dataloader): wrapper of prefetched loader
        """
        if (self.dataloader.sampler is not None and
            isinstance(self.dataloader.sampler,
                       torch.utils.data.distributed.DistributedSampler)):

            self.dataloader.sampler.set_epoch(self.epoch)
        self.epoch += 1
        return PrefetchedWrapper.prefetched_loader(self, self.dataloader)

def get_pytorch_train_loader(data_path, batch_size, workers=5, \
        _worker_init_fn=None, input_size=224):
    """
    train loader function

    :param data_path: image data path
    :param batch_size: batch size in training phase
    :param workers: how much workers we use
    :param _worker_init_fn: initialize worker function
    :param input_size: image size
    :return: (PrefetchedWrapper(train_loader), len(train_loader))
            : prefetcehd wrapper of training loader, and length of training loader
    """
    traindir = os.path.join(data_path, 'train')
    train_dataset = datasets.ImageFolder(
            traindir,
            transforms.Compose([
                transforms.RandomResizedCrop(input_size),
                transforms.RandomHorizontalFlip(),
                ]))

    if torch.distributed.is_initialized():
        train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
    else:
        train_sampler = None

    train_loader = torch.utils.data.DataLoader(
            train_dataset, batch_size=batch_size, shuffle=(train_sampler is None),
            num_workers=workers, worker_init_fn=_worker_init_fn, \
            pin_memory=True, sampler=train_sampler, collate_fn=fast_collate)

    return PrefetchedWrapper(train_loader), len(train_loader)

def get_pytorch_val_loader(data_path, batch_size, workers=5, _worker_init_fn=None, input_size=224):
    """
    validation loader function

    :param data_path: image data path
    :param batch_size: batch size in training phase
    :param workers: how much workers we use
    :param _worker_init_fn: initialize worker function
    :param input_size: image size
    :return: (PrefetchedWrapper(val_loader), len(val_loader)
            : prefetcehd wrapper of validation loader, and length of validation loader
    """
    valdir = os.path.join(data_path, 'val')
    val_dataset = datasets.ImageFolder(
            valdir, transforms.Compose([
                transforms.Resize(int(input_size / 0.875)),
                transforms.CenterCrop(input_size),
                ]))

    if torch.distributed.is_initialized():
        val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset)
    else:
        val_sampler = None

    val_loader = torch.utils.data.DataLoader(
            val_dataset,
            sampler=val_sampler,
            batch_size=batch_size, shuffle=False,
            num_workers=workers, worker_init_fn=_worker_init_fn, pin_memory=True,
            collate_fn=fast_collate)

    return PrefetchedWrapper(val_loader), len(val_loader)


from django.db import models

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

class Status(models.Model):
    id = models.AutoField(
        primary_key=True,
    )
    title = models.CharField(
        verbose_name='Название стадии',
        max_length=64,
        default='',
    )
    order = models.SmallIntegerField(
        verbose_name='Порядок в списке стадий',
        default=0,
    )
    next_status = models.ForeignKey(
        'self',
        verbose_name='Следующая стадия',
        related_name='NextStatus',
        null=True,
        blank=True,
        default=None,
        on_delete=models.SET_NULL,
    )

    def __str__(self):
        return '{0}'.format(self.title)

    class Meta:
        ordering = 'order', 'title',
        verbose_name = 'Статус'
        verbose_name_plural = 'Статусы'
        managed = True

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

class Contract(models.Model):
    id = models.AutoField(
        primary_key=True,
    )
    title = models.CharField(
        verbose_name='Наименование',
        max_length=124,
        default='',
    )
    amount = models.CharField(
        verbose_name='Плановая сумма',
        max_length=124,
        default='',
    )
    comment = models.TextField(
        verbose_name='Комментарий',
        blank=True,
        default='',
    )
    closed = models.BooleanField(
        verbose_name='Закрыт',
        default=False,
    )
    create_date = models.DateTimeField(
        verbose_name='Дата создания контракта',
        auto_now_add=True,
        null=True,
    )

    def __str__(self):
        return '{0}'.format(self.title)

    class Meta:
        ordering = 'title',
        verbose_name = 'Контракт'
        verbose_name_plural = 'Контракты'
        managed = True

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

class Stage(models.Model):
    id = models.AutoField(
        primary_key=True,
    )
    contract = models.ForeignKey(
        Contract,
        verbose_name='Контракт',
        null=True,
        related_name='ContractStatus',
        on_delete=models.SET_NULL,
    )
    status = models.ForeignKey(
        Status,
        verbose_name='Статус контракта',
        null=True,
        related_name='StatusContract',
        on_delete=models.SET_NULL,
    )
    comment_stage = models.TextField(
        verbose_name='Комментарий',
        default='',
    )
    create_date = models.DateTimeField(
        verbose_name='Дата создания стадии',
        auto_now_add=True,
        null=True,
    )

    def __str__(self):
        return '{0} - {1}'.format(self.contract, self.status)

    class Meta:
        ordering = 'status', 'contract',
        verbose_name = 'Стадия'
        verbose_name_plural = 'Стадии'
        managed = True

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

class Attache(models.Model):
    id = models.AutoField(
        primary_key=True,
    )
    name = models.CharField(
        verbose_name='Название файла',
        max_length=124,
        default='',
    )
    file = models.FileField(
        verbose_name='Файл',
        upload_to='contract/attache/%Y/%m/%d',
        null=True,
        blank=True,
    )
    stage = models.ForeignKey(
        Stage,
        verbose_name='Стадия',
        null=True,
        related_name='AttacheStage',
        on_delete=models.SET_NULL,
    )
    create_date = models.DateTimeField(
        verbose_name='Дата создания файла',
        auto_now_add=True,
        null=True,
    )

    def get_human_size(self):
        value = self.file.size
        if value < 512000:
            value = value / 1024.0
            ext = 'Кб'
        elif value < 4194304000:
            value = value / 1048576.0
            ext = 'Мб'
        else:
            value = value / 1073741824.0
            ext = 'Гб'
        return '{0} {1}'.format(str(round(value, 2)), ext)

    def __str__(self):
        return '{0}'.format(self.name)

    class Meta:
        ordering = 'create_date',
        verbose_name = 'Вложение'
        verbose_name_plural = 'Вложения'
        managed = True

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


from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
import tensorflow as tf
# implement variables
x= tf.placeholder(tf.float32, [None,784]) #note None allows any length
W= tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
#implement model
y=tf.nn.softmax(tf.matmul(x,W)+b)#this implements our Model
#placeholder for correct values
y_=tf.placeholder(tf.float32,[None,10])

#cross entropy function
cross_entropy=tf.reduce_mean(
      tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess=tf.InteractiveSession()
tf.global_variables_initializer().run()
for i in range(100):
    batch_xs,batch_ys = mnist.train.next_batch(100)
    sess.run(train_step,feed_dict={x:batch_xs,y_:batch_ys})

# tf.argmax returns the index of the highest entry in a tensor along a given axis
# returns a list of booleans
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
#returns the average of the booleans cast to floats. ie 1=True,0=False
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels}))


# 변수 선언 및 입력:
n = int(input())
arr = list(map(int, input().split()))
freq = {}

# 각 수가 몇 번씩 나왔는지 기록합니다.
for elem in arr:
    freq[elem] = freq.get(elem, 0) + 1

# 정확히 1번만 나온 수 중
# 등장한 최초 위치를 구해줍니다.
ans = -1
for i in range(n - 1, -1, -1):
    # 최초로 나왔다면 답을 갱신합니다.
    if freq[arr[i]] == 1:
        ans = arr[i]

print(ans)

코드트리/모의고사/네카라쿠배2/2_오직한번만주어진수.py

2_오직한번만주어진수.py


# daily challenge mar. 14
# simply path

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        stack = []

        for portion in path.split("/"):
            if portion == "..":
                if stack:
                    stack.pop()
            elif portion == "." or not portion:
                continue
            else:
                stack.append(portion)

        final_path = "/" + "/".join(stack)
        return final_path

sol = Solution()
path = "/a/b/c/.././././//d"

result = sol.simplifyPath(path)
print(result)


height = [4,2,0,3,2,5]
# height = [0,1,0,2,1,0,1,3,2,1,2,1]
all_trapped = 0
for i in range(1,len(height)-1):
    trapped = 0
    water_level= min(max(height[:i]),max(height[i:]))
    if water_level > 0 and trapped >= 0:
        trapped = water_level - height[i]
    if trapped > 0:
        all_trapped+=trapped

print(all_trapped)


# suggestions.py
# Code to handle submitting and reviewing suggestions.
# Author: wHo#6933

# Plans:
# 1. Submit suggestion command
# 2. List pending suggestions command
# 3. Accept/Decline suggestions command

# Json format:
# {
#    "id" (int): {
#       "user": userId (int),
#       "suggestion": suggestion (str)
#       "status": "accepted", "pending", "declined" (str, either 3)
#       }
# }

from typing import List
import discord
from discord import embeds
from discord.ext import commands
from discord_components import ActionRow, Button, ButtonStyle, component

import random
import asyncio

from discord.ext.commands.core import command
from discord_components.interaction import InteractionEventType

from functions import readSuggestions, writeSuggestions, check_admin, generateRandomColor

class suggestionsCommand(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # Submit suggestion
    @commands.command()
    async def suggest(self, ctx, *, suggestion=""):
        # check if suggestion is empty
        if suggestion == "":
            await ctx.send(":x: Empty suggestion >:(")
            return

        data = await readSuggestions()

        data[max(data.keys()) + 1] = {  # get highest id, +1, and add content to it
            "user": int(ctx.author.id),
            "suggestion": suggestion,
            "status": "pending"
        }

        await writeSuggestions(data)
        await ctx.reply(random.choice([":white_check_mark: Your suggestion has been sent for review :D", ":white_check_mark: Your suggestion has been sent for review :>"]))

    # List pending commands
    # Admin only ;-;
    @commands.command()
    async def listSuggestions(self, ctx, resultsPerPage="5"):
        if await check_admin(str(ctx.author.id)) == False:
            await ctx.reply(":x: This command is only for admins :<")
            return

        if not resultsPerPage.isdigit():
            await ctx.send(":x: Invalid results per page value :<")
            return

        index = 0
        data = await readSuggestions()
        idList = [] # List of suggestion IDs to be displayed

        # Populate list
        tmp = []
        for i in data.keys():
            tmp.append(i)
            if i % int(resultsPerPage) == 0 and i != 0 or i == list(data.keys())[-1]: # checks if: it is the max number of result per page, or it is the last suggestion
                idList.append(tmp)
                tmp = []

        # buttons
        options = [ActionRow(
            Button(label="|<", style=ButtonStyle.gray, custom_id="btn_start"),
            Button(label="<", style=ButtonStyle.gray, custom_id="btn_left"),
            Button(label=">", style=ButtonStyle.gray, custom_id="btn_right"),
            Button(label=">|", style=ButtonStyle.gray, custom_id="btn_end")
        )]

        disabledOptions = [ActionRow(
            Button(label="|<", style=ButtonStyle.gray, custom_id="btn_start", disabled=True),
            Button(label="<", style=ButtonStyle.gray, custom_id="btn_left", disabled=True),
            Button(label=">", style=ButtonStyle.gray, custom_id="btn_right", disabled=True),
            Button(label=">|", style=ButtonStyle.gray, custom_id="btn_end", disabled=True)
        )]

        # Display data
        embed = await self.generateSuggestions(ctx, idList, data, 0)
        msg = await ctx.send(embed=embed, components=options)

        # handle button clicks and change pages
        while True:
            try:
                res = await self.bot.wait_for("button_click", timeout=60)
                if res.channel == ctx.channel and res.user == ctx.author:
                    if res.component.custom_id == "btn_start":
                        await res.respond(type=6, content="\u2800") # \u2800 sends empty stuff, used to bypass HTTP error thingy
                        await msg.edit(embed=await self.generateSuggestions(ctx, idList, data, 0), components=options)
                        index = 0
                    if res.component.custom_id == "btn_left" and index != 0:
                        await res.respond(type=6, content="\u2800")
                        await msg.edit(embed=await self.generateSuggestions(ctx, idList, data, index-1), components=options)
                        index -= 1
                    elif res.component.custom_id == "btn_left" and index == 0:
                        await res.respond(type=6, content="\u2800")
                        await msg.edit(embed=await self.generateSuggestions(ctx, idList, data, index), components=options)
                    if res.component.custom_id == "btn_right" and index != (len(idList) - 1):
                        await res.respond(type=6, content="\u2800")
                        await msg.edit(embed=await self.generateSuggestions(ctx, idList, data, index+1), components=options)
                        index += 1
                    elif res.component.custom_id == "btn_right" and index == (len(idList) - 1):
                        await res.respond(type=6, content="\u2800")
                        await msg.edit(embed=await self.generateSuggestions(ctx, idList, data, index), components=options)
                    if res.component.custom_id == "btn_end":
                        await res.respond(type=6, content="\u2800")
                        await msg.edit(embed=await self.generateSuggestions(ctx, idList, data, (len(idList) - 1)), components=options)
                        index = len(idList) - 1
                else:
                    await self.respond(res, "Lmao this isn't your button :>")
            except asyncio.TimeoutError:
                await msg.edit(embed=embed, components=disabledOptions)
                break

    async def generateSuggestions(self, ctx, idList, data, index : int):
        color = await generateRandomColor()
        embed = discord.Embed(title=f"Suggestions, Page {index + 1}", color=color)
        embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/903696474951520397/904335874483965962/logo.png") # CTSS Logo
        embed.set_footer(text=f"Requested by: {ctx.author.name}#{ctx.author.discriminator}, Page {index + 1}", icon_url=f"{ctx.message.author.avatar_url}")

        for i in idList[index]:
            embed.add_field(name=f"Suggestion #{i} by {ctx.author.name}#{ctx.author.discriminator}",
                            value=f"Suggestion: {data[i]['suggestion']}",
                            inline=False)

        return embed

    async def respond(self, res, content):
        await res.respond(content=content)

# Link cog to main bot
def setup(bot):
    bot.add_cog(suggestionsCommand(bot))


a=[1, 3, 2, 5, 2, 2, 3, 1, 1, 6]
print(len(a))

result=[]
for i in range(len(a)):
    start = i -a[i]
    end = i + a[i]
    if start < 0 :
        start = 0
    if end > len(a):
        end = len(a)
    result.append(sum(a[start:end+1]))
print(result)

혼자하는거/기초_예제7번.py


import os
import shutil
import pickle

import pandas as pd

from sklearn.cluster import KMeans

#pd.set_option('display.max_colwidth', -1)

DATA_PATH = "../ML_data"
target = os.path.join(DATA_PATH, "target.csv")
fp = os.path.join(DATA_PATH, "fp_folded.csv")

y = pd.read_csv(target, index_col = "index")

y = y.loc[(y["t_cell"] == 1) & (y["clusters"] == 0),"smiles"].sample(10).to_list()

for sample in y:
	print(sample)

# print(y)

exit()

#X = pd.read_csv(fp, index_col = "index")

#X = X.astype(float)

# y2 = pd.read_csv("target_df_pca_c_oc.csv", index_col = "acc")
#X2 = pd.read_csv("fps_oc.csv", index_col = "acc")

#print((X == X2).all())

#test_row = (X.loc[:,"12"] == X2.loc[:,"12"])

#print(test_row.loc[(test_row == False)])

#print(X.loc["CHEBI:51736", "12"])
#print(X2.loc["CHEBI:51736", "12"])

###########################
#Test the FP generation
###########################

# from rdkit import Chem
# from rdkit.Chem import AllChem, DataStructs

# def convert_to_count(val):
#     if val == 0:
#         return(0)
#     else:
#         return(1)

# def smiles_df_to_fp_df_folded(smiles_df,
#                                 OUTPATH = None,
#                                 count_vector = False,
#                                 nBits = 1024,
#                                 radius = 3,
#                                 useFeatures = False,
#                                 useChirality = True,
#                                 verbose = False,
#                                 **kwargs):

#     result_df = pd.DataFrame(columns = list(range(nBits)))

#     for index, (mol_id, row) in enumerate(smiles_df.iterrows()):

#         #show process
#         if verbose:
#             if index % 1000 == 0:
#                 print(index)

#         mol = Chem.MolFromSmiles(row["smiles"])

#         fp = AllChem.GetHashedMorganFingerprint(
#                              mol,
#                              radius,
#                              nBits = nBits,
#                              useFeatures = useFeatures,
#                              useChirality = useChirality,
#                              ).GetNonzeroElements()

#         result_df.loc[mol_id,:] = 0
#         result_df.loc[mol_id, fp.keys()] = fp.values()

#     #simple way to convert count to bit
#     if not count_vector:
#         result_df = result_df.applymap(convert_to_count)

#     #convert to int (saves memory)
#     result_df = result_df.applymap(int)

#     result_df.index.name = "index"

#     if OUTPATH:
#         result_df.to_csv(OUTPATH)

#     return(result_df)

# smi1 = y.loc[["CHEBI:51736"],["smiles"]]

# print(smi1)

# fp1 =  smiles_df_to_fp_df_folded(smi1)

# print(fp1.loc[:,12])

# # mol1 = Chem.MolFromSmiles(smi1)
# # smi1 = Chem.MolToSmiles(mol1)

# # print(smi1)

# smi2 = y2.loc[["CHEBI:51736"],["smiles"]]

# print(smi2)

# fp2 =  smiles_df_to_fp_df_folded(smi2)

# print(fp2.loc[:,12])

# exit()

# print("C1C2*34567C1~C3~C4~C5~C6~C7~2")

# print(y.loc["CHEBI:51736",:])
# print(y2.loc["CHEBI:51736",:])

# exit()

exit()

print(X.shape)

X.sort_index(inplace = True)
#X = X.iloc[:1000,:]

print(X.iloc[:5,:])

cluster_clf = KMeans(n_clusters=8, random_state=0, n_jobs = -1)
clusters = cluster_clf.fit_predict(X)

print(clusters)

# cluster_clf = KMeans(n_clusters=8, random_state=0, n_jobs = -1)
# clusters = cluster_clf.fit_predict(X.copy())

# print(clusters)

exit()

# exit()
#print(clusters)

y2 = pd.read_csv("target_df_pca_c_oc.csv", )
X2 = pd.read_csv("fps_oc.csv", index_col = "acc")

print(X2.shape)

X2.sort_index(inplace = True)
#X2 = X2.iloc[:1000,:]

print(X2.iloc[:5,:])

cluster_clf = KMeans(n_clusters=8, random_state=0, n_jobs = -1)
clusters2 = cluster_clf.fit_predict(X2)

print(clusters2)

print((clusters2 == clusters).all())

"""
                0    1    2    3    4    5  ...  1018  1019  1020  1021  1022  1023
acc                                         ...
CHEBI:100     0.0  0.0  0.0  1.0  0.0  0.0  ...  0.0   1.0   0.0   0.0   0.0   0.0
CHEBI:10002   0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0   0.0   0.0   0.0   0.0   0.0
CHEBI:10003   0.0  0.0  0.0  1.0  0.0  0.0  ...  0.0   1.0   0.0   0.0   1.0   0.0
CHEBI:100147  0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0   0.0   0.0   0.0   0.0   0.0
CHEBI:100148  0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0   0.0   0.0   0.0   0.0   0.0
"""

"""
[2 2 7 ... 6 2 6]
"""


import os
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

class scrapebook():

    _edge_driver = os.path.join(os.getcwd(), 'msedgedriver.exe') #path to the edge driver

    def __init__(self, isbn) -> None:
        """
        SETUP the init method of the class

        parameter: ISBN number of the book

        example: 9781838559984
        """
        self.url = f"https://www.perlego.com/search?query={isbn}"

        self.driver = webdriver.Edge(executable_path=scrapebook._edge_driver)
        self.wait = WebDriverWait(self.driver,1)

    def loadwebpage(self):
        """
        uses the url of the webpage that had been setup in the init method and
        clicks till it reaches the table of content
        """
        self.driver.get(self.url)
        self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid*='Cookies']"))).click()
        self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[data-test-locator*='new-book']"))).click()

        self.driver.find_element(By.XPATH, "(//*[contains(text(),'Table of contents')])[1]").click()
        pass

    def soupingthecontent(self):
        """
        Once reached we get the page source and find all the texts
        under the table of content and returns the  striped list back to
        """
        soup = BeautifulSoup(self.driver.page_source,"html.parser")

        results = soup.find_all(attrs={'class': ['sc-b81fc1ca-2','kydYov']}, text=True)

        table_of_content = []
        for x in results:
            table_of_content.append(x.text)
        return table_of_content

scarpethis = scrapebook(9781617295980)
scarpethis.loadwebpage()
table_of_content = scarpethis.soupingthecontent()
print(table_of_content)


'''
Always want to combine the two sticks with the smallest lengths to minimize cost. Can use minHeap to get the two sticks with lowest cost. One we combine sticks. We put back into heap

Time: heapify: O(n) + O(nlog(n))
'''

from heapq import *

class Solution:
    def connectSticks(self, sticks: List[int]) -> int:
        heapify(sticks)
        totalCost = 0

        while len(sticks) > 1:
            cost = heappop(sticks) + heappop(sticks)
            heappush(sticks, cost)
            totalCost += cost

        return totalCost


"""Module for ingesting quotes from PDF files."""

import os
import subprocess
from typing import List
import tempfile

from .IngestorInterface import IngestorInterface
from .QuoteModel import QuoteModel

class PDFIngestor(IngestorInterface):
    """Ingestor for parsing quotes from PDF files.

    This class inherits from IngestorInterface and implements the parse method
    for PDF files.
    """

    allowed_extensions = ['pdf']
    """List of allowed file extensions for this ingestor."""

    @classmethod
    def parse(cls, path: str) -> List[QuoteModel]:
        """Parse a PDF file and create a list of QuoteModel objects.

        This method uses the `pdftotext` command-line utility to convert PDF
        content to text and then extracts quotes and authors.

        Parameters:
            path (str): The file path to the PDF file to be ingested.

        Returns:
            List[QuoteModel]: A list of QuoteModel objects.
        """
        if not cls.can_ingest(path):
            raise ValueError(f"Cannot ingest file with unsupported format: {path}")

        try:
            with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as tmp:
                subprocess.run(['pdftotext', path, tmp.name], check=True)
                tmp_path = tmp.name

            quotes = []
            with open(tmp_path, 'r') as file:
                for line in file.readlines():
                    line = line.strip().split(' - ')
                    if len(line) == 2:
                        quote_body = line[0].strip()
                        quote_author = line[1].strip()
                        quotes.append(QuoteModel(quote_body, quote_author))

            os.unlink(tmp_path)  # Clean up the temporary file
            return quotes
        except subprocess.CalledProcessError as e:
            raise Exception(f"Error during PDF to text conversion: {e}")


import math
from torch.optim.lr_scheduler import _LRScheduler

class CosineAnnealingWarmUpRestarts(_LRScheduler):
    r"""Set the learning rate of each parameter group using a cosine annealing
    schedule, where :math:`\eta_{max}` is set to the initial lr, :math:`T_{cur}`
    is the number of epochs since the last restart and :math:`T_{i}` is the number
    of epochs between two warm restarts in SGDR:

    .. math::
        \eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 +
        \cos\left(\frac{T_{cur}}{T_{i}}\pi\right)\right)

    When :math:`T_{cur}=T_{i}`, set :math:`\eta_t = \eta_{min}`.
    When :math:`T_{cur}=0` after restart, set :math:`\eta_t=\eta_{max}`.

    It has been proposed in
    `SGDR: Stochastic Gradient Descent with Warm Restarts`_.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        T_0 (int): Number of iterations for the first restart.
        T_mult (int, optional): A factor increases :math:`T_{i}` after a restart. Default: 1.
        eta_min (float, optional): Minimum learning rate. Default: 0.
        last_epoch (int, optional): The index of last epoch. Default: -1.
        verbose (bool): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
        https://arxiv.org/abs/1608.03983

    A custom scheduler with the addition of [Warmup & Decay]
    """

    def __init__(self, optimizer, T_0, T_warmup=0, T_mult=1, eta_min=0, last_epoch=-1, decay=1, verbose=False):
        if T_0 <= 0 or not isinstance(T_0, int):
            raise ValueError("Expected positive integer T_0, but got {}".format(T_0))
        if T_mult < 1 or not isinstance(T_mult, int):
            raise ValueError("Expected integer T_mult >= 1, but got {}".format(T_mult))
        self.T_0 = T_0
        self.T_i = T_0
        self.T_mult = T_mult
        self.T_warmup = T_warmup
        self.eta_min = eta_min
        self.decay = decay
        self.T_decay = 0

        super(CosineAnnealingWarmUpRestarts, self).__init__(optimizer, last_epoch, verbose)

        self.T_cur = self.last_epoch

    def get_lr(self):
        if not self._get_lr_called_within_step:
            warnings.warn("To get the last learning rate computed by the scheduler, "
                          "please use `get_last_lr()`.", UserWarning)

        if self.T_cur < self.T_warmup:
            return [((base_lr - self.eta_min)*self.T_cur / self.T_warmup) * self.decay ** self.T_decay + self.eta_min
                for base_lr in self.base_lrs]
        else:
            # return [base_lr + (self.eta_max - base_lr) * (1 + math.cos(math.pi * (self.T_cur-self.T_up) / (self.T_i - self.T_up))) / 2
            #         for base_lr in self.base_lrs]
            return [(base_lr - self.eta_min) * (1 + math.cos(math.pi * (self.T_cur - self.T_warmup) / (self.T_i - self.T_warmup))) / 2 * self.decay ** self.T_decay + self.eta_min
                for base_lr in self.base_lrs]

    def step(self, epoch=None):
        """Step could be called after every batch update

        Example:
            >>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
            >>> iters = len(dataloader)
            >>> for epoch in range(20):
            >>>     for i, sample in enumerate(dataloader):
            >>>         inputs, labels = sample['inputs'], sample['labels']
            >>>         optimizer.zero_grad()
            >>>         outputs = net(inputs)
            >>>         loss = criterion(outputs, labels)
            >>>         loss.backward()
            >>>         optimizer.step()
            >>>         scheduler.step(epoch + i / iters)

        This function can be called in an interleaved way.

        Example:
            >>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
            >>> for epoch in range(20):
            >>>     scheduler.step()
            >>> scheduler.step(26)
            >>> scheduler.step() # scheduler.step(27), instead of scheduler(20)
        """

        if epoch is None and self.last_epoch < 0:
            epoch = 0

        if epoch is None:
            epoch = self.last_epoch + 1
            self.T_cur = self.T_cur + 1
            if self.T_cur >= self.T_i:
                self.T_cur = self.T_cur - self.T_i
                self.T_i = (self.T_i - self.T_warmup) * self.T_mult + self.T_warmup
                self.T_decay = self.T_decay + 1
        else:
            if epoch < 0:
                raise ValueError("Expected non-negative epoch, but got {}".format(epoch))
            if epoch >= self.T_0:
                if self.T_mult == 1: # epoch >= self.T_0 && T_mult == 1
                    self.T_cur = epoch % self.T_0
                    self.T_decay = epoch // self.T_0
                else: # epoch >= self.T_0 && T_mult > 1
                    n = int( math.log( (epoch / self.T_0 * (self.T_mult - 1) + 1), self.T_mult ) ) # math.log(지수, 밑)
                    self.T_cur = epoch - self.T_0 * (self.T_mult ** n - 1) / (self.T_mult - 1)
                    self.T_i = self.T_0 * self.T_mult ** (n)
                    self.T_decay = n
            else: # 0 <= epoch < self.T_0
                self.T_i = self.T_0
                self.T_cur = epoch
        self.last_epoch = math.floor(epoch)

        class _enable_get_lr_call:

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

            def __enter__(self):
                self.o._get_lr_called_within_step = True
                return self

            def __exit__(self, type, value, traceback):
                self.o._get_lr_called_within_step = False
                return self

        with _enable_get_lr_call(self):
            for i, data in enumerate(zip(self.optimizer.param_groups, self.get_lr())):
                param_group, lr = data
                param_group['lr'] = lr # change lr here
                self.print_lr(self.verbose, i, lr, epoch)

        self._last_lr = [group['lr'] for group in self.optimizer.param_groups]


# -*- coding: utf-8 -*-
import os
import csv
import matplotlib.pyplot as plt

"""
This script is for plotting each data (force/RMSE & TC(300K) diff from 112.1)
with classified color by normalized distance
"""

if __name__ == '__main__':
    root=os.getcwd()

    tdata=["40"]
    node=["50","100","200","300","500"]
    rstfile=root+"/result/RMSEdata.csv"
    plotfile=root+"/result/grpplot/opt/data-d40only.png"
    labels=('nrm>0.9','0.9>nrm>0.6','0.6>nrm>0.4','0.4>nrm>0.2','0.2>nrm>0.1','0.1>nrm')
    colors=("red","orange","yellow","cyan","c","b")

    grp = []
    for k in tdata:
        for i in node:
            grpname="d"+k+"n"+i
            grp.append(grpname)

    with open(rstfile, 'r') as rslt:
        readcsv = csv.reader(rslt)
        RMSETC = []

        for row in readcsv:
            gnameall = row[0]
            gname = gnameall.split("-")[0]
            if gname in grp:
                normalized = float(row[3])
                if normalized>0.9:
                    RMSETC.append([float(row[1]),float(row[2]),colors[0]])
                elif normalized>0.6:
                    RMSETC.append([float(row[1]),float(row[2]),colors[1]])
                elif normalized>0.4:
                    RMSETC.append([float(row[1]),float(row[2]),colors[2]])
                elif normalized>0.2:
                    RMSETC.append([float(row[1]),float(row[2]),colors[3]])
                elif normalized>0.1:
                    RMSETC.append([float(row[1]),float(row[2]),colors[4]])
                else:
                    RMSETC.append([float(row[1]),float(row[2]),colors[5]])

    print("Number of sample = %d" % len(RMSETC))
    #Plotting all data of correlation of force/RMSE and TC error
    fig = plt.figure()
    ax3 = fig.add_subplot(111)
    plt.title("data# = 40")
    ax3.set_xlabel("TC Err (fm 112.1)")
    ax3.set_ylabel("force/RMSE (meV/A)")
    ax3.grid(True)
    plt.rcParams["legend.edgecolor"] ='green'

    dtn=0
    for k in tdata:
        for i in node:
            for j in range(0, 10):
                ax3.scatter(RMSETC[dtn][1],RMSETC[dtn][0],c=RMSETC[dtn][2],marker='.')
                dtn=dtn+1

    left, right = ax3.get_xlim()
    ax3.set_xlim(-0.1, right*1.2)
    #ax4 is only for plotting legend of all kind of data
    ax4 = ax3.twinx()
    for j in range(0, 6):
        lbl=labels[j]
        clr=colors[j]
        ax4.scatter(RMSETC[0][1],RMSETC[0][0],c=clr,marker='.',label=lbl)
    handler4, label4 = ax4.get_legend_handles_labels()
    ax3.legend(handler4, label4,loc='upper right',title='Normalized dist',bbox_to_anchor=(0.97, 0.85, 0.14, .100),borderaxespad=0.,)
    fig.delaxes(ax4)
    plt.savefig(plotfile)
    plt.close()


n = int(input())
a = [tuple(input().split()) for _ in range(n)]

d = {}

# print(a)
for i in range(n):
    command = a[i][0]
    k = int(a[i][1])

    if command == "add":
        d[k] = int(a[i][2])
    elif command == "remove":
        d.pop(k)
    else:
        # print(k, d)
        if k in d:
            print(d[k])
        else:
            print(None)


# py -m pip install pygame
# py -m pip install pywin32

import pygame, sys, random
import win32api
import win32con
import win32gui

def hide_console():
    window = win32gui.GetForegroundWindow()
    win32gui.ShowWindow(window, win32con.SW_HIDE)

if __name__ == "__main__":
    hide_console()

    pygame.init()

    clock = pygame.time.Clock()

    # Obtener información de la pantalla actual
    screen_info = pygame.display.Info()

    # Definir el ancho y alto de la pantalla
    screen_width = screen_info.current_w
    screen_height = screen_info.current_h

    # Crear la ventana del juego
    screen = pygame.display.set_mode((screen_width, screen_height))

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Aquí puedes agregar el código para dibujar y actualizar el juego.

        pygame.display.flip()  # Actualizar la pantalla
        clock.tick(60)  # Limitar la velocidad de cuadros a 60 FPS


import math

x, y, w, h = map(int, input().split())

'''
직사각형 (0,0)~(w,h)
한수 (x,y)

안에 위치할 경우 :
점 사방면의 거리를 체크하여 가장 짧은 위치 출력

밖에 위치할 경우 :
    case1:
    x>w and y<=h
    case2:
    x<=w and y>h
    case3:
    x>w and y>h
'''

if x<=w and y<=h:
    check = []
    check.append(w-x)
    check.append(x)
    check.append(h-y)
    check.append(y)

    print(min(check))

else:
    if x>w and y<=h:
        print(x-w)
    elif x<=w and y>h:
        print(y-h)
    else:
        print(math.sqrt(x^2 + y^2))


import cv2
import face_recognition
from django.conf import settings
from .faceRecognition import findEncodings
import os, numpy as np
from .attendance import mark_attendance, get_Remarks
from .models import Schedule
import time

class VideoCamera(object):
    t = Schedule.objects.get(is_active=True)
    def __init__(self):
        time.sleep(1)
        self.video = cv2.VideoCapture(settings.CAMERA, cv2.CAP_DSHOW)
        # self.video.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        # self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

    def __del__(self):
        self.video.release()

    def get_frame(self, encodeListKnown, classNames):
        success, image = self.video.read()
        image = cv2.flip(image, 1)

        # print(encodeListKnown)

        if not len(encodeListKnown) == 0 and not Schedule.objects.filter(is_active=True).count() == 0:
            height, width, _ = image.shape
            (text_width, text_height), _ = cv2.getTextSize(str(get_Remarks()), cv2.FONT_HERSHEY_COMPLEX, fontScale=2, thickness=3)
            fontColor = (0,255,0) if get_Remarks() == "EARLY" else (0, 0, 255)

            imgS = cv2.resize(image,(0,0), None, 0.25,0.25)
            imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
            facesCurFrame = face_recognition.face_locations(imgS)
            encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)

            for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame):
                matches = face_recognition.compare_faces(encodeListKnown, encodeFace, 0.7)
                faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)

                matchesIndex = np.argmin(faceDis)
                y1, x2, y2, x1 = faceLoc
                # print(faceLoc)
                y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
                if matches[matchesIndex] and (faceDis[matchesIndex] < 0.4):
                    # name = classNames[matchesIndex].upper()
                    name = classNames[matchesIndex]
                    # print(name)
                    cv2.rectangle(image,(x1, y1), (x2, y2), (0, 255, 0), 2)
                    # cv2.rectangle(image,(x1, y2), (x2, y2+50), (0, 255, 0), cv2.FILLED)
                    #cv2.putText(image, name.split('-')[2].upper(), (x1+6, y2+60), cv2.FONT_HERSHEY_COMPLEX, 1.2, (0,255,0), 3)
                    cv2.putText(image, name.split('_')[1].upper(), (x1+6, y2+60), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 3)
                    cv2.putText(image, str(get_Remarks()), ((width - text_width) // 2, text_height + 20), cv2.FONT_HERSHEY_COMPLEX, 2, fontColor, 3)
                    # mark_attendance(option, name)
                    mark_attendance(name.split('_')[0])

                else:
                    cv2.putText(image, "unknown".upper(), (x1+6, y2+60), cv2.FONT_HERSHEY_COMPLEX, 1.5, (255,255,255), 3)

        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

def gen(camera):
    image_path = os.path.join(settings.MEDIA_ROOT, "registered")
    images = []
    classNames = []
    if not os.path.exists(image_path):
        os.mkdir(image_path)
    myList = os.listdir(image_path)

    for cl in myList:
        curImg = cv2.imread(f'{image_path}/{cl}')
        images.append(curImg)
        classNames.append(os.path.splitext(cl)[0])

    findEncodings(images)

    encodeListKnown = findEncodings(images)
    print('Encoding Complete')
    while True:
        frame = camera.get_frame(encodeListKnown, classNames)
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')


import numpy as np
import torch
from torch import nn
from torch.utils import data

# 生成数据集
def synthetic_data(w, b, num_examples):
    """生成 y = Xw + b + 噪声。"""
    X = torch.normal(0, 1, (num_examples, len(w)))
    y = torch.matmul(X, w) + b
    y += torch.normal(0, 0.01, y.shape)
    return X, y.reshape((-1, 1))

if __name__ == '__main__':
    # 创建带噪声的训练数据集
    true_w = torch.tensor([2, -3.4])
    true_b = 4.2
    features, labels = synthetic_data(true_w, true_b, 1000)

    # 构造一个PyTorch数据迭代器
    batch_size = 10
    dataset = data.TensorDataset(*(features, labels))
    data_iter = data.DataLoader(dataset, batch_size, shuffle=True)

    # 定义模型
    net = nn.Sequential(nn.Linear(2, 1))
    # 初始化模型参数
    net[0].weight.data.normal_(0, 0.01)
    net[0].bias.data.fill_(0)
    # 定义损失函数
    loss = nn.MSELoss()  # 均方误差
    # 定义优化算法
    trainer = torch.optim.SGD(net.parameters(), lr=0.03)
    # 训练
    num_epochs = 3
    for epoch in range(num_epochs):
        for X, y in data_iter:
            l = loss(net(X), y)  # 调用 net(X) 生成预测并计算损失 l（正向传播）
            trainer.zero_grad()
            l.backward()  # 进行反向传播来计算梯度
            trainer.step()  # 调用优化器来更新模型参数
        l = loss(net(features), labels)
        print(f'epoch {epoch + 1}, loss {l:f}')

    w = net[0].weight.data
    print('w的估计误差：', true_w - w.reshape(true_w.shape))
    b = net[0].bias.data
    print('b的估计误差：', true_b - b)


## program that asks users for sandwich preferences and display total cost

import pyinputplus as pyip

# bread type
bread_type = pyip.inputMenu(
    ['wheat', 'white', 'sourdough'],
    prompt = 'Choose your bread type:\n',
    numbered = True)
print(f'You have selected {bread_type}.')

# protein type
protein_type = pyip.inputMenu(
    ['chicken', 'turkey', 'ham', 'tofu'],
    prompt = ' Choose your protein type.\n',
    numbered = True)
print(f'You have selected {protein_type}.')

# cheese type
want_cheese = pyip.inputYesNo(prompt = 'Do you want cheese? (y/n)')

if want_cheese == "yes":
    cheese_type = pyip.inputMenu(
        ['cheddar', 'swiss', 'mozzarella'],
        prompt = 'Choose your cheese type:\n',
        numbered = True)

    print(f'You have selected {cheese_type}.')
else:
    cheese_type = 'no_cheese'

# sauce type
sauce_type = pyip.inputMenu(
    ['mayo', 'mustard', 'lettuce', 'tomato'],
    prompt = ' Choose your sauce type.\n',
    numbered = True)
print(f'You have selected {sauce_type}.')

# quantity
qty = pyip.inputInt('How many sandwiches?', min=1)

# display order
sandwich = [bread_type, protein_type, cheese_type, sauce_type]
print(f'Repeat your sandwich order {sandwich} and quantity is {qty}.')

# display total cost
food_cost = {'wheat': 1, 'white': 1, 'chicken': 2, 'ham': 3, 'mozzarella': 1}

total_cost = 0
for i in range(len(sandwich)):
    food_cost.setdefault(sandwich[i], 0)
    total_cost += food_cost[sandwich[i]]

print(f'Total costs for your sandwiches is ${total_cost * qty}.')


# Read the introduction about garden path sentences and study a few of the examples on Wikipedia.
# Create a new Python file called garden.py.
# Find at least 2 garden path sentences from the web or create them.
# Store the sentences you have identified or created in a list called gardenpathSentences
# Add the following sentences to your list:
# ○ Mary gave the child a Band-Aid.
# ○ That Jill is never here hurts.
# ○ The cotton clothing is made of grows in Mississippi.
# Tokenise each sentence in the list and perform named entity recognition.
# Examine how spaCy has categorised each sentence.
# Using spacy.explain to print the meaning of entities.
# At the bottom of the file is writen a comment about two entities.
# For each entity answer the following questions:
# ○ What was the entity and its explanation that you looked up?
# ○ Did the entity make sense in terms of the word associated with it?

# Import spacy and load english language model
import spacy
nlp = spacy.load("en_core_web_sm")

# Add all sentences under gardenpathSentences variable.
gardenpathSentences = ["The complex houses married and single soldiers and their families.",
"The complex houses married and single soldiers and their families.",
"Mary gave the child a Band-Aid.",
"That Jill is never here hurts.",
"The cotton clothing is made of grows in Mississippi."]

# ANSI escape code for yelow colour.
yelow = "\033[93m"
# ANSI escape code for resetting the colour.
reset = "\033[0m"

# Iterate through each sentence in the list.
for sentence in gardenpathSentences:

# Print original sentence.
    print(f"{yelow}Sentence: {reset}","\n", sentence, )

# Apply NLP to the gardenpathSentences with spaCy.
    nlp_sentence = nlp(sentence)

# Tokenise each sentence.
    print(f"{yelow}Tokenise:{reset} ")
    for token in nlp_sentence:
        print(token.orth_, "--", token.tag_,"--", spacy.explain(token.tag_))

# Find entities for each sentence and explain the entity.
    print(f"{yelow}Entities and explanation:{reset} ")
    for entity in nlp_sentence.ents:
        print(entity, "/", entity.label_,"/", entity.label,"/", spacy.explain(entity.label_))

# Create a blank space after each iteration.
    print("\n")

# Entities looked up:
# ○ What was the entity and its explanation that you looked up?
# ○ Did the entity make sense in terms of the word associated with it?

# 1."GPE" (Geo-Political Entity) - Represents countries, cities, and states.
#   In the sentence "The cotton clothing is made of grows in Mississippi.",
#   "Mississippi" is correctly categorised as a GPE, indicating the state name.
#   It makes sense as Mississippi is a state in the United States.

# 2."PERSON" -Represent person name, people.
#   In the sentence "That Jill is never here hurts."
#   "Jill" is correctly categorised as a PERSON, indicating a person name.
#   It makes sense as Jill is a common name for a person.


import csv_reader
from datetime import datetime, timedelta
import time

class Bus:
    def __init__(self, route_id, direction, trip_id):
        bus_id = f"bus-{route_id}-{direction}-{trip_id}"
        self.bus_id = bus_id
        self.route_id = route_id
        self.direction = direction
        self.trip_id = trip_id
        self.location = None

    def deploy_to_trip(self, stops, trips):
        # Find the index of the first stop for this trip
        first_stop_index = -1
        for i, stop in enumerate(stops):
            if stop == self.trip_id:
                first_stop_index = i
                break

        # If the trip has already started, set the bus's location to the current stop
        if simulation_time.strftime('%H:%M') in trips[f'trip_{self.trip_id}']:
            self.location = stops[first_stop_index]

        # Otherwise, set the bus's location to the first stop
        else:
            self.location = stops[first_stop_index]
            print(f"A new {self.bus_id} has been deployed for trip {self.trip_id} on {self.route_id} - {direction_id} at {simulation_time.strftime('%H:%M')}")

    def move_to_stop(self, stop_name):
        print(f"{self.bus_id} is now at {stop_name} for trip {self.trip_id} on {self.route_id} - {direction_id} at {simulation_time.strftime('%H:%M')}")
        self.location = stop_name

    def complete_trip(self):
        print(f"Trip {self.trip_id} on {self.route_id} - {direction_id} has been completed by {self.bus_id} at {simulation_time.strftime('%H:%M')}")

# Set the initial simulation time
simulation_time = datetime.strptime('5:15', '%H:%M')

# Loop through each minute in the simulation time
while True:
    # Print the current simulation time
    print(f"Simulation time: {simulation_time.strftime('%H:%M')}")

    # Loop through each route
    for route_id, route_data in csv_reader.routes.items():
        # Loop through each direction for this route
        for direction_id, direction_data in route_data.items():
            # Check if the current simulation time matches any of the trip times for this direction
            for trip_num, trip_times in direction_data['trips'].items():
                if simulation_time in trip_times:
                    # Get the index of the stop corresponding to the current trip and simulation time
                    stop_index = trip_times.index(simulation_time)
                    stop_name = direction_data['stops'][stop_index]

                    # Check if a bus is already deployed for this trip
                    bus_deployed = False
                    for bus in direction_data.get('buses', []):
                        if bus.trip_id == trip_num.split('_')[1]:
                            bus_deployed = True
                            current_bus = bus
                            break

                    # If a bus is already deployed, move it to the current stop
                    if bus_deployed:
                        current_bus.move_to_stop(stop_name)

                        # Check if the bus has reached the final stop
                        if stop_index == len(direction_data['stops']) - 1:
                            current_bus.complete_trip()
                            direction_data['buses'].remove(current_bus)

                    # If no bus is deployed, create a new bus and deploy it to the trip
                    else:
                        # Generate a new unique bus id
                        new_bus = Bus(route_id=route_id,
                                    direction=direction_id,
                                    trip_id=trip_num.split('_')[1])
                        new_bus.deploy_to_trip(stops=direction_data['stops'], trips=direction_data['trips'])
                        direction_data.setdefault('buses', []).append(new_bus)

    # Pause the execution of the code for 1 second
    time.sleep(1)

    # Increment the simulation time by 1 minute
    simulation_time += timedelta(minutes=1)


# Даны две строки. Эти строки отличаются друг от друга только одним символом.
# Т.е. вторая строка получена добавлением случайного символа в случайную
# позицию первой строки. Найти этот символ, вывести его и его индекс в строке.

someString_1 = input()
someString_2 = input()

length = len(someString_1)
cnt = 0
if len(someString_2) - len(someString_1) == 1:
    while cnt < length:
        if someString_1[cnt] != someString_2[cnt]:
            break
        cnt += 1
    print('Added symbol is', someString_2[cnt])
    print('The index of the added symbol is', cnt)
else:
    print('Strings do not satisfy the condition of the task')

# Дана строка из набора цифр, и дано число от 0 до 18 включительно.
# Надо определить, присутствуют ли в строке такие 2 цифры, сумма которых
# равна введённому числу. Если есть, то вывести эти две цифры и их индексы.
someStr = input()
someNum = int(input())

length = len(someStr)
cnt = 0
cnt1 = 0
result = False
while cnt < length:
    newStr = someStr[0:cnt] + someStr[cnt + 1:length]
    # someStr_n = someStr[cnt]
    while cnt1 < length - 1:
        # newStr_n = newStr[cnt1]
        if int(someStr[cnt]) + int(newStr[cnt1]) == someNum:
            print(f'The digits are {someStr[cnt]} and {newStr[cnt1]}')
            print(f'The indexes of this digits are {cnt} and {cnt1 + 1}')
            result = True
            break
        else:
            cnt1 += 1
    if result:
        break
    cnt1 = 0
    cnt += 1
if not result:
    print('There are no such digits')