import sys, getopt
from configparser import ConfigParser
import requests
import time
import os
import json

def send_json(json_list):
    """
    This function will send the json to the server
    """
    print('Sending JSON to server...')
    config_object = ConfigParser()
    config_object.read("config.ini")
    api = config_object["API"]
    url = api["url"]
    headers = {'accept': 'application/json', 'X-Scope-OrgID': 'docker',  'Content-Type': 'application/json'}
    for record in json_list:
        data = json.dumps({"streams": [{"stream": {"Aplication": "Malware",
        "fecha_hora": record["Fecha y hora"],
        "alerta": record["Alerta/Anomalia"],
        "usuario": record["Usuario"],
        "IPOrigen": record["IPsource"],
        "IPDestino": record["IPdestination"],
        "Actividad": record["Actividad"],
        "Descripcion": record["Descripcion"],
        "Permisos": record["Permisos"]},
        "values":[[str(time.time_ns()), "{} {} {} -> {} {}".format(record["Fecha y hora"],
        record["Alerta/Anomalia"], record["IPsource"], record["IPdestination"],
        record["Descripcion"])]]}]}, indent = 4)
        r = requests.post(url, headers=headers, data=data)
    print('All logs sent.')

def suricata_jsonfylogs():
    """
    This function will convert all suricata logs to json using the eve.json file
    """
    print('Converting all suricata logs to JSON...')
    # log format: Fecha y hora, Alerta/Anomalia, Usuario, IPsource, IPdestination, Actividad, Descripcion, Permisos "signature"
    # "signature" is the desired field in the eve.json file
    json_list = []
    config_object = ConfigParser()
    config_object.read("config.ini")
    suricatapath = config_object["MAINPATH"]["suricata_path"]
    last_valid_line = config_object["LINE"]["last_line"]
    flag = False
    if(os.path.basename(suricatapath) == 'suricata1.log'):
        print('Suricata path is valid.')
        f = open(suricatapath, "r")
        line = f.readline()
        if(not config_object["LINE"]["last_line"] == 'Nothing'):
            while line:
                if (not line.find(last_valid_line) == -1):
                    flag = True
                    line = f.readline()
                    break
                line = f.readline()
        if(not flag):
            f.seek(0)
            line = f.readline()
        while line:
            if(not line.find('{') == -1):
                index = line.index('{')
                record = json.loads(line[index:])
                last_valid_line = line[0:index]
                print(last_valid_line)
                if(record['event_type'] == 'alert'):
                    json_list.append({"Fecha y hora": record['timestamp'],
                    "Alerta/Anomalia": record['event_type'], "Usuario": "Suricata",
                    "IPsource": record['src_ip'], "IPdestination": record['dest_ip'],
                    "Actividad": record['alert']['action'], "Descripcion": record['alert']['signature'], "Permisos": "None"})
            line = f.readline()
        if(not last_valid_line == 'Nothing'):
            config_object['LINE'] = {
                'last_line': last_valid_line
            }
            with open('config.ini', 'w') as conf:
                config_object.write(conf)
        f.close()

    with open('suricata.json', 'w') as f:
        json.dump(json_list, f, ensure_ascii=False, indent = 4)
    if(len(json_list) > 0):
        send_json(json_list)
    else:
        print("The log file is empty")

def checK_configfile(mode, arg):
    """
    This function will check if the config file exists and if it has the correct configuration
    """
    options = {'API': 'url', 'MAINPATH': 'suricata_path'}
    if(verify_configfile()):
        config_object = ConfigParser()
        config_object.read("config.ini")
        config_option = config_object[mode]
        if(config_option[options[mode]] != arg):
            print('Warning: Config file does not match with the config provided.')
            print('Changing configuration...')
            change_configfile(mode, arg)
            print('Configuration changed.')
    else:
        if not os.path.exists('config.ini'):
            print('Warning: Config file does not exist , creating a new file.')
            open('config.ini', 'w').close()
        config_object = ConfigParser()
        config_object.read("config.ini")
        config_object[mode] = {
            options[mode]: arg
        }
        with open('config.ini', 'w') as conf:
            config_object.write(conf)

def change_configfile(mode, new_option):
    """
    This function will change the path in the config file
    """
    options = {'API': 'url', 'MAINPATH': 'suricata_path'}
    config_object = ConfigParser()
    config_object.read("config.ini")
    config_object[mode] = {
        options[mode]: new_option
    }
    with open('config.ini', 'w') as conf:
        config_object.write(conf)

def verify_configfile():
    """
    This function will verify if the config file exists and if it has the path to the logs
    """
    exists = True
    if os.path.exists('config.ini'):
        config_file = ConfigParser()
        config_file.read('config.ini')
        sections = config_file.sections()
        if len(sections) == 0 or 'MAINPATH' not in sections or 'API' not in sections:
            exists = False
    else:
        print('Config file does not exist.')
        exists = False
    return exists

def main(argv):
    try:
        opts, args = getopt.getopt(argv,"ha:p:",["help","api=","path="])
    except getopt.GetoptError:
        print('Invalid arguments.')
        print('Usage: jsonfylogs.py [-a | --api]  [-p | --path <path>]')
        sys.exit(2)
    if len(opts) != 0:
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print('Usage: jsonfylogs.py [-a | --api]  [-p | --path <path>]')
                sys.exit()
            elif opt in ("-a", "--api"):
                # If this option is selected, is necesary to have in the config file the url of the api
                checK_configfile('API', arg)
            elif opt in ("-p", "--path"):
                # This option will be used to specify the path to the logs
                checK_configfile('MAINPATH', arg)
            else:
                print('Invalid arguments.')
                print('Usage: jsonfylogs.py [-a | --api]  [-p | --path <path>]')
                sys.exit(2)
    else:
        if os.path.exists('config.ini'):
            if(verify_configfile()):
                suricata_jsonfylogs()
            else:
                print('Configuration file is not valid.')
                print('Run the script with the -p and -a option and specify the path to the logs and the URL for the API.')
        else:
            print('Config file does not exist, run the script with the -p and -a option and specify the path to the logs.')
            print('Usage: jsonfylogs.py [-a | --api]  [-p | --path <path>]')
            sys.exit(2)

if __name__ == "__main__":
    main(sys.argv[1:])


from django.urls import path

from . import views

urlpatterns = [
    path('doMonitor', views.doMonitor, name='doMonitor'),
    path('registeredPi', views.registeredPi, name='registeredPi'),
    path('addResponseDevice', views.addResponseDevice, name='addResponseDevice'),
    path('addSensor', views.addSensor, name='addSensor'),
]


# https://www.acmicpc.net/problem/16724

# ===== 라이브러리 ===== #
from collections import Counter
import sys

# ===== 변수/상수 ===== #
input = sys.stdin.readline
LEFT, RIGHT, UP, DOWN = 'L', 'R', 'U', 'D'
dx = { 'L' : 0, 'R' : 0, 'U' : -1, 'D' : 1 }
dy = { 'L' : -1, 'R' : 1, 'U' : 0, 'D' : 0 }

# ===== 함수 ===== #
def find(target: int) -> int:
    if tree[target] == target: return target
    tree[target] = find(tree[target])
    return tree[target]

def union(u: int, v: int) -> None:
    u = find(u)
    v = find(v)
    if u != v: tree[u] = v

def xy_to_tree(x: int, y: int) -> int:
    return x * m + y

def union_area(x: int, y: int, c: str) -> None:
    tx, ty = x + dx[c], y + dy[c]
    if 0 <= tx < n and 0 <= ty < m:
        union(xy_to_tree(x, y), xy_to_tree(tx, ty))

# ===== 입력/초기화 ===== #
n, m = map(int, input().split())
arr = [list(input()) for _ in range(n)]
tree = [i for i in range(n * m)]

# ===== 메인 ===== #
for i in range(n):
    for j in range(m):
        union_area(i, j, arr[i][j])

for i in range(n * m):
    tree[i] = find(tree[i])

# ===== 출력 ===== #
print(len(Counter(tree)))


from . import TownLoader
from . import TTStreet
from toontown.suit import Suit

class TTTownLoader(TownLoader.TownLoader):

    def __init__(self, hood, parentFSM, doneEvent):
        TownLoader.TownLoader.__init__(self, hood, parentFSM, doneEvent)
        self.streetClass = TTStreet.TTStreet
        self.musicFile = 'phase_3.5/audio/bgm/TC_SZ.ogg'
        self.activityMusicFile = 'phase_3.5/audio/bgm/TC_SZ_activity.ogg'
        self.townStorageDNAFile = 'phase_5/dna/storage_TT_town.dna'

    def load(self, zoneId):
        TownLoader.TownLoader.load(self, zoneId)
        Suit.loadSuits(1)
        dnaFile = 'phase_5/dna/toontown_central_' + str(self.canonicalBranchZone) + '.dna'
        self.createHood(dnaFile)

    def unload(self):
        Suit.unloadSuits(1)
        TownLoader.TownLoader.unload(self)


import os
import configparser as cp

globals().update(os.environ)

frps_ini = cp.ConfigParser()
frps_ini.read('frps.ini', encoding='utf8')

for section in frps_ini.sections():
    for option in frps_ini.options(section):
        env_arg_str = f'{section}_{option}'.upper()
        if env_arg_str in globals():
            frps_ini[section][option] = eval(env_arg_str)

with open('frps.ini', 'w+', encoding='utf8') as ini_file:
    frps_ini.write(ini_file)


class Node:

    def __init__(self,value):
        self.value = value
        self.next = None
        self.previous = None

