import os,sys
import xml.etree.ElementTree as etree

import Image

from bchMarkers import getMarker

configHead = """# produced by multiMarker.py

# number of markers
6
"""

markerText = """
# marker %s
%s
%s
0.0 0.0
 1.0000  0.0000 0.0000  %s
 0.0000  1.0000 0.0000  %s
 0.0000  0.0000 1.0000  0.000
"""

class MarkerPanel:
    # multi-marker panel with 6 markers on it
    size = (1100,850)
    margin = 50 # margin around markers
    markerSize = 220 # size of markers on page
    layout = (2,3)
    def __init__(self,markers,
                 size=size,
                 layout = layout,
                 margin=margin,
                 markerSize=markerSize,
                 ):
        margin = margin
        msize = markerSize

        mImages = self.markerImages = []
        for markerId in markers:
            image = getMarker(markerId)
            new = image.resize((msize,msize))
            mImages.append(new)

        firstRow = [ [0,0], [0,0], [0,0] ]
        secondRow = [ [0,0], [0,0], [0,0] ]
        positions = self.markerPositions = [
            firstRow,
            secondRow,
            ]

        mainImage = self.mainImage = Image.new('RGB',size,(255,255,255))
        cx,cy = size[0]/2,size[1]/2
        hsize = msize/2
        if 0:
            firstRow[1] = [cx - hsize,cy - msize - margin]
            secondRow[1] = [cx - hsize,cy + margin]
            firstRow[0] = [firstRow[1][0]-2*margin-msize,firstRow[1][1]]
            secondRow[0] = [secondRow[1][0]-2*margin-msize,secondRow[1][1]]
            firstRow[2] = [firstRow[1][0]+2*margin+msize,firstRow[1][1]]
            secondRow[2] = [secondRow[1][0]+2*margin+msize,secondRow[1][1]]
        else:
            sw,sh = size[0]/3.,size[1]/2.
            cx,cy = sw/2,sh/2
            firstRow[0] = [cx-hsize,cy-hsize]
            secondRow[0] = [firstRow[0][0],firstRow[0][1]+sh]
            firstRow[1] = [firstRow[0][0]+sw,firstRow[0][1]]
            secondRow[1] = [firstRow[1][0],secondRow[0][1]]
            firstRow[2] = [firstRow[1][0]+sw,firstRow[0][1]]
            secondRow[2] = [firstRow[2][0],secondRow[0][1]]

        cx,cy = size[0]/2,size[1]/2
        mIndex = 0
        config = configHead
        trans = [
            [ [-27.75,16.125],[0.0,16.125],[27.75,16.125] ],
            [ [-27.75,-16.125],[0.0,-16.125],[27.75,-16.125] ],
            ] # transforms for config file
        for i,row in enumerate(positions):
            for j,point in enumerate(row):
                mImage = mImages[mIndex]
                ipoint = tuple(map(int,point))
                mainImage.paste(mImage,ipoint)
                # setup config info
                if 0:
                    x = (point[0]+hsize) - cx
                    y = cy - (point[1]+hsize)
                else:
                    x,y = trans[i][j]
                #print point,cx,cy,x,y
                config += markerText%(markers[mIndex],markers[mIndex],
                                      16.125,x,y)

                mIndex += 1
        fnameRoot = '%s_%s_%s_%s_%s_%s'%tuple(markers)
        mainImage.save(fnameRoot+'.jpg')

        # save config file
        fp = open(os.path.join('data',fnameRoot+'.cfg'),'w')
        fp.write(config)
        fp.close()

def mb1_24():
    msize = 53
    ms2 = msize/2
    horCentGap = 35
    hcg = horCentGap/2
    verCentGap = 34
    vcg = verCentGap/2
    horGap = 34
    verGap = 49
    topLeft = [-hcg-msize-horGap-msize-horGap-ms2,vcg+msize+verGap+ms2,7]
    rowOne = [
        topLeft,
        [topLeft[0]+msize+horGap, topLeft[1],8],
        [topLeft[0]+2*msize+2*horGap, topLeft[1],9],
#         [topLeft[0]+3*msize+2*horGap+horCentGap,topLeft[1],19],
#         [topLeft[0]+4*msize+3*horGap+horCentGap,topLeft[1],20],
#         [topLeft[0]+4*msize+3*horGap+horCentGap,topLeft[1],21],
        [hcg+ms2,topLeft[1],19],
        [hcg+msize+horGap+ms2,topLeft[1],20],
        [hcg+2*msize+2*horGap+ms2,topLeft[1],21],
        ]
    rowTwo = [
        [rowOne[0][0],rowOne[0][1]-msize-verGap,10],
        [rowOne[1][0],rowOne[1][1]-msize-verGap,11],
        [rowOne[2][0],rowOne[2][1]-msize-verGap,12],
        [rowOne[3][0],rowOne[3][1]-msize-verGap,22],
        [rowOne[4][0],rowOne[4][1]-msize-verGap,23],
        [rowOne[5][0],rowOne[5][1]-msize-verGap,24],
        ]
    rowThree = [
        [rowTwo[0][0],-vcg-ms2,1],
        [rowTwo[1][0],-vcg-ms2,2],
        [rowTwo[2][0],-vcg-ms2,3],
        [rowTwo[3][0],-vcg-ms2,13],
        [rowTwo[4][0],-vcg-ms2,14],
        [rowTwo[5][0],-vcg-ms2,15],
        ]
    rowFour = [
        [rowThree[0][0],rowThree[0][1]-msize-verGap,4],
        [rowThree[1][0],rowThree[1][1]-msize-verGap,5],
        [rowThree[2][0],rowThree[2][1]-msize-verGap,6],
        [rowThree[3][0],rowThree[3][1]-msize-verGap,16],
        [rowThree[4][0],rowThree[4][1]-msize-verGap,17],
        [rowThree[5][0],rowThree[5][1]-msize-verGap,18],
        ]
    positions = [
        rowOne,
        rowTwo,
        rowThree,
        rowFour,
        ]
    config = configHead
    for i,row in enumerate(positions):
        for j,point in enumerate(row):
            x,y,mId = point
            config += markerText%(mId,mId,msize,x,y)

    fnameRoot = 'markerboard1_24'
    # save config file
    fp = open(os.path.join('data',fnameRoot+'.cfg'),'w')
    fp.write(config)
    fp.close()

if __name__=='__main__':
    if 1:
        markers = eval(sys.argv[1])
        if type(markers[0]) is type(1):
            mp = MarkerPanel(markers)
        else:
            for mlist in markers:
                mp = MarkerPanel(mlist)
        #mp.mainImage.show()
    else:
        mb1_24()


import cv2
import matplotlib.pyplot as plt
import numpy as np
from utils.ocg_utils import get_line_pixels

def visualize_spa_info(
    spa,
    draw_plane=False,
    corners=None,
    start_uv=None,
    end_uv=None,
    break_line=None
):

    H, W = spa.ocg.get_shape()
    image = np.zeros((H, W, 3), dtype=np.uint8)
    if draw_plane:
        plane_map = spa.get_plane_density()
        plane_map[plane_map > 0] = 1
        vs, us = plane_map.nonzero()
        image[vs, us, :] = np.array([127, 127, 127])
    else:
        all_nodes = spa.get_valid_pixels()
        image[all_nodes[:, 1], all_nodes[:, 0], :] = np.array([127, 127, 127])

    area = spa.get_interior_area()
    image[area] = np.array([0, 127, 0])

    if start_uv is not None:
        # Pink
        cv2.circle(image, (start_uv[0], start_uv[1]), 1, (254, 140, 173), -1)
    if end_uv is not None:
        # Green
        cv2.circle(image, (end_uv[0], end_uv[1]), 1, (0, 255, 0), -1)
    if break_line is not None:
        line_u, line_v = get_line_pixels(break_line[0], break_line[1])
        image[line_v, line_u, :] = np.array([255, 0, 0])

    return image

def visualize_room_result(spa, corners_uv, start_uv=None, end_uv=None, draw_plane=False):
    ocg = spa.ocg
    H, W = ocg.get_shape()
    image = np.zeros((H, W, 3), dtype=np.uint8)

    # Draw valid pixels
    if draw_plane:
        plane_map = spa.get_plane_density()
        plane_map[plane_map > 0] = 1
        vs, us = plane_map.nonzero()
        image[vs, us, :] = np.array([127, 127, 127])
    else:
        all_nodes = spa.get_valid_pixels()
        image[all_nodes[:, 1], all_nodes[:, 0], :] = np.array([127, 127, 127])

    # Draw interior area
    area = spa.get_interior_area()
    image[area] = np.array([0, 127, 0])

    # Draw result room shape
    size = corners_uv.shape[0]
    for i in range(size):
        x_u, x_v = corners_uv[i, :]
        y_u, y_v = corners_uv[(i+1) % size, :]

        cv2.line(image, (x_u, x_v), (y_u, y_v), (255, 255, 255), 1)
        cv2.circle(image, (x_u, x_v), 1, (255, 0, 0), -1)
        cv2.circle(image, (y_u, y_v), 1, (255, 0, 0), -1)
    if start_uv is not None:
        # Pink
        cv2.circle(image, (start_uv[0], start_uv[1]), 1, (254, 140, 173), -1)
    if end_uv is not None:
        # Green
        cv2.circle(image, (end_uv[0], end_uv[1]), 1, (0, 255, 0), -1)
    return image

def plot_room_result(spa, corners_uv, start_uv=None, end_uv=None):
    image_spa = visualize_room_result(spa, corners_uv, start_uv, end_uv, draw_plane=False)
    image_plane = visualize_room_result(spa, corners_uv, start_uv, end_uv, draw_plane=True)
    plt.figure("Room shape result")
    plt.clf()
    plt.subplot(121)
    plt.imshow(image_spa)
    plt.subplot(122)
    plt.imshow(image_plane)
    plt.draw()
    plt.waitforbuttonpress(0.1)


import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

from plotly.graph_objs import Scatter, Data
from plotly.offline import plot

from scipy.optimize import curve_fit

neurons_count = 2048

def weight_variable(shape):
    # Since we're using ReLU neurons, it is also good practice to initialize them
    # with a slightly positive initial bias to avoid "dead neurons".
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    # just constant
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def avg_pool_2x2(x):
    return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')

# Import data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# Create the model
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
# 28x28 pixels, 1 color, -1 means calculate automatically this dimension such that
# in total we have 784 elements
x_image = tf.reshape(x, [-1, 28, 28, 1])

# Define architecture of CNN

# 1-st convolutional layer
# 5x5 patch, 1 color (input channel), 32 features (output channel)
W_conv1 = weight_variable([5, 5, 1, 32])
# 32 features requires 32 biases
b_conv1 = bias_variable([32])

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  # 28x28x32
h_pool1 = avg_pool_2x2(h_conv1)  # 14x14x32

# Fully-connected layer
# 7x7x64=3136 neurons -> 1024 neurons (fully-connected, usual matrix multiplication)
W_fc1 = weight_variable([14 * 14 * 32, neurons_count])
b_fc1 = bias_variable([neurons_count])

h_pool1_flat = tf.reshape(h_pool1, [-1, 14 * 14 * 32])  # 1x3136
h_fc1 = tf.nn.relu(tf.matmul(h_pool1_flat, W_fc1) + b_fc1)  # 1x1024

# Readout layer
# 1024 learned features and 10 output digits
W_fc2 = weight_variable([neurons_count, 10])
b_fc2 = bias_variable([10])

# TODO: experiment with W_fc1
y_conv = tf.matmul(h_fc1, W_fc2) + b_fc2  # 1x10

