# From Python
# It requires OpenCV installed for Python
import sys
import cv2
import os
from sys import platform
import argparse
import json

def create_pose_json(op, opWrapper, image):
    try:
        # Process Image
        # Flags
        parser = argparse.ArgumentParser()
        parser.add_argument("--image_path", default=image)
        # parser.add_argument("--image_path", default="../../../examples/media/COCO_val2014_000000000192.jpg")
        # parser.add_argument("--image_path", default="../../../examples/media/Danya.png", help="Process an image. Read all standard formats (jpg, png, bmp, etc.).")
        args = parser.parse_known_args()
        datum = op.Datum()
        imageToProcess = image  # cv2.imread(args[0].image_path) if using imagepath
        datum.cvInputData = imageToProcess
        opWrapper.emplaceAndPop([datum])

        poseModel = op.PoseModel.BODY_25
        #print(op.getPoseBodyPartMapping(poseModel))

        poseModel = {0: 'Nose', 1: 'Neck', 2: 'RShoulder', 3: 'RElbow', 4: 'RWrist', 5: 'LShoulder', 6: 'LElbow', 7: 'LWrist', 8: 'MidHip',
                     9: 'RHip', 10: 'RKnee', 11: 'RAnkle', 12: 'LHip', 13: 'LKnee', 14: 'LAnkle', 15: 'REye', 16: 'LEye', 17: 'REar',
                     18: 'LEar', 19: 'LBigToe', 20: 'LSmallToe', 21: 'LHeel', 22: 'RBigToe', 23: 'RSmallToe', 24: 'RHeel', 25: 'Background'}
        merged = {}
        for person in range(len(datum.poseKeypoints)):
            anchor_point_X = datum.poseKeypoints[person][1][0] #Neck
            anchor_point_Y = datum.poseKeypoints[person][1][1]
            persnum = "Person{}".format(person)
            parts = [{'bodypart': poseModel[bodypart], 'X': str(datum.poseKeypoints[person][bodypart][0] - anchor_point_X), 'Y': str(datum.poseKeypoints[person][bodypart][1] - anchor_point_Y),
                    'Confidence': str(datum.poseKeypoints[person][bodypart][2])} for bodypart in range(len(datum.poseKeypoints[person]))]
            '''lefthand = []
            for part in range(int((datum.handKeypoints[0].size)/3)):
                lefthand.append({'X' : str(datum.handKeypoints[0][part][0]), 'Y': str(datum.handKeypoints[0][part][1])})
            leftHands = ([{'LeftHandParts': {'X' : str(datum.handKeypoints[person][0][part][0]), 'Y': str(datum.handKeypoints[person][0][part][1])} for part in range(datum.handKeypoints[0].size)}])
            parts.append(leftHands)'''
           # parts.append({'RightHand': str(datum.handKeypoints[1])})
            merged[persnum] = parts
        res = json.dumps(merged,               sort_keys=False, indent=4, separators=(',', ': '))
        # Display Image
        #print("Body keypoints: \n" + str(datum.poseKeypoints))
        #cv2.imshow("OpenPose 1.5.1 - Tutorial Python API", datum.cvOutputData)
        #cv2.waitKey(0)
        return res
    except Exception as e:
        print(e)
        return -1


# * in front of parameter means it can accept any number of positional arguments
# kwargs returns item in a dictionary

def super_func(*args, **kwargs):
    total = 0
    for items in kwargs.values():
        total += items
    return sum(args) + total

print(super_func(1, 2, 3, 4, 6, 7, 8, num1=5, num2=60))


from selenium import webdriver
from time import sleep

driver = webdriver.Chrome(executable_path='F:\chromedriver.exe')
driver.maximize_window()

while True:
    list = []
    driver.get('https://www.tiktok.com/')
    scorll = driver.execute_script("window.scrollBy(0,document.body.scrollHeight)")
    get_id_link = driver.find_elements("xpath","//a[@class='tiktok-1lqhxf7-StyledAuthorAnchor emt6k1z1']")
    for id in get_id_link:
        id_link = id.get_attribute('href')
        if id_link not in list:
            list.append(id_link)
        print(id_link)
        #sleep(5)

    for i in list:
        print(i)
    print('__________________________')


class TrieNode:
    def __init__(self, sentence=None):
        self.children = {}
        self.sentence = sentence
        self.hot = 0
        self.is_end = False

class AutocompleteSystem:

    def __init__(self, sentences: List[str], times: List[int]):
        self.trie = TrieNode()
        self.last_node = self.trie
        self.curr_sentence = []
        self.curr_not_found = False

        for i in range(len(sentences)):
            self.add_on_trie(sentences[i], times[i])

    def add_on_trie(self, sentence, hot):
        root = self.trie

        for char in sentence:
            if char not in root.children:
                root.children[char] = TrieNode()
            root = root.children[char]
        root.sentence = sentence
        root.hot -= hot
        root.is_end = True

    def input(self, c: str) -> List[str]:
        def dfs(node):
            nonlocal res
            if node.is_end:
                res.append((node.hot, node.sentence))
            for children in node.children:
                dfs(node.children[children])
        if c == '#':
            self.add_on_trie(''.join(self.curr_sentence), 1)
            self.curr_sentence = []
            self.last_node = self.trie
            self.curr_not_found = False
            return []
        self.curr_sentence.append(c)
        if self.curr_not_found:
            return []
        if c in self.last_node.children:
            self.last_node = self.last_node.children[c]
            res = []
            dfs(self.last_node)
            return [sentence for _, sentence in sorted(res)][:3]
        self.curr_not_found = True
        return []

# Your AutocompleteSystem object will be instantiated and called as such:
# obj = AutocompleteSystem(sentences, times)
# param_1 = obj.input(c)


"""
우리 학교에는 복도 불을 켜고 끄는 마부(Mabu)라는 사람이 있다.
전구마다 불을 켜고 끄는 스위치가 있다.
불이 꺼져 있을 때 스위치를 누르면 불이 켜지고 다시 스위치를 누르면 불이 꺼진다.
처음에는 모든 전구가 꺼져 있다.
마부라는 사람은 특이한 행동을 한다.
복도에 n개의 전구가 있으면, 복도를 n번 왕복한다.
i번째 갈 때 그는 i로 나누어 떨어지는 위치에 있는 스위치만 누른다.
처음 위치로 돌아올 때는 아무 스위치도 건드리지 않는다.
i번째 왕복은 (이런 이상한 행동을 하면서) 복도를 한 번 갔다가 오는 것으로 정의된다.
마지막 전구의 최종 상태를 알아내자.
과연 그 전구는 켜져 있을까 아니면 꺼져 있을까?

Input : 복도에 있는 n번째 전구를 나타내는 숫자가 입력된다. (2^32-1 이하의 정수가 입력된다.) 0은 입력의 끝을 의미하며 그 값은 처리하지 않는다.
Output : 그 전구가 켜져 있으면 "yes"를, 꺼져 있으면 "no"를 출력한다. 테스트 케이스마다 한 줄에 하나씩 출력한다.

"""

"""
=============================================================================
과제 1 : 복도에 있는 n번째 전구의 최종 상태를 출력하시오.
        - 조건 : 0은 입력의 끝을 의미하며 그 값은 처리하지 않는다.
        input = [3, 6241, 8191, 0] (만약 전구번호가 3이면, 3번 왕복한 후의 전구상태를 출력하는 코드를 짜면 된다.)
        출력 : (테스트 케이스마다 한 줄에 하나씩 출력해야함.)
              no
              yes
              no
=============================================================================
"""

# inpust_light_zip = 상태를 알고 싶은 전구 번호를 입력받을 때, 이를 ', '을 기준으로 분해
input_light_zip = input('상태를 알고 싶은 전구 번호를 입력하세요 : ').split(', ')

## 특정 행위 반복 시 전구의 최종 상태를 출력하는 프로그램
for input_light in input_light_zip:                         # 전구 번호를 하나씩 분해
      if input_light == '0':                                # 만약 전구 번호가 '0'이라면, 프로그램 종료
            break

      light_n = -1                                          # light_n = 전구 상태 (-1은 off, 1은 on)
      for light_on_off in range(1, int(input_light) + 1):   # 전구 번호만큼 다음 행위 반복
            if int(input_light) % light_on_off == 0:        # 만약 전구 번호 % i번째 왕복이 나누어 떨어진다면,
                  light_n *= -1                             # 전구 켜거나 끄기

      if light_n == 1:                                      # 만약 전구의 최종 상태가 on이라면, 'yes' 출력
            print('yes')
      elif light_n == -1:                                   # 만약 전구의 최종 상태가 off라면, 'no' 출력
            print('no')


from tkinter import *
import pandas as pd
import tkinter as tk
from tkinter import filedialog
import pandas as pd
#import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
#importing filters
import csv
import numpy
df= pd.read_csv('oct_2019 MELT.csv')

#desk filter
def desk_filter(day,desk):
    global df2
    desk_new=[]
    for i in desk:
        desk_new.append(str(i))
    df1= df[df.Day.isin(day)]
    df2=df1[df1.Desk.isin(desk_new)]  #needs to be a string
    return (df2)

