#!/usr/bin/env python
import sys
py_v = sys.version_info[:2]
if not (py_v == (2, 7) or py_v >= (3, 3)):
    sys.exit('Only Python 2.7 or 3.3 and up are supported. Current version: ' + '.'.join(py_v))

package_name = 'clearup'

from ngs_utils import setup_utils
version = setup_utils.init(package_name, package_name, __file__)

from setuptools import setup, find_packages
setup(
    name=package_name,
    version=version,
    author='Vlad Saveliev, Tristan Lubinsky, Alla Miheenko',
    author_email='vladislav.sav@gmail.com',
    description='Mix up check tool',
    long_description=(open('README.md').read()),
    keywords='bioinformatics',
    url='https://github.com/AstraZeneca-NGS/ClearUp',
    license='GPLv3',
    packages=find_packages(),
    package_data={
        package_name:
            ['snps/*.bed.gz*'],
        '':
            setup_utils.find_package_files('static', '') +
            setup_utils.find_package_files('templates', ''),
    },
    include_package_data=True,
    zip_safe=False,
    scripts=['start.py', 'manage.py', 'genotyper.py'],
    install_requires=setup_utils.get_reqs(),
    classifiers=[
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
        'Natural Language :: English',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: POSIX',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: JavaScript',
        'Topic :: Scientific/Engineering',
        'Topic :: Scientific/Engineering :: Bio-Informatics',
    ],
    test_suite='nose.collector',
    tests_require=['nose'],
)

print("""
-------------------------
 Installation complete!
-------------------------
Usage:
$ ./manage.py init_db
$ ./manage.py load_bcbio_project <bcbio_final_path>
$ ./manage.py load_data <dir_with_bams_and_beds> name=<project_name> genome=<genome_build_name>
$ ./start.py
""")


import argparse
import os

VALID_RESOURCES = frozenset(
    ["deployments", "statefulsets", "stacks", "cronjobs", "horizontalpodautoscalers"]
)

def check_include_resources(value):
    resources = frozenset(value.split(","))
    if not resources <= VALID_RESOURCES:
        raise argparse.ArgumentTypeError(
            f"--include-resources argument should contain a subset of [{', '.join(sorted(VALID_RESOURCES))}]"
        )
    return value

def get_parser():
    parser = argparse.ArgumentParser()
    upscale_group = parser.add_mutually_exclusive_group(required=False)
    downscalescale_group = parser.add_mutually_exclusive_group(required=False)
    parser.add_argument(
        "--dry-run",
        help="Dry run mode: do not change anything, just print what would be done",
        action="store_true",
    )
    parser.add_argument(
        "--debug", "-d", help="Debug mode: print more information", action="store_true"
    )
    parser.add_argument(
        "--once", help="Run loop only once and exit", action="store_true"
    )
    parser.add_argument(
        "--interval", type=int, help="Loop interval (default: 30s)", default=30
    )
    parser.add_argument("--namespace", help="Namespace")
    parser.add_argument(
        "--include-resources",
        type=check_include_resources,
        default="deployments",
        help=f"Downscale resources of this kind as comma separated list. [{', '.join(sorted(VALID_RESOURCES))}] (default: deployments)",
    )
    parser.add_argument(
        "--grace-period",
        type=int,
        help="Grace period in seconds for deployments before scaling down (default: 15min)",
        default=900,
    )
    upscale_group.add_argument(
        "--upscale-period",
        help="Default time period to scale up once (default: never)",
        default=os.getenv("UPSCALE_PERIOD", "never"),
    )
    upscale_group.add_argument(
        "--default-uptime",
        help="Default time range to scale up for (default: always)",
        default=os.getenv("DEFAULT_UPTIME", "always"),
    )
    downscalescale_group.add_argument(
        "--downscale-period",
        help="Default time period to scale down once (default: never)",
        default=os.getenv("DOWNSCALE_PERIOD", "never"),
    )
    downscalescale_group.add_argument(
        "--default-downtime",
        help="Default time range to scale down for (default: never)",
        default=os.getenv("DEFAULT_DOWNTIME", "never"),
    )
    parser.add_argument(
        "--exclude-namespaces",
        help="Exclude namespaces from downscaling, comma-separated list of regex patterns (default: kube-system)",
        default=os.getenv("EXCLUDE_NAMESPACES", "kube-system"),
    )
    parser.add_argument(
        "--exclude-deployments",
        help="Exclude specific deployments from downscaling (default: kube-downscaler,downscaler)",
        default=os.getenv("EXCLUDE_DEPLOYMENTS", "kube-downscaler,downscaler"),
    )
    parser.add_argument(
        "--downtime-replicas",
        type=int,
        help="Default amount of replicas when downscaling (default: 0)",
        default=int(os.getenv("DOWNTIME_REPLICAS", 0)),
    )
    parser.add_argument(
        "--deployment-time-annotation",
        help="Annotation that contains a resource's last deployment time, overrides creationTime. Use in combination with --grace-period.",
    )
    parser.add_argument(
        "--enable-events",
        help="Emit Kubernetes events for scale up/down",
        action="store_true",
    )
    return parser


'''7) Faça um programa que o usuário informe a quantidade de alunos de uma turma, o sistema deve
ler o peso e altura de cada aluno, ao final informar a média dos pesos, alturas e imc.
8) o programa anterior, deve informar ao final o aluno com maior e menor imm'''
imc=0
mediaaltura=0
mediapeso=0
somaaltura=0
somapeso=0
altura=0
peso=0
i=1
aluno=int(input("informe a quantidade de alunos"))
for i in range (aluno):
    peso=float(input("informe o peso do aluno",))
    somapeso=somapeso+peso
    altura=int(input("informe a altura do aluno",))
    somaaltura=somaaltura+altura
    i=i+1
mediapeso=(mediapeso+somapeso)/aulo
mediaaltura=(mediaaltura+somaaltura)/aluno
imc=(somapesopeso/(somaaltura*somaaltura))/aluno
print("media dos pesos", mediapeso)
print("media das alturas", mediaaltura)
print("media dos imc", imc)


from django.test import TestCase
from api.models import Food
from api.models import Meal
from rest_framework.test import APIClient
from rest_framework import status
from django.urls import reverse
from rest_framework.test import APIRequestFactory
from api.views import FoodViews
class MealViewsTest(TestCase):
    """Test suite for the meal api views."""

    def setUp(self):
        """Define the test client and other test variables."""
        self.client = APIClient()
        self.apple = Food.objects.create(name="apple", calories=50)
        self.oatmeal = Food.objects.create(name="oatmeal", calories=400)
        self.breakfast = Meal.objects.create(name="breakfast")
        self.snack = Meal.objects.create(name="snack")
        self.lunch = Meal.objects.create(name="lunch")
        self.dinner = Meal.objects.create(name="dinner")
        self.breakfast.foods.add(self.apple)

    def test_gets_all_meals(self):
        response = self.client.get('/api/v1/meals/')
        js = response.json()
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(js), 4)
        self.assertEqual(js[0]["name"], self.breakfast.name)
        self.assertEqual(js[1]["name"], self.snack.name)
        self.assertEqual(js[2]["name"], self.lunch.name)
        self.assertEqual(js[3]["name"], self.dinner.name)

    def test_gets_single_meal(self):
        response = self.client.get(f'/api/v1/meals/{self.breakfast.id}/foods')

        meal_response = response.json()

        self.assertEqual(meal_response['name'], 'breakfast')
        self.assertEqual(meal_response['foods'][0]['name'], self.apple.name)
        self.assertEqual(meal_response['foods'][0]['calories'], self.apple.calories)

    def test_api_can_add_food_to_a_meal(self):
        """Test the api can add food to a meal capability."""
        response = self.client.post(f'/api/v1/meals/{self.breakfast.id}/foods/{self.oatmeal.id}')
        # import code; code.interact(local=dict(globals(), **locals()))

        self.assertEqual(response.data['message'], "Successfully added oatmeal to breakfast")

    def test_api_can_delete_food_from_a_meal(self):
        """Test the api can delete a food from a meal"""
        response = self.client.delete(f'/api/v1/meals/{self.breakfast.id}/foods/{self.apple.id}')
        # import code; code.interact(local=dict(globals(), **locals()))

        self.assertEqual(response.data['message'], "Successfully removed apple from breakfast")


# -*- coding: utf-8 -*
import os
import re
import numpy as np
import six
from PIL import Image
from itertools import chain
import glob
import time
import matplotlib.pylab as plt
from sklearn.datasets import fetch_mldata
import chainer
import chainer.links as L
import chainer.functions as F
from chainer import Chain, optimizers, Variable, serializers, iterators, training, datasets
from chainer.datasets import LabeledImageDataset, tuple_dataset
from chainer.training import extensions, triggers
from chainer.serializers import npz
from chainer.backends import cuda
from chainer import Function
from chainer import Link, ChainList
from chainer import cuda
from shuffle import shuffle
from augmentation import augmentation
from resize import resize
from excel import change_excel
from edit import edit_excel
from scale_augmentation import scale_data_augmentation
from count_image import count_image
from accuracy import accuracy
import xlwt
import shutil
import openpyxl as xl
from natsort import natsorted
from decimal import *

def image2Train(pathsAndLabels, channels=3):

    allData = []
    count_train_label = np.zeros(G)

    #データの追加(画像ファイル，ラベル)
    for pathsAndLabel in pathsAndLabels:
        path = pathsAndLabel[0]
        label = pathsAndLabel[1]
        imagelist = glob.glob(path + '*')
        count_train_label[int(label)] = len(imagelist)
        for imgName in imagelist:
            allData.append([imgName, label])
    allData = np.random.permutation(allData)#シャッフル

    #チャンネルが1の時は，画像ファイルとラベルデータに追加
    if channels == 1:
        imageData = []
        labelData = []
        for pathAndLabel in allData:
            img = Image.open(pathsAndLabel[0])
            imgData = np.asarray([np.float32(img)/255.0])#画像の正規化
            imageData.append(imgData)
            labelData.append(np.int32(pathsAndLabel[1]))

        threshold = np.int32(len(imageData)/8*7)#データの何割を教師データとテストデータにするか
        train = (imageData[0:threshold], labelData[0:threshold])
        test = (imageData[threshold:], labeData[threshold:])
    #RGBの時の処理
    else:
        imageData = []
        labelData = []
        for pathAndLabel in allData:
            img = Image.open(pathAndLabel[0])

            #新たに追加
            img = np.asarray(img, dtype=np.float32)
            img = img[:, :, ::-1]
            img -= np.array([103.939, 116.779, 123.68], dtype=np.float32)
            #print(img)
            img = img/255.0

            imageData.append(img)
            labelData.append(np.int32(pathAndLabel[1]))

        dataset = {}
        dataset['train_img'] = np.array(imageData[0:N]).transpose(0,3,1,2)
        dataset['train_label'] = np.array(labelData[0:N])

    return (dataset['train_img'], dataset['train_label']), count_train_label

