import math
import numpy as np
import torch
from torch.autograd.functional import vjp
from einops import rearrange

from model.base import BaseModule

class Mish(BaseModule):
    def forward(self, x):
        return x * torch.tanh(torch.nn.functional.softplus(x))

class Upsample(BaseModule):
    def __init__(self, dim):
        super(Upsample, self).__init__()
        self.conv = torch.nn.ConvTranspose2d(dim, dim, 4, 2, 1)

    def forward(self, x):
        return self.conv(x)

class Downsample(BaseModule):
    def __init__(self, dim):
        super(Downsample, self).__init__()
        self.conv = torch.nn.Conv2d(dim, dim, 3, 2, 1)

    def forward(self, x):
        return self.conv(x)

class Rezero(BaseModule):
    def __init__(self, fn):
        super(Rezero, self).__init__()
        self.fn = fn
        self.g = torch.nn.Parameter(torch.zeros(1))

    def forward(self, x):
        return self.fn(x) * self.g

class Block(BaseModule):
    def __init__(self, dim, dim_out, groups=8):
        super(Block, self).__init__()
        self.block = torch.nn.Sequential(torch.nn.Conv2d(dim, dim_out, 3,
                                         padding=1), torch.nn.GroupNorm(
                                         groups, dim_out), Mish())

    def forward(self, x, mask):
        output = self.block(x * mask)
        return output * mask

class ResnetBlock(BaseModule):
    def __init__(self, dim, dim_out, time_emb_dim, groups=8):
        super(ResnetBlock, self).__init__()
        self.mlp = torch.nn.Sequential(Mish(), torch.nn.Linear(time_emb_dim,
                                                               dim_out))

        self.block1 = Block(dim, dim_out, groups=groups)
        self.block2 = Block(dim_out, dim_out, groups=groups)
        if dim != dim_out:
            self.res_conv = torch.nn.Conv2d(dim, dim_out, 1)
        else:
            self.res_conv = torch.nn.Identity()

    def forward(self, x, mask, time_emb):
        h = self.block1(x, mask)
        h += self.mlp(time_emb).unsqueeze(-1).unsqueeze(-1)
        h = self.block2(h, mask)
        output = h + self.res_conv(x * mask)
        return output

class LinearAttention(BaseModule):
    def __init__(self, dim, heads=4, dim_head=32):
        super(LinearAttention, self).__init__()
        self.heads = heads
        hidden_dim = dim_head * heads
        self.to_qkv = torch.nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
        self.to_out = torch.nn.Conv2d(hidden_dim, dim, 1)

    def forward(self, x):
        b, c, h, w = x.shape
        qkv = self.to_qkv(x)
        q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)',
                            heads = self.heads, qkv=3)
        k = k.softmax(dim=-1)
        context = torch.einsum('bhdn,bhen->bhde', k, v)
        out = torch.einsum('bhde,bhdn->bhen', context, q)
        out = rearrange(out, 'b heads c (h w) -> b (heads c) h w',
                        heads=self.heads, h=h, w=w)
        return self.to_out(out)

class Residual(BaseModule):
    def __init__(self, fn):
        super(Residual, self).__init__()
        self.fn = fn

    def forward(self, x, *args, **kwargs):
        output = self.fn(x, *args, **kwargs) + x
        return output

class SinusoidalPosEmb(BaseModule):
    def __init__(self, dim, pe_scale):
        super(SinusoidalPosEmb, self).__init__()
        self.dim = dim
        self.pe_scale = pe_scale

    def forward(self, x):
        device = x.device
        half_dim = self.dim // 2
        emb = math.log(10000) / (half_dim - 1)
        emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
        emb = self.pe_scale * x.unsqueeze(1) * emb.unsqueeze(0)
        emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
        return emb

class ScoreMatchingNetwork(BaseModule):
    def __init__(self, base_dim, class_dim, n_classes, dim_mults=(1, 2, 4),
                 groups=8, pe_scale=1000):
        super(ScoreMatchingNetwork, self).__init__()

        dims = [1 + class_dim, *map(lambda m: base_dim * m, dim_mults)]
        in_out = list(zip(dims[:-1], dims[1:]))

        self.time_pos_emb = SinusoidalPosEmb(base_dim, pe_scale)
        self.mlp = torch.nn.Sequential(torch.nn.Linear(base_dim, base_dim * 4),
                               Mish(), torch.nn.Linear(base_dim * 4, base_dim))

        cond_total = class_dim + base_dim
        self.c_embedding = torch.nn.Embedding(n_classes, class_dim)
        self.class_block = torch.nn.Sequential(torch.nn.Linear(cond_total, 4 * class_dim),
                                        Mish(), torch.nn.Linear(4 * class_dim, class_dim))

        self.downs = torch.nn.ModuleList([])
        self.ups = torch.nn.ModuleList([])
        num_resolutions = len(in_out)

        for ind, (dim_in, dim_out) in enumerate(in_out):
            is_last = ind >= (num_resolutions - 1)
            self.downs.append(torch.nn.ModuleList([
                       ResnetBlock(dim_in, dim_out, time_emb_dim=base_dim),
                       ResnetBlock(dim_out, dim_out, time_emb_dim=base_dim),
                       Residual(Rezero(LinearAttention(dim_out))),
                       Downsample(dim_out) if not is_last else torch.nn.Identity()]))

        mid_dim = dims[-1]
        self.mid_block1 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=base_dim)
        self.mid_attn = Residual(Rezero(LinearAttention(mid_dim)))
        self.mid_block2 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=base_dim)

        for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])):
            self.ups.append(torch.nn.ModuleList([
                     ResnetBlock(dim_out * 2, dim_in, time_emb_dim=base_dim),
                     ResnetBlock(dim_in, dim_in, time_emb_dim=base_dim),
                     Residual(Rezero(LinearAttention(dim_in))),
                     Upsample(dim_in)]))
        self.final_block = Block(base_dim, base_dim)
        self.final_conv = torch.nn.Conv2d(base_dim, 1, 1)

    def forward(self, x, mask, c, t):
        t_ = self.time_pos_emb(t)
        t = self.mlp(t_)

        x = x.unsqueeze(1)
        mask = mask.unsqueeze(1)

        condition = torch.cat([t_, self.c_embedding(c)], 1)
        condition = self.class_block(condition).unsqueeze(-1).unsqueeze(-1)
        condition = torch.cat(x.shape[2]*[condition], 2)
        condition = torch.cat(x.shape[3]*[condition], 3)
        x = torch.cat([x, condition], 1)

        hiddens = []
        masks = [mask]
        for resnet1, resnet2, attn, downsample in self.downs:
            mask_down = masks[-1]
            x = resnet1(x, mask_down, t)
            x = resnet2(x, mask_down, t)
            x = attn(x)
            hiddens.append(x)
            x = downsample(x * mask_down)
            masks.append(mask_down[:, :, :, ::2])

        masks = masks[:-1]
        mask_mid = masks[-1]
        x = self.mid_block1(x, mask_mid, t)
        x = self.mid_attn(x)
        x = self.mid_block2(x, mask_mid, t)

        for resnet1, resnet2, attn, upsample in self.ups:
            mask_up = masks.pop()
            x = torch.cat((x, hiddens.pop()), dim=1)
            x = resnet1(x, mask_up, t)
            x = resnet2(x, mask_up, t)
            x = attn(x)
            x = upsample(x * mask_up)

        x = self.final_block(x, mask)
        output = self.final_conv(x * mask)

        return (output * mask).squeeze(1)

