"""Data module for the Punjabi languages alphabet and related characters."""

__author__ = 'Nimit Bhardwaj <nimitbhardwaj@gmail.com>'
__license__ = 'MIT License. See LICENSE.'
__credits__ = 'Talha Javed Mukhtar <tjaved.bscs15seecs@seecs.edu.pk'

#The Functions Needed for making the data of alphabets is here

#The Digits are given under, the given list starts from 0 to 9, that is
#the index of the list tell the digit in punjabi
DIGITS_GURUMUKHI = ['੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', '੯']
DIGITS_SHAHMUKHI = ['۰', '۱', '۲', '۳', '٤', '۵', '٦', '۷', '۸', '۹']

#Below are the independent vowels of the punjabi language in gurumukhi script.
#They give the sound aaa, e, ee, u, uuu, ea, eaa, o, ou
#These vowels are the base of the dependent vowels
INDEPENDENT_VOWELS_GURUMUKHI = ['ਆ', 'ਇ', 'ਈ', 'ਉ', 'ਊ', 'ਏ', 'ਐ', 'ਓ', 'ਔ']
#There are four independent vowels in the shahmukhi script, which can also be joined with consonants
INDEPENDENT_VOWELS_SHAHMUKHI = ['ا', 'و', 'ی', 'ے']

#The given are the dependent vowels, these are added after or on the consonants
DEPENDENT_VOWELS_GURUMUKHI = ['ਾ', 'ਿ', 'ੀ', 'ੁ', 'ੂ', 'ੇ', 'ੈ', 'ੋ', 'ੌ']
#In the shahmukhi script, the following dependent vowels perform the action of diacritics
DEPENDENT_VOWELS_SHAHMUKHI = ['َ', 'ِ', 'ُ']

#Below are the consonants of the punjabi language in gurumukhi script.
#except first 3 consonants in first row, all other are used in normal writting
CONSONANTS_GURUMUKHI = ['ੳ', 'ਅ', 'ੲ', 'ਸ', 'ਹ',\
              			'ਕ', 'ਖ', 'ਗ', 'ਘ', 'ਙ',\
              			'ਚ', 'ਛ', 'ਜ', 'ਝ', 'ਞ',\
		              	'ਟ', 'ਠ', 'ਡ', 'ਢ', 'ਣ',\
		              	'ਤ', 'ਥ', 'ਦ', 'ਧ', 'ਨ',\
		              	'ਪ', 'ਫ', 'ਬ', 'ਭ', 'ਮ',\
		              	'ਯ', 'ਰ', 'ਲ', 'ਵ', 'ੜ']
#The following are the consonants in shahmukhi script
CONSONANTS_SHAHMUKHI = ['ء', 'ب', 'پ', 'ت', 'ٹ',\
						'ث', 'ج', 'چ', 'ح', 'خ',\
						'د', 'ڈ', 'ذ', 'ر', 'ڑ',\
					    'ز', 'ژ', 'س', 'ش', 'ص',\
						'ض', 'ط', 'ظ', 'ع', 'غ',\
						'ف', 'ق', 'ک', 'گ', 'ل',\
						'م', 'ن', 'ه', 'ھ']

#In gurumukhi script, only a dot is added to some of the consonants, this dot is
#known as the bindi in hindi or punjabi, they change the sound of the
#consonant like , ਜ is for 'j' sound, while ਜ਼ is for 'z' sound
BINDI_CONSONANTS_GURUMUKHI = ['ਖ਼', 'ਗ਼', 'ਜ਼', 'ਫ਼', 'ਲ਼', 'ਸ਼']

#Here are some other symbols that are used in punjabi

OTHER_SYMBOLS_GURUMUKHI = ['ੱ', 'ਂ', 'ਃ', 'ੰ', 'ੑ', 'ੴ', 'ਁ']
#Now here is the explanation of these symbols, symbol at index 0 is addak, it halfens the
#sound, at 2 is bindi on the alphabet, it gives a nasal sound, then symbol at
#index 4 gives a ha sound, then at index 4 is tippi does almost same function as bindi above
#, then is halant cuts the natural vowel sound, then is Ek Omkar, meaning God is One.

OTHER_SYMBOLS_SHAHMUKHI = ['ﺁ', 'ۀ', 'ﻻ']

#Here is a note that all the alphabets can be made by adding the consonant with the dependent vowel sound or with some other symbols


num=600851475143
minor=2 #menor fator
for i in range(0,num):
    if minor >= num: #o menor fator nao pode ser maior que o maior fator
        break
    elif num % minor == 0: # checar se é divisivel por i
        num = num / minor
    else:
        minor= minor + 1
print ("O maior fator primo é: ", str(num))


from tkinter import *
from com import *

class UI(Tk):

	def __init__(self, ports):
		Tk.__init__(self)
		self.geometry("1400x850")
		self.resizable(0,0)
		self.title('Contrôle ECG')
		self.ecgC = None
		self.ecg = None
		self.vfc = None
		self.var = StringVar()
		self.var.trace('w', self.UIChangePort)
		self.drop = OptionMenu(self, self.var, ports)
		self.drop.place(x=20,y=20)

		self.etat = Label(self, text="Déconnecté", font=("Segoe UI", 15))
		self.etat.place(x=120, y=16)

		Label(self, text="Console", font=("Segoe UI", 13)).place(x=1100, y=20)

		self.console = Text(width=40,height=48, bd=0, font=("Consolas", 10))
		self.console.bind("<Key>", lambda e: "break")
		self.console.place(x=1100, y=50)

		self.e = Entry(self, bd=0, font=("Consolas", 10), width=40, state=DISABLED)
		self.e.place(x=1100, y=780)

		self.e.bind("<Return>", self.UICommand)

		self.debug = IntVar()
		self.c = Checkbutton(self, text='Débug', variable=self.debug, borderwidth=1)
		self.c.place(x=1100, y=800)

		self.sound = IntVar()
		self.c2 = Checkbutton(self, text='Sound', variable=self.sound, borderwidth=1)
		self.c2.place(x=1300, y=800)

	def connected(self):
		self.e.config(state='normal')

		self.delayT = Label(self, text="Délai (ms)", font=("Segoe UI", 12))
		self.delayT.place(x=50, y=300)

		self.delay = Label(self, text="0", font=("Segoe UI", 12))
		self.delay.place(x=130, y=300)

		self.BPM = Label(self, text='??', font=("Segoe UI", 20))
		self.BPM.place(x=1000, y=300)

		self.ecgC = Canvas(self, width=1000, height=200, bg="light green")
		self.ecgC.place(x=50, y=100)

		self.btn1 = Button(self, width=20, text='ECG', command=lambda:com.sendECG(self))
		self.btn1.place(x=325, y=380)

		self.btn2 = Button(self, width=20, text='VFC', command=lambda:com.sendVFC(self))
		self.btn2.place(x=625, y=380)

	def UICommand(self, event):
		command = self.e.get()
		self.e.delete(0, END)
		send(self, command)

	def log(self, text, dir):
		self.console.tag_config('ECG', foreground='red')
		self.console.tag_config('PC', foreground='blue')
		self.console.tag_config('INFO', background='pink', foreground='white')
		self.console.see('end')
		if (dir == 'ECG' or dir == 'INFO'):
			self.console.insert(END, text + '\n', dir)
		else:
			self.console.insert(END, text, dir)

	def changeState(self, text):
		self.etat.config(text=text)

	def UIChangePort(self, *args):
		port = self.var.get()
		setPort(self, port)

	def createLine(self, x1, y1, x2, y2):
		return self.ecgC.create_line(x1, y1, x2, y2, fill="white", width=2)

	def createLineVFC(self, x1, y1, x2, y2):
		return self.vfcC.create_line(x1, y1, x2, y2, fill="white")

	def dispTime(self, delay):
		self.delay.config(text=delay)

	def dispBPM(self, BPM):
		self.BPM.config(text=BPM)

	def ecgSpread(self, ecg = None):
		if (ecg == None):
			return self.ecg
		else:
			self.ecg = ecg

	def startVFC(self, vfc):
		self.vfcC = Canvas(self, width=1000, height=200, bg="light blue")
		self.vfcC.place(x=50, y=500)
		self.vfc = vfc

	def vfcSpread(self):
		return self.vfc

	def resultVFC(self, result):
		self.result = Label(self, text=result, font=("Segoe UI", 20))
		self.result.place(x=500, y=750)


from twisted.internet.defer import inlineCallbacks

from conductor_device.conductor_parameter import ConductorParameter

class WmFrequency(ConductorParameter):
    priority = 1
    center_frequency = 368.55468e12
    frequency_span = 200e6

    @inlineCallbacks
    def initialize(self):
        yield self.connect()

    @inlineCallbacks
    def update(self):
        response = yield self.cxn.yesr8_hfwm.get_frequency(1)
        if response is None:
            return

        frequency = float(response['Hz'])
        self.value = frequency

        min_frequency = self.center_frequency - self.frequency_span / 2
        max_frequency = self.center_frequency + self.frequency_span / 2
        if frequency != sorted([min_frequency, frequency, max_frequency])[1]:
            yield self.cxn.beeper.beep('m2 verdi mode hop')


from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from builtins import *  # NOQA
from future.utils import itervalues, iteritems, iterkeys  # NOQA

import pytest
import selfactualize as sa

# test DAG
@pytest.fixture
def dag_1():
    op_1 = sa.wrap_function(lambda x, y=7: x + y, 'x, y? => z', 'op_1')
    op_2 = sa.wrap_function(lambda x: 3 * x, 'x => z', 'op_2')
    dag_1 = (
        sa.DAG(
            name='dag_1', input_names=['x', 'm'], input_required=[True, False],
            output_names=['z'])
        .add_op(op_1)
        .add_op(op_2)
        .add_flow('x', 'op_1.x')
        .add_flow('m', 'op_1.y')
        .add_flow('op_1.z', 'op_2.x')
        .add_flow('op_2.z', 'z')
    )
    return dag_1

@pytest.fixture
def dag_2():
    op_1 = sa.wrap_function(lambda x: (x, x + 1), 'x => y, z', 'op_1')
    op_2 = sa.wrap_function(lambda x: x, 'x => z', 'op_2')
    op_3 = sa.wrap_function(lambda x: x, 'x => z', 'op_3')
    op_4 = sa.wrap_function(lambda a, b: (a, b), 'a, b => x, y', 'op_4')
    op_5 = sa.wrap_function(lambda x: x, 'x => z', 'op_5')
    dag_2 = (
        sa.DAG(
            name='dag_2', input_names=['x'], input_required=[True],
            output_names=['y', 'z'])
        .add_op(op_4)
        .add_op(op_3)
        .add_op(op_2)
        .add_op(op_5)
        .add_op(op_1)
        .add_flow('x', 'op_1.x')
        .add_flow('op_1.y', 'op_2.x')
        .add_flow('op_1.z', 'op_3.x')
        .add_flow('op_2.z', 'op_4.a')
        .add_flow('op_3.z', 'op_4.b')
        .add_flow('op_4.x', 'op_5.x')
        .add_flow('op_4.y', 'y')
        .add_flow('op_5.z', 'z')
    )
    return dag_2

class TestDAG(object):

    def test_execution_order(self, dag_1, dag_2):
        dag_1.run({'x': 10})
        assert dag_1.execution_order == ['op_1', 'op_2']
        dag_2.run({'x': 10})
        assert (
            dag_2.execution_order == ['op_1', 'op_2', 'op_3', 'op_4', 'op_5'] or
            dag_2.execution_order == ['op_1', 'op_3', 'op_2', 'op_4', 'op_5']
        )

    def test_run(self, dag_1, dag_2):
        assert dag_1.run({'x': 3}) == {'z': 30}
        assert dag_1.run({'x': 1, 'm': 1}) == {'z': 6}
        assert dag_2.run({'x': 10}) == {'y': 11, 'z': 10}