def image2Test(pathsAndLabels, channels=3):

    allData = []
    count_test_label = np.zeros(G)

    #データの追加(画像ファイル，ラベル)
    for pathsAndLabel in pathsAndLabels:
        path = pathsAndLabel[0]
        label = pathsAndLabel[1]
        imagelist = glob.glob(path + '*')
        count_test_label[int(label)] = len(imagelist)
        for imgName in imagelist:
            allData.append([imgName, label])
    allData = np.random.permutation(allData)#シャッフル

    #チャンネルが1の時は，画像ファイルとラベルデータに追加
    if channels == 1:
        imageData = []
        labelData = []
        for pathAndLabel in allData:
            img = Image.open(pathsAndLabel[0])
            imgData = np.asarray([np.float32(img)/255.0])#画像の正規化
            imageData.append(imgData)
            labelData.append(np.int32(pathsAndLabel[1]))

        threshold = np.int32(len(imageData)/8*7)#データの何割を教師データとテストデータにするか
        train = (imageData[0:threshold], labelData[0:threshold])
        test = (imageData[threshold:], labeData[threshold:])
    #RGBの時の処理
    else:
        imageData = []
        labelData = []
        for pathAndLabel in allData:
            img = Image.open(pathAndLabel[0])

            #新たに追加
            img = np.asarray(img, dtype=np.float32)
            img = img[:, :, ::-1]
            img -= np.array([103.939, 116.779, 123.68], dtype=np.float32)
            img = img/255.0
            imageData.append(img)
            labelData.append(np.int32(pathAndLabel[1]))

        dataset = {}

        dataset['test_img'] = np.array(imageData[0:N_test]).transpose(0,3,1,2)
        dataset['test_label'] = np.array(labelData[0:N_test])

    return (dataset['test_img'], dataset['test_label']), count_test_label

class CNN(Chain):
    def __init__(self):
        super(CNN, self).__init__(
            conv1 = L.Convolution2D(3, 40, 15), # 入力:3 , 出力:40。両方記述。filter 5
            conv2 = L.Convolution2D(40, 50, 15), # 入力:40 , 出力:50。両方記述。filter 5
            l1 = L.Linear(None, 500),  # ここの入力の計算は以下の参考HPを参照。
            l2 = L.Linear(500, 500),
            l3 = L.Linear(500, G, initialW=np.zeros((G, 500), dtype=np.float32))#ここの値は設定する出力の数によって変更
        )
    def forward(self, x, ratio = 0.1):
        h = F.max_pooling_2d(F.relu(self.conv1(x)), 2)
        h = F.max_pooling_2d(F.relu(self.conv2(h)), 2)
        h = F.dropout(F.relu(self.l1(h)), ratio)
        h = F.dropout(F.relu(self.l2(h)), ratio)
        h = self.l3(h)
        return h

class VGG(chainer.Chain):
    def __init__(self, class_labels, pretrained_model='VGG_ILSVRC_16_layers.npz'):
        super(VGG, self).__init__()
        with self.init_scope():
            self.base = BaseVGG()
            self.fc6 = L.Linear(None, 793, initialW=chainer.initializers.HeNormal())
            self.fc7 = L.Linear(None, 252, initialW=chainer.initializers.HeNormal())
            self.fc8 = L.Linear(None, class_labels, initialW=chainer.initializers.HeNormal())
        npz.load_npz(pretrained_model, self.base)

    def __call__(self, x, t):
        h = self.predict(x)
        loss = F.softmax_cross_entropy(h,t)
        chainer.report({'loss': loss, 'accuracy': F.accuracy(h,t)}, self)
        return loss

    def predict(self, x):
        h = self.base(x)
        h = F.relu(self.fc6(h))
        h = F.relu(self.fc7(h))
        h = self.fc8(h)
        return h

class BaseVGG(Chain):
    def __init__(self):
        super(BaseVGG, self).__init__()
        with self.init_scope():
            self.conv1_1 = L.Convolution2D(None, 64, 3, 1, 1)
            self.conv1_2 = L.Convolution2D(64, 64, 3, 1, 1)
            self.conv2_1 = L.Convolution2D(64, 128, 3, 1, 1)
            self.conv2_2 = L.Convolution2D(128, 128, 3, 1, 1)
            self.conv3_1 = L.Convolution2D(128, 256, 3, 1, 1)
            self.conv3_2 = L.Convolution2D(256, 256, 3, 1, 1)
            self.conv3_3 = L.Convolution2D(256, 256, 3, 1, 1)
            self.conv4_1 = L.Convolution2D(256, 512, 3, 1, 1)
            self.conv4_2 = L.Convolution2D(512, 512, 3, 1, 1)
            self.conv4_3 = L.Convolution2D(512, 512, 3, 1, 1)
            self.conv5_1 = L.Convolution2D(512, 512, 3, 1, 1)
            self.conv5_2 = L.Convolution2D(512, 512, 3, 1, 1)
            self.conv5_3 = L.Convolution2D(512, 512, 3, 1, 1)

    def __call__(self, x):
        h = F.relu(self.conv1_1(x))
        h = F.relu(self.conv1_2(h))
        h = F.max_pooling_2d(h, ksize=2, stride=2)

        h = F.relu(self.conv2_1(h))
        h = F.relu(self.conv2_2(h))
        h = F.max_pooling_2d(h, ksize=2, stride=2)

        h = F.relu(self.conv3_1(h))
        h = F.relu(self.conv3_2(h))
        h = F.relu(self.conv3_3(h))
        h = F.max_pooling_2d(h, ksize=2, stride=2)

        h = F.relu(self.conv4_1(h))
        h = F.relu(self.conv4_2(h))
        h = F.relu(self.conv4_3(h))
        h = F.max_pooling_2d(h, ksize=2, stride=2)

        h = F.relu(self.conv5_1(h))
        h = F.relu(self.conv5_2(h))
        h = F.relu(self.conv5_3(h))
        h = F.max_pooling_2d(h, ksize=2, stride=2)

        return h

