import pandas as pd
import ast  # For safely evaluating strings as Python literals
import matplotlib.pyplot as plt

def extract_bitstring_array(bitstring_timeline):
    """
    Extracts and cleans bitstrings from the 'BranchBitstringTimeline' column.
    """
    second_array_str = bitstring_timeline.split('array([')[-1].split('])')[0]
    bitstrings = [s.strip().replace('[', '').replace(']', '').replace(' ', '') for s in second_array_str.split(',')]
    cleaned_bitstrings = [''.join(filter(lambda x: x in '01', s)) for s in bitstrings]
    return cleaned_bitstrings

def pad_bitstrings(bitstrings):
    """
    Pads the bitstrings in the array to ensure equal length.
    """
    max_length = max(len(bitstring) for bitstring in bitstrings)
    return [bitstring.ljust(max_length, '0') for bitstring in bitstrings]

def plot_bitstrings(bitstrings):
    """
    Plots the bitstrings with different colors for 0s and 1s.
    """
    plt.figure(figsize=(12, 8))
    for i, bitstring in enumerate(bitstrings):
        for j, bit in enumerate(bitstring):
            color = 'blue' if bit == '1' else 'red'
            plt.plot(j, i, color=color, marker='o', markersize=4 if bit == '0' else 6)
    plt.xlabel('Entry in Array')
    plt.ylabel('Position in Array')
    plt.title('Bitstring Changes Over Time')
    plt.show()

def parsing_function(string_data):
    # Remove 'array', parentheses, and potentially problematic whitespace characters
    clean_data = string_data.replace('array', '').replace('(', '').replace(')', '')
    clean_data = clean_data.replace('\n', '').replace('\20', '').replace('\t', '').replace(' ', '')

    try:
        # Evaluate the cleaned string
        timeline = ast.literal_eval(clean_data)
        return timeline if len(timeline) == 2 else ([], [])
    except Exception as e:
        print(f"Error parsing string: {e}")
        return [], []

def apply_cumulative_coverage(bitstrings, final_coverage_bitstring):
    """Apply cumulative coverage logic to bitstrings based on the final coverage bitstring."""
    cumulative_bitstring = ['0'] * len(final_coverage_bitstring)
    for i, bitstring in enumerate(bitstrings):
        for j, bit in enumerate(bitstring):
            if bit == '1' or (cumulative_bitstring[j] == '1' and final_coverage_bitstring[j] == '1'):
                cumulative_bitstring[j] = '1'
        bitstrings[i] = ''.join(cumulative_bitstring)
    return bitstrings

def calculate_coverage(bitstring):
    """Calculate coverage as the number of '1's divided by the length of the bitstring."""
    if bitstring:
        return bitstring.count('1') / len(bitstring)
    return 0

def apply_cumulative_coverage(bitstrings, final_coverage_bitstring):
    """
    Apply cumulative coverage logic to bitstrings based on the final coverage bitstring.
    """
    cumulative_bitstring = list(final_coverage_bitstring)  # Start with the final coverage bitstring
    aggregated_bitstrings = []

    for bitstring in bitstrings:
        for index, bit in enumerate(bitstring):
            # Update the cumulative bitstring: once a bit is covered, it remains covered
            if bit == '1':
                cumulative_bitstring[index] = '1'
        # Append the current state of the cumulative bitstring to the list
        aggregated_bitstrings.append(''.join(cumulative_bitstring))

    return aggregated_bitstrings

# Example usage:
# final_coverage = '11001'  # This is the final coverage bitstring
# bitstring_timeline = ['00000', '01000', '11000', '10001']  # Sample timeline of bitstrings
# aggregated_timeline = apply_cumulative_coverage(bitstring_timeline, final_coverage)
# print(aggregated_timeline)  # Output: ['00000', '01000', '11000', '11001']

def apply_cumulative_coverage_to_row(row):
    """
    Applies cumulative coverage logic to a single row of the DataFrame.
    """
    # Extract the bitstrings and the final coverage bitstring from the row
    bitstrings = row['BranchBitstringTimeline']
    final_coverage_bitstring = row['BranchCoverageBitString']

    # Apply the cumulative coverage logic
    aggregated_bitstrings = apply_cumulative_coverage(bitstrings, final_coverage_bitstring)

    return aggregated_bitstrings

# Load the reference dataset and create a set of (Project, Bug) IDs
reference_df = pd.read_csv('final_filtered_reduced_dataset.csv')
reference_ids = set(zip(reference_df['Project'], reference_df['Bug']))

# Initialize an empty DataFrame to hold the unified data
unified_df = pd.DataFrame()

# Load each "1-" CSV file, filter and collect the data
csv_files = ['1-complement_data_wave_1.csv', '1-complement_data_wave_2.csv', '1-everyTrialReport.csv']
for file in csv_files:
    temp_df = pd.read_csv(file)
    temp_df['ID_tuple'] = list(zip(temp_df['Project'], temp_df['Bug']))
    temp_df = temp_df[temp_df['ID_tuple'].isin(reference_ids)]
    temp_df = temp_df.drop('ID_tuple', axis=1)
    unified_df = pd.concat([unified_df, temp_df], ignore_index=True)

# Remove entries where 'Generation_success' equals 0
unified_df = unified_df[unified_df['Generation_success'] != 0]

# Save the filtered unified DataFrame to a new CSV
#unified_df.to_csv('unified_dataset_filtered.csv', index=False)

data = unified_df

# Apply the functions
data['BranchBitstringTimeline'] = data['BranchBitstringTimeline'].apply(extract_bitstring_array)
data['BranchBitstringTimeline'] = data['BranchBitstringTimeline'].apply(pad_bitstrings)
data.drop(columns=['BranchCoverageTimeline'], inplace=True)
# Example of plotting the first entry
#plot_bitstrings(data['Padded_Bitstrings'].iloc[0])  # Remove this line if plotting is not needed

# Optionally, save the processed data
data.to_csv('unified_dataset_filtered.csv', index=False)

# Save the first 5 entries to a separate file
data.head(8).to_csv('first_8_entries.csv', index=False)


# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
import os
import socket
import struct
import cv2
import face_recognition
import time
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer

app = Flask(__name__)

UPLOAD_PATH = '/data/img/upload'
VIDEO_IMG_PATH = '/data/img/tmp'
VIDEO_LIST_PATH = ['rtsp://172.31.34.43/stream2']
STORAGE_PATH = 'http://172.28.50.66:11111'

@app.route('/api/upload', methods=['POST', 'GET'])
def uploads():
    if request.method == 'POST':
        f = request.files['file']
        t = int(time.time())
        upload_path = os.path.join(UPLOAD_PATH, str(t) + '_' + f.filename)
        f.save(upload_path)
        return upload_path

@app.route('/api/video_list', methods=['POST', 'GET'])
def get_video_list():
    if request.method == 'GET':
        result = []
        for p in VIDEO_LIST_PATH:
            video_img_path = get_video_img(p)
            data = {
                'img': STORAGE_PATH + video_img_path,
                'tunnel': p,
            }
            result.append(data)

        return jsonify(result)

def get_video_img(v):
    start = time.time()
    cap = SingletonModel(v)
    end = time.time()
    print(end - start)
    if cap.isOpened():
        ret, frame = cap.read()
        ip = v.split('/')[2]
        ip_int = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip)))[0])
        t = time.time()
        path = os.path.join(VIDEO_IMG_PATH, str(t) + '_' + str(ip_int) + '_' + 'a.jpg')
        print(path)
        res = cv2.imwrite(path, frame)
        if res:
            return path
        else:
            return 'error: not save img'

class SingletonModel(object):
    tunnul_list = {}

    def __new__(cls, v, *args, **kwd):
        if v in SingletonModel.tunnul_list:
            return SingletonModel.tunnul_list[v]
        else:
            SingletonModel.tunnul_list.update({v: cv2.VideoCapture(v)})
            return SingletonModel.tunnul_list[v]

@app.route('/api/conn_websocket/')
def conn_websocket():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            message = ws.receive()
            ws.send(message)
    return 'success'

if __name__ == '__main__':
    # app.run(host='0.0.0.0', port=8888, debug=True)
    http_server = WSGIServer(('0.0.0.0', 8888), app, handler_class=WebSocketHandler)
    http_server.serve_forever()


import json

import numpy as np
import pandas as pd

f = open('macedonia_map.geojson', encoding='utf-8')
jdata = json.load(f)
mkd_pts = []  # mapa od makedonija

for feature in jdata['features']:
    if feature['geometry']['type'] == 'Polygon':
        mkd_pts.extend(feature['geometry']['coordinates'][0])
        mkd_pts.append([None, None])  # mark the end of a polygon

    elif feature['geometry']['type'] == 'MultiPolygon':
        for polyg in feature['geometry']['coordinates']:
            mkd_pts.extend(polyg[0])
            mkd_pts.append([None, None])  # end of polygon
    elif feature['geometry']['type'] == 'LineString':
        mkd_pts.extend(feature['geometry']['coordinates'])
        mkd_pts.append([None, None])
    else:
        pass
    # else: raise ValueError("geometry type irrelevant for map")

mkd_x, mkd_y = zip(*mkd_pts)

def generate_data():

    return pd.DataFrame({
        "Time": [i for i in range(0, 10) for j in range(0,100)],
        "Latitude": np.random.rand(1000) * 1.1 + 41.04,
        "Longitude": np.random.rand(1000) * 2.36 + 20.53,
        "Count": np.random.rand(1000) * 100,
    }
)


import os
from PIL import Image
import pyocr
import pdf2image #pdfファイルをPIL Imageオブジェクトに変換する
import openpyxl

# pdfファイルをimgオブジェクトに変換
def pdf_to_image(pdf_path):
    img = pdf2image.convert_from_path(pdf_path, 300)
    print(type(img)) #List型
    print(type(img[0])) #PIL.PpmImagePlugin.PpmImageFile型
    return img

# 画像から文字を読み込む
def read_text(img):
    builder = pyocr.builders.TextBuilder(tesseract_layout=3)
    text = tool.image_to_string(img[0], lang='jpn', builder=builder)
    return text

# excelファイルを作成
def make_Excel(filename, text):

    # ファイルの存在確認
    if os.path.exists(filename):
        print('このファイルは存在しています')
        book = openpyxl.load_workbook(filename)
    else:
        print('新規ファイルを作成します')
        # ブックを作成
        book = openpyxl.Workbook()

    book_active = book.active
    print(type(book_active)) #openpyxl.worksheet.worksheet.Worksheet型
    book_active.cell(row=1, column=1).value = 'this'
    book.save(filename)

if __name__ == '__main__':
    path='C:/Program Files/Tesseract-OCR/tesseract.exe'
    # tesseractパスをセット
    pyocr.tesseract.TESSERACT_CMD = path
    tools = pyocr.get_available_tools()
    tool = tools[0]

    # pdfファイルのパスをセット
    pdf_path = 'C:/Users/shodai/Downloads/sample.pdf'
    img = pdf_to_image(pdf_path)
    text = read_text(img)
    make_Excel('sample.xlsx', text)


from csc148_queue import Queue

def list_queue(lst, queue):
    for item in lst:
        queue.add(item)

    while not queue.is_empty():
        q_1 = queue.remove()
        if isinstance(q_1, list):
            for item in q_1:
                queue.add(item)
        else:
            print(q_1)

if __name__ == '__main__':
    q = Queue()
    #i = int(input('type a int:'))

    #while i != 148:
    #    q.add(i)
    #    i = int(input('type a int:'))

    #print(sum(q._content))

    list_1 = [1, 3, 5]
    list_2 = [1, [3, 5], 7]
    list_3 = [1, [3, [5, 7], 9], 11]
    #list_queue(list_1, q)
    #list_queue(list_2, q)
    list_queue(list_3, q)


from odoo import models, fields, api, _