# Define loss and optimizer
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_conv, y_))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# Start session
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.global_variables_initializer())
train_accuracy = []
for i in range(1000):
    batch = mnist.train.next_batch(50)
    train_accuracy.append(accuracy.eval(feed_dict={x: batch[0], y_: batch[1]}))
    print("step %d, training accuracy %g" % (i, train_accuracy[-1]))
    train_step.run(feed_dict={x: batch[0], y_: batch[1]})

def fit_f(x, a, b, c, d):
    return a*x**0.5 + b*x**0.25 + c*x**0.125 + d*x**0.0625

fit_args, _ = curve_fit(fit_f, list(range(len(train_accuracy))), train_accuracy)
train_accuracy_smoothed = [fit_f(x, *fit_args) for x in range(len(train_accuracy))]
plot(Data([
    Scatter(y=train_accuracy, name='Train accuracy'),
    Scatter(y=train_accuracy_smoothed, line=dict(shape='spline'), name='Train accuracy (smoothed)'),
]), image='svg')

print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


from collections import defaultdict #나중에 제거
from random import uniform
from math import sqrt
import numpy as np
import matplotlib.pyplot as plt
from copy import deepcopy
from player_1 import Player, Record_Hitter, Record_Pitcher
import csv

#make list of players19
f = open('player_record/hitter19.csv', 'rt', encoding='UTF8')
lines = csv.reader(f)
record19 = [line for line in lines]
f.close()

player_list = [Player(record[1], record[2], 'Hitter') for record in record19[1:]]
player_names = [record[1] for record in record19[1:]]

for player in player_list:
    for record in record19:
        if player.name == record[1]:
            player.update(Record_Hitter(record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[8], record[9], record[10], record[11], record[12], record[13], 2019))

X =[[player.record[i].AVG] for i in range(len(player.record)) for player in player_list]

#k-means clustering
def point_avg(points):
    """
    Accepts a list of points, each with the same number of dimensions.
    NB. points can have more dimensions than 2

    Returns a new point which is the center of all the points.
    """
    if len(points)==1:
        new_center= np.mean(points)
    else:
        new_center= [np.mean([x[y] for x in points]) for y in range(len(points[0]))]
    return new_center

def update_centers(data_set, assignments):
    """
    Accepts a dataset and a list of assignments; the indexes
    of both lists correspond to each other.
    Compute the center for each of the assigned groups.
    Return `k` centers where `k` is the number of unique assignments.
    """
    new_means = defaultdict(list)
    for assignment, point in zip(assignments, data_set):
        new_means[assignment].append(point)
    centers = [point_avg(points) for points in new_means.values()]
    return centers

def assign_points(data_points, centers):
    """
    Given a data set and a list of points betweeen other points,
    assign each point to an index that corresponds to the index
    of the center point on it's proximity to that point.
    Return an array of indexes of centers that correspond to
    an index in the data set; that is, if there are N points
    in `data_set` the list we return will have N elements. Also
    If there are Y points in `centers` there will be Y unique
    possible values within the returned list.
    """
    assignments = []
    for point in data_points:
        shortest = 10000  # positive infinity
        shortest_index = 0
        for i in range(len(centers)):
            val = distance(point, centers[i])
            if val < shortest:
                shortest = val
                shortest_index = i
        assignments.append(shortest_index)
    return assignments

def distance(a, b):
    difference_sq= [(a[x]-b[x])**2 for x in range(len(a))]
    _sum=sum(difference_sq)
    return sqrt(_sum)

def generate_k(data_set, k):
    """
    Given `data_set`, which is an array of arrays,
    find the minimum and maximum for each coordinate, a range.
    Generate `k` random points between the ranges.
    Return an array of the random points within the ranges.
    """
    centers = []
    dimensions = len(data_set[0])
    min_max = defaultdict(int)

    for point in data_set:
        for i in range(dimensions):
            val = point[i]
            min_key = 'min_{0}d'.format(i)
            max_key = 'max_{0}d'.format(i)
            if min_key not in min_max or val < min_max[min_key]:
                min_max[min_key] = val
            if max_key not in min_max or val > min_max[max_key]:
                min_max[max_key] = val

    for _k in range(k):
        rand_point = []
        for i in range(dimensions):
            min_val = min_max['min_{0}d'.format(i)]
            max_val = min_max['max_{0}d'.format(i)]

            rand_point.append(uniform(min_val, max_val))
        centers.append(rand_point)
    return centers

def k_means(dataset, k):
    k_points = generate_k(dataset, k)
    assignments = assign_points(dataset, k_points)
    old_assignments = None
    while assignments != old_assignments:
        new_centers = update_centers(dataset, assignments)
        old_assignments = assignments
        assignments = assign_points(dataset, new_centers)
    return zip(assignments, dataset)

Player_kmeans = k_means(X, 3)
Player_kmeans = list(Player_kmeans)
k_values=[i[0] for i in Player_kmeans]
player_values=[i[1] for i in Player_kmeans]

fig=plt.figure(figsize=(5,5))
axis = fig.add_subplot(111)
axis.set_title('k-means clustering with AVG of KBO players in 2019')
axis.grid(True)

plt.scatter(k_values, player_values, c = k_values, edgecolor = 'none', s=100)
plt.show()


import mmcv
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint

from mmcompression.datasets.pipelines import Compose
from mmcompression.models import build_compressor

def init_compressor(config, checkpoint=None, device="cuda:0"):
    """Initialize a compressor from config file.

    Args:
        config (str or :obj:`mmcv.Config`): Config file path or the config
            object.
        checkpoint (str, optional): Checkpoint path. If left as None, the model
            will not load any weights.
        device (str, optional) CPU/CUDA device option. Default 'cuda:0'.
            Use 'cpu' for loading model on CPU.
    Returns:
        nn.Module: The constructed compressor.
    """
    if isinstance(config, str):
        config = mmcv.Config.fromfile(config)
    elif not isinstance(config, mmcv.Config):
        raise TypeError(
            f"config must be a filename or Config object,but got {type(config)}"
        )
    if checkpoint is not None:
        config.model.pretrained = None
    config.model.train_cfg = None
    model = build_compressor(config.model, test_cfg=config.get("test_cfg"))
    if checkpoint is not None:
        checkpoint = load_checkpoint(model, checkpoint, map_location="cpu")
    model.cfg = config  # save the config in the model for convenience
    model.to(device)
    model.eval()
    return model

class LoadImage:
    """A simple pipeline to load image."""

    def __call__(self, results):
        """Call function to load images into results.

        Args:
            results (dict): A result dict contains the file name
                of the image to be read.

        Returns:
            dict: ``results`` will be returned containing loaded image.
        """

        if isinstance(results["img"], str):
            results["filename"] = results["img"]
            results["ori_filename"] = results["img"]
        else:
            results["filename"] = None
            results["ori_filename"] = None
        img = mmcv.imread(results["img"])
        results["img"] = img
        results["img_shape"] = img.shape
        results["ori_shape"] = img.shape
        return results

def inference_compressor(model, img, return_image=False):
    """Inference image(s) with the compressor.

    Args:
        model (nn.Module): The loaded compressor.
        img (str/ndarray or list[str/ndarray]): Either image files or loaded
            images.
        return_image (bool): Whether return the image after inference.
    """
    cfg = model.cfg
    device = next(model.parameters()).device  # model device
    # build the data pipeline
    test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:]
    # test_pipeline = cfg.data.test.pipeline
    test_pipeline = Compose(test_pipeline)
    # prepare data
    data = dict(img=img)
    data = test_pipeline(data)
    data = collate([data], samples_per_gpu=1)
    if next(model.parameters()).is_cuda:
        # scatter to specified GPU
        data = scatter(data, [device])[0]
    else:
        data["img_metas"] = [i[0] for i in data["img_metas"].data]
    # forward the model
    with torch.no_grad():
        result = model(return_loss=False, return_image=return_image, **data)
    return result


import getopt
import subprocess
import sys

