# valores_dict: dicionário com valores de:
	# 'capacidade': int
	# 'Pessoas': int
	# # 'CO2': float
	# 'Temperatura': float
	# 'Umidade': float
# return: nível de risco, 'baixo', 'medio', 'alto'.
def calcula_risco(valores_dict):
	co2 = valores_dict['CO2']
	pessoas = valores_dict['Pessoas']
	capacidade = valores_dict['capacidade']

	if co2 >= 1000: return 'alto'
	else:
		if pessoas > (2.0/3.0)*capacidade: return 'medio'
		else:
			if co2 > 400 and pessoas >= capacidade/2.0: return 'medio'
			else: return 'baixo'

# nome_instalacao: string
# return: dicionário com valores de:
	# 'capacidade': float
	# 'Pessoas': float
	# # 'CO2': float
	# 'Temperatura': float
	# 'Umidade': float
def get_ultimas_medicoes(conn, nome_instalacao=""):
	with conn.cursor() as cur:
		query = """SELECT i.nome, m."tipoDado", m.valor, i."capacidadePessoas" FROM medicao m
					JOIN instalacao i ON m."idInstalacao" = i.id
				WHERE m."ultimaMedicao" = TRUE"""
		where = " AND i.nome = %(nome)s" if nome_instalacao else ""

		params = {'nome': nome_instalacao}
		cur.execute(query + where, params)
		dados = cur.fetchall()

	dadosDict = {}
	for dado in dados:
		agrupa_medidas_por_sala(dadosDict, dado['nome'], dado['capacidadePessoas'], dado['tipoDado'], dado['valor'])
	return dadosDict

# medidasSala: dicionário
# nome: nome da instalação, string
# capacidade: capacidade de cada instalação, int
# medida: tipo da medida, string
# valor: valor de cada medição, float
def agrupa_medidas_por_sala(medidasSala, nome, capacidade, medida, valor):
	if nome not in medidasSala:
		medidaDict = {'capacidade': capacidade}
		medidasSala[nome] = medidaDict
	medidasSala[nome][medida] = valor

# return: dicionário com a quantidade de cada tipo de risco encontrado no banco
def get_count_salas_risco_all(conn):
	risco = {'baixo': 0, 'medio': 0, 'alto': 0}
	ultimasMedicoes = get_ultimas_medicoes(conn)
	for medicao in ultimasMedicoes.values():
		risco[calcula_risco(medicao)] += 1

	return risco

# risco: string, pode ser 'baixo', 'medio' ou 'alto'
# return: quantidade de salas com o risco especificado
def get_count_salas_risco(conn, risco):
	qtdSalasRisco = 0
	ultimasMedicoes = get_ultimas_medicoes(conn)
	for medicao in ultimasMedicoes.values():
		if calcula_risco(medicao) == risco:
			qtdSalasRisco += 1

	return qtdSalasRisco

# return: quantidade de salas com risco baixo
def get_count_salas_baixo_risco(conn):
	return get_count_salas_risco(conn, 'baixo')

# return: quantidade de salas com risco medio
def get_count_salas_medio_risco(conn):
	return get_count_salas_risco(conn, 'medio')

# return: quantidade de salas com risco alto
def get_count_salas_alto_risco(conn):
	return get_count_salas_risco(conn, 'alto')

def get_count_salas_disponiveis_pra_uso(conn):
	riscoDict = get_count_salas_risco_all(conn)
	return riscoDict['baixo'] + riscoDict['medio']


import functools

class LogDecorator:
    def __init__(self, logger, message=None):
        self.logger = logger
        self.message = message

    def __call__(self, fn):
        @functools.wraps(fn)
        def decorated(*args, **kwargs):
            try:
                message = self.message if self.message else fn.__qualname__
                self.logger.debug(f"Starting: {message} ({args},{kwargs})")
                result = fn(*args, **kwargs)
                self.logger.debug(f"Finished: {message}.")
                return result
            except Exception as ex:
                self.logger.debug(f"Exception {ex}")
                raise

        return decorated


from __future__ import annotations

from pathlib import Path

from click.testing import CliRunner, Result

from cdv.cmds.cli import cli

class TestCdvCommands:
    def test_encode_decode(self):
        runner = CliRunner()
        puzhash: str = "3d4237d9383a7b6e60d1bfe551139ec2d6e5468205bf179ed381e66bed7b9788"

        # Without prefix
        result: Result = runner.invoke(cli, ["encode", puzhash])
        address: str = "xch184pr0kfc8fakucx3hlj4zyu7cttw235zqkl308kns8nxhmtmj7yqxsnauc"
        assert result.exit_code == 0
        assert address in result.output
        result = runner.invoke(cli, ["decode", address])
        assert result.exit_code == 0
        assert puzhash in result.output

        # With prefix
        result = runner.invoke(cli, ["encode", puzhash, "--prefix", "txch"])
        test_address: str = "txch184pr0kfc8fakucx3hlj4zyu7cttw235zqkl308kns8nxhmtmj7yqth5tat"
        assert result.exit_code == 0
        assert test_address in result.output
        result = runner.invoke(cli, ["decode", test_address])
        assert result.exit_code == 0
        assert puzhash in result.output

    def test_hash(self):
        runner = CliRunner()
        str_msg: str = "chia"
        b_msg: str = "0xcafef00d"

        result: Result = runner.invoke(cli, ["hash", str_msg])
        assert result.exit_code == 0
        assert "3d4237d9383a7b6e60d1bfe551139ec2d6e5468205bf179ed381e66bed7b9788" in result.output
        result = runner.invoke(cli, ["hash", b_msg])
        assert result.exit_code == 0
        assert "8f6e594e007ca1a1676ef64469c58f7ece8cddc9deae0faf66fbce2466519ebd" in result.output

    def test_test(self):
        runner = CliRunner()
        with runner.isolated_filesystem():
            result: Result = runner.invoke(cli, ["test", "--init"])
            assert result.exit_code == 0
            assert Path("./tests").exists() and Path("./tests/test_skeleton.py").exists()

            # 2023-10-17 Commenting subsequent tests because pytest throws an import file mismatch error
            # It seems that the test_skeleton module is being imported from the test enviroment but is
            # also present in the tests directory, causing the mismatch.
            # This repo has a tool (build-init-files.py) for creating missing __init__ files which may
            # have been intended as a solution to this problem, but as of now it doesn't work.

            # result = runner.invoke(cli, ["test", "--discover"])
            # assert result.exit_code == 0
            # assert "TestSomething" in result.output

            # result = runner.invoke(cli, ["test"])
            # assert result.exit_code == 0
            # assert "test_skeleton.py ." in result.output


import sys,os

prefix = sys.argv[1]
wd=sys.argv[2]
if os.getcwd() != wd:
    os.chdir(wd)

fp = open(prefix + '.fa','r')
query_seq = ''
for line in fp:
    if line[0] != '>':
        query_seq += line[:-1]
fp.close()
qlen = len(query_seq)

fp = open(prefix + '.foldseek', 'r')
hits = []
for line in fp:
    words = line.split()
    dnum = words[1].split('.')[0]
    qstart = int(words[6])
    qend = int(words[7])
    qresids = set([])
    for qres in range(qstart, qend + 1):
        qresids.add(qres)
    evalue = float(words[10])
    hits.append([dnum, evalue, qstart, qend, qresids])
fp.close()
hits.sort(key = lambda x:x[1])

qres2count = {}
for res in range(1, qlen + 1):
    qres2count[res] = 0

rp = open(prefix + '.foldseek.flt.result', 'w')
rp.write('ecodnum\tevalue\trange\n')
for hit in hits:
    dnum = hit[0]
    evalue = hit[1]
    qstart = hit[2]
    qend = hit[3]
    qresids = hit[4]
    for res in qresids:
        qres2count[res] += 1
    good_res = 0
    for res in qresids:
        if qres2count[res] <= 100:
            good_res += 1
    if good_res >= 10:
        rp.write(dnum + '\t' + str(evalue) + '\t' + str(qstart) + '-' + str(qend) + '\n')
rp.close()


import tensorflow as tf
import numpy as np

#1:
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)

#2: crate a 2D input with 2 channels
A = np.array([[[1, 2],           # 0-channel
               [3, 4]],
              [[1, 2],           # 1-channel
               [3, 4]]], dtype = 'float32')
