import io
import os
import time
from collections import defaultdict, deque
import datetime
import pandas as pd

import torch
import torch.distributed as dist

from pathlib import Path
import logging
log = logging.getLogger()
console = logging.StreamHandler()
log.addHandler(console)
log.setLevel(logging.INFO)

CSV_COL_ORDER = ['init_timestamp', 'train_timestamp', 'train_dur', 'train_speed',
                 'train_eval_start_timestamp', 'train_eval_end_timestamp', 'train_eval_dur', 'train_eval_speed',
                 'val_eval_start_timestamp', 'val_eval_end_timestamp', 'val_eval_dur', 'val_eval_speed',
                 'f_timestamp', 'epoch_dur',
                 'train_loss', 'train_acc1', 'train_acc5', 'train_best_acc1_batch', 'train_best_acc5_batch',
                 'val_loss', 'val_acc1', 'val_acc5', 'val_best_acc1_batch', 'val_best_acc5_batch'
                 ]

class SmoothedValue(object):
    """Track a series of values and provide access to smoothed values over a
    window or the global series average.
    """

    def __init__(self, window_size=20, fmt=None):
        if fmt is None:
            fmt = "{median:.4f} ({global_avg:.4f})"
        self.deque = deque(maxlen=window_size)
        self.total = 0.0
        self.count = 0
        self.fmt = fmt

    def update(self, value, n=1):
        self.deque.append(value)
        self.count += n
        self.total += value * n

    def synchronize_between_processes(self):
        """
        Warning: does not synchronize the deque!
        """
        if not is_dist_avail_and_initialized():
            return
        t = torch.tensor([self.count, self.total],
                         dtype=torch.float64, device='cuda')
        dist.barrier()
        dist.all_reduce(t)
        t = t.tolist()
        self.count = int(t[0])
        self.total = t[1]

    @property
    def median(self):
        d = torch.tensor(list(self.deque))
        return d.median().item()

    @property
    def avg(self):
        d = torch.tensor(list(self.deque), dtype=torch.float32)
        return d.mean().item()

    @property
    def global_avg(self):
        return self.total / self.count

    @property
    def max(self):
        return max(self.deque)

    @property
    def value(self):
        return self.deque[-1]

    def __str__(self):
        return self.fmt.format(
            median=self.median,
            avg=self.avg,
            global_avg=self.global_avg,
            max=self.max,
            value=self.value)

class MetricLogger(object):
    def __init__(self, delimiter="\t"):
        self.meters = defaultdict(SmoothedValue)
        self.delimiter = delimiter

    def update(self, **kwargs):
        for k, v in kwargs.items():
            if isinstance(v, torch.Tensor):
                v = v.item()
            assert isinstance(v, (float, int))
            self.meters[k].update(v)

    def __getattr__(self, attr):
        if attr in self.meters:
            return self.meters[attr]
        if attr in self.__dict__:
            return self.__dict__[attr]
        raise AttributeError("'{}' object has no attribute '{}'".format(
            type(self).__name__, attr))

    def __str__(self):
        loss_str = []
        for name, meter in self.meters.items():
            loss_str.append(
                "{}: {}".format(name, str(meter))
            )
        return self.delimiter.join(loss_str)

    def synchronize_between_processes(self):
        for meter in self.meters.values():
            meter.synchronize_between_processes()

    def add_meter(self, name, meter):
        self.meters[name] = meter

    def log_every(self, iterable, print_freq, header=None):
        i = 0
        if not header:
            header = ''
        start_time = time.time()
        end = time.time()
        iter_time = SmoothedValue(fmt='{avg:.4f}')
        data_time = SmoothedValue(fmt='{avg:.4f}')
        space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
        log_msg = [
            header,
            '[{0' + space_fmt + '}/{1}]',
            'eta: {eta}',
            '{meters}',
            'time: {time}',
            'data: {data}'
        ]
        if torch.cuda.is_available():
            log_msg.append('max mem: {memory:.0f}')
        log_msg = self.delimiter.join(log_msg)
        MB = 1024.0 * 1024.0
        for obj in iterable:
            data_time.update(time.time() - end)
            yield obj
            iter_time.update(time.time() - end)
            if i % print_freq == 0 or i == len(iterable) - 1:
                eta_seconds = iter_time.global_avg * (len(iterable) - i)
                eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
                if torch.cuda.is_available():
                    print(log_msg.format(
                        i, len(iterable), eta=eta_string,
                        meters=str(self),
                        time=str(iter_time), data=str(data_time),
                        memory=torch.cuda.max_memory_allocated() / MB))
                else:
                    print(log_msg.format(
                        i, len(iterable), eta=eta_string,
                        meters=str(self),
                        time=str(iter_time), data=str(data_time)))
            i += 1
            end = time.time()
        total_time = time.time() - start_time
        total_time_str = str(datetime.timedelta(seconds=int(total_time)))
        print('{} Total time: {} ({:.4f} s / it)'.format(
            header, total_time_str, total_time / len(iterable)))

class CustomLogger:
    def __init__(self, args):
        self.logs = {}
        self.msg_list = []
        self.epochs = args.epochs
        self.output_dir = Path(args.output_dir)
        self.temp_epoch = {'train_loss': [], 'train_acc1': [], 'train_acc5': [],
                           'val_loss': [], 'val_acc1': [], 'val_acc5': []
                           }
        self.best_acc_batch = {'train_acc1': 0,
                               'train_acc5': 0,
                               'val_acc1': 0,
                               'val_acc5': 0
                               }
        self.list_args(args)
        self.n_batches = {}

    @staticmethod
    def get_ep_name(epoch):
        ep_str = str(epoch + 1)
        for i in [2, 3]:
            if len(ep_str) < i:
                ep_str = '0' + ep_str
        return f'ep_{ep_str}'

    @staticmethod
    def now():
        return datetime.datetime.now().replace(microsecond=0)

    def save_num_batches(self, train_dataloader, val_dataloader, batch_size):
        for loader, split in zip([train_dataloader, val_dataloader], ['train', 'val']):
            num_batches, total_count = 0, 0
            for _, targets in loader:
                num_batches += 1
                total_count += targets.shape[0]
            msg = f'{split} data volume: {total_count} images, separated to {num_batches} batches ' \
                  f'(batch size {batch_size})'
            self.log(msg)
            self.n_batches[split] = num_batches

    def list_args(self, args):
        start_msg = "LeViT + FFCV" if args.ffcv_load == 'Y' else "LeViT ONLY"
        self.log(start_msg)
        self.log("Listing arguments:")
        self.log(args)
        # for k, v in vars(args).items():
        #     self.log(f'{k}={v}')

    def log(self, msg):
        log.info(msg)
        self.msg_list.append(str(msg))

    def start_epoch(self, epoch):
        ep_name = self.get_ep_name(epoch)
        self.logs[ep_name] = {}
        self.logs[ep_name]['init_timestamp'] = self.now()

    def start_eval(self, epoch, split):
        ep_name = self.get_ep_name(epoch)
        self.logs[ep_name][f'{split}_eval_start_timestamp'] = self.now()

    def update(self, **kwargs):
        for k, v in kwargs.items():
            self.temp_epoch[k].append(v)
            if 'acc' in k:
                self.best_acc_batch[k] = max(self.best_acc_batch[k], v)

    def sum_train(self, epoch):
        ep_name = self.get_ep_name(epoch)
        self.logs[ep_name]['train_timestamp'] = self.now()
        self.logs[ep_name]['train_dur'] = self.logs[ep_name]['train_timestamp'] - self.logs[ep_name]['init_timestamp']
        train_dur = self.logs[ep_name]['train_dur'].seconds
        train_speed = train_dur / self.n_batches['train']
        self.logs[ep_name]['train_speed'] = train_speed
        msg = f'{self.now()} - EPOCH [{ep_name.split("_")[-1]}] TRAIN_SPEED {round(train_speed, 5)} sec/batch'
        self.log(msg)

    def sum_eval(self, epoch, split):
        ep_name = self.get_ep_name(epoch)
        now = self.now()
        self.logs[ep_name][f'{split}_eval_end_timestamp'] = now
        self.logs[ep_name][f'{split}_eval_dur'] = now - self.logs[ep_name][f'{split}_eval_start_timestamp']
        eval_dur = self.logs[ep_name][f'{split}_eval_dur'].seconds
        eval_speed = eval_dur / self.n_batches[split]
        self.logs[ep_name][f'{split}_eval_speed'] = eval_speed
        loss = round(sum(self.temp_epoch[f'{split}_loss']) / len(self.temp_epoch[f'{split}_loss']), 4)
        acc1 = round(sum(self.temp_epoch[f'{split}_acc1']) / len(self.temp_epoch[f'{split}_acc1']), 2)
        acc5 = round(sum(self.temp_epoch[f'{split}_acc5']) / len(self.temp_epoch[f'{split}_acc5']), 2)
        self.logs[ep_name][f'{split}_best_acc1_batch'] = self.best_acc_batch[f'{split}_acc1']
        self.logs[ep_name][f'{split}_best_acc5_batch'] = self.best_acc_batch[f'{split}_acc5']
        self.best_acc_batch[f'{split}_acc1'] = 0
        self.best_acc_batch[f'{split}_acc5'] = 0
        best_batch_acc1 = round(self.logs[ep_name][f'{split}_best_acc1_batch'], 2)
        best_batch_acc5 = round(self.logs[ep_name][f'{split}_best_acc5_batch'], 2)
        msg = f'{self.now()} - EPOCH [{ep_name.split("_")[-1]}] ' \
              f'EVAL_{split}_SPEED {round(eval_speed, 5)} sec/batch | ' \
              f'LOSS {loss}, ACC1 {acc1}% (BEST {best_batch_acc1}%), ACC5 {acc5}% (BEST {best_batch_acc5}%)'
        self.log(msg)

    def sum_epoch(self, epoch):
        ep_name = self.get_ep_name(epoch)
        now = datetime.datetime.now().replace(microsecond=0)
        self.logs[ep_name]['f_timestamp'] = now
        self.logs[ep_name]['epoch_dur'] = now - self.logs[ep_name]['init_timestamp']
        ep = ep_name.split('_')[-1]
        all_duration = sum([self.logs[x]['train_dur'].seconds for x in self.logs if 'ep' in x])
        avg_time_diff = all_duration / (epoch+1)
        eta = (self.epochs - (epoch+1)) * avg_time_diff
        eta = datetime.timedelta(seconds=round(eta))
        train_speed = self.logs[ep_name]['train_speed']
        msg = f'{now} - EPOCH [{ep}]/{self.epochs}, TRAIN_SPEED {round(train_speed, 5)} sec/batch  ETA {eta}| '
        for k in self.temp_epoch:
            if len(self.temp_epoch[k]) == 0:
                # self.logs[ep_name][k] = None
                msg += f'{k}: NO CALC, '
            else:
                avg = sum(self.temp_epoch[k]) / len(self.temp_epoch[k])
                self.logs[ep_name][k] = avg
                if 'acc' in k:
                    val = str(round(avg, 2)) + '%'
                else:
                    val = str(round(avg, 4))
                if len(val) < 7:
                    msg += ' '*(7-len(val))
                msg += f'{k}: {val}, '
                self.temp_epoch[k] = []
        msg = msg[:-2]
        self.log(msg)

    def save_logged_data(self):
        df = pd.DataFrame.from_dict(self.logs, orient='index')
        cols = [col for col in CSV_COL_ORDER if col in df.columns]
        df = df[cols]
        if self.output_dir:
            df.to_csv(f'{self.output_dir}/logged_data.csv')
        with open(f'{self.output_dir}/raw_logs.txt', 'w') as f:
            for msg in self.msg_list:
                f.write(msg+'\n')

def is_photo(x: str):
    for f in ['jpg', 'jpeg', 'JPG', 'JPEG']:
        if f in x:
            return True
    return False

