# -- Format transcriptions + translation into English (if necessary)
from   googletrans import Translator
import pandas as pd
import itertools
import spacy
import json
import re
import os

BASE_DIR  = '/home/runner/work/Castena/Castena'
TRANSLATE = False

list_original_transcriptions   = [file for file in os.listdir(BASE_DIR + '/data/original_spanish_transcriptions/') if '.txt' in file]
list_translated_transcriptions = [file for file in os.listdir(BASE_DIR + '/data/translated_transcriptions/') if '.txt' in file]

translator = Translator(service_urls=['translate.googleapis.com'])
nlp = spacy.load('es_core_news_sm')

# -- Define auxiliar functions
def translate_text(text, target_lang='en'):
    # Tokenize text and find proper nouns (omit translation in these cases)
    doc = nlp(text)
    named_entities = [ent.text for ent in doc if ent.pos_ == 'PROPN' and ent.dep_ in ['NNP', 'NN']]
    named_entities_list = []
    # Replace proper nouns for temporal __identifier__
    for entity in named_entities:
        text = text.replace(entity, f'__{entity}__')
        named_entities_list.append(entity)

    translated_text = translator.translate(text, dest=target_lang).text
    final_translated_text = []

    i = 0
    for text in translated_text.split(' '):
      if '__' in text and len(named_entities_list):
        final_translated_text.append(named_entities_list[i])
        i+=1
      else:
        final_translated_text.append(text)
    return ' '.join(final_translated_text)

def capitalize_proper_nouns(text):
    # Text analysis with SpaCy
    doc = nlp(text)

    modified_text = []

    for token in doc:
        if token.pos_ not in ["PROPN", "NOUN"]:
            # Si es un nombre propio y ya está en mayúscula, conservarlo
            modified_text.append(token.text)
        else:
            # De lo contrario, capitalizar la primera letra
            modified_text.append(token.text.capitalize())

    modified_text = " ".join(modified_text)

    # Correct punctuation signs
    modified_text = modified_text.replace(" .. ", "...")\
                                 .replace(" , ", ", ")\
                                 .replace(" . ", ". ")\
                                 .replace(" .... ", "...")\
                                 .replace(" ... ", "...")\
                                 .replace(",¿", " ¿")\
                                 .replace(",.", ",")\
                                 .replace("?.", "? ")
    return modified_text

# -- For loop to format every original transcription (if not already processed)
for original_transcription in list_original_transcriptions:
	if original_transcription not in list_translated_transcriptions:
		transcription_df = pd.read_table(BASE_DIR + '/data/original_spanish_transcriptions/' + original_transcription, sep='|', header=None)
		transcription_df.rename(columns={0: 'time', 1: 'speaker', 2: 'transcript'}, inplace=True)

		transcription_df['time'] = pd.to_timedelta(transcription_df['time'])
		transcription_df['speaker_change'] = transcription_df['speaker'] != transcription_df['speaker'].shift()

		result = transcription_df.groupby(['speaker', transcription_df['speaker_change'].cumsum()]).agg({\
	                                                                               'time': ['min', 'max'],
	                                                                               'transcript': lambda x: '.'.join(x)
	                                                                               })
		result.columns = result.columns.droplevel()
		result.columns = ['min_time', 'max_time', 'transcript']
		result.reset_index(inplace=True)
		result['min_time'] = result['min_time'].apply(lambda x: str(x).replace('0 days ', ''))
		result['max_time'] = result['max_time'].apply(lambda x: str(x).replace('0 days ', ''))

		# -- Preprocess transcript
		result['transcript'] = result['transcript'].apply(capitalize_proper_nouns)

		result['literal_transcript'] = 'Desde el instante ' + result['min_time'] + ' hasta ' + result['max_time'] +\
						' ' + result['speaker'] + ' dice: \"' + result['transcript'] + '\"'
		if TRANSLATE:
			result['literal_transcript'] = result['literal_transcript'].apply(translate_text)

		result = result.sort_values('min_time')
		result_text = '\n\n'.join(result['literal_transcript'])

		# -- Save text as .txt file
		with open(BASE_DIR + '/data/translated_transcriptions/' + original_transcription, 'w') as f:
			f.write(result_text)

print("Processing finished successfully!")


from time import sleep
from onvif import ONVIFCamera
import zeep

class MoverCamSimple:

    def __init__(self):
        self.XMAX = 1
        self.XMIN = -1
        self.YMAX = 1
        self.YMIN = -1
        self.IP = '192.168.78.90'
        self.USER = 'admin'
        self.PASS = 'Admin321'
        self.PORT_PROTOCOL = 554

    def zeep_pythonvalue(self, xmlvalue):
        return xmlvalue

    def moves(self):
        mycam = ONVIFCamera(self.IP, 80, self.USER, self.PASS)
        media = mycam.create_media_service()
        # Create ptz service object
        self.ptz = mycam.create_ptz_service()

        # Get target profile
        zeep.xsd.simple.AnySimpleType.pythonvalue = self.zeep_pythonvalue
        media_profile = media.GetProfiles()[0]

        # Get PTZ configuration options for getting continuous move range
        self.request = self.ptz.create_type('GetConfigurationOptions')
        self.request.ConfigurationToken = media_profile.PTZConfiguration.token
        ptz_configuration_options = self.ptz.GetConfigurationOptions(self.request)

        self.request = self.ptz.create_type('ContinuousMove')
        self.request.ProfileToken = media_profile.token
        self.ptz.Stop({'ProfileToken': media_profile.token})

        if self.request.Velocity is None:
            self.request.Velocity = self.ptz.GetStatus({'ProfileToken': media_profile.token}).Position
            self.request.Velocity = self.ptz.GetStatus({'ProfileToken': media_profile.token}).Position
            self.request.Velocity.PanTilt.space = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].URI
            self.request.Velocity.Zoom.space = ptz_configuration_options.Spaces.ContinuousZoomVelocitySpace[0].URI

        # Get range of pan and tilt
        # NOTE: X and Y are velocity vector
        #global XMAX, XMIN, YMAX, YMIN
        self.XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Max
        self.XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Min
        self.YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Max
        self.YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Min

    def perform_move(self,timeout):
        # Start continuous move
        self.ptz.ContinuousMove(self.request)
        # Wait a certain time
        sleep(timeout)
        # Stop continuous move
        self.ptz.Stop({'ProfileToken': self.request.ProfileToken})

    def move_up(self,timeout=1):
        print('move up...')
        self.request.Velocity.PanTilt.x = 0
        self.request.Velocity.PanTilt.y = self.YMAX
        self.perform_move(self.ptz, self.request,timeout)

    def move_down(self,timeout=1):
        print('move down...')
        self.request.Velocity.PanTilt.x = 0
        self.request.Velocity.PanTilt.y = self.YMIN
        self.perform_move(self.ptz, self.request,timeout)

    def move_right(self,timeout=1):
        print('move right...')
        self.request.Velocity.PanTilt.x = self.XMAX
        self.request.Velocity.PanTilt.y = 0
        self.perform_move(self.ptz, self.request,timeout)

    def move_left(self,timeout=1):
        print('move left...')
        self.request.Velocity.PanTilt.x = self.XMIN
        self.request.Velocity.PanTilt.y = 0
        self.perform_move(self.ptz, self.request,timeout)

    def zoom_up(self,timeout=1):
        print('zoom up')
        self.request.Velocity.Zoom.x = 1
        self.request.Velocity.PanTilt.x = 0
        self.request.Velocity.PanTilt.y = 0
        self.perform_move(self.ptz, self.request,timeout)

    def zoom_down(self,timeout=1):
        print('zoom down')
        self.request.Velocity.Zoom.x = -1
        self.request.Velocity.PanTilt.x = 0
        self.request.Velocity.PanTilt.y = 0
        self.perform_move(self.ptz, self.request,timeout)

    # VER MOVIMIENTO

    # Create media service object

if __name__=='__main__':
    ob = MoverCamSimple()
    ob.moves()
    ob.move_up(5)


from copy import copy

DEBUG = False

def debugPrint(s):
    if DEBUG:
        print(s)

with open("input.txt", "r") as f:
    # There's only one line for this input
    line = f.readline().strip('\n')
    vals = [int(v) for v in line.split(',')]

#memory = [1002, 4, 3, 4, 33]
#memory = [3,9,8,9,10,9,4,9,99,-1,8]
#memory = [3,9,7,9,10,9,4,9,99,-1,8]
#memory = [3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]
#memory = [3,3,1105,-1,9,1101,0,0,12,4,12,99,1]
#memory = [3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]

#memory = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]
#vals = [1102,34915192,34915192,7,4,7,99,0]
#vals = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]
#vals = [104,1125899906842624,99]

memory = {i: v for i, v in enumerate(vals)}

def readMemory(pos):
    try:
        return memory[pos]
    except KeyError:
        debugPrint(f"{pos} not in memory, initializing with 0.")
        memory[pos] = 0
        return 0

# Applying problem modifications
halt = False
ptr = 0 # Start at the beginning, duh
relative_base = 0
while not halt:
    instruction = str(readMemory(ptr))
    opcode = int(instruction[-2:])
    mode = instruction[-3::-1]
    # Append leading 0s to mode
    debugPrint(mode)
    mode += ("0" * (3 - len(mode)))
    debugPrint(f"MEM[{ptr}]: [{opcode}] / [{mode}]")

    if opcode in [1, 2, 5, 6, 7, 8]:
        operators = []
        debugPrint(mode)
        if mode[0] == '0': # Position
            # Use value as address
            operators.append(readMemory(readMemory(ptr+1)))
        elif mode[0] == '1': # Immediate mode
            operators.append(readMemory(ptr+1))
        elif mode[0] == '2': # Relative mode
            operators.append(readMemory(readMemory(ptr+1) + relative_base))
        else:
            debugPrint("Unrecognized mode for first operand.")

        if mode[1] == '0':
            operators.append(readMemory(readMemory(ptr+2)))
        elif mode[1] == '1':
            operators.append(readMemory(ptr+2))
        elif mode[1] == '2':
            operators.append(readMemory(readMemory(ptr+2) + relative_base))
        else:
            debugPrint("Unrecognized mode for second operand.")

        if mode[2] == '0':
            operators.append(readMemory(ptr+3))
        elif mode[2] == '2':
            operators.append(readMemory(ptr+3) + relative_base)

        if opcode == 1:
            debugPrint(f"[1]: {operators[0]} + {operators[1]} to MEM[{operators[2]}]")
            memory[operators[2]] = operators[0] + operators[1]
        elif opcode == 2:
            debugPrint(f"[2]: {operators[0]} * {operators[1]} to MEM[{operators[2]}]")
            memory[operators[2]] = operators[0] * operators[1]

        # jump-if-true
        elif opcode == 5:
            debugPrint(f"[5]: {operators[0]} != 0, jump to {operators[1]}")
            if operators[0] != 0:
                ptr = operators[1]
                continue # Don't increment ptr

        # jump-if-false
        elif opcode == 6:
            debugPrint(f"[6]: {operators[0]} == 0, jump to {operators[1]}")
            if operators[0] == 0:
                ptr = operators[1]
                continue # Don't increment ptr

        # less than
        elif opcode == 7:
            debugPrint(f"[7]: {operators[0]} < {operators[1]} to MEM[{operators[2]}]")
            if operators[0] < operators[1]:
                memory[operators[2]] = 1
            else:
                memory[operators[2]] = 0

        # equals
        elif opcode == 8:
            debugPrint(f"[8]: {operators[0]} == {operators[1]} to MEM[{operators[2]}]")
            if operators[0] == operators[1]:
                memory[operators[2]] = 1
            else:
                memory[operators[2]] = 0

    elif opcode == 3: # Save it to address
        if mode[0] == '0': # Position
            # Use value as address
            operator = readMemory(readMemory(ptr+1))
        elif mode[0] == '1': # Immediate mode
            operator = readMemory(ptr+1)
        elif mode[0] == '2': # Relative mode
            operator = readMemory(ptr+1) + relative_base
        else:
            debugPrint("Unrecognized mode for first operand.")

        debugPrint(f"[3]: Will save input at {operator}")
        input_v = input("Input: ")
        memory[operator] = int(input_v)
    elif opcode == 4:
        if mode[0] == '0': # Position
            # Use value as address
            debugPrint("[4] Position mode")
            output = readMemory(readMemory(ptr+1))
        elif mode[0] == '1': # Immediate mode
            debugPrint("[4] Immediate mode")
            output = readMemory(ptr+1)
        elif mode[0] == '2': # Relative mode
            debugPrint("[4] Relative mode")
            output = readMemory(readMemory(ptr+1) + relative_base)
        else:
            debugPrint("Unrecognized mode for first operand.")

        print(f"###: {output}")
    elif opcode == 9:
        if mode[0] == '0': # Position
            # Use value as address
            debugPrint("[9] Position mode")
            operator = readMemory(readMemory(ptr+1))
        elif mode[0] == '1': # Immediate mode
            debugPrint("[9] Immediate mode")
            operator = readMemory(ptr+1)
        elif mode[0] == '2': # Relative mode
            debugPrint("[9] Relative mode")
            operator = readMemory(readMemory(ptr+1) + relative_base)
        else:
            debugPrint("Unrecognized mode for first operand.")

        debugPrint(f"[9]: Setting relative base to {operator}.")
        relative_base += operator

    elif opcode == 99:
        halt = True
    if opcode == 3 or opcode == 4 or opcode == 9:
        ptr += 2
    elif opcode == 5 or opcode == 6:
        ptr += 3
    elif opcode == 1 or opcode == 2 or opcode == 7 or opcode == 8:
        ptr += 4