desk_filter([1],[3])
#print(df2)

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)

        # create a horizontal scrollbar and the canvas
        hscrollbar = Scrollbar(self, orient=HORIZONTAL)
        hscrollbar.pack(fill=X, side=BOTTOM, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE, anchor=W)
        vscrollbar.config(command=canvas.yview)
        hscrollbar.config(command=canvas.xview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

if __name__ == "__main__":

    class SampleApp(Tk):

        def __init__(self, *args, **kwargs):
            root = Tk.__init__(self, *args, **kwargs)

            self.frame = VerticalScrolledFrame(root)
            self.frame.grid(row=0, column=0)
            #self.label = Label(text="Shrink the window to activate the scrollbar.")
            #self.label.grid(row=1, column=0)
            def graphdesk(desk):
            #print('you are printing imaginary graphs!')

                #placeholder dataframes

                Data1 = {'Country': ['US','CA','GER','UK','FR'],
                        'GDP_Per_Capita': [45000,42000,52000,49000,47000]
                       }

                df1 = DataFrame(Data1, columns= ['Country', 'GDP_Per_Capita'])
                df1 = df1[['Country', 'GDP_Per_Capita']].groupby('Country').sum()

                Data2 = {'Year': [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010],
                        'Unemployment_Rate': [9.8,12,8,7.2,6.9,7,6.5,6.2,5.5,6.3]
                       }

                df2 = DataFrame(Data2,columns=['Year','Unemployment_Rate'])
                df2 = df2[['Year', 'Unemployment_Rate']].groupby('Year').sum()

                Data3 = {'Interest_Rate': [5,5.5,6,5.5,5.25,6.5,7,8,7.5,8.5],
                        'Stock_Index_Price': [1500,1520,1525,1523,1515,1540,1545,1560,1555,1565]
                       }

                df3 = DataFrame(Data3,columns=['Interest_Rate','Stock_Index_Price'])

                #placeholder dataframes

                newWindow = tk.Toplevel()

                print(desk)
                figure1 = plt.Figure(figsize=(6,5), dpi=100)
                ax1 = figure1.add_subplot(111)
                bar1 = FigureCanvasTkAgg(figure1, newWindow)
                bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
                df1.plot(kind='bar', legend=True, ax=ax1)
                ax1.set_title('Country Vs. GDP Per Capita')

                figure2 = plt.Figure(figsize=(5,4), dpi=100)
                ax2 = figure2.add_subplot(111)
                line2 = FigureCanvasTkAgg(figure2, newWindow)
                line2.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
                df2.plot(kind='line', legend=True, ax=ax2, color='r',marker='o', fontsize=10)
                ax2.set_title('Year Vs. Unemployment Rate')

                figure3 = plt.Figure(figsize=(5,4), dpi=100)
                ax3 = figure3.add_subplot(111)
                ax3.scatter(df3['Interest_Rate'],df3['Stock_Index_Price'], color = 'g')
                scatter3 = FigureCanvasTkAgg(figure3, newWindow)
                scatter3.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
                ax3.legend()
                ax3.set_xlabel('Interest Rate')
                ax3.set_title('Interest Rate Vs. Stock Index Price')

            deskNum=tk.StringVar()
            entry_deskNum = tk.Entry(self.frame.interior, textvariable=deskNum, width=6).grid(row=0, column=0)
            button_graphdesk = tk.Button(self.frame.interior, text = 'Graph the desk!', command=lambda:graphdesk(deskNum.get())).grid(row=0, column=1, sticky='w'+'e')
            headers = []
            for col in df2.columns:
                #print(col)
                headers.append(col)
            headers[0] = 'Desk#'
            headerindex = 0
            for i in headers:
                tk.Label(self.frame.interior,text=i,font=("Helvetica", 8),bg = 'cyan',anchor= 'e',relief = 'solid').grid(row = 1, column = headerindex, sticky = 'w'+'e')
                headerindex +=1
            df2.to_csv('headless.csv', header=False, index=False)
            listedDF = df2.values.tolist()
            i_index = 2
            j_index = 0
            for i in listedDF:
                for j in i:
                    if i[0] < 101:
                        tk.Label(self.frame.interior, text=j,font=("Helvetica", 8),bg = 'lightgreen',anchor= 'e',relief = 'solid').grid(row = i_index, column = j_index, sticky = 'w'+'e')
                    else:
                        tk.Label(self.frame.interior,text=j,font=("Helvetica", 8),bg = 'orange', anchor = 'e', relief = 'solid').grid(row = i_index, column = j_index, sticky = 'w'+'e')
                    j_index +=1
                i_index +=1
                j_index = 0

    app = SampleApp()
    app.mainloop()


from PIL import Image
import numpy as np
import torch
import matplotlib.pyplot as plt
import math
from tools.misc_functions import *
from tensorboardX import SummaryWriter
import os
from tools.config import *

import argparse
parser = argparse.ArgumentParser(description='cam')
parser.add_argument('--model', default='vgg16', type=str, help='model: [vgg16, resnet50, densenet121, darts].')
parser.add_argument('--dataset', default='imagenet', type=str, help='dataset: [imagenet, place].')
parser.add_argument('--epoch', default=20, type=int, help='epoch: from 0 to 20.')
parser.add_argument('--image_dir', default='{}/val/n01514668/ILSVRC2012_val_00029921.JPEG'.format(get_dataset_dir("imagenet")),
                    type=str, help='the image wanna to cam.')
parser.add_argument('--cam_class', default=7, type=int, help='class: from 0 to 999.')
parser.add_argument('--mask_rate', default=0.05, type=float, help='the mask rate of cam.')
parser.add_argument('--is_ori', default=0, type=int, help='1 for ori and 0 for add mask')
args = parser.parse_args()

if args.dataset == 'imagenet' and args.model == 'vgg16':
    from models.imagenet.vgg16 import *
    net = vgg16(finding_masks=False).cuda().eval()
if args.dataset == 'imagenet' and args.model == 'resnet50':
    from models.imagenet.resnet50 import *
    net = resnet50(finding_masks=False).cuda().eval()
if args.dataset == 'imagenet' and args.model == 'densenet121':
    from models.imagenet.densenet121 import *
    net = densenet121(finding_masks=False).cuda().eval()
if args.dataset == 'imagenet' and args.model == 'darts':
    from models.imagenet.darts import *
    net = darts(finding_masks=False).cuda().eval()
if args.dataset == 'place' and args.model == 'vgg16':
    from models.place.vgg16 import *
    net = vgg16(finding_masks=False).cuda().eval()
if args.dataset == 'place' and args.model == 'resnet50':
    from models.place.resnet50 import *
    net = resnet50(finding_masks=False).cuda().eval()
if args.dataset == 'place' and args.model == 'densenet121':
    from models.place.densenet121 import *
    net = densenet121(finding_masks=False).cuda().eval()
if args.dataset == 'place' and args.model == 'darts':
    from models.place.darts import *
    net = darts(finding_masks=False).cuda().eval()

class CamExtractor():
    def __init__(self, model, target_layer):
        self.model = model
        self.target_layer = target_layer
        self.conv_out = None
    def hook_mask(self, layer):
        def hook_function(module, input, output):
            self.conv_out = output
        return layer.register_forward_hook(hook_function)
    def forward_pass(self, x):
        self.hook_mask(self.target_layer)
        x = self.model(x)
        return self.conv_out, x

class GradCam():
    def __init__(self, model, target_layer):
        self.model = model
        self.model.eval()
        self.extractor = CamExtractor(self.model, target_layer)

    def generate_cam(self, input_image):
        conv_output, model_output = self.extractor.forward_pass(input_image)
        target = conv_output.data.cpu().numpy()[0]
        cam = np.zeros(target.shape[1:], dtype=np.float32)
        for i in range(target.shape[0]):
            cam += target[i, :, :]
        cam = (cam - np.min(cam)) / (np.max(cam) - np.min(cam))
        cam = np.uint8(cam * 255)

        cam = np.uint8(Image.fromarray(cam).resize((input_image.shape[2],
                        input_image.shape[3]), Image.ANTIALIAS)) / 255

        return cam

def show_binary(img, cam, cnt, mask_rate=0.2, is_focus=True, H=None, W=None):

    if is_focus:
        threshold = sorted(cam.copy().reshape(-1))[-int(mask_rate*224*224)]
        cam = np.where(cam.copy() > threshold, 0, 0.5)

    else:
        threshold = sorted(cam.copy().reshape(-1))[int(mask_rate*224*224)]
        cam = np.where(cam.copy() < threshold, 0, 0.5)
    img_copy = np.array(img.copy()).transpose(2, 0, 1)

    th = [0, 0, 0]

    for i in range(3):
        for j in range(224):
            for k in range(224):
                if cam[j][k] != 0:
                    img_copy[i][j][k] = int(float(img_copy[i][j][k]) + (th[i] - img_copy[i][j][k]) * 0.8)

    img_copy = img_copy.transpose(1, 2, 0)

    if not os.path.exists('./results'):
        os.makedirs('./results')
    if not os.path.exists('./results/cam_1x1'):
        os.makedirs('./results/cam_1x1')
    if not os.path.exists('./results/cam_1x1/{}'.format(args.model)):
        os.makedirs('./results/cam_1x1/{}'.format(args.model))
    if not os.path.exists('./results/cam_1x1/{}/{}'.format(args.model, args.dataset)):
        os.makedirs('./results/cam_1x1/{}/{}'.format(args.model, args.dataset))
    if not os.path.exists('./results/cam_1x1/{}/{}/{:03d}'.format(args.model, args.dataset, args.cam_class)):
        os.makedirs('./results/cam_1x1/{}/{}/{:03d}'.format(args.model, args.dataset, args.cam_class))
    Image.fromarray(img_copy).save('./results/cam_1x1/{}/{}/{:03d}/block{:02d}.jpg'.format(args.model, args.dataset,
                                                                                args.cam_class, cnt-1))

def draw_binary(net, img, mask_rate=0.2, is_focus=True):
    origin_img, img = preprocess_image(img)
    if not os.path.exists('./results/cam_1x1/{}/{}/{:03d}'.format(args.model, args.dataset, args.cam_class)):
        os.makedirs('./results/cam_1x1/{}/{}/{:03d}'.format(args.model, args.dataset, args.cam_class))
    origin_img.save('./results/cam_1x1/{}/{}/{:03d}/origin00.png'.format(args.model, args.dataset, args.cam_class))
    img.requires_grad = False
    minn = img.min()
    maxx = img.max()

    img_draw = img.clone()
    img_draw = (img_draw - minn) / (maxx - minn)

    cnt = 1

    if args.model == 'vgg16':
        target_layers = [net.features[2], net.features[6], net.features[9], net.features[13], net.features[16],
                         net.features[19], net.features[23], net.features[26], net.features[29], net.features[33],
                         net.features[36], net.features[39], net.mask]
    elif args.model == 'resnet50':
        target_layers = [net.mask, net.layer1[0].mask, net.layer1[1].mask, net.layer1[2].mask, net.layer2[0].mask,
                         net.layer2[1].mask, net.layer2[2].mask, net.layer2[3].mask, net.layer3[0].mask,
                         net.layer3[1].mask, net.layer3[2].mask, net.layer3[3].mask, net.layer3[4].mask,
                         net.layer3[5].mask, net.layer4[0].mask, net.layer4[1].mask, net.layer4[2].mask]
    elif args.model == 'densenet121':
        target_layers = [net.features.mask0, net.features.mask1, net.features.transition1.mask, net.features.mask2,
                         net.features.transition2.mask, net.features.mask3, net.features.transition3.mask,
                         net.features.mask5]
    elif args.model == 'darts':
        target_layers = [net.mask0, net.mask1, net.cells[0].mask, net.cells[1].mask, net.cells[2].mask,
                         net.cells[3].mask, net.cells[4].mask, net.cells[5].mask, net.cells[6].mask, net.cells[7].mask,
                         net.cells[8].mask, net.cells[9].mask, net.cells[10].mask, net.cells[11].mask,
                         net.cells[12].mask, net.cells[13].mask]

    leng = len(target_layers)+1

    for layer in target_layers:
        cnt += 1
        grad_cam = GradCam(net, target_layer=layer)
        cam = grad_cam.generate_cam(img.cuda())
        show_binary(origin_img, cam, cnt, mask_rate, is_focus, H=math.floor(math.sqrt(leng)),
                    W=math.ceil(leng/math.floor(math.sqrt(leng))))

def main():

    mask_dir = './checkpoint/{}/{}/{:03d}/net_iter{:03d}.pth'.format(args.dataset, args.model, args.cam_class, args.epoch)

    net.load_masks(mask_dir)

    with torch.no_grad():
        masks = net.get_masks()
        for key in masks.keys():
            mask = (masks[key].data[...])
            if args.is_ori == 0:
                masks[key].mask[...] = torch.sigmoid(mask).gt(0.5)
            else:
                masks[key].mask[...] = torch.sigmoid(mask).gt(-5)
    # for key in masks.keys():
    #     print(net.get_masks()[key].mask[...].sum())

    img = Image.open(args.image_dir).convert('RGB')

    draw_binary(net, img, mask_rate=args.mask_rate)

if __name__ == '__main__':
    main()


import pytest
from pathlib import Path
import numpy as np
from numpy.testing import assert_allclose
from blendtorch import btt

BLENDDIR = Path(__file__).parent / "blender"

@pytest.mark.background
def test_projection():
    launch_args = dict(
        scene=BLENDDIR / "cam.blend",
        script=BLENDDIR / "cam.blend.py",
        num_instances=1,
        named_sockets=["DATA"],
        background=True,
    )

    ortho_xy_expected = np.array(
        [
            [480.0, 80],
            [480.0, 80],
            [480.0, 400],
            [480.0, 400],
            [160.0, 80],
            [160.0, 80],
            [160.0, 400],
            [160.0, 400],
        ]
    )

    proj_xy_expected = np.array(
        [
            [468.148, 91.851],
            [431.111, 128.888],
            [468.148, 388.148],
            [431.111, 351.111],
            [171.851, 91.851],
            [208.888, 128.888],
            [171.851, 388.148],
            [208.888, 351.111],
        ]
    )

    z_expected = np.array([6.0, 8, 6, 8, 6, 8, 6, 8])

    with btt.BlenderLauncher(**launch_args) as bl:
        addr = bl.launch_info.addresses["DATA"]
        ds = btt.RemoteIterableDataset(addr, max_items=2)
        item = next(iter(ds))
        assert_allclose(item["ortho_xy"], ortho_xy_expected, atol=1e-2)
        assert_allclose(item["ortho_z"], z_expected, atol=1e-2)
        assert_allclose(item["proj_xy"], proj_xy_expected, atol=1e-2)
        assert_allclose(item["proj_z"], z_expected, atol=1e-2)


import tkinter as tk
from tkinter import ttk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter import scrolledtext
import pandas as pd
from src.main import diagnose
import time

def processData(event=None):
    if finished:
        return
    beforeStart.after(0, beforeStart.destroy())
    userInput = e1.get()
    chat.insert(END, '(You):\n', '(You)')
    chat.insert(END, userInput, 'yourword')
    chat.insert(END, '\n')
    chat.see(tk.END)
    checkingSymptoms()
    e1.delete(0, END)

def AISolution():
    global finished
    finished = True
    result = diagnose(record)
    chat.insert(END, 'Doc:\n', 'Doc')
    chat.insert(END, "Ok. It seems you've got " + str(result), 'Docword')
    chat.insert(END, '\n')
    chat.see(tk.END)
    return

def checkingSymptoms():
    if finished:
        return
    global loc
    for i in range(len(record)):
        if record[i] == -1:
            chat.insert(END, 'Doc:\n', 'Doc')
            chat.insert(END, "Got it, did you feel " + symptoms[i] + " recently?", 'Docword')
            chat.insert(END, '\n')
            chat.see(tk.END)
            YesButton = ttk.Button(gui, text="Yes I have that feeling", bootstyle=SUCCESS, command=makeTrue)
            YesButton.place(x=100, y=415)
            NoButton = ttk.Button(gui, text="No, I don't have that feeling", bootstyle=FLAT, command=makeFalse)
            NoButton.place(x=250, y=415)
            loc = i
            return
    AISolution()

def makeTrue():
    if finished:
        return
    chat.insert(END, '(You):\n', '(You)')
    chat.insert(END, "Yes I have that feeling", 'yourword')
    chat.insert(END, '\n')
    chat.see(tk.END)
    record[loc] = 1
    checkingSymptoms()
def makeFalse():
    if finished:
        return
    chat.insert(END, '(You):\n', '(You)')
    chat.insert(END, "No, I don't have that feeling", 'yourword')
    chat.insert(END, '\n')
    chat.see(tk.END)
    record[loc] = 0
    checkingSymptoms()

symptoms = ['arm pain', 'back pain', 'leg pain', 'ankle pain', 'inner thigh pain', 'back thigh pain', 'shoulder pain', 'tendon pain', 'swelling','headache', 'weakness', 'stiffness', 'difficulty moving/straightening ','nausea', 'bruising ', 'tenderness', 'numbness','difficulty putting weight on', 'dizziness or blurry vision', 'spasms','elbow pain', 'difficulty balancing ', 'light and sound irritation',' Trouble controlling bowels or bladder', 'injury']
record = []
cur = 0
loc = 0
finished = False
for _ in symptoms:
    record.append(-1)
print(symptoms)
print(record)
print(len(symptoms))
print(len(record))
gui = tk.Tk()
gui.title('HealAI')
gui.geometry("500x500")
style = ttk.Style("minty")

e1 = tk.Entry(gui, width=50)
e1.insert(0, "")

e1.grid(row=0, column=1)
e1.place(x=115, y=455)

quitButton = ttk.Button(gui, text="End Chat", bootstyle=(INFO, OUTLINE), command=gui.quit)
quitButton.place(x=25, y=450)

sentButton = ttk.Button(gui, text="|>", bootstyle=(SUCCESS, OUTLINE), command=processData)
sentButton.place(x=440, y=450)

chat = scrolledtext.ScrolledText(gui, height=24, width=70)
chat.place(x=0, y=0)
chat.tag_config('(You)', foreground='blue')
chat.tag_config('yourword', foreground='grey')
chat.tag_config('Doc', foreground='green')
chat.tag_config('Docword', foreground='black')

beforeStart = tk.Label(gui, text="Please describe your symptom below:")
beforeStart.place(x=120, y=425)

gui.bind('<Return>', processData)

gui.mainloop()


import click
from lirc.exceptions import LircdCommandFailureError

from stb.remote import Remote
from stb.utils import get_config_file

@click.command(short_help="Send IR signals")
@click.argument("key", required=True)
@click.option("-r", "--remote", default=None, help="The remote to press keys on.")
def press(key, remote):
    """
    Simulate a button press by sending an IR signal
    """
    if not remote:
        remote = get_config_file().get("lirc.remote")

    try:
        Remote(remote).press(key)
        click.secho(f"Emitted {key} successfully", fg="green")
    except LircdCommandFailureError as error:
        click.secho(f"Error while trying to transmit {key}: ", fg="red")
        print(error)


"""Useful mixins for models."""
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import get_language

from hvad.models import NoTranslation, TranslationManager

class HvadPublishedManager(TranslationManager):
    """
    Returns all objects, which are published and in the currently
    active language if check_language is True (default).

    :param request: A Request instance.
    :param check_language: Option to disable language filtering.

    """
    def published(self, request, check_language=True):
        kwargs = {'translations__is_published': True}
        if check_language:
            language = getattr(request, 'LANGUAGE_CODE', get_language())
            if not language:
                self.model.objects.none()
            kwargs.update({'translations__language_code': language})
        return self.get_queryset().filter(**kwargs)

@python_2_unicode_compatible
class TranslationModelMixin(object):
    """Mixin to provide custom django-hvad overrides."""
    def __str__(self):
        return self.translation_getter('title')

    def check_for_result(self, language, translation, result, name):
        if not result:
            try:
                translation = self.translations.get(language_code=language)
            except ObjectDoesNotExist:
                pass
            else:  # pragma: nocover
                result = getattr(translation, name, '')
        return translation, result

    def translation_getter(self, name):
        """
        Custom translation getter.

        1. Try the current language
        2. Try base language (e.g. 'en' instead of 'en-gb')
        3. Try default sys language
        4. Use any translation

        """
        stuff = self.safe_translation_getter(name, NoTranslation)
        if stuff is not NoTranslation:
            return stuff

        translation = None
        result = None

        # Check for the current language
        translation, result = self.check_for_result(
            get_language(), translation, result, name)

        # Check for the current main language
        translation, result = self.check_for_result(
            get_language()[:2], translation, result, name)

        # Check for the default language
        translation, result = self.check_for_result(
            settings.LANGUAGE_CODE, translation, result, name)

        if not result:
            # Check for any available language
            for trans in self.translations.all():  # pragma: nocover
                translation = trans
                result = getattr(translation, name, '')
                if result:
                    break

        setattr(self, self._meta.translations_cache, translation)
        return result


import asyncio
import multiprocessing
import time as pytime
import traceback
from ctypes import c_bool
from datetime import datetime
from threading import Thread
from typing import List

from alpaca_trade_api import StreamConn

from tc2.account.data_stream.StreamUpdate import StreamUpdate
from tc2.account.data_stream.StreamUpdateType import StreamUpdateType
from tc2.data.data_structs.account_data.AccountInfo import AccountInfo
from tc2.data.data_structs.account_data.Order import Order
from tc2.data.data_structs.price_data.Candle import Candle
from tc2.log.LogFeed import LogFeed, LogLevel
from tc2.util.date_util import DATE_TIME_FORMAT

class AccountDataStream:
    """
    Connects to Alpaca and Polygon data streams and provides data access to AbstractAccount's.
    """

    # StreamConn from alpaca-trade-api library.
    alpaca_stream: StreamConn = None

    # Stream listener state (true until program is stopped).
    running = True

    # Thread-sharable list containing data updates.
    _livestream_updates: 'multiprocessing list' = None

    # Marker to know when to prune the updates list.
    _queue_initially_filled = multiprocessing.Value(c_bool, False)

    @classmethod
    def get_updates(cls,
                    livestream_updates: 'multiprocessing list') -> List[StreamUpdate]:
        return [StreamUpdate.from_json(update_json) for update_json in livestream_updates]

    @classmethod
    def connect_to_streams(cls,
                           symbols: List[str],
                           logfeed_data: LogFeed) -> None:
        """
        Starts a thread that listens for alpaca and polygon data streams.
        """

        # Initialize multi-threaded access to data updates.
        if cls._livestream_updates is not None:
            logfeed_data.log(LogLevel.ERROR, 'Tried to connect to account data streams twice!')
            print('Tried to connect to account data streams twice!')
            return
        cls._livestream_updates = multiprocessing.Manager().list()
        cls._queue_initially_filled = multiprocessing.Value(c_bool, False)

        # Define off-thread logic for handling stream messages.
        def init_streams():

            while cls.running:
                try:
                    # Create a new event loop for this thread.
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)

                    # From alpaca-trade-api.
                    cls.alpaca_stream = StreamConn(data_stream='polygon')

                    @cls.alpaca_stream.on(r'^trade_updates$')
                    async def on_trade_updates(conn, channel, data):
                        # logfeed_data.log(LogLevel.DEBUG, 'Alpaca raw trade update: {0}'.format(data))
                        try:
                            print('receiving order from ws')
                            order = Order.from_alpaca_api(data.order, logfeed_data)
                            if order is None:
                                logfeed_data.log(LogLevel.WARNING, 'Data stream could not decode an order. Ignoring it')
                                print('Data stream could not decode an order. Ignoring it')
                                cls._queue_update(moment=datetime.now(),
                                                  update_type=StreamUpdateType.STARTED_UP)
                            else:
                                cls._on_trade_update(order)
                        except Exception as e:
                            logfeed_data.log(LogLevel.ERROR, 'Error handling alpaca trade update:')
                            logfeed_data.log(LogLevel.WARNING, traceback.format_exc())
                            traceback.print_exc()

                    @cls.alpaca_stream.on(r'^account_updates$')
                    async def on_account_updates(conn, channel, msg):
                        logfeed_data.log(LogLevel.DEBUG, 'Alpaca raw account update: {0}'.format(msg))
                        print('Alpaca raw account update: {0}'.format(msg))
                        try:
                            print('receiving acct update from ws')
                            cls._on_account_update(msg, logfeed_data)
                        except Exception as e:
                            logfeed_data.log(LogLevel.ERROR, 'Error handling alpaca account update: ')
                            logfeed_data.log(LogLevel.WARNING, traceback.format_exc())
                            traceback.print_exc()

                    @cls.alpaca_stream.on(r'^status$')
                    async def on_status(conn, channel, msg):
                        try:
                            cls._on_status_update(msg.message, logfeed_data)
                        except Exception as e:
                            logfeed_data.log(LogLevel.ERROR, 'Error handling polygon status update:')
                            logfeed_data.log(LogLevel.WARNING, traceback.format_exc())
                            traceback.print_exc()

                    @cls.alpaca_stream.on(r'^A$')
                    async def on_second_bars(conn, channel, data):
                        # start_queue = pytime.monotonic()
                        try:
                            # print(str(data))
                            # print(f'is {data.start:%Y/%m/%d_%H:%M:%S}')
                            # print(f'at {datetime.now():%Y/%m/%d_%H:%M:%S}')
                            cls._on_data_update(data)
                        except Exception as e:
                            logfeed_data.log(LogLevel.ERROR, 'Error handling polygon candle update:')
                            logfeed_data.log(LogLevel.WARNING, traceback.format_exc())
                            traceback.print_exc()
                        # queue_time_ms = (pytime.monotonic() - start_queue) * 1000
                        # moment = datetime.strptime(data.start.strftime(DATE_TIME_FORMAT), DATE_TIME_FORMAT)
                        """
                        try:
                            if queue_time_ms > 80:
                                print(f'took {queue_time_ms:.0f}ms to queue {data.symbol} {moment:%M:%S} candle')
                            else:
                                print(f'queued {data.symbol} {moment:%M:%S} candle at {datetime.now():%M:%S}')
                        except Exception as e:
                            traceback.print_exc()
                        """

                    # Subscribe to alpaca and polygon streams
                    channels_to_stream = ['trade_updates', 'account_updates']
                    channels_to_stream.extend(f'A.{symbol}' for symbol in symbols)

                    logfeed_data.log(LogLevel.INFO, 'Subscribing to polygon and alpaca streams')
                    cls.alpaca_stream.run(channels_to_stream)
                except Exception as e:
                    logfeed_data.log(LogLevel.ERROR, 'Polygon and alpaca streams disconnected unexpectedly')
                    logfeed_data.log(LogLevel.WARNING, traceback.format_exc())
                    pytime.sleep(2)
                    logfeed_data.log(LogLevel.INFO, 'Attempting to re-connect data streams')

        # Connect to the streams in another thread
        cls.streams_thread = Thread(target=init_streams)
        cls.streams_thread.start()

    @classmethod
    def add_symbol(cls,
                   symbol: str) -> None:
        """Starts listening for data updates on the symbol, if not already listening."""
        cls.alpaca_stream.unsubscribe(f'A.{symbol}')
        cls.alpaca_stream.subscribe(f'A.{symbol}')

    @classmethod
    def remove_symbol(cls,
                      symbol: str) -> None:
        """Stops listening for data updates on the symbol."""
        cls.alpaca_stream.unsubscribe(f'A.{symbol}')

    @classmethod
    def shutdown(cls):
        """Unsubscribes to alpaca and polygon stream updates and closes the connection."""
        cls.running = False
        if cls.alpaca_stream is not None:
            async def close_task():
                await cls.alpaca_stream.close()

            asyncio.create_task(close_task)
        pytime.sleep(0.2)
        pytime.sleep(0.2)
        pytime.sleep(0.2)

    """
    Private methods...
    """

    @classmethod
    def _on_account_update(cls,
                           raw_msg,
                           logfeed_data: LogFeed) -> None:
        """
        Adds an update signal to the queues, which are processed by AbstractAccount's on other threads.
        """
        # Decode raw msg into json
        data = raw_msg.account

        # Check that the account is active
        if data['status'].lower() != 'active':
            logfeed_data.log(LogLevel.WARNING, 'Alpaca account status is "{0}"'.format(data['status']))
            logfeed_data.log(LogLevel.WARNING, 'Alpaca account status is "{0}"'.format(data['status']))

        # Convert account info json into an AccountInfo object
        acct_info = AccountInfo(data['id'], float(data['cash']), float(data['cash_withdrawable']))

        # Add the account update to the data queue
        cls._queue_update(moment=datetime.now(),
                          update_type=StreamUpdateType.ACCT_INFO,
                          acct_info=acct_info.to_json())

    @classmethod
    def _on_trade_update(cls,
                         order: Order) -> None:
        """
        Adds the updated order to the queues, which are processed by AbstractAccount's on other threads.
        """

        # Signal the running strategy to respond to this new order update
        cls._queue_update(moment=datetime.now(),
                          update_type=StreamUpdateType.ORDER,
                          symbol=order.symbol,
                          order=order.to_json())

    @classmethod
    def _on_data_update(cls,
                        data) -> None:
        """
        Adds the new candle to the queues, which are processed by AbstractAccount's on other threads.
        """

        # Get candle's symbol
        symbol = data.symbol

        # Get candle's pandas timestamp as a datetime
        moment = datetime.strptime(data.start.strftime(DATE_TIME_FORMAT), DATE_TIME_FORMAT)

        # Compile candle object
        candle = Candle(moment=moment,
                        open=data.open,
                        high=data.high,
                        low=data.low,
                        close=data.close,
                        volume=data.volume)

        # Signal the running strategy to respond to this new price data
        cls._queue_update(moment=moment,
                          update_type=StreamUpdateType.CANDLE,
                          symbol=symbol,
                          candle=candle.to_json())

    @classmethod
    def _on_status_update(cls,
                          event: str,
                          logfeed_data: LogFeed) -> None:
        """
        Logs messages received from alpaca.markets and polygon.io.
        """

        # Ignore uninteresting polygon status updates
        if event == 'Connecting to Polygon' or event == 'Connected Successfully':
            logfeed_data.log(LogLevel.DEBUG, event)
            try:
                cls._queue_update(moment=datetime.now(),
                                  update_type=StreamUpdateType.STARTED_UP)
            except Exception as e:
                logfeed_data.log(LogLevel.ERROR, 'Error queuing ws startup update:')
                logfeed_data.log(LogLevel.WARNING, traceback.format_exc())
                traceback.print_exc()

        # Log successful authentication with polygon websocket
        elif event == 'authenticated':
            logfeed_data.log(LogLevel.DEBUG,
                             'Successfully authenticated Polygon.io live stream (all channels unsubscribed)')

        # Log successful channel subscription messages
        elif event.startswith('subscribed to:'):
            logfeed_data.log(LogLevel.DEBUG,
                             'Subscribed to Polygon websocket channel: {0}'.format(event.split('to: ')[1]))

        # Log unrecognized polygon status updates
        else:
            logfeed_data.log(LogLevel.INFO, 'Unknown polygon.io status message: {0}'.format(event))

    @classmethod
    def _queue_update(cls,
                      moment: datetime,
                      update_type: StreamUpdateType,
                      acct_info: dict = None,
                      symbol: str = None,
                      candle: dict = None,
                      order: dict = None) -> None:
        """
        Adds an update to the stream's queue.
        """

        # Create a StreamUpdate object
        update = StreamUpdate(update_moment=moment,
                              update_type=update_type,
                              acct_info=acct_info,
                              symbol=symbol,
                              candle=candle,
                              order=order)

        # Add the update to the multi-threaded list
        cls._livestream_updates.append(update.to_json())

        # Prune the update queue
        if cls._queue_initially_filled.value and len(cls._livestream_updates) > 600:
            while len(cls._livestream_updates) > 500:
                cls._livestream_updates.pop(0)
        elif len(cls._livestream_updates) > 600:
            cls._queue_initially_filled.value = True