def _load_checkpoint_for_ema(model_ema, checkpoint):
    """
    Workaround for ModelEma._load_checkpoint to accept an already-loaded object
    """
    mem_file = io.BytesIO()
    torch.save(checkpoint, mem_file)
    mem_file.seek(0)
    model_ema._load_checkpoint(mem_file)

def setup_for_distributed(is_master):
    """
    This function disables printing when not in master process
    """
    import builtins as __builtin__
    builtin_print = __builtin__.print

    def print(*args, **kwargs):
        force = kwargs.pop('force', False)
        if is_master or force:
            builtin_print(*args, **kwargs)

    __builtin__.print = print

def is_dist_avail_and_initialized():
    if not dist.is_available():
        return False
    if not dist.is_initialized():
        return False
    return True

def get_world_size():
    if not is_dist_avail_and_initialized():
        return 1
    return dist.get_world_size()

def get_rank():
    if not is_dist_avail_and_initialized():
        return 0
    return dist.get_rank()

def is_main_process():
    return get_rank() == 0

def save_on_master(*args, **kwargs):
    if is_main_process():
        torch.save(*args, **kwargs)

def init_distributed_mode(args):
    args.distributed = False
    return
    # if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
    #     args.rank = int(os.environ["RANK"])
    #     args.world_size = int(os.environ['WORLD_SIZE'])
    #     args.gpu = int(os.environ['LOCAL_RANK'])
    # elif 'SLURM_PROCID' in os.environ:
    #     args.rank = int(os.environ['SLURM_PROCID'])
    #     args.gpu = args.rank % torch.cuda.device_count()
    # else:
    #     print('Not using distributed mode')
    #     args.distributed = False
    #     return
    #
    # args.distributed = True
    #
    # torch.cuda.set_device(args.gpu)
    # args.dist_backend = 'nccl'
    # print('| distributed init (rank {}): {}'.format(
    #     args.rank, args.dist_url), flush=True)
    # torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
    #                                      world_size=args.world_size, rank=args.rank)
    # torch.distributed.barrier()
    # setup_for_distributed(args.rank == 0)

def replace_batchnorm(net):
    for child_name, child in net.named_children():
        if hasattr(child, 'fuse'):
            setattr(net, child_name, child.fuse())
        elif isinstance(child, torch.nn.Conv2d):
            child.bias = torch.nn.Parameter(torch.zeros(child.weight.size(0)))
        elif isinstance(child, torch.nn.BatchNorm2d):
            setattr(net, child_name, torch.nn.Identity())
        else:
            replace_batchnorm(child)

def replace_layernorm(net):
    import apex
    for child_name, child in net.named_children():
        if isinstance(child, torch.nn.LayerNorm):
            setattr(net, child_name, apex.normalization.FusedLayerNorm(
                child.weight.size(0)))
        else:
            replace_layernorm(child)


import os
from flask import Flask, render_template, session, url_for, request, redirect

#################################################
# Flask Setup
#################################################

app = Flask(__name__)

#################################################
# View functions
#################################################

@app.route('/')
def index():
    return render_template('home.html')

@app.route('/charts')
def charts():
    return render_template('charts.html')

@app.route('/survey')
def survey():
    return render_template('survey.html')

@app.route('/map')
def map():
    return render_template('map.html')

@app.route('/add', methods=['GET','POST'])
def add_person():
    form = AddForm()

    if form.validate_on_submit():
        gender = form.gender.data
        relevant_experience = form.relevant_experience.data
        education_level = form.education_level.data
        major_discipline = form.major_discipline.data
        company_type = form.company_type.data
        company_size = form.company_size.data

        new_entry = Person(gender,relevant_experience,education_level,major_discipline,company_type,company_size)
        db.session.add(new_entry)
        db.session.commit()

        return redirect(url_for('list_person'))

    return render_template('add.html',form=form)

@app.route('/list')
def list_person():
    person = Person.query.all()
    person = str(person[-1])

    return render_template('list.html', person=person)

@app.route('/delete', methods=['GET', 'POST'])
def delete_person():

    form = DelForm()

    if form.validate_on_submit():
        id = form.id.data
        person = Person.query.get(id)
        try:
            db.session.delete(person)
            db.session.commit()
        except:
            db.session.rollback()

        return redirect(url_for('list_person'))

    return render_template('delete.html', form=form)

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


import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    maxDiff = None
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_Sample_Input_1(self):
        input = """3
2 3
1 3
1 2"""
        output = """3"""
        self.assertIO(input, output)

    def test_Sample_Input_2(self):
        input = """4
2 3 4
1 3 4
4 1 2
3 1 2"""
        output = """4"""
        self.assertIO(input, output)

    def test_Sample_Input_3(self):
        input = """3
2 3
3 1
1 2"""
        output = """-1"""
        self.assertIO(input, output)

def resolve():
  # キューに入れて貪欲？
  from collections import deque
  import copy

  inf = 10**18+1
  N = int(input())
  A = [deque([sorted([int(x)-1, i]) for x in input().split(" ")]) for i in range(N)]
  count = 0
  target = set()
  for i in range(N):
    target.add(i)

  POOL = set()
  while target:
    count+=1
    temp = set()
    for t in target:
      i, j = A[t].popleft()
      if (i, j) in POOL:
        POOL.remove((i, j))
        if len(A[i]): temp.add(i)
        if len(A[j]): temp.add(j)
      else:
        POOL.add((i, j))
    target = temp

  for i in range(N):
    if len(A[i]):
      print(-1)
      return
  else:
    print(count)

import sys
if sys.argv[-1] == './Main.py':
  resolve()

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


from .__version__ import __version__
from . import config
from .sounds import Beeper
from .page.connect import Module as Connect
from .page.labels import Module as Labels
from .page.peers import Module as Peers
from .page.peer import Module as Peer
from .peer import Server
from .node import Client as Node

import deskapp
import lank.name

from threading import Thread
import sys

class Application:
    def __init__(self):
        print(f'desklank v{__version__}')
        self.header = 'Peer-to-Peer Encrypted Communication: Connect to Begin'
        self.verbose = '-v' in sys.argv or '--verbose' in sys.argv

        try:
            from .systray import Icon as TrayIcon
            self.tray_icon = TrayIcon(self)
            self.tray_thread = Thread(target=self.tray_icon.run)

        except Exception as e:
            em = str(e)
            if not em: em = type(e)
            print(f'WARNING - Unable to setup system tray icon: {em}')
            self.tray_icon = None
            self.tray_thread = None

        self.desk = deskapp.App(
            modules=[Connect, Labels, Peers],
            title=f'desklank v{__version__}',
            header=self.header,
            v_split=(0.35 if self.verbose else 0.18),
            h_split=0.2,
            demo_mode=False)
        self.desk.top = self
        self.desk.tw = self.tw
        self.desk.data['labels'] = [ ]

        self.sounds = Beeper()

        self.server = None
        self.node = None
        self.interests = config.load_interests()
        self.peers = { label: None for label in config.load_peers() }

        self.finished = False
        self.exiting = False

    def run(self):
        try:
            if self.tray_thread:
                self.tray_thread.start()

            self.sounds.start()
            self.desk.start()
            self.finished = True

        except KeyboardInterrupt:
            pass

        finally:
            self.quit()
            if self.tray_thread:
                self.tray_thread.join()

    def quit(self):
        if self.exiting: return
        self.exiting = True

        if self.tray_icon:
            self.tray_icon.stop()

        self.sounds.stop()
        self.sounds.join()

        if not self.finished:
            self.desk.close()

        self.disconnect()

    def connect(self, port, label, pwd, alias):
        self.desk.print('connecting')
        self.desk.data['connect'] = False
        self.desk.set_header(
            self.tw(self.desk.frontend.screen_w - 2, ''))

        self.server = Server(self, label, port, verbose=self.verbose)
        self.server.start()
        self.server.ready.wait()

        if self.server.sock:
            self.node = Node(self, port, label, pwd, alias,
                self.error, self.on_connect, verbose=self.verbose)
            self.node.start()

        else:
            self.disconnect()

    def disconnect(self):
        if not self.server: return

        self.desk.print('disconnecting')
        self.desk.data['labels'] = [ ]

        server = self.server
        self.server = None
        server.stop()
        server.join()

        if self.node:
            node = self.node
            self.node = None
            node.stop()
            node.join()

        self.desk.print('finished')
        self.desk.data['connect'] = None
        self.desk.set_header(
            self.tw(self.desk.frontend.screen_w - 2, self.header))
        self.sounds.beep('error')

    def error(self, e, context=None):
        ctxt = f'<{context}> ' if context else ''
        etxt = f'{e}'
        if not etxt: etxt = type(e)
        self.desk.print(f'** ERROR {ctxt}** {etxt}')
        self.sounds.beep('robot_error')

    def on_connect(self, labels):
        self.desk.data['connect'] = True
        self.desk.data['labels'] = sorted(labels)

        for label in self.desk.data['labels']:
            if label in self.peers:
                if not self.peers[label]:
                    page = Peer(self.desk, label)
                    self.desk.logic.setup_panel(page)
                    self.peers[label] = page

        self.desk.print('connected and ready')
        self.desk.set_header(
            self.tw(self.desk.frontend.screen_w - 2, 'You are connected'))
        self.sounds.beep('success')

    def notify(self, signed):
        if signed.name == lank.name.REGISTER:
            self._notify_(signed.label, f'{signed.label} has changed keys')

        elif signed.name == lank.name.PEER:
            if self.desk.data['connect']:
                msg = f'{signed.label} signed on'
                if ':' in signed.key[signed.key.index(':')+1:]:
                    alias = signed.key[signed.key.index(':')+1:]
                    alias = alias[alias.index(':')+1:]
                    msg += f' as {alias}'
                self._notify_(signed.label, msg, 'ping')

        else:
            self._notify_(signed.label, f'{signed.label} has done something')

    def _notify_(self, title, msg, sound=None):
        if self.tray_icon:
            self.tray_icon.notify(msg, f'{title} | desklank')

        self.desk.set_header(self.tw(self.desk.frontend.screen_w - 2,
            f'[{title}] >> {msg}'))

        if sound:
            self.sounds.beep(sound)

    def tw(self, w, txt='', c=' '):
        if not isinstance(txt, str): txt = f'{txt}'
        size = len(txt)
        if size >= w: return txt
        return txt + c*(w-size)


from Brain import Brain
import tensorflow as tf
import numpy as np
from NN_Translate import NNTranslate
import threading