if __name__ == '__main__':
    print('class_labels変更した?')
    #以下パラメータの設定
    k = 10 #試行回数
    n_epoch = 20 #更新回数
    batch_size = 125 #バッチサイズ
    batch_size_predict = 1
    cnt_trial = 1#試行回数ごとの写真フォルダ分けに使用
    h = 90#入力画像の高さ
    w = 78#入力画像の幅
    gpu = 0 #GPUを用いるなら0,CPUなら-1
    N_test = 793#テスト画像枚数(ここの数字は再確認)

    #以下扱うディレクトリのパス設定
    input_dir = 'C:\\Users\\user\\Desktop\\input'#入力教師用画像フォルダ
    input_testing_dir = 'C:\\Users\\user\\Desktop\\input_test'#入力評価用画像フォルダ
    main_dir = 'C:\\Users\\user\\Desktop\\main'#mainフォルダ
    result_dir = 'C:\\Users\\user\\Desktop\\result'#結果フォルダ

    #main_dirがなければ作成
    if not os.path.exists(main_dir):
        os.mkdir(main_dir)

    #result_dirがなければ作成
    if not os.path.exists(result_dir):
        os.mkdir(result_dir)

    #誤判別時の画像出力フォルダ作成
    miss_judge_train_dir = os.path.join(result_dir, 'miss_judge_train')
    miss_judge_test_dir = os.path.join(result_dir, 'miss_judge_test')

    #誤班別時画像出力フォルダがなければ，作成
    if not os.path.exists(miss_judge_train_dir):
        os.mkdir(miss_judge_train_dir)
    if not os.path.exists(miss_judge_test_dir):
        os.mkdir(miss_judge_test_dir)
    for j in range(1, k+1):
        if not os.path.exists(os.path.join(miss_judge_train_dir, str(j)+'_trial')):
            os.mkdir(os.path.join(miss_judge_train_dir, str(j)+'_trial'))
        if not os.path.exists(os.path.join(miss_judge_test_dir, str(j)+'_trial')):
            os.mkdir(os.path.join(miss_judge_test_dir, str(j)+'_trial'))
        for l in range(1, n_epoch+1):
            if not os.path.exists(os.path.join(os.path.join(miss_judge_train_dir, str(j)+'_trial'), str(l))):
                os.mkdir(os.path.join(os.path.join(miss_judge_train_dir, str(j)+'_trial'), str(l)))
            if not os.path.exists(os.path.join(os.path.join(miss_judge_test_dir, str(j)+'_trial'), str(l))):
                os.mkdir(os.path.join(os.path.join(miss_judge_test_dir, str(j)+'_trial'), str(l)))

    #正解時の画像出力フォルダ作成
    correct_judge_train_dir = os.path.join(result_dir, 'correct_judge_train')
    correct_judge_test_dir = os.path.join(result_dir, 'correct_judge_test')

    #正解判別時画像出力フォルダがなければ，作成
    if not os.path.exists(correct_judge_train_dir):
        os.mkdir(correct_judge_train_dir)
    if not os.path.exists(correct_judge_test_dir):
        os.mkdir(correct_judge_test_dir)
    for j in range(1,k+1):
        if not os.path.exists(os.path.join(correct_judge_train_dir, str(j)+'_trial')):
            os.mkdir(os.path.join(correct_judge_train_dir, str(j)+'_trial'))
        if not os.path.exists(os.path.join(correct_judge_test_dir, str(j)+'_trial')):
            os.mkdir(os.path.join(correct_judge_test_dir, str(j)+'_trial'))
        for l in range(1, n_epoch+1):
            if not os.path.exists(os.path.join(os.path.join(correct_judge_train_dir, str(j)+'_trial'), str(l))):
                os.mkdir(os.path.join(os.path.join(correct_judge_train_dir, str(j)+'_trial'), str(l)))
            if not os.path.exists(os.path.join(os.path.join(correct_judge_test_dir, str(j)+'_trial'), str(l))):
                os.mkdir(os.path.join(os.path.join(correct_judge_test_dir, str(j)+'_trial'), str(l)))

    #以下訓練と評価
    for i in range(1, k+1):
        start_time = time.clock()
        book = xlwt.Workbook()
        print(str(i) + '_trial')
        #試行ごとのフォルダ作成
        current_dir = os.path.join(main_dir, str(i)+'_trial')
        if not os.path.exists(current_dir):
            os.mkdir(current_dir)

        #試行ごとの結果フォルダ作成
        current_result_dir = os.path.join(result_dir, str(i)+'_trial')
        if not os.path.exists(current_result_dir):
            os.mkdir(current_result_dir)

        train_dir = os.path.join(current_dir, 'training')
        test_dir = os.path.join(current_dir, 'testing')

        #shuffleにより評価用画像枚数を返す．
        #N_testはテスト枚数,flagが0ならinputdirから教師用とテスト用に8:2でわける．flagが1なら教師用フォルダから教師用に，評価用フォルダから評価用にわける．

        #N_test = shuffle(input_dir, current_dir, flag = 0)
        N_test = shuffle(input_dir, current_dir, input_testing_dir, flag = 1)#N_test:評価用画像枚数

        #scale_augmentationの実行
        scale_data_augmentation(os.path.join(train_dir, 'image1'), os.path.join(train_dir, 'image2'), (h,w))

        #resizeの実行
        resize(os.path.join(train_dir, 'image2'), os.path.join(train_dir, 'image3'), h, w)
        resize(os.path.join(test_dir, 'image1'), os.path.join(test_dir, 'image2'), h, w)

        #data augmentationの実行
        augmentation(os.path.join(train_dir, 'image3'), os.path.join(train_dir, 'image4'), (h,w))

        #count_imageの実行
        #これにより教師用画像枚数とグループ数取得
        N, G = count_image(os.path.join(train_dir, 'image4'))
        print("N:" + str(N))
        print("N_test:" + str(N_test))

        #画像フォルダのパス
        IMG_DIR_train = os.path.join(train_dir, 'image4')
        IMG_DIR_test = os.path.join(test_dir, 'image2')

        #各グループのパス
        dnames_train = glob.glob('{}/*'.format(IMG_DIR_train))
        dnames_train = sorted(dnames_train, key=lambda s: int(re.search(r'\d+', s).group()))
        dnames_test = glob.glob('{}/*'.format(IMG_DIR_test))
        dnames_test = sorted(dnames_test, key=lambda s: int(re.search(r'\d+', s).group()))

        #画像ファイルパス一覧
        fnames_train = [glob.glob('{}/*.jpg'.format(d)) for d in dnames_train]
        fnames_train = list(chain.from_iterable(fnames_train))
        fnames_test = [glob.glob('{}/*.jpg'.format(d)) for d in dnames_test]
        fnames_test = list(chain.from_iterable(fnames_test))

        # それぞれにフォルダ名から一意なIDを付与し、画像を読み込んでデータセット作成
        labels_train = [os.path.basename(os.path.dirname(fn)) for fn in fnames_train]
        dnames_train = [os.path.basename(d) for d in dnames_train]
        labels_train = [dnames_train.index(l) for l in labels_train]
        d_train = LabeledImageDataset(list(zip(fnames_train, labels_train)))

        labels_test = [os.path.basename(os.path.dirname(fn)) for fn in fnames_test]
        dnames_test = [os.path.basename(d) for d in dnames_test]
        labels_test = [dnames_test.index(l) for l in labels_test]
        d_test = LabeledImageDataset(list(zip(fnames_test, labels_test)))

        #VGG用の前処理関数
        def transform(data):
            img, label = data
            img = L.model.vision.vgg.prepare(img, size=(h, w))
            img = img / 255. #正規化する．0〜1に落とし込む
            return img, label

        train = chainer.datasets.TransformDataset(d_train, transform)
        test = chainer.datasets.TransformDataset(d_test, transform)

        model = VGG(class_labels = G)

        #GPUの設定
        if gpu >= 0:
            print('GPUを用います')
            cuda.get_device(0).use()
            model.to_gpu(0)

        optimizer = optimizers.Adam() # 最適化関数
        optimizer.setup(model)
        # model.base.disable_update()

        #ラベルごとのトータル誤判別数
        miss_train_total = np.zeros(G)
        miss_test_total = np.zeros(G)

        #ラベルごとのトータル正解数
        correct_train_total = np.zeros(G)
        correct_test_total = np.zeros(G)

        #何を何と判別したか2次元配列
        miss_train_judge = np.zeros([G,G])#ここも
        miss_test_judge = np.zeros([G,G])

        cnt_train = 0#画像を保存するように使用
        cnt_test = 0#画像を保存するときの数
        cnt_train_correct_judge = 0
        cnt_test_correct_judge =0

        print(str(i)+'_trial')
        #エクセル書き込み
        sheet = book.add_sheet(str(i)+'_trial')
        sheet.write(1, 0, '教師用')
        sheet.write(2, 0, '評価用')
        sheet.write(6, 0, '教師用')
        sheet.write(6, G+3, '評価用')

        #葉齢ごとの判別率
        for l in range(0, G):
            sheet.write(7, l+1, 'stage'+str(l))

        for l in range(0, G):
            sheet.write(7, l+G+4, 'stage'+str(l))

        sheet.write(n_epoch+15, 0, '誤判別のやーつ(教師用)')
        sheet.write(n_epoch+15, 3, '誤判別先')
        for l in range(0,G):
            sheet.write(n_epoch+16, l+1, l)
            sheet.write(n_epoch+l+17, 0, l)

        sheet.write(n_epoch+15, G+3, '誤判別のやーつ(評価用)')
        for l in range(0, G):
            sheet.write(n_epoch+16, l+G+4, l)
            sheet.write(n_epoch+l+17, G+3, l)

        #trainer周りの設定
        train_iter = iterators.SerialIterator(train, batch_size)
        test_iter = iterators.SerialIterator(test, 1, repeat=False, shuffle=False)

        updater = training.StandardUpdater(train_iter, optimizer, device = gpu)
        trainer = training.Trainer(updater, (n_epoch, 'epoch'), out=current_result_dir)

        trainer.extend(extensions.dump_graph('main/loss'))
        #trainer.extend(extensions.snapshot(), trigger=(epoch, 'epoch'))
        trainer.extend(extensions.LogReport())
        trainer.extend(extensions.observe_lr())
        trainer.extend(extensions.PrintReport(
            ['epoch',
            'main/loss',
            'main/accuracy',
            'test/main/loss',
            'test/main/accuracy',
            'elapsed_time',
            'lr',], sheet = sheet, flag = 1))
        trainer.extend(extensions.ProgressBar(update_interval=1))
        trainer.extend(extensions.Evaluator(test_iter, model, device = gpu), name='test')

        trainer.extend(extensions.PlotReport(['main/loss'], 'epoch', file_name='main_loss.png', marker = ''))
        trainer.extend(extensions.PlotReport(['main/accuracy'], 'epoch', file_name='main_accuracy.png'))
        trainer.extend(extensions.PlotReport(['test/main/loss'], 'epoch', file_name='test_loss.png'))
        trainer.extend(extensions.PlotReport(['test/main/accuracy'], 'epoch', file_name='test_accuracy.png'))
        trainer.extend(extensions.PlotReport(['main/loss', 'test/main/loss'], x_key='epoch', file_name='loss.png', marker=""))
        trainer.extend(extensions.PlotReport(['main/accuracy', 'test/main/accuracy'], x_key='epoch', file_name='accuracy.png', marker=""))

        #trainer.extend(extensions.ExponentialShift('lr', lr_drop_ratio),trigger=(lr_drop_epoch, 'epoch'))

        trainer.run()

        paths = []

        for j in range(0, G):
            if j < 10:
                paths.append(np.asarray([os.path.join(os.path.join(test_dir, 'image2'), 'stage0'+str(j)+'\\'), j]))
            else:
                paths.append(np.asarray([os.path.join(os.path.join(test_dir, 'image2'), 'stage'+str(j)+'\\'), j]))

        (x_test, t_test), correct_test_label = image2Test(paths)

        #以下正確なaccuracyを求めるため
        test_loss = 0
        test_accuracy = 0
        miss_train_copy = miss_train_total.copy()
        miss_test_copy = miss_test_total.copy()
        correct_train_copy = correct_train_total.copy()
        correct_test_copy = correct_test_total.copy()

        for i in range(0, N_test, batch_size_predict):
            x = Variable(cuda.to_gpu(x_test[i:i+batch_size_predict]))#評価画像データ
            t = Variable(cuda.to_gpu(t_test[i:i+batch_size_predict]))#評価ラベル
            y = model.predict(x)
            model.zerograds()
            loss = F.softmax_cross_entropy(y, t)

            #こっから誤判別を特定するプログラム
            acc, data, data2, index, pred, corre, correct_index  = accuracy(y, t)
            acc.to_cpu()
            data.to_cpu()
            data2.to_cpu()
            index.to_cpu()
            pred.to_cpu()
            corre.to_cpu()
            correct_index.to_cpu()
            t.to_cpu()
            x.to_cpu()
            for i in range(len(data.data)):
                miss_test_total[data.data[i]] += 1
                miss_test_judge[data.data[i]][data2.data[i]] += 1

            for i in range(len(corre.data)):
                correct_test_total[corre.data[i]] += 1

            #こっからは誤判別した画像を出力するプログラム(最終更新時のみ)
            for inde in index.data:
                e = np.array(x.data[inde])
                b = np.array(e[0])#青色
                g = np.array(e[1])#緑色
                r = np.array(e[2])#赤色
                img = np.dstack((np.dstack((r,g)),b))

                #print(img)
                img = img * 255.0
                img += np.array([123.68, 116.779, 103.939], dtype=np.float32)
                img = img/255.0
                #print(img)
                plt.imsave(os.path.join(miss_judge_test_dir, str(cnt_trial)+'_trial\\'+str(n_epoch)+'\\'+str(cnt_test)+ '_epoch_' +str(n_epoch)+'_'+str(t.data[inde])+'to'+str(pred.data[inde])+'.jpg'), img)
                cnt_test += 1
            for correct_inde in correct_index.data:
                c_e = np.array(x.data[correct_inde])
                c_b = np.array(c_e[0])#青色
                c_g = np.array(c_e[1])#緑色
                c_r = np.array(c_e[2])#赤色
                c_img = np.dstack((np.dstack((c_r,c_g)),c_b))

                c_img = c_img * 255.0
                c_img += np.array([123.68, 116.779, 103.939], dtype=np.float32)
                c_img = c_img/255.0
                plt.imsave(os.path.join(correct_judge_test_dir, str(cnt_trial)+'_trial\\'+str(n_epoch)+'\\'+str(cnt_test_correct_judge)+'_epoch_'+str(n_epoch)+'_'+str(t.data[correct_inde])+'to'+str(pred.data[correct_inde])+'.jpg'), c_img)
                cnt_test_correct_judge += 1

            test_loss += loss.data*len(t.data)
            test_accuracy += acc.data*len(t.data)

            miss_test_each = miss_test_total - miss_test_copy
            correct_test_each = correct_test_total - correct_test_copy

        #ターミナル上に出力
        print("test acc:{:.04f}".format(test_accuracy/N_test))
        print('miss_test_total : ' + str(miss_test_total))
        print('miss_test_each :' + str(miss_test_each))
        print('correct_test_each :' + str(correct_test_each))
        print()

        # sheet.write(0, 1, n_epoch)#単純にエポック数(現時点)
        sheet.write(3, n_epoch, Decimal(test_accuracy/N_test).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP))#評価用画像の判別率

        sheet.write((n_epoch + 7), 0, n_epoch)
        sheet.write((n_epoch + 7), G+3, n_epoch)
        for i in range(len(correct_test_each)):
            if correct_test_label[i] != 0:
                sheet.write((n_epoch + 7), (i + G+4), Decimal(correct_test_each[i]/correct_test_label[i]).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP))

        #最終epochの誤判定時における、何が何を予測したのかを表示
        for i in range(0, G):
            for j in range(0,G):
                if j==i:
                    sheet.write((n_epoch+17+i), (i+G+4), correct_test_each[i])
                else:
                    sheet.write((n_epoch+17+i), (j+G+4), miss_test_judge[i][j])

        #ここから先は前後のラベルを含んだ判別率を求める．
        num_zengo = np.zeros(G)#前後を含んだ正解数
        for i in range(0, G):
            if i == 0:
                num_zengo[i] = correct_test_each[i] + miss_test_judge[i][i+1]
            elif i == (G-1):
                num_zengo[i] = correct_test_each[i] + miss_test_judge[i][i-1]
            else:
                num_zengo[i] = correct_test_each[i] + miss_test_judge[i][i-1] + miss_test_judge[i][i+1]

        #num_zengoの出力とラベルごとの前後を含んだ判別率の出力
        for i in range(len(num_zengo)):
            if correct_test_label[i] != 0:
                sheet.write((n_epoch + 8), (i + G + 4), num_zengo[i])
                sheet.write((n_epoch + 9), (i + G + 4), Decimal(num_zengo[i]/correct_test_label[i]).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP))

        #最後に前後を含んだ評価用画像の判別率を算出し，出力
        num_zengo_total = 0
        for i in range(0, G):
            num_zengo_total += num_zengo[i]
        sheet.write(4, n_epoch, Decimal(num_zengo_total/N_test).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP))

        cnt_trial+=1
        end_time = time.clock()
        sheet.write(0,0,end_time-start_time)
        print(end_time - start_time)

        serializers.save_npz(os.path.join(current_result_dir, 'model.npz'), model)
        # shutil.rmtree(train_dir)#必要ならData augmentaion後の教師画像フォルダの削除

        book.save(os.path.join(result_dir, 'result'+str(cnt_trial-1)+'_trial.xls'))

        change_excel(os.path.join(result_dir, 'result'+str(cnt_trial-1)+'_trial.xls'))
        os.remove(os.path.join(result_dir, 'result'+str(cnt_trial-1)+'_trial.xls'))

    excel_names = glob.glob(os.path.join(result_dir, "*.xlsx"))
    ordered_excel = natsorted(excel_names)

    outfile = os.path.join(result_dir, 'result.xlsx')
    wb2 = xl.Workbook()
    wb2.save(outfile)
    print(str(ordered_excel))
    for i, inputfile in enumerate(ordered_excel):
        print(str(i))
        sheettitle = str(i+1) + '_trial'
        print(sheettitle)
        print(str(inputfile))

        wb1 = xl.load_workbook(filename = inputfile)
        ws1 = wb1.worksheets[0]

        wb = xl.load_workbook(filename = outfile)
        if i > 0:
            wb.create_sheet()
        ws = wb.worksheets[i]
        ws.title = sheettitle

        for row in ws1:
            for cell in row:
                ws[cell.coordinate].value = cell.value

        wb.save(outfile)