class ResConfigSettings(models.TransientModel):
    _inherit = 'res.config.settings'

    l10n_sa_api_mode = fields.Selection(related='company_id.l10n_sa_api_mode', readonly=False)

    @api.depends('company_id')
    def _compute_company_informations(self):
        super()._compute_company_informations()
        for record in self:
            if self.company_id.country_code == 'SA':
                record.company_informations += _(
                    '\nBuilding Number: %s, Plot Identification: %s\nNeighborhood: %s',
                    self.company_id.l10n_sa_edi_building_number,
                    self.company_id.l10n_sa_edi_plot_identification,
                    self.company_id.street2,
                )


"""
This file is part of the Verifying explainability of a deep learning tissue classifier trained on RNA-seq data project.

Verifying explainability of a deep learning tissue classifier trained on RNA-seq data project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Verifying explainability of a deep learning tissue classifier trained on RNA-seq data project is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with the Verifying explainability of a deep learning tissue classifier trained on RNA-seq data project.  If not, see <http://www.gnu.org/licenses/>.
"""
from sklearn.utils.random import sample_without_replacement
from sklearn.cluster import KMeans
from sklearn import metrics
import numpy as np

def get_kmeans_score(umap_df, label_col, verb=True):
    umap_unlabel = umap_df.drop(label_col, axis=1)
    km = KMeans(n_clusters=29, n_init=100, max_iter=10000, init="random")
    km_arr = km.fit_predict(umap_unlabel)
    umap_df["km"] = km_arr
    if verb == True:
        print(
            "Homogeneity: ", metrics.homogeneity_score(umap_df["type"], umap_df["km"])
        )
        print(
            "Completeness: ", metrics.completeness_score(umap_df["type"], umap_df["km"])
        )
        print("V-measure: ", metrics.v_measure_score(umap_df["type"], umap_df["km"]))
    return umap_df

def get_kmeans_dict(umap_df, label_col):
    kmeans_dict = {}
    umap_df = get_kmeans_score(umap_df, "type", verb=False)
    kmeans_dict["Homogeneity"] = metrics.homogeneity_score(
        umap_df["type"], umap_df["km"]
    )
    kmeans_dict["Completeness"] = metrics.completeness_score(
        umap_df["type"], umap_df["km"]
    )
    kmeans_dict["V-Measure"] = metrics.v_measure_score(umap_df["type"], umap_df["km"])
    return kmeans_dict

    umap_df_dict[i] = [shap_umap_df, random_umap_df, edger_umap_df, full_umap_df]

def get_random_gene_df(gene_df, n_genes, label_col="type"):
    labels = gene_df.loc[:, label_col]
    unlab_df = gene_df.drop(label_col, axis=1)
    index_set = sample_without_replacement(gene_df.shape[1], n_genes)
    gene_arr_all = gene_df.columns
    gene_arr_rand = gene_arr_all[index_set]
    gene_df_rand = gene_df[gene_arr_rand]
    gene_df_rand["type"] = labels
    return gene_df_rand

def get_p_value(alt_hypo, test_stat_null, num_samples):
    """
    Params:
        @null_hypo <list> : list of bootstrap samples from the null hypothesis
        @test_hypo <float> : single statistic we are doing the test on
    """
    alt_hypo = np.array(alt_hypo)
    p_value = 1-(len(alt_hypo[alt_hypo >= test_stat_null])/len(alt_hypo))
    if p_value == 0.0:
        p_value = 1/num_samples
    return p_value


import torch
from config import cfg
from models.net import choose_net
import torchvision.transforms as T
from dataset import MyData
from torch.utils.data import DataLoader
from utils.utils import get_transform
from tqdm import tqdm
from torch.nn import functional as F
import numpy as np
from PIL import Image

USE_CUDA = torch.cuda.is_available()
device = torch.device("cuda:0" if USE_CUDA else "cpu")
config_files = ['../input/b2b3b4-1/configs/efficientnetb2.yaml', '../input/b2b3b4-1/configs/efficientnetb3.yaml', '../input/b2b3b4-1/configs/efficientnetb4.yaml']

def load_model(config_file, imgs_path):
    outputs = None
    # for config_file in config_files:
    cfg.merge_from_file(config_file)
    model = choose_net(name=cfg.MODEL.NAME, num_classes=cfg.MODEL.CLASSES, weight_path=cfg.MODEL.WEIGHT_FROM)

    # weight_path = cfg.MODEL.MODEL_PATH + cfg.MODEL.NAME + '.pth'
    weight_path = '../input/b2b3b4-2/weights/'+ cfg.MODEL.NAME + '.pth'
    checkpoint = torch.load(weight_path)
    state_dict = checkpoint['state_dict']
    model.load_state_dict(state_dict)
    model.to(device)
    model.eval()
    transform = T.Compose([
        T.Resize(cfg.INPUT.SIZE_TRAIN),
        T.ToTensor(),
        T.Normalize(mean=cfg.INPUT.PIXEL_MEAN, std=cfg.INPUT.PIXEL_STD)
    ])

    for img_path in imgs_path:
        img = Image.open(img_path).convert('RGB')
        img = transform(img)
        img = img.unsqueeze(0)
        img = img.cuda()
        with torch.no_grad():
            output, _ = model(img)
            if outputs is None:
                outputs = output
            else:
                outputs = torch.cat((outputs, output), dim=0)
    return outputs, imgs_name

if __name__=='__main__':

    import os
    from os.path import join
    from tqdm import tqdm
    import pandas as pd

    root = '/kaggle/input/cassava-leaf-disease-classification'
    path_dir = join(root, 'test_images')
    imgs_name = os.listdir(path_dir)
    imgs_path = [os.path.join(path_dir, e) for e in imgs_name]
    pred = torch.zeros(size=[len(imgs_name), 5])
    for config_file in config_files:
        output, imgs_name = load_model(config_file, imgs_path)
        pred += output.cpu()/3
    pred = F.softmax(pred, dim=1).cpu().numpy()
    pred = pred.argmax(1)
    sub = pd.DataFrame({'image_id': imgs_name, 'label': pred})
    # print(sub)
    sub.to_csv("submission.csv", index=False)


"""Web handlers for items"""

import Context
import Util
from Item import Item
from Logger import log
from mod_python import apache

def item_handler(req, player, target, components):
	"""Handle a request for item information, for the given target ID"""
	if len(components) != 1:
		return apache.HTTP_NOT_FOUND

	req.content_type = "text/plain"
	item = Item.load(target)

	if req.method != 'GET':
		# If it's not a GET request, throw a wobbly
		return apache.HTTP_METHOD_NOT_ALLOWED

	log.debug("Item handler: requested " + str(components))
	if components[0] == 'desc':
		# Get description
		info = item.context_get(player.get_context())
		Util.render_info(info, req)
	else:
		return apache.HTTP_NOT_FOUND

	return apache.OK

def item_names_handler(req, components):
	"""Handle a request for item class information"""
	# We must have at most one component in the request URL
	if len(components) > 1:
		return apache.HTTP_NOT_FOUND

	req.content_type = "text/plain"

	# Now handle everything else: it's all GETs from here on
	if req.method != 'GET':
		# If it's not a GET, throw a wobbly
		return apache.HTTP_METHOD_NOT_ALLOWED

	log.debug("Items handler: requested " + str(components))
	if len(components) == 0:
		for icls in Item.list_all_classes():
			write_class(req, icls)
	else:
		if not write_class(req, components[0]):
			return apache.HTTP_NOT_FOUND

	return apache.OK

def write_class(req, name):
	"""Get the class details for the given class (name), and render it
	back to the requester. Return True if successful."""
	try:
		cls = Item.get_class(name)
	except ImportError:
		return False

	req.write(name + ":" + cls.name_for() + "\n")

	return True


#!/usr/bin/python
# -*- coding: utf-8 -*-
import keyboard
import time

filename = 'codes.txt'
COUNT = 0

def incrementCode():
    global COUNT
    COUNT = COUNT + 1

def resetCode():
    global COUNT
    COUNT = 0

def printCode():
    with open(filename) as fp:
        for (i, code) in enumerate(fp):
            if i == COUNT:
                code = code.strip('\n')
                code = code.strip('\t')
                print ('Attempting code', code)
                for num in list(code):
                    time.sleep(0.22)
                    keyboard.press(num)
                    time.sleep(0.05)
                    keyboard.release(num)

                if 'str' in code:
                    break
                break

    incrementCode()

keyboard.add_hotkey('ctrl+.', printCode)
keyboard.add_hotkey('ctrl+]', resetCode)

keyboard.wait('ctrl+shift+0')


import itertools
import re
import collections

L = '<'
R = '>'
LEFT = '<'
RIGHT = '>'

class NgrexPattern(object):
    """
    A NgrexPattern is a tgrep-type pattern for matching node configurations in Networkx structures.
    """

    def __init__(self):
        self._pattern = None

    def finditer(self, graph):
        """
        Returns an iterator yielding MatcherObj instances over all matches for the ngrex pattern
        in graph.

        Args:
            graph(DiGraph): graph

        Yields:
            MatcherObj: an iterator yielding MatcherObj instances over all matches for the
                ngrex pattern in graph.
        """
        raise NotImplementedError('Should have implemented this')

    @property
    def pattern(self):
        """
        str: The pattern string from which the ngrex object was compiled.
        """
        return self._pattern

    def __str__(self):
        return self.pattern

class NodePattern(NgrexPattern):
    def __init__(self, attributes, name=None):
        super(NodePattern, self).__init__()
        self._name = name
        self._attributes = _get_attributes_regex(attributes)
        self._pattern = '{' + _attributes_to_str(self._attributes) + '}'
        if name:
            self._pattern += '=' + name

    def finditer(self, graph):
        for node in graph.nodes():
            if self._attributes:
                if _match(self._attributes, graph.node[node]):
                    yield MatcherObj(self, graph, [(self._name, node)])
            else:
                yield MatcherObj(self, graph, [(self._name, node)])

class EdgePattern(NgrexPattern):
    def __init__(self, governor, dependant, edge_attributes, direction=LEFT):
        """
        Args:
            direction(str): right if 'governor >edge dependant', left if 'dependant <edge governor'
        """
        super(EdgePattern, self).__init__()
        self._governor = governor
        self._dependant = dependant
        self._direction = direction
        self._edge_attributes = _get_attributes_regex(edge_attributes)

        if self._direction == LEFT:
            args = (dependant, '<', governor)
        else:
            args = (governor, '>', dependant)
        self._pattern = '({args[0].pattern}) {args[1]}{{{edge}}} ({args[2].pattern})'.format(
            args=args, edge=_attributes_to_str(self._edge_attributes))

    def finditer(self, graph):
        governors = self._governor.finditer(graph)
        dependants = self._dependant.finditer(graph)
        for g, d in itertools.product(governors, dependants):
            for p, c, e in graph.edges(data=True):
                if p == g.group(0) and c == d.group(0):
                    if _match(self._edge_attributes, e):
                        if self._direction == LEFT:
                            yield MatcherObj(self, graph, d._nodes + g._nodes)
                        else:
                            yield MatcherObj(self, graph, g._nodes + d._nodes)

class CoordinationPattern(NgrexPattern):
    def __init__(self, pattern1, pattern2, is_conj=True):
        """
        Args:
            is_conj(bool): if is_conj is true, then it is an "AND"; otherwise, it is an "OR".
        """
        super(CoordinationPattern, self).__init__()
        self._pattern1 = pattern1
        self._pattern2 = pattern2
        self._is_conj = is_conj
        self._pattern = '{} {} {}'.format(pattern2.pattern,
                                          '&' if is_conj else '|',
                                          pattern1.pattern)

    def finditer(self, graph):
        if self._is_conj:
            matchers1 = self._pattern1.finditer(graph)
            matchers2 = self._pattern2.finditer(graph)
            for m1, m2 in itertools.product(matchers1, matchers2):
                if m1.group(0) == m2.group(0):
                    nodes = list(m1._nodes)
                    if len(m2._nodes) > 2:
                        nodes.extend(m2._nodes[1:])
                    yield MatcherObj(self, graph, nodes)
        else:
            for m in self._pattern1.finditer(graph):
                yield m
            for m in self._pattern2.finditer(graph):
                yield m

