#!/usr/bin/env python3
import requests
import sys
from bs4 import BeautifulSoup

class WrongNumberOfArgsError(Exception):
    pass

class InfiniteLoopError(Exception):
    pass

def to_snake_case(string):
    return string \
            .replace(',', '_') \
            .replace('.', '_') \
            .replace(' ', '_') \
            .replace('-', '_') \

def roads_to_philosophy(url, previous):
    try:
        data = requests.get(url)

        data.raise_for_status()

        road = BeautifulSoup(data.text, 'html.parser')

        title = road.find(id='firstHeading').text

        if title in previous:
            raise InfiniteLoopError

        previous.append(title)

        print(title)

        if title == 'Philosophy':
            return print(f"{len(previous)} roads from {previous[0]} to Philosophy")

        content = road.find(id='mw-content-text')

        allLinks = content.select('p > a')

        for link in allLinks:
            if (link.get('href') is not None) \
                    and \
                (link['href'].startswith('/wiki/')) \
                    and \
                (not link['href'].startswith('/wiki/Wikipedia:')) \
                    and \
                (not link['href'].startswith('/wiki/Help:')):

                return roads_to_philosophy('https://en.wikipedia.org' + link['href'], previous)

        return print("It leads to a dead end !")

    except requests.HTTPError as e:
        if (data.status_code == 404):
            return print("It leads to a dead end !")

    except InfiniteLoopError:
        return print("It leads to an infinite loop !")

    except Exception as e:
        return print(f'An exception occurred: {e}')

def orquestrator():
    try:
        if len(sys.argv) != 2:
            raise WrongNumberOfArgsError

        previous = []

        query = to_snake_case(sys.argv[1].strip())

        url = f'https://en.wikipedia.org/wiki/{query}'

        roads_to_philosophy(url, previous)

    except WrongNumberOfArgsError:
        return print('Wrong number of args!')

if __name__ == '__main__':
    orquestrator()


#!/usr/local/bin/python3
#
# Authors: Bobby Rathore (brathore), Neha Supe (nehasupe), Kelly Wheeler (kellwhee)
#
# Mountain ridge finder
# Based on skeleton code by D. Crandall, Oct 2019

from PIL import Image
import numpy as np
from scipy.ndimage import filters
import sys
import os
import imageio

class HMM:
    def __init__(self, transitional_probabilities, emission_probabilities):
        """
        Constructor for the HMM model class
        :param transitional_probabilities:
        :param emission_probabilities:
        """
        self.transitional_probabilities = transitional_probabilities
        self.emission_probabilities = emission_probabilities

    def get_emission_dist(self, emission):
        return self.emission_probabilities[:, emission]

    @property
    def get_number_of_states(self):
        return self.transitional_probabilities.shape[0]

    @property
    def get_transition_probabilities(self):
        return self.transitional_probabilities

def get_edge_strength(input_image) -> np.array:
    """
    calculate "Edge strength map" of an image
    :param input_image: the original image for which we want the edge strengths
    :return: a 2D numpy vector containing the edge strength matrix
    """
    grayscale = np.array(input_image.convert("L"))
    filtered_y = np.zeros(grayscale.shape)
    filters.sobel(grayscale, 0, filtered_y)
    return np.sqrt(filtered_y ** 2)

def draw_edge(image, y_coordinates, color, thickness):
    """
    draw a "line" on an image (actually just plot the given y-coordinates for each x-coordinate)
    image is the image to draw on y_coordinates is a list, containing the
    y-coordinates and length equal to the x dimension size of the image
    color is a (red, green, blue) color triple (e.g. (255, 0, 0) would be pure red
    thickness is thickness of line in pixels
    :param image: the original image object to put pixels on
    :param y_coordinates: the coordinates where we shall put pixels
    :param color: color of the pixels
    :param thickness: density/thickness of the pixels
    :return: image object with superimposed pixels
    """
    for (x, y) in enumerate(y_coordinates):
        for t in range(
            int(max(y - int(thickness / 2), 0)),
            int(min(y + int(thickness / 2), image.size[1] - 1)),
        ):
            image.putpixel((x, t), color)
    return image

def bayes_net(edge_strength_matrix: np.array, filename: str, image) -> None:
    """
    Naive Bayes Net implementation for the given image matrix
    :param edge_strength_matrix: a 2D numpy vector containing the edge strength matrix
    :param filename: name of the file we're working with
    :param image: the original image object to put pixels on
    :return: None
    """
    # Save for our records
    imageio.imwrite(
        "bayes_net/{0}_output_simple.jpg".format(filename.split(".")[0].split("/")[-1]),
        draw_edge(
            image=image.copy(),
            y_coordinates=edge_strength_matrix.argmax(axis=0),
            color=(0, 0, 255),
            thickness=5,
        ),
    )

    # Save for grading system
    imageio.imwrite(
        "output_simple.jpg",
        draw_edge(
            image=image,
            y_coordinates=edge_strength_matrix.argmax(axis=0),
            color=(0, 0, 255),
            thickness=5,
        ),
    )
    return None

def viterbi(edge_strength_matrix: np.array, filename: str, image) -> None:
    """
    Viterbi implementation for the given image matrix
    :param edge_strength_matrix: a 2D numpy vector containing the edge strength matrix
    :param filename: name of file we're working with
    :param image: the original image object to put pixels on
    :return: None
    """
    # Initial probabilities are normally distributed
    normally_distributed_initial_probabilities = np.full(
        edge_strength_matrix.shape[0], 1 / edge_strength_matrix.shape[0]
    )
    max_of_each_row = np.amax(edge_strength_matrix, axis=0)

    # Setup Emission Probabilities
    emission_probabilities = np.array(
        [
            each_row / max_of_each_row[index]
            for index, each_row in enumerate(edge_strength_matrix)
        ]
    )

    # Setup transitional Probabilities
    all_rows = range(edge_strength_matrix.shape[0])
    column_value_for_each_row = [row for row in all_rows]

    # Take absolute value of each row normalized with it's corresponding column value
    transitional_probabilities = np.array(
        [
            np.array(
                [
                    abs(
                        (
                            column
                            - np.max(
                                [
                                    abs(row - absolute_column_value)
                                    for absolute_column_value in column_value_for_each_row
                                ]
                            )
                        )
                        / np.max(
                            [
                                abs(row - absolute_column_value)
                                for absolute_column_value in column_value_for_each_row
                            ]
                        )
                    )
                    for column in [
                        abs(row - absolute_column_value)
                        for absolute_column_value in column_value_for_each_row
                    ]
                ]
            )
            for row in all_rows
        ]
    )

    # Viterbi algorithm begins here
    first_product, second_product = (
        np.empty((transitional_probabilities.shape[0], edge_strength_matrix.shape[1])),
        np.empty((transitional_probabilities.shape[0], edge_strength_matrix.shape[1])),
    )

    # Setup the first column by multiplying the initial and emission probabilities
    first_product[:, 0] = (
        normally_distributed_initial_probabilities * emission_probabilities[:, 0]
    )
    second_product[:, 0] = 0

    # Update each column along the way with the maximum value
    for column in range(1, edge_strength_matrix.shape[1]):
        first_product[:, column] = np.max(
            first_product[:, column - 1]
            * transitional_probabilities.T
            * emission_probabilities[:, column].T,
            1,
        )
        second_product[:, column] = np.argmax(
            first_product[:, column - 1] * transitional_probabilities.T, 1
        )

    # Get the y_coordinates ready
    resultant_matrix = np.empty(edge_strength_matrix.shape[1])
    resultant_matrix[-1] = np.argmax(
        first_product[:, edge_strength_matrix.shape[1] - 1]
    )

    # "Backtracking"
    for column in reversed(range(1, edge_strength_matrix.shape[1])):
        resultant_matrix[column - 1] = second_product[
            int(resultant_matrix[column]), column
        ]

    # Save for our records
    imageio.imwrite(
        "viterbi/{0}_output_map.jpg".format(filename.split(".")[0].split("/")[-1]),
        draw_edge(
            image=image.copy(),
            y_coordinates=resultant_matrix,
            color=(255, 0, 0),
            thickness=5,
        ),
    )

    # Save for grading system
    imageio.imwrite(
        "output_map.jpg",
        draw_edge(
            image=image, y_coordinates=resultant_matrix, color=(255, 0, 0), thickness=5
        ),
    )

    return None

def viterbi_with_logs(
    edge_strength_matrix: np.array,
    filename: str,
    image,
    row: int = 0,
    column: int = 0,
    human: bool = False,
) -> None:
    """
    Similar viterbi implementation as above but without initial probabilities,
    with human feedback incorporation and logs to avoid underflow errors
    :param edge_strength_matrix: a 2D numpy vector containing the edge strength matrix
    :param filename: the name of the file we're working with
    :param image: the original image object to put pixels on
    :param row: row pixel value where human thinks the ridge is
    :param column: column pixel value where human thinks the ridge is
    :param human: a flag to determine whether human feedback is to be considered or not
    :return: None
    """
    # Setup Transitional Probabilities
    transition_probabilities = np.repeat(
        np.linspace(
            0, edge_strength_matrix.shape[0] - 1, edge_strength_matrix.shape[0]
        ),
        edge_strength_matrix.shape[0],
    ).reshape(
        edge_strength_matrix.shape[0], edge_strength_matrix.shape[0]
    ).T - np.linspace(
        0, edge_strength_matrix.shape[0] - 1, edge_strength_matrix.shape[0]
    ).reshape(
        edge_strength_matrix.shape[0], 1
    )

    # Take the max of each column for each row and reshape
    transition_probabilities = np.amax(
        np.absolute(transition_probabilities), axis=0
    ).reshape(1, edge_strength_matrix.shape[0]) - np.absolute(transition_probabilities)

    # Divide by sum to normalize
    transition_probabilities = transition_probabilities / np.sum(
        transition_probabilities, axis=0
    ).reshape(1, edge_strength_matrix.shape[0])

    # Add a small value to avoid log infinity errors
    transition_probabilities += 0.00001

    # Setup Emission probabilities
    emission_probabilities = edge_strength_matrix / np.amax(
        edge_strength_matrix, axis=0
    )

    # Add a small value to avoid log infinity errors
    emission_probabilities += 0.00001

    # If we're considering human feedback in our algorithm,
    # Make the column values essentially equal to zero
    # And make that particular pixel equal to 1
    if human:
        emission_probabilities[:, column] = 0.00000001
        emission_probabilities[row, column] = 1

    # All observable intermediate states
    intermediate_states = np.array([0 for _ in range(edge_strength_matrix.shape[0])])
    all_possible_paths = [str(path) for path in range(edge_strength_matrix.shape[0])]

    # Make a backup to act as a backtracking device
    intermediate_states_backup = intermediate_states.copy()

    for column in range(1, edge_strength_matrix.shape[1]):
        for row in range(edge_strength_matrix.shape[0]):
            intermediate_states[row] = np.amax(
                np.log(transition_probabilities[:, row])
                + intermediate_states_backup
                + np.log(emission_probabilities[row, column])
            )
            all_possible_paths[row] += " " + np.argmax(
                np.log(transition_probabilities[:, row])
                + intermediate_states_backup
                + np.log(emission_probabilities[row, column])
            ).astype(str)
        intermediate_states_backup = intermediate_states.copy()

    resultant_matrix = np.array(
        all_possible_paths[np.argmax(intermediate_states)].split(" ")
    ).astype(int)

    # Save for our records
    imageio.imwrite(
        "{0}/{1}_output_{2}.jpg".format(
            "human_viterbi" if human else "viterbi",
            filename.split(".")[0].split("/")[-1],
            "human" if human else "map",
        ),
        draw_edge(
            image=image, y_coordinates=resultant_matrix, color=(0, 255, 0), thickness=5
        ),
    )

    # Save for grading system
    imageio.imwrite(
        "output_human.jpg",
        draw_edge(
            image=image, y_coordinates=resultant_matrix, color=(0, 255, 0), thickness=5
        ),
    )

    return None