import matplotlib.pyplot as plt
import numpy as np
import pickle
import json
from pylab import plot, show, savefig, xlim, figure, ylim, legend, boxplot, setp, axes
from i3Deep import utils
import pandas as pd
import os
import seaborn as sns

def plot_dice_box_plots():
    for i, task in enumerate(tasks):
        fig = plt.figure(constrained_layout=True, figsize=(figsizes[i][0], figsizes[i][1]))
        gs = fig.add_gridspec(4, 4)
        for j, class_name in enumerate(task_classes[i]):
            df_methods = {}
            for k, method in enumerate(methods):
                filename = base_path + task + "/refinement_" + set + "/eval_results/processed/dice/" + method + ".csv"
                if not os.path.isfile(filename):
                    continue
                df = pd.read_csv(filename)
                df = df.iloc[:, j+1].to_numpy()
                df_methods[method_names[k]] = df
            df = pd.DataFrame.from_dict(df_methods, orient='index').T
            sns.set_theme(style="whitegrid")
            ax = fig.add_subplot(gs[gridspec_indices[i][j][0], gridspec_indices[i][j][1]])
            ax = sns.boxplot(data=df, ax=ax)
            ax.tick_params(axis='x', rotation=20)
            ax.set_ylim(0, 1)
            ax.set_title("{}".format(class_name))
        plt.suptitle("{}".format(task_names[i]), fontsize=16)
        # plt.show()
        plt.savefig(base_path + "Evaluation/Results/" + set + "/" + task_names[i] + ".png", bbox_inches='tight')
        plt.clf()

if __name__ == '__main__':
    base_path = "/gris/gris-f/homelv/kgotkows/datasets/nnUnet_datasets/nnUNet_raw_data/nnUNet_raw_data/"
    tasks = ["Task070_guided_all_public_ggo", "Task002_BrainTumour_guided", "Task008_Pancreas_guided"]
    task_names = ["COVID-19", "Brain Tumor", "Pancreas"]
    task_classes = [["GGO"], ["Edema", "Non-enhancing Tumor", "Enhancing Tumor"], ["Pancreas", "Cancer"]]
    methods = ["automatic", "my_method", "P_Net", "watershed", "GraphCut1"]  # ["automatic", "my_method", "P_Net", "watershed", "random_walker", "GraphCut1", "random1", "random2", "random3"]
    method_names = ["Preseg.", "nnU-Net", "P-Net", "Watershed", "Graph-Cut"]  # ["Preseg.", "nnU-Net", "P-Net", "Watershed", "Random Walker", "Graph-Cut", "RS1", "RS2", "RS3"]
    set = "test"
    figsizes = [[8, 5], [29, 10], [12, 5]]
    gridspec_indices = [[[slice(0, 4), slice(0, 4)]],
                        [[slice(0, 2), slice(0, 1)], [slice(0, 2), slice(1, 2)], [slice(0, 2), slice(2, 3)]],
                        [[slice(0, 4), slice(0, 2)], [slice(0, 4), slice(2, 4)]]]

    plot_dice_box_plots()


import numpy as np
import math
import scipy.stats as stats
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor

from settree.set_data import apply_operation

DTYPE = np.float32
MAX_INT = np.iinfo(np.int32).max

def complementary(curr_as, record):
    return [i for i in range(len(record)) if i not in curr_as]

def mse(y, weights=None):
    """
    Mean squared error for decision tree (ie., mean) predictions
    """
    return np.average((y - np.average(y, weights=weights)) ** 2, weights=weights)

def entropy(y, weights=None):
    """
    Entropy of a label sequence
    """
    hist = np.bincount(y, weights)
    return stats.entropy(hist)
    # ps = hist / np.sum(hist)
    # return -np.sum([p * np.log2(p) for p in ps if p > 0])

def gini(y, weights=None):
    """
    Gini impurity (local entropy) of a label sequence
    """
    hist = np.bincount(y, weights)
    N = np.sum(hist)
    return 1 - sum([(i / N) ** 2 for i in hist])

class DatasetMemoryQueue():
    """
    FIFO queue for keeping running memory of calculated statistics.
    Is used for avoiding excess computations and increase efficiency.
    """

    def __init__(self, operations, use_attention_set, use_attention_set_comp, attention_set_limit):

        """

        The running memory queue is kept as a list of np.arrays with the structure : [flat_base, flat_as_1, ... flat_as_n]
        Where flat_as_i is an array that contains the aggregated results for the ith stage.

        Parameters
        ----------

        operations : list of numpy functions
            The list of aggregation operators to use when building the tree.

        use_attention_set : bool
            Whether to use the attention-set mechanism.

        use_attention_set_comp : bool
            Whether to use the attention-set compatibles set.

        attention_set_limit : int
            The number of ancestors to scan while scanning split criteria with the attention-sets.
            When attention_set_limit=1, scans only the direct ancestors.
        """

        self.operations = operations
        self.n_operations = len(self.operations)

        self.use_attention_set = use_attention_set
        self.use_attention_set_comp = use_attention_set_comp
        self.attention_set_limit = attention_set_limit
        self.attention_set_states = [False, True] if self.use_attention_set_comp else [False]

        self.X = None

    def _init(self, X_set, mask_inds):
        """
        Calculate the flattened dataset without any attention set
        """
        self.n_features = X_set.shape[1]
        self.base_len = self.n_features * self.n_operations

        self.max_memory = self.n_features * self.n_operations
        if self.use_attention_set:
            if self.use_attention_set_comp:
                self.max_memory = self.max_memory * (1 + np.abs(self.attention_set_limit) * 2)
            else:
                self.max_memory = self.max_memory * (1 + np.abs(self.attention_set_limit))

        X = []
        for i in mask_inds:
            record = X_set.records[i]
            X.append(np.concatenate([op(record) for op in self.operations]))

        self.X = X
        self.records_len = np.full(shape=(len(mask_inds,)), fill_value=self.base_len).astype(int)

    def _get_flat_record(self, record, attention_set):
        record = record[attention_set]
        if len(record):
            flat_record = []
            for op in self.operations:
                flat_record.append(op(record))
            flat_record = np.concatenate(flat_record)
        else:
            flat_record = np.full(shape=(self.n_features * self.n_operations,), fill_value=np.finfo(np.float32).min)
        return flat_record

    def _calc_flatten_dataset_for_current_attention_set(self, X_set, mask_inds):

        flat_record_len = self.base_len * 2 if self.use_attention_set_comp else self.base_len

        for ind in mask_inds:
            as_mem = X_set.attention_set[ind]
            record = X_set.records[ind]

            prev_as = as_mem[-1]
            flat_record = self._get_flat_record(record, prev_as)

            if self.use_attention_set_comp:
                prev_as = complementary(prev_as, record)
                flat_comp_record = self._get_flat_record(record, prev_as)
                flat_record = np.concatenate([flat_record, flat_comp_record])

            # if the memory if full
            # dump the first memory, shift the rest to the right and insert a new memory
            if self.records_len[ind] >= self.max_memory:
                mem_flat_record = self.X[ind]
                mem_base = mem_flat_record[:self.base_len]
                mem_as = mem_flat_record[self.base_len:-flat_record_len]
                self.X[ind] = np.concatenate([mem_base, flat_record, mem_as])
                self.records_len[ind] = self.max_memory

            # if there is already a flatten attention-set in memory
            # shift the current memory to the right and insert a new memory
            elif self.records_len[ind] > self.base_len:
                mem_flat_record = self.X[ind]
                mem_base = mem_flat_record[:self.base_len]
                mem_as = mem_flat_record[self.base_len:]
                self.X[ind] = np.concatenate([mem_base, flat_record, mem_as])
                self.records_len[ind] += flat_record_len

            else:
                mem_base = self.X[ind]
                self.X[ind] = np.concatenate([mem_base, flat_record])
                self.records_len[ind] += flat_record_len

    def _get_feature_number_to_args(self, cur_depth, apply_attention_set=False):
        ind2args = {}
        c = 0
        for op in self.operations:
            for i in range(self.n_features):
                ind2args[c] = {'feature': i,
                               'op': op,
                               'use_attention_set': False,
                               'use_attention_set_comp': False}
                c += 1

        # if the model is using the attention-sets - add it to mapping
        if apply_attention_set:
            for as_level in list(range(-1, max(-cur_depth, -self.attention_set_limit) - 1, -1)):
                for as_comp in self.attention_set_states:
                    for op in self.operations:
                        for i in range(self.n_features):
                            ind2args[c] = {'feature': i,
                                           'op': op,
                                           'use_attention_set': as_level,
                                           'use_attention_set_comp': as_comp}
                            c += 1

        return ind2args

    def reset(self):
        del self.X
        del self.records_len
        self.X = None
        self.records_len = None

    def enqueue_and_get(self, X_set, mask_inds, cur_depth):
        if cur_depth == 0:
            self._init(X_set, mask_inds)
            ind2args = self._get_feature_number_to_args(cur_depth, False)
        else:
            if self.use_attention_set:
                self._calc_flatten_dataset_for_current_attention_set(X_set, mask_inds)
                ind2args = self._get_feature_number_to_args(cur_depth, True)
            else:
                ind2args = self._get_feature_number_to_args(cur_depth, False)

        X = np.stack([self.X[i] for i in mask_inds])
        return X, ind2args

class BaseSplitter():
    """
    Abstract splitter class
    Splitters are called by tree builders to find the best splits.
    """

    def __init__(self, classifier=True, criterion='entropy', max_features=None, min_samples_leaf=1, random_state=None):
        """
        Parameters
        ----------
        classifier : bool
            Whether the tree used for classification or regression

        criterion : {"gini", "entropy", "mse"}, default="entropy"
            The function to measure the quality of a split.

        max_features : int, float, {"auto", "sqrt", "log2"} or None, default="auto"
            The number of features to consider when looking for the best split:
                - If int, then consider `max_features` features at each split.
                - If float, then `max_features` is a fraction and
                  `int(max_features * n_features)` features are considered at each
                  split.
                - If "auto", then `max_features=sqrt(n_features)`.
                - If "sqrt", then `max_features=sqrt(n_features)`.
                - If "log2", then `max_features=log2(n_features)`.
                - If None, then `max_features=n_features`.

        min_samples_leaf : int or float, default=1
            The minimum number of samples required to be at a leaf node.
            A split point at any depth will only be considered if it leaves at
            least ``min_samples_leaf`` training samples in each of the left and
            right branches.  This may have the effect of smoothing the model,
            especially in regression.
            - If int, then consider `min_samples_leaf` as the minimum number.
            - If float, then `min_samples_leaf` is a fraction and
              `ceil(min_samples_leaf * n_samples)` are the minimum
              number of samples for each node.

        min_weight_leaf : double
            The minimal weight each leaf can have, where the weight is the sum
            of the weights of each sample in it.

        random_state : int, RandomState instance or None, default=None
            Used to pick randomly the `max_features` used at each split.
        """

        self.criterion = criterion
        self.classifier = classifier
        self.min_samples_leaf = min_samples_leaf
        self.random_state = random_state
        self.max_features = max_features

    def init(self, n_samples, n_features):

        self.n_samples = n_samples
        self.n_features = n_features

        if isinstance(self.min_samples_leaf, float):
            self.min_samples_leaf = math.ceil(self.min_samples_leaf * self.n_features)

        if self.criterion in CRITERIONS:
            self.criterion = CRITERIONS[self.criterion]
        else:
            raise ValueError('Invalid criterion name {}'.format(self.criterion))

        if isinstance(self.max_features, float):
            self.max_features = math.ceil(self.max_features * n_features)
        elif self.max_features == 'auto' or self.max_features == 'sqrt':
            self.max_features = math.ceil(np.sqrt(self.n_features))
        elif self.max_features == 'log2':
            self.max_features = math.ceil(np.log2(self.n_features))
        elif self.max_features == None:
            self.max_features = self.n_features
        else:
            raise ValueError('Invalid value for max_features, {}'.format(self.max_features))

    def end(self):
        pass

    def node_split(self, X_set, y, mask_inds, cur_depth):
        raise NotImplemented