class MatcherObj:
    """
    Match objects always have a boolean value of True.
    """

    def __init__(self, pattern, graph, nodes):
        """
        Args:
            nodes(list): [(name, node)]
        """
        self._pattern = pattern
        self._graph = graph
        self._nodes = nodes

    def __bool__(self):
        return True

    def group(self, index):
        """
        Returns the input node captured by the given group during the previous match operation.
        """
        return self._nodes[index][1]

    def groups(self):
        """
        Returns a list containing all the subgroups of the match, from 0 up to however many nodes
        are in the pattern.
        """
        return (node[1] for node in self._nodes)

    def get(self, name):
        for node in self._nodes:
            if node[0] == name:
                return node[1]
        raise KeyError(name)

    @property
    def pattern(self):
        """
        The expression object whose `finditer()` produced this instance
        """
        return self._pattern

    @property
    def graph(self):
        """
        The graph passed to `finditer()`
        """
        return self._graph

def validate_names(pattern):
    def _helper(p, names):
        if isinstance(p, NodePattern):
            if p._name in names:
                raise KeyError(p._name)
            if p._name:
                names.add(p._name)
        elif isinstance(p, EdgePattern):
            _helper(p._governor, names)
            _helper(p._dependant, names)
        elif isinstance(p, CoordinationPattern):
            _helper(p._pattern1, names)
            _helper(p._pattern2, names)
    _helper(pattern, set())

def _get_attributes_regex(attributes):
    def _get_regex(v):
        v = v[1:-1]
        if v:
            if v[0] != '^':
                v = '^' + v
            if v[-1] != '$':
                v += '$'
        return re.compile(v)
    return {k: _get_regex(v) for k, v in attributes.items()}

def _match(attributes, element):
    for k, v in attributes.items():
        if k not in element or not v.match(element[k]):
            return False
    return True

def _attributes_to_str(attributes):
    return ','.join(['{}:/{}/'.format(k, v.pattern) for k, v in attributes.items()])


"""
Class to represent a variable returned by the ESMValTool preprocessor.

Matt Nicholson
22 May 2020
"""
import iris
import logging

from esmvalcore.preprocessor import area_statistics

class ESMVariable:

    def __init__(self, var_dict):
        """
        ESMVariable instance constructor.

        Parameters
        ----------
        var_dict : dictionary
            Dictionary containing variable metadata returned by the ESMValTool
            preprocessor.

        Returns
        -------
        ESMVariable object.
        """
        self.activity       = var_dict['activity']
        self.alias          = var_dict['alias']
        self.dataset        = var_dict['dataset']
        self.diagnostic     = var_dict['diagnostic']
        self.end_year       = var_dict['end_year']
        self.ensemble       = var_dict['ensemble']
        self.exp            = var_dict['exp']
        self.filename       = var_dict['filename']
        self.frequency      = var_dict['frequency']
        self.grid           = var_dict['grid']
        self.institute      = var_dict['institute']
        self.long_name      = var_dict['long_name']
        self.mip            = var_dict['mip']
        self.modeling_realm = var_dict['modeling_realm']
        self.preprocessor   = var_dict['preprocessor']
        self.project        = var_dict['project']
        self.recipe_dataset_index = var_dict['recipe_dataset_index']
        self.short_name     = var_dict['short_name']
        self.standard_name  = var_dict['standard_name']
        self.start_year     = var_dict['start_year']
        self.units          = var_dict['units']
        self.variable_group = var_dict['variable_group']
        self.level          = self._parse_var_level()
        self.cube           = self._parse_cube()
        self._log_obj()

    def update_cube(self, new_cube):
        """
        Update the value of an ESMVariable instance's cube attribute.

        Parameters
        ----------
        var_cube : Iris cube
            Iris cube containing the data of the variable represented in the
            ESMVariable instance.

        Returns
        -------
        None.
        """
        self.cube = new_cube

    def get_area_statistic(self, stat):
        """
        Get the area statistic of an ESMVariable instance's Iris cube.

        Parameters
        ----------
        stat : str
            Area statistic. Passed to ESMValCore area statistics function.

        Returns
        -------
        ESMVariable instance
            ESMVariable with area statistic cube.
        """
        area_stat_cube = area_statistics(self.cube, stat)
        self.update_cube(area_stat_cube)
        return self

    def _parse_cube(self):
        """
        Read a model output variable into an Iris cube and add it to it's respective
        ESMVariable instance.

        Parameters
        ----------
        None.

        Returns
        -------
        None.
        """
        cube = iris.load_cube(self.filename)
        return cube

    def _parse_var_level(self):
        """
        Parse the level extracted from the variable by the preprocessor,
        if applicable.

        Parameters
        ----------
        self

        Returns
        -------
        None
        """
        vars_3d = ['mmrbc', 'mmrdust', 'mmrso4', 'mmrss', 'so2']
        if self.short_name in vars_3d:
            self.level = '100 hPa'

    def _log_obj(self):
        """
        Write information about an ESMVariable object instance to the ESMVariable
        log file. Logger object MUST already be initialized.

        Parameters
        ----------
        None - HOWEVER a logger object named 'ESMVariable' must be already initialized.
        """
        obj_log = logging.getLogger('ESMVariable')
        attrs = [a for a in dir(self) if not a.startswith('__') and not callable(getattr(self, a))]
        attrs.remove('cube')  # We only want to log the cube's shape, not all it's attributes
        obj_log.debug('New ESMVariable instance created.')
        for attr in attrs:
            obj_log.debug('    {} : {}'.format(attr, getattr(self, attr)))
        obj_log.debug('    Cube shape : {}'.format(self.cube.data.shape))

    def __repr__(self):
        return "<ESMVariable object - {} {} {} {}".format(self.dataset, self.ensemble,
                                                          self.exp, self.short_name)


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from metrics import *

from tree.randomForest import RandomForestClassifier

np.random.seed(42)
print("============================================================")
print("Predicting on iris data")
print("============================================================")
X = pd.read_csv("iris.data")
col = ["sepal length", "sepal width", "petal length", "petal width", "label"]
X.columns = col
X = X.sample(frac=1,random_state=40)
X = X.reset_index(drop=True)
y = X["label"]

X_train = X.loc[:89].reset_index(drop=True)
y_train = X_train["label"]
X_train = X_train.drop(["label"], axis=1)

X_test = X[90:].reset_index(drop=True)
y_test = X_test["label"]
X_test = X_test.drop(["label"], axis=1)

n_estimators = 5
for criteria in ['entropy', 'gini']:

    Classifier_RF = RandomForestClassifier(n_estimators=n_estimators, criterion = criteria, max_depth=None)

    Classifier_RF.fit(X_train, y_train)
    y_hat = Classifier_RF.predict(X_test)
    fig, fig2 = Classifier_RF.plot()
    print('***Criteria :'+str(criteria)+"***")

    print('Accuracy: ', accuracy(y_hat, y_test))
    for cls in y.unique():
        print("***Class :"+str(cls)+"***")
        print('Precision: ', precision(y_hat, y_test, cls))
        print('Recall: ', recall(y_hat, y_test, cls))
#plt.show()


import sys
from random import sample
from JogodaMemoria.memoriagui import *
from PyQt5.QtWidgets import QMainWindow,QApplication
class Main(QMainWindow,Ui_MainWindow):
    # globais
    elementos_matriz = [numero for numero in range(1, 9)]*2
    print(elementos_matriz)
    matriz = []
    jogadas = termina = c = 0
    def __init__(self):
        super().__init__(parent=None)
        super().setupUi(self)
        self.x1 = None
        self.y1 = None
        self.x2 = None
        self.y2 = None
        self.mascara1 = None
        self.mascara2 = None
        self.foi_clicado = None
        self.foi_sorteado = None
        self.forma_matriz()
        self.add_asterisco()
        # Cliques
        self.btn0x0.clicked.connect(self.input_btn0x0)
        self.btn0x1.clicked.connect(self.input_btn0x1)
        self.btn0x2.clicked.connect(self.input_btn0x2)
        self.btn0x3.clicked.connect(self.input_btn0x3)
        self.btn1x0.clicked.connect(self.input_btn1x0)
        self.btn1x1.clicked.connect(self.input_btn1x1)
        self.btn1x2.clicked.connect(self.input_btn1x2)
        self.btn1x3.clicked.connect(self.input_btn1x3)
        self.btn2x0.clicked.connect(self.input_btn2x0)
        self.btn2x1.clicked.connect(self.input_btn2x1)
        self.btn2x2.clicked.connect(self.input_btn2x2)
        self.btn2x3.clicked.connect(self.input_btn2x3)
        self.btn3x0.clicked.connect(self.input_btn3x0)
        self.btn3x1.clicked.connect(self.input_btn3x1)
        self.btn3x2.clicked.connect(self.input_btn3x2)
        self.btn3x3.clicked.connect(self.input_btn3x3)
    def forma_matriz(self):
        """Função que estrutura a matriz 4x4 cobrindo-a com '*' e
        acrescenta False referente ao par ainda não encontrado.
        Estrutura: [valor_sample,'*',False]. Sem parâmetros de entrada."""
        lista_temp = []
        for linha in range(0, 4):
            for coluna in range(1, 5):
                elemento_sorteado = sample(self.elementos_matriz, 1)[0]
                lista_temp.append(elemento_sorteado)
                self.elementos_matriz.remove(elemento_sorteado)
                lista_temp.append('*')
                lista_temp.append(False) # Se o par já foi sorteado
                lista_temp.append(False) # Se já foi clicado
                if coluna % 4 == 0:
                    self.matriz.append(lista_temp)
                    lista_temp = []
            print(self.matriz)
    #Butões
    def setter_btn(self,x,y):
        self.foi_clicado = self.matriz[x][y * 4 + 3]
        self.foi_sorteado = self.matriz[x][y * 4 + 2]
        if self.foi_sorteado is False and self.foi_clicado is False:
            self.matriz[x][y * 4 + 1] = str(self.matriz[x][y * 4]) #asterisco recebendo o valor
            self.matriz[x][y * 4 + 3] = True
            print(self.matriz)
            if self.c == 0:
                self.x1 = x
                self.y1 = y
            else:
                self.x2 = x
                self.y2 = y
                self.c = 0
                return self.verifica(self.x1, self.y1, self.x2, self.y2)
            self.c += 1
    def add_asterisco(self):
        """Função que inicialmente adiciona asteriscos nos botões"""
        for x in range(0, 4):
            for y in range(0, 4):
                eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/ast.png"))')
    def add_icon(self, x, y):
        """Função que adiciona o ícone no botão conforme o valor referente na matriz."""
        if self.matriz[x][y*4] == 1:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g1.png"))')
        elif self.matriz[x][y*4] == 2:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g2.png"))')
        elif self.matriz[x][y*4] == 3:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g3.png"))')
        elif self.matriz[x][y*4] == 4:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g4.png"))')
        elif self.matriz[x][y*4] == 5:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g5.png"))')
        elif self.matriz[x][y*4] == 6:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g6.png"))')
        elif self.matriz[x][y*4] == 7:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g7.png"))')
        else:
            eval(f'self.btn{x}x{y}.setIcon(QtGui.QIcon("icons/g8.png"))')
        return eval(f'self.btn{x}x{y}.setIconSize(QtCore.QSize(140,140))')
    def input_btn0x0(self):
        x, y = 0, 0
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn0x1(self):
        x, y = 0, 1
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn0x2(self):
        x, y = 0, 2
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn0x3(self):
        x, y = 0, 3
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn1x0(self):
        x, y = 1, 0
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn1x1(self):
        x, y = 1, 1
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn1x2(self):
        x, y = 1, 2
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn1x3(self):
        x, y = 1, 3
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn2x0(self):
        x, y = 2, 0
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn2x1(self):
        x, y = 2, 1
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn2x2(self):
        x, y = 2, 2
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn2x3(self):
        x, y = 2, 3
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn3x0(self):
        x, y = 3, 0
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn3x1(self):
        x, y = 3, 1
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn3x2(self):
        x, y = 3, 2
        self.add_icon(x, y)
        return self.setter_btn(x, y)
    def input_btn3x3(self):
        x, y = 3, 3
        self.add_icon(x, y)
        return self.setter_btn(x, y)

    #Verificação dos Pares
    def verifica(self,x1,y1,x2,y2):
        self.jogadas += 1
        if self.matriz[x1][y1 * 4] != self.matriz[x2][y2 * 4]:
            #Retornar asterisco se o par for diferente.
            self.matriz[x1][y1 * 4 + 1] = '*'
            self.matriz[x2][y2 * 4 + 1] = '*'
            #Retornar foi_clicado como False.
            self.matriz[x2][y2 * 4 + 3] = False
            self.matriz[x1][y1 * 4 + 3] = False
            self.ln_resultado.setText('\t\t\tVocê errou... tente de novo.')
            #Retorna asterisco se não formar par.
            eval(f'self.btn{x1}x{y1}.setIcon(QtGui.QIcon("icons/ast.png"))')
            eval(f'self.btn{x2}x{y2}.setIcon(QtGui.QIcon("icons/ast.png"))')
        else:
            self.termina += 1
            self.ln_resultado.setText('\t\t\tParabéns você acertou !')
            #Retornar foi_sorteado como True
            self.matriz[x1][y1 * 4 + 2] = True
            self.matriz[x2][y2 * 4 + 2] = True
            if self.termina == 8:
                self.ln_resultado.setText(f'\t\tParabéns! Você descobriu todos os times com {self.jogadas} jogadas')
        print(f'Jogadas: {self.jogadas}, termina: {self.termina}')
