import pandas as pd
import numpy as np
import Cryptodome
import re
import random
import datetime as datetime
import os

class TShift:
    """
    This class creates timeshift for a given patient in both structure and unstructured forms

    :Attributes:
        -lookup_timeshift
    """

    def __init__(self, patients, adend=None):
        """
        - min 30 day shift, max 180
        :param patients: list-like, describes the patient identification number in the data
        """
        self.shifts = [i for i in range(-180, -30)] + [j for j in range(31, 181)]
        self.lookup_timeshift = {pt: datetime.timedelta(days=random.choice(self.shifts)) for pt in patients}
        if adend is None:
            self.adend = " (ANON) "
        else:
            self.adend = adend

    def find_dates(self, text, debug=False):
        """
        - Date Formats - needed American Dates
        This returns all regex math objects for a given date pattern
        # need to quantify the different changes in the dates
        """
        # need to classify dates
        _ = re.finditer(r"[0-9]+/[0-9]+/[0-9]{2,4}", text)
        # _ = re.finditer(r"[0-9]+/[0-9]+/[0-9]{2}",text)
        if debug:
            for x in _:
                print(x.group())
            return _
        else:
            for x in _:
                yield x

    def to_datetime(self, match):
        """
        This fu
        :param date:
        """
        # find the length of the last group and retrun the striped date and start and end of the given match objects in tuple form
        return (match.start(), match.end(), datetime.datetime.strptime(str(match.group()), "%m/%d/%y"))

    def update_dates(self, pt, text):
        """
        This function updates the date with the equivalent timeshift in the file
        :param pt:
        :param text:
        """
        if type(text) is not str:
            print(text)
            raise
        shifted = 0
        matches = [self.to_datetime(match) for match in self.find_dates(text)]
        for match in matches:
            date = match[2] + self.lookup_timeshift[pt]
            text = text[:match[0] + shifted] + date.strftime("%m/%d/%y") + self.adend + text[match[1] + shifted:]
            shifted += len(self.adend)
        return text

    def update_dates_df(self, df_ref, date_cols):
        """
        shifts the listed datetime columns and returns the changed columns
        """
        tshift = []
        for idx in df_ref.index:
            shifted = self.shift_dates(df_ref[idx], date_cols[idx])
            tshift.append(shifted)
        ts = pd.Series(tshift)
        return ts

    def try_parse_date(self, text):
        text = str(text)
        if text == 'nan' or text == 'NaT':
            return pd.NaT, None
        elif not '-' in text:
            text = str(text[:4]+'-'+text[4:6]+'-'+text[6:])
        for datetime_fmt in ('%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d', '%d-%b-%y'):
            try:
                return datetime.datetime.strptime(text, datetime_fmt), datetime_fmt
            except ValueError:
                pass
        raise ValueError('no valid date format found, please use the format: %Y-%m-%d %H:%M, %Y-%m-%d, %d-%b-%y \n -see https://strftime.org/ for more information')

    def update_timeshifts(self, df_ref):
        for pt in df_ref:
            if pt not in self.lookup_timeshift.keys():
                self.lookup_timeshift[pt] = datetime.timedelta(days=random.choice(self.shifts))

    def shift_dates(self, patients, date):
        """
        :arg pt - reference for date shifts
        :arg date - date to shift
        :returns shifted_date - shifted datetime as string
        """
        try:
            if np.isnan(patients):
                return pd.NaT
        except:
            raise Exception("Not an allowed type. Please use the empi column.")
        #if patients not in self.lookup_timeshift.keys():
        #    self.lookup_timeshift[patients] = datetime.timedelta(days=random.choice(self.shifts))

        date, fmt = self.try_parse_date(date)
        if fmt == None:
            return date
        shifted_date = date + self.lookup_timeshift[patients]
        shifted_date_str = shifted_date.strftime(fmt)

        return shifted_date_str

    def update_lookup(self, patients):
        if patients not in self.lookup_timeshift.keys():
            self.lookup_timeshift[patients] = datetime.timedelta(days=random.choice(self.shifts))
            return self.lookup_timeshift[patients]

"""
datetime formats:

from datetime import datetime

'STUDY_DATE'
datetime_str = '2013-09-24'
datetime_object = datetime.strptime(datetime_str, '%Y-%m-%d')

'XXX_DATETIME'
datetime_str = '2013-09-23 16:36'
datetime_object = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M')
"""


import os
import numpy as np

import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

from torchvision import transforms

## 네트워크 저장하기
def save(ckpt_dir, net, optim, epoch):
    if not os.path.exists(ckpt_dir):
        os.makedirs(ckpt_dir)

    torch.save({'net': net.state_dict(), 'optim': optim.state_dict()},
               "%s/model_epoch%d.pth" % (ckpt_dir, epoch))

## 네트워크 불러오기
def load(ckpt_dir, net, optim):
    if not os.path.exists(ckpt_dir):
        epoch = 0
        return net, optim, epoch

    ckpt_lst = os.listdir(ckpt_dir)
    ckpt_lst.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))

    dict_model = torch.load('%s/%s' % (ckpt_dir, ckpt_lst[-1]))

    net.load_state_dict(dict_model['net'])
    optim.load_state_dict(dict_model['optim'])
    epoch = int(ckpt_lst[-1].split('epoch')[1].split('.pth')[0])

    return net, optim, epoch

# 훈련 파라미터 설정하기
from init import dir_data

lr = 1e-3
batch_size = 4
num_epoch = 3

base_dir = './drive/MyDrive/DACrew/unet'
data_dir = dir_data
ckpt_dir = os.path.join(base_dir, "checkpoint")
log_dir = os.path.join(base_dir, "log")

# 훈련을 위한 Transform과 DataLoader
from loader import Dataset
from transform import ToTensor, Normalization, RandomFlip

transform = transforms.Compose([Normalization(mean=0.5, std=0.5), RandomFlip(), ToTensor()])

dataset_train = Dataset(data_dir=os.path.join(data_dir, 'train'), transform=transform)
loader_train = DataLoader(dataset_train, batch_size=batch_size, shuffle=True)#, num_workers=8)

dataset_val = Dataset(data_dir=os.path.join(data_dir, 'val'), transform=transform)
loader_val = DataLoader(dataset_val, batch_size=batch_size, shuffle=False)#, num_workers=8)

# 네트워크 생성하기
from Unet import UNet

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net = UNet().to(device)

# 손실함수 정의하기
fn_loss = nn.BCEWithLogitsLoss().to(device)

# Optimizer 설정하기
optim = torch.optim.Adam(net.parameters(), lr=lr)

# 그밖에 부수적인 variables 설정하기
num_data_train = len(dataset_train)
num_data_val = len(dataset_val)

num_batch_train = np.ceil(num_data_train / batch_size)
num_batch_val = np.ceil(num_data_val / batch_size)

# 그 밖에 부수적인 functions 설정하기
fn_tonumpy = lambda x: x.to('cpu').detach().numpy().transpose(0, 2, 3, 1)
fn_denorm = lambda x, mean, std: (x * std) + mean
fn_class = lambda x: 1.0 * (x > 0.5)

# Tensorboard 를 사용하기 위한 SummaryWriter 설정
writer_train = SummaryWriter(log_dir=os.path.join(log_dir, 'train'))
writer_val = SummaryWriter(log_dir=os.path.join(log_dir, 'val'))

# 네트워크 학습시키기
st_epoch = 0
# 학습한 모델이 있을 경우 모델 로드하기
net, optim, st_epoch = load(ckpt_dir=ckpt_dir, net=net, optim=optim)

for epoch in range(st_epoch + 1, num_epoch + 1):
        net.train()
        loss_arr = []

        for batch, data in enumerate(loader_train, 1):
            # forward pass
            label = data['label'].to(device)
            input = data['input'].to(device)

            output = net(input)

            # backward pass
            optim.zero_grad()

            loss = fn_loss(output, label)
            loss.backward()

            optim.step()

            # 손실함수 계산
            loss_arr += [loss.item()]

            print("TRAIN: EPOCH %04d / %04d | BATCH %04d / %04d | LOSS %.4f" %
                  (epoch, num_epoch, batch, num_batch_train, np.mean(loss_arr)))

            # Tensorboard 저장하기
            label = fn_tonumpy(label)
            input = fn_tonumpy(fn_denorm(input, mean=0.5, std=0.5))
            output = fn_tonumpy(fn_class(output))

            writer_train.add_image('label', label, num_batch_train * (epoch - 1) + batch, dataformats='NHWC')
            writer_train.add_image('input', input, num_batch_train * (epoch - 1) + batch, dataformats='NHWC')
            writer_train.add_image('output', output, num_batch_train * (epoch - 1) + batch, dataformats='NHWC')

        writer_train.add_scalar('loss', np.mean(loss_arr), epoch)

        with torch.no_grad():
            net.eval()
            loss_arr = []

            for batch, data in enumerate(loader_val, 1):
                # forward pass
                label = data['label'].to(device)
                input = data['input'].to(device)

                output = net(input)

                # 손실함수 계산하기
                loss = fn_loss(output, label)

                loss_arr += [loss.item()]

                print("VALID: EPOCH %04d / %04d | BATCH %04d / %04d | LOSS %.4f" %
                      (epoch, num_epoch, batch, num_batch_val, np.mean(loss_arr)))

                # Tensorboard 저장하기
                label = fn_tonumpy(label)
                input = fn_tonumpy(fn_denorm(input, mean=0.5, std=0.5))
                output = fn_tonumpy(fn_class(output))

                writer_val.add_image('label', label, num_batch_val * (epoch - 1) + batch, dataformats='NHWC')
                writer_val.add_image('input', input, num_batch_val * (epoch - 1) + batch, dataformats='NHWC')
                writer_val.add_image('output', output, num_batch_val * (epoch - 1) + batch, dataformats='NHWC')

        writer_val.add_scalar('loss', np.mean(loss_arr), epoch)

        # epoch 50마다 모델 저장하기
        # if epoch % 50 == 0:
        #     save(ckpt_dir=ckpt_dir, net=net, optim=optim, epoch=epoch)
        save(ckpt_dir=ckpt_dir, net=net, optim=optim, epoch=epoch)

        writer_train.close()
        writer_val.close()

# 훈련 모델 테스트
import matplotlib.pyplot as plt

transform = transforms.Compose([Normalization(mean=0.5, std=0.5), ToTensor()])

dataset_test = Dataset(data_dir=os.path.join(data_dir, 'test'), transform=transform)
loader_test = DataLoader(dataset_test, batch_size=batch_size, shuffle=False)#, num_workers=8)

# 그밖에 부수적인 variables 설정하기
num_data_test = len(dataset_test)
num_batch_test = np.ceil(num_data_test / batch_size)

# 결과 디렉토리 생성하기
result_dir = os.path.join(base_dir, 'result')
if not os.path.exists(result_dir):
    os.makedirs(os.path.join(result_dir, 'png'))
    os.makedirs(os.path.join(result_dir, 'numpy'))

net, optim, st_epoch = load(ckpt_dir=ckpt_dir, net=net, optim=optim)

with torch.no_grad():
      net.eval()
      loss_arr = []

      for batch, data in enumerate(loader_test, 1):
          # forward pass
          label = data['label'].to(device)
          input = data['input'].to(device)

          output = net(input)

          # 손실함수 계산하기
          loss = fn_loss(output, label)

          loss_arr += [loss.item()]

          print("TEST: BATCH %04d / %04d | LOSS %.4f" %
                (batch, num_batch_test, np.mean(loss_arr)))

          # Tensorboard 저장하기
          label = fn_tonumpy(label)
          input = fn_tonumpy(fn_denorm(input, mean=0.5, std=0.5))
          output = fn_tonumpy(fn_class(output))

          # 테스트 결과 저장하기
          for j in range(label.shape[0]):
              id = num_batch_test * (batch - 1) + j

              plt.imsave(os.path.join(result_dir, 'png', 'label_%04d.png' % id), label[j].squeeze(), cmap='gray')
              plt.imsave(os.path.join(result_dir, 'png', 'input_%04d.png' % id), input[j].squeeze(), cmap='gray')
              plt.imsave(os.path.join(result_dir, 'png', 'output_%04d.png' % id), output[j].squeeze(), cmap='gray')

              np.save(os.path.join(result_dir, 'numpy', 'label_%04d.npy' % id), label[j].squeeze())
              np.save(os.path.join(result_dir, 'numpy', 'input_%04d.npy' % id), input[j].squeeze())
              np.save(os.path.join(result_dir, 'numpy', 'output_%04d.npy' % id), output[j].squeeze())