##print("A.shape", A.shape)         # (channels, rows, cols) = (2, 2, 2)
A = np.transpose(A, (1, 2, 0))      # (rows, cols, channels) = (2, 2, 2)
A= np.expand_dims(A, axis = 0)      # (batch,rows, cols, channels)=(1, 2, 2, 2)

#3: kernel with 2-channels
W = np.array([[[1, -1],           # 0-channel
               [2, -2]],
              [[1, -1],           # 1-channel
               [2, -2]]], dtype = 'float32')
##print("W.shape", W.shape)         # (channels, rows, cols) = (2, 2, 2)
W = np.transpose(W, (1, 2, 0))      # (rows, cols, channels) = (2, 2, 2)
W= np.expand_dims(W, axis = 2)      # (rows, cols, filters, channels) = (2, 2, 1, 2)

#4: build a model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Input(A.shape[1:])) # shape = (2, 2, 2)
model.add(tf.keras.layers.Conv2DTranspose(filters=1,
                                 kernel_size = (2, 2),
                                 strides = (2, 2),
                                 padding = 'valid', # 'same
                                 use_bias = False,
                                 kernel_initializer = tf.constant_initializer(W)))
model.summary()

#5: apply A to model
B = model.predict(A)     # (batch, new_rows, new_cols, filters)
print("B.shape=", B.shape)
print("B[0,:,:,0]=\n", B[0,:,:,0])


# coding:utf-8

friuts = ['apple','banana','orange']

#result是一个可迭代的对象
result = filter(lambda x: 'e' in x,friuts)
print(list(result))
# 上面使用过了，在内存中就会销毁，所以下面的不会执行
for i in result:
    print(i)

print('-----------------------')

def filter_func(item):
    if 'e' in item:
        return True

filter_result = filter(filter_func,friuts)

for i in filter_result:
    print(i)

map_result = map(filter_func,friuts)
print(list(map_result))
# [True, None, True]
# 由于第二个不含e

from functools import reduce
# 累加
add_result = reduce(lambda x,y:x+y,[0,1,2,3,4,5])
# 累乘
multip_result = reduce(lambda x,y:x*y,[1,2,3,4,5])
print(add_result) # 15
print(multip_result)

# 字符串累加
add_result_str = reduce(lambda x,y:x+y,friuts)
# 字符串累乘 报错
# multip_result_str = reduce(lambda x,y:x*y,friuts)
# print(multip_result_str)

11.高阶函数练习.py


# This can be used,
#    $ python asgi_h11_server.py localhost 5009
# and tested,
#    $ curl -v localhost:5009

import asyncio
import sys

import h11

from echo_app import app

async def asgi_server(reader, writer):
    connection = h11.Connection(h11.SERVER)
    to_app = asyncio.Queue()
    from_app = asyncio.Queue()
    scope = None
    complete = False
    while not complete and not reader.at_eof():
        connection.receive_data(await reader.read(100))
        while True:
           event = connection.next_event()
           if isinstance(event, h11.Request):
               scope = create_scope(event)
           elif isinstance(event, h11.Data):
              await to_app.put(create_message(event))
           elif isinstance(event, h11.EndOfMessage):
              await to_app.put(create_message(event))
              complete = True
              break
           elif isinstance(event, h11.ConnectionClosed):
               complete = True
               break
           elif event is h11.NEED_DATA:
               break
    await app(scope, to_app.get, from_app.put)
    while True:
        message = await from_app.get()
        if message["type"] == "http.response.start":
            writer.write(
                connection.send(
                    h11.Response(status_code=message["status"], headers=message["headers"])
                )
            )
        elif message["type"] == "http.response.body":
            writer.write(connection.send(h11.Data(data=message.get("body", b""))))
            if not message.get("more_body", False):
                writer.write(connection.send(h11.EndOfMessage()))
                break
    await writer.drain()
    writer.close()

def create_scope(request):
    return {
        "type": "http",
        "method": request.method.decode(),
        "scheme": "http",
        "raw_path": request.target,
        "path": request.target.decode(),
        "headers": request.headers,
    }

def create_message(event):
    if isinstance(event, h11.EndOfMessage):
        return {
            "type": "http.request",
            "more_body": False,
        }
    elif isinstance(event, h11.Data):
        return {
            "type": "http.request",
            "body": event.data,
            "more_body": True,
        }

async def main(host, port):
    server = await asyncio.start_server(asgi_server, host, port)
    await server.serve_forever()

if __name__ == "__main__":
    host, port = sys.argv[1], sys.argv[2]
    asyncio.run(main(host, port))


import pyttsx3
import pyaudio
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
from random import randint

engine = pyttsx3.init('sapi5')
voice = engine.getProperty('voices')
# print(voice)
engine.setProperty('voice', voice[1].id)
engine.setProperty('rate', 150)

# Making the speak function so that our Jarvis can speak
def speak(text, pr=1):
    if pr==1:
        print(text)
    engine.say(text)
    engine.runAndWait()
# speak('Hello World')

def wish():
    date = datetime.datetime.now().hour
    # print(date)
    if date<12:
        speak('Good Morning sir.')
    elif date<18:
        speak('Good Afternoon sir.')
    elif date<24:
        speak('Good Evening sir.')
    speak("I am Jarvis. How may I help you?")

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Listening...')
        # r.pause_threshold = 1
        audio = r.listen(source)
    try:
        print('Recognizing...')
        query = r.recognize_google(audio, language='en-us')
        print(f'User said : {query}')
    except Exception as e:
        print('Say that again please...')
        return 'None'
    return query

if __name__ == "__main__":
    wish()

    # Wring the logic of the program
    while True:
        query = takeCommand().lower()
        if 'tell me' in query or 'wikipedia' in query:
            speak('Searching in wikipedia...')
            query = query.replace('tell me', '')
            try:
                results = wikipedia.summary(query, sentences=5)
                speak(f'\nAccroding to wikipedia, {results}')
            except Exception as e:
                speak("Sorry, couldn't find any result..")

        elif 'search in google' in query or  'google search' in query or 'search google' in query or 'google search' in query  :
            speak('What should I search for you...')
            googleSearchQuery = takeCommand().lower()
            if googleSearchQuery != 'none':
                speak('Searching in google about this topic...')
                webbrowser.open(f"https://www.google.com/search?q={googleSearchQuery}")

        elif 'open google' in query or 'go to google' in query:
            speak('Opening Google')
            webbrowser.open('https://google.com/')

        elif 'open facebook' in query or 'go to facebook' in query:
            speak('Opening Facebook')
            webbrowser.open('https://facebook.com/')

        elif 'open stack overflow' in query or 'go to stack overflow' in query:
            speak('Opening Stackoverflow')
            webbrowser.open('https://stackoverflow.com/')
        elif 'open git hub' in query or 'go to git hub' in query or 'git hub' in query:
            speak('Opening Github')
            webbrowser.open('https://github.com/')

        elif 'open youtube' in query or 'go to youtube' in query:
            speak('Opening Youtube')
            webbrowser.open('https://youtube.com/')

        elif 'open code with harry' in query or 'go to code with harry' in query or 'code with harry' in query:
            speak('Opening Your Favourate Channel')
            webbrowser.open('https://youtube.com/')

        elif 'open messenger' in query or 'go to messenger' in query:
            speak('Opening Messenger')
            webbrowser.open('https://www.facebook.com/messages/')

        elif "open fn's club" in query or "go to fn's club" in query or "fn's club" in query or "club" in query:
            speak("Opening Fn'sclub")
            webbrowser.open('https://club.fnsoftwares.com/')

        elif 'open google activity' in query or 'google activity' in query or 'open my activity' in query or 'my activity.google' in query or 'my activity.google.com' in query or 'my activity' in query or 'check my google activity' in query :
            speak('Opening Your ')
            webbrowser.open('https://myactivity.google.com/')

        elif   "go now" in query or "ok stop now" in query or "ok stop" in query or "stop" in query or  "you can stop" in query or "stop now" in query:
            speak('Thank you sir.\nCall me anytime you need.')
            exit()

        else:
            n = randint(1, 5)
            if n == 1:
                speak("Sir, should I stop?")
            elif n == 2:
                speak("Sir, what should I do now?")
            elif n == 2:
                speak("Sir, should I do anything more?")
            elif n == 3:
                speak("What else I have to do sir?")
            elif n == 4:
                speak("Anything else sir?")
            elif n == 5:
                speak("Please give me an order sir")
            elif n == 6:
                speak("Sir, Should I go now?")