if __name__ == '__main__':
    app = QApplication(sys.argv)
    tela = Main()
    tela.show()
    sys.exit(app.exec_())


import os
import sys
import threading
import queue
import logging
import time

import pyglet

import telebot
import telebot.types
from requests.exceptions import ReadTimeout
from telebot.apihelper import ApiException

import common
from tele_bot.bot_def import *
import version as ver

__all__ = ['TelegramBot', 'like_trhows']

logger = logging.getLogger("{:s}.TelegramBot".format(common.SOLUTION))

def like_trhows(func):
    def wrapped(*args, **kwargs):
        try:
            func(*args, *kwargs)
        except (ReadTimeout, ApiException):
            raise

    return wrapped

class TelegramBot(telebot.TeleBot):
    def __init__(self, token, u_model, m_daemon):
        super().__init__(token)

        logger.info("bot created with token: {:s}".format(token))

        bot = self

        self.__stop_f = False

        self.__model = u_model
        self.__machine_daemon = m_daemon

        self.__reg_state = ''
        self.__reg_pos = None
        self.__reg_item = None

        self.__cam_sel_id = None
        self.__cam_sel_state = None
        self.__cam_sel_state_str = None

        self.__now_requester = None

        self.__create_cam_menu()

        @bot.message_handler(commands=[C_START, C_HELP])
        def handle_start(msg):
            logger.info("Rx \"{:s}\" by {:s} : {:s}".format(msg.text,
                                                            str(msg.chat.id),
                                                            msg.chat.first_name))
            self.__show_m(msg)

        @bot.message_handler(content_types=['audio'])
        def handle_audio(msg):
            audio_file = self.get_file(msg.audio[-1].file_id)
            logger.info("audio: {:s}".format(audio_file))

            song = pyglet.media.load(audio_file)
            song.play()
            pyglet.app.run()

        @bot.message_handler(content_types=['text'])
        def handle_text(msg):
            t_comm = msg.text

            logger.info("Rx \"{:s}\" by {:s} : {:s}".format(t_comm,
                                                        str(msg.chat.id),
                                                        msg.chat.first_name))

            if t_comm == C_A_RES: self.__restart_bot(msg)
            elif t_comm == C_A_STOP: self.__stop_bot(msg)
            elif t_comm == C_CAMS: self.__show_cams_m(msg)
            elif t_comm in [C_A_WHO_ARE, C_A_WHO_R, C_A_WHO_UR]: self.__show_who_are(msg)
            elif t_comm == C_A_SYS_INFO: self.__get_system_info(msg)
            elif t_comm in [C_R_ACC, C_R_KICK]: self.__do_reg(msg)
            elif t_comm == C_R_NEXT: self.__show_next_reg(msg)
            elif t_comm == C_U_REG: self.__add_req_reg(msg)
            elif t_comm == C_V_UREG: self.__add_req_ureg(msg)
            elif t_comm in [C_MENU, C_BACK, C_UPD]: self.__show_m(msg)
            elif t_comm in [C_C_ON, C_C_OFF]: self.__cam_switch_state(msg)
            elif t_comm in [C_MD_ON, C_MD_OFF]: self.__cam_switch_md_state(msg)
            elif t_comm == C_C_LAST: self.__get_last_frame(msg)
            elif t_comm == C_C_NOW: self.__get_now_frame(msg)
            elif t_comm == C_C_NOW_ALL: self.__get_now_frame_all(msg)
            elif t_comm in CAM_M_L: self.__show_cam_m(msg)

    def __create_cam_menu(self):
        cams_n = self.__model.get_cameras_len()

        for n in range(cams_n):
            cam_name_tmp = self.__model.get_camera_by_i(n).cam_name
            CAM_M_L.append(cam_name_tmp)
            CAM_KB.row(*[cam_name_tmp])

        CAM_KB.row(*[C_MENU])

    def __def_reg(self):
        self.__reg_state = ''
        self.__reg_pos = None
        self.__reg_item = None

    def hi_protect(func):
        def wrapped(s, msg, *args, **kwargs):
            c_id = str(msg.chat.id)
            if c_id == ADMIN_ID:
                return func(s, msg)
        return wrapped

    def mid_protect(func):
        def wrapped(s, msg, *args, **kwargs):
            c_id = str(msg.chat.id)
            if s.__model.is_viewer(c_id):
                return func(s, msg)
        return wrapped

    def hm_protect(func):
        def wrapped(s, msg, *args, **kwargs):
            c_id = str(msg.chat.id)
            if s.__model.is_viewer(c_id) or c_id == ADMIN_ID:
                return func(s, msg)
        return wrapped

    @hi_protect
    def __restart_bot(self, msg):
        self.send_message(ADMIN_ID, "Rebooting...")
        common.reset_app()

    @hi_protect
    def __stop_bot(self, msg):
        self.send_message(ADMIN_ID, "Stopping...")
        self.__stop_f = True

    def __show_m(self, msg):
        t_id = str(msg.chat.id)

        if t_id == ADMIN_ID:
            self.__show_admin_m(msg)
        elif self.__model.is_viewer(t_id):
            self.__show_viewer_m(msg)
        else:
            self.__show_undef_m(msg)

        self.__def_reg()

    @hm_protect
    def __show_cams_m(self, msg):
        self.send_message(msg.chat.id, TO_RULE, reply_markup=CAM_KB)

    @mid_protect
    def __show_viewer_m(self, msg):
        self.send_message(msg.chat.id, TO_RULE, reply_markup=VIEWERS_KB)

    def __show_undef_m(self, msg):
        self.send_message(msg.chat.id, TO_RULE, reply_markup=UNDEF_KB)

    @hi_protect
    def __show_admin_m(self, _):
        self.send_message(ADMIN_ID, TO_RULE, reply_markup=ADMIN_KB)

    def __show_reg_m(self):
        self.send_message(ADMIN_ID, TO_RULE, reply_markup=REG_KB)

    def __show_kick_m(self):
        self.send_message(ADMIN_ID, TO_RULE, reply_markup=KICK_KB)

    def __switch_sel_cam_state(self, state):
        self.__cam_sel_state = state
        self.__cam_sel_stat_str = "работает" if state else "не работает"

    @hm_protect
    def __show_cam_m(self, msg):
        self.__cam_sel_id = CAM_M_L.index(msg.text)
        self.__switch_sel_cam_state(self.__model.get_camera_by_i(self.__cam_sel_id).state)

        CAM_CTRL_KB = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)

        if self.__model.get_camera_by_i(self.__cam_sel_id).state:
            CAM_CTRL_KB.row(*[C_C_OFF])
        else:
            CAM_CTRL_KB.row(*[C_C_ON])

        if self.__model.get_camera_by_i(self.__cam_sel_id).motion_detect:
            CAM_CTRL_KB.row(*[C_MD_OFF])
        else:
            CAM_CTRL_KB.row(*[C_MD_ON])

        for row in CAM_CTRL_M_L:
            CAM_CTRL_KB.row(*row)

        self.send_message(msg.chat.id, TO_RULE, reply_markup=CAM_CTRL_KB)
        time.sleep(0.2)

    def __show_bot_started(self):
        msg = BOT_START.format(ver.V_FULL)
        self.send_message(ADMIN_ID, msg)
        self.send_message(ADMIN_ID, TO_RULE, reply_markup=GET_KB)

        # for i in range(0, self.__model.get_viewers_len()):
        #     (s_id, s_name) = self.__model.get_viewer_by_i(i)
        #     self.send_message(s_id, msg)
        #     self.send_message(s_id, TO_RULE, reply_markup=GET_KB)

        logger.info(msg)

    def __show_bot_stopped(self):
        self.send_message(ADMIN_ID, BOT_STOP)

        # for i in range(0, self.__model.get_viewers_len()):
        #     (s_id, s_name) = self.__model.get_viewer_by_i(i)
        #     self.send_message(s_id, BOT_STOP)

        logger.info(BOT_STOP)

    @hi_protect
    def __show_next_reg(self, _):
        c_len = 0

        if self.__reg_state == C_A_WHO_UR:
            c_len = self.__model.get_ureg_req_len()
        elif self.__reg_state == C_A_WHO_R:
            c_len = self.__model.get_reg_req_len()
        elif self.__reg_state == C_A_WHO_ARE:
            c_len = self.__model.get_viewers_len()

        if c_len <= 0:
            self.__def_reg()
            self.send_message(ADMIN_ID, "No more users")
            self.__show_admin_m(_)

            return

        if self.__reg_pos is None:
            self.__reg_pos = 0
        else:
            if c_len > (self.__reg_pos + 1):
                self.__reg_pos += 1
            else:
                self.__reg_pos = 0

        item = None

        if self.__reg_state == C_A_WHO_UR:
            item = self.__model.get_ureg_req_by_i(self.__reg_pos)
        elif self.__reg_state == C_A_WHO_R:
            item = self.__model.get_reg_req_by_i(self.__reg_pos)
        elif self.__reg_state == C_A_WHO_ARE:
            item = self.__model.get_viewer_by_i(self.__reg_pos)

        (n_id, n_name) = item
        self.__reg_item = item

        self.send_message(ADMIN_ID, "Selected: \"{:s} : {:s}\"".format(n_name, str(n_id)))

    @hi_protect
    def __show_who_are(self, msg):
        t_comm = msg.text

        pred = False

        if t_comm == C_A_WHO_ARE:
            pred = self.__show_who_are_viewer()
        elif t_comm == C_A_WHO_R:
            pred = self.__show_who_are_w_reg()
        elif t_comm == C_A_WHO_UR:
            pred = self.__show_who_are_w_ureg()

        if pred:
            self.__reg_state = t_comm

            if t_comm == C_A_WHO_ARE:
                self.__show_kick_m()
            else:
                self.__show_reg_m()
            self.__show_next_reg(msg)

    def __show_who_are_viewer(self):
        if self.__model.get_viewers_len() > 0:
            self.send_message(ADMIN_ID, "There are viewers:\n{:s}".format(self.__model.get_viewers_list_str()))
            return True

        return False

    def __show_who_are_w_reg(self):
        if self.__model.get_reg_req_len() > 0:
            self.send_message(ADMIN_ID, "There are want's to reg:\n{:s}".format(self.__model.get_reg_req_list_str()))
            return True

        return False

    def __show_who_are_w_ureg(self):
        if self.__model.get_ureg_req_len() > 0:
            self.send_message(ADMIN_ID, "There are want's to unreg:\n{:s}".format(self.__model.get_ureg_req_list_str()))
            return True

        return False

    @like_trhows
    def __show_alert(self, alert):
        if alert.type == common.T_CAM_NOW_PHOTO:
            if isinstance(alert.who, list):
                for who in alert.who:
                    self.send_photo(chat_id=int(who), photo=open(alert.img, 'rb'))
            else:
                self.send_photo(chat_id=int(alert.who), photo=open(alert.img, 'rb'))
        elif alert.type == common.T_CAM_MOVE_PHOTO:
            logger.info("Alert: {:s} saved photo in {:s}".format(alert.msg,
                                                                 alert.img))
            # self.send_message(chat_id=ADMIN_ID, text="MOVE photo:\n{:s}".format(alert.msg))
            self.send_photo(chat_id=ADMIN_ID, photo=open(alert.img, 'rb'))

            for i in range(0, self.__model.get_viewers_len()):
                (s_id, s_name) = self.__model.get_viewer_by_i(i)
                # self.send_message(chat_id=s_id, text="MOVE photo:\n{:s}".format(alert.msg))
                self.send_photo(chat_id=s_id, photo=open(alert.img, 'rb'))
        elif alert.type == common.T_CAM_MOVE_MP4:
            logger.info("Alert: {:s} saved video in {:s}".format(alert.msg,
                                                                 alert.img))
            # self.send_message(chat_id=ADMIN_ID, text="MOVE video:\n{:s}".format(alert.msg))
            self.send_video(chat_id=ADMIN_ID, data=open(alert.img, 'rb'))

            for i in range(0, self.__model.get_viewers_len()):
                (s_id, s_name) = self.__model.get_viewer_by_i(i)
                # self.send_message(chat_id=s_id, text="MOVE video:\n{:s}".format(alert.msg))
                self.send_video(chat_id=s_id, data=open(alert.img, 'rb'))
        elif alert.type in (common.T_SYS_NOW_INFO, common.T_SYS_ALERT):
            self.send_message(chat_id=ADMIN_ID, text=alert.msg, parse_mode="markdown")
        elif alert.type == common.T_CAM_SW:
            chat = telebot.types.Chat(ADMIN_ID, 'private')
            msg = telebot.types.Message(0, 0, 0, chat, 0, [])
            msg.text = alert.cam

            if alert.cam is not None:
                self.__show_cam_m(msg)
            self.send_message(chat_id=ADMIN_ID, text=alert.msg, parse_mode="markdown")

            for i in range(0, self.__model.get_viewers_len()):
                (s_id, s_name) = self.__model.get_viewer_by_i(i)
                if alert.cam is not None:
                    msg.chat.id = s_id
                    self.__show_cam_m(msg)

                self.send_message(s_id, alert.msg)

    @like_trhows
    def __show_alerts(self):
        last_alert = self.__model.no_tr_alert

        if last_alert is not None:
            self.__show_alert(last_alert)
            self.__model.clear_no_tr_alert()

        if self.__model.is_alerts_exists():
            alert = self.__model.get_alert()

            self.__show_alert(alert)

            self.__model.clear_no_tr_alert()

    @hi_protect
    def __do_reg(self, msg):
        t_comm = msg.text

        pred = False

        if t_comm == C_R_ACC:
            pred = self.__do_acc()
        elif t_comm == C_R_KICK:
            pred = self.__do_kick()

        if pred:
            self.__show_next_reg(msg)

    def __add_req_reg(self, msg):
        t_id = str(msg.chat.id)
        t_name = msg.chat.first_name

        self.__model.add_reg_req(t_id, t_name)
        self.send_message(ADMIN_ID, "User \"{:s} : {:s}\" want to register".format(t_id,
                                                                                t_name))

    @mid_protect
    def __add_req_ureg(self, msg):
        t_id =str(msg.chat.id)
        t_name = msg.chat.first_name

        self.__model.add_ureg_req(t_id, t_name)
        self.send_message(ADMIN_ID, "User \"{:s} : {:s}\" want to unregister".format(t_id,
                                                                                t_name))

    @hm_protect
    def __cam_switch_state(self, msg):
        state = True if msg.text == C_C_ON else False

        if state != self.__cam_sel_state:
            self.__switch_sel_cam_state(state)
            self.__model.camera_switch_state(self.__cam_sel_id, state)

    @hm_protect
    def __cam_switch_md_state(self, msg):
        state = True if msg.text == C_MD_ON else False

        if state != self.__model.get_camera_by_i(self.__cam_sel_id).motion_detect:
            self.__model.camera_switch_md_state(self.__cam_sel_id, state)

    @hm_protect
    def __get_last_frame(self, msg):
        last_f_p = self.__model.get_camera_last_f(self.__cam_sel_id)
        if os.path.exists(last_f_p):
            self.send_photo(msg.chat.id, photo=open(last_f_p, 'rb'))

    @hm_protect
    def __get_now_frame(self, msg):
        self.__model.get_now_photo(self.__cam_sel_id, msg.chat.id)

    @hm_protect
    def __get_now_frame_all(self, msg):
        cams_n = self.__model.get_cameras_len()

        for n in range(cams_n):
            self.__model.get_now_photo(n, msg.chat.id)

    @hi_protect
    def __get_system_info(self, _):
        self.__machine_daemon.get_now_status()

    def __do_acc(self):
        if not self.__reg_item is None:
            (a_id, a_name) = self.__reg_item

            chat = telebot.types.Chat(a_id, 'private')
            msg = telebot.types.Message(0, 0, 0, chat, 0, [])

            if self.__reg_state == C_A_WHO_R:
                self.__model.add_viewer(a_id)
                self.send_message(ADMIN_ID, "User \"{:s} : {:s}\" was added to viewers".format(a_id,
                                                                                a_name))
                self.send_message(a_id, "You are added to viewers")
            elif self.__reg_state == C_A_WHO_UR:
                self.__model.kick_viewer(a_id)
                self.send_message(ADMIN_ID, "User \"{:s} : {:s}\" was kicked from viewers".format(a_id,
                                                                                a_name))
                self.send_message(a_id, "You are kicked from viewers")

            self.__show_m(msg)

            return True

        self.send_message(ADMIN_ID, "Bad try add viewer")
        return False

    def __do_kick(self):
        if not self.__reg_item is None:
            (k_id, k_name) = self.__reg_item

            if self.__reg_state == C_A_WHO_R:
                self.__model.kick_reg_req(k_id)
                self.send_message(ADMIN_ID, "User \"{:s} : {:s}\" was kicked from register requests".format(k_id,
                                                                                k_name))
            elif self.__reg_state == C_A_WHO_UR:
                self.__model.kick_ureg_req(k_id)
                self.send_message(ADMIN_ID, "User \"{:s} : {:s}\" was kicked from unregister requests".format(k_id,
                                                                                k_name))
            elif self.__reg_state == C_A_WHO_ARE:
                self.__model.kick_viewer(k_id)
                self.send_message(ADMIN_ID, "User \"{:s} : {:s}\" was kicked from viewers".format(k_id,
                                                                                k_name))
            return True

        self.send_message(ADMIN_ID, "Bad try kick viewer")
        return False

    def __get_updates(self):
        total = 0
        updates = self.get_updates(offset=self.last_update_id, timeout=UPD_TMT)
        while updates:
            total += len(updates)
            for update in updates:
                if update.update_id > self.last_update_id:
                    self.last_update_id = update.update_id

            self.process_new_updates(updates)
            updates = self.get_updates(offset=self.last_update_id + 1, timeout=UPD_TMT)
        return total

    def __skip_updates_m(self):
        total = 0
        updates = self.get_updates(offset=self.last_update_id, timeout=UPD_TMT)
        while updates:
            total += len(updates)
            for update in updates:
                if update.update_id > self.last_update_id:
                    self.last_update_id = update.update_id
            updates = self.get_updates(offset=self.last_update_id + 1, timeout=UPD_TMT)
        return total

    @like_trhows
    def do_work(self):
        logger.info("skipped: {:s}".format(str(self.__skip_updates_m())))
        self.__show_bot_started()

        # self.__model.check_cameras()
        # self.__machine_daemon.start_work()

        while not self.__stop_f:
            upds_num = self.__get_updates()
            if upds_num:
                logger.info("rx updates: {:s}".format(str(upds_num)))
            else:
                time.sleep(common.WAIT_TIMEOUT)
            self.__show_alerts()

        # self.__model.switch_off_cameras()
        # self.__machine_daemon.stop_work()

        self.__show_bot_stopped()

    def stop_bot(self):
        self.__stop_f = True