print("AVERAGE TEST: BATCH %04d / %04d | LOSS %.4f" %
        (batch, num_batch_test, np.mean(loss_arr)))

# 시각화

##
lst_data = os.listdir(os.path.join(result_dir, 'numpy'))

lst_label = [f for f in lst_data if f.startswith('label')]
lst_input = [f for f in lst_data if f.startswith('input')]
lst_output = [f for f in lst_data if f.startswith('output')]

lst_label.sort()
lst_input.sort()
lst_output.sort()

##
id = 0

label = np.load(os.path.join(result_dir,"numpy", lst_label[id]))
input = np.load(os.path.join(result_dir,"numpy", lst_input[id]))
output = np.load(os.path.join(result_dir,"numpy", lst_output[id]))

## 플롯 그리기
plt.figure(figsize=(8,6))
plt.subplot(131)
plt.imshow(input, cmap='gray')
plt.title('input')

plt.subplot(132)
plt.imshow(label, cmap='gray')
plt.title('label')

plt.subplot(133)
plt.imshow(output, cmap='gray')
plt.title('output')

plt.show()


import pymysql

def application(environ, start_response):
    conn = pymysql.connect("localhost", "app_sql", "app_sql", "app_sql")
    with conn.cursor() as cursor:
        post_data = ''
        if environ.get("REQUEST_METHOD") == "POST":
            try:
                request_body_size = int(environ.get('CONTENT_LENGTH', 0))
            except (ValueError):
                request_body_size = 0
            post_data = environ['wsgi.input'].read(request_body_size)

        headers = {k[5:]: v for (k, v) in environ.items() if k.startswith("HTTP_")}
        cursor.execute(
            "CREATE TEMPORARY TABLE IF NOT EXISTS `headers` (`name` VARCHAR(255) PRIMARY KEY, `value` VARCHAR(4095))"
        )

        for k, v in headers.items():
            cursor.execute(
                "INSERT INTO `headers` VALUES (%s, %s) ON DUPLICATE KEY UPDATE `value` = %s",
                (k, v, v),
            )

        app_args = [environ["PATH_INFO"], environ["QUERY_STRING"], post_data, None, None]

        try:
            cursor.callproc("app", app_args)
        except pymysql.Error as e:
            print(e)
            start_response("500 Internal Server Error", [("Content-Type", "text/html")])
            return b"Somethin dun broke"

        cursor.execute("SELECT @_app_3, @_app_4")
        status, resp = cursor.fetchone()
        cursor.execute("SELECT `name`, `value` FROM `resp_headers`")
        headers = list(cursor.fetchall())

        conn.commit()

        start_response(status, headers)
        return resp


from Vector import Vector
from Mesh   import Mesh

class Curve_N():
    ##!
    ##! Calculate Numerical and, if defined, Analytical unit normal vector.
    ##! Store in self.Ns_Num and self.Ns_Ana.
    ##!
    ##! Analytical values are calculated, if provided by
    ##! actual Curve class (ie, Circle, Ellipse,....): def N(self,t)
    ##!

    Ns_Num=None
    Ns_Ana=None

    dNs=[]
    dN=0.0

    def Calc_Num_N(self,t):
        T=self.Calc_Num_T(t)

        N=None
        if (T):
            N=T.Hat2()
        return N

    def Calc_Num_Ns(self):
        self.Ns_Num=self.Calc_Mesh_Type_Num("N")

    def Calc_Ana_Ns(self):
        self.Ns_Ana=self.Calc_Mesh_Type_Ana("n")

    ##!
    ##! Verify analytical unit normals against the numerical.
    ##!

    def Calc_Verify_N(self,n):
        dn=0.0
        if (self.Ns_Num[n] and self.Ns_Ana[n]):
            dn=self.Ns_Num[n]-self.Ns_Ana[n]
            dn=dn.Length()

        self.dNs.append( dn )
        self.dN+=dn

    ##!
    ##! Calculate unit normals.
    ##!

    def Verify_Ns(self):
        self.dN,self.dNs,self.dN_Max=self.Verify_Mesh_Type("dR")

        return [
            "Unit Normal:\t\t",
            "%.2e" % self.dN,
            str(self.dN_Max)
        ]

    ##!
    ##! Draw unit normals as SVG.
    ##!

    def Ns_SVG(self):
        return self.Mesh_Vector_SVGs(
            "N",
            self.Curve_Component_Get("N","Color","Thick")
        )


import logging
import time
import requests
from requests.auth import HTTPDigestAuth
import os
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

LOGIN_FLAG = False
SHUTDOWN_FLAG = False
RESTART_FLAG = False
RESET_FLAG = False

def logging_start():
    logging.basicConfig(filename="/var/log/aim-power/result.log",
                        format="%(asctime)s:%(levelname)s:%(message)s",
                        level=logging.INFO)
    logging.info("ADDER: ==== Started Logging ====")

def logging_stop():
    logging.info("ADDER: ==== Stopped Logging ====")
    time.sleep(1)
    logging.shutdown()

def send_power_on():
    logging.info("ADDER: Power On")
    r = requests.get("http://10.10.10.254/hidden.htm?M0:O1=On", auth=HTTPDigestAuth("api", "api"))
    assert(r.status_code == 200)

def send_power_off():
    logging.info("ADDER: Power Off")
    r = requests.get("http://10.10.10.254/hidden.htm?M0:O1=Off", auth=HTTPDigestAuth("api", "api"))
    assert(r.status_code == 200)

def send_power_restart():
    logging.info("ADDER: Power Restart")
    r = requests.get("http://10.10.10.254/hidden.htm?M0:O1=Restart", auth=HTTPDigestAuth("api", "api"))
    assert(r.status_code == 200)

def start_driver():
    driver = webdriver.Firefox()
    wait = WebDriverWait(driver, 30)
    return driver, wait

def aim_login():
    global LOGIN_FLAG
    LOGIN_FLAG = False
    logging.info("ADDER: Login Aim")
    try:
        driver, wait = start_driver()
        driver.navigate.to("http://10.10.10.10/")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#username"))).send_keys("admin")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#password"))).send_keys("password")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#login"))).click()
        LOGIN_FLAG = wait.until(EC.presense_of_element_located((By.LINK_TEXT, "DASHBOARD"))).is_displayed()
    except Exception as e:
        logging.info("ADDER: Problem with Aim Login - Stacktrace: %s" %e)
    finally:
        driver.quit()
    # ret = os.system("ruby aim_login.rb")
    # if ret == 0:
    #     LOGIN_FLAG = True
    # else:
    #     logging.info("ADDER: Problem with Aim Login")

def aim_shutdown():
    global SHUTDOWN_FLAG
    SHUTDOWN_FLAG = False
    logging.info("ADDER: Login and Shutdown Aim")
    try:
        driver, wait = start_driver()
        driver.navigate.to("http://10.10.10.10/")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#username"))).send_keys("admin")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#password"))).send_keys("password")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#login"))).click()
        wait.until(EC.presense_of_element_located((By.LINK_TEXT, "DASHBOARD"))).is_displayed()
        driver.navigate.to("http://10.10.10.10/admin/process_power.php?mode=shutdown")
        time.sleep(5)
        driver.refresh()
        found = driver.find_elements((By.LINK_TEXT, "DASHBOARD"))
        if len(found) == 0:
            SHUTDOWN_FLAG = True
    except Exception as e:
        logging.info("ADDER: Problem with Aim Shutdown - Stacktrace: %s" %e)
    finally:
        driver.quit()
    # ret = os.system("ruby aim_shutdown.rb")
    # if ret == 0:
    #     SHUTDOWN_FLAG = True
    # else:
    #     logging.info("ADDER: Problem with Aim Shutdown")

def aim_restart():
    global RESTART_FLAG
    RESTART_FLAG = False
    logging.info("ADDER: Login and Restart Aim")
    try:
        driver, wait = start_driver()
        driver.navigate.to("http://10.10.10.10/")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#username"))).send_keys("admin")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#password"))).send_keys("password")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#login"))).click()
        wait.until(EC.presense_of_element_located((By.LINK_TEXT, "DASHBOARD"))).is_displayed()
        driver.navigate.to("http://10.10.10.10/admin/process_power.php?mode=restart")
        time.sleep(20)
        driver.refresh()
        RESTART_FLAG = wait.until(EC.presense_of_element_located((By.LINK_TEXT, "DASHBOARD"))).is_displayed()
    except Exception as e:
        logging.info("ADDER: Problem with Aim Restart - Stacktrace: %s" %e)
    finally:
        driver.quit()
    # ret = os.system("ruby aim_restart.rb")
    # if ret == 0:
    #     RESTART_FLAG = True
    # else:
    #     logging.info("ADDER: Problem with Aim Restart")

def aim_reset():
    global RESET_FLAG
    RESET_FLAG = False
    logging.info("ADDER: Login and Reset Aim")
    try:
        driver, wait = start_driver()
        driver.navigate.to("http://10.10.10.10/")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#username"))).send_keys("admin")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#password"))).send_keys("password")
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#login"))).click()
        wait.until(EC.presense_of_element_located((By.LINK_TEXT, "DASHBOARD"))).is_displayed()
        wait.until(EC.presense_of_element_located((By.LINK_TEXT, "UPDATES"))).click()
        wait.until(EC.presense_of_element_located((By.LINK_TEXT, "Reset AIM Configuration"))).click()
        wait.until(EC.presense_of_element_located((By.CSS_SELECTOR, "#confirm_reset_link"))).click()
        time.sleep(120)
        RESET_FLAG = wait.until(EC.presense_of_element_located((By.LINK_TEXT, "DASHBOARD"))).is_displayed()
    except Exception as e:
        logging.info("ADDER: Problem with Aim Reset - Stacktrace: %s" %e)
    finally:
        driver.quit()
    # ret = os.system("ruby aim_reset.rb")
    # if ret == 0:
    #     RESET_FLAG = True
    # else:
    #     logging.info("ADDER: Problem with Aim Reset")

if __name__ == "__main__":
    logging_start()
    execution = 0
    passes = 0
    fails = 0
    while True:
        try:
            execution += 1
            send_power_on()
            time.sleep(60)

            aim_login()
            time.sleep(60)

            send_power_off()
            time.sleep(60)

            send_power_on()
            time.sleep(60)

            aim_login()
            time.sleep(60)

            send_power_restart()
            time.sleep(60)

            aim_shutdown()
            time.sleep(60)

            send_power_restart()
            time.sleep(60)

            aim_restart()
            time.sleep(60)

            aim_reset()
            time.sleep(60)

            aim_login()
            time.sleep(60)

            send_power_off()
            time.sleep(60)

            if LOGIN_FLAG and SHUTDOWN_FLAG and RESET_FLAG and RESTART_FLAG:
                passes += 1
            else:
                fails += 1
            logging.info("ADDER: Exes: %d Passes: %d Fails: %d" %(execution, passes, fails))
        except KeyboardInterrupt:
            logging_stop()
            break


import tensorflow as tf
import numpy as np
from pathlib import Path

def one_hot_embs(words, words_vocab_file):
  vocab_size = 0
  with Path(words_vocab_file).open() as f:
    indices = [idx for idx, tag in enumerate(f)]
    vocab_size = len(indices) + 1

  vocab_words = tf.contrib.lookup.index_table_from_file(
    words_vocab_file, num_oov_buckets=1
  )

  word_ids = vocab_words.lookup(words)
  return tf.one_hot(word_ids, vocab_size)

def glove(words, words_vocab_file, glove_file):
  vocab_words = tf.contrib.lookup.index_table_from_file(
    words_vocab_file, num_oov_buckets=1
  )

  word_ids = vocab_words.lookup(words)
  glove = np.load(glove_file)['embeddings']
  variable = np.vstack([glove, [[0.] * 300]])
  variable = tf.Variable(variable, dtype=tf.float32, trainable=False)
  word_embeddings = tf.nn.embedding_lookup(variable, word_ids)

  return word_embeddings


import os
import sys
import getopt

import torch
import torch.optim as optim
import torch.functional as F
from tqdm import tqdm

import utils
import Invincea

USE_CUDA = torch.cuda.is_available()
DEVICE = torch.device("cuda" if USE_CUDA else "cpu")

