import discord
from discord.ext import commands
from commands.cr_Exceptions import cr_Exception

class cr_Typewritter(commands.Cog):
    def __init__(self, client):
        try:
            self.client = client
        except Exception as e:
            print(str(e))

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def tw(self, ctx, *, arg1):
        # typewritter command
        try:
            input_text = arg1
            output_text = f''
            for char in input_text:
                if char.isalpha():
                    output_text += f':regional_indicator_{char.lower()}: '
                else:
                    output_text += f':blue_square: '
            await ctx.channel.purge(limit=1)
            await ctx.channel.send(output_text)
        except Exception as e:
            print(str(e))

    @tw.error
    async def tw_error(self, ctx):
        try:
            await ctx.channel.purge(limit=1)
            embed_title = f'**Brak uprawnień!**\n'
            embed_description = f'**Nie masz odpowiednich uprawnień do wykonania tej komendy.**\n'
            embedVar = discord.Embed(title=embed_title, description=embed_description, color=0xff0000)
            await ctx.channel.send(embed=embedVar)
        except Exception as e:
            print(str(e))


import argparse
import os

import cv2
import numpy as np
import torch
from torchvision import models, transforms

from pytorch_grad_cam import GradCAM, \
                             ScoreCAM, \
                             GradCAMPlusPlus, \
                             AblationCAM, \
                             XGradCAM, \
                             EigenCAM, \
                             EigenGradCAM

from pytorch_grad_cam import GuidedBackpropReLUModel
from pytorch_grad_cam.utils.image import show_cam_on_image, \
                                         deprocess_image, \
                                         preprocess_image

from config import *
from PIL import Image
import matplotlib.pyplot as plt
from model import resnet50

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--use-cuda', action='store_true', default=True,
                        help='Use NVIDIA GPU acceleration')
    parser.add_argument('--image-path', type=str, default=os.path.join(DATA_DIR, '0194dd14-5be1-4855-84e2-dbbdf5fcbb2d.jpg'),
                        help='Input image path')
    parser.add_argument('--aug_smooth', action='store_true',
                        help='Apply test time augmentation to smooth the CAM')
    parser.add_argument('--eigen_smooth', action='store_true',
                        help='Reduce noise by taking the first principle componenet'
                        'of cam_weights*activations')
    parser.add_argument('--method', type=str, default='gradcam',
                        choices=['gradcam', 'gradcam++',
                                 'scorecam', 'xgradcam',
                                 'ablationcam', 'eigencam',
                                 'eigengradcam', 'layercam'],
                        help='Can be gradcam/gradcam++/scorecam/xgradcam'
                             '/ablationcam/eigencam/eigengradcam/layercam')

    args = parser.parse_args()
    args.use_cuda = args.use_cuda and torch.cuda.is_available()
    if args.use_cuda:
        print('Using GPU for acceleration')
    else:
        print('Using CPU for computation')

    return args

if __name__ == '__main__':
    """ python cam.py -image-path <path_to_image>
    Example usage of loading an image, and computing:
        1. CAM
        2. Guided Back Propagation
        3. Combining both
    """

    args = get_args()
    methods = \
        {"gradcam": GradCAM,
         "scorecam": ScoreCAM,
         "gradcam++": GradCAMPlusPlus,
         "ablationcam": AblationCAM,
         "xgradcam": XGradCAM,
         "eigencam": EigenCAM,
         "eigengradcam": EigenGradCAM}

    model = resnet50(num_classes=3)
    weights_path = os.path.join(SAVE_DIR, 'Resnet50_epoch70_20210816_151629_handcropAllData_BSize8', 'best43.pth')
    model.load_state_dict(torch.load(weights_path))

    # Choose the target layer you want to compute the visualization for.
    # Usually this will be the last convolutional layer in the model.
    # Some common choices can be:
    # Resnet18 and 50: model.layer4[-1]
    # VGG, densenet161: model.features[-1]
    # mnasnet1_0: model.layers[-1]
    # You can print the model to help chose the layer
    target_layer = model.layer4[-1]

    cam = methods[args.method](model=model,
                               target_layer=target_layer,
                               use_cuda=args.use_cuda)

    rgb_img = cv2.imread(args.image_path, 1)[:, :, ::-1]
    rgb_img = cv2.resize(rgb_img, RESIZE_SIZE)
    rgb_img = np.float32(rgb_img) / 255
    input_tensor = preprocess_image(rgb_img, mean=[0.485, 0.456, 0.406],
                                             std=[0.229, 0.224, 0.225])

    # data_transform = transforms.Compose(
    #     [transforms.Resize(256),
    #      transforms.CenterCrop(224),
    #      transforms.ToTensor(),
    #      transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
    #
    # img = Image.open(args.image_path)
    # plt.imshow(img)
    # # [N, C, H, W]
    # rgb_img = data_transform(img)
    # # expand batch dimension
    # input_tensor = torch.unsqueeze(rgb_img, dim=0)

    # If None, returns the map for the highest scoring category.
    # Otherwise, targets the requested category.
    target_category = None

    # AblationCAM and ScoreCAM have batched implementations.
    # You can override the internal batch size for faster computation.
    cam.batch_size = 32

    grayscale_cam = cam(input_tensor=input_tensor,
                        target_category=target_category,
                        aug_smooth=args.aug_smooth,
                        eigen_smooth=args.eigen_smooth)

    # Here grayscale_cam has only one image in the batch
    grayscale_cam = grayscale_cam[0, :]

    cam_image = show_cam_on_image(rgb_img, grayscale_cam, use_rgb=True)

    # cam_image is RGB encoded whereas "cv2.imwrite" requires BGR encoding.
    cam_image = cv2.cvtColor(cam_image, cv2.COLOR_RGB2BGR)

    gb_model = GuidedBackpropReLUModel(model=model, use_cuda=args.use_cuda)
    gb = gb_model(input_tensor, target_category=target_category)

    cam_mask = cv2.merge([grayscale_cam, grayscale_cam, grayscale_cam])
    cam_gb = deprocess_image(cam_mask * gb)
    gb = deprocess_image(gb)

    cv2.imwrite(f'{args.method}_cam.jpg', cam_image)
    cv2.imwrite(f'{args.method}_gb.jpg', gb)
    cv2.imwrite(f'{args.method}_cam_gb.jpg', cam_gb)


from smt import boolean as bl
from smt import bitvector as bv

from concolica import interlocked

_name_index = interlocked.Counter()

def unique_name(name):
    return '{0}_{1:x}'.format(name, _name_index.increment())

def mask(size):
    """The basic bitmask to extract the value of bit-size 'size'."""

    if size == 8:
        return 0xff
    elif size == 16:
        return 0xffff
    elif size == 32:
        return 0xffffffff
    elif size == 64:
        return 0xffffffffffffffff
    elif size == 128:
        return 0xffffffffffffffffffffffffffffffff

def concretise(state, value, count=8):
    values = set()
    constraint = None

    if not value.symbolic:
        return [value]
    elif not isinstance(value, bv.Symbol):
        new_value = bv.Symbol(value.size, unique_name('concretise'))
        constraint = (new_value == value)
        state.solver.add(constraint)
        value = new_value

    # we now know that value is a symbol

    # TODO: this really hurts performance, but it will probably also help
    # with finding bugs... add in again once I have better path culling
    # heuristics again

    #values.add(maximum(state, value))
    #values.add(minimum(state, value))

    #if len(values) == 1:
        # max == min, our work here is done...
    #    return list(values)

    while len(values) < count:
        if not state.solver.check(constraint):
            break

        m = state.solver.model(constraint)
        if value.name not in m:
            # solver doesn't know anything about our value yet...
            constraint = value != 0xbeefcafe
            continue

        model_value = m[value.name]
        values.add(model_value)

        if constraint is not None:
            constraint = bl.BinaryOperation(
                constraint,
                bl.BinaryOperator.And,
                value != model_value)
        else:
            constraint = value != model_value

    #print list(map(lambda x:hex(x.value), values))

    return list(values)

def minimum(state, value):
    if not value.symbolic:
        return value

    absolute_max = -1 & mask(value.size)
    lower = 0
    upper = absolute_max

    while (upper - lower) > 1:
        mid = (upper + lower) // 2
        if state.solver.check(value < bv.Constant(value.size, mid)):
            upper = mid
        else:
            lower = mid

    return bv.Constant(value.size, lower)

def maximum(state, value):
    if not value.symbolic:
        return value

    absolute_max = -1 & mask(value.size)
    lower = 0
    upper = absolute_max

    while (upper - lower) > 1:
        mid = (upper + lower) // 2
        if state.solver.check(value > bv.Constant(value.size, mid)):
            lower = mid
        else:
            upper = mid

    return bv.Constant(value.size, upper)

def arbitrary(state, value):
    if state.solver.check(value == bv.Constant(value.size, 0xc01db33f)):
        return True
    else:
        return False

class String(object):

    def __init__(self, state, address):
        self.state = state
        self.address = address

    def __iter__(self):
        terminated = False
        index = 0
        constraint = bl.Constant(True)
        while not terminated:
            read_address = self.address + bv.Constant(self.address.size, index)
            byte = self.state.read(read_address, 8)

            if self.state.solver.check(byte.can_be_nonzero()):
                if byte.symbolic:
                    if not constraint.symbolic:
                        constraint = (byte != 0)
                    else:
                        # not sure that I've implemented &= in smt
                        constraint = constraint & (byte != 0)

                    # this might look silly, but it actually makes the
                    # output smt formulae substantially smaller...

                    returned_constraint = bl.Symbol(unique_name('string_length'))
                    self.state.solver.add(returned_constraint == constraint)
                    yield (byte, returned_constraint)
                else:
                    yield (byte, constraint)
            else:
                terminated = True
                yield (bv.Constant(8, 0), constraint)
            index += 1

class OutputBuffer(object):

    def __init__(self, state, address):
        self.state = state
        self.address = address
        self.index = 0

    def copy(self, new_state):
        new = OutputBuffer(new_state, self.address)
        new.index = self.index
        return new

    def append(self, c):
        if isinstance(c, str):
            c = bv.Constant(8, ord(c))

        write_address = self.address + bv.Constant(self.address.size, self.index)
        self.index += 1
        self.state.write(write_address, c)

    def append_string(self, s, max_len=None):
        if max_len is not None:
            if isinstance(s, str):
                l = 0
                for c in s:
                    if l > max_len:
                        break
                    self.append(c)
                    l += 1
            elif isinstance(s, String):
                l = 0
                for c, constraint in s:
                    if l > max_len:
                        break
                    self.append(c)
                    l += 1
            else:
                raise NotImplementedError()
        else:
            if isinstance(s, str):
                for c in s:
                    self.append(c)
            elif isinstance(s, String):
                for c, constraint in s:
                    self.append(c)
            else:
                raise NotImplementedError()

class BoundOutputBuffer(OutputBuffer):

    def __init__(self, state, address, length):
        OutputBuffer.__init__(self, state, address)
        if isinstance(length, int):
            self.length = length
        else:
            self.length = length.value

    def copy(self, new_state):
        new = BoundOutputBuffer(new_state, self.address, self.length)
        new.index = self.index
        return new

    def append(self, c):
        if self.index < self.length:
            OutputBuffer.append(self, c)

