from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.models import User,Permission
from django.utils.encoding import force_bytes,force_text
from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode
from django.template.loader import render_to_string
from django.contrib.auth import login
from django.views.generic import ListView, DetailView
from django import forms
from django_filters.views import FilterView
from django_tables2.views import SingleTableMixin
from .tables import CategoriaTable,PerfilTable,GastoTable
from .filters import CategoriaFilter,PerfilFilter,GastoFilter
from .models import Categorias,Perfiles,Gastos
from .forms import GastoForm,CategoriaForm,PerfilForm,SignUpForm
from .tokens import account_activation_token
from django.core.mail import send_mail

from .functions import obtenerPerfiles,formatear_informacion_del_perfil,envia_email_confirmacion,obtener_gasto_mas_caro,obtener_gasto_mas_barato,obtener_gasto_total_y_mensual

def index(request):
    p = obtenerPerfiles(request.user)
    perfiles = None
    if p != None:
        perfiles = formatear_informacion_del_perfil(p)
    return render(request, 'mainGastos/index.html',{'perfiles':perfiles})

def cuenta_activada(request):
    return render(request, 'registration/account_activation_email_success.html')

#CRUD de categorías
def categoria_list(request):
    table = CategoriaTable(Categorias.objects.all().filter(usuario=request.user))
    mensajeNoCategorias = False
    notTheOwner = False

    if not Categorias.objects.filter(usuario=request.user):
        mensajeNoCategorias = True
    return render(request, "crud/categoria/listar_categoria.html", {
        "table": table,
        "mensajeNoCategorias":mensajeNoCategorias
    })

def categoria_view(request, pk, template_name='crud/categoria/detalle_categoria.html'):
    categoria = get_object_or_404(Categorias, pk=pk)
    return render(request, template_name, {'object':categoria})

def categoria_create(request, template_name='crud/categoria/categoria_create_form.html'):
    form = CategoriaForm(request.POST or None)
    if form.is_valid():
        f = form.save(commit=False)
        f.usuario = request.user
        f.save()
        return redirect('listar_categoria')
    return render(request, template_name, {'form':form})

def categoria_update(request, pk, template_name='crud/categoria/categoria_form.html'):
    categoria= get_object_or_404(Categorias, pk=pk)
    form = CategoriaForm(request.POST or None, instance=categoria)
    isOwner = False
    userOfCategory = Categorias.objects.get(id=pk).usuario
    if (request.user == userOfCategory):
        isOwner = True
    if form.is_valid():
        form.save()
        return redirect('listar_categoria')
    return render(request, template_name, {'form':form,'isOwner':isOwner})

def categoria_delete(request, pk, template_name='crud/categoria/categoria_confirm_delete.html'):
    categoria= get_object_or_404(Categorias, pk=pk)
    isOwner = False
    userOfCategory = Categorias.objects.get(id=pk).usuario
    if (request.user == userOfCategory):
        isOwner = True
    if request.method=='POST':
        categoria.delete()
        return redirect('listar_categoria')
    return render(request, template_name, {'object':categoria,'isOwner':isOwner})

#CRUD de perfiles

def perfil_list(request):
    table = PerfilTable(Perfiles.objects.all().filter(usuario=request.user))
    mensajeNoPerfiles = False

    if not Perfiles.objects.filter(usuario=request.user):
        mensajeNoPerfiles = True
    return render(request, "crud/perfil/listar_perfil.html", {
        "table": table,
        "mensajeNoPerfiles":mensajeNoPerfiles
    })

    return render(request, "crud/perfil/listar_perfil.html", {
        "table": table
    })

def perfil_view(request, pk, template_name='crud/perfil/detalle_perfil.html'):
    perfil = get_object_or_404(Perfiles, pk=pk)
    return render(request, template_name, {'object':perfil})

def perfil_create(request, template_name='crud/perfil/perfil_create_form.html'):
    form = PerfilForm(request.POST or None)
    if form.is_valid():
        f = form.save(commit=False)
        f.usuario = request.user
        f.save()
        return redirect('listar_perfil')
    return render(request, template_name, {'form':form})

def perfil_update(request, pk, template_name='crud/perfil/perfil_form.html'):
    perfil= get_object_or_404(Perfiles, pk=pk)
    form = PerfilForm(request.POST or None, instance=perfil)
    isOwner = False
    userOfProfile = Perfiles.objects.get(id=pk).usuario
    if (request.user == userOfProfile):
        isOwner = True
    if form.is_valid():
        form.save()
        return redirect('listar_perfil')
    return render(request, template_name, {'form':form,'isOwner':isOwner})

def perfil_delete(request, pk, template_name='crud/perfil/perfil_confirm_delete.html'):
    perfil= get_object_or_404(Perfiles, pk=pk)
    isOwner = False
    userOfProfile = Perfiles.objects.get(id=pk).usuario
    if (request.user == userOfProfile):
        isOwner = True
    if request.method=='POST':
        perfil.delete()
        return redirect('listar_perfil')
    return render(request, template_name, {'object':perfil,'isOwner':isOwner})

#CRUD de gastos

def gasto_list(request,plk):
    table = GastoTable(Gastos.objects.all().filter(fk_id_perfil=plk))
    nombre_perfil = Perfiles.objects.get(id=plk)
    mensajeNoGastos = False

    if not Gastos.objects.filter(fk_id_perfil=nombre_perfil):
        mensajeNoGastos = True
    return render(request, "crud/gasto/listar_gasto.html", {
        "table": table,
        "perfilN":plk,
        "nombre_perfil":nombre_perfil,
        "mensajeNoGastos":mensajeNoGastos
    })

def gasto_view(request, pk,plk, template_name='crud/gasto/detalle_gasto.html'):
    gasto = get_object_or_404(Gastos, pk=pk)
    return render(request, template_name, {'object':gasto})

def gasto_create(request,plk, template_name='crud/gasto/gasto_create_form.html'):
    perfil = Perfiles.objects.get(id=plk)
    user = perfil.usuario
    existenCategorias = False
    categorias = Categorias.objects.filter(usuario=user)
    if(categorias):
        existenCategorias = True
    form = GastoForm(request.POST or None)
    isOwner = False
    if (request.user == user):
        isOwner = True
    if form.is_valid():
        f = form.save(commit=False)
        f.fk_id_categoria = Categorias.objects.get(id=request.POST['categoria'])
        f.fk_id_perfil = perfil
        f.usuario = request.user
        f.save()
        return redirect('listar_gasto', plk)
    return render(request, template_name, {'existenCategorias':existenCategorias,'categorias':categorias,'form':form,'isOwner':isOwner})

def gasto_update(request, pk,plk, template_name='crud/gasto/gasto_form.html'):
    gasto= get_object_or_404(Gastos, pk=pk)
    form = GastoForm(request.POST or None, instance=gasto)
    isOwner = False
    userOfGasto = Gastos.objects.get(id=pk).fk_id_categoria.usuario
    if (request.user == userOfGasto):
        isOwner = True
    if form.is_valid():
        form.save()
        return redirect('listar_gasto', plk)
    return render(request, template_name, {'form':form,'isOwner':isOwner})

def gasto_delete(request, pk,plk, template_name='crud/gasto/gasto_confirm_delete.html'):
    gasto= get_object_or_404(Gastos, pk=pk)
    isOwner = False
    userOfGasto = Gastos.objects.get(id=pk).fk_id_categoria.usuario
    if (request.user == userOfGasto):
        isOwner = True
    if request.method=='POST':
        gasto.delete()
        return redirect('listar_gasto', plk)
    return render(request, template_name, {'object':gasto,'isOwner':isOwner})

#Registro de Usuario
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            envia_email_confirmacion(user,current_site,urlsafe_base64_encode(force_bytes(user.pk)),account_activation_token.make_token(user))
            return redirect('account_activation_sent')
    else:
        form = SignUpForm()
    return render(request, 'registration/signup.html', {'form': form})

def account_activation_sent(request):
    return render(request, 'registration/account_activation_sent.html')

def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.profile.email_confirmed = True

        #Añadir permisos de edicion y borrado de perfiles,categorias y gastos
        permisoEditaPerfiles = Permission.objects.get(name='Can change perfiles')
        permisoBorraPerfiles = Permission.objects.get(name='Can delete perfiles')
        permisoEditaCategorias = Permission.objects.get(name='Can change categorias')
        permisoBorraCategorias = Permission.objects.get(name='Can delete categorias')
        permisoEditaGastos = Permission.objects.get(name='Can change gastos')
        permisoBorraGastos = Permission.objects.get(name='Can delete gastos')

        user.user_permissions.add(permisoEditaPerfiles)
        user.user_permissions.add(permisoBorraPerfiles)
        user.user_permissions.add(permisoEditaCategorias)
        user.user_permissions.add(permisoBorraCategorias)
        user.user_permissions.add(permisoEditaGastos)
        user.user_permissions.add(permisoBorraGastos)

        user.save()
        login(request, user)
        return redirect('c_activada')
    else:
        return render(request, 'registration/account_activation_invalid.html')

#Resumen de un perfil
def resumen(request,plk):
    perfil = Perfiles.objects.get(id=plk)

    isOwner = False
    userOfProfile = perfil.usuario
    if (request.user == userOfProfile):
        isOwner = True

    try:
        informacion = {}
        informacion['nombre_perfil'] = perfil.nombre
        informacion['gasto_total'] = obtener_gasto_total_y_mensual(perfil)[1]
        informacion['mas_caro'] = obtener_gasto_mas_caro(perfil)
        informacion['mas_barato'] = obtener_gasto_mas_barato(perfil)
        return render(request, 'mainGastos/resumen.html',{'isOwner':isOwner,'informacion': informacion})
    except:
        return render(request, 'mainGastos/resumen.html',{'isOwner':isOwner,'informacion': None,'plk':plk})

    #if not Gastos.objects.filter(fk_id_perfil=nombre_perfil):
    #    mensajeNoGastos = True
    #return render(request, "crud/gasto/listar_gasto.html", {
    #    "table": table,
    #    "perfilN":plk,
    #    "nombre_perfil":nombre_perfil,
    #    "mensajeNoGastos":mensajeNoGastos
    #})


# plots a Fourier expansion of a rectangular wave
from pylab import *

# prepare the plot
figure()
hold(True)

# number of points to display the wave
N = 2**8
t = linspace(0, 1, N)
y = zeros(N)

for n in range(1, 8, 2):
    # the sine waves, added
    y += 4/(pi*n)*sin(2*pi*n*t*2)

    # plot the graph
    plot(t, y)

# annotate the graph
axis([0, 1, -1.4, 1.4])
grid()
xlabel('Time [seconds]')
ylabel('Value []')
title('Fourier expansion of a rectangular wave')
savefig('../images/fourier_expansion.png', dpi=150)


#Number Guessing Game Objectives:

# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Track the number of turns remaining.
# If they run out of turns, provide feedback to the player.
# Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode).

import random
from art import logo
from replit import clear

def lives(level):
  """Takes Level response and returns life count"""
  if level == "easy":
    tries = 10
  elif level == "hard":
    tries = 5
  else:
    print("Invalid Entry")
  return tries