class ThirdPartySplitter(BaseSplitter):
    """
    Provides common API for external (third party) splitters
    """

    def __init__(self, classifier=True, criterion='entropy', max_features=None, min_samples_leaf=None, random_state=None,
                 operations=None, use_attention_set=True, use_attention_set_comp=True, attention_set_limit=1):

        self.SMALLEST = np.finfo(DTYPE).min
        self.LARGEST = np.finfo(DTYPE).max

        super().__init__(classifier, criterion, max_features, min_samples_leaf, random_state)

        self.operations = operations
        self.use_attention_set = use_attention_set
        self.use_attention_set_comp = use_attention_set_comp
        self.attention_set_limit = attention_set_limit

        self.memory_queue = DatasetMemoryQueue(operations=self.operations,
                                               use_attention_set=self.use_attention_set,
                                               use_attention_set_comp=self.use_attention_set_comp,
                                               attention_set_limit=self.attention_set_limit)

    def init(self, n_samples, n_features):
        self.attention_set_states = [False, True] if self.use_attention_set_comp else [False]
        self.n_samples = n_samples
        self.n_features = n_features * len(self.operations)
        if self.use_attention_set:
            n_attention_set_levels = np.abs(self.use_attention_set)
            if self.use_attention_set_comp:
                self.n_features = self.n_features * (n_attention_set_levels * 2 + 1)
            else:
                self.n_features = self.n_features * (n_attention_set_levels + 1)

        if isinstance(self.min_samples_leaf, float):
            self.min_samples_leaf = math.ceil(self.min_samples_leaf * self.n_features)

        if self.criterion in CRITERIONS:
            self.criterion = CRITERIONS[self.criterion]
        else:
            raise ValueError('Invalid criterion name {}'.format(self.criterion))

    def node_split(self, X_set, y, mask_inds, cur_depth):
        raise NotImplemented

    def end(self):
        self.memory_queue.reset()

class SklearnSetSplitter(ThirdPartySplitter):

    def __init__(self, classifier=True, criterion='entropy', max_features=None, min_samples_leaf=None, random_state=1,
                 operations=None, use_attention_set=False, use_attention_set_comp=True, attention_set_limit=1):

        super().__init__(classifier, criterion, max_features, min_samples_leaf, random_state,
                         operations, use_attention_set, use_attention_set_comp, attention_set_limit)

    def node_split(self, X_set, y, mask_inds, cur_depth):

        y = y.take(mask_inds)
        X, ind2args = self.memory_queue.enqueue_and_get(X_set, mask_inds, cur_depth)
        rand_state = self.random_state.randint(0, MAX_INT)

        if self.classifier:
            clf = DecisionTreeClassifier(criterion='entropy',
                                         splitter='best',
                                         max_depth=1,
                                         min_samples_split=2,
                                         min_samples_leaf=1,
                                         min_weight_fraction_leaf=0.0,
                                         max_features=self.max_features,
                                         random_state=rand_state).fit(X, y)
        else:
            clf = DecisionTreeRegressor(criterion='mse',
                                        splitter='best',
                                        max_depth=1,
                                        min_samples_split=2,
                                        min_samples_leaf=1,
                                        min_weight_fraction_leaf=0.0,
                                        max_features=self.max_features,
                                        random_state=rand_state).fit(X, y)

        threshold = clf.tree_.threshold[0]
        feature_num = clf.tree_.feature[0]
        gain = clf.tree_.impurity[0]

        if feature_num < 0:
            feature_num = 0
            is_leaf = True
        else:
            is_leaf = False

        best_split = ind2args[feature_num]
        best_split['threshold'] = threshold
        best_split['gain'] = gain
        best_split['is_leaf'] = is_leaf
        return best_split

SPLITTERS = {'sklearn': SklearnSetSplitter}
CRITERIONS = {'gini': gini, 'entropy': entropy, 'mse': mse}


"""
Define problem for speed testing sparse solvers.

"""

import numpy as np
import dedalus.public as de

def build_LHS(Nz):

    # Parameters
    dt = 1e-3
    kx = 50 * np.pi
    sigma = 1
    Prandtl = 1.
    Reynolds = 1e2
    ts = de.timesteppers.SBDF3

    # Create bases and domain
    z_basis = de.Fourier('z', Nz, interval=(-1, 1), dealias=3/2)
    domain = de.Domain([z_basis], grid_dtype=np.complex128)

    # 2D Boussinesq hydrodynamics
    problem = de.IVP(domain, variables=['p','b','u','w'])
    problem.parameters['P'] = 1 / Reynolds / Prandtl
    problem.parameters['R'] = 1 / Reynolds
    problem.parameters['kx'] = kx
    problem.parameters['sigma'] = sigma
    problem.substitutions['Bz'] = "1"
    problem.substitutions['dx(A)'] = "1j*kx*A"
    problem.add_equation("dt(b) - P*(dx(dx(b)) + dz(dz(b))) + Bz*w      = 0")
    problem.add_equation("dt(u) - R*(dx(dx(u)) + dz(dz(u))) + dx(p)     = 0")
    problem.add_equation("dt(w) - R*(dx(dx(w)) + dz(dz(w))) + dz(p) - b = 0")
    if kx == 0:
        problem.add_equation("dx(u) + dz(w) = 0", condition="(nz != 0)")
        problem.add_equation("p = 0", condition="(nz == 0)")
    else:
        problem.add_equation("dx(u) + dz(w) = 0")

    # Build solver
    solver = problem.build_solver(ts)

    # Step solver to form pencil LHS
    for i in range(10):
        solver.step(dt)

    return solver.pencils[0].LHS


#!/usr/bin/python

import os
from os import listdir
import re

def main():
    module = AnsibleModule(
        argument_spec=dict(
            path=dict(required=True),
            filter=dict(required=False),
            result=dict(required=False, default='all', choices=['first', 'all'])
        )
    )

    path = module.params.get('path')
    path = os.path.expanduser(path)

    directory_content = [f for f in listdir(path)]
    filter = module.params.get('filter')
    if filter:
        pattern = re.compile(filter)
        directory_content = [f for f in directory_content if pattern.match(f)]

    should_modify_return_result = module.params.get('result')
    if should_modify_return_result == 'first' and len(directory_content) > 0:
        directory_content = directory_content[0]

    module.exit_json(content=directory_content)

from ansible.module_utils.basic import *

main()


import json
import os
import re
from typing import Any, Dict

from . import files as sm_files

def parse_sm_config() -> Dict[str, Any]:
    """Attempt to parse SageMaker configuration.

    Returns:
        A dictionary of SageMaker config keys/values or empty dict if not found.
    """
    conf = {}
    if os.path.exists(sm_files.SM_PARAM_CONFIG) and os.path.exists(
        sm_files.SM_RESOURCE_CONFIG
    ):
        conf["sagemaker_training_job_name"] = os.getenv("TRAINING_JOB_NAME")
        # Hyperparameter searches quote configs...
        for k, v in json.load(open(sm_files.SM_PARAM_CONFIG)).items():
            cast = v.strip('"')
            if re.match(r"^-?[\d]+$", cast):
                cast = int(cast)
            elif re.match(r"^-?[.\d]+$", cast):
                cast = float(cast)
            conf[k] = cast
    return conf


# -*- coding: utf-8 -*-
import xlrd

# 읽기 라이브러리를 통해 현재 같은 디렉터리상에 있는 test.xls를 불러와 workbook에 할당합니다.
workbook = xlrd.open_workbook('test.xls')

# 워크북에 할당된 엑셀 데이터의 첫번째시트를 불러옵니다.
worksheet = workbook.sheet_by_index(0)

# nrows에 불러온 첫번째 시트의 행수를 불러옵니다.
nrows = worksheet.nrows

# 불러온 데이터를 저장할 딕셔너리를 선언합니다.
datadict = {}

# 행수만큼의 for loop 를 돌려서 행단위로 데이터를 불러와 datadict에 저장합니다.
for row_num in range(nrows):
    datadict[row_num] = {}
    # field_cnt는 열의 개수입니다. 열갯수는 여러분이 지정하시면 됩니다.
    for col in range(field_cnt):
        # datadict[row_num]에 열숫자별로 셀데이터를 저장합니다.
        datadict[row_num][col] = worksheet.cell_value(row_num, col)

workbookw = xlwt.Workbook(encoding='utf-8')  # utf-8 인코딩 방식의 workbook 생성

workbookw.default_style.font.height = 20 * 11
worksheetw = workbookw.add_sheet('시트 이름')  # 시트 생성

# 2번째 행부터 데이터를 입력합니다.
for row_num in range(nrows):
    for col in range(field_cnt):
        worksheetw.write(row_num, col, datadict[row_num][col])

# 할당된 데이터셋을 'result.xls'로 저장합니다.
workbookw.save("result.xls")


from django.shortcuts import render
from . models import *

def index(request):
	services = Service.objects.all()[:3]
	team_members = TeamMember.objects.all()[:3]

	events = TimelineEvent.objects.all().order_by('date')
	projects = Project.objects.all().order_by('-date')

	pictures = Picture.objects.all().order_by('-date')

	jobs = Job.objects.all()

	return render(request, 'myapp/index.html', {
			'services' : services,
			'team_members' : team_members,
			'events' : events,
			'projects' : projects,
			'pictures' : pictures,
			'jobs' : jobs,
 		})


from django.test import TestCase

from contacts.models import Contact

class ContactTests(TestCase):
    """Contact model tests."""

    def test_str(self):

        contact = Contact(first_name='gulsah', last_name='acar')

        self.assertEquals(
            str(contact),
            'gulsahacar',
        )


from ftw.upgrade import UpgradeStep
from opengever import activity
from opengever.base.model import Base
from opengever.base.model import create_session
from opengever.base.model import get_tables

class InstallActivity(UpgradeStep):

    def __call__(self):
        self.create_activity_tables()
        self.setup_install_profile(
            'profile-opengever.activity:default')
        self.setup_install_profile(
            'profile-collective.js.timeago:default')

    def create_activity_tables(self):
        """When installing the activity suppackage via upgrade-step we need
        to initialize its database tables.

        If it is installed on an new plone-site `opengever.base.hooks` takes
        care of that.
        """
        Base.metadata.create_all(
            create_session().bind,
            tables=get_tables(activity.model.tables),
            checkfirst=True)


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# 面向对象的高级编程

from types import MethodType

# 使用__slots__，给实例绑定属性和方法时，限制属性
print('----------------------使用__slots__----------------------')

class Student(object):
    pass

print('----------------------给实例绑定一个属性----------------------')
s = Student()
s.name = 'jack'
print('name==', s.name)

print('----------------------给实例绑定一个属性----------------------')

def set_age(self, age):
    self.age = age

s.set_age = MethodType(set_age, s)
s.set_age(25)
print('age==', s.age)
print('----------------------给class绑定----------------------')
Student.set_age = set_age  # 直接给class绑定,所有的都能调用
s2 = Student()
s2.set_age(26)
print('age==', s2.age)
print('----------------------使用__slots__限制实例属性----------------------')

class Teacher(object):
    __slots__ = ('name', 'age')  # 用tuple定义允许绑定的属性名称，只对当前类的实例有效，对继承的子类无效

# 使用@property，把一个方法变成属性调用
print('----------------------使用@property_----------------------')

class Student(object):
    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        self._score = value

s = Student()
s.score = 99
print('score==', s.score)


# import the pygame module, so you can use it
import pygame
import random
from collections import namedtuple
from pygame import gfxdraw

ui_id = namedtuple("ui_id", "Owner Item Index")
class motion:
    pass