from django.core.paginator import Paginator
from django.forms import model_to_dict
from rest_framework import viewsets, status
from rest_framework.response import Response
from django_redis import get_redis_connection
from rest_framework.decorators import action
from databases.models import Databases, DBItem
from databases.serializers import DatabaseSerializer, DBItemSerializer
from project_monitor import settings
from format import format_result
import datetime
import logging
import requests

logger = logging.getLogger('log')

class DatabaseViewSet(viewsets.ModelViewSet):
    queryset = Databases.objects.all()
    serializer_class = DatabaseSerializer

    def list(self, request, *args, **kwargs):
        """
        重写查询方法，增加翻页功能
        :param request: 请求对象，从中获取查询字符串参数，包括翻页参数及条件查询参数
        :param args:
        :param kwargs:
        :return:
        """
        # 查询条件
        search_dict = dict()
        name = request.query_params.get('name', None)
        db_type = request.query_params.get('db_type', None)
        is_monitor = request.query_params.get('is_monitor', None)
        if name:
            search_dict['name'] = name
        if db_type:
            search_dict['db_type'] = db_type
        if is_monitor:
            search_dict['is_monitor'] = is_monitor
        # 查询数据
        db_list = Databases.objects.get_queryset().filter(**search_dict, is_delete=0).order_by('id')
        # 设置翻页
        current_page = int(request.query_params.get('current_page', 0))
        pre_page = int(request.query_params.get('pre_page', 0))
        if current_page != 0 and pre_page != 0:
            paginator = Paginator(db_list, pre_page)
            result = paginator.page(current_page)
            data = self.get_serializer(result, many=True).data
            # 定义返回结果
            res = dict()
            res['total_page'] = paginator.num_pages
            res['current_page'] = current_page
            res['pre_page'] = pre_page
            res['total_count'] = paginator.count
            res['data'] = data
            return Response(res)
        else:
            return Response(self.get_serializer(db_list, many=True).data)

    @action(detail=False, methods=['put'])
    def delete(self, request):
        """
        逻辑删除数据库中的资源信息
        :param request:
        :return:
        """
        db_id = request.data.get('ids', None)
        db = Databases.objects.filter(id__in=db_id).update(is_delete=1, remove_time=datetime.datetime.now())
        return Response(db)

    @action(detail=False, methods=['get'], url_path="tag")
    def get_tag(self, request, *args, **kwargs):
        db_type = request.query_params.get('server_type', None)
        database_info = Databases.objects.filter(db_type=db_type).all()
        tag_info = []
        if database_info:
            for database in database_info:
                tag = db_type + '_' + database.ip_address + '_' + database.sid
                device_ip = database.ip_address
                device_name = database.name
                tag_info.append({"tag": tag, "device_name": device_name, "device_ip": device_ip})
            return Response(data=tag_info, status=status.HTTP_200_OK)
        return Response(data=None, status=status.HTTP_204_NO_CONTENT)

    @action(methods=['get'], detail=False, url_path="monitor")
    def get_monitor(self, request, *args, **kwargs):
        """
        查询redis数据库中的实时数据信息
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        db_name = request.query_params.get('db_name', None)
        if db_name is None:
            return Response(status=400, data={"detail": "参数错误！"})
        conn = get_redis_connection("default")
        res = conn.hgetall(db_name)
        if res is None:
            return Response(data={"detail": "未查询到数据"})
        else:
            data = format_result(res)
            return Response(data)

    @action(methods=['get'], detail=False, url_path='history')
    def get_history_monitor(self, request, *args, **kwargs):
        """
        查询opentsdb中的数据库监控数据
        :param request: start=2020/07/14-00:00:00&end=2020/07/14-00:00:00&m=sum:hwAvgDuty1min
        :param args:
        :param kwargs:
        :return:
        """
        metric = request.query_params.get('m', None)
        start = request.query_params.get('start', None)
        end = request.query_params.get('end', None)
        try:
            r = requests.get(settings.OPENTSDB_URL + "query?start=" + start + "&end=" + end + "&m=" + metric, timeout=3)
        except Exception as e:
            logger.error(e)
            return Response(data={"detail": "发生异常！"}, status=500)

        if len(r.json()) > 0 and r.status_code == 200:
            dps = r.json()[0]['dps']
            return Response(dps)
        else:
            return Response(data={"detail": "未查询到数据！"})

    @action(detail=False, methods=['GET'])
    def search(self, request):
        query = request.query_params.get('query', None)
        db_type = request.query_params.get('db_type', None)
        is_monitor = request.query_params.get('is_monitor', None)
        if query is not None:
            db_info = Databases.objects.get_queryset().filter(is_delete=0, sid__contains=query, is_monitor=is_monitor,
                                                              db_type__contains=db_type)
            if not len(db_info):
                db_info = Databases.objects.get_queryset().filter(is_delete=0, ip_address__contains=query,
                                                                  is_monitor=is_monitor, db_type__contains=db_type)
            return Response(
                self.get_serializer(db_info, many=True).data)
        return Response(status=status.HTTP_200_OK)

class DBItemViewSet(viewsets.ModelViewSet):
    queryset = DBItem.objects.all()
    serializer_class = DBItemSerializer

    def list(self, request, *args, **kwargs):
        """
        重写查询方法，增加翻页功能
        :param request: 请求对象，从中获取查询字符串参数，包括翻页参数及条件查询参数
        :param args:
        :param kwargs:
        :return:
        """
        # 查询条件
        search_dict = dict()
        item_name = request.query_params.get('item_name', None)
        if item_name:
            search_dict['item_name'] = item_name
        # 查询数据
        item_list = DBItem.objects.get_queryset().filter(**search_dict).order_by('id')
        # 设置翻页
        current_page = int(request.query_params.get('current_page', 0))
        pre_page = int(request.query_params.get('pre_page', 0))
        if current_page != 0 and pre_page != 0:
            paginator = Paginator(item_list, pre_page)
            result = paginator.page(current_page)
            data = self.get_serializer(result, many=True).data
            # 定义返回结果
            res = dict()
            res['total_page'] = paginator.num_pages
            res['current_page'] = current_page
            res['pre_page'] = pre_page
            res['total_count'] = paginator.count
            res['data'] = data
            return Response(res)
        else:
            return Response(self.get_serializer(item_list, many=True).data)

    @action(detail=True, methods=['POST'])
    def get_database_available(self, request):
        """
        获取可用于告警规则的中间件监控项
        :return:
        """
        db_type = request.data['db_type']
        if db_type:
            db_item = DBItem.objects.filter(db_type=db_type).all()
            if db_item:
                db_item = model_to_dict(db_item)
                return Response(db_item, status=status.HTTP_200_OK)


import argparse
import os
from git import Repo
import json

def create_tag(tag_name: str):
    repo = Repo(os.path.dirname(os.path.realpath(__file__)))
    repo.create_tag(tag_name, message=f"chore(bump): v{tag_name}")
    print(f"Tag {tag_name} created")
    # commit changelog
    repo.git.add("CHANGELOG.md")
    repo.git.add("package.json")
    repo.index.commit("chore(VERSION): update VERSION")
    print("Changelog updated | Version file updated")
    # push tag
    try:
        origin = repo.remote(name="origin")
        origin.push(tag_name)
        origin.push()
        print("Tag pushed to origin")
    except OSError:
        os.system(f"git push --atomic origin main {tag_name}")

def generate_changelog(VERSION: str):
    print(f"Generating changelog for VERSION {VERSION}")
    os.system(f"git-chglog --next-tag v{VERSION} --output CHANGELOG.md")

def update_package(VERSION: str):
    with open("package.json", "r") as f:
        package = json.load(f)
    package["version"] = VERSION
    with open("package.json", "w") as f:
        json.dump(package, f, indent=4)
    print("Package.json updated")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("VERSION", help="Version to create tag for")
    args = parser.parse_args()
    generate_changelog(args.VERSION)
    update_package(args.VERSION)
    create_tag(args.VERSION)


"""empty message