import numpy as np
import torch
from torchvision.utils import make_grid
from .base import BaseTrainer
from .utils import inf_loop, MetricTracker, load_state_dict, rename_parallel_state_dict, autocast, use_fp16

class Trainer(BaseTrainer):
    """
    Trainer class
    """
    def __init__(self, model, optimizer=None, data_loader=None, args=None, cls_num_list=None, training_exp=None):
        super().__init__(model, optimizer, args, cls_num_list)

        self.distill = False

        # add_extra_info will return info about individual experts. This is crucial for individual loss. If this is false, we can only get a final mean logits.
        self.add_extra_info = self.config._config.get('add_extra_info', False)
        if self.args.num_experts == 1:
            self.add_extra_info = False

        self.data_loader = data_loader
        self.len_epoch = len(self.data_loader)
        self.scaler = None

        # self.lr_scheduler = lr_scheduler
        self.log_step = int(np.sqrt(data_loader.batch_size))
        self.training_exp = training_exp
        self.device = args.gpu
        self.model = self.model.to(self.device)

    def _train_epoch(self, epoch):
        """
        Training logic for an epoch

        :param epoch: Integer, current training epoch.
        :return: A log that contains average loss and metric in this epoch.
        """

        self.model.train()

        if hasattr(self.criterion, "_hook_before_epoch"):
            self.criterion._hook_before_epoch(epoch)

        for batch_idx, data in enumerate(self.data_loader):
            if self.distill and len(data) == 4:
                data, target, idx, contrast_idx = data
            else:
                data, target = data

            data, target = data.to(self.device), target.to(self.device)

            self.optimizer.zero_grad()

            with autocast():
                if self.real_model.requires_target:
                    output = self.model(data, target=target)
                    output, loss = output
                else:
                    extra_info = {}
                    output = self.model(data)

                    if self.add_extra_info:
                        if isinstance(output, dict):
                            logits = output["logits"]
                            extra_info.update({
                                "logits": logits.transpose(0, 1)
                            })
                        else:
                            extra_info.update({
                                "logits": self.real_model.backbone.logits
                            })

                    if isinstance(output, dict):
                        output = output["output"]

                    # if self.distill:
                    #     loss = self.criterion(student=output, target=target, teacher=teacher, extra_info=extra_info)
                    if self.add_extra_info and "ldae" in self.args.method:
                        loss = self.criterion(output_logits=output, target=target, extra_info=extra_info, training_exp=self.training_exp, device=self.device)
                    else:
                        loss = self.criterion(output_logits=output, target=target)

            if not use_fp16:
                loss.backward()
                self.optimizer.step()
            else:
                self.scaler.scale(loss).backward()
                self.scaler.step(self.optimizer)
                self.scaler.update()

        return

    def _valid_epoch(self, epoch):
        """
        Validate after training an epoch

        :param epoch: Integer, current training epoch.
        :return: A log that contains information about validation
        """
        self.model.eval()

        with torch.no_grad():
            if hasattr(self.model, "confidence_model") and self.model.confidence_model:
                cumulative_sample_num_experts = torch.zeros((self.model.backbone.num_experts, ), device=self.device)
                num_samples = 0
                confidence_model = True
            else:
                confidence_model = False
            for batch_idx, (data, target) in enumerate(self.valid_data_loader):
                data, target = data.to(self.device), target.to(self.device)

                if confidence_model:
                    output, sample_num_experts = self.model(data)
                    num, count = torch.unique(sample_num_experts, return_counts=True)
                    cumulative_sample_num_experts[num - 1] += count
                    num_samples += data.size(0)
                else:
                    output = self.model(data)
                if isinstance(output, dict):
                    output = output["output"]
                loss = self.criterion(output, target)

                self.writer.set_step((epoch - 1) * len(self.valid_data_loader) + batch_idx, 'valid')
                self.valid_metrics.update('loss', loss.item())
                for met in self.metric_ftns:
                    self.valid_metrics.update(met.__name__, met(output, target, return_length=True))
                self.writer.add_image('input', make_grid(data.cpu(), nrow=8, normalize=True))

            if confidence_model:
                print("Samples with num_experts:", *[('%.2f'%item) for item in (cumulative_sample_num_experts * 100 / num_samples).tolist()])

        # add histogram of model parameters to the tensorboard
        for name, p in self.model.named_parameters():
            self.writer.add_histogram(name, p, bins='auto')
        return self.valid_metrics.result()

    def _progress(self, batch_idx):
        base = '[{}/{} ({:.0f}%)]'
        if hasattr(self.data_loader, 'n_samples'):
            current = batch_idx * self.data_loader.batch_size
            total = self.data_loader.n_samples
        else:
            current = batch_idx
            total = self.len_epoch
        return base.format(current, total, 100.0 * current / total)

    def update_mode(self, model_para):
        self.model.load_state_dict(model_para)