import os
import sys
import time
import argparse

import numpy as np

import matplotlib
matplotlib.use('Agg')

from coffea.util import load

from multiprocessing import Pool

from pocket_coffea.utils.configurator import Configurator
from pocket_coffea.utils.plot_utils import PlotManager
from pocket_coffea.parameters.plotting import style_cfg

def slice_accumulator(accumulator, entrystart, entrystop):
    '''Returns an accumulator containing only a reduced set of histograms, i.e. those between the positions `entrystart` and `entrystop`.'''
    _accumulator = dict([(key, value) for key, value in accumulator.items()])
    _accumulator['variables'] = dict(
        [(key, value) for key, value in accumulator['variables'].items()][
            entrystart:entrystop
        ]
    )
    return _accumulator

parser = argparse.ArgumentParser(description='Plot histograms from coffea file')
parser.add_argument('--cfg', default=os.getcwd() + "/config/test.json", help='Config file with parameters specific to the current run', required=False)
parser.add_argument("-i", "--inputfile", required=True, type=str, help="Input file")
parser.add_argument('--plot_dir', default=None, help='Sub-directory inside the plots folder to save plots', required=False)
parser.add_argument('-v', '--version', type=str, default=None, help='Version of output (e.g. `v01`, `v02`, etc.)')
parser.add_argument('-j', '--workers', type=int, default=8, help='Number of parallel workers to use for plotting')
parser.add_argument('-o', '--only', type=str, default='', help='Filter histograms name with string', required=False)
parser.add_argument('-oc', '--only_cat', type=str, default=[''], nargs="+", help='Filter categories with string', required=False)
parser.add_argument('-os', '--only_syst', type=str, nargs="+", default='', help='Filter systematics with a list of strings', required=False)
parser.add_argument('-e', '--exclude', type=str, default=None, help='Exclude categories with string', required=False)
parser.add_argument('--split_systematics', action='store_true', help='Split systematic uncertainties in the ratio plot')
parser.add_argument('--partial_unc_band', action='store_true', help='Plot only the partial uncertainty band corresponding to the systematics specified as the argument `only_syst`')
parser.add_argument('--overwrite', action='store_true', help='Overwrite plots in output folder')
parser.add_argument('--log', action='store_true', help='Set y-axis scale to log')
parser.add_argument('--density', action='store_true', help='Set density parameter to have a normalized plot')
parser.add_argument('-d', '--data_key', type=str, default='DATA', help='Prefix for data samples', required=False)

args = parser.parse_args()
config = Configurator(args.cfg, plot=True, plot_version=args.version)

print("Starting ", end='')
print(time.ctime())
start = time.time()

if os.path.isfile( args.inputfile ): accumulator = load(args.inputfile)
else: sys.exit(f"Input file '{args.inputfile}' does not exist")

if args.plot_dir:
    plot_dir_parent = os.path.dirname(config.plots)
    config.plots = os.path.join(plot_dir_parent, args.plot_dir)

if not args.overwrite:
    if os.path.exists(config.plots):
        raise Exception(f"The output folder '{config.plots}' already exists. Please choose another output folder or run with the option `--overwrite`.")

if not os.path.exists(config.plots):
    os.makedirs(config.plots)

def make_plots(entrystart, entrystop):
    '''Function that instantiates multiple PlotManager objects each managing a different subset of histograms.'''
    _accumulator = slice_accumulator(accumulator, entrystart, entrystop)
    plotter = PlotManager(
        hist_cfg=_accumulator['variables'],
        plot_dir=config.plots,
        style_cfg=style_cfg,
        only_cat=args.only_cat,
        data_key=args.data_key,
        log=args.log,
        density=args.density,
        save=True
    )
    plotter.plot_datamc_all(syst=True, spliteras=False)

# Filter dictionary of histograms with `args.only`
accumulator['variables'] = { k : v for k,v in accumulator['variables'].items() if args.only in k }
if args.exclude:
    accumulator['variables'] = { k : v for k,v in accumulator['variables'].items() if not args.exclude in k }
HistsToPlot = list(accumulator['variables'].keys())

NtotHists = len(HistsToPlot)
NHistsToPlot = len([key for key in HistsToPlot if args.only in key])
print("# tot histograms = ", NtotHists)
print("# histograms to plot = ", NHistsToPlot)
print("Histograms to plot:", HistsToPlot)

# Parallelization of plotting
delimiters = np.linspace(0, NtotHists, args.workers + 1).astype(int)
chunks = [(delimiters[i], delimiters[i+1]) for i in range(len(delimiters[:-1]))]
pool = Pool()
# Parallel calls of make_plots on different subsets of histograms
pool.starmap(make_plots, chunks)
pool.close()

end = time.time()
runTime = round(end-start)
print("Finishing ", end='')
print(time.ctime())
print(f"Drawn {NHistsToPlot} plots in {runTime} s")


def menu():
    print("\033[1;34m","=-"*10,"Escolha a opção desejada", "-="*10)
    print("\033[0;32m","""
                      Cadastro de Produtos.[1]
                      Alterar Produtos.....[2]
                      Excluir Produtos.....[3]
                      Venda de Produtos....[4]
                      Compra de Produtos...[5]
                      Colsultar estoque....[6]
                      Sair do programa.....[0]
""")
    print("\033[1;34m","=-"*9, "Por favor digite um numero", "-="*10)
    a = (input("Digite um dos numeros para acessar as funcionalidades do programa: "))
    return(a)
def print2():
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
def cadastro():
    import os
    os.system('cls')
    print("""                        Escolha sua opção
                   ===========================""")
    print2()
    print("\033[1;36m","                  Continuar..[1]")
    print("\033[1;31m" ,"                  Voltar.....[2]")
    print("\033[1;34m")
    a = input("                   Digite a opção desejada: ")
    print("\033[0;32m")
    return(a)
def selecao():
    ca = cadastro()
    while not ca.isdigit():
        ca = cadastro()
    cad = int(ca)
    return (cad)

def tempo(x):
    import time
    time.sleep(1)
    print(x)


'''
Write a function called sum_pairs which accepts a list and a number and returns the first pair of numbers that sum to the number passed
to the function.

sum_pairs([4,2,10,5,1], 6) # [4,2]
sum_pairs([11,20,4,2,1,5], 100) # []
'''

def sum_pairs(nums, sum):
    result = []
    for (i, x) in enumerate(nums):
        for (j, y) in enumerate(nums):
            if i == j:
                break
            elif sum == x + y:
                result.append(y)
                result.append(x)
                return result
    return result

print(sum_pairs([4,2,10,5,1], 6)) # [4,2]
print(sum_pairs([11,20,4,2,1,5], 100)) # []


from fastapi import APIRouter, Depends, status

from src.core.cottages.exceptions import NoCottageWithThisId, NoPermission
from src.core.cottages.schemas import CottageCreate, CottageRead, CottageUpdate
from src.core.cottages.services import CottageService, get_cottage_service
from src.core.users.dependencies import current_user
from src.core.users.models import User
from src.core.utils.models import ErrorModel

def get_create_list_router() -> APIRouter:
    router = APIRouter(prefix="/cottages")

    @router.post(
        "",
        status_code=status.HTTP_201_CREATED,
        response_model=CottageCreate,
        responses={
            status.HTTP_401_UNAUTHORIZED: {
                "content": {
                    "application/json": {
                        "examples": {
                            "Unauthorized": {
                                "summary": "No token",
                                "value": {
                                    "detail": "Unauthorized"
                                }
                            }
                        }
                    }
                }
            },
        },
    )
    async def create_cottage(
            cottage_create: CottageCreate,
            cottage_service: CottageService = Depends(get_cottage_service),
            user: User = Depends(current_user)
    ):
        cottage = await cottage_service.create(user.id, cottage_create)
        return cottage

    @router.get(
        "",
        status_code=status.HTTP_200_OK,
        response_model=list[CottageRead]
    )
    async def get_cottages(
            cottage_service: CottageService = Depends(get_cottage_service),
    ):
        cottages = await cottage_service.get_all()
        return cottages

    @router.get(
        "/{cottage_id}",
        status_code=status.HTTP_200_OK,
        response_model=CottageRead,
        responses={
            status.HTTP_400_BAD_REQUEST: {
                "content": {
                    "application/json": {
                        "examples": {
                            NoCottageWithThisId.detail: {
                                "summary": "No cottage with this id",
                                "value": {
                                    "detail": NoCottageWithThisId.detail
                                }
                            }
                        }
                    }
                }
            },
        }
    )
    async def get_cottage_by_id(
            cottage_id: int,
            cottage_service: CottageService = Depends(get_cottage_service)
    ):
        cottage = await cottage_service.get_by_id(cottage_id)
        if cottage is None:
            raise NoCottageWithThisId
        return cottage

    @router.put(
        "/{cottage_id}",
        response_model=CottageCreate,
        responses={
            status.HTTP_400_BAD_REQUEST: {
                "content": {
                    "application/json": {
                        "examples": {
                            NoCottageWithThisId.detail: {
                                "summary": "No cottage with this id",
                                "value": {
                                    "detail": NoCottageWithThisId.detail
                                }
                            }
                        }
                    }
                }
            },
            status.HTTP_401_UNAUTHORIZED: {
                "content": {
                    "application/json": {
                        "examples": {
                            "Unauthorized": {
                                "summary": "No token",
                                "value": {
                                    "detail": "Unauthorized"
                                }
                            }
                        }
                    }
                }
            },
            status.HTTP_403_FORBIDDEN: {
                "content": {
                    "application/json": {
                        "examples": {
                            NoPermission.detail: {
                                "summary": "You don’t have permission to access.",
                                "value": {
                                    "detail": NoPermission.detail
                                }
                            }
                        }
                    }
                }
            }
        }
    )
    async def update_cottage(
            cottage_id: int,
            cottage_update: CottageUpdate,
            cottage_service: CottageService = Depends(get_cottage_service),
            user: User = Depends(current_user)
    ):
        current_cottage = await cottage_service.get_by_id(cottage_id)
        if current_cottage is None:
            raise NoCottageWithThisId
        elif current_cottage.owner != user.id:
            raise NoPermission
        cottage = await cottage_service.update(user.id, cottage_id, cottage_update)
        return cottage

    @router.delete(
        "/{cottage_id}",
        response_model=str,
        responses={
            status.HTTP_400_BAD_REQUEST: {
                "model": ErrorModel,
                "content": {
                    "application/json": {
                        "examples": {
                            NoCottageWithThisId.detail: {
                                "summary": "No cottage with this id",
                                "value": {
                                    "detail": NoCottageWithThisId.detail,
                                }
                            }
                        }
                    }
                }
            },
            status.HTTP_403_FORBIDDEN: {
                "model": ErrorModel,
                "content": {
                    "application/json": {
                        "examples": {
                            NoPermission.detail: {
                                "summary": "You don't have permission to access",
                                "value": {
                                    "detail": NoPermission.detail,
                                }
                            }
                        }
                    }
                }
            }
        }
    )
    async def delete_cottage(
            cottage_id: int,
            cottage_service: CottageService = Depends(get_cottage_service),
            user: User = Depends(current_user)
    ):
        current_cottage = await cottage_service.get_by_id(cottage_id)
        if current_cottage is None:
            raise NoCottageWithThisId
        elif current_cottage.owner != user.id:
            raise NoPermission
        result = await cottage_service.delete(user.id, cottage_id)
        return result

    return router