print(logo)
number = random.randint(1, 100) #this will give me a random number to use
level = input("Welcome to Guessing Game: Easy or Hard?\n").lower()
#print(level)
#print(number)
tries = lives(level)
#print(tries)

game_in_play = True

while game_in_play != False:
  while tries > 0:
    guess = int(input(f"You have {tries} attempts left, What number do you guess?"))
    if tries == 0:
      print("Game Over")
      game_in_play = False
    elif guess == number:
      print("You guessed correctly!")
      game_in_play = False
    elif guess > number:
      print("Your guess is too high")
      tries -= 1
    elif guess < number:
      print("Your guess is too Low")
      tries -= 1
    else:
      game_in_play = False
  print("Game Over")
  game_in_play = False


# ============================= C R E D I T S =============================
# Authors: Sophia Sun, Thomas Wang
# Date: June 25, 2020
# Purpose: Dominoes Game with GUI Interface
# Note: Special Thanks to Mr. Smith of ICU3U1 at Milliken Mills High School
# =========================================================================

from DominoHand import *
from Domino import *

class DominoTable :
    def __init__ (self, canvas, x = 0, y = 0): #x,y is mididle of canvas
        self.list1 = [] #auto starts with 66 so don't append it into the list just drop it out maxwidth = 620
        self.start = 6 #startvalue
        self.end = 6 #end value
        self.x = x #x coord to start
        self.y = y #ycoord to start
        self.canvas = canvas #canvas
        self.frontRows = 0 #rows appended to front
        self.backRows = 0 #rows appended to back
        self.xLength1 = x #x axis of the front
        self.xLength2 = x # x axis of the back
        self.yLength1 = y # y axis of the front
        self.yLength2 = y # y axis of the back

    def drawFirst(self): #draws the 66 domino
        tempDomino = Domino(66)
        tempDomino.shiftDraw(self.canvas,self.x,self.y)

    def eraseDomino(self, canvas, x, y):
        canvas.delete(x, y)

    def addToTable(self, val, pos = "F"): #F to add to front B for back
        right = 530; left = 0; size1 = 74; size2 = size1/2
        tempDomino = Domino(val)
        if(pos=="B"):
            if(tempDomino.val//10==self.end):
                self.end = tempDomino.val%10
                if(self.backRows%2==1):
                    tempDomino.flip()
            else:
                self.end = tempDomino.val//10
                if(self.backRows%2==0):
                    tempDomino.flip()
            if(self.backRows%2==0):
                if(self.xLength2+size1<=right):
                    self.xLength2+=size1
                    tempDomino.shiftDraw(self.canvas,self.xLength2,self.yLength2)
                else:
                    self.xLength2+=size2
                    self.yLength2-=size1
                    tempDomino.setOrientation("V")
                    tempDomino.flip()
                    tempDomino.shiftDraw(self.canvas,self.xLength2,self.yLength2)
                    self.backRows+=1
            else:
                if(self.xLength2-size1>=left):
                    self.xLength2-=size1
                    tempDomino.shiftDraw(self.canvas,self.xLength2,self.yLength2)
                else:
                    self.yLength2-=size1 #80, 40
                    tempDomino.setOrientation("V")
                    tempDomino.shiftDraw(self.canvas,self.xLength2,self.yLength2)
                    self.backRows+=1
                    self.xLength2-=size2 #make it so that the new row spawns dominos at the right spot
            self.list1.append(tempDomino)

        else:
            if(tempDomino.val//10==self.start):
                self.start = tempDomino.val%10
                if(self.frontRows%2==0):
                    tempDomino.flip()
            else:
                self.start= tempDomino.val//10
                if(self.frontRows%2==1):
                    tempDomino.flip()

            if(self.frontRows%2==0):
                if(self.xLength1-3*size2>=left):
                    self.xLength1-=size1
                    tempDomino.shiftDraw(self.canvas,self.xLength1,self.yLength1)
                else:
                    self.xLength1-=size2
                    tempDomino.setOrientation("V")
                    tempDomino.flip()
                    tempDomino.shiftDraw(self.canvas,self.xLength1,self.yLength1)
                    self.yLength1+=size1
                    self.frontRows+=1
                    self.xLength1-=size1 #make it so that the new row spawns dominos at the right spot
            else:
                if(self.xLength1+3*size2<=right):
                    self.xLength1+=size1
                    tempDomino.shiftDraw(self.canvas,self.xLength1,self.yLength1)
                else:
                    self.xLength1+=size1
                    tempDomino.setOrientation("V")
                    tempDomino.shiftDraw(self.canvas,self.xLength1,self.yLength1)
                    self.yLength1+= size1
                    self.frontRows+=1
                    self.xLength1+=size2 #make it so that the new row spawns dominos at the right spot

            self.list1.insert(0,tempDomino)


### -----
# author: luo xin,
# creat: 2022.9.25, modify: 2023.1.17
# des: Time formats conversions. year-month-day-hour, day-of-year, decimal year.
# -----

'''ref: https://www.cnblogs.com/maoerbao/p/11518831.html
'''

import numpy as np
from astropy.time import Time

def date2doy(year, month, day, hour=0, minute=0):
    '''
    convert year-month-day-hour-minute to doy (day-of-year)
    month:0~12
    day:0~31
    hour: 0~24
    minute:0~60
    '''
    month_leapyear=[31,29,31,30,31,30,31,31,30,31,30,31]
    month_notleap= [31,28,31,30,31,30,31,31,30,31,30,31]
    doy=0
    if month==1:
            pass
    elif year%4==0 and (year%100!=0 or year%400==0):
            for i in range(month-1):
                    doy+=month_leapyear[i]
    else:
            for i in range(month-1):
                    doy+=month_notleap[i]
    doy+=day
    doy+=(hour+minute/60)/24
    return doy

def doy2date(year, doy):
    '''
    convert doy(day-of-year) to year-month-day-hour-minute formate
    the function returns the month and the day of the month.
    '''
    month_leapyear=[31,29,31,30,31,30,31,31,30,31,30,31]
    month_notleap= [31,28,31,30,31,30,31,31,30,31,30,31]

    if year%4==0 and (year%100!=0 or year%400==0):
        for i in range(0,12):
            if doy>month_leapyear[i]:
                doy-=month_leapyear[i]
                continue
            if doy<=month_leapyear[i]:
                month=i+1
                day=doy
                break
    else:
        for i in range(0,12):
            if doy>month_notleap[i]:
                doy-=month_notleap[i]
                continue
            if doy<=month_notleap[i]:
                month=i+1
                day=doy
                break

    return month, day

def dt64_to_dyr(dt64):
    """
    des: convert datetime64 to decimal year format.
    e.g., '2020-05-23T03:25:22.959373696' -> 2020.3907103825136.
    args:
        dt64: np.datetime64 format time
    """
    year = dt64.astype('M8[Y]')
    days = (dt64 - year).astype('timedelta64[D]')
    year_next = year + np.timedelta64(1, 'Y')
    days_of_year = (year_next.astype('M8[D]') - year.astype('M8[D]')).astype('timedelta64[D]')
    dt_float = 1970 + year.astype(float) + days / (days_of_year)
    return dt_float

# def gps2dyr(time): ## deprecated
#     """ Converte from GPS time to decimal years. """
#     time_gps = Time(time, format="gps")
#     time_dyr = Time(time_gps, format="decimalyear").value
#     return time_dyr

### convert time (second format) to decimal year
def second_to_dyr(time_second, time_start='2000-01-01 00:00:00.0'):
    ''' this function suitable for the jason data, sentinel-3 data,
        and the cryosat2 data for time conversion.
    '''
    second_start = Time(time_start) ## the start of the second time, some case should be 1970.1.1
    second_start_gps = Time(second_start, format="gps").value  ## seconds that elapse since gps time.
    time_start = time_second + second_start_gps    ## seconds between time_start and gps time + seconds between gps time and the given time_second.
    time_start_gps = Time(time_start, format="gps")
    time_second_dyr = Time(time_start_gps, format="decimalyear").value
    return time_second_dyr


from bitarray import bitarray

class Adjmat(object):

    def __init__(self, inp):
        data = inp.split('\n')
        self.length = int(data[0].split(' ')[0])
        #self.bits = []
        #for i in range(self.length):
        #    ba = bitarray(self.length)
        #    ba.setall(0)
        #    self.bits.append(ba)
        self.bits = [bitarray([0] * self.length) for x in range(self.length)]
        self.set_links(data[1:])

    def set_links(self, data):
        for line in data:
            source, target = line.split(' -> ')
            for s in source.split(' '):
                for t in target.split(' '):
                    self.bits[int(s)][int(t)] = 1

    def __repr__(self):
        return '\n'.join(l.to01() for l in self.bits)

    def setlink(self, source, target):
        self.bits[source][target] = 1

def test():
    a = Adjmat('''5 5
0 -> 1
1 -> 2
2 -> 0 1 2 3 4
0 1 2 3 4 -> 4
0 -> 3''')
    print(a)


import logging
import mapnik
import xml.etree.ElementTree as ET
import os
import subprocess
import tempfile

# Set up logging
logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO)

# Parameters
shpPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-04-24/Zanzibar/Zanzibar.shp"
epsDir = "C:/Projects/BirthsAndPregnanciesMapping/results/eps"
max_img_size = 1000 # Max width or height of output image

# Create style
stroke = mapnik.Stroke()
stroke.color = mapnik.Color(0,0,0)
stroke.width = 1.0
symbolizer = mapnik.LineSymbolizer(stroke)
rule = mapnik.Rule()
rule.symbols.append(symbolizer)
style = mapnik.Style()
style.rules.append(rule)

# Create Datasource
datasource = mapnik.Shapefile(file=shpPath)

# Create layer
layer = mapnik.Layer("boundaries")
layer.datasource = datasource
layer.styles.append("boundariesStyle")

# Calculate image output size
envelope = datasource.envelope()
dLong = envelope.maxx - envelope.minx
dLat = envelope.maxy - envelope.miny
aspectRatio = dLong / dLat

if dLong > dLat:
    width = max_img_size
    height = int(width / aspectRatio)
elif dLat > dLong:
    height = max_img_size
    width = int(aspectRatio * height)
else:
    width = max_img_size
    height = max_img_size

# Create map
map = mapnik.Map(width, height)
map.append_style("boundariesStyle", style)
map.layers.append(layer)
map.zoom_all()

# Output to temporary postscript file
outPsPath = os.path.join(tempfile.gettempdir(), "ZanzibarAdminBoundaries.ps")
mapnik.render_to_file(map, outPsPath)

# Convert postscript to EPS file using ghostscript
outEpsPath = os.path.join(epsDir, "ZanzibarAdminBoundaries.eps")
subprocess.call(["C:/Program Files/gs/gs9.14/bin/gswin64c",
                 "-dDEVICEWIDTHPOINTS=%s" % width,
                 "-dDEVICEHEIGHTPOINTS=%s" % height,
                 "-sDEVICE=eps2write",
                 "-o",
                 outEpsPath,
                 outPsPath])

# Delete temporary file
os.remove(outPsPath)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        ('course', '0002_auto_20151024_0149'),
        ('storage', '0003_activitytype_activityverb'),
    ]

    operations = [
        migrations.CreateModel(
            name='ValueHistory',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('student', models.CharField(max_length=255)),
                ('value', models.FloatField()),
                ('course_datetime', models.DurationField()),
                ('datetime', models.DateTimeField(auto_now_add=True)),
                ('group', models.ForeignKey(to='course.CourseGroup')),
            ],
        ),
        migrations.CreateModel(
            name='Variable',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=100, blank=True)),
                ('label', models.CharField(max_length=255, blank=True)),
                ('num_bins', models.PositiveSmallIntegerField(default=10, blank=True)),
                ('last_consumed_activity_pk', models.PositiveIntegerField(default=0, blank=True)),
                ('type', models.CharField(default=b'IN', max_length=3, choices=[(b'IN', b'Input variable'), (b'OUT', b'Output variable')])),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SingleEventVariable',
            fields=[
                ('variable_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='stats.Variable')),
                ('aggregation', models.CharField(default=b'AVG', max_length=5, choices=[(b'AVG', b'Use the average value'), (b'SUM', b'Use the cumulative value'), (b'MAX', b'Use the highest value'), (b'MIN', b'Use the lowest value')])),
                ('types', models.ManyToManyField(to='storage.ActivityType')),
                ('verbs', models.ManyToManyField(to='storage.ActivityVerb')),
            ],
            options={
                'abstract': False,
            },
            bases=('stats.variable',),
        ),
        migrations.AddField(
            model_name='variable',
            name='course',
            field=models.ForeignKey(to='course.Course'),
        ),
        migrations.AddField(
            model_name='variable',
            name='polymorphic_ctype',
            field=models.ForeignKey(related_name='polymorphic_stats.variable_set+', editable=False, to='contenttypes.ContentType', null=True),
        ),
        migrations.AddField(
            model_name='valuehistory',
            name='variable',
            field=models.ForeignKey(related_name='+', to='stats.Variable'),
        ),
    ]