class RLBrain:
    def __init__(
            self,
            session, id,
            features=NNTranslate.features,
            actions=NNTranslate.actions,
            gamma=0.99, memory_size=5000,
            eplison=0.9, batch_size=256, **kwargs
    ):
        tf.compat.v1.disable_eager_execution()
        self.features, self.actions, self.gamma, self.eplison = features, actions, gamma, eplison
        self.learn_step, self.memory_size, self.memory_count, self.batch_size = 0, memory_size, 0, batch_size
        self.session, self.id = session, str(id)
        if "restore" in kwargs:
            self.memory = kwargs["memory"]
            self.memory_count = kwargs["memory_count"]
            self.suicide_vars = kwargs["suicide_vars"]
            self.swap_vars = kwargs["swap_vars"]
        else:
            self.memory = {
                "s": np.zeros([self.memory_size, self.features]), "s_": np.zeros([self.memory_size, self.features]),
                "a": np.zeros([self.memory_size, 1]), "r": np.zeros([self.memory_size, 1]),
                "m": np.zeros([self.memory_size, self.actions])
            }
            self._build_net()

    def _build_net(self):
        s = tf.compat.v1.placeholder(tf.float64, shape=(None, self.features), name='s' + self.id)
        s_ = tf.compat.v1.placeholder(tf.float64, shape=(None, self.features), name='s_' + self.id)
        r = tf.compat.v1.placeholder(tf.float64, shape=(None,), name='r' + self.id)
        a = tf.compat.v1.placeholder(tf.int32, shape=(None,), name='a' + self.id)
        mask = tf.compat.v1.placeholder(tf.float64, shape=(None, self.actions), name='m' + self.id)
        w_init, b_init = tf.random_normal_initializer(0.0, 0.01), tf.constant_initializer(0.01)

        def hidden(previous):
            previous = tf.compat.v1.layers.dense(previous, 30, tf.nn.leaky_relu, True,
                                                 kernel_initializer=w_init, bias_initializer=b_init)
            previous = tf.compat.v1.layers.dense(previous, 40, tf.nn.leaky_relu, True,
                                                 kernel_initializer=w_init, bias_initializer=b_init)
            previous = tf.compat.v1.layers.dense(previous, 50, tf.nn.leaky_relu, True,
                                                 kernel_initializer=w_init, bias_initializer=b_init)
            previous = tf.compat.v1.layers.dense(previous, 30, tf.nn.leaky_relu, True,
                                                 kernel_initializer=w_init, bias_initializer=b_init)
            return previous

        with tf.compat.v1.variable_scope('eval_net_' + self.id):
            eval_out = tf.compat.v1.layers.dense(hidden(s), self.actions, tf.nn.sigmoid, True,
                                                 kernel_initializer=w_init, bias_initializer=b_init)
        with tf.compat.v1.variable_scope('target_net_' + self.id):
            target_out = tf.compat.v1.layers.dense(hidden(s_), self.actions, tf.nn.sigmoid, True,
                                                   kernel_initializer=w_init, bias_initializer=b_init)
        tf.identity(eval_out, name='eval_' + self.id)
        # Q eval net #
        indices = tf.stack([tf.range(tf.shape(a)[0], dtype=tf.int32), a], axis=1)
        q_eval = tf.gather_nd(eval_out, indices)
        # Q target net #
        action_values = tf.add(target_out, 1)
        action_values = tf.multiply(action_values, mask)
        action_values = tf.add(action_values, -1)
        q_target = r + self.gamma * tf.reduce_max(action_values)
        q_target = tf.stop_gradient(q_target)
        # Training #
        loss = tf.reduce_min(tf.compat.v1.squared_difference(q_target, q_eval))
        tf.compat.v1.train.RMSPropOptimizer(0.01, name='trainer_' + self.id).minimize(loss)
        # Swap #
        self.swap_vars = 0
        t_params = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, scope='target_net_' + self.id)
        e_params = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, scope='eval_net_' + self.id)
        for t, e in zip(t_params, e_params):
            tf.compat.v1.assign(t, e, name='swap_' + self.id + "_" + str(self.swap_vars))
            self.swap_vars += 1
        # Suicide #
        self.suicide_vars = 0
        network_vars = []
        network_vars.extend([item for item in t_params])
        network_vars.extend([item for item in e_params])
        for var in network_vars:
            tf.compat.v1.assign(var, tf.zeros(var.shape, dtype=tf.float64),
                                name='suicide_' + self.id + "_" + str(self.suicide_vars))
            self.suicide_vars += 1

        self.session.run(tf.compat.v1.global_variables_initializer())
        self.init = tf.compat.v1.global_variables()

    def get(self, status):
        status_nn = NNTranslate.state_to_nn(status)[np.newaxis, :]
        if np.random.uniform() < self.eplison + self.learn_step * 1e-6:
            action_values = self.session.run(
                ['eval_' + self.id + ":0"],
                feed_dict={"s" + self.id + ":0": status_nn}
            )
            action_values = np.array(action_values) + 1
        else:
            action_values = 1 / (1 + np.exp(-np.random.normal(size=self.actions)))
            action_values = action_values + 1
        action_values = action_values * NNTranslate.get_available_mask(status)
        action = np.argmax(action_values)
        return NNTranslate.nn_to_action(action)

    def add_observation(self, s, a, r, s_, batch_size=None, learn=True):
        if batch_size is not None:
            self.batch_size = batch_size
        pos = self.memory_count % self.memory_size
        self.memory["s"][pos, :] = NNTranslate.state_to_nn(s)[np.newaxis, :]
        self.memory["a"][pos, :] = NNTranslate.action_to_nn(a)
        self.memory["r"][pos, :] = r
        self.memory["s_"][pos, :] = NNTranslate.state_to_nn(s_)[np.newaxis, :]
        self.memory["m"][pos, :] = NNTranslate.get_available_mask(s_)
        self.memory_count += 1
        if learn:
            threading.Thread(target=self.learn).start()

    def learn(self):
        self.session.run(['swap_' + self.id + "_" + str(i) for i in range(self.swap_vars)])
        batch = np.random.choice(min(self.memory_size, self.memory_count), size=self.batch_size)
        self.session.run(
            ["trainer_" + self.id],
            feed_dict={
                "s" + self.id + ":0": self.memory["s"][batch, :],
                "a" + self.id + ":0": self.memory["a"][batch, 0],
                "r" + self.id + ":0": self.memory["r"][batch, 0],
                "s_" + self.id + ":0": self.memory["s_"][batch, :],
                "m" + self.id + ":0": self.memory["m"][batch, :]
            }
        )
        self.learn_step += 1

    def reset(self):
        self.session.run(['suicide_' + self.id + "_" + str(i) for i in range(self.suicide_vars)])
        self.learn_step, self.memory_count = 0, 0
        self.memory = {
            "s": np.zeros([self.memory_size, self.features]), "s_": np.zeros([self.memory_size, self.features]),
            "a": np.zeros([self.memory_size, 1]), "r": np.zeros([self.memory_size, 1]),
            "m": np.zeros([self.memory_size, self.actions])
        }

    def save(self):
        frozen_graph = tf.compat.v1.graph_util.convert_variables_to_constants(
            self.session,
            tf.compat.v1.get_default_graph().as_graph_def(),
            ['eval_' + self.id]
        )
        tf.io.write_graph(frozen_graph, "../pb/", "load_model.pb", as_text=False)


import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# 1. 데이터
x = np.array([1,2,3,4,5,6,7,8,9,10])
y = np.array([1,2,3,4,5,6,7,8,9,10])

# [검색] train과 test를 섞어서 7:3으로 찾을 수 있는 방법을 찾아라.
# 힌트: 사이킷런

x_train, x_test, y_train, y_test =  train_test_split(x, y,
                                                     train_size=0.7,
                                                      shuffle=True, # 명시 안할 경우 True가 default
                                                     random_state=1004)
# seed : 랜덤 난수에 따라 정해진 랜덤치로 뽑음 난수 바뀌기 전까지 고정되는 셈
# size : 퍼센트로 접근

print(x_test) # [ 1  9 10]
print(x_train) # [2 7 6 3 4 8 5]
print(y_test)
print(y_train)

# 디버그 시 줄 옆에 빨간 점 + F5
# 빨간 점 전까지 실행, 다시 F5 누르면 거기서부터 이어서 실행, 빈 곳 말고 내용 있는 곳 찍어야됨

# 2. 모델
model = Sequential()
model.add(Dense(10, input_dim=1))
model.add(Dense(1))

# 3. 컴파일, 훈련
model.compile(loss = 'mse', optimizer='adam')
model.fit(x_train, y_train, epochs=100, batch_size=1)

# 4. 평가, 예측
loss = model.evaluate(x_test, y_test)
print("loss : ", loss)
result = model.predict([11])
print('[11]의 예측값 : ', result)

# model.add(Dense(10, input_dim=1))
# model.add(Dense(1))
# epochs=100, batch_size=1
# loss :  7.579122740649855e-14
# [11]의 예측값 :  [[11.]]


import server
import sys
import argparse
import logging

def status(args):
	rack = server.Rack(args.id)
	rack.status()

def shutdown(args):
	rack = server.Rack(args.id)
	if args.force:
		rack.log.info("Forced shutdown of rack %s timeout =%s",args.id, args.timeout)
		rack.force_shutdown(args.timeout)
	else:
		rack.log.info("Shutdown of rack %s timeout=%s", args.id, args.timeout)
		rack.shutdown(args.timeout)

parser = argparse.ArgumentParser(prog="rack", description='Manage racks')
subparsers = parser.add_subparsers()
parser_status = subparsers.add_parser("status", help="Display status of ESXi servers in the rack")
parser_status.add_argument("id", help="ID of rack")
parser_status.set_defaults(func=status)
parser_shutdown = subparsers.add_parser("shutdown", help="Shutdown whole rack")
parser_shutdown.add_argument("-f", "--force", action="store_true", help="Force shutdown (possible data loss)")
parser_shutdown.add_argument("-t", "--timeout", action="store", type=int, default=300, help="Server shutdown timeout in seconds")
parser_shutdown.add_argument("id", help="ID of rack")
parser_shutdown.set_defaults(func=shutdown)

args = parser.parse_args()
args.func(args)


# components.py - provides front end reactive components using dash.
# @TODO: Why does this module export DATASET?
# breakpoint()
__version__ = '0.2'
__all__ = ['region_dropdown', 'region_dropdown_', 'region_dropdown_u2d','rangeslider', 'train_slider', 'y_slider', 'x_axis-dropdown','y-axis-dropdown']

import dash_core_components as dcc
import dash_html_components as html

import data_loader  # shouldn't be neded here
from data_loader import datasets
import common.utils  as utils # get_reg_files shold be moved from utils into data_loader class
from common.better_title import better_title
from lib.predict_data import period, dates, date_marks

LATEST = '5/25/2020'

options = [] # labels needed by app.layout

rangeslider = dcc.RangeSlider(
    id = 'slider',
    marks = date_marks,
    min = 0,
    max = period,
    value = [1, 55])

train_slider = html.Div(
    [
    html.Label("Train Period (days since patient zero)"),
    dcc.RangeSlider(id = 'train_slider',
            marks = date_marks,
            min = 0,
            max = period,
            value = [1, 55]),
    ],
    style = {'margin-top' : '33px'}
)

# This is kind of brittle in that graph doesn't work at all without y_slider -- should degrade gracefully!
y_slider = html.Div(
    [
    html.Label(''),
    dcc.RangeSlider(id = 'yslider',
        vertical = True,
        min = 0,
        max = 300000,
        value = [1, 300000]),
    ],
    style = {'backgroundColor' : '', 'width' : 'auto', 'height' : '400px', 'float' : 'left','margin-left':'10px', 'margin-right':0,'padding-right':0,'padding-left':'10px'},
)
# @TODO: import styles from CSS

def single_region_dropdown_(area: str='USA', val: str=None):
    area = None
    #for v, k in data_loader.area.items():

#    breakpoint()
    if area is not None:
        #rint(getattr(data_loader, area).items())
        for v, k in getattr(data_loader, area).items():
            options.append(dict([('label', k), ('value', v)]))
    dropdown = html.Div([
    #html.H4(""),
    #html.P("Starting Population:",
    #    style={'width':'auto', 'margin-top':'.0em', 'margin-bottom':'', 'padding-top':'.01em','backgroundColor':'#'}),
    dcc.Dropdown(
        id = 'single_region_dropdown',
        options = options,
        multi=False,
        placeholder = 'Select Geographic Region to run model on'
        ),
    #html.P("Data current up to " + LATEST),
    ],
    style={'width':'350px', 'color':'#222', 'font-color':'#222'}
    )
    return dropdown
single_region_dropdown = single_region_dropdown_()

def region_dropdown_(area: str, val: str=None):
    #for v, k in data_loader.area.items():
    if area is not None:
        #rint(getattr(data_loader, area).items())
        for v, k in getattr(data_loader, area).items():
            options.append(dict([('label', k), ('value', v)]))
    dropdown = html.Div([
    #html.H4(""),
    html.P("Select regions to display and use feeling sliders to set date range:",
        style={'width':'auto', 'margin-top':'.05em', 'margin-bottom':'', 'padding-top':'5vw','backgroundColor':'#'}),
    dcc.Dropdown(
        id = 'region_dropdown',
        options = options,
        value=val,
        multi=True
        ),
    #html.P("Data current up to " + LATEST),
    ],
    style={'width':'75%'}
    )

    return dropdown