class DummyOutputBuffer():

    def __init__(self):
        self.string = ''
        self.index = 0

    def copy(self, new_state):
        new = DummyOutputBuffer()
        new.string = str(self.string)
        new.index = self.index
        return new

    def append(self, c):
        if isinstance(c, str):
            self.string += c
        elif c.symbolic:
            self.string += '?'
        else:
            self.string += chr(c.value)
        self.index += 1

    def append_string(self, s, max_len=None):
        if max_len is not None:
            if isinstance(s, str):
                l = 0
                for c in s:
                    if l > max_len:
                        break
                    self.append(c)
                    l += 1
            elif isinstance(s, String):
                l = 0
                for c, constraint in s:
                    if l > max_len:
                        break
                    self.append(c)
                    l += 1
            else:
                raise NotImplementedError()
        else:
            if isinstance(s, str):
                for c in s:
                    self.append(c)
            elif isinstance(s, String):
                for c, constraint in s:
                    self.append(c)
            else:
                raise NotImplementedError()

def concrete_format_string(state, output, fmt, va_args):
    percent = False
    zero_fill = False
    left_align = False
    width = ''

    arg_index = 0

    states = [state]
    outputs = [output]
    for char, constraint in String(state, fmt):
        if char.symbolic:
            # we don't handle symbolic input strings, except to attempt
            # to insert a %n
            if not percent:
                if state.solver.check(constraint & (char == ord('%'))):
                    percent = True
                else:
                    output.append('?')
            else:
                if state.solver.check(constraint & (char == ord('n'))):
                    raise 'boomerlolwtfformatpwned'
                output.append('?')
        else:
            # here is the meat of it
            c = chr(char.value)
            #print(c)

            # if we're not in a format specification
            if not percent:
                if c == '%':
                    percent = True
                else:
                    output.append(c)

            # we're in a format specification
            else:
                output_strings = []
                output_constraints = []

                if c == '%':
                    output_strings.append('%')
                elif c == 'c':
                    # print a single character
                    value = va_args[arg_index].resize(8)
                    if value.symbolic:
                        output_strings.append('?')
                    else:
                        output_strings.append('{0}'.format(chr(value.value)))
                elif c == 'd':
                    # print a decimal number
                    value = va_args[arg_index]
                    if value.symbolic:
                        output_strings.append('?')
                    else:
                        output_strings.append('{0:d}'.format(value.value))
                elif c == 'i':
                    # print an integer
                    value = va_args[arg_index]
                    if value.symbolic:
                        output_strings.append('?')
                    else:
                        output_strings.append('{0:d}'.format(value.value))
                elif c == 'n':
                    # writeback current chars written
                    output_strings.append('n_not_supported')
                elif c == 'o':
                    # print integer in octal
                    output_strings.append('o_not_supported')
                elif c == 's':
                    # print a string
                    strptr = va_args[arg_index]
                    if strptr.symbolic:
                        # oh fuck me sideways
                        for ptr in concretise(state, strptr):
                            s = String(state, ptr)
                            tmp = DummyOutputBuffer()
                            tmp.append_string(s)
                            output_strings.append(tmp.string)
                            output_constraints.append(strptr == ptr)
                    else:
                        s = String(state, strptr)
                        tmp = DummyOutputBuffer()
                        tmp.append_string(s)
                        output_strings.append(tmp.string)
                elif c == 'u':
                    # print an unsigned integer
                    output_strings.append('u_not_supported')
                elif c == 'x':
                    # print integer in hexadecimal
                    value = va_args[arg_index]
                    if value.symbolic:
                        output_strings.append('?')
                    else:
                        output_strings.append('{0:x}'.format(value.value))
                elif c in '123456789':
                    width += c
                elif c == '0':
                    zero_fill = True
                elif c == '-':
                    left_align = True
                else:
                    # skip unrecongised characters
                    pass

                def _format_output_string(string, width, zero_fill, left_align):
                    if len(width) > 0:
                        width = int(width)
                        while len(string) < int(width):
                            if zero_fill:
                                string = '0' + string
                            elif left_align:
                                string += ' '
                            else:
                                string = ' ' + string
                    return string

                import functools

                format_output_string = functools.partial(
                    _format_output_string,
                    width=width,
                    zero_fill=zero_fill,
                    left_align=left_align)

                if len(output_strings) > 1:
                    output_strings = list(map(format_output_string, output_strings))

                    # we need to make a copy here as we're going
                    # to be modifying these lists
                    for s, o in list(zip(states, outputs)):
                        for i, output_string in enumerate(output_strings):
                            if i != len(output_strings) - 1:
                                new_s = s.fork()
                                new_o = o.copy(new_s)
                                states.append(new_s)
                                new_s.solver.add(output_constraints[i])
                                new_o.append_string(output_string)
                                outputs.append(new_o)
                            else:
                                s.solver.add(output_constraints[i])
                                o.append_string(output_string)

                    percent = False
                    zero_fill = False
                    left_align = False
                    arg_index += 1

                elif len(output_strings) == 1:
                    output_string = format_output_string(output_strings[0])

                    for output in outputs:
                        output.append_string(output_string)

                    percent = False
                    zero_fill = False
                    left_align = False
                    arg_index += 1

    return states, outputs

def format_string(s, output, fmt, var_args):
    if fmt.symbolic:
        fmts = concretise(s, fmt)
    else:
        fmts = [fmt]

    ss = []
    os = []

    total_fmts = len(fmts)
    while len(fmts):
        f_ = fmts.pop()

        if total_fmts > 1:
            s_ = s.fork()
            o_ = output.copy(s)
            v_ = var_args.copy(s)
        else:
            s_ = s
            o_ = output
            v_ = var_args

        ns, no = concrete_format_string(s_, o_, f_, v_)

        ss += ns
        os += no

    return ss, os


class vertice:
    def __init__(self,dado,dado1):
        self.dado=dado
        self.dado1=dado1
        self.grauEntrada=0
        self.grauSaida=0
    def getDado(self):
        return self.dado
    def getGrauEntrada(self):
        return self.grauEntrada
    def getGrauSaida(self):
        return self.grauSaida
    def addGrauSaida(self):
        self.grauSaida+=1
    def removeGrauSaida(self):
        self.grauSaida-=1
    def addGrauEntrada(self):
        self.grauEntrada+=1
    def removeGrauEntrada(self):
        self.grauEntrada-=1
    def printarDados(self):
        print(self.dado)
        print(self.qntArestas)

class aresta:
    def __init__(self,origem,destino):
        self.origem=origem
        self.destino=destino
    def getOrigem(self):
        return self.origem
    def getDestino(self):
        return self.destino

class Grafo:
    def __init__(self,direcionado=False):
        self.lista_vertices = []
        self.lista_arestas = []
        self.direcionado = direcionado

    def insere_v(self,dado,dado1=None):
        self.lista_vertices.append(vertice(dado,dado1))

    def veri_vertice(self,vertice):
        for i in self.lista_vertices:
            if i.dado == vertice:
                return i
        else:
            return None

    def insere_a(self,u,v):
        origem= self.veri_vertice(u)
        destino= self.veri_vertice(v)

        if origem != None and destino != None:
            self.lista_arestas.append(aresta(u,v))
            for i in self.lista_vertices:
                if i.dado == origem.dado:
                    i.addGrauSaida()
                    break
            for i in self.lista_vertices:
                if i.dado == destino.dado:
                    i.addGrauEntrada()
                    break

        if self.direcionado:
            self.lista_arestas.append(aresta(v,u))
            for i in self.lista_vertices:
                if i.dado == destino.dado:
                    i.addGrauSaida()
                    break
            for i in self.lista_vertices:
                if i.dado == origem.dado:
                    i.addGrauEntrada()
                    break

    def remove_a(self,u,v):
        origem= self.veri_vertice(u)
        destino= self.veri_vertice(v)
        if origem != None and destino != None:
            for i in self.lista_arestas:
                if i.origem == u and i.destino == v:
                    for j in self.lista_vertices:
                        if j.dado==u:
                            j.removeGrauSaida()
                    for j in self.lista_vertices:
                        if j.dado==v:
                            j.removeGrauEntrada()
                    self.lista_arestas.remove(i)
            if self.direcionado:
                for i in self.lista_arestas:
                    if i.origem == v and i.destino == u:
                        for j in self.lista_vertices:
                            if j.dado==v:
                                j.removeGrauSaida()
                        for j in self.lista_vertices:
                            if j.dado==u:
                                j.removeGrauEntrada()
                        self.lista_arestas.remove(i)
    def remove_v(self,u):
        vertice=self.veri_vertice(u)
        l=[]
        if vertice != None:
            for i in self.lista_vertices:
                if i.dado == u:
                    l.append(i)
            for i in l:
                self.lista_vertices.remove(i)
            l=[]
            for i in self.lista_arestas:
                if i.origem == u or i.destino == u:
                    if i.origem != u:
                        for j in self.lista_vertices:
                            if j.dado == i.origem:
                                j.removeGrauSaida()
                    else:
                        for j in self.lista_vertices:
                            if j.dado == i.destino:
                                j.removeGrauEntrada()
                    l.append(i)
            for i in l:
                self.lista_arestas.remove(i)
    def printarTodosOsDados(self):
        for i in self.lista_vertices:
            x=0
            print(f'Vertice : {i.dado}')
            print(f'Grau Saida: {i.grauSaida}')
            print(f'Grau Entrada: {i.grauEntrada}')
            l=[]
            for j in self.lista_arestas:
                if j.origem == i.dado:
                    l.append([j.origem,j.destino])
                    x=1
            if x:
                print('Arestas:',end=' ')
            for i in l:
                print(" -> ".join([str(i[0]),str(i[-1])]),end='')
                if i != l[-1]:
                    print(' | ',end='')
                else:
                    print('\n',end='')
            else:
                if x == 0:
                    print('Não tem arestas')

    def grau_saida(self,dado):
        for i in self.lista_vertices:
            if i.dado == dado:
                return i.grauSaida
        else:
            return 0

    def grau_entrada(self,dado):
        for i in self.lista_vertices:
            if i.dado == dado:
                return i.grauEntrada
        else:
            return 0
    def alcancavel(self,u,v):
        l=[]
        for i in self.lista_arestas:
            if i.origem == u:
                l.append(i)
        for i in l:
            if i.destino == v:
                return True
            else:
                self.alcancavel(i.destino,v)
        else:
            return False

b=Grafo(True)
b.insere_v(1)
b.insere_v(2)
b.insere_v(3)
b.insere_v(4)
b.insere_v(5)
b.insere_a(1,2)
b.insere_a(1,3)
b.insere_a(1,4)
b.insere_a(1,5)
b.insere_a(4,1)
b.remove_a(1,4)
b.remove_v(3)
b.printarTodosOsDados()


class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = len(nums)
        for i in range(l+1):
            if i not in nums:
                return i

    def missingNumber2(self, nums):
        l = len(nums)
        return l*(l+1) // 2 - sum(nums)

if __name__ =='__main__':
    print(Solution().missingNumber2([3,1,0]))


# coding=utf-8
# 关于性能方面的相关计算，比如cpu,内存，存储等方面的利用率，总量，使用量等