##977. 有序数组的平方
# 给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。
# 示例 1：
# 输入：nums = [-4,-1,0,3,10]
# 输出：[0,1,9,16,100]
# 解释：平方后，数组变为 [16,1,0,9,100]
# 排序后，数组变为 [0,1,9,16,100]

class Solution:
    def sortedSquares(self, nums):
        i = 0
        n = len(nums)
        negative=-1
        for i in range(n):
            if nums[i]<0:
                negative =i
        positive = negative+1
        res=[]
        while negative >=0 or positive<=n-1:
            if negative <0:
                res.append(nums[positive]*nums[positive])
                positive+=1
            elif positive>=n:
                res.append(nums[negative]*nums[negative])
                negative-=1
            elif nums[positive]*nums[positive] <= nums[negative]*nums[negative]:
                res.append(nums[positive]*nums[positive])
                positive+=1
            else:
                res.append(nums[negative]*nums[negative])
                negative-=1
        return res

s=Solution()
print(s.sortedSquares([-1]))


def main():
    with open("rucksack.txt", "r") as f:
        lines = f.readlines()
        rucksacks = [i.strip() for i in lines]
    sum=0
    while len(rucksacks)>0:
        sackOne = set(rucksacks.pop())
        sackTwo = set(rucksacks.pop())
        sackThree = set(rucksacks.pop())
        olChar= (sackOne.intersection(sackTwo)).intersection(sackThree).pop()

        if olChar.isupper()==True:
            sum+=ord(olChar)-ord("A")+27
        else:
            sum+=ord(olChar)-ord("a")+1
    print(sum)