region_dropdown = region_dropdown_(None, None) # Python, what's not to <3!
region_dropdown2 = region_dropdown_(None, None) # Python, what's not to <3!
region_dropdown_zapp = region_dropdown_(None, None) # Python, what's not to <3!
region_dropdown_wb = region_dropdown_(None, None) # Python, what's not to <3!
region_dropdown_mod = region_dropdown_(None, None) # Python, what's not to <3!

owid_countries = ['Australia', 'Austria', 'Belgium', 'Bolivia', 'Bulgaria', 'Canada', 'Croatia'
 'Cyprus', 'Czechia', 'Denmark', 'Estonia', 'Finland', 'France', 'Hungary'
 'Iceland', 'Ireland', 'Israel', 'Italy', 'Japan', 'Latvia', 'Lithuania'
 'Luxembourg', 'Malaysia', 'Malta', 'Netherlands', 'Norway', 'Poland'
 'Portugal', 'Romania', 'Serbia', 'Slovakia', 'Slovenia', 'South Africa'
 'Spain', 'Sweden', 'Switzerland', 'United Kingdom', 'United States']

def region_dropdown_u2d(area: str, val: str=None):  # -> dcc.dropdown ?
    options = []
    if area is not None:
        for c in owid_countries:
            options.append(dict([('label', c), ('value', c)]))

    dropdown = html.Div([
    #html.H4(""),
    html.P("Select regions to display and use feeling sliders to set date range:",
        style={'width':'auto', 'margin-top':'.05em', 'margin-bottom':'', 'padding-top':'5vw','backgroundColor':'#'}),
    dcc.Dropdown(
        id = 'region_dropdown_',
        options = options,
        value=val,
        multi=True
        ),
    #html.P("Data current up to " + LATEST),
    ],
    style={'width':'75%'}
    )

    return dropdown

# this should be in app
x_axis_dropdown = [
    html.H4("x-Axis"),
    #html.P("Use links on right to edit, save & download"),
    dcc.Dropdown(
        id='x-axis-dropdown',
        options=[
            {'label': name, 'value': file} for file, name in datasets.items()],
        placeholder='Select a dataset to view...',
        value='current_cases_by_country.csv',
        style={'display':'block'},
        ),
    dcc.Dropdown(
        id='x-axis-feature-dropdown',
        placeholder='Select x-axis feature',
        style={'display':'block'},
        value='deaths',
        ),
]

y_axis_dropdown = [ #right
    html.H4("y-Axis"),
    #html.P("Use links on right to edit, save & download"),
    dcc.Dropdown(
        id='y-axis-dropdown',
        options=[
            {'label': name, 'value': file} for file, name in datasets.items()],
        placeholder="Select a dataset to view...",
        value="global_demographic_data.csv",
        style={'display':'block'},
        ),
    dcc.Dropdown(
        id='y-axis-feature-dropdown',
        placeholder='Select y-axis feature',
        value='population',
        style={'display':'block'},
        ),
]

USGlobal_ = [dcc.RadioItems(
                    id="USGlobal",
                    options=[
                        {'label': 'Global Case Data', 'value': 'World'},
                        {'label': 'USA Case Data', 'value': 'USA'},
                        {'label': 'New York Case Data', 'value': 'NYC'}
                        ], value='World', labelStyle={'display': 'block'}
                    )]


import random as r

def randomLicensePlate():

    new_or_old = r.randint(0, 1)
    print(new_or_old)
    if new_or_old == 0:
        return old_licensePlate()
    else:
        return newLicensePlate()

def old_licensePlate():
    old = ""
    for i in range(3):
        character = r.randint(65, 122)
        old += chr(character)
    for i in range(3):
        old += str(r.randint(0, 9))
    return old

def newLicensePlate():
    new = ""
    for i in range(4):
        new += str(r.randint(0, 9))
    for i in range(3):
        character = r.randint(65, 122)
        new += chr(character)
    return new

print(randomLicensePlate())


# You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions
# (i.e. North, East, South, West). Return true if you can reach position [N-1, N-1] or false otherwise.

# Empty positions are marked .. Walls are marked W. Start and exit positions are empty in all test cases.

def path_finder(maze):
    start = (0, 0)
    maze_list = maze.split('\n')
    target = len(maze_list) -1, len(maze_list[0]) -1

    stack = []
    stack.append(start)
    explored = set()

    while len(stack):
        node = stack.pop(0)
        if node == target:
            return True

        explored.add(node)

        for n in neighbors(node, maze_list, len(maze_list) -1):
            if n not in stack and n not in explored:
                stack.append(n)

    return False

def neighbors(vertex, graph, n):
    x, y = vertex
    moves = [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]
    neighbors_node = set()
    for (r, c) in moves:
        if 0 <= r <= n and 0 <= c <= n and graph[r][c] != 'W':
            neighbors_node.add((r,c))

    return neighbors_node

a = "\n".join([
  ".W.",
  ".W.",
  "..."
])

b = "\n".join([
  ".W.",
  ".W.",
  "W.."
])

c = "\n".join([
  "......",
  "......",
  "......",
  "......",
  "......",
  "......"
])

d = "\n".join([
  "......",
  "......",
  "......",
  "......",
  ".....W",
  "....W."
])

# print(a)
# print('===========')
# print(a.split('\n'))

print(path_finder(a))
print(path_finder(b))
print(path_finder(c))
print(path_finder(d))


from sys import stdin

def solve(target: int, coins: list) -> int:
    length = len(coins)
    current_coin, *others = coins

    # Handle base cases
    if target == 0:
        return 1
    if length == 0:
        return 0
    if length == 1:
        return 1 if target % current_coin == 0 else 0

    return sum(
        solve(target - i * current_coin, others)
        for i in range(target//current_coin + 1)
    )

COINS_COUNT, TARGET = map(int, stdin.readline().split())
COINS = sorted(map(int, stdin.read().split()), reverse=True)
answer = solve(TARGET, COINS)
print(answer)


#Write  a  program  in  python  to  find  out  maximum  and  minimum  number  out  of  three user entered number.

a = int(input("\n\tEnter First Number : "))
b = int(input("\n\tEnter Second Number : "))
c = int(input("\n\tEnter Third Number : "))

if a > b and a > c :
	print(a," is Biggest Number")

elif b > a and b > c :
	print(b," is Biggest Number")

elif c > b and c > a :
	print(c," is Biggest Number")

if a < b and a < c :
	print(a," is smallest Number ")

elif b < a and b < c :
	print(b," is smallest Number")

elif c < b and c < a :
	print(c," is smallest Number")


"""This file includes a collection of utility functions that are useful for
implementing DQN."""
import gym
import numpy as np
import random

def sample_n_unique(sampling_f, n):
    res = []
    while len(res) < n:
        candidate = sampling_f()
        if candidate not in res:
            res.append(candidate)
    return res

class Schedule(object):
    def value(self, t):
        raise NotImplementedError()

class ConstantSchedule(object):
    def __init__(self, value):
        self._v = value

    def value(self, t):
        """See Schedule.value"""
        return self._v

def linear_interpolation(l, r, alpha):
    return l + alpha * (r - l)

class PiecewiseSchedule(object):
    def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None):
        idxes = [e[0] for e in endpoints]
        assert idxes == sorted(idxes)
        self._interpolation = interpolation
        self._outside_value = outside_value
        self._endpoints      = endpoints

    def value(self, t):
        """See Schedule.value"""
        for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):
            if l_t <= t and t < r_t:
                alpha = float(t - l_t) / (r_t - l_t)
                return self._interpolation(l, r, alpha)

        # t does not belong to any of the pieces, so doom.
        assert self._outside_value is not None
        return self._outside_value

class LinearSchedule(object):
    def __init__(self, schedule_timesteps, final_p, initial_p=1.0):
        self.schedule_timesteps = schedule_timesteps
        self.final_p            = final_p
        self.initial_p          = initial_p

    def value(self, t):
        fraction  = min(float(t) / self.schedule_timesteps, 1.0)
        return self.initial_p + fraction * (self.final_p - self.initial_p)

def get_wrapper_by_name(env, classname):
    currentenv = env
    while True:
        if classname in currentenv.__class__.__name__:
            return currentenv
        elif isinstance(env, gym.Wrapper):
            currentenv = currentenv.env
        else:
            raise ValueError("Couldn't find wrapper named %s"%classname)

class ReplayBuffer(object):
    def __init__(self, size, frame_history_len):
        self.size = size
        self.frame_history_len = frame_history_len

        self.next_idx      = 0
        self.num_in_buffer = 0

        self.obs      = None
        self.action   = None
        self.reward   = None
        self.done     = None

    def can_sample(self, batch_size):
        return batch_size + 1 <= self.num_in_buffer

    def _encode_sample(self, idxes):
        obs_batch      = np.concatenate([self._encode_observation(idx)[np.newaxis, :] for idx in idxes], 0)
        act_batch      = self.action[idxes]
        rew_batch      = self.reward[idxes]
        next_obs_batch = np.concatenate([self._encode_observation(idx + 1)[np.newaxis, :] for idx in idxes], 0)
        done_mask      = np.array([1.0 if self.done[idx] else 0.0 for idx in idxes], dtype=np.float32)

        return obs_batch, act_batch, rew_batch, next_obs_batch, done_mask

    def sample(self, batch_size):
        assert self.can_sample(batch_size)
        idxes = sample_n_unique(lambda: random.randint(0, self.num_in_buffer - 2), batch_size)
        return self._encode_sample(idxes)

    def encode_recent_observation(self):
        assert self.num_in_buffer > 0
        return self._encode_observation((self.next_idx - 1) % self.size)

    def _encode_observation(self, idx):
        end_idx   = idx + 1 # make noninclusive
        start_idx = end_idx - self.frame_history_len
        # this checks if we are using low-dimensional observations, such as RAM
        # state, in which case we just directly return the latest RAM.
        if len(self.obs.shape) == 2:
            return self.obs[end_idx-1]
        # if there weren't enough frames ever in the buffer for context
        if start_idx < 0 and self.num_in_buffer != self.size:
            start_idx = 0
        for idx in range(start_idx, end_idx - 1):
            if self.done[idx % self.size]:
                start_idx = idx + 1
        missing_context = self.frame_history_len - (end_idx - start_idx)
        # if zero padding is needed for missing context
        # or we are on the boundry of the buffer
        if start_idx < 0 or missing_context > 0:
            frames = [np.zeros_like(self.obs[0]) for _ in range(missing_context)]
            for idx in range(start_idx, end_idx):
                frames.append(self.obs[idx % self.size])
            return np.concatenate(frames, 0)
        else:
            # this optimization has potential to saves about 30% compute time \o/
            img_h, img_w = self.obs.shape[2], self.obs.shape[3]
            return self.obs[start_idx:end_idx].reshape(-1, img_h, img_w)

    def store_frame(self, frame):
        if len(frame.shape) > 1:
            # transpose image frame into (img_c, img_h, img_w)
            frame = frame.transpose(2, 0, 1)

        if self.obs is None:
            self.obs      = np.empty([self.size] + list(frame.shape), dtype=np.uint8)
            self.action   = np.empty([self.size],                     dtype=np.int32)
            self.reward   = np.empty([self.size],                     dtype=np.float32)
            self.done     = np.empty([self.size],                     dtype=np.bool)
        self.obs[self.next_idx] = frame

        ret = self.next_idx
        self.next_idx = (self.next_idx + 1) % self.size
        self.num_in_buffer = min(self.size, self.num_in_buffer + 1)

        return ret

    def store_effect(self, idx, action, reward, done):
        self.action[idx] = action
        self.reward[idx] = reward
        self.done[idx]   = done


import os

def parse_fin_est_dat_file(relative_location):
    with open(relative_location, "r") as fin_est_dat:
        lines = census_file.readlines()
        return(parse_fin_est_dat_lines(lines))