def who(options):
    cmd = 'who '
    if options:
        cmd += options
    proc = subprocess.Popen(
        cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout_value = proc.communicate('through stdin to stdout')[0]
    sys.exit(stdout_value[:-1])

if __name__ == '__main__':
    options, remainder = getopt.getopt(
        sys.argv[1:], 'bdlprTtuw',
        ['boot', 'dead', 'login', 'process',
         'runlevel', 'mesg', 'time', 'users'])
    who_options = ''
    for opt, arg in options:
        who_options += '{0} '.format(opt)

    who(who_options)


import socket

import pyautogui

# Set up a server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 12345))
server_socket.listen(1)

print("Server listening...")

# Accept incoming connections
client_socket, client_address = server_socket.accept()
print(f"Connection from {client_address}")

while True:
    command = client_socket.recv(1024).decode()
    if not command:
        break
    if command == "move_cursor":
        # Receive coordinates (x, y)
        x, y = map(int, client_socket.recv(1024).decode().split(","))
        # Move the cursor
        pyautogui.moveTo(x, y)

client_socket.close()
server_socket.close()


import argparse
import os
import pickle as pkl
import numpy as np
import json

from IPython import embed
import matplotlib.pyplot as plt

from sklearn.neighbors import KernelDensity
def kde_sklearn(x, x_grid, bandwidth=0.2, **kwargs):
    """Kernel Density Estimation with Scikit-learn"""
    kde_skl = KernelDensity(bandwidth=bandwidth, **kwargs)
    kde_skl.fit(x[:, np.newaxis])
    # score_samples() returns the log-likelihood of the samples
    log_pdf = kde_skl.score_samples(x_grid[:, np.newaxis])
    return np.exp(log_pdf)

def create_histograms(counts):
    print('\nNote, the epochs are not parametrized in the function: create_histograms\n')
    for exp, value in counts.items():
        max_num_counts = int(np.array(counts[exp]['counts']).max())
        if max_num_counts < 500:
            max_num_counts = 500
        x_grid = np.linspace(0, max_num_counts, max_num_counts) # you can choose the amplitude changing 500
        plt.figure()
        info_exp = counts[exp]['name_exp']
        plt.title(info_exp['dataset'] + ' ' + info_exp['arch'] + ' BS' + str(info_exp['b']) + ' ' + info_exp['sampler'] + ' norm ' + str(info_exp['normalizer']) + ' Temp' + str(info_exp['temperature']) )
        for c in value['counts']:
            pdf = kde_sklearn(c, x_grid, bandwidth=2)  #Note, the bandwidth can be changed here
            plt.plot(x_grid, pdf, label=f"Mean: {np.mean(np.array(c)):.2f} std: {np.std(np.array(c)):.2f}, epoch: {(sum(c)/50000) :.1f}", linewidth=2)
            plt.grid()
        plt.xlabel('Counts')
        plt.ylabel('Number of data points')
        plt.legend()
        plt.tight_layout()
        plt.savefig(os.path.join(value['save_path'], 'kde.pdf'), dpi=2560, bbox_inches='tight')
        plt.close()

        plt.figure()
        plt.title(info_exp['dataset'] + ' ' + info_exp['arch'] + ' BS' + str(info_exp['b']) + ' ' + info_exp['sampler'] + ' norm ' + str(info_exp['normalizer']) + ' Temp' + str(info_exp['temperature']) )
        for c in value['counts']:
            plt.hist(c, bins=x_grid, alpha=0.5, label=f"Mean: {np.mean(np.array(c)):.2f} std: {np.std(np.array(c)):.2f}, epoch: {(sum(c)/50000) :.1f}", linewidth=2)
            plt.grid()
        plt.xlabel('Counts')
        plt.ylabel('Number of data points')
        plt.legend()
        plt.tight_layout()
        plt.savefig(os.path.join(value['save_path'], 'histogram.pdf'), dpi=2560, bbox_inches='tight')
        plt.close()

            # plt.figure()
            # plt.hist(c, bins=200)
            # plt.savefig(os.path.join(value['save_path'], 'histogram.pdf', dpi=2560, bbox_inches='tight'))

def get_params_from_log(f):
    blacklist = ['lrs', 'B', 'd', 's', 'ids', 'd', \
                'save', 'metric', 'nc', 'g', 'j', 'env', 'burnin', \
                'alpha', 'delta', 'beta', 'lambdas', 'append', \
                'ratio', 'bfrac', 'l2', 'v', 'frac', 'rhos']
    r = {}
    for l in open(f,'r', encoding='latin1'):
        if '[OPT]' in l[:5]:
            r = json.loads(l[5:-1])
            fn = r['filename']
            for k in blacklist:
                r.pop(k, None)
            #r = {k: v for k,v in r.items() if k in whitelist}
            r['t'] = fn[fn.find('(')+1:fn.find(')')]
            return r
    assert len(r.keys) > 0, 'Could not find [OPT] marker in '+f

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='count_visualization',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--sd', default=f'..{os.sep}results') #Note this is not used now since we are saving on the exp run folder
    parser.add_argument('--exp', default=f'..{os.sep}results', required=True)
    parser.add_argument('--epochs', default=[59,119,159,179])
    opt = vars(parser.parse_args())

    epochs = [str(ep) for ep in opt['epochs']]

    exp_path = os.path.join(f'..{os.sep}results{os.sep}', opt['exp'])

    # Parsing the experiment folder creating a dict of runs
    exp_runs = {}
    for exp in os.listdir(exp_path):
        if not exp == 'analysis_experiments':
            exp_runs[exp] = exp

    # embed()

    # Creating a dictionary (keys are exp_runs) of dictionaries containing the
    # actual counts (filtered by epochs) and the saving path
    counts = {}
    for exp, run in exp_runs.items():
        path = os.path.join(exp_path, exp)
        counts[exp] = {'counts': []}
        counts[exp]['name_exp'] = get_params_from_log(os.path.join(path, 'logs', 'flogger.log')) #To load the logger
        counts[exp]['save_path'] = os.path.join(path, 'analysis')
        for file in os.listdir(os.path.join(path, 'sample_counts')):
            if file.split('_')[-1].split('.')[0] in epochs:
                with open(os.path.join(path, 'sample_counts', file), 'rb') as f:
                    counts[exp]['counts'].append(pkl.load(f))
        if not os.path.isdir(counts[exp]['save_path']):
            os.makedirs(counts[exp]['save_path'], exist_ok=True)

    create_histograms(counts)


from django.shortcuts import render
from players.models import playerdata
# Create your views here.
from django.http import JsonResponse
import json
from .models import updates,matches,leagues,allaccouncements,StateAssociations,BoardManageMent,SelectionCommittee,AthletesCommission
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def getPlayers(request):
	if request.method == "GET":
		information = playerdata.objects.all()
		f=["playerid","team","firstname","lastname","fathername","address","phonenumber","Email","gender","age","city","state","photo","adhar","birth","Height","Goals","Wins","Nationality","JersyNo","Weight","GamesNo","Losses"]
		jsoninformation = serializers.serialize('python', information)
		actual_data = [d['fields'] for d in jsoninformation]
		# jsoninformation.insert(0,{"result":len(jsoninformation),"msg":"DataFound"})
		# print(type(actual_data))
		# actual_data["msg"] = "Data Found"
		information = {"msg" :"DataFound","status_code":200,"result":len(jsoninformation),"data":actual_data}
		output = json.dumps(information)

		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# serialized_queryset = serializers.serialize('json', some_queryse
@csrf_exempt
def getPlayer(request,play):
	if request.method == "GET":
		player = [playerdata.objects.get(playerid =play )]

		jsoninformation = serializers.serialize('json', player)
		obj = json.loads(json.loads(json.dumps(jsoninformation)))
		output = json.dumps(obj)
		return HttpResponse(output, content_type='application/json')
	if request.method == "DELETE":
		try:
			player = playerdata.objects.get(playerid =play )
			player.delete()
		except:
			return JsonResponse({"status":"player Not Found"})
		return JsonResponse({"status":"success"})

	if request.method == "POST":
		# print(request['body'])
		# print(request.body)
		jsom = json.loads(request.body)
		print(jsom.data)
		return JsonResponse({"om":"om"})

@csrf_exempt
def latestUpdates(request):
	if request.method=="GET":
		up = updates.objects.all()
		# jsoninformation = serializers.serialize('json', up)
		jsoninformation = serializers.serialize('python', up)
		actual_data = [d['fields'] for d in jsoninformation]
		actual_data.insert(0,{"result":len(actual_data)})## = f"{len(actual_data)}"

		actual_data.insert(0,{"msg":"data found"})
		# actual_data["result"] = f"{len(actual_data)}"

		# actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})

@csrf_exempt
def StateViseAssociations(request,state):
	if request.method=="GET":
		assosiations = StateAssociations.objects.all().filter(state=state)
		jsoninformation = serializers.serialize('python', assosiations)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})

@csrf_exempt
def StateAssociationsAll(request):
	if request.method=="GET":
		assosiations = StateAssociations.objects.all()
		jsoninformation = serializers.serialize('python', assosiations)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})

@csrf_exempt
def getAllBoardMembers(request):
	if request.method=="GET":
		board = BoardManageMent.objects.all()
		jsoninformation = serializers.serialize('python', board)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})

def getAllSelectionCommittee(request):
	if request.method=="GET":
		board = SelectionCommittee.objects.all()
		jsoninformation = serializers.serialize('python', board)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})

def getAthletesCommission(request):
	if request.method=="GET":
		board = AthletesCommission.objects.all()
		jsoninformation = serializers.serialize('python', board)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})

def upmatches(request):
	if request.method=="GET":
		m = matches.objects.all()
		jsoninformation = serializers.serialize('python', m)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})
def accouncements(request):
	if request.method=="GET":
		m = allaccouncements.objects.all()
		jsoninformation = serializers.serialize('python', allaccouncements)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})

def upcomeingLeagues(request):
	if request.method=="GET":
		m = leagues.objects.all()
		jsoninformation = serializers.serialize('python', m)
		actual_data = [d['fields'] for d in jsoninformation]
		output = json.dumps(actual_data)
		# return JsonResponse({"players":output})
		return HttpResponse(output, content_type='application/json')
		# return JsonResponse({"data":jsoninformation})


def BiggerGreater(word):
    output = ''
    if word == max(word)*len(word):
        return ''

    for i in range(len(word)-1, 1, -1):
        if word[i] > word[i-1]:
            output = word[:i-1] + word[i] + word[i-1]
            return output

    the_letter = max(word)
    for curr_letter in word:
        if curr_letter > word[0] and curr_letter < the_letter:
            the_letter = curr_letter

    temp_word = sorted(word)
    temp_word.remove(the_letter)
    output = the_letter + ''.join(temp_word)

    if output <= word:
        return ''
    else:
        return output


import argparse, os, numpy as np, pandas as pd, matplotlib.pyplot as plt, matplotlib.cm as colormap, torch, json

from itertools import count
from tensorboardX import SummaryWriter
from scipy.stats import entropy
from pathlib import Path

from pettingzoo.mpe import simple_spread_v2
from pettingzoo.mpe import simple_reference_v2

from hammer import PPO
from sum_guessing_game import GuessingSumEnv
from utils import read_config

def plot(obs, actions, messages, discrete_mes=False, nagents=2):
    columns = ["index"]
    for i in range(nagents):

        columns.append("obs"+str(i+1))
        columns.append("action"+str(i+1))
        columns.append("message"+str(i+1))

    df = pd.DataFrame(columns=columns)
    for k in range(len(obs)):
        point=[0]
        for i in range(nagents):
            point.append(list(obs[k].values())[i][0])
            point.append(list(actions[k].values())[i][0])
            point.append(messages[k][i][0])
        df = df.append(pd.DataFrame([point], columns=columns))

    print(df)
    if discrete_mes:
        for x in range(nagents):
            m = "message"+str(x+1)
            df.loc[df[m] < 0.5, m] = 0
            df.loc[df[m] >= 0.5, m] = 1

    df["obs_sum"] = df["obs1"] + df["obs2"] + df["obs3"]
    df["obs12_sum"] = df["obs1"] + df["obs2"]
    df["obs13_sum"] = df["obs1"] + df["obs3"]
    df["obs32_sum"] = df["obs3"] + df["obs2"]

    # df["action1_err"] = abs(df["action1"] - df["obs_sum"])
    # df["action2_err"] = abs(df["action2"] - df["obs_sum"])
    # df["action3_err"] = abs(df["action3"] - df["obs_sum"])

    savedir = "plots/sumguessing/3agents_discrete_initial"
    if not os.path.exists(savedir): os.makedirs(savedir)

    plots = [
        {
            "x": "obs1",
            "y": "obs2",
            "c": "message1"
        },

        {
            "x": "obs1",
            "y": "obs32_sum",
            "c": "message1"
        },

        {
            "x": "obs1",
            "y": "obs_sum",
            "c": "message1"
        },

    ]

    for p in plots:
        name = "--".join([p["x"],p["y"],p["c"]])
        df.plot.scatter(x=p["x"], y=p["y"], c=p["c"], colormap="viridis")
        plt.savefig(os.path.join(savedir, name+".png"))
        # plt.show()

    # # Mean and Standard Deviation
    # print(df["action1_err"].mean(), df["action1_err"].std()) # 0.7698002555758323, 0.5571670516844823 in 10000 eps
    # print(df["action2_err"].mean(), df["action2_err"].std()) # 0.7838607136086739, 0.5664230119884279 in 10000 eps

def run(args):

    SCALE = 10.0
    env = GuessingSumEnv(num_agents=args.nagents, scale=SCALE, discrete=0)

    env.reset()
    agents = env.agents

    obs_dim = 1

    action_dim = 1

    config = read_config(args.config)
    if not config:
        print("config required")
        return

    random_seed = args.randomseed
    if random_seed:
        print("Random Seed: {}".format(random_seed))
        env.seed(random_seed)
        torch.manual_seed(random_seed)
        np.random.seed(random_seed)

    betas = (0.9, 0.999)

    HAMMER = PPO(
        agents=agents,
        single_state_dim=obs_dim,
        single_action_dim=action_dim,
        meslen = args.meslen,
        n_agents=len(agents), # required for discrete messages
        lr=config["lr"],
        betas=betas,
        gamma = config["gamma"],
        K_epochs=config["K_epochs"],
        eps_clip=config["eps_clip"],
        actor_layer=config["actor_layer"],
        critic_layer=config["critic_layer"],
        dru_toggle=args.dru_toggle,
        is_discrete=config["is_discrete"],
        sharedparams=0
    )
    HAMMER.load(args.load)
    HAMMER.policy_old.action_var[0] = 1e-10 # For evaluation, reducing the variance in action (exploration) to close to zero
    log_dir = Path('test/eval')
    for i in count(0):
        temp = log_dir/('run{}'.format(i))
        if temp.exists():
            pass
        else:
            writer = SummaryWriter(logdir=temp)
            log_dir = temp
            break

    if args.dru_toggle:
        print("Using DRU")
    else:
        print("Not Using DRU")

    # logging variables
    ep_reward = 0
    global_timestep = 0

    env.reset()

    obs_set = []
    action_set = []
    message_set = []
    diff_set = []
    ep_rew = []
    obs = env.reset()

    i_episode = -1
    episode_rewards = 0
    for timestep in count(1):

        action_array = []

        actions, messages = HAMMER.policy_old.act(obs, HAMMER.memory, HAMMER.global_memory)
        obs_set.append(obs)
        action_set.append(actions)
        message_set.append(messages)
        next_obs, rewards, is_terminals, infos = env.step(actions)

        HAMMER.memory_record(rewards, is_terminals)
        episode_rewards += np.mean(list(rewards.values()))
        ep_rew.append(episode_rewards)

        obs = next_obs

        # If episode had ended
        if all([is_terminals[agent] for agent in agents]):
            i_episode += 1
            writer.add_scalar('Avg reward for each agent, after an episode', episode_rewards, i_episode)
            obs = env.reset()
            print('Episode {} \t  Avg reward for each agent, after an episode: {}'.format(i_episode, episode_rewards))
            episode_rewards = 0

        if i_episode == args.maxepisodes:
            break

    # print(np.mean(ep_rew))

    plot(obs=obs_set, actions=action_set, messages=message_set, discrete_mes=args.dru_toggle, nagents=args.nagents)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", type=str, default='configs/sumguessing.yaml', help="config file name")
    parser.add_argument("--load", type=str, default="save/guesser--nagents3--dru0--meslen1--rs--99/model_checkpoints/checkpoint_ep_10000")

    parser.add_argument("--nagents", type=int, default=3)
    parser.add_argument("--maxepisodes", type=int, default=10000)
    parser.add_argument("--dru_toggle", type=int, default=0)
    parser.add_argument("--meslen", type=int, default=1, help="message length")
    parser.add_argument("--randomseed", type=int, default=10)

    args = parser.parse_args()
    run(args=args)