if __name__ == "__main__":

    if not os.path.exists("viterbi"):
        os.makedirs("viterbi")

    if not os.path.exists("bayes_net"):
        os.makedirs("bayes_net")

    if not os.path.exists("human_viterbi"):
        os.makedirs("human_viterbi")

    (input_filename, gt_row, gt_col) = sys.argv[1:]

    # load in image
    input_image_bayes_net = Image.open(input_filename)
    input_image_viterbi = Image.open(input_filename)
    input_image_viterbi_with_log = Image.open(input_filename)

    # compute edge strength mask
    edge_strength = get_edge_strength(input_image_bayes_net)
    imageio.imwrite(
        "edges.jpg", np.uint8(255 * edge_strength / (np.amax(edge_strength)))
    )

    # Module 1: Bayes Net
    bayes_net(
        edge_strength_matrix=edge_strength,
        filename=input_filename,
        image=input_image_bayes_net,
    )

    # Module 2: Viterbi
    viterbi(
        edge_strength_matrix=edge_strength,
        filename=input_filename,
        image=input_image_viterbi,
    )

    # Module 3: Viterbi with human feedback
    viterbi_with_logs(
        edge_strength_matrix=edge_strength,
        filename=input_filename,
        image=input_image_viterbi_with_log,
        row=int(gt_row),
        column=int(gt_col),
        human=True,
    )


#!/usr/bin/python3
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
import weasyprint
import shutil
import os
import time
import json

def nfe_read(driver):
	nfe_dict = {}
	for fieldset in driver.find_elements_by_tag_name("fieldset"):
		try:
			legend = fieldset.find_element_by_tag_name("legend")
			table = fieldset.find_element_by_tag_name("table")
			tbody = table.find_element_by_tag_name("tbody")
			section = legend.get_attribute('textContent').strip()
			section_dict = {}
			for tr in tbody.find_elements_by_tag_name("tr"):
				for td in tr.find_elements_by_tag_name("td"):
					try:
						label = td.find_element_by_tag_name("label")
						span = td.find_element_by_tag_name("span")
						attribute = label.get_attribute('textContent').strip()
						value = span.get_attribute('textContent').strip()
						section_dict[attribute] = value
					except BaseException as Argument:
						continue;
			if len(section_dict) > 0:
				nfe_dict[section] = section_dict
		except BaseException as Argument:
			continue;

	return nfe_dict

def download_html(driver, filename):
	driver.find_element_by_id("ctl00_ContentPlaceHolder1_hplImprimir").click()
	driver.switch_to_window(driver.window_handles[1])
	with open(filename, "w") as f:
	    f.write(driver.page_source)

def nfe_navigate(driver, chave):
	driver.get("http://www.nfe.fazenda.gov.br/portaL/consultaRecaptcha.aspx")
	driver.find_element_by_link_text("Serviços").click()
	driver.find_element_by_link_text("Consultar NF-e Completa").click()
	txtChave=driver.find_element_by_id('ctl00_ContentPlaceHolder1_txtChaveAcessoCompleta')
	txtChave.send_keys(chave)
	try:
		element = WebDriverWait(driver, 120).until(
			EC.presence_of_element_located((By.ID, "ctl00_ContentPlaceHolder1_btnVoltar"))
		)
		print("Detected NF-E screen, waiting it to load")
		time.sleep(1)
	except:
		print("Timeout on NF-E captcha screen")

def validar_chave(chave):
	n = 2;
	soma = 0
	digitos =  list(chave);
	if len(digitos) != 44:
		print("Comprimento inválido (%s)" % len(digitos))
		return False;

	for i in digitos[0:43]:
		soma = soma + int(i) * (n + 2)
		n = (n + 7) % 8

	resto = (soma % 11)
	if resto == 0 or resto == 1:
		dv = 0
	else:
		dv = 11 - resto

	if (dv == int(digitos[-1])):
		return True
	else:
		print("Digito de verificação inválido %s != %s" % (dv, int(digitos[-1])))
		return False

def decode_chave(chave):
	if not validar_chave(chave):
		print("Chave invalida")
		return None;

	self = {}
	self["UF"] = chave[0:2]
	self["YY"] = chave[2:4]
	self["MM"] = chave[4:6]
	self["cnpj"] = chave[6:20]
	self["model"] = chave[20:22]
	self["serie"] = chave[22:25]
	self["numero"] = chave[25:34]
	self["emissao"] = chave[35]
	self["codigo"] = chave[35:43];
	self["dv"] = chave[43];
	return self

def nfe_download_json(driver, filename):
	data = nfe_read(driver)
	print(data["Dados da NF-e"]["Série"])
	print(data["Dados da NF-e"]["Número"])
	print(data["Dados da NF-e"]["Data de Emissão"])
	print(data["Dados da NF-e"]["Valor Total da Nota Fiscal"])
	print("Saving it")
	with open(filename, 'w') as f:
		json.dump(data, f)

def cache_path(chave, ext):
	chave_fields = decode_chave(chave)
	if chave_fields is None:
		return False

	return "cache/%s/%s/%s.%s" % (chave_fields["YY"], chave_fields["MM"], chave, ext)

def nfe_download_to_cache(chave):

	chave_fields = decode_chave(chave)
	if chave_fields is None:
		return False

	newpath = "cache/%s/%s" % (chave_fields["YY"], chave_fields["MM"])
	if not os.path.exists(newpath):
	    shutil.copytree("cache/css", newpath + "/css")

	if os.path.isfile(cache_path(chave, "json")) and os.path.isfile(cache_path(chave, "html")):
		print("%s hit cache" % chave)
		return True

	print("Starting selenium with Firefox")
	driver = webdriver.Firefox()

	nfe_navigate(driver, chave)

	print("Downloading values")
	nfe_download_json(driver, cache_path(chave, "json"))

	print("Saving SnapShot")
	download_html(driver, cache_path(chave, "html"))

	print("Finishing section")
	driver.quit()

	return True

def download_json(chave):
	if not nfe_download_to_cache(chave):
		return None

	with open(cache_path(chave, "json"), 'r') as f:
		return json.load(f)

def nfe_create_pdf(chave):
	if not nfe_download_to_cache(chave):
		return
	pdf = weasyprint.HTML(cache_path(chave, "html")).write_pdf()
	with open(cache_path(chave, "pdf"), 'wb') as f:
		f.write(pdf)

	return cache_path(chave, "pdf")


# coding=utf-8
import os
import requests
from tqdm import tqdm
from mindsearch.utils.logger import Logger

logger = Logger(__name__).get_logger()

def download_url(url, save_path):
    """
    Download file from remote `url` to local directory, the file will be named `path` locally.
    """
    if os.path.dirname(save_path) != '':
        os.makedirs(os.path.dirname(save_path), exist_ok=True)

    req = requests.get(url, stream=True, verify=False)
    if req.status_code != 200:
        logger.error("Exception when downloading {}, response code {}".format(url, req.status_code))
        req.raise_for_status()
        return

    download_filepath = f"{save_path}_part"
    with open(download_filepath, "wb") as writer:
        content_length = req.headers.get('Content-Length')
        total = int(content_length) if content_length is not None else None
        progress = tqdm(unit="B", total=total, unit_scale=True)
        for chunk in req.iter_content(chunk_size=1024):
            if chunk:
                writer.write(chunk)
                progress.update(len(chunk))

    os.rename(download_filepath, save_path)
    progress.close()


import numpy as np
import math
import h5py
import openpyxl
from scipy import signal as signal
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_score, recall_score
from sklearn.externals import joblib
import joblib

NegativeThreshold = 15
PositiveThreshold = 5
Threshold =  NegativeThreshold + PositiveThreshold
TimeWidth = 32                    #时间窗长度
BreakTime = 30
InvalidTime = 5
standard = {                      #归一化基准
            'ip': 225,
            'Bt': 2.05,
            'axuv_ca_01': 1.3,
            'sxr_cb_024': 1.5,
            'sxr_cc_049': 4,
            'vs_c3_aa001': 5,
            'vs_ha_aa001': 1,
            'exsad1': 6, 'exsad2': 2.5, 'exsad4': 1.3, 'exsad7': 4, 'exsad8': 1, 'exsad10': 6,
            'Ivfp': 3,
            'Ihfp': 1,
            'MA_POL_CA01T': 2, 'MA_POL_CA02T': 2, 'MA_POL_CA03T': 2, 'MA_POL_CA05T': 2, 'MA_POL_CA06T': 2,
            'MA_POL_CA07T': 2, 'MA_POL_CA19T': 2, 'MA_POL_CA20T': 2, 'MA_POL_CA21T': 2, 'MA_POL_CA22T': 2,
            'MA_POL_CA23T': 2, 'MA_POL_CA24T': 2
            }

#训练信号
lf_tags = [
            r'\ip',
            r'\Bt',
            r'\axuv_ca_01',
            r'\sxr_cb_024',
            r'\vs_c3_aa001',
            r'\vs_ha_aa001',
            r'\sxr_cc_049',
            r'\exsad1', r'\exsad2', r'\exsad4', r'\exsad7', r'\exsad8', r'\exsad10',
            r'\Ivfp', r'\Ihfp'
        ]

hf_tags = [
            r'\MA_POL_CA01T', r'\MA_POL_CA02T', r'\MA_POL_CA03T', r'\MA_POL_CA05T', r'\MA_POL_CA06T',
            r'\MA_POL_CA07T',r'\MA_POL_CA19T', r'\MA_POL_CA20T', r'\MA_POL_CA21T', r'\MA_POL_CA22T', r'\MA_POL_CA23T', r'\MA_POL_CA24T'
        ]
all_tags =  lf_tags + hf_tags
for i in range(len(all_tags)):       #去掉\
    all_tags[i] = all_tags[i][1:]

#对10Hz采样的信号进行加工处理
def process_10Hz(data):
    processed_data = []
    section = math.ceil(len(data) / 10)
    for j in range(section):
        if j < (section - 1):
            mean = np.mean(data[(10 * j) :(10 * j + 10)])
            processed_data.append(mean)
        else:
            mean = np.mean(data[(10 * j):])
            processed_data.append(mean)
    return processed_data

#对250Hz采样的信号进行加工处理
def process_250Hz(data):
    processed_data = []
    section = math.ceil(len(data) / 250)
    for j in range(section):
        if j < (section - 1):
            mean = np.mean(data[(250 * j):(250 * j + 250)])
            processed_data.append(mean)
        else:
            mean = np.mean(data[(250 * j):])
            processed_data.append(mean)
    return processed_data