def parse_fin_est_dat_lines(fin_est_dat_lines):
    fin_est_dat_dict = {}
    for line in fin_est_dat_lines:
        line_dict = parse_fin_est_dat_line(line)
        fin_est_dat_dict[line_dict['ID']] = line_dict
    return(fin_est_dat_dict)

def parse_fin_est_dat_line(line):
    fin_est_dat_dict = {}
    fin_est_dat_dict['ID'] = line[0:12]
    fin_est_dat_dict['Item Code'] = line[12:15]
    fin_est_dat_dict['Amount'] = int(line[15:27].strip())
    fin_est_dat_dict['Year of data'] = line[27:31]
    fin_est_dat_dict['Imputation type/item data flag'] = line[31:32]
    return(fin_est_dat_dict)

local_state_govt_expenses_sql_header = """INSERT INTO local_state_govt_expenses (state_code, county_code, pid6_place, expense_code, amount, year)
VALUES
"""

def write_fin_est_dat_sql_table_to_file(filename):
    local_state_govt_expenses_sql_table = """CREATE TABLE IF NOT EXISTS local_state_govt_expenses (
    expense_code char(3),
    county_code char(3),
    state_code char(2),
    pid6_place char(6),
    amount integer,
    year integer,
    PRIMARY KEY(expense_code, pid6_place, year)
);"""

    with open(filename, 'w') as sql_out:
        sql_out.write(local_state_govt_expenses_sql_table)

def write_fin_est_dat_sql_entry_to_file(entry_data, opened_file):
    if entry_data != {}:
        fin_est_dat_sql_stub = "    ('{state_code}', {county_code}, '{pid6_place}', " + \
            "'{expense_code}', '{amount}', {year})"
        opened_file.write(
            fin_est_dat_sql_stub.format(
                state_code = entry_data['state_code'],
                county_code = entry_data['county_code'],
                pid6_place = entry_data['pid6_place'],
                expense_code = entry_data['expense_code'],
                amount = entry_data['amount'],
                year = entry_data['year']
            )
        )

def fin_est_dat_line_to_dict(line):
    entry_data = {}
    ## Pre-2017 has a different format that I'm not wanting to fuck with right now.
    if line[2] != "0":
        entry_data['state_code'] = line[:2].strip()
        entry_data['county_code'] = "'{}'".format(line[3:6].strip()) if entry_data['state_code'] != '09' else 'Null'
        entry_data['pid6_place'] = line[6:12]
        entry_data['expense_code'] = line[12:15]
        entry_data['amount'] = int(line[15:27])
        entry_data['year'] = int(line[27:31])
    return(entry_data)

def read_fin_est_dat_files_write_sql(fin_est_dat_directory, sql_out_dir):
    for filename in os.listdir(fin_est_dat_directory):
        file_to_open = "{}/{}.sql".format(sql_out_dir, filename)
        with open(file_to_open, 'w') as fin_est_dat_sql:
            fin_est_dat_sql.write("""INSERT INTO local_state_govt_expenses (state_code, county_code, pid6_place, expense_code, amount, year)
VALUES
""")
            with open(fin_est_dat_directory + "/" + filename, 'r') as fin_est_dat_txt:
                expense_lines = fin_est_dat_txt.readlines()
                first_line = expense_lines[0]
                entry_data = fin_est_dat_line_to_dict(first_line)
                write_fin_est_dat_sql_entry_to_file(entry_data, fin_est_dat_sql)
                for expense in expense_lines[1:]:
                    entry_data = fin_est_dat_line_to_dict(expense)
                    if entry_data != {}:
                        fin_est_dat_sql.write(',\n')
                    write_fin_est_dat_sql_entry_to_file(entry_data, fin_est_dat_sql)


from __future__ import annotations

import unittest
from pathlib import Path
from unittest import mock

from mantidimaging.core.io.filenames import FilenameGroup
from mantidimaging.core.io.instrument_log import InstrumentLog
from mantidimaging.gui.windows.image_load_dialog.field import Field
from mantidimaging.gui.windows.image_load_dialog.presenter import LoadPresenter
from mantidimaging.core.utility.data_containers import FILE_TYPES, Indices

class ImageLoadDialogPresenterTest(unittest.TestCase):

    def _files_equal(self, file1, file2):
        self.assertEqual(Path(file1).absolute(), Path(file2).absolute())

    def setUp(self):
        self.fields = {ft.fname: mock.create_autospec(Field) for ft in FILE_TYPES}
        self.v = mock.MagicMock(fields=self.fields)
        self.v.sample = self.fields["Sample"]
        self.p = LoadPresenter(self.v)

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.LoadPresenter.do_update_flat_or_dark")
    def test_do_update_field(self, mock_do_update_flat_or_dark):
        selected_file = "SelectedFile"
        self.v.select_file.return_value = selected_file
        ft = FILE_TYPES.FLAT_BEFORE
        field = mock.MagicMock(file_info=ft)

        self.p.do_update_field(field)

        self.v.select_file.assert_called_once_with(ft.fname, True)
        mock_do_update_flat_or_dark.assert_called_once_with(field, selected_file)

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.LoadPresenter.do_update_flat_or_dark")
    def test_do_update_field_when_no_file_selected(self, mock_do_update_flat_or_dark):
        self.v.select_file.return_value = None
        ft = FILE_TYPES.FLAT_BEFORE
        field = mock.MagicMock(file_info=ft)

        self.p.do_update_field(field)

        self.v.select_file.assert_called_once_with(ft.fname, True)
        mock_do_update_flat_or_dark.assert_not_called()

    def test_update_field_with_filegroup_sample(self):
        mock_file_group = mock.create_autospec(FilenameGroup)
        file_list = [mock.Mock()]
        file_log_path = mock.Mock()
        mock_file_group.all_files.return_value = file_list
        mock_file_group.log_path = file_log_path

        mock_field_path = mock.PropertyMock()
        type(self.fields["Sample Log"]).path = mock_field_path

        self.p.update_field_with_filegroup(FILE_TYPES.SAMPLE, mock_file_group)

        mock_file_group.find_all_files.assert_called_once_with()
        mock_file_group.find_log_file.assert_called_once_with()
        self.fields["Sample"].set_images.assert_called_once_with(file_list)
        mock_field_path.assert_called_once_with(file_log_path)

    def test_update_field_with_filegroup_dark_before(self):
        mock_file_group = mock.create_autospec(FilenameGroup)
        file_list = [mock.Mock()]
        mock_file_group.all_files.return_value = file_list

        self.p.update_field_with_filegroup(FILE_TYPES.DARK_BEFORE, mock_file_group)

        mock_file_group.find_all_files.assert_called_once_with()
        mock_file_group.find_log_file.assert_not_called()
        self.fields["Dark Before"].set_images.assert_called_once_with(file_list)

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.FilenameGroup")
    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.read_image_dimensions")
    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.LoadPresenter.update_field_with_filegroup")
    def test_do_update_sample_no_related(self, mock_update_field, mock_read_image_dimensions, mock_filename_group):
        selected_file = "/a/b/img_000.tif"
        mock_read_image_dimensions.return_value = [10, 11]
        mock_sample_fg = mock.create_autospec(FilenameGroup)
        mock_filename_group.from_file.return_value = mock_sample_fg
        mock_sample_fg.all_indexes = [0, 1, 2, 3]
        mock_sample_fg.find_related.return_value = None

        self.p.do_update_sample(selected_file)

        mock_update_field.assert_called_once_with(FILE_TYPES.SAMPLE, mock_sample_fg)
        self.fields["Sample"].update_indices.assert_called_once_with(4)
        self.fields["Sample"].update_shape.assert_called_once_with([10, 11])
        self.v.ok_button.setEnabled.assert_called_once_with(True)

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.FilenameGroup")
    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.read_image_dimensions")
    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.LoadPresenter.update_field_with_filegroup")
    def test_do_update_sample_related_flat_before(self, mock_update_field, mock_read_image_dimensions,
                                                  mock_filename_group):
        selected_file = "/a/b/img_000.tif"
        mock_read_image_dimensions.return_value = [10, 11]
        mock_sample_fg = mock.create_autospec(FilenameGroup)
        mock_fb_fg = mock.create_autospec(FilenameGroup)
        mock_filename_group.from_file.return_value = mock_sample_fg
        mock_sample_fg.all_indexes = [0, 1, 2, 3]
        mock_sample_fg.find_related.side_effect = lambda ft: mock_fb_fg if ft == FILE_TYPES.FLAT_BEFORE else None

        self.p.do_update_sample(selected_file)

        updated_fields = [c.args[0] for c in mock_update_field.mock_calls]
        self.assertIn(FILE_TYPES.SAMPLE, updated_fields)
        self.assertIn(FILE_TYPES.FLAT_BEFORE, updated_fields)
        self.assertNotIn(FILE_TYPES.FLAT_AFTER, updated_fields)
        self.assertNotIn(FILE_TYPES.DARK_BEFORE, updated_fields)
        self.assertNotIn(FILE_TYPES.DARK_AFTER, updated_fields)

    @mock.patch("mantidimaging.core.io.filenames.FilenameGroup.all_files")
    @mock.patch("mantidimaging.core.io.filenames.FilenameGroup.find_all_files")
    def test_do_update_flat_or_dark(self, mock_find_all_files, mock_all_files):
        file_name = "/aaa_0000.tiff"
        ft = FILE_TYPES.FLAT_BEFORE
        field = mock.MagicMock(file_info=ft)
        files_list = [file_name, "aaa_0001.tiff"]
        mock_all_files.return_value = files_list

        self.p.do_update_flat_or_dark(field, file_name)

        field.set_images.assert_called_once_with(files_list)

    def test_do_update_single_file(self):
        file_name = "file_name"
        field = mock.MagicMock(file_info=FILE_TYPES.PROJ_180)

        self.p.do_update_single_file(field, file_name)

        self.assertEqual(field.path, Path(file_name))

    def test_do_update_single_file_no_file_selected(self):
        file_name = "file_name"
        field = mock.MagicMock(file_info=FILE_TYPES.PROJ_180)

        self.p.do_update_single_file(field, None)

        self.assertNotEqual(field.path, file_name)

    def test_do_update_sample_log_no_sample_selected(self):
        field = mock.MagicMock()
        self.p.sample_fg = None
        self.assertRaises(RuntimeError, self.p.do_update_sample_log, field, "")

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.LoadPresenter.ensure_sample_log_consistency")
    def test_do_update_sample_log(self, mock_ensure):
        file_name = "file_name"

        field = mock.MagicMock(file_info=FILE_TYPES.SAMPLE_LOG)

        self.p.sample_fg = mock.create_autospec(FilenameGroup)
        self.p.do_update_sample_log(field, file_name)

        mock_ensure.assert_called_once_with(field, file_name, [])

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.load_log")
    def test_ensure_sample_log_consistency_matching(self, mock_load_log):
        """
        Test behaviour when the number of projection angles and files matches
        """
        mock_log = mock.create_autospec(InstrumentLog)
        mock_load_log.return_value = mock_log
        file_name = "file_name"
        field = mock.MagicMock()
        field.path = None
        field.use = None
        test_filenames = ["file1", "file2"]

        self.p.ensure_sample_log_consistency(field, file_name, test_filenames)

        mock_load_log.assert_called_once_with(Path(file_name))
        mock_log.raise_if_angle_missing.assert_called_once_with(test_filenames)
        self.assertIsNotNone(field.path)
        self.assertIsNotNone(field.use)

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.load_log")
    def test_ensure_sample_log_consistency_exits_when_none_or_empty_str(self, mock_load_log):
        mock_log = mock.create_autospec(InstrumentLog)
        mock_load_log.return_value = mock_log
        file_name = None
        field = mock.MagicMock()
        test_filenames = ["file1", "file2"]

        self.p.ensure_sample_log_consistency(field, file_name, test_filenames)

        mock_load_log.assert_not_called()
        mock_log.raise_if_angle_missing.assert_not_called()

        file_name = ""
        self.p.ensure_sample_log_consistency(field, file_name, test_filenames)

        mock_load_log.assert_not_called()
        mock_log.raise_if_angle_missing.assert_not_called()

    @mock.patch("mantidimaging.gui.windows.image_load_dialog.presenter.FilenameGroup.find_all_files")
    def test_get_parameters(self, _):
        sample_path = Path("/sample/tomo/tomo_0001.tiff")
        sample_log_path = Path("/sample/tomo.log")
        sample_indices = Indices(0, 10, 1)

        type(self.fields["Sample"]).path = mock.PropertyMock(return_value=sample_path)
        self.fields["Sample"].use.isChecked.return_value = True
        type(self.fields["Sample"]).indices = mock.PropertyMock(return_value=sample_indices)
        type(self.fields["Sample Log"]).path = mock.PropertyMock(return_value=sample_log_path)

        flat_before_path = Path("/sample/flat_before/flat_before_0001.tiff")
        flat_before_log = Path("/sample/flat_before.log")
        flat_after_path = Path("/sample/flat_after/flat_after_0001.tiff")
        flat_after_log = Path("/sample/flat_after.log")
        dark_before_path = Path("/sample/dark_before/dark_before_0001.tiff")
        dark_after_path = Path("/sample/dark_after/dark_after_0001.tiff")
        proj_180_path = Path("/sample/180deg/180deg.tiff")
        self.fields["Flat Before"].use.isChecked.return_value = True
        type(self.fields["Flat Before"]).path = mock.PropertyMock(return_value=flat_before_path)
        type(self.fields["Flat Before Log"]).path = mock.PropertyMock(return_value=flat_before_log)
        self.fields["Flat After"].use.isChecked.return_value = True
        type(self.fields["Flat After"]).path = mock.PropertyMock(return_value=flat_after_path)
        type(self.fields["Flat After Log"]).path = mock.PropertyMock(return_value=flat_after_log)
        type(self.fields["Dark Before"]).path = mock.PropertyMock(return_value=dark_before_path)
        type(self.fields["Dark After"]).path = mock.PropertyMock(return_value=dark_after_path)
        type(self.fields["180 degree"]).path = mock.PropertyMock(return_value=proj_180_path)

        pixel_size = 24
        dtype = "float32"
        sinograms = True
        self.v.pixelSize.value.return_value = pixel_size
        self.v.pixel_bit_depth.currentText.return_value = dtype
        self.v.images_are_sinograms.isChecked.return_value = sinograms

        lp = self.p.get_parameters()

        lp_sample = lp.image_stacks[FILE_TYPES.SAMPLE]
        lp_flat_before = lp.image_stacks[FILE_TYPES.FLAT_BEFORE]
        lp_flat_after = lp.image_stacks[FILE_TYPES.FLAT_AFTER]
        lp_dark_before = lp.image_stacks[FILE_TYPES.DARK_BEFORE]
        lp_dark_after = lp.image_stacks[FILE_TYPES.DARK_AFTER]
        lp_proj_180deg = lp.image_stacks[FILE_TYPES.PROJ_180]

        self._files_equal(next(lp_sample.file_group.all_files()), sample_path)
        self._files_equal(lp_sample.log_file, sample_log_path)
        self.assertEqual(lp_sample.indices, sample_indices)

        self._files_equal(next(lp_flat_before.file_group.all_files()), flat_before_path)
        self._files_equal(next(lp_flat_after.file_group.all_files()), flat_after_path)
        self._files_equal(next(lp_dark_before.file_group.all_files()), dark_before_path)
        self._files_equal(next(lp_dark_after.file_group.all_files()), dark_after_path)
        self._files_equal(next(lp_proj_180deg.file_group.all_files()), proj_180_path)

        self._files_equal(lp_flat_before.log_file, flat_before_log)
        self._files_equal(lp_flat_after.log_file, flat_after_log)
        self.assertIsNone(lp_dark_before.log_file)
        self.assertIsNone(lp_dark_after.log_file)
        self.assertIsNone(lp_proj_180deg.log_file)

        self.assertEqual(lp.name, sample_path.name)
        self.assertEqual(lp.dtype, dtype)
        self.assertEqual(lp.sinograms, sinograms)
        self.assertEqual(lp.pixel_size, pixel_size)

        self.assertNotIn(FILE_TYPES.SAMPLE_LOG, lp.image_stacks.keys())
        self.assertNotIn(FILE_TYPES.FLAT_BEFORE_LOG, lp.image_stacks.keys())
        self.assertNotIn(FILE_TYPES.FLAT_AFTER_LOG, lp.image_stacks.keys())