# https://www.google.com/search?q=myactivity


from collections import defaultdict
import os, sys, traceback, uuid
import logging
from arelle import UrlUtil, XmlUtil, ModelValue, XbrlConst, XmlValidate
from arelle.FileSource import FileNamedStringIO
from arelle.ModelObject import ModelObject
from arelle.Locale import format_string
from arelle.PrototypeInstanceObject import FactPrototype
from arelle.ValidateXbrlDimensions import isFactDimensionallyValid
ModelRelationshipSet = None # dynamic import

AUTO_LOCATE_ELEMENT = '771407c0-1d0c-11e1-be5e-028037ec0200' # singleton meaning choose best location for new element

def load(modelManager, url, nextaction=None, base=None, useFileSource=None):
    if nextaction is None: nextaction = _("loading")
    from arelle import (ModelDocument, FileSource)
    modelXbrl = create(modelManager)
    if useFileSource is not None:
        modelXbrl.fileSource = useFileSource
        modelXbrl.closeFileSource = False
        url = url
    elif isinstance(url,FileSource.FileSource):
        modelXbrl.fileSource = url
        modelXbrl.closeFileSource= True
        url = modelXbrl.fileSource.url
    else:
        modelXbrl.fileSource = FileSource.FileSource(url)
        modelXbrl.closeFileSource= True
    modelXbrl.modelDocument = ModelDocument.load(modelXbrl, url, base, isEntry=True)
    del modelXbrl.entryLoadingUrl
    if modelXbrl.modelDocument is not None and modelXbrl.modelDocument.type < ModelDocument.Type.DTSENTRIES:
        # at this point DTS is fully discovered but schemaLocated xsd's are not yet loaded
        modelDocumentsSchemaLocated = set()
        while True: # need this logic because each new pass may add new urlDocs
            modelDocuments = set(modelXbrl.urlDocs.values()) - modelDocumentsSchemaLocated
            if not modelDocuments:
                break
            modelDocument = modelDocuments.pop()
            modelDocumentsSchemaLocated.add(modelDocument)
            modelDocument.loadSchemalocatedSchemas()

    #from arelle import XmlValidate
    #uncomment for trial use of lxml xml schema validation of entry document
    #XmlValidate.xmlValidate(modelXbrl.modelDocument)
    modelManager.cntlr.webCache.saveUrlCheckTimes()
    modelManager.showStatus(_("xbrl loading finished, {0}...").format(nextaction))
    return modelXbrl

def create(modelManager, newDocumentType=None, url=None, schemaRefs=None, createModelDocument=True, isEntry=False):
    from arelle import (ModelDocument, FileSource)
    modelXbrl = ModelXbrl(modelManager)
    modelXbrl.locale = modelManager.locale
    if newDocumentType:
        modelXbrl.fileSource = FileSource.FileSource(url) # url may be an open file handle, use str(url) below
        modelXbrl.closeFileSource= True
        if createModelDocument:
            modelXbrl.modelDocument = ModelDocument.create(modelXbrl, newDocumentType, str(url), schemaRefs=schemaRefs, isEntry=isEntry)
            if isEntry:
                del modelXbrl.entryLoadingUrl
    return modelXbrl