Revision ID: 1fa16ee86342
Revises: dfa694f4994d
Create Date: 2020-04-22 10:18:55.373757

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '1fa16ee86342'
down_revision = 'dfa694f4994d'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('job_signup', schema=None) as batch_op:
        batch_op.add_column(sa.Column('stuId', sa.BigInteger(), nullable=True, comment='申请学生的学生id号'))
        batch_op.alter_column('userId',
               existing_type=mysql.BIGINT(display_width=20),
               comment='申请学生的用户id号',
               existing_comment='申请学生的id号',
               existing_nullable=True)

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('job_signup', schema=None) as batch_op:
        batch_op.alter_column('userId',
               existing_type=mysql.BIGINT(display_width=20),
               comment='申请学生的id号',
               existing_comment='申请学生的用户id号',
               existing_nullable=True)
        batch_op.drop_column('stuId')

    # ### end Alembic commands ###


import pika
import json
from threading import Thread

from projetoRobo.SS import compartilhados
from copy import deepcopy
import time

class ReceptorSA(Thread):

    def __init__(self, host):
        print("Iniciando RabbitMQ receptor..")
        super(ReceptorSA, self).__init__()
        self._nome = "g2"
        self._exchange = 'SA_to_SS'

        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=str(host)))
        self.channel = self.connection.channel()
        self.channel.exchange_declare(exchange=self._exchange, exchange_type='direct')

        result = self.channel.queue_declare(exclusive=True)
        self._queue_name = result.method.queue

        self.channel.queue_bind(exchange=self._exchange, queue=self._queue_name, routing_key=self._nome)

        self.channel.basic_consume(self.trata_msg_recebida, queue=self._queue_name, no_ack=True)

    def trata_msg_recebida(self, ch, method, properties, body):
        try:
            msg = json.loads(body)
        except:
            return

        print("RECEBENDO DO SA")
        # Identificador (indica que a msg veio do SS)
        msg['_dir'] = 'sa'

        with compartilhados.sw_lock:
            # Copia a mensagem para o buffer de transmissao
            foo = deepcopy(msg)
            if 'jogadorA' in msg:

                if msg['jogadorA'] == self.robo:
                    foo = {'_dir': 'sa', 'cmd': 1100, 'modo_jogo': msg['modo_jogo'],
                           'cacas': msg['cacas'], 'x': msg['xA'], 'y': msg['yA']}

                elif msg['jogadorB'] == self.robo:
                    foo = {'_dir': 'sa', 'cmd': 1100, 'modo_jogo': msg['modo_jogo'],
                           'cacas': msg['cacas'], 'x': msg['xB'], 'y': msg['yB']}

                with compartilhados.sacomrx:
                    compartilhados.sw_msg = deepcopy(foo)
                    # Chama o gerente
                    compartilhados.sw_event.set()
                    # Tempo de seguranca para o gerente pegar a msg
                    time.sleep(0.2)

            else:

                with compartilhados.sacomrx:
                    compartilhados.sw_msg = deepcopy(msg)
                    # Chama o gerente
                    compartilhados.sw_event.set()
                    # Tempo de seguranca para o gerente pegar a msg
                    time.sleep(0.2)

            compartilhados.sw_event.clear()

    def run(self):
        self.channel.start_consuming()


import serial
import re
import threading

class PiArduinoCommunicator2:

    def __init__(self, ofen):
        print("PiArduinoCommunicator2 initialized")

        self.ofen = ofen

        self.ser = serial.Serial("/dev/ttyACM0", 9600)  # change ACM number as found from ls /dev/tty/ACM*
        self.ser.baudrate = 9600

        self.error = {"error":False, "message":"none"}

        self.t1 = threading.Thread(target=self.readFromSerialLoop, args=())
        self.t1.start()

    def get_error(self):
        return self.error

    def decideTempOrSettings(self,striL):
        try:

            #striL = stri
            #striL = striL[2:]
            #striL = striL[:-5]
            #stri = stri.replace(" ","")

            if "D" in striL:
                strParts = re.split("-",striL)
                value = round(float(strParts[-1]),1)
                print("D")
                print(value)
                self.ofen.set_Drosselklappe(value)
            elif "G" in striL:
                strParts = re.split("-",striL)
                value = round(float(strParts[-1]),1)
                if value >= 0.5:
                    value = 1.0
                else:
                    value = 0.0
                if not self.ofen.get_FanValue() == value:
                    self.ofen.fanAction()
                print("G")
                print(value)
            elif "L" in striL:
                strParts = re.split("-",striL)
                value = round(float(strParts[-1]),1)
                self.ofen.set_airInput(value)
                print("L")
                print(value)
            elif "A" in striL:
                strParts = re.split("-",striL)
                value = round(float(strParts[-1]),1)
                if not self.ofen.get_autoMode() == value:
                    self.ofen.autoModeAction()
                print("A")
                print(value)
            elif "F" in striL:
                strParts = re.split("-",striL)
                value = round(float(strParts[-1]),1)
                if not self.ofen.get_FastHeatupValue() == value:
                    self.ofen.fastHeatUpAction()
                print("F")
                print(value)
            elif "H" in striL:
                strParts = re.split("-",striL)
                value = round(float(strParts[-1]),1)
                self.ofen.set_temp2hold(value)
                print("H")
                print(value)
            elif "T:" in striL:
                strParts = re.split(":",striL)
                #print(strParts[1])
                self.processTempString(strParts[1])
            else:
                msg = "TempSet-StringParsingError:NO MATCH Please check serial connection"
                print(msg)
                self.error["error"] = True
                self.error["message"] = msg

        except Exception as e:
            msg = "TempSet-StringParsingException: Please check serial connection"
            print(msg)
            print(e)
            self.error["error"] = True
            self.error["message"] = msg

    def processTempString(self,stri):
        error = 0
        values = [0,0,0,0,0,0,0]

        print("Temperatures: " + str(stri))

        try:
            strParts = re.split("-",stri)
            for idx, strPart in enumerate(strParts):
                    try:
                        if(strPart.lower() == "nan"):
                            msg = "TemperatureStringParsingException NO DIGIT (NAN): Please check serial connection and temperature sensors "
                            print(msg)
                            self.error["error"] = True
                            self.error["message"] = msg
                            values[idx] = 0
                        else:
                            a = float(strPart)
                            #print(int(a))
                            values[idx] = int(a)
                            self.error = {"error":False, "message":"none"}
                    except:
                        msg = "TemperatureStringParsingException INT CAST: Please check serial connection and temperature sensors "
                        print(msg + strPart)
                        self.error["error"] = True
                        self.error["message"] = msg
                        values[idx] = 0
        except Exception as e:
            msg = "TemperatureStringParsingException: Please check serial connection and temperature sensors "
            print(msg)
            self.error["error"] = True
            self.error["message"] = msg
            values = [0,0,0,0,0,0,0]

        self.ofen.setTempData(values)

    def readFromSerialLoop(self):
        while True:
            try:
                #read_ser=self.ser.readline()
                #Read incomind Data from Serial, decode Bytes as UTF-8 String, cut \r\n (=trailing characters)
                read_ser = self.ser.readline().decode('utf-8').rstrip().replace(" ","")
                self.decideTempOrSettings(read_ser)
            except:
                print("Serial Connection ERROR")
                self.ofen.setTempData([0,0,0,0,0,0,0])

    def write2Serial_woodWarning(self):
        print("Write 2 Serial")
        self.ser.write("lessWood".encode('utf-8'))

    def write2Serial_errorWarning(self):
        print("Write 2 Serial")
        self.ser.write("error\n".encode('utf-8'))

    def onShutdown(self):
        self.t1.join()