import toml
from pathlib import Path
from typing import Optional, Union, Iterable
import blobconverter
import shutil

from tensorflow.keras.applications.resnet import (
    ResNet50,
    ResNet101,
    ResNet152,
)

from tensorflow.keras.applications.resnet_v2 import (
    ResNet50V2,
    ResNet101V2,
    ResNet152V2,
)

from tensorflow.keras.applications.mobilenet import MobileNet

from tensorflow.keras.preprocessing import image_dataset_from_directory
from tensorflow.keras.metrics import (
    BinaryAccuracy,
    CategoricalAccuracy,
    Precision,
    Recall,
)
from tensorflow.keras.backend import epsilon
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.callbacks import EarlyStopping

from tensorflow.keras.models import load_model
import typer

import tensorflow as tf
from tensorflow.python.framework.convert_to_constants import (
    convert_variables_to_constants_v2,
)

import tensorflow as tf

from tensorflow.python.keras import backend as K

config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.InteractiveSession(config=config)
K.set_session(tf.compat.v1.Session(config=config))

tf.config.run_functions_eagerly(True)

import typer

MODEL_TYPES = {
    "ResNet50": ResNet50,
    "ResNet101": ResNet101,
    "ResNet152": ResNet152,
    "ResNet50V2": ResNet50V2,
    "ResNet101V2": ResNet101V2,
    "ResNet152V2": ResNet152V2,
    "MobileNet": MobileNet,
}

def F1(y_true, y_pred):
    prec_fun = Precision()
    rec_fun = Recall()

    precision = prec_fun(y_true, y_pred)
    recall = rec_fun(y_true, y_pred)

    return 2 * ((precision * recall) / (precision + recall + epsilon()))

class CNN:
    def __init__(
        self,
        model_path: Optional[Union[str, Path]] = None,
        base_model: Optional[str] = None,
    ):
        """Initialize a new CNN model.

        Parameters
        ----------
        model_path : Optional[Union[str, Path]]
            Path to model, by default None
            If it is `None`, a `ResNet50v2` with weights of `imagenet` is loaded.
        base_model : Optional[str], optional
            Base model to load weights on it, by default None.
            If it is `None`, a local saved model will be loaded using `model_path`.
        """
        if model_path is not None:
            self.load(model_path, base_model)
        else:
            self.load()

    def train(
        self,
        train_images_folder: Union[Path, str],
        val_images_folder: Union[Path, str],
        labels_names: Union[str, Iterable[str]] = "inferred",
        n_labels: Optional[int] = None,
        color_mode: str = "rgb",
        image_size: Iterable[int] = (256, 256),
        shuffle: bool = True,
        batch_size: int = 32,
        optimizer: str = "adam",
        epochs: int = 10,
        metrics: Iterable[str] = ("F1", "binary_accuracy", "precision", "recall"),
        early_stopping_metric: str = "val_F1",
        early_stopping_patience: str = 5,
        early_stopping_mode: str = "max",
    ):
        if n_labels is None:
            assert (
                not labels_names == "inferred"
            ), f"If labels are inferred `n_labels` must be passed."
            n_labels = len(labels_names)

        if n_labels > 2:
            label_mode = "int"
            loss_function = "sparse_categorical_crossentropy"
            self.MODEL.add(Dense(n_labels, activation="softmax"))
        else:
            label_mode = "binary"
            loss_function = "binary_crossentropy"
            self.MODEL.add(Dense(1, activation="sigmoid"))

        train_dataset = image_dataset_from_directory(
            train_images_folder,
            labels=labels_names,
            batch_size=batch_size,
            color_mode=color_mode,
            image_size=image_size,
            shuffle=shuffle,
            label_mode=label_mode,
        )

        validation_dataset = image_dataset_from_directory(
            val_images_folder,
            labels=labels_names,
            batch_size=batch_size,
            color_mode=color_mode,
            image_size=image_size,
            shuffle=shuffle,
            label_mode=label_mode,
        )

        metrics_list = []

        for m in metrics:
            if m == "binary_accuracy":
                if label_mode == "binary":
                    metrics_list.append(BinaryAccuracy())
                else:
                    metrics_list.append(CategoricalAccuracy())
            elif m == "precision":
                metrics_list.append(Precision())
            elif m == "recall":
                metrics_list.append(Recall())
            elif m == "F1":
                metrics_list.append(F1)

        self.MODEL.compile(
            optimizer=optimizer, loss=loss_function, metrics=metrics_list
        )

        early_stopping_monitor = EarlyStopping(
            monitor=early_stopping_metric,
            patience=early_stopping_patience,
            mode=early_stopping_mode,
            restore_best_weights=True,
        )

        self.MODEL.fit(
            train_dataset,
            validation_data=validation_dataset,
            epochs=epochs,
            callbacks=[early_stopping_monitor],
        )

    def save(self, model_path: Union[str, Path]):
        """Save the architecture and the weights of the model.

        Parameters
        ----------
        model_path : Union[str, Path]
            Path to the folder where the model will be saved.
        """

        self.MODEL.save(model_path)

    def load(
        self,
        model_path: Union[str, Path] = "imagenet",
        base_model: Optional[str] = "ResNet50v2",
    ):
        """Load the architecture and the weights of a model.

        Parameters
        ----------
        model_path : Union[str, Path]
            Path to the model saved.
        base_model : Optional[str], optional
            Base model to load weights on it, by default None.
            If it is `None`, a local saved model will be loaded using `model_path`.
        """

        if base_model is None:
            self.MODEL = load_model(model_path, custom_objects={"F1": F1})

        else:
            self.MODEL = Sequential()
            model = MODEL_TYPES[base_model](weights=model_path)
            self.MODEL.add(model)

    def to_pb(self, path_out_folder):
        # path of the directory where you want to save your model

        frozen_graph_filename = "frozen_graph"
        model = self.MODEL
        full_model = tf.function(lambda x: model(x))
        full_model = full_model.get_concrete_function(
            tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype)
        )  # Get frozen ConcreteFunction
        frozen_func = convert_variables_to_constants_v2(full_model)
        frozen_func.graph.as_graph_def()
        layers = [op.name for op in frozen_func.graph.get_operations()]
        print("-" * 60)
        print("Frozen model layers: ")

        for layer in layers:
            print(layer)

        print("-" * 60)
        print("Frozen model inputs: ")
        print(frozen_func.inputs)
        print("Frozen model outputs: ")
        print(frozen_func.outputs)  # Save frozen graph to disk
        tf.io.write_graph(
            graph_or_graph_def=frozen_func.graph,
            logdir=path_out_folder,
            name=f"{frozen_graph_filename}.pb",
            as_text=False,
        )

    def to_blob(self, path_out_folder):
        self.to_pb(path_out_folder)

        blob_path = blobconverter.from_tf(
            frozen_pb=f"{path_out_folder}/frozen_graph.pb",
            data_type="FP16",
            shaves=5,
            version = blobconverter.Versions.v2020_1,
            optimizer_params=[
                "--reverse_input_channels",
                "--input_shape=[1,224,224,3]",
            ],
        )

        shutil.move(blob_path, f"{path_out_folder}/depthai_model.blob")

def main(config_path: Optional[str] = "./CNN_stress/config.toml"):

    config_dict = toml.load(config_path)

    model = CNN(**config_dict["load"])
    model.train(**config_dict["training"])
    model.save(**config_dict["save"])
    model.load(config_dict["save"]["model_path"], base_model=None)

if __name__ == "__main__":
    typer.run(main)


import sys
import glob

import cv2
import numpy as np

from keras.applications.resnet50 import decode_predictions

import tensorflow as tf

# target model
output_model = "./models/output.tflite"
output_quant_model = "./models/output_quant.tflite"

# load validation set
image_folder = "../calibration"
img_path = glob.glob(image_folder+"/*")
if len(img_path)==0:
    print("image not found")
    sys.exit(1)

validation_data_set=[]
for file_name in img_path:
    img = cv2.imread(file_name) #BGR
    img = cv2.resize(img,(224, 224))
    ary = np.asarray(img, dtype=np.float32)
    ary = np.expand_dims(ary, axis=0)
    ary = ary/255.0
    validation_data_set.append(ary)