#-*- encoding: UTF-8 -*-
import sys
from douban.books_api import BooksAPI
from douban.movies_api import MoviesAPI
from clint.arguments import Args
from clint.textui import puts, colored, indent
SPACE = ' '

class DouBanCLI(object):

    @property
    def valid_actions(self):
        return ['book', 'movie']

    # flags are not used yet
    def route(self, action, name, flags):
        if not action in self.valid_actions:
            puts(colored.red('%s is not a valid action' %action))
            exit()

        getattr(self, action)(name)

    def book(self, book_name):
        api = BooksAPI()
        res = api.search_book({'q': book_name, 'count': 1})
        book = self._get_first_matched_id_from(res, 'book')
        self._print_book_info(book)

    def movie(self, movie_name):
        api = MoviesAPI()
        res = api.search_movie({'q': movie_name, 'count': 1})
        movie = self._get_first_matched_id_from(res, 'movie')
        self._print_movie_info(movie)

    def _get_first_matched_id_from(self, res, obj_type='book'):
        count = int(res['total'])
        if count == 0:
            print(u'找不到结果')
            exit()
        else:
            print(u'共%s个结果，返回第1个结果' %res['total'])
            mapper = {'book': 'books', 'movie': 'subjects'}
            key = mapper[obj_type]
            if len(res[key]) >= 1:
                return res[key][0]

    def _print_book_info(self, book):
        if book != None:
            # print(book)
            print(u'')
            print(u'书名: %s' % colored.green(book['title']))
            print(u'')
            print(u'作者: %s' % colored.green(SPACE.join(book['author'])))
            print(u'作者简介: %s' % colored.green(book['author_intro']))
            print(u'')
            print(u'页数: %s' % book['pages'])
            print(u'出版日期: %s' % book['pubdate'])
            print(u'定价: %s' % book['price'])
            self._print_rating(book['rating'])
            self._print_tags(book['tags'])
            if sys.platform == 'win32':
                print(u'简介')
                print(colored.yellow(book['summary'].encode('GBK', 'ignore')))
            else:
                print('简介: %s' %colored.yellow(book['summary']))
            print('')
            # print(u'目录: %s' % book['catalog'])
        else:
            print(u'无法找到相关结果')

    def _print_rating(self, rating, obj_type='book'):
        if obj_type == 'book':
            print(u'共有%s人次评分, 平均分: %s'%(colored.yellow(rating['numRaters']), colored.yellow(rating['average'])))
        else:
            print(u'共有%s人收藏, 平均分: %s'%(colored.yellow(rating['stars']), colored.yellow(rating['average'])))

    def _print_tags(self, tags):
        tag_names = [tag['name'] for tag in tags]
        print(u'标签: %s' % u', '.join(tag_names))

    def _print_movie_info(self, movie):
        if movie != None:
            print(u'名称: %s' % colored.yellow(movie['title']))
            self._print_rating(movie['rating'], 'movie')
            print(u'年份: %s' % movie['year'])
            print(u'类型: %s' % movie['subtype'])
            print(u'导演: %s' % self._get_name(movie['directors']))
            print(u'主演: %s' % self._get_name(movie['casts']))
            print(u'分类: %s' % ' '.join(movie['genres']))
        else:
            print(u'无法找到相关结果')

    def _get_name(self, directors_or_actors):
        return u', '.join([someone['name'] for someone in directors_or_actors])

def fetch_names(grouped_args):
    return SPACE.join(grouped_args[1:])

def main():

    cli = DouBanCLI()

    args = Args()

    # grouped['_'] does not contain flags
    grouped_args = args.grouped['_'].all

    if len(grouped_args) <= 1:
        print(colored.yellow('USAGE: douban book book_name'))
        print(colored.yellow('USAGE: douban movie movie_name'))
    else:
        action = grouped_args[0]
        name = fetch_names(grouped_args)
        show_detail = True if '-d' in args.flags.all else False
        cli.route(action, name, {'show_detail': show_detail})

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
"""Modul für einfache Modbus-Operationen.

Das Modul baut eine Modbus-TCP-Verbindung auf. Es gibt verschiedene Funktionen, um die gelesenen Register zu
formatieren.
"""
import logging
import struct
from enum import Enum
from typing import Callable, Iterable, Union, overload, List

import pymodbus
from pymodbus.client.sync import ModbusTcpClient, ModbusSerialClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from urllib3.util import parse_url

from modules.common.fault_state import FaultState

log = logging.getLogger(__name__)

class ModbusDataType(Enum):
    UINT_8 = 8, "decode_8bit_uint"
    UINT_16 = 16, "decode_16bit_uint"
    UINT_32 = 32, "decode_32bit_uint"
    UINT_64 = 64, "decode_64bit_uint"
    INT_8 = 8, "decode_8bit_int"
    INT_16 = 16, "decode_16bit_int"
    INT_32 = 32, "decode_32bit_int"
    INT_64 = 64, "decode_64bit_int"
    FLOAT_16 = 16, "decode_16bit_float"
    FLOAT_32 = 32, "decode_32bit_float"
    FLOAT_64 = 64, "decode_64bit_float"

    def __init__(self, bits: int, decoding_method: str):
        self.bits = bits
        self.decoding_method = decoding_method

_MODBUS_HOLDING_REGISTER_SIZE = 16
Number = Union[int, float]

class ModbusClient:
    def __init__(self, delegate: Union[ModbusSerialClient, ModbusTcpClient], address: str, port: int = 502):
        self.delegate = delegate
        self.address = address
        self.port = port

    def __enter__(self):
        self.delegate.__enter__()
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.delegate.__exit__(exc_type, exc_value, exc_traceback)

    def close_connection(self) -> None:
        try:
            log.debug("Close Modbus TCP connection")
            self.delegate.close()
        except Exception as e:
            raise FaultState.error(__name__+" "+str(type(e))+" " +
                                   str(e)) from e

    def __read_registers(self, read_register_method: Callable,
                         address: int,
                         types: Union[Iterable[ModbusDataType], ModbusDataType],
                         byteorder: Endian = Endian.Big,
                         wordorder: Endian = Endian.Big,
                         **kwargs):
        try:
            multi_request = isinstance(types, Iterable)
            if not multi_request:
                types = [types]

            def divide_rounding_up(numerator: int, denominator: int):
                return -(-numerator // denominator)

            number_of_addresses = sum(divide_rounding_up(
                t.bits, _MODBUS_HOLDING_REGISTER_SIZE) for t in types)
            response = read_register_method(
                address, number_of_addresses, **kwargs)
            if response.isError():
                raise FaultState.error(__name__+" "+str(response))
            decoder = BinaryPayloadDecoder.fromRegisters(response.registers, byteorder, wordorder)
            result = [struct.unpack(">e", struct.pack(">H", decoder.decode_16bit_uint())) if t ==
                      ModbusDataType.FLOAT_16 else getattr(decoder, t.decoding_method)() for t in types]
            return result if multi_request else result[0]
        except pymodbus.exceptions.ConnectionException as e:
            raise FaultState.error(
                "TCP-Client konnte keine Verbindung zu " + str(self.address) + ":" + str(self.port) +
                " aufbauen. Bitte Einstellungen (IP-Adresse, ..) und " + "Hardware-Anschluss prüfen.") from e
        except pymodbus.exceptions.ModbusIOException as e:
            raise FaultState.warning(
                "TCP-Client " + str(self.address) + ":" + str(self.port) +
                " konnte keinen Wert abfragen. Falls vorhanden, parallele Verbindungen, zB. node red," +
                "beenden und bei anhaltender Fehlermeldung Zähler neu starten.") from e
        except Exception as e:
            raise FaultState.error(__name__+" "+str(type(e))+" " +
                                   str(e)) from e

    @overload
    def read_holding_registers(self, address: int, types: Iterable[ModbusDataType], byteorder: Endian = Endian.Big,
                               wordorder: Endian = Endian.Big, **kwargs) -> List[Number]:
        pass

    @overload
    def read_holding_registers(self, address: int, types: ModbusDataType, byteorder: Endian = Endian.Big,
                               wordorder: Endian = Endian.Big, **kwargs) -> Number:
        pass

    def read_holding_registers(self, address: int,
                               types: Union[Iterable[ModbusDataType], ModbusDataType],
                               byteorder: Endian = Endian.Big,
                               wordorder: Endian = Endian.Big,
                               **kwargs):
        return self.__read_registers(
            self.delegate.read_holding_registers, address, types, byteorder, wordorder, **kwargs
        )

    @overload
    def read_input_registers(self, address: int, types: Iterable[ModbusDataType], byteorder: Endian = Endian.Big,
                             wordorder: Endian = Endian.Big,
                             **kwargs) -> List[Number]:
        pass

    @overload
    def read_input_registers(self, address: int, types: ModbusDataType, byteorder: Endian = Endian.Big,
                             wordorder: Endian = Endian.Big, **kwargs) -> Number:
        pass

    def read_input_registers(self, address: int,
                             types: Union[Iterable[ModbusDataType], ModbusDataType],
                             byteorder: Endian = Endian.Big,
                             wordorder: Endian = Endian.Big,
                             **kwargs):
        return self.__read_registers(self.delegate.read_input_registers, address, types, byteorder, wordorder, **kwargs)

class ModbusTcpClient_(ModbusClient):
    def __init__(self, address: str, port: int = 502):
        parsed_url = parse_url(address)
        host = parsed_url.host
        if parsed_url.port is not None:
            port = parsed_url.port
        super().__init__(ModbusTcpClient(host, port), address, port)

class ModbusSerialClient_(ModbusClient):
    def __init__(self, port: int):
        super().__init__(ModbusSerialClient(method="rtu", port=port, baudrate=9600, stopbits=1, bytesize=8, timeout=1),
                         "Serial",
                         port)


from rest_framework import serializers

from spacare.quyen.models import Quyen

class QuyenSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quyen
        fields = "__all__"
        extra_kwargs = {
            "id": {"read_only": True},
            "created_at": {"read_only": True},
            "updated_at": {"read_only": True},
        }


import numpy as np
import pytest

from pandas_profiling.report.formatters import (
    fmt_array,
    fmt_bytesize,
    fmt_class,
    fmt_color,
    fmt_numeric,
)

@pytest.mark.parametrize(
    "text, color, expected",
    [("This is a warning", "red", 'This is a warning')],
)
def test_fmt_color(text, color, expected):
    assert fmt_color(text, color) == expected

@pytest.mark.parametrize(
    "text, cls, expected",
    [
        (
            "This text is muted",
            "text-muted",
            'This text is muted',
        )
    ],
)
def test_fmt_class(text, cls, expected):
    assert fmt_class(text, cls) == expected

@pytest.mark.parametrize(
    "num, fmt, expected",
    [
        (0, None, "0.0 B"),
        (100, "Bytes", "100.0 Bytes"),
        (1024, None, "1.0 KiB"),
        (1024.0, None, "1.0 KiB"),
        (1024 ** 4, "Bytes", "1.0 TiBytes"),
        (1024 ** 3 * 7.5, None, "7.5 GiB"),
        (1024 ** 8, None, "1.0 YiB"),
    ],
)
def test_fmt_bytesize(num, fmt, expected):
    if fmt is None:
        assert fmt_bytesize(num) == expected
    else:
        assert fmt_bytesize(num, fmt) == expected

@pytest.mark.parametrize(
    "array, threshold, expected",
    [
        (np.array([1, 2, 3], dtype=np.int16), 3, "[1 2 3]"),
        (
            np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float32),
            1,
            "[ 1. ... 10.]",
        ),
        (
            np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float32),
            3,
            "[ 1.  2.  3. ...  8.  9. 10.]",
        ),
    ],
)
def test_fmt_array(array, threshold, expected):
    assert fmt_array(array, threshold) == expected