from collections import deque
N = int(input())
table = [list(map(int,input())) for _ in range(N)]

dx = [0,0,1,-1]
dy = [1,-1,0,0]
visited = [item[:] for item in table]
ans = []
for i in range(N):
    for j in range(N):
        if visited[i][j] == 1:
            visited[i][j] = 0
            tmp = 0
            q = deque()
            q.append((i,j))
            while q:
                x, y= q.popleft()

                for k in range(4):
                    nx = x + dx[k]
                    ny = y + dy[k]
                    if 0 <= nx < N and 0 <= ny < N:
                        if visited[nx][ny] == 1:
                            visited[nx][ny] = 0
                            q.append((nx,ny))
                            tmp+=1
            ans.append(tmp)

print(len(ans))
ans.sort()
for i in ans:
    print(i+1)


import numpy as np
### Heuristics
def manhattan(c_1,c_2):
     return abs(c_1[0]-c_2[0])+ abs(c_1[1]-c_2[1])

def euclidian(c_1,c_2):
    return np.sqrt((c_1[0]-c_2[0])**2+ (c_1[1]-c_2[1])**2)

def true(c_1,c_2):
    return max(abs(c_1[0]-c_2[0]),abs(c_1[1]-c_2[1]))

## A star
class Position():
    def __init__(self,
                 coords,
                 parent=None,
                 g=0,
                 h=0):
        self.coords = coords
        self.parent = parent
        self.g = g
        self.h = h
        self.f = h+g

    def __eq__(self, position):
        return self.coords == position.coords

    def replace(self, position):
        self.parent = position.parent
        self.g = position.g
        self.h = position.h
        self.f = position.f

def wall_to_matrix(wallStates):
    matrix = np.zeros((20,20), dtype=int)
    for pos in wallStates:
        matrix[pos[0],pos[1]] =1
    return matrix

def check_move(coords, wallStates):
    x,y = coords
    test_1 = (x>=0) and (x<20)
    test_2 = (y>=0) and (y<20)
    if test_1 and test_2:
        if type(wallStates) == list:
            return not(coords in wallStates)
        else:
            return (wallStates[x,y] == 0)
    else:
        return False

def check_closed(closed, position):
    tests = list(map(lambda aux: aux == position, closed))
    return any(tests)

def check_open(open, position):
    tests = list(map(lambda aux: aux == position, open))
    if any(tests):
        return open[tests.index(True)]
    else:
        return None

def get_children(parent, destination, wallStates, distance):
    children = []
    for action in [(0,1),(0,-1),(1,0),(-1,0)]:
        coords = (parent.coords[0]+action[0], parent.coords[1]+action[1])
        if check_move(coords, wallStates):
            g = parent.g+1
            h = distance(coords,parent.coords)
            child = Position(g=g,h=h,coords=coords,parent=parent)
            children.append(child)
    return children

def a_search(start, destination, wallStates, distance=manhattan):
    start = Position(start)
    destination = Position(destination)
    open, closed = [start], []
    num_iter = 0
    while len(open) != 0:
        num_iter += 1
        actual_idx = sorted(range(len(open)), key=lambda idx: open[idx].f)[0]
        actual_pos = open[actual_idx]
        open.pop(actual_idx)
        closed.append(actual_pos)
        if actual_pos.coords == destination.coords:
            path = []
            while actual_pos != start:
                path.append(actual_pos.coords)
                actual_pos = actual_pos.parent
            return path[::-1], num_iter
        else:
            children = get_children(actual_pos, destination, wallStates, distance)
            for child in children:
                if check_closed(closed, child):
                    continue
                other_position = check_open(open, child)
                if other_position is None:
                    open.append(child)
                else:
                    if child.f < other_position.f:
                        other_position.replace(child)
    print('Pas de chemin possible')

## Temporal A star
def check_move_bis(coords, wallStates, timetable, prev_coords=None):
    x,y,t = coords

    test_1 = (x,y) not in wallStates
    if prev_coords is not None:
        prev_x, prev_y, prev_t = prev_coords
        add_test = ((x,y,prev_t) in timetable) and ((prev_x,prev_y,t) in timetable)
        test_1 = test_1 and (not add_test)
    test_2 = (x>=0) and (x<20)
    test_3 = (y>=0) and (y<20)
    return test_1 and test_2 and test_3

def get_children_bis(parent, destination, wallStates, timetable, distance=manhattan):
    children = []
    for action in [(0,1),(0,-1),(1,0),(-1,0),(0,0)]:
        coords = (parent.coords[0]+action[0], parent.coords[1]+action[1], parent.coords[2]+1)
        if action == (0,0):
            prev_coords = None
        else:
            prev_coords = parent.coords
        if check_move_bis(coords, wallStates, timetable, prev_coords):
            g = parent.g +1
            h = distance(coords,parent.coords)
            child = Position(g=g,h=h,coords=coords,parent=parent)
            children.append(child)
    coords = (parent.coords[0], parent.coords[1], parent.coords[2]+1)
    return children

def a_search_bis(start, destination, wallStates, timetable, max_length=None):
    start = Position(start)
    destination = Position(destination)
    open, closed = [start], []
    t = 0
    maximas = []
    while len(open) != 0:
        t += 1
        actual_idx = sorted(range(len(open)), key=lambda idx: open[idx].f)[0]
        actual_pos = open[actual_idx]
        open.pop(actual_idx)
        closed.append(actual_pos)
        if actual_pos.coords[:2] == destination.coords[:2]:
            path = []
            while actual_pos != start:
                path.append(actual_pos.coords)
                timetable.append(actual_pos.coords)
                actual_pos = actual_pos.parent
            path.append(start.coords)

            return path[::-1], timetable, t,True
        else:
            if max_length is not None:
                if actual_pos.coords[-1] == max_length:
                    maximas.append(actual_pos)
                    continue
            children = get_children_bis(actual_pos, destination, wallStates, timetable)
            for child in children:
                if check_closed(closed, child):
                    continue
                other_position = check_open(open, child)
                if other_position is None:
                    open.append(child)
                else:
                    if child.f < other_position.f:
                        other_position.replace(child)
    maximas = sorted(maximas, key=lambda pos: pos.f)
    actual_pos = maximas[-1]
    path = []
    while actual_pos != start:
        path.append(actual_pos.coords)
        timetable.append(actual_pos.coords)
        actual_pos = actual_pos.parent
    path.append(start.coords)
    return path[::-1], timetable, t, False


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('webstore', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='shopandgoods',
            name='goodsid',
            field=models.ForeignKey(to='webstore.Goods', related_name='goods'),
            preserve_default=True,
        ),
    ]


from flask import Flask, render_template, request, redirect
import speech_recognition as sr
from googletrans import Translator
from gtts import gTTS
import os
import playsound
from model_main_test import *

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    transcript = ""
    is_spoof = ""
    confidence = 0
    indication = ""

    def speak(text):
        tts = gTTS(text=text, lang='zh-cn')

        filename = "translated.mp3"
        tts.save(filename)
        playsound.playsound(filename)
        # os.remove(filename)
        return

    if request.method == "POST":
        print("FORM DATA RECEIVED")

        recognizer = sr.Recognizer()
        trans = Translator()

        # # THIS FOR TEST AUDIO FILES
        # audioFile = sr.AudioFile('bonafide3.flac')
        # with audioFile as source:
        #     recognizer.adjust_for_ambient_noise(source)
        #     data = recognizer.record(source)

        # THIS FOR MICROPHONE INPUT
        with sr.Microphone() as source:
            recognizer.adjust_for_ambient_noise(source)
            indicaction = 'Start recording'
            data = recognizer.listen(source, 6, 4)
            indication = 'End recording'
            with open('speech.flac', 'wb') as f:
                f.write(data.get_flac_data())

        # detect = spoofdetect_stack('speech.flac','test/LA_aug.pth','test/PA_noise.pth')

        detect = spoofdetect('speech.flac','test/SA_abs_10000.pth')

        if detect[0]>detect[1]:
            is_spoof = 'Spoof!'
            confidence = detect[0]*100
        else:
            is_spoof = 'Bonafide'
            confidence = detect[1]*100

        if is_spoof == 'Bonafide':
            try:
                srctext = recognizer.recognize_google(data)
                transcript = trans.translate(srctext, dest='zh-cn', src='en').text
                speak(transcript)

                with open('srctext.txt', 'w') as file:
                    file.write(srctext)

                with open('desttext.txt', 'w') as file:
                    file.write(transcript)

            except:
                transcript = 'I dont understand.... or something goes wrong'

    return render_template('index.html', transcript=transcript, is_spoof=is_spoof, confidence=confidence, indication=indication)

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


import plotly.graph_objects as go

fig = go.Figure()
data = ech_gb_rc_floored["count"]
fig.add_trace(go.Pie(labels=data.index, values=data.values, name=data.index.name))

fig.update_traces(
    textinfo="percent+label",
#     hole=0.4,
    hoverinfo="label+percent+value",
    textposition="inside",
)

fig.update_layout(
    title_text="Response codes distribution among all echidna clicks"
)
fig.show()


import tensorflow as tf

# training data
X = [1,2,3]
Y = [1,2,3]

# variables
w = tf.Variable(tf.random_normal([1]), name='weight')
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

# hypothesis
hypothesis = x * w

# cost function
cost = tf.reduce_sum(tf.square(hypothesis - y))

# Gradient descent algorithm (use optimizer instead)
learning_rate = 0.1
gradient = tf.reduce_mean((w * x - y) * x)
descent = w - learning_rate * gradient
update = w.assign(descent)