#verify Tensorflow lite
interpreter = tf.lite.Interpreter(model_path=output_model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

print("tf lite float")

for i in range(len(validation_data_set)):
    interpreter.set_tensor(input_details[0]['index'], validation_data_set[i])
    interpreter.invoke()
    preds_tf_lite = interpreter.get_tensor(output_details[0]['index'])
    print('Predicted:', decode_predictions(preds_tf_lite, top=3)[0])

#verify quantized tensorflow lite
interpreter = tf.lite.Interpreter(model_path=output_quant_model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

print("tf lite int8")

for i in range(len(validation_data_set)):
    data = validation_data_set[i]
    data = data*255
    data = data.astype(np.uint8)
    interpreter.set_tensor(input_details[0]['index'], data)
    interpreter.invoke()
    preds_tf_lite = interpreter.get_tensor(output_details[0]['index'])
    print('Predicted:', decode_predictions(preds_tf_lite, top=3)[0])


from gz.math7 import clamp

from sdformat13 import Pbr, PbrWorkflow, Material  # noqa: F401
import sdformat13 as sdf

import os

MATERIAL_NUMBER = 0

def add_material(geom, material):
    """
    Converts an SDFormat material to an MJCF material.

    :param mjcf.Element geom: The MJCF geom to add the material
    :param sdf.Material material: The SDF material to convert
    :return: The newly created MJCF material.
    :rtype: mjcf.Element
    """
    pbr = material.pbr_material()
    sp_color = material.specular()
    em_color = material.emissive()
    specular = (sp_color.r() + sp_color.g() + sp_color.b()) / 3.0
    emissive = (em_color.r() + em_color.g() + em_color.b()) / 3.0
    asset = geom.root.asset
    r_mat = None
    if pbr is not None:
        workflow = pbr.workflow(sdf.PbrWorkflowType.METAL)
        if workflow is not None:
            if workflow.albedo_map():
                f_without_extension, extension = os.path.splitext(
                    os.path.basename(workflow.albedo_map()))
                if not extension:
                    raise RuntimeError("Unable to find the extension {}"
                                       .format(workflow.albedo_map()))

                texture_loaded = asset.find('texture',
                                            f_without_extension)
                if texture_loaded is None:
                    texture = asset.add('texture',
                                        name=f_without_extension,
                                        type='2d',
                                        file=workflow.albedo_map(),
                                        gridsize='1 1')
                    r_mat = asset.add("material",
                                      name="material_" + f_without_extension,
                                      texture=texture,
                                      texrepeat="1 1",
                                      texuniform=True,
                                      specular=specular,
                                      emission=emissive)
                else:
                    r_mat = asset.find('material',
                                       'material_' + f_without_extension)
    else:
        global MATERIAL_NUMBER
        diff = material.diffuse()
        amb = material.ambient()
        MATERIAL_NUMBER = MATERIAL_NUMBER + 1
        r_mat = asset.add("material",
                          name="material_" + str(MATERIAL_NUMBER),
                          specular=specular,
                          emission=emissive,
                          rgba=[clamp(diff.r() * 0.8 + amb.r() * 0.4, 0, 1),
                                clamp(diff.g() * 0.8 + amb.g() * 0.4, 0, 1),
                                clamp(diff.b() * 0.8 + amb.b() * 0.4, 0, 1),
                                clamp(diff.a() * 0.8 + amb.a() * 0.4, 0, 1)])
    geom.material = r_mat
    return r_mat


import calendar

from aquilon.worker.formats.formatters import ObjectFormatter
from aquilon.aqdb.model import Xtn

class TransactionFormatter(ObjectFormatter):
    def fill_proto(self, xtn, skeleton, embedded=True, indirect_attrs=True):
        skeleton.start_time = calendar.timegm(xtn.start_time.utctimetuple())
        skeleton.username = xtn.username
        skeleton.command = xtn.command
        skeleton.request_id = str(xtn.id)
        skeleton.return_code = xtn.return_code
        if xtn.end:
            skeleton.end_time = calendar.timegm(
                xtn.end.end_time.utctimetuple())
        else:
            # Need some sort of value for the protobuf (since protobufs do
            # not have a concept of null).
            skeleton.end_time = 0
        skeleton.is_readonly = int(xtn.is_readonly)

        for i in xtn.args:
            arg = skeleton.arguments.add()
            arg.name = i.name
            arg.value = i.value

ObjectFormatter.handlers[Xtn] = TransactionFormatter()


#!/usr/bin/env python3
import sys

import tree_successor

def test_sequence(sequence):
    tree = tree_successor.Tree()
    for i in sequence:
        tree.insert(i)

    # toto tedy zacne na minimum
    node = tree.successor(None)
    for element in sorted(sequence):
        print(node.key)
        assert node is not None, "Expected successor {}, got None".format(
            element)
        assert node.key == element, "Expected successor {}, got {}".format(
            element, node.key)
        node = tree.successor(node)
    assert node is None, "Expected no successor, got {}".format(node.key)

if __name__ == '__main__':
    sequence = [i for i in range(38)]
    test_sequence(sequence)


import re
import pymysql

f = open("member.html", "r", encoding='utf')
test = re.sub('\s+', " ", f.read())

pattern = re.compile('(.+?) 	 .+?(.+?).+?	 (.+?)	 (.+?)	')
data1 = re.findall(pattern, test)
# print(data1)

db = pymysql.connect("localhost", "root", "123456", "shenzy", charset='utf8mb4')
print("成功连接数据库")

cursor = db.cursor()
sql = "insert into qqgroup(nickname, name, qq, sex) values (%s, %s, %s, %s)"
try:
    cursor.executemany(sql, data1)
    db.commit()
    print("insert success")
except Exception as e:
    print("Error", str(e), sql)

db.close()


import torch.nn as nn

class DiceLoss(nn.Module):
    def __init__(self, eps=0.):
        super().__init__()
        self.eps = eps

    def forward(self, input, target):
        return dice_loss(input, target, self.eps)

def dice_loss(input, target, eps=0.):
    input = input.view(-1)
    target = target.view(-1)

    prod = (input * target).sum()
    in_sq = (input * input).sum()
    tgt_sq = (target * target).sum()

    dice = (2 * prod + eps) / (in_sq + tgt_sq + eps)

    return 1 - dice


# -*- coding: utf-8 -*-

""" Module summary description.

More detailed description.
"""
import pandas as pd
from matplotlib import pyplot as plt

from _scripts.plot_pandas_series import pandas_plot

__author__ = 'Benjamin Pillot'
__copyright__ = 'Copyright 2019, Benjamin Pillot'
__email__ = 'benjaminpillot@riseup.net'

ratio = 1/(1000 * 6.00372)
fontsize = 24
df = pd.read_csv("/home/benjamin/ownCloud/Post-doc Guyane/GREECE model/Results/Solar PV/"
                 "output_ac_power_permissive_contour.csv", index_col=0, sep=",")

# new_df = pd.DataFrame(index=df.index, columns=["C10", "C20", "C30", "C35", "C40", "C45", "C50", "C55", "C60", "C65"])
new_df = pd.DataFrame(index=df.index)
# new_df["P4, C65"] = df["polygon 6"] * 29.34 * ratio
new_df["P4, C65"] = df["polygon 6"] * ratio * 100
# new_df["P4, C45"] = df["polygon 6"] * 28.04 * ratio
# new_df["P3, C40"] = df["polygon 2"] * 24.78 * ratio
new_df["P3, C40"] = df["polygon 2"] * ratio * 100
# new_df["P2, C30"] = df["polygon 5"] * 17.29 * ratio
new_df["P2, C30"] = df["polygon 5"] * ratio * 100
# new_df["P1, C10"] = df["polygon 71"] * 4.66 * ratio
new_df["P1, C10"] = df["polygon 71"] * ratio * 100
# new_df["C20"] = df["polygon 5"] * 9.76 * ratio
# new_df["C30"] = df["polygon 5"] * 17.29 * ratio
# new_df["C35"] = df["polygon 2"] * 20.96 * ratio
# new_df["C40"] = df["polygon 2"] * 24.78 * ratio
# new_df["C45"] = df["polygon 6"] * 28.04 * ratio
# new_df["C50"] = df["polygon 6"] * 29.34 * ratio + df["polygon 71"] * 1.16 * ratio
# new_df["C55"] = df["polygon 6"] * 29.34 * ratio + df["polygon 71"] * 3.77 * ratio
# new_df["C60"] = df["polygon 5"] * 6.26 * ratio + df["polygon 6"] * 29.34 * ratio
# new_df["C65"] = df["polygon 5"] * 8.87 * ratio + df["polygon 6"] * 29.34 * ratio

new_df.index = pd.DatetimeIndex(new_df.index)
new_df = new_df[new_df.index.month == 2]

ax = pandas_plot(new_df, fontsize=fontsize, day_interval=2)
ax.set_ylabel("Power (% of $P_{max}$)", fontsize=fontsize)
ax.set_ylim(0, 100)
ax.legend(new_df.columns, fontsize=fontsize)
plt.show()


from __future__ import annotations

from behavior.plans import DIFFERENCING_SCHEMA

METHODS = [
    "lr",
    "huber",
    "svr",
    "kr",
    "rf",
    "gbm",
    "mlp",
    "mt_lasso",
    "lasso",
    "dt",
    "mt_elastic",
    "elastic",
]

# Any feature that ends with any keyword in BLOCKED_FEATURES is dropped
# from the input schema. These features are intentionally dropped since
# we don't want feature selection/model to try and learn from these.
BLOCKED_FEATURES: list[str] = DIFFERENCING_SCHEMA + [
    "plan_type",  # Plan Type
    "cpu_id",  # CPU ID
    "relid",  # Scan index into range able
    "indexid",  # Index OID
]


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests aButton widget."""
import unittest
from misura.canon.logger import Log as logging
from misura.client.tests import iutils_testing
from misura.client import widgets
from misura.canon import option
from PyQt4 import QtGui

class aButton(unittest.TestCase):

    def setUp(self):
        self.root = option.ConfigurationProxy()

    def wgGen(self):
        self.assertTrue(self.root.has_key('test'))
        widget = widgets.build(self.root, self.root, self.root.gete('test'))
        # The current value is not initialized (gete() returns {current:None} )
        self.assertTrue(widget is not False)
        return widget

    def test(self):
        self.root.sete('test', option.ao({}, 'test', 'Button')['test'])
        # Test with short reply
        self.root['test'] = 'test text'
        widget = self.wgGen()
        msgBox = widget._msgBox()
        self.assertEqual(msgBox.informativeText(), 'test text')
        # Try with long reply
        self.root['test'] = 'test text\n' * 100
        widget.current = self.root['test']
        msgBox = widget._msgBox()
        self.assertTrue(str(msgBox.informativeText()).startswith('test text'))
        self.assertEqual(msgBox.detailedText(), self.root['test'])

        iutils_testing.show(widget, __name__)

if __name__ == "__main__":
    unittest.main(verbosity=2)


from game_files.const import *

class Maze:
    '''maze class structure'''

    def __init__(self):
        self.structure = []

    def creation(self):
        '''load map and create maze'''

        with open('game_files/map.txt') as fichier:
            content = []
            #loop through lines in file
            for ligne in fichier:
                file_sprites = []
                #loop through sprites (letters) in file
                for sprite in ligne:
                  #ignore '\n'
                    if sprite != '\n':
                        #add sprite to line list
                        file_sprites.append(sprite)
                #add line to level list
                content.append(file_sprites)
            #save structure
            self.structure = content

    def display_maze(self, window):
        '''method for displaying maze from creation()'''

        background = py.image.load(FLOOR).convert()
        finishline = py.image.load(ICON_GUARDIAN).convert()
        walls = py.image.load(WALL).convert()

        #check list level
        num_ligne = 0
        for ligne in self.structure:
            #Oloop through list of lines
            num_case = 0
            for sprite in ligne:
                #real position in pixels
                _x = num_case * SPRITE_SIZE
                _y = num_ligne * SPRITE_SIZE
                if sprite == '0':
                    window.blit(background, (_x, _y))
                elif sprite == 'm':
                    window.blit(walls, (_x, _y))
                elif sprite == 'd':
                    window.blit(background, (_x, _y))
                elif sprite == 'a':
                    window.blit(finishline, (_x, _y))

                num_case += 1
            num_ligne += 1


import glob
import json
import requests

def parse_taxonomy_files(source_dir):
    """

    :param source_dir: Directory where the JSON files are stored
    :return:
    """
    r = requests.get("https://alpha.nationalarchives.gov.uk/staticdata/taxonomy_keys.json")
    if r.status_code == requests.codes.ok:
        taxonomy_lookup = r.json()
    else:
        return
    master = {}
    files = glob.glob(f"{source_dir}/*")
    for i, file in enumerate(files):
        print(f"Working on {i} of {len(files)}")
        with open(file, "r") as f:
            j = json.load(f)
            try:
                for x in j["hits"]["hits"]:
                    cat_ref = x["_source"].get("CATALOGUE_REFERENCE")
                    if cat_ref:
                        shard = "".join([x for x in cat_ref[0:2] if x.isalpha()]).lower()
                        d = {
                            "iaid": x["_id"],
                            "taxonomy_ids": [
                                taxonomy_lookup.get(y) for y in x["_source"]["TAXONOMY_ID"]
                            ],
                        }
                        if not master.get(shard):
                            master[shard] = {}
                        master[shard][cat_ref] = d
            except KeyError:
                print(f"File with error: {file}")
    for k, v in master.items():
        with open(f"taxonomy_{k}.json".lower(), "w") as wf:
            json.dump(v, wf, indent=2)

def get_taxonomy(catalogue_reference):
    """
    return the taxonomy data and the information asset ID for a given catalogue reference
    :param catalogue_reference:
    :return:
    """
    if catalogue_reference:
        pass
    return None, None

def make_taxonomy_lookup():
    taxo = {}
    r = requests.get("https://alpha.nationalarchives.gov.uk/staticdata/taxonomy.json")
    if r.status_code == requests.codes.ok:
        j = r.json()
    for list_item in j:
        taxo[list_item["code"]] = list_item
    with open("taxonomy_keys.json", "w") as wf:
        json.dump(taxo, wf, indent=2)

if __name__ == "__main__":
    parse_taxonomy_files(
        source_dir="/home/ec2-user/Python-3.8.1/ds-alpha-code/ildbweb/Graph/tmp/TAXONOMY/"
    )
    # make_taxonomy_lookup()


pirate_ship = [int(x) for x in input().split('>')]
warship = [int(y) for y in input().split('>')]
max_health = int(input())

while True:
    command = input().split()

    if command[0] == 'Retire':
        print(f'Pirate ship status: {sum(pirate_ship)}')
        print(f'Warship status: {sum(warship)}')
        exit()

    if command[0] == 'Fire':
        idx, dmg = map(int, (command[1], command[2]))
        if idx < 0 or idx >= len(warship):
            continue
        warship[idx] -= dmg
        if warship[idx] <= 0:
            print('You won! The enemy ship has sunken.')
            exit()

    elif command[0] == 'Defend':
        start_idx, end_idx, dmg = map(int, (command[1], command[2], command[3]))
        if start_idx < 0 or start_idx >= len(pirate_ship) or end_idx < 0 or end_idx >= len(pirate_ship):
            continue
        for i in range(start_idx, end_idx + 1):
            pirate_ship[i] -= dmg
            if pirate_ship[i] <= 0:
                print('You lost! The pirate ship has sunken.')
                exit()

    elif command[0] == 'Repair':
        idx, health = map(int, (command[1], command[2]))
        if idx < 0 or idx >= len(pirate_ship):
            continue
        pirate_ship[idx] = min(max_health, health + pirate_ship[idx])

    elif command[0] == 'Status':
        counter = 0
        for sect in pirate_ship:
            if sect / max_health < 0.2:
                counter += 1
        if counter != 0:
            print(f'{counter} sections need repair.')


import matplotlib.pyplot as plt
import numpy as np

def fungsi(x):
    return 4*(x**2) + x + 6

def kartesian():
    x = np.linspace(-3,3,100)
    y = 4*(x**2) + x + 6

    plt.plot(x,y)
    plt.show()

def trapezcomp(fx, bwh, ats, klm):
    lbr_klm = (ats - bwh) / klm
    x = bwh

    integrasi = fx(bwh)
    for k in range(1, klm):
        x = x + lbr_klm
        integrasi += 2 * fx(x)

    return (integrasi + fx(ats)) * lbr_klm * 0.5

def romberg(fx, bwh, ats, klm):
    kartesian()
    iterasi = np.zeros((klm, klm))

    for k in range(0, klm):
        iterasi[k, 0] = trapezcomp(fx, bwh, ats, 2**k)

        for j in range(0, k):
            iterasi[k, j+1] = (4**(j+1) * iterasi[k, j] - iterasi[k-1, j]) / (4**(j+1) - 1)

        print(iterasi[k, 0:k+1])

    return iterasi

bawah = int(input("Batas bawah: "))
atas = int(input("Batas atas: "))
kolom = int(input("Jumlah kolom: "))

iterasi = romberg(fungsi, bawah, atas, kolom)
hasil = iterasi[kolom-1, kolom-1]
print(hasil)


import os
import pickle
import re

import numpy as np
import pandas as pd
from django.conf import settings
from django.core.files.storage import default_storage
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from pymongo import MongoClient
from rest_framework import status
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_swagger import renderers
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

@api_view(['GET'])
def index(request, name):
    return HttpResponse("Hey " + name + ", it works well!")

@api_view(['POST'])
#@renderer_classes([renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer])
def setup_fraud_detection(request):
    # save log file and api file from client
    bounty_id = request.POST.get('bountyId')
    print(bounty_id)
    logfile = bounty_id + '_' + request.POST.get('logfilename')
    apifile = bounty_id + '_' + request.POST.get('apifilename')
    files_dir = settings.TESTING_FILES_ROOT
    save_path = os.path.join(files_dir, '', logfile)
    path = default_storage.save(save_path, request.FILES['logfile'])
    save_path = os.path.join(files_dir, '', apifile)
    path = default_storage.save(save_path, request.FILES['apifile'])

    # generate a machine learning model to detect fraud on testing works
    generate_model(bounty_id, os.path.join(files_dir, logfile), os.path.join(files_dir, apifile))

    return Response(default_storage.path(path), status.HTTP_200_OK)

@api_view(['POST'])
def verify_testing_works(request):
    bounty_id = request.POST.get('bountyId')
    logfile = bounty_id + '_TestingResult_' + request.POST.get('logfilename')
    apifile = bounty_id + '_restapi.csv'
    files_dir = settings.TESTING_FILES_ROOT
    save_path = os.path.join(files_dir, '', logfile)
    path = default_storage.save(save_path, request.FILES['logfile'])

    clf, enc = load_model(bounty_id)
    feature_log = retrieve_feature(os.path.join(files_dir, logfile))
    result = predict(clf, enc, os.path.join(files_dir, logfile))

    return Response(result, status.HTTP_200_OK)

def generate_model(bounty_id, logfile, apifile):
    feature_data = retrieve_feature(logfile)
    api_pattern = retrieve_api(apifile)
    labeled_data = label_data(bounty_id, feature_data, api_pattern)

    feature_data = retrieve_feature(logfile)
    pattern_api = retrieve_api(apifile)
    label_data_file = label_data(bounty_id, feature_data, pattern_api)
    methods, urls = distinct_field(distinct_data(label_data_file, feature_data))
    detection_model, enc = train_model(methods, urls, label_data_file)
    store_model(bounty_id, detection_model, enc)

def retrieve_feature(logfile):
    data = []
    with open(logfile, 'r') as logfile:
        for line in logfile:
            if ("Mapped \"{[" in line):
                temp_url = re.search(r'\{\[(.*?)\]', line)
                base_url = re.sub("\{.*?\}", "", temp_url.group(1)).rstrip('/')
                patterns = ['/swagger-resources', '/error']
                if any(pattern in base_url for pattern in patterns):
                    continue
                temp_method = re.search(r'methods=\[(.*?)\]', line)
                if temp_method:
                    method = temp_method.group(1)
                else:
                    method = "NULL"
                    #                 data_line = "Base Url: {0:<50s} Methods: {1}".format(base_url+",", method)
                data_row = method.lower() + "," + base_url
                data.append(data_row)

    return data

def retrieve_api(apifile):
    patterns = []
    with open(apifile, 'r') as file:
        for line in file:
            method, url = line.split(",")
            patterns.append(method.lower() + "," + url.rstrip('\n'))

    return patterns

def label_data(bounty_id, feature_data, patterns):
    label_data_file = bounty_id + ".lbl"
    with open(label_data_file, 'w') as file:
        for d in feature_data:
            handson_test = '0'
            if any(pattern in d.replace(" ", "") for pattern in patterns):
                handson_test = '1'
            label_data = d + ',' + handson_test + '\n'
            file.write(label_data)

    return label_data_file

def distinct_data(label_data_file, feature_data_file):
    distinct_data = []
    with open(label_data_file, 'r') as featurefile:
        for d in featurefile:
            if isNewData(d, distinct_data):
                distinct_data.append(d)

    return distinct_data

def isNewData(d, data):
    if any(x in d for x in data):
        return False
    else:
        return True

def distinct_field(distinct_data):
    distinct_method = []
    distinct_url = []
    distinct_label = []
    feature_data = []
    for f in distinct_data:
        m, u, l = f.rstrip('\n').split(',')
        if (isNewData(m, distinct_method)):
            distinct_method.append(m)
        if (isNewData(u, distinct_url)):
            distinct_url.append(u)
        if (isNewData(l, distinct_label)):
            distinct_label.append(l)
        feature_data.append(m + ',' + u)

    return distinct_method, distinct_url

def train_model(distinct_method, distinct_url, label_data_file):
    enc = preprocessing.OneHotEncoder(categories=[distinct_method, distinct_url], handle_unknown='ignore')
    col_names = ['method', 'url', 'label']
    feature_cols = ['method', 'url']
    apitest = pd.read_csv(label_data_file, header=None, names=col_names)
    # apitest.label = apitest.label.astype(str)
    X = apitest[['method', 'url']].values.tolist()
    y = apitest.label

    enc.fit(X)
    X = enc.transform(X).toarray()
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)

    clf = DecisionTreeClassifier()
    clf = clf.fit(X_train, y_train)

    return clf, enc

def store_model(bounty_id, clf, enc):
    clf_serial = pickle.dumps(clf)
    enc_serial = pickle.dumps(enc)
    # save a serialized classifier in mongodb
    clf_serial = pickle.dumps(clf)
    client = MongoClient('localhost:27017')
    db = client.Axius_FraudDetection
    db.classifier.insert_one({'bountyId': bounty_id, 'model': clf_serial, 'enc': enc_serial})

def load_model(bounty_id):
    client = MongoClient('localhost:27017')
    db = client.Axius_FraudDetection
    data = db.classifier.find_one({'bountyId': bounty_id})
    # loaded_clf = pickle.load(open(clf_file, 'rb'))
    clf_serial = data['model']
    clf = pickle.loads(clf_serial)
    enc_serial = data['enc']
    enc = pickle.loads(enc_serial)

    return clf, enc

def predict(clf, enc, input_data_file):
    feature_data = retrieve_feature(input_data_file)
    input_data = convert_feature(feature_data)
    input = enc.transform(input_data).toarray()
    result = clf.predict(input).tolist()
    num_real_testing_trial = result.count(1)
    percent_real_testing_trial = num_real_testing_trial / len(result) * 100

    response = { 'trials': num_real_testing_trial, 'percent': percent_real_testing_trial}
    return response

def convert_feature(feature_data):
    data = []
    for d in feature_data:
        method, url = d.split(',')
        data.append([method, url])

    return data

class TestView(APIView):
    permission_classes = [AllowAny]
    # renderer_classes = [
    #     renderers.OpenAPIRenderer,
    #     renderers.SwaggerUIRenderer
    # ]
    def get(self, request, name):
        return HttpResponse("Hello " + name + ",  this is a message from GET of Class View")

    def post(self, request, name):
        return HttpResponse("Hello " + name + ", this is a message from POST of Class View")


# myproject/ex_urls/views.py
# -*- coding: UTF-8 -*-

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def articles(request):
    return render(request,
                  'ex_urls/index.html',
                  {'year_list': (2003, 2004, 2005,),}
                  )

def redirect_to_year(request):
    year = 2006
    return HttpResponseRedirect(reverse('urls:news-year-archive', args=(year,)))

def special_case_2003(request):
    html = "It is now only 2003"
    return HttpResponse(html)

def year_archive(request, *args, **kwargs):
    try:
        html = "It is key Year: %s" %\
                (kwargs['year'],)
    except KeyError:
        html = "It is Year: %s" %\
                (args[0],)
    return HttpResponse(html)

def month_archive(request, *args, **kwargs):

    try:
        html = "It is now key Year: %s Month: %s" %\
         (kwargs['year'], kwargs['month'])
    except KeyError:
        html = "It is now Year: %s Month: %s" %\
         (args[0], args[1])
    return HttpResponse(html)

def day_archive(request, *args, **kwargs):
    try:
        html = "It is now key"+\
        " Year: %s Month: %s Day: %s and arg3: %s" %\
        (kwargs['year'], kwargs['month'], kwargs['day'], kwargs['extra'])
    except KeyError:
        html = "It is now Year: %s Month: %s Day: %s" %\
        (args[0], args[1], args[2])
    return HttpResponse(html)


from replit import clear
#HINT: You can call clear() to clear the output in the console.

from art import logo

print(logo)
print("Welcome to the silent auction.")
input("The bid is about to start enter any key to continue: ")

continue_bid = True
bid_dict = {}

while continue_bid:

    clear()

    name = input("What is your name?: ")
    bid = input("What is your bid? £ : ")
    bid_dict[name] = float(bid)
    next_bidder = input("Are there any other bidders? Type 'yes' or 'no': ")

    if next_bidder == "yes":
        continue_bid = True
    else:
        continue_bid = False

max_bid = max(bid_dict, key=bid_dict.get)

print(f"{max_bid} won with a bid of £{bid_dict[max_bid]}!")

#Challenge: is to create a dictionary, where each person's name is the key and their bid will be the value

#after each bid is inputted, the user should be able to type 'yes' if there is someone else yet to bid or 'no' if they are the last bidder.

#if the user clicks 'yes' the console should clear() so their bid remains a secret and if they answer 'no' the highest bidder and their bid can be printted.

# the last step will require the program to loop through the dictionary to find the highest value/bid


import hashlib
import binascii
import pandas as pd
import string
import base64
import codecs

from Crypto.Cipher import AES

def string_to_char(input):
    """Turn hexstring to ASCII"""
    length = len(input)

    c = []

    i = 0
    while i < length:
        chars = chr(int(input[i:i + 2], 16))
        c.append(chars)
        i += 2

    final = ''.join(c)
    return final

def ascii_only(input):
    """Return only if the input is an ASCII character"""
    if input in string.ascii_letters:
        return input

def decrypt_aes(encrypted, key):
    """Decrypt a bytestring using AES"""
    pass

def ascii_to_bin(input):
    """Turn a hexstring into a bytestring"""
    length = len(input)

    c = []

    i = 0
    while i < length:
        chars = chr(int(input[i:i + 2], 16)).encode()
        c.append(chars)
        i += 2

    final = b''.join(c)
    return final

def rot13(input):
    s = input
    enc = codecs.getencoder("rot-13")
    os = enc(s)[0]

    return os

# Message in the front of the coin
# rot 13
# Decrypted message is: crypto means crypto mea
front = '70 65 6c 63 67 62 20 7a 72 6e 61 ' \
        '66 20 70 65 6c 63 67 62 20 7a 72 ' \
        '6e'
front = front.split()
front = ''.join(front)
df = pd.Series(front)
key = df.apply(string_to_char)
key = key.to_frame()
key = key.to_records()
key = key[0][1]
key = rot13(key)
print(key)

# Message on the back of the coin
# no idea what this decrypts into yet
# TODO: try AES
back = '28 00 00 00 00 00 0c 4d 36 14 1e ' \
       '16 52 0e 13 17 57 07 4f 50 08 11 ' \
       '41 0a 1c 47 43 1b 17 50 00 07 45 ' \
       '4d 15 0e 1e 06 0f 13 0b 50 17 00 ' \
       '4d 04 06 4d 4e 10 41 11 06 16 1f ' \
       '1a 43 00 0c 0b 05 4e 1e 4f 15 1b ' \
       '1c 50 07 0a 52 04 00 12'
back = back.split()
back = ''.join(back)
df = pd.Series(back)
back_encrypted = df.apply(ascii_to_bin)
back_encrypted = back_encrypted.to_frame()
back_encrypted = back_encrypted.to_records()
back_encrypted = back_encrypted[0][1]
print(back_encrypted)
# write out the hexbytes conversion to a file
with open('back.enc', 'wb') as f:
    f.write(back_encrypted)

pass


import string
import re

# Variable definitions
# Define files for reading.
file_name = "a_example.txt"
#file_name = "b_lovely_landscapes.txt"
#file_name = "b_short_lovely_landscapes2.txt"
#file_name = "c_memorable_moments.txt"
#file_name = "d_pet_pictures.txt"
#file_name = "e_shiny_selfies.txt"

# Writes the new order to the file
file_OUT_name = "solution_a.txt"
#file_OUT_name = "solution_b.txt"
#file_OUT_name = "solution_c.txt"
#file_OUT_name = "solution_d.txt"
#file_OUT_name = "solution_w.txt"

#open the file
f = open(file_name, 'r')
file_info = f.readlines()
f.close()

# Variable definitions
photo_orientation = ["0"]
photo_tags = ["0"]
photo_num_tags = ["0"]
photo = ["0"]
i = 0
tag_match = "no"
m = 0;
tracker = " "

for line in file_info:
    line = line.strip("\n")
    testBoolean = line.isnumeric()
    if testBoolean:
        num_images = line
        print( "Is digit", num_images, "\n")
        photo[0] = num_images
    else:
        photo.append(i)
        photo[i] = line
        photo_list = line.split(" ")
        for t in range(0,len(photo_list),1):
            if(t == 0):
                photo_orientation.append(photo_list[t])
                tracker = tracker + "."
            elif(t == 1):
                photo_num_tags.append(photo_list[t])
                tracker = tracker + "."
            else:
                for a in range(0,len(photo_tags),1):
                    if photo_list[t] == photo_tags[a]:
                        tag_match = "yes"
                        tracker = tracker + "."
                    else:
                        m=0
                if tag_match == "no":
                    photo_tags.append(photo_list[t])
                    tracker = tracker + "."
                else:
                    tag_match = "no"
            tracker = tracker + "."
        tracker = tracker + "."
        print(tracker, num_images, i)
    tracker = ""
    i = i +1;
print("end read :: \n")

########################################################
#print results
print("photo_orientation array ", photo_orientation)
print("photo_tags array ", photo_tags)
print("photo_list array ", photo_list)
print("photo array ", photo)

########################################################
# Variable definitions

gallery_photos = ["0"]
gallery_scores = [0]
p1 = 0 # photo one
p2 = 0 # photo two
t = 0 # tags counter
score_001 = 0
score_002 = 0
score_003 = 0
score_total = 0
relativescore = 0
stringScore = ""
stringPattern = ""
string_FullPattern = ""
tracker= ""
r =0
remove_photos = [0]

gallery_photos[0] = photo[0]
for t in range(1,len(photo_tags),1):
    string_FullPattern = photo_tags[t]
    z = len(photo)
    s=0
    for s in range(1,z,1):
        print("start tag: ", t, " of ", len(photo_tags), " removed: ", s, " of ", (len(photo)), "entry: ", photo_tags[t], " entry: ", photo[s])
        if re.findall(string_FullPattern, photo[s]):
            #gallery_photos[s] = photo[s]
            gallery_photos.append(photo[s])
            remove_photos.append(s)
            print("Matched: sorted ", string_FullPattern, " s:",s," z:", z)
            tracker= tracker + "~~"
        else:
            tracker= tracker + "--"
            print("No Match")
    tracker= tracker + "##"

    for r in range((len(remove_photos)-1),0,-1):
        print(" removed: ", r, " of ", (len(remove_photos)-1), "entry: ", remove_photos[r], " entry: ", photo[remove_photos[r]])
        photo[remove_photos[r]] = " nullified "
        remove_photos[r] = 0

print(tracker)
tracker= ""

print("End keyword sort")

########################################################
#print results
print("gallery_photos array ", gallery_photos)

########################################################
# sort the array so that horizontal images are first.
sortingOne = ""
sortingTwo = ""
sortingThree = ""
s = 0
stringPattern = "^V"
z = len(photo) -2
tracker= ""
for s in range(0,z,1):
    if re.match(stringPattern, photo[s]):
        tracker= tracker + "$$"
        if re.match(stringPattern, photo[s+1]):
            tracker= tracker + "$$"
            # no sorting needed
            s = s+1
        else:
            tracker= tracker + "^^"
            sortingOne = photo[s];
            sortingTwo = photo[s+1];
            sortingThree = photo[s+2];
            if re.match(stringPattern, photo[s+2]):
                tracker= tracker + "$$"
                photo[s] = sortingTwo
                photo[s+1] = sortingOne
                #photo[s+2] = sortingThree
                tracker= tracker + "&&"
                s = s+2
            else:
                photo[s] = sortingTwo
                photo[s+1] = sortingThree
                photo[s+2] = sortingOne
                s = s+1
    else:
        tracker= tracker + "**"
    print(tracker,"\n")
    tracker=""

print("End vertical vs horizontal sort")

########################################################
#print results
print("gallery_photos array ", gallery_photos)

########################################################
# begin the scorecard
for p1 in range(1,len(gallery_photos),1):

    if p1 == 0:
       gallery_scores[p1] = 0
    else:
        for t in range(1,len(photo_tags),1):
            stringPattern = photo_tags[t]
            if re.findall(stringPattern, gallery_photos[p1]):
                if re.findall(stringPattern, gallery_photos[p2]):
                    #the number of common tags between S i and S i+1
                    score_001 = score_001 + 1
                else:
                    #the number of tags in S i but not in S i+1
                    score_002 = score_002 + 1

            if re.findall(stringPattern, gallery_photos[p2]):
                if re.findall(stringPattern, gallery_photos[p1]):
                    score_003 = score_003 + 0
                else:
                    #the number of tags in S i+1 but not in S i.
                    score_003 = score_003 + 1

    ## fix em, score on a is not showing up right, 0 3 0 should be 1 3 0
    print(p1, " of ", len(gallery_photos), "final scores: ", score_001,score_002,score_003)
    gallery_scores.append(min(score_001,score_002,score_003))
    score_001 = 0
    score_002 = 0
    score_003 = 0

########################################################
#print results
print("gallery_photos array ", gallery_photos)
print("gallery_scores array", gallery_scores)
print("\n")

#print results
print("gallery_scores array", gallery_scores)
for score_001 in range(0,len(gallery_scores),1):
    score_total = score_total + gallery_scores[score_001]
print("\n score_total: ", score_total,"\n" )

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

# Writes the new order to the file
f = open(file_OUT_name, "w")
#fix me array call in a for loop
#for new_photo in gallery_photos:
s = 0
for s in range(0,len(gallery_photos)-1,1):
########################################################
    sortingOne = ""
    sortingTwo = ""
    sortingThree = ""
    stringPattern = "^V"
    if re.match(stringPattern, gallery_photos[s]):
        if re.match(stringPattern, gallery_photos[s+1]):
            my_string = gallery_photos[s]
            my_list = my_string.split(' ')
            my_string2 = gallery_photos[s+1]
            my_list2 = my_string2.split(' ')
            f.write(str(my_list[0]) + " " + str(my_list2[0]) +"\n")
            s = s+1
    else:
        my_string = gallery_photos[s]
        my_list = my_string.split(' ')
        f.write(str(my_list[0]) + "\n")

f.close()


from .settings import *

ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

ASGI_APPLICATION = "formProject.routing.application"
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}


import re

from decoders.point_decoder import PointDecoder

class OverridePointDecoder(PointDecoder):
    """
    A point decoder that is applied to points in the override point set in siemens master.
    This is useful for when you want to decode points who's building has not fully been decoded
    """

    @staticmethod
    def decode_point_type(attr_dict):
        name = PointDecoder.decode_point_name(attr_dict)
        type_map = {'STHS.HWRT': 'Hot Water Return',
                    'STHS.HWST': 'Hot Water Supply',
                    'SEV.HX1.HW': 'Hot Water Supply',  # unknown, check back
                    'MCHWRT': 'Hot Water Return',
                    'MCHWST': 'Hot Water Supply',
                    'EV.HX2.HWR': 'Hot Water Return',
                    'SHHWRT': 'Hot Water Return',
                    'SHHWST': 'Hot Water Supply'}

        return type_map.get(name)


import requests
from bs4 import BeautifulSoup

def searchWeather(city):
    try:
        # creating url and requests instance
        url = "https://www.google.com/search?q="+"weather"+city
        html = requests.get(url).content

        # getting raw data
        soup = BeautifulSoup(html, 'html.parser')
        temp = soup.find('div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text
        str = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text

        # formatting data
        data = str.split('\n')
        time = data[0]
        sky_desc = data[1]

        # printing all data
        city = city
        temp = temp
        time = time
        desc = sky_desc

        #print(other_data)
        weather_info = f'\nToday is: {time}\n\nCity: {city.title()}\nTemperature: {temp}\nWeather Condition: {desc}'

    except Exception:
        weather_info = f'\nThere was problem retrieving that value!'

    return weather_info


import PySimpleGUI as sg
import re

class TelaRestaurante:
    def __init__(self) -> None:
        sg.ChangeLookAndFeel('Material2')
        self.__window = None

    def abre(self):
        return self.__window.Read()

    def fecha(self):
        self.__window.Close()

    def mostra_mensagem_erro(self, mensagem: str) -> None:
        sg.popup_error(mensagem)

    def trata_string(self, valor: str, min_len=None, max_len=None):
        valor_tratado = ' '.join(
            [palavra[0].upper() + palavra[1:] for palavra in valor.split()])
        if not valor_tratado:
            raise ValueError('Entrada inválida. O valor não pode ser vazio.')
        if re.search('\d', valor_tratado):
            raise ValueError(
                'Entrada inválida. O valor não deve conter dígitos.')
        if min_len and len(valor_tratado) < min_len:
            raise ValueError(
                f'A entrada deve ter no mínimo {min_len} caracteres!')
        if max_len and len(valor_tratado) > max_len:
            raise ValueError(
                f'A entrada deve ter no máximo {max_len} caracteres!')

        return valor_tratado

    def valida_inteiro(self, valor: str, nome_campo=None):
        try:
            return int(valor)
        except:
            erro = 'Por favor, insira um número inteiro'
            if nome_campo:
                raise ValueError(erro + f' no campo {nome_campo}.')
            raise ValueError(erro + '.')

    def mostra_opcoes(self, capacidade_maxima_cadastrada=None, cidades_cadastradas=[]):
        eh_tela_cadastro = capacidade_maxima_cadastrada is None and len(
            cidades_cadastradas) == 0
        index = 0
        column = []
        if not eh_tela_cadastro:
            botoes = [sg.Button('Voltar'), sg.Button('Confirmar')]
            nome_tela = 'Atualização de dados do restaurante'
            for cidade_cadastrada in cidades_cadastradas:
                column.append([sg.Text(f'- {cidade_cadastrada}', key=f'nova_cidade {cidade_cadastrada} {index}'), sg.Button(
                    'Remover cidade', key=f'remove_cidade {cidade_cadastrada} {index}')])
                index += 1
        else:
            botoes = [sg.Button('Confirmar')]
            nome_tela = 'Informações do Restaurante'

        layout = [
            [sg.Text('Tela Inicial')],
            [sg.Text('Capacidade máxima de pessoas', size=(15, 1)),
             sg.InputText(key='capacidade_maxima', default_text=capacidade_maxima_cadastrada)],
            [sg.Text('Cidade permitidas', size=(15, 1)),
             sg.InputText(key='cidade', do_not_clear=False),
             sg.Button('Adicionar cidade')],
            [sg.Column(column, key='cidades_section')],
            botoes
        ]

        self.__window = sg.Window(nome_tela).Layout(layout)
        botao, valores = self.abre()

        if not botao:
            exit(0)

        cidades = [*cidades_cadastradas]
        while True:
            try:
                if botao == 'Adicionar cidade':
                    raw_cidade = valores['cidade']
                    cidade_adicionada = self.trata_string(raw_cidade, 3)
                    if cidade_adicionada in cidades:
                        raise ValueError('Cidade já foi adicionada')

                    cidades.append(cidade_adicionada)
                    self.__window.extend_layout(
                        self.__window['cidades_section'], [[sg.Text(f'- {cidade_adicionada}', key=f'nova_cidade {cidade_adicionada} {index}'), sg.Button('Remover cidade', key=f'remove_cidade {cidade_adicionada} {index}')]])
                    index += 1
                    self.__window.refresh()
                    botao, valores = self.abre()
                    continue

                if botao.startswith('remove_cidade'):
                    _, *cidade_a_ser_removida, ind = botao.split(' ')
                    cidade_a_ser_removida = ' '.join(cidade_a_ser_removida)
                    self.__window[f'nova_cidade {cidade_a_ser_removida} {ind}'].hide_row(
                    )
                    cidades.remove(cidade_a_ser_removida)
                    self.__window.refresh()
                    botao, valores = self.abre()
                    continue

                if botao == 'Voltar':
                    self.fecha()
                    return {
                        'voltar': True
                    }

                if botao == 'Confirmar':
                    if len(cidades) == 0:
                        raise ValueError(
                            'Por favor, insira pelo menos uma cidade.')

                    capacidade_maxima = self.valida_inteiro(
                        valores['capacidade_maxima'], 'capacidade máxima')

                    self.fecha()
                    return {
                        'capacidade_maxima': capacidade_maxima,
                        'cidades': cidades,
                    }
            except Exception as err:
                self.mostra_mensagem_erro(err)
                botao, valores = self.abre()


def subfactorial(b,a):
    """
    Defines the probability function
    :param b: drawn balls
    :param a: total balls
    :return: the probability of chosing b from a
    """
    c = a-b
    test = 1
    for i in range(b+1, a+1):
      test *= i/c
      c=c-1
    return int(test)

def prob(b, a):
    """
    Optimise the function subfactorial
    :param b: drawn balls
    :param a: total balls
    :return: the probability of chosing b from a
    """
    if(a-b)>b:
        return subfactorial(a-b, a)
    else:
        return subfactorial(b,a)

def main():
    total = int(input("Enter the total number of lottery balls: "))
    drawn = int(input("Enter the number of the drawn balls: "))
    if total <= 0:
        print("The number of balls must be a positive number.")
    elif (drawn > total and total > 0):
        print("At most the total number of balls can be drawn.")
    else:
        print("The probability of guessing all ", drawn, " balls correctly is 1/", prob(drawn, total), sep="")

if __name__ == "__main__":
    main()


#!/usr/bin/python3.4
# coding: utf8

from PIL import Image
import os,sys

inputPath=sys.argv[1]
outputPath=sys.argv[2]
img = Image.open(inputPath)
print("actual size : ",img.size[0],"x",img.size[1]," pixels.")
newSizeX=int(input("enter new size x : "))
newSizeY=int(input("enter new size y : "))
img = img.resize((newSizeX,newSizeY))
img.save(outputPath)


import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import preProcessData

#Read the csv file
dfRaw = preProcessData.dfDaily #pd.read_csv("Gemini_BTCUSD_1h.csv", header=1)

#to view all columns
pd.set_option("display.max.columns", None)

print(dfRaw.head())
print(dfRaw.tail())
print(dfRaw.describe())
print(dfRaw.info())
print(dfRaw.std(numeric_only=None))

#plots
#sns.boxplot(x='BullishBearish', y='rsi', data=dfRaw)
#sns.boxplot(dfRaw['close'])
#sns.lineplot(dfRaw[['open', 'close']])
#plt.show()

#heatmap correlation
corr_matrix = dfRaw.corr(method='spearman')
f, ax = plt.subplots(figsize=(16,8))
sns.heatmap(corr_matrix, annot=True, fmt='.2f', linewidth=0.4,
            annot_kws={"size": 10}, cmap='coolwarm', ax=ax)
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)
plt.show()


#!/usr/bin/env python3

from mne_features.feature_extraction import extract_features
import mne
from joblib import Parallel, delayed
import pandas as pd

def compute_features(i, ch_name, epochs):
    ch_data = epochs.get_data(picks=ch_name)
    features = extract_features(ch_data, sfreq=epochs.info['sfreq'], selected_funcs=selected_funcs, funcs_params=selected_params, return_as_df=False)
    feature_dict = {}
    for feature_name, feature_values in zip(selected_funcs, features):
        feature_dict[f'{ch_name}_{feature_name}'] = feature_values[0]
    return feature_dict

def main():
    feature_df = pd.DataFrame()
    participants = pd.read_csv('../participants.tsv', sep='\t')
    subject_ids = participants['participant_id'].unique()
    frequency_bands = [0, 2, 4, 8, 13, 18, 24, 30, 49]
    selected_funcs = [
        'mean', 'std', 'kurtosis', 'skewness', 'quantile', 'ptp_amp',
        'pow_freq_bands', 'spect_entropy', 'app_entropy', 'samp_entropy',
        'hurst_exp', 'hjorth_complexity', 'hjorth_mobility', 'line_length',
        'wavelet_coef_energy', 'higuchi_fd', 'zero_crossings', 'svd_fisher_info'
    ]
    selected_params = {
        'quantile__q': [0.1, 0.25, 0.75, 0.9],
        'pow_freq_bands__freq_bands': frequency_bands,
    }

    for sub_id in subject_ids:
        epochs = mne.read_epochs(f'../derivatives/{sub_id}/ses-t1/eeg/{sub_id}_ses-t1_task-resteyesc_proc-clean_epo.fif')
        results = Parallel(n_jobs=-1, backend='loky')(delayed(compute_features)(i, ch_name, epochs) for i, ch_name in enumerate(epochs.ch_names))
        feature_dict = {}
        for result in results:
            feature_dict.update(result)
        subject_age = participants.loc[participants['participant_id'] == sub_id, 'age'].values[0]
        feature_dict['age'] = subject_age
        feature_df = feature_df.append(pd.DataFrame(feature_dict, index=[0]), ignore_index=True)
        feature_df.to_csv('feature_df.csv', index=False)
if __name__ == "__main__":
    main()


import cv2
# load the image and show it
image = cv2.imread("../../images/jurassic-world.jpg")
# cv2.imshow("original", image)
# cv2.waitKey(0)

cropped = image[70:170, 440:540]
# cv2.imshow("cropped", cropped)
# cv2.waitKey(0)

cv2.imwrite("../../images/output/crop.jpg", cropped)


#!/usr/bin/env python

# -*- encoding: utf-8

'''
                      ______   ___  __
                     / ___\ \ / / |/ /
                    | |    \ V /| ' /
                    | |___  | | | . \
                     \____| |_| |_|\_\
 ==========================================================================
@author: Yekun Chai

@license: School of Informatics, Edinburgh

@contact: s1718204@sms.ed.ac.uk

@file: load_data.py

@time: 26/06/2018 16:09

@desc：

'''
import pandas as pd
import spacy

from SL_config import *

def gen_label(label_index, defn_toks):
    labels_list = label_index.split()

    labels = [OUT_SIGN] * len(defn_toks)

    try:
        for label in labels_list:
            label = int(label)
            labels[label] = IN_SIGN
    except Exception as e:
        print(e)
        print("tokens:", defn_toks)
        print("label_index", label_index)
    return labels

# @timeit
def load_data(load_silver_iter=0):
    pos_df = pd.read_csv(POS_DATA, sep='\t')
    # ==================================================
    # 2.93 sec
    # pos_data = []
    # for i, row in pos_df.iterrows():
    #     label_index = row['label_index']
    #     defn = row['definition']
    #     tok_defn = word_tokenize(defn)
    #     labels = gen_label(label_index, defn)
    #     pos_tags = nltk.pos_tag(tok_defn)
    #     line = [(word, tag, label) for (word,tag), label in zip(pos_tags, labels)]
    #     pos_data.append(line)
    # ==================================================

    # ==================================================

    neg_df = pd.read_csv(NEG_DATA, sep='\t')
    # neg_df['tokens_num'] = neg_df["definition"].apply(lambda x: len(word_tokenize(x)))
    # ==================================================
    # neg_df['labels'] = OUT_SIGN * neg_df['tokens_num']
    # neg_df['pos_tags'] =  neg_df["definition"].apply(lambda x: nltk.pos_tag(word_tokenize(x)))
    # neg_df['neg_data'] = neg_df['pos_tags'].apply(lambda x: [(word, tag, OUT_SIGN) for word, tag in x])
    # ==================================================
    # 2.91 sec

    nlp = spacy.load('en')
    pos_data = []
    for i, row in pos_df.iterrows():
        label_index = row['label_index']
        defn = row['definition'].lower()
        doc = nlp(defn, disable=['ner', 'textcat'])
        defn_toks = [w.text for w in doc]

        labels = gen_label(label_index, defn_toks)
        line = [(w, label) for w, label in zip(doc, labels)]
        pos_data.append(line)

    silver_pos_data = []
    if load_silver_iter > 0:
        ITER_NUM = load_silver_iter
        SILVER_POS_DATA = os.path.join(silver_dir, CRF_MODEL, '{}pos.csv'.format(ITER_NUM - 1))
        print("start loading silver data: %s" % SILVER_POS_DATA)
        silver_pos_df = pd.read_csv(SILVER_POS_DATA, sep='\t')
        for _, row in silver_pos_df.iterrows():
            label_index = row['label_index']
            defn = row["definition"]
            defn = defn.lower()
            doc = nlp(defn, disable=['ner', 'textcat'])
            defn_toks = [w.text for w in doc]
            labels = gen_label(label_index, defn_toks)
            line = [(w, label) for w, label in zip(doc, labels)]
            silver_pos_data.append(line)
    pos_data.extend(silver_pos_data)

    neg_data = []
    for i, row in neg_df.iterrows():
        defn = row['definition'].lower()
        doc = nlp(defn, disable=['ner', 'textcat'])
        line = [(w, OUT_SIGN) for w in doc]
        neg_data.append(line)

    return pos_data, neg_data

# @timeit
def load_unlabel_data():
    if TEST_MODE is True:
        print("Start test mode:\n" + '*' * 80)
        unlabel_df = pd.read_csv(UNLABEL_DATA, sep='\t', chunksize=1000, nrows=10000)
    else:
        unlabel_df = pd.read_csv(UNLABEL_DATA, sep='\t', chunksize=10000)

    # neg_df['tokens_num'] = neg_df["definition"].apply(lambda x: len(word_tokenize(x)))
    # ==================================================
    # neg_df['labels'] = OUT_SIGN * neg_df['tokens_num']
    # neg_df['pos_tags'] =  neg_df["definition"].apply(lambda x: nltk.pos_tag(word_tokenize(x)))
    # neg_df['neg_data'] = neg_df['pos_tags'].apply(lambda x: [(word, tag, OUT_SIGN) for word, tag in x])
    # ==================================================

    # unlabel_data = []
    # # unlabel_df['unlabel_data'].tolist()
    # unlabel_defids = []
    # # unlabel_df.tolist()
    # unlabel_word = []
    #
    # for _, row in unlabel_df.iterrows():
    #     try:
    #         row_data = nltk.pos_tag(word_tokenize(row["definition"]))
    #         unlabel_data.append(row_data)
    #     except Exception as e:
    #         print('%s, %s' % (e, row))
    #     unlabel_defids.append(row['defid'])
    #     unlabel_word.append(row['word'])
    # # ==================================================

    nlp = spacy.load('en')
    for _, chunk in enumerate(unlabel_df):
        unlabel_data = []
        for i, row in chunk.iterrows():
            definition = row['definition']
            if type(definition) is not str:
                with open(ERR_LOG, 'a') as f:
                    f.write(str(row))
                print("!" * 80 + "\n" + str(row))
                definition = str(definition)
            defn = definition.lower()
            doc = nlp(defn, disable=['ner', 'textcat'])
            line = [(w,) for w in doc]
            unlabel_data.append(line)
        unlabel_defids = chunk['defid'].tolist()
        unlabel_word = chunk['word'].tolist()
        unlabel_defn = chunk['definition'].tolist()

        yield unlabel_data, unlabel_defids, unlabel_word, unlabel_defn

if __name__ == '__main__':
    # load_data()

    # gen_unlabeled_data()
    load_unlabel_data()


import streamlit as st
import matplotlib.pyplot as plt
from nii import Image3D
import time
tick = time.time()
image = Image3D("avg152T1_LR_nifti.nii.gz")
print("Time taken: {}".format(time.time()-tick))
option_ph = st.empty()
filename_ph = st.empty()
slider_ph1 = st.empty()
slider_ph2 = st.empty()
image_ph = st.empty()
def main():
    global image
    path = filename_ph.text_input("File name",'avg152T1_LR_nifti.nii.gz')
    option = option_ph.selectbox(
                                    'Select view mode',
                                    ('Manual', 'Automatic')
                                )
    if image.path != path:
        image.update_path(path)
    if(len(image.nii_data.shape)==3):
        if option == 'Manual':
            print(image.nii_data.shape[2],image.nii_data.shape[1])
            sl1 = slider_ph1.slider('Select y_dim', 0, image.nii_data.shape[2],0,1)
            sl2 = slider_ph2.slider('Select x_dim', 0, image.nii_data.shape[1],0,1)
            fig = image.plot_both_slices(sl2,sl1)
            image_ph.pyplot(fig)
        else:
            for i in range(0,image.nii_data.shape[2]):
                fig = image.plot_from_current_slice()
                sl1 = slider_ph1.slider('Select slide', 0, image.nii_data.shape[2],image.current_silce,1)
                image_ph.pyplot(fig)
                image.increment_slice_number()

if __name__ == "__main__":
    main()


"""
Example of converting restricted and unrestricted EBCC calculations
to spin-orbital (GHF) EBCC calculations.
"""

import numpy as np
from pyscf import gto, scf

from ebcc import REBCC, UEBCC, GEBCC

# Define the molecule using PySCF
mol = gto.Mole()
mol.atom = "H 0 0 0; F 0 0 1.1"
mol.basis = "cc-pvdz"
mol.build()

# Run a RHF calculation using PySCF
rhf = scf.RHF(mol)
rhf.kernel()

# Run a REBCC calculation
rcc = REBCC(rhf, ansatz="QCISD")
rcc.kernel()

# Convert to unrestricted and run kernel - unless the UEBCC solution
# breaks some symmetry this should converge immediately to the same
# solution as the REBCC calculation.
uebcc_from_rebcc = UEBCC.from_rebcc(rcc)
uebcc_from_rebcc.kernel()

# Conversion of REBCC to GEBCC goes via a UEBCC intermediate, here
# we just convert the UEBCC object we just created. Once again, in
# the absence of symmetry breaking this should converge immediately
# to the same solution as the REBCC calculation.
gebcc_from_uebcc = GEBCC.from_uebcc(uebcc_from_rebcc)
gebcc_from_uebcc.kernel()


import numpy as np
from chapter3_分析实验.C3_1_y_1 import enframe

def SNR_Calc(s, r):
    """
    计算信号的信噪比
    :param s: 信号
    :param r1: 噪声
    :return:
    """
    Ps = np.sum(np.power(s - np.mean(s), 2))
    Pr = np.sum(np.power(r - np.mean(r), 2))
    return 10 * np.log10(Ps / Pr)

def LMS(xn, dn, M, mu, itr):
    """
    使用LMS自适应滤波
    :param xn:输入的信号序列
    :param dn:所期望的响应序列
    :param M:滤波器的阶数
    :param mu:收敛因子(步长)
    :param itr:迭代次数
    :return:
    """
    en = np.zeros(itr)  # 误差序列,en(k)表示第k次迭代时预期输出与实际输入的误差
    W = np.zeros((M, itr))  # 每一行代表一个加权参量,每一列代表-次迭代,初始为0
    # 迭代计算
    for k in range(M, itr):
        x = xn[k:k - M:-1]
        y = np.matmul(W[:, k - 1], x)
        en[k] = dn[k] - y
        W[:, k] = W[:, k - 1] + 2 * mu * en[k] * x
    # 求最优输出序列
    yn = np.inf * np.ones(len(xn))
    for k in range(M, len(xn)):
        x = xn[k:k - M:-1]
        yn[k] = np.matmul(W[:, -1], x)
    return yn, W, en

def NLMS(xn, dn, M, mu, itr):
    """
    使用Normal LMS自适应滤波
    :param xn:输入的信号序列
    :param dn:所期望的响应序列
    :param M:滤波器的阶数
    :param mu:收敛因子(步长)
    :param itr:迭代次数
    :return:
    """
    en = np.zeros(itr)  # 误差序列,en(k)表示第k次迭代时预期输出与实际输入的误差
    W = np.zeros((M, itr))  # 每一行代表一个加权参量,每一列代表-次迭代,初始为0
    # 迭代计算
    for k in range(M, itr):
        x = xn[k:k - M:-1]
        y = np.matmul(W[:, k - 1], x)
        en[k] = dn[k] - y
        W[:, k] = W[:, k - 1] + 2 * mu * en[k] * x / (np.sum(np.multiply(x, x)) + 1e-10)
    # 求最优输出序列
    yn = np.inf * np.ones(len(xn))
    for k in range(M, len(xn)):
        x = xn[k:k - M:-1]
        yn[k] = np.matmul(W[:, -1], x)
    return yn, W, en

def SpectralSub(signal, wlen, inc, NIS, a, b):
    """
    谱减法滤波
    :param signal:
    :param wlen:
    :param inc:
    :param NIS:
    :param a:
    :param b:
    :return:
    """
    wnd = np.hamming(wlen)
    y = enframe(signal, wnd, inc)
    fn, flen = y.shape
    y_a = np.abs(np.fft.fft(y, axis=1))
    y_a2 = np.power(y_a, 2)
    y_angle = np.angle(np.fft.fft(y, axis=1))
    Nt = np.mean(y_a2[:NIS, ], axis=0)

    y_a2 = np.where(y_a2 >= a * Nt, y_a2 - a * Nt, b * Nt)

    X = y_a2 * np.cos(y_angle) + 1j * y_a2 * np.sin(y_angle)
    hatx = np.real(np.fft.ifft(X, axis=1))

    sig = np.zeros(int((fn - 1) * inc + wlen))

    for i in range(fn):
        start = i * inc
        sig[start:start + flen] += hatx[i, :]
    return sig

def SpectralSubIm(signal, wind, inc, NIS, Gamma, Beta):
    pass


"""
Nesta implementação em Java, o objetivo é ilustrar o uso do objeto 'this'. Em
Python, o objeto equivalente é 'self'.
"""

class Conta:
    def __init__(self, saldo):
        self.saldo = saldo

if __name__ == "__main__":

    conta_teste = Conta(123.45)

    assert conta_teste.saldo == 123.45