def train_model(model, epochs, train_loader, optimizer):
    model.train()
    for epoch in range(epochs):
        total_loss = 0
        total_correct = 0
        total = 0
        with tqdm(train_loader, desc='Train Epoch #{}'.format(epoch)) as t:
            for data, target in t:
                data, target = data.to(DEVICE), target.to(DEVICE)
                optimizer.zero_grad()
                output = model(data)
                optimizer.zero_grad()
                loss = F.binary_cross_entropy(output, target)
                loss.backward()
                optimizer.step()
                total += len(data)
                total_correct += output.round().eq(target).sum().item()
                total_loss += loss.item() * len(data)
                t.set_postfix(loss='{:.4f}'.format(total_loss / total), accuracy='{:.4f}'.format(total_correct / total))

def train(train_csv_path, model_path, batch_size, epochs):
    try:
        train_loader = utils.get_data_loader(train_csv_path, batch_size, True)
    except Exception as e:
        print(e)
        sys.exit(1)
    model = Invincea.Invincea().to(DEVICE)
    optimizer = optim.Adam(model.parameters())
    if model_path == None:
        model_path = 'model.dat'
    if os.path.isfile(model_path):
        model.load_state_dict(torch.load(model_path))
    train_loader(model, epochs, train_loader, optimizer)
    torch.save(model.state_dict(), model_path)

def main(argv):
    try:
        train_csv_path = None
        model_path = None
        batch_size = 128
        epochs = 10
        optlist, args = getopt.getopt(argv[1:], '', ['help', 'train=', 'model=', 'batch_size=', 'epochs=',])
        for opt, arg in optlist:
            if opt == '--help':
                utils.help()
                sys.exit(0)
            elif opt == '--train':
                train_csv_path = arg
            elif opt == '--model':
                model_path = arg
            elif opt == '--batch_size':
                batch_size = int(arg)
            elif opt == '--epochs':
                epochs = int(arg)
        if train_csv_path == None:
            print('The following values must be input')
            print('train')
            utils.help()
            sys.exit(1)
        train(train_csv_path, model_path, batch_size, epochs)
    except Exception as e:
        print(e)
        sys.exit(1)

if __name__ == '__main__':
    main(sys.argv)


# -*- coding: utf-8 -*-
import pickle
import gzip
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

def load_data():
    f = gzip.open('../mnist.pkl.gz', 'rb')
    train_data, val_data, test_data = pickle.load(f, encoding='bytes')
    f.close()
    return train_data, val_data, test_data

def load_data_wrapper():
    train_data, val_data, test_data = load_data()
    train_X = [x.reshape(784, 1) for x in train_data[0]]
    train_y = [vectorize(y) for y in train_data[1]]

    val_X = [x.reshape(784, 1) for x in val_data[0]]
    test_X = [x.reshape(784, 1) for x in test_data[0]]

    return (list(zip(train_X, train_y)),
            list(zip(val_X, val_data[1])),
            list(zip(test_X, test_data[1]))
            )

def vectorize(i):
    y = np.zeros((10, 1))
    y[i] = 1.0
    return y

def plot_iamges6 (data):
    ilist = np.random.permutation(range(len(data)))
    fig = plt.figure()

    for j in range(1, 7):
        image, _ = data[ilist[j]]
        image = image.reshape(28, -1)
        ax = fig.add_subplot(1, 6, j)
        ax.matshow(image, cmap=matplotlib.cm.binary)
        plt.xticks(np.array([]))
        plt.yticks(np.array([]))

    plt.show()


def check(score):
    if score > 2000:
        return 2000
    elif score < -15:
        return -15
    else:
        return score

def calculate():
    player_rating = int(input("Player Rating: "))
    opponent_rating = int(input("Opponent Rating: "))
    score = int(input("Player Score: "))
    opponent_score = int(input("Opponent Score: "))

    expected_score = round(1 / (1 + 10 ** ((opponent_rating - player_rating) / 280)), 1)
    opponent_expected_score = round(1 / (1 + 10 ** ((player_rating - opponent_rating) / 280)), 1)

    output = player_rating + (32 * (score - expected_score))
    second_output = opponent_rating + (32 * (opponent_score - opponent_expected_score))

    print("\nPlayer new MMR:", check(output))
    print("Opponent new MMR:", check(second_output))

calculate()


import pandas as pd
import json

def scatter(path="data/test500.csv"):
    merg = pd.read_csv(path)
    Dict_scatter = {}
    Dict_scatter["label"] = 'Relationship between Box Office and movie budget'
    dane_scatter = merg[['BoxOffice', 'Budget']].rename(columns={'BoxOffice': 'y', 'Budget': 'x'})
    Dict_scatter["data"] = dane_scatter[["x", "y"]].to_dict('records')
    Dict_scatter["backgroundColor"] = 'rgb(65, 148, 217)'
    dane_scatter = json.dumps([Dict_scatter])

    return dane_scatter

def bar_plot(path="data/test500.csv"):
    merg = pd.read_csv(path)
    dataset = merg[['BoxOffice', 'Main Producer']].groupby('Main Producer').mean()
    dataset.sort_values(by=['BoxOffice'], inplace=True)
    dataset = dataset.tail(20)
    Dict_bar = {}
    Dict_bar['type'] = 'bar'
    Dict_bar['x'] = dataset.index.values.tolist()
    Dict_bar['y'] = dataset.BoxOffice.values.tolist()
    Dict_bar = json.dumps([Dict_bar])

    return Dict_bar

def pie_chart(path="data/test500.csv"):
    merg = pd.read_csv(path)

    dataset_pie = merg[['Main genre', 'BoxOffice']].groupby('Main genre').sum()
    dataset_pie.sort_values(by=['BoxOffice'], inplace=True)
    dataset_pie = dataset_pie.tail(5)
    dane_pie = json.dumps(dataset_pie.BoxOffice.values.tolist())
    labels_pie = json.dumps(dataset_pie.index.values.tolist())

    return labels_pie, dane_pie

def radar_chart(path="data/test500.csv"):
    merg = pd.read_csv(path)

    data_radar_1 = merg[['BoxOffice', 'Budget', 'Number of reviews', 'Average Rating', 'Nominations']]
    data_radar_1 -= data_radar_1.min()
    data_radar_1 /= data_radar_1.max()
    data_radar_1 *= 100
    data_radar_1 = pd.concat([data_radar_1, merg['Main genre']], axis=1)
    data_radar_1 = data_radar_1.loc[data_radar_1['Main genre'].isin(['Dramat', 'Akcja', 'Fantasy'])]
    data_radar_1 = data_radar_1.groupby('Main genre').mean()

    list_radar = json.dumps(
        [{
            'type': 'scatterpolar',
            'r': data_radar_1.iloc[0].values.tolist(),
            'theta': data_radar_1.columns.tolist(),
            'fill': 'toself',
            'name': data_radar_1.index[0]
        }, {
            'type': 'scatterpolar',
            'r': data_radar_1.iloc[1].values.tolist(),
            'theta': data_radar_1.columns.tolist(),
            'fill': 'toself',
            'name': data_radar_1.index[1]
        }, {
            'type': 'scatterpolar',
            'r': data_radar_1.iloc[2].values.tolist(),
            'theta': data_radar_1.columns.tolist(),
            'fill': 'toself',
            'name': data_radar_1.index[2]
        }]
    )

    return list_radar


import functools
import typing
import string
import random
import pytest

def leap(year):
    """
    Nimmt eine Jahreszahl als Parameter und prüft ob es sich um ein Schaltjahr handelt.
    Definition Schaltjahr rch vier teilbar ist. Ausnahme: Jahreszahl durch einhundert, aber nicht
    durch vierhundert teilbar, so handelt es sich doch um ein normales Jahr.

    args:
        year: int (positives integer >= 1582)

    return:
        evaluation: bool (True, wenn year ein Schaltjahr, False wenn kein Schaltjahr
    """
    if year  % 4 == 0 and year > 1582:
        if year % 100 == 0 and year % 400 != 0:
            return False
        else:
            return True
    else:
        return False
######################################################################
## Lösung Teil 2 (Tests)

def test_leap():
    a = 1604
    b = 2100
    c = 404
    assert leap(a) == True
    assert leap(b) == False
    assert leap(c) == False
######################################################################


from concurrent.futures import ThreadPoolExecutor
from tornado import gen
from tornado.ioloop import IOLoop

# instantiate a pool with 2 threads
thread_pool = ThreadPoolExecutor(2)

def block_func(count):
    import time
    for _ in range(count):
        time.sleep(1)

@gen.coroutine
def call_blocking():
        print("Start")
        # submit method to call blocking method
        yield thread_pool.submit(block_func, 10)
        print("End")

if __name__ == "__main__":
        IOLoop.current().run_sync(lambda:call_blocking())


import os
import shutil

from cato_common.domain.file import File
from cato_common.domain.image import Image
from cato_server.configuration.app_configuration_defaults import (
    AppConfigurationDefaults,
)
from cato_server.images.oiio_binaries_discovery import OiioBinariesDiscovery
from cato_server.images.oiio_command_executor import OiioCommandExecutor
from cato_server.storage.abstract.abstract_file_storage import AbstractFileStorage
from cato_server.storage.abstract.image_repository import ImageRepository
from cato_server.storage.abstract.test_result_repository import TestResultRepository
from cato_server.usecases.create_thumbnail import CreateThumbnail
from tests.unittests.cato_server.images.image_comparators.utils import images_are_equal
from tests.utils import mock_safe

def test_should_create_thumbnail(test_result_factory, tmp_path, test_resource_provider):
    test_result = test_result_factory(reference_image=1)
    image = Image(
        id=0,
        name="the_image.png",
        original_file_id=2,
        channels=[],
        width=1920,
        height=1080,
    )
    original_file = File(id=0, name="the_image.png", hash="hash", value_counter=0)
    saved_thumbnail_file = File(
        id=10, name="the_image.png", hash="hash", value_counter=0
    )
    saved_thumbnail_path = tmp_path / "saved_thumbnail.png"

    def save_thumbnail(path):
        shutil.copy(path, saved_thumbnail_path)
        return saved_thumbnail_file

    mock_image_repository = mock_safe(ImageRepository)
    mock_file_storage = mock_safe(AbstractFileStorage)
    mock_test_result_repository = mock_safe(TestResultRepository)
    mock_image_repository.find_by_id.return_value = image
    mock_file_storage.find_by_id.return_value = original_file
    mock_file_storage.save_file = save_thumbnail
    mock_file_storage.get_path.return_value = test_resource_provider.resource_by_name(
        os.path.join("sphere_test_images", "exr_multichannel_16_bit.exr")
    )
    create_thumbnail = CreateThumbnail(
        mock_image_repository,
        mock_file_storage,
        OiioBinariesDiscovery(),
        mock_test_result_repository,
        OiioCommandExecutor(),
        AppConfigurationDefaults().create(),
    )

    create_thumbnail.create_thumbnail(test_result)

    assert images_are_equal(
        saved_thumbnail_path,
        test_resource_provider.resource_by_name(
            os.path.join("sphere_test_images", "expected_thumbnail.png")
        ),
    )


#coding:utf-8

import os
import sys
import logging
import argparse
import tensorflow as tf

from dataset import Dataset
from multi_gpus import MultiGpusCRNN
import utils

## logging config
logging.basicConfig(
  level = logging.INFO,
  format = '[%(levelname)-8s %(asctime)-11s L%(lineno)-4d] %(message)s',
  datefmt = '%m-%d %H:%M')

def save(saver, sess, logdir, step):
    model_name = 'model.ckpt'
    checkpoint_path = os.path.join(logdir, model_name)
    logging.info('Storing checkpoint {} to {}.'.format(step, logdir))
    sys.stdout.flush()
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    saver.save(sess, checkpoint_path, global_step=step)