main()


"""
This work is licensed under the terms of the MIT license.
For a copy, see <https://opensource.org/licenses/MIT>.

Developed by NISLAB - Network and Information Security Laboratory
at George Emil Palade University of Medicine, Pharmacy, Science and
Technology of Târgu Mureş <https://nislab.umfst.ro/>

Contributors: Roland Bolboaca
"""

#!/usr/bin/env python3

## Listener Types ##
# 0 - Messages won't be printed on screen or written to file
# 1 - Messages will be written to a LOG file
# 2 - Messages will be written to a ASC file
# 3 - Messages will be also written to a BLF file

## Sending Types ##
# 0 - Read from file and send.
# 1 - Send Test Message

## Demo Sending only
# 2 - Send DM1 message (DEMO)

## Sending Delay ##
# Expressed in seconds

LOG_FILE = "/var/log/diasfw/dfw.log"
PIPE_PATH = "/tmp/canfw_pipe"
LISTENER_TYPE = 0

# Not used
#SENDING_DELAY = 0.2
#SENDING_TYPE = 0

# Not used
#SENDING_DEMO = 1
#SENDING_DELAY_DM1 = 1

# The module listens for frames on the REC channel and forwards them to the SEND channel.
#CAN_CHANNEL_SEND = 'vcan0'
CAN_CHANNEL_REC = 'vcan0'

# Internal Logging
LOGFILE = "/var/log/diasfw/pycan.log"
LOGLEVEL = "DEBUG"


from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import logging
import time
import argparse
import json
import datetime
from pyspectator.processor import Cpu
from time import sleep
cpu = Cpu(monitoring_latency=1)

awaitingResponse = False

AllowedActions = ['both', 'publish', 'subscribe']

# Custom MQTT message callback
def customCallback(client, userdata, message):
    global awaitingResponse
    print("Received a new message: ")
    print(message.payload)
    print("from topic: ")
    print(message.topic)
    print("--------------\n\n")
    # If the message did not come from our own, we set the awaitResponse flag
    if (message.topic != subscribeTopic + '/' + clientId):
        awaitingResponse = True

# Read in command-line parameters
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint")
parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path")
parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path")
parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path")
parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override")
parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False,
                    help="Use MQTT over WebSocket")
parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicPubSub",
                    help="Targeted client id")
parser.add_argument("-t", "--topic", action="store", dest="topic", default="sdk/test/Python", help="Targeted topic")
parser.add_argument("-s", "--subscribetopic", action="store", dest="subscribeTopic", default="room/public/", help="Targeted topic")
parser.add_argument("-m", "--mode", action="store", dest="mode", default="both",
                    help="Operation modes: %s"%str(AllowedActions))
parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!",
                    help="Message to publish")

args = parser.parse_args()
host = args.host
rootCAPath = args.rootCAPath
certificatePath = args.certificatePath
privateKeyPath = args.privateKeyPath
port = args.port
useWebsocket = args.useWebsocket
clientId = args.clientId
topic = args.topic
subscribeTopic = args.subscribeTopic

if args.mode not in AllowedActions:
    parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions)))
    exit(2)

if args.useWebsocket and args.certificatePath and args.privateKeyPath:
    parser.error("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.")
    exit(2)

if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath):
    parser.error("Missing credentials for authentication.")
    exit(2)

# Port defaults
if args.useWebsocket and not args.port:  # When no port override for WebSocket, default to 443
    port = 443
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883

# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
if useWebsocket:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
if args.mode == 'both' or args.mode == 'subscribe':
    myAWSIoTMQTTClient.subscribe(subscribeTopic + '/+', 1, customCallback)
time.sleep(2)

# Publish to the same topic in a loop forever
loopCount = 0
while True:

    # If we are awaiting a response, the means we got a message, return some useless result.
    if awaitingResponse:
        awaitingResponse = False
        message = {}

        returnSelector = int(time.time()) % 15
        if returnSelector == 1:
            message['message'] = "What do you mean?"
        elif returnSelector == 2:
            message['message'] = "Don't think I understand what you mean"
        elif returnSelector == 3:
            message['message'] = "Could you repeat that question?"
        elif returnSelector == 4:
            message['message'] = "Machine says YeS!"
        elif returnSelector == 5:
            message['message'] = "Can you ask this to someone else? I have no idea"
        elif returnSelector == 6:
            message['message'] = "At your service"
        elif returnSelector == 7:
            message['message'] = "The Moon is an astronomical body that orbits planet Earth and is Earth's only permanent natural satellite. "
        elif returnSelector == 8:
            message['message'] = "I cannot make any cat sounds"
        elif returnSelector == 9:
            message['message'] = "Are you sure?"
        elif returnSelector == 10:
            message['message'] = "The Sind sparrow (Passer pyrrhonotus) is a bird of the sparrow family, Passeridae, found around the Indus valley region in South Asia. "
        elif returnSelector == 11:
            message['message'] = "Mmmmm..."
        elif returnSelector == 12:
            message['message'] = "Don't think that is possible"
        elif returnSelector == 13:
            message['message'] = "Computer software, or simply software, is a generic term that refers to a collection of data or computer instructions that tell the computer how to work, in contrast to the physical hardware from which the system is built, that actually performs the work"
        else:
            message['message'] = "yeah, sure!"

        message['sequence'] = loopCount
        messageJson = json.dumps(message)

        # Publish to the topic
        myAWSIoTMQTTClient.publish(subscribeTopic + '/' + clientId, messageJson, 1)

        # Log this
        print('Published topic %s: %s' % (subscribeTopic + '/' + clientId, messageJson))

    if ((loopCount % 10) == 0) and loopCount < 1000:
        if args.mode == 'both' or args.mode == 'publish':
            # Send our CPU usage
            message = {}
            message['message'] = str(datetime.datetime.now()) + ": The CPU load of client " + clientId + " is " + str(cpu.load)
            message['sequence'] = loopCount
            messageJson = json.dumps(message)
            myAWSIoTMQTTClient.publish(topic, messageJson, 1)

            print('Published topic %s: %s' % (topic, messageJson))

    loopCount +=1
    time.sleep(1)


import numpy as np
import cv2
import time
import win32gui, win32ui, win32con, win32api, win32com.client
import pytesseract as tes
import KAW.Utils as Utils
import KAW.Button as Button
from pyautogui import press, typewrite, hotkey
from Scratch.keypress import PressKey, ReleaseKey

player_1 = np.asarray([0, 130, 90])  # white!
player_2 = np.asarray([0, 255, 255])  # yellow! note the order

ball_1 = np.asarray([50, 170, 0])  # white!
ball_2 = np.asarray([255, 255, 255])  # yellow! note the order

RIGHT = 0x27
LEFT = 0x25
SPACE = 0x20
A = 0x41
D = 0x44