import os
import numpy as np
import cv2

# dair_path = {
#     'single': 'dair_single_2022_09_19_20_24_05_FromKris',
#     'late': 'dair_single_late_2022_09_19_20_24_05_FromKris',
#     'v2vnet': 'dair_npj_v2vnet_w_2022_09_17_19_50_39',
#     'disconet': 'dair_npj_pointpillar_disconet_w_2022_09_13_11_12_24',
#     'when2com': 'dair_npj_when2com_2022_09_18_21_30_04',
#     'where2comm': 'dair_npj_where2comm_multiscale_resnet_max_2022_09_14_23_08_17',
#     'v2xvit': 'dair_npj_v2xvit_w_2022_09_06_12_31_46_FromKris'
# }

dair_path = {
    'single': 'logs/dair_single_late_2022_09_22_20_19_14',
    'disconet': 'logs/dair_disconet_2022_09_22_20_27_45',
    'when2com': 'logs/dair_when2com_2022_09_22_23_07_02',
    'where2comm': 'bp_logs/dair_npj_where2comm_multiscale_resnet_max_2022_09_14_23_08_17'
}

v2x_path = {
    'single': 'logs/v2x2_single_2022_09_22_01_28_30',
    'late': 'logs/v2x2_single_late_2022_09_22_01_28_30',
    'where2comm': 'logs/v2x2_npj_where2comm_multiscale_resnet_max_2022_09_22_01_17_57'
}

# Crop and merge image
def load_img(root_dir, img_id, mode):
    img_dir = os.path.join('opencood/', root_dir, 'vis_{}'.format(mode), '{}_{:05d}.png'.format(mode, img_id))
    if not os.path.exists(img_dir):
        print(img_dir)
        return None
    img = cv2.imread(img_dir)
    H, W, _ = img.shape
    if mode == '3d':
        h, w = 340, 50
    else:
        h, w = 460, 50 # for dair
        # h, w = 50, 350  # for v2x
    img = img[h:H-h,w:W-w]
    return img

dataset = 'dair'
root_save_path = 'opencood/visualization/merged/{}'.format(dataset)
if not os.path.exists(root_save_path):
    os.mkdir(root_save_path)

def merge_img(img_id, picked_model, align='row', mode='3d'):
    images = []
    for model in picked_model:
        image = load_img(model, img_id, mode)
        if image is not None:
            images.append(image)
        else:
            return None

    if align == 'row':
        images = np.concatenate(images, axis=1)
    else:
        images = np.concatenate(images, axis=0)

    image_save_path = os.path.join(root_save_path, mode, '{:05d}.png'.format(img_id))
    print(image_save_path)
    # if not os.path.exists(image_save_path):
    cv2.imwrite(image_save_path, images)
    return images

# mode = '3d'
# align = 'row'
mode = 'bev'
align = 'col'
start_idx = 0
end_idx = 100
gap = 100

picked_mode = ['single', 'when2com', 'disconet', 'where2comm']
# dataset = 'v2x'
# picked_model = [v2x_path[x] for x in picked_mode]
picked_model = [dair_path[x] for x in picked_mode]
video_save_path = os.path.join(root_save_path, 'result_video')
if not os.path.exists(video_save_path):
    os.makedirs(video_save_path)

for start_id in range(start_idx, end_idx, gap):
    end_id = start_id + gap
    for mode, align in zip(['bev', '3d'], ['col', 'row']):
        save_path = os.path.join(root_save_path, mode)
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        img_array = []
        for img_id in range(start_id, end_id):
            image = merge_img(img_id, picked_model, align, mode)

            if image is None:
                continue
            height, width, layers = image.shape
            size = (width,height)
            img_array.append(image)

        out = cv2.VideoWriter(os.path.join(root_save_path, 'result_video/{}_{}_{}.mp4'.format(dataset, mode, start_id, end_id)), cv2.VideoWriter_fourcc(*'mp4v'), 15, size)
        for i in range(len(img_array)):
            out.write(img_array[i])
        out.release()
        break


from django.urls import path
from .views import OrdersPageView, OrderListView, OrderDetailView, MyOrderListView
from . import views

urlpatterns = [
    path('', OrdersPageView.as_view(), name='orders'),
    path('create/', views.order_create, name='order_create'),
    path('order_list/', OrderListView.as_view(), name='order_list'),
    path('detail_order/<pk>/', OrderDetailView.as_view(), name='detail_order'),
    # path('my_orders/', views.my_orders, name='my_orders'),
    path('my_orders/', MyOrderListView.as_view(), name='my_orders'),
]


import mock

from django.contrib.auth import get_user_model

from bulbs.contributions.tasks import (
    check_and_update_freelanceprofiles, check_and_run_send_byline_email
)
from bulbs.utils.test import make_content, BaseIndexableTestCase

from example.testcontent.models import TestContentObj

User = get_user_model()

class BylineTaskTestCase(BaseIndexableTestCase):

    def setUp(self):
        super(BylineTaskTestCase, self).setUp()
        self.king = User.objects.create(first_name="King", last_name="Kush")
        self.content = make_content(TestContentObj, published=self.now, authors=[self.king])

    def test_task_calls_send_success(self):
        with mock.patch("django.core.mail.EmailMultiAlternatives.send") as mock_send:
            check_and_run_send_byline_email.delay(self.content.id, [])
            self.assertTrue(mock_send.called)

    def test_update_freelanceprofile(self):
        user = User.objects.create(email="admin@theonion.com", username="favoriteguy")
        self.assertFalse(hasattr(user, "freelanceprofile"))
        self.content.authors.add(user)
        self.content.save()
        check_and_update_freelanceprofiles.delay(self.content.id)

        user = User.objects.get(id=user.id)
        self.assertTrue(hasattr(user, "freelanceprofile"))
        self.assertTrue(user.freelanceprofile.is_freelance)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 00:12:30 2020