# run
session = tf.Session()
session.run(tf.global_variables_initializer())

for step in range(26):
    session.run(update, feed_dict={x: X, y: Y})
    print(step, session.run(cost, feed_dict={x: X, y: Y}), session.run(w))


#%% INIT

# import packages

import pyrealsense2 as rs # realsense specific
import numpy as np
import cv2
from matplotlib import pyplot as plt
import math
import sys
import platform

# init variables

# picture properties
rows = 360
columns = 640
f_rate = 30

# colors - in RGB
blue = (255,0,0)
green = (0, 255, 0)
red = (0,0,255)
yellow = (200, 250, 0)

# set program steps
step_1 = False
step_2 = False
step_3 = False
step_4 = False

# variables
klick_counter = 0 # confirms number of registered mouse clicks

# click position - pixel location
ix = 0
iy = 0

ch_poi = np.zeros((2,2))  	#chosen point
koord = np.zeros((2,3))		# coordinates

#%% FUNCTIONS

def get_mouse_position(event, x, y, flags, param):
	global ix, iy, klick_counter
	if event == cv2.EVENT_LBUTTONDOWN: # if mouse is clicked
		ix, iy = x, y # save x and y at moment
		klick_counter += 1 # add on click registed
		print ("button clicked")

def good_features_to_track(src_color):
	gray = cv2.cvtColor(src_color, cv2.COLOR_BGR2GRAY) # covert image from source to destination format
	corners = cv2.goodFeaturesToTrack(gray, 1, 0.01, 10) # "strong corners of image are found"
	corners = np.int0(corners) # turn into integers
	for i in corners:
		x_corner, y_corner = i.ravel() # flatten
	return x_corner, y_corner

# print system properties

print ("Python Version: "+sys.version)
print ("Windows Version: "+platform.platform())

# init realsense image pipeline

#streams
pipeline = rs.pipeline() 														#create pipeline
config = rs.config()

# runtime error when notcommented out														#create a configuration
# config.enable_stream(rs.stream.color, columns, 360, rs.format.bgr8, f_rate)	#get the color stream
# config.enable_stream(rs.stream.depth, columns, 480, rs.format.z16, f_rate)		#get the depth stream
# config.enable_stream(rs.stream.infrared, 1, columns, rows, rs.format.y8, f_rate) #get left IR streams
# config.enable_stream(rs.stream.infrared, 2, columns, rows, rs.format.y8, f_rate) #get right IR streams

# start streaming
profile = config.resolve(pipeline)
profile = pipeline.start(config)

# get the depth sensor scale
depth_sensor = profile.get_device().first_depth_sensor()
depth_scale = depth_sensor.get_depth_scale()
print("Depth Scale is: ",depth_scale)

# create an align object
align_to = rs.stream.color
align = rs.align(align_to)

"""
MAIN PROGRAM
"""

def main():
	# get global variables = variables that can be changed in main function
	global step_1, step_2, step_3, step_4, klick_counter,ch_poi, koord, corner_picture_0, corner_picture_1
	# start the main - try
	try:
		while True:

			frames = pipeline.wait_for_frames()
			depth_frame = frames.get_depth_frame()
			color_frame = frames.get_color_frame()
			aligned_frames = align.process(frames)
			aligned_depth_frame = aligned_frames.get_depth_frame()
			aligned_color_frame = aligned_frames.get_color_frame()

			# validate frames
			if not aligned_depth_frame or not aligned_color_frame:
				continue

			ir_left_frame = frames.get_infrared_frame(1)
			ir_right_frame = frames.get_infrared_frame(2)
			depth_image = np.asanyarray(aligned_depth_frame.get_data())
			color_image = np.asanyarray(aligned_color_frame.get_data())

			# intrinsics and extrinsics
			depth_intrin = depth_frame.profile.as_video_stream_profile().intrinsics
			color_intrin = color_frame.profile.as_video_stream_profile().intrinsics
			depth_to_color_intrin = depth_frame.profile.get_extrinsics_to(color_frame.profile)

			delta = 8
			try:

				if cv2.waitKey(1) == ord('k') or step_1 == True:
					print("Test2")
					step_1 = True
					cv2.setMouseCallback('Align Example', get_mouse_position)
					cv2.rectangle(color_image, (int(ch_poi[0][0]) - delta, int(ch_poi[0][1]) - delta), (int(ch_poi[0][0]) + delta, int(ch_poi[0][1]) + delta), red, 0)
					cv2.rectangle(color_image, (int(ch_poi[1][0]) - delta, int(ch_poi[1][1]) - delta), (int(ch_poi[1][0]) + delta, int(ch_poi[1][1]) + delta), red, 0)

					# print ix and iy
					if klick_counter <= 2:
						ch_poi[klick_counter-1][0] = ix
						ch_poi[klick_counter-1][1] = iy
						if klick_counter == 2:
							klick_counter = 0
							step_1 = False
							step_2 = True
			except:
				print ("error at second try")

			try:
				if step_2 == True:

					corner_picture_0 = color_image[int(ch_poi[0][1]) - delta: int(ch_poi[0][1]) + delta, int(ch_poi[0][0]) - delta: int(ch_poi[0][0]) + delta]
					corner_picture_1 = color_image[int(ch_poi[1][1]) - delta: int(ch_poi[1][1]) + delta, int(ch_poi[1][0]) - delta: int(ch_poi[1][0]) + delta]

					koord[0][0], koord[0][1] = good_features_to_track(corner_picture_0)
					koord[1][0], koord[1][1] = good_features_to_track(corner_picture_1)

					for i in range(0,2):
						koord[i][0] = ch_poi[i][0] - delta + koord[i][0]
						koord[i][1] = ch_poi[i][1] - delta + koord[i][1]

					cv2.rectangle(color_image, (int(koord[0][0]) - delta, int(koord[0][1]) - delta), (int(koord[0][0]) + delta, int(koord[0][1])+delta), green, 0)
					cv2.rectangle(color_image, (int(koord[1][0]) - delta, int(koord[1][1]) - delta), (int(koord[1][0]) + delta, int(koord[1][1])+delta), green, 0)

					step_3 = True
			except:
				print ("error at third try")

			try:
				zero = 0
				np.float64(zero)
				if step_3 == True:
					for i in range(0,2):
						z = aligned_depth_frame.get_distance(int(koord[i][0]), int(koord[i][1]))
						# print z
						if z > 0:
							koord[i][2] = z
					if koord[0][2] > 0 and koord[1][2] > 0:
						step_3 = False
						step_4 = True
			except:
				print ("Error at the fourth try")

			try:
				if step_4 == True:
					depth_point_1 = rs.rs2_deproject_pixel_to_point(depth_intrin, [koord[0][0], koord[0][1]], koord[0][2])
					depth_point_2 = rs.rs2_deproject_pixel_to_point(depth_intrin, [koord[1][0], koord[1][1]], koord[1][2])
					vector_12 = np.zeros((1,3))
					for i in range(0,3):
						vector_12[0][i] = depth_point_1[i] - depth_point_2[i]
					print ("the position of point 1 is " + str(depth_point_1))
					print ("the position of point 2 is " + str(depth_point_2))
					print ("the vector between the two points is " + str(vector_12))
					# dist_12 = math.sqrt(vector_12[0][0]**2 + vector_12[0][1]**2 + vector_12[0][2]**2)
					# dist_12 = dist_12 * 1000
					# dist_12 = int(dist_12)
					# print ("the 3D distance between points is " + str(dist_12) + "mm")
					step_4 = False
			except:
				print ("error at fifth try")

			try:
				cv2.namedWindow('Align Example', cv2.WINDOW_AUTOSIZE)
				cv2.imshow('Align Example', color_image)

			except:
				print ("error occured during streaming")

			if cv2.waitKey(1) == 27: # when 0. program updates whenever button is pressed. when 1 program closes when escape is held
				break
	except:
		print ("error occured in first try")
	finally:
		cv2.destroyAllWindows()
		pipeline.stop()

if __name__ == '__main__':
	main()


from django.contrib import admin
from django.contrib.admin.filters import ListFilter
from .models import Listing
# Register your models here.
class ListingAdmin(admin.ModelAdmin):
    list_display=('id' , 'title','is_published','price','list_date','realtor')
    list_display_links=('id','title')
    list_editable=('is_published',)
    list_filter=('title','list_date','city')
    list_per_page=20
    search_fields=('city','title','realtor')

admin.site.register(Listing,ListingAdmin)


from collections import OrderedDict
import torch
from catalyst.dl import SupervisedRunner, AccuracyCallback, EarlyStoppingCallback, MultiMetricCallback
from efficientnet_pytorch import EfficientNet
import pandas as pd

from common.metrics import catalyst_roc_auc, catalyst_logloss, catalyst_acc_score
from common.sampler import BalancedBatchSampler
from deep_fake.augs.v0 import train_aug, valid_aug
from deep_fake.deep_fake_data import DeepFakeDs

FOLD = 0

full_df = pd.read_csv('/home/lyan/Documents/kaggle/deep_fake/fakes_folds.csv', index_col=0)
valid_df = full_df[full_df.fold == FOLD]
train_df = full_df[full_df.fold != FOLD]
train_ds = DeepFakeDs(df=train_df, aug=train_aug)
valid_ds = DeepFakeDs(df=valid_df, aug=valid_aug)

sampler = BalancedBatchSampler(dataset=train_ds, labels=train_ds.labels)

train_loader = torch.utils.data.DataLoader(train_ds, shuffle=True, batch_size=32, num_workers=10)
valid_loader = torch.utils.data.DataLoader(valid_ds, shuffle=False, batch_size=32, num_workers=10)

class Squeeze(torch.nn.Module):
    def forward(self, x):
        return torch.squeeze(x)

model = EfficientNet.from_pretrained('efficientnet-b3')
model._fc = torch.nn.Sequential(
    torch.nn.Linear(1536, 1),
    Squeeze(),
)

experiment_name = 'deepfake_crops_effnet_b3_224_v1'

lr = 1e-3

optimizer = torch.optim.Adam(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.5, patience=4, mode='min')
criterion = torch.nn.BCEWithLogitsLoss()
loaders = OrderedDict()
loaders["train"] = train_loader
loaders["valid"] = valid_loader

num_epochs = 50
logdir = "/var/data/deepfake/" + experiment_name
runner = SupervisedRunner()

runner.train(
    fp16=False,
    model=model,
    criterion=criterion,
    optimizer=optimizer,
    loaders=loaders,
    logdir=logdir,
    scheduler=scheduler,
    num_epochs=num_epochs,
    callbacks=[
        MultiMetricCallback(metric_fn=catalyst_roc_auc, prefix='rocauc',
                            input_key="targets",
                            output_key="logits",
                            list_args=['_']),
        MultiMetricCallback(metric_fn=catalyst_logloss, prefix='logloss',
                            input_key="targets",
                            output_key="logits",
                            list_args=['_']),
        MultiMetricCallback(metric_fn=catalyst_acc_score, prefix='acc',
                            input_key="targets",
                            output_key="logits",
                            list_args=['_']),
        EarlyStoppingCallback(patience=10, min_delta=0.01)
    ],
    verbose=True
)


import re