@pytest.mark.parametrize(
    "value, precision, expected",
    [
        (79.999531, 3, "80"),
        (79.999531, 10, "79.999531"),
        (81.000000, 10, "81"),
        (81, 10, "81"),
        (81.999861123123123123, 10, "81.99986112"),
    ],
)
def test_fmt_numeric(value, precision, expected):
    assert fmt_numeric(value, precision) == expected


from django.test import Client, TestCase
from django.urls import reverse
from django_dynamic_fixture import G

from animal_crossing_new_horizons.acnh_api.models import Villager, Fossil, Fish, Insect

class APITestVillagers(TestCase):
    def test_villagers_api(self):
        G(Villager, name='tom')
        G(Villager, name='jerry')

        c = Client()

        response = c.get(reverse('villagers-list'))

        self.assertEqual(2, len(response.json()['results']))

    def test_villagers_api_filters(self):
        G(Villager, name='villager1', personality='personality1')
        G(Villager, name='villager2', personality='personality2')

        c = Client()

        filters = {
            'personality': 'personality1'
        }
        response = c.get(reverse('villagers-list'), data=filters)
        results = response.json()['results']

        self.assertEqual(1, len(results))
        self.assertEqual('villager1', results[0]['name'])

class APITestFossils(TestCase):
    def test_fossils_api(self):
        G(Fossil, name='fossil1')
        G(Fossil, name='fossil2')

        c = Client()

        response = c.get(reverse('fossils-list'))

        self.assertEqual(2, len(response.json()['results']))

    def test_fossils_api_filters(self):
        G(Fossil, name='fossil1', in_catalog=True)
        G(Fossil, name='fossil2', in_catalog=False)

        c = Client()

        filters = {
            'in_catalog': True
        }
        response = c.get(reverse('fossils-list'), data=filters)
        results = response.json()['results']

        self.assertEqual(1, len(results))
        self.assertEqual('fossil1', results[0]['name'])

class APITestFish(TestCase):
    def test_fish_api(self):
        G(Fish, name='fish1')
        G(Fish, name='fish2')

        c = Client()

        response = c.get(reverse('fish-list'))

        self.assertEqual(2, len(response.json()['results']))

    def test_fish_api_filters(self):
        G(Fish, name='fish1', sell_price=200)
        G(Fish, name='fish2', sell_price=500)

        c = Client()

        filters = {
            'sell_price': '200'
        }
        response = c.get(reverse('fish-list'), data=filters)
        results = response.json()['results']

        self.assertEqual(1, len(results))
        self.assertEqual('fish1', results[0]['name'])

class APITestInsects(TestCase):
    def test_insects_api(self):
        G(Insect, name='insect1')
        G(Insect, name='insects2')

        c = Client()

        response = c.get(reverse('insects-list'))

        self.assertEqual(2, len(response.json()['results']))

    def test_insects_api_filters(self):
        G(Insect, name='insect1', sell_price=200)
        G(Insect, name='insect2', sell_price=500)

        c = Client()

        filters = {
            'sell_price': '200'
        }
        response = c.get(reverse('insects-list'), data=filters)
        results = response.json()['results']

        self.assertEqual(1, len(results))
        self.assertEqual('insect1', results[0]['name'])


import sys
import os.path

def input_to_array(input_filepath):
  values = []
  full_filepath = os.path.dirname(__file__) + '/' + input_filepath

  file_lines = open(full_filepath, 'r').readlines()
  for value in file_lines:
    values.append(value)

  return list(map(parse_array_elements, values))

def parse_array_elements(n):
  parsed = int(n.strip())
  return parsed

def part1(values):

  return

def part2(values):

  return

if __name__ == "__main__":
  input_filepath = 'input.txt'
  values = input_to_array(input_filepath)

  if(len(sys.argv) > 1 and sys.argv[1] == '2'):
    answer = part2(values)
    print('== part 2 ==')
  else:
    answer = part1(values)
    print('== part 1 ==')

  print(answer)


import datetime

import pandas as pd
import numpy as np

import matplotlib
import matplotlib.dates
import matplotlib.pyplot as plt
import matplotlib.ticker

import tempfile

from urllib.error import HTTPError

import constants
import dateinterval

matplotlib.use('agg')
plt.style.use('dark_background')

def download_csv_data(url, **kwargs):
    """Download data from a specified url.
    Args:
        url (str): url to an online .csv file
        **kwargs: arbitrary keyword arguments
    """
    return pd.read_csv(url, **kwargs)

def get_data_url(location, interval):
    """Get the url to the online .csv dataset from Protezione Civile based on the location and the interval of interest.
    Args:
        location (Location): location
        interval (DateInterval): date interval
    Return:
        str: url to the requested .csv document
    """
    url = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/"
    if location.level == 'stato':
        url += "dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale"
    elif location.level == 'regione':
        url += "dati-regioni/dpc-covid19-ita-regioni"
    elif location.level == 'provincia':
        url += "dati-province/dpc-covid19-ita-province"
    else:
        raise ValueError("Invalid location")
    if interval.is_single_day():
        url += f"-{interval.start.year:0>4}{interval.start.month:0>2}{interval.start.day:0>2}"
    url += ".csv"
    return url

class InfectionDataset:
    """Dataset containing various stats on the infection status. All data is organized in parallel arrays aligned by
    date, which is mandatory in every dataset.
    Attributes:
        location (Location): location of the data
        interval (DateInterval): date interval
        data (dict(str, numpy.ndarray): a dict mapping a stat name to its values.
    """

    def __init__(self, location, interval, data):
        """
        Initiate dataset
        Args:
            location (Location): location of the data
            interval (DateInterval): date interval
            data (dict): a dict mapping a stat to its values over time.
        """
        self.location = location
        self.interval = interval
        if 'data' not in data:
            raise ValueError("Dataset has no associated dates")
        data_size = len(data['data'])
        if any(len(values) != data_size for values in data.values()):
            raise ValueError("Dataset data sizes are inconsistent")
        self.data = data

    @property
    def dates(self):
        """Show the dates array"""
        return self.data['data']

    @property
    def stats(self):
        """Return a list containing the available stats"""
        stats = set(self.data.keys()) - {'data'}
        return stats

    @classmethod
    def download(cls, location, interval, **kwargs):
        dataframe = download_csv_data(
            get_data_url(location, interval),
            converters={
                'data': datetime.datetime.fromisoformat
            },
            **kwargs
        )
        # Filter dataframe by date and location
        dataframe = dataframe[[date in interval for date in dataframe['data']]]
        if location.level == 'regione':
            dataframe = dataframe[dataframe['denominazione_regione'] == str(location)]
        elif location.level == 'provincia':
            dataframe = dataframe[dataframe['denominazione_provincia'] == str(location)]
        available_stats = set(dataframe.keys()) & set(constants.stats.keys())
        data = {'data': np.array(dataframe['data'])}
        for stat in available_stats:
            data[stat] = np.array(dataframe[stat])
        return cls(location, interval, data)

    def get_data(self, stat, interval):
        indices = np.where(date in interval for date in self.dates)
        return self[stat][indices]

    def __len__(self):
        return len(self.dates)

    def __getitem__(self, item):
        return self.data[item]

    def __setitem__(self, key, value):
        if len(value) != len(self):
            raise ValueError("Length of provided data does not match with dataset size.")
        self.data[key] = value

def readable_number(num, thousands_sep="'"):
    """Convert number to string and format it in a human readable way
    Args:
        num (int, float): number
        thousands_sep (str): separator for the thousands
    Return:
        str: formatted number
    """
    return f"{num:,}".replace(',', thousands_sep)

def get_report(location, date):
    """Get a full report based on location and date.
    Args:
        location (Location): requested location
        date (datetime.datetime): requested date
    Return:
        str: full report with all available
    """
    dummy_interval = dateinterval.DateInterval(date, date)
    try:
        dataset = InfectionDataset.download(location, dummy_interval)
    except HTTPError:
        return f"Non ci sono dati per '{location}' in data {date.strftime('%d/%m/%Y')}. Prova con un'altra data, " \
               f"un altro luogo. Consulta il comando /help per ulteriori informazioni."
    report = f"*{location}* - {date.strftime('%d/%m/%Y')}:\n"
    for stat in sorted(dataset.stats):
        stat_name = stat.replace('_', ' ').capitalize()
        number = readable_number(dataset.get_data(stat, dummy_interval)[0])
        report += f"  _{stat_name}_: {number}\n"
    report += f"\nReport generato da {constants.bot_username}"
    return report

def plot_trend(stat, location, interval):
    dataset = InfectionDataset.download(location, interval)
    dates = dataset.dates
    if stat in dataset.stats:
        values = dataset[stat]
    else:
        raise KeyError(dataset.stats)
    return plot(dates, values, location=location, stat=stat.replace('_', ' '))

def plot(dates, values, **kwargs):
    # Create plot and style
    fig, ax = plt.subplots()
    style = stylize_plot(fig, ax, npoints=len(values), **kwargs)
    ax.plot_date(dates, values, **style)
    ax.fill_between(dates, values, np.min(values), color=style['color'], alpha=0.3)
    # Make temporary file
    temp_file = tempfile.NamedTemporaryFile(mode='w+b', prefix='plot-', suffix='.png', delete=True)
    plt.savefig(temp_file, bbox_inches='tight')
    temp_file.seek(0)
    return temp_file

def stylize_plot(fig, ax, **kwargs):
    """Add style to the plot
    Args:
        fig (matplotlib.pyplot.Figure): figure object
        ax (matplotlib.pyplot.Axes): axes object
        kwargs: arbitrary keyword arguments
    Return
        dict: keyword arguments to be used in plotting function
    """
    stat = kwargs.get('stat', '???')
    column = stat.replace(' ', '_')
    location = kwargs.get('location', '???')
    # Line style
    data_marker = '.' if kwargs.get('npoints', 14) < 14 else ''
    color = constants.stats[column]['style']['color'] if column in constants.stats else 'red'
    style = {'marker': data_marker, 'linestyle': '-', 'color': color}
    # Image style
    ax.grid(which='both', color='lightslategray')
    ax.get_xaxis().set_major_formatter(matplotlib.dates.ConciseDateFormatter(
        matplotlib.dates.AutoDateLocator()
    ))
    ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(
        lambda x, p: readable_number(int(x))
    ))
    # Labels and title
    xlabel = 'Data'
    ylabel = stat.capitalize()
    title = f"{location}: {ylabel}"
    ax.set_xlabel(xlabel, color='slateblue')
    ax.set_ylabel(ylabel, color='slateblue')
    ax.set_title(title, color=color)
    return style