class ModelXbrl:

    def __init__(self, modelManager):
        self.modelManager = modelManager
        self.init()

    def init(self, keepViews=False):
        self.uuid = uuid.uuid1().urn
        self.namespaceDocs = defaultdict(list)
        self.urlDocs = {}
        self.errors = []
        self.logCountErr = 0
        self.logCountWrn = 0
        self.logCountInfo = 0
        self.arcroleTypes = defaultdict(list)
        self.roleTypes = defaultdict(list)
        self.qnameConcepts = {} # indexed by qname of element
        self.nameConcepts = defaultdict(list) # contains ModelConcepts by name
        self.qnameAttributes = {}
        self.qnameAttributeGroups = {}
        self.qnameGroupDefinitions = {}
        self.qnameTypes = {} # contains ModelTypes by qname key of type
        self.baseSets = defaultdict(list) # contains ModelLinks for keys arcrole, arcrole#linkrole
        self.relationshipSets = {} # contains ModelRelationshipSets by bas set keys
        self.qnameDimensionDefaults = {} # contains qname of dimension (index) and default member(value)
        self.facts = []
        self.factsInInstance = []
        self.contexts = {}
        self.units = {}
        self.modelObjects = []
        self.qnameParameters = {}
        self.modelVariableSets = set()
        self.modelCustomFunctionSignatures = {}
        self.modelCustomFunctionImplementations = set()
        if not keepViews:
            self.views = []
        self.langs = {self.modelManager.defaultLang}
        from arelle.XbrlConst import standardLabel
        self.labelroles = {standardLabel}
        self.hasXDT = False
        self.hasTableRendering = False
        self.hasFormulae = False
        self.formulaOutputInstance = None
        self.log = logging.getLogger("arelle")
        self.log.setLevel(logging.DEBUG)
        self.modelXbrl = self # for consistency in addressing modelXbrl

    def close(self):
        if not self.isClosed:
            self.closeViews()
            if self.formulaOutputInstance:
                self.formulaOutputInstance.close()
            if hasattr(self,"fileSource") and self.closeFileSource:
                self.fileSource.close()
            modelDocument = self.modelDocument if hasattr(self,"modelDocument") else None
            self.__dict__.clear() # dereference everything before closing document
            if modelDocument:
                modelDocument.close()

    @property
    def isClosed(self):
        return not bool(self.__dict__)  # closed when dict is empty

    def reload(self,nextaction,reloadCache=False):
        from arelle import ModelDocument
        self.init(keepViews=True)
        self.modelDocument = ModelDocument.load(self, self.fileSource.url, isEntry=True, reloadCache=reloadCache)
        self.modelManager.showStatus(_("xbrl loading finished, {0}...").format(nextaction),5000)
        self.modelManager.reloadViews(self)

    def closeViews(self):
        if not self.isClosed:
            for view in range(len(self.views)):
                if len(self.views) > 0:
                    self.views[0].close()

    def relationshipSet(self, arcrole, linkrole=None, linkqname=None, arcqname=None, includeProhibits=False):
        global ModelRelationshipSet
        if ModelRelationshipSet is None:
            from arelle import ModelRelationshipSet
        key = (arcrole, linkrole, linkqname, arcqname, includeProhibits)
        if key not in self.relationshipSets:
            ModelRelationshipSet.create(self, arcrole, linkrole, linkqname, arcqname, includeProhibits)
        return self.relationshipSets[key]

    def baseSetModelLink(self, linkElement):
        for modelLink in self.baseSets[("XBRL-footnotes",None,None,None)]:
            if modelLink == linkElement:
                return modelLink
        return None

    def matchSubstitutionGroup(self, elementQname, subsGrpMatchTable):
        if elementQname in subsGrpMatchTable:
            return subsGrpMatchTable[elementQname] # head of substitution group
        elementMdlObj = self.qnameConcepts.get(elementQname)
        if elementMdlObj is not None:
            subsGrpMdlObj = elementMdlObj.substitutionGroup
            while subsGrpMdlObj is not None:
                subsGrpQname = subsGrpMdlObj.qname
                if subsGrpQname in subsGrpMatchTable:
                    return subsGrpMatchTable[subsGrpQname]
                subsGrpMdlObj = subsGrpMdlObj.substitutionGroup
        return subsGrpMatchTable.get(None)

    def isInSubstitutionGroup(self, elementQname, subsGrpQnames):
        return self.matchSubstitutionGroup(elementQname, {
                  qn:(qn is not None) for qn in (subsGrpQnames if hasattr(subsGrpQnames, '__iter__') else (subsGrpQnames,)) + (None,)})

    def createInstance(self, url=None):
        from arelle import (ModelDocument, FileSource)
        if self.modelDocument.type == ModelDocument.Type.INSTANCE: # entry already is an instance
            return self.modelDocument # use existing instance entry point
        priorFileSource = self.fileSource
        self.fileSource = FileSource.FileSource(url)
        if self.uri.startswith("http://"):
            schemaRefUri = self.uri
        else:   # relativize local paths
            schemaRefUri = os.path.relpath(self.uri, os.path.dirname(url))
        self.modelDocument = ModelDocument.create(self, ModelDocument.Type.INSTANCE, url, schemaRefs=[schemaRefUri], isEntry=True)
        if priorFileSource:
            priorFileSource.close()
        self.closeFileSource= True
        del self.entryLoadingUrl
        # reload dts views
        from arelle import ViewWinDTS
        for view in self.views:
            if isinstance(view, ViewWinDTS.ViewDTS):
                self.modelManager.cntlr.uiThreadQueue.put((view.view, []))

    def saveInstance(self):
        with open(self.modelDocument.filepath, "w", encoding='utf-8') as fh:
            XmlUtil.writexml(fh, self.modelDocument.xmlDocument, encoding="utf-8")

    def matchContext(self, entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, dims, segOCCs, scenOCCs):
        from arelle.ModelFormulaObject import Aspect
        from arelle.ModelValue import dateUnionEqual
        from arelle.XbrlUtil import sEqual
        if dims: segAspect, scenAspect = (Aspect.NON_XDT_SEGMENT, Aspect.NON_XDT_SCENARIO)
        else: segAspect, scenAspect = (Aspect.COMPLETE_SEGMENT, Aspect.COMPLETE_SCENARIO)
        for c in self.contexts.values():
            if (c.entityIdentifier == (entityIdentScheme, entityIdentValue) and
                ((c.isInstantPeriod and periodType == "instant" and dateUnionEqual(c.instantDatetime, periodEndInstant, instantEndDate=True)) or
                 (c.isStartEndPeriod and periodType == "duration" and dateUnionEqual(c.startDatetime, periodStart) and dateUnionEqual(c.endDatetime, periodEndInstant, instantEndDate=True)) or
                 (c.isForeverPeriod and periodType == "forever")) and
                 # dimensions match if dimensional model
                 (dims is None or (
                    (c.qnameDims.keys() == dims.keys()) and
                        all([cDim.isEqualTo(dims[cDimQn]) for cDimQn, cDim in c.qnameDims.items()]))) and
                 # OCCs match for either dimensional or non-dimensional modle
                 all(
                   all([sEqual(self, cOCCs[i], mOCCs[i]) for i in range(len(mOCCs))])
                     if len(cOCCs) == len(mOCCs) else False
                        for cOCCs,mOCCs in ((c.nonDimValues(segAspect),segOCCs),
                                            (c.nonDimValues(scenAspect),scenOCCs)))
                ):
                    return c
        return None

    def createContext(self, entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, priItem, dims, segOCCs, scenOCCs,
                      afterSibling=None, beforeSibling=None):
        xbrlElt = self.modelDocument.xmlRootElement
        if afterSibling == AUTO_LOCATE_ELEMENT:
            afterSibling = XmlUtil.lastChild(xbrlElt, XbrlConst.xbrli, ("schemaLocation", "roleType", "arcroleType", "context"))
        cntxId = 'c-{0:02n}'.format( len(self.contexts) + 1)
        newCntxElt = XmlUtil.addChild(xbrlElt, XbrlConst.xbrli, "context", attributes=("id", cntxId),
                                      afterSibling=afterSibling, beforeSibling=beforeSibling)
        entityElt = XmlUtil.addChild(newCntxElt, XbrlConst.xbrli, "entity")
        XmlUtil.addChild(entityElt, XbrlConst.xbrli, "identifier",
                            attributes=("scheme", entityIdentScheme),
                            text=entityIdentValue)
        periodElt = XmlUtil.addChild(newCntxElt, XbrlConst.xbrli, "period")
        if periodType == "forever":
            XmlUtil.addChild(periodElt, XbrlConst.xbrli, "forever")
        elif periodType == "instant":
            XmlUtil.addChild(periodElt, XbrlConst.xbrli, "instant",
                             text=XmlUtil.dateunionValue(periodEndInstant, subtractOneDay=True))
        elif periodType == "duration":
            XmlUtil.addChild(periodElt, XbrlConst.xbrli, "startDate",
                             text=XmlUtil.dateunionValue(periodStart))
            XmlUtil.addChild(periodElt, XbrlConst.xbrli, "endDate",
                             text=XmlUtil.dateunionValue(periodEndInstant, subtractOneDay=True))
        segmentElt = None
        scenarioElt = None
        from arelle.ModelInstanceObject import ModelDimensionValue
        if dims: # requires primary item to determin ambiguous concepts
            ''' in theory we have to check full set of dimensions for validity in source or any other
                context element, but for shortcut will see if each dimension is already reported in an
                unambiguous valid contextElement
            '''
            from arelle.PrototypeInstanceObject import FactPrototype, ContextPrototype, DimValuePrototype
            fp = FactPrototype(self, priItem, dims.items())
            # force trying a valid prototype's context Elements
            if not isFactDimensionallyValid(self, fp, setPrototypeContextElements=True):
                self.info("arelleLinfo",
                    _("Create context for %(priItem)s, cannot determine valid context elements, no suitable hypercubes"),
                    modelObject=self, priItem=priItem)
            fpDims = fp.context.qnameDims
            for dimQname in sorted(fpDims.keys()):
                dimValue = fpDims[dimQname]
                if isinstance(dimValue, DimValuePrototype):
                    dimMemberQname = dimValue.memberQname  # None if typed dimension
                    contextEltName = dimValue.contextElement
                else: # qname for explicit or node for typed
                    dimMemberQname = None
                    contextEltName = None
                if contextEltName == "segment":
                    if segmentElt is None:
                        segmentElt = XmlUtil.addChild(entityElt, XbrlConst.xbrli, "segment")
                    contextElt = segmentElt
                elif contextEltName == "scenario":
                    if scenarioElt is None:
                        scenarioElt = XmlUtil.addChild(newCntxElt, XbrlConst.xbrli, "scenario")
                    contextElt = scenarioElt
                else:
                    self.info("arelleLinfo",
                        _("Create context, %(dimension)s, cannot determine context element, either no all relationship or validation issue"),
                        modelObject=self, dimension=dimQname),
                    continue
                dimConcept = self.qnameConcepts[dimQname]
                dimAttr = ("dimension", XmlUtil.addQnameValue(xbrlElt, dimConcept.qname))
                if dimConcept.isTypedDimension:
                    dimElt = XmlUtil.addChild(contextElt, XbrlConst.xbrldi, "xbrldi:typedMember",
                                              attributes=dimAttr)
                    if isinstance(dimValue, (ModelDimensionValue, DimValuePrototype)) and dimValue.isTyped:
                        XmlUtil.copyNodes(dimElt, dimValue.typedMember)
                elif dimMemberQname:
                    dimElt = XmlUtil.addChild(contextElt, XbrlConst.xbrldi, "xbrldi:explicitMember",
                                              attributes=dimAttr,
                                              text=XmlUtil.addQnameValue(xbrlElt, dimMemberQname))
        if segOCCs:
            if segmentElt is None:
                segmentElt = XmlUtil.addChild(entityElt, XbrlConst.xbrli, "segment")
            XmlUtil.copyNodes(segmentElt, segOCCs)
        if scenOCCs:
            if scenarioElt is None:
                scenarioElt = XmlUtil.addChild(newCntxElt, XbrlConst.xbrli, "scenario")
            XmlUtil.copyNodes(scenarioElt, scenOCCs)

        self.modelDocument.contextDiscover(newCntxElt)
        XmlValidate.validate(self, newCntxElt)
        return newCntxElt

    def matchUnit(self, multiplyBy, divideBy):
        multiplyBy.sort()
        divideBy.sort()
        for u in self.units.values():
            if u.measures == (multiplyBy,divideBy):
                return u
        return None

    def createUnit(self, multiplyBy, divideBy, afterSibling=None, beforeSibling=None):
        xbrlElt = self.modelDocument.xmlRootElement
        if afterSibling == AUTO_LOCATE_ELEMENT:
            afterSibling = XmlUtil.lastChild(xbrlElt, XbrlConst.xbrli, ("schemaLocation", "roleType", "arcroleType", "context", "unit"))
        unitId = 'u-{0:02n}'.format( len(self.units) + 1)
        newUnitElt = XmlUtil.addChild(xbrlElt, XbrlConst.xbrli, "unit", attributes=("id", unitId),
                                      afterSibling=afterSibling, beforeSibling=beforeSibling)
        if len(divideBy) == 0:
            for multiply in multiplyBy:
                XmlUtil.addChild(newUnitElt, XbrlConst.xbrli, "measure", text=XmlUtil.addQnameValue(xbrlElt, multiply))
        else:
            divElt = XmlUtil.addChild(newUnitElt, XbrlConst.xbrli, "divide")
            numElt = XmlUtil.addChild(divElt, XbrlConst.xbrli, "unitNumerator")
            denElt = XmlUtil.addChild(divElt, XbrlConst.xbrli, "unitDenominator")
            for multiply in multiplyBy:
                XmlUtil.addChild(numElt, XbrlConst.xbrli, "measure", text=XmlUtil.addQnameValue(xbrlElt, multiply))
            for divide in divideBy:
                XmlUtil.addChild(denElt, XbrlConst.xbrli, "measure", text=XmlUtil.addQnameValue(xbrlElt, divide))
        self.modelDocument.unitDiscover(newUnitElt)
        XmlValidate.validate(self, newUnitElt)
        return newUnitElt

    @property
    def nonNilFactsInInstance(self): # indexed by fact (concept) qname
        try:
            return self._nonNilFactsInInstance
        except AttributeError:
            self._nonNilFactsInInstance = [f for f in self.factsInInstance if not f.isNil]
            return self._nonNilFactsInInstance

    def qnameFactsInInstance(self, facts): # indexed by fact (concept) qname
        if facts is self.factsInInstance: # may be all facts in inst or just nonNil factsInInst
            try:
                return self._qnameFactsInInstance
            except AttributeError:
                _qname_factsInInstance = defaultdict(list)
                for f in self.factsInInstance:
                    _qname_factsInInstance[f.qname].append(f)
                self._qnameFactsInInstance = _qname_factsInInstance
                return self._qnameFactsInInstance
        elif facts is getattr(self,"_nonNilFactsInInstance",None):
            try:
                return self._qnameNonNilFactsInInstance
            except AttributeError:
                _qname_factsInInstance = defaultdict(list)
                for f in self._nonNilFactsInInstance:
                    _qname_factsInInstance[f.qname].append(f)
                self._qnameNonNilFactsInInstance = _qname_factsInInstance
                return self._qnameNonNilFactsInInstance
        return None

    def matchFact(self, otherFact):
        for fact in self.facts:
            if (fact.isTuple):
                if fact.isDuplicateOf(otherFact):
                    return fact
            elif (fact.qname == otherFact.qname and fact.isVEqualTo(otherFact)):
                if not fact.isNumeric:
                    if fact.xmlLang == otherFact.xmlLang:
                        return fact
                else:
                    if (fact.decimals == otherFact.decimals and
                        fact.precision == otherFact.precision):
                        return fact
        return None

    def createFact(self, conceptQname, attributes=None, text=None, parent=None, afterSibling=None, beforeSibling=None):
        if parent is None: parent = self.modelDocument.xmlRootElement
        newFact = XmlUtil.addChild(parent, conceptQname, attributes=attributes, text=text,
                                   afterSibling=afterSibling, beforeSibling=beforeSibling)
        self.modelDocument.factDiscover(newFact, parentElement=parent)
        XmlValidate.validate(self, newFact)
        return newFact

    def modelObject(self, objectId):
        if isinstance(objectId, _INT_TYPES):  # may be long or short in 2.7
            return self.modelObjects[objectId]
        # assume it is a string with ID in a tokenized representation, like xyz_33
        try:
            return self.modelObjects[_INT(objectId.rpartition("_")[2])]
        except ValueError:
            return None

    # UI thread viewModelObject
    def viewModelObject(self, objectId):
        modelObject = ""
        try:
            if isinstance(objectId, (ModelObject,FactPrototype)):
                modelObject = objectId
            elif isinstance(objectId, str) and objectId.startswith("_"):
                modelObject = self.modelObject(objectId)
            if modelObject is not None:
                for view in self.views:
                    view.viewModelObject(modelObject)
        except (IndexError, ValueError, AttributeError)as err:
            self.modelManager.addToLog(_("Exception viewing properties {0} {1} at {2}").format(
                            modelObject,
                            err, traceback.format_tb(sys.exc_info()[2])))

    def logArguments(self, codes, msg, codedArgs):
        # determine logCode
        messageCode = None
        for argCode in codes if isinstance(codes,tuple) else (codes,):
            if (isinstance(argCode, ModelValue.QName) or
                (self.modelManager.disclosureSystem.EFM and argCode.startswith("EFM")) or
                (self.modelManager.disclosureSystem.GFM and argCode.startswith("GFM")) or
                (self.modelManager.disclosureSystem.HMRC and argCode.startswith("HMRC")) or
                (self.modelManager.disclosureSystem.SBRNL and argCode.startswith("SBR.NL")) or
                argCode[0:3] not in ("EFM", "GFM", "HMR", "SBR")):
                messageCode = argCode
                break

        # determine message and extra arguments
        fmtArgs = {}
        extras = {"messageCode":messageCode}
        for argName, argValue in codedArgs.items():
            if argName in ("modelObject", "modelXbrl", "modelDocument"):
                try:
                    entryUrl = self.modelDocument.uri
                except AttributeError:
                    entryUrl = self.entryLoadingUrl
                refs = []
                for arg in (argValue if isinstance(argValue, (tuple,list)) else (argValue,)):
                    if arg is not None:
                        if isinstance(arg, _STR_BASE):
                            objectUrl = arg
                        else:
                            try:
                                objectUrl = arg.modelDocument.uri
                            except AttributeError:
                                try:
                                    objectUrl = self.modelDocument.uri
                                except AttributeError:
                                    objectUrl = self.entryLoadingUrl
                        file = UrlUtil.relativeUri(entryUrl, objectUrl)
                        ref = {}
                        if isinstance(arg,ModelObject):
                            ref["href"] = file + "#" + XmlUtil.elementFragmentIdentifier(arg)
                            ref["sourceLine"] = arg.sourceline
                            ref["objectId"] = arg.objectId()
                        else:
                            ref["href"] = file
                        refs.append(ref)
                extras["refs"] = refs
            elif argName == "sourceLine":
                if isinstance(argValue, _INT_TYPES):    # must be sortable with int's in logger
                    extras["sourceLine"] = argValue
            elif argName != "exc_info":
                if isinstance(argValue, (ModelValue.QName, ModelObject, bool, FileNamedStringIO)):
                    fmtArgs[argName] = str(argValue)
                elif isinstance(argValue, _INT_TYPES):
                    # need locale-dependent formatting
                    fmtArgs[argName] = format_string(self.modelManager.locale, '%i', argValue)
                elif isinstance(argValue,float):
                    # need locale-dependent formatting
                    fmtArgs[argName] = format_string(self.modelManager.locale, '%f', argValue)
                else:
                    fmtArgs[argName] = argValue
        if "refs" not in extras:
            try:
                file = os.path.basename(self.modelDocument.uri)
            except AttributeError:
                try:
                    file = os.path.basename(self.entryLoadingUrl)
                except:
                    file = ""
            extras["refs"] = [{"href": file}]
        return (messageCode,
                (msg, fmtArgs) if fmtArgs else (msg,),
                extras)

    def info(self, codes, msg, **args):
        messageCode, logArgs, extras = self.logArguments(codes, msg, args)
        if messageCode == "asrtNoLog":
            self.errors.append(args["assertionResults"])
        else:
            self.logCountInfo += 1
            self.log.info(*logArgs, exc_info=args.get("exc_info"), extra=extras)

    def warning(self, codes, msg, **args):
        messageCode, logArgs, extras = self.logArguments(codes, msg, args)
        if messageCode:
            self.logCountWrn += 1
            self.log.warning(*logArgs, exc_info=args.get("exc_info"), extra=extras)

    def error(self, codes, msg, **args):
        messageCode, logArgs, extras = self.logArguments(codes, msg, args)
        if messageCode:
            self.errors.append(messageCode)
            self.logCountErr += 1
            self.log.error(*logArgs, exc_info=args.get("exc_info"), extra=extras)

    def exception(self, codes, msg, **args):
        messageCode, logArgs, extras = self.logArguments(codes, msg, args)
        self.log.exception(*logArgs, exc_info=args.get("exc_info"), extra=extras)

    def profileActivity(self, activityCompleted=None, minTimeToShow=0):
        import time
        try:
            if activityCompleted:
                timeTaken = time.time() - self._startedAt
                if timeTaken > minTimeToShow:
                    self.modelManager.addToLog("{0} {1:.2f} secs".format(activityCompleted, timeTaken))
        except AttributeError:
            pass
        self._startedAt = time.time()

    def saveDTSpackage(self):
        if self.fileSource.isArchive:
            return
        from zipfile import ZipFile
        import os
        entryFilename = self.fileSource.url
        pkgFilename = entryFilename + ".zip"
        with ZipFile(pkgFilename, 'w') as zip:
            numFiles = 0
            for fileUri in sorted(self.urlDocs.keys()):
                if not (fileUri.startswith("http://") or fileUri.startswith("https://")):
                    numFiles += 1
                    # this has to be a relative path because the hrefs will break
                    zip.write(fileUri, os.path.basename(fileUri))
        self.info("info",
                  _("DTS of %(entryFile)s has %(numberOfFiles)s files packaged into %(packageOutputFile)s"),
                modelObject=self,
                entryFile=os.path.basename(entryFilename), packageOutputFile=pkgFilename, numberOfFiles=numFiles)