class LinkedList:

    def __init__(self,value = None):
        self.head = None
        self._size = 0
        if value:
            for i in value:
                self.__append__(i)

    def __append__(self,element):
        if self.head == None:
            self.head = Node(element)
        else:
            pointer = self.head
            while pointer.next != None:
                pointer = pointer.next
            pointer.next = Node(element)
            pointer2 = pointer.next
            pointer2.previous = pointer
        self._size += 1

    def iter(self):
        return self

    def __len__(self):
        return self._size

    def __str__(self):
        if self.head == None:
            return ''
        string = ''
        for i in range (len(self) -1):
            string += str(self[i])
            string += ','
        string += str(self[len(self) -1])
        return string

    def __repr__(self):
        if self.head == None:
            return 'LinkedList([])'
        string = 'LinkedList(['
        for i in range(len(self) -1):
            string += str(self[i])
            string += ','
        string += str(self[len(self) -1])
        string += '])'
        return string

    def __getitem__(self,index):
        pointer = self.head
        for x in range (index):
            if pointer != None:
                pointer = pointer.next
            else:
                raise IndexError("list index out of range")
        if pointer == None:
            raise IndexError("list index out of range")
        else:
            return pointer.value

    def __setitem__(self,index,element):
        pointer = self.head
        for x in range (index):
            if pointer != None:
                pointer = pointer.next
            else:
                raise IndexError("list index out of range")
        if pointer == None:
            raise IndexError("list index out of range")
        else:
            pointer.value = element

    def __indice__(self,value):
        pointer = self.head
        if pointer.value == value:
            return 0
        else:
            count = 1
            while pointer != None:
                pointer = pointer.next
                if pointer.value == value:
                    return count
                count += 1
            raise ValueError("LinkedList doesnt have this value")

    def __select__(self,index):
        if index == 0:
            self.head = self.head.next
            self._size -= 1
        pointer = self.head
        for i in range(index):
            pointer = pointer.next
        if pointer == None:
            raise IndexError('LinkedList index out of range')
        else:
            pointer2 = pointer.previous
            pointer3 = pointer.next
            pointer2.next = pointer3
            pointer3.previous = pointer2
            self._size -= 1
            return pointer
    def __insert__(self,index,value):
        if index == 0:
            pointer = self.head
            pointer.previous = Node(value)
            self.head = pointer.previous
            self.head.next = pointer
        else:
            pointer = self.head
            for i in range(index):
                if pointer != None:
                    pointer = pointer.next
                else:
                    raise IndexError('LinkedList index out of range')
            pointer2 = pointer.previous
            pointer3 = Node(value)
            pointer2.next = pointer3
            pointer3.previous = pointer2
            pointer.previous = pointer3
            pointer3.next = pointer

    def __concatenate__(self,self2):
        if self2.head != None:
            pointer = self.head
            for i in range(self._size -1):
                pointer = pointer.next
                if pointer == None:
                    raise IndexError('LinkedList index out of range')
            pointer2 = self2.head
            self._size += self2._size
            pointer2.previous = pointer
            pointer.next = pointer2
            self2.head = None
            self2.size = 0

class Pointer:
    def __init__(self,linkedList):
        self.linkedList = linkedList
        self.position = self.linkedList.head

    def __next__(self):
        self.position = self.position.next
        if self.position == None:
            raise StopIteration('List has ended')
        return self.position.value

    def iter(self):
        return self

class Line(LinkedList):

    def __select__(self):
        pointer = self.head
        pointer2 = pointer.next
        self.head = pointer2
        pointer2.previous = None
        self._size -= 1

    def __insert__(self):
        return None

class Stack(LinkedList):

    def __select__(self):
        pointer = self.head
        for i in range(self._size -1):
            pointer = pointer.next
        pointer2 = pointer.previous
        pointer = None
        pointer2.next = None
        self._size -= 1

    def __insert__(self):
        return None


import numpy as np
import matplotlib.pyplot as plt

#0. x
#1. y
#2. z
#3. xd
#4. yd
#5. zd
#6. rho11
#7. rho12
#8. rho13
#9. rho22
#10. rho23
#11. rho33
#12. rho_bar11
#13. rho_bar12
#14. rho_bar13
#15. rho_bar22
#16. rho_bar23
#17. rho_bar33
#18. rho11_im
#19. rho12_im
#20. rho13_im
#21. rho22_im
#22. rho23_im
#23. rho33_im
#24. rho_bar11_im
#25. rho_bar12_im
#26. rho_bar13_im
#27. rho_bar22_im
#28. rho_bar23_im
#29. rho_bar33_im
#30. N
#31. N_bar
#32. t

time=[]
rho11_av=[]
rho22_av=[]
rho33_av=[]
rho12_av=[]
rho13_av=[]
rho23_av=[]

rho11=[]
rho22=[]

for i in range(0,10000):
	data = np.loadtxt("/home/erickurquilla1999/Documents/physics/thesis/my_neutrino_program/my_neutrino_program/output/step_"+str(i)+".txt", unpack = True, skiprows=1)

	time.append(data[32][30])

	rho11_av.append(sum(data[6])/len(data[6]))
	rho22_av.append(sum(data[9])/len(data[9]))
	rho33_av.append(sum(data[11])/len(data[11]))

	rho12_amp=[]
	for i in range(0,len(data[7])):
		rho12_amp.append((data[7][i]**2+data[19][i]**2)**0.5)
	rho12_av.append(sum(rho12_amp)/len(rho12_amp))

	rho13_amp=[]
	for i in range(0,len(data[8])):
		rho13_amp.append((data[8][i]**2+data[20][i]**2)**0.5)
	rho13_av.append(sum(rho13_amp)/len(rho13_amp))

	rho23_amp=[]
	for i in range(0,len(data[10])):
		rho23_amp.append((data[10][i]**2+data[22][i]**2)**0.5)
	rho23_av.append(sum(rho23_amp)/len(rho23_amp))

plt.plot(time,rho11_av)
plt.plot(time,rho12_av)
plt.plot(time,rho13_av)
plt.plot(time,rho22_av)
plt.plot(time,rho23_av)
plt.plot(time,rho33_av)
plt.legend(["rho11_av","rho12_av","rho13_av","rho22_av","rho23_av","rho33_av"])
#plt.yscale("log")
plt.show()


import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")

filename = "abalone.data.txt"
# x and y coordinates, whitespace-separated
X = np.loadtxt( filename, delimiter=',', usecols=(2,4) )
model = 5.1 * X[:,0] ** 2

plt.scatter(X[:, 0],X[:, 1], marker = 'o', s=150, alpha = 0.5,label='Observed')
plt.scatter(X[:, 0],model,marker='.',color='blue',label=r'Model: W=5.1D$^2$ ')
plt.xlabel('D')
plt.ylabel('W')
plt.legend()

plt.savefig("abalone.png")


#
# @lc app=leetcode id=240 lang=python3
#
# [240] Search a 2D Matrix II
#

# @lc code=start
from typing import List

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m = len(matrix)
        n = len(matrix[0])

        r, c = 0, n - 1
        while r < m and c >= 0:
            if matrix[r][c] == target:
                return True
            if matrix[r][c] > target:
                c -= 1
            else:
                r += 1

        return False

# @lc code=end


# -*- coding: utf-8 *-*
import os
from PyQt4 import QtGui

from mqme.tileitem import TileItem
from mqme.config import Config

class TileSetPicture(QtGui.QLabel):

    def __init__(self, parent, picture_path, queue):
        super(TileSetPicture, self).__init__(parent)
        self._parent = parent
        self._queue = queue
        self._items = []
        self._base_pixmap = QtGui.QPixmap(picture_path)
        self.config = Config()
        self.current_file = self.config.current_file()
        path_elements = os.path.split(picture_path)
        self._base_name = os.path.splitext(
            path_elements[len(path_elements) - 1]
        )[0]
        if not 'tilesets' in self.current_file:
            self.current_file['tilesets'] = {}
        if not 'pathes' in self.current_file:
            self.current_file['pathes'] = {}
        self.current_file['pathes'][self._base_name] = picture_path
        if not self._base_name in self.current_file['tilesets']:
            self.current_file['tilesets'][self._base_name] = {}
        self._current_item = None

    def base_name(self):
        return self._base_name

    def pixmap(self):
        return self._base_pixmap

    def read_tilesets_config(self):
        self.current_file = self.config.current_file()
        tileset_dict = self.current_file['tilesets'][self._base_name]
        for tile_name, tile in tileset_dict.items():
            item = TileItem(self, self._queue,
                tile['crop_x'], tile['crop_y'],
                tile['crop_width'], tile['crop_height']
            )
            item.set_name(tile_name)
            item.show()
            self._items.append(item)

    def set_height(self, height):
        pixmap = self._base_pixmap.scaledToHeight(height)
        self.setGeometry(0, 0, pixmap.width(), pixmap.height())
        self.setPixmap(pixmap)
        for item in self._items:
            item.update_geometry()

    def mousePressEvent(self, event):
        self._current_item = TileItem(self, self._queue, event.x(), event.y())
        self._current_item.show()

    def mouseReleaseEvent(self, event):
        if self._current_item is not None:
            if self._current_item.real_width() == 1:
                self._current_item.hide()
            else:
                status = False
                while not status:
                    name, status = QtGui.QInputDialog.getText(
                        self._parent, 'Tile name', 'Name :'
                    )
                name = str(name)
                self._current_item.set_name(name)
                self.current_file['tilesets'][
                    self._base_name
                ][name] = self._current_item.to_dict()
                self.current_file['tilesets']
                self._items.append(self._current_item)
                self._queue.put({'name': 'config.save'})
                self._queue.put({
                    'name': 'tileset.update',
                    'tileset': self._base_name
                })
            self._current_item = None

    def mouseMoveEvent(self, event):
        if self._current_item is not None:
            rect = self._current_item.geometry()
            width = event.x() - rect.x()
            if width < 3:
                width = 3
            height = event.y() - rect.y()
            if height < 3:
                height = 3
            self._current_item.set_size(width, height)

    def remove_item(self, item):
        self._items.pop(self._items.index(item))
        item.hide()
        del self.current_file[
            'tilesets'
        ][self._base_name][item.to_dict()['name']]

    def remove(self):
        del self.current_file['tilesets'][self._base_name]


import random

import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.utils.data import Dataset
from torchvision import datasets

def set_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed)
    random.seed(seed)

set_seed(0)

class CIFAR10FromTxt(Dataset):
    def __init__(self, txt_path, root, train, transform, download, need_idx):
        self.need_idx =  need_idx
        self.base_dataset = datasets.CIFAR10(root, train, transform, download=download)
        self.raw_idxs = []
        self.targets = []
        self.txt_path = txt_path

        with open(self.txt_path, 'r') as f:
            lines = f.readlines()
            for line in lines:
                line = line.strip('\n')
                line = line.split(' ')
                raw_idx = int(line[0][8:])
                label = int(line[1][6:])
                self.raw_idxs.append(raw_idx)
                self.targets.append(label)

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

    def __getitem__(self, index):
        raw_idx, label = self.raw_idxs[index], self.targets[index]
        img, _ = self.base_dataset.__getitem__(raw_idx)
        if self.need_idx:
            return img, label, raw_idx
        else:
            return img, label