#main = PiArduinoCommunicator2()


# Módulos necesarios
import random
import sys
import pygame
from graphics import *
import sounds

# Datos de pantalla
alto_pantalla = 800
ancho_pantalla = 600

# Preparamos las listas y variables de gráficos
img_xwing_lista = []
explosion_bites = []

# Las variables las declaro a None ya que serán cargadas en un def más adelante, y por
# tanto deben existir antes de entrar en el def.
img_tief = None
img_shuttle = None
img_stroopers = None
img_falconm = None
img_corveta = None
laser_verde = None
laser_rojo = None
fondo = None

# Preparamos las variables para cargar los sonidos
snd_laser_empire = None
snd_laser_rebels = None
snd_explosion = None

# Definimos la variables de configuración del juego.
desplazamiento_de_fondo = 0
tiempo_anim_giro = 10
vel_laser_r = 10
vel_laser_v = -10
vel_tief = 3
indice_naves_aleatorias = 2
player_2 = False
saturacion_disparo = 25
saturacion_tiempo_ties = [0, 100]
naves_destruidas = 0
size_letra = 25
puntos_a_sumar = 5

# ------------------------------ Pintar Puntos -------------------------------------------------------- #
def pintar_puntos_pantalla(jugador):

    # Comprobamos la ID del jugador
    x = 20
    y = 0
    if jugador[3] == 1:
        y = 5
    elif jugador[3] == 2:
        x = ancho_pantalla+50
        y = 5
    texto_pantalla = myfont.render(f'Puntos Piloto {jugador[3]}', False, (255, 0, 0))
    screen.blit(texto_pantalla, (x, y))
    texto_pantalla = myfont.render(str(jugador[6]), False, (255, 0, 0))
    screen.blit(texto_pantalla, (x, y+20))

# ------------------------------ Naves Aleatorias ----------------------------------------------------- #
def random_naves_aleatoras(naves_destruidas):
    if naves_destruidas == 10:
        pasada_de_nave_adorno(lista_naves_aleatorias[0])
    elif naves_destruidas == 20:
        pasada_de_nave_adorno(lista_naves_aleatorias[1])

# ------------------------------ Pasada nave adorno---------------------------------------------------- #
def pasada_de_nave_adorno(imagen):
    lista_naves_adorno.append([imagen, random.randint(0,ancho_pantalla),600])

# ------------------------------ Actualizar y pintar naves de adorno ---------------------------------- #
def actualiza_y_pinta_naves_adorno():
    for nave in lista_naves_adorno:
        if nave[0] == img_falconm:
            screen.blit(nave[0], (nave[1], nave[2]))
            nave[2] -= 5
            if nave[2] > 2000: lista_naves_adorno.remove(nave)
        else:
            screen.blit(nave[0], (nave[1], nave[2]))
            nave[2] -= 2
            if nave[2] > 2000: lista_naves_adorno.remove(nave)

# ------------------------------ Dibujar lista de jugadores ------------------------------------------- #
def dibujar_lista_jugadores():
    for jugador in lista_jugadores:
        screen.blit(jugador[0], (jugador[1], jugador[2]))

# ------------------------------ Actualizar animación giros jugador ------------------------------------#
def actualiza_animacion_direccion_jugador(jugador, valor):
    # Miramos el tiempod de animacion
    if valor == "derecha":
        if jugador[4] < 30:
            jugador[4] += 1
    elif valor == "izquierda":
        if jugador[4] > 0:
            jugador[4] -= 1
    elif valor == "centro":
        if jugador[4] < 15:
            jugador[4] += 1
        elif jugador[4] > 15:
            jugador[4] -= 1
    jugador[0] = img_xwing_lista[jugador[4]]

# ------------------------------ Dibujar objetos dinámicos -------------------------------------------- #
def dibujar_lista_objetos_dinamicos(lista_objetos_dinamicos):
    for objeto in lista_objetos_dinamicos:
        screen.blit(objeto[0], (objeto[1], objeto[2]))

# ------------------------------ Crear nueva explosión  ----------------------------------------------- #
def nueva_explosion(pos_x, pos_y):
    # explosion [fase (entero de 1 a 13) y pos]
    lista_explosiones.append([0, pos_x - 100, pos_y - 100])

# ------------------------------ Animar y pintar explosión -------------------------------------------- #
def actualizar_y_pintar_explosiones():
    for explosion in lista_explosiones:
        # Pinto la explosion
        screen.blit(explosion_bites[explosion[0]], (explosion[1], explosion[2]))
        # Actualizo la explosion
        if explosion[0] < len(explosion_bites) - 1:
            explosion[0] += 1
        else:
            lista_explosiones.remove(explosion)

# ------------------------------ Chequear impactos de disparos rojos ---------------------------------- #
def chequea_colision_impactos(lista_objetos, lista_lasers_rojos):
    # Chequeamos para cada laser
    for laser in lista_lasers_rojos:
        for objeto in lista_objetos:
            # Chequeo altura
            if abs((objeto[2] - laser[2])) < 10:
                # Chequeo horizontal
                ancho_nave = objeto[0].get_width()
                if (laser[1] - objeto[1] > 0) and (laser[1] - objeto[1] < ancho_nave):
                    nueva_explosion(objeto[1], objeto[2])
                    # y con sonido!
                    snd_explosion.play()
                    lista_objetos.remove(objeto)
                    # Veo qué jugador disparó el laser
                    id_player = laser[3]
                    # Sumo los puntos
                    for player in lista_jugadores:
                        if player[3] == id_player: player[6] += puntos_a_sumar
                    lista_laseres_rojos.remove(laser)
                    return True

# ------------------------------ Chequear impacto de disparo en player -------------------------------- #
def chequea_impacto_en_jugador(lst_jugadores, lst_lasers_verdes):
    # Chequeamos para cada laser
    for laser in lst_lasers_verdes:
        for _jugador in lst_jugadores:
            # Chequeo altura
            if abs((_jugador[2] - laser[2])) < 10:
                ancho_nave = _jugador[0].get_width()
                if (laser[1] - _jugador[1] > 0) and (laser[1] - _jugador[1] < ancho_nave):
                    nueva_explosion(_jugador[1], _jugador[2])
                    # y con sonido!
                    snd_explosion.play()
                    lista_jugadores.remove(_jugador)

# ------------------------------ Actualiza lista aparación enemigos ----------------------------------- #
def actualiza_aparicion_ties():
    if saturacion_tiempo_ties[0] < saturacion_tiempo_ties[1]:
        saturacion_tiempo_ties[0] += 1
    else:
        nave = random.randint(0, 101)
        if nave < 15:
            inserta_nave_ia(img_stroopers, (random.randint(0, ancho_pantalla)), 0, lista_objetos_enemigos)
        elif nave > 90:
            inserta_nave_ia(img_shuttle, (random.randint(0, ancho_pantalla)), 0, lista_objetos_enemigos)
        else:
            inserta_nave_ia(img_tief, (random.randint(0, ancho_pantalla)), 0, lista_objetos_enemigos)
        saturacion_tiempo_ties[0] = 0

# ------------------------------ Insertar nueva nave IA ----------------------------------------------- #
def inserta_nave_ia(img_nave, pos_x, pos_y, lista_objetos):
    lista_objetos.append([img_nave, pos_x, pos_y])

# ------------------------------ Insertar nuevo jugador ----------------------------------------------- #
def insertar_nuevo_jugador(img_nave, pos_x, posy, new_id, estado_animacion, tiempo_animacion, puntos):
    lista_jugadores.append([img_nave, pos_x, posy, new_id, estado_animacion, tiempo_animacion, puntos])

# ------------------------------ player dispara un láser ---------------------------------------------- #
def dispara_laser(posx, posy, lista_objetos, player):
    if saturacion_disparo_player[player-1] == saturacion_disparo:
        # Dispara (guardamos el jugador que disparó para contar los puntos.
        lista_objetos.append([laser_rojo, posx, posy, player])
        lista_objetos.append([laser_rojo, posx + 52, posy, player])
        # Marco saturación de disparo
        saturacion_disparo_player[player-1] = 0
        # Emito sonido
        snd_laser_rebels.play()

# ------------------------------ enemigos disparan un láser ------------------------------------------- #
def disparar_laser_enemigos(posx, posy, lista_objetos):
    # Dispara
    lista_objetos.append([laser_verde, posx + 15, posy + 15])
    lista_objetos.append([laser_verde, posx + 21, posy + 15])
    # Emito sonido
    snd_laser_empire.play()

# ------------------------------ Control de tiempos de disparo / enfriamiento de armas ---------------- #
def actualiza_saturacion_disparos():
    if saturacion_disparo_player[0] < saturacion_disparo:
        saturacion_disparo_player[0] += 1
    if saturacion_disparo_player[1] < saturacion_disparo:
        saturacion_disparo_player[1] += 1

# ------------------------------ Actualizar posición objetos en movimiento ---------------------------- #
def actualiza_posiciones_dinamicos(lista_objetos_dinamicos):
    for objeto in lista_objetos_dinamicos:
        if objeto[0] == laser_rojo:
            # Está fuera de pantalla?
            if objeto[2] > 0:
                objeto[2] -= vel_laser_r
            else:
                lista_objetos_dinamicos.remove(objeto)
        if objeto[0] == laser_verde:
            # Está fuera de pantalla?
            if objeto[2] < alto_pantalla:
                objeto[2] -= vel_laser_v
            else:
                lista_objetos_dinamicos.remove(objeto)
        elif objeto[0] == img_tief:
            if objeto[2] < alto_pantalla:
                objeto[2] += vel_tief
                # Disparamos?
                if random.randint(0, 100) == 100:
                    disparar_laser_enemigos(objeto[1], objeto[2], lista_laseres_verdes)
            else:
                lista_objetos_dinamicos.remove(objeto)
        elif objeto[0] == img_shuttle:
            if objeto[2] < alto_pantalla:
                objeto[2] += vel_tief - 1
            else:
                lista_objetos_dinamicos.remove(objeto)
        elif objeto[0] == img_stroopers:
            if objeto[2] < alto_pantalla:
                objeto[2] += vel_tief - 2
            else:
                lista_objetos_dinamicos.remove(objeto)

# ------------------------------ insertamos un nuevo jugador humano ----------------------------------- #
def crear_nuevo_jugador(lst_jugadores, pos_x, pos_y, new_id):
    # Chequeamos que no esté ya jugando
    existe = False
    for new_jugador in lst_jugadores:
        if new_jugador[3] == new_id:
            existe = True
    if not existe:
        # Creamos jugador_1 con img_xwing, pos_x, pos_y, id player 1 y estado animación 15 y puntos
        insertar_nuevo_jugador(img_xwing, pos_x, pos_y, new_id, 15, tiempo_anim_giro, 0)