class Diffusion(BaseModule):
    def __init__(self, n_feats, n_classes, base_dim, class_dim,
                 beta_min, beta_max):
        super(Diffusion, self).__init__()
        self.estimator = ScoreMatchingNetwork(base_dim, class_dim, n_classes)
        self.n_feats = n_feats
        self.n_classes = n_classes
        self.base_dim = base_dim
        self.class_dim = class_dim
        self.beta_min = beta_min
        self.beta_max = beta_max
        self.batch = 16
        self.tau = 0.95
        self.omega = 0.05
        self.silence_threshold = -20.0

    def get_beta(self, t):
        beta = self.beta_min + (self.beta_max - self.beta_min) * t
        return beta

    def get_gamma(self, s, t, p=1.0, use_torch=False):
        beta_integral = self.beta_min + 0.5*(self.beta_max - self.beta_min)*(t + s)
        beta_integral *= (t - s)
        if not use_torch:
            gamma = math.exp(-0.5*p*beta_integral)
        else:
            gamma = torch.exp(-0.5*p*beta_integral).unsqueeze(-1).unsqueeze(-1)
        return gamma

    def estimate_x0(self, xt, mask, c, t):
        t_torch = torch.ones(xt.shape[0], dtype=xt.dtype, device=xt.device,
                             requires_grad=False) * t
        ex0 = self.estimator(xt, mask, c, t_torch)
        alpha_t = self.get_gamma(0, t, p=1.0)
        sigma2_t = 1.0 - self.get_gamma(0, t, p=2.0)
        ex0 = (xt + ex0 * sigma2_t) / alpha_t
        return ex0

    def diffuse(self, x0, mask, t):
        mean = x0 * self.get_gamma(0, t, p=1.0, use_torch=True)
        variance = 1.0 - self.get_gamma(0, t, p=2.0, use_torch=True)
        z = torch.randn(x0.shape, dtype=x0.dtype, device=x0.device,
                        requires_grad=False)
        xt = mean + z * torch.sqrt(variance)
        return xt * mask, z * mask

    @torch.no_grad()
    def forward_diffusion(self, x0, mask, c, n_timesteps=100):
        h = self.tau / n_timesteps
        xs = x0 * mask
        for i in range(n_timesteps):
            s = i*h
            t = s + h
            ex0 = self.estimate_x0(xs, mask, c, s)
            alpha_s = self.get_gamma(0, s, p=1.0)
            alpha_t = self.get_gamma(0, t, p=1.0)
            sigma_s = math.sqrt(1.0 - self.get_gamma(0, s, p=2.0))
            sigma_t = math.sqrt(1.0 - self.get_gamma(0, t, p=2.0))
            xs = 2*xs - (alpha_s * ex0 + sigma_s * (xs - alpha_t * ex0) / sigma_t)
            xs *= mask
        return xs

    def reverse_diffusion(self, z, mask, c,
                          pitch_fn, chroma_fn, loudness_fn, clf_fn,
                          pitch_value, chroma_value, loudness_value,
                          pitch_weight, chroma_weight, loudness_weight,
                          clf_weight, n_timesteps=100):
        h = self.tau / n_timesteps
        base_norm = torch.linalg.norm(z).item()
        pitch_weight *= base_norm
        chroma_weight *= base_norm
        loudness_weight *= base_norm
        clf_weight *= base_norm
        alpha = torch.from_numpy(np.linspace(0, 1, self.batch)).float().to(z)
        alpha = alpha.unsqueeze(-1).unsqueeze(-1).detach()
        xt = torch.cat([z * mask]*self.batch, 0)
        mask = torch.cat([mask]*self.batch, 0)
        c = torch.cat([c]*self.batch, 0)

        def opt_pitch_fn(x):
            error = (pitch_fn(x) - pitch_value) ** 2
            error = error * (loudness_value > self.silence_threshold)
            return 0.5 * torch.mean(error, dim=(1, 2))

        def opt_chroma_fn(x):
            error = torch.mean((chroma_fn(x) - chroma_value) ** 2, dim=1)
            error = error * (loudness_value > self.silence_threshold).squeeze(1)
            return 0.5 * torch.mean(error, dim=1)

        def opt_loudness_fn(x):
            threshold = self.silence_threshold * torch.ones_like(loudness_value)
            loudness_source = torch.maximum(loudness_value, threshold)
            loudness_converted = torch.maximum(loudness_fn(x), threshold)
            error = (loudness_source - loudness_converted) ** 2
            return 0.5 * torch.mean(error, dim=(1, 2))

        def opt_clf_fn(x):
            msk = (loudness_value > self.silence_threshold).squeeze(1)
            cls_result = clf_fn(x)[:, c[0].item(), :]
            cls_result = ~msk + cls_result * msk
            return cls_result.min(-1)[0]

        with torch.no_grad():
            pitch_error = opt_pitch_fn(xt.detach())
            chroma_error = opt_chroma_fn(xt.detach())
            loudness_error = opt_loudness_fn(xt.detach())
            clf_prob = opt_clf_fn(xt.detach())
        print('\nInitial MSE in pitch = %.4f' % pitch_error.mean().item())
        print('Initial MSE in chroma = %.4f' % chroma_error.mean().item())
        print('Initial MSE in loudness = %.4f' % loudness_error.mean().item())
        print('Initial min probability = %.2f%%' % (100.0 * clf_prob.mean().item()))
        ones = torch.ones_like(clf_prob).detach()

        with torch.no_grad():
            ex0 = self.estimate_x0(xt, mask, c, self.tau)

        chroma_list = []
        for i in range(n_timesteps):
            t = self.tau - i*h
            s = t - h
            if t < self.omega:
                chroma_list.append(chroma_error[k])

            alpha_s = self.get_gamma(0, s, p=1.0)
            alpha_t = self.get_gamma(0, t, p=1.0)
            sigma_s = math.sqrt(1.0 - self.get_gamma(0, s, p=2.0))
            sigma_t = math.sqrt(1.0 - self.get_gamma(0, t, p=2.0))

            pitch_error, v = vjp(opt_pitch_fn, ex0, ones, create_graph=False, strict=True)
            v_norm = torch.linalg.norm(v, dim=(1, 2), keepdim=True)
            v_pitch = v * (pitch_weight / v_norm)

            chroma_error, v = vjp(opt_chroma_fn, ex0, ones, create_graph=False, strict=True)
            v_norm = torch.linalg.norm(v, dim=(1, 2), keepdim=True)
            v_chroma = v * (chroma_weight / v_norm)

            loudness_error, v = vjp(opt_loudness_fn, ex0, ones, create_graph=False, strict=True)
            v_norm = torch.linalg.norm(v, dim=(1, 2), keepdim=True)
            v_loudness = v * (loudness_weight / v_norm)

            clf_prob, v = vjp(opt_clf_fn, ex0, ones, create_graph=False, strict=True)
            v_norm = torch.linalg.norm(v, dim=(1, 2), keepdim=True)
            v_clf = v * (clf_weight / v_norm)

            v = (v_clf - v_chroma - v_loudness - v_pitch) / alpha_t
            with torch.no_grad():
                ex0_mod = ex0 + alpha*v
                xt = alpha_s * ex0_mod + sigma_s * (xt - alpha_t * ex0_mod) / sigma_t
                xt *= mask
                ex0_fwd = self.estimate_x0(xt, mask, c, s)
                pitch_error = opt_pitch_fn(ex0_fwd).cpu().numpy()
                chroma_error = opt_chroma_fn(ex0_fwd).cpu().numpy()
                loudness_error = opt_loudness_fn(ex0_fwd).cpu().numpy()
                clf_prob = opt_clf_fn(ex0_fwd).cpu().numpy()
                if np.isnan(pitch_error).all() or np.isnan(chroma_error).all():
                    xt = torch.cat([ex0[0, :, :].unsqueeze(0)]*self.batch, 0)
                    print('Forced stop at timestep %.3f [score function failure]' % t)
                    break
                if i % 4 == 0 or t < self.omega:
                    k = np.nanargmin(chroma_error)
                elif i % 4 == 1:
                    k = np.nanargmin(loudness_error)
                elif i % 4 == 2:
                    k = np.nanargmin(pitch_error)
                else:
                    k = np.nanargmax(clf_prob)
                if t < self.omega and chroma_error[k] > min(chroma_list):
                    xt = torch.cat([ex0[0, :, :].unsqueeze(0)]*self.batch, 0)
                    print('Early stop!')
                    break
                print('\nt = %.3f' % t)
                print('MSE in pitch = %.4f' % pitch_error[k].item())
                print('MSE in chroma = %.4f' % chroma_error[k].item())
                print('MSE in loudness = %.4f' % loudness_error[k].item())
                print('Min probability = %.2f%%' % (100.0 * clf_prob[k].item()))
                ex0 = torch.cat([ex0_fwd[k, :, :].unsqueeze(0)]*self.batch, 0)
                xt = torch.cat([xt[k, :, :].unsqueeze(0)]*self.batch, 0)

        with torch.no_grad():
            pitch_error = opt_pitch_fn(xt.detach()).cpu().numpy()
            chroma_error = opt_chroma_fn(xt.detach()).cpu().numpy()
            loudness_error = opt_loudness_fn(xt.detach()).cpu().numpy()
            clf_prob = opt_clf_fn(xt.detach()).cpu().numpy()
        k = 0
        print('\nFinal MSE in pitch = %.4f' % pitch_error[k])
        print('Final MSE in chroma = %.4f' % chroma_error[k])
        print('Final MSE in loudness = %.4f' % loudness_error[k])
        print('Final min probability = %.2f%%' % (100.0 * clf_prob[k]))
        return xt[k, :, :].unsqueeze(0)

    @torch.no_grad()
    def forward(self, z, mask, c, n_timesteps=100):
        h = self.tau / n_timesteps
        xt = z * mask
        for i in range(n_timesteps):
            t = self.tau - i*h
            s = t - h
            ex0 = self.estimate_x0(xt, mask, c, t)
            alpha_s = self.get_gamma(0, s, p=1.0)
            alpha_t = self.get_gamma(0, t, p=1.0)
            sigma_s = math.sqrt(1.0 - self.get_gamma(0, s, p=2.0))
            sigma_t = math.sqrt(1.0 - self.get_gamma(0, t, p=2.0))
            xt = alpha_s * ex0 + sigma_s * (xt - alpha_t * ex0) / sigma_t
            xt *= mask
        return xt

    def loss_t(self, x0, mask, c, t):
        xt, z = self.diffuse(x0, mask, t)
        noise_estimation = self.estimator(xt, mask, c, t)
        noise_estimation *= torch.sqrt(1.0 - self.get_gamma(0, t, p=2.0, use_torch=True))
        loss = torch.sum((noise_estimation + z)**2) / (torch.sum(mask)*self.n_feats)
        return loss

    def compute_loss(self, x0, mask, c, offset=1e-5):
        t = torch.rand(x0.shape[0], dtype=x0.dtype, device=x0.device,
                       requires_grad=False)
        t = torch.clamp(t, offset, 1.0 - offset)
        return self.loss_t(x0, mask, c, t)


"""

Write a Python script to convert Fahrenheit to Celsius and Celsius to Fahrenheit.

Celcius Formula:  Celsius = (Fahrenheit - 32) / (9 / 5)

Fahrenheit Formula:  Fahrenheit = Celsius * 9 / 5 + 32

Prompt the user to enter a Fahrenheit / Celsius value and then perform the calculations.

"""

def fahrenheit_to_celsius():
   fahrenheit=int(input("Enter the Fahrenheit :"))
   celsius =(fahrenheit-32) /(9/5)
   print('celsius is ',celsius)

def celsius_to_fahrenheit():
   celsius=int(input("Enter the Celsius :"))
   fahrenheit =celsius*9/5+32
   print('fahrenheit is ',fahrenheit)

fahrenheit_to_celsius()
celsius_to_fahrenheit()


# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
import PSim
import pickle
import csv
import simplex
import time

fit_type = 'global'

load_time = time.strftime('%Y.%m.%d.%H.%M')
filename = "simplex_{}_output_{}.log".format(fit_type, load_time)

with open("pickled_data.p", "r") as file:
    pickled_data = pickle.load(file)

powers = pickled_data['powers']
xdata = pickled_data['allxdata']
ydata = pickled_data['allydata']
xarray = pickled_data['xarray']
yarrays = pickled_data['yarrays']
averages = pickled_data['averages']
period = 50  # ns

with open("pickled_data_250.p", "r") as file:
    pickled_data_250 = pickle.load(file)

powers_250 = pickled_data_250['powers']
xdata_250 = pickled_data_250['allxdata']
ydata_250 = pickled_data_250['allydata']
xarray_250 = pickled_data_250['xarray']
yarrays_250 = pickled_data_250['yarrays']
averages_250 = pickled_data_250['averages']
period_250 = 1.0 / 250000.0 / 1e-9  # ns

ssn = 0

def scalar_min(data):
    xdata, ydata, scaled_ysim = data[0]
    xdata_250, ydata_250, scaled_ysim_250 = data[1]
    err_20 = 0
    err_250 = 0
    num_points = 0
    if (fit_type is 'global') or (fit_type is 20):  # 20 MHz data
        for dat, sim in zip(ydata, scaled_ysim):
            for x, d, s in zip(xdata, dat, sim):
                try:
                    if s > 0:
                        log_s = np.log(s)
                    else:
                        log_s = 0
                    log_d = np.log(d)
                    error = (log_s - log_d)
                    # error = np.log(error)
                    err_20 += error*error
                    num_points = num_points + 1
                except:
                    err_20 += 8e20
        err_20 = err_20 / num_points
        num_points = 0
    if (fit_type is 'global') or (fit_type is 250):  # 250 kHz data
        for dat, sim in zip(ydata_250[:-1], scaled_ysim_250[:-1]):  # Exclude the lowest noisy power
            for x, d, s in zip(xdata_250, dat, sim):
                try:
                    if s > 0:
                        log_s = np.log(s)
                    else:
                        log_s = 0
                    log_d = np.log(d)
                    error = (log_s - log_d)
                    # error = np.log(error)
                    if x >= -0.25 and x <= 120:
                        err_250 += error*error
                        num_points = num_points + 1
                except:
                    err_250 += 8e20
        err_250 = err_250 / num_points
    if fit_type is 'global':
        err = np.sqrt(err_250*err_20)
    elif fit_type is 20:
        err = err_20
    elif fit_type is 250:
        err = err_250
    else:
        err = 6e20
    if np.isnan(err):
        err = 7e20
    fitness = err * 100
    return fitness

def evaluate(p):
    global ssn
    dummy_x = np.zeros(10)
    dummy_y = np.zeros([10, 10])
    data = [[dummy_x, dummy_y, dummy_y], [dummy_x, dummy_y, dummy_y]]
    if fit_type is 'global' or fit_type is 20:  # 20 MHz data
        sim = PSim.DecaySim(reprate=20000000, tolerance=0.005, step=5e-12)
        sim.trap = p[0]
        sim.EHdecay = p[1] * sim.step
        sim.Etrap = p[2] * sim.step
        sim.FHloss = p[3] * sim.step
        sim.Gdecay = p[4] * sim.step
        sim.G2decay = p[5] * sim.step
        sim.G3decay = p[6] * sim.step
        sim.GHdecay = p[7] * sim.step
        sim.Gescape = p[8] * sim.step
        sim.Gform = p[9] * sim.step * 0
        sim.G3loss = p[10] * sim.step
        sim.scalar = p[11]
        for power in powers:
            sim.addPower(power)
        sim.runSim()
        interp_signals = []
        for this_run in sim.signal:
            interp_this = np.interp(xarray, sim.xdata, this_run)
            interp_signals.append(interp_this)
        interp_signals = np.array(interp_signals)
        data[0] = [xarray, yarrays, interp_signals]
    if fit_type is 'global' or fit_type is 250:  # 250 kHz data
        sim_250 = PSim.DecaySim(reprate=250000, tolerance=0.005, step=5e-12)
        sim_250.trap = p[0]
        sim_250.EHdecay = p[1] * sim_250.step
        sim_250.Etrap = p[2] * sim_250.step
        sim_250.FHloss = p[3] * sim_250.step
        sim_250.Gdecay = p[4] * sim_250.step
        sim_250.G2decay = p[5] * sim_250.step
        sim_250.G3decay = p[6] * sim_250.step
        sim_250.GHdecay = p[7] * sim_250.step
        sim_250.Gescape = p[8] * sim_250.step
        sim_250.Gform = p[9] * sim_250.step * 0
        sim_250.G3loss = p[10] * sim_250.step
        sim_250.scalar = p[11]
        for power in powers_250:
            sim_250.addPower(power)
        sim_250.runSim()
        interp_signals_250 = []
        for this_run in sim_250.signal:
            interp_this = np.interp(xarray_250, sim_250.xdata, this_run)
            interp_signals_250.append(interp_this)
        interp_signals_250 = np.array(interp_signals_250)
        data[1] = [xarray_250, yarrays_250, interp_signals_250]
    fitness = scalar_min(data=data)
    for param in p:
        if param < 0:
            fitness = fitness * 100000
    with open(filename, 'a') as log_file:
        writer = csv.writer(log_file, dialect="excel-tab")
        row = [ssn, '{:.4e}'.format(fitness)]
        for var in p:
            row.append('{:.4e}'.format(var))
        writer.writerow(row)
    ssn = ssn + 1
    return fitness

