# -*- encoding: utf-8 -*-
import distutils.core
from django.shortcuts import render_to_response, render, redirect
from django.template import RequestContext, Context
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django.core.validators import validate_email
from django.template.loader import get_template
from django.http import HttpResponse
from slugify import slugify
from django import template
from django.conf import settings
from django.db.models import Q
from threading import Thread
from django.template.loader import get_template
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.db.models import Case, When, Max, F, Count, Value, Q, Sum, BooleanField, TextField, IntegerField

from datetime import datetime, date, timedelta
from django.utils import timezone

import json
import xlrd
import xlwt
import collections
import shutil
import os
import time

from academico.function import HORA_INI, HORA_FINI, UPDATE_CURSOS_PATH
from curso.form import CursoForm, CursoParteDosForm, ModuloForm, ClaseForm, MaterialForm
from curso.models import Curso, Modulo, Clase, Material
from integrado.models import Usuario, Ficha, Pais, Region, Comuna, Producto
from integrado.function import elige_choices, filtros_cabecera
from academico.models import AlumnoFicha, AlumnoCurso, Alumno, Sala, Horario
from integrado.form import AlumnoCursoForm, FiltroFichasForm, FiltroCursosForm
from academico.form import HorarioForm, UsuarioDocenteForm

# ------------------------------------
# ******* AREA ACADEMICA *********
# ------------------------------------
def fichas(request, tipo_fichas=""):
    listado_fichas = []

    tipo_de_fichas = int(tipo_fichas)

    filtroFichasForm = FiltroFichasForm()

    # -------------------------------------------------
    # bloque hecho para los filtros de las paginas
    query_set = Ficha.objects.filter(ficha_tipocurso=tipo_fichas)
    if request.POST:
        lst_query = filtros_cabecera(request)
        for l in lst_query:
            filtroFichasForm.fields[l['key']].initial = l['value']

            if l['key'] == 'ficha_estado':
                query_set = query_set.filter(ficha_estado=l['value'])
            if l['key'] == 'curso':
                query_set = query_set.filter(curso_id=l['value'])
            if l['key'] == 'vendedor':
                query_set = query_set.filter(usuario_id=l['value'])
    # -------------------------------------------------

    for f in query_set.order_by("ficha_id"):

        ficha_estado = elige_choices(Ficha.FICHA_ESTADO, f.ficha_estado)
        ficha_tipocurso = elige_choices(Ficha.TIPO_CURSO, f.ficha_tipocurso)
        estado_ficha = elige_choices(Ficha.OPCIONES, f.ficha_activo)

        alumno_ficha = AlumnoFicha.objects.filter(ficha=f).exclude(af_activo='N').annotate(
            cantidad_fichas=Count('alumno')).filter(cantidad_fichas__gt=0)

        # solo muestra las fichas con alumnos
        if len(alumno_ficha) > 0 and f.ficha_procesocreacion >= 1:

            try:
                producto = f.producto.prod_nombre.title()
            except:
                producto = ""

            try:
                curso = f.curso.cur_nombre.title()
            except:
                curso = ""

            try:
                cliente = f.cliente.cli_nombre.title()
            except:
                cliente = ""

            listado_fichas.append({
                'ficha_id': f.ficha_id,
                'ficha_estado': ficha_estado,
                'id_ficha_estado': f.ficha_estado,
                'producto': producto,
                'curso': curso,
                'ficha_tipocurso': ficha_tipocurso,
                'cliente': cliente,
                'cantidad': len(alumno_ficha),
                'usuario': "{n} {ap}".format(n=f.usuario.usu_nombre.title(), ap=f.usuario.usu_apepat.title()),
                'ficha_activo': f.ficha_activo,
                'estado_ficha': estado_ficha
            })

    lst_profesores = Usuario.objects.filter(usu_tipousuario=5).exclude(usu_usuarioactivo='N')

    titulo = ''
    if tipo_fichas == '1':
        titulo = 'E-learning'
    elif tipo_fichas == '2':
        titulo = 'Presenciales'
    elif tipo_fichas == '3':
        titulo = 'Semi-Presenciales'

    data = {
        'usuario': request.session["dicUsuario"],
        'listado_fichas': listado_fichas,
        'tipo_de_fichas': tipo_de_fichas,
        'AlumnoCursoForm': AlumnoCursoForm(),
        'lst_profesores': lst_profesores,
        'titulo': titulo,
        'filtroFichasForm': filtroFichasForm,
        'tipo_fichas': tipo_fichas,
    }
    return render(request, 'integrado/page/fichas.html', data)