def main(args):
  ## build model
  optimizer = tf.train.AdamOptimizer(1e-4)
  mg_crnn = MultiGpusCRNN(args.n_gpus, optimizer,
      batch_size=args.batch_size/args.n_gpus,
      with_spatial_transform=args.with_spatial_transform)
  objective = mg_crnn.objective
  loss = mg_crnn.loss
  error = mg_crnn.error
  predict = mg_crnn.predict
  probability = mg_crnn.log_prob

  ## build dataset
  dataset = Dataset(args.img_path_prefix, args.img_list_file, args.label_list_file,
      args.lexicon_file, val_ratio=args.val_ratio, test_ratio=args.test_ratio)
  n_train_batches = dataset.n_train_samples / args.batch_size
  n_val_batches = dataset.n_val_samples / args.batch_size
  n_test_batches = dataset.n_test_samples / args.batch_size

  ## start session, to fit the model
  config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
  with tf.Session(config=config) as sess:
    ## init parameters
    sess.run(tf.global_variables_initializer())
    saver = tf.train.Saver(var_list=tf.trainable_variables(),
        max_to_keep=args.max_checkpoints)

    for i in xrange(n_train_batches * args.n_epochs):
      # {m0.image, m0.label, m1.image, m1.label, ...}
      batches = [dataset.next_train_batch(args.batch_size/args.n_gpus)
          for j in range(args.n_gpus)]
      feed_dict = mg_crnn.feed_dict(batches)
      result = sess.run([objective, loss, error], feed_dict=feed_dict)

      if (i+1) % args.validate_every == 0:
        logging.info('step {}, epoch {}, loss {}, train err {}'.format(
            i+1, batches[-1].epoch_id, result[1], result[2]))
        ## evaluate on dev set
        if n_val_batches > 0:
          val_batches = [dataset.next_val_batch(args.batch_size/args.n_gpus)
              for j in range(args.n_gpus)]
          feed_dict = mg_crnn.feed_dict(val_batches)
          val_result = sess.run([predict, error], feed_dict=feed_dict)
          ## val_result[pred/err][gpu][0]
          pred = [sample for j in range(args.n_gpus)
              for sample in utils.sparse2dense((val_result[0][j].indices,
              val_result[0][j].values, val_result[0][j].dense_shape)) ]
          label = [sample for j in range(args.n_gpus)
              for sample in utils.sparse2dense(val_batches[j].labels) ]
          n_exact_matches = sum([1 for p, t in zip(pred, label) if p == t])
          accuracy = n_exact_matches / float(args.batch_size)
          logging.info('val err {}, acc {}'.format(val_result[1], accuracy))
          logging.info('val last sample pred:  {}'.format(pred[-1]))
          logging.info('val last sample label: {}'.format(label[-1]))

      if (i+1) % args.checkpoint_every == 0:
        save(saver, sess, args.checkpoint_dir, i)

    ## evaluate on test set
    if n_test_batches > 0:
      test_err = 0
      for i in xrange(n_test_batches):
        batches = [dataset.next_test_batch(args.batch_size/arg.n_gpus)
            for j in range(args.n_gpus)]
        feed_dict = mg_crnn.feed_dict(batches)
        batch_err = sess.run([error], feed_dict=feed_dict)
        test_err += batch_err[0]
      test_err /= n_test_batches
      logging.info('Test error {}'.format(test_err))

if __name__ == '__main__':
  def _get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--img_path_prefix', default='./data/image',
        help='Prefix of image path')
    parser.add_argument('--img_list_file', default='./data/image_list.txt',
        help="Contain images' path")
    parser.add_argument('--label_list_file', default='./data/label_list.txt',
        help="ontain images' label")
    parser.add_argument('--lexicon_file', default='./data/lexicon.txt',
        help='Vocabulary, one word per line')
    parser.add_argument('--with_spatial_transform', type=bool, default=False)
    parser.add_argument('--n_gpus', type=int, default=1)
    parser.add_argument('--batch_size', type=int, default=128)
    parser.add_argument('--n_epochs', type=int, default=20)
    parser.add_argument('--val_ratio', type=float, default=0.2)
    parser.add_argument('--test_ratio', type=float, default=0.1)
    parser.add_argument('--validate_every', type=int, default=100)
    parser.add_argument('--checkpoint_every', type=int, default=2000)
    parser.add_argument('--checkpoint_dir', default='./checkpoint')
    parser.add_argument('--max_checkpoints', type=int, default=10)
    args = parser.parse_args()
    return args
  args = _get_args()

  main(args)


""" References Views """

# Django rest framework
from rest_framework import viewsets, mixins, status
from rest_framework.decorators import action
from rest_framework.response import Response

# Reference models
from reference.models import Reference

# Reference serializers
from reference.serializers import ReferenceModelSerializer

class ReferenceViewSet(viewsets.GenericViewSet,
                       mixins.ListModelMixin,
                       mixins.RetrieveModelMixin):
    """ The viewset of references """

    queryset = Reference.objects.all()
    serializer_class = ReferenceModelSerializer
    lookup_field = 'id'

    def retrieve(self, request, *args, **kwargs):
        """
            Retrieves the model of the reference and if it
            asks for availability, returns a boolean
            :param request: The request donde by the user
            :param args: Some arguments carried on the
            :param kwargs: Some keyword arguments carried on the request
            :return: The retrieved object
        """
        shoe = Reference.objects.get(id=kwargs['id'])
        data = ReferenceModelSerializer(shoe).data
        if request.META.get('QUERY_STRING'):
            quantity = request.META['QUERY_STRING'].split('=')[1]
            if shoe.stock < int(quantity):
                data = {
                    'available': 'no'
                }
            else:
                data = {
                    'available': 'yes'
                }
        return Response(data, status=status.HTTP_200_OK)

    @action(detail=True, methods=['get'])
    def quantity(self, request, *args, **kwargs):
        """
            Retrieves the availability of the reference
            :param request: The request done by the user
            :param args: Some arguments carried on the request
            :param kwargs: Some keyword arguments carried on the request
            :return: A message saying if the object is available or not
        """
        shoe = Reference.objects.get(id=kwargs['id'])
        quantity = request.data['quantity']
        if shoe.stock < int(quantity):
            data = {
                'message': '0'
            }
        else:
            data = {
                'message': '1'
            }
        return Response(data, status=status.HTTP_200_OK)


import tkinter as tk
import u3
import time

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()
        self.stopped = False

        # Connect to the LabJack U3-HV
        self.d = u3.U3()

        # Define the digital output lines for the Fill and Vent switches
        # Replace the pin numbers with the correct pin numbers for your switching board
        self.FILL_SWITCH = 8

        self.fill_time_var = tk.DoubleVar()
        self.fill_time_var.set(1) # set default value
        self.vent_time_var = tk.DoubleVar()
        self.vent_time_var.set(1) # set default value

    def create_widgets(self):

        # Initialize the fill_time_var and vent_time_var StringVars
        self.fill_time_var = tk.StringVar()
        self.vent_time_var = tk.StringVar()

        # Create a label and entry widget for fill time
        self.fill_time_label = tk.Label(self, text="Fill time (s)")
        self.fill_time_label.grid(row=0, column=0, sticky="W")
        self.fill_time_entry = tk.Entry(self, textvariable=self.fill_time_var)
        self.fill_time_entry.grid(row=0, column=1)

                # Create a label and entry widget for vent time
        self.vent_time_label = tk.Label(self, text="Vent time (s)")
        self.vent_time_label.grid(row=1, column=0, sticky="W")
        self.vent_time_entry = tk.Entry(self, textvariable=self.vent_time_var)
        self.vent_time_entry.grid(row=1, column=1)

        # Create a label to display the current cycle number
        self.cycle_number_label = tk.Label(self, text="Cycle number")
        self.cycle_number_label.grid(row=2, column=0, sticky="W")

        self.entry = tk.Entry(self)
        self.entry.grid(row=2, column=1)

        self.cycle_number = tk.StringVar()
        self.cycle_number_label = tk.Label(self, textvariable=self.cycle_number)
        self.cycle_number_label.grid(row=3, column=1)

        self.run_button = tk.Button(self, text="Start Testing", command=self.run)
        self.run_button.grid(row=4, column=0, columnspan=2, pady=10)

        self.quit = tk.Button(self, text="Stop Testing", command=self.stop)
        self.quit.grid(row=5, column=0, columnspan=2, pady=10)

        self.output = tk.Text(self, height=10, width=30)
        self.output.grid(row=0, column=2, rowspan=5, padx=10)

        # Create the fill light
        self.fill_light = tk.Canvas(self, width=50, height=50)
        self.fill_light.grid(row=6, column=0, padx=10, pady=10)
        self.fill_light_shape = self.fill_light.create_oval(10, 10, 40, 40, fill="grey")
        self.fill_light_label = tk.Label(self, text="On/OFF")
        self.fill_light_label.grid(row=7, column=0)

    def stop(self):
        self.stopped = True

    def run(self):
        self.stopped = False

        fill_time = float(self.fill_time_entry.get())
        vent_time = float(self.vent_time_entry.get())

        # Get the number of cycles from the Entry widget
        num_cycles_input = self.entry.get()
        if num_cycles_input == "":
            self.output.insert(tk.END, "Please enter a valid number of cycles\n")
            return

        # Convert the input to an integer
        num_cycles = int(num_cycles_input)

        try:
            # Loop for the specified number of cycles
            for i in range(num_cycles):

                if self.stopped:
                    break

                # Turn on the Fill switch
                self.d.setDOState(ioNum=self.FILL_SWITCH, state=1)
                self.fill_light.itemconfig(self.fill_light_shape, fill='green')
                self.master.update()
                time.sleep(fill_time)

                # Turn off the Fill switch
                self.d.setDOState(ioNum=self.FILL_SWITCH, state=0)
                self.fill_light.itemconfig(self.fill_light_shape, fill='Red')
                self.master.update()
                time.sleep(vent_time)

                # Update the current cycle number display
                self.cycle_number.set("Current cycle completed: " + str(i+1) + "\n")
                self.master.update()

            # Display a message indicating that the loop is complete
            self.output.insert(tk.END,str(i+1) + "  Cycle complted"+ "\n")

        except Exception as e:
            # If an error occurs, stop the loop and display an error message
            self.output.insert(tk.END, "An error occurred: " + str(e) + "\n")

    def withdraw(self):
        self.master.withdraw()

root = tk.Tk()
app = Application(master=root)
app.mainloop()


""" Unit tests """

import json
import unittest
from unittest.mock import patch
from test.unit import mock_response
from requests.auth import HTTPBasicAuth
from requests import Session

from xcputils.ingestion.http import HttpIngestor, HttpMethod, HttpRequest

class TestHttpIngestor(unittest.TestCase):
    """ Test xcputils.ingest.http """

    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)

    @patch.object(Session, 'get')
    def test_get(self, mock_get):
        """ Test xcputils.ingest.get """

        mock_get.return_value = mock_response(json_data={"ip": "1.2.3.4"})
        result = HttpIngestor(
            http_request=HttpRequest(url="https://mock.com/ip")) \
            .write_to_string()
        self.assertTrue("ip" in result, f"key 'ip' not in: {result}")

    @patch.object(Session, 'get')
    def test_get_html(self, mock_get):
        """ Test xcputils.ingest.get HTML """

        mock_get.return_value = mock_response(content="<!DOCTYPE html>")
        result = HttpIngestor(
            http_request=HttpRequest(url="https://mock.com")) \
            .write_to_string()
        self.assertEqual(result[0:15], "<!DOCTYPE html>")

    @patch.object(Session, 'get')
    def test_auth(self, mock_get):
        """ Test xcputils.ingest.get authentication """

        mock_get.return_value = mock_response(json_data={"authenticated": True})
        result = HttpIngestor(
            http_request=HttpRequest(
                url="https://mock.com/basic-auth",
                auth=HTTPBasicAuth('postman', 'password'))) \
            .write_to_string()
        result = json.loads(result)
        self.assertEqual(result["authenticated"], True, result)

    @patch.object(Session, 'post')
    def test_post(self, mock_post):
        """ Test xcputils.ingest.post """

        data = {"test_key": "test_value"}

        mock_post.return_value = mock_response(json_data={"data" : data})
        result = HttpIngestor(
            http_request=HttpRequest(
                url="https://mock.com/post",
                method=HttpMethod.POST,
                body=data)
            ) \
            .write_to_string()
        result = json.loads(result)
        self.assertEqual(
            result["data"],
            data,
            f"Expected to contain data: {data}: {result}")

if __name__ == '__main__':
    unittest.main()


from setuptools import setup, find_packages
import textwrap
from yardstick.openstack.common import setup as common_setup