# hy
# 2017/6/29

from pecan import rest
import wsmeext.pecan as wsme_pecan
from ceilometer.api.controllers.v2 import base
import wsme
from datetime import datetime
from ceilometer import storage
import pecan
from ceilometer.api.controllers.v2 import utils as v2_utils

class Capability(base.Base):
    """
    对应的性能结果
    """
    cpu_util = [float]
    memory_util = [float]
    disk_read_rate = [float]
    disk_write_rate = [float]
    network_read_rate = [float]
    network_write_rate = [float]
    memory_total = [float]
    memory_usage = [float]

    def __init__(self, startTime, endTime, timeType):
        delta = endTime - startTime
        delta = delta.days + 1  # 因为最后一天要计算进去
        if timeType == "hour":
            self.__init_group_value(delta * 24)
        if timeType == "day":
            self.__init_group_value(delta)
        if timeType == "month":
            if startTime.year == endTime.year:
                self.__init_group_value(endTime.month - startTime.month + 1)
            if startTime.year < endTime.year:
                self.__init_group_value(

                    endTime.month + (endTime.year - startTime.year - 1) * 12 + (12 - startTime.month + 1))

    def __init_group_value(self, length):
        self.cpu_util = [0] * length
        self.memory_util = [0] * length
        self.disk_write_rate = [0] * length
        self.disk_read_rate = [0] * length
        self.network_write_rate = [0] * length
        self.network_read_rate = [0] * length
        self.memory_usage = [0] * length
        self.memory_total = [0] * length

def verify_params(startTime, endTime, timeType):
    """
    验证参数是否合法
    :param startTime:
    :param endTime:
    :param timeType:
    :return:
    """

    if startTime == None or endTime == None or timeType == None:
        raise wsme.exc.MissingArgument(argname="missingArg", msg='startTime,endTime,timeType are need')
    if timeType not in ('hour', 'day', 'month'):
        raise wsme.exc.UnknownArgument(argname="missingArg", msg='timeType value must be one of {hour,day,month}')
    try:
        startTime += " 00:00:00"
        startTime = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
        endTime += " 23:59:59"
        endTime = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
    except ValueError:
        raise wsme.exc.UnknownArgument(argname="missingArg", msg='time format error,must like that:year-month-day')

    return startTime, endTime, timeType

def get_period_by_timeType(timeType):
    """
    获取对应的时间间隔
    :param timeType: 单位 秒
    :return:
    """
    # hour表示返回的数据间隔以小时为单位
    # day表示以天为单位
    # month表示以月为单位
    str_to_second = {"hour": 3600, "day": 86400, "month":2592000}
    return str_to_second[timeType]

def get_q_from_condition(resource_uuid, startTime, endTime):
    """
    获取过滤条件
    :param resource_uuid:
    :param startTime:
    :param endTime:
    :return:
    """
    q = []
    q_item = base.Query()
    q_item.field = "resource_id"
    q_item.type = "string"
    q_item.op = "eq"
    q_item.value = resource_uuid
    q.append(q_item)
    start_item = base.Query()
    start_item.field = "timestamp"
    start_item.op = "le"
    start_item.value = str(endTime)
    q.append(start_item)
    end_item = base.Query()
    end_item.field = "timestamp"
    end_item.op = "ge"
    end_item.value = str(startTime)
    q.append(end_item)
    return q

def set_value_to_result(result=None, data=None, timeType=None, startTime=None, computed=None):
    """
    将值根据日期放到正确的位置上
    :param c: sample值
    :param result: Capability
    :param data:
    :param timeType:
    :param startTime:
    :return:
    """
    dict_to_result = {"memory": result.memory_total, "cpu_util": result.cpu_util,
                      "disk.read.bytes.rate": result.disk_read_rate,
                      "disk.write.bytes.rate": result.disk_write_rate,
                      "network.incoming.bytes.rate": result.network_read_rate,
                      "network.outgoing.bytes.rate": result.network_write_rate,
                      "memory.usage": result.memory_usage}
    for c in computed:
        time = c.duration_start
        if timeType == "hour":
            delta = ((time - startTime).days) * 24 + time.hour + 1
            dict_to_result[data][delta - 1] = c.avg
        if timeType == "day":
            delta = time - startTime
            dict_to_result[data][delta.days] = c.avg
        if timeType == "month":
            if startTime.year == time.year:
                delta = time.month - startTime.month
                dict_to_result[data][delta] = c.avg
            if time.year > startTime.year:
                delta = (time.year - startTime.year - 1) * 12 + time.month + (12 - startTime.month + 1)
                dict_to_result[data][delta] = c.avg
    return result

class CapabilityController(rest.RestController):
    _custom_actions = {
        'vm': ['GET'],
        'vm_util': ['GET'],
    }

    @wsme_pecan.wsexpose(Capability, str, str, str, str)
    def vm(self, vm_uuid=None, startTime=None, endTime=None, timeType=None):
        """
        获取虚拟机内存使用率，cpu利用率，磁盘读取速率，写速率，网络读速率，写速率
        memory        内存总量
        cpu_util      cpu利用率
        memory.usage  内存使用量
        disk.device.read.bytes.rate 磁盘读取速率
        disk.device.write.bytes.rate 磁盘写速率
        network.incoming.bytes.rate  网络读速率
        network.outgoing.bytes.rate  网络写速率
        :param vm_uuid:
        :param startTime:
        :param endTime:
        :param timeType: {hour,day,month,year}
        :return:
        """
        if vm_uuid:
            # 验证参数
            startTime, endTime, timeType = verify_params(startTime, endTime, timeType)
            period = get_period_by_timeType(timeType)
            q = get_q_from_condition(vm_uuid, startTime, endTime)
            kwargs = v2_utils.query_to_kwargs(q, storage.SampleFilter.__init__)
            dataType = ["cpu_util", "memory", "memory.usage", "disk.read.bytes.rate",
                        "disk.write.bytes.rate",
                        "network.incoming.bytes.rate",
                        "network.outgoing.bytes.rate"]
            result = Capability(startTime, endTime, timeType)
            # dict_to_result = {"memory": result.memory_total, "cpu_util": result.cpu_util,
            #                   "disk.read.bytes.rate": result.disk_read_rate,
            #                   "disk.write.bytes.rate": result.disk_write_rate,
            #                   "network.incoming.bytes.rate": result.network_read_rate,
            #                   "network.outgoing.bytes.rate": result.network_write_rate,
            #                   "memory.usage": result.memory_usage}
            for data in dataType:
                kwargs['meter'] = data
                f = storage.SampleFilter(**kwargs)
                try:
                    computed = pecan.request.storage_conn.get_meter_statistics(
                        f, period)
                except Exception:
                    continue;
                if (len(computed) != 0):
                    result = set_value_to_result(result, data, timeType, startTime, computed)
            result.memory_util = [
                (result.memory_usage[i] / result.memory_total[i]) * 100 if result.memory_total[i] != 0 else 0 for i in
                range(len(result.memory_total))]
            result.disk_read_rate = [item / 1024 for item in result.disk_read_rate]
            result.disk_write_rate = [item / 1024 for item in result.disk_write_rate]
            result.network_read_rate = [item / 1024 for item in result.network_read_rate]
            result.network_write_rate = [item / 1024 for item in result.network_write_rate]
        else:
            raise wsme.exc.MissingArgument(argname="missingArg", msg='must pass vm_uuid')

        return result

    @wsme_pecan.wsexpose(str)
    def vm_util(self):
        from ceilometer.compute.virt import inspector
        vm_inspector = inspector.get_hypervisor_inspector()
        Instance = inspector.collections.namedtuple('Instance', ['name', 'UUID', 'id'])
        instance = Instance("hy2", "94e67441-b4dc-4e30-880a-87b60947b67d", "94e67441-b4dc-4e30-880a-87b60947b67d")
        cpu_uils = vm_inspector.inspect_cpus(instance)
        disk_info = vm_inspector.inspect_disk_info(instance)
        memeory_usage = vm_inspector.inspect_memory_usage(instance)
        return "ok"


import genericpath
import re
import sys
import argparse
import os
import shutil
import boto3
import yaml
import zipfile
import os.path
from os import path
import time

list_processed_component = []
general_d = {}

def zip(src, dst):
    zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(src)
    for dirname, subdirs, files in os.walk(src):
        for filename in files:
            absname = os.path.abspath(os.path.join(dirname, filename))
            arcname = absname[len(abs_src) + 1:]
            print('zipping %s as %s' % (os.path.join(dirname, filename),
                                        arcname))
            zf.write(absname, arcname)
    zf.close()

def create_components(name):
    if (name not in list_processed_component):
        for component_recipe in os.listdir(build_recipes_path):
            recipe_file_path = os.path.join(build_recipes_path, component_recipe)
            with open(recipe_file_path) as f:
                try:
                    response = gg_client.create_component_version(inlineRecipe=f.read())
                    print(response)
                except Exception as e:
                    print("Failed to create the component using the recipe at {}.\nException: {}".format(recipe_file_path, e))
                    exit(1)

def upload_artifacts(file_name, object_name=None):
    if object_name is None:
        object_name = file_name
    try:
        print("Uploading artifacts to the bucket {} with key {}.".format(bucket, object_name))
        result = s3_client.upload_file(file_name, bucket, object_name)
        print(result)
    except Exception as e:
        print("Failed to upload the artifacts to the bucket {} with key {}.\nException: {}".format(bucket, object_name, e))
        exit(1)
    print("Successfully uploaded the artifacts to the bucket {} with key {}.".format(bucket, object_name))

def create_artifacts(name):
    if (name not in list_processed_component):
        for component in os.listdir(artifacts_path):
            component_path = os.path.join(artifacts_path, component)

            for version in os.listdir(component_path):
                if version.startswith("."):
                    continue
                version_path = os.path.join(component_path, version)
                component_latest_version = get_latest_version(component, version)
                build = os.path.join(build_artifacts_path, component, component_latest_version)
                os.makedirs(build, mode=0o777, exist_ok = True)
                zip(version_path+"/", build+"/"+name)
                upload_artifacts(build+"/"+name+".zip", "artifacts/"+name+".zip")
                return "artifacts/"+name+".zip"

def create_recipes_with_artifacts(res, name):

    if (name not in list_processed_component):
        os.makedirs(build_recipes_path, mode=0o777, exist_ok=True)
        for component_recipe in os.listdir(recipes_path):
            component = component_recipe.split("-")
            c_name = component[0]
            c_version = component[1].split(".yaml")[0]
            latest_version = get_latest_version(c_name, c_version)
            print(latest_version)
            with open(os.path.join(recipes_path, component_recipe)) as f:
                recipe = f.read()
            recipe = recipe.replace("$BUCKETNAME$", bucket)
            recipe = recipe.replace("$COMPONENT_VERSION$", latest_version)
            recipe = recipe.replace("$PATHZIP$", res)

            recipe = yaml.load(recipe)
            recipe["ComponentVersion"]=latest_version
            d[c_name] = {'componentVersion': recipe["ComponentVersion"]}
            general_d[c_name] = {'componentRecipes': component_recipe, 'componentVersion': recipe["ComponentVersion"]}

            recipe_file_name = "{}-{}.json".format(c_name, latest_version)
            with open(os.path.join(build_recipes_path, recipe_file_name), "w") as f:
                f.write(yaml.dump(recipe))

    else:
        for component_recipe in os.listdir(recipes_path):
            component = component_recipe.split("-")
            c_name = component[0]
            d[c_name] = {'componentVersion': general_d[c_name]['componentVersion']}