class particle:
    def __init__(self, width, height, anomoly, particle_distance):
        self.width = width
        self.height = height
        self.x = random.randint(1, width)
        self.y = random.randint(1, height)
        self.size = random.randint(1, 2)
        self.mult = random.randint(0, 255)
        self.vector_x = random.randint(-2, 2)
        self.vector_y = random.randint(-2, 2)
        self.color = (int(random.randint(0, 255)), int(random.randint(0, 255)), int(random.randint(0, 255)))
        self.anomoly = anomoly
        self.anomolygravity = random.randint(particle_distance/2, particle_distance)+50
    def update(self, *args):
        self.x += self.vector_x
        self.y += self.vector_y
        if self.x > self.width:
            self.x = 1
            self.vector_x = random.randint(-2, 2)
            self.vector_y = random.randint(-2, 2)
        if self.x < 1:
            self.x = self.width
            self.vector_x = random.randint(-2, 2)
            self.vector_y = random.randint(-2, 2)
        if self.y > self.height:
            self.y = 1
            self.vector_x = random.randint(-2, 2)
            self.vector_y = random.randint(-2, 2)
        if self.y < 1:
            self.y = self.height
            self.vector_x = random.randint(-2, 2)
            self.vector_y = random.randint(-2, 2)
        while (self.vector_x == 0) or (self.vector_y == 0):
            self.vector_x = random.randint(-2, 2)
            self.vector_y = random.randint(-2, 2)

class particle_generator:
    def __init__(self, surface, particle_count, particle_distance, anomoly_count):
        self.pausing = False
        self.surface = surface
        self.surface_width = surface.get_width()
        self.surface_height = surface.get_height()
        self.particle_count = particle_count
        self.particle_distance = particle_distance
        self.particle_array = [] # start with an empty list
        self.anomoly_count = anomoly_count
        self.anomoly_array = []
        particle_number = 1
        for particle_number in range(self.particle_count):
            isAnomoly = False
            if (particle_number <= self.anomoly_count):
                isAnomoly = True
            myparticle = particle(self.surface_width, self.surface_height, isAnomoly, self.particle_distance)
            self.particle_array.append(myparticle) # top of 1st story, upper left
            if (isAnomoly):
                self.anomoly_array.append(myparticle)

    def update(self, *args):
        #for particle in self.particle_array:
            #pygame.draw.circle(self.surface, (100,100,100), (particle[0], particle[1]), particle[2], 0)
            #gfxdraw.circle(self.surface, particle[0], particle[1], particle[2], (100,100,100))
            #gfxdraw.pixel(self.surface, particle[0], particle[1], (100,100,100))
        #for anomolyparticle in self.anomoly_array:
        for particle in self.particle_array:
            if (not self.pausing):
                particle.update()
            gfxdraw.filled_circle(self.surface, particle.x, particle.y, particle.size, particle.color)
            if (abs(anomolyparticle.x-particle.x) < anomolyparticle.anomolygravity) and (abs(anomolyparticle.y-particle.y) < anomolyparticle.anomolygravity):
                for particle2 in self.particle_array:
                    if (abs(particle2.x-particle.x) < anomolyparticle.anomolygravity) and (abs(particle2.y-particle.y) < anomolyparticle.anomolygravity) and (particle.size == particle2.size):
                        rednumber = (particle.color[0]+particle2.color[0])/2
                        greennumber = (particle.color[1]+particle2.color[1])/2
                        bluenumber = (particle.color[2]+particle2.color[2])/2
                        color = (int(rednumber),int(greennumber),int(bluenumber))
                        pygame.draw.aaline(self.surface, color, (particle.x,particle.y),(particle2.x,particle2.y), 1)

    def reset(self, *args):
        self.particle_array = [] # start with an empty list

        particle_number = 1
        for particle_number in range(self.particle_count):
            myparticle = particle(self.surface_width, self.surface_height, False, self.particle_distance)
            self.particle_array.append(myparticle) # top of 1st story, upper left

    def mousemotion(self, *args):
        self.mouse_x, self.mouse_y = args[0]

    def pause(self, *args):
        self.pausing = not self.pausing

# define a main function
def main():

    # initialize the pygame module
    pygame.init()
    # load and set the logo
    logo = pygame.image.load("logo32x32.png")
    pygame.display.set_icon(logo)
    pygame.display.set_caption("minimal program")

    screen_width = 1500
    screen_height = 1100

    bg_image = pygame.image.load("spacee-740x463.jpg")

    # create a surface on screen that has the size of screen_width x screen_height
    #screen = pygame.display.set_mode((screen_width,screen_height))
    screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
    myparticle_generator = particle_generator(screen, 200, 100, 200);
    # define a variable to control the main loop
    running = True
    clock = pygame.time.Clock()
    fps = 60
    # main loop
    while running:
        # event handling, gets all event from the eventqueue
        for event in pygame.event.get():
            #if event.type == pygame.MOUSEBUTTONDOWN:
            #
            #elif event.type == pygame.MOUSEBUTTONUP:
            #
            #elif event.type == pygame.MOUSEMOTION:
            if event.type == pygame.MOUSEMOTION:
                myparticle_generator.mousemotion(event.pos)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    myparticle_generator.reset()
                if event.key == pygame.K_SPACE:
                    myparticle_generator.pause()
                if event.key == pygame.K_ESCAPE:
                    running = False

            # only do something if the event is of type QUIT
            if event.type == pygame.QUIT:
                # change the value to False, to exit the main loop
                running = False
        clock.tick(fps)

        #screen.blit(bg_image, (0, 0))
        screen.fill((0,0,0))
        myparticle_generator.update()
        # draw anim
        #dirty_rect = screen.blit(100, 240)
        # update screen
        #pygame.display.update(dirty_rect)
        pygame.display.flip()

# run the main function only if this module is executed as the main script
# (if you import this as a module then nothing is executed)
if __name__=="__main__":
    # call the main function
    main()


#!/bin/python
# -*- coding: utf-8 -*-
# @File  : worker.py
# @Author: wangms
# @Date  : 2018/10/9
from subprocess import Popen, PIPE, STDOUT

class Worker(object):
    def __init__(self):
        self.task_name = ''
        self.task_command = ''
        self.server = ''

    def run(self, command):
        p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
        for line in iter(p.stdout.readline, ''):
            if line == '':
                break
            print(line.strip())


'''
Author : dhawal gupta
This is supposed to run the with the start state from a script which is entered thorught the command line

'''

import random
import numpy as np
import pickle as pkl
# import random
from Final import *
import time
from make_puzzle import generate_puzzle

state = np.zeros((3, 3)).astype(int)
goal = np.zeros((3, 3)).astype(int)
end_state = 'end.txt'
with open(end_state) as fil:
    # read the goal state
    row = 0  # the currebt row
    line = fil.readline()
    while line:
        for col, no in enumerate(line.split()):
            goal[row][col] = no
        line = fil.readline()
        row = row + 1

if len(sys.argv)  < 2:
    print("Start File not enterd hence generation it from random")
    # raise Exception("Enter the start file atleast")
    state = generate_puzzle(goal, steps = 50)
else:
    start_file = sys.argv[1]

    end_state = 'end.txt'

    if len(sys.argv) > 2:
        end_state = sys.argv[2]

    state = np.zeros((3,3)).astype(int)
    goal =  np.zeros((3,3)).astype(int)

    with open(start_file) as fil:
        # read the goal state
        row = 0 # the currebt row
        line = fil.readline()
        while line:
            for col,no in enumerate(line.split()):
                state[row][col] = no
            line = fil.readline()
            row = row + 1

    with open(end_state) as fil:
        # read the goal state
        row = 0 # the currebt row
        line = fil.readline()
        while line:
            for col,no in enumerate(line.split()):
                goal[row][col] = no
            line = fil.readline()
            row = row + 1

timeh1 = 0
timeh2 = 0
timeh3 = 0
print("Fir h3")
timeh3 = time.time()
objh3 = run_experiment_check_montonicity(start_state = state, goal_state = goal, h_function=h3)
timeh3 = time.time() - timeh3
print("Fpor H2")
timeh2 = time.time()
objh2 = run_experiment_check_montonicity(start_state = state, goal_state = goal, h_function=h2)
timeh2 = time.time() - timeh2
# timeh1 = time.time()
# objh1 = run_experiment_check_montonicity(start_state = state, goal_state = goal, h_function=h1)
# timeh1 = time.time() - timeh1

print("Time h1 : {}\nTime h2 : {}\nTime h3 : {}".format(timeh1, timeh2, timeh3))
# list1 = list(objh1.closed_list.keys())
list2 = list(objh2.closed_list.keys())
list3 = list(objh3.closed_list.keys())
# sets1 = set(list1)
sets2 = set(list2)
sets3 = set(list3)

# print(seth1)
# print(seth2)
# print(seth3)

val = sets3.issubset(sets2)
print(val)
if not val:
    print(sets3.difference(sets2))

# val = sets2.issubset(sets1)
# print(val)
# if not val:
#     print(sets2.difference(sets1))


import json, os, re
from PySimpleGUI import PySimpleGUI as sg
from time import sleep

version = 'v1.0.1'

def ConfigureConfig():
    '''
        Checks config file at root;
        If a file does not exist, it creates a standard version of the file automatically;
        '''
    Default = {
        'Version' : '1.0',
        'SystemRef' :
        {
            'Name' : 'ICT 001',
            'SystemName' : 'brbelict001'
        }
    }

    DefaultContent = json.dumps(Default, indent = True)

    with open(r'config\config.json', 'w+') as file:
        file.write(DefaultContent)

def checkwirelist(ref) -> bool:
    '''
        Check condition of wireless files in the reference folder
        -> 'ref' = Reference name
        -> Return flag check (bool)
        '''
    try:
        file = open(refroot + '\\' + ref + '\\wirelist', 'r')

    except (FileExistsError,PermissionError,FileNotFoundError) as erro:
        print(f'Load erro ref >> {erro} <<')
        return False

    else:
        file.close()
        return True

def LabelValidation(label):
    '''
        Valid test label Expression
        '''
    exp_reg = re.compile(r'^[1-2]{1}%{1}\w')
    match = re.match(exp_reg, label)
    if match:
        return True
    else:
        return False

class Wiredata:

    def __init__(self, board, label):
        self.board = board
        self.label = label
        self.BoardWirelist = self.LoadBoardWirelist(board)
        self.LabelWirelist = self.LoadLabelWirelist()
        if not self.LabelWirelist == None:
            self.TestType = self.GetTestType()
            self.Module = self.GetModule()
            self.SubExist = self.SubCheck()

    def LoadBoardWirelist(self, board):
        with open(refroot + '\\' + board + '\\wirelist') as file:
            BoardWirelist = file.read()
            return BoardWirelist

    def LoadLabelWirelist(self):
        # LabelWire = re.findall(fr'test \w+ "' + self.label + '\"' + r'.+end test', self.BoardWirelist, flags=re.M | re.DOTALL)
        LabelWire = re.findall(fr'test \w+ \"{self.label}\".+end test', self.BoardWirelist, flags=re.M | re.DOTALL)
        if LabelWire:
            LabelWire = LabelWire[0]
            cut_end = LabelWire.find('end test')
            LabelWire = LabelWire[:cut_end]
            return LabelWire
        else:
            return None

    def GetTestType(self):
        testtype = re.findall(r'\w+', self.LabelWirelist)
        return testtype[1]

    def GetModule(self):
        if self.TestType == 'analog':   # Module info not present in analog test's wire list
            return None
        else:
            module = re.findall(r'\w+', self.LabelWirelist)
            return module[7]

    def SubCheck(self):
        if 'subtest' in self.LabelWirelist:
            return True
        else:
            return False

