import copy
from enum import Enum
import math

import numpy as np
import torch
from torch import Tensor, eye, nn
# from torch import Tensor, eye, manual_seed, nn, no_grad, optim

# from graph_deep_decoder.graph_clustering import Ups

# Constants for Upsampling Type
class Ups(Enum):
    NONE = 0
    LI = 1          # Linear Interpolation
    U_MAT = 2       # Directly applies matrix U
    U_MEAN = 3     # Applies matrix U and compute the 1 hop mean
    U_LM = 4        # Learning Mean 1 hope
    GF = 5          # Applies U and then learn a Graph Filter
    NVGF = 6        # Applies U and then learn a NodeVarian-GF

# Error messages
ERR_DIFF_N_LAYERS = 'Length of the nodes and features vector must be the same'
ERR_A_NON_SYM = 'Matrix A for upsampling should be symmetric'
ERR_WRONG_INPUT_SIZE = 'Number of input samples must be 1'
ERR_UNK_UPS = 'Unkown upsampling type {}'
ERR_NO_UPS = 'Upsampling is None but layers have different sizes'

class GraphDecoder(nn.Module):
    """
    This class represent a basic graph decoder with only one layer following
    the model G(C) = ReLU(HC)v, where instead of upsampling a fixed
    low pass graph filter is used.
    """
    def __init__(self, features, H, scale_std=0.01, device='cpu'):
        """
        The arguments are:
        - features: the number of features
        - H: fixed graph filter
        - scale_std: scale the std of the learnable weights initialization
        """
        super().__init__()
        N = H.shape[0]
        self.input = Tensor(H).view([1, N, N]).to(device)
        self.v = torch.ones(features)/math.sqrt(features)
        self.v[math.ceil(features/2):] *= -1
        self.v = self.v.to(device)
        self.conv = nn.Conv1d(N, features, kernel_size=1,
                              bias=False)
        std = scale_std/math.sqrt(N)
        self.conv.weight.data.normal_(0, std)
        self.relu = torch.nn.ReLU()
        self.conv.to(device)

    def forward(self, input):
        return self.relu(self.conv(input)).squeeze().t().mv(self.v)

    def analytical_squared_jacobian(self):
        """
        Return its squared Jacobian computed analitically
        """
        U = self.input.numpy().squeeze()
        C = self.conv.weight.data.numpy().squeeze().T
        diag_v = np.diag(self.v.numpy().squeeze())
        return (U.dot(C) > 0).dot(diag_v**2).dot((U.dot(C) > 0).T)*(U.dot(U.T))

    def autograd_squared_jacobian(self):
        """
        Return its squared Jacobian computed using autograd
        """
        dec_copy = copy.deepcopy(self)
        y = dec_copy(dec_copy.input)
        outs = torch.eye(y.shape[0])

        jac = []
        for out in outs:
            y = dec_copy(dec_copy.input)
            dec_copy.zero_grad()
            y.backward(out[:])
            allgrads = np.zeros(0)
            for p in dec_copy.parameters():
                gra = p.grad.data.numpy().flatten()
                allgrads = np.append(allgrads, gra)
            jac += [allgrads]
        Jac = np.array(jac).squeeze()
        return Jac.dot(Jac.T)

    def count_params(self):
        return sum(p.numel() for p in self.model.parameters()
                   if p.requires_grad)

class GraphDeepDecoder(nn.Module):
    def __init__(self,
                 # Decoder args
                 features, nodes, Us,
                 # Ups args
                 As=None,  ups=Ups.U_MEAN,
                 gamma=0.5, K=2,
                 batch_norm=False,
                 # Activation functions
                 act_fn=nn.Tanh(), last_act_fn=nn.Tanh(),
                 input_std=0.01, w_std=0.01,
                 device='cpu'):
        assert len(features) == len(nodes), ERR_DIFF_N_LAYERS
        assert isinstance(ups, Ups) or ups is None, \
            ERR_UNK_UPS.format(ups)

        super(GraphDeepDecoder, self).__init__()
        self.model = nn.Sequential()
        self.fts = features
        self.nodes = nodes
        self.Us = Us
        self.As = As
        self.ups_type = ups
        self.kernel_size = 1
        self.gamma = gamma
        self.K = K
        self.batch_norm = batch_norm
        self.act_fn = act_fn
        self.last_act_fn = last_act_fn
        self.w_std = w_std/np.sqrt(features)
        self.dev = device
        self.build_network()

        if self.ups_type is None or self.ups_type is Ups.NONE:
            shape = [1, self.fts[0], self.nodes[-1]]
        else:
            shape = [1, self.fts[0], self.nodes[0]]
        std = input_std/np.sqrt(shape[2])
        self.input = Tensor(torch.zeros(shape)).data.normal_(0, std)
        self.input = self.input.to(device)

        self.model.to(device)

    def add_layer(self, module):
        self.model.add_module(str(len(self.model) + 1), module)

    def build_network(self):
        for l in range(len(self.fts)-1):
            conv = nn.Conv1d(self.fts[l], self.fts[l+1], self.kernel_size,
                             bias=False)
            conv.weight.data.normal_(0, self.w_std[l])
            self.add_layer(conv)

            # Check if there is upsampling in layer l
            if self.Us[l] is not None:
                A = self.As[l] if self.As else None

                if self.ups_type is Ups.LI:
                    ups = Interpolate(self.nodes[l], self.nodes[l+1], self.dev)
                elif self.ups_type is Ups.U_MAT:
                    ups = Upsampling(self.Us[l], self.dev)
                elif self.ups_type is Ups.U_MEAN:
                    ups = MeanUps(self.Us[l], A,
                                  self.gamma, self.dev)
                elif self.ups_type is Ups.U_LM:
                    ups = LearnMeanUps(self.Us[l], A,
                                       self.gamma, self.dev)
                elif self.ups_type is Ups.GF:
                    ups = GFUps(self.Us[l], A, self.K, self.dev)
                elif self.ups_type is Ups.NVGF:
                    ups = NVGFUps(self.Us[l], A, self.K, self.dev)
                else:
                    raise RuntimeError('Unknown upsampling type')

                self.add_layer(ups)

            if l < (len(self.fts)-2):
                # Not the last layer
                if self.act_fn is not None:
                    self.add_layer(self.act_fn)
                if self.batch_norm:
                    self.add_layer(nn.BatchNorm1d(self.fts[l+1]))
            else:
                # Last layer
                if self.last_act_fn is not None:
                    self.add_layer(self.last_act_fn)
        return self.model

    def forward(self, x):
        return self.model(x).T.squeeze()

    def count_params(self):
        return sum(p.numel() for p in self.model.parameters()
                   if p.requires_grad)

    def autograd_squared_jacobian(self):
        """
        Return its squared Jacobian computed using autograd
        """
        dec_copy = copy.deepcopy(self)
        y = dec_copy(dec_copy.input)
        outs = torch.eye(y.shape[0])

        jac = []
        for out in outs:
            y = dec_copy(dec_copy.input)
            dec_copy.zero_grad()

            y.backward(out[:])
            allgrads = np.zeros(0)
            for p in dec_copy.parameters():
                gra = p.grad.data.numpy().flatten()
                allgrads = np.append(allgrads, gra)
            jac += [np.array(allgrads)]

        Jac = np.array(jac).squeeze()
        return Jac.dot(Jac.T)

    def Us_norms(self):
        norms = []
        for i, layer in enumerate(self.model):
            if not isinstance(layer, Upsampling):
                continue
            norm = {'layer': i, 'norm': np.linalg.norm(layer.U_T)}
            norms.append(norm)
        return norms

    def Us_to_unit_norm(self):
        for i, layer in enumerate(self.model):
            if not isinstance(layer, Upsampling):
                continue
            layer.U_T /= np.linalg.norm(layer.U_T)

class Upsampling(nn.Module):
    # NOTE: Previous Ups.NO_A
    def __init__(self, U, device='cpu'):
        nn.Module.__init__(self)
        self.child_size = U.shape[0]
        self.parent_size = U.shape[1]
        self.U_T = Tensor(U).t().to(device)

    def forward(self, input):
        assert input.shape[0] == 1, ERR_WRONG_INPUT_SIZE
        # n_channels = input.shape[1]
        # output = input[0, :, :].mm(self.U_T)
        # return output.view([1, n_channels, self.child_size])

        return input.matmul(self.U_T)

# NOTE: Previous Ups.REG
class Interpolate(nn.Module):
    def __init__(self, child_size, parent_size):
        super(Interpolate, self).__init__()
        self.sf = parent_size/child_size

    def forward(self, input):
        assert input.shape[0] == 1, ERR_WRONG_INPUT_SIZE
        return nn.functional.interpolate(input, scale_factor=self.sf,
                                         mode='linear',
                                         align_corners=True)

class MeanUps(Upsampling):
    # NOTE: Previous Ups.BIN/WEI
    def __init__(self, U, A, gamma=0.5, device='cpu'):
        assert A is not None
        assert np.allclose(A, A.T), ERR_A_NON_SYM
        Upsampling.__init__(self, U)
        # NOTE: Not clear if it is better to normalize A!!
        if np.linalg.matrix_rank(np.diag(np.sum(A, 0))) != A.shape[0]:
            self.A = np.linalg.pinv(np.diag(np.sum(A, 0))).dot(A)
        else:
            self.A = np.linalg.inv(np.diag(np.sum(A, 0))).dot(A)
            # D_inv_sqrt = 1/np.sqrt(np.sum(A, 0))
            # self.A = D_inv_sqrt@A@D_inv_sqrt

        # self.A = A
        self.A = gamma*np.eye(A.shape[0]) + (1-gamma)*self.A
        self.A = Tensor(self.A)
        self.U_T = Tensor(U).t().mm(self.A.t()).to(device)

class LearnMeanUps(Upsampling):
    # NOTE: previous Learning Gamma
    def __init__(self, U, A, gamma_init=0.5, device='cpu'):
        assert A is not None
        assert np.allclose(A, A.T), ERR_A_NON_SYM
        Upsampling.__init__(self, U)
        self.gamma = nn.Parameter(Tensor([gamma_init])).to(device)
        self.A = Tensor(np.linalg.inv(np.diag(np.sum(A, 0))).dot(A)).to(device)

    def forward(self, input):
        assert input.shape[0] == 1, ERR_WRONG_INPUT_SIZE
        # NOTE: restrict gamma to [0,1] interval?
        n_channels = input.shape[1]
        A_gamma = self.gamma*eye(self.child_size) + (1-self.gamma)*self.A
        output = input[0, :, :].mm(self.U_T.mm(A_gamma.t()))
        return output.view([1, n_channels, self.child_size])

class GFUps(Upsampling):
    def __init__(self, U, A, K, device='cpu'):
        assert A is not None
        assert np.allclose(A, A.T), ERR_A_NON_SYM
        super(GFUps, self).__init__(U)
        N = A.shape[0]
        self.hs = nn.Parameter(torch.Tensor(K)).to(device)
        stdv = 1. / math.sqrt(K)
        self.hs.data.uniform_(-stdv, stdv)
        self.A = Tensor(A)
        self.K = K
        self.Apows = torch.zeros(K, N, N).to(device)
        for i in range(K):
            self.Apows[i, :, :] = torch.matrix_power(self.A, i)

    def forward(self, input):
        assert input.shape[0] == 1, ERR_WRONG_INPUT_SIZE
        n_channels = input.shape[1]
        H = (self.hs.view([self.K, 1, 1])*self.Apows).sum(0)
        output = input[0, :, :].mm(self.U_T.mm(H))
        return output.view([1, n_channels, self.child_size])

class NVGFUps(Upsampling):
    def __init__(self, U, A, K):
        assert A is not None
        assert np.allclose(A, A.T), ERR_A_NON_SYM
        super(NVGFUps, self).__init__(U)
        N = A.shape[0]
        self.A = Tensor(A)
        self.hs = nn.Parameter(torch.Tensor(K, N))
        # stdv = 1. / math.sqrt(K)
        # self.hs.data.uniform_(-stdv, stdv)
        self.Apows = torch.zeros(K, N, N)
        self.K = K
        for i in range(K):
            self.Apows[i, :, :] = torch.matrix_power(self.A, i)

    def forward(self, input):
        assert input.shape[0] == 1, ERR_WRONG_INPUT_SIZE
        n_channels = input.shape[1]
        H = (self.hs.view([self.K, self.child_size, 1])*self.Apows).sum(0)
        output = input[0, :, :].mm(self.U_T.mm(H.t()))
        return output.view([1, n_channels, self.child_size])


import cvzone
import cv2
from cvzone.SelfiSegmentationModule import SelfiSegmentation
import os

cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
cap.set(cv2.CAP_PROP_FPS, 60) #60FPS