def create_recipes_without_artifacts(name):
    if (name not in list_processed_component):
        os.makedirs(build_recipes_path, mode=0o777, exist_ok=True)
        for component_recipe in os.listdir(recipes_path):
            component = component_recipe.split("-")
            c_name = component[0]
            c_version = component[1].split(".yaml")[0]

            latest_version = get_latest_version(c_name, c_version)
            print(latest_version)
            with open(os.path.join(recipes_path, component_recipe)) as f:
                recipe = f.read()
            recipe = recipe.replace("$COMPONENT_VERSION$", latest_version)

            recipe = yaml.load(recipe)
            recipe["ComponentVersion"]=latest_version
            d[c_name] = {'componentVersion': recipe["ComponentVersion"]}
            general_d[c_name] = {'componentRecipes': component_recipe, 'componentVersion': recipe["ComponentVersion"]}

            recipe_file_name = "{}-{}.json".format(c_name, latest_version)
            with open(os.path.join(build_recipes_path, recipe_file_name), "w") as f:
                f.write(yaml.dump(recipe))
    else:

        for component_recipe in os.listdir(recipes_path):
            component = component_recipe.split("-")
            c_name = component[0]
            d[c_name] = {'componentVersion': general_d[c_name]['componentVersion']}

def get_account_number():
    try:
        response = sts_client.get_caller_identity()
        if response is not None:
            account = response["Account"]
            return account
    except Exception as e:
        print("Cannot get the account id from the credentials.\nException: {}".format(e))
        exit(1)

def get_latest_version(c_name, c_version):
    try:
        account = get_account_number()
        print("Fetching the component {} from the account: {}, region: {}".format(c_name, account, region))
        response = gg_client.list_component_versions(
            arn="arn:aws:greengrass:{}:{}:components:{}".format(region, account, c_name),
        )
        if response is not None:
            print(response)
            component_versions = response["componentVersions"]
            if component_versions:
                versions = component_versions[0]["componentVersion"]
                split = versions.split("-")[0].split(".")
                major = split[0]
                minor = split[1]
                patch = split[2]
                return "{}.{}.{}".format(major, minor, str(int(patch) + 1))
            else:
                return c_version
    except Exception as e:
        print("Error getting the latest version of the component.\nException: {}".format(e))

def create_distribution(d, g_name):
    d['aws.greengrass.Cli'] = {'componentVersion': '2.3.0'}
    #d['aws.greengrass.SecureTunneling'] = {'componentVersion': '1.0.3'}
    d['aws.greengrass.Nucleus'] = {'componentVersion': '2.3.0'}
    response = gg_client.create_deployment(
            targetArn=gname_prefix+g_name,
            deploymentName='InstancesGroupAWS',
            components=d,
            deploymentPolicies={
                'failureHandlingPolicy': 'DO_NOTHING',
                'componentUpdatePolicy': {
                    'timeoutInSeconds': 123,
                    'action': 'SKIP_NOTIFY_COMPONENTS'
                },
                'configurationValidationPolicy': {
                    'timeoutInSeconds': 123
                }
            }
        )
    print("\n\n")
    print(d)

cpath = "Components/"
gname_prefix = "arn:aws:iot:eu-central-1:**************:thinggroup/"

parser = argparse.ArgumentParser()
parser.add_argument(
    "--cmps_path",
    default=cpath,
    help="You must specify the folder where the components are located",
)

args = parser.parse_args()
rootdir = args.cmps_path

if(not path.exists(rootdir)):
    print("The path is not valid.")
    exit(1)

session = boto3.Session(
    region_name="eu-central-1",
    aws_access_key_id='',
    aws_secret_access_key=''
)

gg_client = session.client("greengrassv2")
sts_client = session.client("sts")
s3_client = session.client("s3")
region = "eu-central-1"
bucket = "ggv2-example-component-artifacts"

groups = os.listdir(rootdir)
for group in groups:
    d = {}
    g = os.listdir(rootdir+"/"+group)
    print("\n\nPROCESSING GROUP:", group)
    for component in g:
        dir_path = os.path.dirname(os.path.realpath(__file__))+"/"+rootdir+"/"+group+"/"+component
        artifacts_path = os.path.join(dir_path, "artifacts")
        recipes_path = os.path.join(dir_path, "recipes")

        build_dir_path = os.path.join(dir_path, "build")
        build_artifacts_path = os.path.join(build_dir_path, "artifacts")
        build_recipes_path = os.path.join(build_dir_path, "recipes")

        shutil.rmtree(build_dir_path, ignore_errors=True, onerror=None)

        if(os.path.exists(artifacts_path)):
            res = create_artifacts(component)
            create_recipes_with_artifacts(res, component)
            create_components(component)
        else:
            create_recipes_without_artifacts(component)
            create_components(component)

        list_processed_component.append(component)

    create_distribution(d, group)


import os.path

from setuptools import find_packages, setup

def read(rel_path):
    here = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(here, rel_path), "r") as fp:
        return fp.read()

def get_version(rel_path):
    for line in read(rel_path).splitlines():
        if line.startswith("__version__"):
            delim = '"' if '"' in line else "'"
            return line.split(delim)[1]
    else:
        raise RuntimeError("Unable to find version string.")

def get_long_description():
    with open("README.md", "r") as f:
        text = f.read()
    return text

setup(
    name="esp-idf-size",
    version=get_version("esp_idf_size/__init__.py"),
    author="Espressif Systems",
    author_email="",
    description="Firmware size analysis for ESP-IDF",
    long_description_content_type="text/markdown",
    long_description=get_long_description(),
    url="https://github.com/espressif/esp-idf-size",
    packages=find_packages(),
    python_requires=">=3.7",
    install_requires=["pyyaml"],
    extras_require={
        "dev": [
            "pre-commit",
            "coverage",
            "jsonschema",
        ],
    },
    keywords=["espressif", "embedded", "project", "size"],
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Natural Language :: English",
        "Environment :: Console",
        "Topic :: Software Development :: Embedded Systems",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Operating System :: POSIX",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: MacOS :: MacOS X",
    ],
    include_package_data=True,
)


from unittest import TestCase

from b26_toolkit.b26_toolkit.instruments import DummyInstrument
from src.scripts import ScriptDummy, ScriptDummyWithSubScript, ScriptDummyWithInstrument

class TestScriptDummy(TestCase):

    def setUp(self):
        self.script = ScriptDummy('main scripts')
        self.script_with_sub = ScriptDummyWithSubScript({'sub_script':self.script}, 'script with d')

        self.inst = DummyInstrument()
        self.script_with_inst = ScriptDummyWithInstrument({'dummy_instrument':self.inst}, 'script with inst')

    def test_init(self):
        self.script.run()

        self.script.update({'count': 10})

        self.assertEqual(self.script.settings['count'],10)

    def test_to_dict(self):

        self.assertEqual(self.script.settings,self.script.to_dict()[self.script.name]['settings'])
        s = self.script_with_sub
        print(('script name', s.name))
        for key, val in s.to_dict()[s.name].items():
            print((key, val))
        print('----------------------')
        print((self.inst.to_dict()))

    def test_with_inst(self):
        instr = {}
        script_with_inst = ScriptDummyWithInstrument(instr)


from ..extensions import db
from flask_restful import fields

