'''
Created on Apr 1, 2014

@author: irwink
'''

from django.shortcuts import render, redirect

from Instructors.models import TemplateDynamicQuestions, Challenges, ChallengesQuestions, TemplateTextParts, LuaLibrary, QuestionLibrary, QuestionProgrammingFiles
from Instructors.lupaQuestion import CodeSegment
from django.http import HttpResponse
from Instructors.views.utils import (addSkillsToQuestion, extractTags,
                                     getCourseSkills, getSkillsForQuestion,
                                     initialContextDict, saveTags,
                                     update_or_create_challenge_questions)
from Instructors.constants import unassigned_problems_challenge_name, unlimited_constant

from Badges.enums import ObjectTypes
from Instructors.questionTypes import QuestionTypes

import re
from django.contrib.auth.decorators import login_required, user_passes_test
from decimal import Decimal
from oneUp.decorators import instructorsCheck
from oneUp.ckeditorUtil import config_ck_editor
import os.path
import zipfile
from oneUp.settings import BASE_DIR
from shutil import copyfile

@login_required
@user_passes_test(instructorsCheck, login_url='/oneUp/students/StudentHome', redirect_field_name='')
def templateDynamicQuestionForm(request):
    context_dict, currentCourse = initialContextDict(request)

    # In this view, these are the names of the attributes which are just passed through with no processing.
    # We put them in an array so that we can copy them from one item to
    # another programmatically instead of listing them out.
    passthrough_attributes = ['preview', 'difficulty',
                              'instructorNotes', 'setupCode', 'numParts', 'author', 'submissionsAllowed', 'resubmissionPenalty']

    context_dict['skills'] = getCourseSkills(currentCourse)
    context_dict['tags'] = []
    if request.POST:
        # If there's an existing question, we wish to edit it.  If new question,
        # create a new Question object.
        if 'questionId' in request.POST:
            question = TemplateDynamicQuestions.objects.get(
                pk=int(request.POST['questionId']))
            isModifying = True
        else:
            question = TemplateDynamicQuestions()
            isModifying = False

        # Copy all strings from POST to database object.
        for attr in passthrough_attributes:
            setattr(question, attr, request.POST[attr])

        # used to fill in info for question text
        question.questonText = ''

        # if user did not specify author of the question, the author will be the user
        if question.author == '':
            question.author = request.user.username

        question.save()  # Writes to database.

        if request.FILES:
            print('we got files')
            files = request.FILES.getlist('testFile')
            saveFiles(currentCourse, question, files,
                      request.user, isModifying)

        # loops through and adds the multiple parts(the actual text) into to the template array
        templateArray = []
        partPointsArray = []
        numTemplateParts = int(request.POST['numParts'])
        # the 1 is the start of the range and we need to go all the way to the numparts (inclusive)
        for i in range(1, numTemplateParts+1):
            templateArray.append(request.POST['templateTextVisible'+str(i)])
            partPointsArray.append(int(request.POST['partpoints'+str(i)]))

        def combineCodeSegments(codeSegments):
            output = ""
            for codeSegment in codeSegments:
                output += codeSegment['code']
                output += "\n"
            return output

        # Add the path of the question files directory to the programinterface.program_checker
        '''LUA_PROBLEMS_ROOT = os.path.join(
            BASE_DIR, 'lua/problems/')  # This is for lua problems

        setupCode = re.sub("programinterface.program_checker\s*\(",
                           "programinterface.program_checker("+LUA_PROBLEMS_ROOT+",", question.setupCode)
        print("Replaced setupCode")
        print(setupCode)'''

        # Takes the array and converts the parts into lua code
        question.code = combineCodeSegments(
            templateToCodeSegments(question.setupCode, templateArray))

        # Fix the question type
        question.type = QuestionTypes.templatedynamic
        question.save()  # Writes to database.

        # Query that gets all objects that are in foreign key relation to the question and deletes them all
        TemplateTextParts.objects.filter(dynamicQuestion=question).delete()

        # Used for the number of parts in the array
        count = int(1)

        # make a new object that is a part and add all the fields it needs
        for text, partpoints in zip(templateArray, partPointsArray):
            textPart = TemplateTextParts()
            textPart.partNumber = count
            textPart.dynamicQuestion = question
            textPart.templateText = text
            textPart.pointsInPart = partpoints
            textPart.save()
            count += 1

        # Processing and saving tags in DB
        saveTags(request.POST['tags'], question, ObjectTypes.question)

        if 'challengeID' in request.POST:
            # save in ChallengesQuestions if not already saved
            update_or_create_challenge_questions(request,question)

            # Processing and saving skills for the question in DB
            addSkillsToQuestion(currentCourse, question, request.POST.getlist(
                'skills[]'), request.POST.getlist('skillPoints[]'))

            makeDependentLibraries(
                question, request.POST.getlist('dependentLuaLibraries[]'))

            redirectVar = redirect(
                '/oneUp/instructors/challengeQuestionsList', context_dict)
            redirectVar['Location'] += '?challengeID=' + \
                request.POST['challengeID']
            return redirectVar

        # Question is unassigned so create unassigned challenge object
        challenge = Challenges()
        challenge.challengeName = unassigned_problems_challenge_name
        challenge.courseID = currentCourse
        challenge.numberAttempts = unlimited_constant
        challenge.timeLimit = unlimited_constant
        challenge.save()
        ChallengesQuestions.addQuestionToChallenge(question, challenge, 0, 0)

        redirectVar = redirect(
            '/oneUp/instructors/challengeQuestionsList?problems', context_dict)
        return redirectVar

    elif request.method == 'GET':
        if 'view' in request.GET:
            context_dict['view'] = request.GET['view']
        context_dict['luaLibraries'] = getAllLuaLibraryNames()
        context_dict["initalTemplateTextPart"] = "What is [|r1|] + [|r2|]? [{make_answer('ans1','number',5,exact_equality(r1+r2),10,r1+r2)}]"
        context_dict['checkInitalTemplateTextPart'] = True

        if Challenges.objects.filter(challengeID=request.GET['challengeID'], challengeName=unassigned_problems_challenge_name):
            context_dict["unassign"] = 1

        if 'challengeQuestionID' in request.GET:
            context_dict['challengeQuestionID'] = request.GET['challengeQuestionID']

        if 'challengeID' in request.GET:
            context_dict['challengeID'] = request.GET['challengeID']
            chall = Challenges.objects.get(
                pk=int(request.GET['challengeID']))
            context_dict['challengeName'] = chall.challengeName
            context_dict['challenge'] = True

        # If questionId is specified then we load for editing.
        if 'questionId' in request.GET:
            question = TemplateDynamicQuestions.objects.get(
                pk=int(request.GET['questionId']))

            # Copy all of the attribute values into the context_dict to
            # display them on the page.
            context_dict['questionId'] = request.GET['questionId']
            for attr in passthrough_attributes:
                context_dict[attr] = getattr(question, attr)

            # TODO: get all matching templateTextPart objects and then add their code to the
            # context dictionary as templateTextParts
            # get form the database the matching question for the parts
            templateTextParts = TemplateTextParts.objects.filter(
                dynamicQuestion=question)
            context_dict['templateTextParts'] = templateTextParts
            context_dict['checkInitalTemplateTextPart'] = False

            context_dict['selectedLuaLibraries'] = getLibrariesForQuestion(
                question)

            testFiles = QuestionProgrammingFiles.objects.filter(
                questionID=question)
            testFileIDs = []
            testFileNames = []
            if(testFiles):
                for f in testFiles:
                    testFileIDs.append(f.programmingFileID)
                    testFileNames.append(f.programmingFileName)

            context_dict['programmingFiles'] = zip(testFileIDs, testFileNames)
            # Extract the tags from DB
            context_dict['tags'] = extractTags(question, "question")

            if 'challengeID' in request.GET:
                # get the challenge points for this problem to display
                if 'challengeQuestionID' in request.GET:
                    challenge_questions = ChallengesQuestions.objects.filter(pk=int(request.GET['challengeQuestionID']))
                    context_dict['points'] = challenge_questions[0].points
                else:
                    context_dict['points'] = 0

                # set default skill points - 1
                context_dict['q_skill_points'] = int('1')

                # Extract the skill
                context_dict['selectedSkills'] = getSkillsForQuestion(
                    currentCourse, question)

        else:
            context_dict['difficulty'] = 'Easy'
            context_dict["setupCode"] = "r1 = math.random(10) + 1 \nr2 = math.random(10) + 1"
            context_dict["numParts"] = 1
            context_dict['tags'] = []

    # question = LupaQuestion(code,[],5,"edit",1)
    # context_dict["test"] = question.getQuestionPart(1);

    if 'questionId' in request.POST:
        return redirect('challengesView')

    context_dict['ckeditor'] = config_ck_editor()

    return render(request, 'Instructors/TemplateDynamicQuestionForm.html', context_dict)

def HTMLquotesToRegularQuotes(str):
    return str.replace(r"'", "'", 10000).replace(r'"', '"', 10000)

# First we set up a regular expression to separate the templateText into parts.
# We do this here rather than in the function because we would rather have it only run once
# since the regular expression is always the same.
templateCodeSplitRegex = re.compile(r"\[\{(.*?)\}\]", re.DOTALL)
templateVarSplitRegex = re.compile(r"\[\|(.*?)\|\]", re.DOTALL)

def templateToCodeSegments(setupCode, templateArray):
    code_segments = list()
    sys_code = '''
        exact_equality = function(a)
            return function(b,pts)
                if tonumber(a)==tonumber(b) then
                    return {success=true,value=pts}
                else
                    return {success=false,value=0}
                end
            end
        end

        approximate_equality = function(a,fudgefraction)
            return function(b,pts)
                a = tonumber(a)
                b = tonumber(b)
                if a == 0 then
                    if b <= fudgefraction and b >= -fudgefraction then
                        return {success=true,value=pts}
                    else
                        return {success=false,value=0}
                    end
                else
                    if math.abs((a-b)/a)<=fudgefraction then
                        return {success=true,value=pts}
                    else
                        return {success=false,value=0}
                    end
                end
            end
        end

        string_equality_ignore_spaces = function(str)
            return function(b,pts)
                if b == nil then
                    return {success=false,value=0}
                end
                local str_no_space = str:gsub("%s*","")
                local b_no_space = b:gsub("%s*","")
                if string.upper(str_no_space) == string.upper(b_no_space) then
                    return {success=true,value=pts}
                else
                    return {success=false,value=0}
                end
            end
        end

        _answer_checkers = {}
        _pts = {}
        _sampleans = {}
        make_answer = function(name,type,size,checker,pts,sampleans)
            _answer_checkers[_part][name] = checker
            _pts[_part][name] = pts
            _sampleans[_part][name] = sampleans
            print(make_input(name,type,size))
        end
        _part_max_points = function(part)
            return function()
                local sum = 0
                for k,v in pairs(_pts[part]) do
                    sum = sum + v
                end
                return sum
            end
        end
        _evaluate_answer = function(part)
            return function(answers)
                results = {}
                for inputName,value in next, answers do --python.iter(answers) do
                    results[inputName] = _answer_checkers[part][inputName](
                        value,_pts[part][inputName])
                end
                return results
            end
        end
        _part_example_answers = function(part)
            return function()
                return _sampleans[part]
            end
        end
    '''
    code_segments.append(CodeSegment.new(CodeSegment.system_lua, sys_code, ""))
    code_segments.append(CodeSegment.new(CodeSegment.template_setup_code,
                                         setupCode + "\n", ""))  # Newline added to help readability

    count = int(1)

    for templateText in templateArray:
        code = ""
        code += 'part_'+str(count) + \
            '_max_points = _part_max_points('+str(count)+')\n'
        code += 'evaluate_answer_' + \
            str(count)+' = _evaluate_answer('+str(count)+')\n'
        code += 'part_' + \
            str(count)+'_example_answers = _part_example_answers('+str(count)+')\n'
        code += '''
part_'''+str(count)+'''_text = function ()
    _part = '''+str(count)+'''
    _answer_checkers[_part] = {}
    _pts[_part] = {}
    _sampleans[_part] = {}
    output = ""
    '''

        code_segments.append(CodeSegment.new(CodeSegment.system_lua, code, ""))
        count += 1
        # First we split out the variable eval parts and convert them to code print statements
        pieces = re.split(templateVarSplitRegex, templateText)
        templateTextNoValues = pieces[0]
        i = 1
        # l will always be odd because of how split works when parenthesis are used in the regular expression
        l = len(pieces)
        value_comment = '\n--value\n'
        while i < l:
            templateTextNoValues += "[{"+value_comment+"print("+pieces[i]+")}]"
            i += 1
            templateTextNoValues += pieces[i]
            i += 1

        pieces = re.split(templateCodeSplitRegex, templateTextNoValues)
        # TODO: escape quotation marks from pieces
        piece_code = "print([======["+pieces[0]+"]======])\n"
        code_segments.append(CodeSegment.new(CodeSegment.template_richtext,
                                             piece_code, pieces[0]))
        i = 1
        # l will always be odd because of how split works when parenthesis are used in the regular expression
        l = len(pieces)
        while i < l:
            piece_code = HTMLquotesToRegularQuotes(pieces[i]) + "\n"
            if pieces[i].startswith(value_comment):
                piece_type = CodeSegment.template_expression
            else:
                piece_type = CodeSegment.template_code
            code_segments.append(CodeSegment.new(
                piece_type, piece_code, pieces[i]))
            i += 1
            piece_code = "print([======["+pieces[i]+"]======])\n"
            code_segments.append(CodeSegment.new(CodeSegment.template_richtext,
                                                 piece_code, pieces[i]))
            i += 1

        code_segments.append(CodeSegment.new(
            CodeSegment.system_lua, "end\n", ""))
    return code_segments