segmentor = SelfiSegmentation()
fpsReader = cvzone.FPS()

listIMG = os.listdir('Resources')
imgList = []
for imgPath in listIMG:
    img = cv2.imread(f'Resources/{imgPath}')
    imgList.append(img)

indexImg = 0

while True:
    success, img = cap.read()
    imgOut = segmentor.removeBG(img, imgList[indexImg], threshold=0.8)
    #If one, then everything is out
    #Just replace imgBG with (b,g,r) color combo for simple colours

    imgStack = cvzone.stackImages([img, imgOut],2,1)
    _, imgStack = fpsReader.update(imgStack, color=(0,0,255))

    cv2.imshow('Result Combn', imgStack)
    key = cv2.waitKey(1)
    if key == ord('a'):
        if indexImg>0:
            indexImg -= 1

    elif key == ord('d'):
        if indexImg < len(imgList)-1:
            indexImg += 1

    elif key == ord('q'):
        break


#Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
from datetime import date
maior = 0
menor = 0
anoatual = date.today().year
for anonasc in range(1, 8):
    anonasc = int(input('Em que ano a {}° pessoa nasceu? '.format(anonasc)))
    if anoatual - anonasc >=18:
        maior += 1
    elif anoatual - anonasc <18:
        menor += 1
print('da lista informada, temos {} maiores de idade e {} menores de idade.'.format(maior, menor))


from rtruffle.source_section import SourceSection

from som.compiler.method_generation_context import MethodGenerationContextBase

from som.interpreter.ast.nodes.field_node import create_write_node, create_read_node
from som.interpreter.ast.nodes.global_read_node import create_global_node
from som.interpreter.ast.nodes.return_non_local_node import CatchNonLocalReturnNode

from som.vmobjects.primitive import empty_primitive
from som.vmobjects.method_ast import AstMethod

class MethodGenerationContext(MethodGenerationContextBase):
    def __init__(self, universe, holder, outer):
        MethodGenerationContextBase.__init__(self, universe, holder, outer)

        self._embedded_block_methods = []

    def add_embedded_block_method(self, block_method):
        self._embedded_block_methods.append(block_method)

    def assemble(self, method_body):
        if self._primitive:
            return empty_primitive(self.signature.get_embedded_string())

        if self.needs_to_catch_non_local_returns:
            method_body = CatchNonLocalReturnNode(
                method_body, method_body.source_section
            )

        trivial_method = method_body.create_trivial_method(self.signature)
        if trivial_method is not None:
            return trivial_method

        arg_inner_access, size_frame, size_inner = self.prepare_frame()

        return AstMethod(
            self.signature,
            method_body,
            arg_inner_access,
            size_frame,
            size_inner,
            # copy list to make it immutable for RPython
            self._embedded_block_methods[:],
            self._get_source_section_for_method(method_body),
            self.lexical_scope,
        )

    def _get_source_section_for_method(self, expr):
        src_body = expr.source_section
        assert isinstance(src_body, SourceSection)
        src_method = SourceSection(
            identifier="%s>>#%s"
            % (
                self.holder.name.get_embedded_string(),
                self.signature.get_embedded_string(),
            ),
            source_section=src_body,
        )
        return src_method

    def get_outer_self_context_level(self):
        level = 0
        ctx = self.outer_genc
        while ctx is not None:
            ctx = ctx.outer_genc
            level += 1
        return level

    def get_context_level(self, var_name):
        if var_name in self._locals or var_name in self._arguments:
            return 0
        assert self.outer_genc is not None
        return 1 + self.outer_genc.get_context_level(var_name)

    def get_variable(self, var_name):
        if var_name in self._locals:
            return self._locals[var_name]

        if var_name in self._arguments:
            return self._arguments[var_name]

        if self.outer_genc:
            outer_var = self.outer_genc.get_variable(var_name)
            if outer_var:
                self._accesses_variables_of_outer_context = True
                return outer_var
        return None

    def get_local(self, var_name):
        if var_name in self._locals:
            return self._locals[var_name]

        if self.outer_genc:
            outer_local = self.outer_genc.get_local(var_name)
            if outer_local:
                self._accesses_variables_of_outer_context = True
                return outer_local
        return None

    def get_self_read(self):
        return self.get_variable("self").get_read_node(self.get_context_level("self"))

    def get_object_field_read(self, field_name):
        if not self.has_field(field_name):
            return None
        return create_read_node(self.get_self_read(), self.get_field_index(field_name))

    def get_global_read(self, var_name):
        return create_global_node(var_name, self.universe, self, None)

    def get_object_field_write(self, field_name, exp):
        if not self.has_field(field_name):
            return None
        return create_write_node(
            self.get_self_read(), exp, self.get_field_index(field_name)
        )


import dask.array as da
import numpy as np
import pytest

from iris._lazy_data import is_lazy_masked_data

real_arrays = [
    np.arange(3),
    np.ma.array(range(3)),
    np.ma.array(range(3), mask=[0, 1, 1]),
]
lazy_arrays = [da.from_array(arr) for arr in real_arrays]

@pytest.mark.parametrize(
    "arr, expected", zip(real_arrays + lazy_arrays, [False] * 4 + [True] * 2)
)
def test_is_lazy_masked_data(arr, expected):
    result = is_lazy_masked_data(arr)
    assert result is expected


"""Place cell related functions."""

import numpy as np

from spiketools.spatial.utils import compute_nbins
from spiketools.spatial.occupancy import compute_bin_counts_pos
from spiketools.spatial.checks import check_bin_definition
from spiketools.utils.checks import check_array_orientation
from spiketools.utils.extract import (get_range, get_values_by_time_range, get_values_by_times,
                                      threshold_spikes_by_values)

###################################################################################################
###################################################################################################

def compute_place_bins(spikes, position, timestamps, bins, area_range=None,
                       speed=None, speed_threshold=None, time_threshold=None,
                       occupancy=None, orientation=None):
    """Compute the spatially binned spiking activity.

    Parameters
    ----------
    spikes : 1d array
        Spike times, in seconds.
    position : 1d or 2d array
        Position values.
    timestamps : 1d array
        Timestamps, in seconds, corresponding to the position values.
    bins : int or list of [int, int]
        The bin definition for dividing up the space. If 1d, can be integer.
        If 2d should be a list, defined as [number of x_bins, number of y_bins].
    area_range : list of list, optional
        Edges of the area to bin, defined as [[x_min, x_max], [y_min, y_max]].
    speed : 1d array, optional
        Current speed for each position.
        Should be the same length as timestamps.
    speed_threshold : float, optional
        Speed threshold to apply.
        If provided, any position values with an associated speed below this value are dropped.
    time_threshold : float, optional
        A maximum time threshold, per bin observation, to apply.
        If provided, any bin values with an associated time length above this value are dropped.
    occupancy : 1d or 2d array, optional
        Computed occupancy across the space.
        If provided, used to normalize bin counts.
    orientation : {'row', 'column'}, optional
        The orientation of the position data.
        If not provided, is inferred from the position data.

    Returns
    -------
    place_bins : 2d array
        The spike activity per spatial bin.

    Examples
    --------
    Compute spike activity across 2d spatial bins:

    >>> spikes = np.array([0.2, 0.25, 0.3, 0.38, 0.41, 0.5, 0.59, 0.77, 0.95, 0.96])
    >>> position = np.array([[0.1, 0.3, 0.35, 0.36, 0.37, 0.4, 0.45, 0.46, 0.55, 0.7],
    ...                      [1.0, 1.5, 1.55, 1.65, 1.66, 2.0, 3.0, 4.0, 5.5, 7.0]])
    >>> timestamps = np.array([0.01, 0.03, 0.2, 0.25, 0.45, 0.46, 0.47, 0.49, 0.5, 0.65])
    >>> bins = [3, 2]
    >>> compute_place_bins(spikes, position, timestamps, bins)
    array([[5, 0, 0],
           [0, 1, 4]])
    """

    if speed is not None:
        spikes = threshold_spikes_by_values(\
            spikes, timestamps, speed, speed_threshold, time_threshold)

    spike_positions = get_values_by_times(timestamps, position, spikes, time_threshold)
    place_bins = compute_bin_counts_pos(spike_positions, bins, area_range, occupancy, orientation)

    return place_bins

def compute_trial_place_bins(spikes, position, timestamps, bins, start_times, stop_times,
                             area_range=None, speed=None, speed_threshold=None, time_threshold=None,
                             trial_occupancy=None, flatten=False, orientation=None):
    """Compute the spatially binned spiking activity, across trials.

    Parameters
    ----------
    spikes : 1d array
        Spike times, in seconds.
    position : 1d or 2d array
        Position values.
    timestamps : 1d array
        Timestamps, in seconds, corresponding to the position values.
    bins : int or list of [int, int]
        The bin definition for dividing up the space. If 1d, can be integer.
        If 2d should be a list, defined as [number of x_bins, number of y_bins].
    start_times, stop_times : 1d array
        The start and stop times, in seconds, of each trial.
    area_range : list of list, optional
        Edges of the area to bin, defined as [[x_min, x_max], [y_min, y_max]].
    speed : 1d array, optional
        Current speed for each position.
        Should be the same length as timestamps.
    speed_threshold : float, optional
        Speed threshold to apply.
        If provided, any position values with an associated speed below this value are dropped.
    time_threshold : float, optional
        A maximum time threshold, per bin observation, to apply.
        If provided, any bin values with an associated time length above this value are dropped.
    trial_occupancy : 2d or 3d array, optional
        Computed occupancy across the space, across trials.
        If provided, used to normalize bin counts per trial.
    flatten : bool, optional, default: False
        Whether the flatten the spatial bins per trial. Only used if position data are 2d.
    orientation : {'row', 'column'}, optional
        The orientation of the position data.
        If not provided, is inferred from the position data.

    Returns
    -------
    place_bins_trial : 1d or 2d or 3d array
        The spike activity per spatial bin, per trial.
        If `flatten` is True, for a 2d position input, the output is 2d, as [n_trial, n_bins].
        Otherwise, for a 2d position input, the output is 3d, as [n_trials, n_ybins, n_xbins].

    Examples
    --------
    Compute spike activity, in 1d spatial bins across 2 trials:

    >>> spikes = np.array([0.15, 0.22, 0.28, 0.41, 0.50, 0.65, 0.77, 0.81, 0.95])
    >>> position = np.array([1.0, 3.5, 2.0, 1.5, 3.0, 3.5, 4.0, 5.0, 3.5, 2.5])
    >>> timestamps = np.array([0.10, 0.20, 0.25, 0.35, 0.45, 0.55, 0.6, 0.7, 0.80, 0.95])
    >>> bins = 2
    >>> start_times, stop_times = np.array([0, 0.6]), np.array([0.4, 1.0])
    >>> compute_trial_place_bins(spikes, position, timestamps, bins, start_times, stop_times)
    array([[2., 1.],
           [3., 1.]])

    Compute spike activity across trials, normalizing by trial-level occupancy:

    >>> from spiketools.spatial.occupancy import compute_trial_occupancy
    >>> trial_occ = compute_trial_occupancy(position, timestamps, bins, start_times, stop_times)
    >>> compute_trial_place_bins(spikes, position, timestamps, bins,
    ...                          start_times, stop_times, trial_occupancy=trial_occ)
    array([[10., 20.],
           [20.,  5.]])
    """

    t_occ = None
    t_speed = None

    bins = check_bin_definition(bins, position)
    orientation = check_array_orientation(position) if not orientation else orientation

    place_bins_trial = np.zeros([len(start_times), *np.flip(bins)])
    for ind, (start, stop) in enumerate(zip(start_times, stop_times)):

        t_spikes = get_range(spikes, start, stop)
        t_times, t_pos = get_values_by_time_range(timestamps, position, start, stop)
        if speed is not None:
            _, t_speed = get_values_by_time_range(timestamps, speed, start, stop)

        if trial_occupancy is not None:
            t_occ = trial_occupancy[ind, :]

        place_bins_trial[ind, :] = compute_place_bins(t_spikes, t_pos, t_times, bins, area_range,
                                                      t_speed, speed_threshold, time_threshold,
                                                      t_occ, orientation)

    if flatten:
        place_bins_trial = np.reshape(place_bins_trial, [len(start_times), compute_nbins(bins)])

    return place_bins_trial


from board import *