class Publisher(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    @staticmethod
    def simple_fields():
        return {
                'id': fields.String,
                'name': fields.String
                }

    @staticmethod
    def get(id):
        return Publisher.query.get(id);

    @staticmethod
    def create(name):
        has_one = Publisher.query.filter_by(name=name).first()
        if has_one:
            return has_one
        new_one = Publisher(name=name)
        db.session.add(new_one)
        db.session.commit()
        return new_one

    @staticmethod
    def update(id, name):
        publisher = Publisher.query.get(id)
        if publisher:
            publisher.name = name
        db.session.commit()
        return publisher

    @staticmethod
    def delete(id):
        publisher = Publisher.query.get(id)
        if publisher:
            db.session.delete(publisher)
            db.session.commit()
        return publisher


from prefect import Flow, Task, Parameter
from prefect.tasks.control_flow import case
from prefect.engine import signals
import saspy
import os
import time
import prefect

class RunSpreTask(Task):
    def run(self, **params):
        print(params)
        # Get the values from the global parameters
        FA_PATH = prefect.context.parameters['FA_PATH']
        RUN_INSTANCE = prefect.context.parameters['RUN_INSTANCE']
        if type(prefect.context.map_index) != int:
            MAP_INDEX = 0
        else:
            MAP_INDEX = prefect.context.map_index+1

        STAGE_INDEX = 1
        if 'STAGE_INDEX' in params:
            STAGE_INDEX = params["STAGE_INDEX"]

        # Prepare the JSON string to pass to core_run_sas. The JSON string will have all a NAME VALUE pair of each input
        list_params = []
        for key, value in params.items():
            dict_param = dict()
            dict_param["NAME"] = key
            dict_param["VALUE"] = value
            list_params.append(dict_param)

        # Create a SAS session and run the core_run_sas.sas wrapper passing the parameters
        sas = saspy.SASsession()
        sas.set_batch(True)
        sas.symput('FA_PATH', FA_PATH)
        sas.symput('RUN_INSTANCE', RUN_INSTANCE)
        sas.symput('INPUT_PARAMETERS', list_params)
        sas.symput('MAP_INDEX', MAP_INDEX)

        r = sas.submit('''
            %put INPUT_PARAMETERS: &INPUT_PARAMETERS;
            %include "&FA_PATH\prefect\source\core_run_sas.sas";
        ''')
        N_PARTITIONS = sas.symget('N_PARTITIONS')

        # Show the log and save it in a file
        # print(r['LOG'])
        log_name = params['NODE_CODE'] + "_" + str(STAGE_INDEX) + "_" + str(MAP_INDEX) + "_" +\
            time.strftime("%Y%m%d_%H%M%S") + '.log'
        log_file = open(os.path.join(
            RUN_INSTANCE+'\\logs', log_name), "w")
        log_file.write(r['LOG'])
        log_file.close()
        print('Check SAS Logs: ' + RUN_INSTANCE + '\\logs\\'+log_name)
        # Close the SAS session
        sas.endsas()

        # Check ig the log as any ERRORs and change the state of the task
        if (sas.check_error_log):
            print("SAS submit finished with errors")
            raise signals.FAIL()

        if type(N_PARTITIONS) != int:
            N_PARTITIONS = 0
        print("The number of partitions is: " + str(N_PARTITIONS))
        # Return the number of the partitions in case this variable was created in SAS
        return [i for i in range(N_PARTITIONS)]

class PartitionCardinalityTask(Task):
    def run(self, n_partitions):
        run_partitions_flg = 0
        if len(n_partitions) > 1:
            run_partitions_flg = 1
        print(n_partitions)
        print(run_partitions_flg)
        return run_partitions_flg

# Global parameters
BASE_DT = Parameter('BASE_DT', default='12312019')
ENTITY_ID = Parameter('ENTITY_ID', default='SASBank_1')
CYCLE_ID = Parameter('CYCLE_ID', default='10000')
FA_ID = Parameter('FA_ID', default='2022.1.1')
FA_PATH = Parameter(
    'FA_PATH', default='C:\\Development\\Temp\\Prefect_Cirrus_Core\\core\\2022.1.1')
RUN_INSTANCE = Parameter(
    'RUN_INSTANCE', default='C:\\Development\\Temp\\Prefect_Cirrus_Core\\core\\2022.1.1\\prefect\\run_instance\\prefect-spre-10000-12312019')

flow = Flow("Data_Preparation")

# Initialize and run the tasks
initialize = RunSpreTask(name='Initialize', log_stdout=True)
flow.set_dependencies(task=initialize,
                      upstream_tasks=[],
                      keyword_tasks=dict(BASE_DT=BASE_DT,
                                         CYCLE_ID=CYCLE_ID,
                                         ENTITY_ID=ENTITY_ID,
                                         FA_ID=FA_ID,
                                         FA_PATH=FA_PATH,
                                         RUN_INSTANCE=RUN_INSTANCE,
                                         NODE_CODE='core_node_init.sas',
                                         RUN_OPTION='core_cfg.run_option',
                                         SYSTEM_OPTION='sys_cfg.run_option',
                                         FLOW_OPTION='core_res.flow_option',
                                         )
                      )

filter_by_entity = RunSpreTask(name='Filter by Entity', log_stdout=True)
flow.set_dependencies(task=filter_by_entity,
                      upstream_tasks=[initialize],
                      keyword_tasks=dict(
                          GROUP_FLG='N',
                          NODE_CODE='core_node_filter_entity.sas',
                          ENTITY_IN='core_lnd.entity',
                          ENTITY_OUT='core_res.entity',
                      )
                      )

prepare_enrichment = RunSpreTask(name='Prepare Enrichment', log_stdout=True)
flow.set_dependencies(task=prepare_enrichment,
                      upstream_tasks=[initialize],
                      keyword_tasks=dict(
                          NODE_CODE='core_node_prepare_enrichment.sas',
                          EXECUTION_CONFIG='sys_cfg.execution_config',
                          ENRICHMENT_CONFIG='sys_cfg.enrichment_config',
                          ENRICHMENT_STAGE1='core_stg.enrichment_config_stage1',
                          ENRICHMENT_STAGE2='core_stg.enrichment_config_stage2',
                          ENRICHMENT_STAGE3='core_stg.enrichment_config_stage3',
                          ENRICHMENT_STAGE4='core_stg.enrichment_config_stage4',
                          ENRICHMENT_STAGE5='core_stg.enrichment_config_stage5',
                      )
                      )

# enrichment_stage_1 = RunSpreTask(name='Enrichment Stage1', log_stdout=True)
# flow.set_dependencies(task=enrichment_stage_1,
#                       upstream_tasks=[prepare_enrichment, filter_by_entity
#                                       ],
#                       keyword_tasks=dict(
#                           NODE_CODE='core_node_set_cardinality_byn.sas',
#                           ENRICHMENT_CONFIG='core_stg.enrichment_config_stage1',
#                           STAGE=1,
#                           ENRICHMENT_CARDINALITY='core_stg.enrichment_cardinality_1',
#                       )
#                       )

# map_run_partition_stage1 = RunSpreTask(
#     name='Run Partition Stage 1', log_stdout=True)
# flow.set_dependencies(task=map_run_partition_stage1,
#                       upstream_tasks=[enrichment_stage_1],
#                       keyword_tasks=dict(
#                           RUN=enrichment_stage_1,
#                       ),
#                       mapped=True,
#                       )
# flow.set_dependencies(task=map_run_partition_stage1,
#                       upstream_tasks=[enrichment_stage_1],
#                       keyword_tasks=dict(
#                           STAGE=1,
#                           NODE_CODE='core_node_run_task.sas',
#                           ENRICHMENT_CONFIG='core_stg.enrichment_config_stage_1',
#                           RUN_TYPE='CODE',
#                           FUNCTIONAL_CCY='USD',
#                           ENRICH_COUNTERPARTY_FLG='N',
#                           ENRICHMENT_CARDINALITY='core_stg.enrichment_cardinality_1',
#                           PARTITION_INPUT='core_stg.enrichment_config_stage1_part&MAP_INDEX.',
#                           RESULT_LIST_OUT='core_stg.result_list_1_&MAP_INDEX.',
#                           RUN_RESULT_OUT='core_stg.result_1_&MAP_INDEX.',
#                       )
#                       )
max_stages = 2
stages = dict()
for i in range(1, max_stages+1):
    task = dict()
    task['enrichment_stage_auto_' +
         str(i)] = RunSpreTask(name='Enrichment Stage Auto '+str(i), log_stdout=True)
    task['partition_cardinality_' + str(i)] = PartitionCardinalityTask(
        name='Check Partition Cardinality Stage '+str(i), log_stdout=True)
    task['map_run_partition_auto_stage_' +
         str(i)] = RunSpreTask(name='Run Partition Auto Stage '+str(i), log_stdout=True)
    stages['stage' + str(i)] = task

previous_key = None
for stage_index, (stage_key, stage_value) in enumerate(stages.items()):

    task_list = list(stage_value.keys())
    enrichment_stage_auto_n = stage_value[task_list[0]]
    partition_cardinality_n = stage_value[task_list[1]]
    map_run_partition_auto_stage_n = stage_value[task_list[2]]

    if previous_key is None:
        list_upstream_tasks = [prepare_enrichment, filter_by_entity]
    else:
        list_upstream_tasks = [previous_key]

    flow.set_dependencies(task=enrichment_stage_auto_n,
                          upstream_tasks=list_upstream_tasks,
                          keyword_tasks=dict(
                              NODE_CODE='core_node_set_cardinality_byn.sas',
                              ENRICHMENT_CONFIG='core_stg.enrichment_config_stage' +
                              str(stage_index+1),
                              STAGE=stage_index+1,
                              ENRICHMENT_CARDINALITY='core_stg.enrichment_cardinality_' +
                              str(stage_index+1),
                          )
                          )

    flow.set_dependencies(task=partition_cardinality_n,
                          upstream_tasks=[enrichment_stage_auto_n],
                          keyword_tasks=dict(n_partitions=enrichment_stage_auto_n
                                             )
                          )

    with case(partition_cardinality_n, 1):
        flow.set_dependencies(task=map_run_partition_auto_stage_n,
                              upstream_tasks=[enrichment_stage_auto_n],
                              keyword_tasks=dict(
                                  RUN=enrichment_stage_auto_n,
                              ),
                              mapped=True,
                              )
        flow.set_dependencies(task=map_run_partition_auto_stage_n,
                              upstream_tasks=[partition_cardinality_n],
                              keyword_tasks=dict(
                                  STAGE=stage_index+1,
                                  NODE_CODE='core_node_run_task.sas',
                                  ENRICHMENT_CONFIG='core_stg.enrichment_config_stage_' +
                                  str(stage_index+1),
                                  RUN_TYPE='CODE',
                                  FUNCTIONAL_CCY='USD',
                                  ENRICH_COUNTERPARTY_FLG='N',
                                  ENRICHMENT_CARDINALITY='core_stg.enrichment_cardinality_' +
                                  str(stage_index+1),
                                  PARTITION_INPUT='core_stg.enrichment_config_stage' +
                                  str(stage_index+1)+'_part&MAP_INDEX.',
                                  RESULT_LIST_OUT='core_stg.result_list_' +
                                  str(stage_index+1)+'_&MAP_INDEX.',
                                  RUN_RESULT_OUT='core_stg.result_' +
                                  str(stage_index+1)+'_&MAP_INDEX.',
                              )
                              )

    previous_key = map_run_partition_auto_stage_n

flow.visualize()
flow.run()


def int_to_str(input_int):

    if input_int < 0:
        is_negative = True
        input_int *= -1
    else:
        is_negative = False

    output_str = []
    while input_int > 0:
        output_str.append(chr(ord("0") + input_int % 10))
        input_int //= 10
    output_str = output_str[::-1]

    output_str = ''.join(output_str)

    if is_negative:
        return '-' + output_str
    else:
        return output_str

input_int = 123
print(input_int)
print(type(input_int))

output_str = int_to_str(input_int)
print(output_str)
print(type(output_str))

def str_to_int(input_str):
    output_int = 0

    if input_str[0] == "-":
        start_idx = 1
        is_negative = True
    else:
        start_idx = 0
        is_negative = False

    for i in range(start_idx, len(input_str)):
        place = 10**(len(input_str) - (i+1))
        digit = ord(input_str[i]) - ord("0")
        output_int += place * digit

    if is_negative:
        return -1 * output_int
    else:
        return output_int

s = "554"
x = str_to_int(s)
print(type(x))

s = "123"
print(str_to_int(s))

s = "-123"
print(str_to_int(s))


from decimal import Decimal

import logic_bank_utils.util as logic_bank_utils
from logic_bank.util import row_prt, prt

(did_fix_path, sys_env_info) = \
    logic_bank_utils.add_python_path(project_dir="LogicBankTutorial", my_file=__file__)
print("\n" + did_fix_path + "\n\n" + sys_env_info + "\n\n")
import os
from shutil import copyfile
# from logic_bank.util import prt

def setup_db():
    """ copy db/database-gold.db over db/database.db"""
    print("\n" + prt("restoring database-gold\n"))

    basedir = os.path.abspath(os.path.dirname(__file__))
    basedir = os.path.dirname(basedir)

    print("\n********************************\n"
          "  IMPORTANT - create database.db from database-gold.db in " + basedir + "/payment_allocation/db/\n" +
          "            - from -- " + prt("") +
          "\n********************************")

    db_loc = os.path.join(basedir, "db/database.db")
    db_source = os.path.join(basedir, "db/database-gold.db")
    copyfile(src=db_source, dst=db_loc)

setup_db()

import sqlalchemy_utils

import db.models as models
from logic_bank.exec_row_logic.logic_row import LogicRow
from logic import session  # opens db, activates logic listener <--

pre_cust = session.query(models.Customer).filter(models.Customer.Id == "ALFKI").one()
session.expunge(pre_cust)

"""
    Create Order row
"""

cust_alfki = session.query(models.Customer).filter(models.Customer.Id == "ALFKI").one()

amount_total = 500  # 500 should work; change to 1000 to see constraint fire

new_order = models.Order(AmountTotal=amount_total)
cust_alfki.OrderList.append(new_order)

session.add(new_order)
session.commit()  # this fires the rules (adjust balance, verify <=2000)

post_cust = session.query(models.Customer).filter(models.Customer.Id == "ALFKI").one()

print("\nadd_order, update completed\n\n")

logic_row = LogicRow(row=post_cust, old_row=pre_cust, ins_upd_dlt="*", nest_level=0, a_session=session, row_sets=None)

assert post_cust.Balance == pre_cust.Balance + amount_total,\
    "ERROR - incorrect adjusted Customer Result (EXPECTED - now add rules)"

logic_row.log("Correct adjusted Customer Result")

print("\nadd_order, ran to completion\n\n")


hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]