def getAllLuaLibraryNames():
    return [ll.libraryName for ll in LuaLibrary.objects.all()]

def getLibrariesForQuestion(question):
    return [ql.library.libraryName for ql in QuestionLibrary.objects.filter(question=question)]

def makeDependentLibraries(question, libraryNameList):
    existingDeps = list(map(lambda x: x.library.libraryName,
                            QuestionLibrary.objects.filter(question=question)))
    namesWithoutExisting = [
        val for val in libraryNameList if val not in existingDeps]
    existingWithoutNames = [
        val for val in existingDeps if val not in libraryNameList]
    for name in namesWithoutExisting:
        ql = QuestionLibrary()
        ql.question = question
        ql.library = LuaLibrary.objects.get(libraryName=name)
        ql.save()
    for name in existingWithoutNames:
        QuestionLibrary.objects.filter(
            question=question, library__libraryName=name).delete()

def saveFiles(courseID, question, files, user, isModifying):

    LUA_PROBLEMS_ROOT = os.path.join(
        BASE_DIR, 'lua/problems/')  # This is for lua problems

    FILE_UPLOAD_DIR = LUA_PROBLEMS_ROOT + \
        str(question.questionID)

    if not isModifying:
        # define the access rights
        access_rights = 0o755
        try:
            os.mkdir(FILE_UPLOAD_DIR, access_rights)
        except:
            print("Creation of the directory %s failed" % FILE_UPLOAD_DIR)
            return
        else:
            print("Successfully created the directory %s" % FILE_UPLOAD_DIR)

    for f in files:
        fileName = f.name
        print("filename", fileName)
        # Someone put this in.  This is a terrible idea as our programming answer checker depends on the model directory being zipped.
        # It also means that file deletion likely doesn't work properly for .zip files.
        # We should not unzip uploaded .zip files.
        #if ".zip" in fileName:
        #    print("for zip file", fileName)
        #    with zipfile.ZipFile(f, 'r') as zipf:
        #        zipf.extractall(FILE_UPLOAD_DIR)

        completeDirName = os.path.join(FILE_UPLOAD_DIR, fileName)

        # if file with the same name already exists, remove it
        if os.path.exists(completeDirName):
            os.remove(completeDirName)
            relatedFile = QuestionProgrammingFiles.objects.filter(
                questionID=question, programmingFileName=fileName)
            for rF in relatedFile:
                rF.delete()

        try:
            # This line removed.  See previous comment.  If previously covered next three lines.
            #if not ".zip" in fileName:
            theFile = open(completeDirName, "wb")
            theFile.write(f.read())
            theFile.close()
            testFile = QuestionProgrammingFiles()
            testFile.questionID = question
            testFile.programmingFileName = fileName
            testFile.programmingFileUploader = user
            testFile.programmingFileFolderName = str(question.questionID)
            testFile.save()

        except:
            continue

    '''for f in files:
        fileName = f.name
        if ".head" in fileName or ".tail" in fileName:
            print("for head or tail", fileName)
            testFile = TestProblemFiles()
            testFile.questionID = question
            testFile.testProblemFile = f
            testFile.testProblemFileName = fileName
            testFile.testProblemFileUploader = user
            testFile.save()

        else:
            print("model", fileName)
            testFile = TestProblemModelFiles()
            testFile.questionID = question
            testFile.testProblemModelFile = f
            testFile.testProblemModelFileName = fileName
            testFile.testProblemModelFileUploader = user
            testFile.save()
    print("done saving files")'''

@login_required
@user_passes_test(instructorsCheck, login_url='/oneUp/students/StudentHome', redirect_field_name='')
def removeFileFromQuestion(request):
    import shutil
    if request.user.is_authenticated:
        if request.POST:

            if 'fileID' in request.POST and 'fileName' in request.POST:
                fileID = request.POST['fileID']
                testFile = QuestionProgrammingFiles.objects.get(
                    programmingFileID=int(fileID))
                fileName = testFile.programmingFileName
                folderName = testFile.programmingFileFolderName
                testFile.delete()
                LUA_PROBLEMS_ROOT = os.path.join(
                    BASE_DIR, 'lua/problems/')  # This is for lua problems

                #if ".zip" in fileName:
                #    subDir = fileName.split(".zip")[0]
                #    FILE_UPLOAD_DIR = LUA_PROBLEMS_ROOT + \
                #        folderName+"/"+subDir
                #    if os.path.exists(FILE_UPLOAD_DIR):
                #        shutil.rmtree(FILE_UPLOAD_DIR)

                #else:
                FILE_UPLOAD_DIR = LUA_PROBLEMS_ROOT + \
                    folderName+"/"+fileName
                if os.path.exists(FILE_UPLOAD_DIR):
                    os.remove(FILE_UPLOAD_DIR)

                return HttpResponse(200)
            else:
                return HttpResponse(403, 'something went wrong')
        return HttpResponse(403, 'something went wrong')
    else:
        return HttpResponse(403)


import random

#Daftar ini memberikan gambaran tentang waktu acara.
Kalimat_starter = random.randint(1)
if Kalimat_starter == 1 :
    kalimat_1 = ("Pada hari Rabu, ")

#Daftar ini menceritakan tentang karakter utama dari cerita ini.
karakter = random.randint(1)
if karakter == 1 :
    kalimat_2 = ("Rachel pergi ke PIM ")

#Daftar ini menentukan hari yang tepat di mana beberapa insiden telah terjadi.
waktu = random.randint(1)
if waktu == 1 :
    kalimat_3 = ("Ia berangkat pada jam 7 malam")

#Daftar ini mendefinisikan plot cerita.
story_plot = random.randint(1)
if story_plot == 1 :
    kalimat_4 = ("Semuanya terlihat normal saja sampai pada akhirnya ada suatu kejadian yang janggal di depan Mall, ")

#Daftar ini mendefinisikan tempat di mana insiden itu terjadi.
tempat = random.randint(1)
if tempat == 1 :
    kalimat_5 = ("Di depan mall ada sosok yang mengerikan ")

#Daftar ini mendefinisikan karakter kedua dari cerita.
second_character = random.randint(1)
if second_character == 1 :
    kalimat_6 = ("Sosok itu berlumuran tanah kotor ")

#Daftar ini mendefinisikan usia karakter kedua.
usia = random.randint(1)
if usia == 1 :
    kalimat_7 = ("Sosok itu tiada henti melihat ke arah saya ")

#Daftar ini menceritakan tentang pekerjaan yang dilakukan karakter kedua.
pekerjaan = random.randint(1)
if pekerjaan == 1 :
    kalimat_8 = ("Sosok itu terlihat sangat menyeramkan.")

print (kalimat_1, kalimat_2, kalimat_3, kalimat_4, kalimat_5, kalimat_6, kalimat_7, kalimat_8)

Praktikum LPP/Rachel Araya - Praktikum #4.py


# pylint: skip-file
import sys
import numpy as np

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
from torchvision.transforms import transforms, functional
from pytorch_metric_learning.distances import CosineSimilarity
from pytorch_metric_learning.utils.inference import InferenceModel, MatchFinder
from PIL import Image
import time

sys.path.append("./src")
import utils.config as cfg
from datasets import LandmarkHDF5Dataset
from utils import TrainTransforms

MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]

def convert_pil_to_tensor(pil_img):
    image_array = np.asarray(pil_img)
    print("im arr:", image_array.shape)
    image_array = np.expand_dims(image_array, axis=0)
    print("im arr after expands:", image_array.shape)
    print("image_array[0] shape:", image_array[0].shape)

    img = image_array[0].reshape(3, 200, 200).astype("float32")
    print("img.shape: ", img.shape)
    image_tensor = torch.from_numpy(img)
    return image_tensor

tf_list = TrainTransforms(mean=MEAN, std=STD, as_hdf5=True)

def image_tensor_to_numpy(tensor_image):
    print(1111111111111111111)
    # print(tensor_image.shape)
    # print(tensor_image.shape)
    tensor_image = tensor_image.reshape(tensor_image.shape[1], tensor_image.shape[2], tensor_image.shape[0])
    return (tensor_image.numpy()).astype(np.uint8)

def imshow(img, figsize=(8, 4)):
    # img = inv_normalize(img)
    plt.figure(figsize=figsize)
    plt.imshow(img)
    plt.show()

print("dataset")

# train_dataset = LandmarkHDF5Dataset(
#     root=cfg.HDF5_DIR_PATH,
#     running_mode="train",
#     transforms_list=tf_list,
#     measure_time=False,
#     is_metric=True,
# )

print("dataset loaded")
# im_path = "data/temp/garniak.jpg"
im_path = "data/temp/tshirt.jpg"
image = Image.open(im_path)
image = image.resize((200, 200)).convert("RGB")
im_type = 2
img_type = torch.tensor(im_type)
#####################################

input_image_tensor = convert_pil_to_tensor(image)
input_im_array = image_tensor_to_numpy(input_image_tensor)

# temp = Image.fromarray(image_tensor_to_numpy(input_image_tensor))
# temp.show()
# raise
#####################################
model_path = "data/results/golden-laughter-3/model/metric-golden-laughter-3-e9.path"
device = torch.device("cuda")
model = torch.load(model_path)
model.to(device)
model.eval()

print("model loaded")

match_finder = MatchFinder(distance=CosineSimilarity(), threshold=0.7)
inference_model = InferenceModel(model, match_finder=match_finder)

img = torch.unsqueeze(input_image_tensor, 0)
# img = [img_type, img[0]]
print(img.shape)
inference_model.train_knn(train_dataset)
start = time.time()
distances, indices = inference_model.get_nearest_neighbors(img.float(), k=10)
print(type(distances))
print(distances)
nearest_imgs = [convert_image(train_dataset[i][0]) for i in indices.cpu()[0]]
stop = time.time()
print(f"TIME : {(stop-start):.2f}")