from multiprocessing.connection import wait
from emails import emails
from jokes import joke_list
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import random
import time

#getting random joke
num = random.randint(0,59)
joke = joke_list[num]

#getting a random email
rand_email = random.randint(0,9)
email = emails[rand_email]

#setting driver to firefox and going to nate's site
PATH = "/usr/local/bin/chromedriver"
driver = webdriver.Chrome(PATH)
driver.get("https://apexsoccer.org")

#enter eric jones into nate's "Name" field of his user form
elem = driver.find_element(By.ID, "form-field-name")
elem.clear()
elem.send_keys("Eric Jones")

#enter a ridiculous email into the "Email field"
second_elem = driver.find_element(By.ID, "form-field-email")
second_elem.clear()
second_elem.send_keys(email)

#enter the joke into the message field and submit
third_elem = driver.find_element(By.ID, "form-field-6ed25c0")
third_elem.clear()
third_elem.send_keys(joke)

click_elem = driver.find_element(By.TAG_NAME, "button")
click_elem.click()

time.sleep(3)
#close my connection
driver.close()


class BinarySearchNode:
    def __init__(self,data):
        self.data=data
        self.left=None
        self.right=None

    def add_child(self,data):
        if data == self.data:
            return

        if data < self.data:
            if self.left:
                self.left.add_child(data)
            else:
                self.left = BinarySearchNode(data)

        else:
            if self.right:
                self.right.add_child(data)
            else:
                self.right = BinarySearchNode(data)

    def in_order_traversal(self):
        elements = []

        if self.left:
            elements += self.left.in_order_traversal()

        elements.append(self.data)

        if self.right:
            elements += self.right.in_order_traversal()

        return elements

    def search(self,val):
        if self.data == val:
            return True

        if val < self.data:
            if self.left:
                return self.left.search(val)
            else:
                return False

        if val > self.data:
            if self.right:
                return self.right.search(val)
            else:
                return False

def build_tree(elements):
    root = BinarySearchNode(elements[0])

    for i in range(1,len(elements)):
        root.add_child(elements[i])

    return root

if __name__ ==  '__main__':
    countries = ["India","Pakistan","Germany","USA","China","India","UK","USA"]
    country_tree = build_tree(countries)
    print(country_tree.in_order_traversal())
    print("is UK in the list?",country_tree.search("UK"))
    print("is in the list?",country_tree.search("Sweden"))


__author__ = 'saeedamen' # Saeed Amen

#
# Copyright 2016 Cuemacro
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and limitations under the License.
#

"""
TickerFactory

Creating lists of tickers from a shortcuts.

"""

import pandas
import numpy

from findatapy.util.loggermanager import LoggerManager

class TickerFactory(object):

    def create_ticker(self, csv_file, out_csv_file):
        # reader = csv.DictReader(open(csv_file))

        data_frame = pandas.read_csv(csv_file, dtype=object)

        rows = 100000
        # category	source	freq	ticker	cut	fields	sourceticker

        data_frame_out = pandas.DataFrame(index=numpy.arange(0, rows),
                                          columns=('category', 'source', 'freq', 'ticker', 'cut', 'fields', 'sourceticker'))
        i = 0

        for category_source_freq_fields in data_frame['category.source.freq.fields']:
            if isinstance(category_source_freq_fields, str):
                spl = category_source_freq_fields.split('.')
                category = spl[0]
                source = spl[1]
                freq = spl[2]
                fields = spl[3]

                for cut_postfix in data_frame['cut.postfix']:
                    if isinstance(cut_postfix, str):
                        spl1 = cut_postfix.split('.')
                        cut = spl1[0]
                        postfix = spl1[1]
                        for ticker in data_frame['ticker']:
                            if isinstance(ticker, str):
                                if 'midfix' in data_frame.columns:
                                    for midfix in data_frame['midfix']:
                                        if isinstance(midfix, str):
                                            for postmidfix in data_frame['postmidfix']:
                                                if isinstance(postmidfix, str):
                                                    ticker_ext = ticker + midfix + postmidfix
                                                    sourceticker = ticker + midfix + postmidfix + ' ' + postfix
                                                    data_frame_out.loc[i] = [category, source, freq, ticker_ext,
                                                                             cut, fields, sourceticker]

                                                    i = i + 1
                                else:
                                    for postmidfix in data_frame['postmidfix']:
                                        if isinstance(postmidfix, str):
                                            ticker_ext = ticker + postmidfix
                                            sourceticker = ticker + postmidfix + ' ' + postfix
                                            data_frame_out.loc[i] = [category, source, freq, ticker_ext, cut, fields,
                                                                     sourceticker]

                                            i = i + 1

        data_frame_out = data_frame_out[0:i]

        data_frame_out.to_csv(out_csv_file)

        # for line in reader:
        #     category = line["category"]
        #     source = line["source"]
        #     freq = line["freq"]
        #     ticker = line["ticker"]
        #     cut = line["cut"]
        #     sourceticker = line["sourceticker"]

if __name__ == '__main__':

    logger = LoggerManager.getLogger(__name__)

    tf = TickerFactory()
    root = 'E:/Remote/canary/conf'

    csv_file = root + '/fx_vol_tickers_maker.csv'
    out_csv_file = root + '/fx_vol_tickers.csv'

    tf.create_ticker(csv_file, out_csv_file)

    csv_file = root + '/fx_forwards_tickers_maker.csv'
    out_csv_file = root + '/fx_forwards_tickers.csv'

    tf.create_ticker(csv_file, out_csv_file)


"""Storage application views."""
import json
import logging
import re
import tempfile
from datetime import datetime
from distutils.util import strtobool
from functools import lru_cache
from pathlib import Path
from typing import Dict, List, Tuple, Union
from urllib.parse import urlencode, urlparse

import pytz
from bs4 import BeautifulSoup

from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils import timezone
from django.views import View

from rest_framework.response import Response
from rest_framework.viewsets import ViewSet

from resolwe.flow.models import Data
from resolwe.flow.models.collection import Collection
from resolwe.permissions.utils import get_user
from resolwe.storage.connectors import connectors
from resolwe.storage.connectors.baseconnector import BaseStorageConnector
from resolwe.storage.models import FileStorage, ReferencedPath

logger = logging.getLogger(__name__)

class UploadConfig(ViewSet):
    """Get the upload configuration."""

    def list(self, request):
        """Return the JSON representing the upload configuration.

        The returning object is JSON representation of the dictionary with the
        following fields:

        - type: the type of upload connector. Currently we
          support 'LOCAL', and 'S3' connector types. Upload through server is
          always supported.

        - credentials: the dictionary representing the set of credentials that
          are used to upload data. This dictionary is specific to connector
          type and may be empty.
        """
        try:
            upload_connector = connectors.for_storage("upload")[0]
            prefix = str(get_user(request.user).id)
            response = {
                "type": upload_connector.CONNECTOR_TYPE.name,
                "config": upload_connector.temporary_credentials(prefix),
            }
        except Exception:
            message = "Upload connector could not be determined."
            logger.exception(message)
            raise ImproperlyConfigured(message)

        return Response(response)

class DataBrowseView(View):
    """Emulate nginx JSON directory view of the data directory.

    Use information in database to construct JSON response that emulates nginx
    autoindex module with autoindex_format set to json. See
    http://nginx.org/en/docs/http/ngx_http_autoindex_module.html
    for details.
    """

    def _get_mtime(self, entry: datetime) -> str:
        """Convert datetime entry to nginx autoindex compatible string.

        The timezone returned by autoindex module was set to GMT so we convert
        from our timetone to GMT.
        """
        gmt = timezone.localtime(entry, pytz.timezone("GMT"))
        return gmt.strftime("%a, %d %b %Y %H:%M:%S %Z")

    def _path_to_dict(
        self, referenced_path: ReferencedPath, base_path: Union[str, Path]
    ) -> Dict[str, Union[str, int]]:
        """Convert ReferencedPath to dictionary emulating nginx response."""
        assert referenced_path.file_storage is not None
        data = {
            "name": Path(referenced_path.path).relative_to(base_path).as_posix(),
            "type": "file",
            "mtime": self._get_mtime(referenced_path.file_storage.created),
            "size": referenced_path.size,
            "md5": referenced_path.md5,
        }
        if referenced_path.path.endswith("/"):
            data.pop("size")
            data["type"] = "directory"
        return data

    def _get_datum(self, data_id: int) -> Data:
        """Get datum with given id and check it's permissions."""
        # Check permissions and load requested data object.
        data = Data.objects.filter(pk=data_id).filter_for_user(self.request.user)
        # Send response with status 403 when requested data object does not exists.
        if not data.exists():
            raise PermissionDenied()

        return data.get()

    def _resolve_dir(
        self, relative_path: Path, file_storage: FileStorage
    ) -> List[Dict[str, Union[str, int]]]:
        """Resolve directory."""
        # Empty path evaluates to "."
        regex_path = relative_path.as_posix() + "/" if relative_path != Path() else ""
        # Show only entries in this directory.
        regex = "^{}[^/]+/?$".format(regex_path)
        return [
            self._path_to_dict(path, regex_path)
            for path in file_storage.files.filter(path__regex=regex)
        ]

    def _resolve_file(self, relative_path: Path, file_storage: FileStorage) -> str:
        """Resolve file URI and return signed url.

        :raises PermissionDenied: if presigned URL could not be generated.
        """
        # Redirect to the resource.
        force_download = strtobool(self.request.GET.get("force_download", "false"))
        default_storage_location = file_storage.default_storage_location
        assert default_storage_location is not None
        presigned_url = default_storage_location.connector.presigned_url(
            file_storage.subpath / relative_path, force_download=force_download
        )
        if presigned_url is None:
            raise PermissionDenied()

        return presigned_url

    def _get_response(
        self, datum: Data, relative_path: Path
    ) -> Tuple[Union[str, list], bool]:
        """Return a (response, is_file) tuple.

        :raises PermissionDenied: when path can not be resolved.
        """
        file_storage: FileStorage = datum.location

        if (
            relative_path == Path()
            or file_storage.files.filter(path=relative_path.as_posix() + "/").exists()
        ):
            # If directory
            return (self._resolve_dir(relative_path, file_storage), False)
        elif file_storage.files.filter(path=relative_path.as_posix()).exists():
            # If file
            return (self._resolve_file(relative_path, file_storage), True)

        raise PermissionDenied()

    def get(
        self, request: HttpRequest, *args: Union[str, int], **kwargs: Union[str, int]
    ) -> HttpResponse:
        """Giver URL either redirect to resource or serve a list of resources.

        If URL points to a file then redirect to a default storage location.
        If URL points to a directory then send a JSON encoded list of entires
        in this directory emulating nginx autoindex module.

        :param request: the given request. When the user requests URL
            http://platform-centos.genialis.local/data/1/..., then the value of
            parameter should be 1/... .
        """

        data_id = int(kwargs["data_id"])
        relative_path = str(kwargs.get("uri", ""))
        if Path(urlparse(relative_path).path).suffix in [".html", ".htm"]:
            redirect_url = reverse("HTMLPreprocessorView", args=args, kwargs=kwargs)
            arguments = urlencode(request.GET)
            if arguments:
                redirect_url = f"{redirect_url}?{arguments}"
            return redirect(redirect_url)

        datum = self._get_datum(data_id)
        response, is_file = self._get_response(datum, Path(relative_path))
        if is_file:
            return redirect(response)
        elif response:
            return JsonResponse(response, safe=False)
        else:
            raise PermissionDenied()