prices = [30, 25, 40, 20, 20, 35, 50, 35]

last_week = [2, 3, 5, 8, 4, 4, 6, 2]

# Create total_price variable
total_price = 0

# Create for loop to sum total price
for price in prices:
  total_price += price

# Create average_price variable
average_price = total_price / len(prices)

# Print average_price
print(average_price)

# Reduce all prices by 5
new_prices = [price -5 for price in prices]

# Print new_prices
print(new_prices)

# Create total_revenue variable
total_revenue = 0

# Create for loop for total revenue calculation
for i in range(len(hairstyles)):
  total_revenue += prices[i] * last_week[i]

# Print total_revenue
print("Total Revenu:", total_revenue)

# Create and print out average_daily_revenue
average_daily_revenue = total_revenue / 7
print(average_daily_revenue)

# Create cuts_under_30 variable
cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]
print(cuts_under_30)


import contextlib
import re
import textwrap
import traceback
from typing import Iterable, List, Optional

from streamlit.runtime.metrics_util import gather_metrics

_SPACES_RE = re.compile("\\s*")
_EMPTY_LINE_RE = re.compile("\\s*\n")

@gather_metrics("echo")
@contextlib.contextmanager
def echo(code_location="above"):
    """Use in a `with` block to draw some code on the app, then execute it.

    Parameters
    ----------
    code_location : "above" or "below"
        Whether to show the echoed code before or after the results of the
        executed code block.

    Example
    -------
    >>> import streamlit as st
    >>>
    >>> with st.echo():
    >>>     st.write('This code will be printed')

    """
    from streamlit import code, empty, source_util, warning

    if code_location == "below":
        show_code = code
        show_warning = warning
    else:
        placeholder = empty()
        show_code = placeholder.code
        show_warning = placeholder.warning

    try:
        # Get stack frame *before* running the echoed code. The frame's
        # line number will point to the `st.echo` statement we're running.
        frame = traceback.extract_stack()[-3]
        filename, start_line = frame.filename, frame.lineno

        # Read the file containing the source code of the echoed statement.
        with source_util.open_python_file(filename) as source_file:
            source_lines = source_file.readlines()

        # Get the indent of the first line in the echo block, skipping over any
        # empty lines.
        initial_indent = _get_initial_indent(source_lines[start_line:])

        # Iterate over the remaining lines in the source file
        # until we find one that's indented less than the rest of the
        # block. That's our end line.
        #
        # Note that this is *not* a perfect strategy, because
        # de-denting is not guaranteed to signal "end of block". (A
        # triple-quoted string might be dedented but still in the
        # echo block, for example.)
        # TODO: rewrite this to parse the AST to get the *actual* end of the block.
        lines_to_display: List[str] = []
        for line in source_lines[start_line:]:
            indent = _get_indent(line)
            if indent is not None and indent < initial_indent:
                break
            lines_to_display.append(line)

        code_string = textwrap.dedent("".join(lines_to_display))

        # Run the echoed code...
        yield

        # And draw the code string to the app!
        show_code(code_string, "python")

    except FileNotFoundError as err:
        show_warning("Unable to display code. %s" % err)

def _get_initial_indent(lines: Iterable[str]) -> int:
    """Return the indent of the first non-empty line in the list.
    If all lines are empty, return 0.
    """
    for line in lines:
        indent = _get_indent(line)
        if indent is not None:
            return indent

    return 0

def _get_indent(line: str) -> Optional[int]:
    """Get the number of whitespaces at the beginning of the given line.
    If the line is empty, or if it contains just whitespace and a newline,
    return None.
    """
    if _EMPTY_LINE_RE.match(line) is not None:
        return None

    match = _SPACES_RE.match(line)
    return match.end() if match is not None else 0


"""
Test handle tool functionality.
"""

import unittest

import pytest
from gaphas.aspect import ConnectionSink, Connector
from gi.repository import Gdk, Gtk

from gaphor import UML
from gaphor.application import Application
from gaphor.diagram.connectors import IConnect
from gaphor.diagram.diagramtools import ConnectHandleTool, DiagramItemConnector
from gaphor.diagram.general.comment import CommentItem
from gaphor.diagram.general.commentline import CommentLineItem
from gaphor.diagram.usecases.actor import ActorItem
from gaphor.ui.abc import UIComponent
from gaphor.ui.event import DiagramOpened

@pytest.fixture
def application():
    Application.init(
        services=[
            "event_manager",
            "component_registry",
            "element_factory",
            "main_window",
            "properties_manager",
            "properties",
            "namespace",
            "diagrams",
            "toolbox",
            "elementeditor",
            "export_menu",
            "tools_menu",
        ]
    )
    main_window = Application.get_service("main_window")
    main_window.open()
    yield Application
    Application.shutdown()

@pytest.fixture
def element_factory(application):
    return application.get_service("element_factory")

@pytest.fixture
def event_manager(application):
    return application.get_service("event_manager")

@pytest.fixture
def diagram(element_factory):
    return element_factory.create(UML.Diagram)

@pytest.fixture
def comment(element_factory, diagram):
    return diagram.create(CommentItem, subject=element_factory.create(UML.Comment))

@pytest.fixture
def commentline(diagram):
    return diagram.create(CommentLineItem)

def test_aspect_type(commentline):
    aspect = Connector(commentline, commentline.handles()[0])
    assert isinstance(aspect, DiagramItemConnector)

def test_query(comment):
    assert IConnect(comment, commentline)

def test_allow(commentline, comment):
    aspect = Connector(commentline, commentline.handles()[0])
    assert aspect.item is commentline
    assert aspect.handle is commentline.handles()[0]

    sink = ConnectionSink(comment, comment.ports()[0])
    assert aspect.allow(sink)

def test_connect(diagram, comment, commentline):
    sink = ConnectionSink(comment, comment.ports()[0])
    aspect = Connector(commentline, commentline.handles()[0])
    aspect.connect(sink)
    canvas = diagram.canvas
    cinfo = canvas.get_connection(commentline.handles()[0])
    assert cinfo, cinfo

class HandleToolTestCase(unittest.TestCase):
    """
    Handle connection tool integration tests.
    """

    def setUp(self):
        Application.init(
            services=[
                "event_manager",
                "component_registry",
                "element_factory",
                "main_window",
                "properties_manager",
                "properties",
                "namespace",
                "diagrams",
                "toolbox",
                "elementeditor",
                "export_menu",
                "tools_menu",
            ]
        )
        self.component_registry = Application.get_service("component_registry")
        self.event_manager = Application.get_service("event_manager")

        self.main_window = Application.get_service("main_window")
        self.main_window.open()

    def shutDown(self):
        Application.shutdown()

    def get_diagram_view(self, diagram):
        """
        Get a view for diagram.
        """
        view = self.component_registry.get(UIComponent, "diagrams").get_current_view()

        # realize view, forces bounding box recalculation
        while Gtk.events_pending():
            Gtk.main_iteration()

        return view

    def test_iconnect(self):
        """
        Test basic glue functionality using CommentItem and CommentLine
        items.
        """
        element_factory = Application.get_service("element_factory")
        diagram = element_factory.create(UML.Diagram)
        self.event_manager.handle(DiagramOpened(diagram))
        comment = diagram.create(
            CommentItem, subject=element_factory.create(UML.Comment)
        )

        actor = diagram.create(ActorItem, subject=element_factory.create(UML.Actor))
        actor.matrix.translate(200, 200)
        diagram.canvas.update_matrix(actor)

        line = diagram.create(CommentLineItem)

        view = self.get_diagram_view(diagram)
        assert view, "View should be available here"
        comment_bb = view.get_item_bounding_box(comment)

        # select handle:
        handle = line.handles()[-1]
        tool = ConnectHandleTool(view=view)

        tool.grab_handle(line, handle)
        handle.pos = (comment_bb.x, comment_bb.y)
        item = tool.glue(line, handle, handle.pos)
        assert item is not None

        tool.connect(line, handle, handle.pos)
        cinfo = diagram.canvas.get_connection(handle)
        assert cinfo.constraint is not None
        assert cinfo.connected is actor, cinfo.connected

        Connector(line, handle).disconnect()

        cinfo = diagram.canvas.get_connection(handle)

        assert cinfo is None

    def test_connect_comment_and_actor(self):
        """Test connect/disconnect on comment and actor using comment-line.
        """
        element_factory = Application.get_service("element_factory")
        diagram = element_factory.create(UML.Diagram)
        self.event_manager.handle(DiagramOpened(diagram))
        comment = diagram.create(
            CommentItem, subject=element_factory.create(UML.Comment)
        )

        line = diagram.create(CommentLineItem)

        view = self.get_diagram_view(diagram)
        assert view, "View should be available here"

        tool = ConnectHandleTool(view)

        # Connect one end to the Comment:
        handle = line.handles()[0]
        tool.grab_handle(line, handle)

        handle.pos = (0, 0)
        sink = tool.glue(line, handle, handle.pos)
        assert sink is not None
        assert sink.item is comment

        tool.connect(line, handle, handle.pos)
        cinfo = diagram.canvas.get_connection(handle)
        assert cinfo is not None, None
        assert cinfo.item is line
        assert cinfo.connected is comment

        # Connect the other end to the Actor:
        actor = diagram.create(ActorItem, subject=element_factory.create(UML.Actor))

        handle = line.handles()[-1]
        tool.grab_handle(line, handle)

        handle.pos = (0, 0)
        sink = tool.glue(line, handle, handle.pos)
        assert sink, f"No sink at {handle.pos}"
        assert sink.item is actor
        tool.connect(line, handle, handle.pos)

        cinfo = view.canvas.get_connection(handle)
        assert cinfo.item is line
        assert cinfo.connected is actor

        # Try to connect far away from any item will only do a full disconnect
        self.assertEqual(
            len(comment.subject.annotatedElement), 1, comment.subject.annotatedElement
        )
        assert actor.subject in comment.subject.annotatedElement

        sink = tool.glue(line, handle, (500, 500))
        assert sink is None, sink
        tool.connect(line, handle, (500, 500))

        cinfo = view.canvas.get_connection(handle)
        assert cinfo is None

    def skiptest_connect_3(self):
        """Test connecting through events (button press/release, motion).
        """
        element_factory = Application.get_service("element_factory")
        diagram = element_factory.create(UML.Diagram)

        comment = diagram.create(
            CommentItem, subject=element_factory.create(UML.Comment)
        )
        # self.assertEqual(30, comment.height)
        # self.assertEqual(100, comment.width)

        actor = diagram.create(ActorItem, subject=element_factory.create(UML.Actor))
        actor.matrix.translate(200, 200)
        diagram.canvas.update_matrix(actor)
        # assert actor.height == 60, actor.height
        # assert actor.width == 38, actor.width

        line = diagram.create(CommentLineItem)
        assert line.handles()[0].pos, (0.0, 0.0)
        assert line.handles()[-1].pos, (10.0, 10.0)

        view = self.get_diagram_view(diagram)
        assert view, "View should be available here"

        tool = ConnectHandleTool(view)

        tool.on_button_press(Gdk.Event(x=0, y=0, state=0))
        tool.on_button_release(Gdk.Event(x=0, y=0, state=0))

        handle = line.handles()[0]
        assert (0.0, 0.0) == view.canvas.get_matrix_i2c(line).transform_point(
            *handle.pos
        )
        cinfo = diagram.canvas.get_connection(handle)
        assert cinfo.connected is comment
        # self.assertTrue(handle.connected_to is comment, 'c = ' + str(handle.connected_to))
        # self.assertTrue(handle.connection_data is not None)

        # Grab the second handle and drag it to the actor

        tool.on_button_press(Gdk.Event(x=10, y=10, state=0))
        tool.on_motion_notify(Gdk.Event(x=200, y=200, state=0xFFFF))
        tool.on_button_release(Gdk.Event(x=200, y=200, state=0))

        handle = line.handles()[-1]
        assert (200, 200) == view.canvas.get_matrix_i2c(line).transform_point(
            handle.x, handle.y
        )
        cinfo = diagram.canvas.get_connection(handle)
        assert cinfo.connected is actor
        # self.assertTrue(handle.connection_data is not None)
        self.assertTrue(actor.subject in comment.subject.annotatedElement)

        # Press, release, nothing should change

        tool.on_button_press(Gdk.Event(x=200, y=200, state=0))
        tool.on_motion_notify(Gdk.Event(x=200, y=200, state=0xFFFF))
        tool.on_button_release(Gdk.Event(x=200, y=200, state=0))

        handle = line.handles()[-1]
        assert (200, 200) == view.canvas.get_matrix_i2c(line).transform_point(
            handle.x, handle.y
        )
        cinfo = diagram.canvas.get_connection(handle)
        assert cinfo.connected is actor
        # self.assertTrue(handle.connection_data is not None)
        self.assertTrue(actor.subject in comment.subject.annotatedElement)

        # Move second handle away from the actor. Should remove connection

        tool.on_button_press(Gdk.Event(x=200, y=200, state=0))
        tool.on_motion_notify(Gdk.Event(x=500, y=500, state=0xFFFF))
        tool.on_button_release(Gdk.Event(x=500, y=500, state=0))

        handle = line.handles()[-1]
        assert (500, 500) == view.canvas.get_matrix_i2c(line).transform_point(
            handle.x, handle.y
        )
        cinfo = diagram.canvas.get_connection(handle)
        assert cinfo is None
        # self.assertTrue(handle.connection_data is None)
        self.assertEqual(len(comment.subject.annotatedElement), 0)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/29 11:51