class Solution:
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        counter = 0
        new_head = head
        tail, cursor = None, head

        queue = [None] * (k)

        while cursor:
            counter += 1
            r = counter % k

            if counter == k:
                new_head = cursor

            queue[r - 1] = cursor
            cursor = cursor.next

            if r == 0:
                for i in range(1, k):
                    queue[k - i].next = queue[k - i - 1]
                else:
                    if tail:
                        tail.next = queue[k - 1]
                    tail = queue[0]
            queue[r] = None

        else:
            if tail:
                tail.next = queue[0]

        return new_head

from helper import array_2_list
from helper import print_list

s = Solution()

raw = [1, 2, 3, 4, 5]
case = array_2_list(raw)

r = s.reverseKGroup(case, 3)
print_list(r)


from flask import Blueprint
from App.views.localidades import cidades
from flask import jsonify,request
from App.schema.localidades.localidades import CidadesSchema

routescidades = Blueprint('routescidades',__name__)

#Pesquisa Cidade Por id ou por nome
@routescidades.route('/get/cidade/<idcidade>', methods=['GET'])
def get_cidade(idcidade):
    try:
        data = []
        if len(request.args) > 0:
            data = request.args.get('dataonly').split(',')

        if len(data) > 0 and data[0] != '':
            cidadesschema = CidadesSchema(only=data)
        else:
            cidadesschema = CidadesSchema()

        cidade = cidades.get_cidade(idcidade)
        return jsonify({'data':cidadesschema.dump(cidade,many=True)})
    except:
        return jsonify({'data': {},'erro':True})