class HTMLPreprocessorView(DataBrowseView):
    """Serve HTML files.

    Pull the file to the server, pre-sign all the links in the file (including
    CSS and Javascript) and serve the modified file.
    """

    def get(
        self, request: HttpRequest, *args: Union[str, int], **kwargs: Union[str, int]
    ) -> HttpResponse:
        """Serve transformed HTML."""

        def _process_url(
            url: str, from_connector: BaseStorageConnector, subpath: Path
        ) -> str:
            """Presign URL if necessary."""
            parsed_url = urlparse(url)
            # We have to process link when it is relative (no scheme and no
            # netloc is given). Is should also not be anchor link (no path).
            if parsed_url.scheme or parsed_url.netloc or not parsed_url.path:
                return url

            # HTML files should be redirected to HTMLProcessor view.
            if Path(parsed_url.path).suffix in [".htm", ".html"]:
                return reverse("HTMLPreprocessorView", args=args, kwargs=kwargs)
            else:
                presigned_url = from_connector.presigned_url(
                    subpath / url, expiration=3600
                )
                if presigned_url is None:
                    raise RuntimeError(
                        "Unable to presign URL {url} for data object with id {subpath}."
                    )
                return presigned_url

        data_id = int(kwargs["data_id"])
        relative_path = Path(str(kwargs.get("uri", "")))
        assert relative_path.suffix in [
            ".html",
            ".htm",
        ], f"Only HTML files can be served, {relative_path} requested."
        datum = self._get_datum(data_id)
        subpath = Path(datum.location.subpath)
        from_connector = datum.location.default_storage_location.connector
        # Temporary file is opened with mode 'w+b' by default.
        with tempfile.SpooledTemporaryFile() as stream:
            from_connector.get(subpath / relative_path, stream)
            stream.seek(0)
            soup = BeautifulSoup(stream)
            tags_attributes = {
                "a": "href",
                "link": "href",
                "script": "src",
                "img": "src",
            }
            for tag in soup.findAll(list(tags_attributes.keys())):
                attribute = tags_attributes[tag.name]
                if attribute in tag.attrs:
                    tag[attribute] = _process_url(
                        tag[attribute], from_connector, subpath
                    )
            result = str(soup)
        response = HttpResponse(result)
        if strtobool(self.request.GET.get("force_download", "false")):
            response["Content-Disposition"] = "attachment"
        return response

class UriResolverView(DataBrowseView):
    """Get resolved and signed URLs for a given list of URIs."""

    def get(
        self, request: HttpRequest, *args: Union[str, int], **kwargs: Union[str, int]
    ) -> HttpResponse:
        """
        Return empty response.

        GET Method should not be disabled, but since it is implemented in
        superclass, it is overwritten.
        """
        return HttpResponse("")

    def post(
        self, request: HttpRequest, *args: Union[str, int], **kwargs: Union[str, int]
    ) -> HttpResponse:
        """Get resolved and signed URLs for a given list of URIs."""

        content = {}
        try:
            content = json.loads(request.read())
        except json.decoder.JSONDecodeError:
            pass

        response_data = {}
        for uri in content.get("uris", []):
            match = re.match(r"(\d+)/(.+)", uri)
            if not match:
                response_data[uri] = ""
                continue
            data_id = int(match.group(1))
            relative_path = Path(match.group(2))
            datum = self._get_datum(data_id)
            try:
                response_data[uri] = self._get_response(datum, relative_path)[0]
            except PermissionDenied:
                response_data[uri] = ""

        return JsonResponse(response_data)

    def _get_datum(self, data_id: int) -> Data:
        """
        Get datum with given id and check it's permissions.

        Speedup: Since checking permissions if quite slow, this method
        can become a real bottleneck if there are > 100 Data object to
        check. However, if they are from the same collection it is easy
        to check, just confirm that the user has view permission on
        collection. That can be checked only once and than cached.
        """

        @lru_cache(maxsize=1)
        def has_view_permission(collection_id: int) -> bool:
            collection = Collection.objects.filter(pk=collection_id).filter_for_user(
                self.request.user
            )
            return collection.exists()

        datum = Data.objects.get(pk=data_id)

        if datum.collection and has_view_permission(datum.collection.id):
            return datum

        return super()._get_datum(data_id)


# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright(c) 2019 Nippon Telegraph and Telephone Corporation
# Filename: EmRecoverUtilClusterLink.py
'''
Utility for restoration(Inter-cluster link creation)
'''

import json
import EmRecoverUtilBase
from EmCommonLog import decorater_log

class EmRecoverUtilClusterLink(EmRecoverUtilBase.EmRecoverUtilBase):
    '''
    Utility for restoration
    '''

    @decorater_log
    def __init__(self):
        '''
        Constructor
        '''

        super(EmRecoverUtilClusterLink, self).__init__()

    @decorater_log
    def _create_recover_ec_message(self, ec_message, db_info):
        '''
        Create inter-cluster link generation EC message for restoration
        Parameter:
            ec_message : EC message for "recover service"
            db_info : DB information
        Return Value :
            Result : Success：True  Failure：False
            EC message for restoration(JSON)
        '''
        self.common_util_log.logging(
            " ", self.log_level_debug, "db_info = %s" % db_info, __name__)
        self.common_util_log.logging(
            " ", self.log_level_debug, "ec_message = %s" %
            ec_message, __name__)

        return_ec_message = \
            {
                "device":
                {
                    "name": None,
                    "cluster-link-physical-interface_value": 0,
                    "cluster-link-physical-interface": [],
                    "cluster-link-lag-interface_value": 0,
                    "cluster-link-lag-interface": []
                }
            }

        self._gen_json_name(return_ec_message, db_info, ec_message)

        self._gen_json_cluster_link_phy(return_ec_message, db_info, ec_message)

        self._gen_json_cluster_link_lag(return_ec_message, db_info, ec_message)

        if return_ec_message["device"][
                "cluster-link-physical-interface_value"] == 0 and \
            return_ec_message["device"][
                "cluster-link-lag-interface_value"] == 0:
            self.common_util_log.logging(
                " ", self.log_level_debug,
                "Need not recover CLUSTER-LINK.", __name__)
            return True, None

        self.common_util_log.logging(
            " ", self.log_level_debug,
            "return_ec_message = %s" % return_ec_message, __name__)

        return True, json.dumps(return_ec_message)

    @decorater_log
    def _create_recover_db_info(self, ec_message, db_info):
        '''
        Create inter-cluster link creation DB information for restoration
        Parameter:
            ec_message : EC message for "recover service"
            db_info : DB information
        Return Value :
            Result : Success：True  Failure：False
            DB information for restoration(JSON)
        '''
        return_db_info = db_info.get(self.name_cluster_link)
        for cl_if in return_db_info.get("cluster-link_info"):
            if cl_if.get("type") == self._if_type_phy:
                if_type = self._if_type_phy
            else:
                if_type = self._if_type_lag
            cl_if["name"] = self._convert_ifname(
                cl_if.get("name"), ec_message, if_type)
        for phys_if in return_db_info.get("physical-interface"):
            phys_if["name"] = self._convert_ifname(
                phys_if.get("name"), ec_message, self._if_type_phy)
        for lag_if in return_db_info.get("lag"):
            lag_if["if_name"] = self._convert_ifname(
                lag_if.get("if_name"), ec_message, self._if_type_lag)
        for lag_mem_if in return_db_info.get("lag_member"):
            lag_mem_if["lag_if_name"] = self._convert_ifname(
                lag_mem_if.get("lag_if_name"), ec_message, self._if_type_lag)
            lag_mem_if["if_name"] = self._convert_ifname(
                lag_mem_if.get("if_name"), ec_message, self._if_type_phy)

        self.common_util_log.logging(
            " ", self.log_level_debug,
            "return_db_info = %s" % return_db_info, __name__)

        return True, json.dumps(return_db_info)

    @decorater_log
    def _gen_json_cluster_link_phy(self, json, db_info, ec_message):
        '''
            Set the inter-cluster link information (physical) to the EC message storage dictionary object
            to be used for restoration based on restoration expansion/EC message for "recover service"
            and DB information
            Explanation about parameter：
                json：EC message storage dictionary object
                db_info : DB information
                ec_message : EC message for restoration expansion/"recover service"
        '''
        cluster_links_db = db_info.get(self.name_cluster_link, {})

        for cluster_link_db in cluster_links_db.get("cluster-link_info", []):
            if cluster_link_db.get("type") == self._if_type_phy:
                old_name = cluster_link_db.get("name")
                name = self._convert_ifname(
                    old_name, ec_message, self._if_type_phy)
                address = cluster_link_db.get("address")
                prefix = cluster_link_db.get("prefix")
                condition = None
                for phys in cluster_links_db.get("physical-interface", []):
                    if phys.get("name") == old_name:
                        condition = phys.get("condition")
                        break
                metric = cluster_link_db.get("ospf").get("metric")
                json["device"]["cluster-link-physical-interface"].append(
                    {"name": name,
                     "address": address,
                     "prefix": prefix,
                     "condition": condition,
                     "ospf": {"metric": metric}})

        json["device"]["cluster-link-physical-interface_value"] = len(
            json["device"]["cluster-link-physical-interface"])

    @decorater_log
    def _gen_json_cluster_link_lag(self, json, db_info, ec_message):
        '''
            Set the inter-cluster link information (LAG) to the EC message storage dictionary object
            to be used for restoration based on restoration expansion/EC message for "recover service"
            and DB information
            Explanation about parameter：
                json：EC message storage dictionary object
                db_info : DB information
                ec_message : EC message for restoration expansion/"recover service"
        '''
        cluster_links_db = db_info.get(self.name_cluster_link, {})

        for cluster_link_db in cluster_links_db.get("cluster-link_info", []):
            if cluster_link_db.get("type") == self._if_type_lag:
                cl_link_list = \
                    {
                        "name": None,
                        "address": None,
                        "prefix": None,
                        "leaf-interface_value": 0,
                        "leaf-interface": [],
                        "ospf": None
                    }
                old_lag_name = cluster_link_db.get("name")
                name = self._convert_ifname(
                    old_lag_name, ec_message, self._if_type_lag)
                cl_link_list["name"] = name
                cl_link_list["address"] = cluster_link_db.get("address")
                cl_link_list["prefix"] = cluster_link_db.get("prefix")

                for lag_mem_db in cluster_links_db.get("lag_member", []):
                    if lag_mem_db.get("lag_if_name") == old_lag_name:
                        old_lag_mem = lag_mem_db.get("if_name")
                        member_if_name = self._convert_ifname(
                            old_lag_mem, ec_message, self._if_type_phy)
                        condition = None
                        for phys in cluster_links_db.get(
                                "physical-interface", []):
                            if phys.get("name") == old_lag_mem:
                                condition = phys.get("condition")
                                break
                        cl_link_list["leaf-interface"].append({
                            "name": member_if_name,
                            "condition": condition})
                cl_link_list["leaf-interface_value"] = \
                    len(cl_link_list["leaf-interface"])

                metric = cluster_link_db.get("ospf").get("metric")
                cl_link_list["ospf"] = {"metric": metric}

                json["device"][
                    "cluster-link-lag-interface"].append(cl_link_list)

        json["device"]["cluster-link-lag-interface_value"] = \
            len(json["device"]["cluster-link-lag-interface"])