# @Author  : lj
# @File    : main.py
from flask import Flask

app = Flask(__name__)
@app.route('/',methods=['GET'])
def healthz():
    return {
        'code': 200,
        'data': None
    }
if __name__ == '__main__':
    app.run(host='0.0.0.0')


# Vigénere's Cipher
# Created by Fer Cortés & Arantza Parra
# Date: 2023/09/08

# This code is a implementation of the Vigenere's Cipher.
# It is a method of encrypting alphabetic text by
# using alphabetic substitution.

# Encryption formula: E_k(M_i) = (M_i + K_i) mod 26

# Decryption formula: D_k(C_i) = (C_i - K_i) mod 26

# The alphabet used will be "abcdefghijklmnopqrstuvwxyz ",
# the space is included.

alf = list("abcdefghijklmnopqrstuvwxyz ")

# function to get the index of the key
def keyShift(key: str) -> int:
    return alf.index(key)

# First, we need to assign a number to each letter in the alphabet
letterToIndex = dict(zip(alf, range(len(alf))))
indexToLetter = dict(zip(range(len(alf)), alf))

def extend_key(text, key):
    extended_key = ''
    key_len = len(key)
    text_len = len(text)
    for i in range(text_len):
        extended_key += key[i % key_len]
    return extended_key

def encrypt(plaintext, key):
    encrypted = ''
    extended_key = extend_key(plaintext, key)

    for i in range(len(plaintext)):
        number = (letterToIndex[plaintext[i]] + letterToIndex[extended_key[i]]) % len(alf)
        encrypted += indexToLetter[number]

    return encrypted

def decrypt(cipher, key):
    decrypted = ''
    extended_key = extend_key(cipher, key)

    for i in range(len(cipher)):
        number = (letterToIndex[cipher[i]] - letterToIndex[extended_key[i]]) % len(alf)
        decrypted += indexToLetter[number]

    return decrypted

def main():
    # Print the menu
    print("Choose an option:")
    print("1. Encrypt")
    print("2. Decrypt")

    # Get user's choice
    choice = input("Enter your choice (1/2): ")

    # Validate the choice
    while choice not in ['1', '2', '3']:
        print("Invalid choice. Please enter 1 or 2")
        choice = input("Enter your choice (1/2): ")

    # Process based on the choice
    if choice == '1':
        # Get plaintext or ciphertext from the user
        text = input("Enter the text: ")
        # Get the key from the user
        key = input("Enter the key: ")

        result = encrypt(text, key)
        print("Encrypted Text:", result)
    else:
        text = input("Enter the cipher: ")
        key = input("Enter the key: ")
        result = decrypt(text, key)
        print("Decrypted Text:", result)

if __name__ == "__main__":
    main()


sad = ["sad", "miserable", "depress", "upset", "unhappy", "sorrow", "deject", "regret", "down", "despair"]
anxious = ["anxious", "worry", "concern", "apprehen", "fear", "fret"]
blood = ["bleeding", "blood", "discharge", "red"]
irritated = ["irritated", "angry", "annoyed"]
tired = ["tired", "sleepy", "insomnia", "no sleep", "sleep"]
appetite = ["hungry", "food"]
negative = ["negative", "depressed", "hate"]
hopelessness = ["hopeless", "motivation", "unbother", "uncaring"]     ##we will use AI to add to this word bank
diagnosed = "no"
ppdcalender = 0

# --- Define your functions below! ---

# The chatbot introduces itself and gives the user instructions.
def intro():
    print("Hi, my name is Abigail. Let's talk!")

# Choose a response based on the user's input.
def process_input(answer):
    # Define a list of possible ways the user might say hello.
    greetings = ["hi", "hello", "hey", "hey there", "sup"]
    # Define a list of possible ways the user might say bye.
    farewells = ["bye", "see ya", "goodbye", "quit", "exit", "bye bye"]

    if is_valid_input(answer, farewells):
        say_goodbye()
        return True # The user wants to exit!
    else:
        say_greeting()

# Display a greeting message to the user.
def say_greeting():
  print("Hey there!")

# Display a farewell message to the user.
def say_goodbye():
  print("See you next time!")

# Display a default message to the user.
#def say_default():
  #print("That's cool!")

# Check if user_input matches one of the elements
#  in valid_responses.
def is_valid_input(user_input, valid_responses):
  for item in valid_responses:
    if user_input == item:
      # If you find a matching response, the input is
      #  valid for this kind of response.
      return True
  # If you didn't find a matching response, after
  #  going through the entire list, the input
  #  isn't valid for this kind of response.
  return False

# --- Put your main program below! ---
def main():
    global diagnosed

    intro()
    def text():
        file = open("diary.txt", "w")
        file.truncate()
        diary = input("Please input your diary entry for today >>>")
        file.write(diary)
        file.close()

    def ppdchecker():
        ppd = [sad, irritated, tired, appetite, negative, hopelessness, anxious]

        def ppdcheck():
            questions = ["do you feel more sad then usual >>>", "do you feel irritated easily >>>", "are you experiencing insomnia >>>", "have you experienced loss of appitite >>>", "have you noticed a dip in your mood lately >>>"]
            yes = 0
            for i in range(0,5):
                question = input(questions[i])
                if question == "yes":
                    yes = yes+1
            if yes > 2:
                print("""You may have post partum depression, here are some links to read and raise awareness. We will moniter this and if the trend continues reccomend you to a doctor

                """)
                found = True
                return found
            else:
                print("After further questioning you do not seem at risk of post partum depression")
        ppdcount=0
        for i in range(len(ppd)):
            word1 = ppd[i]
            with open(r'diary.txt', 'r') as f:
                content = f.read()
                for word in word1:
                    occurences = content.count(word)
                    ppdcount = ppdcount + occurences
        if ppdcount > 5:
            print("""Some of the things you have written have indicated possible post partum depression.
        Please can you answer some more questions to further explore this""")
            return ppdcheck()

    add=0
    found = False
    go = "yes"
    text()
    while go != "no" and diagnosed == "no" :
        found = ppdchecker()
        if found == True:
            add = add+1
            found = False
        if add > 2:   ##for purpose of demo this is only twice normally it would be more
            print("""We have noticed consistant symptoms with post partum depression, we advice you go talk to (here we would link to reccomended doctors

    """)
            diagnosed = input("Have you been to see a doctor about post partum depression? If yes we will stop checking for this issue >>>")
            add = 0
    ##        ###add algorithm to find contact details for relevant doctors

        go = input("Would u like to add another entry? >>>")
        if go == "yes":
            text()

    if diagnosed != "no":
        print("You have seen a doctor about this issue so we will no longer check for it, this prototype focuses on diagnoses of post partum depression so cannot check for any other issues, thank you for testing! We will now monitor this issue and see if it improves in two months")
    else:
        print("Thank you for using our app, this prototype focuses on diagnoses of post partum depression so cannot check for any other issues, thank you for testing!")

    done = False # Use this to keep track of when the user wants to exit.

    while not done:
        answer = input("Goodbye :)")
        done = process_input(answer)

# DON'T TOUCH! Setup code that runs your main() function.
if __name__ == "__main__":
  main()


# -*- coding:utf-8 -*-
import sys
import numpy as np
import queue

def solve():
    N, M = list(map(int, sys.stdin.readline().split()))
    meiro = []
    for i in range(N):
        line = list(input())
        meiro.append(line)
    meiro = np.array(meiro)

    # 各点までの最短距離の配列
    d = [[float("inf") for _ in range(M)] for __ in range(N)]  # 初期値はINF

    # 移動4方向のベクトル
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    # スタート地点とゴール地点の座標を取得する
    for y in range(M):
        for x in range(N):
            if meiro[y][x] == "S": sy, sx = y, x
            if meiro[y][x] == "G": gy, gx = y, x

    def bfs():
        """(sx, sy)から(gx, gy)への最短路を求める
        たどり着けないとINF
        """
        que = queue.Queue()
        que.put((sy, sx))  # スタート地点をキューに入れる
        d[sy][sx] = 0      # スタート地点の距離は0

        # キューが空になるまで幅優先探索でループする
        while not que.empty():
            # キューの先頭を取り出す
            y, x = que.get()

            # 取り出した地点がゴール地点なら探索をやめる
            if y == gy and x == gx: break

            # 移動4方向をループ
            for i in range(4):
                # 移動した後の点をnx, ny とする
                ny, nx = y + dy[i], x + dx[i]

                # 移動が可能かの判定と、すでに訪れたことがあるかの判定（d[ny][nx] != INFなら訪れたことある）
                if 0 <= ny < M and 0 <= nx < N and meiro[ny][nx] != "#" and d[ny][nx] == float("inf"):
                    # 移動できるならキューに入れ、その点の距離を(x,y)からの距離+1で確定する
                    que.put((ny, nx))
                    d[ny][nx] = d[y][x] + 1
        return d[gy][gx]

    ans = bfs()
    print(ans)