res_imgs = np.hstack([input_im_array, *nearest_imgs])
imshow(res_imgs)


#! /usr/bin/env python3
from typing import Callable
import numpy as np
from sklearn import datasets

digits = datasets.load_digits()

def test_digit_classify(classifier: Callable, # function for classification
                        test_count: int=1000 # test dataset
                        ):
    correct = 0
    for img, target in zip(digits.images[:test_count], digits.target[:test_count]):
        vector = np.matrix.flatten(img)
        output = classifier(vector)
        answer = list(output).index(max(output))
        if answer == target:
            correct += 1
    return (correct / test_count)


from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

with open('PlanilhaGoogle\\id_da_planilha.txt', 'r') as arquivo:
    id_da_planilha = arquivo.read()

def autenticar_acesso():
    # ETAPA DE AUTENTICAÇÃO COM O GOOGLE:
    creds = None

    if os.path.exists('PlanilhaGoogle\\token.json'):
        creds = Credentials.from_authorized_user_file('PlanilhaGoogle\\token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'PlanilhaGoogle\\client_secret.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('PlanilhaGoogle\\token.json', 'w') as token:
            token.write(creds.to_json())

    return creds

def pegar_arquivo(creds):
    try:
        service = build('sheets', 'v4', credentials=creds)

        sheet = service.spreadsheets()  # -> Pega tod0 o arquivo.

        return sheet

    except HttpError as err:
        print(err)

def pegar_dados_planilha(intervalo: str = 'Página1!A:Z') -> list:
    creds = autenticar_acesso()

    # LER OS DADOS DA PLANILHA: (GET)
    try:
        sheet = pegar_arquivo(creds)

        result = sheet.values().get(spreadsheetId=id_da_planilha,
                                    range=intervalo).execute()  # -> Leio o arquivo, passando as informações.

        valores = result.get('values', [])  # -> Obtendo os dados da planilha que foi pega anteriormente.

        return valores

    except HttpError as err:
        print(err)

def atualizar_dados_intervalo_planilha(valores_adicionar: list, intervalo: str):
    creds = autenticar_acesso()

    # ADICIONAR/EDITAR DADOS NA PLANILHA: (UPDATE)
    try:
        sheet = pegar_arquivo(creds)

        sheet.values().update(spreadsheetId=id_da_planilha,  # -> Atualizo o arquivo, passando as informações
                              range=intervalo, valueInputOption='USER_ENTERED',
                              body={'values': valores_adicionar}).execute()

    except HttpError as err:
        print(err)

def adicionar_dados_fim_planilha(valores_adicionar: list, intervalo: str = 'Página1!A:A') -> None:
    """
    Adiciona os valores na primeira linha disponível da coluna informada.
    :param valores_adicionar: Valores a serem adicionados.
    :param intervalo: Intervalo onde será adicionado os valores.
    :return: None
    """
    creds = autenticar_acesso()

    # ETAPA DE MANIPULAÇÃO DA PLANILHA:
    try:
        sheet = pegar_arquivo(creds)

        sheet.values().append(spreadsheetId=id_da_planilha, range=intervalo,
                              valueInputOption='USER_ENTERED', body={'values': valores_adicionar}).execute()

    except HttpError as err:
        print(err)

def adicionar_dados_intervalo_planilha(valores_adicionar: list, intervalo: str):
    creds = autenticar_acesso()

    # ETAPA DE MANIPULAÇÃO DA PLANILHA:
    try:
        sheet = pegar_arquivo(creds)

        sheet.values().append(spreadsheetId=id_da_planilha, range=intervalo,
                              valueInputOption='USER_ENTERED', body={'values': valores_adicionar}).execute()

    except HttpError as err:
        print(err)

def remover_dados_planilha(intervalo: str = 'Página1!A1:Z99'):
    creds = autenticar_acesso()

    # ETAPA DE MANIPULAÇÃO DA PLANILHA:
    try:
        sheet = pegar_arquivo(creds)

        sheet.values().clear(spreadsheetId=id_da_planilha, range=intervalo, body={}).execute()

    except HttpError as err:
        print(err)

def atualizar_formatacao_planilha(base: bool = True, request: bool = False):
    """
    formatacao=False -> Se a formatação for False, cell_format e request NÃO devem ser informados,
    pois os dados padrão da função SERÃO usados.
    formatacao=True -> Se a formatação for True, cell_format e request DEVEM ser informados,
    pois os dados padrão da função NÃO serão usados.
    """
    creds = autenticar_acesso()

    if base:
        cell_format = {
            'horizontalAlignment': 'LEFT',
            'backgroundColor': {
                'red': 1,
                'green': 1,
                'blue': 1
            }
        }

        request = {
            'repeatCell': {
                'range': {
                    'sheetId': 0,
                    'startRowIndex': 0,
                    'endRowIndex': 99,
                    'startColumnIndex': 0,
                    'endColumnIndex': 99
                },
                'cell': {
                    'userEnteredFormat': cell_format
                },
                'fields': 'userEnteredFormat.horizontalAlignment,userEnteredFormat.backgroundColor'
            }
        }

    # ETAPA DE MANIPULAÇÃO DA PLANILHA:
    try:
        sheet = pegar_arquivo(creds)

        sheet.batchUpdate(spreadsheetId=id_da_planilha, body={'requests': [request]}).execute()

    except HttpError as err:
        print(err)

if __name__ == '__main__':
    pass


# -*- coding:utf-8 -*-
# 动态规划理解
# 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。
# 给一个数组，返回它的最大连续子序列的和

class Solution:

    def FindGreatestSumOfSubArray(self, array):
        if not array:
            return None

        cur_sum = 0  # 记录当前和
        greatest_sum = array[0]  # 不能设置为0，当全是负数时会有问题
        for i in range(len(array)):
            if cur_sum <= 0:
                cur_sum = array[i]  # 之前和若为负，就丢弃
            else:
                cur_sum += array[i]

            if cur_sum > greatest_sum:
                greatest_sum = cur_sum

        return greatest_sum


## plot training of full convolutional neural network using partially / fully observable states

import numpy as np
import matplotlib.pyplot as plt
import pickle
import sys
import gym
import pandas as pd

sys.path.append('../../modules/')
from Analysis.analysis_utils import get_avg_std, get_grids, analysis_specs, LINCLAB_COLS, structured_unstructured
from modules.Utils import running_mean as rm

data_dir = '../../Data/results/'
groups_to_split = ['env_name','representation']

conv_df = pd.read_csv('../../Data/conv_mf_retraining.csv')
conv_df_gb = conv_df.groupby(groups_to_split)["save_id"]
labels_for_plot = {'conv':'Partially Observable State', 'reward_conv':'Fully Observable State'}
rep_to_col = {'unstructured':'blue', 'structured':'red'}

sh_df = pd.read_csv('../../Data/train_test_shallowAC.csv')
sh_df['representation'] = sh_df['representation'].apply(structured_unstructured)
sh_df_gb = sh_df.groupby(groups_to_split)["save_id"]

envs = ['gridworld:gridworld-v1', 'gridworld:gridworld-v4', 'gridworld:gridworld-v3', 'gridworld:gridworld-v5']
grids = get_grids(envs)

def compare_conv_fc(env, conv_gb,fc_gb):
    fig, ax = plt.subplots(1,2, sharex='col')
    if env[-1] == '5':
        rwd_colrow0 = (3,9)
        rwd_colrow1= (16,9)
    else:
        rwd_colrow0 = (5,5)
        rwd_colrow1=(14,14)

    rect0 = plt.Rectangle(rwd_colrow0, 1, 1, facecolor='b',edgecolor=None, alpha=0.3)
    rect1 = plt.Rectangle(rwd_colrow1, 1, 1, facecolor='g', edgecolor=None,alpha=0.3)
    ax[0].pcolor(grids[envs.index(env)],cmap='bone_r',edgecolors='k', linewidths=0.1)
    ax[0].axis(xmin=0, xmax=20, ymin=0,ymax=20)
    ax[0].set_aspect('equal')
    ax[0].add_patch(rect0)
    #ax[0].add_patch(rect1)
    ax[0].get_xaxis().set_visible(False)
    ax[0].get_yaxis().set_visible(False)
    ax[0].invert_yaxis()

    # show CONV Results
    id_list = list(conv_gb.get_group((env,'reward_conv')))
    train_array = []
    for i, id_num in enumerate(id_list):
        with open(data_dir+ f'{id_num}_data.p', 'rb') as f:
            dats = pickle.load(f)

            raw_score = dats['total_reward']#[0:5000]
            print(len(raw_score))
            normalization = analysis_specs['avg_max_rwd'][env+'1']
            training_transformed = rm((np.asarray(raw_score)+2.5)/(normalization +2.5),200)
            train_array.append(training_transformed)
            print('done', id_num)

    mean_perf = np.mean(train_array,axis=0)
    std_perf = np.std(train_array,axis=0)/np.sqrt(len(train_array))
    mins = mean_perf-std_perf
    maxes = mean_perf+std_perf

    ax[1].plot(np.arange(len(mean_perf)),mean_perf, color="gray", label='Image (Conv)')
    ax[1].fill_between(np.arange(len(mean_perf)),mins, maxes, color='gray', alpha=0.2)

    # show FC Results
    for rep in ['unstructured','structured']:
        id_list = list(fc_gb.get_group((env,rep)))
        train_array = []
        filler = np.zeros(10000)
        filler[:] = np.nan
        for i, id_num in enumerate(id_list):
            with open(data_dir+ f'{id_num}_data.p', 'rb') as f:
                dats = pickle.load(f)
                raw_score = dats['total_reward'][5000:-1]
                if len(raw_score)==9999:
                    raw_score+= list(filler)
                print(len(raw_score))
                normalization = analysis_specs['avg_max_rwd'][env+'1']
                training_transformed = rm((np.asarray(raw_score)+2.5)/(normalization +2.5),200)
                train_array.append(training_transformed)
                print('done', id_num)

        mean_perf = np.nanmean(train_array,axis=0)
        std_perf = np.nanstd(train_array,axis=0)/np.sqrt(len(train_array))
        mins = mean_perf-std_perf
        maxes = mean_perf+std_perf

        ax[1].plot(np.arange(len(mean_perf)),mean_perf, color=LINCLAB_COLS[rep_to_col[rep]], label=f'{rep} (FC)')
        ax[1].fill_between(np.arange(len(mean_perf)),mins, maxes, color=LINCLAB_COLS[rep_to_col[rep]], alpha=0.2)

    ax[1].set_ylim(0,1.1)
    ax[1].set_yticks([0,1])
    ax[1].set_yticklabels([0,100])
    ax[1].set_ylabel('Performance \n(% Optimal)')
    ax[1].set_xlabel('Episodes')
    ax[1].legend(loc='upper center', bbox_to_anchor = (0.5,1.1))
    plt.savefig(f'../figures/CH1/compare_conv_fc{env[-2:]}.svg')
    plt.show()

compare_conv_fc(envs[1],conv_df_gb,sh_df_gb)

def plot_train_test(df, df_gb, envs, reps, save=False):
    fig, ax = plt.subplots(len(envs),2, sharex='col')
    for e, env in enumerate(envs):
        if env[-1] == '5':
            rwd_colrow0 = (3,9)
            rwd_colrow1= (16,9)
        else:
            rwd_colrow0 = (5,5)
            rwd_colrow1=(14,14)

        rect0 = plt.Rectangle(rwd_colrow0, 1, 1, facecolor='b',edgecolor=None, alpha=0.3)
        rect1 = plt.Rectangle(rwd_colrow1, 1, 1, facecolor='g', edgecolor=None,alpha=0.3)
        ax[e,0].pcolor(grids[e],cmap='bone_r',edgecolors='k', linewidths=0.1)
        ax[e,0].axis(xmin=0, xmax=20, ymin=0,ymax=20)
        ax[e,0].set_aspect('equal')
        ax[e,0].add_patch(rect0)
        ax[e,0].add_patch(rect1)
        ax[e,0].get_xaxis().set_visible(False)
        ax[e,0].get_yaxis().set_visible(False)
        ax[e,0].invert_yaxis()

        for r, rep in enumerate(reps):
            train_test_array = []
            id_list = list(df_gb.get_group((env,rep)))
            print(env,rep)
            for i, id_num in enumerate(id_list):
                # get training data
                train_dat_id = list(df.loc[df['save_id']==id_num]['load_from'])[0]
                with open(data_dir+ f'{train_dat_id}_data.p', 'rb') as f:
                    dats = pickle.load(f)
                    raw_score = dats['total_reward'][0:5000]
                    normalization = analysis_specs['avg_max_rwd'][env+'1']
                    training_transformed = (np.asarray(raw_score)+2.5)/(normalization +2.5)
                # get testing data
                with open(data_dir+ f'{id_num}_data.p', 'rb') as f:
                    dats = pickle.load(f)
                    raw_score = dats['total_reward']
                    normalization = analysis_specs['avg_max_rwd'][env+'1']
                    testing_transformed = (np.asarray(raw_score)+2.5)/(normalization +2.5)

                train_test_data = rm(np.concatenate((training_transformed,testing_transformed)),200)
                train_test_array.append(train_test_data)
                print('done', id_num)

            mean_perf = np.mean(train_test_array,axis=0)
            std_perf = np.std(train_test_array,axis=0)/np.sqrt(len(train_test_array))
            mins = mean_perf-std_perf
            maxes = mean_perf+std_perf

            ax[e,1].plot(np.arange(len(mean_perf)),mean_perf, color=LINCLAB_COLS[rep_to_col[rep]], label=labels_for_plot[rep])
            ax[e,1].fill_between(np.arange(len(mean_perf)),mins, maxes, color=LINCLAB_COLS[rep_to_col[rep]], alpha=0.2)
            ax[e,1].set_ylim(0,1.1)
            ax[e,1].axvline(x=4801, linestyle=":",color='gray')
        ax[e,1].set_ylabel('Performance \n(% Optimal)')

    ax[e,1].set_xlabel('Episodes')
    ax[0,1].legend(loc='upper center', bbox_to_anchor = (0.5,1.1))
    plt.savefig('../figures/CH1/conv_net_retrain.svg')
    plt.show()

def plot_all(save=True, cutoff=25000):
    fig, axs = plt.subplots(4, 2, sharex='col')
    for i in range(len(grids)):
        rect = plt.Rectangle((5,5), 1, 1, color='g', alpha=0.3)
        axs[i,0].pcolor(grids[i],cmap='bone_r',edgecolors='k', linewidths=0.1)
        axs[i,0].axis(xmin=0, xmax=20, ymin=0,ymax=20)
        axs[i,0].set_aspect('equal')
        axs[i,0].add_patch(rect)
        axs[i,0].get_xaxis().set_visible(False)
        axs[i,0].get_yaxis().set_visible(False)
        axs[i,0].invert_yaxis()

    for ind, name in enumerate(envs):
        for rep_to_plot in reps:
            v_list = list(df_gb.get_group((name,rep_to_plot)))
            for i in v_list:
                print(i[0:8])
                if i[0:8] in ['69aa8807','9ea97939']:
                    v_list.remove(i)
            avg_, std_ = get_avg_std(v_list,cutoff=cutoff, smoothing=200)
            axs[ind,1].plot(avg_, label=f'{labels_for_plot[rep_to_plot]}')
            axs[ind,1].fill_between(np.arange(len(avg_)),avg_-std_/np.sqrt(len(v_list)), avg_+std_/np.sqrt(len(v_list)), alpha=0.3)
            axs[ind,1].set_ylim([-4,12])
        if ind == len(envs)-1:
            axs[ind,1].set_xlabel('Episodes')
            #axs[ind,1].set_ylabel('Cumulative \nReward')
    axs[0,1].legend(loc='upper center', ncol=1, bbox_to_anchor=(0.2,1.1))
    if save:
        plt.savefig('../figures/CH1/conv_retraining.svg',format='svg')

    plt.show()

#plot_all(cutoff=25000)


# -*- coding: utf-8 -*-
"""
Created on Sat Dec  5 06:11:52 2020

@author: Notebook
"""

def getSeatParameters(seat):
    row = seat[:7].replace('F', '0').replace('B', '1')
    row = int(row, base=2)
    col = seat[7:].replace('L','0').replace('R', '1')
    col = int(col, base=2)
    return row, col, row*8+col

with open('C:/Users/Notebook/Documents/AOC/2020/input_d5.txt') as f:
    seats = f.readlines()

N = [getSeatParameters(seat)[2] for seat in seats]
print(max(N))

N = sorted(N)
for i in range(1, len(N)):
    if N[i]-N[i-1] == 2:
        print(N[i]-1)
        break


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 08:05:12 2020

@author: andris
"""

import pandas as pd

#%% read excel
df = pd.read_excel("ikon.xlsx", index_col=0, keep_default_na=False)

#%% Drop duplicate exhibitions
"""
These exhibtions are duplicated in the Ikon archive.
i.e.:
- ARTFORT FESZTIVÁL, GENIUS LOCI
- "Nem is a föld miatt, nem is az ég miatt" (Apollinaire)
- „Bestia bestia látlak” - A Bizottság-kiállításhoz kapcsolódó filmklub
- (H)arcok. Dunaújvárosi művészek önmagukról - előadás
- ...bárányok a folyónál
- TÜKÖR: Hiroshi Teshigahara: A másik arca (Tanin no kao) filmvetítés Varró Attila filmesztéta előadásával
- UTÓSZEZON: Torino Frankfurt, Kassel, Sao Paulo - vetítések, előadások, beszélgetések
"""
duplicates = df[df.duplicated(subset=['title', 'date', 'gallery', 'artists'], keep=False)]
df.drop_duplicates(subset=['title', 'date', 'gallery', 'artists'], keep='first')

#%% remove dash '-' artists
def print_dashes(df):
    for idx, row in df.iterrows():
        if any( "-" == a for a in row['artists'].split("; ") ):
            print(row['artists'])

for idx, row in df.iterrows():
    artists = row['artists'].split("; ")
    artists = [a for a in artists if a != "-"]
    df.loc[idx, 'artists'] = "; ".join(artists)

df2.to_excel("ikon.xlsx")


### This algorithm written as an example of how
### genetic algorithm could\shoud work
###
### Here it solves a little problem of finding variables of equation (see equation function)
### Data type of variables is float

### Do not change gene_number
### Change only chromosome number, mutation chance and limit

from random import uniform
from random import randint
import os

class GeneticAlgorithm:
    """
    Genetic algorithms are commonly used to generate
    high-quality solutions to optimization and search problems

    :param gene_number       is a number of genes
    :param chromosome_number is a number of chomosomes
    :param value_needed      is a value closer to which result should be
    :param limit             is optional value, sets limit of iterations (executed loop will be for loop), if limit is not set
                             it automatically sets limit as infinity (in this case loop will be while loop)

    Pseudocode:
    START
        Generate the initial population
        Compute fitness
        REPEAT
            Selection
            Crossover
            Mutation
            Compute fitness
        UNTIL population has converged
    STOP

    """

    def __init__(self, gene_number, chromosome_number, mutation_chance, limit):
        self.chromosomes_for_filter = chromosome_number
        l = self.initialize_population(gene_number, chromosome_number)
        # probabilities = self.fitness(l)
        print('Start : ')
        for i, chromosome in enumerate(l):
            print(f'#{i} {chromosome} val : {self.equation(chromosome[0], chromosome[1], chromosome[2])}')

        l, probabilities = self.fitness(l)
        for i_to_limit in range(limit):
            _l = self.crossover(l)
            _l = self.mutation(_l, mutation_chance)
            _l, probabilities = self.fitness(_l)
            l = _l
            # print(f'iter {i_to_limit} / {limit}')

        print('Result : ')
        for i, chromosome in enumerate(l):
            print(f'#{i} {chromosome} val : {self.equation(chromosome[0], chromosome[1], chromosome[2])}')

    def initialize_population(self, gene_number, chromosome_number):
        """
        Initializing population to work with
        :return: list with population (Chomosomes and genes)
        """
        l = []
        for chromosome in range(chromosome_number):
            l.append([])
            for gene in range(gene_number):
                l[-1].append(round(uniform(0.01, 100), 2))
        return l

    def equation(self, x, y, z):
        return (3*(x**4) + 2*(x**2) + y) / (z**2)

    def fitness(self, l):
        """
        It is vitally important function, which defines are parameters
        fit or not for the solution
        :param l: list with  population
        :return: probability that individual will be selected for further reproduction
        """

        values = {}
        for i, chromosome in enumerate(l):
            values[i] = self.equation(chromosome[0], chromosome[1], chromosome[2]) # index : value

        _values = []

        for index in values:
            _values.append((index, values[index]))

        probabilities = [] # now in probabilities the less 1 val is better
        for index, eqvalue in _values:
            probabilities.append((index, abs(eqvalue-11)))

        probabilities.sort(key=lambda tup: tup[1])
        probabilities = probabilities[:self.chromosomes_for_filter]

        _l = []
        for index, percentage in probabilities:
            _l.append(l[index])

        return _l, probabilities

    def crossover(self, l):
        """
        Get all off-springs  (population size = a(i) ... a(i+1) )
        Here we use 'One Point Crossover'

        :return: new l
        """
        _l = []
        for i, chromosome_i in enumerate(l):
            for j in range(i + 1, len(l)):
                parent_1 = l[i]
                parent_2 = l[j]
                new_parent_1_left = l[i][:len(l[i])//2]
                new_parent_1_right = l[j][len(l[i])//2:]
                new_parent_2_left = l[j][:len(l[j])//2]
                new_parent_2_right = l[i][len(l[j])//2:]
                new_parent_1 = []
                new_parent_1.extend(new_parent_1_left)
                new_parent_1.extend(new_parent_1_right)
                new_parent_2 = []
                new_parent_2.extend(new_parent_2_left)
                new_parent_2.extend(new_parent_2_right)
                _l.append(new_parent_1)
                _l.append(new_parent_2)

        return _l

    def mutation(self, _l, mutation_chance):
        """
        For some chromosomes add mutation
        :return: list with mutated chromosomes
        """

        mutation_chance = mutation_chance*100
        for i, chromosome in enumerate(_l):
            if round(uniform(0, 1), 2) <= mutation_chance: # 2 because it is mutation
                # mutate
                _l[i][randint(0, len(chromosome)) - 1] = round(uniform(0.01, 100), 2)

        return _l

import time
start = time.perf_counter()
GeneticAlgorithm(gene_number=3, chromosome_number=10, mutation_chance=0.01, limit=30000)
print(f'finished in {round(time.perf_counter() - start)} sec')


# 팽창연산
# 영상 속 사물의 주변을 덧붙여 영역을 확장
# 해당 예시는 사각형 3x3 픽셀 영역 기준으로 모자란 부분에 팽창하여
# 하얀색 글자 내의 작은 점들이 덮어짐, 전체적으로 굵어짐

import cv2
import numpy as np

img = cv2.imread("./img/morph_hole.png")

k = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))

# cv2.dilate(입력영상, 구조화 요소 커널 객체)
dst = cv2.dilate(img, k)

merged = np.hstack((img, dst))
cv2.imshow("Dilation", merged)
cv2.waitKey(0)
cv2.destroyAllWindows()


import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision

class AE(nn.Module):
    def __init__(self, in_channels = 1, hidden_dims=[128, 256, 512], z_dim=128):
        super(AE, self).__init__()
        self.fc1 = nn.Linear(12800, z_dim) # 均值 向量mu
        self.fc2 = nn.Linear(z_dim, 12800) #decoder_input
        self.conv1 = nn.Sequential(
                    nn.Conv2d(in_channels, out_channels=hidden_dims[0],kernel_size= 3, stride= 2, padding  = 1),
                    nn.BatchNorm2d(hidden_dims[0]),
                    nn.LeakyReLU(),
                    nn.MaxPool2d(kernel_size = 2, return_indices=True))
        self.conv2 = nn.Sequential(
                    nn.Conv2d(hidden_dims[0], out_channels=hidden_dims[1],kernel_size= 3, stride= 2, padding  = 1),
                    nn.BatchNorm2d(hidden_dims[1]),
                    nn.LeakyReLU(),
                    nn.MaxPool2d(kernel_size = 2, return_indices=True))
        self.conv3 = nn.Sequential(
                    nn.Conv2d(hidden_dims[1], out_channels=hidden_dims[2],kernel_size= 3, padding  = 1),
                    nn.BatchNorm2d(hidden_dims[2]),
                    nn.LeakyReLU(),
                    nn.MaxPool2d(kernel_size = 2, return_indices=True))
        self.upsample = nn.MaxUnpool2d(2)
        #ConvTranspose2d 逆卷積

        self.trans1 = nn.Sequential(
                    nn.ConvTranspose2d(hidden_dims[2],
                                       hidden_dims[1],
                                       kernel_size = 3,
                                       stride = 1,
                                       padding = 1,
                                       output_padding = 0),
                    nn.BatchNorm2d(hidden_dims[1]),
                    nn.LeakyReLU())
        self.trans2 = nn.Sequential(
                    nn.ConvTranspose2d(hidden_dims[1],
                                       hidden_dims[0],
                                       kernel_size = 3,
                                       stride = 2,
                                       padding = 1,
                                       output_padding = 1),
                    nn.BatchNorm2d(hidden_dims[0]),
                    nn.LeakyReLU())
        self.trans3 = nn.Sequential(
                            nn.ConvTranspose2d(hidden_dims[0],
                                               hidden_dims[0],
                                               kernel_size = 3,
                                               stride = 2,
                                               padding = 1,
                                               output_padding = 1),
                            nn.BatchNorm2d(hidden_dims[0]),
                            nn.LeakyReLU(),
                            nn.Conv2d(hidden_dims[0], out_channels = 1,
                                      kernel_size = 3, padding = 1),
                            nn.Tanh())

    def latent_code(self,x):
        result = torch.flatten(x, start_dim=1)
        return self.fc1(result)

    def forward(self, x):
        #print(x.size())
        x, indice1 = self.conv1(x)
        #print(x.size())
        x, indice2 = self.conv2(x)
        #print(x.size())
        x, indice3 = self.conv3(x)
        #print(x.size())
        x = self.upsample(x,indice3)
        #print(x.size())
        x = self.trans1(x)
        #print(x.size())
        x = self.upsample(x,indice2)
        x = self.trans2(x)
        x = self.upsample(x,indice1)
        x = self.trans3(x)
        return x

#%%
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision
from torchvision import transforms
from torchvision.utils import save_image
from torchvision import datasets
from torch.utils.data import DataLoader
from IPython.display import Image
from IPython.core.display import Image, display
from dae import AE

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
learning_rate = 1e-3
batch_size = 32
num_epoch = 150
transform =  transforms.Compose([
        transforms.Grayscale(),
        transforms.RandomHorizontalFlip(),
        transforms.RandomVerticalFlip(),
        transforms.Resize((160, 160)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.5],std=[0.5])
        ])
data = datasets.ImageFolder('./normal',transform = transform)
dataloader = DataLoader(data, batch_size = batch_size, shuffle = True)
len(data.imgs), len(dataloader)
model = AE().to(device)
model
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay = 0.0001)
criterion = nn.MSELoss(reduction='sum')
Loss = []
for epoch in range(num_epoch):
    num_data = 0
    total_loss = 0
    for i, (images, _) in enumerate(dataloader):
        images = images.to(device)
        #print(images.size())
        batch_num = len(images)
        num_data += batch_num
        recon_images = model(images)
        loss = criterion(recon_images, images)
        total_loss += loss
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    Loss.append(total_loss)
    if (epoch+1) % 10 == 0:
        print('Train epoch: {}/{} Training Loss: {}'.format(epoch+1, num_epoch, total_loss/num_data))
invTrans = transforms.Compose([
    transforms.Normalize(mean = [0.],std = [ 1/0.5]),
    transforms.Normalize(mean = [ -0.5],std = [ 1.]),
    ])
torch.save(model.state_dict(), 'params130.pkl')
pretrained_dict = torch.load('params130.pkl')
model_dict = model.state_dict()

#%%
from PIL import Image as pic
test_image = pic.open('./normal/normal/Defect_P0000_P0135_000_000.jpg')
test_image
fixed_x = transform(test_image)
model.load_state_dict(torch.load('params130.pkl', map_location=torch.device('cpu')))
model.eval()
save_image(invTrans(fixed_x).data, 'sample_image.png')
display(Image('sample_image.png', width=160, unconfined=True))
fixed_x = fixed_x.to(device)
recon_x= model(fixed_x.view(-1,1,160,160))
recon_x = invTrans(recon_x.view(1,160,160))
save_image(recon_x.data, 'recon_image.png')
display(Image('recon_image.png', width=160, unconfined=True))

#https://arxiv.org/pdf/2008.12589.pdf


import copy
from pubsub import pub
import wx
import wx.grid
from wx.lib.agw.customtreectrl import EVT_TREE_ITEM_CHECKED

from _ids import ID_POLYGON
import _icons as ico
from frames.frame_design import ObjectFrame, GAP
from frames.property_panels import SelectionTree

class CorrelationSelectionTree(SelectionTree):
    def __init__(self, parent, object_menu_page):
        super().__init__(parent, object_menu_page)

    def GetIndices(self):
        items = self.GetCheckedItems()
        indices = []
        for i, item in enumerate(items):
            if item.IsChecked() and not item.HasChildren():
                indices.append(i)

        return indices

    def CheckAllItems(self, parent=None):
        if parent is None:
            parent = self.tree.GetRootItem()

        child, cookie = self.tree.GetFirstChild(parent)

        while child:
            self.tree.CheckItem2(child, checked=True, torefresh=True)

            self.CheckAllItems(child)
            child, cookie = self.tree.GetNextChild(parent, cookie)

class CorrelationFrame(ObjectFrame):
    def __init__(self, parent, title, mgr, object_menu_page, items, types):
        super().__init__(parent=parent, title=title)

        self._items = items
        self._types = types

        self._mgr = mgr
        self._object_menu_page = object_menu_page
        self._correlation, self._labels = mgr.GetCorrelationMatrix()

        self.splitter = wx.SplitterWindow(self.custom, wx.ID_ANY, style=wx.SP_THIN_SASH | wx.SP_LIVE_UPDATE)
        self.selection = CorrelationSelectionTree(self.splitter, self._object_menu_page)
        self.properties = wx.Panel(self.splitter)
        self.splitter.SplitVertically(self.selection, self.properties, 200)
        self.grid = wx.grid.Grid(self.properties)

        self.custom_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.InitUI()
        self.Load()
        self.Center()

        # events -------------------------------------------------------------------------------------------------------
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(EVT_TREE_ITEM_CHECKED, self.OnTreeItemChecked, self.selection.tree)
        self.apply_button.Bind(wx.EVT_BUTTON, self.OnApplyButton)
        self.ok_button.Bind(wx.EVT_BUTTON, self.OnOKButton)

    def InitUI(self):
        self.SetIcon(ico.correlation_16x16.GetIcon())

        # selection tree -----------------------------------------------------------------------------------------------
        self.selection.Populate(self._items, self._types)
        self.selection.CheckAllItems()

        n = len(self._correlation)
        self.grid.CreateGrid(n, n)
        self.grid.SetColLabelTextOrientation(wx.VERTICAL)

        # disable lower half of the correlation matrix (including diagonal)
        n = len(self._correlation)
        for j in range(0, n):
            for i in range(j, n):
                self.grid.SetReadOnly(i, j, True)
                self.grid.SetCellBackgroundColour(i, j, wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE))

        # change row and column options
        for i in range(0, n):
            # labels
            self.grid.SetColLabelValue(i, self._labels[i])
            self.grid.SetRowLabelValue(i, self._labels[i])

            # sizes
            self.grid.SetColSize(i, 30)
            self.grid.SetRowSize(i, 30)

        self.grid.SetColLabelSize(wx.grid.GRID_AUTOSIZE)

        # sizing -------------------------------------------------------------------------------------------------------
        self.custom_sizer.Add(self.splitter, 1, wx.EXPAND | wx.ALL, GAP)
        self.custom.SetSizer(self.custom_sizer)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.grid, 1, wx.EXPAND)
        self.properties.SetSizer(sizer)
        self.custom_sizer.Fit(self.custom)

        self.Realize()

    def OnClose(self, event):
        pass

    def OnTreeItemChecked(self, event):
        indices = self.selection.GetIndices()
        n = len(self._correlation)
        for i in range(0, n):
            if i in indices:
                self.grid.ShowCol(i)
                self.grid.ShowRow(i)
            else:
                self.grid.HideCol(i)
                self.grid.HideRow(i)

    def OnApplyButton(self, event):
        return self.Save()

    def OnOKButton(self, event):
        saved = self.OnApplyButton(None)
        if saved:
            self.Close(True)

    def Load(self):
        # load upper half of the correlation matrix
        n = len(self._correlation)
        for j in range(0, n):
            for i in range(0, j):
                self.grid.SetCellValue(i, j, str(self._correlation[i][j]))

                # set alignment
                self.grid.SetCellAlignment(i, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER)

            # Fill diagonal with ones
            self.grid.SetCellValue(j, j, str(1))
            self.grid.SetCellAlignment(j, j, wx.ALIGN_CENTER, wx.ALIGN_CENTER)

    def Save(self):
        # Save upper half of the grid to the upper and lower half of the correlation matrix
        correlation = copy.deepcopy(self._correlation)
        n = len(correlation)
        for j in range(1, n):
            for i in range(0, j):
                try:
                    value = float(self.grid.GetCellValue(i, j))
                    if -1. <= value <= 1.:
                        correlation[i][j] = value
                        correlation[j][i] = value
                    else:
                        msg = 'coefficient ({},{}) must be in the range -1 to 1'.format(i, j)
                        box = wx.MessageDialog(self, msg, caption='Value Error')
                        box.ShowModal()
                        box.Destroy()
                        return False

                except ValueError:
                    msg = 'coefficient ({},{}) must be a number'.format(i, j)
                    box = wx.MessageDialog(self, msg, caption='Type Error')
                    box.ShowModal()
                    box.Destroy()
                    return False

        self._mgr.SetCorrelationMatrix(correlation)
        return True

class EntityCorrelationFrame(CorrelationFrame):
    def __init__(self, parent, mgr, object_menu_page):

        items = (object_menu_page.subsurface,)
        types = (ID_POLYGON,)

        super().__init__(parent, 'Correlated polygons', mgr, object_menu_page, items, types)

    def OnClose(self, event):
        pub.sendMessage('entity_correlation_closed')

        event.Skip()

class VariableCorrelationFrame(CorrelationFrame):
    def __init__(self, parent, mgr, object_menu_page):

        items = (object_menu_page.statics, object_menu_page.scalers)
        types = ('scalers', 'statics')

        super().__init__(parent, 'Correlated variables', mgr, object_menu_page, items, types)

    def OnClose(self, event):
        pub.sendMessage('variable_correlation_closed')

        event.Skip()


from rest_framework import serializers
from .models import *

class DepartmentSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=10, min_length=2, error_messages={
        "max_length": "最多10个字",
        "min_length": "最少2个字"
    })

    def create(self, validated_data):
        instance = Department.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        instance.name = validated_data.get("name", instance.name)
        instance.save()
        return instance

class EmployeeSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=10, min_length=2, error_messages={
        "max_length": "最多10个字",
        "min_length": "最少2个字"
    })
    gender = serializers.CharField(max_length=10)
    age = serializers.CharField(max_length=10)
    position = serializers.CharField(max_length=20, min_length=2, error_messages={
        "max_length": "最多20个字",
        "min_length": "最少2个字"
    })
    salary = serializers.IntegerField()
    department = serializers.CharField(source='department.name', read_only=True)

    def create(self, validated_data):
        instance = Employee.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        instance.name = validated_data.get("name", instance.name)
        instance.gender = validated_data.get("gender", instance.gender)
        instance.age = validated_data.get("age", instance.age)
        instance.position = validated_data.get("position", instance.position)
        instance.salary = validated_data.get("salary", instance.salary)
        instance.save()
        return instance


#!/bin/python3

import math
import os
import random
import re
import sys

class Node:
    def __init__(self):
        self.children = {}
        self.count = 0

class Trie:
    def __init__(self):
        self.root = Node()

    def add(self, word):
        cur = self.root

        for character in word:
            if not character in cur.children:
                cur.children[character] = Node()
            cur = cur.children[character]
            cur.count += 1

    def find(self, word):
        cur = self.root

        for character in word:
            if not character in cur.children:
                return 0
            cur = cur.children[character]

        return cur.count

if __name__ == '__main__':
    tries = Trie()

    n = int(input())

    for n_itr in range(n):
        opContact = input().split()
        op = opContact[0]
        contact = opContact[1]

        if op == 'add':
            tries.add(contact)
        elif op == 'find':
            print(tries.find(contact))


import ctypes
from ctypes import c_void_p, c_uint64, c_int32, c_ulonglong, c_size_t, c_float, c_longlong, c_bool
import numpy as np

import os
import time

src_dir = os.path.join(os.path.dirname(__file__))

start_time = time.time()
print("LOADING....")
if os.environ.get("COMPILE_MPM") or not os.path.isfile(f"{src_dir}/libmaniskill_mpm.so"):
    command = f"nvcc -O3 -Xptxas -O3,-v -ccbin=g++ --compiler-options -fPIC -shared {src_dir}/csrc/integrator.cu -o {src_dir}/libmaniskill_mpm.so"
    print(command)
    if os.system(command) != 0:
        print("Failed to compile mpm library")
        exit()

lib = ctypes.cdll.LoadLibrary(f"{src_dir}/libmaniskill_mpm.so")
print(f"Loaded with {time.time() - start_time} secs.")

cuda_stream_t = c_void_p
texture_t = c_ulonglong

class vec3(ctypes.Array):
    _length_ = 3
    _type_ = ctypes.c_float

    length = 3
    ctype = ctypes.c_float
    size = 12
    np_type = np.float32

    def __repr__(self):
        return f"ivec3({self[0]}, {self[1]}, {self[2]})"

class quat(ctypes.Array):
    _length_ = 4
    _type_ = ctypes.c_float

    length = 4
    ctype = ctypes.c_float
    size = 16
    np_type = np.float32

    def __repr__(self):
        return f"quat({self[0]}, {self[1]}, {self[2]}, {self[3]})"

class ivec3(ctypes.Array):
    _length_ = 3
    _type_ = ctypes.c_int

    length = 3
    ctype = ctypes.c_int
    size = 12
    np_type = np.int32

    def __repr__(self):
        return f"ivec3({self[0]}, {self[1]}, {self[2]})"

class mat3(ctypes.Array):
    _length_ = 9
    _type_ = ctypes.c_float

    length = 9
    ctype = ctypes.c_float
    size = 36
    np_type = np.float32

    def __repr__(self):
        return f"ivec3({self[0]}, {self[1]}, {self[2]}, {self[3]}, {self[4]}, {self[5]}, {self[6]}, {self[7]}, {self[8]})"

class texture_resources(ctypes.Structure):
    _fields_ = [("array", c_void_p), ("texture", texture_t)]

class float32:
    length = 1
    ctype = ctypes.c_float
    size = 4
    np_type = np.float32

class int32:
    length = 1
    ctype = ctypes.c_int
    size = 4
    np_type = np.int32

class int64:
    length = 1
    ctype = ctypes.c_int64
    size = 8
    np_type = np.int64

lib.cuda_alloc.restype = c_void_p
lib.cuda_alloc.argtypes = [c_size_t]

lib.cuda_free.argtypes = [c_void_p]

lib.cuda_upload.argtypes = [c_void_p, c_void_p, c_size_t]
lib.cuda_upload_async.argtypes = [c_void_p, c_void_p, c_size_t, cuda_stream_t]

lib.cuda_download.argtypes = [c_void_p, c_void_p, c_size_t]
lib.cuda_download_async.argtypes = [c_void_p, c_void_p, c_size_t, cuda_stream_t]

lib.cuda_copy.argtypes = [c_void_p, c_void_p, c_size_t]

lib.cuda_copy2d.argtypes = [c_void_p, c_size_t, c_void_p, c_size_t, c_size_t, c_size_t]

lib.cuda_zero.argtypes = [c_void_p, c_size_t]
lib.cuda_zero_async.argtypes = [c_void_p, c_size_t, cuda_stream_t]

lib.create_volume.argtypes = [c_void_p, c_int32, c_int32]
lib.create_volume.restype = texture_resources

lib.destroy_volume.argtypes = [texture_resources]

lib.cuda_stream_create.restype = cuda_stream_t
lib.cuda_stream_destroy.argtypes = [cuda_stream_t]
lib.cuda_stream_sync.argtypes = [cuda_stream_t]

lib.compute_grid_lower.argtypes = [
    c_void_p,
    c_float,
    c_float,
    c_void_p,
    c_int32,
    cuda_stream_t,
]

lib.compute_svd.argtypes = [
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_float,
    c_int32,
    cuda_stream_t,
]

lib.compute_svd_grad.argtypes = [
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,
    c_float,
    c_int32,
    cuda_stream_t,
]

lib.p2g.argtypes = [
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,

    ctypes.POINTER(ivec3),
    # ivec3,

    c_float,
    c_float,
    c_float,
    c_void_p,
    c_void_p,
    c_void_p,
    c_int32,
    cuda_stream_t,
]

lib.p2g_grad.argtypes = [
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,

    ctypes.POINTER(ivec3),
    # ivec3,

    c_float,
    c_float,
    c_float,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    c_int32,
    cuda_stream_t,
]

lib.grid_op_v2.argtypes = [c_void_p] * 11 + [c_float] * 4 + [c_void_p, ctypes.POINTER(ivec3), c_int32, cuda_stream_t]

lib.grid_op_v2_grad.argtypes = [c_void_p] * 11 + [c_void_p] * 6 + [c_float] * 4 + [c_void_p, c_void_p, ctypes.POINTER(ivec3), c_int32, cuda_stream_t]

lib.g2p.argtypes = [
    c_void_p,
    c_void_p,
    c_void_p,
    c_float,
    c_float,
    c_float,
    ctypes.POINTER(ivec3),
    c_void_p,
    c_float,
    c_void_p,
    c_void_p,
    c_int32,
    cuda_stream_t,
]

lib.g2p_grad.argtypes = [
    c_void_p,
    c_void_p,
    c_void_p,
    c_float,
    c_float,
    c_float,
    ctypes.POINTER(ivec3),
    c_void_p,
    c_float,
    c_void_p,
    c_void_p,
    c_int32,

    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,
    c_void_p,

    cuda_stream_t,
]

lib.render.argtypes = [c_void_p] * 13 + [c_float, ctypes.POINTER(ivec3), c_int32, c_bool, ctypes.POINTER(ivec3), c_int32, c_int32, c_float, c_int32, c_void_p, cuda_stream_t]

lib.particle_sdf.argtypes = [c_void_p] * 5 + [c_int32, ctypes.POINTER(ivec3), c_float] + [c_void_p] * 3 + [c_int32, cuda_stream_t]

lib.compute_dist.argtypes = [c_void_p] * 6 + [c_int32] + [c_void_p] * 4 + [c_int32, c_int32, cuda_stream_t]

lib.particle2mass.argtypes = [c_void_p] * 3 + [ctypes.POINTER(ivec3), c_float, c_float] + [c_void_p] * 4 + [c_int32, c_int32, c_int32, cuda_stream_t]

class array:
    def __init__(self, dtype=float32, length=0):
        assert length > 0
        if dtype == float:
            dtype = float32
        if dtype == int:
            dtype = int32
        self.dtype = dtype

        self.bytes = dtype.size
        self.nbytes = dtype.size * length
        self.data_ptr = lib.cuda_alloc(self.nbytes)

        shape = (length,)
        if dtype.length != 1:
            shape = shape + (dtype.length,)
        self.shape = shape

        self.zero()

    def upload_async(self, arr: np.ndarray, stream):
        # only for pos
        n = arr.shape[0]
        assert arr.shape[0] == self.shape[0]
        data_size = self.bytes * n

        assert self.dtype.np_type == arr.dtype
        assert self.shape == arr.shape
        assert self.nbytes == arr.nbytes
        assert arr.data.contiguous
        ptr = arr.__array_interface__["data"][0]
        lib.cuda_upload_async(self.data_ptr, ptr, data_size, stream)

    def upload(self, arr: np.ndarray, strict=False):
        arr = np.ascontiguousarray(arr, dtype=self.dtype.np_type)
        n = arr.shape[0]
        if strict:
            assert n == self.shape[0]
        assert n <= self.shape[0], f"{n} {self.shape[0]}"
        data_size = self.bytes * n

        assert self.dtype.np_type == arr.dtype, f"{self.dtype.np_type}, {arr.dtype}"
        assert (arr.shape[0],) + self.shape[1:] == arr.shape, f"{self.shape}, {arr.shape}"

        ptr = arr.__array_interface__["data"][0]
        lib.cuda_upload(self.data_ptr, ptr, data_size)

    def download(self, n=None, device='numpy', stream=None):
        if device != 'numpy':
            import torch
            x = self.download(n, 'numpy')
            return torch.tensor(x, device=device)

        if n is not None:
            shape = (n,) + self.shape[1:]
            data_size = self.bytes * n
        else:
            shape = self.shape
            data_size = self.nbytes
        #shape = (n,) + self.shape[1:] if n is not None else self.shape
        arr = np.empty(shape, self.dtype.np_type)
        ptr = arr.__array_interface__["data"][0]

        if stream is not None:
            lib.cuda_download(ptr, self.data_ptr, data_size)
        else:
            lib.cuda_download_async(ptr, self.data_ptr, data_size, stream)
        return arr

    """
    def download_async(self, stream):
        arr = np.empty(self.shape, self.dtype.np_type)
        ptr = arr.__array_interface__["data"][0]
        lib.cuda_download_async(ptr, self.data_ptr, self.nbytes, stream)
        return arr
    """

    def copy_to_torch(self, tensor):
        assert tensor.device.type == "cuda"
        assert tensor.is_contiguous()
        width = spitch = self.dtype.size
        dpitch = tensor.stride()[0] * tensor.element_size()
        height = self.nbytes // width
        lib.cuda_copy2d(tensor.data_ptr(), dpitch, self.data_ptr, spitch, width, height)

    def cuda_add(self, values, stream=None):
        # TODO: make it faster
        x = self.download(n=len(values), stream=stream)
        x += values
        self.upload(x, stream)

    def zero(self, stream=None):
        if stream is None:
            lib.cuda_zero(self.data_ptr, self.nbytes)
        else:
            lib.cuda_zero_async(self.data_ptr, self.nbytes, stream)

    def zero_async(self, stream):
        lib.cuda_zero_async(self.data_ptr, self.nbytes, stream)

    def __del__(self):
        lib.cuda_free(self.data_ptr)

    def __repr__(self):
        return self.download().__repr__()


import logging
import json

from flask import request, jsonify;

from cfg import app;

logger = logging.getLogger(__name__)

@app.route('/salad-spree', methods=['POST'])
def evaluate_salad():
    data = request.get_json()
    logging.info("data sent for evaluation {}".format(data))
    result = salad_spree(data.get("number_of_salads"), data.get("salad_prices_street_map"))
    logging.info("result : {}".format(result))

    return json.dumps({'result': int(result)})

def salad_spree(num, list_array):
    index = 0
    min_value = 0
    temp_value = 0
    for array in list_array:
        for elements in range(len(array)-num+1):
            index = 0
            temp_value = 0
            for loop in range(num):
                if array[elements+loop] != "X":
                    temp_value += int(array[elements+loop])
                else:
                    break
                index += 1

            if index == num and (min_value == 0 or min_value > temp_value):
                min_value = temp_value

    return min_value


import pygame
from pygame.rect import Rect
from pygame.gfxdraw import pie
from math import pi, sqrt
import numpy as np
from Constants.constants import *
# remove after
import matplotlib.pyplot as plt

class Scenario(object):
    def __init__(self, simulation, window, mapParameters, cars, initial):
        self.simulation = simulation
        self.window = window
        self.mapParameters = mapParameters
        self.cars = cars
        self.collision_array = None
        self.initial = initial
        self.cost_array = None
        self.n_players = simulation.number_players

    def  drawBackgroundImage(self):
        fundo = pygame.image.load('./Img/star.png')
        fundo = pygame.transform.scale(fundo, (SCREEN_WIDTH, SCREEN_HEIGHT))
        pista = pygame.image.load('./Img/pista.png')
        pista = pygame.transform.scale(pista, (SCREEN_WIDTH -200, SCREEN_HEIGHT))

        sensorPoint = pygame.image.load("./Img/luzAzul.png")
        sensorPoint = pygame.transform.scale(sensorPoint, (SENSOR_HEIGHT, SENSOR_HEIGHT))

        if self.initial == False:
            self.window.blit(fundo, (0,0))
        self.window.blit(pista, (200,0))

        # cars
        for i in range(self.n_players):
            self.cars[i] = pygame.transform.scale(self.cars[i], (CARS_HEIGHT, CARS_WIDTH))
            car_rotate = pygame.transform.rotate(self.cars[i], round(-self.simulation.player[i].pose.rotation * RAD2DEGREE)%360)
            burntCar = pygame.image.load("./Img/carroQueimado.png")
            burntCar = pygame.transform.scale(burntCar, (CARS_HEIGHT, CARS_WIDTH))
            x = M2PIX * self.simulation.player[i].pose.position.x
            y = M2PIX * self.simulation.player[i].pose.position.y
            # print(x, y)
            if self.initial == False:
                collide = self.simulation.player[i].bumper_state
                if collide == False:
                    if i == 0:
                        self.drawSensors(self.simulation.player[i].sensors, (x,y), sensorPoint)
                    self.window.blit(car_rotate, (x-car_rotate.get_rect().center[0], y-car_rotate.get_rect().center[1]))
                else:
                    # explosion = []
                    # if self.simulation.player[i].animationFrame != 45:
                    #     for j in range(1, 45):
                    #         explosion.append(pygame.image.load("./Img/explosion/exp (" + str(j) + ").png"))
                    #         explosion[j-1] = pygame.transform.scale(explosion[j-1], (200, 200))
                    burntCar = pygame.transform.rotate(burntCar, round(-self.simulation.player[i].pose.rotation * RAD2DEGREE)%360)
                    self.window.blit(burntCar, (x-burntCar.get_rect().center[0], y-burntCar.get_rect().center[1]))
                    # if self.simulation.player[i].animationFrame < 45:
                    #     # self.window.blit(explosion[self.simulation.player[i].animationFrame - 1], (x-100, y-100))
                    #     self.simulation.player[i].animationFrame += 1

        self.drawScore()
        windowScale = pygame.transform.scale(pygame.display.get_surface(), (SCREEN_WIDTH * self.mapParameters[0], SCREEN_HEIGHT * self.mapParameters[0]))
        self.window.fill((0,0,0))
        self.window.blit(windowScale, self.mapParameters[1])

    def drawSensors(self, sensors, centerPos, sensorPoint):
        if self.simulation.player[0].controllable != False:
            for i in range(N_SENSORS):
                pygame.draw.line(self.window, COLOR_SENSOR, sensors[i].distance()[0], centerPos, 1)
                center = sensors[i].distance()[0]
                self.window.blit(sensorPoint, (center[0] - SENSOR_HEIGHT/2, center[1] - SENSOR_HEIGHT/2))

    def drawScore(self):

        font = pygame.font.SysFont('Comic Sans MS', 30)
        generation = "Geração: " + str(self.simulation.generation)
        textsurface = font.render(generation, False, (255, 255, 255))
        self.window.blit(textsurface, (20,200))
        distance = "Melhor distância: "
        textsurface = font.render(distance, False, (255, 255, 255))
        self.window.blit(textsurface, (15,240))
        distance = str(self.simulation.better_distance * M2PIX) + " pix"
        textsurface = font.render(distance, False, (255, 255, 255))
        self.window.blit(textsurface, (100,265))

        if self.simulation.better_distance >= (INITIAL_DISTANCE - 2) * PIX2M:
            conclusion = "Eu aprendi a dirigir, Jony!"
            textsurface = font.render(conclusion, False, (255, 255, 255))
            self.window.blit(textsurface, (15,300))

    def matrixCollision(self):
        pxarray = pygame.PixelArray(self.window)
        array = np.array(pxarray, dtype="int32")
        for i in range(SCREEN_WIDTH):
            for j in range(SCREEN_HEIGHT):
                if array[i,j] < self.window.map_rgb((110,110,110)):
                    array[i, j] = 0
                elif  array[i,j] >= self.window.map_rgb((118,118,118)):
                    array[i, j] = 0
                else:
                    array[i,j] = 1
        # plt.matshow(array)
        # plt.show()
        self.collision_array = array
        self.cost_function()
        self.initial = False
        return array

    def cost_function(self):
        array = np.copy(self.collision_array)
        nodeArray = np.empty((SCREEN_WIDTH, SCREEN_HEIGHT), dtype=Node)

        # preparing array
        for i in range(SCREEN_WIDTH):
            for j in range(SCREEN_HEIGHT):
                if array[i,j] == 0:
                    nodeArray[i, j] = Node(i,j,-1)
                else:
                    nodeArray[i, j] = Node(i,j,-2)

        # queue of pixels
        queue = []
        # set zero for finish line
        initialPoint = FINISH_LINE[0]
        finishPoint = FINISH_LINE[1]
        for i in range(initialPoint[0], finishPoint[0] + 1):
            nodeArray[i, initialPoint[1]].setCost(0)
            queue.append(nodeArray[i, initialPoint[1]])

        while len(queue) != 0:
            node = queue.pop(0)
            # print(type(node.neighbor))
            for nodes in node.neighbor:
                if nodeArray[nodes].cost == -2:
                    queue.append(nodeArray[nodes])
                    nodeArray[nodes].setCost(node.cost + 1)

        for i in range(SCREEN_WIDTH):
            for j in range(SCREEN_HEIGHT):
                array[i, j] = nodeArray[i,j].cost

        self.cost_array = array
        # plt.matshow(array)
        # plt.show()
        self.simulation.resetTime()

class Node(object):

    def __init__(self, i, j, cost):

        self.i = i
        self.j = j
        self.cost = cost
        self.neighbor = self.getNeighbor()

    def setCost(self, cost):

        self.cost = cost

    def getNeighbor(self):
        neighbor = []
        for di in range(-1,2):
            for dj in range(-1,2):
                if self.is_index_valid(self.i+di, self.j+dj) and (di != 0 or dj != 0):
                    neighbor.append((self.i+di, self.j+dj))

        return neighbor

    def is_index_valid(self, i, j):
        return 0 <= i < SCREEN_WIDTH and 0 <= j < SCREEN_HEIGHT


"""
Setups the environment for tests.
Import this module to have the side effect
that the project root dir will be added to ``sys.path``,
i.e. ``import preloaded`` works afterwards.
In the test code, you would have this::

    import _setup_test_env  # noqa

The ``# noqa`` is to ignore the warning that this module is not used.
See :func:`setup` below for details.
"""

def setup():
    """
    Calls necessary setups.
    """
    import logging
    import os
    import sys

    my_dir = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
    root_dir = os.path.dirname(my_dir)
    sys.path.insert(0, root_dir)

    # Enable all logging, up to debug level.
    logging.basicConfig(level=logging.DEBUG, format='%(message)s')

    try:
        # noinspection PyUnresolvedReferences
        import better_exchook
        better_exchook.install()
        better_exchook.replace_traceback_format_tb()
    except ImportError:
        print("no better_exchook")

    import preloaded
    assert preloaded.__file__.startswith(root_dir)

    try:
        # noinspection PyUnresolvedReferences
        import faulthandler
        # Enable after libSigSegfault, so that we have both,
        # because faulthandler will also call the original sig handler.
        faulthandler.enable()
    except ImportError:
        print("no faulthandler")

    _try_hook_into_tests()

def _try_hook_into_tests():
    """
    Hook into nosetests or other unittest based frameworks.

    The hook will throw exceptions such that a debugger like PyCharm can inspect them easily.
    This will only be done if there is just a single test case.

    This code might be a bit experimental.
    It should work though. But if it does not, we can also skip this.
    Currently any exception here would be fatal though, as we expect this to work.

    Also see: https://youtrack.jetbrains.com/issue/PY-9848
    """
    import sys
    get_trace = getattr(sys, "gettrace", None)
    in_debugger = False
    if get_trace and get_trace() is not None:
        in_debugger = True

    # get TestProgram instance from stack...
    from unittest import TestProgram
    # noinspection PyProtectedMember,PyUnresolvedReferences
    top_frame = sys._getframe(1)
    if not top_frame:
        # This will not always work. Just silently accept this. This should be rare.
        return

    test_program = None
    frame = top_frame
    while frame:
        local_self = frame.f_locals.get("self")
        if isinstance(local_self, TestProgram):
            test_program = local_self
            break
        frame = frame.f_back

    test_names = None
    if test_program:  # nosetest, unittest
        test_names = getattr(test_program, "testNames")

    test_session = None
    try:
        # noinspection PyPackageRequirements,PyUnresolvedReferences
        import pytest
    except ImportError:
        pass
    else:
        frame = top_frame
        while frame:
            local_self = frame.f_locals.get("self")
            if isinstance(local_self, pytest.Session):
                test_session = local_self
                break
            frame = frame.f_back
        if test_session and not test_names:
            test_names = test_session.config.args

    if not test_names:
        # Unexpected, but just silently ignore.
        return
    if len(test_names) >= 2 or ":" not in test_names[0]:
        # Multiple tests are being run. Do not hook into this.
        # We only want to install the hook if there is only a single test case.
        return

    # Skip this if we are not in a debugger.
    if test_program and in_debugger:  # nosetest, unittest

        # Ok, try to install our plugin.
        class _ReraiseExceptionTestHookPlugin:
            @staticmethod
            def _reraise_exception(test, err):
                exc_class, exc, tb = err
                print("Test %s, exception %s %s, reraise now." % (test, exc_class.__name__, exc))
                raise exc

            handleFailure = _reraise_exception
            handleError = _reraise_exception

        config = getattr(test_program, "config")
        config.plugins.addPlugin(_ReraiseExceptionTestHookPlugin())

setup()


from __future__ import absolute_import, print_function

import json
from copy import deepcopy
from functools import partial

from flask import Blueprint, abort, current_app, make_response, request, \
    url_for
from invenio_db import db
from invenio_oauth2server import require_api_auth, require_oauth_scopes
from invenio_pidstore.errors import PIDInvalidAction
from invenio_records_rest.utils import obj_or_import_string
from invenio_records_rest.views import \
    create_error_handlers as records_rest_error_handlers
from invenio_records_rest.views import \
    create_url_rules as records_rest_url_rules
from invenio_records_rest.views import need_record_permission, pass_record
from invenio_rest import ContentNegotiatedMethodView
from invenio_rest.views import create_api_errorhandler
from webargs import fields
from webargs.flaskparser import use_kwargs
from werkzeug.utils import secure_filename

from ..api import Deposit
from ..errors import FileAlreadyExists, WrongFile
from ..scopes import write_scope
from ..search import DepositSearch
from ..signals import post_action
from ..utils import extract_actions_from_class

def create_error_handlers(blueprint):
    """Create error handlers on blueprint."""
    blueprint.errorhandler(PIDInvalidAction)(create_api_errorhandler(
        status=403, message='Invalid action'
    ))
    records_rest_error_handlers(blueprint)

def create_blueprint(endpoints):
    """Create Invenio-Deposit-REST blueprint.

    See: :data:`invenio_deposit.config.DEPOSIT_REST_ENDPOINTS`.

    :param endpoints: List of endpoints configuration.
    :returns: The configured blueprint.
    """
    blueprint = Blueprint(
        'invenio_deposit_rest',
        __name__,
        url_prefix='',
    )
    create_error_handlers(blueprint)

    for endpoint, options in (endpoints or {}).items():
        options = deepcopy(options)

        if 'files_serializers' in options:
            files_serializers = options.get('files_serializers')
            files_serializers = {mime: obj_or_import_string(func)
                                 for mime, func in files_serializers.items()}
            del options['files_serializers']
        else:
            files_serializers = {}

        if 'record_serializers' in options:
            serializers = options.get('record_serializers')
            serializers = {mime: obj_or_import_string(func)
                           for mime, func in serializers.items()}
        else:
            serializers = {}

        file_list_route = options.pop(
            'file_list_route',
            '{0}/files'.format(options['item_route'])
        )
        file_item_route = options.pop(
            'file_item_route',
            '{0}/files/<path:key>'.format(options['item_route'])
        )

        options.setdefault('search_class', DepositSearch)
        search_class = obj_or_import_string(options['search_class'])

        # records rest endpoints will use the deposit class as record class
        options.setdefault('record_class', Deposit)
        record_class = obj_or_import_string(options['record_class'])

        # backward compatibility for indexer class
        options.setdefault('indexer_class', None)

        for rule in records_rest_url_rules(endpoint, **options):
            blueprint.add_url_rule(**rule)

        search_class_kwargs = {}
        if options.get('search_index'):
            search_class_kwargs['index'] = options['search_index']

        if options.get('search_type'):
            search_class_kwargs['doc_type'] = options['search_type']

        ctx = dict(
            read_permission_factory=obj_or_import_string(
                options.get('read_permission_factory_imp')
            ),
            create_permission_factory=obj_or_import_string(
                options.get('create_permission_factory_imp')
            ),
            update_permission_factory=obj_or_import_string(
                options.get('update_permission_factory_imp')
            ),
            delete_permission_factory=obj_or_import_string(
                options.get('delete_permission_factory_imp')
            ),
            record_class=record_class,
            search_class=partial(search_class, **search_class_kwargs),
            default_media_type=options.get('default_media_type'),
        )

        deposit_actions = DepositActionResource.as_view(
            DepositActionResource.view_name.format(endpoint),
            serializers=serializers,
            pid_type=options['pid_type'],
            ctx=ctx,
        )

        blueprint.add_url_rule(
            '{0}/actions/<any({1}):action>'.format(
                options['item_route'],
                ','.join(extract_actions_from_class(record_class)),
            ),
            view_func=deposit_actions,
            methods=['POST'],
        )

        deposit_files = DepositFilesResource.as_view(
            DepositFilesResource.view_name.format(endpoint),
            serializers=files_serializers,
            pid_type=options['pid_type'],
            ctx=ctx,
        )

        blueprint.add_url_rule(
            file_list_route,
            view_func=deposit_files,
            methods=['GET', 'POST', 'PUT'],
        )

        deposit_file = DepositFileResource.as_view(
            DepositFileResource.view_name.format(endpoint),
            serializers=files_serializers,
            pid_type=options['pid_type'],
            ctx=ctx,
        )

        blueprint.add_url_rule(
            file_item_route,
            view_func=deposit_file,
            methods=['GET', 'PUT', 'DELETE'],
        )
    return blueprint

class DepositActionResource(ContentNegotiatedMethodView):
    """Deposit action resource."""

    view_name = '{0}_actions'

    def __init__(self, serializers, pid_type, ctx, *args, **kwargs):
        """Constructor."""
        super(DepositActionResource, self).__init__(
            serializers,
            default_media_type=ctx.get('default_media_type'),
            *args,
            **kwargs
        )
        for key, value in ctx.items():
            setattr(self, key, value)

    @pass_record
    @need_record_permission('update_permission_factory')
    def post(self, pid, record, action):
        """Handle deposit action.

        After the action is executed, a
        :class:`invenio_deposit.signals.post_action` signal is sent.

        Permission required: `update_permission_factory`.

        :param pid: Pid object (from url).
        :param record: Record object resolved from the pid.
        :param action: The action to execute.
        """
        record = getattr(record, action)(pid=pid)

        db.session.commit()
        # Refresh the PID and record metadata
        db.session.refresh(pid)
        db.session.refresh(record.model)
        post_action.send(current_app._get_current_object(), action=action,
                         pid=pid, deposit=record)
        response = self.make_response(pid, record,
                                      202 if action == 'publish' else 201)
        endpoint = '.{0}_item'.format(pid.pid_type)
        location = url_for(endpoint, pid_value=pid.pid_value, _external=True)
        response.headers.extend(dict(Location=location))
        return response

class DepositFilesResource(ContentNegotiatedMethodView):
    """Deposit files resource."""

    view_name = '{0}_files'

    def __init__(self, serializers, pid_type, ctx, *args, **kwargs):
        """Constructor."""
        super(DepositFilesResource, self).__init__(
            serializers,
            *args,
            **kwargs
        )
        for key, value in ctx.items():
            setattr(self, key, value)

    @pass_record
    @need_record_permission('read_permission_factory')
    def get(self, pid, record):
        """Get files.

        Permission required: `read_permission_factory`.

        :param pid: Pid object (from url).
        :param record: Record object resolved from the pid.
        :returns: The files.
        """
        return self.make_response(obj=record.files, pid=pid, record=record)

    @require_api_auth()
    @require_oauth_scopes(write_scope.id)
    @pass_record
    @need_record_permission('update_permission_factory')
    def post(self, pid, record):
        """Handle POST deposit files.

        Permission required: `update_permission_factory`.

        :param pid: Pid object (from url).
        :param record: Record object resolved from the pid.
        """
        # load the file
        uploaded_file = request.files['file']
        # file name
        key = secure_filename(
            request.form.get('name') or uploaded_file.filename
        )
        # check if already exists a file with this name
        if key in record.files:
            raise FileAlreadyExists()
        # add it to the deposit
        record.files[key] = uploaded_file.stream
        record.commit()
        db.session.commit()
        return self.make_response(
            obj=record.files[key].obj, pid=pid, record=record, status=201)

    @require_api_auth()
    @require_oauth_scopes(write_scope.id)
    @pass_record
    @need_record_permission('update_permission_factory')
    def put(self, pid, record):
        """Handle the sort of the files through the PUT deposit files.

        Expected input in body PUT:

        .. code-block:: javascript

            [
                {
                    "id": 1
                },
                {
                    "id": 2
                },
                ...
            }

        Permission required: `update_permission_factory`.

        :param pid: Pid object (from url).
        :param record: Record object resolved from the pid.
        :returns: The files.
        """
        try:
            ids = [data['id'] for data in json.loads(
                request.data.decode('utf-8'))]
        except KeyError:
            raise WrongFile()

        record.files.sort_by(*ids)
        record.commit()
        db.session.commit()
        return self.make_response(obj=record.files, pid=pid, record=record)

class DepositFileResource(ContentNegotiatedMethodView):
    """Deposit files resource."""

    view_name = '{0}_file'

    get_args = dict(
        version_id=fields.UUID(
            location='headers',
            load_from='version_id',
        ),
    )
    """GET query arguments."""

    def __init__(self, serializers, pid_type, ctx, *args, **kwargs):
        """Constructor."""
        super(DepositFileResource, self).__init__(
            serializers,
            *args,
            **kwargs
        )
        for key, value in ctx.items():
            setattr(self, key, value)

    @use_kwargs(get_args)
    @pass_record
    @need_record_permission('read_permission_factory')
    def get(self, pid, record, key, version_id=None, **kwargs):
        """Get file.

        Permission required: `read_permission_factory`.

        :param pid: Pid object (from url).
        :param record: Record object resolved from the pid.
        :param key: Unique identifier for the file in the deposit.
        :param version_id: File version. Optional. If no version is provided,
            the last version is retrieved.
        :returns: the file content.
        """
        try:
            obj = record.files[str(key)].get_version(version_id=version_id)
            return self.make_response(
                obj=obj or abort(404), pid=pid, record=record)
        except KeyError:
            abort(404)

    @require_api_auth()
    @require_oauth_scopes(write_scope.id)
    @pass_record
    @need_record_permission('update_permission_factory')
    def put(self, pid, record, key):
        """Handle the file rename through the PUT deposit file.

        Permission required: `update_permission_factory`.

        :param pid: Pid object (from url).
        :param record: Record object resolved from the pid.
        :param key: Unique identifier for the file in the deposit.
        """
        try:
            data = json.loads(request.data.decode('utf-8'))
            new_key = data['filename']
        except KeyError:
            raise WrongFile()
        new_key_secure = secure_filename(new_key)
        if not new_key_secure or new_key != new_key_secure:
            raise WrongFile()
        try:
            obj = record.files.rename(str(key), new_key_secure)
        except KeyError:
            abort(404)
        record.commit()
        db.session.commit()
        return self.make_response(obj=obj, pid=pid, record=record)

    @require_api_auth()
    @require_oauth_scopes(write_scope.id)
    @pass_record
    @need_record_permission('update_permission_factory')
    def delete(self, pid, record, key):
        """Handle DELETE deposit file.

        Permission required: `update_permission_factory`.

        :param pid: Pid object (from url).
        :param record: Record object resolved from the pid.
        :param key: Unique identifier for the file in the deposit.
        """
        try:
            del record.files[str(key)]
            record.commit()
            db.session.commit()
            return make_response('', 204)
        except KeyError:
            abort(404, 'The specified object does not exist or has already '
                  'been deleted.')