def draw_contours(img):
    try:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        # print(img[30][40])
        mask = cv2.inRange(img, ball_1, ball_2)
        ret, thresh = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        mask = cv2.inRange(img, player_1, player_2)
        ret, thresh = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
        contours1, hierarchy1 = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        height, width, _ = img.shape
        min_x, min_y = width, height
        max_x = max_y = 0
        for contour, hier in zip(contours, hierarchy):
            (x, y, w, h) = cv2.boundingRect(contour)
            min_x, max_x = min(x, min_x), max(x + w, max_x)
            min_y, max_y = min(y, min_y), max(y + h, max_y)
            if w > 80 and h > 80:
                cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255), 3)
        if max_x - min_x > 0 and max_y - min_y > 0:
            cv2.rectangle(img, (min_x, min_y), (max_x, max_y), (255, 255, 0), 2)

        height, width, _ = img.shape
        min_x, min_y = width, height
        max_x = max_y = 0
        for contour, hier in zip(contours1, hierarchy1):
            (x, y, w, h) = cv2.boundingRect(contour)
            min_x, max_x = min(x, min_x), max(x + w, max_x)
            min_y, max_y = min(y, min_y), max(y + h, max_y)
            if w > 80 and h > 80:
                cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255), 3)
        if max_x - min_x > 0 and max_y - min_y > 0:
            cv2.rectangle(img, (min_x, min_y), (max_x, max_y), (255, 255, 0), 2)
        # img = cv2.drawContours(img, contours, -1, (255, 255, 255), 10)
        return img
    except TypeError:
        return cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

def custom_get_positions(region=None):
    hwin = Utils.getFireFox()
    if region:
        left, top, x2, y2 = region
        width = x2 - left + 1
        height = y2 - top + 1
    else:
        width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
        height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
        left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
        top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)

    signedIntsArray = bmp.GetBitmapBits(True)
    img = np.fromstring(signedIntsArray, dtype='uint8')
    img.shape = (height, width, 4)

    srcdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwin, hwindc)
    win32gui.DeleteObject(bmp.GetHandle())
    return img

def get_player_pos_x(img):
    try:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(img, player_1, player_2)
        ret, thresh = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        x, y, w, h = cv2.boundingRect(contours[0])
        return x + (w * .5)
    except IndexError:
        print("cant find!!!")
        return 500

def get_ball_pos_x(img):
    try:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(img, ball_1, ball_2)
        ret, thresh = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        x, y, w, h = cv2.boundingRect(contours[0])
        return x + (w * .5)
    except IndexError:
        print("cant find!!!")
        return 500

def process_img(image):
    original_image = image
    # convert to gray
    processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # edge detection
    # processed_img = cv2.Canny(image, threshold1=100, threshold2=500)
    # processed_img = image
    return processed_img

def getColumn(image):
    black_pixels_mask = np.all(image == [0, 0, 0], axis=-1)

def releaseKeys():
    ReleaseKey(SPACE)
    ReleaseKey(LEFT)
    ReleaseKey(RIGHT)

def main():
    keypressed = SPACE
    timesin = 0
    while True:
        # screen = grab_screen(region=(20, 40, 1900, 900))
        # ns = cv2.rectangle(screen, (170, 182), (123, 200), (0, 0, 255), 2)
        # img = cv2.cvtColor(ns, cv2.COLOR_BGR2GRAY)
        # cv2.imshow('window', img)
        current_window = win32gui.GetForegroundWindow()
        start = time.time()
        img = custom_get_positions(region=(383, 157, 1530, 1025))
        if (current_window == Utils.getFireFox()):
            ball_x = get_ball_pos_x(img)
            player_x = get_player_pos_x(img)
            newimg = draw_contours(img)
            newimg = cv2.resize(newimg, (1300, 700))
            cv2.imshow('window', newimg)
            if (ball_x + 28 > player_x and ball_x - 28 < player_x):
                PressKey(SPACE)
            else:
                if (player_x > ball_x):
                    PressKey(LEFT)
                    PressKey(SPACE)
                elif (player_x < ball_x):
                    PressKey(RIGHT)
                    PressKey(SPACE)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
    time.sleep(12)

main()