def hill_climbing(board):
    start_time = time.time()
    i = 0
    optimum = (len(board) - 1) * len(board) / 2
    # Main Loop
    # Breaks if:
    # 1. reached iteration limit
    # 2. local maximum reached
    # 3. optimum is reached.

    while evaluate_state(board) != optimum:
        i += 1
        if i == 10000:  # Give up after 1000 tries. (very unreasonable time :D)
            break
        # Bestneighbour starts off as current state
        bestneighbour = board.copy()

        # Loop to find best neighbour state of current
        for column, row in enumerate(board):
            # A neighbour state is a state where a single queen differs in location
            # A queen can either go up or down on a board (unless at edge, while statement checks this)
            upboard = board.copy()   # Possible neighbours where a queen in "column" moves up
            downboard = board.copy() # Possible neighbours where a queen in "column" moves down

            # Move queen downwards and check if state is better or equal
            while downboard[column]+1 < len(board)-1:
                downboard[column] = downboard[column] + 1
                if evaluate_state(downboard) > evaluate_state(bestneighbour):  # Better
                    bestneighbour = downboard.copy()
                if evaluate_state(downboard) == evaluate_state(bestneighbour) and downboard != board: # Equal but different, give it a chance to become best
                    if random.randint(0, 100) > 50:
                        bestneighbour = downboard.copy()

            # Move queen upwards and check if state is better or equal
            while upboard[column] - 1 > 0:
                upboard[column] = upboard[column] - 1
                if evaluate_state(upboard) > evaluate_state(bestneighbour):  # Better
                    bestneighbour = upboard.copy()
                elif evaluate_state(upboard) == evaluate_state(bestneighbour) and upboard != board: # Equal but different, give it a chance to become best
                    if random.randint(0,100) > 50:
                        bestneighbour = upboard.copy()

        # Best neighbour is found after for loop...
        # If lower or equal, random-restart

        # If bestneighbour found is worse than board, break, accepting defeat by local maximum
        if evaluate_state(bestneighbour) <= evaluate_state(board):
            for column, row in enumerate(board):  # For each column, place the queen in a random row
                board[column] = random.randint(0, len(board) - 1)
        else:
            board = bestneighbour.copy()

    # Loop breaked either because
    # 1. reached iteration limit
    # 2. local maximum reached
    # 3. optimum is reached.
    # If optimum was reached, print solution...
    print("Final State")
    if evaluate_state(board) == optimum:
        print_board(board)
        print("Solved!")
        print("---  Time: %s sec ---" % (time.time() - start_time))
        return
    else:
        print_board(board)
        print("Could not find optimal solution.")
        print("Points away from optimum: ", optimum - evaluate_state(board))
    print("---  Time: %s sec ---" % (time.time() - start_time))


import json
import time
import requests
from requests import *
from datetime import datetime
from config import *
from tiktok_module import downloader

api = "https://api.telegram.org/bot" + token_bot
update_id = 0

def SendVideo(userid,msgid):
	tg_url = api + "/sendvideo"
	data = {
		"chat_id":userid,
		"caption":"تم تنزْيلُِ عٍبَرٍ : @SEL_TK_BOT \n\n𝚂𝙴𝙻𝚅𝙴𝚁 - 𝙳𝙴𝚅 : 𖥳𖥳𖥳 @SELVER7 𖥳𖥳𖥳\n𝙲𝙷 : 𖥳𖥳𖥳 @M_GO_17q 𖥳𖥳𖥳",
		"parse_mode":"html",
		"reply_to_message_id":msgid,
		"reply_markup":json.dumps({
			"inline_keyboard":[
				[
					{
						"text":"𝚂𝙴𝙻𝚅𝙴𝚁 - 𝙳𝙴𝚅 <3",
						"url":"https://t.me/SELVER7"
					}
				]
			]
		})
	}
	res = post(
		tg_url,
		data=data,
		files={
			"video":open("video.mp4","rb")
		}
	)

def SendMsg(userid,text,msgid):
	tg_url = api + "/sendmessage"
	post(
		tg_url,
		json={
			"chat_id":userid,
			"text":text,
			"parse_mode":"html",
			"reply_to_message_id":msgid
		}
	)

def get_time(tt):
	ttime = datetime.fromtimestamp(tt)
	return f"{ttime.hour}-{ttime.minute}-{ttime.second}-{ttime.day}-{ttime.month}-{ttime.year}"

def Bot(update):
	try:
		global last_use
		userid = update['message']['chat']['id']
		meseg = update['message']['text']
		msgid = update['message']['message_id']
		timee = update['message']['date']
		dl = downloader.tiktok_downloader()
		if update['message']['chat']['type'] != "private":
			SendMsg(
				userid,
				"آلُِبَوُت يعٍملُِ فُقٌطُ فُي آلُِدِرٍدِشُة آلُِخـآصة!",
				msgid
			)
			return
		first_name = update['message']['chat']['first_name']
		print(f"{get_time(timee)}-> {userid} - {first_name} -> {meseg}")
		if meseg.startswith('/start'):
			SendMsg(
				userid,
				"آهـلُِآبَڪ فُي بَوُت تحٍميلُِ فُيدِيوُهـآت من تيڪ توُڪ\n\nڪيفُ تستخـدِم هـذَآ بَوُت ؟ :\nفُقٌطُ آرٍسلُِ رٍآبَطُ فُيدِيوُ من تيڪ توُڪ آلُِي هـذَآ بَوُت !!\n",
				msgid
			)
		elif "tiktok.com" in meseg and "https://" in meseg :
			getvid = dl.musicaldown(url=meseg,output_name="video.mp4")
			if getvid == False:
				SendMsg(
					userid,
					"فُشُلُِ فُي تحٍميلُِ فُيدِيوُ\n\nحاول مجددا لا حقا",
					msgid
				)
				return
			elif getvid == "private/remove":
				SendMsg(
					userid,
					"فُشُلُِ فُي تحٍميلُِ فُيدِيوُ\n\nڪآن آلُِفُيدِيوُ خـآصًآ أوُ تمت إزْآلُِته",
					msgid
				)
			elif getvid == "file size is to large":
				SendMsg(
					userid,
					"فُشُلُِ فُي تحٍميلُِ فُيدِيوُ\n\nحٍجٍم فُيدِيوُ ڪبَيرٍ ",
					msgid
				)
			else:
				SendVideo(
					userid,
					msgid
				)
		elif "/help" in meseg:
			SendMsg(
				userid,
				"ڪيفُ تستخـدِم هـذَآ بَوُت ؟ :\فُقٌطُ آرٍسلُِ رٍآبَطُ فُيدِيوُ من تيڪ توُڪ آلُِي هـذَآ بَوُت ! ",
				msgid
			)
		elif meseg.startswith("/donation"):
			SendMsg(
				userid,
				"Support me on\n\nko-fi (EN): https://ko-fi.com/fowawaztruffle\nsaweria (ID): https://saweria.co/fowawaztruffle\ntrakteerid (ID): https://trakteer.id/fowawaz\nQRIS (EWALLET,BANK): https://s.id/nusantara-qr",
				msgid
			)
	except KeyError:
		return


from Bio import SeqIO
from itertools import permutations

def Overlap(sequences,k):
	overlaps = []
	for a,b in permutations(sequences,2):

		if a[-k:] == b[:k]:
			overlaps.append([a,b])

	return overlaps

def main():
	sequence = {}
	fasta = SeqIO.parse(open(input('insert fasta file: ')),'fasta')
	for i in fasta:
		sequence[str(i.seq)] = i.id

	overlaps = Overlap(list(sequence.keys()),3)

	for a,b in overlaps:
		print(sequence[a],sequence[b])

if __name__ == '__main__':
	main()


# -*- coding: utf-8 -*-
"""
Created on Tue Dec  6 14:25:05 2022

@author: MaxKo
"""

prioritySum = 0

with open('Day3Input.txt') as f:
    while True:
        rucksack = f.readline()
        if not rucksack:
            print(prioritySum)
            break
        divider = int(len(rucksack) / 2)
        c1 = rucksack[:divider]
        c2 = rucksack[divider:]
        mistake = set(c1) & set(c2)
        for m in mistake:
            if m >= 'a':
                prioritySum += ord(m) - 96
            else:
                prioritySum += ord(m) - 38


import pygame
from pygame.locals import *

from gl import Renderer
import shaders

deltaTime = 0.0

# Inicializacion de pygame
pygame.init()
clock = pygame.time.Clock()
screenSize = (960, 540)
screen = pygame.display.set_mode(screenSize, DOUBLEBUF | OPENGL)

# Inicializacion de nuestro Renderer en OpenGL
r = Renderer(screen)
r.setShaders(shaders.vertex_shader, shaders.fragment_shader)
r.createObjects()

cubeX = 0
cubeY = 0
cubeZ = 0
cubeP = 0
cubeR = 0
cubeYawl = 0

isPlaying = True
while isPlaying:

    # Para revisar si una tecla esta presionada
    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        cubeX -= 2 * deltaTime
    if keys[pygame.K_d]:
        cubeX += 2 * deltaTime
    if keys[pygame.K_w]:
        cubeY -= 2 * deltaTime
    if keys[pygame.K_s]:
        cubeY += 2 * deltaTime
    if keys[pygame.K_z]:
        cubeZ -= 2 * deltaTime
    if keys[pygame.K_x]:
        cubeZ += 2 * deltaTime
    if keys[pygame.K_UP]:
        cubeP += 25 * deltaTime
    if keys[pygame.K_DOWN]:
        cubeP -= 25 * deltaTime
    if keys[pygame.K_LEFT]:
        cubeR += 25 * deltaTime
    if keys[pygame.K_RIGHT]:
        cubeR -= 25 * deltaTime
    if keys[pygame.K_y]:
        cubeYawl -= 25 * deltaTime
    if keys[pygame.K_u]:
        cubeYawl += 25 * deltaTime
    if keys[pygame.K_F5]:
        cubeX = 0
        cubeY = 0
        cubeZ = 0
        cubeP = 0
        cubeR = 0
        cubeYawl = 0

    for ev in pygame.event.get():
        if ev.type == pygame.QUIT:
            isPlaying = False
        elif ev.type == pygame.KEYDOWN:
            # para revisar en el momento que se presiona una tecla
            if ev.key == pygame.K_1:
                r.filledMode()
            elif ev.key == pygame.K_2:
                r.wireframeMode
            elif ev.key == pygame.K_ESCAPE:
                isPlaying = False

    r.translateCube(cubeX, cubeY, cubeZ)
    r.rollCube(cubeR)
    r.pitchCube(cubeP)
    r.yawlCube(cubeYawl)
    # Main Renderer Loop
    r.render()

    pygame.display.flip()
    clock.tick(60)
    deltaTime = clock.get_time() / 1000

pygame.quit()


#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals

AUTHOR = u'LukasWoodtli'
SITENAME = u'Rezepte'
SITEURL = 'http://lukaswoodtli.github.io/Rezepte'

PATH = 'content'

TIMEZONE = 'Europe/Zurich'

DEFAULT_LANG = u'de'

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

DEFAULT_PAGINATION = 5
PAGINATION_PATTERNS = ( (1, '{base_name}/', '{base_name}/index.html'), (2, '{base_name}/page/{number}/', '{base_name}/page/{number}/index.html'), )

MARKDOWN = {
            'extension_configs': {
                        'markdown.extensions.extra': {},
                        'markdown.extensions.sane_lists': {},
                        'markdown.extensions.toc': {},
                        'markdown.extensions.footnotes': {},
                        'markdown.extensions.attr_list': {}
            },
            'output_format': 'html5',
}

DOCUTILS_SETTINGS = {'table_style' : 'borderless'} # 'math_output': 'mathjax'

THEME = "blue-penguin"

TAG_URL = 'tag/{slug}/'
TAG_SAVE_AS = 'tag/{slug}/index.html'
TAGS_URL = 'tags/'
TAGS_SAVE_AS = 'tags/index.html'
CATEGORY_URL = 'category/{slug}/'
CATEGORY_SAVE_AS = 'category/{slug}/index.html'
CATEGORIES_URL = 'categories/'
CATEGORIES_SAVE_AS = 'categories/index.html'
ARCHIVES_URL = 'archives/'
ARCHIVES_SAVE_AS = 'archives/index.html'

# Keep the generated blog index but save it under different name
#INDEX_SAVE_AS = 'blog_index.html'

DISPLAY_PAGES_ON_MENU = True

# use those if you want pelican standard pages to appear in your menu
MENU_INTERNAL_PAGES = (
    ('Inspirationen', 'pages/ideen.html', 'pages/ideen.html'),
    ('Ausprobieren',  'pages/rezept-ideen-zum-ausprobieren.html', 'pages/rezept-ideen-zum-ausprobieren.html'),
    ('Tags', TAGS_URL, TAGS_SAVE_AS),
    ('Kategorien', CATEGORIES_URL, CATEGORIES_SAVE_AS),
    ('Alle', ARCHIVES_URL, ARCHIVES_SAVE_AS),
)


from kivy.uix.boxlayout import BoxLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior

from pyClasses.annotations.annotationRegister import annotationRegister

from functools import partial

class ToolbarContainer(BoxLayout):
  pass