class RBFSampler(BaseEstimator, TransformerMixin):
    """Approximates feature map of an RBF kernel by Monte Carlo approximation
    of its Fourier transform.

    It implements a variant of Random Kitchen Sinks.[1]

    Read more in the :ref:`User Guide <rbf_kernel_approx>`.

    Parameters
    ----------
    gamma : float
        Parameter of RBF kernel: exp(-gamma * x^2)

    n_components : int
        Number of Monte Carlo samples per original feature.
        Equals the dimensionality of the computed feature space.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Notes
    -----
    See "Random Features for Large-Scale Kernel Machines" by A. Rahimi and
    Benjamin Recht.

    [1] "Weighted Sums of Random Kitchen Sinks: Replacing
    minimization with randomization in learning" by A. Rahimi and
    Benjamin Recht.
    (http://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf)
    """

    def __init__(self, gamma=1., n_components=100, random_state=None):
        self.gamma = gamma
        self.n_components = n_components
        self.random_state = random_state

    def fit(self, X, y=None):
        """Fit the model with X.

        Samples random projection according to n_features.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            Training data, where n_samples in the number of samples
            and n_features is the number of features.

        Returns
        -------
        self : object
            Returns the transformer.
        """

        X = check_array(X, accept_sparse='csr')
        random_state = check_random_state(self.random_state)
        n_features = X.shape[1]

        self.random_weights_ = (np.sqrt(2 * self.gamma) * random_state.normal(
            size=(n_features, self.n_components)))

        self.random_offset_ = random_state.uniform(0, 2 * np.pi,
                                                   size=self.n_components)
        return self

    def transform(self, X):
        """Apply the approximate feature map to X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            New data, where n_samples in the number of samples
            and n_features is the number of features.

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
        """
        check_is_fitted(self, 'random_weights_')

        X = check_array(X, accept_sparse='csr')
        projection = safe_sparse_dot(X, self.random_weights_)
        projection += self.random_offset_
        np.cos(projection, projection)
        projection *= np.sqrt(2.) / np.sqrt(self.n_components)
        return projection


"""
We use pre-trained image model to build embeddings with annoy to build approximate nearest neighbours
to perform a prediction
"""

# from tensorflow.keras.applications.vgg16 import VGG16
# from tensorflow.keras.applications.vgg16 import preprocess_input

from tensorflow.keras.applications.mobilenet import MobileNet
from tensorflow.keras.applications.mobilenet import preprocess_input
from tensorflow.keras.preprocessing import image

from tensorflow.keras.preprocessing import image_dataset_from_directory
import numpy as np
import tqdm
from annoy import AnnoyIndex
import glob
import os

model = MobileNet(weights='imagenet', include_top=False)

batch_size = 16
data_cat = image_dataset_from_directory(directory='dogs-vs-cats/train/cat', image_size=(224, 224), batch_size=batch_size, shuffle=False, labels=None)

counter = 1

for idx, x in enumerate(tqdm.tqdm(data_cat)):
    x = preprocess_input(x)
    features = model.predict(x)
    batch_size = features.shape[0]
    features = features.reshape(batch_size, -1)
    np.save(f"dogs-vs-cats-numpy/{counter}", features)
    counter += 1
    if idx > 10:
        break

del data_cat
dog_counter = counter
print(f"dog indices start at {counter}")
data_dog = image_dataset_from_directory(directory='dogs-vs-cats/train/dog', image_size=(224, 224), batch_size=batch_size, shuffle=False, labels=None)

for idx, x in enumerate(tqdm.tqdm(data_dog)):
    x = preprocess_input(x)
    features = model.predict(x)
    batch_size = features.shape[0]
    features = features.reshape(batch_size, -1)
    f = features.shape[1]
    np.save(f"dogs-vs-cats-numpy/{counter}", features)
    counter += 1
    if idx > 10:
        break

del data_dog

# f = 25088
t = AnnoyIndex(f, 'angular')
fname = glob.glob("dogs-vs-cats-numpy/*")
indx = 0
cat_indx = []
dog_indx = []
for f in fname:
    item_index = int(os.path.basename(f).split(".")[0])
    v = np.load(f)
    for i in range(v.shape[0]):
        t.add_item(indx, v[i, :])
        indx += 1
        if item_index > dog_counter:
            dog_indx.append(indx)
        else:
            cat_indx.append(indx)

t.build(50)
t.save('dog-vs-cats.ann')

def get_estimate(indxs, label_0, label_1):
    l0 = 0
    l1 = 0
    for indx in indxs:
        if indx in label_0:
            l0 += 1
        else:
            l1 += 1
    # print(l0, l1)
    return 0 if l0 > l1 else 1

output = t.get_nns_by_vector(v[1, :], 50)
get_estimate(output, cat_indx, dog_indx)

output = t.get_nns_by_vector(t.get_item_vector(dog_indx[10]), 50)
get_estimate(output, cat_indx, dog_indx)

batch_size = 16
data_cat = image_dataset_from_directory(directory='dogs-vs-cats/train/cat', image_size=(224, 224), batch_size=batch_size, shuffle=False, labels=None)

counter = 1

correct = 0
incorrect = 0

for idx, x in enumerate(tqdm.tqdm(data_cat)):
    if idx <= 10:
        continue
    x = preprocess_input(x)
    features = model.predict(x)
    batch_size = features.shape[0]
    features = features.reshape(batch_size, -1)
    for i in range(batch_size):
        output = t.get_nns_by_vector(features[i, :], 50)
        if output == 0:
            correct += 1
        else:
            correct += 1

del data_cat

data_dog = image_dataset_from_directory(directory='dogs-vs-cats/train/dog', image_size=(224, 224), batch_size=batch_size, shuffle=False, labels=None)

for idx, x in enumerate(tqdm.tqdm(data_dog)):
    if idx <= 10:
        continue
    x = preprocess_input(x)
    features = model.predict(x)
    batch_size = features.shape[0]
    features = features.reshape(batch_size, -1)
    for i in range(batch_size):
        output = t.get_nns_by_vector(features[i, :], 50)
        if output == 1:
            correct += 1
        else:
            correct += 1

del data_dog

print(f"correct: {correct}\nincorrect: {incorrect}")


import pandas as pd

def calculate_exercise_one():
    index_names = df[df['Star Rating'] == 1].index

    total, words = 0, 0

    for i in index_names:
        words += df.iloc[i].wordcount
        total += 1

    print("Total words: ", words, "\n", "Total one-star ratings: ", total, "\n", "Average words per rating: ", words/total)

df = pd.read_csv("resources/reviews_sentiment.csv", sep=";")
calculate_exercise_one()


class Binary:
    def __init__(self, array):
        self.arr = array

    def binary(self, low, high, x):
        if high >= low:
            mid = (high+low)//2

            if self.arr[mid] == x:
                return True
            elif self.arr[mid] > x:
                return self.binary(low, mid-1, x)
            else:
                return self.binary(mid+1, high, x)
        else:
            return False

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

obj = Binary(arr)

validity = obj.binary(0, 9, 11)

print(validity)


"""
    Модуль для работы с БД.
    СУБД - SQLite3
"""

import sqlite3 as sq
import aiosqlite
from typing import Tuple, Optional
from loguru import logger
from config import DB_PATH

class YandexDB:
    TABLE = "rus"
    REGION_TITLE = "region_title"
    REGION_CODES = "region_codes"
    TITLE_SETTLE = "title_settle"
    CODES_SETTLE = "codes_settle"
    DIRECTION = "direction"
    TITLE = "title"
    STATION_TYPE = "station_type"
    TRANSPORT_TYPE = "transport_type"
    YANDEX_CODE = "yandex_code"
    name_db = DB_PATH
    base = None

    def __init__(self, name_db: str = "RusCode") -> None:
        """
        Магический метод класса, инициализирует БД.
        Создает БД с расширением db и производится подключение к конкретной БД.
        Создается курсор из соединения с БД

        :param name_db: Передает имя файла БД, по умолчанию "code_rus"
        :type name_db: str
        """
        if name_db.endswith(".db"):
            self.name = name_db
        else:
            self.name = name_db + ".db"

        with sq.connect(self.name) as con:  # производится подключение к БД
            self.__cur = con.cursor()  # Создается курсор из соединения с БД
            self.__base = con  # соединения с БД

    @classmethod
    async def connect_db(cls) -> None:
        cls.base = await aiosqlite.connect(cls.name_db)

    def add_table(self, table: str = "user (?, ?, ?)") -> None:
        """
        Метод класса, создает таблицу БД.

        :param table: Передает имя таблицы
        """
        try:
            query = f"CREATE TABLE IF NOT EXISTS {table}"
            self.__cur.execute(query)
            self.__base.commit()
        except sq.Error as err:
            logger.exception(err)

    def insert_data(self, table: str, data: tuple) -> None:
        """
        Метод класса записывает данные в таблицу БД.

        :param table: Передает имя таблицы, в которую производится запись.
        :param data: Передает данные для записи в таблицу БД.
        :rtype data: Tuple[Any]
        """
        if len(data) > 1:
            symbol = ", ".join("?" * len(data))
            query = f"INSERT INTO {table} VALUES ({symbol})"

        else:
            query = f"INSERT INTO {table} VALUES (?)"

        self.__cur.execute(query, data)
        self.__base.commit()

    def add_column(self, name_tb: str, name_column) -> None:
        """
        Метод класса добавляет поле в таблицу БД.

        :param name_tb: Передает имя таблицы, в которой производится запись.
        :param name_column: Передает имя поля, которое будет добавлено в таблицу БД.
        """
        query = f"ALTER TABLE {name_tb} ADD COLUMN {name_column}"
        self.__cur.execute(query)
        self.__base.commit()

    def delete_table(self, name_tb) -> None:
        """
        Метод класса удаляет таблицу БД.

        :param name_tb: Передает имя таблицы, которую нужно удалить.
        """
        query = f"DROP TABLE IF EXISTS {name_tb}"
        self.__cur.execute(query)
        self.__base.commit()

    @classmethod
    async def select_region(cls, user_msg: str) -> Optional[Tuple]:
        """
        Метод класса делает запрос к БД, для получения кода региона, поле БД REGION_CODES
        Args:
            user_msg: Передает название региона.

        Returns: row
        Raises:
            aiosqlite.Error: При ошибки запроса к БД.
        """
        try:
            table = cls.TABLE
            value = (f"%{user_msg}%", f"%{user_msg}")
            query = (
                f"SELECT {cls.REGION_CODES}, {cls.REGION_TITLE} FROM {table} "
                f"WHERE {cls.REGION_TITLE} LIKE ? OR {cls.REGION_TITLE} LIKE ?"
            )

            cursor = await cls.base.execute(query, value)
            row = await cursor.fetchone()
            return row

        except aiosqlite.Error as err:
            logger.exception(err)
            return None


# @file kg.py
# @brief startup and AP mode selection
# README: Startup code
# MODULE_ARCH:
# CLASS_ARCH:
# GLOBAL USAGE:
#standard
import getopt
import sys
import unittest

#extend
from configobj import ConfigObj

#library
import lib.globalclasses as gc
from lib.const import *
import codes.app as app
import codes.cli as cli
import codes.ut as ut
import codes.ui as ui

if __name__ =='__main__':
    # Read system parameters which are assigned while we launching "start.py".
    # If the input parameter is invalid, then display usage and return "command
    # line syntax" error code.
    apmode = AP_MODE_NORMAL

    #command line paramters handler
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ht", [])
        for opt, arg in opts:
            if opt == '-h':
                print ('sim.py [ -h ] [ -t ]')
                print ('    -h, --help: help message')
                print ('    -t, --test: unit test mode')
                sys.exit()
            elif opt in ("-t", "--test"):
                apmode = AP_MODE_UNITTEST
                print("Running as unittest mode!")
    except getopt.GetoptError:
        print ('usage: kg.py [ -h ] [ -t ]')
        sys.exit(2)

    #init global classes
    gc.SETTING  = ConfigObj("include/kg.ini")
    gc.UI = ui.UserInterface()
    gc.GAP = app.KApp()

    #run by different mode
    if apmode == AP_MODE_UNITTEST:
        suite = unittest.TestLoader().loadTestsFromTestCase(ut.UTGeneral)
        unittest.TextTestRunner(verbosity = 2).run(suite)
    else:

        cli.Cli().cmdloop()