def solution(n, words):
    answer = []
    list_w = [[] for _ in range(n)]
    k = 0
    dup = {x for x in words if words.count(x) > 1}
    dup = list(dup)
    dic = {}

    for i in range(len(words) // n):
        for j in range(n):
            list_w[j].append(words[k])
            k += 1
    if len(words) != k:
        for i in range(len(words) - k):
            list_w[i].append(words[k])
            k += 1

    for i in range(len(words) - 1):
        if words[i][-1] != words[i + 1][0]:
            for j in range(n):
                if words[i + 1] in list_w[j]:
                    answer.append(j + 1)
                    answer.append(list_w[j].index(words[i + 1]) + 1)

    if len(answer) == 0:
        if len(dup) == 0:
            answer.append(0)
            answer.append(0)
        else:
            for i in range(n):
                if dup[0] in list_w[i]:
                    dic[i] = list_w[i].index(dup[0])
            answer.append(max(dic) + 1)
            answer.append(dic[max(dic)] + 1)

    return answer


from matplotlib import pyplot as plt
from skimage.io import imread
import numpy as np

def line_curve():
    H = np.hstack((x ** 2, x, ones))
    return H

image = imread(r"image8.png",as_gray=True)

mean = image.mean()
print(mean)

filter_image = image > mean

x = []
y = []

j = 0

#print(filter_image)
for row in filter_image:
    i = 0
    j += 1
    for colomn in row:
        i += 1
        if not(colomn):
            x.append(i)
            y.append(j) # len(row)-i)

x = np.array(x).reshape((len(x),1))
y = np.array(y).reshape((len(y), 1))

ones = np.ones(len(x)).reshape((len(x), 1))

H = line_curve()

abc1 = np.linalg.inv(np.dot(H.T,H))
abc2 = np.dot(H.T,y)

abc = np.dot(abc1,abc2)
print(abc)
yhat = np.dot(H,abc)
#print(x)
#print(len(yhat))
for i in range(0,len(yhat),500):
    #print(i)
    plt.plot(x,yhat,'w.')

plt.imshow(filter_image)
plt.show()


"""
lc link: https://leetcode.com/problems/valid-word-abbreviation/

another commonly asked question in meta interview

the pattern is really similar to the greedy solution for wildcard matching
see code for confluent preparation, link to the optimal solution:
https://leetcode.com/problems/wildcard-matching/discuss/17810/Linear-runtime-and-constant-space-solution

use state (i, j) to represent pointer in word and abbr respecitvely
(1) when j is a number, advance j
(2) when number > 0, advance i to match (here the number is the wildcard)
(3) when number = 0, advance i and j
(4) in the end we should match the rest of word with wildcard, and both word and abbr
should be fully consumed.
"""

class Solution:
    def validWordAbbreviation(self, word: str, abbr: str) -> bool:
        m, n = len(word), len(abbr)
        num = 0
        i, j = 0, 0
        while i < m or j < n:
            if j < n and abbr[j].isdigit():
                # handles leading zero and replacing empty string case
                if num == 0 and int(abbr[j]) == 0:
                    return False
                num = num * 10 + int(abbr[j])
                j += 1
            elif num > 0:
                # prevents timeout for big test cases
                if num > m - i + 1:
                    return False
                i += 1
                num -= 1
            elif i < m and j < n and word[i] == abbr[j]:
                i += 1
                j += 1
            else:
                # no match, and no abbreviation
                return False
        # match with remaining chars if possible
        while num > 0:
            i += 1
            num -= 1
        return i == m and j == n


from bst import BinarySearchTree
from bintree import BinaryNode

def get_smallest_ite(tree: BinarySearchTree) -> int:
    """returns the smallest element in input_tree. O(log n)"""
    result = None
    if tree is None:
        print("Tree is None!!!")
    else:
        node = tree.root
        if node is None:
            print("the root is None")
        else:
            while node.left:
                node = node.left
            result = node.elem
    return result

def get_greatest_ite(tree: BinarySearchTree) -> int:
    """returns the greatest element in input_tree. O(log n)"""
    result = None
    if tree is None:
        print("Tree is None!!!")
    else:
        node = tree.root
        if node is None:
            print("the root is None")
        else:
            while node.right:
                node = node.right
            result = node.elem
    return result

def get_smallest_rec(tree: BinarySearchTree) -> int:
    """returns the smallest element in input_tree"""
    result = None
    if tree is None:
        print("Tree is None!!!")
    else:
        result = _get_smallest_rec(tree.root)
    return result

def _get_smallest_rec(node: BinaryNode) -> int or None:
    result = None
    if node is not None:
        if node.left:
            result = _get_smallest_rec(node.left)
        else:
            return node.elem
    return result

def sum_elements(tree: BinarySearchTree) -> int:
    """returns the sum of the elements. O(n)"""
    result = None
    if tree is None:
        print("input_tree is None!!!")
    else:
        elements = tree.inorder_list()
        result = sum(elements)
    return result

def sum_elements_rec(tree: BinarySearchTree) -> int:
    """returns the sum of the elements. O(n)"""
    result = None
    if tree is None:
        print("input_tree is None!!!")
    else:
        result = _sum_elements_rec(tree.root)
    return result

def _sum_elements_rec(node: BinaryNode) -> int or None:
    """returns the sum of all elements in the subtree node"""
    result = 0
    if node is not None:
        result = node.elem + _sum_elements_rec(node.left) + _sum_elements_rec(node.right)
    return result

def array2bst(input_list: list) -> BinarySearchTree:
    """ gets a sorted list and creates a balanced bst"""
    result = BinarySearchTree()
    if input_list and len(input_list) >= 1:
        _array2bst(input_list, 0, len(input_list) - 1, result)
    return result

def _array2bst(input_list: list, start: int, end: int,
               tree: BinarySearchTree) -> None:
    if start <= end:
        index_mid = (start + end) // 2
        tree.insert(input_list[index_mid])
        _array2bst(input_list, start, index_mid - 1, tree)
        _array2bst(input_list, index_mid + 1, end, tree)

def _array2bst2(input_list: list, tree: BinarySearchTree) -> None:
    if len(input_list) > 0:
        index_mid = len(input_list) // 2
        tree.insert(input_list[index_mid])

        _array2bst2(input_list[:index_mid], tree)
        _array2bst2(input_list[index_mid + 1:], tree)

if __name__ == "__main__":
    input_tree = BinarySearchTree()
    values = [25, 20, 36, 10, 22, 30, 40, 5, 12, 28, 38, 48]
    for x in values:
        input_tree.insert(x)
    input_tree.draw()

    print("Smallest element: ", get_smallest_ite(input_tree))
    assert get_smallest_ite(input_tree) == min(values)

    print("Smallest element: ", get_smallest_rec(input_tree))
    tree_empty = BinarySearchTree()
    print("Smallest element: ", get_smallest_rec(tree_empty))
    assert get_smallest_rec(input_tree) == min(values)

    print("Greatest element: ", get_greatest_ite(tree_empty))
    print("Greatest element: ", get_greatest_ite(input_tree))
    assert get_greatest_ite(input_tree) == max(values)

    # Test array2bst
    l_values = [1, 2, 3, 4, 5, 6, 7]
    print(l_values)
    tree1 = array2bst(l_values)
    tree1.draw()
    data = [4, 2, 6, 1, 3, 5, 7]
    tree2 = BinarySearchTree()
    for x in data:
        tree2.insert(x)
    assert tree1 == tree2


#!/usr/bin/python

from __future__ import print_function
import libvirt
import sched, time
import os
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

CONFIG_FILE = '../vmlist.conf'

global conn
global vmlist
global vmobjlist
global s
global memoryinfolist

# s = sched.scheduler(time.time, time.sleep)

class UpdateGraph(object):
    def __init__(self, ax, conn, vmlist, memoryinfolist, vmobjlist, machine_to_graph):
        self.success = 0
        self.memoryinfolist = memoryinfolist
        self.vmobjlist = vmobjlist
        self.line, = ax.plot([], [], 'k-')
        self.line2, = ax.plot([], [], 'g-')
        self.ax = ax

        # Set up plot parameters
        minutes = 2
        self.ax.set_xlim(0, 60 * minutes) #2 minutes
        self.ax.set_ylim(0, 3000) #2 gb = 3000
        self.ax.grid(True)
        self.xset = []
        self.yset = []
        self.yset_used = []
        self.machine_to_graph = machine_to_graph

    def init(self):
        self.success = 0
        self.line.set_data([], [])
        self.line2.set_data([], [])
        return self.line,

    def __call__(self, x):
        # This way the plot can continuously run and we just keep
        # watching new realizations of the process
        if x == 0:
            return self.init()

        for i, vmobj in enumerate(self.vmobjlist):
            memoryinfolist[i] = vmobj.memoryStats()

            actual = memoryinfolist[i]['actual'] / 1024.0
            unused = memoryinfolist[i]['unused'] / 1024.0
            used  = actual - unused

            if i == self.machine_to_graph:
                print("Ploting {} {}".format(x, actual))
                self.xset.append(x)
                self.yset.append(actual)
                self.yset_used.append(used)
                self.line.set_data(self.xset, self.yset)
                self.line2.set_data(self.xset, self.yset_used)

            print("{}: {} {}"
                .format(vmlist[i],
                        actual,
                        unused))

        print('-' * 80)

        st = os.popen('virsh nodememstats').read()
        print(st)
        print('-' * 80)

        return self.line, self.line2

def run(sc):
    for i in range(len(vmobjlist)):
        memoryinfolist[i] = vmobjlist[i].memoryStats()
        print("{}: {} {}"
            .format(vmlist[i],
                    memoryinfolist[i]['actual'] / 1024.0,
                    memoryinfolist[i]['unused'] / 1024.0))
    print('-' * 80)

    t = os.popen('virsh nodememstats').read()
    print(t)
    print('-' * 80)

    s.enter(2, 1, run, (sc,))

if __name__ == '__main__':
    conn = libvirt.open('qemu:///system')
    vmlist = open(CONFIG_FILE, 'r').read().strip().split()

    vmobjlist = []

    for vmname in vmlist:
        vm = conn.lookupByName(vmname)
        if vm:
            vmobjlist.append(vm)
        else:
            print('Unable to locate {}.'.format(vmnane))
            exit(-1)

    for vm in vmobjlist:
        vm.setMemoryStatsPeriod(1)

    memoryinfolist = [None] * len(vmobjlist)

    #TODO have a graph for each machine
    fig, ax = plt.subplots()
    ug = UpdateGraph(ax, conn, vmlist, memoryinfolist, vmobjlist, 0)
    anim = FuncAnimation(fig, ug, init_func=ug.init, interval=1000, blit=True)

    plt.show()

    # s.enter(2, 1, run, (s,))
    # s.run()


extend_offer = {
	"code": "extend_offer",
	"comment":"",
	"descr": '''Extend Offer''',
	"header": '''Extend Offer''',
	"componentType": "Task",
	"affordanceType":"Item",
	"optional": False,
	"enabled": True,
	"logEnabled": True,
	"freezable": True,
	"accessPermissions": ["dept_task","ofa_task"],
	"viewPermissions": ["dept_task","ofa_task"],
	"blockers": ["approve_offer"],
	"containers": [],
	"statusMsg": "Offer extended to candidate",
	"successMsg":"Extend Offer Complete",
	"className": "Submit",
	"config": {
		"dashboardEvents": [],

		"submitText": "Submit",
		"submitFreeze": {
			"freezeJobAction": False,
			"freezeSelf": False,
			"freezeAllPredecessors": False,
			"freezeTasks": [],
			"unfreezeJobAction": False,
			"unfreezeSelf": False,
			"unfreezeAllPredecessors": False,
			"unfreezeTasks": [],
			"setJobActionRevisionsRequired": False,
			"clearJobActionRevisionsRequired": False,
		},

		"date": True,
		"dateText": "Date Extended",
		"dateRequired": True,
		"prompts": [
			{
				"code": "approval_date",
				"label": "Date Extended",
				"enabled": True,
				"required": True,
				"data_type": "date",
				"date_format":"M/D/Y"
		}],
	},
}


from tkinter import *
from animator import *
from math import *
import paho.mqtt.client as mqtt
import threading

root = Tk()
logFrame = Frame(root)
logFrame.grid(column=0, row=0)
indicFrame = Frame(root)
indicFrame.grid(column=0, row=1)

indicadores = []
for i in range(7):
  l = Frame(indicFrame, bg="gray", width=100, height=20)
  l.grid(column=i, row=0)
  indicadores.append(l)

indic_atual = -1

canvasFrame = Frame(root)
canvasFrame.grid(column=0, row=2)
canv = Canvas(canvasFrame, width=700, height=600, bg="white")
canv.grid(column=0, row=0)

animator = Animator(canv, root)

lab = Label(logFrame,text="Ligue-4", font =("Comic Sans", 14))
lab.grid(row=0, column=0)

def thread_function(name):
  client.loop_forever()

def on_message(client, userdata, msg):
  msg.payload = msg.payload.decode("utf-8")
  print(msg.topic + " " + str(msg.payload) + "\n")
  data = str(msg.payload)
  tipo = data[0]
  slots = []
  nmbCol = 7
  nbmLin = 6
  if (tipo == 'J'):

    i = 1
    while (data[i] != ';'):
      actCol = (i - 1) % nmbCol
      actLin = floor((i - 1) / nmbCol)
      if (actCol == 0):
        slots.append([])
      if (data[i] == 'X'):
        slots[actLin].insert(actCol, SlotStates.P1)
      elif data[i] == 'O':
        slots[actLin].insert(actCol,SlotStates.P2)
      else:
        slots[actLin].insert(actCol,SlotStates.EMPTY)
      i += 1

    i += 1
    col = int(data[i])
    actualPlayer = SlotStates.EMPTY
    actualPlayerData = data[i + 1]

    if (actualPlayerData == 'X'):
      actualPlayer = SlotStates.P1
    elif (actualPlayerData == 'O'):
      actualPlayer = SlotStates.P2

    animator.drawCanvas(slots)
    endY = 0
    for i in range(5, -1, -1):
      if (slots[i][col] == SlotStates.EMPTY):
        slots[i].insert(col, actualPlayer)
        endY = i
        break
    animator.animatePlacement(col, endY, 600, actualPlayer)

    fill = ""

    if actualPlayer == SlotStates.P1:
      fill = "blue"
    else:
      fill = "red"

    for i in range(7):
      indicadores[i].config(bg='gray')
    indicadores[col].config(bg= fill)

  elif(tipo == 'F'):
    jogador = data[1]
    #T = Text(root=root, bg="grey", fg="black")
    if (jogador == '-'):

      lab.config(font =("Comic Sans", 14), text="EMPATE!! COMO?") # nao tem comic sans >:(
      lab.grid(column= 0, row=0)
    else:
      cor = "vermelho"
      if (jogador == 'O'):
        cor = "azul"

      #lab = Label(logFrame, text = "Jogador "+cor+" venceu!!")
      lab.config(font =("Comic Sans", 14), text = "Jogador "+cor+" venceu!!")
      lab.grid(column= 0, row=0)

  elif(tipo == 'C'):
    cob = int(data[1])
    c = data[2]

    fill = ""
    if c == 'O':
      fill = "blue"
    else:
      fill = "red"

    print(fill)
    for i in range(7):
      indicadores[i].config(bg='gray')
    indicadores[cob].config(bg=fill)

  elif(tipo == 'L'):
    #lab = Label(logFrame, text = "")
    lab.config(font =("Comic Sans", 14), text="Ligue-4")
    canv.delete('all')

    #lab.grid(column= 0, row=0)

def on_connect(client, userdata, flags, rc):
  print("CONECTADO (" + str(rc) + ")")

print("CONECTANDO")
client = mqtt.Client()
client.on_message = on_message
client.on_connect = on_connect
client.connect("broker.mqtt-dashboard.com", 1883, 60)
client.subscribe("PIC_LIGUE_4:JOGO")

x = threading.Thread(target=thread_function, args=(client,))
x.start()

root.mainloop()


import datetime
import json
import time
from datetime import datetime, timedelta
import time
from watchdog.events import FileSystemEventHandler

class Achievements(FileSystemEventHandler):
    checks = [
        ("minecraft:recipes/misc/charcoal", "has_log"),
        ("minecraft:story/iron_tools", "iron_pickaxe"),
        ("minecraft:story/enter_the_nether", "entered_nether"),
        ("minecraft:nether/find_bastion", "bastion"),
        ("minecraft:nether/find_fortress", "fortress"),
        ("minecraft:recipes/decorations/ender_chest", "has_ender_eye"),
        ("minecraft:story/follow_ender_eye", "in_stronghold"),
        ("minecraft:story/enter_the_end", "entered_end"),
    ]

    def __init__(self):
        self.startTime = None
        self.this_run = [None] * (len(self.checks) + 1)
        self.endTime = datetime.now()
        self.path = None
        self.pauses = 0

    def on_modified(self, event):
        self.path = event.src_path

    def checkAdvancements(self, igt):
        igt = igt / 20
        self.endTime = datetime.now()
        self.pauses += 1
        if self.startTime == None:
            # print("Setting start time")
            self.startTime = datetime.now() - timedelta(seconds=igt)

        try:
            achievements_file = open(self.path)
            achievements = json.load(achievements_file)
            achievements_file.close()
        except:
            print("Could not open achievements at, ", self.path)
            print("Will try again at next auto save/pause")
            time.sleep(0.1)
            self.checkAdvancements(igt)
            return

        if self.endTime < self.startTime:
            print("endTime was before startTime, setting endTime equal to start...")
            self.endTime = self.startTime

        self.this_run[0] = "0:" + str(
            time.strftime(
                "%M:%S",
                time.gmtime((self.endTime - self.startTime).total_seconds()),
            )
        )

        if igt != None:
            offset = (self.endTime - self.startTime).total_seconds() - (igt)
            for idx in range(len(self.checks)):
                if (
                    self.checks[idx][0] in achievements
                    and achievements[self.checks[idx][0]]["done"]
                    and self.this_run[idx + 1] == None
                ):
                    time_str = (
                        self.checks[idx][1],
                        achievements[self.checks[idx][0]]["criteria"][
                            self.checks[idx][1]
                        ],
                    )
                    time_str = time_str[1]
                    time_str = time_str[0:19]
                    time_timefmt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
                    seconds = (time_timefmt - self.startTime).total_seconds() - offset
                    if seconds < 0:
                        seconds = (time_timefmt - self.startTime).total_seconds()
                        print(
                            "IGT Offset was too high (likely couldn't load stats file) would've caused underflow, recovering using RTA"
                        )
                    self.this_run[idx + 1] = "0:" + str(
                        time.strftime("%M:%S", time.gmtime(seconds))
                    )

    def getRun(self):
        if self.this_run[0] == None:
            self.this_run[0] = "0:00:00"
        return self.this_run


#!/usr/bin/env python

#  2018 JHU CLSP (Aswin Shanmugam Subramanian)
#  Apache 2.0  (http://www.apache.org/licenses/LICENSE-2.0)

from load_data import save_list
import argparse

parser = argparse.ArgumentParser(description='Create REVERB list')
parser.add_argument('--data_dir', default='wav/REVERB_WSJCAM0_tr/data/mc_train',
                    help='Base directory of the REVERB challenge parallel simulation data.')
parser.add_argument('--dest_dir', default='data',
                    help='Base directory to store the list.')
args = parser.parse_args()

save_list(args.data_dir, args.dest_dir)


import psutil
import os
import platform
import socket
import wmi

class Grabber:
    def get_cpu_info()-> dict:
        data = {}
        data['cpu_cores'] = psutil.cpu_count()
        data['cpu_frequency']= psutil.cpu_freq().current
        data['cpu_usage'] = psutil.cpu_percent(interval=1, percpu=True)
        return data

    def get_ram_info() -> dict:
        data = {}
        data['ram_total'] = str((psutil.virtual_memory().total *1e-9))[:4] +" gb"
        data['ram_available'] = str((psutil.virtual_memory().available*1e-9))[:4] +" gb"
        data['ram_used'] = str((psutil.virtual_memory().used*1e-9))[:4] +" gb"
        data['ram_percent'] = psutil.virtual_memory().percent
        return data
    def get_disk_info() -> dict:
        disk_partitions = psutil.disk_partitions(all=False)
        disk_usage = {}

        for partition in disk_partitions:
            try:
                usage = psutil.disk_usage(partition.mountpoint)
                diskk = partition.device.removesuffix('\\')
                disk_usage[diskk] = {
                    'total': str((usage.total *1e-9))[:4] +" gb",
                    'used': str((usage.used *1e-9))[:4] +" gb",
                    'free': str((usage.free *1e-9))[:4]+" gb" ,
                    'percent': usage.percent
                }
            except PermissionError:
                continue
        return disk_usage

    def get_motherboard_info()-> dict:
        c = wmi.WMI()
        motherboard = c.Win32_BaseBoard()[0]

        data = {}
        data['motherboard_manufacturer'] = motherboard.Manufacturer
        data['motherboard_model'] = motherboard.Product
        data['motherboard_serial_number'] = motherboard.SerialNumber

        return data

    def get_screen_info()-> dict:
        c = wmi.WMI()
        screens = c.Win32_DesktopMonitor()

        screen_info = []
        for screen in screens:
            info = {}
            try:
                info['manufacturer'] = screen.Manufacturer
            except :
                info['manufacturer'] = "couldn't fetch that"

            info['model'] = screen.Caption
            info['screen_size'] = f"{screen.ScreenWidth}x{screen.ScreenHeight}"

            screen_info.append(info)

        return screen_info

    def get_os_info()-> dict:
        os_info = {}
        os_info['OS_system'] = platform.system()
        os_info['OS_release'] = platform.release()
        os_info['OS_version'] = platform.version()
        os_info['OS_architecture'] = platform.machine()

        return os_info

    def get_network_info()-> dict:
        network_info = {}
        network_info['hostname'] = socket.gethostname()
        network_info['ip_addresses'] = socket.gethostbyname_ex(socket.gethostname())[2]
        return network_info

    def get_gpu_info()-> dict:
        c = wmi.WMI(namespace='root\\CIMV2')
        gpus = c.Win32_VideoController()
        gpu_info = []
        for gpu in gpus:
            info = {
                'name': gpu.Name,
                'driver_version': gpu.DriverVersion,
                'memory': gpu.AdapterRAM,
                'status': gpu.Status
            }
            gpu_info.append(info)
        return gpu_info

    def get_running_processes() -> list:
        running_processes = []
        for process in psutil.process_iter(['pid', 'name']):
            running_processes.append({'pid': process.pid, 'name': process.name()})
        return running_processes

    def get_all() -> dict:
        data = {}
        data['cpu']         = Grabber.get_cpu_info()
        data['gpu']         = Grabber.get_gpu_info()
        data["os"]          = Grabber.get_os_info()
        data["screen"]      = Grabber.get_screen_info()
        data["disks"]       = Grabber.get_disk_info()
        data["ram"]         = Grabber.get_ram_info()
        data["motherboard"] = Grabber.get_motherboard_info()
        data['network']     = Grabber.get_network_info()
        data["running_processes"] = Grabber.get_running_processes()
        return data


import auth
import json
import re

class DeckHandler(auth.AuthObject):

    def retrieve_decks(self, username):
        if self.user_exists(username):
            cur = self.db.cursor()
            cur.execute("SELECT deck FROM users WHERE username = '%s';" % username)
            for row in cur.fetchall():
                deck = row[0]
                return deck
        return False

    def set_deck(self, username, new_deck_name, new_deck):
        if self.user_exists(username):
            cur = self.db.cursor()
            decks = self.retrieve_decks(username)
            if decks:
                decks = json.loads(decks)
            else:
                decks = {}
            if new_deck:
                decks[new_deck_name] = new_deck
            else:
                decks[new_deck_name] = []

            cur.execute("UPDATE users SET deck = '%s' WHERE username = '%s';" % (json.dumps(decks), username))

            self.db.commit()

            return True
        return False

    def del_deck(self, username, deck_name):
        cur = self.db.cursor()
        decks = self.retrieve_decks(username)

        decks = json.loads(decks)

        del decks[deck_name]

        cur.execute("UPDATE users SET deck = '%s' WHERE username = '%s';" % (json.dumps(decks), username))

        self.db.commit()

    def get_stats(self, username):
        cur = self.db.cursor()

        cur.execute("SELECT wins, losses FROM users WHERE username = '%s';" % username)

        for row in cur.fetchall():
            wins = row[0]
            losses = row[0]
            return {"wins": wins, "losses": losses}
        return False


import os
import stomp
import socket
import json
import logging
from evdev import InputDevice, list_devices, categorize, ecodes

logging.basicConfig(level=logging.DEBUG)

host = os.environ.get('STOMP_HOST', "localhost")
port = os.environ.get('STOMP_PORT', 61613)
client = os.environ.get('SUBSTATION_ID', "demo")
destination = os.environ.get('STOMP_TOPIC', '/topic/substations')
scanner = os.environ.get('SCANNER', '/dev/input/event0')

conn = stomp.Connection(host_and_ports=[(host, int(port))])

def find_input():
    devices = [InputDevice(fn) for fn in list_devices()]
    for dev in devices:
        print(dev.fn, dev.name, dev.phys)

def attach_scanner():
    return InputDevice(scanner)

def connect():
    try:
        print('Connecting as <%s> to <%s:%s>' % (client, host, port))
        conn.start()
        conn.connect()
        message = json.dumps({"client": client,
                              "command": "connection",
                              "value": "%s: Reporting for duty" % client})
        conn.send(body=message, destination=destination)
        return True

    except stomp.exception.ConnectFailedException:
        print('Unable to connect to Stomp server')
    except socket.error:
        print('Stomp unable to get a socket')

def sender(command, value):
    if value != "restart":
        print('Sending command <%s> value <%s> to server.\n' %
              (command, value, ))
        message = json.dumps({"client": client,
                              "command": command,
                              "value": value})
        try:
            conn.send(body=message, destination=destination)
        except stomp.exception.NotConnectedException:
            conn = connect()
            conn.send(body=message, destination=destination)
    return True

def read_input(dev):
    print("Reading from %s" % dev.name)
    scancodes = {
        # Scancode: ASCIICode
        0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8',
        10: u'9', 11: u'0', 12: u'-', 13: u'=', 14: u'BKSP', 15: u'TAB', 16: u'q', 17: u'w', 18: u'e', 19: u'r',
        20: u't', 21: u'y', 22: u'u', 23: u'i', 24: u'o', 25: u'p', 26: u'[', 27: u']', 28: u'CRLF', 29: u'LCTRL',
        30: u'a', 31: u's', 32: u'd', 33: u'f', 34: u'g', 35: u'h', 36: u'j', 37: u'k', 38: u'l', 39: u';',
        40: u'"', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'z', 45: u'x', 46: u'c', 47: u'v', 48: u'b', 49: u'n',
        50: u'm', 51: u',', 52: u'.', 53: u'/', 54: u'RSHFT', 56: u'LALT', 100: u'RALT'
    }

    capscodes = {
        0: None, 1: u'ESC', 2: u'!', 3: u'@', 4: u'#', 5: u'$', 6: u'%', 7: u'^', 8: u'&', 9: u'*',
        10: u'(', 11: u')', 12: u'_', 13: u'+', 14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R',
        20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'{', 27: u'}', 28: u'CRLF', 29: u'LCTRL',
        30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u':',
        40: u'\'', 41: u'~', 42: u'LSHFT', 43: u'|', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N',
        50: u'M', 51: u'<', 52: u'>', 53: u'?', 54: u'RSHFT', 56: u'LALT', 100: u'RALT'
    }
    # setup vars
    input_buffer = ''
    caps = False
    command = None
    value = None

    # grab that shit
    dev.grab()

    # loop
    for event in dev.read_loop():
        if event.type == ecodes.EV_KEY:
            # Save the event temporarily to introspect it
            data = categorize(event)
            if data.scancode == 42:
                if data.keystate == 1:
                    caps = True
                if data.keystate == 0:
                    caps = False
            if data.keystate == 1:  # Down events only
                if caps:
                    key_lookup = u'{}'.format(capscodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(
                        data.scancode)  # Lookup or return UNKNOWN:XX
                else:
                    key_lookup = u'{}'.format(scancodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(
                        data.scancode)  # Lookup or return UNKNOWN:XX
                if (data.scancode != 42) and (data.scancode != 28):
                    input_buffer += key_lookup  # Print it all out!
                if(data.scancode == 28):
                    if command is None:
                        command = input_buffer
                        value = None
                    else:
                        value = input_buffer
                        sender(command, value)
                        command = None
                        value = None
                    input_buffer = ''

try:
    find_input()
    connect()
    scanner = attach_scanner()
    read_input(scanner)
except KeyboardInterrupt:
    message = json.dumps({"client": client,
                          "command": "connection",
                          "value": "%s: Disconnected gracefully" % client})
    conn.send(body=message, destination=destination)
    conn.disconnect()
    print('\n\nKeyboard exception received. Exiting.')
    exit()