def main():
    try:
        logname = 'best_{}.log'.format(fit_type)
        with open(logname, 'rb') as best_file:
            reader = csv.reader(best_file, dialect='excel-tab')
            p0 = []
            for val in reader.next():
                p0.append(np.float(val))
        p0 = np.array(p0)
        ranges = p0*0.02
        s = simplex.Simplex(evaluate, p0, ranges)
        p, err, iter = s.minimize(epsilon=0.00001, maxiters=2000,
                                  monitor=0)
        with open(logname, 'a') as save_file:
            writer = csv.writer(save_file, dialect='excel-tab')
            writer.writerow(p)
            writer.writerow([ssn, err])
    except Exception as e:
        print(e)

if __name__ == '__main__':
    main()


import uuid

from odoo import models, fields, _, api, tools
from odoo.exceptions import ValidationError

class InventoryManagement(models.Model):
    _name = 'inventory.management'
    _description = 'Inventory Management'

    @tools.ormcache()
    def _get_default_uom_id(self):
        # Deletion forbidden (at least through unlink)
        return self.env.ref('uom.product_uom_unit')

    product_id = fields.Many2one('product.product', string='Product', required=True, index=True)
    uom_id = fields.Many2one('uom.uom', 'Unit of Measure', default=_get_default_uom_id, required=True,
                             help="Default unit of measure used for all stock operations.")
    product_material_category_id = fields.Many2one(related='product_id.product_material_category_id', store=True)
    product_material_id = fields.Many2one(related='product_id.product_material_id', store=True)
    product_alloy_id = fields.Many2one(related='product_id.product_alloy_id', store=True)
    product_stiffness_id = fields.Many2one(related='product_id.product_stiffness_id', store=True)
    product_long = fields.Float(string='Size 3')
    product_width = fields.Float(string='Size 2')
    product_thickness = fields.Float(string='Size 1')
    quantity = fields.Float(string='Quantity')
    quantity_kg = fields.Float(string='Quantity Kg')
    lot = fields.Char(string='Lot')
    warehouse_id = fields.Many2one('oristar.warehouse', string='Warehouse')
    last_update_time = fields.Datetime(string='Last Update')
    erp_id = fields.Char(string='ERP ID', readonly=True, default=lambda self: uuid.uuid4())

    @api.constrains('erp_id')
    def _check_erp_id(self):
        for r in self:
            existing_record = self.search([('erp_id', '=', r.erp_id), ('id', '!=', r.id)])
            if existing_record:
                raise ValidationError(_("ERP ID must be unique."))


import numpy as np

import sem.kps_tracker
import third_party.sort

class ObjectTracker():
    """
    this class tracks the bbox and semantic keypoints
    """
    def __init__(self, sort_max_age, sort_min_hit, last_img_id):
        # reset tracker id
        third_party.sort.KalmanBoxTracker.count = 1
        self.bbox_tracker = third_party.sort.Sort(sort_max_age, sort_min_hit, last_img_id)
        self.kps_tracker = sem.kps_tracker.KpsTracker()
        self.lost_object_ids = []

def convert_bboxes_list2array(object_bboxes):
    """
    :param object_bboxes: list of detected bbox
    :return: size nx4, bbox in xyxy format
    """
    det = np.zeros((0, 4))
    for bbox in object_bboxes:
        bbox = np.reshape(bbox, (1, -1))
        det = np.concatenate((det, bbox), axis=0)
    return det


# A. Roma and Lucky Numbers

n, k = map(int, input().split())
a = list(input().split())

ans = 0
lucky = ['4', '7']
for x in a:
    count = 0
    for digit in x:
        if digit in lucky:
            count += 1
            if count > k:
                break
    if count <= k:
        ans += 1

print(ans)


#!/usr/bin/env python3
# coding: utf-8
# File: abstract_textrank.py
# Author: lhy<lhy_in_blcu@126.com,https://huangyong.github.io>
# Date: 18-4-17

from collections import defaultdict
import jieba.posseg as pseg
from .textrank import *
from .sentence_similarity import *
import re

class AbstarctTextrank:
    def __init__(self):
        self.span = 3
        self.similer = SimilarityCompute()
        self.sim_score = 0.5 #句子相似度阈值，用于构建句子之间的边

    def sentence_split(self, text):
        sentence_dict = {}
        sentences = [sentence for sentence in re.split(r'[？！。;；\n\r]', text) if sentence]
        for index, sentence in enumerate(sentences):
            sentence_dict[index] = [sentence, [word.word for word in pseg.cut(sentence) if word.flag[0] not in ['x', 'u', 'p', 'w']]]
        return sentence_dict

    def extract_abstract(self, text, num_sentences):
        sentence_dict = self.sentence_split(text)
        g = textrank_graph()
        cm = defaultdict(int)
        for i, s1 in sentence_dict.items():
            for j, s2 in sentence_dict.items():
                sim_score = self.similer.similarity_cosine(s1[1], s2[1])
                if sim_score >= 0.5:
                    cm[(s1[0], s2[0])] += 1
        for terms, w in cm.items():
            g.addEdge(terms[0], terms[1], w)
        nodes_rank = g.rank()
        nodes_rank = sorted(nodes_rank.items(), key=lambda asd: asd[1], reverse=True)
        return nodes_rank[:num_sentences]

# def test():
#     text = '''（原标题：央视独家采访：陕西榆林产妇坠楼事件在场人员还原事情经过）
#     央视新闻客户端11月24日消息，2017年8月31日晚，在陕西省榆林市第一医院绥德院区，产妇马茸茸在待产时，从医院五楼坠亡。事发后，医院方面表示，由于家属多次拒绝剖宫产，最终导致产妇难忍疼痛跳楼。但是产妇家属却声称，曾向医生多次提出剖宫产被拒绝。
#     事情经过究竟如何，曾引起舆论纷纷，而随着时间的推移，更多的反思也留给了我们，只有解决了这起事件中暴露出的一些问题，比如患者的医疗选择权，人们对剖宫产和顺产的认识问题等，这样的悲剧才不会再次发生。央视记者找到了等待产妇的家属，主治医生，病区主任，以及当时的两位助产师，一位实习医生，希望通过他们的讲述，更准确地还原事情经过。
#     产妇待产时坠亡，事件有何疑点。公安机关经过调查，排除他杀可能，初步认定马茸茸为跳楼自杀身亡。马茸茸为何会在医院待产期间跳楼身亡，这让所有人的目光都聚焦到了榆林第一医院，这家在当地人心目中数一数二的大医院。
#     就这起事件来说，如何保障患者和家属的知情权，如何让患者和医生能够多一份实质化的沟通？这就需要与之相关的法律法规更加的细化、人性化并且充满温度。用这种温度来消除孕妇对未知的恐惧，来保障医患双方的权益，迎接新生儿平安健康地来到这个世界。'''
#
#     abstracter = AbstarctTextrank()
#     keysentences = abstracter.extract_abstract(text, 3)
#
#     for sent in keysentences:
#         print(sent)
#     '''
#     ('就这起事件来说，如何保障患者和家属的知情权，如何让患者和医生能够多一份实质化的沟通', 1.0)
#     ('事情经过究竟如何，曾引起舆论纷纷，而随着时间的推移，更多的反思也留给了我们，只有解决了这起事件中暴露出的一些问题，比如患者的医疗选择权，人们对剖宫产和顺产的认识问题等，这样的悲剧才不会再次发生', 0.9999999860476693)
#     ('（原标题：央视独家采访：陕西榆林产妇坠楼事件在场人员还原事情经过）', 0.99999402813924)
#     '''
#
# test()


import requests,json
import urllib3
urllib3.disable_warnings()
url = "https://api.covid19tracking.narrativa.com/api/countries/spain/regions"
response = requests.request("GET", url, verify=False)
data = dict(json.loads(response.text))
print("Spain Regions")
print("--------")
sort=[]
for elem in data["countries"][0]["spain"]:
    sort.append(elem["name"])

sort=sorted(sort)
for elem in sort:
    print(elem)


# coding: utf-8

import os
import zipfile
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import *

from chardet import detect
from com import *
from fastpip import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from res.res import *
from settings import *
from ui import *

from .messagebox import MessageBox
from .query_file_path import QueryFilePath

DEFAULT_CUSTOM_TMPDIR = "scf_reqs"
DEFAULT_GENERATED_DIR = "scf_dist"

