#!/usr/bin/env python3
# Author:   Michael E. Rose <michael.ernst.rose@gmail.com>
"""Computes centralities for all nodes of a all networks."""

import time
from pathlib import Path

import networkx as nx
import numpy as np
import pandas as pd

COAUTHOR_FOLDER = Path("./206_coauthor_networks")
INFORMAL_FOLDER = Path("./209_informal_networks")
TARGET_FOLDER = Path("./220_centralities")

ATTENUATIONS = list(map(lambda x: x/100.0, list(range(5, 96, 10))))

def compute_centralities(G, H, degree=True, eigvec=True, weight=None):
    """Return DataFrame with node-wise network measures."""
    start = time.time()
    # Neighborhood centrality
    df = discounted_neighborhood(G)
    print("... computing other centralities")
    label = ""
    if weight:
        label = "_w"
    # Other centralities
    if degree:
        df["degree" + label] = pd.Series(dict(nx.degree(H, weight=weight)))
    if eigvec:
        df["eigenvector" + label] = pd.Series(
            nx.eigenvector_centrality_numpy(G, weight=weight))
    diff = time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
    print("... Time for computation:", diff)
    return df

def discounted_neighborhood(net):
    """Compute discounted neighborhood centrality."""
    print("... computing neighborhood centrality")
    nodes = sorted(net.nodes())
    M_sum = G = M = nx.adjacency_matrix(net, nodelist=nodes, weight=None).todense()
    I = np.identity(len(G))
    # First iteration
    idx = 1
    vec = np.array(M.sum(axis=0))[0]
    centr = {alpha: (alpha**idx)*vec for alpha in ATTENUATIONS}
    # All other iterations
    while np.any(M):
        idx += 1
        W = np.matmul(M, G)
        Z = W.clip(max=1) - (I + M_sum)
        M = Z.clip(min=0)
        vec = np.array(M.sum(axis=0))[0]
        centr = {alpha: np.add(old, (alpha**idx) * vec) for
                 alpha, old in centr.items()}
        M_sum = np.add(M_sum, M)
    # Create DataFrame from dictionary
    df = pd.DataFrame.from_dict(centr)
    df.index = nodes
    df.columns = [f"neighborhood_{int(alpha*100)}" for alpha in df.columns]
    return df

def giant(H):
    """Return giant component of a network."""
    try:
        components = sorted(nx.connected_components(H), key=len, reverse=True)
    except nx.NetworkXNotImplemented:  # Directed network
        components = sorted(nx.weakly_connected_components(H),
                            key=len, reverse=True)
    return H.subgraph(components[0])

def main():
    files = INFORMAL_FOLDER.glob("*.gexf")
    files.extend(COAUTHOR_FOLDER.glob("*.gexf"))

    print(">>> Now working on:")
    for file in sorted(files):
        # Read in
        year = file.name[:-5]
        if file.parts[-2] == "206_coauthor_networks":
            net_type = 'coauth'
        else:
            net_type = 'informal'
        ident = "_".join([net_type, year])
        print(f"... {ident} ...")
        H = nx.read_gexf(file)
        G = giant(H)

        # Centralities (with predefined attenuation factors)
        centr = compute_centralities(G, H, weight=None).sort_index()
        centr.to_csv((TARGET_FOLDER/ident).with_suffix(".csv"), index_label="node")

if __name__ == '__main__':
    main()


import math

x1 = float(input("x1 "))
h = float(input("крок "))

eps = float(input("точність "))

def opt(w, a, b, c, h):
    print(w, a, b, c)
    if w < a:
        c = b
        while a > w:
            a -= h
    elif w > c:
        a = b
        while c < w:
            c += h
    elif w < b:
        c = b
    elif w > b:
        a = b
    else:
        w = b
    return a, w, c

def fun(a):
    return a * a + 4 * a * math.sin(a) + math.cos(a)

def find_min(h, x1):
    k = 0
    x2 = x1 + h
    f1 = fun(x1)
    f2 = fun(x2)
    if f1 > f2:
        x3 = x1 + 2 * h
        _x = x2
    else:
        x3 = x1 - h
        _x = x1
    f3 = fun(x3)

    fmin = min(f1, f2, f3)
    f_x = max(f1, f2, f3)

    x1, x2, x3 = sorted([x1, x2, x3])

    while abs((fmin - f_x) / f_x) > eps:
        x1, x2, x3 = opt(_x, x1, x2, x3, h)
        f1 = fun(x1)
        f2 = fun(x2)
        f3 = fun(x3)

        tmp = sorted([(f1, x1), (f2, x2), (f3, x3)])
        fmin, xmin = tmp[0]

        a1 = (f2 - f1) / (x2 - x1)
        a2 = (1 / (x3 - x2)) * (((f3 - f1) / (x3 - x1)) - ((f2 - f1) / (x2 - x1)))

        _x = (x2 + x1) / 2 - a1 / (2 * a2)
        f_x = fun(_x)

    return f1, f2, f3, fmin, _x

print(find_min(h, x1))


from consumible import views
from django.urls import path

urlpatterns = [
    path('lista_consumible/', views.ConsumibleListView.as_view() , name="Listado-Consumible"),
    path('detalle_consumible/<int:pk>/', views.ConsumibleDetailView.as_view(), name="Detalle-Consumible"),
    path('crear_consumible/', views.CreateConsumibleView.as_view(), name="Crear-Consumible"),
    path('editar_consumible/<int:pk>/', views.ConsumibleEditView.as_view(), name="Editar-Consumible"),
    path('eliminar_consumible/<int:pk>/', views.DeleteConsumibleView.as_view(), name="Eliminar-Consumible"),
]


# ---
# jupyter:
#   jupytext:
#     formats: ipynb,py
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.3.3
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# %reload_ext autoreload
# %autoreload 2
# %matplotlib inline

# +
import torch
from torchvision import models
import random
import os
import numpy as np
import pandas as pd
from fastai.vision import ImageList, transform
from functools import partial

from hw_grapheme.densenet import Dnet_1ch

from hw_grapheme.dl_utils.radam import Over9000
from hw_grapheme.loss_func import Loss_combine
from hw_grapheme.callbacks import Metric_idx, Metric_tot, MixUpCallback

from hw_grapheme.dl_utils.csvlogger import CSVLogger
from fastai.basic_train import Learner

from torch import nn
from fastai.callbacks import SaveModelCallback

# import fastai
# import warnings

# import matplotlib.pyplot as plt
# import torch.nn.functional as F

# from sklearn.model_selection import KFold
# from fastai.callbacks import SaveModelCallback, TrackerCallback
# from fastai.callback import Callback
# from torch import nn, Tensor

# from hw_grapheme.dl_utils.radam import RAdam, Over9000
# from hw_grapheme.dl_utils.mish_activation import Mish, to_Mish

# warnings.filterwarnings("ignore")

# fastai.__version__

# from functools import partial
#

# +
sz = 128
bs = 128
nfolds = 4 #keep the same split as the initial dataset
fold = 1
SEED = 2019
TRAIN = '../data/processed_data/train_images/'
LABELS = '../data/train.csv'

def seed_everything(seed):
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = True

seed_everything(SEED)
# -

df = pd.read_csv(LABELS)
nunique = list(df.nunique())[1:-1]
print(nunique)
df.head()