import os
from stat import ST_CTIME, ST_MODE, S_ISREG

import numpy as np
import cv2
from cv_bridge import CvBridge, CvBridgeError
import rospy
import time
from edgecar_msgs.msg import WheelsCmdStamped
from std_msgs.msg import Bool
from sensor_msgs.msg import CompressedImage

from scanner import Scanner

import config as cfg
import masks as masks

class DrivingModule:
    def __init__(self):
        self.vehicle_name = rospy.get_param("~veh", "edgecar")
        self.start_driving_subscription_name = "/{}/ai/start_driving".format(self.vehicle_name)
        self.image_subscription_name = '/{}/camera_node/image/compressed'.format(self.vehicle_name)
        self.pub_car_cmd_name = '/{}/wheels_driver_node/wheels_cmd'.format(self.vehicle_name)

        self.sub_start_using_ai = rospy.Subscriber(self.start_driving_subscription_name, Bool, self.start_using_ai)

        self.pub_car_cmd = rospy.Publisher(self.pub_car_cmd_name, WheelsCmdStamped, queue_size=1)
        self.wheels_cmd = WheelsCmdStamped()

        self.scanner = Scanner()

        self.image_subscriber = None  # will be used later on when we start using AI
        self.running = False
        self.kl = None

        self.counter = 0

        self.bridge = CvBridge()

def start_using_ai(self, data):
        if data.data:
            rospy.loginfo("[{}] Start Driving making use of CV AI : {}".format(rospy.get_name(), data.data))
            self.running = True
            self.image_subscriber = rospy.Subscriber(self.image_subscription_name, CompressedImage, self.process_img)
            rospy.loginfo("[{}] Subscribed to image topic".format(rospy.get_name()))
        elif not data.data:
            self.stop_running()

def process_img(self, data):
    if data:
        try:
            angle = cfg.MAX_ANGLE
            throttle = cfg.MAX_THROTTLE

            img = self.bridge.compressed_imgmsg_to_cv2(data)
            hsv_data = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

            mask = None
            image_result = None

            mask_bounds = masks.limits[cfg.LOCATION]
            mask = cv2.inRange(hsv_data, np.array(mask_bounds[0][0]), np.array(mask_bounds[0][1]))
            mask2 = cv2.inRange(hsv_data, np.array(mask_bounds[1][0]), np.array(mask_bounds[1][1]))
            total_mask = mask | mask2
            total_mask = cv2.erode(total_mask, (3, 3), 2)
            total_mask = cv2.dilate(total_mask, (3, 3), 2)

            image_result = cv2.bitwise_and(img, img, mask=total_mask)

            self.scanner.set_image(total_mask)
            #d = self.scanner.find_direction()
            #p = Plotter.plot_direction(image_result, d)
            (target, absdir, left, right) = self.scanner.direction_exp()
            #p = Plotter.plot_direction_exp(image_result, d)

            angle = angle * absdir
            throttle = throttle

            self.wheels_cmd.header.stamp = data.header.stamp
            self.wheels_cmd.velocity = throttle
            self.wheels_cmd.rotation = angle
            self.pub_car_cmd.publish(self.wheels_cmd)

            if self.counter % 20 == 0:
                rospy.loginfo("[{}] outputs : {}".format(rospy.get_name(), outputs))
                self.counter = 0
            self.counter += 1

        except CvBridgeError as e:
            rospy.logerr("error cvbridge stuff : ", e)

    def stop_running(self):
        rospy.loginfo("[{} Must stop running AI container".format(rospy.get_name()))
        if not self.image_subscriber is None:
            self.image_subscriber.unregister()
            self.image_subscriber = None
            rospy.logdebug("[{}] Finished unsubscribing from image stream".format(rospy.get_name()))
        self.running = False

    def on_shutdown(self):
        rospy.loginfo('[DrivingModule] onShutdown ...')

if __name__ == '__main__':
    rospy.init_node('driving_node', anonymous=False)
    driving_module = DrivingModule()
    rospy.on_shutdown(driving_module.on_shutdown)
    rospy.spin()


def buyChoco(prices: list[int], money: int) -> int:
    prices = sorted(prices)
    if prices[0] + prices[1] <= money:
        return money - (prices[0] + prices[1])
    else:
        return money

if __name__ == '__main__':
    testcases = [([1, 2, 2], 3), ([3, 2, 3], 3)]
    for case in testcases:
        print(f"{case} -> {buyChoco(case[0], case[1])}")

Competition/Biweekly-105/6395. Buy Two Chocolates.py


from barrier import Barrier

class Rectangle(object):
    def __init__(self, x, y, w, h, angle = 0.0, speed = 0.0, color = None):
        self.color = color
        self.x = float(x)
        self.y = float(y)
        self.w = float(w)
        self.h = float(h)
        self.angle = float(angle)
        self.speed = float(speed)

    def get_corners(self):
        """Returns rectangle corners as a list of 4 tuples"""
        w = self.w
        h = self.h
        x = self.x
        y = self.y

        sin_a = sin(self.angle)
        cos_a = cos(self.angle)

        # Get x and  y distances from robot center to corners
        dx1 = (w/2) * cos_a - (h/2) * sin_a
        dy1 = (w/2) * sin_a + (h/2) * cos_a
        dx2 = (w/2) * cos_a + (h/2) * sin_a
        dy2 = (w/2) * sin_a - (h/2) * cos_a

        # Return corner coordinates with respect to origin
        return [(x + dx1, y + dy1), (x + dx2, y + dy2), (x - dx1, y - dy1), (x - dx2, y - dy2)]

    def get_lines(self):
        """Returns edges of rectangle as a list of 4 barriers"""
        c = self.get_corners()
        return [Barrier(c[0][0], c[0][1], c[1][0], c[1][1]),
                Barrier(c[1][0], c[1][1], c[2][0], c[2][1]),
                Barrier(c[2][0], c[2][1], c[3][0], c[3][1]),
                Barrier(c[3][0], c[3][1], c[0][0], c[0][1])]

    def is_colliding(self, object):
        """Returns if rectangle is colliding with barrier"""
        if isinstance(object, Barrier):
            for edge in self.get_lines():
                if edge.is_colliding(object):
                    return True
            return False
        elif isinstance(object, Rectangle):
            for edge in object.get_lines():
                if self.is_colliding(edge):
                    return True
            return False

    def get_normal_angle(self, barrier):
        """Returns the normal angle to a barrier, used in collision math"""
        x = self.x
        y = self.y
        x1 = barrier.x1
        y1 = barrier.y1
        x2 = barrier.x2
        y2 = barrier.y2

        # Avoid division by 0
        if x1 == x2:
            x2 += 0.0001

        # Get equations of barrier line (y = mx + b), m is slope, b is y-intercept
        m = (y2 - y1) / (x2 - x1)
        b = y1 - m*x1

        # Y-distance from the point to the line
        y_distance = m*x + b - y

        # If y-distance is positive, then the point is clockwise from the line with respect to Point 1
        if y_distance >= 0:
            # Return the barrier's angle minus 90 degrees
            return atan(m) - PI/2
        # Otherwise, the point is counterclockwise from the line with respect to Point 1
        else:
            # Return the barrier's angle plus 90 degrees
            return atan(m) + PI/2


import argparse
import logging
import multiprocessing
import signal
import sys

from gsuite_grant_analyzer.bigquery_helpers import (bq_create_client,
                                                    bq_create_dataset,
                                                    bq_create_table,
                                                    bq_insert_rows)

from gsuite_grant_analyzer.google_api_helpers import (
    create_delegated_credentials, create_directory_client,
    get_denormalized_scopes_for_user, get_users)

# Hard limit on the number of processes from the command line. This limit can
# be raised, however, expect more throttling from the APIs as you go up.
MAX_PROCESSES = 8

# These scopes must be granted in G Suite Admin Console to the service account
# client. See README.md file for more information on setup.
SCOPES = [
    "https://www.googleapis.com/auth/admin.directory.user.readonly",
    "https://www.googleapis.com/auth/admin.directory.user.security",
    "https://www.googleapis.com/auth/bigquery",
    "https://www.googleapis.com/auth/cloud-platform"
]

logging.basicConfig(filename="gsuite_grant_analyzer.log",
                    level=logging.DEBUG,
                    format="%(asctime)s [%(levelname)s] [%(name)s] %(message)s")

logger = logging.getLogger(__name__)

terminate_processes = multiprocessing.Value("i", 0)

def handle_signal(s, f):
    """Handles termination by CTRL-C.

  Args:
    s: signal
    f: frame
  """
    del s
    del f
    global terminate_processes
    terminate_processes = multiprocessing.Value("i", 1)

def parse_args(args):
    """Parses script arguments.

  Args:
    args: script arguments

  Returns:
    Parsed arguments
  """
    parser = argparse.ArgumentParser(
        description="Finds applications and scopes for all users in a given "
        "OU and loads them into BigQuery")
    parser.add_argument("--domain", help="Domain", type=str, required=True)
    parser.add_argument("--ou",
                        help="Organizational Unit path, default is /",
                        type=str,
                        required=False,
                        default="/")
    parser.add_argument("--sa",
                        help="Path to Service Account credentials",
                        type=str,
                        required=True)
    parser.add_argument("--admin",
                        help="Administrator email",
                        type=str,
                        required=True)
    parser.add_argument("--project",
                        help="Project where BigQuery dataset will be created",
                        type=str,
                        required=True)
    parser.add_argument("--dry-run",
                        help="Do not load data into BigQuery",
                        required=False,
                        dest="dry_run",
                        action="store_true",
                        default=False)
    parser.add_argument("--processes",
                        help="Number of concurrent processes (default: 4)",
                        type=int,
                        required=False,
                        dest="num_processes",
                        default=4)

    return parser.parse_args(args)

def build_rows_process(queue, users, directory_client, process_number,
                       num_processes):
    """A process functions to process all users in parallel.

  Gets all users, but processes and builds the rows only for the subset of
  users assigned to the process.

  Args:
    queue: shared synchronized queue where results are stored
    users: list of all users
    directory_client: client for the Directory SDK API
    process_number: number of this process, from 0 to num_processes
    num_processes: total number of processes
  """
    rows = []
    total_users = len(users)
    for i, user in enumerate(users, 1):
        if terminate_processes.value:
            break
        if i % num_processes == process_number:
            logger.debug("Process #%s - User %d/%d: %s", process_number, i,
                         total_users, user)
            rows.extend(get_denormalized_scopes_for_user(
                directory_client, user))

    # Post results in the queue, if not terminating
    if not terminate_processes.value:
        queue.put({
            "process_number": process_number,
            "message_type": "DATA",
            "data": rows
        })

    # Post process complete message
    queue.put({"process_number": process_number, "message_type": "STOP"})