install_requires = common_setup.parse_requirements(['tools/pip-requires'])
install_options = common_setup.parse_requirements(['tools/pip-options'])
tests_require = common_setup.parse_requirements(['tools/test-requires'])
setup_require = common_setup.parse_requirements(['tools/setup-requires'])
dependency_links = common_setup.parse_dependency_links([
    'tools/pip-requires',
    'tools/pip-options',
    'tools/test-requires',
    'tools/setup-requires'
])

setup(
    name='yardstick',
    version=common_setup.get_version('yardstick'),
    description='DNS as a Service',
    author='Kiall Mac Innes',
    author_email='kiall@hp.com',
    url='https://launchpad.net/yardstick',
    packages=find_packages(exclude=['bin']),
    include_package_data=True,
    test_suite='nose.collector',
    setup_requires=setup_require,
    install_requires=install_requires,
    tests_require=tests_require,
    extras_require={
        'test': tests_require,
        'optional': install_options,
    },
    dependency_links=dependency_links,
    scripts=[
        'bin/yardstick',
    ],
    cmdclass=common_setup.get_cmdclass(),
    # entry_points=textwrap.dedent("""
    #     [yardstick.storage]
    #     sqlalchemy = yardstick.storage.impl_sqlalchemy:SQLAlchemyStorage
    # """),
)


# -*- coding: utf-8 -*-
# File   : prepare.py
# Author : Kai Ao
# Email  : capino627@163.com
# Date   : 2020/12/12 11:11
#
# This file is part of Rotation-Decoupled Detector.
# https://github.com/Capino512/pytorch-rotation-decoupled-detector
# Distributed under MIT License.

import sys

sys.path.append('.')

import os
import json
import numpy as np

from bs4 import BeautifulSoup as bs
from utils.box.bbox_np import xywha2xy4

def xml2json(dir_xml, dir_json):
    os.makedirs(dir_json, exist_ok=True)
    for xml in os.listdir(dir_xml):
        objs = []
        name = os.path.splitext(xml)[0]
        for obj in bs(open(os.path.join(dir_xml, xml)), "html.parser").findAll('hrsc_object'):
            xywha = []
            xywha.append(float(obj.select_one('mbox_cx').text))
            xywha.append(float(obj.select_one('mbox_cy').text))
            xywha.append(float(obj.select_one('mbox_w').text))
            xywha.append(float(obj.select_one('mbox_h').text))
            xywha.append(np.rad2deg(float(obj.select_one('mbox_ang').text)))
            obj = dict()
            obj['name'] = 'ship'
            obj['bbox'] = xywha2xy4(xywha).tolist()
            objs.append(obj)
        if objs:
            json.dump(objs, open(os.path.join(dir_json, name + '.json'), 'wt'), indent=2)

def main():
    # (1)
    dir_xml = os.path.join(dir_dataset, 'labelXml')
    out_dir_json = os.path.join(dir_dataset, 'annotations')
    xml2json(dir_xml, out_dir_json)

    # (2)
    out_dir = os.path.join(dir_dataset, 'image-sets')
    os.makedirs(out_dir, exist_ok=True)
    for image_set in ['trainval', 'test']:
        pairs = []
        with open(os.path.join(dir_dataset, 'ImageSets', f'{image_set}.txt')) as f:
            for line in f.readlines():
                line = line.strip()
                img = os.path.join('images', f'{line}.bmp')
                anno = os.path.join('annotations', f'{line}.json')
                if not os.path.exists(os.path.join(dir_dataset, anno)):
                    anno = None
                pairs.append([img, anno])
        json.dump(pairs, open(os.path.join(out_dir, f'{image_set}.json'), 'wt'), indent=2)

if __name__ == '__main__':

    # directory hierarchy

    # root/images/100000001.bmp
    # ----/images/...

    # root/labelXml/100000001.xml
    # ----/labelXml/...

    # (1) convert annotation files
    # (2) generate image-set files

    dir_dataset = '<replace with your local path>'

    main()


# The base of this code was copied from the below link:
# https://www.proxiesapi.com/blog/recursively-scraping-webpages-with-scrapy.html.php
# We will still be obeying the ROBOTS.txt file, and we will be taking in 'start_urls'
# from the google_search.py file.

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
import bisect

suggested_URLs = []

def lister(suggested_url):
    global suggested_URLs
    bisect.insort(suggested_URLs, suggested_url)
    # print(suggested_URLs)
    # print("\n\n\n\n")
    # suggested_URLs += [suggested_url]

def getURLs():
    return suggested_URLs

class WebWalkerSpider(CrawlSpider):
    name = 'web_walker'
    # start_urls = ['http://www.geeksforgeeks.org/']
    start_urls = []
    cont = True

    # Want to read in seeds from file walker_seeds.txt
    seeds = open('walker/spiders/walker_seeds.txt', 'r')
    num_url = 0

    while cont:
        num_url += 1
        url = seeds.readline()
        # print("Read URL: " + url)
        start_urls += [url]

        if not url:
            cont = False
            break

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    custom_settings = {
        'CONCURRENT_REQUESTS': 10,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 25,
        'CONCURRENT_ITEMS': 100,
        'REACTOR_THREADPOOL_MAXSIZE': 400,
        # Hides printing item dicts
        'LOG_LEVEL': 'INFO',
        'RETRY_ENABLED': False,
        'REDIRECT_MAX_TIMES': 1,
        # Stops loading page after 5mb
        'DOWNLOAD_MAXSIZE': 5592405,
        # Grabs xpath before site finish loading
        'DOWNLOAD_FAIL_ON_DATALOSS': False,
        'DEPTH_LIMIT' : 5,
        'DEPTH_PRIORITY': 1,
        'SCHEDULER_DISK_QUEUE' : 'scrapy.squeues.PickleFifoDiskQueue',
        'SCHEDULER_MEMORY_QUEUE' :'scrapy.squeues.FifoMemoryQueue'
    }

    def parse_item(self, response):
        # print('Downloaded... ' + response.url)
        # print(response.text)
        # print("ECDSA appears: " + str(response.text.count("ECDSA")))
        suggested = {}

        if (response.text.count(self.query) > 4):
            suggested = tuple((response.text.count(self.query), response.url))
            print(suggested)
            lister(suggested)

        yield

    def close(self, reason):
        print("****************************************SPIDER CLOSING****************************************")
        final_list = getURLs()
        final_list.reverse()
        for url in final_list:
            print(url)

        # In here, we should parse the page, identify the count of words that
        # match the keywords, and weight them according to matches and extensions

        # filename = 'storage/' response.url.split("/")[-1]   '.html'
        # print('Saving as :' filename)
        # with open(filename, 'wb') as f:
        #    f.write(response.body)


import requests
from framework.utils.logger import Logger
from framework.constants.methods import Methods

class API():

    def __init__(self, method: Methods, url, data=None):
        self.send_request(method, url, data)

    def send_request(self, method: Methods, url, data=None):
        Logger.info('Отправляю запрос "' + method.value + '" на ' + url)
        self.__url = url
        self.__data = data
        if method == Methods.GET:
            self.__response = requests.get(url=self.__url, data=self.__data)
        if method == Methods.POST:
            self.__response = requests.post(url=self.__url, data=self.__data)
        if method == Methods.PUT:
           self.__response = requests.put(url=self.__url, data=self.__data)
        if method == Methods.DELETE:
            self.__response = requests.put(url=self.__url, data=self.__data)
        if method == Methods.HEAD:
            self.__response = requests.head(url=self.__url, data=self.__data)
        if method == Methods.OPTIONS:
            self.__response = requests.options(url=self.__url, data=self.__data)

    def get_status(self):
        Logger.info('Получаю статус запроса')
        return self.__response.status_code

    def is_json(self):
        Logger.info('Проверка, являются ли полученные данные json')
        res = self.get_headers().get('content-type')
        return 'application/json' in res

    def get_json(self):
        Logger.info('Получаю данные в формате json')
        return self.__response.json()

    def get_headers(self):
        Logger.info('Получение заголовков')
        return self.__response.headers


from bs4 import BeautifulSoup
import urllib.request

url = 'http://planet.mu/releases/'
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
html = response.read()
soup = BeautifulSoup(html, "lxml")

artist = []
title = []
url = []

for bbr in soup.find_all(class_="box-inner"):
    ra = bbr.find_all(class_="release-artist")
    rt = bbr.find_all(class_="release-title")

    for art in ra:
     artist.append(art.text)
    for tit in rt:
     title.append(tit.text)
     for link in tit.find_all("a"):
         url.append(link['href'])


import requests
import json
from web3 import Web3
import abi
from datetime import datetime
from web3.logs import STRICT, IGNORE, DISCARD, WARN
from attributedict.collections import AttributeDict
from hexbytes import HexBytes

# Infura URL
url = 'https://mainnet.infura.io/v3/78069d72b81f4ecfb015f49e0801102f'
contractAddress = '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d'
web3 = Web3(Web3.HTTPProvider(url))
contract = web3.eth.contract(address=contractAddress, abi=abi.ABI)
# Hashed value of the Birth() event
birthEvent = Web3.toHex(Web3.keccak(text='Birth(address,uint256,uint256,uint256,uint256)'))

"""
Queries using Infura to retrieve logs.
The payload uses the Birth() event as a filter because we only care about those.
Returns data in json format.
"""
def getLogs(fromBlock, toBlock):
    print('Querying blocks from ', fromBlock, 'to ', toBlock)
    headers = {'content-type': 'application/json'}
    payload = {
        'jsonrpc':'2.0',
        'method':'eth_getLogs',
        'params': [
            {'address': contractAddress,
            'fromBlock': Web3.toHex(fromBlock),
            'toBlock': Web3.toHex(toBlock),
            'topics': [birthEvent]}
            ],
        'id':1
    }
    # Makes post requests
    r = requests.post(url, data = json.dumps(payload))
    # Converts byte list to json
    decodedContent = r.content.decode("utf-8")
    data = json.loads(decodedContent)
    return data

"""
This function is necessary as the log needs to be formatted in the way
'contract.events.Birth().processLog(log)' processes it.

Namely:
1.) The log must be converted from a Dictionary to an Attribute Dictionary.
2.) The hex numbers need to be converted from string to hexbytes for:
blockHash, topics, transactionHash
3.) blockNumber, logIndex, and transactionIndex must be converted from
hex string to integer
"""
def convertLog(log):
    log = AttributeDict(log)
    log.blockHash = HexBytes(int(log.blockHash, 16))
    log.transactionHash = HexBytes(int(log.transactionHash, 16))
    encodedTopics = []
    for topic in log.topics:
        encodedTopics.append(HexBytes(int(topic, 16)))

    log.topics = encodedTopics
    log.blockNumber = int(log.blockNumber,16)
    log.logIndex = int(log.logIndex,16)
    log.transactionIndex = int(log.transactionIndex,16)
    return log
    # print(log)

"""
Returns total births and the kitty with the most births from the starting block
to ending block.
Because Infura getLogs only allows for 10000 logs at a time, we have to call
getLogs multiple times in intervals. I'll set the interval to 5000.

Uses a Dictionary to keep track of the number of births of each matron, where
the key is the matron's ID.
For some reason, I'm encountering duplicate logs, so I'm using a Set to keep
track of the newborn kitties so I'm not counting repeats.
"""
def solveKitty(start, fin):
    INTERVAL = 5000
    totalBirths = mostBirths = naturalBirths = 0
    kittyWithMostBirths = None # stores ID of kitty with most births
    matrons = {} # Dictionary of natrons and the corresponding number of births
    newBorns = set() # Set of each new kitty that was born

    end = min(fin, start + INTERVAL) # Ending block of the current block interval
    while(start <= end):
        data = getLogs(start, end) # Retrieve logs from this interval

        for log in data['result']:
            # Decode the log to obtain the kittyId passed into the Birth event
            tx = log['transactionHash']
            """
            TOO SLOW and goes past Infura's usage limit
            ------------------------------------------------
            receipt = web3.eth.getTransactionReceipt(tx)
            logs = contract.events.Birth().processReceipt(receipt)
            """

            log = convertLog(log)
            # processed_log = contract.events.Birth().processLog(receipt['logs'][0])
            logs = contract.events.Birth().processLog(log)

            # If the newBorn is a duplicate, ignore it
            newBornId = logs['args']['kittyId']
            if newBornId in newBorns:
                continue

            totalBirths += 1

            newBorns.add(newBornId)
            matronId = logs['args']['matronId']
            if matronId != 0:
                naturalBirths += 1

            # print('Processing kittyId ', kittyId)
            # Store kittyID into dictionary
            if matronId in matrons:
                matrons[matronId] += 1
            else:
                matrons[matronId] = 1
            # If matronId == 0, the cat is 1st generation so it doesn't count
            if matrons[matronId] > mostBirths and matronId != 0:
                mostBirths = matrons[matronId]
                kittyWithMostBirths = matronId

        print('total births so far: ', totalBirths)
        print('most births so far: ', mostBirths, ' by ', kittyWithMostBirths)

        start = start + INTERVAL + 1
        end = min(fin, start + INTERVAL)

    # print(matrons)
    # print('\n', newBorns)
    return (totalBirths, naturalBirths, mostBirths, kittyWithMostBirths)