range(fold*len(df)//nfolds,(fold+1)*len(df)//nfolds)

# +
stats = ([0.0692], [0.2051])
data = (ImageList.from_df(df, path='.', folder=TRAIN, suffix='.png',
        cols='image_id', convert_mode='L')
        .split_by_idx(range(fold*len(df)//nfolds,(fold+1)*len(df)//nfolds))
        .label_from_df(cols=['grapheme_root','vowel_diacritic','consonant_diacritic'])
        .transform(transform.get_transforms(do_flip=False,max_warp=0.1), size=sz, padding_mode='zeros')
        .databunch(bs=bs)).normalize(stats)

# data.show_batch()
# -

data

# +
Metric_grapheme = partial(Metric_idx,0)
Metric_vowel = partial(Metric_idx,1)
Metric_consonant = partial(Metric_idx,2)

arch = models.densenet121
model = Dnet_1ch(arch, nunique)

learn = Learner(data, model, loss_func=Loss_combine(), opt_func=Over9000,
        metrics=[Metric_grapheme(),Metric_vowel(),Metric_consonant(),Metric_tot()])

learn.model = nn.DataParallel(learn.model)

logger = CSVLogger(learn,f'log{fold}')
learn.clip_grad = 1.0
learn.split([model.head1])
learn.unfreeze()
# -

learn.summary()

learn.fit_one_cycle(100, max_lr=slice(0.2e-2,1e-2), wd=[1e-3,0.1e-1], pct_start=0.0,
    div_factor=100, callbacks = [logger, SaveModelCallback(learn,monitor='metric_tot',
    mode='max',name=f'model_{fold}'),MixUpCallback(learn)])
#metrics: Metric_grapheme, Metric_vowel, Metric_consonant, Metric_tot (competition metric)


from __future__ import print_function
import numpy as np
import random

from rnn_layers import *

import tensorflow as tf
import time, os, json, sys
import numpy as np
import matplotlib.pyplot as plt

#import pandas as pd

import tensorflow.python.platform
from tensorflow.contrib import rnn
from tensorflow.contrib import legacy_seq2seq

import argparse

from six.moves import cPickle
from six import text_type

# this module is from the utils.py file of this folder
# it handles loading texts to digits (aka. tokens) which are recognizable for the model
from utils import TextLoader

from coco_utils import *
from captioning import *

# this module is from the char_rnn.py file of this folder
# the task is implementing the CharRNN inside the class definition from this file
from char_rnn import Model

from optparse import OptionParser

parser = OptionParser()
parser.add_option('-g', '--gpu_num', dest='gpu_num', type='string', default='0')

def part_1():
    # implement rnn_step_forward
    # errors should be less than 1e-8
    x, prev_h, Wx, Wh, b, expected_next_h = getdata_rnn_step_forward()

    next_h, _ = rnn_step_forward(x, prev_h, Wx, Wh, b)

    print('next_h error: ', rel_error(expected_next_h, next_h))

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

    # implement rnn_step_backward
    # errors should be less than 1e-8
    np.random.seed(2177)

    x, h, Wx, Wh, b, expected_next_h = getdata_rnn_step_forward()
    out, cache = rnn_step_forward(x, h, Wx, Wh, b)
    dnext_h = np.random.randn(*out.shape)
    dx_num, dprev_h_num, dWx_num, dWh_num, db_num = getdata_rnn_step_backward(x,h,Wx,Wh,b,dnext_h)

    dx, dprev_h, dWx, dWh, db = rnn_step_backward(dnext_h, cache)

    print('dx error     : ', rel_error(dx_num, dx))
    print('dprev_h error: ', rel_error(dprev_h_num, dprev_h))
    print('dWx error    : ', rel_error(dWx_num, dWx))
    print('dWh error    : ', rel_error(dWh_num, dWh))
    print('db error     : ', rel_error(db_num, db))

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

    # implement rnn_forward
    # errors should be less than 1e-7
    x,h0,Wx,Wh,b, expected_h = getdata_rnn_forward()

    h, _ = rnn_forward(x, h0, Wx, Wh, b)

    print('h error: ', rel_error(expected_h, h))

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

    # implement rnn_forward
    # errors should be less than 1e-7
    np.random.seed(2177)

    x,h0,Wx,Wh,b, expected_h = getdata_rnn_forward()
    out, cache = rnn_forward(x, h0, Wx, Wh, b)
    dout = np.random.randn(*out.shape)
    dx_num, dh0_num, dWx_num, dWh_num, db_num = getdata_rnn_backward(x,h0,Wx,Wh,b,dout)

    dx, dh0, dWx, dWh, db = rnn_backward(dout, cache)

    print('dx error: ', rel_error(dx_num, dx))
    print('dh0 error: ', rel_error(dh0_num, dh0))
    print('dWx error: ', rel_error(dWx_num, dWx))
    print('dWh error: ', rel_error(dWh_num, dWh))
    print('db error: ', rel_error(db_num, db))

def part_2(gpu_num):

    model_path='./models_captioning'
    data_path ='./coco/coco_captioning'

    data = load_coco_data(base_dir=data_path)
    if len(data)==8 :
        print('COCO data load complete')

    for k, v in data.items():
        if type(v) == np.ndarray:
            print(k, type(v), v.shape, v.dtype)
        else:
            print(k, type(v), len(v))

#train_data = load_coco_data(base_dir=data_path, max_train=512*100)
    train_data = data

    captions = train_data['train_captions']
    img_idx  = train_data['train_image_idxs']
    img_features = train_data['features'][img_idx]
    word_to_idx = train_data['word_to_idx']
    idx_to_word = train_data['idx_to_word']

    n_words = len(word_to_idx)
    maxlen = train_data['train_captions'].shape[1]
    input_dimension = train_data['features'].shape[1]

    print(n_words)
    print(maxlen)
    print(img_features.shape, captions.shape)

    vcaptions = train_data['val_captions']
    vimg_idx  = train_data['val_image_idxs']
    vimg_features = train_data['features'][vimg_idx]
    print(vimg_features.shape, vcaptions.shape)

    def train(img_features, captions):
        #---------------------------------------------------------
        # You must show maxlen, n_words, caption.shap
        #---------------------------------------------------------
        print(maxlen, n_words, captions.shape)

        #################################################
        # TODO: Implement caption training
        # - save your trained model in model_path
        # - must print about 10 loss changes !!
        #################################################
        img_feature_dim = img_features.shape[1]
        batch_size = 512
        n_epochs = 100

        conf = tf.ConfigProto()
        conf.gpu_options.per_process_gpu_memory_fraction = 0.2
        os.environ['CUDA_VISIBLE_DEVICES'] = gpu_num

        def calc_caption_length(caption):
            for i, word_idx in enumerate(caption):
                if word_idx == 0:
                    return min(len(caption), i+2)
            return len(caption)
        caption_lens = np.array([calc_caption_length(caption) for caption in captions])
        vcaption_lens = np.array([calc_caption_length(caption) for caption in vcaptions])

        known_caption_idxs = np.all(captions != 3, axis=1)

        known_captions = captions[known_caption_idxs]
        known_caption_lens = caption_lens[known_caption_idxs]
        known_img_features = img_features[known_caption_idxs]

        tf.reset_default_graph()

        if gpu_num == '0':
            captioning = Captioning(img_feature_dim, maxlen, n_words, 386, 3)
        elif gpu_num == '1':
            captioning = Captioning(img_feature_dim, maxlen, n_words, 848, 3)
        elif gpu_num == '2':
            captioning = Captioning(img_feature_dim, maxlen, n_words, 496, 3)
        elif gpu_num == '3':
            captioning = Captioning(img_feature_dim, maxlen, n_words, 612, 3)
        input_sequences, input_sequence_lens, input_img_features, \
            loss, optimize, drop_out_keep_rate, teacher_force = captioning.build_model()
        predict_indices = captioning.predict()

        # Saver
        saved_model_path = 'saved_model_{}/ass3_show_and_tell.ckpt'.format(gpu_num)
        epoch_save_path = 'saved_model/ass3_epoch.txt'
        min_valid_loss = 9999.99
        max_BLEU = -1.0
        saver = tf.train.Saver()
        with tf.Session(config=conf) as sess:
            sess.run(tf.global_variables_initializer())

            def generate_minibatch():
                permutation = np.random.permutation(len(known_captions))
                return known_captions[permutation][:batch_size], \
                    known_caption_lens[permutation][:batch_size], \
                    known_img_features[permutation][:batch_size]

            def generate_minibatch_valid(data_size):
                permutation = np.random.permutation(data_size)
                return vcaptions[permutation][:batch_size], \
                    vcaption_lens[permutation][:batch_size], \
                    vimg_features[permutation][:batch_size]

            for epoch in range(n_epochs):
                start_time = time.time()
                data_size = captions.shape[0]
                steps = data_size // batch_size

                # train
                loss_sum = 0.0
                for step in range(steps):
                    input_seqs, input_seq_lens, input_imgs = generate_minibatch()
                    feed_dict = {
                        input_sequences: input_seqs,
                        input_sequence_lens: input_seq_lens,
                        input_img_features: input_imgs,
                        drop_out_keep_rate: 0.1,
                    }
                    train_loss, _, train_force = sess.run([loss, optimize, teacher_force], feed_dict=feed_dict)
                    loss_sum += train_loss

                # validation
                val_loss_sum = 0.0
                val_data_size = vcaptions.shape[0]
#                val_steps = val_data_size // batch_size
#                for step in range(val_steps):
#                    input_seqs, input_seq_lens, input_imgs = generate_minibatch_valid(val_data_size)
#                    feed_dict = {
#                        input_sequences: input_seqs,
#                        input_sequence_lens: input_seq_lens,
#                        input_img_features: input_imgs,
#                    }
#                    val_loss, val_force = sess.run([loss, teacher_force], feed_dict=feed_dict)
#                    val_loss_sum += val_loss

                # test sentence from validation
                pick_idx = random.randrange(val_data_size)
                feed_dict = {
                    input_img_features: np.expand_dims(img_features[pick_idx], axis=0),
                }

                pred_indices = sess.run([predict_indices], feed_dict=feed_dict)
                print([idx_to_word[idx] for idx in pred_indices[0][0]])

                # BLEU score
                def image_captioning(features) :
                    pr_captions = np.zeros((features.shape[0],maxlen),int)
                    feed_dict = {
                        input_img_features: features,
                    }
                    predicts = sess.run([predict_indices], feed_dict=feed_dict)
                    pr_captions = np.array(predicts[0])
                    return pr_captions

                def evaluate_model(data, split):
                    BLEUscores = {}

                    minibatch = sample_coco_minibatch(data, split=split, batch_size="All")
                    gt_captions, features, urls = minibatch
                    gt_captions = decode_captions(gt_captions, data['idx_to_word'])

                    pr_captions = image_captioning(features)
                    pr_captions = decode_captions(pr_captions, data['idx_to_word'])

                    total_score = 0.0

                    for gt_caption, pr_caption, url in zip(gt_captions, pr_captions, urls):
                        total_score += BLEU_score(gt_caption, pr_caption)

                    BLEUscores[split] = total_score / len(pr_captions)

                    return BLEUscores[split]

                cur_BLEU = evaluate_model(train_data, 'val')

                print('epoch {} : '.format(epoch) + ('train loss %.4f, ' % (loss_sum / steps)) + \
                        ('BLEU score %.4f' % cur_BLEU))

                if cur_BLEU > max_BLEU:
                    max_BLEU = cur_BLEU
                    saver.save(sess, saved_model_path)
                    print('model saved!!')

                if (epoch > 4) and (max_BLEU * 0.9) > cur_BLEU:
                    print('early stop!!')
                    break

        #print("Current Cost: ", loss_value, "\t Epoch {}/{}".format(epoch, n_epochs))

        #################################################
        #                END OF YOUR CODE               #
        #################################################

    train(img_features, captions)

def part_3(gpu_num):
    # for TensorFlow vram efficiency: if this is not specified, the model hogs all the VRAM even if it's not necessary
    # bad & greedy TF! but it has a reason for this design choice FWIW, try googling it if interested
    conf = tf.ConfigProto()
    conf.gpu_options.allow_growth = True
    os.environ['CUDA_VISIBLE_DEVICES'] = gpu_num

    # argparsing
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    # Data and model checkpoints directories
    parser.add_argument('--data_dir', type=str, default='data/tinyshakespeare',
                                help='data directory containing input.txt with training examples')
    parser.add_argument('--save_dir', type=str, default='models_char_rnn',
                                help='directory to store checkpointed models')
    parser.add_argument('--save_every', type=int, default=1000,
                                help='Save frequency. Number of passes between checkpoints of the model.')
    parser.add_argument('--init_from', type=str, default=None,
                                help="""continue training from saved model at this path (usually "save").
                                     Path must contain files saved by previous training process:
                                     'config.pkl'        : configuration;
                                     'chars_vocab.pkl'   : vocabulary definitions;
                                     'checkpoint'        : paths to model file(s) (created by tf).
                                     Note: this file contains absolute paths, be careful when moving files around;
                                     'model.ckpt-*'      : file(s) with model definition (created by tf)
                                     Model params must be the same between multiple runs (model, rnn_size, num_layers and seq_length).
                                     """)
    # Model params
    parser.add_argument('--model', type=str, default='lstm',
                                help='lstm, rnn, gru, or nas')
    parser.add_argument('--rnn_size', type=int, default=128,
                                help='size of RNN hidden state')
    parser.add_argument('--num_layers', type=int, default=3,
                                help='number of layers in the RNN')
    # Optimization
    parser.add_argument('--seq_length', type=int, default=500,
                                help='RNN sequence length. Number of timesteps to unroll for.')
    parser.add_argument('--batch_size', type=int, default=128,
                                help="""minibatch size. Number of sequences propagated through the network in parallel.
                                        Pick batch-sizes to fully leverage the GPU (e.g. until the memory is filled up)
                                        commonly in the range 10-500.""")
    parser.add_argument('--num_epochs', type=int, default=50,
                                help='number of epochs. Number of full passes through the training examples.')
    parser.add_argument('--grad_clip', type=float, default=20.,
                                help='clip gradients at this value')
    parser.add_argument('--learning_rate', type=float, default=0.001,
                                help='learning rate')
    parser.add_argument('--decay_rate', type=float, default=0.97,
                                help='decay rate for rmsprop')
    parser.add_argument('--output_keep_prob', type=float, default=0.1,
                                help='probability of keeping weights in the hidden layer')
    parser.add_argument('--input_keep_prob', type=float, default=0.1,
                                help='probability of keeping weights in the input layer')

    # needed for argparsing within jupyter notebook
    # https://stackoverflow.com/questions/30656777/how-to-call-module-written-with-argparse-in-ipython-notebook
    sys.argv = ['-f']
    args = parser.parse_args()

    if gpu_num == '0':
        args.save_dir = 'models_char_rnn_{}'.format(gpu_num)
        args.init_from = args.save_dir
        args.rnn_size = 749
        args.num_layers = 1
        args.decay_rate = 0.5
        args.output_keep_prob = 0.1
        args.input_keep_prob = 0.1
        args.grad_clip = 5.0
        args.num_epochs = 500
    elif gpu_num == '1':
        args.save_dir = 'models_char_rnn_{}'.format(gpu_num)
        args.init_from = args.save_dir
        args.rnn_size = 486
        args.num_layers = 2
        args.decay_rate = 0.1
        args.output_keep_prob = 0.1
        args.input_keep_prob = 0.1
        args.grad_clip = 20.0
        args.num_epochs = 500
    elif gpu_num == '2':
        args.save_dir = 'models_char_rnn_{}'.format(gpu_num)
        args.init_from = args.save_dir
        args.rnn_size = 486
        args.num_layers = 2
        args.decay_rate = 0.1
        args.output_keep_prob = 0.1
        args.input_keep_prob = 0.1
        args.grad_clip = 10.0
        args.num_epochs = 500
    elif gpu_num == '3':
        args.save_dir = 'models_char_rnn_{}'.format(gpu_num)
        args.init_from = args.save_dir
        args.rnn_size = 749
        args.num_layers = 1
        args.decay_rate = 0.1
        args.output_keep_prob = 0.1
        args.input_keep_prob = 0.1
        args.grad_clip = 20.0
        args.num_epochs = 500

    # protip: always check the data and poke around the data yourself
    # you will get a lot of insights by looking at the data
    data_loader = TextLoader(args.data_dir, args.batch_size, args.seq_length)
    data_loader.reset_batch_pointer()

    # training loop definition
    def train(args):
        data_loader = TextLoader(args.data_dir, args.batch_size, args.seq_length)
        args.vocab_size = data_loader.vocab_size
        print("vocabulary size: " + str(args.vocab_size))

        # check compatibility if training is continued from previously saved model
        init_from = args.init_from
        if not os.path.isdir(args.init_from):
            init_from = None

        if init_from is not None:
            # check if all necessary files exist
            assert os.path.isdir(init_from)," %s must be a a path" % init_from
            assert os.path.isfile(os.path.join(init_from,"config.pkl")),"config.pkl file does not exist in path %s"%init_from
            assert os.path.isfile(os.path.join(init_from,"chars_vocab.pkl")),"chars_vocab.pkl.pkl file does not exist in path %s" % init_from
            ckpt = tf.train.latest_checkpoint(init_from)
            assert ckpt, "No checkpoint found"

            # open old config and check if models are compatible
            with open(os.path.join(init_from, 'config.pkl'), 'rb') as f:
                saved_model_args = cPickle.load(f)
            need_be_same = ["model", "rnn_size", "num_layers", "seq_length"]
            for checkme in need_be_same:
                assert vars(saved_model_args)[checkme]==vars(args)[checkme],"Command line argument and saved model disagree on '%s' "%checkme

            # open saved vocab/dict and check if vocabs/dicts are compatible
            with open(os.path.join(init_from, 'chars_vocab.pkl'), 'rb') as f:
                saved_chars, saved_vocab = cPickle.load(f)
            assert saved_chars==data_loader.chars, "Data and loaded model disagree on character set!"
            assert saved_vocab==data_loader.vocab, "Data and loaded model disagree on dictionary mappings!"

        if not os.path.isdir(args.save_dir):
            os.makedirs(args.save_dir)
        with open(os.path.join(args.save_dir, 'config.pkl'), 'wb') as f:
            cPickle.dump(args, f)
        with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'wb') as f:
            cPickle.dump((data_loader.chars, data_loader.vocab), f)

        print("building the model... may take some time...")
        ##################### This line builds the CharRNN model defined in char_rnn.py #####################
        tf.reset_default_graph()
        model = Model(args)
        print("model built! starting training...")

        with tf.Session(config=conf) as sess:
            sess.run(tf.global_variables_initializer())
            saver = tf.train.Saver(tf.global_variables(), max_to_keep=1)
            # restore model
            if init_from is not None:
                saver.restore(sess, ckpt)
            for e in range(args.num_epochs):
                sess.run(tf.assign(model.lr, args.learning_rate * (args.decay_rate ** (e/args.num_epochs))))
                data_loader.reset_batch_pointer()
                state = sess.run(model.initial_state)

                for b in range(int(data_loader.num_batches)):
                    start = time.time()
                    x, y = data_loader.next_batch()
                    feed = {model.input_data: x, model.targets: y}
                    for i, (c, h) in enumerate(model.initial_state):
                        feed[c] = state[i].c
                        feed[h] = state[i].h

                    train_loss, state, _ = sess.run([model.cost, model.final_state, model.train_op], feed)

                    end = time.time()

                    # print training log every 100 steps
                    if ((e * data_loader.num_batches + b) % 100 == 0):
                        print("{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}"
                                    .format(e * data_loader.num_batches + b,
                                    args.num_epochs * data_loader.num_batches,
                                    e, train_loss, end - start))
                    if (e * data_loader.num_batches + b) % args.save_every == 0\
                                    or (e == args.num_epochs-1 and b == data_loader.num_batches-1):
                        # save for the last result
                        checkpoint_path = os.path.join(args.save_dir, 'model.ckpt')
                        saver.save(sess, checkpoint_path, global_step=e * data_loader.num_batches + b)
                        print("model saved to {}".format(checkpoint_path))

    for i in range(1):
        train(args)
        print('==============================={}==================================='.format(i))
        part_3_sample(gpu_num)
        print('====================================================================')

def part_3_sample(gpu_num):
    conf = tf.ConfigProto()
    conf.gpu_options.allow_growth = True
    os.environ['CUDA_VISIBLE_DEVICES'] = gpu_num

    def sample_eval(args):
        with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f:
            saved_args = cPickle.load(f)
        with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f:
            chars, vocab = cPickle.load(f)
        #Use most frequent char if no prime is given
        if args.prime == '':
            args.prime = chars[0]
        tf.reset_default_graph()
        model = Model(saved_args, training=False)

        with tf.Session(config=conf) as sess:
            tf.global_variables_initializer().run()
            saver = tf.train.Saver(tf.global_variables())
            ckpt = tf.train.get_checkpoint_state(args.save_dir)
            if ckpt and ckpt.model_checkpoint_path:
                saver.restore(sess, ckpt.model_checkpoint_path)
                print(str(model.sample(sess, chars, vocab, args.n, args.prime)),'utf-8')

    parser_sample = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser_sample.add_argument('--save_dir', type=str, default='models_char_rnn',
            help='model directory to store checkpointed models')
    parser_sample.add_argument('-n', type=int, default=500,
            help='number of characters to sample')
    parser_sample.add_argument('--prime', type=text_type, default=u'',
            help='prime text')
    sys.argv = ['-f']

    args_sample = parser_sample.parse_args()
    args_sample.save_dir = 'models_char_rnn_{}'.format(gpu_num)

    sample_eval(args_sample)

def main():
    options, args = parser.parse_args()
    gpu_num = options.gpu_num

    part_3(gpu_num)
#part_3_sample(gpu_num)

if __name__ == '__main__':
    main()


import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import fsolve

# setting up the problem

# defining Boundary conditions
y0 = 0.0  # initial position
yL = 0.0  # final position

# defining time interval
x0 = 0.0
xE = 1.0
xeval = np.linspace(x0, xE, 100)

# defining function for system of ODEs
def derivs(x, s):
    """
    Function for the system of ODEs
    dy/dt = v
    dv/dt = y^2 + cos(2*pi*x) - sin^4(pi*x)

    Parameters
    ----------
    x : position (float)
    s : state vector  (float)
        s[0] = y(x)
        s[1] = dy/dx == v(x)
    """
    y = s[0]
    v = s[1]

    dvdx = y**2 + np.cos(2*np.pi*x) - (np.sin(np.pi*x))**4
    return [v, dvdx]

# getting accurate dy/dx using root finding approach

# defining objective function as a function of guess derivative

def objective(v):
    sol = solve_ivp(derivs, [x0, xE], np.array(
        [y0, v], dtype='object'), t_eval=xeval)
    end_point = sol.y[0][-1]
    return end_point - yL

vRoot = fsolve(objective, -1)
print("Optimal dy/dx: %2.3f" % vRoot)

# obtaining solution for vRoot
sol = solve_ivp(derivs, [x0, xE], np.array(
    [y0, vRoot], dtype='object'), t_eval=xeval)

# plotting the solution
plt.figure(figsize=(10, 5.5), dpi=100)
plt.plot(xeval, sol.y[0], color='blue', label="y(x): $y\'(x=0)$=%2.3f" % vRoot)
# plotting the boundary conditions
plt.plot([x0, xE], [y0, y0], 'ro', ms=10, label='Boundary Conditions')
plt.grid(alpha=0.2)
plt.legend(loc=1)
plt.xlabel('x', fontsize=16)
plt.ylabel('y', fontsize=16)
plt.title(
    'Solution for $\\dfrac{d^2y}{dt^2} = y^2 +\cos(2\pi x) - \sin^4(\pi x)$\n')
plt.savefig('Assignment3.jpg', bbox_inches='tight', dpi=300)
plt.show()


import pandas as pd
from .get_schedulers import get_schedulers
from .get_queues import get_queues

def __jobs_to_df(jobs):

    scheduled_jobs = jobs['scheduler']
    df_scheduled = pd.DataFrame(
        zip(scheduled_jobs, ['scheduled']*len(scheduled_jobs)),
        columns=['job_id', 'status'])

    queued_jobs = jobs['queue']
    df_queued = pd.DataFrame(
        zip(queued_jobs, ['queued']*len(queued_jobs)),
        columns=['job_id', 'status'])

    df = pd.concat([df_scheduled, df_queued])
    return df

def get_jobs():

    jobs = {
        'scheduler': [],
        'queue': [],
    }

    schedulers = get_schedulers()
    for _, scheduler in schedulers.items():
        jobs['scheduler'] += scheduler.get_jobs()

    queues = get_queues()
    for _, queue in queues.items():
        jobs['queue'] += queue.get_jobs()

    return __jobs_to_df(jobs)


# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

def solve(N, K, A):
    if K > 50:
        print(" ".join([str(N) for i in range(N)]))
        sys.exit()

    for i in range(K):
        A_new = [0 for i in range(N)]
        imos_table = [0 for i in range(N)]

        for j in range(N): # ここで一度状態の差分についてをimos_tableに保存
            left = max(0, j - A[j])
            right = j + A[j] + 1
            imos_table[left] += 1
            if right >= N:
                pass
            else:
                imos_table[right] -= 1

        # tmp を使って前から順に状態を計算していく
        tmp = 0
        for j in range(N):
            tmp += imos_table[j]
            A_new[j] += tmp

        A = copy.deepcopy(A_new)

    print(" ".join(map(str, A)))

def main():
    N, K = LI()
    A = LI()
    # N = 2 * 10 ** 5
    # K = 41
    # A = [0 for i in range(2* 10 ** 5)]
    solve(N, K, A)

if __name__ == "__main__":
    main()


# https://leetcode.com/problems/reconstruct-itinerary/description/

class Solution(object):
    def findItinerary(self, tickets):
        """
        :type tickets: List[List[str]]
        :rtype: List[str]
        """
        itinerary = []
        flights = {}

        for dep, arr in tickets:
            if dep not in flights:
                flights[dep] = [arr]
            else:
                flights[dep].append(arr)
                flights[dep] = sorted(flights[dep])

        def makeItin(start):
            nonlocal itinerary, flights
            if start in flights:
                ends = flights[start]
                while ends:
                    makeItin(ends.pop(0))
            itinerary.insert(0, start)

        makeItin('JFK')

        return itinerary

# test cases:
# [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]  gives Line 19: KeyError: 'KUL'
# findItinerary([["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"],["SJC","JFK"],["JFK","ZBC"]])

# [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]] should return ["JFK","NRT","JFK","KUL"]
# JS solution: https://goo.gl/JwnyVJ  builds itinerary backwards; used the helper function in this code to get a python solution

# [["EZE","TIA"],["EZE","HBA"],["AXA","TIA"],["JFK","AXA"],["ANU","JFK"],["ADL","ANU"],["TIA","AUA"],["ANU","AUA"],["ADL","EZE"],["ADL","EZE"],["EZE","ADL"],["AXA","EZE"],["AUA","AXA"],["JFK","AXA"],["AXA","AUA"],["AUA","ADL"],["ANU","EZE"],["TIA","ADL"],["EZE","ANU"],["AUA","ANU"]]


import random
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QColor
from qgis.core import QgsExpression, QgsExpressionContext, QgsExpressionContextUtils

from .qgis2threejscore import calculateDEMSize
from .qgis2threejstools import logMessage
from .stylewidget import StyleWidget, ColorWidgetFunc, OpacityWidgetFunc, OptionalColorWidgetFunc, ColorTextureWidgetFunc

colorNames = []

class DEMPropertyReader:

  def __init__(self, layerId, properties=None):
    properties = properties or {}
    self.layerId = layerId
    self.properties = properties

  def demSize(self, canvasSize):
    if self.layerId == "FLAT":
      return QSize(2, 2)

    sizeLevel = self.properties.get("horizontalSlider_DEMSize", 2)
    roughening = 0
    if self.properties.get("checkBox_Surroundings", False):
      roughening = self.properties.get("spinBox_Roughening", 0)
    return calculateDEMSize(canvasSize, sizeLevel, roughening)

class VectorPropertyReader:

  def __init__(self, objectTypeManager, renderContext, layer, properties):
    assert(properties is not None)
    self.renderContext = renderContext
    self.expressionContext = QgsExpressionContext()
    self.expressionContext.appendScope(QgsExpressionContextUtils.layerScope(layer))
    self.layer = layer
    properties = properties or {}
    self.properties = properties

    if properties:
      self.objType = objectTypeManager.objectType(layer.geometryType(), properties["comboBox_ObjectType"])
      self.visible = properties.get("visible", True)
    else:
      self.visible = False

    self._exprs = {}
    self.exprAlt = QgsExpression(properties.get("fieldExpressionWidget_altitude") or "0")
    self.exprLabel = QgsExpression(properties.get("labelHeightWidget", {}).get("editText") or "0")

  def evaluateExpression(self, expr_str, f):
    if expr_str not in self._exprs:
      self._exprs[expr_str] = QgsExpression(expr_str)

    self.expressionContext.setFeature(f)
    return self._exprs[expr_str].evaluate(self.expressionContext)

  def readFillColor(self, vals, f):
    return self._readColor(vals, f)

  def readBorderColor(self, vals, f):
    return self._readColor(vals, f, isBorder=True)

  # read color from COLOR or OPTIONAL_COLOR widget
  def _readColor(self, widgetValues, f, isBorder=False):
    global colorNames

    mode = widgetValues["comboData"]
    if mode == OptionalColorWidgetFunc.NONE:
      return None

    if mode == ColorWidgetFunc.EXPRESSION:
      val = self.evaluateExpression(widgetValues["editText"], f)
      try:
        if isinstance(val, str):
          a = val.split(",")
          if len(a) >= 3:
            a = [max(0, min(int(c), 255)) for c in a[:3]]
            return "0x{:02x}{:02x}{:02x}".format(a[0], a[1], a[2])
          return val.replace("#", "0x")

        raise
      except:
        logMessage("Wrong color value: {}".format(val))
        return "0"

    if mode == ColorWidgetFunc.RANDOM or f is None:
      if len(colorNames) == 0:
        colorNames = QColor.colorNames()
      colorName = random.choice(colorNames)
      colorNames.remove(colorName)
      return QColor(colorName).name().replace("#", "0x")

    # feature color
    symbol = self.layer.renderer().symbolForFeature(f, self.renderContext)
    if symbol is None:
      logMessage('Symbol for feature not found. Please use a simple renderer for {0}.'.format(self.layer.name()))
      return "0"

    else:
      sl = symbol.symbolLayer(0)
      if sl:
        if isBorder:
          return sl.strokeColor().name().replace("#", "0x")

        if symbol.hasDataDefinedProperties():
          expr = sl.dataDefinedProperty("color")
          if expr:
            # data defined color
            rgb = expr.evaluate(f, f.fields())

            # "rrr,ggg,bbb" (dec) to "0xRRGGBB" (hex)
            r, g, b = [max(0, min(int(c), 255)) for c in rgb.split(",")[:3]]
            return "0x{:02x}{:02x}{:02x}".format(r, g, b)

    return symbol.color().name().replace("#", "0x")

  def readOpacity(self, widgetValues, f):
    vals = widgetValues

    if vals["comboData"] == OpacityWidgetFunc.EXPRESSION:
      try:
        val = self.evaluateExpression(widgetValues["editText"], f)
        return min(max(0, val), 100) / 100
      except:
        logMessage("Wrong opacity value: {}".format(val))
        return 1

    symbol = self.layer.renderer().symbolForFeature(f, self.renderContext)
    if symbol is None:
      logMessage('Symbol for feature not found. Please use a simple renderer for {0}.'.format(self.layer.name()))
      return 1
    #TODO [data defined property]
    return self.layer.opacity() * symbol.opacity()

  @classmethod
  def toFloat(cls, val):
    try:
      return float(val)
    except Exception as e:
      logMessage('{0} (value: {1})'.format(e.message, str(val)))
      return 0

  # functions to read values from height widget (z coordinate)
  def useZ(self):
    return self.properties.get("radioButton_zValue", False)

  def useM(self):
    return self.properties.get("radioButton_mValue", False)

  def isHeightRelativeToDEM(self):
    return self.properties.get("comboBox_altitudeMode") is not None

  def altitude(self):
    return float(self.exprAlt.evaluate(self.expressionContext) or 0)

  def labelHeight(self):
    return float(self.exprLabel.evaluate(self.expressionContext) or 0)

  def setContextFeature(self, f):
    self.expressionContext.setFeature(f)

  # read values from style widgets
  def values(self, f):
    assert(f is not None)
    vals = []
    for i in range(16):   # big number for style count
      p = "styleWidget" + str(i)
      if p not in self.properties:
        break

      widgetValues = self.properties[p]
      if len(widgetValues) == 0:
        break

      widgetType = widgetValues["type"]
      comboData = widgetValues.get("comboData")
      if widgetType == StyleWidget.COLOR:
        vals.append(self.readFillColor(widgetValues, f))

      elif widgetType == StyleWidget.OPTIONAL_COLOR:
        vals.append(self.readBorderColor(widgetValues, f))

      elif widgetType == StyleWidget.COLOR_TEXTURE:
        if comboData == ColorTextureWidgetFunc.MAP_CANVAS:
          vals.append(comboData)
        elif comboData == ColorTextureWidgetFunc.LAYER:
          vals.append(widgetValues.get("layerIds", []))
        else:
          vals.append(self.readFillColor(widgetValues, f))

      elif widgetType == StyleWidget.OPACITY:
        vals.append(self.readOpacity(widgetValues, f))

      elif widgetType == StyleWidget.CHECKBOX:
        vals.append(widgetValues["checkBox"])

      else:
        expr = widgetValues["editText"]
        val = self.evaluateExpression(expr, f)
        if val is None:
          logMessage("Failed to evaluate expression: " + expr)
          if widgetType == StyleWidget.FILEPATH:
            val = ""
          else:
            val = 0
        vals.append(val)
    return vals


import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable

import numpy as np

# class Loss_DCSNN2(nn.Module):
#     def __init__(self, device, lam_recon=10., lam_reg = 0.1, lam_local = 1., s = 1.):
#         super().__init__()
#         self.lam_recon = lam_recon
#         self.lam_reg = lam_reg
#         self.lam_local = lam_local
#         self.device = device
#         self.s = s
#         self.BCEWithLogitsLoss = nn.BCEWithLogitsLoss()

#     def forward(self, global_features, local_features, local_features_recon, local_aggre_features, D_global, D_local, S):
#         omega_x = global_features.mm(Variable(D_global,requires_grad=False).t())/self.s # logit values

#         # global loss
#         global_loss = self.BCEWithLogitsLoss(omega_x, S)
#         norm = global_features.norm(dim=1)
#         reg_global = (norm - torch.ones_like(norm).cuda()).pow(2).mean()

#         # reconstruction loss
#         recon_loss = 1/local_features.flatten().size(0)*torch.norm(local_features.flatten()-local_features_recon.flatten())

#         # local aggregation loss
#         local_omega_x = local_aggre_features.mm(Variable(D_local,requires_grad=False).t())/self.s
#         local_loss = self.BCEWithLogitsLoss(local_omega_x, S)
#         norm = local_aggre_features.norm(dim=1)
#         reg_local = (norm - torch.ones_like(norm).cuda()).pow(2).mean()

#         # total loss
#         loss =  global_loss + self.lam_local*local_loss + self.lam_recon*recon_loss + self.lam_reg * (reg_global + reg_local)

#         return loss, global_loss, local_loss, recon_loss, reg_global, reg_local

def _compute_homography_est_loss(h4_est, h4):
    return F.mse_loss(h4_est.view(1,-1), h4.view(1,-1).float())

def _compute_matching_loss(ms,kp,kpw,h,gt_radious):
    kp = kp.flip(1) # flip to x,y coordinates from h,w
    kp = torch.cat((kp, kp.new_ones((kp.size(0),1))), axis=1).float()
    kpw_ = torch.mm(h.float(), kp.t()).t()
    kpw_ /= kpw_[:,2].view(kpw_.size(0),1)
    kpw_ = kpw_[:,:2]
    kpw_ = kpw_.flip(1) # flip back to h,w coordinates
    # kp = kp[:,:2]
    dist = torch.norm(kpw_.view(kpw_.size(0),1,2) - kpw.view(1,kpw.size(0),2), p=2, dim=-1) # nkp (k) X nkpw (q)
    s = (dist<=gt_radious).float()
    s_pred = ms[:-1,:-1]

    s_pred_k = ms[:-1,-1]
    s_pred_q = ms[-1,:-1]

    s_k = torch.where(s.sum(1) == 0, s.new_tensor(1.), s.new_tensor(0.))
    s_q = torch.where(s.sum(0) == 0, s.new_tensor(1.), s.new_tensor(0.))

    # loss =  - (s_k*s_pred_k.log()).sum() - (s_q*s_pred_q.log()).sum()
    loss_term1 = -(s*s_pred).sum()
    loss_term2 = - (s_k*s_pred_k).sum()
    loss_term3 = - (s_q*s_pred_q).sum()
    # if (s*s_pred).sum() > 0.:
    #     loss -= (s*s_pred.log()).sum()
    # print(loss_term1.item(), loss_term2.item(),loss_term3.item())
    # if np.isnan(loss_term1.item()):
    #     aa = 1
    loss = loss_term1 + loss_term2 + loss_term3
    return loss
    # return F.binary_cross_entropy(s_pred, s) +F.binary_cross_entropy(s_pred_k, s_k)+ \
                # F.binary_cross_entropy(s_pred_q, s_q)

def compute_matcher_loss(matching_scores, h4_ests, H, H4, kpts_k, kpts_q, lam, device, gt_radious=4.):
    nimg = len(matching_scores)
    matching_loss = torch.zeros(1).float().to(device)
    homoest_loss = torch.zeros(1).float().to(device)

    for ms, kp, kpw, h, h4_est, h4 in zip(matching_scores, kpts_k, kpts_q, H, h4_ests, H4):
        matching_loss += _compute_matching_loss(ms,kp,kpw,h,gt_radious)
        homoest_loss += _compute_homography_est_loss(h4_est, h4)
    matching_loss /= nimg
    homoest_loss /= nimg
    homoest_loss*=lam

    return matching_loss + homoest_loss, matching_loss, homoest_loss

def descriptor_loss(net_out, H, positive_margin=1., negative_margin=0.2):
    lds, lds_warp = net_out['localdesc_k'], net_out['localdesc_q']
    kpts, kpts_warp = net_out['kpts_k'], net_out['kpts_q']
    assert len(kpts) == len(kpts_warp) & len(lds) == len(lds_warp) & len(lds) == H.size(0)
    nimg = len(kpts)
    loss = lds[0].new_zeros(1)

    for ld, ldw, kp, kpw, h in zip(lds, lds_warp, kpts, kpts_warp, H):
        kp = kp.flip(1) # flip to x,y coordinates from h,w
        kp = torch.cat((kp, kp.new_ones((kp.size(0),1))), axis=1).float()

        kpw_ = torch.mm(h.float().to(kp), kp.t()).t()
        kpw_ = kpw_/kpw_[:,2].view(-1,1)
        kpw_ = kpw_[:,:2]
        kp = kp[:,:2]

        kpw_ = kpw_.flip(1) # flip back to h,w coordinates

        # kpw_ = torch.where(kpw_<0, kpw_.new_tensor(0), kpw_)
        # kpw_ = torch.where(kpw_>223., kpw_.new_tensor(223), kpw_)

        dist = torch.norm(kpw_.view(kpw_.size(0),1,2) - kpw.view(1,kpw.size(0),2), p=2, dim=-1) # nkpw X nkpw_
        s = (dist<=8.).float()
        # print(s.sum().item())
        ld_mat = torch.einsum('dl,dw->lw', ld, ldw)
        loss_p = torch.max(torch.zeros_like(ld_mat), positive_margin-ld_mat*s)*s
        loss_p = loss_p.sum()/torch.nonzero(s,as_tuple=False).size(0)
        loss_m = torch.max(torch.zeros_like(ld_mat), ld_mat*(1.-s) - negative_margin)
        loss_m = loss_m.sum()/torch.nonzero(1-s,as_tuple=False).size(0)
        loss += loss_p + loss_m

    loss /= nimg
    # if torch.isnan(loss):
    #     aa = 1

    return loss

class Loss_DCSNN(nn.Module):
    def __init__(self, device, lamda = [0.1, 10, 0.001], temp = 0.5, self_learning=True):
        super().__init__()
        self.lam_reg, self.lam_kp, self.lam_ld = lamda
        self.device = device
        self.T = temp
        self.self_learning = self_learning

    # def forward(self, global_feature_q, global_feature_k, key_queue, S, kp_gt, kp_out, kp_warp_gt, kp_warp_out):
    def forward(self, key_queue, adj_mat, kpts_gt_k, kpts_gt_q, net_out, H):
        globaldesc_q = net_out['globaldesc_q']
        globaldesc_k = net_out['globaldesc_k']
        kpts_q = net_out['scores_map_q']
        kpts_k = net_out['scores_map_k']

        # regularization
        norm = globaldesc_q.norm(dim=1)
        reg_global = (norm - torch.ones_like(norm).cuda()).pow(2).mean()

        # global loss
        omega_x = globaldesc_q.mm(Variable(key_queue,requires_grad=False))/self.T # logit values
        global_loss = F.binary_cross_entropy_with_logits(omega_x, adj_mat)

        # self learning
        if self.self_learning:
            norm_k = globaldesc_k.norm(dim=1)
            reg_global_self = (norm_k - torch.ones_like(norm_k).cuda()).pow(2).mean()
            reg_global += reg_global_self

            self_omega_x = (globaldesc_q*Variable(globaldesc_k,requires_grad=False)).sum(dim=1)/self.T
            label = torch.ones_like(self_omega_x) # self label
            global_loss_self = F.binary_cross_entropy_with_logits(self_omega_x, label)
            global_loss += global_loss_self

        # kp_example = kpts_k[0].cpu().detach().numpy()
        # from PIL import Image
        # kp_example = Image.fromarray(kp_example, mode='L')

        # kpgt_example = kpts_gt_k.squeeze()[0].cpu().detach().numpy()
        # from PIL import Image
        # kpgt_example = Image.fromarray(kpgt_example, mode='L')

        # keypoint - element-wise bce
        # kp_bce = F.binary_cross_entropy_with_logits(kpts_q, kpts_gt_q.squeeze()) \
        #        + F.binary_cross_entropy_with_logits(kpts_k, kpts_gt_k.squeeze())
        # kp_bce = F.binary_cross_entropy(torch.sigmoid(kpts_q), kpts_gt_q.squeeze()) \
        #        + F.binary_cross_entropy(torch.sigmoid(kpts_k), kpts_gt_k.squeeze())
        kp_loss = F.binary_cross_entropy(kpts_q, kpts_gt_q.squeeze()) \
               + F.binary_cross_entropy(kpts_k, kpts_gt_k.squeeze())

        ld_loss = descriptor_loss(net_out, H) # local descriptor loss

        # total loss
        reg_global *= self.lam_reg
        kp_loss *= self.lam_kp
        ld_loss *= self.lam_ld
        loss =  global_loss + reg_global + kp_loss + ld_loss

        return loss, global_loss, reg_global, kp_loss, ld_loss

def setup_loss(method, device, **kwargs):
    method = method.lower()
    # if method in ['dpsh']:
    #     criterion = Loss_DPSH(device, **kwargs)
    # elif method in ['dhn']:
    #     criterion = Loss_DHN(device, **kwargs)
    # elif method in ['dhnnl2']:
    #     criterion = Loss_DHNNL2(device, **kwargs)
    # elif method in ['dcsnn']:
    #     criterion = Loss_DCSNN(device, **kwargs)
    # if method in ['dcsnn2']:
    #     criterion = Loss_DCSNN2(device, **kwargs)
    # else:
    #     raise ValueError('Unknown method type!')
    criterion = Loss_DCSNN(device, **kwargs)
    return criterion


from talon import Context, actions

ctx = Context()

ctx.matches = r"""
tag: ultisnips
"""

@ctx.action_class("user")
class user_actions:
    def snippet_search(text: str):
        # XXX - to complete
        # actions.user.ide_command_palette()
        # actions.insert("Insert Snippet")
        actions.insert(text)

    def snippet_insert(text: str):
        """Inserts a snippet"""
        actions.user.vim_insert_mode(text)
        actions.key("tab")


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None or head.next == None:
            return False
        p_faster = head.next
        p_slower = head
        while p_faster and p_slower:
            p_faster = p_faster.next
            p_slower = p_slower.next
            if p_faster:
                p_faster = p_faster.next
            if p_faster is p_slower:
                return True
        return False


# encoding:utf-8
import copy
import numpy as np
import random

a,b = map(int,input().split())
# 1digit
def function(n):
    if n==0 or n==1:
        return n
    else:
        if n%4==0:
            return n
        elif n%4==1:
            return 1
        elif n%4==2:
            return n+1
        else:
            return 0

if a==0:
    print(function(b))
    exit()

else:
    print(function(a-1)^function(b))

'''
# F(0,n)を求める
def F(n):
    if n==0:
        tmp_ans = 0
    else:
        true_count = (n+1)//2
        if (n+1)%2==0:
            if true_count%2==0:
                tmp_ans = 0
            else:
                tmp_ans = 1
        else:
            if true_count%2==0:
                tmp_ans = n
            else:
                if n%2==0:
                    tmp_ans = n+1
                else:
                    tmp_ans = n-1

    return tmp_ans

max_digit = 0
num = b
while num > 0:
    max_digit += 1
    num = num//2

a_digits= []
b_digits = []
digits = []

A = F(a-1)
B = F(b)
# print(A,B)
for i in range(max_digit):
    a_digits.append(A%2)
    b_digits.append(B%2)
    A = A//2
    B = B//2

for i in range(max_digit):
    if (a_digits[i] == 1 and b_digits[i] == 1) or (a_digits[i] == 0 and b_digits[i]==0):
        digits.append(0)
    else:
        digits.append(1)

ans = 0
for i in range(max_digit):
    ans += digits[i]*2**i

print(ans)
'''
'''
if a == b:
    print(a)
    exit()

def xor_0(a,b):
    if((b-a+1)//2)%2 == 0:
        if (b-a+1)%2==0:
            digit = 0
        else:
            if a%2==0:
                # 0 xor 0
                digit = 1
            else:
                # 1 xor 1
                digit = 1
    else:
        if (b-a+1)%2==0:
            digit = 1
        else:
            if a%2==0:
                # 0 xor 0
                digit = 1
            else:
                # 0 xor 1
                digit = 0

    return digit

max_digit = 0
num = b
while num > 0:
    max_digit += 1
    num = num//2

def digit_xor(a,b,i):
    if i == 0:
        return xor_0(a,b)
    else:
        count = 0
        posi_a = a%(2**(i+1))
        if posi_a>2**i:
            count += 2**i-a+1
        elif posi_a==0:
            pass
        else:
            count += 2**i

        posi_b = b%(2**(i+1))
        if posi_b > 2**i:
            count += 2**i
        else:
            count += posi_b

    if count%2==0:
        return 0
    else:
        return 1

digits = []
for i in range(max_digit):
    digits.append(digit_xor(a,b,i))

ans = 0
print(digits)
for i in range(len(digits)):
    ans += digits[i]*2**i

print(ans)
'''


#!/usr/bin/env python3
#
# Usage: .py
#

from timeit import timeit
import unittest

from bank_account.account import timer
from bank_account.account import Account

class TestTimer(unittest.TestCase):
    def test_timer_decorator(self):
        @timer
        def to_be_decorated(self, amount):
            pass
        to_be_decorated(self, amount=10)

from bank_account.account import AmountError, BalanceError
import bank_account.account as acc

class AmountErrorTest(unittest.TestCase):
    def test_account_amount_error_deposit(self):
        with self.assertRaises(AmountError):
            acc.Account(account_number='123456',
                          account_holder='John Smith',
                          opening_balance=100,
                          account_type='deposit',
                          transaction=[20, 30]).deposit(amount = -1)

    def test_account_amount_error_withdraw(self):
        with self.assertRaises(AmountError):
            acc.Account(account_number='823456',
                          account_holder='John Smyth',
                          opening_balance=101,
                          account_type='savings',
                          transaction=[20, 30]).withdraw(amount = -1)

    def test_current_account_amount_error_deposit(self):
        with self.assertRaises(AmountError):
            acc.CurrentAccount(account_number='789123',
                            account_holder='jon smith',
                            opening_balance=106,
                            overdraft_limit = 1000,
                            transaction=[20, 30]).deposit(amount = -2)

    def test_current_account_amount_error_withdraw(self):
        with self.assertRaises(AmountError):
            acc.CurrentAccount(account_number='889123',
                            account_holder='juan smith',
                            opening_balance=108,
                            overdraft_limit = -1001,
                            transaction=[20, 30]).withdraw(amount = -3)

class BalanceErrorTest(unittest.TestCase):
    def test_current_account_balance_error(self):
        with self.assertRaises(BalanceError):
            acc.CurrentAccount(account_number='889123',
                            account_holder='juan smith',
                            opening_balance=100,
                            overdraft_limit = -100,
                            transaction=[20, 30]).withdraw(amount = 500)

from bank_account.account import Account
from bank_account.account import CurrentAccount
from bank_account.account import DepositAccount
from bank_account.account import InvestmentAccount

class AccountTest(unittest.TestCase):
    def test_account_has_account_number(self):
        account = Account(account_number='123456',
                          account_holder='John Smith',
                          opening_balance=100,
                          account_type='deposit',
                          transaction=[20, 30])
        self.assertEqual(account.account_number, '123456')

    def test_account_has_account_holder(self):
        account = Account(account_number='234567',
                          account_holder='John Doe',
                          opening_balance=101,
                          account_type='investment',
                          transaction=[20, 30])
        self.assertEqual(account.account_holder, 'John Doe')

    def test_account_has_opening_balance(self):
        account = Account(account_number='345678',
                          account_holder='Jane Smith',
                          opening_balance=102,
                          account_type='savings',
                          transaction=[20, 30])
        self.assertEqual(account._opening_balance, 102)

    def test_account_has_account_type(self):
        account = Account(account_number='456789',
                          account_holder='bob dole',
                          opening_balance=103,
                          account_type='deposit',
                          transaction=[20, 30])
        self.assertEqual(account.account_type, 'deposit')

    def test_account_has_string_representation(self):
        account = Account(account_number='567891',
                        account_holder='jane dole',
                        opening_balance=104,
                        account_type='savings',
                          transaction=[20, 30])
        self.assertEqual(str(account), "Account[567891] - jane dole, savings account = 104")

    def test_account_has_technical_representation(self):
        account = Account(account_number='567891',
                        account_holder='jane dole',
                        opening_balance=104,
                        account_type='savings',
                        transaction=[20, 30])
        self.assertEqual(repr(account), "Account('567891', 'jane dole', 104, 'savings')")

    def test_account_has_iter_method(self):
        my_list = list()
        my_iter = iter(my_list)
        with self.assertRaises(StopIteration):
            Account('567891', 'jane dole', 104, 'savings', next(my_iter))

    def test_account_only_allows_for_account_number_in_string_format(self):
        with self.assertRaises(TypeError):
            Account(567891, 'jane dole', 104, 'savings', [20, 30])

    def test_account_only_allows_for_digits_in_account_number(self):
        with self.assertRaises(ValueError):
            Account('A67891', 'jane dole', 104, 'savings', [20, 30])

    def test_account_only_allows_for_account_number_to_be_of_len_6(self):
        with self.assertRaises(ValueError):
            Account('4678917', 'jane dole', 104, 'savings', [20, 30])

    def test_account_only_allows_for_name_in_correct_format(self):
        with self.assertRaises(ValueError):
            Account('467891', 'jane.dole@gmail.com', 104, 'savings', [20, 30])

    def test_account_only_allows_positive_opening_balance(self):
        with self.assertRaises(ValueError):
            Account('467891', 'sam dole', -102, 'investment', [20, 30])

    def test_account_has_three_account_types(self):
        self.assertEqual(
            Account.TYPES,
            ('current', 'savings', 'deposit', 'investment')
        )

    def test_account_only_allows_for_valid_type(self):
        with self.assertRaises(ValueError):
            Account('567891', 'jane dole', 104, 'practice', [20, 30])

    def test_account_deposit_instance_method(self):
        account = Account(account_number='567891',
                        account_holder='jane dole',
                        opening_balance=104,
                        account_type='savings',
                        transaction=[20,30])
        self.assertIsNone(account.deposit(amount=20))

    def test_account_withdraw_instance_method(self):
        account = Account(account_number='678912',
                        account_holder='james smith',
                        opening_balance=105,
                        account_type='investment',
                        transaction=[10,20])
        self.assertIsNone(account.withdraw(amount=30))

    def test_account_get_balance_instance_method(self):
        account = Account(account_number='789123',
                        account_holder='jon smith',
                        opening_balance=106,
                        account_type='deposit',
                        transaction=[20, 30])
        self.assertEqual(account.get_balance, account._opening_balance)

    def test_account_increment_instance_count(cls):
        cls.assertIsNone(Account.increment_instance_count())

    def test_account_static_method(cls):
        cls.assertIsNone(Account.static_function())

class CurrentAccountTest(unittest.TestCase):
    def test_current_account_has_string_representation(self):
        current_account = CurrentAccount(account_number='789123',
                                        account_holder='jon smith',
                                        opening_balance=106,
                                        overdraft_limit = 1000,
                                        transaction=[20, 30])
        self.assertEqual(str(current_account), "CurrentAccount[789123] - jon smith, account = 106, overdraft limit = 1000")

    def test_current_account_has_technical_respresentation(self):
        current_account = CurrentAccount(account_number='891237',
                                        account_holder='jon jones',
                                        opening_balance=115,
                                        overdraft_limit = 1500,
                                        transaction=[20, 30])
        self.assertEqual(repr(current_account), "CurrentAccount('891237', 'jon jones', 115, 1500)")

    def test_current_account_withdraw_instance_method(self):
        current_account = CurrentAccount(account_number='123796',
                                        account_holder='sam jones',
                                        opening_balance=179,
                                        overdraft_limit = -100,
                                        transaction=[20, 30])
        self.assertIsNone(current_account.withdraw(100))

class DepositAccountTest(unittest.TestCase):
    def test_deposit_account_has_string_representation(self):
        deposit_account = DepositAccount(account_number='891234',
                                        account_holder='jony smith',
                                        opening_balance=109,
                                        interest_rate = 0.5,
                                        transaction=[20, 30])
        self.assertEqual(str(deposit_account), "DepositAccount[891234] - jony smith, account = 109, interest rate = 0.5")

    def test_deposit_account_has_technical_respresentation(self):
        deposit_account = DepositAccount(account_number='912372',
                                        account_holder='jon ellis',
                                        opening_balance=120,
                                        interest_rate = 0.6,
                                        transaction=[20, 30])
        self.assertEqual(repr(deposit_account), "DepositAccount('912372', 'jon ellis', 120, 0.6)")

    def test_deposit_account_interest_method(self):
        deposit_account = DepositAccount(account_number='123729',
                                        account_holder='jony ellis',
                                        opening_balance=132,
                                        interest_rate = 0.7,
                                        transaction=[20, 30])
        self.assertEqual(deposit_account.interest(), deposit_account._opening_balance * deposit_account.interest_rate)

class InvestmentAccountTest(unittest.TestCase):
    def test_investment_account_has_string_representation(self):
        investment_account = InvestmentAccount(account_number='912347',
                                        account_holder='jonny jones',
                                        opening_balance=115,
                                        risk_level = 'high',
                                        transaction=[20, 30])
        self.assertEqual(str(investment_account), "InvestmentAccount[912347] - jonny jones, account = 115, risk level = high")

    def test_investment_account_has_technical_respresentation(self):
        investment_account = InvestmentAccount(account_number='123729',
                                        account_holder='jonny ellis',
                                        opening_balance=121,
                                        risk_level = 'low',
                                        transaction=[20, 30])
        self.assertEqual(repr(investment_account), "InvestmentAccount('123729', 'jonny ellis', 121, low)")

    def test_investment_account_has_risk_type(self):
        investment_account = InvestmentAccount(account_number='237298',
                                        account_holder='jim ellis',
                                        opening_balance=127,
                                        risk_level = 'high',
                                        transaction=[20, 30])
        self.assertEqual(investment_account.risk_level, 'high')

    def test_investment_account_has_three_risk_types(self):
        self.assertEqual(
            InvestmentAccount.RISK_TYPES,
            ('low', 'medium', 'high')
        )

    def test_investment_account_only_allows_for_valid_risk_type(self):
        with self.assertRaises(ValueError):
            InvestmentAccount('767891', 'jonathan dole', 94, 'super high', [20, 30])


KEYS = {
'access_token' :'自分のやつ書いてね',
'access_token_secret':'自分のやつ書いてね',
'api_key' :'自分のやつ書いてね',
'api_secret' : '自分のやつ書いてね'

}

#correct Twitter data
import json
from requests_oauthlib import  OAuth1Session
twitter = OAuth1Session(KEYS['api_key'],KEYS['api_secret'],KEYS['access_token'],KEYS['access_token_secret'])

def getTwitterData(key_word,latitude,longtitude,radius,repeat=10):
    url = "https://api.twitter.com/1.1/search/tweets.json"
    #取得パラメータ
    params = {'q':key_word,'count':'100','geocode':'%s,%s,%skm' % (latitude,longtitude,radius),'result_type':'recent'}
    tweets = []
    mid = -1

    for i in range(repeat):
        params['max_id'] = mid #midより古いIDをツイート
        res = twitter.get(url,params = params)
        if res.status_code ==200:
            #レスポンスからツイートする
            sub_tweets = json.loads(res.text)['statuses']

            user_ids = []

            for tweet in sub_tweets:
                user_ids.append(int(tweet['id']))
                tweets.append(tweet)

            if len(user_ids)>0:
                min_user_id = min(user_ids)
                mid = min_user_id -1
            else:
                mid = -1
                print(mid)
        else:
                print("Failed:%d" % res.status_code)

    print("ツイート取得数:%s" % len(tweets))
    return tweets

import time,calendar

def YmdHMS(created_at):
    time_utc = time.strptime(created_at,'%a %b %d %H:%M:%S +0000 %Y')
    unix_time = calendar.timegm(time_utc)
    time_local = time.localtime(unix_time)
    return time.strftime("%Y/%m¥/%d %H:%M:%S",time_local)

#latitude35.1686111111 longtitude:136.910277778

tweets_atuma = getTwitterData("サイトウ",35.1761591,136.9082679,20,repeat=10)
for tweet in tweets_atuma:
    print(YmdHMS(tweet["created_at"]))
    print(tweet["text"]+"\n")


# This file serves creates an example netCDF file to demonstrate the tools
# for reading and writing parameter scan data.

from exceptions import *
from dakota_file import DakotaFile
import numpy as np
import xarray as xr
import main
import os

# First create an instance of the dakota_netcdf class!
my_netcdf = DakotaFile()

# Unlike the Monte-Carlo sampling case we do not need any run settings
# so the add_settings function should not be called

# We need to add some parameter scan variables

# ------------------------------------------------------------------------
# WRITE EXAMPLE 1
# ------------------------------------------------------------------------

# The simplest way is to build a dictionary of needed variables and call
# the add_variable_from_dict function.

# Performing a parameter scan requires 3 variables. Upper and lower bounds
# and the number of partitions.

# Give our variable a name!
name = 'test_scan1'

# Specify that the variable should be scanned
var_type = 'scan'

# Make a dictionary of the needed data
lower_bounds  = np.random.rand(4,3)
upper_bounds  = np.random.rand(4,3)
partitions    = np.random.randint(2,10,size=(4,3))

variable_dict = { 'lower_bounds' : lower_bounds, 'upper_bounds' : upper_bounds,
                  'partitions' : partitions }

my_netcdf.add_variable_from_dict( name, var_type, variable_dict )

# -----------------------------------------------------------------------
# WRITE EXAMPLE 2
# -----------------------------------------------------------------------

# We can also add a variable by constructing an Xarray dataset
# To do this the data must be created as data arrays and then added to the dataset

# Create a name for this new variable
name = 'test_scan2'

var_type = 'scan'

lower_bounds1 = xr.DataArray(lower_bounds)
upper_bounds1 = xr.DataArray(upper_bounds)
partitions1   = xr.DataArray(partitions)

dataset = xr.Dataset( {'lower_bounds' : lower_bounds1, 'upper_bounds' : upper_bounds1,
                       'partitions' : partitions1 } )

my_netcdf.add_variable_from_dataset( name, var_type, dataset )

# ----------------------------------------------------------------------
# WRITE EXAMPLE 3
# ----------------------------------------------------------------------

# One of the advantages of using a dataset is that one can also specify the dimensions
# and coordinates of variables. It may be convenient to have these available in the
# interface script.

# Create a name for this new variable
name = 'test_scan3'

var_type = 'scan'

# Coordinates
x = np.array( [0.2,0.3,0.4,0.5,0.6] )
y = np.array( [2.5,3.5,4.5] )
z = np.array( [5.2,5.3] )

# Convert coordinates to data arrays
x = xr.DataArray(x,dims=['x'])
y = xr.DataArray(y,dims=['y'])
z = xr.DataArray(z,dims=['z'])

# Construct variable data arrays which include dimensions and coordinates
lower_bounds = np.random.rand(5,3,2)
lower_bounds = xr.DataArray(lower_bounds, coords=[x,y,z], dims=['x','y','z'])

upper_bounds = np.random.rand(5,3,2) + 2.0
upper_bounds = xr.DataArray(upper_bounds, coords=[x,y,z], dims=['x','y','z'])

partitions   = np.random.randint(2,10,size=(5,3,2))
partitions   = xr.DataArray(partitions,   coords=[x,y,z], dims=['x','y','z'])

dataset = xr.Dataset( {'lower_bounds':lower_bounds, 'upper_bounds':upper_bounds,
                       'partitions':partitions}, attrs={'type':'scan'} )

my_netcdf.add_variable_from_dataset( name, var_type, dataset )

# -----------------------------------------------------------------------
# WRITE EXAMPLE 4
# -----------------------------------------------------------------------

# We can also add a variable by constructing an Xarray dataset directly from numpy
# arrays if coordinate information is not required

# Create a name for this new variable
name = 'test_scan4'

var_type = 'scan'

lower_bounds = 0.0
upper_bounds = 1.0
partitions   = 7

dataset = xr.Dataset( {'lower_bounds' : lower_bounds, 'upper_bounds' : upper_bounds,
                       'partitions' : partitions } )

my_netcdf.add_variable_from_dataset( name, var_type, dataset )

# ----------------------------------------------------------------------
# WRITE THE FILE
# ----------------------------------------------------------------------

filename = 'DAKOTA.nc'
my_netcdf.write(filename)

#=======================================================================
# READING EXAMPLES
#=======================================================================

# To build an interface between DAKOTA and your code you will need to write something
# to read a netcdf file like the one just created and pass the new data to your code.
# The following examples demonstrate reading a netcdf.

# Create a new instance of the
my_netcdf2 = DakotaFile()

filename = 'DAKOTA.nc'
my_netcdf2.read(filename)

# ----------------------------------------------------------------------
# READ EXAMPLE 1
# ----------------------------------------------------------------------

# We can read one of the variables in the netcdf file back into a dictionary of data
# We shall read test_scan2 which was originally written as a dataset

variable_dict = my_netcdf2.get_variable_as_dict('test_scan2')

print('Read Example 1:')
print()

for key, var in variable_dict.items():

    print( key+':' )
    print( var )
    print()

# After running DAKOTA the varied data for each variable should be available as the
# 'values' entry of that variable's dictionary: variable_dict['values']

# ----------------------------------------------------------------------
# READ EXAMPLE 2
# ----------------------------------------------------------------------

# We can also read a variable in the netcdf file back into a dataset
# If the coordinates were also written to the data arrays or the dataset itself
# these will also be available

dataset = my_netcdf2.get_variable_as_dataset('test_scan3')

print('Read Example 2:')
print()

for key in dataset:

    print( key+':' )
    print( dataset[key].dims )
    print( dataset[key].coords )
    print( dataset[key].data )
    print()

# After running DAKOTA the varied data for each variables should be available within the
# 'values' data array of the variables dataset: dataset['values'].data


import subprocess
import time
from matplotlib import pyplot as plt
from FAN_CONFIG import *

def get_sensor_temp(hw_path, sensor_number, string_pattern="temp{}_input"):
    cmd = ["cat", hw_path + "/" + string_pattern.format(sensor_number)]
    temp = int(subprocess.check_output(cmd).strip().decode()) / 1000.
    return temp

def get_sensor_fanspeed(hw_path, sensor_number, string_pattern="fan{}_input"):
    cmd = ["cat", hw_path + "/" + string_pattern.format(sensor_number)]
    speed = int(subprocess.check_output(cmd).strip().decode())
    return speed

def mean_cpu_temp(hw_path, sensor_numbers=[2, 3, 4, 10, 11, 12]):
    cpu_temps = []
    for sensor_number in sensor_numbers:
        cpu_temps.append(get_sensor_temp(hw_path, sensor_number))
    temp_mean = float(sum(cpu_temps) / len(sensor_numbers))
    return temp_mean

def max_cpu_temp(hw_path, sensor_numbers=[2, 3, 4, 10, 11, 12]):
    cpu_temps = []
    for sensor_number in sensor_numbers:
        cpu_temps.append(get_sensor_temp(hw_path, sensor_number))
    temp_max = max(cpu_temps)
    return temp_max

def set_fanspeed(hw_path, pwm_number, pwm_value):
    set_config(hw_path, pwm_number)
    write_pwm_file(hw_path, pwm_number, pwm_value, "pwm{}")

# PWM Configuration...

def set_pwm_enable(hw_path, pwm_number, value="1"):
    write_pwm_file(hw_path, pwm_number, value, "pwm{}_enable")

def set_pwm_mode(hw_path, pwm_number, value="1"):
    write_pwm_file(hw_path, pwm_number, value, "pwm{}_mode")

def set_pwm_step(hw_path, pwm_number, value="1"):
    write_pwm_file(hw_path, pwm_number, value, "pwm{}_step_output")

def set_pwm_start(hw_path, pwm_number, value="10"):
    write_pwm_file(hw_path, pwm_number, value, "pwm{}_start_output")

def set_pwm_stop(hw_path, pwm_number, value="10"):
    write_pwm_file(hw_path, pwm_number, value, "pwm{}_stop_output")

def set_pwm_target(hw_path, pwm_number, value="60000"):
    write_pwm_file(hw_path, pwm_number, value, "pwm{}_target")

def set_pwm_tolerance(hw_path, pwm_number, value="3000"):
    write_pwm_file(hw_path, pwm_number, value, "pwm{}_tolerance")

def write_pwm_file(hw_path, pwm_number, value, string_pattern):
    file = open(hw_path + "/" + string_pattern.format(pwm_number), "w")
    file.write(str(value))
    file.close()

def set_config(hw_path, pwm_number):
    set_pwm_enable(hw_path, pwm_number, "1")
    set_pwm_mode(hw_path, pwm_number, "1")
    # set_pwm_step(hw_path, pwm_number, "1")
    # set_pwm_start(hw_path, pwm_number, "10")
    # set_pwm_stop(hw_path, pwm_number, "10")
    # set_pwm_target(hw_path, pwm_number, "60000")
    # set_pwm_tolerance(hw_path, pwm_number, "3000")

def reset_fan_config(hw_path, pwm_number):
    set_pwm_enable(hw_path, pwm_number, "2")
    set_pwm_mode(hw_path, pwm_number, "1")

def plot_fan_speeds(hw_path, fan_numbers=range(1, 5)):
    for fan_number in fan_numbers:
        real_speeds = []
        fan_speeds = list(range(256))
        fan_speeds.reverse()
        # seconds to max speed
        t_end = time.time() + 10
        while time.time() < t_end:
            set_fanspeed(hwmon7, fan_number, fan_speeds[0])

        for speed in fan_speeds:
            real_speed = get_sensor_fanspeed(hw_path, fan_number)
            real_speeds.append(real_speed)
            # print(real_speed)
            t_end = time.time() + 0.2
            while time.time() < t_end:
                set_fanspeed(hwmon7, fan_number, speed)
                time.sleep(.05)
        print(real_speeds)
        fan_speeds.reverse()
        plt.figure()
        plt.plot(fan_speeds, real_speeds)
    plt.show()

def control_fans(fan_numbers=[1, 2, 3, 4], old_pwm_values=None):
    pwm_values = {}
    for fan_number in fan_numbers:
        if eval("FAN{}_ENABLE".format(fan_number)):
            hw_path = eval("FAN{}_HW".format(fan_number))
            hw_temp = eval("FAN{}_HW_TEMP".format(fan_number))
            hw_temp_sensors = eval("FAN{}_HW_TEMP_SENSOR".format(fan_number))
            min_pwm = eval("FAN{}_MIN_PWM ".format(fan_number))
            max_pwm = eval("FAN{}_MAX_PWM ".format(fan_number))
            min_temp = eval("FAN{}_MIN_TEMP".format(fan_number))
            max_temp = eval("FAN{}_MAX_TEMP".format(fan_number))

            temp = max_cpu_temp(hw_temp, hw_temp_sensors)

            fanpwm = max(min_pwm,
                         min(max_pwm, min_pwm + ((temp - min_temp) * (max_pwm - min_pwm)) / (max_temp - min_temp)))

            if old_pwm_values is not None:
                alpha = 0.85 # smoothing value
                fanpwm = int(old_pwm_values[fan_number] * alpha + fanpwm * (1 - alpha))
            pwm_values[fan_number] = int(fanpwm)
            set_fanspeed(hw_path, fan_number, int(fanpwm))
    return pwm_values

def fan_control_service(fan_numbers=[1, 2, 3, 4],DEBUG=False):
    old_values = None
    while True:
        old_values = control_fans(fan_numbers, old_values)
        time.sleep(10)
        if DEBUG:
            print("mean: {0:.2f} C".format(mean_cpu_temp(hwmon0)) + "\t" + "max: {0:.2f} C".format(
                max_cpu_temp(hwmon0)))
            print("pwmvalues:")
            print(old_values)


"""
This problem was asked by Facebook.

Given a multiset of integers, return whether it can be partitioned into two subsets whose sums are the same.

For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true, since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55.

Given the multiset {15, 5, 20, 10, 35}, it would return false, since we can't split it up into two subsets that add up to the same sum.
"""
def checkSubset(arr, s, i):
    if s == 0:
        return True
    if i == len(arr)-1:
        if s == arr[i]:
            return True
        else:
            return False
    # Check for including and excluding ith element
    if arr[i] <= s:
        return checkSubset(arr, s-arr[i], i+1) or checkSubset(arr, s, i+1)
    # Check excluding the ith element only
    else:
        return checkSubset(arr, s, i+1)

def partition(arr):
    S = sum(arr)
    if S&1:
        return False
    else:
        return checkSubset(arr, S/2, 0)

arr = [15, 5, 20, 10, 35, 15, 10]
print(partition(arr))
arr = [15, 5, 20, 10, 35]
print(partition(arr))


#  file: api/urls.py
from django.urls import path, register_converter
from api.converters import DateConverter

from api.views import StockListListAPIView, StockListRetrieveAPIView
from api.views import StockInformationHistoryListAPIView, StockInformationHistoryRetrieveAPIView, StockInformationSparkListAPIView
from api.views import StockPriceHistoryListAPIView, StockPriceHistoryRetrieveAPIView, StockPriceSparkListAPIView
from api.views import HistoricalStockPriceAPIView, StockSummaryAPIView, StockYearlyFinancialStatementsAPIView, StockQuarterlyFinancialStatementsAPIView, StockProfileAPIView

app_name = 'api'
register_converter(DateConverter, 'date')

urlpatterns = [
    path('stocklist/', StockListListAPIView.as_view(), name='stocklist-list'),
    path('stocklist/<str:ticker>/',
         StockListRetrieveAPIView.as_view(), name='stocklist-detail'),

    path('stockinformationhistory/<str:ticker>/',
         StockInformationHistoryListAPIView.as_view(), name='stockinformationhistory-list'),
    path('stockinformationhistory/<str:ticker>/<date:update_date>/',
         StockInformationHistoryRetrieveAPIView.as_view(), name='stockinformationhistory-detail'),
    path('stockinformationspark/<str:ticker>/<date:s_date>-<date:e_date>/',
         StockInformationSparkListAPIView.as_view(), name='stockinformationspark-list'),

    path('stockpricehistory/<str:ticker>/',
         StockPriceHistoryListAPIView.as_view(), name='stockpricehistory-list'),
    path('stockpricehistory/<str:ticker>/<date:update_date>/',
         StockPriceHistoryRetrieveAPIView.as_view(), name='stockpricehistory-detail'),
    path('stockpricespark/<str:ticker>/<date:s_date>-<date:e_date>/',
         StockPriceSparkListAPIView.as_view(), name='stockpricespark-list'),

    path('historicalstockprice/<str:ticker>/<date:s_date>-<date:e_date>/',
          HistoricalStockPriceAPIView.as_view(), name='historicalstockprice-list'),
    path('stocksummary/<str:ticker>/',
          StockSummaryAPIView.as_view(), name='stocksummary-detail'),
    path('stockyearlyfinancialstatements/<str:ticker>/',
          StockYearlyFinancialStatementsAPIView.as_view(), name='stockyearlyfinancialstatements-detail'),
    path('stockquarterlyfinancialstatements/<str:ticker>/',
          StockQuarterlyFinancialStatementsAPIView.as_view(), name='stockquarterlyfinancialstatements-detail'),
    path('stockprofile/<str:ticker>/',
          StockProfileAPIView.as_view(), name='stockprofile-detail'),
]


def check():

    global flag

    check = 0

    if a[0] == a[1] and a[1] == a[2]:
        check += 1
    if a[3] == a[4] and a[4] == a[5]:
        check += 1
    if a[0]+1 == a[1] and a[1]+1 == a[2]:
        check += 1
    if a[3]+1 == a[4] and a[4]+1 == a[5]:
        check += 1

    if check == 2:
        flag = 1
        return   # 의미 없는 return이다

def perm(n, k):
    if n == k:
        check()
    else:
        for i in range(k, n):
            a[i], a[k] = a[k], a[i]
            perm(n, k+1)
            a[i], a[k] = a[k], a[i]

flag = 0
a = [1, 2, 4, 7, 6, 3]
perm(6, 0)

if flag:
    print("BabyGin")
else:
    print("Not BabyGin")


from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton, QPlainTextEdit, QMessageBox

def handCalc():
    print("统计按钮被点击了")
    info = textEdit.toPlainText()

    salary_above_20k = ''
    salary_below_20k = ''

    for line in info.splitlines():
        if not line.strip():
            continue
        parts = line.split(' ')
        name, salary, age = parts

app = QApplication([])
window = QMainWindow()
window.resize(500, 400)
window.move(300, 310)
window.setWindowTitle("薪资统计")

textEdit = QPlainTextEdit(window)
textEdit.setPlaceholderText("请输入薪资表")
textEdit.move(10, 25)
textEdit.resize(300, 340)

button = QPushButton('统计', window)
button.move(360,160)
# Slot
button.clicked.connect(handCalc())

window.show()

app.exec_()


types_mapping = {
    "1": ("Нормальная ЭКГ"),
    "2": ("Вариант нормальной"),
    "3": ("Патологическая"),
    "4": ("Неинтерпретируемая"),
    "101": ("ЧСС(уд/мин)"),

    "11": ("Нормальное положение"),
    "12": ("Горизонтальное"),
    "13": ("Вертикальное"),
    "14": ("Вправо"),
    "15": ("Влево"),

    "21": ("Синусовый ритм"),
    "22": ("Синусовая тахикардия"),
    "23": ("Синусовая брадикардия"),
    "24": ("Экстрасистолия"),
    "25": ("Синусовая аритмия"),
    "26": ("Трепетание предсердий"),
    "27": ("Фибрилляция предсердий"),
    "28": ("Желудочковая тахикардия"),

    "31": ("Укорочённый PQ интервал"),
    "32": ("AV-блокада"),
    "33": ("Удлинённый QT интервал"),
    "34": ("зменение зубца T"),
    "35": ("(БЛНПГ)Блокада левой ножки пучка Гиса"),
    "36": ("(НБЛНПГ)Неполная блокада левой ножки пучка Гиса"),
    "37": ("(ПБПНПГ)Полная блокада правой ножки пучка Гиса"),
    "38": ("(НБПНПГ)Неполная блокада правой ножки пучка Гиса"),

    "41": ("Гипертрофия левого желудочка"),
    "42": ("Гипертрофия правого желудочка"),
    "43": ("Гипертрофия левого предсердия"),
    "44": ("Гипертрофия правого предсердия"),
    "45": ("Ишемические изменения"),
    "46": ("Смещение ST-сегмента"),
    "47": ("Кардиостимулятор (из заключения)")
}

default_data = [
    {'group_label': "Общее",
     'group_data': [{"view": "checkbox", "label": "Нормальная ЭКГ", "value": 0, "name": "1"},
                    {"view": "checkbox", "label": "Вариант нормальной", "value": 0, "name": "2"},
                    {"view": "checkbox", "label": "Патологическая", "value": 0, "name": "3"},
                    {"view": "checkbox", "label": "Неинтерпретируемая", "value": 0, "name": "4"},
                    {"view": "text", "label": "ЧСС(уд/мин)", "value": 0, "name": "101"},
                    ]},
    {'group_label': "Отклонение оси сердца",
     'group_data': [{"view": "checkbox", "label": "Нормальное положение", "value": 0, "name": "11"},
                    {"view": "checkbox", "label": "Горизонтальное", "value": 0, "name": "12"},
                    {"view": "checkbox", "label": "Вертикальное", "value": 0, "name": "13"},
                    {"view": "checkbox", "label": "Вправо", "value": 0, "name": "14"},
                    {"view": "checkbox", "label": "Влево", "value": 0, "name": "15"},
                    ]},
    {'group_label': "Ритм",
     'group_data': [{"view": "checkbox", "label": "Синусовый ритм", "value": 0, "name": "21"},
                    {"view": "checkbox", "label": "Синусовая тахикардия", "value": 0, "name": "22"},
                    {"view": "checkbox", "label": "Синусовая брадикардия", "value": 0, "name": "23"},
                    {"view": "checkbox", "label": "Экстрасистолия", "value": 0, "name": "24"},
                    {"view": "checkbox", "label": "Синусовая аритмия", "value": 0, "name": "25"},
                    {"view": "checkbox", "label": "Трепетание предсердий", "value": 0, "name": "26"},
                    {"view": "checkbox", "label": "Фибрилляция предсердий", "value": 0, "name": "27"},
                    {"view": "checkbox", "label": "Желудочковая тахикардия", "value": 0, "name": "28"},

                    ]},
    {'group_label': "Нарушения функции проводимости",
     'group_data': [{"view": "checkbox", "label": "Укорочённый PQ интервал", "value": 0, "name": "31"},
                    {"view": "checkbox", "label": "AV-блокада", "value": 0, "name": "32"},
                    {"view": "checkbox", "label": "Удлинённый QT интервал", "value": 0, "name": "33"},
                    {"view": "checkbox", "label": "Изменение зубца T", "value": 0, "name": "34"},
                    {"view": "checkbox", "label": "(БЛНПГ)Блокада левой ножки пучка Гиса", "value": 0, "name": "35"},
                    {"view": "checkbox", "label": "(НБЛНПГ)Неполная блокада левой ножки пучка Гиса", "value": 0,
                     "name": "36"},
                    {"view": "checkbox", "label": "(ПБПНПГ)Полная блокада правой ножки пучка Гиса", "value": 0,
                     "name": "37"},
                    {"view": "checkbox", "label": "(НБПНПГ)Неполная блокада правой ножки пучка Гиса", "value": 0,
                     "name": "38"}
                    ]},
    {'group_label': "Другие Показатели",
     'group_data': [{"view": "checkbox", "label": "Гипертрофия левого желудочка", "value": 0, "name": "41"},
                    {"view": "checkbox", "label": "Гипертрофия правого желудочка", "value": 0, "name": "42"},
                    {"view": "checkbox", "label": "Гипертрофия левого предсердия", "value": 0, "name": "43"},
                    {"view": "checkbox", "label": "Гипертрофия правого предсердия", "value": 0, "name": "44"},
                    {"view": "checkbox", "label": "Ишемические изменения", "value": 0, "name": "45"},
                    {"view": "checkbox", "label": "Смещение ST-сегмента", "value": 0, "name": "46"},
                    {"view": "checkbox", "label": "Кардиостимулятор (из заключения)", "value": 0, "name": "47"},
                    ]}

]

default_history = [
    {'group_label': "Общие",
     'group_data': [{"view": "checkbox", "label": "Нарушение функций щитовидной железы", "value": 0, "name": "1"},
                    {"view": "checkbox", "label": "Сахарный диабет I типа", "value": 0, "name": "2"},
                    {"view": "checkbox", "label": "Сахарный диабет II типа", "value": 0, "name": "3"},
                    {"view": "checkbox", "label": "Хроническая обструктивная болезнь легких", "value": 0, "name": "4"},
                    {"view": "checkbox", "label": "Обструктивное апноэ сна", "value": 0, "name": "5"},
                    {"view": "checkbox", "label": "Хроническая болезнь легких", "value": 0, "name": "6"},
                    {"view": "text", "label": "Рост", "value": 0, "name": "101"},
                    {"view": "text", "label": "Вес", "value": 0, "name": "102"},
                    ]},
    {'group_label': "Вредные привычки и онкология",
     'group_data': [{"view": "checkbox", "label": "Алкоголь", "value": 0, "name": "11"},
                    {"view": "checkbox", "label": "Курение", "value": 0, "name": "12"},
                    {"view": "checkbox", "label": "Употребление наркотиков", "value": 0, "name": "13"},
                    ]},
    {'group_label': "Кардиология",
     'group_data': [{"view": "checkbox", "label": "Артериальная гипертензия", "value": 0, "name": "21"},
                    {"view": "checkbox", "label": "Ишемическая болезнь сердца", "value": 0, "name": "22"},
                    {"view": "checkbox", "label": "Сердечная недостаточность", "value": 0, "name": "23"},
                    {"view": "checkbox", "label": "Поражение клапанного аппарата сердца", "value": 0, "name": "24"},
                    {"view": "checkbox", "label": "Сердечная недостаточность", "value": 0, "name": "25"},
                    {"view": "checkbox", "label": "Кардиомиопатии", "value": 0, "name": "26"},
                    ]},

    {'group_label': "Пороки сердца",
     'group_data': [{"view": "checkbox", "label": "Дефект межпредсердной перегородки", "value": 0, "name": "31"},
                    {"view": "checkbox", "label": "Другие пороки сердца", "value": 0, "name": "32"},
                    ]},
    {'group_label': "Ритм и проводимость",
     'group_data': [{"view": "checkbox", "label": "Нарушения ритма", "value": 0, "name": "41"},
                    {"view": "checkbox", "label": "Нарушение проводимости", "value": 0, "name": "42"},
                    {"view": "checkbox", "label": "Генетическая/наследственная предрасположенность", "value": 0, "name":"43"},
                    ]},
]