def analyze():
    """Main function for G Suite Grant Analyzer."""
    signal.signal(signal.SIGINT, handle_signal)
    signal.signal(signal.SIGTERM, handle_signal)

    args = parse_args(sys.argv[1:])

    logger.info("### G Suite Grant Analyzer ###")
    logger.debug("Domain=%s", args.domain)
    logger.debug("OU=%s", args.ou)
    logger.debug("Admin=%s", args.admin)
    logger.debug("SA=%s", args.sa)
    logger.debug("Project=%s", args.project)
    logger.debug("Dry run=%s", args.dry_run)
    logger.debug("Processes=%d", args.num_processes)

    if args.num_processes > MAX_PROCESSES:
        logger.error(
            "The maximum number of processes is %d. Please, edit your command "
            "line.", MAX_PROCESSES)
        exit(1)

    # Get credentials for service account and create services and clients
    logger.info("Creating credentials...")
    delegated_credentials = create_delegated_credentials(
        service_account_file=args.sa, scopes=SCOPES, user=args.admin)
    logger.info("Creating Directory API client...")
    directory = create_directory_client(delegated_credentials)

    if not args.dry_run:
        logger.info("Setting up BigQuery...")
        bq_client = bq_create_client(args.project, delegated_credentials)
        dataset = bq_create_dataset(bq_client)
        table = bq_create_table(bq_client, dataset)

    logger.info("Setup complete.")

    logger.info("Getting user list...")
    users = get_users(directory, args.domain, args.ou)
    total_users = len(users)
    logger.info("Got %d users", total_users)

    # Shared queue for process messages
    queue = multiprocessing.Queue()

    # Stores running processes by process number
    processes = {}

    # Create and start processes
    for process_number in range(0, args.num_processes):
        logger.info("Creating process %d", process_number)
        process = multiprocessing.Process(target=build_rows_process,
                                          args=(queue, users, directory,
                                                process_number,
                                                args.num_processes))
        processes[process_number] = process
        process.start()

    total_rows = 0

    # Process results until all processes have terminated
    while processes:
        message = queue.get()
        process_number = message["process_number"]
        message_type = message["message_type"]
        if message_type == "DATA":
            # Insert data in BQ
            if not args.dry_run and not terminate_processes.value:
                logger.info("Inserting data from process #%d", process_number)
                data = message["data"]
                total_rows += len(data)
                bq_insert_rows(bq_client, table, data)
        elif message_type == "STOP":
            # Remove completed process from running processes
            processes[process_number].join()
            logger.info("Process #%d completed", process_number)
            del processes[process_number]
        else:
            logger.error("Unknown message %s from process",
                         message["message_type"])
            exit(1)

    logger.info("All processes terminated - %d rows processed", total_rows)

if __name__ == "__main__":
    analyze()


# 빨간색과 파란색을 교대로 100개 긋는다

# 그래픽 라이브러리를 도입한다
from tkinter import *
# 화면 초기화
w = Canvas(Tk(), width=900, height=400)
w.pack()

# 선을 교대로 많이 긋는다 ---- (*1)
for i in range(100):
    x = i * 9
    if i % 2 == 0:
        c = "#ff0000"
    else:
        c = "#0000FF"
    w.create_line(x, 0, x, 400, fill=c)

mainloop()


import os, os.path

path = '/dev'

def counting():
    l = list(os.listdir(path))
    # print(len(l))
    length = 0
    for i in l:
        if not (os.path.isdir('/dev/' + i)):
            length = length + 1
        # print(length)
    return length

counting()

def structure(p):
    for i in os.listdir(p):
        if (os.path.isdir(os.path.join(p, i))):
            subP = p + '/' + i
            print(subP)
            print(os.listdir(subP))
            structure(subP)

structure(path)

# konwersja jpg na png
def conversion(path):
    for i in os.listdir(path):
        if (os.path.isfile(os.path.join(path, i))):
            if i[-4:] == '.jpg':
                os.rename(path + '/' + i, path + '/' + i[:-4] + '.png')

conversion(path)


import os
import sys
from io import StringIO
import discord

def main():
  client = discord.Client()

  @client.event
  async def on_ready():
    print("C++ bot is alive")

  @client.event
  async def on_message(message):

    if message.author == client.user:
      return

    if message.content.startswith("!hello"):
      await message.channel.send(f"hello")

    if message.content.startswith("!runPython"):
      # remove the command and
      message.content = message.content[len("!runPython")+1:]
      code = '\n'.join(message.content.split('\n'))
      save_stdout = sys.stdout
      output = StringIO()
      sys.stdout = output
      exec(code)
      await message.channel.send(output.getvalue())
      sys.stdout = save_stdout
      print(output.getvalue())

    if message.content.startswith("!runC++"):
      message.content = message.content[len("!runC++")+1:]
      code = '\n'.join(message.content.split('\n'))
      # write the code in the code.cpp
      with open('code.cpp', 'w') as f:
        f.write(code)
      # use terminal commands to compile and run it
      os.system('clang++-7 -pthread -std=c++17 -o out code.cpp')
      os.system('./out > out.txt')
      #return the output
      with open('out.txt', 'r') as f:
        output = f.read()
      await message.channel.send(output)

  client.run(TOKEN)

if __name__ == "__main__":
  main()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 找 p，q 的公共祖先，p，q 有可能不在树中
# 所以要在后序遍历的位置匹配节点，遍历每一个节点
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        self.foundP, self.foundQ = False, False
        node = self.find(root, p, q)
        if not self.foundP or not self.foundQ:
            return None
        return node

    def find(self, node:'TreeNode', p:'TreeNode', q:'Treenode') -> bool:
        if not node:
            return None

        left = self.find(node.left, p, q)
        right = self.find(node.right, p, q)

        # 左右都找到了一个节点，说明当前节点就是 LCA 节点
        if left and right:
            return node

        # 节点匹配并且做标记
        if node is p or node is q:
            if node is p:
                self.foundP = True
            if node is q:
                self.foundQ = True
            return node

        # 向上传递找到的节点
        return left if left else right


from pandas.core.frame import DataFrame
from sklearn.neural_network import MLPRegressor
from typing import List

def train(data: DataFrame, response_vars: List[str]) -> MLPRegressor:
    # split response and predictor vars
    y = data[response_vars]
    predictor_vars = data.columns.difference(response_vars)
    X = data[predictor_vars]
    # create and fit the model to the data
    model = MLPRegressor()
    model.fit(X, y)

    return model


class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        low, fast = nums[0], nums[0]
        while True:
            low = nums[low]
            fast = nums[nums[fast]]
            if low == fast:
                break

        ptr1 = nums[0]
        ptr2 = low
        while ptr1 != ptr2:
            ptr1 = nums[ptr1]
            ptr2 = nums[ptr2]

        return ptr1


# import tensorflow as tf
from tensorflow.keras.models import Sequential  # 시퀀셜 모델 -> 순차적으로 레이어 층을 더해주는 모델을 순차모델이라고 한다.
from tensorflow.keras.layers import Dense  # 덴스 레이어를 쓸수있다.
import numpy as np

#1. 데이터 정제해서 값 도출 -> 학습 데이터
x =  np.array([1,2,3])  # x.shape = (3, 1) (행, 열)
y =  np.array([1,2,3])

#2. 모델구성
model = Sequential()  # 순차모델로 만든다.
model.add(Dense(1, input_dim=1))  # Dense로 만들어진 노드를 모델에 add하면 모델안에 있는 다른 노드들과 연결된다.(출력 노드개수, 열)

#3. 컴파일, 훈련 -> 컴퓨터가 알아듣게 훈련시킴 그게 컴파일 y = wx + b 최적의 weight값을 빼기 위한 최소의 mse값을 찾는다.
model.compile(loss='mse', optimizer='adam') # 평균 제곱 에러 mse 이 값은 작을수록 좋다. optimizer='adam'은  mse값 감축시키는 역할. 85점 이상이면 쓸만하다.

model.fit(x, y, epochs=4200, batch_size=1) # epochs 훈련량을 의미  batch_size 몇개씩 데이터를 넣을지 지정해줌. batch가 작을수록 값이정교해짐 시간 성능 속도? 배치사이즈가 작을 수록 시간이 많이 필요함
#위의 데이터들로 훈련하겠다 fit.
# 두 데이터의 행이 같아야 한다.

#4. 평가, 예측
loss = model.evaluate(x, y) # 평가하다. -> 모델의 최종적인 accuracy(정확도)와 loss 값을 알 수 있다.
print('loss : ', loss)  # loss : 6.158037269129654e-14 -> loss는 예측값과 실제값이 차이나는 정도를 나타내는 지표이며 작을 수록 좋다.
# 전체 샘플의 개수들 중에서 얼마나 나의 알고리즘이 정답이라고 예측한 샘플이 포함되었는지의 비율을 의미한다.
result = model.predict([4]) # 새로운 x값을 predcit한 결과
print('4의 예측값 : ', result)  # 4의 예측값 : [[3.9999993]]
                                # 5의 예측값 : [[4.992851]]


from pathlib import Path
from torch.utils.data import Dataset
import pickle
import numpy as np
import pandas as pd

class Cholec80Helper(Dataset):
    def __init__(self, hparams, data_p, dataset_split=None):
        assert dataset_split != None
        self.data_p = data_p
        assert hparams.data_root != ""
        self.data_root = Path(hparams.data_root)
        self.number_vids = len(self.data_p)
        self.dataset_split = dataset_split
        self.factor_sampling = hparams.factor_sampling

    def __len__(self):
        return self.number_vids

    def __getitem__(self, index):
        vid_id = index
        p = self.data_root / self.data_p[vid_id]
        unpickled_x = pd.read_pickle(p)
        stem = np.asarray(unpickled_x[0],
                          dtype=np.float32)[::self.factor_sampling]
        y_hat = np.asarray(unpickled_x[1],
                           dtype=np.float32)[::self.factor_sampling]
        y = np.asarray(unpickled_x[2])[::self.factor_sampling]
        return stem, y_hat, y

class Cholec80():
    def __init__(self, hparams):
        self.name = "Cholec80Pickle"
        self.hparams = hparams
        self.class_labels = [
            "Preparation",
            "CalotTriangleDissection",
            "ClippingCutting",
            "GallbladderDissection",
            "GallbladderPackaging",
            "CleaningCoagulation",
            "GallbladderRetraction",
        ]
        self.out_features = self.hparams.out_features
        self.features_per_seconds = hparams.features_per_seconds
        hparams.factor_sampling = (int(25 / hparams.features_subsampling))
        print(
            f"Subsampling features: 25features_ps --> {hparams.features_subsampling}features_ps (factor: {hparams.factor_sampling})"
        )

        self.data_p = {}
        self.data_p["train"] = [(
            f"{self.features_per_seconds:.1f}fps/video_{i:02d}_{self.features_per_seconds:.1f}fps.pkl"
        ) for i in range(1, 41)]
        self.data_p["val"] = [(
            f"{self.features_per_seconds:.1f}fps/video_{i:02d}_{self.features_per_seconds:.1f}fps.pkl"
        ) for i in range(41, 49)]
        self.data_p["test"] = [(
            f"{self.features_per_seconds:.1f}fps/video_{i:02d}_{self.features_per_seconds:.1f}fps.pkl"
        ) for i in range(49, 81)]

        # Datasplit is equal to Endonet and Multi-Task Recurrent ConvNet with correlation loss for surgical vid analysis
        self.weights = {}
        self.weights["train"] = [
            1.6411019141231247,
            0.19090963801041133,
            1.0,
            0.2502662616859295,
            1.9176363911137977,
            0.9840248158200853,
            2.174635818337618,
        ]
        self.weights["train_log"] = [1.25, 0.5, 1.0, 0.25, 1.25, 1., 1.5]

        self.data = {}
        for split in ["train", "val", "test"]:
            self.data[split] = Cholec80Helper(hparams,
                                              self.data_p[split],
                                              dataset_split=split)

        print(
            f"train size: {len(self.data['train'])} - val size: {len(self.data['val'])} - test size:"
            f" {len(self.data['test'])}")

    @staticmethod
    def add_dataset_specific_args(parser):  # pragma: no cover
        cholec80_specific_args = parser.add_argument_group(
            title='cholec80 dataset specific args options')
        cholec80_specific_args.add_argument("--features_per_seconds",
                                                  default=25,
                                                  type=float)
        cholec80_specific_args.add_argument("--features_subsampling",
                                                  default=5,
                                                  type=float)

        return parser