#对500Hz采样的信号进行加工处理
def process_500Hz(data):
    processed_data = []
    section = math.ceil(len(data) / 500)
    for j in range(section):
        if j < (section - 1):
            mean = np.mean(data[(500 * j):(500 * j + 500)])
            processed_data.append(mean)
        else:
            mean = np.mean(data[(500 * j):])
            processed_data.append(mean)
    return processed_data

#下降时间
def down_time(data):
    ip = data
    ba = signal.butter(8, 0.04, 'lowpass')
    ip_ = signal.filtfilt(ba[0], ba[1], ip)
    start = 0
    end = 0
    for i in range(len(ip_ - 640)):
        if ip_[i] > ip_[i + 20] > ip_[i + 40] and ip_[i] * 0.95 > ip_[i + 160] and ip_[i] * 0.9 > ip_[i + 320] \
                and ip_[i] * 0.8 > ip_[i + 640]:
            start = i
            break
    for i in range(start, len(ip_ - 640)):
        if ip_[i] <= 10:
            end = i
            break
    if start and end:
        if end - start < 600:
            shot_label = -1
        else:
            shot_label = 1
    k = []
    for i in range(190):
        k_i = (data[50 * i + 49] - data[50 * i]) / 0.005
        k.append(k_i)
    if shot_label == 1:
        # print("此炮为正常炮")
        DownTime = (start + 500) / 10000
        DownData = data[start]
    else:
        # print("此炮为破裂炮")
        for i in range(30, 190):
            if (k[i] > -4000) and (k[i + 1] < -4000):
                for j in range(50):
                    error = data[50 * i + 50 + j + 1] - data[50 * i + 50 + j]
                    if error < -5:
                        DownTime = ((50 * i + 50 + j) / 10000) + 0.05
                        down_data = data[50 * i + 50 + j]
                        break
                break
    return  DownTime, shot_label

def reduce_sampling(shot):
    reduce_sampling_signal = {}
    g = h5py.File(r"/home/axk/chipsvm/data/{}.hdf5".format(shot), 'r')
    dataset = g.get("ip")
    data = list(dataset["data"])
    time = list(dataset["time"])
    DownTime, shot_flag = down_time(data)
    if shot_flag == -1:
        print("此炮为正常炮")
        shot_label = -1
        print("DownTime : {}".format(DownTime))
        for shottag in all_tags:
            dataset = g.get(shottag)
            data = np.array(dataset["data"])
            time = np.array(dataset["time"])
            data = data[time > 0.1]
            time = time[time > 0.1]
            data = data[time <= DownTime]
            time = time[time <= DownTime]
            datatemp = data[time < 0.11]
            if len(datatemp) < 200:
                processed_data = process_10Hz(data)
            elif len(datatemp) < 3000:
                processed_data = process_250Hz(data)
            else:
                processed_data = process_500Hz(data)
            reduce_sampling_signal.update({shottag:processed_data})
    else:
        print("此炮为破裂炮")
        shot_label = 1
        print("DownTime : {}".format(DownTime))
        for shottag in all_tags:
            dataset = g.get(shottag)
            data = np.array(dataset["data"])
            time = np.array(dataset["time"])
            data = data[time > 0.1]
            time = time[time > 0.1]
            data = data[time <= DownTime]
            time = time[time <= DownTime]
            datatemp = data[time < 0.11]
            if len(datatemp) < 200:
                processed_data = process_10Hz(data)
            elif len(datatemp) < 3000:
                processed_data = process_250Hz(data)
            else:
                processed_data = process_500Hz(data)
            reduce_sampling_signal.update({shottag: processed_data})
    g.close()
    return reduce_sampling_signal, shot_label

def time_chipping(shot):
    signal, shot_label = reduce_sampling(shot)
    data = signal["ip"]
    step = len(data) - TimeWidth + 1
    incident = np.mat(np.ones((step, 1)))
    for tag in all_tags:
        data = signal[tag]
        data = (np.array(data)) / (standard[tag])
        chip = []
        for i in range(step):
            chip.append(data[i: (i + TimeWidth)])
        chip = np.mat(chip)
        incident = np.hstack((incident, chip))
    incident = np.delete(incident, 0, axis=1)
    incident = np.array(incident)
    return incident

#获取测试炮和其对应的标签，正常炮200个，破裂炮200个
np.random.seed(4)
TestBreak = np.load(r"/home/axk/chipsvm/BreakTest.npy")
TestNormal = np.load(r"/home/axk/chipsvm/NormalTest.npy")
# TestBreak = np.random.choice(TestBreak, 200)
# TestNormal = np.random.choice(TestNormal, 200)
BreakLabel = []
for i in range(len(TestBreak)):
    BreakLabel.append(1)
BreakLabel = np.array(BreakLabel)

NormalLabel = []
for i in range(len(TestNormal)):
    NormalLabel.append(-1)
NormalLabel = np.array(NormalLabel)
TestTemp = list(TestBreak) + list(TestNormal)
LabelTemp = list(BreakLabel) + list(NormalLabel)
TrainIndex = np.arange(len(LabelTemp))
TrainIndex = np.random.permutation(TrainIndex)
test = []
label = []
for i in TrainIndex:
    test.append(TestTemp[i])
    label.append(LabelTemp[i])
label = np.array(label)
print("label : ")
print(len(label))

#对测试炮进行预测
clf = joblib.load(r"/home/axk/chipsvm/SVMmodal/svmModel1c0.1.plk")
gamma = 1
C = 0.1
name = "shot" + str(gamma) + "vs" + str(C)
n = 1
shotlabel = []
Advance = []
for shot in test:
    flag = -1
    chip = time_chipping(shot)
    chiplength = len(chip)
    print("第{}炮".format(n))
    n += 1
    print(chip.shape)
    ChipPredict = []
    for i in range(len(chip)):
        count_positive = 0
        count_negative = 1
        ChipPred_Label = clf.predict([chip[i]])
        ChipPredict.append(ChipPred_Label)
        if len(ChipPredict) > Threshold:
            Sect = np.array(ChipPredict[-Threshold : ])
            num = Sect[Sect == 1].size
            if (num/len(Sect)) > 0.5:
                if Sect[0] == 1:
                    for j in range(1,len(Sect)):
                        if ((Sect[j-1]==1)and(Sect[j]==1)):
                            count_negative += 1
                            if count_negative > NegativeThreshold:
                                flag = 1
                                break
                        elif (((Sect[j-1]==1)and(Sect[j]==-1))or((Sect[j-1]==-1)and(Sect[j]==-1))):
                            count_positive += 1
                            if count_positive >= PositiveThreshold:
                                flag = -1
                                count_negative = 0
                                break
                        elif ((Sect[j-1]==-1)and(Sect[j]==1)):
                            count_positive = 0
                            count_negative += 1
                            if count_negative > NegativeThreshold:
                                flag = 1
                                break
        if flag == 1:
            shotlabel.append(flag)
            AdvanceTime = chiplength - i - 1
            print("提前时间 ： {}".format(AdvanceTime))
            Advance.append(AdvanceTime)
            break
    if flag == -1:
        shotlabel.append(flag)
    print(shotlabel[-1])
print("shotlabel  :   {}".format(len(shotlabel)))
print(shotlabel)
print(label)
# 评价
print("返回给定测试集和对应标签的平均准确率")
shotlabel = np.array(shotlabel)
correct = 0
for i in range(len(label)):
        if int(label[i]) == int(shotlabel[i]):
            correct += 1
print(correct)
accuary = correct / len(shotlabel)
print(accuary)
print("混淆矩阵：")
conf = confusion_matrix(label, shotlabel)
print(conf)
print("precision : ")
precision = precision_score(label, shotlabel)
print(precision)
print("recall : ")
recall = recall_score(label, shotlabel)
print(recall)
print("FPR : ")
FPR = conf[0, 1] / (conf[0, 1] + conf[0, 0])
print(FPR)

result = [name,accuary,precision,recall,FPR,conf[0,0],conf[0,1],conf[1,0],conf[1,1]]
title = ["name","accuary","precision","recall","FPR","conf[0,0]","conf[0,1]","conf[1,0]","conf[1,1]"]
np.save(r"/home/axk/shotsvm/result/1c0.1/single/title.npy",title)
np.save(r"/home/axk/shotsvm/result/1c0.1/single/{}.npy".format(name),result)
Aname = "advance" + str(gamma) + "vs" + str(C)
np.save(r"/home/axk/shotsvm/result/1c0.1/single/{}.npy".format(Aname),Advance)


import cv2
import numpy as np
from threading import Thread
import time
import argparse
#from gui import onmouse, updateGUI
from gui import gui, getPath
from VideoStream import VideoStream#, VideoSave

parser = argparse.ArgumentParser()
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
                    default='1280x720')
parser.add_argument('--fps', help='Frames per second',
                    default=20)

args = parser.parse_args()
resW, resH = args.resolution.split('x')
w, h = int(resW), int(resH)
FPS = int(args.fps)

# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()

# Initialize video stream
cv2.namedWindow("test",1)
g=gui()
cv2.setMouseCallback("test",g.onmouse)
path=g.getPath()
videostream = VideoStream(resolution=(w,h),framerate=FPS).start()
out=None
#videosave = None#VideoSave(path, FPS, (w,h)).start()

time.sleep(1)

while True:
    t1 = cv2.getTickCount()

    frame = videostream.read()
    #cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)
    cv2.imshow('frame', frame)

    img=g.updateGUI()
    cv2.imshow("test",img)

    if g.getRecordingStatus():
        if out == None:
            #out=cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*'mp4v'), FPS, (w,h), True)
            #out=cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*'MJPG'), FPS, (w,h), True)
            out=cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*'WMV2'), 10, (w,h), True)
            print("recording start")
        out.write(frame)
    else:
        if not out == None:
            out.release()
            out=None
            print("recording stopped")

    '''
    if g.getRecordingStatus():
        path=g.getPath()
        videostream.recordupdate(True, path)
    else:
        videostream.recordupdate(False)
    '''
    '''
    if g.getRecordingStatus():
        if videosave==None:#videosave.getStatus():
            path=g.getPath()
            videosave = VideoSave(path, FPS, (w,h)).start()
            print("recording start")
        videosave.writeframe(img)

    else:
        if not videosave==None:#videosave.getStatus():
            videosave.stop()
            print("recording stop")
            videosave=None
    '''
    # Calculate framerate
    t2 = cv2.getTickCount()
    time1 = (t2-t1)/freq
    frame_rate_calc= 1/time1

    # Press 'q' to quit
    if cv2.waitKey(1) == ord('q'):
        break