class CIFAR10Noisy(Dataset):
    def __init__(self, root, train, transform=None, download=True, noise_type='symmetric', noise_rate=0.2,
                 need_idx=True):
        self.base_dataset = datasets.CIFAR10(root, train, transform, download=download)
        self.noise_type = noise_type
        self.noise_rate = noise_rate
        self.noisy_sample_idx = []
        self.clean_sample_idx = []
        self.need_idx = need_idx
        self.base_transform = transform
        # add label noise
        if self.noise_type == 'symmetric':
            self.uniform(noise_rate, 10)
        elif self.noise_type == 'asymmetric':
            self.flip(noise_rate, 10)

    def to_txt(self, txt_path):
        with open(txt_path, 'w') as f:
            for i in range(self.base_dataset.__len__()):
                l = self.base_dataset.targets[i]
                f.write('raw_idx:' + str(i) + ' label:' + str(l) + '\n')

    def uniform(self, noise_rate: float, num_classes: int):
        """Add symmetric noise"""

        # noise transition matrix
        ntm = noise_rate * np.full((num_classes, num_classes), 1 / (num_classes - 1))
        np.fill_diagonal(ntm, 1 - noise_rate)

        figure = plt.figure()
        axes = figure.add_subplot(111)
        # plt.matshow(ntm, cmap='viridis')
        # caxes = axes.matshow(ntm, interpolation='nearest',cmap=plt.cm.Blues)
        caxes = axes.matshow(ntm, interpolation='nearest', cmap="viridis")
        # axes.set_xticklabels([''] + alphabets)
        # axes.set_yticklabels([''] + alphabets)
        cbar = figure.colorbar(caxes, )
        plt.show()

        sample_indices = np.arange(len(self.base_dataset))

        # generate noisy label by noise transition matrix
        for i in sample_indices:
            label = np.random.choice(num_classes, p=ntm[self.base_dataset.targets[i]])
            if label != self.base_dataset.targets[i]:
                self.noisy_sample_idx.append(i)
            self.base_dataset.targets[i] = label

        self.noisy_sample_idx = np.array(self.noisy_sample_idx)
        self.clean_sample_idx = np.setdiff1d(sample_indices, self.noisy_sample_idx)

        print('Noise type: Symmetric')
        print('Noise rate:', noise_rate)
        print('Noise transition matrix:\n', ntm)
        print('Clean samples:', len(self.clean_sample_idx), 'Noisy samples:', len(self.noisy_sample_idx))

    def flip(self, noise_rate: float, num_classes: int):
        """Add asymmetric noise"""

        # noise transition matrix
        ntm = np.eye(num_classes) * (1 - noise_rate)

        d = {9: 1, 2: 0, 3: 5, 5: 3, 4: 7}  # truck->automobile, bird->airplane, cat->dog, dog->cat, deer->horse
        for raw_class, new_class in d.items():
            ntm[raw_class][new_class] = noise_rate

        for i in [0, 1, 6, 7, 8]:
            ntm[i][i] = 1

        figure = plt.figure()
        axes = figure.add_subplot(111)
        # plt.matshow(ntm, cmap='viridis')

        caxes = axes.matshow(ntm, interpolation='nearest', cmap=plt.cm.Blues)
        # axes.set_xticklabels([''] + alphabets)
        # axes.set_yticklabels([''] + alphabets)
        figure.colorbar(caxes)
        plt.show()

        sample_indices = np.arange(len(self.base_dataset))

        # generate noisy label by noise transition matrix
        for i in sample_indices:
            label = np.random.choice(num_classes, p=ntm[self.base_dataset.targets[i]])
            if label != self.base_dataset.targets[i]:
                self.noisy_sample_idx.append(i)
            self.base_dataset.targets[i] = label

        self.noisy_sample_idx = np.array(self.noisy_sample_idx)
        self.clean_sample_idx = np.setdiff1d(sample_indices, self.noisy_sample_idx)

        print('Noise type: Asymmetric')
        print('Noise rate:', noise_rate)
        print('Noise transition matrix:\n', ntm)
        print('Clean samples:', len(self.clean_sample_idx), 'Noisy samples:', len(self.noisy_sample_idx))

    def __len__(self):
        return self.base_dataset.__len__()

    def __getitem__(self, index):
        if self.need_idx:
            return self.base_dataset.__getitem__(index), index
        else:
            return self.base_dataset.__getitem__(index)