if __name__ == "__main__":
    solve()


#!/usr/bin/env python3

# Create a SSH connection
import paramiko
import os

import pprint
pp = pprint.PrettyPrinter(indent=4)

ssh = paramiko.SSHClient()
ssh._policy = paramiko.WarningPolicy()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh_config = paramiko.SSHConfig()
user_config_file = os.path.expanduser("~/.ssh/config")
if os.path.exists(user_config_file):
    with open(user_config_file) as f:
        ssh_config.parse(f)

cfg = {'hostname': 'dr-gfs00702.svale.netledger.com'}

user_config = ssh_config.lookup(cfg['hostname'])

cfg["hostname"] = user_config["hostname"]
cfg["username"] = user_config["user"]

if 'identityfile' in user_config:
    cfg['key_filename'] = user_config['identityfile']
#key=paramiko.RSAKey.from_private_key_file(pkey)
#cfg["pkey"] = key

if 'proxycommand' in user_config:
   cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])

ssh.connect(**cfg)
stdin, stdout, stderr = ssh.exec_command("ls -al")

for out_line in stdout.readlines():
        pp.pprint(out_line)

for err_line in stderr.readlines():
        pp.pprint(err_line)

ssh.close()


import argparse
import scipy
from scipy import ndimage
import cv2
import numpy as np
import sys
from collections import OrderedDict
import os

import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.models as models
import torch.nn.functional as F
from torch.utils import data, model_zoo

from model.deeplabv2 import Res_Deeplab
from data import get_data_path, get_loader
import torchvision.transforms as transform

from PIL import Image
import scipy.misc
from utils.loss import CrossEntropy2d

IMG_MEAN = np.array((104.00698793,116.66876762,122.67891434), dtype=np.float32)

MODEL = 'deeplabv2' # deeeplabv2, deeplabv3p

def get_arguments():
    """Parse all the arguments provided from the CLI.

    Returns:
      A list of parsed arguments.
    """
    parser = argparse.ArgumentParser(description="UDA evaluation script")
    parser.add_argument("-m","--model-path", type=str, default=None, required=True,
                        help="Model to evaluate")
    parser.add_argument("--gpu", type=int, default=(0,),
                        help="choose gpu device.")
    parser.add_argument("--save-output-images", action="store_true",
                        help="save output images")
    return parser.parse_args()

class VOCColorize(object):
    def __init__(self, n=22):
        self.cmap = color_map(22)
        self.cmap = torch.from_numpy(self.cmap[:n])

    def __call__(self, gray_image):
        size = gray_image.shape
        color_image = np.zeros((3, size[0], size[1]), dtype=np.uint8)

        for label in range(0, len(self.cmap)):
            mask = (label == gray_image)
            color_image[0][mask] = self.cmap[label][0]
            color_image[1][mask] = self.cmap[label][1]
            color_image[2][mask] = self.cmap[label][2]

        # handle void
        mask = (255 == gray_image)
        color_image[0][mask] = color_image[1][mask] = color_image[2][mask] = 255

        return color_image

def color_map(N=256, normalized=False):
    def bitget(byteval, idx):
        return ((byteval & (1 << idx)) != 0)

    dtype = 'float32' if normalized else 'uint8'
    cmap = np.zeros((N, 3), dtype=dtype)
    for i in range(N):
        r = g = b = 0
        c = i
        for j in range(8):
            r = r | (bitget(c, 0) << 7-j)
            g = g | (bitget(c, 1) << 7-j)
            b = b | (bitget(c, 2) << 7-j)
            c = c >> 3

        cmap[i] = np.array([r, g, b])

    cmap = cmap/255 if normalized else cmap
    return cmap

def get_label_vector(target, nclass):
    # target is a 3D Variable BxHxW, output is 2D BxnClass
    hist, _ = np.histogram(target, bins=nclass, range=(0, nclass-1))
    vect = hist>0
    vect_out = np.zeros((21,1))
    for i in range(len(vect)):
        if vect[i] == True:
            vect_out[i] = 1
        else:
            vect_out[i] = 0

    return vect_out

def get_iou(data_list, class_num, dataset, save_path=None):
    from multiprocessing import Pool
    from utils.metric import ConfusionMatrix

    ConfM = ConfusionMatrix(class_num)
    f = ConfM.generateM
    pool = Pool()
    m_list = pool.map(f, data_list)
    pool.close()
    pool.join()

    for m in m_list:
        ConfM.addM(m)

    aveJ, j_list, M = ConfM.jaccard()

    classes = np.array(("road", "sidewalk",
        "building", "wall", "fence", "pole",
        "traffic_light", "traffic_sign", "vegetation",
        "terrain", "sky", "person", "rider",
        "car", "truck", "bus",
        "train", "motorcycle", "bicycle"))

    for i, iou in enumerate(j_list):
        print('class {:2d} {:12} IU {:.2f}'.format(i, classes[i], 100*j_list[i]))

    print('meanIOU: ' + str(aveJ) + '\n')
    if save_path:
        with open(save_path, 'w') as f:
            for i, iou in enumerate(j_list):
                f.write('class {:2d} {:12} IU {:.2f}'.format(i, classes[i], 100*j_list[i]) + '\n')
            f.write('meanIOU: ' + str(aveJ) + '\n')
    return aveJ

def evaluate(model, dataset, ignore_label=250, save_output_images=False, save_dir=None, input_size=(512,1024)):

    if dataset == 'cityscapes':
        num_classes = 19
        data_loader = get_loader('cityscapes')
        data_path = get_data_path('cityscapes')
        test_dataset = data_loader( data_path, img_size=input_size, img_mean = IMG_MEAN, is_transform=True, split='val')
        testloader = data.DataLoader(test_dataset, batch_size=1, shuffle=False, pin_memory=True)
        interp = nn.Upsample(size=input_size, mode='bilinear', align_corners=True)
        ignore_label = 250

    elif dataset == 'gta':
        num_classes = 19
        data_loader = get_loader('gta')
        data_path = get_data_path('gta')
        test_dataset = data_loader(data_path, list_path = './data/gta5_list/train.txt', img_size=(1280,720), mean=IMG_MEAN)
        testloader = data.DataLoader(test_dataset, batch_size=1, shuffle=True, pin_memory=True)
        interp = nn.Upsample(size=(720,1280), mode='bilinear', align_corners=True)
        ignore_label = 255

    print('Evaluating, found ' + str(len(testloader)) + ' images.')

    data_list = []
    colorize = VOCColorize()

    total_loss = []

    for index, batch in enumerate(testloader):
        image, label, size, name, _ = batch
        size = size[0]
        #if index > 500:
        #    break
        with torch.no_grad():
            output  = model(Variable(image).cuda())
            output = interp(output)

            label_cuda = Variable(label.long()).cuda()
            criterion = CrossEntropy2d(ignore_label=ignore_label).cuda()  # Ignore label ??
            loss = criterion(output, label_cuda)
            total_loss.append(loss.item())

            output = output.cpu().data[0].numpy()

            if dataset == 'cityscapes':
                gt = np.asarray(label[0].numpy(), dtype=np.int)
            elif dataset == 'gta':
                gt = np.asarray(label[0].numpy(), dtype=np.int)

            output = output.transpose(1,2,0)
            output = np.asarray(np.argmax(output, axis=2), dtype=np.int)

            data_list.append([gt.flatten(), output.flatten()])

        if (index+1) % 100 == 0:
            print('%d processed'%(index+1))

    if save_dir:
        filename = os.path.join(save_dir, 'result.txt')
    else:
        filename = None
    mIoU = get_iou(data_list, num_classes, dataset, filename)
    loss = np.mean(total_loss)
    return mIoU, loss

def main():
    """Create the model and start the evaluation process."""

    gpu0 = args.gpu

    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    #model = torch.nn.DataParallel(Res_Deeplab(num_classes=num_classes), device_ids=args.gpu)
    model = Res_Deeplab(num_classes=num_classes)

    checkpoint = torch.load(args.model_path)
    try:
        model.load_state_dict(checkpoint['model'])
    except:
        model = torch.nn.DataParallel(model, device_ids=args.gpu)
        model.load_state_dict(checkpoint['model'])

    model.cuda()
    model.eval()

    evaluate(model, dataset, ignore_label=ignore_label, save_output_images=args.save_output_images, save_dir=save_dir, input_size=input_size)

if __name__ == '__main__':
    args = get_arguments()

    config = torch.load(args.model_path)['config']

    dataset = config['dataset']
    #dataset = 'cityscapes'
    if dataset == 'cityscapes':
        num_classes = 19
        input_size = (512,1024)
    if dataset == 'gta':
        num_classes = 19
        input_size = (1280,720)

    ignore_label = config['ignore_label']
    save_dir = os.path.join(*args.model_path.split('/')[:-1])

    main()


# Recebendo a data informada pelo usuário
dia = int(input("Digite o dia: "))
mes = int(input("Digite o mês: "))
ano = int(input("Digite o ano: "))

# Definindo uma variável booleana para armazenar se a data é válida ou não
data_valida = True

if mes < 1 or mes > 12:
    datvalida = False
elif mes == 2:
    if ano % 4 == 0 and (ano % 100 != 0 or ano % 400 == 0): #verifica se o ano é bissexto
        if dia < 1 or dia > 29:
            datvalida = False
    else:  #se caso não for bissexto
        if dia < 1 or dia > 28:
            datvalida = False
elif mes in (4, 6, 9, 11):  #os meses com 30 dias
    if dia < 1 or dia > 30:
        datvalida = False
else:  #os meses com 31 dias
    if dia < 1 or dia > 31:
        datvalida = False

if datvalida:
    print("Data válida: {}/{}/{}".format(dia, mes, ano))
else:
    print("Data inválida!")


import math
import os
import sys

def main():

    total_ribbon = 0

    for row in open(os.path.join(sys.path[0], 'input'), 'r'):
        present = Present([int(number) for number in row.strip().split('x')])

        total_ribbon += present.measure_ribbon()

    print(total_ribbon)

class Present:
    edges: [[int]]
    areas: [[int]]

    def __init__(self, edges):
        self.edges = sorted(edges)
        self.areas = sorted([edges[0] * edges[1], edges[0] * edges[2], edges[1] * edges[2]])
        self.volume = math.prod(edges)

    def measure_wrapping_paper(self) -> int:
        wrapping_paper = 0
        smallest_side = None

        for area in self.areas:
            wrapping_paper += area * 2

            if smallest_side is None or smallest_side > area:
                smallest_side = area

        wrapping_paper += smallest_side

        return wrapping_paper

    def measure_ribbon(self) -> int:
        return self.edges[0] * 2 + self.edges[1] * 2 + self.volume

if __name__ == "__main__":
    main()


def main():
    grolist = []
    while True:
        try:
            item = input().strip().lower()
            grolist.append(item)
        except (EOFError, KeyError):
            l = sorted(set(grolist))
            for i in l:
                print(f"{grolist.count(i)} {i.upper()}")
            quit()

main()