from dotenv import load_dotenv
from pymongo import MongoClient
import os

load_dotenv()
DATABASE_URL = os.getenv('DATABASE_URL')

DBClient = MongoClient(DATABASE_URL)

# profdict: {
# userID: 1234
# chID: 5678
# points: 1
# }

db = DBClient.test
collection = db.profiles  # the profiles object

# method that takes a dictionary and inserts it into the mongodb profiles dict

def PullAll():
    # all the data inside profiles
    data = collection.find().sort('points', direction=-1)
    return data

def InsertProfile(ProfDict):
    collection.insert_one(ProfDict)

def UpdateProfile(points, mongoID, ProfDict):
    x = collection.find_one(ProfDict)
    newvalues = {
        "$set": {
            'points': points}
    }
    filter = {
        '_id': mongoID
    }
    collection.update_one(
        filter, newvalues)

# returns the profile from the database, 'bruh what' on error

def PullProfile(userID, chID):
    ProfDict = {
        'userID': userID,
        'chID': chID
    }
    x = collection.find_one(ProfDict)
    if x == None:  # there are no matches
        return 'bruh what'
    else:  # the profile exists
        return x


import numpy as np
import random
import itertools
from figure.Figure import Figure
from figure.Figure import COLORS, SHAPES, SIZES

def randombox(imagesize, minrow=0, mincol=0, maxrow=None, maxcol=None, boxsize="medium"):
    """
    Get a random postion for a bounding box
    :return: coords of the bounding box in the form ((r0, r1), (c0, c1))
    """
    if not maxrow:
        maxrow = imagesize[0]
    if not maxcol:
        maxcol = imagesize[1]
    size_bounds = getsizebounds(imagesize)[boxsize]
    width = np.random.randint(size_bounds[0], size_bounds[1])

    r0 = np.random.randint(minrow, maxrow)
    r1 = r0 + width

    c0 = np.random.randint(mincol, maxcol)
    c1 = c0 + width

    return (r0, r1),(c0, c1)

def getsizebounds(imagesize):
    imgwidth = imagesize[0]

    size_bounds = {
        "small": (int(np.floor(imgwidth*0.05)), int(np.floor(imgwidth*0.12))),
        "medium": (int(np.floor(imgwidth*0.13)), int(np.floor(imgwidth*0.18))),
        "large": (int(np.floor(imgwidth*0.19)), int(np.floor(imgwidth*0.25)))
    }

    return size_bounds

def attribute_combinations(exclude_statements=[]):
    """
    Get all allowed attribute combinations for the figures. The allowed combinations can be restricted by the
    exclude_statements property in the configs file.
    :param exclude_statements:
    :return:
    """
    excluded_combs = []
    for exclude_group in exclude_statements:
        # excluded tuples according to the given exclude-statement (COLOR, SIZE, SHAPE)
        # if no valid value is specified for an attribute we count it as wildcard (i.e. add all elements for that attr.)
        excluded_attr = [[exclude_group[0]] if exclude_group[0] in COLORS.keys() else list(COLORS.keys()),
                         [exclude_group[1]] if exclude_group[1] in SIZES else SIZES,
                         [exclude_group[2]] if exclude_group[2] in SHAPES else SHAPES]
        # all excluded combinations
        excluded_combs.extend(list(itertools.product(*excluded_attr)))

    attrs = [list(COLORS.keys()), SIZES, SHAPES]
    included_combs = set(itertools.product(*attrs)) - set(excluded_combs)
    return list(included_combs)

def randomfigure(imagesize, exclude_statements=[]):
    attrs = random.choice(attribute_combinations(exclude_statements))
    shape = attrs[2]
    size = attrs[1]
    pos = randombox(imagesize, boxsize=size)
    color = (attrs[0], COLORS[attrs[0]])
    return Figure(shape=shape, pos=pos, color=color, size=size)


from plugboard.plugboard import PlugBoard
from rotor.rotor import Rotor
from reflector.reflector import Reflector
from typing import List

class Machine(object):
    plugboard = None
    rotors = []
    reflector = None

    def __init__(
        self,
        plugboard: PlugBoard,
        rotors: List[Rotor],
        reflector: Reflector
    ):
        self.plugboard = plugboard
        self.rotors = rotors
        self.reflector = reflector

    def encode(self, letter: str) -> str:
        letter = self.plugboard.parse(letter)

        letter = self.parseForwardThroughRotors(letter)

        letter = self.reflector.parse(letter)

        letter = self.parseBackwardThroughRotors(letter)

        letter = self.plugboard.parse(letter)

        return letter

    def parseForwardThroughRotors(self, letter: str) -> str:
        # The first rotor always rotates
        shouldRotateRotor = True

        for rotor in self.rotors:
            if shouldRotateRotor:
                rotor.rotate()

            shouldRotateRotor = rotor.shouldNextRotate
            letter = rotor.forward(letter)

        return letter

    def parseBackwardThroughRotors(self, letter: str) -> str:
        for rotor in reversed(self.rotors):
            letter = rotor.backward(letter)

        return letter


from channels import Group
from channels.sessions import channel_session
import random
from .models import Player, Group as OtreeGroup, Constants
import json
import time
import django

def ws_connect(message, group_name):
    Group(group_name).add(message.reply_channel)

# again, not an elegant solution, but once a employer has gotten their offer accepted, this number will be set to 0.
# there are a maximum of 5 employers

# Connected to websocket.receive
def ws_message(message, group_name):
    group_id = group_name[5:]
    print('GROUP ID', group_id)
    print('PLAYER::::', message['text'])
    #the above lines have basically no importance
    jsonmessage = json.loads(message.content['text'])
    #this loads the dictionary probably...
    mygroup = OtreeGroup.objects.get(id=group_id)

    if (jsonmessage['role'] == "employer"):
        # handle the data this way
        print('employer')
        curemployer_id = jsonmessage['id_employer']
        curemployer_id_id_in_group = jsonmessage['id_employer_in_group']
        wage_offer = jsonmessage['wage_offer']
        employers_left_in = jsonmessage['employers_left']
        offer_times = jsonmessage['offer_time']
        offer_times += 1
        now = time.time()
        time_left = round(mygroup.auctionenddate - now)

        if curemployer_id_id_in_group == 1:
            mygroup.standing1 = wage_offer
        if curemployer_id_id_in_group == 2:
            mygroup.standing2 = wage_offer
        if curemployer_id_id_in_group == 3:
            mygroup.standing3 = wage_offer
        if curemployer_id_id_in_group == 4:
            mygroup.standing4 = wage_offer
        if curemployer_id_id_in_group == 5:
            mygroup.standing5 = wage_offer

        mygroup.save()

        textforgroup = json.dumps({
            "from": "employer",
            "employer_id": curemployer_id,
            "employer_id_in_group": curemployer_id_id_in_group,
            "wage_offered": wage_offer,
            "offer_time": offer_times,
            "time_left": time_left,
            "employers_left":employers_left_in

        })
        # Note that this corresponds exactly to the fields defined extra under the groups (in models.py)
        Group(group_name).send({
            "text": textforgroup,
        })

    if (jsonmessage['role'] == "worker"):
    # handle the message this way
        print('worker')
        curworker_id = jsonmessage['id_worker']
        curworker_id_id_in_group = jsonmessage['id_worker_in_group']
        curemployer_id_id_in_group = jsonmessage['id_employer_in_group']
        wage_accepted = jsonmessage['wage_accepted']
        offer_times = jsonmessage['offer_time']
        now = time.time()
        employers_left_in = jsonmessage['num_employers_left']
        employers_left_in -= 1

        # mygroup.auctionenddate = now + Constants.extra_time
        are_you_matched = 0
        time_left = round(mygroup.auctionenddate - now)

        # Are you matched directly?
        if curemployer_id_id_in_group == 1:
            mygroup.matched1 += 1
            if mygroup.matched1 == 1:
                are_you_matched = 1  # yes!
        if curemployer_id_id_in_group == 2:
            mygroup.matched2 += 1
            if mygroup.matched2 == 1:
                are_you_matched = 1  # yes
        if curemployer_id_id_in_group == 3:
            mygroup.matched3 += 1
            if mygroup.matched3 == 1:
                are_you_matched = 1  # yes
        if curemployer_id_id_in_group == 4:
            mygroup.matched4 += 1
            if mygroup.matched4 == 1:
                are_you_matched = 1  # yes
        if curemployer_id_id_in_group == 5:
            mygroup.matched5 += 1
            if mygroup.matched5 == 1:
                are_you_matched = 1  # yes:

        # If you are not matched directly, are there other standing offers identical to the one you have just accepted?
        if are_you_matched == 0:
            if wage_accepted == mygroup.standing1:
                if mygroup.matched1 != 1:
                    curemployer_id_id_in_group = 1 # match them!
                    mygroup.matched1 = 1
                    are_you_matched = 2
            else:
                if wage_accepted == mygroup.standing2:
                    if mygroup.matched2 != 1:
                        curemployer_id_id_in_group = 2 # match them!
                        mygroup.matched2 = 1
                        are_you_matched = 2
                else:
                    if wage_accepted == mygroup.standing3:
                        if mygroup.matched3 != 1:
                            curemployer_id_id_in_group = 3 # match them!
                            mygroup.matched3 = 1
                            are_you_matched = 2
                    else:
                        if wage_accepted == mygroup.standing4:
                            if mygroup.matched4 != 1:
                                curemployer_id_id_in_group = 4 # match them!
                                mygroup.matched4 = 1
                                are_you_matched = 2
                        else:
                            if wage_accepted == standing5:
                                if mygroup.matched5 != 1:
                                    curemployer_id_id_in_group = 5 # match them!
                                    mygroup.matched5 = 1
                                    are_you_matched = 2

        if are_you_matched == 0:
            employers_left_in += 1

        if are_you_matched == 2:
            employers_left_in -= 1

        mygroup.save()

        # do something with those that are not first in the receiving end.
        textforgroup = json.dumps({
            "from": "worker",
            "employer_id_in_group": curemployer_id_id_in_group,
            "worker_id_in_group": curworker_id_id_in_group,
            "wage_accepted": wage_accepted,
            "offer_time": offer_times,
            "time_left": time_left,
            "employers_left": employers_left_in,
            "first": are_you_matched
        })
        Group(group_name).send({
            "text": textforgroup,
        })
    print("SERVER::::", textforgroup)

# Connected to websocket.disconnect
def ws_disconnect(message, group_name):
    Group(group_name).discard(message.reply_channel)


"""
Intuition:  Brute Force - Get all possible pair of elements and check if its sum == target.

Optimized Intuiion: Use a hashmap.
Use the formula : x + y = target.
If we know x and target, y can be calculated.
If y is in the hashmap, we have found the pair of numbers

#####################################################################
#Brute Force: Getting all possible pair of elements that result to target
Time Complexity : O(n^2) where n = number of elements
Space Complexity : O(1)

#Hashing
Time Complexity : O(n) where n = number of elements
Space Complexity : O(n)where n = number of elements
#####################################################################

"""

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        if len(nums) == 0:
            return [-1, -1]

        hashMap = {}

        for index in range(len(nums)):
            num = nums[index]

            if (target - num) not in hashMap:
                hashMap[num] = index
            else:
                return [hashMap[(target-num)], index]