class DropDownItem(ButtonBehavior, Label):
  def __init__(self, *args, **kwargs):
    super(DropDownItem, self).__init__(*args, **kwargs)

class AnotationSelect(Button):
  pipeSelectedValue = lambda *x: x

  def __init__(self, **kwargs):
    super(AnotationSelect, self).__init__(**kwargs)

    dropdown = DropDown()

    for name in annotationRegister:
      annotationSelect = DropDownItem(text=name, size_hint_y=None, height=44)
      annotationSelect.bind(on_release = partial(self.select, annotationSelect.text))
      dropdown.add_widget(annotationSelect)

    dropdown.bind(on_select=lambda instance, x: setattr(self, 'text', x))
    self.dropdown = dropdown

  def select(self, value, *args, **kwargs):
    self.dropdown.select(value)
    self.pipeSelectedValue(value)

  def on_release(self, *args, **kwargs):
    self.dropdown.open(self, *args, **kwargs)


import os
import pathlib
from dotctl.scripts import messages
from pytest import CaptureFixture
from tests.fixtures.bin_mock import BinMock

from tests.helpers.setup_script import SetupScript

def test_script(
  capfd: CaptureFixture[str],
  bin_mock: BinMock,
):
  setup_script = SetupScript(
    dir="tests/dotfiles",
    script_file="11-cask.py",
    packages_file="cask.txt",
    script_name="Brew cask packages",
    bin_mock=bin_mock,
    bins=("brew",),
  )
  for package in setup_script.packages:
    setup_script.add_expected_output(
      "checking %s..." % messages.package(package)
    )
    setup_script.add_expected_output(
      "installing %s..." % messages.package(package)
    )
    setup_script.add_expected_command("brew install -q --cask %s" % package)

  process = setup_script.execute()

  assert process.exitcode == 0
  captured = capfd.readouterr()
  assert captured.err == "", "stderr is not empty"

  assert captured.out == setup_script.expected_output(), "stdout does not match"


# -*-coding:utf-8-*-
# @Author: Damon0626
# @Time  : 19-1-16 下午9:47
# @Email : wwymsn@163.com
# @Software: PyCharm

'''
cv2中进行霍夫圆环检测的函数：

cv2.HoughCircles(image, method, dp, minDist, circles=None, param1=None, param2=None, minRadius=None, maxRadius=None)

其中：

image:8位，单通道图像。如果使用彩色图像，需要先转换为灰度图像。

method：定义检测图像中圆的方法。目前唯一实现的方法是cv2.HOUGH_GRADIENT。

dp：累加器分辨率与图像分辨率的反比。dp获取越大，累加器数组越小。

minDist：检测到的圆的中心，（x,y）坐标之间的最小距离。如果minDist太小，则可能导致检测到多个相邻的圆。如果minDist太大，则可能导致很多圆检测不到。

param1：用于处理边缘检测的梯度值方法。

param2：cv2.HOUGH_GRADIENT方法的累加器阈值。阈值越小，检测到的圈子越多。

minRadius：半径的最小大小（以像素为单位）。

maxRadius：半径的最大大小（以像素为单位）。
'''
import cv2
import numpy as np

img = cv2.imread('OpenCV_Logo_with_text.png', 0)
img = cv2.medianBlur(img, 5)  # 中值模糊
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# print(circles)  # (x, y), r
circls = np.uint16(np.around((circles)))

for i in circles[0, :]:
	# print(i)
	# 绘制外圆
	cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)

	# 绘制半径为2的圆心
	cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)