class Interface:

    sg.theme('DarkGreen')

    def main_window(self):
        # Main Window
        # sg.theme('Reddit')
        # Main Layout
        main_layout = [
            [sg.Text('Fixture Reference: ')],
            [sg.Listbox(RefListAvl, size=(20,len(RefListAvl)), key='-SelectRef-', enable_events=True)],
            [sg.Text('Label Search: ')],
            [sg.Input(key='-SearchLabel-', focus=True)],
            [sg.Button('Show', key='-Show-', bind_return_key=True)],
        ]

        # Main Window
        return sg.Window('Fixture Wirelist Consult ' + version, main_layout,icon='appdata/icon.ico', finalize=True)

    def LoadErro(self):
        '''
            Window load, check files in folders error
            '''
        layout_column = [
                [sg.Text('Erro ao realizar leitura de referência.\n Verique a pasta de referências na raiz.',justification='center')],
        ]
        layout = [
            [sg.Column(layout_column, element_justification='center')],
            [sg.Button('OK', bind_return_key=True, focus=True)]
        ]

        window = sg.Window('Erro', layout, icon='appdata/icon.ico', grab_anywhere=True)

        while True:
            event, values = window.read()
            if event == sg.WIN_CLOSED or event == 'Exit' or event == 'OK':
                break
        window.close()

    def ErroMsg(self, msg):
        '''
            Print erro msg. <msg>
            -> msg = string(msg print)
            '''
        layout_column = [
                [sg.Text(msg, justification='center')],
        ]

        layout = [
            [sg.Column(layout_column, element_justification='center')],
            [sg.Button('OK', bind_return_key=True, focus=True)]
        ]

        window = sg.Window('Erro', layout, icon='appdata/icon.ico', grab_anywhere=True)

        while True:
            event, value = window.read()
            if event == sg.WINDOW_CLOSED or value == 'OK' or event == 'OK':
                break
        window.close()

    def WireWindow(self, data):
        layout = [
            [sg.Text(data.label, justification='center')],
            [sg.Multiline(data.LabelWirelist, autoscroll=True, size=(45,15))],
            [sg.Button('Close', key='-close-', bind_return_key=True)]
        ]
        return sg.Window(data.label, layout, icon='appdata/icon.ico', location=(0,0), finalize=True)
# ===========================================================================

if __name__ == "__main__":

    main = Interface()
    # Check COnfig File Exist
    try:
        ConfigFile = open(r'config\config.json', 'r')
    except (FileExistsError, FileNotFoundError) as error:
        ConfigureConfig()
    else:
        ConfigFile.close()

    # Scanning the root folder of recerences
        # Walk files in paste
    refroot = r'refs'
    RefList = []
    for Folder in os.listdir(refroot):
        RefList.append(Folder)

    # Check and lists correct wirelist files available
    RefListAvl = []
    fErro = False
    for ref in RefList:
        if checkwirelist(ref):
            RefListAvl.append(ref.lower())  # References available list
        else:
            fErro = True

    if fErro:
        main.LoadErro()

    main_window = main.main_window()        # main window create
    WindowListObjects = {}     # Window objects open list

    while True:

        InputErro = False
        window, event, value = sg.read_all_windows()

        if window == main_window and event == sg.WINDOW_CLOSED:
            break

        # Main Window Event
        if window == main_window and event == '-Show-':
            # Select Board
            SelectBoard =  value['-SelectRef-']
            if len(SelectBoard) == 0 or not SelectBoard[0] in RefListAvl:
                print('Referência selecionada não encontrada\n')
                main.ErroMsg('Referência selecionada não encontrada')
                InputErro = True
            else:
                SelectBoard =  value['-SelectRef-'][0]

            # Search label
            SearchLabel = value['-SearchLabel-']

            if not LabelValidation(SearchLabel):
                print('Pesquisa no formato incorreto (1/2%nome')
                main.ErroMsg('Pesquisa no formato incorreto (1/2%nome)')
                InputErro = True

            if not InputErro:   # Create window list
                Selection = SelectBoard + SearchLabel                       # Permite abrir janela de mesma label em referencia diferente
                if Selection not in WindowListObjects.keys():
                    WirelistData = Wiredata(SelectBoard, SearchLabel)
                    NewWindow = Interface()
                    if WirelistData.LabelWirelist == None:
                        main.ErroMsg('Label não encontrada')
                        # WindowListObjects.update({SearchLabel: WindowObjet})
                    else:
                        WindowObjet = NewWindow.WireWindow(WirelistData)
                        WindowListObjects.update({Selection: WindowObjet})
                else:
                    print('ja foi aberto')
                    pass

        # Second Windows - OtherWindows monitor (Read)
        for LabelWindow_Selection, Object in WindowListObjects.items():
            if window == Object and event == '-close-':
                print('Event Detect in:', Object, '/', window)
                Object.Close()
                del WindowListObjects[LabelWindow_Selection]
                break


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('courseDetails/<int:myid>', views.courseDetails, name='courseDetails'),
    path('enroll/<int:myid>', views.courseEnroll, name='courseEnroll'),
    path('course/', views.course, name='course'),
    path('about/', views.aboutus, name='about'),
    path('contact/', views.contact, name='contact'),
    path('search', views.search, name='search'),
    path('gallery', views.gallery, name='gallery'),
    path('studentReg/<int:myid>', views.studentReg, name='studentReg'),
    path('termsAndConditions', views.terms, name='termsAndConditions'),
    path('premiumcourse', views.premiumreg, name='premiumcourse'),
]


from flask import Flask, jsonify, request

app = Flask(__name__)
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from src.request.ranking_input import RankingInput
from src.response.ranking_response import RankingResponse

def init():
    pass

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    return 'Cleveland-Ranking: Ranking online system for SuperSearch.'

@app.route('/ranking', methods=['POST'])
def ranking():
    # pass-through: return same searchResponse with extra rankScore.
    request_body = request.json
    ranking_input_obj = RankingInput.from_request_json(request_body)
    response_obj = RankingResponse.from_ranking_input(ranking_input_obj)
    # set default rankScore the same as filtrationScore.
    response_obj.set_default_ranking_score()
    return jsonify(response_obj.__dict__)

if __name__ == '__main__':
    init()
    app.run(host='0.0.0.0', port=80)


import csv
import os

import numpy as np
from imbDRL.data import get_train_test_val, load_csv
from imbDRL.metrics import classification_metrics
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.metrics import Precision, Recall
from tensorflow.keras.optimizers import Adam
from tqdm import tqdm

os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # CPU is faster than GPU on structured data

min_class = [1]  # Labels of the minority classes
maj_class = [0]  # Labels of the majority classes
_X_train, _y_train, _X_test, _y_test = load_csv("./data/aki0.csv", "./data/aki1.csv", "aki", ["hadm_id"], normalization=True)
metrics = [Precision(name="precision"), Recall(name="recall")]

# Thresholds < 0.5 will result in higher recall than standard NN
# Thresholds > 0.5 will result in higher precision than standard NN
thresholds = np.arange(0.0, 1, 0.01)

fp_NN = "./results/aki/nn.csv"
fp_dta = "./results/aki/dta.csv"
fieldnames = ("Gmean", "F1", "Precision", "Recall", "TP", "TN", "FP", "FN")