class CloudFunctionWindow(Ui_cloud_function, QMainWindow, QueryFilePath):
    REQUIRE_FILE = "requirements.txt"
    signal_packing = pyqtSignal(bool, str)
    signal_reqinstalled = pyqtSignal(int, str, bool)
    signal_show_workingtips = pyqtSignal(str)

    def __init__(self, parent):
        super().__init__(parent)
        self.setupUi(self)
        self.__setup_other_widgets()
        self.config = CloudFunctionConfig()
        self.thread_repo = ThreadRepo(500)
        self.environments: Optional[List[EnvDisplayPair]] = None
        self.__signal_connection()
        self.__path_ctrlgroup = (
            self.uiComboBox_preject_path,
            self.uiPushButton_clear_path,
            self.uiPushButton_select_projectdir,
        )
        self.__work_ctrlgroup = (
            self.uiTableWidget_reqirement_lines,
            self.uiPushButton_add_line,
            self.uiPushButton_delete_line,
            self.uiPushButton_start_scfpacking,
        )
        self.__change_ctrlgroups_state(False)

    def display(self):
        self.resize(*self.config.window_size)
        if self.isMaximized():
            self.showMaximized()
        else:
            self.showNormal()
        if self.thread_repo.is_empty():
            self.config_dict_to_widgets()

    def __save_window_size(self):
        if self.isMinimized() or self.isMinimized():
            return
        self.config.window_size = self.width(), self.height()

    def closeEvent(self, event: QCloseEvent):
        if not self.thread_repo.is_empty():
            MessageBox(
                "提示",
                "打包任务正在进行，关闭此窗口不会结束任务，但关闭启动窗口可能会强行结束任务！",
                QMessageBox.Warning,
                parent=self,
            ).exec_()
        self.__save_window_size()
        self.config_widgets_to_dict()
        self.config.save_config()

    def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Escape:
            self.close()

    def eventFilter(self, sender: QObject, event: QEvent) -> bool:
        if (
            sender == self.uiLabel_whatis_cloudfunction
            and event.type() == QEvent.MouseButtonRelease
        ):
            QDesktopServices.openUrl(
                QUrl("https://cloud.tencent.com/product/scf")
            )
            return True
        elif (
            sender == self.uiLabel_set_excludes
            and event.type() == QEvent.MouseButtonRelease
        ):
            CloudExcludesWindow(self).display()
            return True
        return super().eventFilter(sender, event)

    def __signal_connection(self):
        self.uiPushButton_clear_path.clicked.connect(
            self.__remove_combo_project_path
        )
        self.uiPushButton_select_projectdir.clicked.connect(
            lambda: self.__select_dirpath_settext(
                self.uiComboBox_preject_path.setCurrentText
            )
        )
        self.uiPushButton_start_scfpacking.clicked.connect(
            self.__start_cloud_function_packing
        )
        self.uiCheckBox_confirm_project_path.clicked.connect(
            self.__checkbox_confirm_projectpath
        )
        self.uiPushButton_add_line.clicked.connect(self.__add_requirement_line)
        self.uiPushButton_delete_line.clicked.connect(
            self.__delete_requirement_line
        )
        self.uiPushButton_save_config.clicked.connect(
            self.__save_current_configs
        )
        self.uiPushButton_del_scfconfig.clicked.connect(
            self.__delete_selected_config
        )
        self.uiPushButton_switch_config.clicked.connect(
            self.__checkout_saved_config
        )
        self.uiRadioButton_using_projectdir.clicked.connect(
            self.__workingdir_option_changed
        )
        self.uiRadioButton_using_customtemp.clicked.connect(
            self.__workingdir_option_changed
        )
        self.uiRadioButton_using_autotempdir.clicked.connect(
            self.__workingdir_option_changed
        )
        self.uiPushButton_select_customdir.clicked.connect(
            lambda: self.__select_dirpath_settext(
                self.uiLineEdit_customdir_path.setText
            )
        )
        self.uiPushButton_select_generateddir.clicked.connect(
            lambda: self.__select_dirpath_settext(
                self.uiLineEdit_generateddir.setText
            )
        )
        self.signal_packing.connect(self.__on_scfpacking_completed)
        self.signal_reqinstalled.connect(self.__set_requirement_install_result)
        self.signal_show_workingtips.connect(self.uiLabel_working_tips.setText)
        self.uiListWidget_config_list.clicked.connect(
            self.__scfconfig_list_clicked
        )

    def __setup_other_widgets(self):
        self.uiComboBox_python_envs.setView(QListView())
        self.uiComboBox_preject_path.setView(QListView())
        delegate = ItemDelegate(self.uiTableWidget_reqirement_lines, False)
        self.uiTableWidget_reqirement_lines.setItemDelegateForColumn(
            1, delegate
        )
        self.uiTableWidget_reqirement_lines.setItemDelegateForColumn(
            2, delegate
        )
        horiz_head = self.uiTableWidget_reqirement_lines.horizontalHeader()
        horiz_head.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        horiz_head.setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.uiComboBox_preject_path.lineEdit().clear()
        self.uiLabel_set_excludes.installEventFilter(self)
        self.uiLabel_whatis_cloudfunction.installEventFilter(self)
        self.__working_movie = QMovie(":/loading.gif")
        self.__working_movie.setScaledSize(QSize(16, 16))
        self.uiLabel_working_movie.setMovie(self.__working_movie)
        self.uiLabel_working_movie.hide()

    def __show_working(self):
        self.uiLabel_working_tips.clear()
        self.__working_movie.start()
        self.uiLabel_working_movie.show()

    def __hide_working(self):
        self.uiLabel_working_tips.clear()
        self.__working_movie.stop()
        self.uiLabel_working_movie.hide()

    def __load_requirements_update_table(self, confirm: bool):
        if confirm:
            project = self.uiComboBox_preject_path.currentText()
            requirements = os.path.join(project, self.REQUIRE_FILE)
            if not os.path.isfile(requirements):
                return
            with open(requirements, "rb") as b:
                encoding = detect(b.read())["encoding"]
            with open(requirements, "rt", encoding=encoding) as f:
                content_lines = f.readlines()
            self.uiTableWidget_reqirement_lines.clearContents()
            self.uiTableWidget_reqirement_lines.setRowCount(len(content_lines))
            for row, line in enumerate(content_lines):
                self.uiTableWidget_reqirement_lines.setItem(
                    row, 0, QTableWidgetItem(line.strip())
                )
        else:
            self.uiTableWidget_reqirement_lines.setRowCount(0)

    def __change_ctrlgroups_state(self, confirm: bool):
        for ctrl in self.__work_ctrlgroup:
            ctrl.setEnabled(confirm)
        for ctrl in self.__path_ctrlgroup:
            ctrl.setEnabled(not confirm)

    def __checkbox_confirm_projectpath(self):
        project = self.uiComboBox_preject_path.currentText()
        confirm = self.uiCheckBox_confirm_project_path.isChecked()
        if os.path.isabs(project) and os.path.isdir(project):
            if confirm:
                self.__check_add_projectpath(project)
                self.uiLineEdit_generatedname.setPlaceholderText(
                    os.path.basename(project)
                )
                self.uiLineEdit_generateddir.setPlaceholderText(
                    os.path.join(project, DEFAULT_GENERATED_DIR)
                )
                self.uiLineEdit_customdir_path.setPlaceholderText(
                    os.path.join(project, DEFAULT_CUSTOM_TMPDIR)
                )
            else:
                self.uiLineEdit_generateddir.setPlaceholderText("")
                self.uiLineEdit_generatedname.setPlaceholderText("")
                self.uiLineEdit_customdir_path.setPlaceholderText("")
            self.__change_ctrlgroups_state(confirm)
            self.__load_requirements_update_table(confirm)
        else:
            MessageBox(
                "提示",
                "当前的项目路径不是绝对路径或者不是一个目录路径！",
                QMessageBox.Warning,
                parent=self,
            ).exec_()
            self.uiCheckBox_confirm_project_path.setChecked(False)

    def __remove_combo_project_path(self):
        cur_index = self.uiComboBox_preject_path.currentIndex()
        if cur_index != -1:
            del self.config.current.project_paths[cur_index]
            self.uiComboBox_preject_path.removeItem(cur_index)

    def __check_add_projectpath(self, project: str):
        if project and project not in self.config.current.project_paths:
            self.uiComboBox_preject_path.addItem(project)
            self.config.current.project_paths.append(project)

    def __environs_combobox_update(self):
        if self.uiComboBox_python_envs.count() != 0:
            return
        if not self.config.cur_pypaths:
            return
        if self.environments:
            return
        self.environments = [
            EnvDisplayPair(PyEnv(p)) for p in self.config.cur_pypaths
        ]
        item_number = len(self.environments)
        if not item_number:
            return
        for i, envp in enumerate(self.environments):
            self.uiComboBox_python_envs.addItem(envp.display)
            envp.signal_connect(self.uiComboBox_python_envs.setItemText, i)
            envp.load_real_display()
        current_index = self.config.current.selected_env
        if current_index < 0 or current_index >= item_number:
            self.config.current.selected_env = current_index = 0
        self.uiComboBox_python_envs.setCurrentIndex(current_index)

    def __project_paths_combobox_update(self):
        if self.uiComboBox_preject_path.count() != 0:
            return
        self.uiComboBox_preject_path.addItems(self.config.current.project_paths)

    def config_widgets_to_dict(self):
        self.config.current.selected_env = (
            self.uiComboBox_python_envs.currentIndex()
        )
        self.config.current.overwrite_reqfile = (
            self.uiCheckBox_overwrite_requirement.isChecked()
        )
        self.config.current.projectpath_index = (
            self.uiComboBox_preject_path.currentIndex()
        )
        if self.uiRadioButton_using_autotempdir.isChecked():
            self.config.current.working_tmpdir = WorkDir.TmpDir
        elif self.uiRadioButton_using_projectdir.isChecked():
            self.config.current.working_tmpdir = WorkDir.Project
        elif self.uiRadioButton_using_customtemp.isChecked():
            self.config.current.working_tmpdir = WorkDir.Custom
        else:
            self.config.current.working_tmpdir = WorkDir.TmpDir
        self.config.current.custom_tempdir = (
            self.uiLineEdit_customdir_path.text()
        )
        self.config.current.generated_dir = self.uiLineEdit_generateddir.text()
        self.config.current.generated_name = (
            self.uiLineEdit_generatedname.text()
        )
        self.config.current.overwrite_samefile = (
            self.uiCheckBox_overwrite_samefile.isChecked()
        )
        self.config.current.upgrade_requires = (
            self.uiCheckBox_upgrade_requires.isChecked()
        )

    def config_dict_to_widgets(self, config_name=None):
        self.__update_configuration_list()
        if config_name:
            self.config.checkout_cfg(config_name)
        else:
            self.__environs_combobox_update()
        self.uiComboBox_python_envs.setCurrentIndex(
            self.config.current.selected_env
        )
        self.__project_paths_combobox_update()
        self.uiCheckBox_overwrite_requirement.setChecked(
            self.config.current.overwrite_reqfile
        )
        self.uiComboBox_preject_path.setCurrentIndex(
            self.config.current.projectpath_index
        )
        working_dir = self.config.current.working_tmpdir
        self.uiRadioButton_using_projectdir.setChecked(
            working_dir == WorkDir.Project
        )
        self.uiRadioButton_using_customtemp.setChecked(
            working_dir == WorkDir.Custom
        )
        self.uiRadioButton_using_autotempdir.setChecked(
            working_dir == WorkDir.TmpDir
        )
        self.__workingdir_option_changed()
        self.uiLineEdit_customdir_path.setText(
            self.config.current.custom_tempdir
        )
        self.uiLineEdit_generateddir.setText(self.config.current.generated_dir)
        self.uiLineEdit_generatedname.setText(
            self.config.current.generated_name
        )
        self.uiCheckBox_overwrite_samefile.setChecked(
            self.config.current.overwrite_samefile
        )
        self.uiCheckBox_upgrade_requires.setChecked(
            self.config.current.upgrade_requires
        )

    def __select_dirpath_settext(self, settextFunc: Callable[[str], None]):
        _path = self.get_dir_path(self.config.current.previous_path)
        if not _path:
            return
        settextFunc(_path)
        self.config.current.previous_path = _path

    def __get_table_requirement_items(self) -> List[str]:
        requirements = list()
        for i in range(self.uiTableWidget_reqirement_lines.rowCount()):
            item = self.uiTableWidget_reqirement_lines.item(i, 0)
            if not item:
                continue
            require = item.text()
            if not require:
                continue
            requirements.append(require)
        return requirements

    def __on_scfpacking_completed(self, succeeded, message):
        if succeeded:
            MessageBox(
                "打包成功",
                "云函数部署包已打包完成！",
                QMessageBox.Information,
                parent=self,
            ).exec_()
        else:
            MessageBox(
                "打包失败",
                message or "在打包过程中出现了错误...",
                QMessageBox.Critical,
                parent=self,
            ).exec_()

    def __cleartable_requirments(self):
        for i in range(self.uiTableWidget_reqirement_lines.rowCount()):
            item = self.uiTableWidget_reqirement_lines.item(i, 1)
            if item:
                item.setText("")

    def __start_cloud_function_packing(self):
        self.__cleartable_requirments()
        env_index = self.uiComboBox_python_envs.currentIndex()
        if env_index == -1 or not self.environments:
            MessageBox(
                "警告",
                "没有选择任何 Python 环境，请检查...",
                QMessageBox.Warning,
                parent=self,
            ).exec_()
            return
        upgrade = self.uiCheckBox_upgrade_requires.isChecked()
        environment = self.environments[env_index].environ
        projectdir = self.uiComboBox_preject_path.currentText()
        if not (os.path.isabs(projectdir) and os.path.isdir(projectdir)):
            MessageBox(
                "错误",
                "项目目录路径不是绝对路径，或者路径不是一个目录路径...",
                QMessageBox.Critical,
                parent=self,
            ).exec_()
            return
        requirements = self.__get_table_requirement_items()
        if self.uiCheckBox_overwrite_requirement.isChecked():
            self.__write_requirements(projectdir, requirements)
        customtmpdir_text = (
            self.uiLineEdit_customdir_path.text()
            or self.uiLineEdit_customdir_path.placeholderText()
        )
        if self.uiRadioButton_using_autotempdir.isChecked():
            workingdir_type = WorkDir.TmpDir
        elif self.uiRadioButton_using_projectdir.isChecked():
            workingdir_type = WorkDir.Project
        elif self.uiRadioButton_using_customtemp.isChecked():
            if not customtmpdir_text:
                MessageBox(
                    "错误",
                    "没有输入自定义工作目录路径...",
                    QMessageBox.Critical,
                    parent=self,
                ).exec_()
                return
            workingdir_type = WorkDir.Custom
        else:
            MessageBox(
                "错误",
                "未知的工作目录选项，请反馈给开发者...",
                QMessageBox.Critical,
                parent=self,
            ).exec_()
            return
        generated_name = (
            self.uiLineEdit_generatedname.text()
            or self.uiLineEdit_generatedname.placeholderText()
        )
        if not generated_name:
            MessageBox(
                "错误",
                "还没有指定生成的文件名，请检查...",
                QMessageBox.Critical,
                parent=self,
            ).exec_()
            return
        generated_dir = (
            self.uiLineEdit_generateddir.text()
            or self.uiLineEdit_generateddir.placeholderText()
        )
        if not generated_dir:
            MessageBox(
                "错误",
                "还没有指定打包文件保存目录，请检查...",
                QMessageBox.Critical,
                parent=self,
            ).exec_()
            return
        generated_file = Path(generated_dir).joinpath(generated_name)
        if not generated_file.suffix.lower() == ".zip":
            generated_file = generated_file.with_suffix(".zip")
        overwrite_samefile = self.uiCheckBox_overwrite_samefile.isChecked()

        def start_scfpackaging():
            self.signal_show_workingtips.emit("开始检查打包条件...")
            if not overwrite_samefile and generated_file.exists():
                self.signal_packing.emit(
                    False, f"已存在<{generated_file}>文件且不允许覆盖..."
                )
                return
            if not os.path.exists(generated_dir):
                try:
                    os.makedirs(generated_dir, exist_ok=True)
                except PermissionError:
                    self.signal_packing.emit(False, "打包文件保存目录创建失败...")
                    return
            elif not os.path.isdir(generated_dir):
                self.signal_packing.emit(False, "打包文件保存路径不是一个目录...")
                return
            workingdir_handle = ""
            if workingdir_type == WorkDir.TmpDir:
                try:
                    workingdir_handle = TemporaryDirectory()
                except Exception as e:
                    self.signal_packing.emit(False, f"临时工作目录创建失败：\n{e}")
                    return
                requires_install_path = workingdir_handle.name
            elif workingdir_type == WorkDir.Custom:
                if os.path.isabs(customtmpdir_text):
                    workingdir_handle = customtmpdir_text
                else:
                    workingdir_handle = os.path.join(
                        projectdir, customtmpdir_text
                    )
                if not os.path.exists(workingdir_handle):
                    try:
                        os.makedirs(workingdir_handle, exist_ok=True)
                    except Exception as e:
                        self.signal_packing.emit(False, f"自定义工作目录创建失败：\n{e}")
                        return
                elif not os.path.isdir(workingdir_handle):
                    self.signal_packing.emit(False, "自定义工作路径不是目录...")
                    return
                requires_install_path = workingdir_handle
            elif workingdir_type == WorkDir.Project:
                if not os.path.isdir(projectdir):
                    self.signal_packing.emit(False, "作为工作目录的项目目录不可用...")
                    return
                requires_install_path = projectdir
            else:
                self.signal_packing.emit(
                    False, f"未知的工作目录类型：{workingdir_type!r}"
                )
                return
            self.signal_show_workingtips.emit("开始安装项目的依赖包...")
            # 本来设计是每个包独立安装的，但是发现一起安装能节省很多时间
            # 所以就砍掉了每个依赖包安装完成就更新安装结果的功能，改为一次性更新
            if requirements:
                _, result = environment.install(
                    *requirements, target=requires_install_path, upgrade=upgrade
                )
                if not result:
                    self.signal_packing.emit(False, f"一个或多个依赖包安装失败，打包中断...")
                    if isinstance(workingdir_handle, TemporaryDirectory):
                        workingdir_handle.cleanup()
                    return
                for index, name in enumerate(requirements):
                    self.signal_reqinstalled.emit(index, name, result)
            self.signal_show_workingtips.emit("开始创建压缩文件...")
            compressed_arcnames: Dict[Path, Path] = dict()
            exclude_paths = [Path(generated_dir).resolve()]
            try:
                with zipfile.ZipFile(
                    generated_file, "w", zipfile.ZIP_DEFLATED
                ) as binary_file:
                    if workingdir_type != WorkDir.Project:
                        filtered_filepaths = self.__filtered_files(
                            Path(projectdir),
                            exclude_paths + [Path(requires_install_path)],
                        )
                    else:
                        filtered_filepaths = self.__filtered_files(
                            Path(projectdir), exclude_paths
                        )
                    for _path in filtered_filepaths:
                        arcfilename = _path.relative_to(projectdir)
                        binary_file.write(_path, arcfilename)
                        compressed_arcnames[arcfilename] = _path
                    if workingdir_type != WorkDir.Project:
                        for _path in self.__filtered_files(
                            Path(requires_install_path), exclude_paths
                        ):
                            arcfilename = _path.relative_to(
                                requires_install_path
                            )
                            if arcfilename in compressed_arcnames:
                                self.signal_packing.emit(
                                    False,
                                    f"继续打包将使以下文件将在压缩包内重复，请处理：\n"
                                    f"{compressed_arcnames[arcfilename]!s}\n{_path!s}",
                                )
                                return
                            binary_file.write(_path, arcfilename)
            except Exception as e:
                self.signal_packing.emit(False, f"创建压缩文件出错：\n{e}")
                return
            finally:
                if isinstance(workingdir_handle, TemporaryDirectory):
                    self.signal_show_workingtips.emit("正在清理临时文件夹...")
                    workingdir_handle.cleanup()
            self.signal_packing.emit(True, None)

        packaging_thread = QThreadModel(start_scfpackaging)
        packaging_thread.before_starting(
            self.__lock_critical_widgets, self.__show_working
        )
        packaging_thread.after_completion(
            self.__release_critical_widgets, self.__hide_working
        )
        packaging_thread.start()
        self.thread_repo.put(packaging_thread, 0)

    def __filtered_files(
        self, _path: Path, prev_excludeds: List[Path]
    ) -> Generator[Path, None, None]:
        previous_cwd = os.getcwd()
        try:
            os.chdir(_path)
            prev_excludeds.extend(
                Path(apath).resolve()
                for apath in self.config.current.excluded_paths
            )
            for afile in _path.rglob("*"):
                if not afile.is_file():
                    continue
                for excluded in prev_excludeds:
                    if excluded.is_file() and afile.samefile(excluded):
                        break
                    elif excluded.is_dir() and excluded in afile.parents:
                        break
                else:
                    yield afile
        finally:
            os.chdir(previous_cwd)

    def __set_requirement_install_result(
        self, index: int, name: str, res: bool
    ):
        if index < 0 or index >= self.uiTableWidget_reqirement_lines.rowCount():
            return
        item = self.uiTableWidget_reqirement_lines.item(index, 0)
        if item is None or item.text() != name:
            return
        result_item = QTableWidgetItem("安装成功" if res else "安装失败")
        result_item.setData(
            Qt.UserRole, RoleData.Success if res else RoleData.Failed
        )
        self.uiTableWidget_reqirement_lines.setItem(index, 1, result_item)

    def __add_requirement_line(self):
        self.uiTableWidget_reqirement_lines.setRowCount(
            self.uiTableWidget_reqirement_lines.rowCount() + 1
        )

    def __delete_requirement_line(self):
        row = self.uiTableWidget_reqirement_lines.currentIndex().row()
        if row == -1:
            return
        self.uiTableWidget_reqirement_lines.removeRow(row)

    def __write_requirements(self, parent, requirements):
        if not requirements:
            return
        try:
            with open(
                os.path.join(parent, self.REQUIRE_FILE),
                "wt",
                encoding="utf-8",
            ) as f:
                f.write(os.linesep.join(requirements))
        except Exception as e:
            MessageBox(
                "错误",
                f"无法重写‘{self.REQUIRE_FILE}’文件：\n{e}",
                QMessageBox.Critical,
                parent=self,
            ).exec_()

    def __lock_critical_widgets(self):
        self.uiPushButton_start_scfpacking.setEnabled(False)
        self.uiCheckBox_confirm_project_path.setEnabled(False)
        self.uiPushButton_add_line.setEnabled(False)
        self.uiPushButton_delete_line.setEnabled(False)
        self.uiRadioButton_using_customtemp.setEnabled(False)
        self.uiRadioButton_using_autotempdir.setEnabled(False)
        self.uiRadioButton_using_projectdir.setEnabled(False)
        self.uiCheckBox_overwrite_samefile.setEnabled(False)
        self.uiLineEdit_generateddir.setEnabled(False)
        self.uiLineEdit_generatedname.setEnabled(False)
        self.uiPushButton_select_generateddir.setEnabled(False)
        self.uiCheckBox_upgrade_requires.setEnabled(False)
        self.uiCheckBox_overwrite_requirement.setEnabled(False)

    def __release_critical_widgets(self):
        self.uiPushButton_start_scfpacking.setEnabled(True)
        self.uiCheckBox_confirm_project_path.setEnabled(True)
        self.uiPushButton_add_line.setEnabled(True)
        self.uiPushButton_delete_line.setEnabled(True)
        self.uiRadioButton_using_customtemp.setEnabled(True)
        self.uiRadioButton_using_autotempdir.setEnabled(True)
        self.uiRadioButton_using_projectdir.setEnabled(True)
        self.uiCheckBox_overwrite_samefile.setEnabled(True)
        self.uiLineEdit_generateddir.setEnabled(True)
        self.uiLineEdit_generatedname.setEnabled(True)
        self.uiPushButton_select_generateddir.setEnabled(True)
        self.uiCheckBox_upgrade_requires.setEnabled(True)
        self.uiCheckBox_overwrite_requirement.setEnabled(True)

    def __update_configuration_list(self, force=False):
        if force:
            self.uiListWidget_config_list.clear()
        elif self.uiListWidget_config_list.count() != 0:
            return
        self.uiListWidget_config_list.addItems(self.config.multicfg)

    def __save_current_configs(self):
        config_name = (
            self.uiLineEdit_config_name.text()
            or self.uiLineEdit_config_name.placeholderText()
        )
        if not config_name:
            MessageBox(
                "警告",
                "还没有输入要保存的配置方案名称。",
                QMessageBox.Warning,
                parent=self,
            ).exec_()
            return
        if config_name in self.config.multicfg:
            if (
                MessageBox(
                    "询问",
                    f"配置方案列表中已经存在名为{config_name}的配置，确定要覆盖吗？",
                    QMessageBox.Question,
                    (("accept", "确定"), ("reject", "取消")),
                    self,
                ).exec_()
                != 0
            ):
                return
        self.uiLineEdit_config_name.clear()
        self.config_widgets_to_dict()
        self.config.store_curcfg(config_name)
        self.__update_configuration_list(force=True)

    def __delete_selected_config(self):
        if not len(self.config.multicfg):
            MessageBox(
                "提示",
                "没有任何已保存的配置方案。",
                QMessageBox.Information,
                parent=self,
            ).exec_()
            return
        selected_item = self.uiListWidget_config_list.currentItem()
        if not selected_item:
            return MessageBox("提示", "没有选择任何配置。").exec_()
        config_name = selected_item.text()
        if config_name not in self.config.multicfg:
            return
        if (
            MessageBox(
                "询问",
                f"即将被删除的配置：{config_name}",
                QMessageBox.Question,
                (("accept", "确定"), ("reject", "取消")),
                self,
            ).exec_()
            != 0
        ):
            return
        del self.config.multicfg[config_name]
        self.__update_configuration_list(force=True)

    def __checkout_saved_config(self):
        if not len(self.config.multicfg):
            MessageBox(
                "提示",
                "没有已保存的配置。",
                QMessageBox.Information,
                parent=self,
            ).exec_()
            return
        config_item = self.uiListWidget_config_list.currentItem()
        if not config_item:
            MessageBox(
                "提示",
                "没有选择任何配置。",
                QMessageBox.Information,
                parent=self,
            ).exec_()
            return
        self.config_dict_to_widgets(config_item.text())
        self.uiListWidget_config_list.setCurrentRow(-1)
        MessageBox(
            "提示", "配置数据切换成功...", QMessageBox.Information, parent=self
        ).exec_()

    def __workingdir_option_changed(self):
        custom = self.uiRadioButton_using_customtemp.isChecked()
        self.uiLineEdit_customdir_path.setEnabled(custom)
        self.uiPushButton_select_customdir.setEnabled(custom)

    def __scfconfig_list_clicked(self):
        index = self.uiListWidget_config_list.currentRow()
        if index == -1:
            return
        self.uiLineEdit_config_name.setText(
            self.uiListWidget_config_list.item(index).text()
        )