# ------------------------------ Cargador de gráficos del juego --- ----------------------------------- #
def cargar_graficos_juego():
    # Lo vamos a hacer en un único bloque TRY. Si falla la carga, no arrancamos el juego.
    # La idea es no arrancar el juego con gráficos no cargados.
    global img_tief, img_shuttle, img_stroopers, img_falconm, img_corveta, laser_verde, laser_rojo, fondo
    graficos_ok = True
    try:
        # Cargamos animaciones de los PJs
        for x_grp in range(0, len(grf_lst_xwing)):
            img_xwing_lista.append(pygame.image.load(grf_lst_xwing[x_grp]))
        # Cargamos la aminación de la explosión
        for e_grp in range(0, len(grf_lst_explosion)):
            explosion_bites.append(pygame.image.load(grf_lst_explosion[e_grp]))
        # Cargamos las imágenes estáticas
        img_tief = pygame.image.load(grf_tief)
        img_shuttle = pygame.image.load(grf_shuttle)
        img_stroopers = pygame.image.load(grf_stroopers)
        img_falconm = pygame.image.load(grf_falconm)
        img_corveta = pygame.image.load(grf_corveta)
        laser_verde = pygame.image.load(grf_laser_verde)
        laser_rojo = pygame.image.load(grf_laser_rojo)
        fondo = pygame.image.load(grf_fondo)
    except FileNotFoundError:
        # Si hay algún error, no cargamos el juego!
        print("Ha ocurrido una excepción grafica")
        graficos_ok = False
    finally:
        # Devolvemos el resultado de la carga de gráficos
        return graficos_ok

# ------------------------------ Cargador de sonidos del juego ---------------------------------------- #
def cargar_sonidos():
    sonidos_ok = True
    global snd_laser_rebels, snd_laser_empire, snd_explosion
    # Intentamos cargar los archivos de sonido.
    try:
        snd_laser_rebels = pygame.mixer.Sound(sounds.snd_disparo_rebeldes)
        snd_laser_empire = pygame.mixer.Sound(sounds.snd_disparo_imperio)
        snd_explosion = pygame.mixer.Sound(sounds.snd_explosion)
    except FileNotFoundError:
        print("Archivos de sonido no encontrados.")
        sonidos_ok = False
    finally:
        # Devolvemos si hubo éxito o no.
        return sonidos_ok

# ------------------------------ Cargador de música del juego ----------------------------------------- #
def cargar_musica_y_play():
    musica_ok = True
    # Intentamos cargar el archivo de música.
    try:
        pygame.mixer.music.load(sounds.music_environment)
    except FileNotFoundError:
        musica_ok = False
        print("Archivo de música no encontrado.")
    else:
        # Si sí hemos cargado la música, la activamos
        pygame.mixer.music.play(0)
    # Devolvemos si hubo éxito o no.
    return musica_ok

# ----------------------------------------------------------------------------------------------------- #
# -                                        MAIN                                                       - #
# ----------------------------------------------------------------------------------------------------- #
# Inicializamos en el entorno de Pygame
pygame.init()
# También el uso de letras
pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', size_letra)
# Texto de la ventana
pygame.display.set_caption('Python Wars!')
# Ahora intentamos cargar los gráficos.
graficos_cargados = cargar_graficos_juego()
# Intentamos cargar los sonidos.
sonidos_cargados = cargar_sonidos()
# E intentamos cargar la música ambiental
musica_cargada = cargar_musica_y_play()
# Si no se han cargado, no creamos el canvas, salimos directamente.
# Lo mismo si no se han cargado los sonidos.
# En el caso de la música.... jugaremos sin música.
if graficos_cargados and sonidos_cargados:
    # Creamos las listas para almacenar objetos del juego.
    # Lista para control de jugadores humanos
    img_xwing = img_xwing_lista[2]
    # Lista para control de enfriamiento de armas de los jugadores humanos
    saturacion_disparo_player = [saturacion_disparo, saturacion_disparo]
    # Lista de naves aleatorias a elegir por la dinámica del juego.
    lista_naves_aleatorias = [img_falconm, img_corveta]
    # Listas de objetos para actualizar, animar y chequear colisiones
    lista_objetos_enemigos = []
    lista_laseres_verdes = []
    lista_laseres_rojos = []
    lista_naves_adorno = []
    lista_explosiones = []
    lista_jugadores = []
    # Iniciamos la pantalla
    screen = pygame.display.set_mode((alto_pantalla, ancho_pantalla))
    # Creamos jugador_1 con img_xwing, posx, posy, id player 1 y estado animación 15.
    # tiempos entre frames de animaciones y puntos de inicio.
    crear_nuevo_jugador(lista_jugadores, 375, 500, 1)
    done = False
    # Asignamos el reloj de pyGame para el control de frames.
    clock = pygame.time.Clock()
    # Declaramos la variable para salir del juego.
    salir = False
    while not salir:
        # Desplazamiento de los dos rectángulos de fondo de estrellas
        if desplazamiento_de_fondo > ancho_pantalla:
            desplazamiento_de_fondo = 0
        screen.blit(fondo, (0, desplazamiento_de_fondo))
        screen.blit(fondo, (0, desplazamiento_de_fondo - ancho_pantalla))
        desplazamiento_de_fondo += 1.5
        # Control de teclado
        pressed = pygame.key.get_pressed()
        # Salimos?
        if pressed[pygame.K_ESCAPE]:
            salir = True
        # ¿Metemos al player 2?
        if pressed[pygame.K_t]:
            # Creamos jugador_2 con img_xwing, pos_x, pos_y, id player 2 y estado animación 15 y puntos
            crear_nuevo_jugador(lista_jugadores, 500, 500, 2)
            # Lo habilitamos para jugar
            player_2 = True
        if pressed[pygame.K_r]:
            # Creamos jugador_1 con img_xwing, pos_x, pos_y, id player 1 y estado animación 15 y puntos
            crear_nuevo_jugador(lista_jugadores, 370, 500, 1)
        # Movimientos de los jugadores
        for jugador in lista_jugadores:
            # Saco ese jugador (Esto se puede mejorar, pero pierdo claridad
            x = jugador[1]
            y = jugador[2]
            # Dependiendo del jugador que sea, se usan unas teclas u otras
            if jugador[3] == 1:
                # Es player 1
                if pressed[pygame.K_UP] and y > 0:
                    y -= 4
                if pressed[pygame.K_DOWN] and y < ancho_pantalla - 80:
                    y += 4
                if pressed[pygame.K_LEFT] and x > 0:
                    x -= 4
                    actualiza_animacion_direccion_jugador(jugador, "izquierda")
                if pressed[pygame.K_RIGHT] and x < alto_pantalla - 58:
                    x += 4
                    actualiza_animacion_direccion_jugador(jugador, "derecha")
                if not pressed[pygame.K_RIGHT] and not pressed[pygame.K_LEFT]:
                    actualiza_animacion_direccion_jugador(jugador, "centro")
                if pressed[pygame.K_RSHIFT]:
                    dispara_laser(x, y, lista_laseres_rojos, 1)
                if pressed[pygame.K_v]:
                    pasada_de_nave_adorno(img_corveta)
            elif jugador[3] == 2:
                # Es player 2
                if pressed[pygame.K_w] and y > 0:
                    y -= 4
                if pressed[pygame.K_s] and y < ancho_pantalla - 80:
                    y += 4
                if pressed[pygame.K_a] and x > 0:
                    x -= 4
                    actualiza_animacion_direccion_jugador(jugador, "izquierda")
                if pressed[pygame.K_d] and x < alto_pantalla - 58:
                    x += 4
                    actualiza_animacion_direccion_jugador(jugador, "derecha")
                if not pressed[pygame.K_d] and not pressed[pygame.K_a]:
                    actualiza_animacion_direccion_jugador(jugador, "centro")
                if pressed[pygame.K_LSHIFT]:
                    dispara_laser(x, y, lista_laseres_rojos, 2)
            # asignamos los nuevos valores
            # guardamos los nuevos valores de posición
            jugador[1] = x
            jugador[2] = y
        # Dibujamos/Actualizamos la lista de objetos dinámicos
        # ¡¡Van en orden de capa de pintado!! Para controlar quién aparece arriba o abajo cuando se superponen
        actualiza_y_pinta_naves_adorno()
        dibujar_lista_objetos_dinamicos(lista_laseres_rojos)
        dibujar_lista_objetos_dinamicos(lista_laseres_verdes)
        dibujar_lista_objetos_dinamicos(lista_objetos_enemigos)
        dibujar_lista_jugadores()
        chequea_impacto_en_jugador(lista_jugadores, lista_laseres_verdes)
        # Actualizamos el mundo del juego
        actualizar_y_pintar_explosiones()
        actualiza_posiciones_dinamicos(lista_objetos_enemigos)
        actualiza_posiciones_dinamicos(lista_laseres_rojos)
        actualiza_posiciones_dinamicos(lista_laseres_verdes)
        actualiza_saturacion_disparos()
        # Pintamos los textos en pantalla (va en la ultima capa)
        for jugador in lista_jugadores:
            pintar_puntos_pantalla(jugador)
        # Chequeamos triggers
        if chequea_colision_impactos(lista_objetos_enemigos, lista_laseres_rojos):
            naves_destruidas += 1
            random_naves_aleatoras(naves_destruidas)
        actualiza_aparicion_ties()
        # Muestro pantalla y actualizo reloj
        pygame.display.flip()
        clock.tick(60)
        # Veo si se ha activado el evento de salir del juego
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
                pygame.display.quit()
                sys.exit()
else:
    if not graficos_cargados:
        # Salimos por que no se han cargado bien los gráficos
        print("Error al cargar los gráficos el juego.")
    if not sonidos_cargados:
        # Salimos por que no se han cargado bien los sonidos
        print("Error al cargar los sonidos el juego.")
    print("Saliendo....")
# La música es opcional, pero informamos de que no está cargada.
if not musica_cargada:
    print("Error al cargar la música del juego.")


from pychance.parsing import Parser

class PyChance:
    def __init__(self):
        self.tables = {}
        self.parser = Parser(self)

    def add_table(self, name, table):
        self.tables[name] = table

if __name__ == '__main__':
    from pychance.data import SimpleTable

    test_table = SimpleTable("foo", ["[bar]", "baz"])
    test_table2 = SimpleTable("bar", ["testing", "this"])

    color_table = SimpleTable("color", ["red", "blue", "green", "yellow", "orange", "purple"])

    test = PyChance()
    test.add_table("foo", test_table)
    test.add_table("bar", test_table2)
    test.add_table("color", color_table)
    print(test.parser.parse("This is a [foo] test [bar]."))

    print(test.parser.parse("Color 1: [color] Color 2: [color] Color 3: [color]"))

    print(test.parser.parse("{a} test {a}  extra test"))


from typing import Dict, Tuple

def get_parameters_from_pypesto_result(
    pypesto_result,
    pypesto_problem,
    petab_problem,
) -> Tuple[Dict[str, float], Dict[str, float]]:
    scaled_parameters = dict(zip(
        pypesto_problem.x_names,
        pypesto_result.optimize_result.list[0]['x'],
    ))
    unscaled_parameters = petab_problem.unscale_parameters(scaled_parameters)
    return scaled_parameters, unscaled_parameters


# -*- coding: utf-8 -*-
# @Time    : 2023/4/25 00:14
# @Author  : CXRui
# @File    : test_setting_wifi.py
# @Description :
import time
import pytest
import logging
from page.method.system.setting_method import SettingMethod

global setting

@pytest.mark.usefixtures("appium_setup")  # 引用conftest.py中的appium_setup方法，启动appium服务
@pytest.mark.usefixtures("driver_setup")  # 引用conftest.py中的driver_setup方法，创建会话
class TestSettingWifi:

    @pytest.fixture()
    def init_setup(self):
        global setting
        setting = SettingMethod(self.driver, self.platform)
        logging.info("前置：打开设置")
        setting.launch_setting()
        time.sleep(3)

        yield 1
        logging.info("后置：杀掉设置")
        setting.terminate_settting()

    @pytest.mark.test_setting_wifi
    def test_setting_wifi(self, init_setup):
        """
        测试用例案例：打开设置->点击进入WiFi界面->断言，判断是否进入WiFi界面
        :param init_setup: 前置条件 and 后置条件
        :return:
        """
        logging.info("测试：点击Wi-Fi,进入到Wi-Fi连接界面")
        setting.click_wifi_text()
        # 如果已经进入到Wi-Fi界面，但是判断控件找不到，即判定没有进入到Wi-Fi界面，可以用添加or继续判定更加准确，请同学们自由发挥。
        result = setting.check_network_text_status()
        assert result, "没有进入到Wi-Fi界面"