# Create empty files
with open(fp_NN, "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
with open(fp_dta, "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()

# Run the model ten times
for _ in tqdm(range(10)):
    # New train-test split
    X_train, y_train, X_test, y_test, X_val, y_val = get_train_test_val(_X_train, _y_train, _X_test, _y_test, min_class, maj_class,
                                                                        val_frac=0.2, print_stats=False)

    model = Sequential([Dense(256, activation="relu", input_shape=(X_train.shape[-1],)),
                        Dropout(0.2),
                        Dense(256, activation="relu"),
                        Dropout(0.2),
                        Dense(1, activation="sigmoid")])
    model.compile(optimizer=Adam(0.001), loss="binary_crossentropy", metrics=metrics)
    model.fit(X_train, y_train, epochs=30, batch_size=32, validation_data=(X_val, y_val), verbose=0)

    # Predictions of model for `X_test`
    y_pred_val = model(X_val).numpy()
    y_pred_test = model(X_test).numpy()
    NN_stats = classification_metrics(y_test, np.around(y_pred_test).astype(int))

    # Write current NN run to `fp_NN`
    with open(fp_NN, "a", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writerow(NN_stats)

    # Validation F1 of every threshold
    f1scores = [classification_metrics(y_val, (y_pred_val >= th).astype(int)).get("F1") for th in thresholds]

    # Select threshold with highest validation F1
    dta_stats = classification_metrics(y_test, (y_pred_test >= thresholds[np.argmax(f1scores)]).astype(int))

    # Write current DTA run to `fp_dta`
    with open(fp_dta, "a", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writerow(dta_stats)


# Copyright, John Rusnak, 2012
    # This code binding is available under the license agreement of the LGPL with
    # an additional constraint described below,
    # and with the understanding that the webkit API is copyright protected
    # by Apple Computer, Inc. (see below).
    # There is an  additional constraint that any derivatives of this work aimed
    # at providing bindings to GObject, GTK, GDK, or WebKit be strictly
    # python-only bindings with no native code.
    # * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY
    # * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    # * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    # * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
    # * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    # * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    # * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    # * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
    # * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    # * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    # * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    #
    # ******************************************************
    # For the API:
    # /*
    # * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
    # *
    # * Redistribution and use in source and binary forms, with or without
    # * modification, are permitted provided that the following conditions
    # * are met:
    # * 1. Redistributions of source code must retain the above copyright
    # *    notice, this list of conditions and the following disclaimer.
    # * 2. Redistributions in binary form must reproduce the above copyright
    # *    notice, this list of conditions and the following disclaimer in the
    # *    documentation and/or other materials provided with the distribution.
    # *
    # * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
    # * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    # * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    # * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
    # * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    # * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    # * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    # * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
    # * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    # * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    # * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    # */
from ctypes import *
from .gtk3_types import *
from .gtk3_enums import *
from .javascriptcore_types import *
from .javascriptcore_enums import *

OPAQUE_PTR = POINTER(c_void_p)
NULL = c_void_p()

"""Derived Pointer Types"""
_GtkRcStyle = OPAQUE_PTR
_GdkGeometry = OPAQUE_PTR
_PangoFont = OPAQUE_PTR
_WebKitNetworkResponse = OPAQUE_PTR
_GtkLabel = OPAQUE_PTR
_GdkPixbuf = OPAQUE_PTR
_GtkRequisition = OPAQUE_PTR
_GtkRcStyle = OPAQUE_PTR
_PangoEngineShape = OPAQUE_PTR
_GtkRegionFlags = OPAQUE_PTR
_GAsyncResult = OPAQUE_PTR
_cairo_matrix_t = OPAQUE_PTR
_GtkWindow = OPAQUE_PTR
_cairo_font_options_t = OPAQUE_PTR
_JSValue = OPAQUE_PTR
_JSContext = OPAQUE_PTR
_GtkIconFactory = OPAQUE_PTR
_GdkAtom = OPAQUE_PTR
_GdkTimeCoord = OPAQUE_PTR
_GdkColor = OPAQUE_PTR
_GtkWidgetPath = OPAQUE_PTR
_GtkContainer = OPAQUE_PTR
_PangoItem = OPAQUE_PTR
_GClosure = OPAQUE_PTR
_GIcon = OPAQUE_PTR
_GMainContext = OPAQUE_PTR
_GdkDisplay = OPAQUE_PTR
_GInterface = OPAQUE_PTR
_GtkStyleProvider = OPAQUE_PTR
_JSContextGroup = OPAQUE_PTR
_GFileEnumerator = OPAQUE_PTR
_GtkDialog = OPAQUE_PTR
_WebKitWebWindowFeatures = OPAQUE_PTR
_GtkCssProvider = OPAQUE_PTR
_GtkSymbolicColor = OPAQUE_PTR
_void = OPAQUE_PTR
_GtkStyleProperties = OPAQUE_PTR
_GInputStream = OPAQUE_PTR
_GtkIconInfo = OPAQUE_PTR
_GAppInfo = OPAQUE_PTR
_WebKitWebResource = OPAQUE_PTR
_GBytes = OPAQUE_PTR
_GScanner = OPAQUE_PTR
_PangoFont = OPAQUE_PTR
_GtkStyleContext = OPAQUE_PTR
_GMainContext = OPAQUE_PTR
_GtkTextBuffer = OPAQUE_PTR
_GtkTargetList = OPAQUE_PTR
_WebKitWebSettings = OPAQUE_PTR
_GtkNumerableIcon = OPAQUE_PTR
_GdkAppLaunchContext = OPAQUE_PTR
_GObject = OPAQUE_PTR
_PangoLayout = OPAQUE_PTR
_GtkSymbolicColor = OPAQUE_PTR
_WebKitWebBackForwardList = OPAQUE_PTR
_GtkWidget = OPAQUE_PTR
_GtkOffscreenWindow = OPAQUE_PTR
_GParamSpec = OPAQUE_PTR
_GAppLaunchContext = OPAQUE_PTR
_PangoAttrIterator = OPAQUE_PTR
_GFileAttributeMatcher = OPAQUE_PTR
_GtkRequisition = OPAQUE_PTR
_GtkIconSet = OPAQUE_PTR
_GtkIconTheme = OPAQUE_PTR
_GtkSelectionData = OPAQUE_PTR
_GtkWindowGroup = OPAQUE_PTR
_GtkAccelLabel = OPAQUE_PTR
_GtkAdjustment = OPAQUE_PTR
_JSGlobalContext = OPAQUE_PTR
_GApplication = OPAQUE_PTR
_GFileMonitor = OPAQUE_PTR
_PangoLogAttr = OPAQUE_PTR
_GString = OPAQUE_PTR
_GFileAttributeMatcher = OPAQUE_PTR
_PangoContext = OPAQUE_PTR
_WebKitHitTestResult = OPAQUE_PTR
_WebKitWebSettings = OPAQUE_PTR
_GBoxed = OPAQUE_PTR
_GtkPathPriorityType = OPAQUE_PTR
_JSClass = OPAQUE_PTR
_WebKitWebHistoryItem = OPAQUE_PTR
_JSValue = OPAQUE_PTR
_GdkPoint = OPAQUE_PTR
_GAppInfo = OPAQUE_PTR
_GtkSettings = OPAQUE_PTR
_GSource = OPAQUE_PTR
_PangoFontMap = OPAQUE_PTR
_GIOStream = OPAQUE_PTR
_GIOStream = OPAQUE_PTR
_JSString = OPAQUE_PTR
_PangoAttrList = OPAQUE_PTR
_GOutputStream = OPAQUE_PTR
_PangoMatrix = OPAQUE_PTR
_GSource = OPAQUE_PTR
_GtkMisc = OPAQUE_PTR
_GtkApplication = OPAQUE_PTR
_GFileInfo = OPAQUE_PTR
_PangoAnalysis = OPAQUE_PTR
_GEmblemedIcon = OPAQUE_PTR
_PangoFontDescription = OPAQUE_PTR
_GdkCursor = OPAQUE_PTR
_GtkBorder = OPAQUE_PTR
_WebKitWebInspector = OPAQUE_PTR
_GdkWindowAttr = OPAQUE_PTR
_GOptionGroup = OPAQUE_PTR
_GScanner = OPAQUE_PTR
_GFileAttributeInfoList = OPAQUE_PTR
_GCancellable = OPAQUE_PTR
_GtkWidgetClass = OPAQUE_PTR
_GtkContainerClass = OPAQUE_PTR
_GdkEventKey = OPAQUE_PTR
_GtkAdjustment = OPAQUE_PTR
_GdkDragContext = OPAQUE_PTR
_GdkDisplay = OPAQUE_PTR
_GFileIOStream = OPAQUE_PTR
_GtkSettings = OPAQUE_PTR
_GdkScreen = OPAQUE_PTR
_PangoFontMetrics = OPAQUE_PTR
_GCond = OPAQUE_PTR
_GtkIconSource = OPAQUE_PTR
_cairo_surface_t = OPAQUE_PTR
_GdkVisual = OPAQUE_PTR
_PangoFontMap = OPAQUE_PTR
_GSList = OPAQUE_PTR
_WebKitWebFrame = OPAQUE_PTR
_JSString = OPAQUE_PTR
_GActionGroup = OPAQUE_PTR
_cairo_region_t = OPAQUE_PTR
_GtkScrolledWindow = OPAQUE_PTR
_WebKitNetworkRequest = OPAQUE_PTR
_GdkWindow = OPAQUE_PTR
_PangoFontFamily = OPAQUE_PTR
_JSContextGroup = OPAQUE_PTR
_GFile = OPAQUE_PTR
_PangoLayoutIter = OPAQUE_PTR
_GtkClipboard = OPAQUE_PTR
_PangoLayoutRun = OPAQUE_PTR
_GFileInputStream = OPAQUE_PTR
_PangoFontset = OPAQUE_PTR
_GdkWindow = OPAQUE_PTR
_PangoFontDescription = OPAQUE_PTR
_GtkBorder = OPAQUE_PTR
_JSPropertyNameArray = OPAQUE_PTR
_GError = OPAQUE_PTR
_PangoCoverage = OPAQUE_PTR
_GtkAboutDialog = OPAQUE_PTR
_WebKitViewportAttributes = OPAQUE_PTR
_JSClass = OPAQUE_PTR
_WebKitWebHistoryItem = OPAQUE_PTR
_PangoFontFamily = OPAQUE_PTR
_cairo_t = OPAQUE_PTR
_GWeakRef = OPAQUE_PTR
_GdkPixbufAnimationIter = OPAQUE_PTR
_GdkVisual = OPAQUE_PTR
_GdkEventButton = OPAQUE_PTR
_GCancellable = OPAQUE_PTR
_CairoPattern = OPAQUE_PTR
_GdkDevice = OPAQUE_PTR
_GMount = OPAQUE_PTR
_PangoRectangle = OPAQUE_PTR
_GtkAccelGroup = OPAQUE_PTR
_GObject = OPAQUE_PTR
_GPollFD = OPAQUE_PTR
_GtkIconSource = OPAQUE_PTR
_GFile = OPAQUE_PTR
_JSContext = OPAQUE_PTR
_GDrive = OPAQUE_PTR
_PangoFontsetSimple = OPAQUE_PTR
_GtkAllocation = OPAQUE_PTR
_GtkWidget = OPAQUE_PTR
_PangoLayoutLine = OPAQUE_PTR
_GtkIconSet = OPAQUE_PTR
_WebKitWebView = OPAQUE_PTR
_GMutex = OPAQUE_PTR
_PangoTabArray = OPAQUE_PTR
_GtkStyleContext = OPAQUE_PTR
_GValue = OPAQUE_PTR
_GdkDeviceManager = OPAQUE_PTR
_GtkStatusbar = OPAQUE_PTR
_GdkCursor = OPAQUE_PTR
_WebKitDOMDocument = OPAQUE_PTR
_PangoMatrix = OPAQUE_PTR
_GtkPrintOperation = OPAQUE_PTR
_GtkThemingEngine = OPAQUE_PTR
_GString = OPAQUE_PTR
_PangoContext = OPAQUE_PTR
_GFileInfo = OPAQUE_PTR
_GList = OPAQUE_PTR
_WebKitWebView = OPAQUE_PTR
_WebKitWebWindowFeatures = OPAQUE_PTR
_PangoCoverage = OPAQUE_PTR
_GParamSpec = OPAQUE_PTR
_GList = OPAQUE_PTR
_GdkRGBA = OPAQUE_PTR
_GTimeVal = OPAQUE_PTR
_GtkInvisible = OPAQUE_PTR
_GSourceFuncs = OPAQUE_PTR
_JSPropertyNameAccumulator = OPAQUE_PTR
_PangoGlyphString = OPAQUE_PTR
_JSGlobalContext = OPAQUE_PTR
_GFileIOStream = OPAQUE_PTR
_WebKitSecurityOrigin = OPAQUE_PTR
_GObjectClass = OPAQUE_PTR
_GSList = OPAQUE_PTR
_PangoAnalysis = OPAQUE_PTR
_GtkStylePropertyParser = OPAQUE_PTR
_GdkWindowAttr = OPAQUE_PTR
_SoupMessage = OPAQUE_PTR
_WebKitWebDataSource = OPAQUE_PTR
_GdkColor = OPAQUE_PTR
_GdkPixbufAnimation = OPAQUE_PTR
_GEmblem = OPAQUE_PTR
_GdkRectangle = OPAQUE_PTR
_PangoLanguage = OPAQUE_PTR
_PangoAttrList = OPAQUE_PTR
_gunichar = OPAQUE_PTR
_GVolume = OPAQUE_PTR
_GdkWMDecoration = OPAQUE_PTR
_PangoLogAttr = OPAQUE_PTR
_PangoLayout = OPAQUE_PTR
_GPollFD = OPAQUE_PTR
_GFileOutputStream = OPAQUE_PTR
_JSObject = OPAQUE_PTR
_WebKitDOMNode = OPAQUE_PTR
_GInputStream = OPAQUE_PTR
_GtkStyleProperties = OPAQUE_PTR
_WebKitWebNavigationAction = OPAQUE_PTR
_GtkStyle = OPAQUE_PTR
_GParameter = OPAQUE_PTR
_GtkStyle = OPAQUE_PTR
_GIcon = OPAQUE_PTR
_GtkWindow = OPAQUE_PTR
_GtkGradient = OPAQUE_PTR
_cairo_pattern_t = OPAQUE_PTR
_GdkPixbuf = OPAQUE_PTR
_GdkScreen = OPAQUE_PTR
_GMountOperation = OPAQUE_PTR
_GtkWidgetPath = OPAQUE_PTR
_JSPropertyNameArray = OPAQUE_PTR
_GSourceCallbackFuncs = OPAQUE_PTR
_PangoFontFace = OPAQUE_PTR
_GtkTargetEntry = OPAQUE_PTR
_GtkApplication = OPAQUE_PTR
_CairoPattern = OPAQUE_PTR
_GByteArray = OPAQUE_PTR
_GdkPixbufSimpleAnim = OPAQUE_PTR
_JSObject = OPAQUE_PTR
_WebKitGeolocationPolicyDecision = OPAQUE_PTR
_PangoLanguage = OPAQUE_PTR
_GdkDevice = OPAQUE_PTR
_PangoTabArray = OPAQUE_PTR
"""Enumerations"""
GdkWindowType = c_int
GdkWindowWindowClass = c_int
GdkWindowHints = c_int
GdkGravity = c_int
GdkWindowEdgeh = c_int
GdkWindowTypeHint = c_int
GdkWindowAttributesType = c_int
GdkFilterReturn = c_int
GdkModifierType = c_int
GdkWMDecoration = c_int
GdkWMFunction = c_int
GdkCursorType = c_int
GdkPixbufError = c_int
GdkColorspace = c_int
GdkPixbufAlphaMode = c_int
GdkVisualType = c_int
GdkByteOrder = c_int
GdkInputSource = c_int
GdkInputMode = c_int
GdkAxisUse = c_int
GdkDeviceType = c_int
GdkGrabOwnership = c_int
GtkIconSize = c_int
PangoStyle = c_int
PangoWeight = c_int
PangoVariant = c_int
PangoStretch = c_int
PangoFontMask = c_int
GtkWidgetHelpType = c_int
GtkTextDirection = c_int
GtkSizeRequestMode = c_int
GtkAlign = c_int
GtkRcFlags = c_int
GtkRcTokenType = c_int
PangoWrapMode = c_int
PangoEllipsizeMode = c_int
PangoAlignment = c_int
cairo_extend_t = c_int
cairo_filter_t = c_int
CairoPatternype_t = c_int
WebKitLoadStatus = c_int
WebKitNavigationResponse = c_int
WebKitWebViewTargetInfo = c_int
WebKitWebViewViewMode = c_int
WebKitEditingBehavior = c_int
GdkInputSource = c_int
GdkInputMode = c_int
GdkAxisUse = c_int
GdkDeviceType = c_int
GdkGrabOwnership = c_int
GApplicationFlags = c_int
GtkDialogFlags = c_int
GtkResponseType = c_int
WebKitWebNavigationReason = c_int
PangoWrapMode = c_int
PangoEllipsizeMode = c_int
PangoAlignment = c_int
GMountMountFlags = c_int
GMountUnmountFlags = c_int
GDriveStartFlags = c_int
GDriveStartStopType = c_int
cairo_extend_t = c_int
cairo_filter_t = c_int
CairoPatternype_t = c_int
GdkPixbufError = c_int
GdkColorspace = c_int
GdkPixbufAlphaMode = c_int
GtkLicense = c_int
GtkIconSize = c_int
GDriveStartFlags = c_int
GDriveStartStopType = c_int

try:
    libjavascriptcore.JSGlobalContextRelease.restype = None
    libjavascriptcore.JSGlobalContextRelease.argtypes = [_JSContext,_JSGlobalContext]
except:
   pass
try:
    libjavascriptcore.JSContextGroupRelease.restype = None
    libjavascriptcore.JSContextGroupRelease.argtypes = [_JSContext,_JSContextGroup]
except:
   pass
try:
    libjavascriptcore.JSContextGetGroup.restype = _JSContextGroup
    libjavascriptcore.JSContextGetGroup.argtypes = [_JSContext]
except:
   pass
try:
    libjavascriptcore.JSContextGetGlobalObject.restype = _JSObject
    libjavascriptcore.JSContextGetGlobalObject.argtypes = [_JSContext]
except:
   pass
try:
    libjavascriptcore.JSGlobalContextCreate.restype = _JSGlobalContext
    libjavascriptcore.JSGlobalContextCreate.argtypes = [_JSClass]
except:
   pass
try:
    libjavascriptcore.JSGlobalContextCreateInGroup.restype = _JSGlobalContext
    libjavascriptcore.JSGlobalContextCreateInGroup.argtypes = [_JSContextGroup,_JSClass]
except:
   pass
try:
    libjavascriptcore.JSContextGroupRetain.restype = _JSContextGroup
    libjavascriptcore.JSContextGroupRetain.argtypes = [_JSContextGroup]
except:
   pass
try:
    libjavascriptcore.JSGlobalContextRetain.restype = _JSGlobalContext
    libjavascriptcore.JSGlobalContextRetain.argtypes = [_JSGlobalContext]
except:
   pass
from . import javascriptcore__JSObject

import weakref

class JSContext( javascriptcore__JSObject.JSObject):
    """Class JSContext Constructors"""

    """Methods"""
    def JSGlobalContextRelease(  self, ctx, ):
        if ctx: ctx = ctx._object()
        else: ctx = OPAQUE_PTR()

        libjavascriptcore.JSGlobalContextRelease( self._object(),ctx )

    def GroupRelease(  self, group, ):
        if group: group = group._object()
        else: group = OPAQUE_PTR()

        libjavascriptcore.JSContextGroupRelease( self._object(),group )

    def GetGroup(  self, ):

        from .javascriptcore import JSContextGroup
        return JSContextGroup( obj=libjavascriptcore.JSContextGetGroup( self._object() )  or OPAQUE_PTR())

    def GetGlobalObject(  self, ):

        from .javascriptcore import JSObject
        return JSObject( obj=libjavascriptcore.JSContextGetGlobalObject( self._object() )  or OPAQUE_PTR())

    @staticmethod
    def JSGlobalContextCreate( globalObjectClass,):
        if globalObjectClass: globalObjectClass = globalObjectClass._object()
        else: globalObjectClass = OPAQUE_PTR()
        from .javascriptcore import JSGlobalContext
        return JSGlobalContext( obj=    libjavascriptcore.JSGlobalContextCreate(globalObjectClass, )
  or OPAQUE_PTR())
    @staticmethod
    def JSGlobalContextCreateInGroup( group, globalObjectClass,):
        if group: group = group._object()
        else: group = OPAQUE_PTR()
        if globalObjectClass: globalObjectClass = globalObjectClass._object()
        else: globalObjectClass = OPAQUE_PTR()
        from .javascriptcore import JSGlobalContext
        return JSGlobalContext( obj=    libjavascriptcore.JSGlobalContextCreateInGroup(group, globalObjectClass, )
  or OPAQUE_PTR())
    @staticmethod
    def GroupRetain( group,):
        if group: group = group._object()
        else: group = OPAQUE_PTR()
        from .javascriptcore import JSContextGroup
        return JSContextGroup( obj=    libjavascriptcore.JSContextGroupRetain(group, )
  or OPAQUE_PTR())
    @staticmethod
    def JSGlobalContextRetain( ctx,):
        if ctx: ctx = ctx._object()
        else: ctx = OPAQUE_PTR()
        from .javascriptcore import JSGlobalContext
        return JSGlobalContext( obj = libjavascriptcore.JSGlobalContextRetain(ctx, )
  or OPAQUE_PTR())

    def __init__(self, obj = None):
        javascriptcore__JSObject.JSObject.__init__(self, obj, None)
        self._global = None

    def GetGlobalObject(  self, ):
       if not self._global:
           from .javascriptcore import JSObject
           self._global = JSObject( obj=libjavascriptcore.JSContextGetGlobalObject( self._object() ), context = self)
       return self._global

    def get_jsobject(context, name , can_call=False):
        from .javascript import strid, JavascriptClass, JSString, JSFunction
        ident = strid(context)
        import logging
        retval = JavascriptClass._globalobjects.get(ident + name)

        if retval is None:
            names = name.split('.')
            obj = JSContext.GetGlobalObject(context)
            import logging
            for n in names:
                text = JSString.CreateWithUTF8CString( n )
                obj = obj.GetProperty( text, NULL)
                text.Release()
                if not obj:
                    break
            if obj:
                valtype = obj.GetType( context )
                if valtype == kJSTypeObject.value:
                    retval = obj.ToObject( context, NULL )
                    can_call = retval.IsFunction(context)
                    if can_call:
                        retval = JSFunction( context, obj = retval, thisobj = None, name = name)
                elif valtype == kJSTypeNull.value or valtype == kJSTypeUndefined.value:
                    retval = None#obj.ToObject(context, NULL)
                elif valtype == kJSTypeNumber.value:
                    retval = obj.ToNumber( context, NULL )
                elif valtype == kJSTypeBoolean.value:
                    retval = obj.ToBoolean( context )
                elif valtype == kJSTypeString.value:
                    retval = obj.ToStringCopy(context, NULL )
                else:
                    logging.error("Invalid javascript value type encountered!: %d" % valtype)
                    retval = None
            if retval:
                JavascriptClass._globalobjects[ident + name] = retval
            #self._webview.execute_script("python.export_to_python(%s,'%s', %s);" % (name, name, int(can_call)))
            retval = JavascriptClass._globalobjects.get(ident + name)
            if not retval:
                raise Exception("Unknown javascript object by name %s" % name)
        JavascriptClass._globalobjects[ident + name] = retval
        return retval


from pathlib import Path
from typing import List

import cv2
import numpy as np
import torch
from PIL import Image
from torchvision.transforms import ToTensor

from datasets.interop import pascal_parts_colors
from datasets.interop import pascal_texture_planes
from utils.augmentation import MyRandomAffine
from utils.dataset_common import mask_to_torch
from utils.dataset_common import seg_to_image
from utils.visibility import car_planes_visibility
from datasets.dataset_stick import StickDataset

def get_planes(image: np.ndarray, meta, pascal_class: str):
    src_kpoint_dict = meta['kpoints_2d']
    az = meta['vpoint'][0]
    h, w = image.shape[:2]
    visible_planes = car_planes_visibility(pascal_class, int(az))

    planes = []
    kpoints_planes = []
    visibilities = []
    for pl_name in pascal_texture_planes[pascal_class].keys():

        pl_kp_names = pascal_texture_planes[pascal_class][pl_name]

        src_p2d = np.asarray(
            [list(map(float, src_kpoint_dict[k])) for k in pl_kp_names])
        src_p2d = np.int32(src_p2d * w)

        src_mask = cv2.fillPoly(np.zeros_like(image), [src_p2d],
                                color=(1, 1, 1))
        src_to_warp = image * src_mask

        planes.append(src_to_warp)
        kpoints_planes.append(src_p2d)
        visibilities.append(pl_name in visible_planes)

    return np.stack(planes, 0), kpoints_planes, np.stack(visibilities).astype(np.uint8)

def warp_unwarp_planes(src_planes: np.ndarray, src_planes_kpoints: List[np.ndarray], dst_planes_kpoints: List[np.ndarray],
                       src_visibilities: np.ndarray, dst_visibilities: np.ndarray, pascal_class: str):
    h, w = src_planes[0].shape[0:2]
    planes_warped = np.zeros_like(src_planes, dtype=src_planes.dtype)
    planes_unwarped = np.zeros_like(src_planes, dtype=src_planes.dtype)

    keys = list(pascal_texture_planes[pascal_class].keys())
    symmetry_set = [keys.index('left'), keys.index('right')]

    for i, pl_name in enumerate(keys):
        if not src_visibilities[i]:
            continue
        elif not dst_visibilities[i] and i not in symmetry_set:
            continue

        src_plane = src_planes[i]
        src_kpoints_plane = src_planes_kpoints[i]
        j = i
        if i in symmetry_set and not dst_visibilities[i]:
            j = symmetry_set[0] if i == symmetry_set[1] else symmetry_set[1]

        dst_kpoints_plane = dst_planes_kpoints[j]
        H12, _ = cv2.findHomography(src_kpoints_plane, dst_kpoints_plane)
        H21, _ = cv2.findHomography(dst_kpoints_plane, src_kpoints_plane)

        if H12 is not None and H21 is not None:
            src_warped = cv2.warpPerspective(src_plane, H12, dsize=(h, w))
            src_unwarped = cv2.warpPerspective(src_warped, H21, dsize=(h, w))
            if TextureDatasetWithNormal.is_valid(src_warped, pascal_class) and TextureDatasetWithNormal.is_valid(src_unwarped, pascal_class):
                planes_warped[j] = src_warped
                planes_unwarped[i] = src_unwarped

    return planes_warped, planes_unwarped

class TextureDatasetWithNormal(StickDataset):
    def __init__(self, folder: Path, ext: str='*.png', resize_factor: float=1.0,
                 demo_mode: bool=False, do_augmentation: bool=False,
                 use_LAB: bool=True, use_parts: bool=True,
                 quantize_central: bool=False):
        super(TextureDatasetWithNormal, self).__init__(folder, ext,
                                                       resize_factor,
                                                       demo_mode=demo_mode,
                                                       do_augmentation=do_augmentation,
                                                       use_LAB=use_LAB)

        self.quantize_central = quantize_central
        self.use_parts = use_parts

    def __getitem__(self, idx):
        return self.prepare_example(image=self.data[self.mode + '_images'][idx],
                                    image_stick=self.data[self.mode + '_sticks'][idx],
                                    image_meta=self.data[self.mode + '_meta'][idx],
                                    image_normal=self.data[self.mode + '_normal'][idx],
                                    image_part=self.data[self.mode + '_part'][idx],)

    def _load_data(self):
        # Images are loaded only if both normal and part files are found
        train_normal_names = set([p.name for p in self.folder.joinpath('normal_train').glob(self.ext)])
        test_normal_names = set([p.name for p in self.folder.joinpath('normal_test').glob(self.ext)])

        train_part_names = set([p.name for p in self.folder.joinpath('part_train').glob(self.ext)])
        test_part_names = set([p.name for p in self.folder.joinpath('part_test').glob(self.ext)])

        train_names = sorted(list(train_normal_names.intersection(train_part_names)))
        test_names = sorted(list(test_normal_names.intersection(test_part_names)))

        train_normal_paths = sorted([self.folder.joinpath('normal_train', n) for n in train_names])
        test_normal_paths = sorted([self.folder.joinpath('normal_test', n) for n in test_names])

        train_part_paths = sorted([self.folder.joinpath('part_train', n) for n in train_names])
        test_part_paths = sorted([self.folder.joinpath('part_test', n) for n in test_names])

        train_stick_paths = sorted([self.folder.joinpath('stick_train', n) for n in train_names])
        test_stick_paths = sorted([self.folder.joinpath('stick_test', n) for n in test_names])

        train_image_paths = sorted([self.folder.joinpath('train', n) for n in train_names])
        test_image_paths = sorted([self.folder.joinpath('test', n) for n in test_names])

        train_meta_paths = sorted([self.folder.joinpath('meta_train', Path(n).stem + '.yaml') for n in train_names])
        test_meta_paths = sorted([self.folder.joinpath('meta_test', Path(n).stem + '.yaml') for n in test_names])

        if self.demo_mode:
            top_n = 100
            train_normal_paths = train_normal_paths[:top_n]
            test_normal_paths = test_normal_paths[:top_n]
            train_part_paths = train_part_paths[:top_n]
            test_part_paths = test_part_paths[:top_n]
            test_stick_paths = test_stick_paths[:top_n]
            train_stick_paths = train_stick_paths[:top_n]
            train_image_paths = train_image_paths[:top_n]
            test_image_paths = test_image_paths[:top_n]
            train_meta_paths = train_meta_paths[:top_n]
            test_meta_paths = test_meta_paths[:top_n]

        return {
            'train_normal': [self._preprocess(cv2.imread(str(f))) for f in train_normal_paths],
            'eval_normal': [self._preprocess(cv2.imread(str(f))) for f in test_normal_paths],
            'train_part': [self._preprocess(cv2.imread(str(f), cv2.IMREAD_UNCHANGED), interp=cv2.INTER_NEAREST) for f in train_part_paths],
            'eval_part': [self._preprocess(cv2.imread(str(f), cv2.IMREAD_UNCHANGED), interp=cv2.INTER_NEAREST) for f in test_part_paths],
            'train_images': [self._preprocess(cv2.imread(str(f))) for f in train_image_paths],
            'eval_images': [self._preprocess(cv2.imread(str(f))) for f in test_image_paths],
            'train_sticks': [self._preprocess(cv2.imread(str(f))) for f in train_stick_paths],
            'eval_sticks': [self._preprocess(cv2.imread(str(f))) for f in test_stick_paths],
            'train_meta': [self._load_metadata(f) for f in train_meta_paths],
            'eval_meta': [self._load_metadata(f) for f in test_meta_paths]
        }

    @staticmethod
    def quantization(img):
        Z = img.reshape((-1, 3))
        # convert to np.float32
        Z = np.float32(Z)
        # define criteria, number of clusters(K) and apply kmeans()
        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
        K = 2
        ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

        # Now convert back into uint8, and make original image
        center = np.uint8(center)
        res = center[label.flatten()]
        res2 = res.reshape((img.shape))
        return res2

    def prepare_example(self, image, image_stick, image_meta, image_normal, image_part):

        src_image = image
        h, w = src_image.shape[:2]
        assert h == w
        offset = int(w * 0.1)
        pascal_class = self.dataset_meta['pascal_class']

        src_meta = image_meta
        src_stick = image_stick
        src_normal = image_normal
        src_part = image_part
        if self.use_parts:
            src_part = seg_to_image(image_part, pascal_parts_colors[pascal_class])
        src_log_image = src_image.copy()
        src_central_crop = src_image[h//2 - offset:h//2 + offset, w//2 - offset:w//2 + offset].copy()
        src_central_crop = cv2.resize(src_central_crop, (w, h))
        if self.quantize_central:
            src_central_crop = self.quantization(src_central_crop)
            values, counts = np.unique(src_central_crop.reshape(-1, 3), return_counts=True, axis=0)
            src_central_crop = np.ones_like(src_central_crop) * values[np.argmax(counts)]

        dst_idx = np.random.randint(len(self))
        dst_image = self.data[self.mode + '_images'][dst_idx]
        dst_meta = self.data[self.mode + '_meta'][dst_idx]
        dst_stick = self.data[self.mode + '_sticks'][dst_idx]
        dst_normal = self.data[self.mode + '_normal'][dst_idx]
        dst_part = self.data[self.mode + '_part'][dst_idx]
        if self.use_parts:
            dst_part = seg_to_image(dst_part, pascal_parts_colors[pascal_class])
        dst_log_image = dst_image.copy()
        dst_central_crop = dst_image[h//2 - offset:h//2 + offset, w//2 - offset:w//2 + offset].copy()
        dst_central_crop = cv2.resize(dst_central_crop, (w, h))
        if self.quantize_central:
            dst_central_crop = self.quantization(dst_central_crop)
            values, counts = np.unique(dst_central_crop.reshape(-1, 3), return_counts=True, axis=0)
            dst_central_crop = np.ones_like(dst_central_crop) * values[np.argmax(counts)]

        src_planes, src_kpoints_planes, src_visibilities = get_planes(src_image, src_meta, pascal_class)
        dst_planes, dst_kpoints_planes, dst_visibilities = get_planes(dst_image, dst_meta, pascal_class)
        planes_warped, planes_unwarped = warp_unwarp_planes(src_planes, src_kpoints_planes, dst_kpoints_planes,
                                                            src_visibilities, dst_visibilities, pascal_class)

        # Compute masks for both src and dst images
        bg_thresh = 20
        bg_color = 255
        src_image_masked = src_image.copy()
        src_bg_mask = np.all(src_normal <= bg_thresh, axis=-1)
        src_bg_mask = np.tile(src_bg_mask[..., np.newaxis], [1, 1, 3])
        src_image_masked[src_bg_mask] = bg_color

        dst_image_masked = dst_image.copy()
        dst_bg_mask = np.all(dst_normal <= bg_thresh, axis=-1)
        dst_bg_mask = np.tile(dst_bg_mask[..., np.newaxis], [1, 1, 3])
        dst_image_masked[dst_bg_mask] = bg_color

        src_fg_mask = np.bitwise_not(src_bg_mask).astype(np.uint8)
        dst_fg_mask = np.bitwise_not(dst_bg_mask).astype(np.uint8)

        # Data augmentation: all images and planes undergo the same warp
        if self.do_augmentation:
            affine = MyRandomAffine(degrees=10, translate=(0.1, 0.1),
                                    fillcolor=(0, 0, 0), shear=10,
                                    resample=Image.BICUBIC)
            affine.sample_params(w=w, h=h)

            src_planes = affine(*src_planes)
            planes_unwarped = affine(*planes_unwarped)
            src_normal = affine(src_normal)
            src_part = affine(src_part)
            src_image = affine(src_image)
            src_stick = affine(src_stick)
            src_image_masked = affine(src_image_masked,
                                      fillcolor=(255, 255, 255))
            src_fg_mask = affine(src_fg_mask)

        # Compute masks for customizing losses
        kernel = np.ones((15, 15), np.uint8)
        src_inner_mask = cv2.erode(src_fg_mask, kernel)
        src_border_mask = cv2.dilate(src_fg_mask - src_inner_mask,
                                     np.ones((5, 5), np.uint8))
        src_inner_mask = mask_to_torch(src_inner_mask)
        src_border_mask = mask_to_torch(src_border_mask)
        dst_inner_mask = cv2.erode(dst_fg_mask, kernel)
        dst_inner_mask = mask_to_torch(dst_inner_mask)

        # Achtung! Make sure the same normalization is used for training
        planes_unwarped = self.planes_to_torch(planes_unwarped, to_LAB=self.use_LAB)
        planes_warped = self.planes_to_torch(planes_warped, to_LAB=self.use_LAB)
        src_planes = self.planes_to_torch(src_planes, to_LAB=self.use_LAB)

        src_stick = self.to_torch(src_stick, to_LAB=self.use_LAB)
        src_image = self.to_torch(src_image, to_LAB=self.use_LAB)
        src_normal = self.to_torch(src_normal, to_LAB=self.use_LAB)
        src_part = self.to_torch(src_part, to_LAB=self.use_LAB)
        src_log_image = self.to_torch(src_log_image, to_LAB=self.use_LAB)
        src_central_crop = self.to_torch(src_central_crop, to_LAB=self.use_LAB)
        dst_image = self.to_torch(dst_image, to_LAB=self.use_LAB)
        dst_stick = self.to_torch(dst_stick, to_LAB=self.use_LAB)
        dst_normal = self.to_torch(dst_normal, to_LAB=self.use_LAB)
        dst_part = self.to_torch(dst_part, to_LAB=self.use_LAB)
        src_image_masked = self.to_torch(src_image_masked, to_LAB=self.use_LAB)
        dst_image_masked = self.to_torch(dst_image_masked, to_LAB=self.use_LAB)
        dst_log_image = self.to_torch(dst_log_image, to_LAB=self.use_LAB)
        dst_central_crop = self.to_torch(dst_central_crop, to_LAB=self.use_LAB)

        # Cross-Entropy Target
        dst_cycle = self.data[self.mode + '_part'][dst_idx]
        dst_cycle = torch.LongTensor(dst_cycle)
        return {
            'src_kpoints_planes': src_kpoints_planes,
            'dst_kpoints_planes': dst_kpoints_planes,
            'src_vs': src_visibilities,
            'dst_vs': dst_visibilities,
            'src_normal': src_normal,
            'dst_normal': dst_normal,
            'src_part': src_part,
            'dst_part': dst_part,
            'src_part_raw': image_part,  # todo: only for augment_pascal.py
            'dst_cycle': dst_cycle,
            'planes': src_planes,  # Texture planes
            'planes_warped': planes_warped,  # Texture planes
            'planes_unwarped': planes_unwarped,  # Texture planes
            'src_image': src_image,  # source image
            'dst_image': dst_image,  # Destination image
            'src_stick': src_stick,
            'dst_stick': dst_stick,
            'image_meta': src_meta,  # for compatibility with StickDataset
            'src_meta': src_meta,
            'dst_meta': dst_meta,
            'src_image_masked': src_image_masked,
            'dst_image_masked': dst_image_masked,
            'src_inner_mask': src_inner_mask,
            'dst_inner_mask': dst_inner_mask,
            'src_border_mask': src_border_mask,
            'dst_log_image': dst_log_image,
            'src_log_image': src_log_image,
            'src_central': src_central_crop,
            'dst_central': dst_central_crop,
        }

    def to_torch(self, x: np.ndarray, to_LAB: bool):
        """
        Convert a BGR image in 0..255 to a pytorch LAB Tensor in range -1..1
        """
        if to_LAB:
            x = cv2.cvtColor(x, cv2.COLOR_BGR2LAB)
        x = Image.fromarray(x)
        return self.normalizer(ToTensor()(x))

    @staticmethod
    def is_valid(warped_image: np.ndarray, pascal_class: str):
        if pascal_class == 'car':
            error = np.any(warped_image[10, :]) or np.any(warped_image[-10, :])
        else:
            error = np.any(warped_image[:, 10]) or np.any(warped_image[:, -10])

        return not error

    @staticmethod
    def planes_to_torch(planes, to_LAB: bool):
        planes = [p for p in planes]
        if to_LAB:
            planes = [cv2.cvtColor(p, cv2.COLOR_BGR2LAB) for p in planes]
        planes = np.stack(planes)
        planes = np.float32(planes) / 255.
        planes = np.transpose(planes, (0, 3, 1, 2))
        planes = (torch.from_numpy(planes) - 0.5) / 0.5
        return planes