# --------------------
# by osbustaman
# con esta función se asocician los alumnos al curso,
@csrf_exempt
def ajax_asociar_alumno_curso(request):
    the_error = ""
    lst_alumno_curso = []

    date_ini = datetime.strptime(request.POST['fecha_ini'], '%d/%m/%Y').date()
    date_fin = datetime.strptime(request.POST['fecha_fin'], '%d/%m/%Y').date()

    # try:
    ficha = Ficha.objects.get(ficha_id=request.POST['ficha_id'])

    if ficha.ficha_tipocurso==1:
        ac_diasdelasemana = '0:1:2:3:4:5:6'
    else:
        ac_diasdelasemana = request.POST['ac_diasdelasemana']

    ficha.ficha_ini = date_ini
    ficha.ficha_fin = date_fin
    ficha.ficha_diasalasemana = ac_diasdelasemana
    try:
        ficha.ficha_valorhoraprofesor = request.POST['id_valor_hora']
    except:
        ficha.ficha_valorhoraprofesor = 0
    ficha.save()

    alumno_ficha = AlumnoFicha.objects.filter(ficha=ficha).exclude(af_activo='N')
    for af in alumno_ficha:
        ac = AlumnoCurso()

        ac.alumno = af.alumno
        ac.curso = af.ficha.curso
        ac.ficha = af.ficha
        ac.ac_fechainicio = date_ini
        ac.ac_fechafinalizacioncurso = date_fin
        ac.ac_activo = "S"

        ac.save()

    is_save = True

    try:
        ficha.profesor = Usuario.objects.get(usu_id=request.POST['profesores'])
    except:
        pass
    ficha.ficha_estado = 2
    ficha.save()
    # except Exception as e:
    #     is_save = False
    #     the_error = "type error: " + str(e)

    # *****************************************************************************
    # aqui envio las fechas entre un rango de fechas
    # con ciertos dias de la semana por defecto
    # con el timedelta manejo la creacion de las fechas
    # y con range hago el recorrido

    inicio = date_ini
    fin = date_fin
    contador_fecha = 0
    lst_fechas = []

    listado_dias_semana = ficha.ficha_diasalasemana
    lista_fechas = [inicio + timedelta(days=d) for d in range((fin - inicio).days + 1)]
    for f in lista_fechas:
        la_fecha = f
        # pregunto si el numero de dia de la semana corresponde al numero del dia por defecto
        if str(int(datetime.weekday(la_fecha))+1) in listado_dias_semana.split(':'):
            contador_fecha += 1
            lst_fechas.append({
                'contador_fecha':contador_fecha,
                'fecha':la_fecha
            })
    # *****************************************************************************

    datos = {
        'lst_fechas':lst_fechas,
        'ficha_id': ficha.ficha_id,
    }

    file_template = 'academico/ajax/ajax_horario.html'
    template = get_template(file_template)
    el_html = template.render(datos)

    html = {
        'is_save': is_save,
        'the_error': the_error,
        'el_html':el_html,
        'ficha_id':ficha.ficha_id,
        'estado_nuevo': elige_choices(Ficha.FICHA_ESTADO, ficha.ficha_estado),
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# --------------------
# by osbustaman
# con esta función se asocician los alumnos al curso,
@csrf_exempt
def ajax_datos_academico_ficha(request):

    lst_ficha = []

    ficha = Ficha.objects.get(ficha_id=request.POST['ficha_id'])
    ac_diasdelasemana = ficha.ficha_diasalasemana
    valorhoraprofesor = ficha.ficha_valorhoraprofesor
    tipomoneda = ficha.ficha_tipomoneda

    fecha_ini = datetime.strftime(ficha.ficha_ini, "%d/%m/%Y")
    fecha_fin = datetime.strftime(ficha.ficha_fin, "%d/%m/%Y")

    # *****************************************************************************
    # aqui envio las fechas entre un rango de fechas
    # con el timedelta manejo la creacion de las fechas
    # y con range hago el recorrido

    inicio = ficha.ficha_ini
    fin = ficha.ficha_fin
    contador_fecha = 0
    lst_fechas = []
    try:
        profesor = ficha.profesor.to_string
    except:
        profesor = ""

    listado_dias_semana = ficha.ficha_diasalasemana
    lista_fechas = [inicio + timedelta(days=d) for d in range((fin - inicio).days + 1)]
    for f in lista_fechas:
        la_fecha = f
        # pregunto si el numero de dia de la semana corresponde al numero del dia por defecto
        if str(int(datetime.weekday(la_fecha)) + 1) in listado_dias_semana.split(':'):
            contador_fecha += 1
            lst_fechas.append({
                'contador_fecha': contador_fecha,
                'fecha': la_fecha
            })

    # *****************************************************************************

    datos = {
        'lst_fechas': lst_fechas,
        'ficha_id': ficha.ficha_id
    }

    file_template = 'academico/ajax/ajax_horario.html'
    template = get_template(file_template)
    el_html = template.render(datos)
    try:
        pass
    except:
        fecha_ini = ""
        fecha_fin = ""
        el_html = ""
        ac_diasdelasemana = ""
        profesor = ""
        valorhoraprofesor = ""
        tipomoneda = ""

    html = {
        'lst_ficha': lst_ficha,
        'fecha_ini': fecha_ini,
        'fecha_fin': fecha_fin,
        'ficha_estado': ficha.ficha_estado,
        'el_html':el_html,
        'ac_diasdelasemana':ac_diasdelasemana,
        'valorhoraprofesor':valorhoraprofesor,
        'profesor':profesor,
        'tipomoneda':tipomoneda,
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

@csrf_exempt
def ajax_listado_alumnos_matricula(request):

    lst_alumno_ficha = []
    alumno_ficha = AlumnoFicha.objects.filter(ficha_id=request.POST['ficha_id']).exclude(af_activo='N')
    ficha_id = request.POST['ficha_id']

    for af in alumno_ficha:
        tipo_rut = elige_choices(Alumno.TIPO_RUT, af.alumno.alu_tiporut)
        lst_alumno_ficha.append({
            'alu_id': af.alumno.alu_id,
            'tipo_rut': tipo_rut,
            'alu_tiporut': af.alumno.alu_tiporut,
            'alu_rut': af.alumno.alu_rut,
            'alu_nombre': af.alumno.alu_nombre,
            'alu_apellidopat': af.alumno.alu_apellidopat,
            'alu_apellidomat': af.alumno.alu_apellidomat,
            'alu_mail': af.alumno.alu_mail,
            'alu_sexo': af.alumno.alu_sexo,
            'alu_fono': af.alumno.alu_fono,
            'ficha_estado': af.ficha.ficha_estado,
            'af_essence': af.af_essence,
        })

    datos = {
        'lst_alumno_ficha': lst_alumno_ficha,
        'ficha_id': ficha_id,
    }

    file_template = 'integrado/ajax/ajax_listado_alumnos_matricula.html'
    template = get_template(file_template)
    html = template.render(datos)

    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

@csrf_exempt
def ajax_calendario_academico(request):

    num_inicio = HORA_INI
    num_termino = HORA_FINI
    lst_horas=[]
    lst_sala = []

    for i in range(num_inicio,num_termino):
        tiene_dato = False
        fecha = request.POST['fecha']
        hora_ini = "{h}:00:00".format(h=i)
        fecha_nueva = fecha.split("/")[2] + "-" + fecha.split("/")[1] + "-" + fecha.split("/")[0]
        fecha_hora_ini = fecha_nueva + " " + hora_ini
        fecha_ini = datetime.strptime(fecha_hora_ini, '%Y-%m-%d %H:%M:%S')

        try:

            el_horario = Horario.objects.get(hor_fecha=fecha_ini)
            tiene_dato = True
            sala=el_horario.sala.sala_nombre
            la_ficha = Ficha.objects.get(ficha_id=el_horario.ficha_id)

            # -------------------------------------------
            ficha_id = el_horario.ficha_id
            cur_nombre = la_ficha.curso.cur_nombre
            # -------------------------------------------

            if el_horario.hor_break == 'S':
                is_break = 'SI'
            else:
                is_break = 'NO'

        except:
            sala = ''
            is_break = ''
            ficha_id = ''
            cur_nombre = ''

        lst_horas.append({
            'id_hora':i,
            'hora':"{hora}:00".format(hora=i),
            'tiene_dato':tiene_dato,
            'sala':sala,
            'is_break':is_break,
            'cur_nombre':cur_nombre,
            'ficha_id':ficha_id,
        })

    las_salas = Sala.objects.all()
    for s in las_salas:
        lst_sala.append({
            'sala_id':s.sala_id,
            'sala_nombre':s.sala_nombre,
        })

    datos = {
        'fecha':request.POST['fecha'],
        'lst_horas':lst_horas,
        'las_salas':las_salas,
        'la_ficha':request.POST['ficha_id']
    }

    file_template = 'academico/ajax/ajax_calendario_academico.html'
    template = get_template(file_template)
    html = template.render(datos)

    response = {
        'html':html,
    }

    response = json.dumps(response)
    return HttpResponse(response, content_type='application/json')

# ------------------------------------
@csrf_exempt
def ajax_guardar_horario(request):

    lista_err = []
    lst_dato_response = []

    fecha = request.POST['fecha']
    hora_ini  = "{h}:00:00".format(h=request.POST['id_hora'])
    hora_fin  = "{h}:45:00".format(h=request.POST['id_hora'])

    fecha_nueva = fecha.split("/")[2]+"-"+fecha.split("/")[1]+"-"+fecha.split("/")[0]

    fecha_hora_ini = fecha_nueva + " " + hora_ini
    fecha_hora_fin = fecha_nueva + " " + hora_fin

    fecha_ini = datetime.strptime(fecha_hora_ini, '%Y-%m-%d %H:%M:%S')
    fecha_fin = datetime.strptime(fecha_hora_fin, '%Y-%m-%d %H:%M:%S')

    try:

        sala = Sala.objects.get(sala_id=request.POST['sala'])
        ficha = Ficha.objects.get(ficha_id=request.POST['ficha_id'])

        h = Horario()
        h.hor_fecha = fecha_ini
        h.sala = sala
        h.ficha = ficha
        h.hor_break = request.POST['break']
        h.save()

        if h.hor_break == 'S':
            el_break = 'SI'
        else:
            el_break = 'NO'

        lst_dato_response.append({
            'sala_nombre':sala.sala_nombre,
            'el_break':el_break,
            'fecha_ini':str(fecha_ini),
            'el_curso':ficha.curso.cur_nombre,
            'ficha_id':ficha.ficha_id,
        })
        is_save = True
    except Exception as e:
        # print("type error: " + str(e))
        lista_err.append({
            'the_error': str(e),
        })
        is_save = False

    html = {
        'is_save': is_save,
        'lista_err':lista_err,
        'lst_dato_response':lst_dato_response
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

@csrf_exempt
def obtener_listado_profesores(request):
    lst_profesores = []
    for p in Usuario.objects.filter(usu_tipousuario=5):
        lst_profesores.append({
            'key':p.usu_id,
            'value':p.to_string,
        })
    html = {
        'lst_elementos':lst_profesores
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')
# ------------------------------------
# ******* AREA ACADEMICA *********
# ------------------------------------

# ------------------------------------
# ******* AREA RELATORES *********
# ------------------------------------
def listado_relatores(request):

    lst_profesores = []

    query_set_usuario = Usuario.objects.filter(usu_tipousuario=5)
    if request.POST:
        filtro_usu_activo = request.POST['filtro_usu_activo']
        filtro_usu_extranjero = request.POST['filtro_usu_extranjero']
        if request.POST['filtro_usu_activo']:
            query_set_usuario = query_set_usuario.filter(usu_usuarioactivo = request.POST['filtro_usu_activo'])

        if request.POST['filtro_usu_extranjero']:
            query_set_usuario = query_set_usuario.filter(usu_extranjero = request.POST['filtro_usu_extranjero'])
    else:
        filtro_usu_activo = ""
        filtro_usu_extranjero = ""

    for p in query_set_usuario:
        lst_profesores.append({
            'usu_id':p.usu_id,
            'usu_tiporut_name':elige_choices(Usuario.TIPO_RUT, p.usu_tiporut),
            'usu_tiporut':p.usu_tiporut,
            'usu_rut': p.usu_generadorrut,
            'usu_nombre':p.usu_nombre,
            'usu_apepat':p.usu_apepat,
            'usu_apemat':p.usu_apemat,
            'usu_sexo_name':elige_choices(Usuario.SEXO, p.usu_sexo),
            'usu_sexo':p.usu_sexo,
            'usu_mail':p.usu_mail,
            'usu_fono':p.usu_fono,
            'usu_fechanacimiento':p.usu_fechanacimiento,
            'pais_name': p.pais.pa_nombre,
            'pais': p.pais_id,
            'region_name': p.region.re_nombre,
            'region': p.region_id,
            'comuna_name': p.comuna.com_nombre,
            'comuna': p.comuna_id,
            'usu_direccion': p.usu_direccion,
            'usu_estadocivil': p.usu_estadocivil,
            'usu_profesion': p.usu_profesion,
            'usu_extranjero_name': elige_choices(Usuario.OPCIONES, p.usu_extranjero),
            'usu_extranjero': p.usu_extranjero,
            'usu_usuarioactivo_name': elige_choices(Usuario.OPCIONES, p.usu_usuarioactivo),
            'usu_usuarioactivo': p.usu_usuarioactivo,
        })

    data = {
        'usuario': request.session["dicUsuario"],
        'lst_profesores': lst_profesores,
        'usuarioDocenteForm': UsuarioDocenteForm(),
        'filtro_usu_activo':filtro_usu_activo,
        'filtro_usu_extranjero':filtro_usu_extranjero,
    }
    return render(request, 'academico/listado_relatores.html', data)

# funcion para agregar relator
@csrf_exempt
def ajax_add_relator(request):
    lista_err = []

    form = UsuarioDocenteForm(request.POST or None)

    if form.is_valid():

        if Usuario.objects.filter(usu_mail=request.POST['usu_mail']).exists():
            is_save = 2
        else:

            a = form.save(commit=False)
            a.pais = Pais.objects.get(pa_id=request.POST['key_pais'])
            a.region = Region.objects.get(re_id=request.POST['key_region'])
            a.comuna = Comuna.objects.get(com_id=request.POST['key_comuna'])
            a.usu_tipousuario = 5
            a.save()
            is_save = 1
    else:
        # listado de errores, esto funciona como una especie de debug
        for field in form:
            for error in field.errors:
                lista_err.append({
                    'label': field.label,
                    'error': error,
                })
        is_save = 0

    html = {
        'lista_err': lista_err,
        'is_save': is_save
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# funcion para editar un relator
@csrf_exempt
def ajax_edit_relator(request):
    lista_err = []

    usu_instance = Usuario.objects.get(usu_id=request.POST['hdn_usu_id'])
    form = UsuarioDocenteForm(request.POST or None, instance=usu_instance)

    if form.is_valid():

        a = form.save(commit=False)
        a.pais = Pais.objects.get(pa_id=request.POST['key_pais'])
        a.region = Region.objects.get(re_id=request.POST['key_region'])
        a.comuna = Comuna.objects.get(com_id=request.POST['key_comuna'])
        a.save()
        is_save = 1
    else:
        # listado de errores, esto funciona como una especie de debug
        for field in form:
            for error in field.errors:
                lista_err.append({
                    'label': field.label,
                    'error': error,
                })
        is_save = 0

    html = {
        'lista_err': lista_err,
        'is_save': is_save
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# funcion para anular relator
@csrf_exempt
def ajax_anular_relator(request):

    try:
        del_relator = Usuario.objects.get(usu_tipousuario=5, usu_id=request.POST['usu_id'])
        del_relator.usu_usuarioactivo = 'N'
        del_relator.save()

        is_save=True
        the_error = ''
    except Exception as e:
        is_save = False
        the_error = str(e)

    html = {
        'is_save': is_save,
        'the_error':the_error
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# ------------------------------------
# ******* AREA RELATORES *********
# ------------------------------------

# ------------------------------------
# ******* AREA CURSOS *********
# ------------------------------------
# CREANDO CURSO PARTE 0
def listado_cursos(request, accion):

    """
    Funcion que se encarga de mostrar el views que lista los cursos, crea cursos y configura un curso
    :param request: None
    :param accion: si el dato es add, quiere decir que mostrar el template con el listado de los cursos
                   y dando la opción de crear un curso. De lo contrario lo que trae es el id del curso, dando laopcopn de editar
                   o configurar.
    :return  academico/listado_cursos.html
    """

    if accion == 'add':

        # inicializa formularios
        frmCurso = CursoForm()
        frmFiltroCursosForm = FiltroCursosForm()
        lst_cursos = []

        # -------------------------------------------------
        # bloque hecho para los filtros de las paginas
        query_set = Curso.objects.all()

        if request.POST:
            lst_query = filtros_cabecera(request)
            for l in lst_query:
                frmFiltroCursosForm.fields[l['key']].initial = l['value']
                if l['key'] == 'cur_nivel':
                    query_set = query_set.filter(cur_nivel=l['value'])
                if l['key'] == 'cur_tipobanner':
                    query_set = query_set.filter(cur_tipobanner=l['value'])
                if l['key'] == 'cur_cursoactivo':
                    query_set = query_set.filter(cur_cursoactivo=l['value'])
        # -------------------------------------------------

        # listado de cursos
        for c in query_set:
            lst_cursos.append({
                'cur_id':c.cur_id,
                'cur_nombre':c.cur_nombre,
                'cur_nivel':elige_choices(Curso.NIVEL_CURSO, c.cur_nivel),
                'cur_codigocurso':c.cur_codigocurso,
                'cur_valor':c.cur_valor,
                'cur_duracionhoras':c.cur_duracionhoras,
                'producto':c.producto.prod_nombre.title(),
                'cur_codigosence':c.cur_codigosence,
                'ruta':reverse("integrado_namespace:listado_cursos", args=[c.cur_id])
            })

        data = {
            'usuario': request.session["dicUsuario"],
            'frmFiltroCursosForm': frmFiltroCursosForm,
            'frmCurso': frmCurso,
            'lst_cursos': lst_cursos,
            'accion': accion,
            'ruta_modal': reverse('integrado_namespace:ajax_add_primera_parte_curso', args=[]),
        }
    else:

        # dato del curso
        query_set = Curso.objects.get(cur_id=accion)

        # inicializa el formulario de los datos que faltan del curso
        frmCursoParteDosForm = CursoParteDosForm()
        frmModuloForm = ModuloForm()
        frmClaseForm = ClaseForm()

        # variables de configuracion en la pagina
        tabs_avalible=False
        multimedia = ""
        lst_modulos = []

        if query_set.cur_tabs == '2':
            pass
        if query_set.cur_tabs == '3':
            tabs_avalible = True
            multimedia = query_set.cur_imagen
        if query_set.cur_tabs == '4':
            tabs_avalible = True
            multimedia = query_set.cur_imagen
            los_modulos = Modulo.objects.filter(curso=query_set).order_by('-mod_numero')
            for m in los_modulos:
                lst_modulos.append({
                    'mod_id':m.mod_id,
                    'mod_titulo':m.mod_titulo,
                    'mod_numero':m.mod_numero,
                    'cur_nombre':m.curso.cur_nombre,
                    'mod_activar':m.mod_activar,
                    'ruta_modal_clases': reverse('integrado_namespace:add_clase', args=[accion, m.mod_id]),
                })

        frmCursoParteDosForm.fields['cur_descripcionpequenia'].initial = query_set.cur_descripcionpequenia
        frmCursoParteDosForm.fields['cur_introduccion'].initial = query_set.cur_introduccion
        frmCursoParteDosForm.fields['cur_requerimientos'].initial = query_set.cur_requerimientos
        frmCursoParteDosForm.fields['cur_tipobanner'].initial = query_set.cur_tipobanner
        frmCursoParteDosForm.fields['multimedia'].required = False

        dic_miga_pan = {
            'uno': '<a href="{r}" class="btn btn-default">{n}</a>'.format(r=reverse("integrado_namespace:listado_cursos", args=[query_set.cur_id]), n=query_set.cur_nombre),
            'dos': '<a href="javascript:void();" class="btn btn-dark">{}</a>'.format('módulo'),
        }

        data = {
            'usuario': request.session["dicUsuario"],
            'frmCursoParteDosForm':frmCursoParteDosForm,
            'frmModuloForm':frmModuloForm,
            'frmClaseForm':frmClaseForm,
            'accion':accion,
            'cur_nombre':query_set.cur_nombre,
            'tabs_avalible':tabs_avalible,
            'multimedia':multimedia,
            'ruta_modal': reverse('integrado_namespace:ajax_add_modulo_curso', args=[accion]),
            'lst_modulos':lst_modulos,
            'dic_miga_pan':dic_miga_pan,
        }
    return render(request, 'academico/listado_cursos.html', data)

# CREANDO CURSO PARTE 1
@csrf_exempt
def ajax_add_primera_parte_curso(request):

    """
    Funcion que se encarga de crear una primera instancea en la creación de un curso
    en donde se guardan algunos datos
    :param request: None
    :return response
    """
    lista_err = []
    is_save = False
    cur_id  = ""

    if request.POST:
        form = CursoForm(request.POST)
        if form.is_valid():
            a = form.save(commit=False)

            # crea instancea
            a.producto = Producto.objects.get(prod_id=request.POST['id_producto'])
            a.cur_tabs = 2
            a.save()

            # guarda el codigo y el nombre de la carpeta en
            # donde se guardara el curso
            a.cur_codigocurso = a.creaCodigoCurso.upper()
            a.cur_namefolder  = a.creaCodigoCurso.lower()
            a.save()

            # crea ruta de la carpeta en donde se guardara
            # el curso
            path = UPDATE_CURSOS_PATH + a.cur_namefolder

            # crea carpeta en donde se guardara el curso
            if not os.path.exists(path):
                os.makedirs(path)
                # aquí se crea el archivo
                archi = open(path + '/index.php', 'a')
                # aquí se le crea una linea de texto
                archi.write('<?php header("Location: /"); ?>')
                # se cierra el archivo
                archi.close()

            # os.chmod(path, 777)
            # ruta del directorio del curso
            a.cur_rutaimagenvideo = path
            a.save()

            is_save = True
            cur_id = a.cur_id
            request.session['cur_id'] = a.cur_id

        else:
            # listado de errores, esto funciona como una especie de debug
            for field in form:
                for error in field.errors:
                    lista_err.append({
                        'label': field.label,
                        'error': error,
                    })
            is_save = False

    html = {
        'is_save': is_save,
        'cur_id':cur_id,
        'the_error':lista_err,
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# CREANDO CURSO PARTE 2
@csrf_exempt
def ajax_add_segunda_parte_curso(request, cur_id):

    """
    Funcion que se encarga de subir la imagen principal del curso
    :param request: None
    :param cur_id: id del curso
    :return response
    """

    lista_err = []
    is_save = False

    curso = Curso.objects.get(cur_id=cur_id)

    fileName, fileExtension = os.path.splitext(request.FILES['multimedia'].name)
    fileName = str(fileName).replace('-', '').split(' ')
    fileName = 'banner_{hora}{extension}'.format(na=curso.cur_codigocurso.lower(), hora=time.strftime("%H%M%S"),
                                                      extension=fileExtension)
    contenido_file = curso.cur_rutaimagenvideo+ "/" + fileName

    with open(contenido_file, 'wb+') as destination:
        for chunk in request.FILES['multimedia'].chunks():
            destination.write(chunk)
    destination.close()

    is_save = True
    curso.cur_tipobanner = request.POST['cur_tipobanner']
    curso.cur_imagen = fileName
    curso.cur_descripcionpequenia = request.POST['cur_descripcionpequenia']
    curso.cur_introduccion = request.POST['cur_introduccion']
    curso.cur_requerimientos = request.POST['cur_requerimientos']
    curso.cur_tabs = '3'
    curso.save()

    html = {
        'is_save': is_save,
        'the_error':lista_err
    }
    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# CREANDO CURSO PARTE 3
@csrf_exempt
def ajax_add_modulo_curso(request, cur_id):
    """
    Funcion que crea una instancea de un modulo en la base de datos
    :param request: None
    :param
    :return response
    """
    lista_err = []

    form = ModuloForm(request.POST)

    if form.is_valid():

        query_set = Curso.objects.get(cur_id=cur_id)

        a = form.save(commit=False)
        a.curso = query_set
        a.save()

        query_set.cur_tabs = '4'
        query_set.save()
        is_save = True

    else:
        # listado de errores, esto funciona como una especie de debug
        for field in form:
            for error in field.errors:
                lista_err.append({
                    'label': field.label,
                    'error': error,
                })
        is_save = False

    html = {
        'lista_err': lista_err,
        'is_save': is_save
    }

    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# CREANDO CURSO PARTE 4
def add_clase(request, cur_id, mod_id):
    """
    Funcion que se encarga de armar el template html de las clases
    :param request: None
    :param cur_id: id del curso para asociar la clase
    :return render(request, 'academico/cerrar_ficha.html', data)
    """
    frmClaseForm = ClaseForm()
    lst_clases = []
    query_set = Curso.objects.get(cur_id=cur_id)
    #query_clases = Clase.objects.filter(modulo__curso = query_set).exclude(cl_activarclase = 'N')
    query_clases = Clase.objects.filter(modulo_id = mod_id).exclude(cl_activarclase = 'N')

    for c in query_clases:
        lst_clases.append({
            'cl_id':c.cl_id,
            'modulo':c.modulo_id,
            'cl_titulo':c.cl_titulo,
            'cl_numero':c.cl_numero,
            'cl_introduccion':c.cl_introduccion,
            'cl_tipoclase': c.cl_tipoclase,
            'cl_activarclase': c.cl_activarclase,

            'cl_tipoclase_name':elige_choices(Clase.TIPO_CLASE, c.cl_tipoclase),
            'cl_activarclase_name':elige_choices(Clase.OPCIONES, c.cl_activarclase),
            'ruta_material': reverse('integrado_namespace:add_material_clase', args=[cur_id, mod_id, c.cl_id]),
            'cl_modulo_name': c.modulo.mod_titulo.lower(),
        })

    dic_miga_pan = {
        'uno': '<a href="{r}" class="btn btn-default">{n}</a>'.format(r=reverse("integrado_namespace:listado_cursos", args=[query_set.cur_id]), n=query_set.cur_nombre),
        'dos': '<a href="{r}" class="btn btn-default">módulo</a>'.format( r=reverse("integrado_namespace:listado_cursos", args=[query_set.cur_id])),
        'tres':'<a href="javascript:void();" class="btn btn-dark">{}</a>'.format('clases'),
    }

    data = {
        'usuario': request.session["dicUsuario"],
        'frmClaseForm': frmClaseForm,
        'ruta_modal': reverse('integrado_namespace:ajax_add_clase', args=[mod_id]),
        'miga_pan': "{} / modulo / clases".format(query_set.cur_nombre),
        'lst_clases': lst_clases,
        'dic_miga_pan': dic_miga_pan,
    }
    return render(request, 'academico/add_clases.html', data)

# CREANDO CURSO PARTE 5
@csrf_exempt
def ajax_add_clase(request, mod_id):
    """
    Funcion que crea una instancea de una clase en la base de datos
    :param request: None
    :param cur_id : id del curso para asociar la clase
    :return response
    """

    lista_err = []

    try:
        la_clase = Clase.objects.get(cl_id=request.POST['flag_extra'])
        form = ClaseForm(request.POST, instance=la_clase)
    except:
        form = ClaseForm(request.POST or None)

    if form.is_valid():

        query_set_modulo = Modulo.objects.get(mod_id=mod_id)

        a = form.save(commit=False)
        a.modulo = query_set_modulo
        a.save()

        is_save = True

    else:
        # listado de errores, esto funciona como una especie de debug
        for field in form:
            for error in field.errors:
                lista_err.append({
                    'label': field.label,
                    'error': error,
                })
        is_save = False

        print(lista_err)

    html = {
        'lista_err': lista_err,
        'is_save': is_save
    }

    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# CREANDO CURSO PARTE 6.1
@csrf_exempt
def delete_clase_curso(request, cl_id):
    """
    Funcion que crea una instancea de materiales en la base de datos
    :param request: None
    :param cur_id : id del curso para asociar el material a la clase
    :return response
    """
    lista_err = []
    is_save = False
    la_clase = Clase.objects.get(cl_id = cl_id)
    la_clase.cl_activarclase = 'N'
    la_clase.save()

    return redirect('integrado_namespace:add_clase', la_clase.modulo.curso_id, la_clase.modulo_id)

# CREANDO CURSO PARTE 6
def add_material_clase(request, cur_id, mod_id, cl_id):
    """
    Funcion que se encarga de armar el template html de las clases
    :param request: None
    :param cur_id: id del curso para asociar la clase
    :return render(request, 'academico/cerrar_ficha.html', data)
    """
    frmMaterialForm = MaterialForm()
    lst_materiales = []
    query_set = Curso.objects.get(cur_id=cur_id)
    query_set_materiales = Material.objects.filter(clase_id = cl_id).exclude(mat_materialactivo = 'N')

    for m in query_set_materiales:

        lst_materiales.append({
            'mat_id':m.mat_id,
            'mat_titulo':m.mat_titulo,
            'mat_numero':m.mat_numero,
            'mat_numero':m.mat_numero,
            'mat_tipomaterial':elige_choices(Material.TIPO_MATERIAL, m.mat_tipomaterial),
            'cl_id':m.clase.cl_id,
            'mat_texto':m.mat_texto,
            'mat_rutayoutube':m.mat_rutayoutube,
            'id_mat_tipomaterial': m.mat_tipomaterial,
            'mat_nombrearchivo': m.mat_nombrearchivo,
        })

    dic_miga_pan = {
        'uno'   : '<a href="{r}" class="btn btn-default">{n}</a>'.format(r=reverse("integrado_namespace:listado_cursos", args=[query_set.cur_id]), n=query_set.cur_nombre),
        'dos'   : '<a href="{r}" class="btn btn-default">{n}</a>'.format(r=reverse("integrado_namespace:listado_cursos", args=[query_set.cur_id]), n='módulo'),
        'tres'  : '<a href="{r}" class="btn btn-default">{n}</a>'.format(r=reverse("integrado_namespace:add_clase", args=[cur_id, mod_id]), n='clases'),
        'cuatro': '<a href="javascript:void();" class="btn btn-dark">{}</a>'.format('materiales'),
    }

    data = {
        'usuario': request.session["dicUsuario"],
        'frmMaterialForm': frmMaterialForm,
        'ruta_modal': reverse('integrado_namespace:ajax_add_material_clase_curso', args=[cur_id, cl_id]),
        'dic_miga_pan': dic_miga_pan,
        'lst_materiales': lst_materiales,
    }
    return render(request, 'academico/add_material.html', data)

# CREANDO CURSO PARTE 6.1
@csrf_exempt
def ajax_add_material_clase_curso(request, cur_id, cl_id):
    """
    Funcion que crea una instancea de materiales en la base de datos
    :param request: None
    :param cur_id : id del curso para asociar el material a la clase
    :return response
    """
    lista_err = []

    try:
        el_material = Material.objects.get(mat_id=request.POST['flag_extra'])
        form = MaterialForm(request.POST, instance=el_material)
    except:
        form = MaterialForm(request.POST or None)

    if form.is_valid():

        query_set = Curso.objects.get(cur_id=cur_id)

        if request.FILES:

            fileName, fileExtension = os.path.splitext(request.FILES['multimedia'].name)
            fileName = str(fileName).replace('-', '').split(' ')
            fileName = 'archivo_{hora}{extension}'.format(na=query_set.cur_codigocurso.lower(),
                                                          hora=time.strftime("%H%M%S"),
                                                          extension=fileExtension)
            contenido_file = query_set.cur_rutaimagenvideo + "/" + fileName

        query_set_clase = Clase.objects.get(cl_id = cl_id)
        a = form.save(commit=False)
        a.clase = query_set_clase

        if request.FILES:
            a.mat_rutaarchivo = query_set.cur_rutaimagenvideo
            a.mat_nombrearchivo = fileName

        a.save()

        is_save = True

        if request.FILES:
            with open(contenido_file, 'wb+') as destination:
                for chunk in request.FILES['multimedia'].chunks():
                    destination.write(chunk)
            destination.close()

    else:
        # listado de errores, esto funciona como una especie de debug
        for field in form:
            for error in field.errors:
                lista_err.append({
                    'label': field.label,
                    'error': error,
                })
        is_save = False

    html = {
        'lista_err': lista_err,
        'is_save': is_save
    }

    response = json.dumps(html)
    return HttpResponse(response, content_type='application/json')

# CREANDO CURSO PARTE 6.2
@csrf_exempt
def delete_material_clase_curso(request, mat_id):
    """
    Funcion que crea una instancea de materiales en la base de datos
    :param request: None
    :param cur_id : id del curso para asociar el material a la clase
    :return response
    """
    lista_err = []
    is_save = False
    el_material = Material.objects.get(mat_id = mat_id)
    el_material.mat_materialactivo = 'N'
    el_material.save()

    return redirect('integrado_namespace:add_material_clase', el_material.clase.modulo.curso_id)

# ------------------------------------
# ******* AREA CURSOS *********
# ------------------------------------

# ------------------------------------
# ******* AREA FICHAS/ALUMNO/CURSO *********
# ------------------------------------

def cerrar_ficha(request):

    data = {
        'usuario': request.session["dicUsuario"],
    }
    return render(request, 'academico/cerrar_ficha.html', data)

def dar_plazo_ficha(request):

    data = {
        'usuario': request.session["dicUsuario"],
    }
    return render(request, 'academico/dar_plazo_ficha.html', data)

def dar_plazo_alumno(request):

    data = {
        'usuario': request.session["dicUsuario"],
    }
    return render(request, 'academico/dar_plazo_alumno.html', data)

# ------------------------------------
# ******* AREA CURSOS *********
# ------------------------------------


from bs4 import BeautifulSoup
import urllib.request
import os
import time

def main():
    # 先爬取4页代理ip
    # 保存在本地
    get_web()

    # 读取文件 1.txt等格式
    # 提取IP:PORT字段
    get_info()

def get_web():
    get_web_list = ['http://www.xicidaili.com/nn/', 'http://www.xicidaili.com/nt/', 'http://www.xicidaili.com/wn/', 'http://www.xicidaili.com/wt/']

    for x in range(0,len(get_web_list)):

        req = urllib.request.Request(get_web_list[x])
        req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36')

        response = urllib.request.urlopen(req)
        html = response.read().decode('utf-8')

        filename = str(x+1) + ".txt"
        fo = open(filename, "w+")
        fo.write(html)
        fo.close()

        time.sleep(3)

def get_info():

    file_name = ".txt"
    ip_port_list = []

    for x in range(1,5):
        real_name = str(x)+file_name

        info = open(real_name, "r+")
        info = info.read()

        soup=  BeautifulSoup(info, "html.parser")
        test = soup.find_all('td')

        n = 1
        m = 2
        i = 0

        max_num = int(len(test) / 10)

        while i < max_num:
            num_n = str(test[n]).find('	')
            num_m = str(test[m]).find('	')
            ip_port_list.append("%s:%s" % (str(test[n])[4:num_n], str(test[m])[4:num_m]))
            n += 10
            m += 10
            i += 1

    fo = open('IP_PORT.txt', "w")
    for x in range(1,len(ip_port_list)):
        str_test =  ip_port_list[x] + "\n"
        fo.writelines(str_test)
    fo.close()

if __name__ == '__main__':
    main()


# ibrahim fazil
# 8/8/16
# practicing text to voice feature
#

# obj.setBrightness(var = 4, device = 'dimmer', value = 55)

from Alexa import *
from time import *

NIGHT_STAND = '192.168.2.16:49153'
DINING_ROOM = '192.168.2.17:49154'

ITERATIONS = 5

obj = Alexa()
obj.setProperty('rate',-100)
obj.setProperty('volume',4)
obj.connectLocal()

while ITERATIONS > 0:
	obj.say("alexa")
	obj.changeStatus(status = 1, device = 'night stand')
	obj.run()
	obj.getResponse()
	obj.wait()
	obj.confirmStatus(expectedValue = 1, hostip = NIGHT_STAND)
	obj.say("alexa")
	obj.changeStatus(status = 0, device = 'night stand')
	obj.run()
	obj.getResponse()
	obj.wait()
	obj.confirmStatus(expectedValue = 0, hostip = NIGHT_STAND)
	obj.say("alexa")
	obj.changeStatus(status = 1, device = 'dining room')
	obj.run()
	obj.getResponse()
	obj.wait()
	obj.confirmStatus(expectedValue = 1, hostip = DINING_ROOM)
	obj.say("alexa")
	obj.changeStatus(status = 0, device = 'dining room')
	obj.run()
	obj.getResponse()
	obj.wait()
	obj.confirmStatus(expectedValue = 0, hostip = DINING_ROOM)
	ITERATIONS -= 1


import csv
data = []
keys = []
spaces = [4, 6, 8, 10]
with open('C:\\Users\\JUNK\\Desktop\\School\\pp1\\05-ModularProgramming\\zadania\\employees.csv', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        keys = row.keys()
        data.append(row)

def displayHeader():
    order = [1,0,2,3]
    s = "#"+" "*spaces[0]
    for a in order:
        s+=keys[a]+" "*spaces[a]
    print(s)
    print("="*75)
displayHeader()


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

 Stat 202A 2019 Fall - Homework 01
 Author:
 Date :

 INSTRUCTIONS: Please fill in the corresponding function. Do not change function names,
 function inputs or outputs. Do not write anything outside the function.
 Do not use any of Python's built in functions for matrix inversion or for linear modeling
 (except for debugging or in the optional examples section).

"""

import numpy as np

###############################################
## Function 1: (2a) Uniform 				 ##
###############################################

def sample_uniform(low=0, high=1):
	random = np.zeros(10000)
	randomy = np.zeros(10000)

	m = 2**31 - 1
	a = 7**5
	c = 12345

	  # Set the seed using the current system time in microseconds
	import time
	d = int(time.time())

	for i in range (0,10000):
		d = (a * d + c) % m
		random[i] = d / m * (high - low) + low

	for i in range (0,9999):
		randomy[i] = random[i+1]

	import matplotlib.pyplot as plt
	fig1 = plt.figure('Figure1',figsize = (6,4)).add_subplot(111)
	fig1.hist(random)
	fig2 = plt.figure('Figure2',figsize = (6,4)).add_subplot(111)
	fig2.scatter(random,randomy)
	plt.show()

###############################################
## Function 2: (2b) Exponential				 ##
###############################################

def sample_exponential(k=1):
	import math
	randomu = np.zeros(10000)
	randomx = np.zeros(10000)
	r = np.zeros(10000)

	m = 2 ** 31 - 1
	a = 7 ** 5
	c = 12345

	  # Set the seed using the current system time in microseconds
	import time
	d = int(time.time())

	for i in range(0,10000):
	    d = (a * d + c) % m
	    randomu[i] = d / m
	    randomx[i] = - (math.log(randomu[i])) / k

	import matplotlib.pyplot as plt
	plt.hist(randomx)
	plt.show()

###############################################
## Function 3: (2c) Normal	 				 ##
###############################################

def sample_normal(mean=0, var=1):
	import math
	import time
	d1 = int(time.time() * 500 * math.exp(2))
	d2 = int(time.time() * 500 * math.exp(1))
	randomu1 = np.zeros(10000)
	randomu2 = np.zeros(10000)
	theta = np.zeros(10000)
	t = np.zeros(10000)
	r = np.zeros(10000)
	x = np.zeros(10000)
	y = np.zeros(10000)

	m = 2 ** 31 - 1
	a = 7 ** 5
	c = 12345

	for i in range (0,10000):
	    d1 = (a * d1 + c) % m
	    d2 = (a * d2 + c) % m
	    randomu1[i] = d1 / m
	    randomu2[i] = d2 / m
	    theta[i] = 2 * math.pi * randomu1[i]
	    t[i] = - math.log(randomu2[i])
	    r[i] = (2 * var * t[i]) ** (1/2)
	    x[i] = r[i]*math.cos(theta[i]) + mean
	    y[i] = r[i]*math.sin(theta[i]) + mean

	import matplotlib.pyplot as plt
	fig1 = plt.figure('Figure4',figsize = (6,6)).add_subplot(111)
	fig1.scatter(x,y)
	fig2 = plt.figure('Figure5',figsize = (6,4)).add_subplot(111)
	fig2.hist(t)
	plt.show()

###############################################
## Function 4: (3) Monte Carlo 				 ##
###############################################

def monte_carlo(d=2):
	ds = []
	random = []
	n = 0

	m = 2 ** 31 - 1
	a = 7 ** 5
	c = 12345

	for i in range (1, d+1):
		ds.append(int(time.time() * 500 * math.exp(i)))
		random.append(np.zeros(1000000))
	for i in range (0,1000000):
		squaresum = 0
		for j in range (0, d):
			ds[j] = (a * ds[j] + c) % m
			random[j][i] = ds[j]/m   #j is dimension, i is iteration
			squaresum += random[j][i]**2 # sum of squares
		if squaresum <= 1:
			n = n + 1
	volume = n * (2**d) / 1000000
	print ("volume="+str(volume))
	if d == 2:
		pi1 = 4 * n / 1000000
		print ("pi="+str(pi1))

########################################################
## Optional examples (comment out before submitting!) ##
########################################################

## test()


# importing libraries
import time
import subprocess
import numpy
import math

# declaring an empty list to store average signal strength value at 10 different locations
Y = []
ssid = 'FasterThanSonic'  # ssid for which parameters are to be determined

# function to calculate average value of signal strength at a particular location by taking 20 readings of
# signal strength at that location
def average_rssi():
    avg = 0
    for num in range(20):
        subprocess.run(['netsh', 'interface', 'set', 'interface', 'name="Wi-Fi"', 'admin=disabled'])
        subprocess.run(['netsh', 'interface', 'set', 'interface', 'name="Wi-Fi"', 'admin=enabled'])
        time.sleep(4)

        # getting the result of command line command and storing it in a variable
        result = subprocess.check_output(["netsh", "wlan", "show", "network", "mode=Bssid"])

        # converting the result(datatype-bytes) first into string and then storing substrings in list y
        cmd_output_list = list((result.decode('ASCII')).split())

        i_SSID = [index for index, x in enumerate(cmd_output_list) if x == 'SSID']
        i_Network = [index for index, x in enumerate(cmd_output_list) if x == 'Network']
        i_Signal = [index for index, x in enumerate(cmd_output_list) if x == 'Signal']

        for m in range(len(i_SSID)):
            c = cmd_output_list[(i_SSID[m] + 3):i_Network[m]]
            c = tuple(c)
            s = " "
            if s.join(c) == ssid:
                a = cmd_output_list[i_Signal[m] + 2]
                a = a[0: len(a) - 1]
                dbm = ((int(a)) / 2) - 100
                avg += dbm
                break

        time.sleep(20)

    avg /= 20
    return avg

# getting the average value of signal strength at 10 different locations and storing it in the list Y
for i in range(10):
    rssi = average_rssi()
    Y.append(rssi)
    print(Y)
    time.sleep(5)

print(Y)
# converting list Y into a numpy array


from JumpScale import j
import yaml

CATEGORY = "ays:bp"

class Blueprint:
    """
    """

    def __init__(self, aysrepo, path="", content=""):
        self.logger = j.logger.get('j.atyourservice.blueprint')
        self.aysrepo = aysrepo
        self.path = path
        self.active = True
        self.models = []  # can be actions or services or recurring
        self.actions = []
        self.eventFilters = []
        self._contentblocks = []

        if path != "":
            self.name = j.sal.fs.getBaseName(path)
            if self.name[0] == "_":
                self.active = False
            self.name = self.name.lstrip('_')
            self.content = j.sal.fs.fileGetContents(path)
        else:
            self.name = 'unknown'
            self.content = content

        self.is_valid = self._validate_yaml(self.content)

        if self.is_valid:
            content = ""
            nr = 0
            # we need to do all this work because the yaml parsing does not
            # maintain order because its a dict
            for line in self.content.split("\n"):
                if len(line) > 0 and line[0] == "#":
                    continue
                if content == "" and line.strip() == "":
                    continue

                line = line.replace("\t", "    ")
                nr += 1
                if len(content) > 0 and (len(line) > 0 and line[0] != " "):
                    self._add2models(content, nr)
                    content = ""

                content += "%s\n" % line

            # to process the last one
            self._add2models(content, nr)
            self._contentblocks = []

            self.hash = j.data.hash.md5_string(self.content)

            self.is_valid = self._validate_format(self.models)

    def load(self, role="", instance=""):
        self.actions = []
        self.eventFilters = []

        for model in self.models:
            if model is not None:

                if "actions" in model:
                    # found action need to add them to blueprint
                    for actionModel in model["actions"]:
                        if 'actor' not in actionModel:
                            actor0 = ""
                        else:
                            actor0 = actionModel["actor"]
                        if 'service' not in actionModel:
                            service0 = ""
                        else:
                            service0 = actionModel["service"]
                        if 'recurring' not in actionModel:
                            recurring0 = ""
                        else:
                            recurring0 = actionModel["recurring"]
                        servicesFound = self.aysrepo.servicesFind(name=service0, actor=actor0)

                        if len(servicesFound) == 0:
                            raise j.exceptions.Input(message="found action to execute but could not find required service:%s!%s" % (
                                actor0, service0), level=1, source="", tags="", msgpub="")

                        if "action" not in actionModel:
                            raise j.exceptions.Input(message="need to specify action.",
                                                     level=1, source="", tags="", msgpub="")

                        actions = [item.strip() for item in actionModel["action"].split(",") if item.strip() != ""]

                        for serviceObj in servicesFound:
                            for actionName in actions:
                                self.actions.append({
                                    'service_key': serviceObj.model.key,
                                    'action_name': actionName,
                                    'recurring_period': recurring0,
                                })

                elif "eventfilters" in model:
                        # found action need to add them to blueprint
                    for obj in model["eventfilters"]:
                        if 'actor' not in obj:
                            actor0 = ""
                        else:
                            actor0 = obj["actor"]
                        if 'service' not in obj:
                            service0 = ""
                        else:
                            service0 = obj["service"]
                        if 'channel' not in obj:
                            channel0 = ""
                        else:
                            channel0 = obj["channel"]
                        if 'cmd' not in obj:
                            cmd0 = ""
                        else:
                            cmd0 = obj["cmd"]
                        if 'secret' not in obj:
                            secret0 = ""
                        else:
                            secret0 = obj["secret"]
                        if 'action' not in obj:
                            action0 = ""
                        else:
                            action0 = obj["action"]

                        servicesFound = self.aysrepo.servicesFind(name=service0, actor=actor0)

                        if len(servicesFound) == 0:
                            raise j.exceptions.Input(message="found action to execute but could not find required service:%s!%s" % (
                                actor0, service0), level=1, source="", tags="", msgpub="")

                        for serviceObj in servicesFound:
                            self.eventFilters.append({
                                'service_key': serviceObj.model.key,
                                'channel': channel0,
                                'command': cmd0,
                                'secret': secret0,
                                'action_name': action0,
                            })

                else:
                    for key, item in model.items():
                        if key.find("__") == -1:
                            raise j.exceptions.Input(
                                "Key in blueprint is not right format, needs to be $aysname__$instance, found:'%s'" % key)
                        actorname, bpinstance = key.split("__", 1)

                        if instance != "" and bpinstance != instance:
                            self.logger.info(
                                "ignore load from blueprint for: %s:%s" % (actorname, bpinstance))
                            continue

                        if actorname.find(".") != -1:
                            rolefound, _ = actorname.split(".", 1)
                        else:
                            rolefound = actorname

                        if role != "" and role != rolefound:
                            self.logger.info(
                                "ignore load from blueprint based on role for: %s:%s" % (actorname, bpinstance))
                            continue

                        # check if we can find actorname and if not then check if there is a blueprint.  name...
                        if not self.aysrepo.templateExists(actorname) and not actorname.startswith('blueprint.'):
                            blueaysname = 'blueprint.%s' % actorname
                            if self.aysrepo.templateExists(blueaysname):
                                actorname = blueaysname

                        if not self.aysrepo.templateExists(actorname):
                            raise j.exceptions.Input(message="Cannot find actor:%s" %
                                                     actorname, level=1, source="", tags="", msgpub="")

                        actor = self.aysrepo.actorGet(actorname, reload=False)
                        args = {} if item is None else item
                        actor.serviceCreate(instance=bpinstance, args=args)

        # first we had to make sure all services do exist, then we can add these properties
        for action_info in self.actions:
            service = self.aysrepo.serviceGetByKey(action_info['service_key'])
            service.scheduleAction(action_info['action_name'], period=action_info['recurring_period'])
            service.saveAll()

        for event_filter in self.eventFilters:
            service = self.aysrepo.serviceGetByKey(event_filter['service_key'])
            service.model.eventFilterSet(
                channel=event_filter['channel'], action=event_filter['action_name'],
                command=event_filter['command'], secrets=event_filter['secret'])
            service.saveAll()

    def _add2models(self, content, nr):
        # make sure we don't process double
        if content in self._contentblocks:
            return
        self._contentblocks.append(content)
        try:
            model = j.data.serializer.yaml.loads(content)
        except Exception as e:
            msg = "Could not process blueprint (load from yaml):\npath:'%s',\nline: '%s', content:\n######\n\n%s\n######\nerror:%s" % (
                self.path, nr, content, e)
            raise j.exceptions.Input(msg)

        self.models.append(model)

    @property
    def services(self):
        services = []
        for model in self.models:

            if model is not None:
                for key in model.keys():

                    aysname, aysinstance = key.split("__", 1)
                    if aysname.find(".") != -1:
                        rolefound, _ = aysname.split(".", 1)
                    else:
                        rolefound = aysname

                    service = self.aysrepo.serviceGet(role=rolefound, instance=aysinstance, die=False)
                    if service:
                        services.append(service)

        return services

    def disable(self):
        if self.active:
            base = j.sal.fs.getBaseName(self.path)
            dirpath = j.sal.fs.getDirName(self.path)
            newpath = j.sal.fs.joinPaths(dirpath, "_%s" % base)
            j.sal.fs.moveFile(self.path, newpath)
            self.path = newpath
            self.active = False

    def enable(self):
        if self.active is False:
            base = j.sal.fs.getBaseName(self.path)
            if base.startswith("_"):
                base = base[1:]
            dirpath = j.sal.fs.getDirName(self.path)
            newpath = j.sal.fs.joinPaths(dirpath, base)
            j.sal.fs.moveFile(self.path, newpath)
            self.path = newpath
            self.active = True

    def _validate_yaml(self, content):
        try:
            j.data.serializer.yaml.loads(content)
            return True
        except yaml.YAMLError:
            raise j.exceptions.Input('Yaml format is not valid for %s please fix this to continue' % self.name)

    def _validate_format(self, models):
        for model in models:
            if not j.data.types.dict.check(model):
                self.logger.error("Bad formatted blueprint: %s" % self.path)
                return False

            if model is not None:
                for key in model.keys():

                    # this two blocks doesn't have the same format as classic service declaration
                    if key in ['actions', 'eventfilters']:
                        if not j.data.types.list.check(model[key]):
                            self.logger.error("%s should be a list of dictionary: found %s" % (key, type(model[key])))
                            return False
                    else:
                        if key.find("__") == -1:
                            self.logger.error("Key in blueprint is not right format, needs to be $aysname__$instance, found:'%s'" % key)
                            return False

                        aysname, _ = key.split("__", 1)
                        if aysname not in self.aysrepo.templates:
                            self.logger.error("Service template %s not found. Can't execute this blueprint" % aysname)
                            return False

        return True

    def validate(self):
        if not self._validate_yaml(self.content):
            return False

        if not self._validate_format(self.models):
            return False

        return True

    def __str__(self):
        return "%s:%s" % (self.name, self.hash)

    __repr__ = __str__


from django.db import models

class Node(models.Model):
    slug = models.SlugField(null=False, blank=False)
    content = models.TextField(blank=False, null=False)
    creator = models.CharField(max_length=254, blank=False, null=False)
    created = models.DateTimeField(auto_now_add=True, null=False)
    changelog = models.TextField(null=True, blank=True)

    def __unicode__(self):
        return u'%s' % self.slug

    @property
    def revision(self):
        rev = Node.objects.filter(slug=self.slug, created__lte=self.created)
        return rev.count()


import math
def rotateImageNotInPlace(a):
    #first one that doesn't meet the memory constraints
    rotated_array = [[] for i in range(len(a))]
    for i in range(len(a)-1,-1,-1):
        for j in range(len(a[i])):
            rotated_array[j].append(a[i][j])

    return rotated_array

def rotate_circ_in_array_1_step(a,topleft_idx):
    step_threshold = len(a) - 2*topleft_idx[0] - 1
    first_i = topleft_idx[0]
    first_j = topleft_idx[1]
    first = a[first_i][first_j]
    current_i = topleft_idx[0]
    current_j = topleft_idx[1]
    steps_stepped = 0
    while steps_stepped < step_threshold:
        prev_i = current_i + 1
        prev_j = current_j
        a[current_i][current_j] = a[prev_i][prev_j]
        current_i = prev_i
        current_j = prev_j
        steps_stepped += 1
    steps_stepped = 0
    while steps_stepped < step_threshold:
        prev_i = current_i
        prev_j = current_j + 1
        a[current_i][current_j] = a[prev_i][prev_j]
        current_i = prev_i
        current_j = prev_j
        steps_stepped += 1
    steps_stepped = 0
    while steps_stepped < step_threshold:
        prev_i = current_i - 1
        prev_j = current_j
        a[current_i][current_j] = a[prev_i][prev_j]
        current_i = prev_i
        current_j = prev_j
        steps_stepped += 1
    steps_stepped = 0
    while steps_stepped < step_threshold - 1:
        prev_i = current_i
        prev_j = current_j - 1
        a[current_i][current_j] = a[prev_i][prev_j]
        current_i = prev_i
        current_j = prev_j
        steps_stepped += 1
    steps_stepped = 0
    right_of_topleft_i = topleft_idx[0]
    right_of_topleft_j = topleft_idx[1] + 1
    a[right_of_topleft_i][right_of_topleft_j] = first

    return a

def rotateImage(a):
    #idea is in a circle around the middle elt (have to think about case where there is a middle square also) reassign values in chains that form
    #concentric circles throughout the whole array
    #would be hard to do this under time pressure but is cool
    #would actually use around n/2 extra slots but it's the best
    #i got right now
    #how do we go in concentric circles basically by having a go_right bool
    #and go_down, go_up, and go_left bools that update in different inter
    #vals depending on which concentric circle youre in
    #which you would figure out by the indices
    N = len(a)
    num_circles = math.floor(N/2)
    #printAsSquare(a)
    for i in range(num_circles):
        topleft_idx = [i,i]
        step_threshold = len(a) - 2*topleft_idx[0] - 1
        print("topleft_idx[0]:")
        print(topleft_idx[0])
        print("step_threshold:")
        print(step_threshold)
        for j in range(step_threshold):
            a = rotate_circ_in_array_1_step(a,topleft_idx)
        #printAsSquare(a)
    return a
"""
def printAsSquare(a):
    for i in range(len(a)):
        print(a[i])
    print()

a = [[1,2,3], [4,5,6], [7,8,9]]
b = [[10,9,6,3,7], [6,10,2,9,7], [7,6,3,8,2], [8,9,7,9,9], [6,8,6,8,2]]
printAsSquare(rotateImage(a))
printAsSquare(b)
printAsSquare(rotateImage(b))
"""


from unittest import mock
from ojd_daps.flows.enrich.labs.salaries.regex.single_regex_utils import (
    regex_model,
    save_model,
    load_model,
    apply_model,
)

PATH = "ojd_daps.flows.enrich.labs.salaries.regex.single_regex_utils.{}"

def test_regex_model():
    regex = r"(\d*[.]?\d*)"

    model = regex_model(regex, "min")
    assert model("100.0 to 1000.0") == 100.0
    assert model("1000 and 7777.234 - 88.123") == 88.123

    model = regex_model(regex, "max")
    assert model("100.0 to 1000.0") == 1000.0
    assert model("1000 and 7777.234 - 88.123") == 7777.234

    model = regex_model(regex, "mean")
    assert model("100.0 to 1000.0") == 550.0
    assert model("1000 and 7777.234 - 88.123") == 2955.119

    model = regex_model(regex, "median")
    assert model("100.0 to 1000.0") == 550.0
    assert model("1000 and 7777.234 - 88.123") == 1000.0

@mock.patch(PATH.format("save_to_s3"))
def test_save_model(mocked_save_to_s3):
    save_model("a", "b")
    ((args1, kwargs1), (args2, kwargs2)) = mocked_save_to_s3.call_args_list
    assert args1 == ("regex.txt", "a")
    assert args2 == ("picker.txt", "b")

@mock.patch(PATH.format("load_from_s3"), side_effect=lambda x: x)
@mock.patch(PATH.format("regex_model"), side_effect=lambda x, y: (x, y))
def test_load_model(mocked_s3, mocked_model):
    assert load_model() is load_model()  # Check the cache is "working"
    assert load_model() == ("regex.txt", "picker.txt")

@mock.patch(PATH.format("load_model"), side_effect=lambda: (lambda x: x.upper()))
@mock.patch(PATH.format("guess_rate"), side_effect=lambda x: x.lower().title())
def test_apply_model(mocked_load, mocked_guess):
    row = {"job_salary_raw": "hello"}
    assert apply_model(row) == ("HELLO", "Hello")


import unittest
import test_rest_resource
import requests
from datetime import date
from model.project import Project, get_project_from_json

class TestProjects(test_rest_resource.TestRestResource):

    def setUp(self):
        super(TestProjects, self).setUp()
        self.resource_name = 'project'
        self.resources_uri = self.root_uri + 'projects'
        self.single_resource_uri = self.resources_uri + '/1'
        self.example_resource = Project(
            name="Test Project",
            description="some description",
            start_date=date(2013, 1, 1),
            end_date=date(2014, 12, 31),
            status=1,
            owner=1,
            invited_devs=[],
            sprints=[],
            id_=2
        )

        self.update_resource = Project(
            name="Updated Test Project",
            description="some updated description",
            start_date=date(2013, 1, 2),
            end_date=date(2014, 12, 2),
            status=2,
            owner=2,
            invited_devs=[1],
            sprints=[],
            id_=2
        )

        self.invalid_create_new_json = [
            # Not a json object
            'Test',

            # Missing status
            '{"description": "some description", "end_date": "2014-12-31", "start_date": "2013-01-01", "owner": 1, "name": "Test Project"}',

            # Missing description
            '{"status": 1, "end_date": "2014-12-31", "start_date": "2013-01-01", "owner": 1, "name": "Test Project"}',

            # Missing end_date
            '{"status": 1, "description": "some description", "start_date": "2013-01-01", "owner": 1, "name": "Test Project"}',

            # Missing start_date
            '{"status": 1, "description": "some description", "end_date": "2014-12-31", "owner": 1, "name": "Test Project"}',

            # Missing owner
            '{"status": 1, "description": "some description", "end_date": "2014-12-31", "start_date": "2013-01-01", "name": "Test Project"}',

            # Missing name
            '{"status": 1, "description": "some description", "end_date": "2014-12-31", "start_date": "2013-01-01", "owner": 1}',

            # Additional non-existing field (a)
            '{"status": 1, "description": "some description", "end_date": "2014-12-31", "start_date": "2013-01-01", "owner": 1, "name": "Test Project", "a": "a"}',

            # Additional existing field (id)
            '{"status": 1, "description": "some description", "end_date": "2014-12-31", "start_date": "2013-01-01", "owner": 1, "name": "Test Project", "id":1}'
        ]

        self.invalid_update_json = [
            # Non-existing field
            '{"a": "a"}',
        ]

    def test_invite_developers(self):
        method = requests.put
        uri = self.single_resource_uri + '/invite_dev'
        data = '{"email":"vimal@chellakudam"}'
        self.ensure_unauthorized_fails_authorized_passes(method, uri, 204, data=data)

    def test_remove_developers(self):
        method = requests.put
        uri = self.single_resource_uri + '/remove_devs'
        data = '{"devs":[3, 4]}'
        self.ensure_unauthorized_fails_authorized_passes(method, uri, 204, data=data)

    def get_resource_from_json(self, json_str):
        return get_project_from_json(json_str)

if __name__ == '__main__':
    unittest.main()


import unittest

from house_robber_iii import rob, TreeNode

class HouseRobberIIITests(unittest.TestCase):
    """Tests for house robber iii challenge"""

    def test_case_1(self):
        root = TreeNode(3,
                        TreeNode(2,
                                 None,
                                 TreeNode(3)),
                        TreeNode(3,
                                 None,
                                 TreeNode(1)))
        self.assertEqual(rob(root), 7)

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


"""200803_main.py"""
"""네이버 클라우드 API에서 제공하는 CSR 모듈을 활용한 음성을 텍스트로 변환하는 프로그램"""

"""녹음한 음성을 글자로 변경하는 모듈"""

"""
네이버 클라우드 API중 CSR API를 활용함
"""

"""1. 필요한 모듈"""
# 음성을 글로
import requests

"""2. 음성 파일을 글자로 변경"""

def csrFunc(cloudApi_clientId, cloudApi_clientSecret, wantToText):
    """음성을 글자로"""
    """2-1. 어떤 언어의 음성 파일을 변경할 것인지 입력 - 현재 가능한 것은 Eng와 Kor"""
    # inputLang = input('언어를 입력하세요: ')  # lang = "Eng" # 언어 코드 ( Kor, Jpn, Eng, Chn )

    """2-2. 네이버 CSR API를 활용하기 위해서 필요한 정보"""
    url = "https://naveropenapi.apigw.ntruss.com/recog/v1/stt?lang=Kor" # + inputLang
    data = open(wantToText, 'rb')
    headers = {
        "X-NCP-APIGW-API-KEY-ID": cloudApi_clientId,
        "X-NCP-APIGW-API-KEY": cloudApi_clientSecret,
        "Content-Type": "application/octet-stream"
    }
    response = requests.post(url, data=data, headers=headers)
    rescode = response.status_code
    if (rescode == 200):  # 응답이 성공했으면
        response_data = response.json()
        sttResult = response_data['text']
        return sttResult # 글자로 나온 결과와 설정해준 언어를 반환
    else:  # 200(성공)으로 떨어지지 않으면 이유를 출력. 음성 파일에 말이 없어도 에러가 떨어짐
        print("Error : " + response.text)


from flask import Flask, request, jsonify

app = Flask (__name__)

@app.route('/')
def index():
    # stuurt inteface naar browser.
    return app.send_static_file('index.html')

@app.route('/light', methods=['GET'])
def light():
    data = {}
    #zet licht aan. Voeg commando's toe!
    #bevestig licht aan.
    data['light'] = 'ON'
    # converteer dict naat json en print naar interface.
    return jsonify(data)

@app.route('/light', methods=['POST'])
def lightPOST():
    data = request.get_json()
    data['light'] = not data['light']
    return jsonify(data)

if __name__ == "__main__":
    app.run(debug=True)


import numpy as np
import csv
import urllib3
import os

def maybe_download(filename, source_url, work_directory):
    """Download the filename from the source url into the working directory if it does not exist."""
    if not os.path.exists(work_directory):
        os.makedirs(work_directory)
    filepath = os.path.join(work_directory, filename)
    if not os.path.exists(filepath):
        urllib3.disable_warnings()
        with urllib3.PoolManager() as http:
            r = http.request('GET', source_url)
            with open(filepath, 'wb') as fout:
                fout.write(r.read())

        print('{} succesfully downloaded'.format(filename))
    return filepath

def write_file(file_path, text_path, num_tokens):
    total_num_tokens = 0
    print(f'Writing to {file_path}...')
    with open(file_path, 'w', encoding='utf-8') as f_out:
        writer = csv.writer(f_out)
        with open(text_path, 'r') as f:
            for i, text in enumerate(f):

                writer.writerow([text])
                # f_out.write(text)

                # calculate approximate length based on tokens
                total_num_tokens += len(text.split())
                if total_num_tokens > num_tokens:
                    break
                if i % 10000 == 0:
                    print('Processed {:,} documents. Total # tokens: {:,}.'.format(i, total_num_tokens))
    print('{}. # documents: {:,}. # tokens: {:,}.'.format(file_path, i, total_num_tokens))

if __name__=='__main__':
    write_file('assets/val.csv','assets/wikitext-103/valid.txt',1000000)
    write_file('assets/train.csv', 'assets/wikitext-103/train.txt', 1000000)


import math

n=int(input())
number=input()
total=1
p=[7,5,3,2]
a=[]

def Digits(n):

    largest = 0

    while (n):
        r = n % 10
        largest = max(r, largest)

        n = n // 10

    return largest

maxdig=Digits(int(number))
print(maxdig)
for i in number:
    k=int(i)
    f=math.factorial(k)
    total=total*f
print(total)
t=1
for i in p:
    if i<=maxdig:
        count=0
        while t*math.factorial(i)<=total and (total//t)%i==0:
            t=t*math.factorial(i)
            a.append(i)
            count+=1

    else:
        continue
print(t)
for i in a:
    print(i,end="")


from ftw.solr.interfaces import ISolrConnectionManager
from ftw.solr.interfaces import ISolrSettings
from ftw.upgrade import UpgradeStep
from plone.registry.interfaces import IRegistry
from zope.component import getUtility
import logging

logger = logging.getLogger('opengever.core')

class FixDocsOnlyPartiallyIndexedInSolr(UpgradeStep):
    """Fix docs only partially indexed in solr.

    We think affected documents may have been not indexed in solr at all due to
    a bug with date serialization in `ftw.solr`. The bug was only fixed in
    https://github.com/4teamwork/ftw.solr/pull/158.

    Subsequent edits of the document by users via plone or reindex operations
    during upgrades would have partially indexed or restored the document in
    solr, but only some of the fields as we use atomic updates.

    We've seen that all affected documents do not have the created date set as
    we never manually reindex it, as it never changes. Thus apply a heuristic
    to detect broken solr documents. We assume that broken documents do not
    have the field 'created' set to a value in solr.
    """

    deferrable = True

    @property
    def is_solr_enabled(self):
        registry = getUtility(IRegistry)
        settings = registry.forInterface(ISolrSettings)
        return settings.enabled

    def __call__(self):
        if not self.is_solr_enabled:
            return

        self.solr_connection = getUtility(ISolrConnectionManager).connection
        broken_docs = self.find_broken_solr_docs()
        for doc in broken_docs:
            self.reindex_broken_doc(doc)

    def find_broken_solr_docs(self):
        """This method purposefully bypasses ISolrSearch.

        We have to build our own query as ISolrSearch would insert security
        filters for 'allowedRolesAndUsers'. But there are broken solr docs
        where the 'allowedRolesAndUsers' is missing.
        """
        params = {
            u'offset': 0,
            # this queries for all docs where the `created` field is not set
            u'query': u'-created:[* TO *]',
            # choose a very high number well beyond the number of docs we can
            # possibly have, but also well below java max 4 byte int 2147483647
            u'limit': 99999999,
            # only return the UID field
            u'params': {
                u'fl': u'UID'
            }
        }

        solr_response = self.solr_connection.search(
            params, request_handler=u'/select')
        return solr_response.docs

    def reindex_broken_doc(self, doc):
        """Reindex all fields/indexes for a broken solr document.
        """
        plone_uid = doc[u'UID']
        # Do not duplicate this upgrade step as is. Querying the catalog
        # for each object will trigger flushing of the indexing queue,
        # i.e. the indexing queue gets processed for every object...
        brains = self.catalog_unrestricted_search({u'UID': plone_uid})
        if len(brains) != 1:
            logger.error(
                u'Could not find a unique brain for the UID={}'.format(
                    plone_uid)
            )
            return

        brain = brains[0]
        obj = self.catalog_unrestricted_get_object(brain)
        # `catalog_unrestricted_get_object` takes care of logging already
        if obj:
            # we reindex the whole object as we cannot know which fields are
            # missing, also do catalog reindex for convenience
            obj.reindexObject()


import asyncio

@bot.on(admin_cmd(pattern="undlt ?(.*)"))
@bot.on(sudo_cmd(pattern="undlt ?(.*)", allow_sudo=True))
async def _(event):
    if event.fwd_from:
        return
    if event.pattern_match.group(1):
        try:
            marcus = int(event.pattern_match.group(1))
            input_str = marcus
        except Exception:
            input_str = 5
    else:
        input_str = 5
    s = await event.get_chat()
    if s.admin_rights or s.creator:
        a = await event.client.get_admin_log(
            event.chat_id, limit=input_str, search="", edit=False, delete=True
        )
        for i in a:
            await event.reply(i.original.action.message)
    else:
        event = await edit_or_reply(
            event, "`You need administrative permissions in order to do this command`"
        )
        await asyncio.sleep(3)
        await event.delete()

CMD_HELP.update(
    {
        "undlt": "**Plugin :** `undlt`\
        \n**Syntax : **`.undlt <count>`\
        \n**Usage: **Fetches last <count> number of deleted messages and sends you(you must be admin in that group)  \
"
    }
)


"""RbiCloud URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from cloud import views
from django.conf.urls import handler404
from django.conf.urls import handler500
import django.views.static
from RbiCloud import settings

urlpatterns = [
    # path('static/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.STATIC_ROOT, 'show_indexes': settings.DEBUG}),
    ########################## Base ################################
    path('admin/', admin.site.urls),
    path('', views.signin, name='home'),
    path('basecitizen/',views.Base_citizen,name='basecitizen'),
    path('basemanagement/', views.base_manager, name= 'basemanager'),
    path('basebusiness/',views.base_business,name='basebusiness'),
    path('business/', views.business_home, name='business'),
    path('equipment/', views.base_equipment, name='equipment'),
    path('component/', views.base_component, name='componentmanagement/'),
    path('proposal/', views.base_proposal, name='prosal'),
    path('risksummary/', views.base_risksummary, name='risk'),
    path('designcode/', views.base_designcode, name='designcode'),
    path('manufacture/', views.base_manufacture, name= 'manufacture'),
    path('basereport/', views.base_report,name='basereport'), #Dat sua
    ########################## Facility UI################################
    path('damage/thining/<int:proposalID>/', views.ShowThining, name='thining'),
    path('damage/governing/<int:proposalID>/', views.ShowGoverning, name='governing'),
    path('inspection/plan/<int:siteID>/', views.MainInpsectionPlan, name='inspectionPlan'),
    path('inspection/plan/<int:siteID>/<int:planID>/damageMechanism', views.DamamgeMechanism, name='damageMechanism'),
    path('inspection/plan/<int:siteID>/InpsectionPlan<str:name>/InpsectionPlan<str:date>/', views.MainInpsectionPlan,name='inspectionPlan'),
    path('add/<int:siteID>/<int:facilityID>/<int:equipID>/<str:name>/<str:date>/plan/', views.AdddInssepctionPlan,name='addInspectionPlan'),
    path('create/<int:siteID>/plan/', views.CreateInspectionPlan, name='createInspectionPlan'),
    path('facilities/display/<int:siteID>/', views.ListFacilities, name='facilitiesDisplay'),
    path('facilities/<int:siteID>/new/', views.NewFacilities, name='facilitiesNew'),
    path('facilities/<int:facilityID>/edit/', views.EditFacilities, name= 'facilitiesEdit'),
    path('designcode/display/<int:siteID>/', views.ListDesignCode, name='designcodeDisplay'),
    path('designcode/<int:siteID>/new/', views.NewDesignCode, name='designcodeNew'),
    path('designcode/<int:designcodeID>/edit/', views.EditDesignCode, name='designcodeEdit'),
    path('manufacture/display/<int:siteID>/', views.ListManufacture, name='manufactureDisplay'),
    path('manufacture/<int:siteID>/new/', views.NewManufacture , name='manufactureNew'),
    path('manufacture/<int:manufactureID>/edit/', views.EditManufacture, name='manufactureEdit'),
    path('equipment/display/<int:facilityID>/', views.ListEquipment, name='equipmentDisplay'),
    path('equipment/<int:facilityID>/new/', views.NewEquipment, name='equipmentNew'),
    path('equipment/<int:equipmentID>/edit/', views.EditEquipment, name='equipmentEdit'),
    path('component/display/<int:equipmentID>/', views.ListComponent, name='componentDisplay'),
    path('component/<int:equipmentID>/new/', views.NewComponent , name='componentNew'),
    path('component/<int:componentID>/edit/', views.EditComponent, name='componentEdit'),
    path('proposal/display/<int:componentID>/', views.ListProposal, name='proposalDisplay'),
    path('proposal/<int:componentID>/new/', views.NewProposal, name='proposalNew'),
    path('tank/<int:componentID>/new/', views.NewTank , name='tankNew'),
    path('proposal/<int:proposalID>/edit/', views.EditProposal, name='prosalEdit'),
    path('tank/<int:proposalID>/edit/', views.EditTank, name='tankEdit'),
    path('proposal/<int:proposalID>/risk-matrix/', views.RiskMatrix, name='riskMatrix'),
    path('proposal/<int:proposalID>/damage-factor/', views.FullyDamageFactor, name='damgeFactor'),
    path('proposal/<int:proposalID>/chart/', views.RiskChart, name='riskChart'),
    path('proposal/<int:proposalID>/fully-consequence/',views.FullyConsequence, name='fullyConsequence'),
    path('propasal/<int:proposalID>/areaBased-CoF/',views.AreaBasedCoF, name='areaBasedCoF'),
    path('export/<int:index>/<str:type>/', views.ExportExcel, name='exportData'),
    path('site/<int:siteID>/upload/InspectionHistory/', views.uploadInspPlan, name='upload'),
    path('site/<int:siteID>/upload/Plan/', views.upload, name='uploadPlan'),
    path('ManagmentSystems/<int:facilityID>/', views.ManagementSystems, name='managmentsystems'),
    # path('site/<int:siteID>/upload/DCS-SCADA/', views.uploadSCADA, name='uploadScada'),
    ########################## forum ################################
    path('forum/',views.base_forum,name='forum'),
    path('forum/post/<int:postID>',views.posts_forum,name='posts'),
    path('logout',views.logout,name='logout'),
    ########################## Messages ################################
    path('messagesinbox/',views.MessagesInbox,name='messagesInbox'),
    path('messagessent/',views.Email_Message_sent,name='messagesSent'),
    ########################## Help ################################
    path('help/',views.Help, name='help'),
    path('help/UserManual/Citizen',views.Help_Usermanual_Citizen,name='helpUserManualCtizen'),
    path('help/UserManual/Business',views.Help_Usermanual_Business,name='helpUserManualBusiness'),
    path('help/UserManual/Manager',views.Help_Usermanual_Manager,name='helpUserManualManager'),
    path('help/AccountManagement/LoginPasswork',views.Help_AccountManagement_LoginPass,name='LoginPasswork'),
    path('help/AccountManagement/PersonalInfor',views.Help_AccountManagement_PerInfo,name='perinfor'),
    path('help/AccountManagement/AccessDownload',views.Help_AccountManagement_AccessDownload,name='accdownload'),
    path('help/AccountManagement/notification',views.Help_AccountManagement_Notification,name='notification'),
    path('help/PrivateSafe/',views.Private_Safe,name='PrivateSafe'),
    path('help/PoliciesReports/',views.Policies_Reports,name='PoliciesReports'),
    ########################## Dang ki tai khoan ################################
    path('AccountCitizen/', views.AccountCitizen, name='accountcitizen'),
    path('AccountBusiness/',views.AccountBusiness, name='accountbusiness'),
    path('AccountManagement',views.AccountManagement,name='accountmanagement'),
    path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate'),
    ########################## Manager UI################################
    path('management/<int:siteID>/', views.ManagerHome, name= 'manager'),
    # Cuong bo sung 12/8/2020 => thiet ke giao dien hang mmuc co quan quan li
    path('management/<int:siteID>/Home/', views.ManagerHomeDetail, name= 'managerhomedetail'),
    path('management/<int:siteID>/CalculateFunction/', views.CalculateFunctionManager, name= 'calculatefunctionmanager'),
    path('management/<int:siteID>/ToolManager/', views.ToolManager, name= 'toolmanager'),
    path('manufactureMana/display/<int:siteID>/', views.ListManufactureMana, name='manufactureDisplayMana'),
    path('designcodeMana/display/<int:siteID>/', views.ListDesignCodeMana, name='designcodeDisplayMana'),
    path('facilitiesMana/display/<int:siteID>/', views.ListFacilitiesMana, name='facilitiesDisplayMana'),
    path('equipmentMana/display/<int:facilityID>/', views.ListEquipmentMana, name='equipmentDisplayMana'),
    path('componentMana/display/<int:equipmentID>/', views.ListComponentMana, name='componentDisplayMana'),
    path('proposalMana/display/<int:componentID>/', views.ListProposalMana, name='proposalDisplayMana'),
    path('proposalMana/<int:proposalID>/data/', views.Inputdata, name='inputdata'),
    path('proposalMana/<int:proposalID>/damage-factor/', views.FullyDamageFactorMana, name='damgeFactorMana'),
    path('proposalMana/<int:proposalID>/chart/', views.RiskChartMana, name='riskChartMana'),
    path('proposalMana/<int:proposalID>/risk-matrix/', views.RiskMatrixMana, name='riskMatrixMana'),
    path('proposalMana/<int:proposalID>/fully-consequence/',views.FullyConsequenceMana, name='fullyConsequenceMana'),
#testCuong
    path('proposal/<int:proposalID>/corrisionRate/', views.CorrisionRate, name='corrision'),
    path('proposal/<int:proposalID>/caculated/', views.CaculateCorrision, name='Caculate'),
    ############# Verification #############
    path('proposalManaVeri/<int:proposalID>/damage-factor/', views.VeriFullyDamageFactorMana, name='veridamgeFactorMana'),
    path('proposalManaVeri/<int:proposalID>/fully-consequence/',views.VeriFullyConsequenceMana, name='verifullyConsequenceMana'),
    path('verification/<int:faciid>',views.VerificationHome,name='VerificationHome'),
    path('verification/<int:verifiID>/Check',views.VerificationCheck,name='VerificationCheck'),
    path('verificationFaci',views.VerificationNumberFacilities,name='VerificationFaci'),
    ######################### Citizen UI ##############################
    path('citizen/', views.citizen_home, name= 'citizenHome'),
    path('facilityCitizen/display/<int:siteID>/',views.ListfacilityCitizen, name='facilityCitizen'),
    path('ListProposalCitizen/display/<int:facilityID>/<int:siteID>/',views.ListProposalCitizen, name='ListProposalCitizen'),
    path('proposalCitizen/<int:proposalID>/risk-matrix/', views.RiskMatrixCitizen, name='riskMatrixCitizen'),
    path('proposalCitizen/<int:proposalID>/damage-factor/', views.FullyDamageFactorCitizen, name='damgeFactorCitizen'),
    path('proposalCitizen/<int:proposalID>/chart/', views.RiskChartCitizen, name='riskChartCitizen'),
    path('proposalCitizen/<int:proposalID>/fully-consequence/',views.FullyConsequenceCitizen, name='fullyConsequenceCitizen'),
    #############connect thingsboard _____ sensor, gateway #############
    path('newsensor/<int:componentID>/', views.NewSensor, name='newsensor'),
    path('sensor/<int:componentID>/chart/', views.DataChart, name='sensorchart'),
    # Datdz
    path('report/', views.ReportMana, name='reportmana'),
    path('reportfac/<int:siteID>/', views.ReportFacilities, name='reportfacilities'),
    path('reportequip/<int:facilityID>/', views.ReportEquipment, name='reportequipment'),
    path('reportcomp/<int:equipmentID>/', views.ReportComponent, name='reportcomponent'),
    path('reportproposal/<int:componentID>/', views.ReportProposal, name='reportproposal'),
    path('propasal/<int:proposalID>/areaBased-CoF-shell/',views.AreaBasedCoFShell, name='AreaBasedCoFShell')
]
'''
Dkm cuong luong
'''
handler500 = 'cloud.views.handler404'
handler404 = 'cloud.views.handler404'


import re
file = open('/media/baptiste/A68AF7698AF73481/Users/bapti/Documents/OneDrive/Documenten/unief/1ste master/1ste semester/bio-informatics/uniprot_sprot.fasta')
list = file.readlines()
sequence_list = []
for i in range(0,len(list)):
	temp = list[i]
	if temp[0] != '>':
		sequence_list.append(temp[0:len(temp)-2])

#count the amino acids in the sequences

AA = 'ACDEFGHIKLMNPQRSTVWY'
counters=[0]*len(AA)

for i in range(0,len(AA)):
	for j in range(0,len(sequence_list)):
		temp_seq=sequence_list[j]
		temp_counter=temp_seq.count(AA[i])
		counters[i]=counters[i]+temp_counter
print(sum(counters))


from OmniBot import OmniBot
from discord import Embed
from discord.ext import commands

class Eval:
    def __init__(self, bot: OmniBot):
        self.bot = bot
        return

    @commands.command(aliases=["evaluate", "calculate", "math"])
    async def eval(self, context: commands.context.Context, *equation):
        result = eval(''.join(equation))
        embed = Embed(colour=0xd44e52)
        embed.set_author(name=context.author.name, icon_url=context.author.avatar_url)
        embed.add_field(name="Result", value=result, inline=False)
        embed.set_footer(text="Does your maths for you.")
        await context.send(embed=embed)
        return

def setup(bot):
    bot.add_cog(Eval(bot))


"""
Write function scramble(str1,str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

For example:
str1 is 'rkqodlw' and str2 is 'world' the output should return true.
str1 is 'cedewaraaossoqqyt' and str2 is 'codewars' should return true.
str1 is 'katas' and str2 is 'steak' should return false.

Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered
"""

def scramble(s1,s2):
    alfavit = 'abcdefghijklmnopqrstuvwxyz'
    str1_az = {a: 0 for a in alfavit}
    str2_az = {a: 0 for a in alfavit}
    result = {a: 0 for a in alfavit}
    for char in s1:
        str1_az[char] += 1
    for char in s2:
        str2_az[char] += 1
    for char in alfavit:
        result[char] = str2_az[char] - str1_az[char]
    for char in alfavit:
        if result[char] > 0: return False
    return True

if __name__ == '__main__':
    print(scramble('rkqodlw', 'wworld'), "True")
    print(scramble('cedewaraaossoqqyt', 'codewars'), True)
    print(scramble('katas', 'steak'), False)
    print(scramble('scriptjava', 'javascript'), True)
    print(scramble('scriptingjava', 'javascript'), True)


#!/usr/bin/env python3
from sys import stderr, exit

def get_line():
    raw_line = input().strip()
    if raw_line[0] != "#":
        return raw_line, None
    key = raw_line[1:].strip().split()[0].upper()
    if key == "END" or key == "NEXT":
        return None, key
    return None, "GEN_COMMENT"

def get_lines_from_stream(same_length = True, order_matters = False, unique = True, checks=[]):
    """ Puts the sequence of lines fed in into a list or a set (which one of the two depends on the value of the parameter 'order_matters'). In the case of a set the parameter `unique` set to True has the effect to assess unicity in the input stream. The input stream is ended with a line like '# END'."""
    print('#? waiting for a stream of lines. Insert a closing line "# END" after the last row of the table.')
    def get_line():
        raw_line = input().strip()
        if raw_line[0] != "#":
            return raw_line, None
        key = raw_line[1:].strip().split()[0].upper()
        if key == "END" or key == "NEXT":
            return None, key
        return None, "GEN_COMMENT"

    first_line, cmd = get_line()
    while first_line == None:
        first_line, cmd = get_line()

    if order_matters:
        collected_lines = [first_line]
    else:
        collected_lines = {first_line}

    previous_line = first_line
    next_line, cmd = get_line()
    while cmd != "END":
        if cmd == "NEXT":
            print("# Warning: I have asked for one single stream! I will assume this line was a comment and proceed reading and loading the previous table line by line.")
        elif next_line != None:
            if same_length and len(next_line) != len(previous_line):
                print(f"# Error (in the input stream of lines): The line {len(collected_lines)} has length different than the previous lines in the stream. This is not a valid stream here.")
                exit(1)
            previous_line = next_line
            if order_matters:
                collected_lines.append(next_line)
            else:
                if unique and (not order_matters) and next_line in collected_lines:
                    print(f"# Error (in the input stream of lines): The line {len(collected_lines)} is identical to a previous line in the stream. Repetitions are not valid here.")
                    exit(1)
                collected_lines.add(next_line)

        next_line, cmd = get_line()
    print("# FILE GOT")
    return collected_lines