import socket

sock = socket.socket()

address = input("Aдрес сервера - ")

# безопасный ввод данных по умолчанию
if address == '':
    address = 'localhost'
port = int(input("Введите порт: "))
sock.connect((address, port))

msg = ["PINGUIN #1", "PINGUIN #2", "PINGUIN #3", "EXIT"]

# Пользователь считает пингвинов и уходит

for i in range(len(msg)):
    sock.send(msg[i].encode())
    data = sock.recv(1024)
    print(data.decode())
sock.close()


from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.project_homepage),
    path('database/', include('database.urls')),
    path('homepage/', views.homepage, name= 'homepage'),
    path('login/', views.login, name= 'login'),
    path('login/homepage.html', views.homepage, name= 'redirecthome'),
    path('labInfo/', views.labInfo, name= 'labInfo'),
    path('addNewLab/', views.addNewLab, name= 'addNewLab'),
    path('report/', views.report, name= 'report'),
    path('AddNewPCs/', views.AddNewPCs, name= 'AddNewPCs'),
    path('list of pc/', views.list_of_pc, name= 'list of pc'),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


import ccxt
import time

# Enter your exchange API credentials here
API_KEY = 'your_api_key'
API_SECRET = 'your_api_secret'

# Enter your trading parameters here
SYMBOL = 'BTC/USDT'
GRID_SPACING = 100  # Grid spacing in USDT
AMOUNT = 0.01  # Amount to trade in BTC

# Connect to the exchange
exchange = ccxt.binance({
    'apiKey': API_KEY,
    'secret': API_SECRET,
})

# Calculate grid levels
ticker = exchange.fetch_ticker(SYMBOL)
last_price = ticker['close']
grid_levels = [price for price in range(int(last_price) - 500, int(last_price) + 500, GRID_SPACING)]

# Place initial grid orders
for level in grid_levels:
    price = level / 100.0
    sell_order = exchange.create_limit_sell_order(SYMBOL, AMOUNT, price)
    buy_order = exchange.create_limit_buy_order(SYMBOL, AMOUNT, price)

print('Initial grid orders placed. Monitoring for fills...')

# Monitor for filled orders and place new ones accordingly
while True:
    open_orders = exchange.fetch_open_orders(SYMBOL)

    for order in open_orders:
        if order['side'] == 'sell':
            if float(order['price']) >= last_price:
                print(f"Grid sell order filled at {order['price']}")
                new_price = float(order['price']) + (GRID_SPACING / 100.0)
                new_order = exchange.create_limit_sell_order(SYMBOL, AMOUNT, new_price)
                grid_levels.append(new_price)
        elif order['side'] == 'buy':
            if float(order['price']) <= last_price:
                print(f"Grid buy order filled at {order['price']}")
                new_price = float(order['price']) - (GRID_SPACING / 100.0)
                new_order = exchange.create_limit_buy_order(SYMBOL, AMOUNT, new_price)
                grid_levels.append(new_price)

    time.sleep(10)  # Sleep for 10 seconds between checks


from acc_utils.errors import _assert

from .operator_base import OperatorBase

class ConcatOp(OperatorBase):
    def __init__(self, op_type='Concat', axis = 1, concat_info=None, **kwargs):
        super(ConcatOp, self).__init__(op_type=op_type, **kwargs)
        _assert(isinstance(concat_info, list),
                'concat_info must be given as a size list')
        self.axis = axis
        self.size_info = [sum(concat_info[:i])
                          for i in range(len(concat_info))]

    def __repr__(self):
        return super(ConcatOp, self).__repr__() + "offset information: {}\n".format(self.size_info)

    def tensor_to_midap_tensor(self):
        if self.order == 'NCHW':
            super(ConcatOp, self).tensor_to_midap_tensor()
            axis_translate_arr = [-1, 2, 1, 0]
            self.axis = axis_translate_arr[self.axis]


import pandas as pd
import matplotlib.pyplot as plt
import PIL, glob, json
from matplotlib import font_manager, rc

# 내꺼
import graph_manager

# 폰트 설정 / json
FONT_PATH = "C:\\Users\\test2\\Downloads\\data_sicence\\fonts\\NanumGothic.ttf"
FONT_PROP = font_manager.FontProperties(fname=FONT_PATH).get_name()
rc("font", family=FONT_PROP)

with open("rank_point.json", "r", encoding="UTF-8") as file:
    rank_point = json.load(file)

def meta_point_cal(CHAR_LIST):
    data_dic = {}
    for PATH in CHAR_LIST:
        index = PATH.replace("C:\\Users\\test2\\Downloads\\data_sicence\\data\\char_data\\", "")
        index = index.replace(".csv", "")
        data = graph_manager.pickrate_data_loader(PATH, "계급")
        data_dic[index] = 0

        for rank in data:
            if not pd.notna(rank): continue

            point = int(rank_point[rank]) * int(data[rank])
            data_dic[index] += point
    return data_dic

def create_table(data, key_arr):
    data_df2 = {}
    # 인덱스 값 조정
    rank_cnt = 0
    for char in data:
        rank_cnt += 1
        data_df2[str(rank_cnt) + ". " + char] = str(data[char]) + "pt"

    data_df = pd.DataFrame.from_dict(data_df2, orient="index", columns=[key_arr[1]])
    # 표 그리기
    fig, ax = plt.subplots(1, 1)
    table = ax.table(
        cellText=data_df.values,
        cellLoc='right',
        colLabels=data_df.columns,
        rowLabels=data_df.index,
        loc='center'
    )
    table.auto_set_font_size(False)
    table.set_fontsize(12)
    table.scale(1.2, 1.2)
    table.auto_set_column_width([0, 1])
    ax.axis('off')
    plt.title(key_arr[2])
    plt.show()


"""Functions generating the `selected_model_versions` file."""

def write_selected_model_versions_file(
        *,
        actions,
        name,
        tool,
        xccurrentversions_files):
    """Creates a `File` that contains a JSON representation of \
    `[BazelPath: String]`, mapping `.xcdatamodeld` file paths to selected \
    `.xcdatamodel` file names.

    Args:
        actions: `ctx.actions`.
        name: The name of the target creating the file.
        tool: The executable to run to generate the file.
        xccurrentversions_files: A `list` of `File`s containing the
            `xccurrentversion` files to read.

    Returns:
        The generated `File`.
    """
    output = actions.declare_file("{}_selected_model_versions".format(name))

    args = actions.args()
    args.add(output)

    files_args = actions.args()
    files_args.use_param_file("%s", use_always = True)
    files_args.set_param_file_format("multiline")

    files_args.add_all(xccurrentversions_files)

    actions.run(
        arguments = [args, files_args],
        executable = tool,
        inputs = xccurrentversions_files,
        outputs = [output],
        mnemonic = "WriteSelectedModelVersionsFile",
    )

    return output


"""
This module defines the urlpatterns of the 'mycinema' app.

"""

from django.urls import path

from mycinema import views

urlpatterns = [
    path('films/create/', views.FilmCreateView.as_view(), name='add_film'),
    path('films/<int:pk>/', views.FilmDetailView.as_view(), name='film_by_id'),
    path('films/', views.FilmListView.as_view(), name='all_films'),
    path('halls/', views.HallListView.as_view(), name='all_halls'),
    path('halls/create/', views.HallCreateView.as_view(), name='add_hall'),
    path('halls/edit/<int:pk>/', views.HallUpdateView.as_view(), name='edit_hall'),
    path('halls/<int:pk>/', views.HallDetailView.as_view(), name='hall_by_id'),
    path('seances/', views.SeanceListView.as_view(), name='all_seances'),
    path('seances/tomorrow/<int:delta>/', views.SeancesTodayListView.as_view(), name='seances_tomorrow'),
    path('seances/sorted/<int:ord>/', views.SeanceListView.as_view(), name='seances_sorted'),
    path('seances/create/', views.SeanceCreateView.as_view(), name='add_seance'),
    path('seances/edit/<int:pk>/', views.SeanceUpdateView.as_view(), name='edit_seance'),
    path('seances/<int:pk>/', views.SeanceDetailView.as_view(), name='seance_by_id'),
    path('tickets/', views.TicketListView.as_view(), name='all_tickets'),
    path('tickets/<int:pk>/', views.TicketDetailView.as_view(), name='ticket_by_id')
]


# -*- coding: utf-8 -*-
"""
Created on Sat Jul  1 21:25:02 2017

@author: Ohaddoron
"""

from brian2 import *
I_e = 50*namp # electrode current
thresh = -55*mvolt # threshold potential
V0 = -70*mvolt # starting voltage
Rm = 5*Mohm # memberane resistance
Cm = 1*nF # memberane capacitance
tau_m = Rm * Cm # membrane time constant
E_L = -60*mvolt # leaky potetial
refract = 4*msecond # refractory period
N = 100 # num neurons

start_scope()
eqs = '''
dx/dt = (1-x)/tau_D - u*x*
 '''

G = NeuronGroup(1, eqs, threshold='v>1', reset='v=0', method='linear')
G.v = 'rand()'

spikemon = SpikeMonitor(G)

run(50*ms)

plot(spikemon.t/ms, spikemon.i, '.k')
xlabel('Time (ms)')
ylabel('Neuron index');


"""
# Definition for Employee.
class Employee:
    def __init__(self, id: int, importance: int, subordinates: List[int]):
        self.id = id
        self.importance = importance
        self.subordinates = subordinates
"""

class Solution:
    def getImportance(self, employees: List['Employee'], id: int) -> int:
        total=0
        d=defaultdict(list)
        for i in range(len(employees)):
            d[employees[i].id]=employees[i]
        def dfs(id):
            nonlocal total
            total+=d[id].importance
            for subordinate in d[id].subordinates:
                dfs(subordinate)
        dfs(id)
        return total


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 13 13:05:16 2022

@author: Omar
"""

import tkinter as tk
from tkinter import filedialog

def addMore():
    textt.insert(tk.END, "\n Good Bye \n")

def show():
    tk.messagebox.showinfo(title = "Text Widget", message = textt.get("1.0", tk.END))

def openFile():
    filename = tk.filedialog.askopenfilename(filetypes = (("text files", ".txt"), ("All files", ".")))
    # filename = tk.filedialog.askopenfilename(filetypes = (("text files", ".txt"), )) The Same as above
    print(filename)

win = tk.Tk()

win.geometry("700x400+680+150")

# Create menubar that contains:

    # File Menu(open, close)
    # Edit Menu(Copy, Paste)

menuBar = tk.Menu(win)
fileMenu = tk.Menu(menuBar, tearoff = 0)
fileMenu.add_command(label = "Open", command = openFile)
fileMenu.add_separator()
fileMenu.add_command(label = "Close")

menuBar.add_cascade(menu = fileMenu, label = "File")

editMenu = tk.Menu(menuBar, tearoff = 0)
editMenu.add_command(label = "Copy", activebackground = "red", command = show)
editMenu.add_separator()
editMenu.add_command(label = "Paste")

menuBar.add_cascade(menu = editMenu, label = "Edit")

searchMenu = tk.Menu(menuBar, tearoff = 0)
searchMenu.add_command(label = "Find Text")
searchMenu.add_separator()
searchMenu.add_command(label = "Find Next")

menuBar.add_cascade(menu = searchMenu, label = "Search")

win.config(menu = menuBar)

textt = tk.Text(win, width = 30, height = 5, bg = "gray")
textt.grid(row = 0, column = 0, sticky = tk.W, padx = 10)

btn = tk.Button(win, text = "Add Sign", command = addMore)
btn.grid(row = 1, column = 0, sticky = tk.W, padx = 10)

btn2 = tk.Button(win, text = "Show", command = show, bg = "yellow")
btn2.grid(row = 1, column = 0, sticky = tk.E, padx = 10)

win.mainloop()