#Pesquisa Cidade Por id ou por nome
@routescidades.route('/get/cidade/UF/<iduf>', methods=['GET'])
def get_cidade_by_uf(iduf):
    try:
        data = []
        nomecity = ''
        if len(request.args) > 0:
            try:
                data = request.args.get('dataonly').split(',')
            except:
                data = []
            nomecity = request.args.get('nome')
            if nomecity == None:
                nomecity = ''

        if len(data) > 0 and data[0] != '':
            cidadesschema = CidadesSchema(only=data)
        else:
            cidadesschema = CidadesSchema()

        cidade = cidades.get_cidade_by_uf(iduf,nomecity)
        return jsonify({'data':cidadesschema.dump(cidade,many=True)})
    except:
        return jsonify({'data': {},'erro':True})


from django.http import HttpResponse
from django.shortcuts import render
from .forms import UploadFileForm, ShowDataForm
from .models import Grado, Grado_rp30
import csv, io

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            grado = form.cleaned_data['grado']
            curso = form.cleaned_data['curso']
            csv_file1 = request.FILES['f_matriculados']
            csv_file2 = request.FILES['f_abandono']
            if not form.cleaned_data['f_rp30']:
                datos =  read_csv(csv_file1, csv_file2)
                RP30 = None
            else:
                csv_file3 = request.FILES['f_rp30']
                datos =  read_csv(csv_file1, csv_file2, csv_file3)
                RP30 = 'active'
            create_table(grado, curso, datos[0], datos[1], RP30)
            return HttpResponse('
Archivos subidos con éxito.
')
    else:
        form = UploadFileForm()
    return render(request, 'subir_datos.html', {'form': form})

def get_key(val, diccionario):
    for key, value in diccionario.items():
         if val == value:
             return key

def read_csv(f1, f2, f3=None):
    Alumnos = []
    data_matriculados = f1.read().decode('UTF-8')
    data_abandono = f2.read().decode('UTF-8')
    io_matriculados = io.StringIO(data_matriculados)
    io_abandono = io.StringIO(data_abandono)
    cols_alumnos = dict(enumerate(next(csv.reader(io_matriculados))))
    cols_abandono = dict(enumerate(next(csv.reader(io_abandono))))

    if f3 != None:
        data_rp30 = f3.read().decode('UTF-8')
        io_rp30 = io.StringIO(data_rp30)
        cols_rp30 = dict(enumerate(next(csv.reader(io_rp30))))
        lista_rp30 = [row for row in csv.reader(io_rp30)]

    lista_datos = [row for row in csv.reader(io_matriculados)]
    lista_abandono = [row for row in csv.reader(io_abandono)]

    lista_dni = list(dict.fromkeys([str(lista[get_key('Dni', cols_alumnos)]) for lista in lista_datos]))
    lista_cursos = list(dict.fromkeys([lista[get_key('Curso acta', cols_alumnos)] for lista in lista_datos]))
    lista_asignaturas = list(dict.fromkeys([lista[get_key('Asignatura', cols_alumnos)+1] for lista in lista_datos]))

    lista_cursos.sort()
    exp_1 = 'MAT_' + str(int(lista_cursos[0][2:].replace('-','')) + 101) + '_SN'
    exp_2 = 'MAT_' + str(int(lista_cursos[0][2:].replace('-','')) + 202) + '_SN'

    tam = len(lista_datos)
    i = 0
    for dni in lista_dni:
        dict_alu = {'Sexo': lista_datos[i][get_key('Sexo', cols_alumnos)],
                    'Edad': lista_datos[i][get_key('Edad año ingreso al estudio', cols_alumnos)],
                    'Procedencia': lista_datos[i][get_key('Isla procedencia', cols_alumnos)],
                    'Becado': lista_datos[i][get_key('Becario', cols_alumnos)],
                    'Convocatoria': lista_datos[i][get_key('Conv. Preinsc.', cols_alumnos)],
                    'Modalidad': lista_datos[i][get_key('Modalidad', cols_alumnos)],
                    'Especialidad': lista_datos[i][get_key('Especialidad', cols_alumnos)+1]
                    }
        # Trabajo:
        dict_alu['Trabajo'] = 'No' if lista_datos[i][get_key('Ocpación alumno', cols_alumnos)] == 'No aplica' or lista_datos[i][get_key('Ocpación alumno', cols_alumnos)] == 'No consta' else 'Si'
        # Preferencia
        dict_alu['Preferencia'] = int(lista_datos[i][get_key('Preferencia', cols_alumnos)]) if lista_datos[i][get_key('Preferencia', cols_alumnos)] != '' else None
        # Nota Bach/Ciclo
        dict_alu['Nota_Bach'] = float(lista_datos[i][get_key('Nota Bach / Ciclo', cols_alumnos)].replace(',','.')) if lista_datos[i][get_key('Nota Bach / Ciclo', cols_alumnos)] != '' else None
        # Nota Prueba (Ebau)
        dict_alu['Nota_prueba'] = float(lista_datos[i][get_key('Nota prueba', cols_alumnos)].replace(',','.')) if lista_datos[i][get_key('Nota prueba', cols_alumnos)] != '' else None
        # Nota específica (Ebau)
        dict_alu['Nota_esp'] = float(lista_datos[i][get_key('Nota Específica', cols_alumnos)].replace(',','.')) if lista_datos[i][get_key('Nota Específica', cols_alumnos)] != '' else None
        # Nota admisión
        dict_alu['Admision'] = float(lista_datos[i][get_key('Nota admisión', cols_alumnos)].replace(',','.')) if lista_datos[i][get_key('Nota admisión', cols_alumnos)] != '' else None

        for sublist in lista_abandono:
            if sublist[get_key('Dni', cols_abandono)] == dni:
                if sublist[get_key(exp_1, cols_abandono)] == 'N' and sublist[get_key(exp_2, cols_abandono)] == 'N':
                    dict_alu['Abandono'] = 'Si'
                else:
                    dict_alu['Abandono'] = 'No'

        if f3 != None:
            dict_alu['aciertos'] = None
            dict_alu['errores'] = None
            dict_alu['total'] = None
            for sublist in lista_rp30:
                if sublist[get_key('DNI', cols_rp30)] == dni:
                    dict_alu['aciertos'] = int(sublist[get_key('ACIERTOS', cols_rp30)]) if sublist[get_key('ACIERTOS', cols_rp30)] != '' else None
                    dict_alu['errores'] = int(sublist[get_key('ERRORES', cols_rp30)]) if sublist[get_key('ERRORES', cols_rp30)] != '' else None
                    dict_alu['total'] = int(sublist[get_key('TOTAL PRUEBA', cols_rp30)]) if sublist[get_key('TOTAL PRUEBA', cols_rp30)] != '' else None

        contador = 0
        lista_curso1 = []
        lista_curso2 = []
        while dni == lista_datos[i][get_key('Dni', cols_alumnos)]:
            curso = lista_datos[i][get_key('Curso acta', cols_alumnos)]
            asignaturas_matriculadas = 0
            asignaturas_presentadas = 0
            asignaturas_aprobadas = 0

            while curso == lista_datos[i][get_key('Curso acta', cols_alumnos)] and dni == lista_datos[i][get_key('Dni', cols_alumnos)]:
                asignaturas_matriculadas += 1
                n_asignatura = lista_datos[i][get_key('Asignatura', cols_alumnos)+1]
                notas = []
                while lista_datos[i][get_key('Asignatura', cols_alumnos)+1] == n_asignatura:
                    if lista_datos[i][get_key('Calificación', cols_alumnos)] != 'NP':
                        notas.append(float(lista_datos[i][get_key('Calif. Numérica', cols_alumnos)].replace(',','.')))
                    i += 1
                    if i == tam: break
                if notas:
                    asignaturas_presentadas += 1
                    if max(notas) >= 5.0:
                        asignaturas_aprobadas += 1
                    lista_curso1.append([n_asignatura, max(notas)]) if curso == lista_cursos[0] else lista_curso2.append([n_asignatura, max(notas)])
                else:
                    lista_curso1.append([n_asignatura, None]) if curso == lista_cursos[0] else lista_curso2.append([n_asignatura, None])
                if i == tam: break
            contador += 1
            if contador == 1:
                dict_alu['asignaturas_matriculadas_primero'] = asignaturas_matriculadas
                dict_alu['asignaturas_presentadas_primero'] = asignaturas_presentadas
                dict_alu['asignaturas_aprobadas_primero'] = asignaturas_aprobadas
            else:
                dict_alu['asignaturas_matriculadas_segundo'] = asignaturas_matriculadas
                dict_alu['asignaturas_presentadas_segundo'] = asignaturas_presentadas
                dict_alu['asignaturas_aprobadas_segundo'] = asignaturas_aprobadas
            if i == tam: break

        if contador == 1:
            dict_alu['asignaturas_matriculadas_segundo'] = None
            dict_alu['asignaturas_presentadas_segundo'] = None
            dict_alu['asignaturas_aprobadas_segundo'] = None

        dict_alu['notas'] = []
        for asignatura in lista_asignaturas:
            nota_f = []
            for asig_c1 in lista_curso1:
                if asig_c1[0] == asignatura:
                    if asig_c1[1] != None:
                        nota_f.append(asig_c1[1])
            for asig_c2 in lista_curso2:
                if asig_c2[0] == asignatura:
                    if asig_c2[1] != None:
                        nota_f.append(asig_c2[1])
            if nota_f:
                if len(nota_f) == 2:
                    dict_alu['notas'].append(nota_f[-1])
                else:
                    dict_alu['notas'].append(nota_f[0])
            else:
                dict_alu['notas'].append(None)

        media_notas = []
        for nota in lista_curso1:
            if nota[1] != None:
                media_notas.append(nota[1])
        if len(media_notas) != 0:
            media = sum(map(float,media_notas))/float(len(media_notas))
            dict_alu['Nota_media_1'] = round(media, 2)
        else:
            dict_alu['Nota_media_1'] = None

        media_notas.clear()
        for nota in lista_curso2:
            if nota[1] != None:
                media_notas.append(nota[1])
        if len(media_notas) != 0:
            media = sum(map(float,media_notas))/float(len(media_notas))
            dict_alu['Nota_media_2'] = round(media, 2)
        else:
            dict_alu['Nota_media_2'] = None

        Alumnos.append(dict_alu)

    return Alumnos, lista_asignaturas

def create_table(grado, curso, lista, lista_asignaturas, RP30):
    """
    b_grado = Grado.objects.raw('SELECT alumno_id FROM datos_alumnos_grado')
    b_grado_rp30 = Grado.objects.raw('SELECT alumno_id FROM datos_alumnos_grado_rp30')
    alumnos_id_grado =  max(b_grado) if len(b_grado) > 0 else 0
    alumnos_id_grado_rp = max(b_grado_rp30) if len(b_grado_rp30) > 0 else 0
    id_act = max(alumnos_id_grado, alumnos_id_grado_rp)
    """
    if RP30 is None:
        for alumno in lista:
            created = Grado.objects.create(
                Grado = grado,
                Ingreso = curso,
                Sexo = alumno['Sexo'],
                Edad = alumno['Edad'],
                Procedencia = alumno['Procedencia'],
                Trabajo = alumno['Trabajo'],
                Beca = alumno['Becado'],
                Convocatoria = alumno['Convocatoria'],
                Preferencia = alumno['Preferencia'],
                Modalidad = alumno['Modalidad'],
                Especialidad = alumno['Especialidad'],
                Nota_Bach_Ciclo = alumno['Nota_Bach'],
                Nota_Prueba = alumno['Nota_prueba'],
                Nota_Especifica = alumno['Nota_esp'],
                Nota_Admision = alumno['Admision'],
                Abandono = alumno['Abandono'],
                asignaturas_matriculadas_primer_año = alumno['asignaturas_matriculadas_primero'],
                asignaturas_presentadas_primer_año = alumno['asignaturas_presentadas_primero'],
                asignaturas_aprobadas_primer_año = alumno['asignaturas_aprobadas_primero'],
                asignaturas_matriculadas_segundo_año = alumno['asignaturas_matriculadas_segundo'],
                asignaturas_presentadas_segundo_año = alumno['asignaturas_presentadas_segundo'],
                asignaturas_aprobadas_segundo_año = alumno['asignaturas_aprobadas_segundo'],
                media_primer_año = alumno['Nota_media_1'],
                media_segundo_año = alumno['Nota_media_2'],
                asignaturas = lista_asignaturas,
                notas = alumno['notas'],
            )

    else:
        for alumno in lista:
            created = Grado_rp30.objects.create(
                Grado = grado,
                Ingreso = curso,
                Sexo = alumno['Sexo'],
                Edad = alumno['Edad'],
                Procedencia = alumno['Procedencia'],
                Trabajo = alumno['Trabajo'],
                Beca = alumno['Becado'],
                Convocatoria = alumno['Convocatoria'],
                Preferencia = alumno['Preferencia'],
                Modalidad = alumno['Modalidad'],
                Especialidad = alumno['Especialidad'],
                Nota_Bach_Ciclo = alumno['Nota_Bach'],
                Nota_Prueba = alumno['Nota_prueba'],
                Nota_Especifica = alumno['Nota_esp'],
                Nota_Admision = alumno['Admision'],
                Abandono = alumno['Abandono'],
                asignaturas_matriculadas_primer_año = alumno['asignaturas_matriculadas_primero'],
                asignaturas_presentadas_primer_año = alumno['asignaturas_presentadas_primero'],
                asignaturas_aprobadas_primer_año = alumno['asignaturas_aprobadas_primero'],
                asignaturas_matriculadas_segundo_año = alumno['asignaturas_matriculadas_segundo'],
                asignaturas_presentadas_segundo_año = alumno['asignaturas_presentadas_segundo'],
                asignaturas_aprobadas_segundo_año = alumno['asignaturas_aprobadas_segundo'],
                media_primer_año = alumno['Nota_media_1'],
                media_segundo_año = alumno['Nota_media_2'],
                Aciertos = alumno['aciertos'],
                Fallos = alumno['errores'],
                Total_prueba = alumno['total'],
                asignaturas = lista_asignaturas,
                notas = alumno['notas'],
            )

def show_data(request):
    context = {}
    form = ShowDataForm(request.GET)
    context['form'] = form
    if request.method == 'GET':
        if form.is_valid():
            grado = form.cleaned_data['grado']
            curso = form.cleaned_data['curso']
            rp_30 = form.cleaned_data['rp_30']
            if rp_30 == True:
                alumnos = Grado_rp30.objects.raw('SELECT * FROM datos_alumnos_grado_rp30 WHERE "Ingreso" = %s AND "Grado" = %s', [curso, grado])
                context['rp_30'] = 'On'
            else:
                alumnos = Grado.objects.raw('SELECT * FROM datos_alumnos_grado WHERE "Ingreso" = %s AND "Grado" = %s', [curso, grado])
                context['rp_30'] = 'Off'
            context['alumnos'] = alumnos
            context['mensaje'] = 'No se encontraron registros'
    else:
        form = ShowDataForm()
    return render(request, 'mostrar_datos.html', context)


from django.http import JsonResponse
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.parsers import JSONParser

from .serializers import *
from rest_framework import mixins, viewsets
from django.db import connection
from datetime import datetime

from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from Sector.models import ChildCompany, Company
from Worker.models import Role, Contact, Experience

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

@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([permissions.IsAuthenticated])
def Experince_add(request):
    try:
        if request.method == 'POST':
            rol = None
            try:
                rol = Role.objects.get(name=request.data['roleName'])
            except:
                rol = Role.objects.create(name=request.data['roleName'],
                                          created_at=datetime.today(),
                                          updated_at=datetime.today()
                                          )

            contac = Contact.objects.create(name=request.data['contactName'],
                                            email=request.data['contactEmail'],
                                            phone=request.data['contactPhone'],
                                            about=request.data['aboutContact'],

                                            created_at=datetime.today(),
                                            updated_at=datetime.today()
                                            )

            expe = Experience.objects.create(company_id=request.data['company'],
                                             contact_id=contac.id,
                                             fromDate=request.data['fromDate'],
                                             toDate=request.data['toDate'],
                                             role_id=rol.id,

                                             created_at=datetime.today(),
                                             updated_at=datetime.today()
                                             )
        return JsonResponse({'message': 'Experience is created successfully!'}, status=status.HTTP_201_CREATED)
    except:
        return JsonResponse({'message': 'Error!'}, status=status.HTTP_404_NOT_FOUND)

@api_view(['DELETE'])
@authentication_classes([JWTAuthentication])
@permission_classes([permissions.IsAuthenticated])
def experience_delete(request, pk):
    try:
        expe = Experience.objects.get(pk=pk)
        expe.delete()
        return JsonResponse({'message': 'The experience was deleted successfully!'},
                            status=status.HTTP_204_NO_CONTENT)
    except Experience.DoesNotExist:
        return JsonResponse({'message': 'The experience does not exist'}, status=status.HTTP_404_NOT_FOUND)

@api_view(['PUT'])
@authentication_classes([JWTAuthentication])
@permission_classes([permissions.IsAuthenticated])
def experience_update(request, pk):
    try:
        rol = None
        try:
            rol = Role.objects.get(name=request.data['roleName'])
        except:
            rol = Role.objects.create(name=request.data['roleName'],
                                      created_at=datetime.today(),
                                      updated_at=datetime.today()
                                      )
        try:
            contact_to_update = Contact.objects.filter(id=pk).update(name=request.data['contactName'],
                                                                     email=request.data['contactEmail'],
                                                                     phone=request.data['contactPhone'],
                                                                     about=request.data['aboutContact'],

                                                                     updated_at=datetime.today()
                                                                     )
        except:
            return JsonResponse({'message': 'The contact does not exist'}, status=status.HTTP_404_NOT_FOUND)

        try:
            experience_to_update = Experience.objects.filter(contact_id=pk).update(company_id=request.data['company'],
                                                                                contact_id=pk,
                                                                                fromDate=request.data['fromDate'],
                                                                                toDate=request.data['toDate'],
                                                                                role_id=rol.id,
                                                                                updated_at=datetime.today()
                                                                                )
        except Contact.DoesNotExist:
            return JsonResponse({'message': 'The Experience does not exist'}, status=status.HTTP_404_NOT_FOUND)

        return JsonResponse({'message': 'Experience is updated successfully!'}, status=status.HTTP_201_CREATED)
    except:
        return JsonResponse({'message': 'The exp does not exist'}, status=status.HTTP_404_NOT_FOUND)

class experience_detail(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = experienceSerializer
    permission_classes = [IsAuthenticated]  # this will check if it is authenticated or not
    authentication_classes = [JWTAuthentication]  # this will handel authentication automatically

    def get_object(self, queryset=None):
        obj = self.request
        return obj

    def get_queryset(self):
        getData = self.get_object()
        id = getData.GET['id']

        queryset = Experience.objects.filter(pk=id)
        # print(queryset)
        return queryset

class getAllexperienceOfCompanyViews(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = experienceSerializer
    permission_classes = [IsAuthenticated]  # this will check if it is authenticated or not
    authentication_classes = [JWTAuthentication]  # this will handel authentication automatically

    def get_object(self, queryset=None):
        obj = self.request
        return obj

    def get_queryset(self):
        getData = self.get_object()
        id = getData.GET['id']

        queryset = Experience.objects.filter(company_id=id)
        return queryset


# Importing the OpenCV Library
import cv2

# Creating the Haar Cascade
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

# To detect face in image or video
def detect(gray, frame):
	faces = face_cascade.detectMultiScale(gray, 1.3, 5)
	# Draws a rectangle around the detected faces
	for (x,y,w,h) in faces:
		cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)
	return frame

# Face Detection in an Image
def imageDetection():
	# Get the Image Location
	filepath = input("Enter the full path to the image: ")
	# Reading Image
	img = cv2.imread(filepath)
	# Converting Image to GrayScale for better accuracy
	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
	img = detect(gray, img)
	# Finally displaying the resultant image
	cv2.imshow("Face Detection", img)
	cv2.waitKey(0)
	cv2.destroyAllWindows()

# Face Detection in live video
def liveDetection():
	# Capture Video from WebCam
	video_capture = cv2.VideoCapture(0)
	while True:
		# If frame is read correctly, the return value of `video_capture.read()` is true
		_, frame = video_capture.read()
		# Converting frame to grayscale because OpenCV is more accurate with gray scale videos/images
		gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
		canvas = detect(gray, frame)
		# Displays Webcam with the specified video title
		cv2.imshow("Face-Detection", canvas)
		# Quit the program using `q` key from keyboard
		if cv2.waitKey(1) & 0xFF == ord('q'):
			break
	video_capture.release()
	cv2.destroyAllWindows()

# Menu for the given program
while True:
	print()
	print("-" * 22, "MENU", "-" * 22)
	print("Press 1 for Face Detection in an Image")
	print("Press 2 to Live Face Detection from Webcam")
	print("Press 3 to Quit")
	print("-" * 50)

	choice = int(input("Enter the menu option: "))

	if choice == 1:
		imageDetection()
	elif choice == 2:
		liveDetection()
	elif choice == 3:
		break
	else:
		print("\nInvalid Choice. Enter a valid option!")


MIN_NRO_HANGAR=10
MAX_NRO_HANGAR=5000

MIN_OID_AVION=20552
MAX_OID_AVION=24510558

MIN_HANGARES = 1
MAX_HANGARES = 5

MIN_PRECIO_ESPACIO=3000
MAX_PRECIO_ESPACIO=100000
# Códigos de los materiales sacados de:
# https://en.wikipedia.org/wiki/Runway
COMPUESTOS = ['ASP', 'BIT', 'BRI', 'CLA', 'COM', 'CON', 'COP', 'COR', 'GRE', 'GVL', 'GRS', 'ICE', 'LAT', 'MAC', 'PEM', 'PER', 'PSP', 'SAN', 'SMT', 'SNO', 'U']
MIN_LONG        = 1000
MAX_LONG        = 5000
MIN_ANCHO       = 10
MAX_ANCHO       = 500
MIN_AEROLINEAS  = 10
MAX_AEROLINEAS  = 150