"""
Calls contract method getKitty to get kitty's data
"""
def getKittyData(kittyId):
    kittyData = contract.functions.getKitty(kittyId).call()
    """
    GetKitty returns:
        bool isGestating,
        bool isReady,
        uint256 cooldownIndex,
        uint256 nextActionAt,
        uint256 siringWithId,
        uint256 birthTime,
        uint256 matronId,
        uint256 sireId,
        uint256 generation,
        uint256 genes
    """
    if kittyData == None:
        return None
    return (kittyData[5], kittyData[8], kittyData[9])

if __name__ == '__main__':
    # startingBlock=6607985 and endingBlock=7028323
    totalBirths, naturalBirths, mostBirths, kittyWithMostBirths = solveKitty(6607985, 7028323)
    print('FINAL ANSWER -------------------------')
    print('total births: ', totalBirths)
    print('natural births ', naturalBirths)
    print('most births: ', mostBirths)
    print('kitty with most births: ', kittyWithMostBirths)
    birthTime, generation, genes = getKittyData(kittyWithMostBirths)
    birthTime = datetime.fromtimestamp(birthTime)
    print('birthTime=', birthTime,' generation=', generation, ' genes=', genes)


from asyncio.windows_events import NULL
import csv
import cantools
import struct
import json

dbcMessages = []
dbcSignals = []

class PacketManager:
    def createPacketDict(packets_file):
        if(packets_file.endswith('.csv')):
            packet_dict = {}
            packets = []
            fieldNames = ['Timestamp', 'Type', 'ID', 'Data']
            with open(packets_file, newline='\n') as csvfile:
                reader = csv.DictReader(csvfile, fieldnames=fieldNames, delimiter=';')
                i = 0
                for row in reader:
                    #print(row)
                    packets.append(row)
            #print(packets)
            return packets
        elif(packets_file.endswith('.log')):
            packet_dict = {}

    def loadDBCFile(filename):
        print("DBC loading")
        db = cantools.database.load_file(filename)
        i = 0
        nodeList = {}
        for x in db.messages:
            print("")
            print("Message ",i,": ", x)
            print("Signals ",i,": ", x.signals)

            splitMessage = str(x).split(",")
            print("split messages: ", splitMessage)

            annotation = splitMessage[0].split("'")[1::2]
            annotation = str(annotation).strip("[']")
            nodeName = splitMessage[4].split("'")[1::2]
            nodeName = str(nodeName).strip("[']")
            nodeID = splitMessage[1][1:]
            node = {
                "Node_Name": nodeName,
                "Project_ID": '1.1.0',
                "Node_ID": nodeID,
                "Annotation": annotation,
                "Icon_Path": "",
                "xyPosition": ""
            }
            nodeList[i] = node
            i+=1
        return db, nodeList

    def translatePackets(packetID, packetData, timestamp, db):

        reformatedID = int(packetID, 16)
        reformatedData = b''.join([struct.pack('B', int(''.join(x),16)) for x in zip(packetData[0::2], packetData[1::2])])
        try:
            #example for 0x18fef1fe, when translated into Decimal
            #  0x18fef1fe(hex) == 419361278(decimal)
            #  0xcf00203 == 217,055,747
            decoded_message = db.decode_message(reformatedID, reformatedData)
            print(decoded_message)
            print("")
            canID = ''
            if("STATUS" in decoded_message):
                canID = '0x190'

            if("CMD" in decoded_message):
                canID = '0x65'

            if("SENSOR" in decoded_message):
                canID = '0xc8'

            if("IO" in decoded_message):
                canID = '0x1f4'

            if("HEARTBEAT" in decoded_message):
                canID = '0x64'
            if("Engine" in decoded_message):
                canID = '0Xcf004fe'
            if("Wheel" in decoded_message):
                canID = '0Xcf004fe'
            # endFrame = timestamp+=1

            packetJ = {
                "PacketID": packetID,
                "NodeID": "1",
                "Frame_Start": timestamp,
                "CAN_ID" : canID,
                "Control_Field": "1",
                "Data_Field": decoded_message,
                "CRC_Field": "",
                "ACK": "1",
                "Frame_End": timestamp,
            }

            packetJson = {
                "timestamp": timestamp,
                "packet_id": packetID,
                "packet_data": packetData,
                "decoded_message": decoded_message,
                "decoded_id": reformatedID,
            }
            return packetJ
        except:
            pass

            #print('No Message found')

db, nodeList = PacketManager.loadDBCFile("C:\\Users\\chris\\OneDrive\\Documents\\SCHOOL\\CAN-Bus Visualizer\\packetID\\CSS-Electronics-SAE-J1939-DEMO.dbc")
# db = PacketManager.loadDBCFile('j1939.dbc')
# db, nodeList = PacketManager.loadDBCFile('practiceDBC.dbc')

print(json.dumps(nodeList, indent=4))
#PacketManager.translatePackets(id, data, db)
packetCSV = PacketManager.createPacketDict('packets1.csv')
packetCSV.pop(0)   #removes first line
print("")
packetList = {}
i = 0
for x in packetCSV:
    id = (x['ID'])
    data = (x['Data'])
    timestamp = (x['Timestamp'])
    packetInfo = PacketManager.translatePackets(id, data, timestamp, db)
    if(packetInfo):
        #print(packetInfo)
        packetList[i] = (packetInfo)
        i+=1
# out : {'Timestamp;Type;ID;Data': '11T082557132;1;cf00203;cde0270004b827ff'}
# out : {'Timestamp;Type;ID;Data': '11T082557132;1;18fe592f;ffffffffe37cdd7c'}
print(json.dumps(packetList, indent =4 ))


"""
その日に工事する辺をランダム選択
選択する数は毎日同じ数になるようにならす

"""