# Clean up
cv2.destroyAllWindows()
videostream.stop()
#if not videosave == None:
#    videosave.stop()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import jsonfield.fields
from django.conf import settings
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Notification',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)),
                ('level', models.CharField(max_length=20, default='info', choices=[('success', 'success'), ('info', 'info'), ('warning', 'warning'), ('error', 'error')])),
                ('unread', models.BooleanField(default=True)),
                ('actor_object_id', models.PositiveIntegerField()),
                ('verb', models.CharField(max_length=255)),
                ('description', models.TextField(null=True, blank=True)),
                ('target_object_id', models.PositiveIntegerField(null=True, blank=True)),
                ('action_object_object_id', models.PositiveIntegerField(null=True, blank=True)),
                ('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
                ('public', models.BooleanField(default=True)),
                ('deleted', models.BooleanField(default=False)),
                ('emailed', models.BooleanField(default=False)),
                ('data', jsonfield.fields.JSONField(null=True, blank=True)),
                ('action_object_content_type', models.ForeignKey(null=True, blank=True, to='contenttypes.ContentType', related_name='notify_action_object')),
                ('actor_content_type', models.ForeignKey(related_name='notify_actor', to='contenttypes.ContentType')),
                ('recipient', models.ForeignKey(related_name='notifications', to=settings.AUTH_USER_MODEL)),
                ('target_content_type', models.ForeignKey(null=True, blank=True, to='contenttypes.ContentType', related_name='notify_target')),
            ],
            options={
                'ordering': ('-timestamp',),
            },
        ),
    ]


from PyQt5.QtWidgets import QMainWindow, QLabel
from PyQt5.QtCore import QPoint, Qt

from fuzzyclock import FuzzyClock

class SimpleFuzzyClockWindow(QMainWindow):

    def __init__(self, fuzzy_clock=None, size=(190, 35)):
        super().__init__()

        if fuzzy_clock is None:
            self.fuzzy_clock = FuzzyClock()
        else:
            self.fuzzy_clock = fuzzy_clock

        self.main_widget = QMainWindow(self)
        self.setWindowFlags(Qt.FramelessWindowHint)

        self.setFixedSize(size[0], size[1])

        self.label = QLabel(self)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("background-color: rgb(0,0,0);"
                                 "color: rgb(0,255,0);"
                                 "font: bold 14pt 'Times New Roman';")

        self.label.setGeometry(0, 0, size[0], size[1])
        self.set_text(text=self.fuzzy_clock.get_time())

        self.old_pos = self.pos()

    def set_text(self, text=""):
        self.label.setText(text)
        self.show()

    def mousePressEvent(self, event):
        self.old_pos = event.globalPos()

    def mouseMoveEvent(self, event):
        movement = QPoint(event.globalPos() - self.old_pos)
        self.move(self.x() + movement.x(), self.y() + movement.y())
        self.old_pos = event.globalPos()

    def update_label(self):
        self.fuzzy_clock.update()
        self.set_text(self.fuzzy_clock.get_time())


import os
import warnings
from abc import ABCMeta
from collections import namedtuple

import re

from .base import Operation, Bank, Account, Historic, Entity

class AxaBank(Bank):
    def __init__(self):
        super().__init__("Axa", "AXABBE22")

    def __repr__(self):
        return "{}()".format(self.__class__.__name__)

class AxaOp(Operation):
    # Always try to be more specific
    def __init__(self, account, operation_date, effective_date, value,
                 description, amount_remaining, message=""):
        super().__init__(account, operation_date, effective_date, value,
                         description)
        self.amount_remaining = amount_remaining
        self.message = message

class NotAccountOp(AxaOp, metaclass=ABCMeta):
    """The other party is not an account"""
    def __init__(self, account, operation_date, effective_date, value,
                 description, amount_remaining, other_party_name,
                 other_party_place, message=""):
        super().__init__(account, operation_date, effective_date, value,
                         description, amount_remaining, message)
        self.other_party_name = Entity(other_party_name)
        self.other_party_place = other_party_place

    def get_other_party(self):
        return self.other_party_name

class Payment(NotAccountOp):
    pass

class Withdrawal(NotAccountOp):
    pass

class AccountOp(AxaOp, metaclass=ABCMeta):
    def __init__(self, account, operation_date, effective_date, value,
                 description, amount_remaining, other_party_account,
                 other_party_name, message=""):
        super().__init__(account, operation_date, effective_date, value,
                         description, amount_remaining, message)

        self.other_party = Account(iban=other_party_account,
                                   name=other_party_name)

    def get_other_party(self):
        return self.other_party

class Transfer(AccountOp):
    pass

class PossiblyWithinOperation(AccountOp):
    def get_other_party(self):
        other = super().get_other_party()
        if isinstance(other, Account) and other.name == "":
            return self.account.bank
        return other

class Debit(PossiblyWithinOperation):
    """Like fiscal domiciliation"""
    pass

class PermanentOrder(AccountOp):
    pass

class VisaDebit(Debit):
    pass

class Fee(PossiblyWithinOperation):
    def get_other_party(self):
        return self.account.bank

class AxaParser(object):
    OpStr = namedtuple('OpStr', ['id', 'operation_date', 'effective_date',
                                 'writing_date', 'value', 'amount_remaining',
                                 'type', 'other_account', 'other_name',
                                 'machine_name', 'place', 'card_number',
                                 'msg1', 'msg2', 'details'])

    def _parse_general_header(self, hdl, account_name):
        bank = AxaBank()
        type = hdl.readline().strip()
        account_str = hdl.readline()
        bic_str = hdl.readline()
        for _ in range(5):
            # Skip useless lines
            hdl.readline()

        iban = account_str[5:].replace(" ", "").strip()
        bic = bic_str[4:].strip()
        if bank.bic != bic:
            print(len(bank.bic))
            print(len(bic))
            raise ValueError("BIC of the bank is not correct. "
                             "Expecting {}, found {}".format(bank.bic, bic))
        return Account(iban, bank, account_name, type=type)

    def _parse_operation(self, line, line_number, account):
        op_str = self.__class__.OpStr(*line.split(";"))
        # Selecting on type

        other_is_account = False
        other_is_not_account = False
        if op_str.type == "Achat - Bancontact" or \
           op_str.type == "Achat - Maestro" or \
           op_str.type == "Vente glob. - Bancontact":
            factory = Payment
            other_is_not_account = True
        elif op_str.type.startswith("Retrait"):
            factory = Withdrawal
            other_is_not_account = True
        elif op_str.type.startswith("Virement"):
            factory = Transfer
            other_is_account = True
        elif op_str.type == "Ordre permanent":
            factory = PermanentOrder
            other_is_account = True
        elif op_str.type.startswith("Domiciliation") or \
             op_str.type == "Encaissement interne":
            if "visa" in op_str.type.lower():
                factory = VisaDebit
            else:
                factory = Debit
            other_is_account = True
        elif op_str.type.startswith("Contribution"):
            factory = Fee
            other_is_account = True
        elif op_str.type == "Capitalisation":
            factory = Fee  # Weird
            other_is_account = True
        else:
            warnings.warn("Unknown operation type '{}' (line {})."
                          "".format(op_str.type, line_number))
            factory = AxaOp

        def partial(**kwargs):
            return factory(account=account,
                           operation_date=op_str.operation_date,
                           effective_date=op_str.effective_date,
                           value=float(op_str.value.replace(",", ".")),
                           description=op_str.details,
                           amount_remaining=op_str.amount_remaining,
                           message=os.linesep.join([op_str.msg1, op_str.msg2]),
                           **kwargs)

        if other_is_account:
            return partial(other_party_account=op_str.other_account,
                           other_party_name=op_str.other_name)
        elif other_is_not_account:
            return partial(other_party_name=op_str.machine_name,
                           other_party_place=op_str.place)
        else:
            return partial()

    def parse_csv(self, fpath, account_name="n/a", encoding="latin"):
        ops = []
        line_start = re.compile(r"^\d\d\d\d(\s)?/(\s)?\d+")
        with open(fpath, "r", encoding=encoding) as hdl:
            account = self._parse_general_header(hdl, account_name)
            header_line = hdl.readline().strip()  # skip csv header
            curr_line = ""
            for i, line in enumerate(hdl):
                if line_start.match(line):
                    if len(curr_line) > 0:
                        ops.append(self._parse_operation(curr_line.strip(),
                                                         i + 8,
                                                         account))
                    curr_line = line
                else:
                    curr_line += line

        return Historic(ops)


import sys
import pygame

from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_ESCAPE
from pygame.locals import K_F1
from pygame.locals import K_SLASH
from pygame.locals import K_TAB

from pygame.locals import K_h
from pygame.locals import K_i
from pygame.locals import K_q

MAP_DEFAULT_SCALE = 0.1
HERO_DEFAULT_SCALE = 1.0

def exit_game():
    """Shuts down program and PyGame"""
    pygame.quit()
    sys.exit()

class InputControl(object):
    """Class that handles input received such as keyboard and mouse."""

    def __init__(self):
        """Initializes input member variables when instance is created."""
        self.mouse_pos = (0, 0)
        self.mouse_offset = [0.0, 0.0]
        self.wheel_offset = 0.1
        self.wheel_amount = 0.025

        # Modules that input will depend on
        self._hud = None
        self._world = None

    def start(self, hud, world):
        """Assigns other initialized modules that input module needs."""
        self._hud = hud
        self._world = world

    def render(self, display):
        """Does nothing. Input module does not need render anything."""

    def tick(self, clock):
        """Executed each frame. Calls method for parsing input."""
        self.parse_input(clock)

    def _parse_events(self):
        """Parses input events. These events are executed only once when pressing a key."""
        self.mouse_pos = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_game()
            elif event.type == pygame.KEYUP:
                if self._is_quit_shortcut(event.key):
                    exit_game()
                elif event.key == K_h or (
                    event.key == K_SLASH and pygame.key.get_mods() & KMOD_SHIFT
                ):
                    self._hud.help.toggle()
                elif event.key == K_TAB:
                    # Toggle between hero and map mode
                    if self._world.hero_actor is None:
                        self._world.select_hero_actor()
                        self.wheel_offset = HERO_DEFAULT_SCALE
                        self._hud.notification("Ego Mode")
                    else:
                        self.wheel_offset = MAP_DEFAULT_SCALE
                        self.mouse_offset = [0, 0]
                        self.mouse_pos = [0, 0]
                        self._world.scale_offset = [0, 0]
                        self._world.hero_actor = None
                        self._hud.notification("Map Mode")
                elif event.key == K_F1:
                    self._hud.show_info = not self._hud.show_info
                elif event.key == K_i:
                    self._world.show_actor_ids = not self._world.show_actor_ids

            elif event.type == pygame.MOUSEBUTTONDOWN:
                # Handle mouse wheel for zooming in and out
                if event.button == 4:
                    self.wheel_offset += self.wheel_amount
                    if self.wheel_offset >= 1.0:
                        self.wheel_offset = 1.0
                elif event.button == 5:
                    self.wheel_offset -= self.wheel_amount
                    if self.wheel_offset <= 0.1:
                        self.wheel_offset = 0.1

    def _parse_mouse(self):
        """Parses mouse input"""
        if pygame.mouse.get_pressed()[0]:
            x, y = pygame.mouse.get_pos()
            self.mouse_offset[0] += (1.0 / self.wheel_offset) * (x - self.mouse_pos[0])
            self.mouse_offset[1] += (1.0 / self.wheel_offset) * (y - self.mouse_pos[1])
            self.mouse_pos = (x, y)

    def parse_input(self, clock):
        """Parses the input, which is classified in keyboard events and mouse"""
        self._parse_events()
        self._parse_mouse()

    @staticmethod
    def _is_quit_shortcut(key):
        """Returns True if one of the specified keys are pressed"""
        return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)


#!/usr/bin/env python
from random import randint
from typing import Union