#!/usr/bin/python3.5
#PARA RODAR O PROGRAMA  ./insertionSort.py
import sys
#coding=UTF-8

def insertionSort(lista, tamanho):

    for i in range (1,len(lista),1):
        menor = i
        #for j in range(0, i, -1): <== (FOR DANDO ERRO DESCONHECIDO)
        j = i - 1
        while j >= 0:
            if lista[menor] <lista[j]:

                aux = lista[menor]
                lista[menor] = lista[j]
                lista[j] = aux
            else:
                break
            #print (lista)
            j = j - 1
            menor = menor -1

#lista = [2,5,6,3,1,4]
#lista = [54,26,93,17,77,31,44,55,20]
#lista = ["a", "k", "b", "f", "z", "g", "d", "o"]
#print(lista)
#insertionSort(lista, len(lista))
#print(lista)

lista = []
nome = 'num.1000.1.in'
nome = sys.argv[1]
arq = open(nome, 'r')
#lista = ["a", "k", "b", "f", "z", "g", "d", "o"]
i = 0
for line in arq:
    convertido = int(line)
    lista.append(convertido)
    i = i + 1
arq.close()
insertionSort(lista, len(lista))
print(lista)


import ROOT
import uproot
import numpy as np
from   array import array

fileptr = uproot.open("TT_Dilept_13.root")

outputfile = ROOT.TFile("NewRoot.root", 'recreate')
tree = ROOT.TTree("CutTree", "CutTree")

#Electron arrays
elec_pt_arr = array('f', [0.])
elec_eta_arr = array('f', [0.])
elec_phi_arr = array('f', [0.])
elec_charge_arr = array('f', [0.])

#Muon arrays
muon_pt_arr = array('f', [0.])
muon_eta_arr = array('f', [0.])
muon_phi_arr = array('f', [0.])
muon_charge_arr = array('f', [0.])

#Jet arrays
ljet_pt_arr = array('f',[.0])
ljet_eta_arr = array('f',[.0])
ljet_phi_arr = array('f',[.0])
ljet_mass_arr = array('f',[.0])

sljet_pt_arr = array('f',[.0])
sljet_eta_arr = array('f',[.0])
sljet_phi_arr = array('f',[.0])
sljet_mass_arr = array('f',[.0])
#Lepton arrays
l_pt_arr = array('f',[.0])
l_eta_arr = array('f',[.0])
l_phi_arr = array('f',[.0])
l_mass_arr = array('f',[.0])

sl_pt_arr = array('f',[.0])
sl_eta_arr = array('f',[.0])
sl_phi_arr = array('f',[.0])
sl_mass_arr = array('f',[.0])

#Elec branches
tree.Branch("elec_pt", elec_pt_arr, "elec_pt/F")
tree.Branch("elec_eta", elec_arr, "elec_eta/F")
tree.Branch("elec_phi", elec_phi_arr, "elec_phi/F")
tree.Branch("elec_charge", elec_charge_arr, "elec_charge/F")

#Muon branches
tree.Branch("muon_pt", muon_pt_arr, "muon_pt/F")
tree.Branch("muon_eta", muon_eta_arr, "muon_eta/F")
tree.Branch("muon_phi", muon_phi_arr, "muon_phi/F")
tree.Branch("muon_charge", muon_charge_arr, "muon_charge/F")

#Jets branches
tree.Branch("ljet_pt", ljet_pt_arr, "ljet_pt/F")
tree.Branch("ljet_eta", ljet_eta_arr, "ljet_eta/F")
tree.Branch("ljet_phi", ljet_phi_arr, "ljet_phi/F")
tree.Branch("ljet_mass", ljet_mass_arr, "ljet_mass/F")
tree.Branch("sljet_pt", sljet_pt_arr, "sljet_pt/F")
tree.Branch("sljet_eta", sljet_eta_arr, "sljet_eta/F")
tree.Branch("sljet_phi", sljet_phi_arr, "sljet_phi/F")
tree.Branch("sljet_mass", sljet_mass_arr, "sljet_mass/F")

#Lepton Branches
tree.Branch("l_pt", l_pt_arr, "l_pt/F")
tree.Branch("l_eta", l_eta_arr, "l_eta/F")
tree.Branch("l_phi", l_phi_arr, "l_phi/F")
tree.Branch("l_mass", l_mass_arr, "l_mass/F")
tree.Branch("sl_pt", sl_pt_arr, "sl_pt/F")
tree.Branch("sl_eta", sl_eta_arr, "sl_eta/F")
tree.Branch("sl_phi", sl_phi_arr, "sl_phi/F")
tree.Branch("sl_mass", sl_mass_arr, "sl_mass/F")

#originaltags = [mu_pt, mu_eta, mu_phi, mu_charge]
#flattags = [mu_pt_flat, mu_eta_flat, mu_phi_flat, mu_charge_flat]

for i in range(len(e_pt)):
    e_pt_arr[0] = e_pt[i]
    e_phi_arr[0] = e_phi[i]
    e_eta_arr[0] = e_eta[i]
    e_charge_arr[0] = e_charge[i]

    muon_pt_arr[0] = mu_pt[i]
    muon_eta_arr[0] = mu_eta[i]
    muon_phi_arr[0] = mu_phi[i]
    muon_charge_arr[0] = mu_charge[i]

    ljet_pt_arr[0] = ljet_pt[i]
    ljet_eta_arr[0] = ljet_eta[i]
    ljet_phi_arr[0] = ljet_phi[i]
    ljet_mass_arr[0] = ljet_mass[i]

    sljet_pt_arr[0] = sljet_pt[i]
    sljet_eta_arr[0] = sljet_eta[i]
    sljet_phi_arr[0] = sljet_phi[i]
    sljet_mass_arr[0] = sljet_mass[i]

    l_pt_arr[0] = l_pt[i]
    l_eta_arr[0] = l_eta[i]
    l_phi_arr[0] = l_phi[i]
    l_mass_arr[0] = l_mass[i]

    sl_pt_arr[0] = sl_pt[i]
    sl_eta_arr[0] = sl_eta[i]
    sl_phi_arr[0] = sl_phi[i]
    sl_pt_mass[0] = sl_mass[i]

    tree.Fill()

outputfile.Write()
outputfile.Close()


import cv2

camera=cv2.VideoCapture(0)

width=int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))#bu satırda kameramızın çerçevesinin genişliğini int biçimde aldık
height=int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))#bu satırda kameramın çerçevesinin yüksekliğini int biçimde aldık

print(width,height)

fourcc=cv2.VideoWriter_fourcc(*"MPV4")#bu satırda cv2.VideoWriter_fourcckomutuyla videomuzun hangi formatta kayıt
#edileceğini belirleyip fourcc değişkenine atadık

writer=cv2.VideoWriter("kayit.mp4",fourcc,17,(width,height))#1. değişkende kayıt dosyamızın ismini 2. değişkende
#kayıt formatımızı (üstte kayıt formatını cv2.VideoWriter_fourcc komtuyla fourcc değişkenine atadık) 3. değişkende
#bir saniyede kaç frame kaydedeceğini (FPS) 4. değişkende kayıt dosyamızın genişlik ve yüksekliğini belirleyip bir değişkene
#atıyoruz. Videomuz şu an kaydedilmiyor sadece kayıt işleminin nasıl yapılacağı bilgilerini bir değişkene atadık

while True:
    ret,image=camera.read()
    image=cv2.flip(image,1)#kameradan alınan görüntünün yatay veya dikey çevirilmesini sağlar
    #0-> x ekseninde yani dikey 1-> y ekseninde yani yatay -1-> ise hem dikey hem de yatay eksene görünntüyü çevirir
    writer.write(image)#kayıt işlei bu satırda .write komutuyla yapılıyor kayıt özelliklerini writer değişkeninden
    #alıyor
    cv2.imshow("camera",image)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

camera.release()
writer.release()#kamerarla işimiz bittiğinde onu nasıl serbest bırakıyorsak kayıt işlemini de aynı şekilde serbest
#bırakmamız gerk
cv2.destroyAllWindows()

24-)Python ile Görüntü İşleme- UYGULAMA - Kameradan Alınan Görüntünün Kayıt Edilmesi/27-)Kamera kayıt.py


import random
import sys
import copy
import time

class Cue:
    def __init__(self, line, play, idx) -> None:
        self.play = play
        self.idx = idx
        self.variation = False
        if line[0] == '[':
            self.type = "stage_direction"
            self.text = line.strip()
        else:
            self.type = "line"
            try:
                colon_idx = line.index(':')
                self.character = line[:colon_idx]
                self.text = line[colon_idx + 1:].strip()
            except ValueError:
                sys.exit(f"Script mis-formatted at line {idx}: {line}")

    def __str__(self) -> str:
        if self.type == 'stage_direction':
            return f"{self.text}\n"
        else:
            return f"{self.character}: {self.text}\n"

    def make_variation(self, variation_function,  max_depth):
        if self.type != "line":
            return
        prompt = f"{self.character}:"
        depth = 1
        while depth < max_depth and self.idx - depth >= 0:
            cue = self.play.cues[self.idx - depth]
            if cue.type == "line":
                prompt = str(cue) + prompt
            depth += 1
        new_text = variation_function(prompt)
        if len(new_text) > 0 and new_text[-1].isalpha():
            new_text += '—'
        self.text = new_text.strip()
        self.variation = True

class Play:
    def __init__(self, script, variation_function) -> None:
        self.cues = []
        with open(script, 'r') as f:
            lines = f.readlines()
            for idx, line in enumerate(lines):
                if len(line) < 1:
                    continue
                cue = Cue(line, self, idx)
                self.cues.append(cue)
        self.original = copy.deepcopy(self.cues)
        self.variation_function = variation_function

    def print_play(self, variations_only=False):
        for cue in self.cues:
            if variations_only and cue.variation:
                print(cue)
            else:
                print(cue)

    def print_changes(self):
        for cue in self.cues:
            if cue.variation:
                print(
                    f"[ORIGINAL] {self.original[cue.idx]}\n[VARIATION] {cue}")

    def run_play(self, speed=4):
        for cue in self.cues:
            print(cue)
            time.sleep(speed)

    def make_variations(self, chance=0.1, overwrite_variations=False, protected_lines=0, depth=10, log=False):
        print(
            f"Making variations to script with chance [{chance}] based on depth [{depth}]...")
        for cue in self.cues:
            if cue.idx + 1 < protected_lines or (cue.variation and not overwrite_variations):
                continue
            if random.random() < chance:
                cue.make_variation(self.variation_function, depth)
                if log:
                    print(
                        f"[ORIGINAL] {self.original[cue.idx]}\n[VARIATION] {cue}")

    def save_current_script(self, filename, mark_variations=True):
        with open(filename, "w") as f:
            for cue in self.cues:
                line = str(cue)
                if cue.variation and mark_variations:
                    line = line.strip() + " <variation>\n"
                f.write(line)


import math
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

def calc(x):
	return str( math.log (abs ( 12 * math.sin( x ) ) ) )

opt = webdriver.ChromeOptions()
opt.add_experimental_option('w3c', False)

browser = webdriver.Chrome(options=opt)
link = "http://suninjuly.github.io/explicit_wait2.html"
browser.get(link)

button = browser.find_element_by_id("book")
price = WebDriverWait(browser, 12).until(
	EC.text_to_be_present_in_element((By.ID, "price"), "$100")
)
button.click()

x_string = browser.find_element_by_id("input_value")
x_number = int( x_string.text )

answer = calc(x_number)

input_answer = browser.find_element_by_id("answer")
input_answer.send_keys(answer)

send_button = browser.find_element_by_id("solve")
send_button.click()
time.sleep(10)
browser.quit()