def help():
    return "Sure! I can help. Below are the commands that I understand:
" \
            "`Help` - I will display what I can do.
" \
            "`Hello` - I will display my greeting message
" \
            "`Zones` - I will display all the zones in the policy database
" \
            "`Groups` - I will displace all the ISE groups that can be used in a Zone policy
" \
            "`Display [Zone Name]` - I will display the policy for [Zone Name]
" \
            "`Change [Zone Name] policy=[policy] groups=group1, group2, group3`
" \
            "`[ ]` represent variables.
"

def hello(bot_name):
    return "Hi my name is %s bot.
" \
           "Type `Help` to see what I can do.
" % bot_name

def get_zones(saved_policy):

    message = '**The following Zones are defined:**
'
    for zone in saved_policy['zone_policies']:
        message += (zone['zone_name'] + '
')
    message += 'Default Zone'

    return message

def get_groups(groups):

    message = '**The following ISE groups can be used in a zone policy:**
'
    for group in groups:
        message += (group + '
')

    return message

def display_zone_policy(saved_policy, search_zone):

    message = '**Policy for zone**: {}
'.format(search_zone)
    for zone in saved_policy['zone_policies']:
        if zone['zone_name'] == search_zone.strip():
            message += ('**Policy**: ' + zone['zone_policy']['allow_deny'] + '
')
            groups = ', '.join(zone['zone_policy']['group_list'])
            message += ('**Groups**: ' + groups + '
')
    return message

def change_zone_policy(policy, error):

    if error!='':
        return error, []

    '''
    Review Regex at: https://regex101.com/

    \s* matches any whitespace character (equal to [\r\n\t\f\v ])
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    1st Capturing Group ([a-zA-Z0-9>\s]*[A-Za-z0-9])
    --> 1st capturing group captures the zone <--
    Match a single character present in the list below [a-zA-Z0-9>\s]*
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    a-z a single character in the range between a and z (case sensitive)
    A-Z a single character in the range between A and Z (case sensitive)
    0-9 a single character in the range between 0 and 9 (case sensitive)
    > matches the character > literally (case sensitive)
    \s matches any whitespace character (equal to [\r\n\t\f\v ])
    Match a single character present in the list below [A-Za-z0-9]
    --> This is included so that our first group ends on a non-whitespace boundary <--
    A-Z a single character in the range between A and Z (case sensitive)
    a-z a single character in the range between a and z (case sensitive)
    0-9 a single character in the range between 0 and 9 (case sensitive)
    \s* matches any whitespace character (equal to [\r\n\t\f\v ])
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    2nd Capturing Group (policy\s*=\s*[allowdenyAD]*)
    --> 2nd capturing group captures the allow\deny policy <--
    policy matches the characters policy literally (case sensitive)
    \s* matches any whitespace character (equal to [\r\n\t\f\v ])
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    = matches the character = literally (case sensitive)
    \s* matches any whitespace character (equal to [\r\n\t\f\v ])
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    Match a single character present in the list below [allowdenyAD]*
    --> This should match allow, deny, Allow, Deny <--
    \s* matches any whitespace character (equal to [\r\n\t\f\v ])
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    3rd Capturing Group (groups\s*=\s*[a-zA-Z_\s\(\),]*)
    --> 3rd capturing group captures the groups <--
    groups matches the characters groups literally (case sensitive)
    \s* matches any whitespace character (equal to [\r\n\t\f\v ])
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    = matches the character = literally (case sensitive)
    \s* matches any whitespace character (equal to [\r\n\t\f\v ])
    Match a single character present in the list below [a-zA-Z_\s\(\),]*
    '''

    regex_alternate = r"\s*([\w>\s]+[\w])\s+(policy\s*=\s*[allowdenyAD]+)\s+(groups\s*=\s*[\w\s\(\),]+)"

    regex = r"\s*([a-zA-Z0-9>\s]*[a-zA-Z0-9])[\s,]*(policy\s*=\s*[allowdenyAD]*)[\s,]*(groups\s*=\s*[a-zA-Z_\s\(\),\d-]*)"
    print(policy)
    policy_split = re.search(regex, policy)
    zone = policy_split.group(1)
    policy_msg = policy_split.group(2)
    groups_msg = policy_split.group(3)
    print(zone)
    print(policy_msg)
    print(groups_msg)
    policy_msg = policy_msg.split('=')[1].strip()
    groups_msg = groups_msg.split('=')[1]
    message = '**Policy was changed for zone**: {}
'.format(zone)
    message += ('**Policy**: ' + policy_msg + '
')
    message += ('**Groups**: ' + groups_msg + '
')

    groups_msg = groups_msg.split(',')
    for group_index in range(len(groups_msg)):
        groups_msg[group_index]=groups_msg[group_index].strip()

    changed_zones = [{'zone_name' : zone, 'allow_deny' : policy_msg, 'group_list' : groups_msg}]

    return message, changed_zones

def indexed_mapping(saved_policy, ise_groups):
    zone_list = []
    sorted_zone_dict = {}
    sorted_group_dict = {}

    for zone in saved_policy['zone_policies']:
        zone_list.append(zone['zone_name'])

    zone_list = sorted(zone_list, key=str.lower)

    zone_length = 0
    for n, zone_name in enumerate(zone_list, start=1):
        sorted_zone_dict[str(n)] = zone_name
        zone_length = zone_length + 1

    sorted_zone_dict[str(zone_length + 1)] = 'Default Zone'

    ise_groups = sorted(ise_groups, key=str.lower)
    for n, group_name in enumerate(ise_groups, start=1):
        sorted_group_dict[str(n)] = group_name

    return sorted_zone_dict, sorted_group_dict


from django.test import TestCase
from selenium import webdriver
from microinsurance.models import InsuranceProvider, Microinsurance, Company, Branch
import datetime

class MicroinsuranceAdmin(TestCase):

    def test_saving_new_insurace_provider(self):

        provider = InsuranceProvider()
        provider.insurance_provider_name = 'Manulife'
        provider.date_created = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        provider.save()

        all_providers_in_database = InsuranceProvider.objects.all()
        self.assertEquals(len(all_providers_in_database), 1)
        only_provider_in_the_database = all_providers_in_database[0]
        self.assertEquals(provider, only_provider_in_the_database)

        self.assertEquals(only_provider_in_the_database.insurance_provider_name, 'Manulife')
        self.assertEquals(only_provider_in_the_database.date_created.strftime('%Y-%m-%d'), datetime.datetime.now().strftime('%Y-%m-%d'))

    def test_saving_new_microinsurance(self):

        provider = InsuranceProvider()
        provider.insurance_provider_name = 'Manulife'
        provider.date_created = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        provider.save()

        all_providers_in_database = InsuranceProvider.objects.all()
        self.assertEquals(len(all_providers_in_database), 1)
        only_provider_in_the_database = all_providers_in_database[0]
        self.assertEquals(provider, only_provider_in_the_database)

        self.assertEquals(only_provider_in_the_database.insurance_provider_name, 'Manulife')
        self.assertEquals(only_provider_in_the_database.date_created.strftime('%Y-%m-%d'), datetime.datetime.now().strftime('%Y-%m-%d'))

        microinsurance = Microinsurance()
        microinsurance.product_name = 'StudentCARE'
        microinsurance.base_price = 25.00
        microinsurance.retail_price = 30.00
        microinsurance.insurance_limit = 5
        microinsurance.age_requirement = 18
        microinsurance.age_limit = 65
        microinsurance.date_created = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')

        provider_data = InsuranceProvider.objects.get(insurance_provider_name = 'Manulife')

        microinsurance.insurance_provider_name = provider_data
        microinsurance.effectivity_date = datetime.datetime.now().strftime('%Y-%m-%d')
        microinsurance.save()

        all_microinsurance_in_database = Microinsurance.objects.all()
        self.assertEquals(len(all_microinsurance_in_database), 1)
        only_microinsurance_in_the_database = all_microinsurance_in_database[0]
        self.assertEquals(microinsurance, only_microinsurance_in_the_database)

        self.assertEquals(only_microinsurance_in_the_database.product_name, 'StudentCARE')
        self.assertEquals(only_microinsurance_in_the_database.base_price, 25.00)
        self.assertEquals(only_microinsurance_in_the_database.effectivity_date.strftime('%Y-%m-%d'), datetime.datetime.now().strftime('%Y-%m-%d'))
        self.assertEquals(only_microinsurance_in_the_database.insurance_provider_name, provider_data)

    def test_saving_new_branch(self):

        company = Company()
        company.company_name = 'Bideco'
        company.date_created = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        company.active = True
        company.save()

        all_company_in_database = Company.objects.all()
        self.assertEquals(len(all_company_in_database), 1)
        only_company_in_database = all_company_in_database[0]

        self.assertEquals(only_company_in_database.company_name, 'Bideco')
        self.assertEquals(only_company_in_database.date_created.strftime('%Y-%m-%d %H:%M'), datetime.datetime.now().strftime('%Y-%m-%d %H:%M'))
        self.assertEquals(only_company_in_database.active, True)

        branch = Branch()
        branch.branch_name = 'Binangonan branch'
        branch.branch_address = 'Lopez Jaena St., Libid, Binangonan, Rizal'
        company_data = Company.objects.get(company_name = 'Bideco')
        branch.company_name = company_data
        branch.save()

        all_branch_in_database = Branch.objects.all()
        self.assertEquals(len(all_branch_in_database), 1)
        only_branch_in_database = all_branch_in_database[0]

        self.assertEquals(only_branch_in_database.branch_name, 'Binangonan branch')
        self.assertEquals(only_branch_in_database.branch_address, 'Lopez Jaena St., Libid, Binangonan, Rizal')
        self.assertEquals(only_branch_in_database.company_name, company_data)


from rapidsms.contrib.handlers import KeywordHandler
from django.db.models import *
from wallet.models import *
from payee.models import *
from .managers import *

class AuthorizeHandler(KeywordHandler):
    """
    handles incoming replies for transaction
    authorization
    """
    keyword = 'Yes'

    def help(self):
        self.respond("Reply with 'Yes' to authorize transaction")

    def handle(self,message):
        text = text.strip().lower()
        try:
           #match phone number to user
           #smsbill = SmsBill.objects.filter(from_wallet__phone_number__iexact=identity)
           smsbill = SmsBill.for_connection(message.connection)
        except SmsBill.DoesNotExist:
            #send help
            self.help()
        else:
            UserWallet.objects.filter(
            from_wallet__phone_number__iexact=identity
            ).update(authorize=True)
            self.respond("Your bill payment is being processed.")


#!/usr/bin/env python

import gvpn_controller as gvpn
import json
import logging
import os
import select
import signal
import socket
import subprocess
import sys
import threading
import time

CONFIG = gvpn.CONFIG

# thread signal
run_event = threading.Event()

tincan_bin = None
tincan_process = None

# exit handler and register this process
def exit_handler(signum, frame):
    if tincan_process is not None:
        tincan_process.send_signal(signal.SIGINT)
    run_event.clear()

class TinCanException(Exception):
    def __init__(self):
        Exception.__init__(self)
    def __str__(self):
        return "TinCan not running properly."

class UdpServer(gvpn.UdpServer):

    def run_server(self):
        last_time = time.time()
        count = 0
        while run_event.is_set():
            self.serve()
            time_diff = time.time() - last_time
            if time_diff > CONFIG["wait_time"]:
                count += 1
                self.trim_connections()
                logging.debug("send_get_state")
                gvpn.do_get_state(self.sock)
                last_time = time.time()

class WatchDog:
    def __init__(self):
        if socket.has_ipv6:
            self.sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
        else:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(("", 0))
        self.inactive_time = time.time()

    def watch(self):
        socks = select.select([self.sock], [], [], CONFIG["wait_time"])
        if not socks[0]: # Check if the socks is empty
            if time.time() - self.inactive_time > 60:
                logging.debug("TinCan is inactive for 60s")
                raise TinCanException

        for sock in socks[0]:
            data, addr = sock.recvfrom(CONFIG["buf_size"])
            msg = json.loads(data)
            logging.debug("watchdog recv %s %s" % (addr, data))
            msg_type = msg.get("type", None)
            if msg_type == "local_state":
                self.inactive_time = time.time()

def main():

    signal.signal(signal.SIGINT, exit_handler)

    watchdog = WatchDog()

    tincan_path = CONFIG["tincan_path"]

    if os.path.exists(tincan_path):
        tincan_bin = os.path.abspath(tincan_path)

        with open("core_log", "w+") as core_log:
            logging.debug("Starting ipop-tincan");
            tincan_process = subprocess.Popen([tincan_bin],
                    stdout=subprocess.PIPE, stderr=core_log)
            time.sleep(1)

    else:
        logging.debug("TinCan binary doesn't exist at specified directory")
        sys.exit(0)

    server = UdpServer(CONFIG["xmpp_username"], CONFIG["xmpp_password"],
                     CONFIG["xmpp_host"], CONFIG["ip4"])

    run_event.set()
    t = threading.Thread(target=server.run_server)

    logging.debug("Starting Server");
    t.daemon = True
    t.start()
    last_time = time.time()
    watchdog.inactive_time = time.time()
    tincan_attempt = 0

    logging.debug("Starting WatchDog");
    while run_event.is_set():
        try:
            watchdog.watch()
            time_diff = time.time() - last_time
            if time_diff > CONFIG["wait_time"]:
                logging.debug("watchdog send_get_state")
                gvpn.do_get_state(watchdog.sock)
                last_time = time.time()
        except TinCanException:
            tincan_attempt += 1
            logging.error("TinCan Failed {0} times".format(tincan_attempt));
            os.kill(tincan_process.pid, signal.SIGTERM)
            time.sleep(1)
            if tincan_attempt > 3:
                logging.critical("TinCan Failed beyond threshold point");
                run_event.clear()
                break
            with open("core_log", "wb+") as core_log:
                tincan_process = subprocess.Popen([tincan_bin],
                        stdout=subprocess.PIPE, stderr=core_log)
                time.sleep(1)
            server.ctrl_conn_init()
            watchdog.inactive_time = time.time()

if __name__  == "__main__":
    gvpn.parse_config()
    main()


from django.shortcuts import render
from django.http import JsonResponse

from scriptures.models import (
    Book,
    Chapter,
    Scripture,
)

# import json

def scriptures(request):
    scriptures = Scripture.objects.all()

    scripture_list = []

    for s in scriptures:
        books = Book.objects.filter(scripture=s.pk)
        book_list = []
        for b in books:
            book_list.append(
                {
                    "name": b.name,
                    "id": b.pk,
                }
            )

        scripture_list.append(
            {
                "name": s.name,
                "books": book_list,
            }
        )

    data = {"bookSelect": scripture_list}

    return render(request, "scriptures/scriptures.html", data)

def get_book(request, pk):
    book = Book.objects.get(pk=pk)

    chapters = []
    for chapter in book.chapter_set.all():
        chapters.append(
            {
                "number": chapter.number,
                "id": chapter.id,
            }
        )

    data = {
        "name": book.name,
        "chapters": chapters,
    }

    # json_data = json.dumps(data)
    return JsonResponse(data)

def get_chapter(request, pk):
    chapter = Chapter.objects.get(pk=pk)

    verses = []
    for verse in chapter.verse_set.all():
        verses.append(
            {
                "id": verse.id,
                "number": verse.number,
                "text": verse.text,
            }
        )

    data = {
        "bookName": chapter.book.name,
        "number": chapter.number,
        "verses": verses,
    }

    # json_data = json.dumps(data)
    return JsonResponse(data)

def scripture_list(request):
    scriptures = Scripture.objects.all()

    data = {"scriptures": []}
    for s in scriptures:
        print(s.slug)
        data["scriptures"].append(
            {
                "name": s.name,
                "slug": s.slug,
            }
        )

    return render(request, "scriptures/scripture_list.html", data)

def book_list(request, scripture):
    scripture = Scripture.objects.get(slug=scripture)

    data = {
        "scripture": {"slug": scripture.slug},
        "books": [],
    }
    for book in scripture.book_set.all():
        data["books"].append(
            {
                "name": book.name,
                "slug": book.slug,
            }
        )

    return render(request, "scriptures/book_list.html", data)

def chapter_list(request, scripture, book):
    book = Book.objects.get(slug=book)

    data = {
        "scripture": {"slug": book.scripture.slug},
        "book": {"slug": book.slug},
        "chapters": [],
    }

    for chapter in book.chapter_set.all():
        data["chapters"].append(
            {
                "number": chapter.number,
            }
        )

    return render(request, "scriptures/chapter_list.html", data)

def verse_list(request, scripture, book, chapter):
    chapter = Scripture.objects.get(slug=scripture).book_set.get(slug=book).chapter_set.get(number=chapter)

    data = {"verses": []}
    for verse in chapter.verse_set.all():
        data["verses"].append(
            {
                "number": verse.number,
                "text": verse.text,
            }
        )

    return render(request, "scriptures/verse_list.html", data)


# -*- coding: utf-8 -*-
# Copyright (c) 2017, Dirk Chang and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
import json
from frappe import _
from cloud.templates.pages.cloud_company_group import get_context as cloud_get_context

def get_context(context):
	name = frappe.form_dict.group or frappe.form_dict.name

	cloud_get_context(context)

	context.parents = [{"title": context.doc.group_name, "route": "/iot_companies/" + context.doc.company}]
	context.doc.bunch_codes = get_bunch_codes(name, start=0, search=frappe.form_dict.get("search"))

def get_bunch_codes(group, start=0, search=None):
	filters = {
		"owner_type": "Cloud Company Group",
		"owner_id": group
	}
	if search:
		filters["bunch_name"] = ("like", "%{0}%".format(search))

	bunch_codes = frappe.get_all("IOT Device Bunch", filters=filters,
		fields=["name", "bunch_name", "code", "modified", "creation"],
		limit_start=start, limit_page_length=10)

	return bunch_codes


from django.shortcuts import render
from django.shortcuts import get_object_or_404

from portfolio.models import *

# Create your views here.

def index(request):
	template = 'pages/index.html'
	cts = ContentType.objects.filter(show = True)
	var = {
		'cts':cts,
	}
	return render(request, template, var)

def ctype(request, ctype_id):
	template = 'pages/ctype.html'
	ct = get_object_or_404(ContentType, pk=ctype_id)
	var = {
		'ct':ct,
	}
	return render(request, template, var)


liczby = [2,4,5,6,10,14,3,27,9,17]
dzielniki = []
wyniki = []
y = 20
x = 1
while x < y:
    dzielniki.append(x)
    x +=1

for z in dzielniki:
    for l in liczby:
        if((l/z)%2 == 0 or (l/z)%2 == 1):
            if (l not in wyniki):
                wyniki.append(l)

print(3/1%2)
print(wyniki)


"""
Player class and Minimax class for CS331 - Programming Assignment 2

Original C++ game code - authored by wong (April 2015)
Python adaptation - authored by Erich Kramer (April 2017)
Updated by Casey Nord (April 2020)
"""

class HumanPlayer:
    """Defines human player."""
    def __init__(self, symbol):
        """
        Initializes player object with game piece.

        :param: symbol (char) Player game piece.
        """
        self.symbol = symbol

    def get_symbol(self):
        """Returns player symbol.

        :return: (char) Symbol.
        """
        return self.symbol

    @staticmethod
    def get_move():
        """Get human player move.
        Note that this takes col/row input as opposed to the code being written as row/col.
        This feels more natural for the player to input coordinates as x, y
        but for those with experience in linear algebra it feels more natural to program in rows/cols.

        :return: (int)(tuple) Coordinate pair.
        """
        while True:
            try:
                x = int(input("Enter col: "))
                assert (x >= 0), "Value must be positive"
                break
            except:
                print("Value must be a positive integer.")

        while True:
            try:
                y = int(input("Enter row: "))
                assert (x >= 0), "Value must be positive"
                break
            except:
                print("Value must be a positive integer.")
        return y, x

class MinimaxPlayer:
    """Defines minimax computer player.

    This class should manage code for controlling the ai player.
    """
    def __init__(self, symbol):
        """Initialize ai minimax player.

        :param: symbol (char) Player game piece.
        """
        self.symbol = symbol


"""
this component pulls the config of this device from the IPL
component and sets up all the relays on that controller (resource
in the configuration).

To use this component:
1. Setup the ipl component instructions
2. create custom_component/switch and place iplrelay.py into that folder
3. make note of the Name of the IPL you want to use the relays on,
   from the name used in the ipl component. as that is how this
   components communicates with that device

4. create a yaml entry as per below

ipl:
  - name: deviceName
    ...

Example Yaml configuration
switch:
  - platform: iplrelay
    name: deviceName

"""
import logging
import voluptuous as vol
from datetime import timedelta
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import CONF_NAME, CONF_TYPE,CONF_FRIENDLY_NAME
import homeassistant.helpers.config_validation as cv
import custom_components.ipl as IPL

DEPENDENCIES = ['ipl']

_LOGGER = logging.getLogger(__name__)

PIN_SCHEMA = vol.Schema({
    vol.Required(CONF_NAME): cv.string,
})

SCAN_INTERVAL = timedelta(seconds=10)

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the IPL Relay platform."""
    if IPL.ComsDict == {}:
        _LOGGER.error("A connection has not been made to the IPL")
        return False
    else:
        switches = []
        Name = config.get(CONF_NAME)
        Coms = IPL.ComsDict[Name]
        for x in Coms.Controllers[Coms.ConType]['Relay']['Ports']:
            switches.append(IPLRELAY('{0}:{1}'.format(Name,x),x,Coms))
        add_devices(switches)

class IPLRELAY(SwitchDevice):
    """Representation of a switch that can be toggled using SIS commands."""

    def __init__(self, friendly_name, relay, Coms):
        """Initialize the switch."""
        self._name = friendly_name
        self._relaynum = relay
        self.Coms = Coms

    @property
    def name(self):
        """Return the name of the switch."""
        return self._name

    @property
    def should_poll(self):
        """Always Poll"""
        return True

    @property
    def is_on(self):
        """Return true if device is on."""
        return self.Coms.GetRelay(self._relaynum)

    def update(self):
        """Update device state."""
        self.Coms.Update(self._relaynum)

    def turn_on(self, **kwargs):
        """Turn the device on."""
        self.Coms.SetRelay(self._relaynum,'1')

    def turn_off(self, **kwargs):
        """Turn the device off."""
        self.Coms.SetRelay(self._relaynum,'0')


import sys
import numpy as np

def load_data(prior_path, emit_path, trans_path):
    load = lambda path, dim: np.loadtxt(path, delimiter=" ", ndmin=dim)
    prior = load(prior_path, 1)
    emit = load(emit_path, 2)
    trans = load(trans_path, 2)
    return prior, emit, trans

def cal_alpha(pi, b, a, t, j, alpha, sequence):
    """
    pi: prior
    a: transitional prob
    b: emission prob
    t: time at t
    j: the hidden state `j`.
    alpha: np.array, shape = (T, J)
    sequence: store the index of words. shape = (T,)
    """
    if (t == 0):
        alpha[t, j] = pi[j] * b[j, sequence[0]]
    else:
        alpha[t, j] = b[j, sequence[t]] * (alpha[t-1] @ a[:, j])
    return alpha

def cal_beta(pi, b, a, t, j, alpha, beta, sequence, T, J):
    """
    pi: prior
    a: transitional prob
    b: emission prob
    t: time at t, raging from [0, T)
    j: the hidden state `j`, raging from [0, J)
    alpha: np.array, shape = (T, J)
    beta: np.array, shape = (T, J)
    sequence: store the index of words. shape = (T,)
    """
    if (t == T-1):
        beta[t, j] = 1
    else:
        for k in range(J):
            beta[t, j] += b[k, sequence[t+1]] * beta[t+1, k] * a[j, k]
    return alpha

def get_tag(t, alpha, beta):
    """
    t: time at t, raging from [0, T)
    j: the hidden state `j`, raging from [0, J)

    return: str
    """
    prob = alpha[t] * beta[t]
    idx = np.argmax(prob)
    return idx

def predict_one_sample(sequence, a, b, pi):
    T = len(sequence)
    J = a.shape[0]
    # forward
    alpha = np.zeros((T, J))
    for t in range(T):
        for j in range(J):
            cal_alpha(pi, b, a, t, j, alpha, sequence)
    beta = np.zeros((T, J))
    for t in reversed(range(T)):
        for j in range(J):
            cal_beta(pi, b, a, t, j, alpha, beta, sequence, T, J)
    tags = []
    for t in range(T):
        tag = get_tag(t, alpha, beta)
        tags.append(tag)
    # print(tags)
    likelihood = log_likelihood(alpha, T)
    return tags, likelihood

def log_sum_exp_trick(var):
    m = var.max()
    return m + np.log(np.sum(np.exp(var-m)))

def accuracy(y, y_pred):
    c=0
    num=0
    for i,j in zip(y,y_pred):
        num+=len(i)
        for a,b in zip(i,j):
            if a==b:
                c+=1
    # true = sum([1 if i == j else 0 for i, j in zip(y, y_pred)])
    acc = c / num
    return acc

def log_likelihood(alphas, T):
    return np.log(np.sum(alphas[T-1, :]))

def inference(in_file, out_file, metric_file, index_to_word,index_to_tag, a, b, pi):
    in_file = open(in_file, "r")
    out_file = open(out_file, "w")
    dict_index_word = {}
    dict_index_word_reversed = {}
    with open(index_to_word, 'r') as f:
        lines=f.readlines()
        i=0
        for line in lines:
            line=line.replace("\n","")
            dict_index_word[line]=i
            dict_index_word_reversed[i] = line
            i+=1

    dict_index_tag = {}
    dict_index_tag_reversed = {}
    with open(index_to_tag, 'r') as f:
        lines=f.readlines()
        i=0
        for line in lines:
            line=line.replace('\n','')
            dict_index_tag[line]=i
            dict_index_tag_reversed[i] = line
            i+=1
    acc_sum = 0
    log_sum = 0
    n_samples = 0
    all_labels=[]
    all_y=[]
    for line in in_file.readlines():
        line = line.strip()
        sentence = line.split(" ")
        x = [dict_index_word[i.split("_")[0]] for i in sentence]
        y = [dict_index_tag[i.split("_")[1]] for i in sentence]
        labels, likelihood = predict_one_sample(x, a, b, pi)
        all_labels.append(labels)
        all_y.append(y)
        acc = accuracy(all_y, all_labels)
        acc_sum += acc
        log_sum += likelihood
        string = " ".join(["{}_{}".format(dict_index_word_reversed[m], dict_index_tag_reversed[n]) for m, n in zip(x, labels)])
        out_file.write(string + "\n")
        n_samples += 1
    avg_log = log_sum / n_samples
    avg_acc = acc_sum / n_samples
    string = "Average Log-Likelihood: {}\nAccuracy: {}".format(avg_log, avg_acc)
    with open(metric_file, "w") as f:
        f.write(string)

    in_file.close()
    out_file.close()

if __name__ == "__main__":
    test_input_file = sys.argv[1]
    index_to_word_file = sys.argv[2]
    index_to_tag_file = sys.argv[3]
    hmmprior_file = sys.argv[4]
    hmmemit_file = sys.argv[5]
    hmmtrans_file = sys.argv[6]
    predicted_file = sys.argv[7]
    metric_file = sys.argv[8]

    prior, emit, trans = load_data(hmmprior_file, hmmemit_file, hmmtrans_file)
    print("prior: {}, emission: {}, transition: {}".format(prior.shape, emit.shape, trans.shape))

    inference(test_input_file,
              predicted_file,
              metric_file,
              index_to_word_file,
              index_to_tag_file,
              trans,
              emit,
              prior)


import requests
import json
from io import StringIO
from Bio import Seq
from Bio import SeqIO
from Bio import SeqFeature
import sys
import uuid

sbol_type_table = {
    "CDS": "cds",
    "regulatory": "promoter" #promoter is actually a subclass of regulatory
}

def get_sequence_and_features(block, allblocks):
    features = block["sequence"]["features"]
    for f in features:
        f["block_id"] = block["id"]

    if len(block["components"])==0:
        return { "sequence": block["sequence"]["sequence"], "features": features}
    else:
        seq = ""
        for i in range(0, len(block["components"])):
            block_id = block["components"][i]
            bl = allblocks[block_id]
            pos = len(seq)
            output = get_sequence_and_features(bl, allblocks)
            seq += output["sequence"]

            features.append( {
                "block_id": block_id,
                "start" : pos,
                "end" : len(seq),
                "type" : "block",
                "parent_block" : block["id"] + "," + str(i),
            })

            for feature in output["features"]:
                features.append( {
                    "block_id": feature["block_id"],
                    "start" : feature["start"] + pos,
                    "end" : feature["end"] + pos,
                    "type" : feature["type"],
                    "parent_block" : feature.get("parent_block",None)
                })
        return { "sequence": seq, "features": features }

def project_to_genbank(filename, project, allblocks):
    blocks = project["components"]
    seq_obj_lst = []

    for bid in blocks:
        block = allblocks.get(bid)
        if not block:
            continue

        output = get_sequence_and_features(block, allblocks)
        seq = output["sequence"]
        features = output["features"]

        seq_obj = SeqIO.SeqRecord(Seq.Seq(seq,Seq.Alphabet.DNAAlphabet()),block["id"])
        for feature in features:
            sf = SeqFeature.SeqFeature()
            sf.type = feature["type"]
            sf.location = SeqFeature.FeatureLocation(feature["start"],feature["end"])
            sf.qualifiers["block_id"] = feature.get("block_id","")
            sf.qualifiers["parent_block"] = feature.get("parent_block",None)
            seq_obj.features.append(sf)
        seq_obj_lst.append(seq_obj)

    SeqIO.write(seq_obj_lst, open(filename, "w"), "genbank")

def create_block_json(id, sequence, features):
    return {
        "id": id,
        "metadata" : {
            "authors": [],
            "tags": {},
            "version": ""
        },
        "rules": {},
        "components": [],
        "sequence" : {
            "sequence": sequence,
            "features": features
        }
      }

def genbank_to_block_helper(gb, convert_features=False):
    all_blocks = {}
    block_parents = {}
    block_start_pos = {}
    features = []
    newblocks = 0
    sequence = str(gb.seq)
    #root_id = str(uuid.uuid4())
    root_id = gb.id

    #Collect all the neccessary metadata
    root_block = create_block_json(root_id, sequence, [])
    root_block["metadata"]["description"] = gb.description
    root_block["metadata"]["name"] = gb.name
    for annot in gb.annotations:
        try:
            json.dumps(gb.annotations[annot])
            root_block["metadata"][annot] = gb.annotations[annot]
        except:
            pass

    all_blocks[root_id] = root_block
    #all_blocks[gb.id] = root_block

    for f in gb.features:
        qualifiers = f.qualifiers
        start = f.location.start.position
        end = f.location.end.position

        feature = {}
        for q in qualifiers:
            if q != "block_id" and q != "parent_block":
                try:
                    json.dumps(qualifiers[q][0])
                    feature[q] = qualifiers[q][0]
                except:
                    pass
        feature["start"] = start
        feature["end"] = end
        feature["strand"] = f.location.strand
        feature["type"] = f.type

        sbol_type = sbol_type_table.get(f.type)

        if "block_id" in qualifiers:
            block_id = qualifiers["block_id"][0]
            if f.type == 'source':
                continue

            if f.type == "block":
                child_block = create_block_json(block_id, sequence[start:end], [])
                if qualifiers.get("parent_block",None):
                    words = qualifiers["parent_block"][0].split(",")
                    block_parents[block_id] = {
                        "id" : words[0],
                        "index" : int(words[1])
                    }
                else:
                    block_parents[block_id] = {
                        "id" : root_id,
                        "index" : newblocks
                    }
                    newblocks += 1
                child_block["metadata"]["tags"]["sbol"] = sbol_type
                all_blocks[block_id] = child_block
            else:
                feature["block_id"] = block_id
                features.append(feature)
        else:
            if sbol_type and convert_features:
                block_id = str(uuid.uuid4())
                child_block = create_block_json(block_id, sequence[start:end], [])
                child_block["metadata"]["tags"]["sbol"] = sbol_type
                all_blocks[block_id] = child_block
                block_parents[block_id] = {
                    "id" : root_id,
                    "index" : newblocks
                }
                newblocks += 1
            else:
                feature["block_id"] = root_id
                features.append(feature)

    for block_id in block_parents:
        parent = block_parents[ block_id ]
        if block_id in all_blocks and parent["id"] in all_blocks:
            all_blocks[ parent["id"] ]["components"].insert(int(parent["index"]), block_id)
            all_blocks[ parent["id"] ]["sequence"]["sequence"] = ""

    for feature in features:
        block_id = feature["block_id"]
        del feature["block_id"]
        if block_id in all_blocks:
            all_blocks[ block_id ]["sequence"]["features"].append(feature)
    #del all_blocks[gb.id]
    return { "block": all_blocks[root_id], "blocks": all_blocks }

def genbank_to_project(filename, convert_features=False):
    project = {
      'id': str(uuid.uuid4()),
      'metadata': {
        'authors': [],
        'tags': {},
        'version': '',
      },
      'components': [],
    };
    blocks_array = []
    all_blocks = {}
    generator = SeqIO.parse(open(filename,"r"),"genbank")
    for record in generator:
        gb = record
        one_block = genbank_to_block_helper(gb, convert_features)
        project["components"].append(one_block["block"]["id"])
        for bid in one_block["blocks"]:
            all_blocks[bid] = one_block["blocks"][bid]
    return { "project": project, "blocks": all_blocks }


import sys
from decimal import Decimal
from datetime import datetime, timedelta

def printlist(lst, name, **kw):
    import numpy as np
    mean = float(np.mean(lst,0))
    std = np.std(lst)
    stdstr = '%8.3f' % std if std < 10000 else '%8.5g' % std
    sovm = 100*std / mean if mean > 0 else float('nan')
    last = float(lst[-1])
    lstd = 100*(last - mean) / std if std > 0 else float('nan')
    print("{name:10s}={mean:10.5g}, σ={std:10.4g} ({sovm:9.3g}%) [{last:9.2f} ({lstd:7.3g}%)]".format(**locals()), **kw)

def to_dhms(tdelta):
    days = tdelta.days
    hr, sec = divmod(tdelta.seconds, 3600)
    mn, sec = divmod(sec, 60)
    return (days, hr, mn, sec)

def interval_str(days, hr, mn, sec):
    return (('%2dd ' % days) if days else '') + ('%2d:%02d:%02d'% (hr, mn, sec))

class Progress:
    def __init__(self, total):
        self.start = datetime.now()
        self.total = total

    def get_eta(self, i):
        """Returns (end time, time left) as datetime, timedelta objects."""
        now = datetime.now()
        tused = now - self.start

        # timedeltas cannot be multiplied by floats (?), so we get out the
        #seconds, use that, and make it back into a dt
        usedsecs = 24*60*60 * tused.days + tused.seconds + (1e-6 * tused.microseconds)
        tleft = (timedelta(0, (usedsecs) * ((self.total - i) / i)) if i > 0
                else timedelta(0, 0))

        return now + tleft, tleft

    def eta_strs(self, i, timefmt = '(%a %b %d, %H:%M:%S)'):
        """Returns (time left, total time, endtime) as strs"""
        endtime, tleft = self.get_eta(i)
        interval = to_dhms(tleft)
        totinterval = to_dhms(endtime - self.start)

        return (interval_str(*interval), interval_str(*totinterval),
                    endtime.strftime(timefmt))

    def eta_str(self, i, timefmt = '(%a %b %d, %H:%M:%S)'):
        ss = self.eta_strs(i, timefmt=timefmt)
        return 'Ends in ({} / {}) on {}'.format(*ss)

def errprint(*args, **kw):
    kwargs = {'file':sys.stderr}
    kwargs.update(kw)
    print(*args, **kwargs)
    kwargs['file'].flush()

def filefinder(dir, *names, regexp=None, matchall=True, types=Decimal, ext = 'tsv.gz', **args):
    """
    dir             : Directory to look in
    names           : keywords to look for / store into
    regexp          : Define the regular expression for groups (default: #NAME##VALUE#-#NAME##VALUE#....ext)
    matchall        : Match the entire expression
    types           : What types to apply (default: all Decimal)
    ext             : File extension (ignores everything else) (default: 'tsv.gz')
    args            : Like names, but add some constants (such as T=1) for all fs
    """
    import re, fpath
    from collections import namedtuple

    names = [(n + '0' if n in 'f' else n) for n in names]
    FoundFile = namedtuple('FoundFile', names + ['f'])

    try:
        iter(types)
    except TypeError:
        types = [types] * len(names)

    dir = fpath.Dir(dir)
    children = [f for f in dir.children() if f[-1][(-len(ext)-1):] == '.' + ext]

    if regexp is None:
        regexp='-'.join([n + r'(\F)' for n in names])
    regexp = regexp.replace(r'\F', r'(?:[0-9]*\.?[0-9]*)|(?:inf)')
    regexp = regexp.replace(r'\G', r'(?:[0-9]*\.?[0-9]*)|(?:inf)|(?:[0-9]*\.?[0-9]*e[-+0-9]+)')

    regex = re.compile(regexp)
    matches = [(list(regex.finditer(f[-1])), f) for f in children]
    badmatches = [f for ms,f in matches if len(ms) == 0]

    if badmatches and matchall:
        raise ValueError('%s could not match %s' % (regexp, badmatches[0][-1]))
    matches = [(ms[0],f) for ms,f in matches if len(ms) > 0]

    groups = sorted([list(zip(names, [t(m or 'nan') for t,m in zip(types,mtch.groups())]))
        + [('f',f)] for mtch,f in matches])

    pdicts = [dict(lst) for lst in groups]
    for p in pdicts:
        p.update(args)
    return [FoundFile(**d) for d in pdicts]

def filefinder2(dir, *names, delim='_', matchall=True, types=Decimal, ext = 'tsv.gz'):
    """
    Find files based on a standard naming scheme of name value [delim name value...] (literal .) ext

    dir             : Directory to look in
    names           : keywords to look for / store into
    delim           : Delimiter separating file names
    matchall        : Match every file with the given extension
    types           : What types to apply (default: all Decimal). May be a single type or list of types
    ext             : File extension (ignores everything else) (default: 'tsv.gz')
    """
    import re, pathlib
    from collections import namedtuple
    FoundFile = namedtuple('FoundFile', list(names) + ['fname'])

    try:
        iter(types)
    except TypeError:
        types = [types] * len(names)

    dir = pathlib.Path(dir)
    children = [f for f in dir.iterdir() if f.name[(-len(ext)-1):] == '.' + ext]
    #print(len(children), [f[-1][(-len(ext)-1):] for f in dir.children()])

    def handlechild(c):
        cutf = c.name[:(-len(ext)-1)]
        splits = cutf.split(delim)
        if not len(splits) == len(names):
            raise ValueError("%r splits into %d instead of %d" %
                (cutf, len(splits), len(names)))
        ns, valstrs = zip(*[(v[:len(n)], v[len(n):]) for v,n in zip(splits,names)])
        m=0

        nspace = dict()
        nspace['fname'] = c
        #nspace['cutf'] = cutf
        for n,v,n0,t in zip(ns, valstrs, names, types):
            m += 1
            if not n == n0:
                raise ValueError("%r does not match %r in %dth arg %r in %r" % (
                n, n0, m, n+v, cutf))
            try:
                value = t(v)
            except:
                raise ValueError("%r not converted by %r in %dth arg %r in %r" % (
                v, t, m, n+v, cutf))
            nspace[n0] = value
        return FoundFile(**nspace)

    def trycatch(c):
        try:
            return handlechild(c)
        except ValueError as e:
            return None

    if matchall:
        nspaces = [handlechild(c) for c in children]
    else:
        nspaces = [trycatch(c) for c in children]
        nspaces = [n for n in nspaces if n is not None]

    return sorted(nspaces)

def groupfiles(dlst, key):
    bigdict = dict()
    for d in dlst:
        curval = getattr(d, key)
        keylist = bigdict.get(curval, [])
        keylist.append(d)
        bigdict[curval] = keylist
    return bigdict

def groupby(dlst, groupkey, sortby=None):
    if sortby is None:
        return sorted(groupfiles(dlst, groupkey).items())
    else:
        return sorted(groupfiles(dlst, groupkey).items(), key=sortby)


import pytest

import dpnp as inp

import numpy

def vvsort(val, vec, size):
    for i in range(size):
        imax = i
        for j in range(i + 1, size):
            if numpy.abs(val[imax]) < numpy.abs(val[j]):
                imax = j

        temp = val[i]
        val[i] = val[imax]
        val[imax] = temp

        for k in range(size):
            temp = vec[k, i]
            vec[k, i] = vec[k, imax]
            vec[k, imax] = temp

def test_cholesky():
    a = numpy.array([[[1, -2], [2, 5]]])
    ia = inp.array(a)
    result = inp.linalg.cholesky(ia)
    expected = numpy.linalg.cholesky(a)
    numpy.testing.assert_array_equal(expected, result)

def test_det():
    arrays = [
        [[0, 0], [0, 0]],
        [[1, 2], [1, 2]],
        [[1, 2], [3, 4]],
        [[[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]]],
        [[[[1, 2], [3, 4]], [[1, 2], [2, 1]]], [[[1, 3], [3, 1]], [[0, 1], [1, 3]]]]
    ]
    for array in arrays:
        a = numpy.array(array)
        ia = inp.array(a)
        result = inp.linalg.det(ia)
        expected = numpy.linalg.det(a)
        numpy.testing.assert_allclose(expected, result)

@pytest.mark.parametrize("type",
                         [numpy.float64, numpy.float32, numpy.int64, numpy.int32],
                         ids=['float64', 'float32', 'int64', 'int32'])
@pytest.mark.parametrize("size",
                         [2, 4, 8, 16, 300])
def test_eig_arange(type, size):
    a = numpy.arange(size * size, dtype=type).reshape((size, size))
    symm_orig = numpy.tril(a) + numpy.tril(a, -1).T + numpy.diag(numpy.full((size,), size * size, dtype=type))
    symm = symm_orig
    dpnp_symm_orig = inp.array(symm)
    dpnp_symm = dpnp_symm_orig

    dpnp_val, dpnp_vec = inp.linalg.eig(dpnp_symm)
    np_val, np_vec = numpy.linalg.eig(symm)

    # DPNP sort val/vec by abs value
    vvsort(dpnp_val, dpnp_vec, size)

    # NP sort val/vec by abs value
    vvsort(np_val, np_vec, size)

    # NP change sign of vectors
    for i in range(np_vec.shape[1]):
        if np_vec[0, i] * dpnp_vec[0, i] < 0:
            np_vec[:, i] = -np_vec[:, i]

    numpy.testing.assert_array_equal(symm_orig, symm)
    numpy.testing.assert_array_equal(dpnp_symm_orig, dpnp_symm)

    assert (dpnp_val.dtype == np_val.dtype)
    assert (dpnp_vec.dtype == np_vec.dtype)
    assert (dpnp_val.shape == np_val.shape)
    assert (dpnp_vec.shape == np_vec.shape)

    numpy.testing.assert_allclose(dpnp_val, np_val, rtol=1e-05, atol=1e-05)
    numpy.testing.assert_allclose(dpnp_vec, np_vec, rtol=1e-05, atol=1e-05)

def test_eigvals():
    arrays = [
        [[0, 0], [0, 0]],
        [[1, 2], [1, 2]],
        [[1, 2], [3, 4]]
    ]
    for array in arrays:
        a = numpy.array(array)
        ia = inp.array(a)
        result = inp.linalg.eigvals(ia)
        expected = numpy.linalg.eigvals(a)
        numpy.testing.assert_allclose(expected, result, atol=0.5)

def test_matrix_rank():
    arrays = [
        [0, 0],
        # [0, 1],
        [1, 2],
        [[0, 0], [0, 0]],
        # [[1, 2], [1, 2]],
        # [[1, 2], [3, 4]],
    ]
    tols = [None]
    for array in arrays:
        for tol in tols:
            a = numpy.array(array)
            ia = inp.array(a)
            result = inp.linalg.matrix_rank(ia, tol=tol)
            expected = numpy.linalg.matrix_rank(a, tol=tol)
            numpy.testing.assert_array_equal(expected, result)