import tcod.color

from pyrl.components import Equipment, Inventory, Level, Player, Stairs
from pyrl.components.equippable import Equippable, Slot
from pyrl.components.item import Item
from pyrl.components.visual import RenderOrder
from pyrl.components.xp_reward import XpReward
from pyrl.random_utils import SpawnRow, SpawnTable
from pyrl.resources import Fov

from . import config
from .components import Collider, Energy, Fighter, Name, Position, Visual
from .components.ai import basic as basic_ai
from .components.ai import player as player_ai
from .esper_ext import WorldExt
from .resources.map import Map, Rect
from .vector import Vector

def create_room(map: Map, room: Rect) -> None:
    for x in range(room.x1 + 1, room.x2):
        for y in range(room.y1 + 1, room.y2):
            map.tiles[x][y].blocked = False

            map.tiles[x][y].block_sight = False

def create_h_tunnel(map: Map, x1: int, x2: int, y: int) -> None:
    for x in range(min(x1, x2), max(x1, x2) + 1):
        map.tiles[x][y].blocked = False
        map.tiles[x][y].block_sight = False

def create_v_tunnel(map: Map, y1: int, y2: int, x: int):
    for y in range(min(y1, y2), max(y1, y2) + 1):
        map.tiles[x][y].blocked = False
        map.tiles[x][y].block_sight = False

def dummy_map() -> Map:
    map = Map(width=config.MAP_WIDTH, height=config.MAP_HEIGHT, dungeon_level=0)
    create_room(map, Rect(20, 15, 10, 15))
    create_room(map, Rect(35, 15, 10, 15))
    create_h_tunnel(map, 25, 40, 23)
    return map

def random_map(dungeon_level: int) -> Map:
    map = Map(
        width=config.MAP_WIDTH, height=config.MAP_HEIGHT, dungeon_level=dungeon_level
    )

    for _ in range(config.MAX_ROOMS):
        # random width and height
        w = randint(config.ROOM_MIN_SIZE, config.ROOM_MAX_SIZE)
        h = randint(config.ROOM_MIN_SIZE, config.ROOM_MAX_SIZE)
        # random position without going out of the boundaries of the map
        x = randint(0, map.width - w - 1)
        y = randint(0, map.height - h - 1)

        # "Rect" class makes rectangles easier to work with
        new_room = Rect(x, y, w, h)

        if not any(new_room.intersect(other_room) for other_room in map.rooms):
            create_room(map, new_room)
            new_center = new_room.center
            if not map.rooms:
                map.spawn_position = Position(new_center)
            else:
                connect_room(map, new_center)
            map.rooms.append(new_room)

    return map

def connect_room(map: Map, new_center: Vector) -> None:
    # center coordinates of previous room
    prev_center = map.rooms[-1].center
    # flip a coin (random number that is either 0 or 1)
    if randint(0, 1) == 1:
        # first move horizontally, then vertically
        create_h_tunnel(map, prev_center.x, new_center.x, prev_center.y)
        create_v_tunnel(map, prev_center.y, new_center.y, new_center.x)
    else:
        # first move vertically, then horizontally
        create_v_tunnel(map, prev_center.y, new_center.y, prev_center.x)
        create_h_tunnel(map, prev_center.x, new_center.x, new_center.y)

max_monsters_per_room = SpawnRow(2, 1)(3, 4)(5, 6)
monster_spawn_table: SpawnTable[str] = SpawnTable()
monster_spawn_table.add("orc")(80)
monster_spawn_table.add("troll")(15, 3)(30, 5)(60, 7)

def generate_monsters(world: WorldExt) -> None:
    map = world.get_resource(Map)
    our_max_monsters_per_room = max_items_per_room.weight(map.dungeon_level)

    for room in map.rooms:
        number_of_monsters = randint(0, our_max_monsters_per_room)

        for i in range(number_of_monsters):
            # Choose a random location in the room
            position = Position(
                Vector(
                    x=randint(room.x1 + 1, room.x2 - 1),
                    y=randint(room.y1 + 1, room.y2 - 1),
                )
            )

            if not any(match[1] == position for match in world.get_component(Position)):
                monster = world.create_entity(position, Collider(), Energy(1), basic_ai)
                monster_choice = monster_spawn_table.spawn(map.dungeon_level)

                if monster_choice == "orc":
                    world.add_components(
                        monster,
                        Name("Orc"),
                        Visual(
                            char="o",
                            color=tcod.desaturated_green,
                            render_order=RenderOrder.ACTOR,
                        ),
                        Fighter.new(hp=20, defense=0, power=4),
                        XpReward(35),
                    )
                else:
                    world.add_components(
                        monster,
                        Name("Troll"),
                        Visual(
                            char="T",
                            color=tcod.darker_green,
                            render_order=RenderOrder.ACTOR,
                        ),
                        Fighter.new(hp=30, defense=2, power=8),
                        XpReward(100),
                    )

max_items_per_room = SpawnRow(1, 1)(2, 4)
item_spawn_table: SpawnTable[Union[Item, Slot]] = SpawnTable()
item_spawn_table.add(Item.HEALING_POTION)(35)
item_spawn_table.add(Item.LIGHTNING_SCROLL)(25, 4)
item_spawn_table.add(Item.LIGHTNING_SCROLL)(25, 6)
item_spawn_table.add(Item.CONFUSION_SCROLL)(10, 2)
item_spawn_table.add(Slot.MAIN_HAND)(5, 4)
item_spawn_table.add(Slot.OFF_HAND)(15, 8)

def generate_items(world: WorldExt) -> None:
    map = world.get_resource(Map)
    our_max_items_per_room = max_items_per_room.weight(map.dungeon_level)

    for room in map.rooms:
        number_of_items = randint(0, our_max_items_per_room)

        for i in range(number_of_items):
            position = Position(
                Vector(
                    x=randint(room.x1 + 1, room.x2 - 1),
                    y=randint(room.y1 + 1, room.y2 - 1),
                )
            )

            if not any(match[1] == position for match in world.get_component(Position)):
                item_choice = item_spawn_table.spawn(map.dungeon_level)

                if item_choice is Item.HEALING_POTION:
                    world.create_entity(
                        position,
                        Visual("!", tcod.violet, RenderOrder.ITEM),
                        Name("Healing Potion"),
                        Item.HEALING_POTION,
                    )
                elif item_choice is Item.FIREBALL_SCROLL:
                    world.create_entity(
                        position,
                        Visual("#", tcod.red, RenderOrder.ITEM),
                        Name("Fireball Scroll"),
                        Item.FIREBALL_SCROLL,
                    )
                elif item_choice is Item.LIGHTNING_SCROLL:
                    world.create_entity(
                        position,
                        Visual("#", tcod.yellow, RenderOrder.ITEM),
                        Name("Lightning Scroll"),
                        Item.LIGHTNING_SCROLL,
                    )
                elif item_choice is Item.CONFUSION_SCROLL:
                    world.create_entity(
                        position,
                        Visual("#", tcod.purple, RenderOrder.ITEM),
                        Name("Confusion Scroll"),
                        Item.CONFUSION_SCROLL,
                    )
                elif item_choice is Slot.MAIN_HAND:
                    world.create_entity(
                        position,
                        Visual("/", tcod.sky, RenderOrder.ITEM),
                        Name("Sword"),
                        Equippable(slot=Slot.MAIN_HAND, power_bonus=3,),
                    )
                elif item_choice is Slot.OFF_HAND:
                    world.create_entity(
                        position,
                        Visual("[", tcod.darker_orange, RenderOrder.ITEM),
                        Name("Shield"),
                        Equippable(slot=Slot.OFF_HAND, defense_bonus=1,),
                    )

def generate_stairs(world: WorldExt) -> None:
    map = world.get_resource(Map)
    last_room = map.rooms[-1]
    world.create_entity(
        Stairs(map.dungeon_level + 1),
        Position(last_room.center),
        Visual(">", tcod.white, RenderOrder.STAIRS),
        Name("Stairs"),
    )

def add_player(world) -> None:
    map = world.get_resource(Map)

    dagger = world.create_entity(
        Visual("-", tcod.sky, RenderOrder.ITEM),
        Name("Dagger"),
        Equippable(slot=Slot.MAIN_HAND, power_bonus=2,),
    )

    world.create_entity(
        map.spawn_position,
        Visual("@", tcod.white, RenderOrder.ACTOR),
        player_ai,
        Player(),
        Name("Player"),
        Collider(),
        Energy(1),
        Fighter.new(hp=100, defense=1, power=2),
        Inventory(26).add(dagger),
        Level(level_up_base=200, level_up_factor=150),
        Equipment({}).toggle_equip(world, dagger),
    )

def generate_level(world: WorldExt, dungeon_level: int = 1) -> None:
    map = random_map(dungeon_level)
    world.add_resource(map)
    world.add_resource(Fov(map))
    generate_monsters(world)
    generate_items(world)
    generate_stairs(world)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"Interval detection: finding flat sections in the signal"
import numpy as np

from  utils        import initdefaults
from  signalfilter import PrecisionAlg, CppPrecisionAlg
from .splitting    import SplitDetector, PyMultiGradeSplitDetector
from .merging      import PyMultiMerger, EventMerger, PyEventSelector
from ._core        import EventDetector as _EventDetector # pylint: disable=import-error

class PyEventDetector(PrecisionAlg):
    """
    Detect, merge and select flat intervals in `PHASE.measure`

    # Attributes

    * `split`: splits the data into too many intervals. This is based on a grade
    computed for each frame indicating the likelihood that an event is finished.
    See `eventdetection.splitting` for the available grades.

    * `merge`: merges the previous intervals when the difference between their
    population is not statistically relevant.

    * `select`: possibly clips events and discards those too small.
    """
    split: SplitDetector = PyMultiGradeSplitDetector()
    merge: EventMerger   = PyMultiMerger()
    select               = PyEventSelector()
    @initdefaults(frozenset(locals()))
    def __init__(self, **kwa):
        super().__init__(**kwa)

    def compute(self, data:np.ndarray, precision: float) -> np.ndarray:
        "computes the intervals"
        return self.select(data, self.merge(data, self.split(data, precision), precision))

    def __call__(self, data:np.ndarray, precision: float = None)-> np.ndarray:
        precision = self.getprecision(precision, data)
        return self.select(data, self.merge(data, self.split(data, precision), precision))

    @classmethod
    def run(cls, *args, **kwa):
        "instantiates and calls class"
        return cls(**kwa)(*args)

class EventDetector(CppPrecisionAlg, _EventDetector, zattributes = ('precision', 'merge')):
    """
    Detect, merge and select flat intervals in `PHASE.measure`

    # Attributes

    * `split`: splits the data into too many intervals. This is based on a grade
    computed for each frame indicating the likelihood that an event is finished.
    See `eventdetection.splitting` for the available grades.

    * `merge`: merges the previous intervals when the difference between their
    population is not statistically relevant.

    * `select`: possibly clips events and discards those too small.
    """
    split: SplitDetector
    merge: EventMerger
    def __init__(self, **kwa):
        CppPrecisionAlg.__init__(self, **kwa)
        _EventDetector.__init__(self, **kwa)

    def __call__(self, data:np.ndarray, precision: float = None):
        return self.compute(data, self.getprecision(precision, data))

    @classmethod
    def run(cls, *args, **kwa):
        "instantiates and calls class"
        return cls(**kwa)(*args)