@author: celinemazoukh1
"""

# Import Modules ##
#from __future__ import absolute_import, print_function, division
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from tqdm import tqdm
import time

from scipy.optimize import curve_fit

# Define fit functions.
def fit_function(x, A, mu, sigma,B=0):
    return A * np.exp(-1.0 * (x - mu)**2 / (2 * sigma**2)) + B

def fit_functionH(x, m,b):
    return m*x + b

rng = 100000
#resol = 156e9
#tolerance = 100000 #floor(rng/resol)
width = 200

##################
dataName = 'raw-2311-fsp'
paper = 'Fine'
##################

# Load data as a dataframe
print("loading file via pandas")
pdtime = time.time()
df = pd.read_table('{}.txt'.format(dataName),usecols=[6, 7], dtype = np.int64)

pdend=time.time()

print("pd loaded in" , pdend - pdtime)

# work with just the first few elements for now
#df = df.head(4000)
#print(df)

# loop through indices:if within range, add to histo and increment both indices
# if not, check whether too positive or too negative and increment accordingly
#dlist = np.zeros(df.shape)
#'''
loopst = time.time()
i = 0
j = 0
n = df.shape[0]
dlist = [] #np.zeros((n,n), dtype=np.int64)
while i < n and j < n:
    diff = df.iloc[i,0] - df.iloc[j,1]
    #print( i, j)

    if rng>abs(diff):
        dlist.append(diff)

    if diff<0:
        i += 1
    else:
        j += 1

#dlist = dlist.flatten()
dpd = pd.DataFrame(dlist)
loopend = time.time()

#dpd = pd.read_csv('raw3_processed_labviewVeroutput.csv',usecols=[1])
#darray = dpd.to_numpy()
#dpd = (dpd+rng)/width

print("loop complete in", loopend-loopst)
#print(len(dlist))

# write the arrays to a txt file
#dpd.to_csv('raw3_processed_labviewVeroutput.csv')

'''
loopst = time.time()
i = 0
j = 0
n = df.shape[0]
dlist = [] #np.zeros((n,n), dtype=np.int64)
while i < n and j < n:
    diff = df.iloc[i,0] - df.iloc[j,1]
    #print( i, j)

    if rng>abs(diff):
        dlist.append(diff)
        i += 1
        j += 1

    else:
        if diff<0:
            i += 1
        else:
            j += 1

#dlist = dlist.flatten()
dpd = pd.DataFrame(dlist)
loopend = time.time()
#'''
# load and plot the AB counts gen by labview
plt.figure()
coinc = pd.read_table('{}.txt'.format(dataName),usecols=[0, 1], dtype = np.int64)
coinc = coinc.head(101)
'''
# before fitting: slice coinc data to remove bump
wings = coinc.drop('tAB', axis=1) # drops the times column
wings = wings.drop(coinc.index[35:65]) # CHANGE PER EACH SP
wings = wings.to_numpy(dtype= 'float16')
wings=wings.flatten()
print(wings)

# Fit the function to the histogram data.
#xsH = np.linspace(-10000,10000,71)
#poptH, pcovH = curve_fit(fit_functionH, xdata=xsH, ydata=wings)
print(poptH)

'''

coinc.plot(kind='line', x='tAB', y='nAB')
#plt.plot(xsH, fit_functionH(xsH, *poptH), color='red', linestyle='dashed', label='Fitted function')
plt.ylim(0,20000)
plt.xlabel('Time Delay (ns)')
plt.ylabel('Number of Coincidences')
#plt.title('Labview-generated Histogram: {} dataset'.format(dataName))
plt.title('Coincidences Histogram: {} grit sandpaper'.format(paper))

#plt.savefig('labviewHist-{}-final.png'.format(dataName),dpi=200)
plt.savefig('Coincidences Histogram: {} grit sandpaper - ax'.format(paper))
plt.show()

#plt.figure()
#dpd.plot.hist(bins=101)
#plt.show()
'''
print("yeet")

darray = dpd.to_numpy()
# Add histograms of exponential and gaussian data.
data_entries, binscenters, _ =  plt.hist(darray, 101)

# Fit the function to the histogram data.
#popt, pcov = curve_fit(fit_function, xdata=binscenters[1:], ydata=data_entries, p0=[1, 0, 100, 1000])
print(popt)

# Generate enough x values to make the curves look smooth.
xspace = np.linspace(min(binscenters), max(binscenters) , 100000)

# Plot the histogram and the fitted function.
#plt.bar(binscenters, data_entries, width=binscenters[1] - binscenters[0], color='navy', label='Histogram entries')

plt.hist(darray,101)
#plt.plot(xspace, fit_function(xspace, *popt), color='red', linewidth=2.5, label='Fitted function')

# Make the plot nicer.
plt.xlim(min(binscenters),max(binscenters))
#plt.ylim(0,30000)
plt.xlabel('Time Delay (ns)')
plt.ylabel('Number of coincidences')
plt.title('Coincidence Count histogram: {} grit dataset'.format(paper))
plt.legend(loc='best')
#plt.savefig('pyHist-J-{n}-dfLength{l}-FINAL.png'.format(n=dataName,l=len(df)),dpi=200)
plt.show()
plt.clf()
'''


import sys

import pygame

class BlueScreen:
	"""A general class that controls the behavior of the program."""

	def __init__(self):
		"""Create a screen and set its color."""
		pygame.init()

		self.screen = pygame.display.set_mode((1200, 650))
		pygame.display.set_caption("Blue screen")

		self.bg_color = (0, 0, 255)

	def run(self):
		"""Start the program cycle."""
		while True:
			# Monitor mouse and keyboard behavior.
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					sys.exit()

			# Draw a screen on each loop interpretation.
			self.screen.fill(self.bg_color)

			# Show the last drawn screen.
			pygame.display.flip()

if __name__ =='__main__':
	# Create an instance of the screen and run it
	s = BlueScreen()
	s.run()


# -*- coding: utf-8 -*-
import sys
from .WrapperClasses import *

class Generator():

    __TestList__ = TestCaseClass()
    __loadready__ = False
    __versionType__ = None
    __resourceName__ = None
    __resourceType__ = None

    #修改了 load_definition 的方式，作为传入 版本与resourceName
    def load_definition(self,version,resourceName):
        parameters = []
        parameters.append(version)
        parameters.append(resourceName)
        if self.__TestList__.ReturnClassByDataBaseName('MongoDB',parameters,'selectForCount'):
            self.__versionType__ = version
            self.__resourceName__ = resourceName
            self.__loadready__ = True
            return True
        else:
            self.__loadready__ = False
            self.__versionType__ = None
            self.__resourceName__ = None
            return False

    def resouce_type(self):
        return self.__resourceType__

    #获取到正确cases的list
    def correct_cases(self,hint):
        if self.__loadready__:
            parameters = []
            parameters.append(self.__versionType__)
            parameters.append(self.__resourceName__)
            parameters.append('1')
            parameters.append(hint)
            list = self.__TestList__.ReturnClassByDataBaseName('MongoDB',parameters,'selectForList')
            return list
        return None

    #获取到错误cases的list
    def wrong_cases(self):
        if self.__loadready__:
            parameters = []
            parameters.append(self.__versionType__)
            parameters.append(self.__resourceName__)
            parameters.append('0')
            list = self.__TestList__.ReturnClassByDataBaseName('MongoDB', parameters, 'selectForList')
            return list
        return None

    # 通过传入特定的网页来获取参数
    # def __getElement__(self,spec_url):
    #     url = spec_url
    #     try:
    #         req = urllib2.urlopen(url)
    #         soup = BeautifulSoup(req,'html.parser')
    #         title = soup.find('title').text.replace(' ','')
    #         try:
    #             list = title.split('-FHIRv')
    #         except Exception,e:
    #             print e
    #             return False
    #         self.__resourceName__ = list[0].encode('utf-8')
    #         self.__versionType__ = list[1].encode('utf-8')
    #         self.__loadready__ = True
    #         return True
    #     except Exception,e:
    #         print e
    #     return False


import pytest
from diopter.compiler import Language, ObjectCompilationOutput, SourceProgram
from program_markers.instrumenter import InstrumenterMode, instrument_program
from program_markers.iprogram import find_non_eliminated_markers_impl, rename_markers
from program_markers.markers import (
    AsmCommentDetectionStrategy,
    AsmCommentEmptyOperandsDetectionStrategy,
    AsmCommentGlobalOutOperandDetectionStrategy,
    AsmCommentLocalOutOperandDetectionStrategy,
    AsmCommentVolatileGlobalOutOperandDetectionStrategy,
    FunctionCallDetectionStrategy,
    GlobalIntDetectionStrategy,
    GlobalVolatileIntDetectionStrategy,
    LocalVolatileIntDetectionStrategy,
    VRMarker,
)

from .utils import get_system_gcc_O0, get_system_gcc_O3

def test_asm_parsing() -> None:
    asm = """
    call VRMarker0_@PLT
.L2:
    cmpl	$0, -4(%rbp)
    js	.L3
    call	VRMarker1_@PLT
    """
    markers = (
        VRMarker.from_str("VRMarker0_", "int"),
        VRMarker.from_str("VRMarker1_", "int"),
    )
    assert (
        set(
            find_non_eliminated_markers_impl(
                asm, markers, FunctionCallDetectionStrategy()
            )
        )
    ) == set(
        (
            VRMarker.from_str("VRMarker0_", "int"),
            VRMarker.from_str("VRMarker1_", "int"),
        )
    )

    asm = """
    js	.L2
    call	VRMarker1_@PLT
"""
    assert (
        set(
            find_non_eliminated_markers_impl(
                asm, markers, FunctionCallDetectionStrategy()
            )
        )
    ) == set((VRMarker.from_str("VRMarker1_", "int"),))

def test_instrumentation() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
    int foo(int a, int b){
        if (a+b)
            return 1;
        return 0;
    }
    """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )
    assert set(
        (
            VRMarker.from_str("VRMarker0_", "int"),
            VRMarker.from_str("VRMarker1_", "int"),
        )
    ) == set(iprogram.enabled_markers())

    gcc = get_system_gcc_O0()
    assert set(
        (
            VRMarker.from_str("VRMarker0_", "int"),
            VRMarker.from_str("VRMarker1_", "int"),
        )
    ) == set(iprogram.find_non_eliminated_markers(gcc))
    assert set() == set(iprogram.find_eliminated_markers(gcc))

def test_disable_markers() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
    int foo(int a, int b){
        if (a+b)
            return 1;
        return 0;
    }
    """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )

    gcc = get_system_gcc_O0()

    with pytest.raises(AssertionError):
        iprogram.disable_markers((VRMarker.from_str("VRMarker2_", "int"),))

    iprogram0 = iprogram.disable_markers((VRMarker.from_str("VRMarker0_", "int"),))
    assert set((VRMarker.from_str("VRMarker0_", "int"),)) == set(
        iprogram0.disabled_markers()
    )
    assert set((VRMarker.from_str("VRMarker1_", "int"),)) == set(
        iprogram0.find_non_eliminated_markers(gcc)
    )
    assert set((VRMarker.from_str("VRMarker0_", "int"),)) == set(
        iprogram0.find_eliminated_markers(gcc, include_all_markers=True)
    )
    assert set() == set(
        iprogram0.find_eliminated_markers(gcc, include_all_markers=False)
    )
    # disabling the same marker twice shouldn't have any effect
    assert iprogram0 == iprogram0.disable_markers(
        (VRMarker.from_str("VRMarker0_", "int"),)
    )

    iprogram1 = iprogram.disable_remaining_markers()
    assert set(
        (VRMarker.from_str("VRMarker0_", "int"), VRMarker.from_str("VRMarker1_", "int"))
    ) == set(iprogram1.disabled_markers())
    assert set() == set(iprogram1.find_non_eliminated_markers(gcc))
    assert set(
        (
            VRMarker.from_str("VRMarker0_", "int"),
            VRMarker.from_str("VRMarker1_", "int"),
        )
    ) == set(iprogram1.find_eliminated_markers(gcc, include_all_markers=True))
    assert set() == set(
        iprogram1.find_eliminated_markers(gcc, include_all_markers=False)
    )

    iprogram1_1 = iprogram1.disable_remaining_markers()
    assert set(
        (
            VRMarker.from_str("VRMarker0_", "int"),
            VRMarker.from_str("VRMarker1_", "int"),
        )
    ) == set(iprogram1_1.disabled_markers())
    assert set() == set(iprogram1_1.find_non_eliminated_markers(gcc))
    assert set(
        (
            VRMarker.from_str("VRMarker0_", "int"),
            VRMarker.from_str("VRMarker1_", "int"),
        )
    ) == set(iprogram1_1.find_eliminated_markers(gcc, include_all_markers=True))
    assert set() == set(
        iprogram1_1.find_eliminated_markers(gcc, include_all_markers=False)
    )

    iprogram2 = iprogram.disable_remaining_markers()
    # disabling all remaining markers twice shouldn't have any effect
    assert iprogram2 == iprogram2.disable_remaining_markers()
    assert set(
        (VRMarker.from_str("VRMarker0_", "int"), VRMarker.from_str("VRMarker1_", "int"))
    ) == set(iprogram2.disabled_markers())
    assert set(()) == set(iprogram2.find_non_eliminated_markers(gcc))
    assert set(
        (VRMarker.from_str("VRMarker0_", "int"), VRMarker.from_str("VRMarker1_", "int"))
    ) == set(iprogram2.find_eliminated_markers(gcc, include_all_markers=True))
    assert set() == set(
        iprogram2.find_eliminated_markers(gcc, include_all_markers=False)
    )

def test_unreachable() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
    int foo(int a, int b){
        if (a+b){
            return 1;
        }
        return 0;
    }
    """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )
    gcc = get_system_gcc_O0()

    with pytest.raises(AssertionError):
        iprogram.make_markers_unreachable((VRMarker.from_str("VRMarker2_", "int"),))

    iprogram0 = iprogram.make_markers_unreachable(
        (VRMarker.from_str("VRMarker0_", "int"),)
    )
    assert set((VRMarker.from_str("VRMarker0_", "int"),)) == set(
        iprogram0.unreachable_markers()
    )
    assert set((VRMarker.from_str("VRMarker1_", "int"),)) == set(
        iprogram0.find_non_eliminated_markers(gcc)
    )
    assert set((VRMarker.from_str("VRMarker0_", "int"),)) == set(
        iprogram0.find_eliminated_markers(gcc, include_all_markers=True)
    )
    assert set() == set(
        iprogram0.find_eliminated_markers(gcc, include_all_markers=False)
    )
    assert set((VRMarker.from_str("VRMarker0_", "int"),)) == set(
        iprogram0.find_eliminated_markers(gcc, include_all_markers=True)
    )
    assert set() == set(
        iprogram0.find_eliminated_markers(gcc, include_all_markers=False)
    )
    # Making the same marker unreachable twice shouldn't have any effect
    assert iprogram0 == iprogram0.make_markers_unreachable(
        (VRMarker.from_str("VRMarker0_", "int"),)
    )