"""added sos_med1 relationship

Revision ID: 1b537bf709ce
Revises: a05bc3ddcd23
Create Date: 2023-01-27 18:44:16.429531

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '1b537bf709ce'
down_revision = 'a05bc3ddcd23'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.add_column(sa.Column('sos_med1', sa.Integer(), nullable=True))
        batch_op.create_foreign_key(batch_op.f('fk_user_sos_med1_lib_med'), 'lib_med', ['sos_med1'], ['id'])

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.drop_constraint(batch_op.f('fk_user_sos_med1_lib_med'), type_='foreignkey')
        batch_op.drop_column('sos_med1')

    # ### end Alembic commands ###


import random

from src.utils import read_data, write_data
from typing import List, Dict
import re
from tqdm import tqdm
from collections import Counter

def have_constant(target_template: List) -> bool:
    for val in target_template:
        if val.strip() == "1":
        # if val.strip() == "pi" or val.strip() == "PI":
            return True
    return False

def have_pi(target_template: List) -> bool:
    for val in target_template:
        if val.strip() == "PI":
        # if val.strip() == "pi" or val.strip() == "PI":
            return True
    return False

def have_square(target_template: List) -> bool:
    for val in target_template:
        if val.strip() == "^":
            return True
    return False

def count_variable(target_template: List) -> int:
    num_vars = set()
    for val in target_template:
        if val.strip().startswith("temp_"):
            num_vars.add(val.strip())
    return len(num_vars)

def have_multiple_m0(target_template: List):
    target_string = ' '.join(target_template)
    target_string = target_string.replace("()", "").replace("( )", "")
    target_string = re.sub(r"\(.*\)", "temp_m", target_string)
    target_template = target_string.split()
    high_priority_symbol_pos = []
    for idx, val in enumerate(target_template):
        if val in {"*", "/"}:
            high_priority_symbol_pos.append(idx)
    for prev, next in zip(high_priority_symbol_pos[:-1], high_priority_symbol_pos[1:]):
        if next - prev != 2:
            return True
    return False

def check_in_labels(current_tuple, labels):
    if current_tuple in labels:
        return current_tuple
    if current_tuple[-1] in {'+', '*'} and [current_tuple[1], current_tuple[0], current_tuple[-1]] in labels:
        return [current_tuple[1], current_tuple[0], current_tuple[-1]]
    return None

def get_labels(target_norm_post_template: List, target_template: List, remove_duplicate: bool = False):
    assert target_norm_post_template[:2] == ["x", "="]
    if len(target_norm_post_template) == 3:
        assert target_norm_post_template[2].startswith("temp_")
        target_norm_post_template.append("1")
        target_norm_post_template.append("*")
    stack = []
    pointer = 2
    labels = []
    both_m = False
    eq_2_m = {}
    got_duplicate = False
    while pointer != len(target_norm_post_template):
        stack.append(target_norm_post_template[pointer])
        if stack[-1] in {'+', '-', '*', '/', '^'}:
            if len(stack[-3:]) == 3:
                if stack[-3].startswith("m_") and stack[-2].startswith("m_"):
                    both_m = True
                if remove_duplicate:
                    checker = check_in_labels([stack[-3], stack[-2], stack[-1]], labels)
                    if checker:
                        got_duplicate = True
                        m_string = eq_2_m[' '.join(checker)]
                    else:
                        labels.append([stack[-3], stack[-2], stack[-1]])
                        m_string = f"m_{len(labels)}"
                        eq_2_m[' '.join([stack[-3], stack[-2], stack[-1]])] = m_string
                else:
                    labels.append([stack[-3], stack[-2], stack[-1]])
                    m_string = f"m_{len(labels)}"
                stack.pop()
                stack.pop()
                stack.pop()
                stack.append(m_string)
        pointer += 1
    for i, (left, right, op) in enumerate(labels):
        # left = left[-1:] if left.startswith("temp_") else left
        # right = right[-1:] if right.startswith("temp_") else right
        if left.startswith("m_") or right.startswith("m_"):
            if left.startswith("m_") and right.startswith("m_"):
                left_is_smaller = (ord(left[-1:]) - ord(right[-1:])) <= 0
                modified_op = op + "_rev" if op in {'-', '/', '^'} and (not left_is_smaller) else op
                labels[i] = [left, right, modified_op] if left_is_smaller else [right, left, modified_op]
            elif right.startswith("m_"):
                modified_op = op + "_rev" if op in {'-', '/', '^'} else op
                labels[i] = [right, left, modified_op]
        else:
            if left.startswith("temp_") or right.startswith("temp_"):
                if left.startswith("temp_") and right.startswith("temp_"):
                    left_is_smaller = (ord(left[-1:]) - ord(right[-1:])) <= 0
                    modified_op = op + "_rev" if op in {'-', '/', '^'} and (not left_is_smaller) else op
                    labels[i] = [left, right, modified_op] if left_is_smaller else [right, left, modified_op]
                elif right.startswith("temp_"):
                    modified_op = op + "_rev" if op in {'-', '/', '^'} else op
                    labels[i] = [right, left, modified_op]
                else:
                    assert right in {"1", "PI"}
            else:
                pass
                # raise NotImplementedError(f"all constant for label: {labels[i]}")

    for i, (left, right, op) in enumerate(labels):
        left = left[-1:] if left.startswith("temp_") else left
        right = right[-1:] if right.startswith("temp_") else right
        # if (left == "PI" or right == "PI"):# and op not in {'*', '/'}:
        #     print(labels[i])
        labels[i] = [left, right, op]

    max_temp_org = max([v for v in target_template if v.startswith("temp_")])
    max_temp_update = max([v for v in target_norm_post_template if v.startswith("temp_")])
    gap = ord(max_temp_org[-1]) - ord(max_temp_update[-1])
    if gap > 0:
        for i, (left, right, op) in enumerate(labels):
            left = chr(ord(left) + gap) if len(left) == 1 and ord(left) >= ord('a') and ord(left) <= ord('z') else left
            right = chr(ord(right) + gap) if len(right) == 1 and ord(right) >= ord('a') and ord(right) <= ord('z') else right
            labels[i] = [left, right, op]
    return labels, both_m, gap, got_duplicate

def check_intermediate_m_in_order(labels: List[List[str]]):
    current_m_idx = 0
    for idx, (left_var, right_var, op) in enumerate(labels):
        if left_var.startswith("m_"):
            # try:
            assert int(left_var[2:]) - current_m_idx == 1
            # except:
            #     print("not incremental")
            current_m_idx += 1
    return True

def process_obj(obj: Dict, remove_duplicate: bool = False):
    target_template = [val.strip() for val in obj["target_template"]]

    labels, have_both_m, gap, got_duplicate = get_labels(obj["target_norm_post_template"], obj["target_template"], remove_duplicate)
    type_str = "legal"

    # if count_variable(target_template) > 7: ## only 2 in test
    #     type_str = "variable more than 7"
    #     return type_str, labels, gap

    # if have_constant(target_template):
    #     type_str = "have constant"
    #     return type_str, labels
    #
    # if have_pi(target_template):
    #     type_str = "have pi"
    #     print(obj["equation"], obj["target_template"])
    #     return type_str, labels

    if have_square(target_template): ## only 1 in test
        type_str = "have square"
        return type_str, labels, gap, False

    # if have_both_m:
    #     type_str = "have both m0, m1"
    #     return type_str, labels, gap

    # have_same_variable = []
    # for idx, curr_labels in enumerate(labels):
    #     if curr_labels[0] == curr_labels[1]:
    #         have_same_variable.append(idx)
    # if len(have_same_variable) > 0:
    #     if len(have_same_variable) == 1 and have_same_variable[0] == 0:
    #         return "legal", labels, gap
    #     else:
    #         return "have same variable at multiple layer", labels, gap

    # if have_multiple_m0(target_template):
    #     type_str = "have mutiple m0"
    #     return type_str, labels, gap

    return type_str, labels, gap, got_duplicate

def main():
    remove_duplicate = True
    for in_file in ["train23k_processed.json", "valid23k_processed.json", "test23k_processed.json"]:
        print(f"working on... {in_file}")
        in_file = f"../data/math23k/{in_file}"
        if remove_duplicate:
            out_file = in_file.split(".json")[0] + "_nodup_more.json"
        else:
            out_file = in_file.split(".json")[0] + "_all.json"
        data = read_data(in_file)
        count = Counter()
        inst_num_with_gap = 0
        duplicate_num = 0
        for obj in tqdm(data, desc="processing data", total=len(data)):
            type_str, labels, gap, got_duplicate = process_obj(obj, remove_duplicate=remove_duplicate)
            if len(labels) == 0:
                assert len(obj["target_norm_post_template"]) == 3
                print("something", obj["num_list"], obj["equation"])
            if gap > 0:
                inst_num_with_gap += 1
            count[type_str] += 1
            obj["type_str"] = type_str
            obj["equation_layer"] = labels
            duplicate_num += 1 if got_duplicate else 0
            # if type_str == "legal":
            #     check_intermediate_m_in_order(labels)
        # write_data(file=out_file, data = data)

        print(inst_num_with_gap)
        print(f" duplication number: {duplicate_num}")
        for key in count:
            print(f"{key}, valid number: {count[key]}, total: {len(data)}, %: {count[key] * 1.0 / len(data) * 100:.2f}")

def get_five_folds():
    random.seed(42)
    import os
    all_data = []
    for in_file in ["train23k_processed_nodup.json", "valid23k_processed_nodup.json", "test23k_processed_nodup.json"]:
        print(f"working on... {in_file}")
        in_file = f"../data/math23k/{in_file}"
        all_data.append(read_data(in_file))
    all_data = all_data[0] + all_data[1] + all_data[2]
    random.shuffle(all_data)
    num_fold = 5
    fold_size = len(all_data) // num_fold
    output_folder= "math23k_five_fold"
    os.makedirs(f"../data/math23k_five_fold", exist_ok=True)
    for i in range(num_fold):
        if i == num_fold - 1:
            test_data = all_data[i * fold_size:]
            train_data = all_data[:i * fold_size]
        else:
            test_data = all_data[i * fold_size:(i + 1) * fold_size]
            train_data = all_data[:i * fold_size] + all_data[(i + 1) * fold_size:]
        size = len(train_data) + len(test_data)
        print(f"total size : {size}, train: {len(train_data)}, test: {len(test_data)}")
        write_data(file=f"../data/{output_folder}/train_{i}.json", data=train_data)
        write_data(file=f"../data/{output_folder}/test_{i}.json", data=test_data)

if __name__ == '__main__':
    # text = "a () * c"
    # print(re.sub(r"\(.*\)", "temp_m", text))
    # main()
    get_five_folds()
    # print(breakit('(((a+b)+a)+c)'))


from typing import List, Tuple

class Day4:
    def __init__(self):
        self.input = []
        self.bingo_numbers = []
        self.bingo_boards = []
        self.bingo_status = []
        self.load_input()
        print(self.bingo_boards)
        self.solve_part_1()
        self.solve_part_2()

    def load_input(self):
        f = open("../inputs/day4.txt", "r")
        txt = f.read()
        lines = txt.splitlines()
        self.bingo_numbers = list(map(int, lines[0].split(',')))
        self.bingo_boards, self.bingo_status = Day4.parse_bingo_boards(lines)

    def solve_part_1(self):
        print("p1 ====================")
        winning_board: List[Tuple[int, int]]
        winning_num: int
        winning_board, winning_num = Day4.find_winning_board(self.bingo_numbers, self.bingo_boards)
        unused_nums = sum(map(lambda n: n[0] if n[1] == 0 else 0, winning_board))
        print(f'unused({unused_nums}) * winning({winning_num}) = {unused_nums*winning_num}')
        return

    def solve_part_2(self):
        print("p2 ====================")
        return

    @staticmethod
    def find_winning_board(numbers, boards):
        for num in numbers:
            for board in boards:
                if Day4.play_board_turn(board, num):
                    return board, num

    @staticmethod
    def parse_bingo_boards(raw_input: List[str], start_line=2):
        boards = []
        status_boards = []
        board = []
        status = [0]*25
        for line in raw_input[start_line:]:
            if line.strip() == '':
                boards.append(board)
                board = []
            else:
                board.extend(list(map(int, line.split())))
        # capture the last board
        boards.append(board)

        for x in range(len(boards)):
            status_boards.append(status)
        return boards, status_boards

    @staticmethod
    def play_board_turn(board: List[List[int, int]], number):
        if number not in board:
            return False
        else:
            for board_pos in board:
                if board_pos[0] == number:
                    board_pos[1] = 1
                    # check victory
                    Day4.check_win(board, number)

    @staticmethod
    def check_win(board: List[List[int, int]], winning_num):
        # win conditions: horizontal match
        if board[0][1] and board[1][1] and board[2][1] and board[3][1] and board[4][1]:
            return True
        elif board[5][1] and board[6][1] and board[7][1] and board[8][1] and board[9][1]:
            return True
        elif board[10][1] and board[11][1] and board[12][1] and board[13][1] and board[14][1]:
            return True
        elif board[15][1] and board[16][1] and board[17][1] and board[18][1] and board[19][1]:
            return True
        elif board[20][1] and board[21][1] and board[22][1] and board[23][1] and board[24][1]:
            return True

        # win conditions: vertical match
        for i in range(5):
            if sum(map(lambda x: x,board[0:5][1])) == 5:
                # do stuff
                break

        return False

Day4()


import numpy as np
import pandas as pd
import ntpath
import logging

import wx
import wx.grid as gridlib
#import wx.lib.inspection

from lims.plugins.plugin_collection import PluginCollection
import lims.result

EVEN_ROW_COLOUR = '#CCE6FF'
GRID_LINE_COLOUR = '#ccc'

class DataTable(wx.grid.GridTableBase):
    def __init__(self, data=None):
        wx.grid.GridTableBase.__init__(self)
        self.headerRows = 1
        if data is None:
            data = pd.DataFrame()
        self.data = data

    def GetNumberRows(self):
        return len(self.data)

    def GetNumberCols(self):
        return len(self.data.columns) + 1

    def GetValue(self, row, col):
        if col == 0:
            return self.data.index[row]
        return self.data.iloc[row, col - 1]

    def SetValue(self, row, col, value):
        self.data.iloc[row, col - 1] = value

    def GetColLabelValue(self, col):
        if col == 0:
            if self.data.index.name is None:
                return 'Index'
            else:
                return self.data.index.name
        return str(self.data.columns[col - 1])

    def GetTypeName(self, row, col):
        return wx.grid.GRID_VALUE_STRING

    def GetAttr(self, row, col, prop):
        attr = wx.grid.GridCellAttr()
        if row % 2 == 1:
            attr.SetBackgroundColour(EVEN_ROW_COLOUR)
        return attr

class DataGrid(gridlib.Grid):
    def __init__(self, parent, size=wx.Size(1000, 500)):
        self.parent = parent
        gridlib.Grid.__init__(self, self.parent, -1)
        self.SetGridLineColour(GRID_LINE_COLOUR)
        self.SetRowLabelSize(0)
        self.SetColLabelSize(30)
        self.table = DataTable()

class LIMS(wx.Frame):

    def __init__(self, parent, title):
        super(LIMS, self).__init__(parent, title=title, size=wx.Size(1025, 650))

        self.data = None
        self.gbs = None
        self.grid = None
        self.tc_input = None
        self.tc_id = None
        self.tc_name = None
        self.tc_desc = None
        self.tc_file_type = None
        self.cb_proc = None
        self.processors = {}
        self.processor_names = []

        self.get_processors()
        self.InitUI()
        self.Layout()
        self.Centre()
        self.Show()

    def create_grid(self, panel, data):
        table = DataTable(data)
        grid = DataGrid(panel)
        grid.CreateGrid(len(data), len(data.columns))
        grid.SetTable(table)
        grid.AutoSize()
        grid.AutoSizeColumns(True)
        return grid

    def get_processors(self):
        plugins = PluginCollection('lims.processors')
        for proc in plugins.plugins:
            self.processors[proc.name] = proc
            self.processor_names.append(proc.name)

    def InitUI(self):

        #self.SetSize(wx.Size(500, 500))
        processors = ["AAAA", "BBBB", "CCCC"]

        panel = wx.Panel(self, name="MainPanel")
        #self.data_grid = self.create_grid(panel, self.data)

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        #fgs = wx.FlexGridSizer(5, 5, 9, 35)
        gbs = wx.GridBagSizer(9, 30)
        self.gbs = gbs

        stat_txt1 = wx.StaticText(panel, label='')
        #stat_txt2 = wx.StaticText(panel, label='')
        stat_txt3 = wx.StaticText(panel, label='')
        stat_txt3b = wx.StaticText(panel, label='')
        stat_txt4 = wx.StaticText(panel, label='')
        stat_txt4b = wx.StaticText(panel, label='')
        #stat_txt5 = wx.StaticText(panel, label='')

        #Row 1
        lbl_processor = wx.StaticText(panel, label="Processor")
        #tc_proc = wx.TextCtrl(panel, wx.EXPAND)
        self.cb_proc = wx.Choice(panel, wx.EXPAND, choices = self.processor_names)
        self.Bind(wx.EVT_CHOICE , self.on_select_combo, self.cb_proc)
        gbs.Add(lbl_processor, pos=(0,0),flag=wx.EXPAND)
        #gbs.Add(tc_proc, pos=(0,1),flag=wx.EXPAND)
        gbs.Add(self.cb_proc, pos=(0,1),flag=wx.EXPAND)

        gbs.Add(stat_txt1, pos=(0,2),flag=wx.EXPAND)

        lbl_id = wx.StaticText(panel, label="ID:")
        self.tc_id = wx.TextCtrl(panel, wx.EXPAND)
        self.tc_id.SetEditable(False)
        gbs.Add(lbl_id, pos=(0,3),flag=wx.EXPAND)
        gbs.Add(self.tc_id, pos=(0,4),flag=wx.EXPAND)

        #Row 2
        lbl_input = wx.StaticText(panel, label="Input File")
        self.tc_input = wx.TextCtrl(panel)
        btn_select_file = wx.Button(panel, wx.ID_ANY, '...')
        gbs.Add(lbl_input, pos=(1,0),flag=wx.EXPAND)
        gbs.Add(self.tc_input, pos=(1,1),flag=wx.EXPAND)

        #gbs.Add(stat_txt2, pos=(1,2),flag=wx.EXPAND)
        gbs.Add(btn_select_file, pos=(1,2),flag=wx.EXPAND)
        self.Bind(wx.EVT_BUTTON, self.on_select_file, btn_select_file)

        lbl_name = wx.StaticText(panel, label="Name:")
        self.tc_name = wx.TextCtrl(panel)
        self.tc_name.SetEditable(False)
        gbs.Add(lbl_name, pos=(1,3),flag=wx.EXPAND)
        gbs.Add(self.tc_name, pos=(1,4),flag=wx.EXPAND)

        #Row 3
        gbs.Add(stat_txt3, pos=(2,0),flag=wx.EXPAND)
        btn_run = wx.Button(panel, wx.ID_ANY, 'Run')
        self.Bind(wx.EVT_BUTTON, self.on_run, btn_run)
        gbs.Add(btn_run, pos=(2,1),flag=wx.EXPAND)

        gbs.Add(stat_txt3b, pos=(2,2),flag=wx.EXPAND)

        lbl_desc = wx.StaticText(panel, label="Description:")
        self.tc_desc = wx.TextCtrl(panel)
        self.tc_desc.SetEditable(False)
        gbs.Add(lbl_desc, pos=(2,3),flag=wx.EXPAND)
        gbs.Add(self.tc_desc, pos=(2,4),flag=wx.EXPAND)

        #Row 4
        gbs.Add(stat_txt4, pos=(3,0),flag=wx.EXPAND)
        btn_save = wx.Button(panel, wx.ID_ANY, 'Save')
        self.Bind(wx.EVT_BUTTON, self.on_save, btn_save)
        gbs.Add(btn_save, pos=(3,1),flag=wx.EXPAND)

        gbs.Add(stat_txt4b, pos=(3,2),flag=wx.EXPAND)

        lbl_file_type = wx.StaticText(panel, label="File Type:")
        self.tc_file_type = wx.TextCtrl(panel)
        self.tc_file_type.SetEditable(False)
        gbs.Add(lbl_file_type, pos=(3,3),flag=wx.EXPAND)
        gbs.Add(self.tc_file_type, pos=(3,4),flag=wx.EXPAND)

        self.grid = wx.grid.Grid(panel, -1, size= wx.Size(900, 400), name="DataGrid")

        gbs.Add(self.grid, pos=(4,0), span = (1, 5), flag= wx.SYS_VSCROLL_X | wx.SYS_HSCROLL_Y)

        #hbox.Add(gbs, proportion=1, flag=wx.ALL, border=15)
        #panel.SetSizer(hbox)

        self.CreateStatusBar()
        self.SetStatusText("")

        self.set_empty_table()

    def on_select_file(self, event):
        with wx.FileDialog(self, "Select instrument file", wildcard="All file (*.*)|*.*",
                       style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:

            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return     # the user changed their mind

            # Proceed loading the file chosen by the user
            pathname = fileDialog.GetPath()
            file_name = ntpath.basename(pathname)
            self.tc_input.SetValue(pathname)

    def on_select_combo(self, event):
        print("Combobox handler")
        idx = self.cb_proc.GetSelection()
        proc_name = self.cb_proc.GetString(idx)
        print("Processor: " + proc_name)
        if self.processors is not None:
            for key, proc in self.processors.items():
                if proc.name == proc_name:
                    self.tc_name.SetValue(proc.name)
                    self.tc_desc.SetValue(proc.description)
                    self.tc_file_type.SetValue(proc.file_type)

    def on_run(self, event):

        idx = self.cb_proc.GetSelection()
        proc_name = self.cb_proc.GetString(idx)

        file = self.tc_input.GetValue()
        if proc_name == '':
            return

        if self.processors is not None:
            proc = self.processors[proc_name]
            result = proc.execute(file)

        print('onOK handler')
        #item = self.gbs.FindItemAtPosition((4,0))
        #if self.grid != None:
        #    self.gbs.Hide(self.grid)

        #df = pd.DataFrame(np.random.random((100, 10)))
        df = result.df
        df.to_excel(result.table_name +".xlsx", index=False)
        table = DataTable(df)

        self.grid.SetTable(table, takeOwnership=True)
        self.grid.AutoSizeColumns()

        self.gbs.Layout()
        self.Layout()

    def on_save(self, event):
        ival = 1

    def set_empty_table(self):
        data = {'Aliquot':[''],
            	'Analyte Identifier':[''],
                'Measured Value':[''],
                'Units':[''],
                'Dilution Factor':[''],
                'Analysis Date/Time':[''],
                'Comment':[''],
                'Description':[''],
                'User Defined 1':[''],
                'User Defined 2':[''],
                'User Defined 3':[''],
                'User Defined 4':[''],
                'User Defined 5':[''],
                'User Defined 6':[''],
                'User Defined 7':[''],
                'User Defined 8':[''],
                'User Defined 9':[''],
                'User Defined 10':[''],
                'User Defined 11':[''],
                'User Defined 12':[''],
                'User Defined 13':[''],
                'User Defined 14':[''],
                'User Defined 15':[''],
                'User Defined 16':[''],
                'User Defined 17':[''],
                'User Defined 18':[''],
                'User Defined 19':[''],
                'User Defined 20':['']
        }
        df = pd.DataFrame(data)
        table = DataTable(df)
        self.grid.SetTable(table, takeOwnership=True)
        self.grid.AutoSizeColumns()

        self.gbs.Layout()
        self.Layout()
        return table

def main():

    logger = logging.getLogger("LIMS_Run_Processor")
    f_handler = logging.FileHandler('file.log',mode='a')
    f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
    f_handler.setFormatter(f_format)
    logger.addHandler(f_handler)

    app = wx.App()
    ex = LIMS(None, title='Laboratory Information Management System')
    ex.Show()
    #wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

if __name__ == '__main__':
    main()


import json
import os

def get_setting():
    path_utils = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    path_root = os.path.dirname(os.path.dirname(path_utils))
    path_conf = os.path.join(path_root, '.conf')
    path_file_settings_local = os.path.join(path_conf, 'settings_local.json')
    with open(path_file_settings_local, 'r') as f:
        config_str = f.read()
    config = json.loads(config_str)
    return config


import random
import os
from collections import defaultdict
from ducktape.utils.util import wait_until
from ducktape.mark import matrix
from rptest.clients.types import TopicSpec
from rptest.clients.rpk import RpkTool
from rptest.services.admin import Admin
from rptest.clients.default import DefaultClient
from rptest.services.cluster import cluster
from rptest.tests.redpanda_test import RedpandaTest
from rptest.utils.mode_checks import cleanup_on_early_exit

class RackAwarePlacementTest(RedpandaTest):
    def __init__(self, test_context):
        super(RackAwarePlacementTest,
              self).__init__(test_context=test_context,
                             num_brokers=6,
                             extra_rp_conf={
                                 'enable_rack_awareness': True,
                                 'segment_fallocation_step': 1024,
                             })

    def setUp(self):
        # Delay startup, so that the test case can configure redpanda
        # based on test parameters before starting it.
        pass

    def _get_partition_count(self, topic):
        try:
            m = self.client().describe_topic(topic)
            return len(m.partitions)
        except Exception as err:
            self.logger.info(f"describe_topic error: {err}")
            return 0

    def _create_topic(self, topic):
        """Create topic and wait until all partitions are created.
        """
        self.client().create_topic(topic)

        wait_until(
            lambda: self._get_partition_count(topic.name
                                              ) == topic.partition_count,
            timeout_sec=60,
            backoff_sec=1,
            err_msg=
            f"Not all partitions are created in time, expected {topic.partition_count} partitions, found {self._get_partition_count(topic.name)}"
        )

    def _validate_placement(self,
                            topic,
                            rack_layout,
                            num_replicas,
                            ids_mapping={}):
        """Validate the replica placement. The method uses provided
        rack layout and number of replicas for the partitions.
        The validation is done by examining existing replica placemnt
        against the rack layout. The validation succedes if every replica
        is placed on a different rack or if there is not enough racks on
        every available rack.
        """
        num_racks = len(set(rack_layout))
        m = self.client().describe_topic(topic.name)
        replicas = defaultdict(list)
        for part in m.partitions:
            for broker in part.replicas:
                # broker ids are 1-based
                id = ids_mapping[broker] if broker in ids_mapping else broker
                rack = rack_layout[id - 1]
                replicas[part.id].append(rack)

        for part_id, racks in replicas.items():
            expected_racks = min(num_racks, num_replicas)
            self.logger.info(
                f"partition {part_id} is replicated to racks {racks}, expected {expected_racks} racks, total racks {num_racks}"
            )
            assert len(set(racks)) == min(num_racks, num_replicas)

    @cluster(num_nodes=6)
    @matrix(rack_layout_str=['ABCDEF', 'xxYYzz', 'ooooFF'],
            num_partitions=[50, 400],
            replication_factor=[3, 5],
            num_topics=[2])
    def test_replica_placement(self, rack_layout_str, num_partitions,
                               replication_factor, num_topics):
        """
        Test replica placement. The test case creates a set of brokers with
        initialized 'rack' parameter in the configuration. The 'rack' property
        is defined by the 'rack_layout' parameter. Then it creates a topic with
        pre-defined number of partitions and replication factor and validates
        the replica placement.

        The validation procedure checks that:
        - either every replica lives on a different rack;
        - or every rack is used to place one or more replicas of the partition
          (if replication factor is larger than number of racks)

        ----
        @param rack_layout_str is a 6-char string with all rack names combined into a signle string.
                               Every character of the string corresponds to one broker. Every
                               rack id has single character.
        @param num_partitions defines number of partitions that needs to be created.
        @param replication_factor defines recplication factor of all partitions.
        """

        # https://github.com/redpanda-data/redpanda/issues/11276
        if self.debug_mode and num_partitions == 400:
            self.logger.info(
                "Disabling test in debug mode due to slowness/timeouts with large number of partitions."
            )
            cleanup_on_early_exit(self)
            return

        rack_layout = [str(i) for i in rack_layout_str]
        assert len(rack_layout) == 6

        for ix, node in enumerate(self.redpanda.nodes):
            extra_node_conf = {
                # We're introducing two racks, small and large.
                # The small rack has only one node and the
                # large one has four nodes.
                'rack': rack_layout[ix],
                # This parameter enables rack awareness
                'enable_rack_awareness': True,
                'segment_fallocation_step': 4096,
            }
            self.redpanda.set_extra_node_conf(node, extra_node_conf)

        self.redpanda.start()

        if num_topics * num_partitions * replication_factor > 3000:
            # Combination of 2 topics, 5 replicas and 400 partitions can't be run
            # reliably on both debug and release due to ducktape limitations.
            self.logger.info(
                f"combination of num_partitions: {num_partitions}, replication_factor: {replication_factor}, and num_topics: {num_topics} is excluded"
            )
            return

        topics = []
        for tix in range(0, num_topics):
            topic = TopicSpec(partition_count=num_partitions,
                              replication_factor=replication_factor)
            topics.append(topic)
            self._create_topic(topic)

        for topic in topics:
            self._validate_placement(topic, rack_layout, replication_factor)

    def _partition_count(self):
        # use smaller number of partitions for debug builds
        if os.environ.get('BUILD_TYPE', None) == 'debug':
            return random.randint(20, 40)

        return random.randint(200, 300)

    @cluster(num_nodes=6)
    @matrix(rack_layout=['ABCDEF', 'xxYYzz', 'ooooFF'])
    def test_rack_awareness_after_node_operations(self, rack_layout):
        replication_factor = 3

        for ix, node in enumerate(self.redpanda.nodes):
            self.redpanda.set_extra_node_conf(
                node,
                {
                    "rack": rack_layout[ix],
                    'enable_rack_awareness': True,
                    # make fallocation step small to spare the disk space
                    'segment_fallocation_step': 4096,
                })

        self.redpanda.start()
        self._client = DefaultClient(self.redpanda)

        topic = TopicSpec(partition_count=self._partition_count(),
                          replication_factor=replication_factor)
        self.client().create_topic(topic)
        self._validate_placement(topic, rack_layout, replication_factor)

        # decommission one of the nodes
        admin = Admin(self.redpanda)

        brokers = admin.get_brokers()
        to_decommission = random.choice(brokers)['node_id']

        admin.decommission_broker(to_decommission)

        def node_is_removed():
            for n in self.redpanda.nodes:
                if self.redpanda.idx(n) == to_decommission:
                    continue
                brokers = admin.get_brokers(node=n)
                for b in brokers:
                    if b['node_id'] == to_decommission:
                        return False
            return True

        # wait until node is removed and validate rack placement
        wait_until(node_is_removed, 90, 2)

        self._validate_placement(topic, rack_layout, replication_factor)

        # stop the node and add it back with different id
        to_stop = self.redpanda.get_node(to_decommission)
        self.redpanda.stop_node(to_stop)
        self.redpanda.clean_node(node=to_stop, preserve_logs=True)

        new_node_id = 123

        def seed_servers_for(idx):
            seeds = map(
                lambda n: {
                    "address": n.account.hostname,
                    "port": 33145
                }, self.redpanda.nodes)

            return list(
                filter(
                    lambda n: n['address'] != self.redpanda.get_node(idx).
                    account.hostname, seeds))

        # add a node back with different id but the same rack
        # change the seed server list to prevent node from forming new cluster
        self.redpanda.start_node(
            to_stop,
            override_cfg_params={
                "node_id": new_node_id,
                "seed_servers": seed_servers_for(to_decommission),
                "rack": rack_layout[to_decommission - 1],
                'enable_rack_awareness': True,
                # make fallocation step small to spare the disk space
                'segment_fallocation_step': 4096,
            })

        rpk = RpkTool(self.redpanda)

        def new_node_has_partitions():
            for p in rpk.describe_topic(topic.name):
                for r in p.replicas:
                    if r == 123:
                        return True

            return False

        wait_until(new_node_has_partitions, 90, 2)

        def no_partitions_moving():
            for n in self.redpanda.nodes:
                r = admin.list_reconfigurations(node=n)
                if len(r) > 0:
                    return False

            return True

        wait_until(no_partitions_moving, 90, 1)

        self._validate_placement(topic,
                                 rack_layout,
                                 replication_factor,
                                 ids_mapping={new_node_id: to_decommission})

    @cluster(num_nodes=6)
    def test_node_config_update(self):
        """
        * Create a cluster from nodes with no rack id configured
        * edit node configs adding rack ids
        * restart the nodes
        * check that rack aware placement works
        """
        rack_layout = 'AABBCC'
        replication_factor = 3
        num_partitions = 10

        self.redpanda.start()

        self.redpanda.stop()
        for ix, node in enumerate(self.redpanda.nodes):
            self.redpanda.start_node(
                node, override_cfg_params={"rack": rack_layout[ix]})

        admin = Admin(self.redpanda)

        def rack_ids_updated():
            for n in self.redpanda.nodes:
                if any('rack' not in b for b in admin.get_brokers(n)):
                    return False
            return True

        wait_until(rack_ids_updated,
                   timeout_sec=30,
                   backoff_sec=1,
                   err_msg="node configurations didn't get updated")

        topic = TopicSpec(partition_count=num_partitions,
                          replication_factor=replication_factor)
        self._create_topic(topic)
        self._validate_placement(topic, rack_layout, replication_factor)


import cv2
from directkeys import PressKey, ReleaseKey
from grabscreen import grab_screen
import numpy as np
import pyautogui
from sklearn.cluster import KMeans
import threading
import time

uhd_x = 640
uhd_y = 312
BOX = (uhd_x, uhd_y, uhd_x + 640, uhd_y + 480)

hood_y = 410
horizon_y = 175
side_y = 50
keytime = 0.1

STRAIGHT = 0x11
RIGHT = 0x20
LEFT = 0x1E

VERTICES = np.array([[4, horizon_y + side_y],
                     [220, horizon_y], [580, horizon_y],
                     [800, horizon_y + side_y],
                     [800, hood_y], [4, hood_y]])

for i in range(3, 0, -1):
    time.sleep(.4)
    print(i)

def t_key(key_a, key_b, key_c):
    PressKey(key_a)
    ReleaseKey(key_b)
    ReleaseKey(key_c)
    time.sleep(keytime)

def straight():
    print("pressing up")
    thread_straight = threading.Thread(target=t_key,
                                       args=(STRAIGHT, RIGHT, LEFT))
    thread_straight.start()

def right():
    print("pressing r")
    thread_right = threading.Thread(target=t_key,
                                    args=(RIGHT, STRAIGHT, LEFT))
    thread_right.start()

def left():
    print("pressing l")
    thread_left = threading.Thread(target=t_key,
                                   args=(LEFT, STRAIGHT, RIGHT))
    thread_left.start()

def slope(line):
    try:
        y = line[1] - line[3]
        x = line[0] - line[2]
        slope = np.divide(y, x)
    except ZeroDivisionError:
        slope = 100000
    finally:
        return slope

def drive(m=None):
    sign = np.sum(np.sign(m))
    if sign == -2:
        right()
    elif sign == 2:
        left()
    else:
        straight()

def draw_lines(img, lines):
    try:
        m = []
        for coords in lines:
            m.append(slope(coords))
            coords = np.array(coords, dtype='uint32')
            cv2.line(img,
                     (coords[0], coords[1]),
                     (coords[2], coords[3]),
                     [255, 255, 255], 10)
    except TypeError as e:
        print('draw lines error: {}'.format(e))
    else:
        pass
        drive(m)

def roi(img, vertices):
    mask = np.zeros_like(img)
    cv2.fillPoly(mask, vertices, 255)
    masked = cv2.bitwise_and(img, mask)
    return masked

def process_img(original_img):

    processed_img = cv2.Canny(original_img,
                              threshold1=100, threshold2=300)

    processed_img = roi(processed_img, [VERTICES])

    # processed_img = cv2.GaussianBlur(processed_img, (5, 5), 0)
    lines = cv2.HoughLinesP(processed_img, 1,
                            np.pi / 180, 180, np.array([]), 120, 20)

    # draw_lines(processed_img, nlines)

    try:
        nlines = np.array([l[0] for l in lines])
        kmeans = KMeans(n_clusters=2, random_state=0).fit(nlines)
        draw_lines(processed_img, kmeans.cluster_centers_)
    except (ValueError, TypeError) as e:
        print('Kmeans error: {}'.format(e))

    return processed_img

def main():
    while True:
        ti = time.time()
        screen = grab_screen(region=BOX)
        cv2.imshow('window', cv2.cvtColor(screen,
                                          cv2.COLOR_BGR2RGB))

        new_screen = process_img(screen)
        cv2.imshow('window2', new_screen)

        print('{:.2f} FPS'.format(1 / (time.time() - ti)))
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import scrapy
import time
import re
import json
from china.items import ChinaIntroItem_shenzhenL
from china.items import ChinaIntroItem_shanghaiL

class CodeSpider(scrapy.Spider):
    name = 'china_updateAll_l'
    allowed_domains = ['sse.com.cn', 'szse.cn']
    #shanghaiL 无
    #shenzhenL
    type_list_shenzhenL = ["tab2", "tab3", "tab4"]
    url1_shenzhenL = "http://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1110x&TABKEY="
    url2_shenzhenL = "&PAGENO="
    url3_shenzhenL = "&random=0.8452698015484685"

    def start_requests(self):
        #shanghaiL
        url_shanghaiL = "http://query.sse.com.cn/security/stock/downloadStockListFile.do?csrcCode=&stockCode=&areaName=&stockType=1"
        yield scrapy.Request(url_shanghaiL, callback=self.parse_shanghaiL)
        #shenzhenL
        for temp_shenzhenL in self.type_list_shenzhenL:
            num_shenzhenL = 1
            if temp_shenzhenL == "tab2":
                plate_type = "主版"#1
            elif temp_shenzhenL == "tab3":
                plate_type = "中小企业版"#2
            else:
                plate_type = "创业版"#3
            link_shenzhenL = self.url1_shenzhenL + temp_shenzhenL + self.url2_shenzhenL
            url_shenzhenL = self.url1_shenzhenL + temp_shenzhenL + self.url2_shenzhenL + str(num_shenzhenL) + self.url3_shenzhenL
            yield scrapy.FormRequest(url_shenzhenL, callback=self.parse_shenzhenL, meta={"link": link_shenzhenL, "plate_type": plate_type, "num": num_shenzhenL})

    def parse_shanghaiL(self, response):
        data = response.text
        item = ChinaIntroItem_shanghaiL()
        item["data"] = data
        item["doc_source_url"] = None
        yield item
        # with open("/data/OPDCMS/china/listed_company_update/company_list/shanghai_" + self.create_time_shanghaiL + ".txt", "a") as f:
        #     f.write(data)

    def parse_shenzhenL(self, response):
        num = response.meta["num"]
        plate_type = response.meta["plate_type"]
        link = response.meta["link"]
        data = response.body
        if plate_type == "主版":
            data_list = json.loads(data)[1]["data"]
        elif plate_type == "中小企业版":
            data_list = json.loads(data)[2]["data"]
        else:
            data_list = json.loads(data)[3]["data"]
        if len(data_list) != 0:
            for temp_shenzhenL in data_list:
                item = ChinaIntroItem_shenzhenL()
                item["plate_type"] = plate_type
                item["code"] = temp_shenzhenL["zqdm"]
                item["company_short_name_zh"] = re.search(">(.*?)", str(temp_shenzhenL["gsjc"])).group(1)
                item["name_origin"] = temp_shenzhenL["gsqc"]
                item["security_code"] = temp_shenzhenL["sshymc"]
                item["website_url"] = temp_shenzhenL["http"]
                item["gmt_create"] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                item["user_create"] = "zx"
                item["doc_source_url"] = None
                yield item
                num += 1
                url = link + str(num) + self.url3_shenzhenL
                yield scrapy.Request(url, callback=self.parse_shenzhenL, meta={"link": link, "plate_type": plate_type, "num": num})


import random
dic={}
score=0
n=int(input("Enter total number of question : "))
if n>=5:
    for i in range(1,n+1):
        q=input("ENTER YOUR QUESTION HERE : ")
        a=input("ENTER CORRECT ANSWER(True/False) : ")
        A=a.upper()
        dic[q]=A
    list_keys=list(dic.keys())
    list_values=list(dic.values())
    for i in range(1,6):
        m=random.randrange(0,n)
        print('QUESTION',i)
        print(list_keys[m])
        ans=input("enter your answer :")
        Ans=ans.upper()
        if Ans==list_values[m]:
            print("congrats!!! your answer is correct")
            score=score+1
        else:
            print("sorry!!! your answer is wrong")
    print("your total marks is : ",score)
    print("THANK YOU")
else:
    print("INVALID NUMBER OF QUESTION")


import time

from django.conf import settings

def build_photo_url(photo_id, pic_version="thumb", pic_type="photos", cdn=False):
    # identifier = "!"
    if not cdn:
        if photo_id:
            return "".join([
                settings.MEDIA_URL, pic_type, "/", pic_version,
                "/", photo_id[:2], "/", photo_id, ".jpg"
            ])
        else:
            return "".join(["/static/", "images/", "user-default.jpg"])
    else:
        if photo_id:
            return "".join([
                settings.SERVERHOST, "/media/", pic_type, "/", pic_version,
                "/", photo_id[:2], "/", photo_id , ".jpg"
            ])
        else:
            return "".join([settings.SERVERHOST, "/static/", "images/", "user-default", ".jpg"])

def parse_timestamps(timestamps):
    t = time.localtime(timestamps)
    time_str = time.strftime(r'%Y-%m-%d %H:%M:%S', t)
    return time_str


import torch
import torch.nn as nn
from torchvision import models
from REGISTRY import double_class_methods

def construct_model(architecture, method, num_classes, in_channels=1):

    if architecture == "densenet121":
        model = models.densenet121(pretrained=True)
        num_ftrs = model.classifier.in_features
        if method in double_class_methods:
            model.classifier = nn.Linear(num_ftrs, 2 * num_classes)
        else:
            model.classifier = nn.Linear(num_ftrs, num_classes)

    elif architecture == "shortdensenet121":

        class ShortNet(nn.Module):
            def __init__(self, base_model):
              super(ShortNet, self).__init__()
              self.base_model = base_model
              self.global_pool = nn.AvgPool2d(28)
              self.classifier = nn.Linear(512, 14)

            def forward(self, x):
              x = self.base_model.features.conv0(x)
              x = self.base_model.features.norm0(x)
              x = self.base_model.features.relu0(x)
              x = self.base_model.features.pool0(x);
              x = self.base_model.features.denseblock1(x);
              x = self.base_model.features.transition1(x);
              x = self.base_model.features.denseblock2(x);
              x = self.base_model.features.transition2.norm(x);
              x = self.global_pool(x)
              x = x.squeeze(-1).squeeze(-1)
              x = self.classifier(x)
              return x

        model = models.densenet121(pretrained=True)
        model = ShortNet(model)
        num_ftrs = model.classifier.in_features
        if method in double_class_methods:
            model.classifier = nn.Linear(num_ftrs, 2 * num_classes)
        else:
            model.classifier = nn.Linear(num_ftrs, num_classes)

    elif architecture == "resnet50":
        model = models.resnet50(pretrained=True)
        num_ftrs = model.classifier.in_features
        if method in double_class_methods:
            model.classifier = nn.Linear(num_ftrs, 2 * num_classes)
        else:
            model.classifier = nn.Linear(num_ftrs, num_classes)

    else:
        print("Unknown architecture. Aborting...")
        return

    model.architecture = architecture
    model.num_classes = num_classes
    model.method = method
    model.in_channels = in_channels

    return model

def load_model(checkpoint_path):
    checkpoint = torch.load(checkpoint_path);
    architecture = checkpoint['architecture'];
    num_classes = checkpoint['num_classes'];
    train_method = checkpoint['train_method'];
    model_state_dict = checkpoint['model_state_dict'];
    optimizer_state_dict = checkpoint['optimizer_state_dict'];
    starting_epoch = checkpoint['epoch'] if 'epoch'in checkpoint else 0;
    best_acc = checkpoint['best_acc'] if 'best_acc' in checkpoint else 0.0;
    in_channels = checkpoint['in_channels'] if 'in_channels' in checkpoint else 1;

    model = construct_model(architecture, train_method, num_classes, in_channels);
    model.load_state_dict(model_state_dict);
    print("Existing model was trained using {0}".format(train_method))

    return model, starting_epoch, best_acc, train_method

def put_model_to_device(model):
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model = model.to(device)
    return model

def get_num_pool_ops(architecture):
    if architecture == 'vnet':
        num_pool_ops = 4
    else:
        num_pool_ops = 3
    return num_pool_ops


# -*- coding:utf-8 -*-
# @time:2023/2/1810:31
# @author:LX
# @file:controlType.py
# @software:PyCharm

__all__ = ["getStyleLists","getStyleCommentLists"]

STYLE_LIB = {
    ("QPushButton",):{"QPushButton":"/*按钮*/",
                       "QPushButton:hover":"/*鼠标放在按钮上时的样式*/",
                       "QPushButton:pressed":"/*按钮按下时的样式*/",
                       "QPushButton::menu-indicator":"/*菜单指示器子控件(在菜单栏时的样式)*/",
                       "QPushButton:open":"/*按钮在菜单打开时的样式*/"},
    ("QLabel",): {"QLabel": "/*标签*/",
                  "QLabel:hover": "/*鼠标放在标签上时的样式*/"
               },
    ("QLineEdit",):{
        "QLineEdit":"/**/",
        "QLineEdit:read-only":"/*只读时读样式*/"
    },
    ("QWidget",):{
        "QWidget":"/**/"
    },
    ("QComboBox",): {"QComboBox": "/*下拉框*/",
                  "QComboBox:!editable": "/*编辑框样式*/",
                  "QComboBox:editable": "/*编辑框样式(需要将editable设置为真才生效,内容可编辑)*/",
                  "QComboBox::drop-down": "/*下拉按钮样式*/",
                  "QComboBox::drop-down:editable": "/*下拉按钮样式(需要将editable设置为真才生效,内容可编辑)*/",
                  "QComboBox:!editable:on": "/*拉下列表展开时,编辑框样式*/",
                  "QComboBox::drop-down:!editable:on": "/*拉下列表展开时,下拉按钮样式*/",
                  "QComboBox:on": "/*拉下列表展开时,文本的样式*/",
                  "QComboBox::down-arrow": "按钮里的图标样式",
                  "QComboBox::down-arrow:on": "/*拉下列表展开时，移动箭头*/"
                  },
    ("QCheckBox",): {"QCheckBox": "/*复选框,将tristate设置为真时有三种状态(选中,未选中,待选中)*/",
                  "QCheckBox::indicator": "/*文本旁边的标志样式*/",
                  "QCheckBox::indicator:unchecked": "/*文本旁边的标志没有选中时的样式*/",
                  "QCheckBox::indicator:unchecked:hover": "/*文本旁边的标志没有选中时的鼠标放上去时的样式*/",
                  "QCheckBox::indicator:unchecked:pressed": "/*文本旁边的标志没有选中按下时一瞬间的样式*/",
                  "QCheckBox::indicator:checked": "/*文本旁边的标志选中时的样式*/",
                  "QCheckBox::indicator:checked:hover": "/*文本旁边的标志选中时的鼠标放上去时的样式*/",
                  "QCheckBox::indicator:checked:pressed": "/*文本旁边的标志选中按下时一瞬间的样式*/",
                  "QCheckBox::indicator:indeterminate:hover": "/*文本旁边的标志待选中时的鼠标放上去时的样式(需要将tristate设置为真才生效)*/",
                  "QCheckBox::indicator:indeterminate:pressed": "/*文本旁边的标志待选中按下时一瞬间的样式(需要将tristate设置为真才生效)*/"},
    ("QGroupBox",): {"QGroupBox": "/*组合框(与QCheckBox样式相似)*/",
                  "QGroupBox::title": "/*标题样式*/",
                  "QGroupBox::indicator": "/*标题旁边控件样式(需要将checkable)设置为真才生效*/",
                  "QGroupBox::indicator:unchecked": "/*标题旁边控件没有选中时的样式(需要将checkable)设置为真才生效)*/"
                  },
    ("QListView",): {"QListView": "/*列表视图*/",
                  "QListView::item:alternate": "/**/",
                  "QListView::item:selected": "/**/",
                  "QListView::item:selected:!active": "/**/",
                  "QListView::item:selected:active": "/**/",
                  "QListView::item:hover": "/**/"
                  },
    ("QListWidget",): {"QListWidget": "/*列表视图*/",
                       "QListWidget::item:alternate": "/**/",
                       "QListWidget::item:selected": "/**/",
                       "QListWidget::item:selected:!active": "/**/",
                       "QListWidget::item:selected:active": "/**/",
                       "QListWidget::item:hover": "/**/"
                       },
    ("QProgressBar",): {"QProgressBar": "/*进度条*/",
                     "QProgressBar::chunk": "进度条中间颜色区域样式"},
    ("QScrollBar",): {"QScrollBar": '''
            /*滚动条样式
            QScrollBar 指所有滚动条样式
            QScrollBar:horizontal 水平
            QScrollBar:vertical  垂直
            */
            ''',
                   "QScrollBar:horizontal": "/*水平滚动条样式*/",
                   "QScrollBar::handle:horizontal": "/*水平滚动条中手柄的样式*/",
                   "QScrollBar::add-line:horizontal": "/*水平滚动条最右边按钮样式*/",
                   "QScrollBar::sub-line:horizontal": "/*水平滚动条最左边按钮样式*/",
                   "QScrollBar:vertical": "/**/",
                   "QScrollBar::handle:vertical": "/**/",
                   "QScrollBar::add-line:vertical": "/**/",
                   "QScrollBar::sub-line:vertical": "/**/"},
    ("QSlider",):{"QSlider":
                    '''
                    /*
                    滑动条
                    QSlider 指所有滑动条
                    还有 horizontal vertical
                    */
                    ''',
                   "QSlider::groove:horizontal":"/*水平凹槽样式*/",
                   "QSlider::handle:horizontal":"/*水平手柄样式*/",
                   "QSlider::add-page:horizontal":"/*更改手柄前后滑块部分的样式*/",
                   "QSlider::sub-page:horizontal":"/*更改手柄前后滑块部分的样式*/",
                   "QSlider::groove:vertical": "/**/",
                   "QSlider::handle:vertical": "/**/",
                   "QSlider::add-page:vertical": "/**/",
                   "QSlider::sub-page:vertical": "/**/"
                   },
    ("QSpinBox",):{"QSpinBox":"/*微调框*/",
                    "QSpinBox::up-button":"/*上按钮样式*/",
                    "QSpinBox::up-button:hover":"鼠标放在上按钮时的样式",
                    "QSpinBox::up-button:pressed":"鼠标按下 下按钮时的样式",
                    "QSpinBox::up-arrow":"上按钮里小箭头样式",
                    "QSpinBox::down-button":"/*下按钮样式*/",
                    },
    ("QTabWidget",):{"QTabWidget":
                        '''
                        /*
                        标签窗口
                        好用的属性设置
                        documentMode 文档模式
                        tabsCloseable 标签按钮上出现关闭标志
                        movable 标签可移动
                        */
                        ''',
                      "QTabWidget::pane":"/*标签下面框架的样式*/",
                      "QTabBar::tab":"/*标签样式*/",
                      "QTabWidget::tab-bar":"/*标签栏样式(设置颜色无效)*/",
                      "QTabBar::tab:hover":"/*鼠标放在标签上时的样式*/",
                      "QTabBar::tab:selected":"/*标签被选择时的样式*/",
                      "QTabBar::tab:!selected":"/*标签没有被选择时的样式*/",
                      "QTabBar::close-button":"/*关闭按钮的样式(需要将tabsCloseable设置为真才生效)*/",
                      "QTabBar::close-button:hover":"/*鼠标放在关闭按钮上时的样式(需要将tabsCloseable设置为真才生效)*/"
                      },
    ("QTableView",):{"QTableView":"/*表格视图*/",
                      "QTableView QTableCornerButton::section":"/*角落部件样式*/"
                      },
    ("QTreeView",):{"QTreeView":"/*树视图*/",
                     "QTreeView::item":"/**/",
                     "QTreeView::item:hover":"/**/",
                     "QTreeView::item:selected":"/**/",
                     "QTreeView::item:selected:active":"/**/",
                     "QTreeView::item:selected:!active":"/**/",
                     "QTreeView::branch":"/*分支样式*/"},
}

def getStyles(key):
    if isinstance(key,str):
        key = key,
    return STYLE_LIB[key]

# 返回可操作的样式列表
def getStyleLists(key)->list:
    return list(getStyles(key).keys())

# 返回可操作的样式列表说明
def getStyleCommentLists(key)->list:
    return list(getStyles(key).values())

# 融合两个样式列表
def getMergeStyles(style1:list,style2:list)->list:
    return list(set(style1) | set(style2))

# print(getMergeStyles(["QPushButton"],["QPushButton","QPushButton:hover"]))


n = int(input())
last = float(input())

min_freq = 30.0
max_freq = 4000.0
closer = 'closer'

for i in range(n-1):
    now, cl_or_fr = input().strip().split()
    now = float(now)
    now_freq = (last + now) / 2
    if abs(max_freq - min_freq) < 10 ** (-6):
        continue
    now_max, now_min = max(min_freq, now_freq), min(max_freq, now_freq)
    if cl_or_fr == closer:
        if last < now:
            min_freq = now_max
        else:
            max_freq = now_min
    else:
        if last < now:
            max_freq = now_min
        else:
            min_freq = now_max
    last = now

print(min_freq, max_freq)


from multiprocessing import Process, current_process
from time import sleep
import numpy as np

import allogger

def worker_process(id):
    if id % 2 == 0:
        logger = allogger.get_logger(f'worker')
    else:
        logger = allogger.get_logger(scope=f'worker', logdir=f'/tmp/allogger/multiprocessing/{current_process().name}')

    for i in range(10):
        logger.log(i, 'value')
        sleep(np.random.uniform(1, 5))

    if id % 2 != 0:
        allogger.close()

def main():
    allogger.basic_configure('/tmp/allogger/multiprocessing', ['tensorboard'])
    logger = allogger.get_logger('main')

    for i in range(10):
        logger.log(i, 'value')
        sleep(np.random.uniform(1, 5))

    workers = []
    for i in range(20):
        worker = Process(target=worker_process,
                                         args=(i,))
        workers.append(worker)
        worker.start()
    for w in workers:
        w.join()

    allogger.close()

if __name__ == '__main__':
    main()


'''
下载斗罗大第一集
流程：
    1.拿到710-1-1.html页面源代码
    2.从代码中提取m3u8的url
    3.下载m3u8
    4.读取m3u8文件，下载视频
    5.合并视频
'''

import requests
import re
import asyncio
import aiohttp
import aiofiles
import os

# 1.拿到710-1-1.html页面源代码
# 2.从代码中提取m3u8的url

# https://v.v1kd.com/20211117/ttxgRz2V/index.m3u8（第一个m3u8）
# https://v.v1kd.com/20211117/ttxgRz2V/1000kb/hls/index.m3u8（第二个m3u8）

def get_m3u8(url):
    resp = requests.get(url)
    text = resp.text
    resp.close()

    # 从JavaScript提取最好使用re
    obj = re.compile(r'
正在播放(?P<name>.*?)
.*?'
                     r'


from windpowerlib import WindTurbine
import pandas as pd
BATTERY_CAPACITY = 1000

# radius of a turbine is r_turbine=10 meters
R_turbine = 10

# there are 10 turbines
Num_turbine = 1

# the wind power equation is p=v*v*v*0.0006 in W
Conversion_factor = 0.6

# specification of own wind turbine (Note: power curve values and
# nominal power have to be in Watt)
my_turbine = {
    'nominal_power': 3e6,  # in W
    'hub_height': 105,  # in m
    'power_curve': pd.DataFrame(
        data={'value': [p * 1000 for p in [
            0.0, 26.0, 180.0, 1500.0, 3000.0, 3000.0]],  # in W
            'wind_speed': [0.0, 3.0, 5.0, 10.0, 15.0, 25.0]})  # in m/s
}
# initialize WindTurbine object
my_turbine = WindTurbine(**my_turbine)

rutland504 = {
    'nominal_power': 3e6,  # in W
    'hub_height': 10,  # in m
    'power_curve': pd.DataFrame(
        data={'value': [
            0.0, 0.0, 3.0, 11.1, 29.0, 39.0],  # in W
            'wind_speed': [0.0, 3.0, 5.1, 7.0, 11.0, 13.0]})  # in m/s
}
# initialize WindTurbine object
rutland504 = WindTurbine(**rutland504)

n100 = {
    'hub_height': 100,
    'turbine_type': 'N100/2500'}
n100 = WindTurbine(**n100)

e48 = {
    'hub_height': 100,
    'turbine_type': 'E48/800'}
e48 = WindTurbine(**e48)


import sys
sys.stdin = open("input.txt", "r")
input= sys.stdin.readline

T = int(input())
def do_the_cases(T):
    for i in range(T):
        N= int(input())
        ranks = [None for _ in range(N+1)]
        cnt = 0 # 합격자 수
        for i in range(N):
            document, interview = map(int, input().split())
            ranks[document] = interview
        lowest_interview_rank = N+1
        for i in range(1, N+1) :
            if ranks[i] < lowest_interview_rank : #면접 등수가 최저 면접 등수보다 작을 때 (즉 등수가 더 높을 때)
                cnt +=1 # 합격자!
                lowest_interview_rank = ranks[i]
        print(cnt)
do_the_cases(T)


import math

class Solution(object):
    def nearestValidPoint(self, x, y, points):
        vai_points = [point for point in points if point[0] == x or point[1] == y]

        if len(vai_points) == 0:
            return -1
        elif len(vai_points) == 1:
            return points.index(vai_points[0])

        val_list = {points.index(p): abs(p[0] - x) + abs(p[1] - y) for p in vai_points}
        return [k for k, v in val_list.items() if v == min(val_list.values())][0]

    def little_faster(self, x, y, points):
        minDist = math.inf
        ans = -1
        for i in range(len(points)):
            if points[i][0] == x or points[i][1] == y:
                manDist = abs(points[i][0] - x) + abs(points[i][1] - y)
                if manDist < minDist:
                    ans = i
                    minDist = manDist
        return ans

if __name__ == '__main__':
    i_points = [[25, 45], [60, 19], [11, 38], [32, 22], [1, 24], [26, 25], [52, 36], [45, 54], [45, 30], [45, 39],
                [39, 38],
                [25, 38], [39, 57], [47, 51], [47, 49], [37, 21], [16, 43], [53, 33], [10, 50], [30, 29], [3, 31],
                [45, 26],
                [22, 40], [2, 31], [57, 42], [25, 42], [37, 13], [13, 54], [17, 5], [50, 32]]
    i_x = 28
    i_y = 51

    run = Solution()
    print(run.nearestValidPoint(i_x, i_y, i_points))

All Problems/1779. Find Nearest Point That Has the Same X or Y Coordinate.py