from django.shortcuts import render

# Create your views here.
# start game fonk

def start_game(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        image = request.FILES.get('image')
        puzzle = generate_puzzle(image)
        request.session['name'] = name
        request.session['puzzle'] = puzzle
        request.session['moves'] = 0
        request.session['start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return redirect('game')
    return render(request, 'game/start_game.html')

# play game fonk

from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Player, Puzzle

def play_game(request):
    if request.method == 'POST':
        player_name = request.POST.get('player_name')
        puzzle_id = request.POST.get('puzzle_id')
        player_score = int(request.POST.get('player_score'))
        player, created = Player.objects.get_or_create(name=player_name)
        if not created:
            player.score += player_score
            player.save()
        puzzle = Puzzle.objects.get(id=puzzle_id)
        puzzle.correct += 1
        if puzzle.correct == puzzle.rows * puzzle.cols:
            puzzle.status = 'solved'
        puzzle.save()
        return JsonResponse({'success': True})
    else:
        puzzles = Puzzle.objects.all()
        context = {'puzzles': puzzles}
        return render(request, 'play_game.html', context)

#

from django.shortcuts import render
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
from PIL import Image
import io

from .models import Player, Score

def home(request):
    if request.method == 'POST':
        # Get player name and uploaded image
        player_name = request.POST.get('player_name')
        uploaded_image = request.FILES.get('image')

        # Save the player
        player = Player(name=player_name)
        player.save()

        # Convert uploaded image to puzzle format
        image = Image.open(uploaded_image)
        cropped_images = []
        width, height = image.size
        cropped_width, cropped_height = width // 4, height // 4
        for i in range(4):
            for j in range(4):
                box = (j * cropped_width, i * cropped_height, (j + 1) * cropped_width, (i + 1) * cropped_height)
                cropped_images.append(image.crop(box))

        # Shuffle cropped images
        import random
        random.shuffle(cropped_images)

        # Save cropped images
        fs = FileSystemStorage()
        image_paths = []
        for i, cropped_image in enumerate(cropped_images):
            file_name = f"{player.id}_{i}.png"
            file_path = fs.save(file_name, io.BytesIO())
            image_paths.append(file_path)

        # Render game page
        context = {
            'player_id': player.id,
            'image_paths': image_paths,
        }
        return render(request, 'game.html', context)
    else:
        return render(request, 'home.html')

def save_score(request):
    if request.method == 'POST':
        # Get player and score
        player_id = request.POST.get('player_id')
        score = request.POST.get('score')

        # Save the score
        player = Player.objects.get(id=player_id)
        score = Score(player=player, score=score)
        score.save()

        return HttpResponse('Score saved!')
    else:
        return HttpResponse('Invalid request!')

#

from django.shortcuts import render, redirect
from .forms import StartGameForm
from .utils import convert_to_puzzle
import time

def start_game(request):
    """
    Starts the puzzle game.
    """
    if request.method == 'POST':
        form = StartGameForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data.get('name')
            image = form.cleaned_data.get('image')
            puzzle = convert_to_puzzle(image)
            if puzzle:
                request.session['name'] = name
                request.session['puzzle'] = puzzle
                request.session['moves'] = 0
                request.session['start_time'] = time.time()
                request.session['game_over'] = False
                request.session.modified = True
                return redirect('game')
    else:
        form = StartGameForm()

    return render(request, 'start_game.html', {'form': form})

from django.shortcuts import render, redirect
from django.http import HttpResponse
from PIL import Image

def play(request):
    if request.method == 'POST':
        name = request.POST['name']
        image = request.FILES['image']

        # Yüklenen görseli yeniden boyutlandırma
        size = (480, 480)
        im = Image.open(image)
        im_resized = im.resize(size)

        # Yeniden boyutlandırılmış görseli geçici bir dosyada kaydetme
        im_resized_path = f'media/images/{name}.jpg'
        im_resized.save(im_resized_path, "JPEG")

        # Puzzle'ı oluşturma
        puzzle = create_puzzle(im_resized_path)

        # Skorları getirme
        scores = Score.objects.all().order_by('-score')[:10]

        context = {
            'name': name,
            'puzzle': puzzle,
            'scores': scores
        }

        return render(request, 'play.html', context)

    else:
        return redirect('home')

#from django.shortcuts import render
from .models import Puzzle

def puzzle(request):
    if request.method == 'POST':
        size = int(request.POST.get('size'))
        if size < 2:
            size = 2
        elif size > 10:
            size = 10
        puzzle = Puzzle(size)
        puzzle.create_solution()
        puzzle.shuffle()
        request.session['puzzle'] = puzzle
    elif request.method == 'GET':
        puzzle = request.session.get('puzzle')
        if not puzzle:
            puzzle = Puzzle(4)
            puzzle.create_solution()
            puzzle.shuffle()
            request.session['puzzle'] = puzzle

    board = puzzle.get_board()
    context = {
        'board': board,
        'size': puzzle.size,
        'moves': puzzle
    }

#

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')


import pytest
from src.kbt.helpers import divide_by_lines, numbers

def test_divide_by_lines_error():
    data = [1, 2, 3, 4, 5, 6, 7, 8]
    with pytest.raises(Exception) as e:
        divide_by_lines(data, None)
    assert "Error trying to divide the data in None" in str(e)

def test_divide_by_lines_error():
    data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    expected = [[1, 2, 3], [5, 6, 7], [9, 10, 11]]
    length = 4
    result = divide_by_lines(data, length)
    assert result is not None
    assert result == expected, "Result has to be like expected"

@pytest.mark.parametrize("test_input,expected",
                         [(" _ | ||_|", 0), ("     |  |", 1), (" _  _||_ ", 2), (" _  _| _|", 3),
                          ("   |_|  |", 4), (" _ |_  _|", 5), (" _ |_ |_|", 6), (" _   |  |", 7),
                          (" _ |_||_|", 8), (" _ |_| _|", 9)])
def test_numbers_invalid(test_input, expected):
    result = numbers[test_input]
    assert result is not None
    assert result == expected, "Result has to be like expected"


import altair as alt
import math
import pandas as pd
import streamlit as st
from PIL import Image

"""
# Which German Business Sector are you?

Take this personality quiz to find out which part of the Volkswirtschaft is your spirit animal.

This uses clustering from the ifo Business Climate Survey taken by thousands of businesses monthly to determine which sector you're responses are most similar to.
Are you the high-tech industry embodied or heavy industry personified? People have chosen careers over less.
"""
#st.set_page_config(page_title='Which Business Sector are you?', page_icon=':heart:')
# QUESTION 1
st.title('How was lunch?')
vg_statebus = st.radio(
"We evaluate our state of business to be",
('Good', 'Satisfiable', 'Bad'))
if vg_statebus == 'Good':
    vg_statebus_index = 1
if vg_statebus == 'Satisfiable':
    vg_statebus_index = 2
    st.text('7/10')
if vg_statebus == 'Bad':
    vg_statebus_index = 3
    st.text('Ooof')

#vg_statebus = give_choice(['Good', 'Satisfiable', 'Bad'])

# QUESTION 2
st.title('How oldschool are you?')
online = st.radio(
    "I would filled out the ifo survey via",
    ("Paper", "Fax", "Online", "Manual collection"))

#assign integers to answers as in ifo survey
if online == 'Paper':
    online_index = 0
if online == 'Fax':
    online_index =  1
    st.text('They said in the Buzzfeed survey')
if online == 'Online' :
    online_index = 2
    st.text('THANK YOU; FINALLY A NORMAL PERSON')
if online == 'Manual collection':
    online_index = 5
    st.text('Fighting unemployment one special request at a time')

# QUESTION 3
st.title('U scared yet?')
vg_comexp = st.radio(
"During the next 6 months our business operation will be",
('Favourable', 'Not changing', 'Unfavourable'))
#assign integers to answers as in ifo survey
if vg_comexp == 'Favourable':
    vg_comexp_index = 1
if vg_comexp == 'Not changing':
    vg_comexp_index = 2
    st.text('Dream on')
if vg_comexp == 'Unfavourable':
    vg_comexp_index = 3
    st.text('You betcha')

# QUESTION 4
st.title('When did you first become important enough that ifo would care about you?')
age = st.radio(
"",
('Before 1980', 'Before 2000', 'After 2000'))
if age == 'Before 1980':
    age_index=0
if age == 'Before 2000':
    age_index=1
    st.text('TikTok is werid, right?')
if age == 'After 2000':
    image = Image.open('images/lindner.webp')
    st.image(image, width = 300)
    age_index=2

# QUESTION 5
st.title('How greedy are you?')
vg_price = st.radio(
"Our prices in the next 3 months will expectedly be",
('Rising', 'Not changing', 'Falling'))
if vg_price == 'Rising':
    vg_price_index = 1
if vg_price == 'Not changing':
    vg_price_index = 2
    st.text('In this economy?')
if vg_price == 'Falling':
    vg_price_index = 3
    st.text('The unwashed masses thank you')

# QUESTION 6
st.title('Are you hot or not?')
vg_demand_vpq = st.radio(
"In the last 3 months the demand situation has been",
('Rising', 'Not changing', 'Falling'))
if vg_demand_vpq == 'Rising':
    vg_price_index = 1
if vg_demand_vpq == 'Not changing':
    vg_price_index = 2
    st.text('You got it guuurl!')
if vg_demand_vpq == 'Falling':
    vg_price_index = 3
    st.text('We will always love you.')

# QUESTION 7
st.title('Labour exploitation attitudes')
vg_demand_vpq = st.radio(
"The number of your employees will be",
('Increasing', 'Not changing', 'Decreasing'))
if vg_demand_vpq == 'Increasing':
    vg_price_index = 1
if vg_demand_vpq == 'Not changing':
    st.text('Coward.')
    vg_price_index = 2
if vg_demand_vpq == 'Decreasing':
    vg_price_index = 3
    st.text('Our condolences.')

data = pd.read_csv("average_answers_by_sector.csv",engine='python')

# Form responses as in the same format as the ifo survey
our_responses = {'vg_statebus': vg_statebus_index,
                'vg_comexp': vg_comexp_index,
                'vg_priceexp': vg_price_index,
                'is_fax': online_index == 1, # Should be 1 if the respondent answered by fax
                'is_online': online_index == 2, # Should be 1 if the respondent answered online
                'is_neither_online_fax': online_index != 1 and online_index != 2, # Otherwise
                'vg_demand_vpq':vg_price_index,
                'vg_emplexp': 1,
                'year_binned': age_index # AKA age_index 0 if before 1980, 1 if before 2000, 2 otherwise
               }

# This gets the row with the smallest L1 distance to our_responses in the dataframe.
# It output is min_distance_sector wz93 sector code

data['sector'] = data['sector'].replace('0.', '0')
data['sector'] = data['sector'].replace('na', '0')
data['sector'] = data['sector'].astype(int)

#create sector names and assigning them to the variable
sector_names = {
    0: "no sector",
    15: "Food and Drinks",
    16: 'Tobacco',
    17: 'Textiles',
    18: 'Clothing',
    19: 'Leather Goods',
    20: 'Wooden Stuff',
    21: 'Paper Stuff',
    22: 'Media',
    23: 'Energy',
    24: 'Chemicals',
    25: 'Rubber and Plastic Stuff',
    26: 'Other Non Metallic Stuff',
    27: 'Basic Metals',
    28: 'Some Metal Products',
    29: 'Machinery and equipment',
    30: 'Office and Computer',
    31: 'Electrical Machinery',
    32: 'Communication Equipment',
    33: 'Precision Instruments',
    34: 'Motor Vehicles',
    35: 'Other Transport',
    36: 'Furniture',
}

data['sector_name'] = data['sector'].map(sector_names)

min_distance_sector = None
min_distance = 1000
for index, row in data.iterrows():
    distance = 0
    for key, value in our_responses.items():
        distance += abs(value - row[key])
    if distance < min_distance and row['sector'] != 0:
        min_distance = distance
        min_distance_sector = row['sector']

show_checkbox = st.checkbox('Show result')

if show_checkbox:
    st.title("Sector number " + str(min_distance_sector) + ": " + sector_names[min_distance_sector])
    if min_distance_sector == 15:
        im_path = '1.jpeg'
    elif min_distance_sector == 16:
        im_path = 'pipe.jpeg'
    elif min_distance_sector == 17:
        im_path = 'clothes.jpeg'
    elif min_distance_sector == 18:
        im_path = 'clothes.jpeg'
    elif min_distance_sector == 19:
        im_path = 'leather.jpeg'
    elif min_distance_sector == 21:
        im_path = 'forest.jpeg'
    elif min_distance_sector == 22:
        im_path = 'propaganda.jpeg'
    elif min_distance_sector == 23:
        im_path = 'nukes.jpeg'
    elif min_distance_sector == 24:
        im_path = 'oil.jpeg'
    elif min_distance_sector == 25:
        im_path = 'oil.jpeg'
    elif min_distance_sector == 26:
        im_path = 'mine.jpeg'
    elif min_distance_sector == 28:
        im_path = 'machines.jpeg'
    elif min_distance_sector == 29:
        im_path = 'machines.jpeg'
    elif min_distance_sector == 30:
        im_path = 'nerd.jpeg'
    elif min_distance_sector == 31:
        im_path = 'satelite.jpeg'
    elif min_distance_sector == 32:
        im_path = 'satelite.jpeg'
    elif min_distance_sector == 33:
        im_path = 'machines.jpeg'
    elif min_distance_sector == 34:
        im_path = 'transrapid.jpeg'
    elif min_distance_sector == 35:
        im_path = 'transrapid.jpeg'
    elif min_distance_sector == 36:
        im_path = 'furniture.jpeg'
    else:
        im_path=''
    if len(im_path) > 0:
        image = Image.open("images/"+im_path)
        st.image(image, width = 600)


# -*- coding: UTF-8 -*-
import json
from xf import text_tovoice
from xf import voice_totext
from xf import text_tovoice_totext
import time

def test1():
    print("---start---")
    start = time.time()
    voiceResultStr = text_tovoice.init('百度传来了喜讯',
                                      "E:/jianguocloud/learn/Python/pythonTest/pythonUtils/datas/chat/output.mp3")
    print(voiceResultStr)
    voiceResultJson = json.loads(voiceResultStr)
    code = voiceResultJson['code']
    if code == "0":
        print("文字转音频成功")
    else:
        print("文字转音频失败：" + voiceResultStr)
    textResultStr = voice_totext.init("E:/jianguocloud/learn/Python/pythonTest/pythonUtils/datas/chat/output.mp3")
    textResultJson = json.loads(textResultStr)
    code = textResultJson['code']
    if code == "0":
        print("音频转文字成功" + textResultStr)
    else:
        print("音频转文字失败：" + textResultStr)
    end = time.time()
    print(end - start)
    print("---end---")

def test2():
    start = time.time()
    text_tovoice_totext.change("摆渡船来")
    end = time.time()
    print(end - start)

if __name__ == '__main__':
    test2()


# -*- coding: utf-8 -*-
"""
Created on Wed Jan  5 21:46:21 2022

@author: Cumali Atalan
"""

#%%

#gerekli kütüphaneler import edilir.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from tensorflow import keras
from keras.models import Sequential,load_model
from keras.layers import Dense,GlobalAveragePooling2D,Flatten,Conv2D,BatchNormalization,Dropout,MaxPooling2D,Activation
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator as Imgen

from PIL import Image
from sklearn.metrics import confusion_matrix,classification_report

import os

import warnings
warnings.filterwarnings("ignore")

#%%

#verilerin adresi verilir.
train_csv = pd.read_csv("C:\\Users\\tr\\Desktop\\input\\plant-pathology-2021-fgvc8\\train.csv")
train_path = "C:\\Users\\tr\\Desktop\\input\\plant-pathology-2021-fgvc8\\train_images"
test_path = "C:\\Users\\tr\\Desktop\\input\\plant-pathology-2021-fgvc8\\test_images"

#%%
#veriler hakkında bilgi alınır.
train_csv.head(3)
train_csv.info()

#%%

#verilerin içerisinde hangi etikette kaç veri olduğu konsola yazdırılır.
etiketler = train_csv["labels"].value_counts().index
veri = train_csv["labels"].value_counts().values

print(veri)
#%%
# veriler etiketlerine göre pasta grafiğinde gösterilir.

"""
explode = (0, 0.1, 0, 0,0,0,0,0,0,0,0,0)
pie, ax = plt.subplots(figsize=[10,6])
plt.pie(x=data, autopct="%.1f%%",explode=explode, labels=labels, pctdistance=0.5)
plt.title("Delivery Tips by type", fontsize=14);
pie.savefig("DeliveryPieChart.png")
"""

#%%
#her etiket bir class olarak ayrılır.
class_numarasi = len(train_csv["labels"].value_counts())

#%%

# verilerin ön işlemesi yapılır.
# xception'a göre ağırlıklar önceden verilir.
datagen = Imgen(preprocessing_function=keras.applications.xception.preprocess_input,
                 rotation_range=4,
                  shear_range=0.2,
                  zoom_range=0.15,
                  horizontal_flip=True,
                  validation_split=0.2
                 )

#%%
# datagende işlenen verilerin öğrenimi için gerekli veriler verilir.
train_ds = datagen.flow_from_dataframe(
    train_csv,
    directory = train_path, #nereden alacak veriyi
    x_col = 'image',
    y_col = 'labels',
    subset="training",
    color_mode="rgb",
    target_size = (224,224),
    class_mode="categorical",
    batch_size=32,
    shuffle=True,
    seed=123
)
#%%
# datagende işlenen verilerin doğrulaması için gerekli veriler verilir.
val_ds = datagen.flow_from_dataframe(
    train_csv,
    directory = train_path,
    x_col = 'image',
    y_col = 'labels',
    subset="validation",
    color_mode="rgb",
    target_size = (224,224),
    class_mode="categorical",
    batch_size=32,
    shuffle=True,
    seed=123
)

#%%
# np dizileri oluşturulur.
x,y = next(train_ds)
x.shape
#%%
from tensorflow.keras.applications.vgg16 import VGG16

# model olarak VGG16 kullanıyorum.
vgg = VGG16()
#%%
model = Sequential()
vgg_layers = vgg.layers # vgg modelinde katmanları tanımlıyorum.

for i in range(len(vgg_layers)-1):
    model.add(vgg_layers[i])
    #katmanlar modele ekleniyor.
#%%
model.build(x.shape)
model.summary()
#%%

#katman özellikleri aktif ediliyor.

for l in vgg_layers:
    l.trainable = True

#%%

# aktivasyonu softmax olan dense katmanları ekleniyor.

model.add(Dense(class_numarasi, activation="softmax"))
model.summary()
#%%

# model tamamlanırken accuracy'e göre ölçüm yapması bekleniyor.

model.compile(loss = "categorical_crossentropy" , optimizer = "adam" , metrics=["accuracy"])
batch_size = 32

# epoch sayısı verilir. ve her epochta kaç veri işleneceği belirtilir.
# 14900 görseli batch_size bölüp hep epochta öğrenimi işlenecek veri sayısı belirtilir.
# 3700 görseli batch_size bölüp hep epochta doğrulaması işlenecek veri sayısı belirtilir.

#öğrenme başlatılır.
hist = model.fit_generator(train_ds,
                           steps_per_epoch = 14900//batch_size,
                           epochs = 15,
                           validation_data = val_ds,
                           validation_steps = 3700//batch_size)

#%%

#öğrenme ve doğrulama oranları tablolaştırılır.
plt.plot(hist.history["accuracy"],label = "training accuracy")
plt.plot(hist.history["val_accuracy"],label = "validation accuracy")


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_transformers.modeling_bert import BertPooler, BertSelfAttention, BertConfig

from layers.attention import Attention, NoQueryAttention
from layers.squeeze_embedding import SqueezeEmbedding

class GNN(nn.Module):
    def __init__(self, input_dim, hidden_dim, step=2, drop=0.0):
        super(GNN, self).__init__()
        self.step = step
        self.drop = drop
        self.W1 = nn.Parameter(torch.Tensor(input_dim, hidden_dim))
        if input_dim == hidden_dim:
            self.W2 = self.W1
        else:
            self.W2 = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
        self.b1 = nn.Parameter(torch.Tensor(hidden_dim))
        if input_dim == hidden_dim:
            self.b2 = nn.Parameter(torch.Tensor(hidden_dim))
        else:
            self.b2 = self.b1

    def forward(self, X, A):
        """B L H, B L L -> B H L"""
        for i in range(self.step):
            if i == 0:
                X = torch.matmul(X, self.W1)
            else:
                X = torch.matmul(X, self.W2)
            normed_A = A / A.sum(1, keepdim=True)[0]
            X = torch.matmul(A, X)
            if i == 0:
                X = X + self.b1
            else:
                X = X + self.b2
            if i < self.step - 1:
                X = F.relu(X)
                if self.drop > 0:
                    X = F.dropout(X)
        return X

class GNN_RELU(nn.Module):
    def __init__(self, input_dim, hidden_dim, step=2, drop=0.0):
        super(GNN_RELU, self).__init__()
        self.step = step
        self.drop = drop
        self.W1 = nn.Parameter(torch.Tensor(input_dim, hidden_dim))
        if input_dim == hidden_dim:
            self.W2 = self.W1
        else:
            self.W2 = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
        self.b1 = nn.Parameter(torch.Tensor(hidden_dim))
        if input_dim == hidden_dim:
            self.b2 = nn.Parameter(torch.Tensor(hidden_dim))
        else:
            self.b2 = self.b1

    def forward(self, X, A):
        """B L H, B L L -> B H L"""
        normed_A = A / (A.sum(1, keepdim=True)[0])
        for i in range(self.step):
            if i == 0:
                X = torch.matmul(X, self.W1)
            else:
                X = torch.matmul(X, self.W2)

            X = torch.matmul(normed_A, X)
            if i == 0:
                X = X + self.b1
            else:
                X = X + self.b2
            X = F.relu(X)
            if self.drop > 0:
                X = F.dropout(X)
        return X

class GNN_RELU_DIFF(nn.Module):
    def __init__(self, input_dim, hidden_dim, step=2, drop=0.0):
        super(GNN_RELU_DIFF, self).__init__()
        self.step = step
        self.drop = drop
        self.Ws = nn.ParameterList(
            [nn.Parameter(torch.Tensor(input_dim, hidden_dim))])
        self.bs = nn.ParameterList([nn.Parameter(torch.Tensor(hidden_dim))])
        for i in range(1, step):
            self.Ws.append(nn.Parameter(torch.Tensor(hidden_dim, hidden_dim)))
            self.bs.append(nn.Parameter(torch.Tensor(hidden_dim)))

    def forward(self, X, A):
        """B L H, B L L -> B H L"""
        normed_A = A / (A.sum(1, keepdim=True)[0])
        for i in range(self.step):
            X = torch.matmul(X, self.Ws[i])
            X = torch.matmul(normed_A, X)
            X = X + self.bs[i]
            X = F.relu(X)
            if self.drop > 0:
                X = F.dropout(X)
        return X

class SelfAttention(nn.Module):
    def __init__(self, config, opt):
        super(SelfAttention, self).__init__()
        self.opt = opt
        self.config = config
        self.SA = BertSelfAttention(config)
        self.tanh = torch.nn.Tanh()

    def forward(self, inputs):
        # zero_tensor = torch.tensor(np.zeros((inputs.size(0), 1, 1, self.opt.max_seq_len),
        #                                     dtype=np.float32), dtype=torch.float32).to(self.opt.device)
        zero_tensor = 0
        SA_out = self.SA(inputs, zero_tensor)
        return self.tanh(SA_out[0])

class LayerNorm(nn.Module):
    "Construct a layernorm module (See citation for details)."

    def __init__(self, features, eps=1e-6):
        super(LayerNorm, self).__init__()
        self.a_2 = nn.Parameter(torch.ones(features))
        self.b_2 = nn.Parameter(torch.zeros(features))
        self.eps = eps

    def forward(self, x):
        mean = x.mean(-1, keepdim=True)
        std = x.std(-1, keepdim=True)
        return self.a_2 * (x - mean) / (std + self.eps) + self.b_2

class BERT_ALBERT_GCN(nn.Module):
    """
    bert:做encoder 输入：context_asp_ids, context_asp_seg_ids, context_asp_att_mask, adj_matrix, start, end, polarity
    glove+bom做encoder 输入同上 init 时需要embedding_matrix_pkl(conf.tokenizer_pkl),需要embedding层
    除encoder层外一样，能够控制是否加入 pos+pct gnn+pct short_cut
                    /-------short cut +-------\  /---no sa---\
    squeeze -> bert -> norm + gcn -> pct + gelu -> sa + tanh -> bert_pooler -> fc -> logits
    """

    def __init__(self, bert_or_embedding_matrix, opt):
        super(BERT_ALBERT_GCN, self).__init__()
        self.opt = opt
        bert = bert_or_embedding_matrix
        self.context_bert = bert
        self.squeeze_embedding = SqueezeEmbedding()
        if not opt.no_gnn:
            self.gcn = GNN_RELU_DIFF(opt.bert_dim, opt.bert_dim,
                                     step=opt.gnn_step, drop=0.0)
            self.encoder_fn = nn.Linear(opt.bert_dim, opt.bert_dim)
            self.norm = LayerNorm(opt.bert_dim)
        if not opt.no_sa:
            self.bert_self_att = SelfAttention(bert.config, opt)
        if self.opt.pool_tp == 'bert_pool':
            self.bert_pooler = BertPooler(bert.config)
        elif self.opt.pool_tp == 'max_pool':
            self.pool_fc = nn.Linear(opt.bert_dim, opt.bert_dim)
        self.fc = nn.Linear(opt.bert_dim, 3)

    def forward(self, inputs):
        # 解开inputs:context=text+asp
        context, context_seg = inputs[0], inputs[1]
        asp_start, asp_end, adj_matrixs = inputs[2], inputs[3], inputs[4]
        attention_mask = inputs[5]
        for e in inputs:
            assert not torch.isnan(e).any()
        # 获得context_len ,并进行squeezeEmbedding
        context_len = torch.sum(context != 0, dim=-1).long()
        context = self.squeeze_embedding(context, context_len)
        context_ids = context
        context_seg = self.squeeze_embedding(context_seg, context_len)
        attention_mask = self.squeeze_embedding(attention_mask, context_len)
        # context 进行 bert/glove encode
        context, _ = self.context_bert(
            context, context_seg, attention_mask)

        if not self.opt.no_gnn:
            batch_size, seq_len = context.size()[:-1]
            # +short_cut(
            highway = context
            context = self.norm(context)

            # +gnn【cls sep连所有，context按照语法树连成无向图，asp连所有】
            A = adj_matrixs[:, :seq_len, :seq_len]
            context = self.gcn(context, A)

            # + pct + gelu
            context = self.encoder_fn(context)
            context = F.gelu(context)

            # +short_cut)
            if not self.opt.no_short_cut:
                context += highway

        # + sa
        if not self.opt.no_sa:
            rep = self.bert_self_att(context)
        else:
            rep = context
        # + bert_pooler
        if self.opt.pool_tp == 'bert_pool':
            rep = self.bert_pooler(rep)
        elif self.opt.pool_tp == 'max_pool':
            # B L
            mask = torch.zeros(rep.size()[:-1]).to(self.opt.device)
            for i, (seq, s, e, true_len) in enumerate(zip(context_ids, asp_start, asp_end, context_len)):
                seq = seq.tolist()
                first_sep_idx = seq.index(102)
                mask[i, 0] = 1
                mask[i, s:e] = 1
                mask[i, first_sep_idx + 1:true_len] = 1
            rep = rep * mask.unsqueeze(-1)  # B L H * B L 1-->B L H
            rep = rep.max(1)[0]  # B H
            rep = self.pool_fc(rep)
            rep = F.tanh(rep)
        # fc
        out = self.fc(rep)
        return out


import typing as t

"""
Tags: Adjacency matrix

The algorithm finds all shortest path pairs. The graph needs to be represented
as an adjacency matrix.

Example graph definition:

    A   B   C   D

A   0   8  INF  1

B  INF  0   1  INF

C   4  INF  0  INF

D  INF  2   9   0

The diagonal ^ is 0s because the node's distance to itself if 0.

INF - means from this vertex you cannot directly reach the other one

Complexities:
T: O(V ^ 3)
S: O(V ^ 2)
"""

Graph = list[list[t.Any]]
INF = float("inf")

def print_adjacent_matrix(nb_vertices: int, graph: Graph) -> None:
    for i in range(nb_vertices):
        print()
        for j in range(nb_vertices):
            if graph[i][j] == INF:
                print("INF", end=" ")
            else:
                print(graph[i][j], end=" ")

def perform_floyd_warshall(nb_vertices: int, graph: Graph) -> Graph:
    distances = graph
    # Take all vertices one by one as a source V. Iterating over rows, each
    # row represents connections from the current vertex
    for i in range(nb_vertices):
        # Iterate over all cells in the matrix
        for row in range(nb_vertices):
            for col in range(nb_vertices):
                # If direct distance is greater than through another node,
                # pick the one going through another node
                # distances[row][col] = min(
                #     distances[row][col], distances[row][i] + distances[i][col]
                # )

                # OR
                curr_dist = distances[row][col]
                new_dist = distances[row][i] + distances[i][col]
                if new_dist < curr_dist:
                    distances[row][col] = new_dist

    return distances

def main():
    graph = [
        [0, 8, INF, 1],
        [INF, 0, 1, INF],
        [4, INF, 0, INF],
        [INF, 2, 9, 0]
    ]
    nb_vertices = 4
    distances = perform_floyd_warshall(nb_vertices, graph)
    print_adjacent_matrix(nb_vertices, distances)

if __name__ == '__main__':
    main()


import random
from math import sqrt
from scipy.interpolate import lagrange

from main_folder.smpc_addition.network_nodes.RandPoly import RandPoly

class SmpcAdditionNode:
    def __init__(self) -> None:
        pass

    def generate_functions(self, record):
        all_functions = []
        for feature in record:
            func = RandPoly(
                n=2,
                R=[
                    (i, x)
                    for i, x in enumerate(
                        list(
                            [
                                feature,
                                random.randint(2, 250),
                                random.randint(2, 250),
                            ]
                        )
                    )
                ],
            ).poly
            all_functions.append(func)
        return all_functions

    def generate_shares(self, func_array, x_points):
        shares = []
        for f in func_array:
            x_point_shares = []
            for x in x_points:
                x_point_shares.append(f(x))
            shares.append(x_point_shares)
        return shares

    def get_random_points(self, num_points, rand_seed, max_x):
        points = random.Random(rand_seed).sample(range(1, max_x), num_points)
        return points

    def calc_share_sums_one_record(self, f_shares, g_shares, h_shares):
        s_x_points = []
        for x_point in range(len(f_shares)):
            s_x = []
            for i, j, k in zip(f_shares[x_point], g_shares[x_point], h_shares[x_point]):
                sum = i+j+k
                s_x.append(sum)
            s_x_points.append(s_x)
        return s_x_points

    def get_set_of_lagrange_values_one_record(self, s_shares_client, s_shares_server):
        lagrange_set_one_record = []
        for feature in range(len(s_shares_client[0])):
            s_x_feature = [s_shares_client[0][feature]]
            for i in range(len(s_shares_server[0])):
                s_x_feature.append(s_shares_server[feature][i])
            lagrange_set_one_record.append(s_x_feature)
        return lagrange_set_one_record

    def reconstruct(self, shares, x_points):
        f = lagrange(x_points, shares)
        return f

    def distance_to_one_point(self, lagrange_set_one_record, x_points):
        # client interpolation
        s_n_functions = [self.reconstruct(shares, x_points) for shares in lagrange_set_one_record]
        all_s0_vals = [f(0) for f in s_n_functions]

        # calc distance
        distance = 0
        for i in all_s0_vals:
            distance += i**2
        distance = sqrt(distance)

        return distance


import cv2 as cv
import sys

#loads the using weights and correspding configuration rule
def load_model(model_weights="",model_config=""):

	if model_weights == "" and model_config == "":
		print("Model config and weights not found!");
		sys.exit(0);

	net = cv.dnn.readNet(model_weights,model_config);
	return net;

def get_output_layers(net):
    layer_names = net.getLayerNames();
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()];
    return output_layers;


import logging

from odoo import api, models, _
from odoo.tools import ormcache
from odoo.tools.config import config, to_list

_logger = logging.getLogger(__name__)

WEB_BASE_URL_FREEZE = 'web.base.url.freeze'

class IrConfigParameter(models.Model):
    _inherit = 'ir.config_parameter'

    @api.model
    @ormcache()
    def _get_db_url_freeze_allowedlist(self):
        res = []
        allowedlist = config.get("db_url_freeze_allowedlist")
        if allowedlist:
            res = to_list(allowedlist)
        return res

    @api.model
    def get_param(self, key, default=False):
        value = super().get_param(key, default=default)
        if key == WEB_BASE_URL_FREEZE and value and \
            self.env.cr.dbname not in self._get_db_url_freeze_allowedlist():
            _logger.info('%s forced to False', WEB_BASE_URL_FREEZE)
            value = False
        return value