cv2.imshow('detected circles', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()


import os
import time
import json

import numpy as np
from qulacs import QuantumCircuit, QuantumState
from scipy.io import mmwrite
from scipy.optimize import *
from qiskit.algorithms.optimizers import *

class BreakOut(Exception):
	pass

class VSV(object):
	def __init__(self, test_state, num_states=None, directory=None):
		# Set up input parameters
		self.test_state = test_state
		if self.test_state.ndim == 1:
			self.test_state = np.outer(self.test_state, self.test_state.conj())
		self.test_state_purity = np.trace(self.test_state @ self.test_state).real
		self.dimension = len(self.test_state)
		self.nqubits = int(np.log2(self.dimension))
		self.num_states = num_states if num_states else self.dimension
		self.directory = directory if directory is not None else 'temp'

		# Minimizer
		self.min_kwargs = None
		self.params = None
		self.upper_params = None
		self.lower_params = None
		self.lower_param_bounds = [(0, 1)] * self.num_states
		self.upper_param_bounds = [(-2 * np.pi, 2 * np.pi)] * 2 * self.nqubits * self.num_states
		self.param_bounds = np.concatenate((self.lower_param_bounds, self.upper_param_bounds))
		self.lower_constraints = LinearConstraint(np.ones(self.num_states), 1, 1)
		self.constraints = LinearConstraint(
			np.concatenate((np.ones(self.num_states), np.zeros(2 * self.nqubits * self.num_states))), 1, 1)
		self.purity = None
		self.overlap = None
		self.pure_states = None

		# quantities
		self.D_list = None
		self.purity_list = None
		self.overlap_list = None
		self.css = None

		# alternative quantities
		self.fev_D_list = None
		self.fev_purity_list = None
		self.fev_overlap_list = None

		# progress parameters
		self.cost = None
		self.iter = None
		self.fev = None
		self.elapsed_time = None
		self.start_time = None
		self.max_time = None
		self.max_fev = None

	def run(self, min_kwargs=None, params=None, max_fevs=None, max_time=None):
		os.makedirs(f'{self.directory}', exist_ok=True)
		# Generate parameters
		self.params = params or np.concatenate((self.generate_random_lower_params(),
		                                        self.generate_random_upper_params()))
		self.lower_params = self.params[:self.num_states]
		self.upper_params = self.params[self.num_states:]
		# Set break points
		self.iter = 0
		self.fev = 0
		self.elapsed_time = 0
		if max_fevs:
			self.max_fev = max_fevs
		else:
			self.max_fev = None
		self.max_time = max_time
		# Create empty lists
		self.D_list = []
		self.purity_list = []
		self.overlap_list = []
		self.fev_D_list = []
		self.fev_purity_list = []
		self.fev_overlap_list = []
		# Save initial CSS
		p = self.lower_params
		theta, phi = self.upper_params_unpacker(self.upper_params)
		self.css = self.css_density_matrix(p, theta, phi)
		mmwrite(f'{self.directory}/initial_trial_state.mtx', self.css, field='complex', precision=10, symmetry='hermitian')
		# Set up minimizer kwargs
		self.min_kwargs = min_kwargs or dict()
		with open(f'{self.directory}/min_kwargs.json', 'w') as f:
			json.dump(self.min_kwargs, f)
		self.min_kwargs.update(func=self.upper_cost_function, x0=self.upper_params, bounds=self.upper_param_bounds,
		                       callback=self.callback)
		# Start minimization
		self.start_time = time.perf_counter()
		result = self.min_D()
		# Save last CSS
		p = self.lower_params
		theta, phi = self.upper_params_unpacker(self.upper_params)
		self.css = self.css_density_matrix(p, theta, phi)
		mmwrite(f'{self.directory}/calculated_css.mtx', self.css, field='complex', precision=10, symmetry='hermitian')
		# Save data
		np.savetxt(f'{self.directory}/fev_D_list.txt', self.fev_D_list)
		np.savetxt(f'{self.directory}/fev_purity_list.txt', self.fev_purity_list)
		np.savetxt(f'{self.directory}/fev_overlap_list.txt', self.fev_overlap_list)
		np.savetxt(f'{self.directory}/D_list.txt', self.D_list)
		np.savetxt(f'{self.directory}/purity_list.txt', self.purity_list)
		np.savetxt(f'{self.directory}/overlap_list.txt', self.overlap_list)
		np.savetxt(f'{self.directory}/params.txt', self.params)
		np.savetxt(f'{self.directory}/metadata.txt', [self.iter, self.fev])
		# Return result
		return result

	def generate_random_upper_params(self):
		return np.random.uniform(-2 * np.pi, 2 * np.pi, 2 * self.nqubits * self.num_states)

	def generate_random_lower_params(self):
		p = np.random.uniform(0, 1, self.num_states)
		return p / np.sum(p)

	def params_unpacker(self, params):
		p = params[:self.num_states]
		theta, phi = self.upper_params_unpacker(params[self.num_states:])
		return p, theta, phi

	def upper_params_unpacker(self, upper_params):
		return upper_params[:self.nqubits * self.num_states], upper_params[self.nqubits * self.num_states:]

	def updater(self, p, theta, phi):
		self.fev += 1
		# Update params
		self.lower_params = p
		self.upper_params = np.concatenate((theta, phi))
		self.params = np.concatenate((self.lower_params, self.upper_params))
		# Check break conditions
		self.elapsed_time = time.perf_counter() - self.start_time
		if self.max_fev and self.fev >= self.max_fev:
			raise BreakOut('Maximum number of function evaluations reached')
		if self.max_time and self.elapsed_time >= self.max_time:
			raise BreakOut('Maximum time limit reached')

		# Update data
		self.fev_D_list.append(self.cost)
		self.fev_purity_list.append(self.purity)
		self.fev_overlap_list.append(self.overlap)

	def callback(self, *args, **kwargs):
		self.iter += 1
		# Update data
		self.D_list.append(self.cost)
		self.purity_list.append(self.purity)
		self.overlap_list.append(self.overlap)

		self.elapsed_time = time.perf_counter() - self.start_time
		print(f"| {self.iter} | {self.fev} | {self.D_list[-1]:.10f} | {self.elapsed_time:.2f} |")

	def min_D(self):
		try:
			# Print headers
			print("| Iterations | Function Evaluations | HSD | Elapsed Time |")
			# Minimize
			# result = dual_annealing(**self.min_kwargs)
			result = NFT(maxfev=2048, reset_interval=16, callback=self.callback) \
				.minimize(fun=self.upper_cost_function, x0=self.upper_params, bounds=self.upper_param_bounds)
		# Break point reached
		except BreakOut:
			return None

		return result

	def upper_cost_function(self, upper_params):
		# Get theta and phi
		theta, phi = self.upper_params_unpacker(upper_params)
		# Calculate purity and overlap lists
		self.pure_states = self.calculate_pure_states(theta, phi)
		# Minimize to find p
		result = minimize(self.lower_cost_function, x0=self.lower_params, bounds=self.lower_param_bounds,
		                  constraints=self.lower_constraints)
		# Get results
		p = result.x
		self.cost = result.fun
		# Update run
		self.updater(p, theta, phi)
		# Return cost
		return self.cost

	def lower_cost_function(self, p):
		sigma = np.zeros((self.dimension, self.dimension), dtype=np.complex128)
		for i, j in zip(p, self.pure_states):
			sigma += i * j
		self.purity = np.trace(sigma @ sigma).real
		self.overlap = np.trace(self.test_state @ sigma).real
		return self.test_state_purity + self.purity - 2 * self.overlap

	def cost_function(self, params):
		# Get p, theta and phi
		p, theta, phi = self.params_unpacker(params)
		# Calculate purity and overlap lists
		sigma = self.css_density_matrix(p, theta, phi)
		self.purity = np.trace(sigma @ sigma).real
		self.overlap = np.trace(self.test_state @ sigma).real
		self.cost = self.test_state_purity + self.purity - 2 * self.overlap
		# Update run
		self.updater(p, theta, phi)
		# Return cost
		return self.cost

	def calculate_pure_states(self, theta, phi):
		sigmas = []
		for i in range(self.num_states):
			j = i * self.nqubits
			k = (i + 1) * self.nqubits
			sigmas.append(self.prod_state(theta[j:k], phi[j:k]))

		return sigmas

	def css_density_matrix(self, p, theta, phi):
		sigma = np.zeros((self.dimension, self.dimension), dtype=np.complex128)
		for i in range(self.num_states):
			j = i * self.nqubits
			k = (i + 1) * self.nqubits
			sigma += p[i] * self.prod_state(theta[j:k], phi[j:k])

		return sigma

	def prod_state(self, theta, phi):
		qc = QuantumCircuit(self.nqubits)
		for i, [t, p] in enumerate(zip(theta, phi)):
			qc.add_RY_gate(i, t)
			qc.add_RZ_gate(i, p)
		state = QuantumState(self.nqubits)
		qc.update_quantum_state(state)
		statevector = state.get_vector()
		return np.outer(statevector, statevector.conj())


# IMPORT TOOLS
#   STANDARD LIBRARY IMPORTS
#   THIRD PARTY IMPORTS
#   LOCAL APPLICATION IMPORTS
from newbacktest.perfmetrics.winnerloser.class_winloseprofile import WinLoseProfile
from newbacktest.perfmetrics.winnerloser.db_wlprofile import WinLoseProfDatabase
from newbacktest.perfmetrics.winnerloser.db_wlpool import WinLosePoolDatabase
from newbacktest.perfmetrics.perfmetrics_perfprofileupdater_perfmetricnames import PerfMetricNameDatabase

class WinLoseGenerator:
    '''
    Generates and stores dataframes of winner/losers based on the desired criteria.  DFs are stored by stratcode+ipcode combo and then by invest_startdate
    This is unlike the portfoliogenerator, in that it doesn't randomly choose dates.  It takes an input array of them.
    '''

    def generate_bywlprofcode(self, allinvest_startdates, wlprofcode):
        '''generate winner/loser pools'''
        print(allinvest_startdates)
        for invest_startdate in allinvest_startdates:
            print(f'Invest Start_Date: {invest_startdate}\n')

            '''check if pool already exists'''
            wlpdb = WinLosePoolDatabase()
            print(f'Checking if {wlpdb._item_term} already exists for invest_startdate of "{invest_startdate}" and {wlpdb._keyname_term} "{wlprofcode}" in the {wlpdb._dbname}...', end='')
            existence = wlpdb.view_wlpool(wlprofcode, invest_startdate)
            if existence is not None and existence != 0:
                print('it does.\nMoving on to the next invest_startdate...\n\n')
                continue
            else:
                '''Generate WL Pool'''
                print(f'it does not. Generating Win Lose Pooldf for invest_startdate "{invest_startdate}" and {wlpdb._keyname_term} "{wlprofcode}"...')
                wlpdb.add_item(wlprofcode, invest_startdate)

                print(wlpdb)
                print(wlpdb.view_wlpool(wlprofcode, invest_startdate).itemdata)
            print('Moving on to the next trial...\n\n')
        print('All requested WLPools generated.')

    def generate_bywlprofile(self, wlprofile, periodlen, allinvest_startdates):
        '''create winner/loser profile you want to use'''
        wlprofile = WinLoseProfile(wlprofile, periodlen)
        WinLoseProfDatabase().add_item(wlprofile)
        wlprofcode = wlprofile.itemcode
        '''generate wlpools'''
        self.generate_bywlprofcode(allinvest_startdates, wlprofcode)
        '''add wlprofcode to perfmetricnames'''
        PerfMetricNameDatabase().add_item([wlprofcode])
        return wlprofcode


#Day 9 - based on day 5 "Intcode" computer

def getIntsList():
    f = open("puzzle_input/day9.txt", "r")
    ints = [int(x.strip()) for x in f.read().split(',')]
    f.close()
    return ints

def intCode(ints):
    global relative_base
    n = 0
    i = 0

    while(n != 99):
        n = ints[i]
        modes = determineModes(str(n))

        #change the opcode to the last two digits if the mode was supplied
        if(modes != ['0','0','0']):
            n = int(str(n)[-2:])

        #opcode 1 - add two digits and store in position given
        if(n == 1):
            #check whether ints list is long enough to store value in that address
            for value in [i+1, i+2, i+3]:
                if(getValue(value, modes[2]) >= len(ints)):
                    padOutIntsList(getValue(value, modes[2]))

            a = ints[getValue(i+1, modes[0])]
            b = ints[getValue(i+2, modes[1])]

            ints[getValue(i+3, modes[2])] = a + b
            i += 4 #go to next instruction

        #opcode 2 - multiply two digits and store in position given
        elif(n == 2):
            #check whether ints list is long enough to store value in that address
            for value in [i+1, i+2, i+3]:
                if(getValue(value, modes[2]) >= len(ints)):
                    padOutIntsList(getValue(value, modes[2]))

            a = ints[getValue(i+1, modes[0])]
            b = ints[getValue(i+2, modes[1])]

            ints[getValue(i+3, modes[2])] = a * b
            i += 4 #go to next instruction

        #opcode 3 - store input from user in position given
        elif(n == 3):
            ints[getValue(i+1, modes[0])] = int(input("Enter an input: "))
            i += 2 #go to next instruction

        #opcode 4 - output the digit in the position given
        elif(n == 4):
            print(ints[getValue(i+1, modes[0])])
            i += 2 #go to next instruction - this instruction is 2 chars long

        #opcode 5 - jump to given place in program if True
        elif(n == 5):
            if(ints[getValue(i+1, modes[0])] != 0):
                i = ints[getValue(i+2, modes[1])] #set pointer to second parameter
            else:
                i += 3 #go to the next instruction

        #opcode 6 - jump to given place in program if False
        elif(n == 6):
            if(ints[getValue(i+1, modes[0])] == 0):
                i = ints[getValue(i+2, modes[1])] #set pointer to second parameter
            else:
                i += 3 #go to the next instruction

        #opcode 7 - store '1' in position given if first param less than second
        elif(n == 7):
            #check whether ints list is long enough to store value in that address
            if(getValue(i+3, modes[2]) >= len(ints)):
                padOutIntsList(getValue(i+3, modes[2]))

            if(ints[getValue(i+1, modes[0])] < ints[getValue(i+2, modes[1])]):
                ints[getValue(i+3, modes[2])] = 1
            else:
                ints[getValue(i+3, modes[2])] = 0
            i += 4 #go to next instruction

        #opcode 8 - store '1' in position given if first and second params match
        elif (n == 8):
            #check whether ints list is long enough to store value in that address
            if(getValue(i+3, modes[2]) >= len(ints)):
                padOutIntsList(getValue(i+3, modes[2]))

            if(ints[getValue(i+1, modes[0])] == ints[getValue(i+2, modes[1])]):
                ints[getValue(i+3, modes[2])] = 1
            else:
                ints[getValue(i+3, modes[2])] = 0
            i += 4 #go to next instruction

        #opcode 9 - add parameter to relative base
        elif (n == 9):
            #check whether ints list is long enough to store value in that address
            if(getValue(i+1, modes[0]) >= len(ints)):
                padOutIntsList(getValue(i+1, modes[0]))

            relative_base += ints[getValue(i+1, modes[0])]
            i += 2 #go to next instruction

    #return the diagnostic code at position 0 in list
    print("Halting...")

#returns modes if they were supplied, or a list of 0's if none present
def determineModes(instruction):
    if(len(instruction) > 2):
        #get all digits apart from opcode (2 right-most digits)
        modes = instruction[:-2]

        #reversed so it reads left to right (so the first mode comes first)
        modes = list(reversed(modes))

        #pad out the list (where mode is not supplied, mode = 0)
        while(len(modes) < 3):
            modes.append('0')

        return modes
    else:
        return ['0','0','0']

#returns a value depending on which mode is given
def getValue(location, mode):
    if(mode == '0'): #position mode - returns value in that position in list
        return ints[location]

    elif(mode == '1'): #immediate mode - returns the value itself
        return location

    elif(mode == '2'): #relative mode - returns value from relative base offset by location

        return relative_base + ints[location]

#add '0's to the end of the list so we can write to locations in ints list
#that don't currently exist
def padOutIntsList(location):
    for i in range(len(ints), location+1):
        ints.append(0)

#main routine
relative_base = 0
ints = getIntsList()
intCode(ints)


#palindrome with function
def pal(no,word):
    ln=len(no)
    no1=int(no)
    r=0
    for i in range (0,ln):
        a=no1%10
        no1=no1//10
        if(a==0):
            r=r*10+no1
        else:
            r=r*10+a

    if(r==int(no)):
        print("GIVEN NUMBER IS PALINDROME !!!!! ",r)
    else:
        print("NUMBER IS NOT PALINDROME ",r)

    w=word[::-1]
    if(w==word):
        print("GIVEN WORD IS PALINDROME !!!!! ",w)
    else:
       print("GIVEN WORD IS NOT PALINDROME !!!!! ",w)
a=input("ENTER ANY INTEGER : ")
word=input("ENTER ANY WORD")
pal(a,word)


import numpy as np
from brian2 import *
import seaborn as sns
sns.set(font_scale=2.0)

N = 1

# Neuron Parameters
g_l = 0.05 * msiemens / cm2
Cm = 1.0 * ufarad / cm2  # Specific membrane capacitance
E_l = -60 * mV   # Resting potential
V_t = -50 * mV  # Threshold
tau_w = 600 * ms  # Adaptation time constant of w
Delta = 2.5 * mV  # Steep when approaching the threshold
S = 20000 * um2  # Membrane area

a = 0.001 * usiemens  # dynamics of adaptation
a = 0.04 * usiemens  # dynamics of adaptation
b = 0.04 * namp  # w increases by this value at each spike
b = 0.005 * namp  # w increases by this value at each spike
b = 0 * namp  # w increases by this value at each spike

f_m = g_l / Cm
# tau_ m = 1 / f_m
aux = S * Cm

I_0 = 0.25 * namp
I_0 = -0.25 * namp

# Let's create the pulse
dt_array = 0.1
values = np.arange(0, 1000, dt_array)
values[values < 200] = 0
values[values > 600] = 0
values[(200 <= values) * (values <= 600)] = 1

I = TimedArray(values * I_0, dt=0.1*ms)

start_scope()
# Equations
eqs = """
dv / dt = -f_m * (v - E_l) + f_m * Delta * exp((v - V_t) / Delta) - (w / aux) + (I(t) / aux) : volt (unless refractory)
dw / dt = (1 / tau_w) * (a * (v - E_l) - w) :  amp
"""

reset = '''
v = E_l
w += b
'''

V_avg = -55 * mV
w_avg = a * (V_avg - E_l) / aux

# Define neuron
G = NeuronGroup(N, eqs, threshold='v > V_t', reset=reset, refractory=2.5*ms, method='euler')

# State monitor
M = StateMonitor(G, ['v', 'w'], record=0)

# Run this

# Run the model
run(1000 * ms)

# Plot here
fig = plt.figure(figsize=(16, 12))
data = 'Experiment for (a = ' + str(a) + ', b = ' + str(b) + ' )'
fig.suptitle(data)

ax1 = fig.add_subplot(211)
ax1.plot(M.t/ms, (M.v[0] / mV),label='voltage')

ax1.set_ylabel('v')
ax1.set_ylim([-80, -45])

ax1.legend()

ax2 = fig.add_subplot(212, sharex=ax1)
w_sta = a * (M.v[0] - E_l) / aux
ax2.plot(M.t/ms, (M.w[0] / aux), label='w')
ax2.plot(M.t/ms, w_sta, label='w*')
ax2.axhline(np.array(w_avg), label='w*(-55 mV)', color='black')

ax2.set_xlabel('Time (ms)')
ax2.set_ylabel('w')

ax2.legend()

plt.setp(ax1.get_xticklabels(), visible=False)

plt.show()


# Creating a class and object with default constructor

class Car:
    # By default comstructor in python
    def __init__(self,brand,color):
        self.brand=brand
        self.car=color
        print(f"Car's brand is {brand}")
        print(f"Car's color is {color}")

# Creating object of class Car

car1 = Car("BMW","Black")
car2 = Car("Audi","Silver")


import numpy as np
import matplotlib.pyplot as plt
plt.rc('font', family='malgun gothic')
plt.rcParams['axes.unicode_minus'] = False

# x = ['서울', '수원', '연천'] list
# x = {'서울', '수원', '연천'} 순서가 없기 때문에 사용 불가 (인덱싱 불가)

'''
x = ('서울', '수원', '연천')
y = [5, 3, 7]
plt.xlim([-1, 3])
plt.ylim([-5, 10])
plt.plot(x, y)
plt.yticks(list(range(-3, 11, 3)))
plt.xlabel('지역명')
plt.ylabel('친구명')
plt.title('선그래프')
plt.show()
'''

'''
# sin 곡선
x = np.arange(10)
y = np.sin(x)
print(x, y)
# plt.plot(x, y, 'bo')
plt.plot(x, y, 'go--', linewidth=3, markersize=10)
plt.show()
'''

# hold : '복수의 차트'  그리기 명령을 하나의 figure에 표현할 수 있다.
x = np.arange(0, np.pi * 3, 0.1)
print(x)
y_sin = np.sin(x)
y_cos = np.cos(x)

plt.figure(figsize=(10, 5))
plt.plot(x, y_sin, c='r')
plt.scatter(x, y_cos, c='b')
plt.legend(['sin', 'cosine'], loc=1)  # loc는 시계 반대방향으로 움직인다.
plt.show()

# subplot : 여러 개의 영역으로 나눠 차트를 그린다.
plt.subplot(2, 1, 1)
plt.plot(x, y_sin)
plt.title('sine')

plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('cosine')

plt.show()


"""读取get_meta_sub_BERT的输出文件，按照knowledge based方式
找到隐喻动词的平替词的备选词表
Env: 本地, DeepMet"""
import os
import re
import pandas as pd
import numpy as np
import ast
from tqdm import tqdm
import synonyms
import OpenHowNet
import json

os.getcwd()

def keep_only_CN_char(lst):
    """过滤所有非中文汉字"""
    return [w for w in lst if chinese_re.findall(w) != []]

def flattern_lst_of_lst(lst):
    """展开2层嵌套式list"""
    lst = [x for nest_lst in lst for x in nest_lst]  # 方法1
    # lst = sum(lst, [])  # 方法2
    # lst = reduce(lambda x, y: x+y, lst)  # 方法3
    return lst

# 10个词
def get_syns_synonyms(word):
        """从synonyms工具包获得word的近义词"""
        syn_words, _ = synonyms.nearby(word, 10)
        return keep_only_CN_char(syn_words)

def load_HIT_synonyms(file_path):
    """加载哈工大同义词词林扩展版，并输出同义词集合和相关词集合"""
    sym_words, sym_class_words = [], []
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            items = line.strip().split(' ')
            index = items[0]
            if (index[-1] == '='):  # 同义词
                sym_words.append(items[1:])
            if (index[-1] == '#'):  # 近义词
                sym_class_words.append(items[1:])
    return sym_words, sym_class_words

def get_syns_HIT(word, syns_dict):
    """根据哈工大词林找word的同义词"""
    word_syns = []  # 初始化一个词的同义词列表
    for sym_words in syns_dict:  # 遍历同义词表，sym_words为其中的一条
        if word in sym_words:  # 如果句子中的词在同义词表某一条目中，将该条目中它的同义词添加到该词的同义词列表中
            same_sym_words = [w for w in sym_words if w != word]
            word_syns.extend(same_sym_words)
    return keep_only_CN_char(word_syns)

# 10个词
def get_syns_hownet(word):
    """使用Hownet获得特定词汇的近义词，一个sense对应一组近义词。
    Hownet是根据义原（sememe）来确定近义词的，不同sense可能有相同的义原，因此不同sense的近义词可能是一样的"""
    syn_words = hownet_dict_advanced.get_nearest_words(word, language='zh', K=10)
    # 把该词汇对应所有sense的近义词合并，并去除重复项
    syn_words = list(set(flattern_lst_of_lst(syn_words.values())))
    return keep_only_CN_char(syn_words)

def get_same_frame_word(word):
    """输出跟word相同frame的其他词汇"""
    out_words = []
    if word in CFN_word2frame['word'].values:  # 如果word在CFN中存在
        word_frames = CFN_word2frame[CFN_word2frame['word'] == word]['frame']
        out_words = [CFN_frame2word[frame] for frame in word_frames]
        out_words = flattern_lst_of_lst(out_words)
    return keep_only_CN_char(out_words)

if __name__ == '__main__':
    # 读取文件
    filename = 'poetry0-24859w_predict薛24867_edited'
    df_expand = pd.read_excel('./corpus/poetry/' + filename + '_meta_wobert.xlsx')
    # df_expand = pd.read_csv('./corpus/CCL_PSUCMC_meta_bert.csv', converters={"meta_words": ast.literal_eval})
    # df = pd.read_excel('./corpus/poetry/poetry0-100007w_predict薛24867_edited_top1000.xlsx')
    meta_word_col = 'meta_words'  # 找到隐喻词汇所在列的名称
    sentence_col_name = 'content'  # 找到完整句子所在列的名称

    chinese_re = re.compile('[\u4e00-\u9fa5]+')
    meta_filter = [row[meta_word_col] != '' for idx, row in df_expand.iterrows()]
    # # ----------------------用synonyms找隐喻词汇的近义词---------------------------
    df_expand.loc[meta_filter, 'meta_subs_synonyms'] = df_expand.loc[meta_filter, meta_word_col].apply(get_syns_synonyms)
    # # ----------------------用哈工大词林找隐喻词汇的近义词-----------------------------------------------
    HIT_cilin_file_path = './corpus/哈工大词林扩展版/cilin_ex.txt'
    sym_words_list, sym_class_words_list = load_HIT_synonyms(HIT_cilin_file_path)
    df_expand.loc[meta_filter, 'meta_subs_HIT'] = df_expand.loc[meta_filter, meta_word_col].apply(lambda x: get_syns_HIT(x, sym_words_list))
    # # ----------------------用Hownet找隐喻词汇的近义词-----------------------------------------------
    # hownet_dict_advanced = OpenHowNet.HowNetDict(init_sim=True)
    # OpenHowNet.download()
    # df_expand['meta_subs_hownet'] = ''
    # df_expand_copy = df_expand.copy()
    # for idx, row in tqdm(df_expand_copy.iterrows()):
    #     if row[meta_word_col] != '':  #
    #         df_expand.at[idx, 'meta_subs_hownet'] = get_syns_hownet(row[meta_word_col])

    # df_expand.loc[meta_filter, 'meta_subs_hownet'] = df_expand.loc[meta_filter, meta_word_col].apply(get_syns_hownet)
    # ----------------------用中文FrameNet找隐喻词汇的同域词-----------------------------------------------
    with open('./CFN_LEX_CN/CFN_LEX_CN.json') as f:
        CFN_frame2word = json.load(f)
    CFN_word2frame = pd.read_csv('./CFN_LEX_CN/CFN_LEX_CN.csv')
    df_expand.loc[meta_filter, 'meta_subs_CFN'] = df_expand.loc[meta_filter, meta_word_col].apply(get_same_frame_word)

    # ----------------------集合以上所有词汇到一起-----------------------------------------------
    # df_expand['meta_subs'] = df_expand['meta_subs_synonyms'] + \
    #     df_expand['meta_subs_HIT'] + df_expand['meta_subs_hownet'] + \
    #     df_expand['meta_subs_CFN']
    # df_expand.loc[meta_filter, 'meta_subs'] = df_expand.loc[meta_filter, 'meta_subs'].apply(lambda x: list(set(x)))
    df_expand_meta = df_expand[meta_filter]
    df_expand_meta.drop(['predict'], axis=1, inplace=True)
    df_expand_meta.to_excel('./corpus/poetry/' + filename + '_meta_nohownet.xlsx', index=False)


# --- External Imports ---
import numpy
from matplotlib import pyplot

# --- Internal Imports ---
from .Result import Result

# --- STD Imports ---
import typing
import math

colors = {
    "TUMBlue" : [v / 255.0 for v in (0, 82, 147, 0xff)],
    "TUMOrange" : [v / 255.0 for v in (227, 114, 34, 0xff)],
    "warning" : [v / 255.0 for v in (0xff, 0xcc, 0xcc, 0xff)],
    "black" : [0.0, 0.0, 0.0, 1.0],
    "gray" : [0.5, 0.5, 0.5, 1.0]
}

def findMinPrefix(contents: list[Result], quantityName: str):
    minPrefix = (None, None)
    prefixes = set()

    if isinstance(contents, list):
        for results in contents:
            for case in results.cases:
                prefixes.add(case[quantityName].getPrefix())
    elif isinstance(contents, Result):
        for case in contents.cases:
            prefixes.add(case[quantityName].getPrefix())
    else:
        return ValueError(f"Unexpected input type: {type(contents)}")

    for prefix in prefixes:
        exponent = Result.Case.Quantity.getPrefixMap()[prefix]
        if minPrefix[1] == None or minPrefix[2] < exponent:
            minPrefix = (prefix, exponent)

    return minPrefix[0]

def homogenizeUnits(results: Result, quantityName: str, commonPrefix: str = "") -> None:
    if not commonPrefix:
        commonPrefix = findMinPrefix(results, quantityName)

    for case in results.cases:
        case[quantityName].setPrefix(commonPrefix)

def plotQuantity(results: Result,
                 quantityName: str,
                 axes: pyplot.Axes,
                 color: list[float] = colors["TUMBlue"],
                 textColor: list[float] = colors["black"],
                 prefix: str = None,
                 label: str = "",
                 positions: numpy.array = None,
                 barCount: int = 1,
                 barIndex: int = 0,
                 totalWidth: float = 0.8,
                 format = R"{:.2E}") -> typing.Any:
    if not prefix:
        prefix = findMinPrefix(results, quantityName)
    homogenizeUnits(results, quantityName, commonPrefix = prefix)

    if not label:
        label = quantityName

    # Collect values
    values = [case[quantityName].getValue() for case in results.cases]

    if positions is None:
        positions = numpy.arange(len(values))

    # Plot values
    barWidth = totalWidth / barCount
    offsets = positions + (barWidth * (barIndex + 0.5) - totalWidth / 2.0)
    bars = axes.bar(offsets,
                    values,
                    barWidth,
                    label = label,
                    color = color)

    # Draw bar heights
    for rectangle in bars.patches:
        height = rectangle.get_height()
        width = rectangle.get_width()
        position = rectangle.get_x()
        axes.text(
            position + width / 2.0,
            height * ((barIndex + 1) / barCount),
            format.format(height),
            ha = "center",
            va = "bottom",
            color = textColor,
            fontsize = 14
        )

    return bars

def plot(contents: list[Result],
         quantityNames: list[str] = None,
         labelSizes: tuple[int,int] = (16, 16),
         labelColors: tuple[list[float],list[float]] = (colors["black"], colors["black"])) -> None:

    numberOfSubplots = len(contents)
    grid = (int(math.sqrt(numberOfSubplots)), 1)
    if grid[0]:
        grid = (grid[0], math.ceil(numberOfSubplots / grid[0]))

    figure, axisSets = pyplot.subplots(grid[0], grid[1], num = "Benchmark Result")
    if 1 < len(contents):
        axisSets = [axisSets]
    axisSets = numpy.ravel(axisSets)

    colorKeys = list(iter(colors.keys()))
    for results, axes in zip(contents, axisSets):
        labels = [case.name for case in results.cases]
        positions = numpy.arange(len(labels))
        for quantityIndex, quantityName in enumerate(quantityNames):
            colorKey = colorKeys[quantityIndex % len(colorKeys)]
            color = colors[colorKey]
            textColor = colors["gray"] if colorKey == "black" else colors["black"]
            graph = plotQuantity(
                results,
                quantityName,
                axes,
                barCount = len(quantityNames),
                barIndex = quantityIndex,
                positions = positions,
                color = color,
                textColor = textColor)
        axes.set_xticks(positions)
        axes.set_xticklabels(labels, rotation = 45, ha = "right")

        # Set y axis scale
        yRange = [float("inf"), float("-inf")]
        for rectangle in graph:
            height = rectangle.get_height()
            if height < yRange[0]:
                yRange[0] = height
            if yRange[1] < height:
                yRange[1] = height
        if yRange[0] and yRange[1] and 10 < yRange[1] / yRange[0]:
            axes.set_yscale("log")

    axes.grid(visible = True, axis = "y")

    figure.tight_layout()
    pyplot.show()


from layers import FullyConnectedLayer, ReLULayer, softmax_with_cross_entropy

import numpy as np

class TwoLayerNet:
    """ Neural network with two fully connected layers """

    def __init__(self, n_input: int, n_output: int, hidden_layer_size: int, reg: float):
        """
        Initializes the neural network

        Arguments:
        n_input: int - dimension of the model input
        n_output: int - number of classes to predict
        hidden_layer_size: int - number of neurons in the hidden layer
        reg: float - L2 regularization strength
        """
        self.reg = reg

        # Create necessary layers
        self.fc1 = FullyConnectedLayer(n_input, hidden_layer_size)
        self.relu1 = ReLULayer()
        self.fc2 = FullyConnectedLayer(hidden_layer_size, n_output)

    def compute_loss_and_gradients(self, X: np.ndarray, y: np.ndarray):
        """
        Computes total loss and updates parameter gradients
        on a batch of training examples
        Arguments:
        X: np array (batch_size, input_features) - input data
        y: np array of int (batch_size) - classes
        """
        # Before running forward and backward pass through the model,
        # clear parameter gradients aggregated from the previous pass
        # Set parameter gradient to zeros
        self.fc1.dW = np.zeros_like(self.fc1.W)
        self.fc1.dB = np.zeros_like(self.fc1.B)
        self.fc2.dW = np.zeros_like(self.fc2.W)
        self.fc2.dB = np.zeros_like(self.fc2.B)

        # Compute loss and fill param gradients by running forward and backward passes through the model
        fc1_out = self.fc1.forward(X)
        relu1_out = self.relu1.forward(fc1_out)
        fc2_out = self.fc2.forward(relu1_out)
        loss, grad = softmax_with_cross_entropy(fc2_out, y)

        # Backpropagate the gradient through the network and accumulate the parameter gradients
        grad = self.fc2.backward(grad)
        grad = self.relu1.backward(grad)
        grad = self.fc1.backward(grad)

        # Add regularization to the parameter gradients
        self.fc1.dW += self.reg * self.fc1.W
        self.fc2.dW += self.reg * self.fc2.W

        return loss, grad

    def predict(self, X: np.ndarray):
        """
        Produces classifier predictions on the set

        Arguments:
          X: np array (test_samples, num_features)

        Returns:
          y_pred: np.array of int (test_samples)
        """
        # Forward pass
        fc1_out = self.fc1.forward(X)
        relu1_out = self.relu1.forward(fc1_out)
        fc2_out = self.fc2.forward(relu1_out)

        # Output predictions
        pred = np.argmax(fc2_out, axis=1)

        return pred

    def params(self) -> Dict[str, np.ndarray]:
        result = {}

        # Aggregate all of the params
        result['W1'] = self.fc1.W
        result['B1'] = self.fc1.B
        result['W2'] = self.fc2.W
        result['B2'] = self.fc2.B

        return result


"""Mark bad temporal segments via MNE annotate functions and save."""

# %%
# Imports
import json
import sys
from pathlib import Path

from mne.preprocessing import (
    annotate_amplitude,
    annotate_break,
    annotate_muscle_zscore,
    annotate_nan,
)
from mne.utils import logger

from config import (
    FNAME_BADS_TEMPLATE,
    FNAME_RAW_SET_TEMPLATE,
    FNAME_SEGMENTS_TEMPLATE,
    FPATH_DS,
    FPATH_DS_NOT_FOUND_MSG,
    OVERWRITE_MSG,
    SUBJS,
)
from utils import get_raw_data, parse_overwrite

# %%
# Filepaths and settings

sub = 1
overwrite = False

# %%
# When not in an IPython session, get command line inputs
# https://docs.python.org/3/library/sys.html#sys.ps1
if not hasattr(sys, "ps1"):
    defaults = dict(
        sub=sub,
        overwrite=overwrite,
    )

    defaults = parse_overwrite(defaults)

    sub = defaults["sub"]
    overwrite = defaults["overwrite"]

# Check inputs after potential overwriting
if sub not in SUBJS:
    raise ValueError(f"'{sub}' is not a valid subject ID.\nUse: {SUBJS}")
if not FPATH_DS.exists():
    raise RuntimeError(FPATH_DS_NOT_FOUND_MSG.format(FPATH_DS))
if overwrite:
    logger.info("`overwrite` is set to ``True``.")

# %%
# Check overwrite
fname_seg = Path(FNAME_SEGMENTS_TEMPLATE.format(sub=sub))
if fname_seg.exists() and not overwrite:
    raise RuntimeError(OVERWRITE_MSG.format(fname_seg))

# %%
# Get raw data
raw = get_raw_data(FNAME_RAW_SET_TEMPLATE.format(sub=sub))

# %%
# Mark flat segments ... and potentially channels (if a channel is often flat)
annots_flat, bads_flat = annotate_amplitude(raw, flat=0)

# %%
# Mark block breaks as bad
annots_break = annotate_break(raw, t_start_after_previous=2, t_stop_before_next=2)

# %%
# Mark muscle artifacts
raw_copy = raw.copy()
raw_copy.load_data()
raw_copy.notch_filter([50, 100])

thresh_zscore = 4
annots_muscle, _ = annotate_muscle_zscore(
    raw_copy, threshold=thresh_zscore, ch_type="eeg", min_length_good=0.2
)

# %%
# Check for NaN
annots_nan = annotate_nan(raw)

# sanity check: there should be no NaNs ...
assert len(annots_nan) == 0

# %%
# combine annotations
annots_bad = annots_flat + annots_break + annots_muscle + annots_nan

# ensure we can set the bad annotations to raw
raw.set_annotations(raw.annotations + annots_bad)

# save
fname_seg.parent.mkdir(parents=True, exist_ok=True)
annots_bad.save(fname_seg, overwrite=overwrite)

# %%
# update bad channels, if we found previously unknown ones
fname_bads = Path(FNAME_BADS_TEMPLATE.format(sub=sub))
if len(bads_flat) > 0 and fname_bads.exists():
    with open(fname_bads, "r") as fin:
        bads_dict = json.load(fin)

    file_changed = False
    for bad in bads_flat:
        if bad not in bads_dict["bad_by_flat"]:
            bads_dict["bad_by_flat"].append(bad)
            file_changed = True

    if file_changed:
        bads_dict_sorted = {}
        for key, val in bads_dict.items():
            bads_dict_sorted[key] = sorted(val)

        with open(fname_bads, "w") as fout:
            json.dump(bads_dict_sorted, fout, indent=4, sort_keys=True)
            fout.write("\n")

elif not fname_bads.exists():
    logger.info("File on bad channels not found. Did you run 01_find_bads.py?")

# %%


import socket
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    hostname = socket.gethostname()
    return_string = "Hello from {}!".format(hostname)
    return return_string

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


# Raw Package
from datetime import date
from plotly.subplots import make_subplots
import plotly.io as pio
import math

# Data Source
import yfinance as yf

# Data viz
import plotly.graph_objs as go

total_assets = 0
net_gains = 0
start_date = date.today
end_date = date.today

def set_data(stock_profile):
    # Interval required 1 minute
    stock_profile.data = yf.download(tickers=stock_profile.name, period=stock_profile.period,
                                     interval=stock_profile.interval)
    stock_profile.set_current(stock_profile.data.values.item(stock_profile.data.values.size - 2))
    global total_assets, net_gains
    net_gains += stock_profile.net_value
    total_assets += stock_profile.current_value

def get(my_stocks, columns):
    # declare figure
    fig = make_subplots(
        rows=math.ceil(len(my_stocks) / columns), cols=columns,  # loop array
        # subplot_titles=[stock.to_string() for stock in stocks],
        y_title='',  # y_title_font_color=stock.color_text
    )

    backgrounds = []
    interval = ''
    for count, stock in enumerate(my_stocks, start=1):
        row = math.ceil(count / columns)
        col = count - ((row - 1) * columns)
        # fig.add_trace(go.Candlestick(x=stock.data.index,
        # open=stock.data['Open'],
        # high=stock.data['High'],
        # low=stock.data['Low'],
        # close=stock.data['Close'], name=stock.name), row=row, col=col)
        set_data(stock)
        interval = stock.interval_string
        fig.add_trace(go.Scatter(x=stock.data.index, y=stock.data['Close'],
                                 mode='lines', connectgaps=True,
                                 line=dict(color=stock.color_text),
                                 # open=stock.data['Open'],
                                 # high=stock.data['High'],
                                 # low=stock.data['Low'],
                                 # close=stock.data['Close'],
                                 name=f'{stock.name}
{stock.net_value}'),
                      row=row, col=col)

        # Style the X and Y axes for each individual subplot
        fig.update_xaxes(title_text=stock.to_string(), row=row, col=col, rangeslider_visible=False,
                         title_font_color=stock.color_text, title_font_size=12)
        fig.update_yaxes(title_text=stock.name, row=row, col=col, title_font_color="black")
        cur_plot = fig.data[count - 1]
        sd = stock.data
        global start_date, end_date
        start_date = cur_plot.x[0]
        end_date = cur_plot.x[len(cur_plot.x) - 1]
        # Add the colored shape to each subplot depending on net positive or negative
        backgrounds.append(dict(type="rect",
                                xref=cur_plot.xaxis, yref=cur_plot.yaxis,
                                x0=int(start_date.timestamp() * 1000), x1=int(end_date.timestamp() * 1000),
                                y0=min(sd.Low.values), y1=max(sd.High.values), name=f"{stock.name}",
                                fillcolor=stock.color_bg, opacity=0.25, layer="above",
                                line_width=0))

    fig.update_layout(
        title_text=f'My Stock Portfolio - Total: {total_assets} | '
                   f'Net: {round(net_gains, 2)} - {interval} interval {start_date}  {end_date}',
        height=1400, font=dict(size=12), shapes=backgrounds)
    return pio.to_html(fig)


import re, urllib

################--Description--#################
#Regular Expression phone number formatting

################-----Author-----#################
#Carlos Nikiforuk

def main():
    print("\n-----Phone Number formatting----\nTo quit, type quit or exit.\n")
    while(True):
        good = False
        new = ""
        alpha = False
        inp = input("Enter a phone number: ")
        if(inp.lower() not in ['quit', 'exit']):
            format = re.match("([\d]{10})|(\([\d]{3}\)( |)[\d]{3}( |-)[\d]{4})|([\d]{3}(-| )[\d]{3}(-| )[\d]{4})",inp)
            if(format):
                num = re.sub('\D+','',inp)
                print("({}) {}-{}".format(num[0:3],num[3:6],num[6:10]))
            else:
                print("Bad Phone Number")
        else:
            exit()

main()


def main():
	a=[-2,-3,4,-1,-4,1,5,-33]
	dp=[[None for x in range(len(a)-1)] for i in range(len(a)-1)]
	# max_sum=get_max(a,dp)
	print(maxSubArraySum(a,len(a)))

def get_max(a,dp):
	for i in range(len(a)-1):
		if i>0:
			dp[0][i]=dp[0][i-1]+a[i]
		else:
			dp[0][i]=a[i]

	for i in range(1,len(a)):
		for j in range(i,len(a)-1):
			if dp[i][j]==None:
				dp[i][j]=dp[i-1][j]-dp[0][j-1]

	print(dp)
	m=dp[0][0]
	for i in dp:
		for j in i:
			if j:
				if m<j:
					m=j
	print(m)
def maxSubArraySum(a,size):

	max_so_far =a[0]
	curr_max = a[0]

	for i in range(1,size):
		curr_max = max(a[i], curr_max + a[i])
		max_so_far = max(max_so_far,curr_max)

	return max_so_far
if __name__ == '__main__':
	main()


from dsa import *

# get first val,
# incremenet count if the res == n and decrement if not.. and after it if the count == 0  then the new counter starts at 1 and res = n

def majorityElement(self, nums: List[int]) -> int:
    count = 0
    res = nums[0]
    for n in nums:
        if res == n:
            count += 1
        else:
            count -= 1

        if count == 0:
            res = n
            count = 1

    return res


import sys
sys.stdin = open('input_1431.txt')

'''
둘 다 29200KB / 84ms
'''

# T = int(input())
# for t in range(1, T+1):
#     N = int(input())
#     numbers = []
#     for _ in range(N):
#         serial = input()
#         num_sum = 0
#         for i in range(len(serial)):
#             if serial[i].isdigit():
#                 num_sum += int(serial[i])
#         numbers.append((serial, len(serial), num_sum))
#     numbers.sort(key=lambda x:(x[1], x[2], x[0]))
#     for n in range(N):
#         print(numbers[n][0])

def num_sum(serial): # 숫자 합 계산
    ns = 0
    for i in range(len(serial)):
        if serial[i].isdigit():
            ns += int(serial[i])
    return ns

T = int(input())
for t in range(1, T + 1):
    N = int(input())
    numbers = []

    for _ in range(N):
        serial = input()
        numbers.append(serial)

    numbers.sort(key = lambda x:(len(x), num_sum(x), x)) # key tuple 안에 넣어주는 순서대로 정렬됨

    for n in range(N):
        print(numbers[n])


import os, sys
import argparse
import time
import subprocess
import signal
import platform
import webbrowser
from termcolor import colored
import colorama

from utils.consts import *

colorama.init()

parser = argparse.ArgumentParser()
parser.add_argument('-r', '--registration', help='Run Registration',
    action='store_true')
args = vars(parser.parse_args())

# set system/version dependent "start_new_session" analogs
kwargs = {}
if platform.system() == 'Windows':
    # from msdn [1]
    CREATE_NEW_PROCESS_GROUP = 0x00000200  # note: could get it from subprocess
    DETACHED_PROCESS = 0x00000008          # 0x8 | 0x200 == 0x208
    kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
elif sys.version_info < (3, 2):  # assume posix
    kwargs.update(preexec_fn=os.setsid)
else:  # Python 3.2+ and Unix
    kwargs.update(start_new_session=True)

front_call = 'npm run serve'
back_call  = 'java -jar'
back_comp  = 'mvn clean install'
cv_call    = 'python tf_to_stream.py'

reg_call    = 'ng serve'

print(front_path)
print(back_path)
print(cv_path)
print(back_war)

def spc(amount=0):
    '''
        spc(amount=0)
        ---
        Returns:
        <amount>_of_spaces for formating purposes
    '''
    return ' ' * amount

def check_dir(file_path):
    '''
        ensure_dir(file_path)
        ---
        Makes path to <file_path> if it doesn't exist

    '''
    directory = os.path.dirname(file_path)
    if os.path.exists(directory):
        return 0
    return 1

def signal_handler(procs):
        print('You pressed Ctrl+C!')
        for proc in procs:
            proc.kill()
        sys.exit()

def run_proc(call, path):
	try:
	    p = subprocess.Popen(call, cwd=path, shell=True, **kwargs)
	    assert not p.poll()
	    return p
	except OSError as e:
	    print("Execution failed:", e)

def compile_back():
	return subprocess.call(back_comp, cwd=back_path, shell=True)

def preparation():

	err = 0

	print(' Checking Directories...\n')
	if check_dir(front_path) == 0:
		print(colored(' Looking for Front...' + spc(23) + '[ ' , color='white') + colored('  OK  ', color='green') + colored(' ]' , color='white'))
	else:
		print(colored(' Looking for Front...' + spc(23) + '[ ' , color='white') + colored('FAILED', color='red') + colored(' ]' , color='white'))
		print(colored(' Path ', color='yellow'), front_path, colored(' not found', color='yellow'))
		err += 1

	if check_dir(back_path) == 0:
		print(colored(' Looking for Back...' + spc(24) + '[ ' , color='white') + colored('  OK  ', color='green') + colored(' ]' , color='white'))
		if os.path.isfile(back_war):
			print(colored(' -> Looking for Back Executable...' + spc(10) + '[ ' , color='white') + colored('  OK  ', color='green') + colored(' ]' , color='white'))
		else:
			print(colored(' -> Looking for Back Executable...' + spc(10) + '[ ' , color='white') + colored('FAILED', color='red') + colored(' ]' , color='white'))
			print(colored(' -> Compiling...', color='yellow'))
			print()
			compile_back()
			print()
	else:
		print(colored(' Looking for Back...' + spc(24) + '[ ' , color='white') + colored('FAILED', color='red') + colored(' ]' , color='white'))
		print(colored(' Path ', color='yellow'), back_path, colored(' not found', color='yellow'))
		err += 1

	if check_dir(cv_path) == 0:
		print(colored(' Looking for CV...' + spc(26) + '[ ' , color='white') + colored('  OK  ', color='green') + colored(' ]' , color='white'))
	else:
		print(colored(' Looking for CV...' + spc(26) + '[ ' , color='white') + colored('FAILED', color='red') + colored(' ]' , color='white'))
		print(colored(' Path ', color='yellow'), cv_path, colored(' not found', color='yellow'))
		err += 1

	if err > 0:
		print(colored('\n Errors found. Check paths manually.'))
		exit(1)

def running():
	procs = []

	print('Starting Demonstration...\n')

	print('\n#######################################################\n')
	print(colored(' Starting Front...', color='yellow'))
	# print('\n#######################################################\n')
	procs.append(run_proc(front_call, front_path))
	time.sleep(1)

	print('\n#######################################################\n')
	print(colored(' Starting Back...', color='yellow'))
	# print(back_call + ' ' + os.path.basename(back_war))
	procs.append(run_proc(back_call + ' ' + os.path.basename(back_war), os.path.dirname(back_war)))
	time.sleep(1)

	print('\n#######################################################\n')
	print(colored(' Starting CV...', color='yellow'))
	procs.append(run_proc(cv_call, cv_path))

	return procs

def run_registration():
    procs = []

    print('Starting Registration...\n')
    return(procs.append(run_proc(reg_call, reg_path)))

def open_url(url):
    if sys.platform=='win32':
        webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open(url)
    elif sys.platform=='darwin':
        subprocess.Popen(['open', url])
    else:
        try:
            subprocess.Popen(['xdg-open', url])
        except OSError:
            print('Please open a browser on: ' + url)

procs = []

url = 'http://localhost:8080'

if not args.get('registration'):

    try:
        print('\n#######################################################\n')
        preparation()
        print('\n#######################################################\n')
        procs = running()
        print('\n#######################################################\n')

        time.sleep(7)
        open_url(url)

        exit_codes = [p.wait() for p in procs]

    except KeyboardInterrupt:

        for proc in procs:
            proc.kill()
        sys.exit()

        signal.signal(signal.SIGINT, signal_handler(procs))

else:
    url = 'http://localhost:4200'
    procs = run_registration()
    time.sleep(7)
    open_url(url)
    exit_codes = [p.wait() for p in procs]


# AB#143
import pandas as pd
import bs4
from bs4 import BeautifulSoup
from datetime import datetime
import requests
import re
from utilidadesppf import getCodList, clean
from re import findall
from urllib.request import Request, urlopen
def fundinnovation1(path, keywords = '(brazil|latin america region)'):
    try:
        filename = '\\fundinnovation_01.csv'
        titles = []
        links = []
        deadlines = []
        texts = []
        hasBrazil = []
        types = []
        eleg_texts = []
        dia = datetime.today().strftime("%y%m%d")
        ano = datetime.today().strftime('%y')
        page_response = requests.get('https://fundinnovation.dev/en/application-form-step-0/').content.decode('UTF-8')
        soup = BeautifulSoup(page_response, 'lxml')
        titulo = soup.find('h2').text
        #print(titulo)
        titles.append(titulo)

        links.append('https://fundinnovation.dev/en/application-form-step-0/')

        text = soup.find('div', class_= 'block-type-text').find('div', class_ = 'container-small').get_text()
        text = re.sub('\n', ' ', text)
        text = ' '.join(text.split()).strip()
        #print(text)
        texts.append(text)

        if(findall(keywords, text.lower())):
            hasBrazil.append('Y')
        else:
            hasBrazil.append('N')

        if len(findall('grant', text.lower())):
            types.append('grant')
        elif len(findall('fellowship', text.lower())):
            types.append('fellowship')
        elif len(findall('scholarship', text.lower())):
            types.append('scholarship')
        else:
            types.append('other')
        df = pd.DataFrame()
        df['opo_titulo'] = titles
        df['link'] = links
        df['opo_texto'] = texts
        df['opo_texto_ele'] = texts
        df['opo_brazil'] = hasBrazil
        df['opo_tipo'] = types
        df['opo_deadline'] = '31 de dezembro de 20' + ano
        df['codigo'] = getCodList(dia, len(df.index), '_1_', 'fundinnovation_')
        df['atualizacao'] = [dia]*len(df.index)
        df.to_csv(path + filename, index = False)
    except Exception as e:
        print(e)
        print('Erro em fundinnovation1')

def fundinnovation3(path):
    try:
        titulos = []
        textos = []
        dia = datetime.today().strftime('%y%m%d')
        filename = '\\fundinnovation_03.csv'
        req = Request('https://fundinnovation.dev/en/#about', headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'})
        page = urlopen(req).read()
        soup = BeautifulSoup(page, 'lxml')
        soup = soup.find('div', class_='col col-md-5')
        titulo = clean(soup.find('h2').text)
        titulos.append(titulo)
        texto = clean(soup.find('p').get_text())
        textos.append(texto)
        df = pd.DataFrame()
        df['pol_titulo'] = titulos
        df['pol_instituicao'] = ['fundinnovation']*len(df.index)
        df['pol_texto'] = textos
        df['link'] = ['https://fundinnovation.dev/en/#about']
        df['codigo'] = getCodList(dia, len(df.index), '_3_', 'fundinnovation_')
        df['atualizacao'] = [dia]*len(df.index)
        df.to_csv(path+filename, index=False)
    except Exception as e:
        print(e)
        print('Erro em fundinnovation3')


'''
Created on Feb 27, 2018

@author: dgrewal
'''
import logging
import os

import biowrappers.components.io.vcf.tasks as vcf_tasks
from single_cell.utils import helpers

def _get_header(infile):
    '''
    Extract header from the VCF file

    :param infile: input VCF file
    :return: header
    '''

    header = []
    for line in infile:
        if line.startswith('##'):
            header.append(line)
        elif line.startswith('#'):
            header.append(line)
            return header
        else:
            raise Exception('invalid header: missing #CHROM line')

    logging.getLogger("single_cell.helpers.vcfutils").warn(
        "One of the input files is empty"
    )
    return []

def concatenate_vcf(infiles, outfile):
    '''
    Concatenate VCF files

    :param infiles: dictionary of input VCF files to be concatenated
    :param outfile: output VCF file
    '''

    with open(outfile, 'w') as ofile:
        header = None

        for _, ifile in infiles.items():

            if os.path.getsize(ifile) == 0:
                logging.getLogger("single_cell.helpers.vcfutils").warn(
                    'input file {} is empty'.format(ifile)
                )
                continue

            with open(ifile) as f:

                if not header:
                    header = _get_header(f)

                    for line in header:
                        ofile.write(line)
                else:
                    if not _get_header(f) == header:
                        logging.getLogger("single_cell.helpers.vcfutils").warn(
                            'merging vcf files with mismatching headers'
                        )

                for l in f:
                    ofile.write(l)

def merge_vcf(infiles, outfile, tempdir, docker_image=None):
    vcf_files = []
    for infile in infiles:
        if isinstance(infile, str):
            vcf_files.append(infile)
        elif isinstance(infile, dict):
            vcf_files.extend(list(infile.values()))
        elif isinstance(infile, (list, tuple)):
            vcf_files.extend(list(infile))
        else:
            raise Exception("unknown data type")

    helpers.makedirs(tempdir)
    temp_output = os.path.join(tempdir, 'merged.vcf')

    vcf_tasks.merge_vcfs(vcf_files, temp_output)

    vcf_tasks.finalise_vcf(temp_output, outfile, docker_config={'docker_image': docker_image})


import os

from ogb.nodeproppred import PygNodePropPredDataset, Evaluator

import torch
import torch_geometric.transforms as T

from .get_graph_partitions import get_graph_partitions, get_train_node_per_part, neighbor_approx
from .get_label_partitions import get_label_partitions

def load_dataset(dataset_name, num_parts,
                 partition_method=0):
    # load OGB dataset
    dataset = PygNodePropPredDataset(name      = dataset_name,
                                     transform = T.ToSparseTensor())
    data      = dataset[0]
    split_idx = dataset.get_idx_split()

    # Create local partitions
    if partition_method == 0 or 2: # use metis based on graph structure
        print('Partition with metis based on graph structure')
        parts = get_graph_partitions(dataset      = dataset_name,
                                     num_clusters = num_parts,
                                     data = data,
                                     root = os.getcwd())
    elif partition_method == 1: # use label heterogeneous
        print('Partition based on label heterogeneous')
        parts = get_label_partitions(dataset      = dataset_name,
                                     num_clusters = num_parts,
                                     data = data,
                                     root = os.getcwd())
    else:
        print('Unknown partition method')

    train_parts = get_train_node_per_part(num_nodes   = data.x.size(0),
                                          train_nodes = split_idx['train'].numpy(),
                                          parts       = parts)
    if partition_method == 2:
        # convert PyG data structure to scipy's sparse_coo for metis partition
        import numpy as np
        from scipy.sparse import csr_matrix

        row = data.adj_t.storage.row().numpy()
        col = data.adj_t.storage.col().numpy()
        num_nodes = data.adj_t.size(0)

        all_nodes = np.arange(num_nodes)
        sparse_coo_adj = csr_matrix((np.ones_like(row), (row, col)), shape=(num_nodes, num_nodes))

        parts_with_approx = [neighbor_approx(sparse_coo_adj, part) for part in parts]

        data.parts = [torch.tensor(part) for part in parts_with_approx]
    else:
        data.parts = [torch.tensor(part) for part in parts]
    data.train_parts = [torch.tensor(part) for part in train_parts]

    # add eval
    evaluator = Evaluator(name=dataset_name)

    return dataset, data, split_idx, evaluator

def sparse_tensor_to_edge_indices(adj):
    row = adj.storage.row()
    col = adj.storage.col()
    return torch.stack([row, col])


from flask import Flask, request, redirect, url_for, render_template

# Global variable of nested dictionaries. Each dictionary represents a view
# corresponding to a cell in the html table. The entry with the key "centre"
# represents the name of the view. Each view can be thought as a tree node with
# 4 children and a name.
DATA = {"centre":"Once upon a time, there was a big bad world.", "top":None, "bottom":None, "right":None, "left":None}

# Global pointer variable to the current view (node) of the data structure (DATA).
CURRENT = DATA

app = Flask(__name__)

@app.route("/", methods=["GET"])
def get():
    """Handle GET request on root url by pointing CURRENT to the designeted view."""
    global CURRENT

    position = request.args.get("position", None)
    if position is not None:
        CURRENT = CURRENT[position]

    return render_template("index.html", **CURRENT)

@app.route("/", methods=["POST"])
def post():
    """Handle POST request on root url by creating and assigning a new view to CURRENT
    and consequently DATA."""
    global CURRENT

    CURRENT[request.args["position"]] = {"centre":request.form["text"], "top":None, "bottom":None, "right":None, "left":None}

    return render_template("index.html", **CURRENT)

@app.route("/reset", methods=["GET"])
def reset():
    """Handle GET request on /reset url by pointing CURRENT to the root dictionary."""
    global CURRENT

    CURRENT = DATA

    return redirect(url_for("get"))

if __name__ == "__main__":
    app.run(debug=True)