def main():
    from sys import stdin
    input = stdin.readline

    import random

    # 入力を受け取る
    N, M, D, K = map(int, input().split())
    r = [0] * M

    # 処理
    # 一日に工事する辺の数
    construct_num_per_day = min((M // D) + 1, K)
    edge = set(range(1, M+1))
    for i in range(1, D+1):
        sample_i = random.sample(edge, min(len(edge), construct_num_per_day))
        edge = edge - set(sample_i)
        for j in sample_i:
            r[j-1] = i

    # 答えを出力
    print(*r)

if __name__ == '__main__':
    main()


import numpy

#Get number of arrays for each variable
N = int(input())

a = []
b = []

#Get N values for each variable
for _ in range(N):
    a.append(list(map(int, input().split())))

for _ in range(N):
    b.append(list(map(int, input().split())))

#Convert them to numpy arrays
a = numpy.array(a)
b = numpy.array(b)

#Perform matrix multiplication then print
print(numpy.dot(a,b))


from typing import (
    Any,
    Dict,
    List,
    Optional,
)

from easypost.easypost_object import convert_to_easypost_object
from easypost.models import Tracker
from easypost.requestor import (
    RequestMethod,
    Requestor,
)
from easypost.services.base_service import BaseService

class TrackerService(BaseService):
    def __init__(self, client):
        self._client = client
        self._model_class = Tracker.__name__

    def create(self, **params) -> Tracker:
        """Create a Tracker."""
        return self._create_resource(self._model_class, **params)

    def all(self, **params) -> Dict[str, Any]:
        """Retrieve a list of Trackers."""
        url = self._class_url(self._model_class)

        response = Requestor(self._client).request(method=RequestMethod.GET, url=url, params=params)
        response["tracking_code"] = params.get("tracking_code")
        response["carrier"] = params.get("carrier")

        return convert_to_easypost_object(response=response)

    def retrieve(self, id: str) -> Tracker:
        """Retrieve a Tracker."""
        return self._retrieve_resource(self._model_class, id)

    def get_next_page(
        self,
        trackers: Dict[str, Any],
        page_size: int,
        optional_params: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Retrieve the next page of the list Tracker response."""
        optional_params = {
            "tracking_code": trackers.get("tracking_code"),
            "carrier": trackers.get("carrier"),
        }

        return self._get_next_page_resources(self._model_class, trackers, page_size, optional_params)

    def create_list(self, trackers: List[Dict[str, Any]]) -> None:
        """Create a list of Trackers."""
        url = f"{self._class_url(self._model_class)}/create_list"
        wrapped_params = {"trackers": trackers}

        Requestor(self._client).request(method=RequestMethod.POST, url=url, params=wrapped_params)


# -*- coding: utf-8 -*-
from argparse import ArgumentParser

from tqdm import tqdm
import wandb
import numpy as np
import random, os

import torch
from torch.utils.data import DataLoader
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.distributed as dist
from torch.utils.data.distributed import DistributedSampler
from torch.optim.lr_scheduler import ReduceLROnPlateau
import torch.multiprocessing as mp

from model import DecoderTTS
from load_dataset import PrepareDataset, collate_fn
import trainer
import hparams as hp
import writer
SEED=44

def init_process(rank, size, backend='nccl'):
    """ Initialize the distributed environment. """

    dist.init_process_group(
        backend=backend,
        init_method='env://',
        world_size=size,
        rank=rank
    )

def get_model():
    return DecoderTTS(idim=hp.hidden_dim)

def get_dataloader(rank, world_size):

    dataset = PrepareDataset(hp.meta_file, hp.dumpdir)

    train_size = int(0.9 * len(dataset))
    val_size = len(dataset) - train_size
    train_set, val_set = torch.utils.data.random_split(dataset, [train_size, val_size])

    sampler = DistributedSampler(train_set, rank=rank, num_replicas=world_size)

    batch_size = hp.batch_size // world_size

    train_loader = DataLoader(train_set,
                            batch_size=batch_size,
                            collate_fn=collate_fn,
                            num_workers=8,
                            sampler=sampler)
    val_loader = DataLoader(val_set,
                            batch_size=batch_size,
                            shuffle=False,
                            collate_fn=collate_fn,
                            num_workers=8)

    return train_loader, val_loader

def train(rank, world_size):
    init_process(rank, world_size)
    print(f"Rank {rank}/{world_size} training process initialized.\n")
    torch.cuda.set_device(rank)
    # master process gets data
    if rank == 0:
        get_dataloader(rank, world_size)
        get_model()
    dist.barrier()

    m = get_model()
    m.cuda()
    m = DDP(m, device_ids=[rank])
    train_loader, val_loader = get_dataloader(rank, world_size)

    optimizer = torch.optim.Adam(m.parameters(), lr=0.0001  * world_size)
    l1_loss = torch.nn.L1Loss()
    bce_loss = torch.nn.BCEWithLogitsLoss(pos_weight=torch.tensor(hp.bce_weights))

    n_epochs = hp.n_epochs

    if rank == 0: writer.init_wandb(m)

    dist.barrier()

    best_loss = 1e10
    for epoch in range(n_epochs):
        train_loss = trainer.train_fn(m, train_loader, optimizer, l1_loss, bce_loss)
        val_loss, spec_fig, gate_fig, alignment_fig = trainer.eval_fn(m, val_loader, l1_loss, bce_loss)
        print(f'TRAIN LOSS = {sum(train_loss)} | VAL LOSS = {sum(val_loss)} | \n')

        # Log the loss and accuracy values at the end of each epoch
        if rank == 0: writer.log_wandb(epoch, train_loss, val_loss, spec_fig, gate_fig, alignment_fig)

        if best_loss > sum(val_loss):
            best_loss = sum(val_loss)
            torch.save(m.state_dict(), 'checkpoints/model'+str(epoch)+'.pth')
    dist.destroy_process_group()

WORLD_SIZE = torch.cuda.device_count()
def main():
    try:
        mp.spawn(train, args=(WORLD_SIZE,),
                nprocs=WORLD_SIZE, join=True)
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            dist.destroy_process_group()
        except KeyboardInterrupt:
            os.system("kill $(ps aux | grep multiprocessing.spawn | grep -v grep | awk '{print $2}') ")

if __name__ == "__main__":
    main()


import os
import re

from siliconcompiler.tools.surelog.surelog import setup as setup_tool

##################################################
def setup(chip):
    '''
    Import verilog files
    '''

    # Generic tool setup.
    setup_tool(chip)

    tool = 'surelog'
    step = chip.get('arg', 'step')
    index = chip.get('arg', 'index')
    task = chip._get_task(step, index)

    # Runtime parameters.
    chip.set('tool', tool, 'task', task, 'threads', os.cpu_count(),
             step=step, index=index, clobber=False)

    # Command-line options.
    options = []
    # -parse is slow but ensures the SV code is valid
    # we might want an option to control when to enable this
    # or replace surelog with a SV linter for the validate step
    options.append('-parse')
    # We don't use UHDM currently, so disable. For large designs, this file is
    # very big and takes a while to write out.
    options.append('-nouhdm')
    # Write back options to cfg
    chip.add('tool', tool, 'task', task, 'option', options, step=step, index=index)

    # Input/Output requirements
    chip.add('tool', tool, 'task', task, 'output', chip.top() + '.v', step=step, index=index)

    # Schema requirements
    chip.add('tool', tool, 'task', task, 'require', ",".join(['input', 'rtl', 'verilog']),
             step=step, index=index)

    libs = []
    libs.extend(chip.get('asic', 'logiclib', step=step, index=index))
    libs.extend(chip.get('asic', 'macrolib', step=step, index=index))

    def add_require_if_set(*key):
        if not chip.valid(*key):
            return
        if not chip.get(*key):
            return

        chip.add('tool', tool, 'task', task, 'require', ",".join(key),
                 step=step, index=index)

    opt_require = ['ydir', 'idir', 'vlib', 'cmdfile']
    for opt in opt_require:
        add_require_if_set('option', opt)
        for lib in libs:
            add_require_if_set('library', lib, 'option', opt)

################################
#  Custom runtime options
################################
def _remove_dups(chip, type, file_set):
    new_files = []
    for f in file_set:
        if f not in new_files:
            new_files.append(f)
        else:
            chip.logger.warning(f"Removing duplicate '{type}' inputs: {f}")
    return new_files

def runtime_options(chip):

    ''' Custom runtime options, returnst list of command line options.
    '''

    step = chip.get('arg', 'step')
    index = chip.get('arg', 'index')

    cmdlist = []

    libs = []
    libs.extend(chip.get('asic', 'logiclib', step=step, index=index))
    libs.extend(chip.get('asic', 'macrolib', step=step, index=index))

    #####################
    # Library directories
    #####################

    ydir_files = chip.find_files('option', 'ydir')

    for item in libs:
        ydir_files.extend(chip.find_files('library', item, 'option', 'ydir'))

    # Deduplicated source files
    for value in _remove_dups(chip, 'ydir', ydir_files):
        cmdlist.append('-y ' + value)

    #####################
    # Library files
    #####################

    vlib_files = chip.find_files('option', 'vlib')

    for item in libs:
        vlib_files.extend(chip.find_files('library', item, 'option', 'vlib'))

    for value in _remove_dups(chip, 'vlib', vlib_files):
        cmdlist.append('-v ' + value)

    #####################
    # Include paths
    #####################

    idir_files = chip.find_files('option', 'idir')

    for item in libs:
        idir_files.extend(chip.find_files('library', item, 'option', 'idir'))

    for value in _remove_dups(chip, 'idir', idir_files):
        cmdlist.append('-I' + value)

    #######################
    # Variable Definitions
    #######################

    # Extra environment variable defines (don't need deduplicating)
    for value in chip.get('option', 'define'):
        cmdlist.append('-D' + value)

    for item in libs:
        for value in chip.get('library', item, 'option', 'define'):
            cmdlist.append('-D' + value)

    #######################
    # Command files
    #######################

    # Command-line argument file(s).
    cmd_files = chip.find_files('option', 'cmdfile')

    for item in libs:
        cmd_files.extend(chip.find_files('library', item, 'option', 'cmdfile'))

    for value in _remove_dups(chip, 'cmdfile', cmd_files):
        cmdlist.append('-f ' + value)

    #######################
    # Sources
    #######################

    src_files = chip.find_files('input', 'rtl', 'verilog', step=step, index=index)

    # TODO: add back later
    # for item in libs:
    #    src_files.extend(chip.find_files('library', item, 'input', 'verilog'))

    for value in _remove_dups(chip, 'source', src_files):
        cmdlist.append(value)

    #######################
    # Top Module
    #######################

    cmdlist.append('-top ' + chip.top())

    ###############################
    # Parameters (top module only)
    ###############################

    # Set up user-provided parameters to ensure we elaborate the correct modules
    for param in chip.getkeys('option', 'param'):
        value = chip.get('option', 'param', param)
        cmdlist.append(f'-P{param}={value}')

    return cmdlist

##################################################
def post_process(chip):
    ''' Tool specific function to run after step execution
    '''

    # https://github.com/chipsalliance/Surelog/issues/3776#issuecomment-1652465581
    surelog_escape = re.compile(r"#~@([a-zA-Z_0-9.\$/\:\[\] ]*)#~@")

    # Look in slpp_all/file_elab.lst for list of Verilog files included in
    # design, read these and concatenate them into one pickled output file.
    with open('slpp_all/file_elab.lst', 'r') as filelist, \
            open(f'outputs/{chip.top()}.v', 'w') as outfile:
        for path in filelist.read().split('\n'):
            path = path.strip('"')
            if not path:
                # skip empty lines
                continue
            with open(path, 'r') as infile:
                infile_data = infile.read()
                unescaped_data = surelog_escape.sub(r"\\\1 ", infile_data)
                outfile.write(unescaped_data)
                if not unescaped_data.endswith('\n'):
                    # in case end of file is missing a newline
                    outfile.write('\n')


# -*- coding: utf-8 -*-
"""Console script for flipdot_controller."""
import logging
import sys
import time

import click
from serial import Serial

from flipdot_controller.config import ConfigParser
from flipdot_controller.controller import FlipdotController
from flipdot_controller.server import Server

@click.command()
@click.option('--config',
              type=click.Path(exists=True),
              required=True,
              help="TOML config file")
def main(config):
    """Console script for flipdot_controller."""
    logging.basicConfig(level=logging.DEBUG)
    # Read the config
    parser = ConfigParser.create(config)
    # Create controller from config
    with Serial(parser.basic_config['serial_port']) as ser, FlipdotController(
            port=ser, signs=parser.signs_config,
            pins=parser.pin_config) as controller:
        server = Server(controller, port=parser.basic_config['grpc_port'])
        try:
            server.start()
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            server.stop()

if __name__ == "__main__":
    sys.exit(main())  # pylint: disable=E1120


import numpy as np
import time
from src.utils.utils import *

client = None
world = None
carlaMap = None

def main():
    destroy_all_actors(client, world)

    start_time = time.time()
    bp_library = world.get_blueprint_library()
    bp = bp_library.find('vehicle.tesla.model3')
    bp.set_attribute('role_name', 'ego')
    color = bp.get_attribute('color').recommended_values
    bp.set_attribute('color', color[0])

    spawn_points = carlaMap.get_spawn_points()
    ego_tf = spawn_points[0]
    ego = world.spawn_actor(bp, carla.Transform(ego_tf.location + carla.Location(0, 0, 0.6), ego_tf.rotation))

    spectator = world.get_spectator()
    spectator.set_transform(carla.Transform(ego_tf.location, ego_tf.rotation))

    flag = True
    change_wp = None
    i = 0
    while True:
        ego_wp = carlaMap.get_waypoint(ego.get_transform().location)
        if flag and time.time() - start_time > 10:
            print('---try to change lane---')
            change_wp = change_lane(ego)
            flag = False
        if change_wp and change_wp.transform.location.distance(ego.get_transform().location) < 1:
            next_wps = change_wp.next(10)
            if ego_wp.is_junction:
                i += 1
                print('at junction %d --- %d next points' % (i, len(next_wps)))
                change_wp = None
                for wp in next_wps:
                    if compute_connection(ego_wp, wp) == RoadOption.RIGHT:
                        print('turn right')
                        change_wp = wp
                if not change_wp:
                    change_wp = next_wps[0]
            else:
                change_wp = next_wps[0]

        ego_control = carla.VehicleControl()
        ego_control.throttle = 0.3
        if change_wp:
            steer = calculate_steer(change_wp, ego.get_transform())
            ego_control.steer = steer
            # print('change lane; steer %f' % (steer))
        ego.apply_control(ego_control)

def change_lane(vehicle, direction=None):
    """
    变道，返回坐车道或者右车道下一个路径点
    :param vehicle: 控制的车辆
    :param direction: 变道方向
    :return: 路径点
    """
    current_tf = vehicle.get_transform()
    current_wp = carlaMap.get_waypoint(current_tf.location)
    left_wp = current_wp.get_left_lane()
    right_wp = current_wp.get_right_lane()
    change_wp = None
    if left_wp and left_wp.lane_id * current_wp.lane_id > 0:
        change_wp = left_wp.next(10)[0]
    elif right_wp and right_wp.lane_id * current_wp.lane_id > 0:
        change_wp = right_wp.next(10)[0]
    return change_wp

def keep_forward(vehicle):
    """
    让车辆保持目前的速度、沿着当前道路行驶，返回导航的下一个路径点。
    :param vehicle: 控制车辆
    :return: 下一个路径点
    """
    current_tf = vehicle.get_transform()
    current_wp = carlaMap.get_waypoint(current_tf.location)
    return current_wp.next(10)[0]

def calculate_steer(waypoint, vehicle_transform, k_p=1.0, k_d=0.0, k_i=0.0, dt=0.03):
    """
    根据当前位置和下一个目标位置计算汽车转向
    :param waypoint: carla_simulator.Waypoint 下一个路径点
    :param vehicle_transform: carla_simulator.Transform 汽车当前位置
    :param k_p: 比例系数
    :param k_d: 微分系数
    :param k_i: 积分系数
    :param dt: 时间间隔
    :return: [-1,1] 汽车方向
    """
    v_begin = vehicle_transform.location
    v_end = v_begin + carla.Location(x=math.cos(math.radians(vehicle_transform.rotation.yaw)),
                                     y=math.sin(math.radians(vehicle_transform.rotation.yaw)))

    v_vec = np.array([v_end.x - v_begin.x, v_end.y - v_begin.y, 0.0])
    w_vec = np.array([waypoint.transform.location.x -
                      v_begin.x, waypoint.transform.location.y -
                      v_begin.y, 0.0])
    _dot = math.acos(np.clip(np.dot(w_vec, v_vec) /
                             (np.linalg.norm(w_vec) * np.linalg.norm(v_vec)), -1.0, 1.0))

    _cross = np.cross(v_vec, w_vec)

    if _cross[2] < 0:
        _dot *= -1.0
    _de = 0.0
    _ie = 0.0

    return np.clip((k_p * _dot) + (k_d * _de) + (k_i * _ie), -1.0, 1.0)

def compute_connection(current_wpt,  target_wpt, threshold=30):
    """
    计算目前路径点和目标路径点的方向关系
    :param current_wpt: 当前路径点
    :param target_wpt: 目标路径点
    :param threshold: 比较阈值
    :return: 方向
    """
    n = target_wpt.transform.rotation.yaw
    n %= 360.0

    c = current_wpt.transform.rotation.yaw
    c %= 360.0

    diff_angle = (n - c) % 180.0
    if diff_angle < threshold or diff_angle > (180 - threshold):
        return RoadOption.FOLLOW_LANE
    elif diff_angle > 90.0:
        return RoadOption.LEFT
    else:
        return RoadOption.RIGHT

if __name__ == "__main__":
    client = carla.Client('127.0.0.1', 2000)
    world = client.get_world()
    carlaMap = world.get_map()
    try:
        main()
    finally:
        destroy_all_actors(client, world)


# 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性：
#
#
#  每行的元素从左到右升序排列。
#  每列的元素从上到下升序排列。
#
#
#  示例:
#
#  现有矩阵 matrix 如下：
#
#  [
#   [1,   4,  7, 11, 15],
#   [2,   5,  8, 12, 19],
#   [3,   6,  9, 16, 22],
#   [10, 13, 14, 17, 24],
#   [18, 21, 23, 26, 30]
# ]
#
#
#  给定 target = 5，返回 true。
#
#  给定 target = 20，返回 false。
#  Related Topics 二分查找 分治算法
#  👍 483 👎 0
import math

# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """

        max_i = len(matrix)
        max_j = len(matrix[0])

        i = 0
        j = len(matrix[0]) - 1
        while max_i > i >= 0 and max_j > j >= 0:
            if target > matrix[i][j]:
                i += 1
            elif target < matrix[i][j]:
                j -= 1
            else:
                return True
        return False

        #通过二分法把矩阵分成四块，每次可以排除一块，然后在其余三个方块做迭代
        #不同的分法可以简化代码
        # def bin_sch(x_start, x_end, y_start, y_end, target, matrix,min_x,max_x,min_y,max_y):
        #
        #     if min_x > x_start  or x_start >= max_x or \
        #             min_x > x_end  or x_end >= max_x or \
        #             min_y > y_start  or y_start >= max_y or \
        #             min_y > y_end  or y_end >= max_y:
        #         return False
        #
        #     if x_start == x_end and y_start == y_end:
        #         return matrix[x_start][y_start] == target
        #
        #     i = (x_start + x_end)>>1
        #     j = (y_start + y_end)>>1
        #     print(i,",",j)
        #
        #     if matrix[i][j] == target:
        #         return True
        #     elif matrix[i][j] > target:
        #         return bin_sch(x_start, i-1, y_start, j-1, target, matrix,x_start, i, y_start, j) \
        #                or bin_sch(x_start, i-1, j, y_end, target, matrix,x_start, i, j, y_end+1) \
        #                or bin_sch(i, x_end, y_start, j-1, target, matrix,i, x_end+1, y_start, j)
        #     else:
        #         return bin_sch(x_start, i, j+1, y_end, target, matrix,x_start, i+1, j+1, y_end+1) \
        #                or bin_sch(i+1, x_end, y_start, j, target, matrix,i+1, x_end+1, y_start, j+1) \
        #                or bin_sch(i+1, x_end, j+1, y_end, target, matrix,i+1, x_end+1, j+1, y_end+1)
        #
        # return bin_sch(0, len(matrix)-1, 0, len(matrix[0])-1, target, matrix,0, len(matrix), 0, len(matrix[0]))

# leetcode submit region end(Prohibit modification and deletion)
if __name__ == "__main__":
    matrix = [
        [1, 4, 7, 11, 15],
        [2, 5, 8, 12, 19],
        [3, 6, 9, 16, 22],
        [10, 13, 14, 17, 24],
        [18, 21, 23, 26, 30]
    ]
    res = Solution().searchMatrix(matrix, 0)
    print(res)


from __future__ import annotations
from datetime import datetime

from models.base import Base

class Report(Base):
    _CLASS: str = "report"
    _properties: dict[str, object] = {
        "user": str,
        "experiment": str,
        "module": str,
        "timestamp": datetime.fromisoformat,
        "running": bool,
        "datapoints": int,
    }

    user: str = None
    experiment: str = None
    module: str = None
    timestamp: datetime = None
    running: bool = None
    datapoints: int = None

    def toDict(self) -> dict:
        return {
            "user": self.user,
            "experiment": self.experiment,
            "module": self.module,
            "timestamp": self.timestamp.isoformat(),
            "running": self.running,
            "datapoints": self.datapoints
        }

    @classmethod
    def fromDict(cls: Report, data: dict) -> Report | None:
        if not cls.isValid(data):
            return None

        model: Report = Report(f'{data["user"]}-{data["experiment"]}', cls._CLASS)

        model.user = cls._properties["user"](data["user"])
        model.experiment = cls._properties["experiment"](data["experiment"])
        model.module = cls._properties["module"](data["module"])
        model.timestamp = cls._properties["timestamp"](data["timestamp"])
        model.running = cls._properties["running"](data["running"])
        model.datapoints = cls._properties["datapoints"](data["datapoints"])

        return model


import os
import math
import unicodedata
import string

# http://www.asahi-net.or.jp/~ax2s-kmtn/ref/unicode/e_asia.html
CJK_INTERVALS = [
    (0x4E00, 0x9FFF, 'CJK Unified Ideographs'),
    (0x3400, 0x4DBF, 'CJK Unified Ideographs Extension A'),
    (0x20000, 0x2A6DF, 'CJK Unified Ideographs Extension B'),
    (0x2A700, 0x2B73F, 'CJK Unified Ideographs Extension C'),
    (0x2B740, 0x2B81F, 'CJK Unified Ideographs Extension D'),
    (0xF900, 0xFAFF, 'CJK Compatibility Ideographs'),
    (0x2F800, 0x2FA1D, 'CJK Compatibility Ideographs Supplement'),
    (0x3190, 0x319F , 'Kanbun'),
    (0x2E80, 0x2EFF, 'CJK Radicals Supplement'),
    (0x2F00, 0x2FDF, 'CJK Radicals'),
    (0x31C0, 0x31EF, 'CJK Strokes'),
    (0x2FF0, 0x2FFF, 'Ideographic Description Characters'),
    (0xE0100, 0xE01EF, 'Variation Selectors Supplement'),
    (0x3100, 0x312F, 'Bopomofo'),
    (0x31A0, 0x31BF, 'Bopomofo Extended'),
    (0xFF00, 0xFFEF, 'Halfwidth and Fullwidth Forms'),
    (0x3040, 0x309F, 'Hiragana'),
    (0x30A0, 0x30FF, 'Katakana'),
    (0x31F0, 0x31FF, 'Katakana Phonetic Extensions'),
    (0x1B000, 0x1B0FF, 'Kana Supplement'),
    (0xAC00, 0xD7AF, 'Hangul Syllables'),
    (0x1100, 0x11FF, 'Hangul Jamo'),
    (0xA960, 0xA97F, 'Hangul Jamo Extended A'),
    (0xD7B0, 0xD7FF, 'Hangul Jamo Extended B'),
    (0x3130, 0x318F, 'Hangul Compatibility Jamo'),
    (0xA4D0, 0xA4FF, 'Lisu'),
    (0x16F00, 0x16F9F, 'Miao'),
    (0xA000, 0xA48F, 'Yi Syllables'),
    (0xA490, 0xA4CF, 'Yi Radicals'),
]

def is_CJK(c):
    n = ord(c)
    for imin,imax,name in CJK_INTERVALS:
        if n>=imin and n<=imax: return True
    return False

def normalize_text(seed):
    # normalize
    seed = unicodedata.normalize('NFKD', seed)
    # lower
    seed = seed.lower()
    # remove accents
    seed = u''.join([c for c in seed if not unicodedata.combining(c)])
    # normalize whitespaces
    seed = u' '.join(seed.split())
    # remove whitespaces between CJK
    seed = u''.join([seed[i] for i in range(len(seed)) if not (seed[i] in string.whitespace and is_CJK(seed[i-1]) and is_CJK(seed[i+1]))])
    return seed

def load_wordlist(filename):
    path = os.path.join(os.path.dirname(__file__), 'wordlist', filename)
    with open(path, 'r') as f:
        s = f.read().strip()
    s = unicodedata.normalize('NFKD', s)
    lines = s.split('\n')
    wordlist = []
    for line in lines:
        line = line.split('#')[0]
        line = line.strip(' \r')
        assert ' ' not in line
        if line:
            wordlist.append(line)
    return wordlist

filenames = {
    'en':'english.txt',
    'es':'spanish.txt',
    'ja':'japanese.txt',
    'pt':'portuguese.txt',
    'zh':'chinese_simplified.txt'
}

class Mnemonic(object):
    # Seed derivation no longer follows BIP39
    # Mnemonic phrase uses a hash based checksum, instead of a wordlist-dependent checksum

    def __init__(self, lang=None):
        lang = lang or 'en'
        if lang not in filenames:
            raise Exception('lang must be one of '+', '.join(filenames.keys()))
        filename = filenames.get(lang[0:2], 'english.txt')
        self.wordlist = load_wordlist(filename)
       #print("wordlist has %d words"%len(self.wordlist))

    #TODO figure out why electrum uses this (with a blank password) somewhere
    #@classmethod
    #def mnemonic_to_seed(self, mnemonic, passphrase):
    #    PBKDF2_ROUNDS = 2048
    #    mnemonic = normalize_text(mnemonic)
    #    passphrase = normalize_text(passphrase)
    #    return pbkdf2.PBKDF2(mnemonic, 'electrum' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)

    def mnemonic_encode(self, i):
        n = len(self.wordlist)
        words = []
        while i:
            x = i%n
            i = i//n
            words.append(self.wordlist[x])
        return ' '.join(words)

    def mnemonic_decode(self, seed):
        n = len(self.wordlist)
        words = seed.split()
        i = 0
        while words:
            w = words.pop()
            k = self.wordlist.index(w)
            i = i*n + k
        return i

    def make_seed(self, num_bits=132):
        #TODO platform independence
        with open('/proc/sys/kernel/random/entropy_avail', 'r') as f:
            sys_entopy_avail = int(f.readline())
            if(sys_entopy_avail < num_bits): raise Exception('not enough entropy')

        bpw = math.log(len(self.wordlist), 2)
        num_bits = int(math.ceil(num_bits/bpw) * bpw)
        entropy = 1
        # generate a random number s.t.
        # 2**(num_bits-bpw) < entropy < 2**(num_bits)
        # this condition keeps the seed phrase a constant length
        # and keeps the bits of entropy above the minimum

        # need exactly n bits, not ceil(n/8) bytes
        # so generate ceil(n/8) bytes then strip most significant bits
        num_bytes = math.ceil(num_bits/8)
        excess_bits = num_bytes * 8 - num_bits
        while(True):
            random_bytes = os.urandom(num_bytes)
            entropy = int.from_bytes(random_bytes, 'big', signed=False) >> excess_bits

            # keep the number if it will produce the right number of words, otherwise try again
            if(entropy > 2**(num_bits-bpw)): break

        assert 2**(num_bits-bpw) < entropy
        assert entropy < 2**num_bits

        seed = self.mnemonic_encode(entropy)
        assert entropy == self.mnemonic_decode(seed)

        return seed

if __name__ == '__main__':
    m = Mnemonic()
    counter = 0
    while(True):
        if(len(m.make_seed().split()) != 12):
            raise Exception('fuck')
        #print(m.make_seed())
        counter = counter + 1
        if(counter % 1000 == 0): print('generated',counter)


from urllib.request import urlopen as req
from bs4 import BeautifulSoup as soup

def GoldPrice():
	#ปป.แค่ symbol = GPSC
	url = f'https://www.goldtraders.or.th/'
	webopen = req(url)    #เปิดเว็ปโดยไม่เปิด Web Browser urllib.request ทำการดึง(request)
	page_html = webopen.read() # สั่ง read เป็น text , Code html ไปใช้งานต่อ
	webopen.close() # ปิดการ request
	data = soup(page_html,'html.parser') # soupทำการอ่านข้อมูลอัตโนมัติ #แปลงเป็น soup

	allclass = ['DetailPlace_uc_goldprices1_lblBLSell',
				'DetailPlace_uc_goldprices1_lblBLBuy',
				'DetailPlace_uc_goldprices1_lblOMSell',
				'DetailPlace_uc_goldprices1_lblOMBuy']

	allprice = []

	# class = col-xs-6
	for al in allclass:
		rawdata = data.find_all('span',{'id':al}) # print('COUNT',len(rawdata))
		allprice.append(float(rawdata[0].text.replace(',','')))
	# print(allprice)
	header = ['ราคาทองคำแท่ง-ขายออก', 'ราคาทองคำแท่ง-รับซื้อ', 'ทองคำรูปพรรณ-ขายออก', 'ทองคำรูปพรรณ-รับซื้อ']

	result = {}

	for h,p in zip(header,allprice):  #แปลงจาก list เป็น Dictionary
		result[h] = p

	# print(result)
	return result

price = GoldPrice()
# print(price['ทองคำรูปพรรณ-รับซื้อ'])

for h,p in price.items():  #แปลงจาก dict มาคล้าย list
	# print(h,p)
	print(f'{h} ราคา {p} บาท')

# GoldPrice()
# print(GoldPrice())