class CloudExcludesWindow(Ui_cloud_excludes, QMainWindow, QueryFilePath):
    def __init__(self, parent: CloudFunctionWindow = None):
        self.__parent = parent
        super().__init__(parent)
        self.setupUi(self)
        self.__setup_widgets()
        self.uiPushButton_add_dirpath.clicked.connect(self.__add_dirpath)
        self.uiPushButton_add_filepath.clicked.connect(self.__add_filepath)
        self.uiPushButton_del_line.clicked.connect(self.__delete_line)
        self.uiPushButton_clear_items.clicked.connect(self.__clear_table_items)
        self.uiPushButton_new_line.clicked.connect(self.__add_new_line)

    def __setup_widgets(self):
        self.uiPushButton_add_dirpath.setIcon(QIcon(":/add_dir.png"))
        self.uiPushButton_add_filepath.setIcon(QIcon(":/add_file.png"))
        self.uiPushButton_new_line.setIcon(QIcon(":/new_line.png"))
        self.uiPushButton_del_line.setIcon(QIcon(":/del_line.png"))
        self.uiPushButton_clear_items.setIcon(QIcon(":/clear.png"))
        self.uiTableWidget_exclude_paths = DropableTableWidget(
            self,
            tooltip=self.uiTableWidget_exclude_paths_old.toolTip(),
        )
        self.uiTableWidget_exclude_paths.setObjectName(
            "uiTableWidget_exclude_paths"
        )
        self.horizontalLayout.replaceWidget(
            self.uiTableWidget_exclude_paths_old,
            self.uiTableWidget_exclude_paths,
        )
        self.uiTableWidget_exclude_paths_old.deleteLater()
        self.uiTableWidget_exclude_paths.setRowCount(
            len(self.__parent.config.current.excluded_paths)
        )
        for row, text in enumerate(self.__parent.config.current.excluded_paths):
            self.uiTableWidget_exclude_paths.setItem(
                row, 0, QTableWidgetItem(text)
            )

    def display(self):
        self.resize(*self.__parent.config.exc_windowsize)
        if self.isMaximized():
            self.showMaximized()
        else:
            self.showNormal()

    def __save_window_size(self):
        if self.isMinimized() or self.isMinimized():
            return
        self.__parent.config.exc_windowsize = self.width(), self.height()

    def closeEvent(self, event: QCloseEvent):
        self.__parent.config.current.excluded_paths = (
            self.uiTableWidget_exclude_paths.getItemsText()
        )
        self.__save_window_size()

    def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Escape:
            self.close()

    def __add_filepath(self):
        paths, previous = self.get_file_paths(
            self.__parent.config.current.previous_path
        )
        if paths:
            row = self.uiTableWidget_exclude_paths.rowCount()
            self.uiTableWidget_exclude_paths.setRowCount(row + len(paths))
            for increase, _path in enumerate(paths):
                self.uiTableWidget_exclude_paths.setItem(
                    row + increase, 0, QTableWidgetItem(_path)
                )
            self.__parent.config.current.previous_path = previous

    def __add_dirpath(self):
        _path = self.get_dir_path(self.__parent.config.current.previous_path)
        if _path:
            row = self.uiTableWidget_exclude_paths.rowCount()
            self.uiTableWidget_exclude_paths.setRowCount(row + 1)
            self.uiTableWidget_exclude_paths.setItem(
                row, 0, QTableWidgetItem(_path)
            )
            self.__parent.config.current.previous_path = _path

    def __delete_line(self):
        selected_row_indexes = [
            r.row() for r in self.uiTableWidget_exclude_paths.selectedIndexes()
        ]
        if not selected_row_indexes:
            MessageBox(
                "提示", "没有选中任何项目...", QMessageBox.Information, parent=self
            ).exec_()
            return
        selected_row_indexes.sort()
        top_row = selected_row_indexes[0]
        selected_count = len(selected_row_indexes)
        for ii, row in enumerate(selected_row_indexes):
            self.uiTableWidget_exclude_paths.removeRow(row)
            for remain_i in range(ii + 1, selected_count):
                # 因为表格只有一列，行索引不会有重复的，所以这里不做进一步判断
                selected_row_indexes[remain_i] -= 1
        remain_row_count = self.uiTableWidget_exclude_paths.rowCount()
        if remain_row_count:
            if top_row >= remain_row_count:
                top_row = remain_row_count - 1
            self.uiTableWidget_exclude_paths.setRangeSelected(
                QTableWidgetSelectionRange(top_row, 0, top_row, 0), True
            )

    def __add_new_line(self):
        self.uiTableWidget_exclude_paths.setRowCount(
            self.uiTableWidget_exclude_paths.rowCount() + 1
        )

    def __clear_table_items(self):
        self.uiTableWidget_exclude_paths.setRowCount(0)


# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 15:40:29 2018

@author: Kaushik
"""

from flask import Flask, render_template, request, session, redirect, url_for, flash
import os
from werkzeug.utils import secure_filename
from tensorflow.keras.models import load_model
import matplotlib.pyplot as plt
import cv2
import numpy as np

UPLOAD_FOLDER = './flask app/assets/images'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
# Create Database if it doesnt exist

app = Flask(__name__,static_url_path='/assets',
            static_folder='./flask app/assets',
            template_folder='./flask app')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def root():
   return render_template('index.html')

@app.route('/index.html')
def index():
   return render_template('index.html')

@app.route('/contact.html')
def contact():
   return render_template('contact.html')

@app.route('/news.html')
def news():
   return render_template('news.html')

@app.route('/about.html')
def about():
   return render_template('about.html')

@app.route('/faqs.html')
def faqs():
   return render_template('faqs.html')

@app.route('/prevention.html')
def prevention():
   return render_template('prevention.html')

@app.route('/upload_chest.html')
def upload_chest():
   return render_template('upload_chest.html')

@app.route('/upload_ct.html')
def upload_ct():
   return render_template('upload_ct.html')

@app.route('/uploaded_chest', methods = ['POST', 'GET'])
def uploaded_chest():
   if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file:
            # filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], 'upload_chest.jpg'))

   resnet_chest = load_model('/home/zahrael97/Downloads/COVID-19-Detection-Flask-App-based-on-Chest-X-rays-and-CT-Scans-master/models/covid_model_v3.h5')

   image = cv2.imread('./flask app/assets/images/upload_chest.jpg') # read file
   image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # arrange format as per keras
   image = cv2.resize(image,(224,224))
   image = np.array(image) / 255
   image = np.expand_dims(image, axis=0)

   resnet_pred = resnet_chest.predict(image)
   probability = resnet_pred[0]
   print("Resnet Predictions:")
   if probability[0] > 0.5:
      resnet_chest_pred = str('%.2f' % (probability[0]*100) + '% COVID')
   else:
      resnet_chest_pred = str('%.2f' % ((1-probability[0])*100) + '% NonCOVID')
   print(resnet_chest_pred)

   return render_template('results_chest.html',resnet_chest_pred=resnet_chest_pred)

@app.route('/uploaded_ct', methods = ['POST', 'GET'])
def uploaded_ct():
   if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file:
            # filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], 'upload_ct.jpg'))

   resnet_ct = load_model('/home/zahrael97/Downloads/COVID-19-Detection-Flask-App-based-on-Chest-X-rays-and-CT-Scans-master/models/InceptionV3.h5')

   image = cv2.imread('./flask app/assets/images/upload_ct.jpg') # read file
   image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # arrange format as per keras
   image = cv2.resize(image,(224,224))
   image = np.array(image) / 255
   image = np.expand_dims(image, axis=0)

   resnet_pred = resnet_ct.predict(image)
   probability = resnet_pred[0]
   print("Resnet Predictions:")
   if probability[0] > 0.5:
      resnet_ct_pred = str('%.2f' % (probability[0]*100) + '% COVID')
   else:
      resnet_ct_pred = str('%.2f' % ((1-probability[0])*100) + '% NonCOVID')
   print(resnet_ct_pred)

   return render_template('results_ct.html',resnet_ct_pred=resnet_ct_pred)

if __name__ == '__main__':
   app.secret_key = ".."
   app.run()


from Stack import Stack

def divideByTwo(number):
  s = Stack()

  while number > 0:
    remainder = number % 2
    s.push(remainder)
    number = number // 2

  binary = ""

  for i in range(s.getSize()):
    b = s.pop()
    binary += str(b)

  return binary


# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
from segmentation_models import Unet,PSPNet,Linknet,FPN
from segmentation_models.backbones import get_preprocessing
from keras.optimizers import Adam

from segmentation_models import shallow_CNN#,shallow_CNN#,Unet,PSPNet,Linknet,FPN
#from segmentation_models.backbones import get_preprocessing
#from segmentation_models.losses import bce_jaccard_loss
from keras.losses import mean_absolute_error,kullback_leibler_divergence
from segmentation_models.losses import bce_jaccard_loss,cce_jaccard_loss
from keras.optimizers import Adam
#from segmentation_models.metrics import iou_score
from segmentation_models.load_data import load_data_tandem_x, combinations_input_super_resolution
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau,Callback
from keras.layers import Conv2D, Input, BatchNormalization, Add
from keras.models import Model
import time
import numpy as np
from tifffile import imsave
from mat4py import savemat, loadmat
import pickle
import os
import math

from keras import backend as K
import tensorflow as tf
def correlation_coefficient_loss(y_true, y_pred):
    x = y_true
    y = y_pred
#    mx = K.mean(x)
#    my = K.mean(y)
#    xm, ym = x-mx, y-my
#    r_num = K.sum(tf.multiply(xm,ym))
#    r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym))))
#    r = r_num / r_den
#
#    r = K.maximum(K.minimum(r, 1.0), -1.0)
#    mae = K.mean(K.abs(x - y))
    maee = K.l2_normalize(K.abs(x - y))
    return maee #(1 - r)# K.square(r)) #mae + 10*

#def PSNR_loss(y_true, y_pred):
#    max_pixel = K.max(y_true)
#    return 10.0 * math.log10((max_pixel ** 2) / (K.mean(K.square(y_pred - y_true))))

#from scipy.io import sio
#import argparse

def psnr(img1, img2):
    mse = np.mean( (img1 - img2) ** 2 )
    if mse == 0:
        return 100
    PIXEL_MAX = np.max(img1)
    return (20 * math.log10(PIXEL_MAX / math.sqrt(mse)))

def psnr_loss(img1, img2):
    mse = K.mean( (img1 - img2) ** 2 )
    if mse == 0:
        return 100
    PIXEL_MAX = K.max(img1)
    mae = K.mean(K.abs(img1 - img2))
    return  mae + 1000*K.mean(K.abs(K.log(img1/ img2)))

def my_mae_loss(y_true, y_pred):
    x = y_true
    y = y_pred
    mx = K.mean(x)
    my = K.mean(y)
    xm, ym = x-mx, y-my
    r_num = K.sum(tf.multiply(xm,ym))
    r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym))))
    r = r_num / r_den

    r = K.maximum(K.minimum(r, 1.0), -1.0)
    mae = K.sum(K.square(xm)) - K.sum(K.square(ym))

    return mae #(1 - r)# K.square(r)) #mae + 10*

def my_mae_wo_mean_loss(y_true, y_pred):
    x = y_true
    y = y_pred
    mx = K.mean(x)
    my = K.mean(y)
    xm, ym = x-mx, y-my
    r_num = K.sum(tf.multiply(xm,ym))
    r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym))))
    r = r_num / r_den

    r = K.maximum(K.minimum(r, 1.0), -1.0)
    mae1 = K.sum(K.abs(x - y)) # K.sum(K.square(K.abs(x) - K.abs(y))) #  #+
    mae2 = 1 - K.sum(K.square(ym))/K.sum(K.square(xm)) # K.sum(K.square(ym)) #
    mae3 = 1 - K.sum(y)/K.sum(x)
    mae = mae1 + mae2 + mae3
    return mae #(1 - r)# K.square(r)) #mae + 10*

class LossHistory(Callback):
    def on_train_begin(self, logs={}):
        self.losses = []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))

class TimeHistory(Callback):
    def on_train_begin(self, logs={}):
        self.times = []

    def on_epoch_begin(self, batch, logs={}):
        self.epoch_time_start = time.time()

    def on_epoch_end(self, batch, logs={}):
        self.times.append(time.time() - self.epoch_time_start)

#from others import parser_xml
#xml_file=parser_xml(r"C:\Users\massi\Downloads\segmentation_models-master\config.xml")

#indo = loadmat(r"D:\Dataset_SuperRisoluzione\indices.mat")
#indices = _['A']
indices = 0
time_callback = TimeHistory()

# load your data
#folder_1 = r"D:\Works\DLR\Uganda_Solberg\\"
#MODELS_PATH = r"D:\Works\DLR\Uganda_Solberg\model_path\\"

folder_1 = r"D:\Works\DLR\Landcover\\"
MODELS_PATH = r"D:\Works\DLR\Landcover\model_path\\"

ts = str(int(time.time())) #Time stamp for the model distinctness
model_path = os.path.join(MODELS_PATH, 'model-{}.h5'.format(ts))
history_path = os.path.join(MODELS_PATH, 'model-{}.history'.format(ts))

size = 128#64#
n_epochs = 500#200 #
n_batch = 16 #16
model_name = "_CtoX" #
num_bands = 2#1
k_1 = 3# 9#
k_2 = 3#5#
k_3 = 3#5#
l_rate = 0.05 #5 #0.05
#bande = ["05","06","07","8A","11","12"]
#k = 0
#for combinations in bande:
#x_train, y_train, x_val, y_val = load_data_tandem_x(folder_1, size,num_bands,indices)

#np.savez("train_data.npz", x_train = x_train, y_train = y_train, x_val = x_val, y_val = y_val)
train_val = np.load("train_data.npz")

x_train1 = train_val['x_train']
y_train1 = train_val['y_train']
x_val1 = train_val['x_val']
y_val = train_val['y_val']
x_train = x_train1[:n_batch*1600, :,:,:2]
#x_train = np.reshape(x_train[:, :,:,0],(x_train.shape[0], x_train.shape[1],x_train.shape[2], 1))
y_train = y_train1[:n_batch*1600, :,:,:]
x_val = x_val1[:, :,:,:2]

#x_val = np.reshape(x_val1[:, :,:,0],(x_val1.shape[0], x_val1.shape[1],x_val1.shape[2], 1))

#    x_train, y_train, x_val, y_val,x_train2, y_train2, x_val2, y_val2 = combinations_input_super_resolution(x_traina, y_traina, x_vala, y_vala,x_train2a, y_train2a, x_val2a, y_val2a, comb[combinations],num[combinations] )
N = x_train.shape[-1]
print(x_train.shape)
print(x_val.shape)
#train_ground = {"details": y_train[:,:,:,1],"band": y_train[:,:,:,0]}
#val_ground = {"details": y_val[:,:,:,1],"band": y_val[:,:,:,0]}

#model = shallow_CNN(num_bands , k_1, k_2, k_3)

#model.load_weights(MODELS_PATH + "model_weigths"+model_name+".h5")

BACKBONE = 'mobilenetv2'
#size1 = size//4
#size2 = 4*size
base_model = Unet(BACKBONE,input_shape=(size,size, 3), classes=1, activation='sigmoid', encoder_weights='imagenet', freeze_encoder=False)
inp = Input(shape=(size, size, 2))
##bn = BatchNormalization()(inp)
l1 = Conv2D(3, (1, 1))(inp) # map N channels data to 3 channels
outi = base_model(l1)
out2 = K.reshape(K.argmax(outi),(size,size,1))
outi = Add()([K.cast(out2,dtype="float32"), K.cast(inp,dtype="float32")])
#outi = base_model(inp)
#out = Add(name="band")([outi, inp])
model = Model(inp, outi, name=base_model.name)

#
Adamax = Adam(lr=l_rate, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
#####
#losses = {
#"details": "mean_absolute_error" ,# my_mae_wo_mean_loss , # my_mae_loss,#
#"band": "mean_squared_error", #correlation_coefficient_loss , # #
#}
##
#lossWeights = {"details": 1.0, "band": 100.0 }
#metrics2 = {
#"details": "mean_absolute_error" ,
##my_mae_wo_mean_loss , # my_mae_loss,# "mean_absolute_error" ,
#"band": "mean_squared_error",
##correlation_coefficient_loss , # "mean_squared_error",#my_mae_loss, #my_mae_loss, #
##	"band":,# "kullback_leibler_divergence",
#        }
##model.compile( loss=losses, loss_weights=lossWeights, metrics=[mean_absolute_error], optimizer=Adamax)
#model.compile( loss=losses, loss_weights=lossWeights, metrics=metrics2, optimizer=Adamax)

#####

#model.compile( loss=my_mae_wo_mean_loss, metrics=[mean_absolute_error], optimizer=Adamax)
model.compile( loss=cce_jaccard_loss, metrics=[cce_jaccard_loss], optimizer=Adamax)
## fit model
history2 = LossHistory()

callbacks = [
    EarlyStopping(patience=10, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=3, min_lr=l_rate*0.001, verbose=1),
    ModelCheckpoint(MODELS_PATH + "temporary_model"+model_name+".h5", verbose=1, save_best_only=True, save_weights_only=True),
    time_callback,
    history2
]

history = model.fit(
    x= x_train, #[x_train, np.reshape(x_train[:,:,:,0],newshape=(y_train.shape[0],y_train.shape[1],y_train.shape[2],1))], #[x_train,np.reshape(y_train[:,:,:,1],newshape=(y_train.shape[0],y_train.shape[1],y_train.shape[2],1))], #reverse dimensions (in load_data_SR) and input from y_train # x_train,
    y= y_train, #[np.reshape(y_train[:,:,:,1], (x_train.shape[0], x_train.shape[1],x_train.shape[2], 1)), np.reshape(y_train[:,:,:,0], (x_train.shape[0], x_train.shape[1],x_train.shape[2], 1))], #y_train, #[np.reshape(y_train[:,:,:,0],newshape=(y_train.shape[0],y_train.shape[1],y_train.shape[2],1)),np.reshape(y_train[:,:,:,6],newshape=(y_train.shape[0],y_train.shape[1],y_train.shape[2],1))], #######  {"details": np.reshape(y_train[:,:,:,1], (x_train.shape[0], x_train.shape[1],x_train.shape[2], 1)),"band": np.reshape(y_train[:,:,:,0], (x_train.shape[0], x_train.shape[1],x_train.shape[2], 1))}, #y_train, #[np.reshape(y_train[:,:,:,0],newshape=(y_train.shape[0],y_train.shape[1],y_train.shape[2],1)),np.reshape(y_train[:,:,:,6],newshape=(y_train.shape[0],y_train.shape[1],y_train.shape[2],1))],
    batch_size=n_batch,
    epochs=n_epochs, #[x_val,np.reshape(y_val[:,:,:,1],newshape=(y_val.shape[0],y_val.shape[1],y_val.shape[2],1))]
    validation_data= (x_val, y_val), #([x_val, np.reshape(x_val[:,:,:,0],newshape=(x_val.shape[0],x_val.shape[1],x_val.shape[2],1))],[np.reshape(y_val[:,:,:,1],newshape=(y_val.shape[0],y_val.shape[1],y_val.shape[2],1)),np.reshape(y_val[:,:,:,0],newshape=(y_val.shape[0],y_val.shape[1],y_val.shape[2],1))]),callbacks = callbacks
#    validation_data=(x_val, np.reshape(y_val[:,:,:,0],(x_val.shape[0], x_val.shape[1],x_val.shape[2], 1))), callbacks = callbacks #y_val),callbacks = callbacks {"details": np.reshape(y_val[:,:,:,1],(x_val.shape[0], x_val.shape[1],x_val.shape[2], 1)),"band": np.reshape(y_val[:,:,:,0],(x_val.shape[0], x_val.shape[1],x_val.shape[2], 1))}), callbacks = callbacks #y_val),callbacks = callbacks
)

#    pickle.dump(history.history, open(history_path, "wb"))
#    print('Saved model at {}'.format(model_path))
#    print('Saved model history at {}'.format(history_path))
#    dic = {}
#    for a in history.history.keys():
#        dic[a] =  np.asarray(history.history[a])
#    dic_loss = {}
#    dic_loss['losses'] = history2.losses
#    savemat(os.path.join(MODELS_PATH, 'loss-{}_'.format(ts)+'_B'+ combinations+'.mat'),dic_loss)
#
times = time_callback.times
dic_times = {}
dic_times['times'] = times
savemat(MODELS_PATH + 'times'+model_name+'.mat', dic_times)
model.save(MODELS_PATH + "model"+model_name+".h5")

model.save_weights(MODELS_PATH + "model_weigths"+model_name+".h5")

print(np.max(y_val))
# Load best model
#model.load_weights(MODELS_PATH + "model_weigths"+model_name+".h5")
#
##    model.evaluate(x_val, y_val, verbose=1)
## Predict on train, val and test
##    preds_train = model.predict(x_train, verbose=1)
#preds_val = model.predict(x_val, verbose=1)
#k = np.abs(y_val - preds_val)
print(np.max(y_val))
print(np.mean(y_val))
#print(np.mean(np.abs(y_val - x_val)))
#print(np.max(np.abs(y_val - x_val)))
#print(np.mean(k))
#print(np.max(k))
#for kk in range(8):
#    y_val_1 = np.reshape(y_val[50*kk,:,:,0],newshape=(y_val.shape[1],y_val.shape[2],1))
#    x_val_1 = np.reshape(x_val[50*kk,:,:,0],newshape=(y_val.shape[1],y_val.shape[2],1))
#    pred_val_1 = preds_val[50*kk,:,:,:]
#    print(y_val_1.shape)
#    print(pred_val_1.shape)
#    ndvi = y_val_1.astype('float32')
#    im = MODELS_PATH +'target_XSAR_' + str(kk)+ model_name + '.tif'
#    imsave(im, ndvi)
#
#    ndvi2 = pred_val_1.astype('float32')
#    im2 =MODELS_PATH +'output_XSAR_' + str(kk)+ model_name + '.tif'
#    imsave(im2, ndvi2)
#
#    ndvi3 = x_val_1.astype('float32')
#    im3 =MODELS_PATH +'input_XSAR_' + str(kk)+ model_name +'.tif'
#    imsave(im3, ndvi3)

error = []
CC = []
psnr1 = []
errr = []
std = []
error2 = []
CC2 = []
psnr12 = []
errr2 = []
std2 = []

model.load_weights(MODELS_PATH + "model_weigths"+model_name+".h5")
preds_val = model.predict([x_val, np.reshape(x_val[:,:,:,0],newshape=(x_val.shape[0],x_val.shape[1],x_val.shape[2],1))], verbose=1)
preds_val = preds_val[1]

for kk in range(10):#range(0,y_val.shape[0],200):
    y_val_1 = np.reshape(y_val[kk,:,:,0],newshape=(y_val.shape[1],y_val.shape[2]))
    land_1 = np.reshape(y_val[kk,:,:,2],newshape=(y_val.shape[1],y_val.shape[2]))
    x_val_1 = np.reshape(x_val[kk,:,:,0],newshape=(y_val.shape[1],y_val.shape[2]))
    pred_val_1 = preds_val[kk,:,:,:]
    pred_val_1 = np.reshape(preds_val[kk,:,:,:],newshape=(y_val.shape[1],y_val.shape[2]))
    ndvi2 = pred_val_1.astype('float32')
    im2 =MODELS_PATH +'output_XSAR_' + model_name + '_' + str(kk)+ '.tif'
    imsave(im2, ndvi2)

    ndvi2 = x_val_1.astype('float32')
    im2 =MODELS_PATH +'input_NASADEM_' + model_name + '_'  + str(kk)+ '.tif'
    imsave(im2, ndvi2)

    ndvi2 = y_val_1.astype('float32')
    im2 =MODELS_PATH +'reference_XSAR_' + model_name + '_' + str(kk)+ '.tif'
    imsave(im2, ndvi2)

    ndvi2 = land_1.astype('float32')
    im2 =MODELS_PATH +'landsat_treecover_' + model_name + '_'  + str(kk)+ '.tif'
    imsave(im2, ndvi2)

    print(y_val_1.shape)
    print(pred_val_1.shape)
    Diff_noabs = pred_val_1 - y_val_1
    Diff = np.abs(pred_val_1 - y_val_1)
    CC.append(np.corrcoef(y_val_1, pred_val_1))
    psnr1.append(psnr(y_val_1, pred_val_1))
    error.append(np.mean(Diff))
    errr.append(np.mean(Diff_noabs))
    std.append(np.std(Diff_noabs))

    Diff_noabs2 = x_val_1 - y_val_1
    Diff2 = np.abs(x_val_1 - y_val_1)
    CC2.append(np.corrcoef(y_val_1, x_val_1))
    psnr12.append(psnr(y_val_1, x_val_1))
    error2.append(np.mean(Diff2))
    errr2.append(np.mean(Diff_noabs2))
    std2.append(np.std(Diff_noabs2))

print('MAE pred: ' + str(np.mean(error)))
print('PSNR pred : ' +  str(np.mean(psnr1)))
print('CC pred : ' +  str(np.mean(CC)))
print('mean and dev std pred : ' +  str(np.mean(errr)) + ' and ' + str(np.mean(std)))

print('MAE inp: ' + str(np.mean(error2)))
print('PSNR inp: ' +  str(np.mean(psnr12)))
print('CC inp: ' +  str(np.mean(CC2)))
print('mean and dev std pred : ' +  str(np.mean(errr2)) + ' and ' + str(np.mean(std2)))

#    ndvi = y_val_1.astype('float32')
#    im = MODELS_PATH +'target_XSAR_' + str(kk)+ model_name + '.tif'
#    imsave(im, ndvi)
#
#    ndvi2 = pred_val_1.astype('float32')
#    im2 =MODELS_PATH +'output_XSAR_' + str(kk)+ model_name + '.tif'
#    imsave(im2, ndvi2)
#
#    ndvi3 = x_val_1.astype('float32')
#    im3 =MODELS_PATH +'input_XSAR_' + str(kk)+ model_name +'.tif'
#    imsave(im3, ndvi3)


# -*- coding: utf-8 -*-
import threading
import mmap
import struct as st
from math import sin, cos, radians
from random import randint
import pyaudio as pa
import os

from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.slider import Slider
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserIconView

from kivy.clock import Clock, mainthread
from kivy.lang import Builder

class MainApp(App):
    sample_freq = 44100
    duration = 1.0
    freqs = []

    def add_freq(self,w):
        f = Builder.load_file('freqwidget.kv')
        self.freqs.append(f)
        w.add_widget(f)

    def rm_freq(self,w):
        self.freqs.remove(w)
        w.parent.remove_widget(w)

    def openFileDialog(self, w):
        f = Builder.load_file('filedialog.kv')
        w.add_widget(f)

    def save(self, path, filename):
        with open(os.path.join(path, filename), 'w') as stream:
            for f in self.freqs:
                stream.write(str(f.freq) +' '+ str(f.volume) + '\n')

    def load(self, path, filename):
        box = self.root.ids.frcon
        box.clear_widgets()
        #with open(os.path.join(path, filename[0])) as stream:
            #while True:
        file = open(os.path.join(path, filename[0]))
        for data in file.readlines():
                #data = stream.readline().split()
                f = Builder.load_file('freqwidget.kv')
                f.freq = int(data[0])
                f.volume = float(data[1])
                self.freqs.append(f)
                box.add_widget(f)

    def start_play(self, btn):
        self.play()

    def play(self):
        if not self.freqs: return
        fv = [(f.freq, f.volume) for f in self.freqs]
        sf = self.sample_freq
        n = len(self.freqs)
        data = []

        for i in range(int( self.duration * 44100 )):
            x = 0
            for f in fv:
                #x += int(sin(radians(i * (f.freq) / (self.sample_freq / 360))) * 32767)
                x += int(sin(radians(i * f[0] / (sf / 360))) * 32767 * f[1])
            x = int(x / n)
            data.append( st.pack("<h", x) )
            #i = 0 if i == 359 else i + 1
            # x = randint(0,65535) # white noise

        s = pa.PyAudio().open(format=pa.paInt16,
                              channels=1,
                              rate=self.sample_freq,
                              output=True)

        for d in data:
            s.write(d)
        s.close()
        pa.PyAudio().terminate()

if __name__ == '__main__':
    MainApp().run()


from flask import Flask, render_template, request, send_file, make_response
import pandas as pd
import os
import io
from deployment.SynthesisLib import *
import zipfile

app = Flask(__name__)

def generate_single_file_response(df):
    # Convert DataFrame to CSV string
    csv_data = df.to_csv(index=False)
    # Create a response with the CSV data
    response = make_response(csv_data)
    response.headers['Content-Disposition'] = 'attachment; filename=data.csv'
    response.headers['Content-type'] = 'text/csv'
    return response

def generate_zip_file_response(df1, df2):
    # Convert DataFrame to CSV string
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        zip_file.writestr('data_task.csv', df1.to_csv(index=False))
        zip_file.writestr('data_worker.csv', df2.to_csv(index=False))

    # Set the buffer's position to the start
    zip_buffer.seek(0)
    return send_file(zip_buffer, attachment_filename='data.zip', as_attachment=True)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # Retrieve the form input values
        # radio_value = request.form.get('radio')
        checkbox_values = request.form.getlist('checkbox')
        input_text_value = request.form.get('input_text')
        # 0 - worksers
        # 1 - jobs

        if 'checkbox1' in checkbox_values:
            index = 0
            df_worker = generate(index, int(input_text_value))
            synfile = generate_single_file_response(df_worker)

        elif 'checkbox2' in checkbox_values:
            index = 1
            df_task = generate(index, int(input_text_value))
            synfile = generate_single_file_response(df_task)

        elif 'checkbox3' in checkbox_values:
            df_worker = generate(0, int(input_text_value))
            df_task = generate(1, int(input_text_value))
            synfile = generate_zip_file_response(df_task, df_worker)

        else:
            return "Server Error"

        return synfile

    return render_template('index.html')

def convert_to_csv(fake_data):

   # Convert the DataFrame to CSV format
    csv_data = fake_data.to_csv(index=False)
    csv_stream = io.BytesIO()
    csv_stream.write(csv_data.encode())
    csv_stream.seek(0)
    return csv_stream

if __name__ == '__main__':
    app.run(port=5000, host="0.0.0.0")


import os
import time

path = os.path.join(os.getcwd() + 'static/download/')

while True:
    now = time.time()

    for f in os.listdir(path):
        file = os.path.join(path, f)
        if os.stat(file).st_mtime < now - 7200:
            if os.path.isfile(file):
                os.remove(os.path.join(path, f))
    time.sleep(7500)


# https://leetcode.com/problems/text-justification/
# tags: #google, #greedy, #simulation, #string
# Idea for the solution: The main method will manage how many words will fit in each line considering
# at least one space between each word in the same line (greedy)
#
# When a line is considered full, then fill in the line considering:
# 1. If it's one word then it is easy, the result is just that word.
# 2. If it's the last line then the result is all words separated by a single space
# and filling remaining with blank space.
# 3. Otherwise we calculate the size of each space evenly and if there is a remainder we distribute an extra space
# until it is gone
#
# Time complexity: O(n * maxWidth) => main method traverse words list and sub-method traverse the same list
# Space complexity: O(maxWidth) => Space for a single line
from typing import List

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        text_lines = []
        n, current_width, line_start = len(words), 0, 0

        for i, word in enumerate(words):
            m = len(word)
            if current_width + m > maxWidth:
                text_lines.append(self.justify_line(words[line_start: i], current_width, maxWidth))
                line_start = i
                current_width = 0

            if i == n - 1:
                last_line = " ".join(words[line_start: i + 1])
                text_lines.append(last_line + " " * (maxWidth - len(last_line)))

            current_width += m + 1
        return text_lines

    def justify_line(self, line_words: List[str], words_width: int, max_width: int) -> str:
        m = len(line_words)
        remaining = max_width - (words_width - m)
        if remaining == 0:
            return " ".join(line_words)
        elif m == 1:
            return line_words[0] + " " * (max_width - (words_width - 1))

        remaining_divisor = remaining // (m - 1)
        remaining_residual = remaining % (m - 1)
        text_line = ""

        for i, word in enumerate(line_words):
            divisor = ""
            if i > 0:
                divisor = " " * (remaining_divisor + (1 if remaining_residual > 0 else 0))
                remaining_residual -= 1 if remaining_residual > 0 else 0

            text_line += divisor + word

        return text_line

if __name__ == "__main__":
    sol = Solution()

    sol.fullJustify(words=["This", "is", "an", "example", "of", "text", "justification."], maxWidth=16)
    # Output:
    # [
    #    "This    is    an",
    #    "example  of text",
    #    "justification.  "
    # ]

    sol.fullJustify(words=["What", "must", "be", "acknowledgment", "shall", "be"], maxWidth=16)
    # [
    #   "What   must   be",
    #   "acknowledgment  ",
    #   "shall be        "
    # ]

    sol.fullJustify(
        words=["Science", "is", "what", "we", "understand", "well", "enough", "to", "explain", "to", "a", "computer.",
               "Art", "is", "everything", "else", "we", "do"], maxWidth=20)
    # [
    #   "Science  is  what we",
    #   "understand      well",
    #   "enough to explain to",
    #   "a  computer.  Art is",
    #   "everything  else  we",
    #   "do                  "
    # ]


from enum import Enum
import WolfUtils
from Actions import COMMAND_FLAGS
import Actions

class Role:

    def __init__(self, faction):
        self.name = "Default"
        self.description = "This is the default role without any alignment. If you're seeing this, something went wrong. Contact a member of Valhalla Procotol immediately."
        self.alignment = None
        self.player = None
        self.nightly_message = "It is now night. Sit tight and wait for morning -- and hope you don't die in the meantime!"

        self.toughness = 0
        self.indestructible = False

        self.flags = []

        #True if needs a target OTHER than factional kill
        self.needs_target = False

        self.faction = faction
        self.speaks_with_faction = False

        #Alignment peeks return modified or false
        self.tinker = None

    def create_action(self, flag, target):
        #Returns None on Normal Villagers
        return None

    def do_vote(self):
        pass

    async def onDeath(self, killtype):
        self.player.alive = False
        await self.player.game.post_log(self.player.name + " " + killtype.tensename)
        await self.player.game.post_log(self.player.name + " Died")

        if self.player.game.reveal_rule == WolfUtils.DeathReveal.FULL_REVEAL:

            await self.player.game.post_log(self.player.name + " was a "+ self.player.role.name + " aligned with the " + self.player.faction.name)

        elif self.player.game.reveal_rule == WolfUtils.DeathReveal.ALIGNMENT_REVEAL:

            await self.player.game.post_log((self.player.name + " was aligned with the " + self.player.faction.name))

        if await self.player.game.check_wincons():
            await self.player.game.self_destruct()

    def onRevive(self):
        pass

class Villager(Role):
    def __init__(self, faction):
        super(Villager, self).__init__(faction)
        self.name = "Normal Villager"
        self.alignment = Alignment.VILLAGE
        self.description = "You are a Normal Villager. Through your vote and your voice, you wield enormous power and influence in the game. Use your power wisely..."

class MafiaGoon(Role):
    def __init__(self, faction):
        super(MafiaGoon, self).__init__(faction)
        self.name = "Mafia Goon"
        self.alignment = Alignment.MAFIA
        self.factional_kill = True
        self.speaks_with_faction = True
        self.description = "You are a Mafia Goon. You may collaborate with your team by using the ?teamchat command in private chat. During the night, use the ?shoot <name> command to set the factional kill target."
        self.nightly_message = "It is now night. Plan with your buddies to kill a player using ?teamchat <message> Send in the kill using ?shoot <target>."

class Cop(Role):
    def __init__(self, faction):
        super(Cop, self).__init__(faction)
        self.description = "You are a Village Cop. You may peek a player each night using ?peek <target name>. "
        self.name = "Cop"
        self.alignment = Alignment.VILLAGE
        self.needs_target = True
        self.nightly_message = "It is now night. You may see a player's alignment by using the ?peek <player> command."
        self.flags.append(COMMAND_FLAGS.PEEK)
        self.peektype = Actions.PeekTypes.BINARY

    def create_action(self, flag, target):
        #Returns an ActionPeek
        if flag == COMMAND_FLAGS.PEEK:
            print("Peek action created...")
            return Actions.ActionPeek(flag, self.player.game, self.player, target, self.peektype)

        else:
            return None

class Miller(Role):
    def __init__(self, faction):
        super(Miller, self).__init__(faction)
        self.name = "Miller"
        self.alignment = Alignment.VILLAGE
        self.description = "You are a Normal Villager. Through your vote and your voice, you wield enormous power and influence in the game. Use your power wisely..."
        self.tinker = True

class Doctor(Role):
    def __init__(self, faction):
        super(Doctor, self).__init__(faction)
        self.description = "You are a Village Doctor. You may protect a player each night using ?protect <target name>. "
        self.name = "Doctor"
        self.alignment = Alignment.VILLAGE
        self.needs_target = True
        self.nightly_message = "It is now night. You may attempt to protect a player by using the ?protect <target> command."
        self.flags.append(COMMAND_FLAGS.PROTECT)

    def create_action(self, flag, target):

        if flag == COMMAND_FLAGS.PROTECT:
            return Actions.ActionProtect(flag, self.player.game, self.player, target)

        else:
            return None

class Alignment(Enum):

    VILLAGE = ("You are aligned with the Village, meaning you win when all evil factions are dead.", 1)
    WOLF = ("You are aligned with the Wolf team, meaning you win when your team has reached parity with the village and all opposing evil factions are dead.",2)
    MAFIA = ("You are aligned with the Mafia team, meaning you win when your team has reached parity with the village and all opposing evil factions are dead.",3)
    SERIAL_KILLER = ("You are aligned with yourself, and you win when you are alive and there is one or fewer other players alive in the game.",4)
    CULT = ("You are aligned with the Cult. You win when the cult has reached parity with the village and all other evil factions are dead.",5)
    NEUTRAL = ("You are neutral, meaning you have an alternate wincon.",6)

    def __init__(self, wincon, number):
        self.wincon = wincon
        self.number = number


def bin_search(arr, x, l, r):
	mid = (l+r)//2
	# print("Mid =", mid)
	if r < l:
		return -1
	if arr[mid] == x:
		return mid
	if x < arr[mid]:
		return bin_search(arr, x, l, mid - 1)
	else:
		return bin_search(arr, x, mid + 1, r)

for _ in range(int(input())):
	l, m, n = map(int, input().split())
	a = list(input().split())
	b = list(map(int, input().split()))
	c = list(map(int, input().split()))
	# print(a,b,c,sep='\n')
	p, q, r = input().split();
	q = int(q)
	r = int(r)
	ap = bin_search(a, p, 0, l-1)
	aq = bin_search(b, q, 0, m-1)
	ar = bin_search(c, r, 0, n-1)
	# print(ap, aq, ar)
	if ap == -1 or aq == -1 or ar == -1:
		print('DOST HI SAANP HAI')
	else:
		print('SNAKE FOUND')