def test_disable_and_unreachable() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
    int foo(int a, int b){
        if (a+b){
            return 1;
        }
        return 0;
    }
    """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )
    gcc = get_system_gcc_O0()

    iprogram = iprogram.make_markers_unreachable(
        (VRMarker.from_str("VRMarker0_", "int"),)
    )
    with pytest.raises(AssertionError):
        # We can't disable a marker that was already make unreachable
        iprogram.disable_markers((VRMarker.from_str("VRMarker0_", "int"),))

    iprogram = iprogram.disable_markers((VRMarker.from_str("VRMarker1_", "int"),))
    with pytest.raises(AssertionError):
        # We can't make ureachable a marker that was already disabled
        iprogram = iprogram.make_markers_unreachable(
            (VRMarker.from_str("VRMarker1_", "int"),)
        )
    assert set((VRMarker.from_str("VRMarker0_", "int"),)) == set(
        iprogram.unreachable_markers()
    )
    assert set((VRMarker.from_str("VRMarker1_", "int"),)) == set(
        iprogram.disabled_markers()
    )

    assert set(()) == set(iprogram.find_non_eliminated_markers(gcc))
    assert set(
        (
            VRMarker.from_str("VRMarker0_", "int"),
            VRMarker.from_str("VRMarker1_", "int"),
        )
    ) == set(iprogram.find_eliminated_markers(gcc, include_all_markers=True))
    assert set() == set(
        iprogram.find_eliminated_markers(gcc, include_all_markers=False)
    )

    # All markers have already been disabled or made unreachable
    assert iprogram == iprogram.disable_remaining_markers()

def test_refinement() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
    static int foo(int a, int b){
        if (a+b){
            return 1;
        }
        return 0;
    }
    int main(){
        return foo(1,1) - foo(1,2);
    }
    """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )
    gcc = get_system_gcc_O0()
    rprogram, reachable_markers = iprogram.refine_markers_with_runtime_information(
        (), gcc
    )
    assert len(reachable_markers) == 2, reachable_markers
    refined_markers = list(sorted(reachable_markers, key=lambda m: m.id))
    assert isinstance(refined_markers[0], VRMarker)
    assert refined_markers[0].lower_bound == 1
    assert refined_markers[0].upper_bound == 1
    assert isinstance(refined_markers[1], VRMarker)
    assert refined_markers[1].lower_bound == 1
    assert refined_markers[1].upper_bound == 2
    rprogram = iprogram.replace_markers(tuple(refined_markers))
    gcc = get_system_gcc_O3()
    assert len(iprogram.find_eliminated_markers(gcc)) == 0
    assert len(rprogram.find_eliminated_markers(gcc)) == 2

    reachable_markers2 = rprogram.track_reachable_markers((), gcc)
    # The refined markers should be unreachable since their new bounds are tight
    assert len(reachable_markers2) == 0

def test_strategies() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
        static int foo(int a, int b){
            return a + b;
        }
        int main()
        {
            return foo(-1,1);
        }
        """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )
    marker0 = iprogram.enabled_markers()[0]
    marker0 = VRMarker(marker0.name, marker0.id, "int", -10, 10)
    marker1 = iprogram.enabled_markers()[1]
    iprogram = iprogram.replace_markers((marker0,))

    all_marker_strategies = (
        FunctionCallDetectionStrategy(),
        AsmCommentDetectionStrategy(),
        AsmCommentEmptyOperandsDetectionStrategy(),
        AsmCommentLocalOutOperandDetectionStrategy(),
        AsmCommentGlobalOutOperandDetectionStrategy(),
        AsmCommentVolatileGlobalOutOperandDetectionStrategy(),
        LocalVolatileIntDetectionStrategy(),
        GlobalVolatileIntDetectionStrategy(),
        GlobalIntDetectionStrategy(),
    )
    gcc = get_system_gcc_O3()

    for strategy in all_marker_strategies:
        ip = iprogram.with_marker_strategy(strategy)
        markers = ip.find_non_eliminated_markers(gcc)

        assert marker0 not in markers
        assert marker1 in markers

def test_variable_name_and_type() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
        static int foo(long a, int b){
            return a + b;
        }
        """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )

    markers = [marker for marker in iprogram.markers if isinstance(marker, VRMarker)]
    assert len(markers) == 2
    assert {marker.get_variable_name_and_type(iprogram.code) for marker in markers} == {
        ("a", '"long"'),
        ("b", '"int"'),
    }

def test_number_occurences() -> None:
    iprogram = instrument_program(
        SourceProgram(
            code="""
        static int foo(long a, int b){
            return a + b;
        }
        """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )

    markers = [marker for marker in iprogram.markers if isinstance(marker, VRMarker)]
    assert len(markers) == 2
    for marker in markers:
        assert marker.number_occurences_in_code(iprogram.code) == 1

    code = """
        static int foo(long a, int b){
            VRMARKERMACRO0_(a, "long")
            VRMARKERMACRO0_(a, "long")
            VRMARKERMACRO1_(b, "int")
            return a + b;
        }
        """

    markers = sorted(markers, key=lambda m: m.id)
    assert markers[0].number_occurences_in_code(code) == 2
    assert markers[1].number_occurences_in_code(code) == 1

def test_marker_renaming() -> None:
    iprogram_0 = instrument_program(
        SourceProgram(
            code="""
    int foo(int a){
        if (a)
            return 1;
        return 0;
    }
    """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )
    iprogram_1 = instrument_program(
        SourceProgram(
            code="""
    int foo(int a, int b){
        if (a+b)
            return 1;
        return 0;
    }
    """,
            language=Language.C,
        ),
        mode=InstrumenterMode.VR,
    )

    iprogram0, iprogram1 = rename_markers((iprogram_0, iprogram_1))

    assert set((VRMarker.from_str("VRMarker0_", "int"),)) == set(
        iprogram0.enabled_markers()
    )
    assert set(
        (
            VRMarker.from_str("VRMarker1_", "int"),
            VRMarker.from_str("VRMarker2_", "int"),
        )
    ) == set(iprogram1.enabled_markers())

    assert (
        VRMarker.from_str("VRMarker0_", "int").macro_without_arguments()
        in iprogram0.code
    ), iprogram0.code

    assert (
        VRMarker.from_str("VRMarker1_", "int").macro_without_arguments()
        in iprogram1.code
    ), iprogram1.code
    assert (
        VRMarker.from_str("VRMarker2_", "int").macro_without_arguments()
        in iprogram1.code
    ), iprogram1.code

    gcc = get_system_gcc_O0()
    gcc.compile_program(iprogram1, ObjectCompilationOutput())


import numpy as np
import cv2

arucoDict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50)
tag = np.zeros((300, 300, 1), dtype="uint8")

for id in range(50):
    print(id)
    cv2.aruco.drawMarker(arucoDict, id, 300, tag, 1)
    cv2.imshow('ArUco Marker:', tag)
    if cv2.waitKey(1000) & 0xFF == ord('e'):
        break

cv2.destroyAllWindows()


import json
import socket
from uuid import getnode as get_mac
import os
import sys

class Settings:

  def __init__(self, etcf, log):
    self.etcfname = etcf
    self.log = log
    self.mqtt_server = "192.168.1.7"   # From json
    self.mqtt_port = 1883              # From json
    self.mqtt_client_name = "detection_1"   # From json
    self.homie_device = None            # From json
    self.homie_name = None              # From json
    # IP and MacAddr are not important (should not be important).
    if sys.platform.startswith('linux'):
      s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
      s.connect(('<broadcast>', 0))
      self.our_IP =  s.getsockname()[0]
      # from stackoverflow (of course):
      self.macAddr = ':'.join(("%012x" % get_mac())[i:i+2] for i in range(0, 12, 2))
    elif sys.platform.startswith('darwin'):
      host_name = socket.gethostname()
      self.our_IP = socket.gethostbyname(host_name)
      self.macAddr = ':'.join(("%012x" % get_mac())[i:i+2] for i in range(0, 12, 2))
    else:
      self.our_IP = "192.168.1.255"
      self.macAddr = "de:ad:be:ef"
    self.load_settings(self.etcfname)
    print("Settings from", self.etcfname)

  def load_settings(self, fn):
    conf = json.load(open(fn))
    self.mqtt_server = conf.get("mqtt_server_ip", "192.168.1.255")
    self.mqtt_port = conf.get("mqtt_port", 1883)
    self.mqtt_client_name = conf.get("mqtt_client_name", "Bad Client")
    #  Homie,
    self.mqtt_root = conf.get("mqtt_root", "homie/network/status")
    self.mqtt_basic = conf.get("mqtt_basic", "basic")     # is a property, root+basic+/set
    self.mqtt_tb = conf.get("mqtt_tb" "trumpybear")
    self.check_every = conf.get("check_every", 120)
    self.ping_list = conf.get("ping_list", None)
    self.hubitat = conf.get("hubitat", "192.168.1.5")

  def print(self):
    print("==== Settings ====")
    print(self.settings_serialize())

  def settings_serialize(self):
    st = {}
    st['mqtt_server_ip'] = self.mqtt_server
    st['mqtt_port'] = self.mqtt_port
    st['mqtt_client_name'] = self.mqtt_client_name
    st["mqtt_root"] = self.mqtt_root
    st["mqtt_basic"] = self.mqtt_basic
    st["mqtt_tb"] = self.mqtt_tb
    st["check_every"] = self.check_every
    st["ping_list"] = self.ping_list
    st["hubitat"] = self.hubitat
    str = json.dumps(st)
    return str

  def settings_deserialize(self, jsonstr):
    st = json.loads(jsonstr)


#!/usr/bin/env python
"""
Inverts an image
usage: <script> file_in file_out
"""
import sys
from PIL import Image, ImageOps

def main():
    infile = sys.argv[1]
    outfile = sys.argv[2]
    i = Image.open(infile).convert('L')
    i2 = ImageOps.invert(i)
    i2.save(outfile)

if __name__ == '__main__':
    main()


'''
Izveidojiet Python programmu, kas saskaita no 1 līdz lietotāja ievadītam skaitlim, izmantojot for ciklu.
'''

# skaitiit no 1 lidxz skaitlim
def summa(n):
    sum = 0
    for i in range(1, n + 1):
        sum += i
    return sum

# vards
user_input = input("Ievadi skaitli līdz kuram vēlies saskaitīt: ")
user_input = int(user_input)

result = summa(user_input)

# izdrukaa summu
print("Summa no 1 līdz", user_input, "ir", result)