from django.db.models import Q, Sum
from django.http import HttpResponseRedirect
from django.views import View
from django.shortcuts import render
from django import forms
from django.urls import reverse_lazy
from stock.models import Stock, RebookOrder, RebookOrderItem, RebookOrderItemDestinationStock
from django.contrib.auth.models import User
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin

from stock.rebook import RebookOnPositionOverviewBase, BookStockOnPositionBase, BookStockOnPositionFormBase

class RebookOrderForm(forms.ModelForm):
    class Meta:
        model = RebookOrder
        fields = ["user"]
        widgets = {
            'user': forms.RadioSelect(),
        }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.fields['user'].required = True

class RebookOrderItemForm(forms.ModelForm):
    class Meta:
        model = RebookOrderItem
        fields = ["amount"]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs["class"] = "form-control"
        self.fields['amount'].required = True

    def clean_amount(self):
        amount = self.cleaned_data['amount']
        print(f"{self.instance.stock}")
        if amount > self.instance.stock.bestand:
            self.add_error("amount", "Umzubuchende Menge kann nicht größer als der Bestand sein")
        if amount <= 0:
            self.add_error("amount", "Umzubuchende Menge muss mindestens 1 sein")
        return amount

class AssignRebookOrderView(LoginRequiredMixin, View):
    template_name = "rebook/order/accept_rebook.html"
    title = "Umbuchauftrag anlegen"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.stocks = None
        self.context = None
        self.form = None
        self.rebookitem_forms = None

    def dispatch(self, request, *args, **kwargs):
        self.stocks = Stock.objects.filter(pk__in=request.GET.getlist("item"))
        self.form = self.get_form()
        self.rebookitem_forms = self.get_rebookitem_forms()
        self.context = self.get_context()
        return super().dispatch(request, *args, **kwargs)

    def get_rebookitem_forms(self):
        forms = []
        index = 0
        for stock in self.stocks:
            data = {}
            if self.request.method == "POST":
                amount = self.request.POST.getlist("amount")[index]
                data["amount"] = amount
            form = RebookOrderItemForm(data=data)
            form.instance.stock = stock
            form.instance.position = stock.lagerplatz
            form.instance.sku = stock.sku_instance
            forms.append((form, stock))
            index += 1
        return forms

    def get_form(self):
        if self.request.method == "POST":
            form = RebookOrderForm(data=self.request.POST)
        else:
            form = RebookOrderForm()
        return form

    def get_context(self):
        context = {"title": self.title, "stocks": self.stocks, "form": self.form,
                   "rebookitem_forms": self.rebookitem_forms}
        return context

    def get(self, request, *args, **kwargs):
        print(f"Hey dead: ")
        return render(request, self.template_name, self.context)

    def post(self, request, *args, **kwargs):
        if self.form.is_valid() is True:
            has_invalid_form = None
            for form, stock in self.rebookitem_forms:
                print(f"3anlash: {request.method}")
                print(f"sam: {form.data}")
                if form.is_valid() is False:
                    has_invalid_form = True
            if has_invalid_form is True:
                return render(request, self.template_name, self.context)
            else:
                self.save_rebook_order()
                return HttpResponseRedirect(reverse_lazy("stock:list"))
        else:
            return render(request, self.template_name, self.context)

    def save_rebook_order(self):
        rebook_order_instance = self.form.save()
        for rebookitem_form, stock in self.rebookitem_forms:
            rebookitem_form_instance = rebookitem_form.save(commit=False)
            rebookitem_form_instance.rebook_order = rebook_order_instance
            rebookitem_form_instance.save()

class RebookOrderListView(LoginRequiredMixin, generic.ListView):
    template_name = "rebook/order/rebook_order_list.html"
    paginate_by = 15
    title = "Umbuchaufträge Übersicht"

    def get_queryset(self):
        queryset = RebookOrder.objects.filter(user=self.request.user)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(self.get_context())
        return context

    def get_context(self):
        return {"title": self.title}

class RebookOrderView(LoginRequiredMixin, View):
    template_name = "rebook/order/rebook_order.html"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.rebook_order = None
        self.rebook_order_items = None
        self.item = None
        self.context = None

    def dispatch(self, request, *args, **kwargs):
        self.rebook_order = RebookOrder.objects.get(pk=self.kwargs.get("pk"))
        self.rebook_order_items = []
        for item in self.rebook_order.rebookorderitem_set.all():
            rebooked_amount = item.rebookorderitemdestinationstock_set.all().aggregate(
                total=Sum("rebooked_amount")).get("total", 0) or 0
            self.rebook_order_items.append((item, rebooked_amount))

        self.context = self.get_context()
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, self.context)

    def get_context(self):
        return {"title": f"Umbuchauftrag {self.rebook_order.pk}", "rebook_order": self.rebook_order,
                "rebook_order_items": self.rebook_order_items}

class RebookOrderRebookOnPositionOverview(RebookOnPositionOverviewBase):
    template_name = "rebook/order/rebook_on_position_list.html"

    def get_position_from_GET_or_session(self):
        get_value = self.request.GET.get("position", "") or ""

        if get_value != "":
            self.request.session["rebook_order_position"] = get_value
            return get_value.strip()
        else:
            return (self.request.session.get("rebook_order_position", "") or "").strip()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.rebook_order = None
        self.item = None

    def pre_dispatch(self):
        self.rebook_order = RebookOrder.objects.get(pk=self.kwargs.get("pk"))
        self.item = RebookOrderItem.objects.get(pk=self.kwargs.get("item_pk"))
        self.stock = Stock.objects.get(pk=self.item.stock.pk)
        self.position = self.get_position_from_GET_or_session()

    def redirect(self):
        if self.item.rebooked is True and self.item.amount == self.item.rebooked_amount:
            return HttpResponseRedirect(reverse_lazy("stock:rebook_order", kwargs={"pk": self.rebook_order.pk}))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["rebook_order"] = self.rebook_order
        context["rebook_order_item"] = self.item
        rebooked_amount = self.item.rebookorderitemdestinationstock_set.all().aggregate(
            total=Sum("rebooked_amount")).get("total", 0) or 0
        context["rebook_amount"] = self.item.amount-rebooked_amount or 0
        return context

class BookStockOrderOnPositionForm(BookStockOnPositionFormBase):
    def __init__(self, item=None, **kwargs):
        super().__init__(**kwargs)
        self.item = item
        self.stock = self.item.stock

    def get_amount_limit(self):
        rebooked_amount = self.item.rebookorderitemdestinationstock_set.all().aggregate(
            total=Sum("rebooked_amount")).get("total", 0) or 0
        rebooked_amount = self.item.amount-rebooked_amount or 0
        return rebooked_amount

class RebookOrderBookStockOnPosition(BookStockOnPositionBase):
    template_name = "rebook/order/book_stock_on_position.html"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.rebook_order = None
        self.item = None
        self.destination_stock = None
        self.item_destination_stock = None

    def pre_dispatch(self):
        self.rebook_order = RebookOrder.objects.get(pk=self.kwargs.get("pk"))
        self.item = RebookOrderItem.objects.get(pk=self.kwargs.get("item_pk"))
        self.stock = self.item.stock

    def get_context(self):
        context = super().get_context()
        context["rebook_order"] = self.rebook_order
        context["rebook_order_item"] = self.item
        rebooked_amount = self.item.rebookorderitemdestinationstock_set.all().aggregate(
            total=Sum("rebooked_amount")).get("total", 0) or 0
        context["rebook_amount"] = self.item.amount-rebooked_amount or 0
        return context

    def pre_rebook_stock_to_destination(self, destination_stock, destination_sku, destination_position):
        if self.item is not None:
            self.item_destination_stock = RebookOrderItemDestinationStock(
                destination_stock=destination_stock, destination_position=destination_position,
                destination_sku=destination_sku, rebook_order_item=self.item,
                rebooked_amount=self.form.cleaned_data.get("amount"))

    def post(self, request, *args, **kwargs):
        if self.stock.id is None:
            self.item.stock = None
        self.item_destination_stock.save()
        total_amount = self.item.rebookorderitemdestinationstock_set.all().aggregate(
            total=Sum("rebooked_amount")).get("total")
        if self.item.amount == total_amount:
            self.item.rebooked = True
            self.item.save()
        self.finish_rebook_order_if_finished()
        return HttpResponseRedirect(reverse_lazy("stock:rebook_order", kwargs={"pk": self.rebook_order.pk}))

    def finish_rebook_order_if_finished(self):
        items = self.rebook_order.rebookorderitem_set.all()
        for item in items:
            rebooked_amount = 0
            for destination_stock_item in item.rebookorderitemdestinationstock_set.all():
                rebooked_amount += destination_stock_item.rebooked_amount or 0
            if rebooked_amount != item.amount or item.rebooked is not True:
                return

        if items.count() > 0:
            self.rebook_order.completed = True
            self.rebook_order.save()

    def get_form(self):
        if self.request.method == "POST":
            self.form = BookStockOrderOnPositionForm(data=self.request.POST, item=self.item)
        else:
            self.form = BookStockOrderOnPositionForm(item=self.item)
        return self.form


text = 'flipped class room is important'

def reverse(s):
	result = ''.join([ s[i] for i in range(len(s)-1, -1, -1) ])
	return result

def reverse_word(s):
	words = s.split(' ')
	result = []
	for word in words:
		result.append(reverse(word))
	result = ' '.join(result)
	return result

print(reverse_word(text))


import sys
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math

def f_gold ( n ) :
    ar = [ 0 ] * 10
    while ( n > 0 ) :
        digit = math.floor ( n % 10 )
        if ( ar [ digit ] ) :
            return 0
        ar [ digit ] = 1
        n = n / 10
    return 1

#TOFILL
if __name__ == '__main__':
    param = [
    (474,),
    (9445,),
    (90,),
    (30,),
    (37453,),
    (27,),
    (2400,),
    (98,),
    (46,),
    (722,)
        ]
    n_success = 0
    print("class,mutant,test_index,result")
    for i, parameters_set in enumerate(param):
        try:
            print("PROGRAM_TO_CHECK_IF_A_GIVEN_NUMBER_IS_LUCKY_ALL_DIGITS_ARE_DIFFERENT," + sys.argv[1] + "," + str(i) + "," + str(f_gold(*parameters_set)))
        except:
            print("PROGRAM_TO_CHECK_IF_A_GIVEN_NUMBER_IS_LUCKY_ALL_DIGITS_ARE_DIFFERENT," + sys.argv[1] + "," + str(i) + ",EXCEPTION")


# Librerías externas.
import customtkinter
import math

# Librerías propias.
from calculadora.python.metadata.path import PathImages

# Apariencia de la ventana principal.
customtkinter.set_appearance_mode("Dark")
customtkinter.set_default_color_theme("blue")

class VentanaCalculadora(customtkinter.CTk):

    def __init__(self):
        super().__init__()
        # Organizo la ventana principal.
        self.geometry('282x434')
        self.calculadora_titulo = 'Calculadora'
        self.title(self.calculadora_titulo)

        # Creo configuración para la entrada y los botones.
        self.font_entrada = ('Arial', 32, 'bold')
        self.font_botones = ('Arial', 24)
        self.iconbitmap(PathImages.icono)

        self.resultado = ''

        self.home_frame = customtkinter.CTkFrame(self, width=282, height=435)
        self.home_frame.pack()
        self.texto_variable = customtkinter.StringVar()

        # Creo la ventana de entrada de texto.
        self.entrada_texto = customtkinter.CTkEntry(
            self.home_frame, width=280, height=60, font=self.font_entrada,
            justify=customtkinter.RIGHT, textvariable=self.texto_variable)
        self.entrada_texto.place(x=0, y=0)

        self.boton_porcent = customtkinter.CTkButton(
            self.home_frame, text='%', font=self.font_botones,
            command=lambda: self.ingresar_valores('%'), width=70, height=60)
        self.boton_porcent.place(x=0, y=65)

        # Creo los botones de la calculadora.
        boton_ce = customtkinter.CTkButton(
            self.home_frame, text='CE', font=self.font_botones,
            command=lambda: self.ingresar_valores('CE'), width=70, height=60)
        boton_ce.place(x=70, y=65)

        boton_c = customtkinter.CTkButton(
            self.home_frame, text='C', font=self.font_botones,
            command=self.borrar_campo, width=70, height=60)
        boton_c.place(x=140, y=65)

        boton_borrar = customtkinter.CTkButton(
            self.home_frame, text=chr(9003), font=self.font_botones,
            command=self.borrar_campo_parcial, width=70, height=60)
        boton_borrar.place(x=210, y=65)

        boton_inverso = customtkinter.CTkButton(
            self.home_frame, text='1/x', font=self.font_botones,
            command=self.obtener_inverso, width=70, height=60)
        boton_inverso.place(x=0, y=126)

        boton_cuadrado = customtkinter.CTkButton(
            self.home_frame, text='x\u00B2', font=self.font_botones,
            command=self.obtener_cuadrado, width=70, height=60)
        boton_cuadrado.place(x=70, y=126)

        boton_raiz_cuadrada = customtkinter.CTkButton(
            self.home_frame, text='\u221A', font=self.font_botones,
            command=self.obtener_raiz_cuadrada, width=70, height=60)
        boton_raiz_cuadrada.place(x=140, y=126)

        boton_division = customtkinter.CTkButton(
            self.home_frame, text='\u00F7', font=self.font_botones,
            command=lambda: self.ingresar_valores('/'), width=70, height=60)
        boton_division.place(x=210, y=126)

        boton_7 = customtkinter.CTkButton(
            self.home_frame, text='7', font=self.font_botones,
            command=lambda: self.ingresar_valores(7), width=70, height=60)
        boton_7.place(x=0, y=187)

        boton_8 = customtkinter.CTkButton(
            self.home_frame, text='8', font=self.font_botones,
            command=lambda: self.ingresar_valores(8), width=70, height=60)
        boton_8.place(x=70, y=187)

        boton_9 = customtkinter.CTkButton(
            self.home_frame, text='9', font=self.font_botones,
            command=lambda: self.ingresar_valores(9), width=70, height=60)
        boton_9.place(x=140, y=187)

        boton_multiplicacion = customtkinter.CTkButton(
            self.home_frame, text='x', font=self.font_botones,
            command=lambda: self.ingresar_valores('*'), width=70, height=60)
        boton_multiplicacion.place(x=210, y=187)

        boton_4 = customtkinter.CTkButton(
            self.home_frame, text='4', font=self.font_botones,
            command=lambda: self.ingresar_valores(4),
            width=70, height=60)
        boton_4.place(x=0, y=248)

        boton_5 = customtkinter.CTkButton(
            self.home_frame, text='5', font=self.font_botones,
            command=lambda: self.ingresar_valores(5), width=70, height=60)
        boton_5.place(x=70, y=248)

        boton_6 = customtkinter.CTkButton(
            self.home_frame, text='6', font=self.font_botones,
            command=lambda: self.ingresar_valores(6), width=70, height=60)
        boton_6.place(x=140, y=248)

        boton_resta = customtkinter.CTkButton(
            self.home_frame, text='\u2212', font=self.font_botones,
            command=lambda: self.ingresar_valores('-'), width=70, height=60)
        boton_resta.place(x=210, y=248)

        boton_1 = customtkinter.CTkButton(
            self.home_frame, text='1', font=self.font_botones,
            command=lambda: self.ingresar_valores(1), width=70, height=60)
        boton_1.place(x=0, y=309)

        boton_2 = customtkinter.CTkButton(
            self.home_frame, text='2', font=self.font_botones,
            command=lambda: self.ingresar_valores(2), width=70, height=60)
        boton_2.place(x=70, y=309)

        boton_3 = customtkinter.CTkButton(
            self.home_frame, text='3', font=self.font_botones,
            command=lambda: self.ingresar_valores(3), width=70, height=60)
        boton_3.place(x=140, y=309)

        boton_suma = customtkinter.CTkButton(
            self.home_frame, text='+', font=self.font_botones,
            command=lambda: self.ingresar_valores('+'), width=70, height=60)
        boton_suma.place(x=210, y=309)

        boton_mas_menos = customtkinter.CTkButton(
            self.home_frame, text='\u00B1', font=self.font_botones,
            command=self.obtener_nuevo_signo, width=70, height=60)
        boton_mas_menos.place(x=0, y=371)

        boton_0 = customtkinter.CTkButton(
            self.home_frame, text='0', font=self.font_botones,
            command=lambda: self.ingresar_valores(0), width=70, height=60)
        boton_0.place(x=70, y=371)

        boton_cierra = customtkinter.CTkButton(
            self.home_frame, text='.', font=self.font_botones,
            command=lambda: self.ingresar_valores('.'), width=70, height=60)
        boton_cierra.place(x=140, y=371)

        boton_igualdad = customtkinter.CTkButton(
            self.home_frame, text='=', font=self.font_botones,
            command=self.calcular, width=70, height=60)
        boton_igualdad.place(x=210, y=371)

    def ingresar_valores(self, simbolo: int | str) -> None:
        caracteres = ['.', '+', '-', '*', '/']

        if simbolo in list(range(10)) + caracteres:
            self.texto_variable.set(self.texto_variable.get() + str(simbolo))

        if simbolo == '%':
            simbolo.replace('%', '/100')
            self.texto_variable.set(
                self.texto_variable.get() + str(simbolo.replace('%', '/100')))

    def calcular(self):
        self.resultado = str(eval(self.texto_variable.get()))
        self.borrar_campo()
        self.entrada_texto.insert(0, self.resultado)
        self.texto_variable.set(self.resultado)

    def obtener_porcentaje(self) -> None:
        self.resultado = str(float(self.texto_variable.get()) / 100)
        self.entrada_texto.insert(0, self.resultado)
        self.texto_variable.set(self.resultado)

    def borrar_campo(self):
        self.entrada_texto.delete(0, customtkinter.END)

    def borrar_campo_parcial(self):
        self.resultado = self.texto_variable.get()[:-1]
        print(self.resultado)
        self.texto_variable.set(self.resultado)

    def obtener_inverso(self) -> None:
        self.resultado = str(1 / float(self.texto_variable.get()))
        self.texto_variable.set(self.resultado)

    def obtener_cuadrado(self) -> None:
        self.resultado = str(float(self.texto_variable.get()) ** 2)
        self.entrada_texto.delete(0, 'end')
        self.texto_variable.set(self.resultado)

    def obtener_raiz_cuadrada(self) -> None:
        self.resultado = str(math.sqrt(float(self.texto_variable.get())))
        self.entrada_texto.insert(0, self.resultado)
        self.texto_variable.set(self.resultado)

    def obtener_nuevo_signo(self) -> None:
        self.resultado = str(-1 * float(self.texto_variable.get()))
        self.entrada_texto.insert(0, self.resultado)
        self.texto_variable.set(self.resultado)


# write a function that takes in a list of integers as an argument and returns a list of integers comprising only the even numbers.

ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def filter_evens(number):
    num=0
    num=+1
    for num in number:
        if num%2 == 0:
            print(num)

filter_evens(ints)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan  8 14:10:32 2021

@author: siirias
"""
"""
Observations, reference run and control period runs show a decreasing trend
in both length of ice season and ice thickness, but with some differences in
the rate of change. Observations of the ice season length give a trend
of
-10 days/decade in Kemi,
-12 days/decade in Kalajoki and
-13 days/decade in Sälgrund, but
no change in Kylmäpihlaja.

Reference run/control period runs show
-2/-2 days/decade in Kemi,
-9/-2 days/decade in Kalajoki,
-9/0 days/decade in Sälgrund and
-8/0 days/decade in Kylmäpihlaja.

Scenarios (RCP4.5/RCP8.5) predict the change to continue:
-7/-6 days/decade in Kemi,
-10/-11 days/decade in Kalajoki,
-9/-11 days/decade in Sälgrun and
-8/-9 days/decade in Kylmäpihlaja.

\huom{Oisko nämä nätimpi esittää taulukossa? tulee niin monta lukua,
että alkaa mennä teksti sekavaksi}
In addition to decreasing trend, scenarios predict increase in the interannual
variability of these sea ice variables
"""

import pandas as pd

names = ['Kemi', 'Kalajoki', 'Sälgrund', 'Kylmäpihlaja']
observation_trend_length = [-10,-12,-13,0]
reference_trend_length = [-2,-9,-9,-8]
control_trend_length = [-2,-2,0,0]
rcp45_trend_length = [-7, -10, -9, -8]
rcp85_trend_length = [-6, -11, -11, -9]

column_names = ['observations', 'reference', 'control', 'RCP 4.5', 'RCP 8.5']

tmp = [observation_trend_length, reference_trend_length,
        control_trend_length, rcp45_trend_length, rcp85_trend_length]
data = {}
for i,j in zip(column_names,tmp):
    data[i] = j

dat = pd.DataFrame(data, index = names)
dat.name = "Ice season length trends in days/decade"

print(dat.to_latex(label = "tab:ice_season_length_trends", caption = dat.name))


import sys
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
import logging
import json
import re
import hashlib
from Outer import *
from PandasGrapher import *
from PPDFFilterer import *
from PPStator import *
from DFFormatter import *

#--------------------------------------------------------------------------------------
class PPFramor() :

  pd.options.display.float_format = '{:.0f}'.format

  #--------------------------------------------------------------------------------------
  def __init__(self,param,file,tsm=None) :
    self.param=param
    self.tsm=tsm
    self.p=self.param.getAll()
    logging.warning("PPFramor begins")
    self.file=file
    self.decimal='.'
    self.ppregex=self.p['ppregex']
    self.ppregexclude=self.p['ppregexclude']
    self.percentiles=self.p['percentiles']
    self.setRawdatas()
    self.report()
    logging.warning("PPFramor ends")

#--------------------------------------------------------------------------------------
  def getRawdatas(self) :
    return(self.rawdatas)

#--------------------------------------------------------------------------------------
  def getDatas(self) :
    return(self.datas)
#--------------------------------------------------------------------------------------
  def getFile(self) :
    return(self.file)

#--------------------------------------------------------------------------------------
  def setRawdatas(self) :
    self.p['datafile']=self.file
    self.DFF=DFFormatter.getFromFactory(self.p['type'],self.p)

    ppf=PPDFFilterer(self.DFF.getDf(),self.param)
    self.datas=ppf.getDfOK()
    self.ko=ppf.getDfKO()
    self.tsmList=self.datas['ts10m'].unique()
    if self.tsm is not None:
      self.datas=self.datas[ self.datas['ts10m'] == self.tsm ]
    self.rawdatas=self.datas.groupby('PurePath')['ResponseTime'].describe(percentiles=self.percentiles)

#--------------------------------------------------------------------------------------
  def report(self) :
    self.p['out'].h2("PP from " + self.file)
    self.ppStator=PPStator(self.param,self.datas)
    self.ppStatorKO=PPStator(self.param,self.ko)
    with pd.option_context('display.max_rows', None, 'display.max_colwidth', 0, 'display.float_format','{:.2f}'.format) :
      self.p['out'].out("Summary stats",self.ppStator.getXstats(),escape=False)
      self.p['out'].out("Error stats",self.ppStatorKO.getXstats(),escape=False)

#--------------------------------------------------------------------------------------
  def getTsmlist(self,tsm) :
    return(self.tsmList)

#--------------------------------------------------------------------------------------
class PPComparator() :

  #--------------------------------------------------------------------------------------
  def __init__(self,param,f1,f2) :
    self.param=param
    self.p=self.param.getAll()
    self.grapher=PandasGrapher(self.param)
    self.f1=f1
    self.f2=f2
    self.df1=f1.getRawdatas()
    self.df2=f2.getRawdatas()
    self.go()

  @staticmethod
  #--------------------------------------------------------------------------------------
  def deltaCountPe(x) :
    return(PPComparator.deltaPe('count',x))

  @staticmethod
  #--------------------------------------------------------------------------------------
  def deltaStdPe(x) :
    return(PPComparator.deltaPe('std',x))

  @staticmethod
  #--------------------------------------------------------------------------------------
  def deltaMeanPe(x) :
    return(PPComparator.deltaPe('mean',x))

  @staticmethod
  #--------------------------------------------------------------------------------------
  def deltaP50Pe(x) :
    return(PPComparator.deltaPe('50%',x))

  @staticmethod
  #--------------------------------------------------------------------------------------
  def deltaP95Pe(x) :
    return(PPComparator.deltaPe('95%',x))

  @staticmethod
  #--------------------------------------------------------------------------------------
  def deltaPe(field,x) :
    kx=field+"_x"
    ky=field+"_y"
    if x[kx] > 0 :
      return(100*(x[ky]-x[kx])/x[kx])
    return(0)

  #--------------------------------------------------------------------------------------
  def go(self) :
    #print(self.df1)
    #print(self.df2)
    dfm=pd.merge(self.df1,self.df2,on='PurePath',how='outer')
    dfm.reset_index(inplace=True)
    dfm['DMax']=dfm.apply(lambda x: x['max_y'] - x['max_x'],axis=1 )
    dfm['DStd']=dfm.apply(lambda x: x['std_y'] - x['std_x'],axis=1 )
    dfm['DCount']=dfm.apply(lambda x: x['count_y'] - x['count_x'],axis=1 )
    dfm['DMean']=dfm.apply(lambda x: x['mean_y'] - x['mean_x'],axis=1 )
    dfm['DP50']=dfm.apply(lambda x: x['50%_y'] - x['50%_x'],axis=1 )
    dfm['DP95']=dfm.apply(lambda x: x['95%_y'] - x['95%_x'],axis=1 )
    dfm['DStd%']=dfm.apply(PPComparator.deltaStdPe,axis=1 )
    dfm['DCount%']=dfm.apply(PPComparator.deltaCountPe,axis=1 )
    dfm['DMean%']=dfm.apply(PPComparator.deltaMeanPe,axis=1 )
    dfm['DP50%']=dfm.apply(PPComparator.deltaP50Pe,axis=1 )
    dfm['DP95%']=dfm.apply(PPComparator.deltaP95Pe,axis=1 )
    dfm.fillna(value=0,inplace=True)
    filter=True
    if filter :
      #dfm=dfm[(dfm['count_x'] > self.p['autofocuscount']) | (dfm['count_y'] > self.p['autofocuscount']) ]
      #dfm=dfm[(dfm['mean_x'] > self.p['autofocusmean']) | (dfm['mean_y'] > self.p['autofocusmean']) ]
      #dfm=dfm[(abs(dfm['DMeanPe']) > 10)]
      pass
    #logging.warning(dfm)
    if dfm.size == 0 :
      return
    with pd.option_context('display.max_rows', None) :
      self.p['out'].h2("Comparison of requests : x=" + self.f1.getFile() + " y=" + self.f2.getFile())
      self.p['out'].out("Compare",dfm[['PurePath','count_x','count_y','DCount','DCount%',
          'mean_x','mean_y','DMean','DMean%',
          'std_x','std_y','DStd','DStd%',
          '50%_x','50%_y','DP50','DP50%',
          '95%_x','95%_y','DP95','DP95%',
          'max_x','max_y','DMax']],
          escape=False,classes='tablePPcompareProcessor')
      self.graphIt(self.f1.getFile(),self.f1.getDatas())
      self.graphIt(self.f2.getFile(),self.f2.getDatas())

  #--------------------------------------------------------------------------------------
  def graphIt(self,title,df) :
      self.dfall=pd.DataFrame(df.groupby(self.p['timeGroupby'])['StartTime'].count().apply(lambda x: 0))
      self.grapher.setDfall(self.dfall)
      dg=df.groupby(self.p['timeGroupby'])['ResponseTime']
      self.p['out'].h3("Time view for " + title)
      self.grapher.graphBasicsNew("Time view " + title, dg, [
      { 'aggr' : 'Max', 'dgaggr' : dg.max(), 'color' : 'red'},
      { 'aggr' : 'Mean', 'dgaggr' : dg.mean(), 'color' : 'green'},
      { 'aggr' : 'Q50', 'dgaggr' : dg.quantile(0.5), 'color' : 'green'},
      { 'aggr' : 'Q95', 'dgaggr' : dg.quantile(0.95), 'color' : 'green'},
      ])

#--------------------------------------------------------------------------------------
class PPCompareProcessor() :

  #--------------------------------------------------------------------------------------
  def __init__(self,param) :
    self.param=param
    self.p=self.param.getAll()
    self.p['out'].setPPdiv("PPCompareProcessor")
    self.dfs=[]
    logging.warning(self.p)
    self.dfs.append(PPFramor(self.param,self.p['file1']))
    if ('file2' in self.p) & (self.p['file2'] is not None) :
      self.p['out'].h1('PPCompareProcessor compare ' + self.p['file1'] + ' and ' + self.p['file2'])
      #self.dfs.append(PPFramor(self.param,self.p['file1']))
      self.dfs.append(PPFramor(self.param,self.p['file2']))
    else :
      self.dfs.append(PPFramor(self.param,self.p['file1']))
      #self.p['out'].h1('PPCompareProcessor autocompare ' + self.p['file1'])
      #fr=PPFramor(self.param,self.p['file1'])
      #for tsm in fr.getTsmlist('ts10m') :
      #  self.dfs.append(PPFramor(self.param,self.p['file1'],tsm))
      pass

  #--------------------------------------------------------------------------------------
  def setBehavior(self) :
    self.ppregex=self.p['ppregex']
    self.ppregexclude=self.p['ppregexclude']
    pd.options.display.float_format = '{:.0f}'.format

  #--------------------------------------------------------------------------------------
  def go(self) :
    for i in range(0,len(self.dfs)-1) :
      PPComparator(self.param,self.dfs[i],self.dfs[i+1])


def determinant(matrix):

    firstRow = matrix[0]
    n = len(firstRow)

    if n == 1:
        return matrix[0][0]

    deter = 0

    for i in range(n):
        deter = deter + (-1) ** i * firstRow[i] * determinant([[x[j] for j in range(len(x)) if j != i] for x in matrix[1:]])

    return deter


#!/usr/bin/env python
import rospy
from nav_msgs.msg import Path
import time
import rospy
import numpy as np

LongitudTotal=0
longitud_anterior=0
cont=0

def callback(path_msg):
    global longitud_anterior
    global LongitudTotal
    global cont
    path_length=0
    for i in range(len(path_msg.poses) - 1):
        position_a_x = path_msg.poses[i].pose.position.x
        position_b_x = path_msg.poses[i+1].pose.position.x
        position_a_y = path_msg.poses[i].pose.position.y
        position_b_y = path_msg.poses[i+1].pose.position.y

        path_length += np.sqrt(np.power((position_b_x - position_a_x), 2) + np.power((position_b_y- position_a_y), 2))
    if(longitud_anterior==0):
        longitud_anterior=path_length
    LongitudTotal+=-path_length+longitud_anterior
    longitud_anterior=path_length
    if cont==0:
        print("Longitud total del camino global: ",path_length)
    if path_length<=0.2:
        print("Longitud total del camino local: ",LongitudTotal)
    cont+=1

rospy.init_node('suscriptor')
rospy.Subscriber("/move_base/TebLocalPlannerROS/global_plan", Path, callback)
rospy.spin()


from typing import List

import requests
import collections

Pokemon = collections.namedtuple('Pokemon', 'name, weight')

def find_pokemon_from_name(id: str) -> List[Pokemon]:
    url = f'https://pokeapi.co/api/v2/pokemon-species/{id}'

    resp = requests.get(url)
    resp.raise_for_status()

    results = resp.json()

    information = results['flavor_text_entries']

    print(results['name'])
    print(information[0])


"""
Module containing functionality for pre-setting build config files, directories, ...
"""

from typing import Dict
import os

from pyggui.helpers import Json

def update_config_file(dir_path: str, data: Dict) -> None:
    """
    Function updates the current config file in the project using this library.
    Where config file is just a config.json file saved in the build directory on the top level of the project.

    Args:
        dir_path (str): Path to projects directory.
        data (Dict): Dictionary of key, value pairs to update in the file.
    """
    build_path = os.path.join(dir_path, "build")
    if not os.path.isdir(build_path):
        os.mkdir(build_path)

    config_file_path = os.path.join(build_path, "configure.json")
    if os.path.isfile(config_file_path):
        Json.update(config_file_path, data)
    else:
        Json.save(config_file_path, data)


#!/usr/bin/env python3
import os
import sys
import pprint
import re
import json
import networkx as nx

def usage(exitVal, filename=""):
    print(f"Error: Incorrect usage")
    if exitVal == -2:
        print(f"File {filename} does not exist\n")
    print(f'Usage: {os.path.basename(sys.argv[0])} filename')
    exit(exitVal)

def getAdjList():
    pass

def main():

    f = open("unique_syscalls.txt", "r")
    calls = [line.strip() for line in f.readlines()]

    if len(sys.argv) < 2:
        usage(-1)
    filename = sys.argv[1]
    try:
        adj_file = open(filename, "rb")
    except FileNotFoundError:
        usage(-2, filename)

    G = nx.read_multiline_adjlist(adj_file, create_using=nx.DiGraph)

    # Get pagerank and append to feature vector:
    pr = nx.pagerank(G)

    fv = []
    for call in calls:
        fv.append(pr.get(call, 0))

    # Get average clustering value and append to feature vector:
    fv.append(nx.average_clustering(G, weight='weight'))

    # Get eigenvector centrality values and append all to feature vector:
    ec = nx.eigenvector_centrality(G, weight='weight')
    for call in calls:
        fv.append(ec.get(call, 0))
    print(fv)
    print(len(fv))

if __name__ == '__main__':
    main()


class Solution:
    def letterCombinations(self, digits: str) -> List[str]:

        num_letter = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}

        def combine(index, string):

            if len(string) == len(digits):
                res.append(string)
                return

            for char in num_letter[digits[index]]:
                string += char
                combine(index + 1, string)
                string = string[:-1]

        res = []
        if len(digits) == 0:
            return res

        combine(0, '')
        return res


# -*- coding: utf-8 -*-
import logging
from redis.lock import LuaLock

logger = logging.getLogger(__name__)

class RedisLuaLock(LuaLock):
    @classmethod
    def lua_acquire(cls, keys, args, client):
        args = tuple(keys) + tuple(args)
        return client.eval(cls.LUA_ACQUIRE_SCRIPT, len(keys), *args)

    @classmethod
    def lua_release(cls, keys, args, client):
        args = tuple(keys) + tuple(args)
        try:
            client.eval(cls.LUA_RELEASE_SCRIPT, len(keys), *args)
        except Exception:
            logger.warn("Fail to release redis lua lock")
        return True

    @classmethod
    def lua_extend(cls, keys, args, client):
        args = tuple(keys) + tuple(args)
        return client.eval(cls.LUA_EXTEND_SCRIPT, len(keys), *args)


# 795×300 pixels.
# 72dpi or 92dpi

# _1977
# aden
# brannan
# brooklyn
# clarendon
# earlybird
# gingham
# hudson
# inkwell
# kelvin
# lark
# lofi
# maven
# mayfair
# moon
# nashville
# perpetua
# reyes
# rise
# slumber
# stinson
# toaster
# valencia
# walden
# willow
# xpro2

import os
from PIL import Image
from PIL import ImageOps
from PIL import ImageEnhance
from PIL import ImageFilter
from PIL import ImageDraw
from PIL import ImageFont
from PIL.ImageFilter import (
    RankFilter, MedianFilter, MinFilter, MaxFilter, EDGE_ENHANCE,
)
import pilgram.css
import shutil

from img_temperature import set_temperature

pilgramfilters_name = [
    #'_1977',
    # 'aden',
    # 'brannan',
    # 'brooklyn',
    'clarendon',
    # 'earlybird',
    'gingham',
    'hudson',
    # 'inkwell',
    # 'kelvin',
    'lark',
    # 'lofi',
    # 'maven',
    # 'mayfair',
    # 'moon',
    # 'nashville',
    # 'perpetua',
    'reyes',
    'rise',
    'slumber',
    'stinson',
    # 'toaster',
    'valencia',
    'walden',
    # 'willow',
    # 'xpro2'
]

base_path = '/Users/cadu/Downloads/fotos_originais'
images_abs_paths = [os.path.join(base_path, f) for f in os.listdir(base_path) if f.endswith('jpg')]
# image_abs_path = images_abs_paths[0]
# image = PIL.Image.open(image_abs_path)

out_dir = os.path.join(os.path.normpath(base_path + os.sep + os.pardir), 'fotosout')

watermark_text = " ©  Necto Systems® - www.necto.com.br  "

font = ImageFont.truetype('/Users/cadu/Library/Fonts/MYRIADPRO-REGULAR.OTF', 20)

try:
    os.makedirs(out_dir)
    print('diretorio recem criado')
except FileExistsError:
    # os.rmdir(out_dir)  # does not remove non empty directorys
    shutil.rmtree(out_dir)
    os.makedirs(out_dir)
    print('diretorio foi apagado, e recriado')

for image_abs_path in images_abs_paths:
    image = None
    image = Image.open(image_abs_path)
    image.thumbnail((600, 600))
    # image = ImageOps.equalize(image)
    # image = image.filter(MaxFilter(size=3))

    enhancer = ImageEnhance.Color(image)
    image = enhancer.enhance(0.2)

    enhancer = ImageEnhance.Brightness(image)
    image = enhancer.enhance(1.4)

    enhancer = ImageEnhance.Contrast(image)
    image = enhancer.enhance(1.2)

    drawing = ImageDraw.Draw(image)
    text_w, text_h = drawing.textsize(watermark_text, font)
    image_width, image_height = image.size
    text_position = image_width - text_w, (image_height - text_h) - 20
    text_image = Image.new('RGB', (text_w, (text_h)), color='#000000')
    text_image.putalpha(20)
    drawing.text((text_position[0], text_position[1]), watermark_text, fill="#ffffff", font=font)

    for filter_name in pilgramfilters_name:
        pilgram_filter = getattr(pilgram, filter_name)
        # o filtro não pode retornar para a mesma var !!!!
        image_filtered = pilgram_filter(image)

        image_filtered = set_temperature(image_filtered, 9100)
        image_filtered.paste(text_image, text_position, text_image)
        image_filtered.save(os.path.join(out_dir, f'{filter_name}_{os.path.basename(image_abs_path)}'), quality=72)

print(f'Exit directory: {out_dir}')


import numpy as np
from alexnet import alexnet
from game_trainer import _balanced_file_name

WIDTH = 80
HEIGHT = 60
LR = 1e-3
EPOCH = 8
MODEL_NAME = "pyets2-truck-{}-{}-{}-epochs.model".format(LR, 'alexnetv2', EPOCH)

model = alexnet(WIDTH, HEIGHT, LR)

training_data = np.load(_balanced_file_name)

train = training_data[:-500]
test = training_data[-500:]

X = np.array([i[0] for i in train]).reshape(-1, WIDTH, HEIGHT, 1)
Y = [i[1] for i in train]

test_x = np.array([i[0] for i in test]).reshape(-1, WIDTH, HEIGHT, 1)
test_y = [i[1] for i in test]

model.fit({'input': X}, {'targets': Y}, n_epoch=EPOCH,
          validation_set=({'input': test_x}, {'targets': test_y}),
          snapshot_step=500, show_metric=True, run_id=MODEL_NAME)

# tensorboars --logdir=foo:c:/..../

model.save(MODEL_NAME)


import requests
import random

list_url = ["https://www.google.com/", "https://www.facebook.com/", "https://www.twitter.com/",
            "https://www.amazon.com/", "https://www.apple.com/"]

link = random.choice(list_url)

res = requests.get(link)
print(f'Status code is {res.status_code} from {link} with length of {len(res.text)} symbols')

# Task2

weather_link = "https://geocoding-api.open-meteo.com/v1/search?name="

city = input('Enter your city: ')

res2 = requests.get(f'{weather_link}{city}&count=1')

if len(res2.json()) - 1:
    data = res2.json()
    data2 = requests.get(f'https://api.open-meteo.com/v1/forecast?latitude='
                         f'{data["results"][0]["latitude"]}&longitude={data["results"][0]["longitude"]}'
                         f'&current_weather=true').json()
    print(f"Current temperature in {city} is {data2['current_weather']['temperature']}")
else:
    print(f'There no such city as {city}')


from scipy.stats import kurtosis, entropy

import mne
from mne.utils import _check_preload
import numpy as np
import matplotlib.pyplot as pl

import logging
logger = logging.getLogger(__name__)

def mark_tms_bad(raw, events, tmin=-0.002, tmax=0.01):
    ""
    #eog_events = mne.preprocessing.find_eog_events(raw)
    onsets = events[:, 0] / raw.info['sfreq'] + tmin
    durations = [tmax] * len(events)
    descriptions = ['bad artifact'] * len(events)
    tms_annot = mne.Annotations(onsets, durations, descriptions,
                                orig_time=raw.info['meas_date'])
    raw.set_annotations(tms_annot)

    return raw

def interpolate_tms_pulse(inst, tmin=-0.002, tmax=0.01, order=3, points=1):
    """[summary]

    Parameters
    ----------
    inst : [type]
        [description]
    tmin : float, optional
        [description], by default -0.002
    tmax : float, optional
        [description], by default 0.01
    order : int, optional
        [description], by default 3
    points : int, optional
        [description], by default 1

    Returns
    -------
    [type]
        [description]
    """

    _check_preload(inst, 'interpolate')

    t = inst.times
    mask_artifact = np.logical_and(t > tmin, t < tmax)

    t_interp_min = tmin - points / inst.info['sfreq']
    t_interp_max = tmax + points / inst.info['sfreq']

    mask_interp = np.logical_and(t >= t_interp_min,
                                 t <= t_interp_max)

    mask_interp = np.logical_and(np.logical_not(mask_artifact),
                                 mask_interp)

    epoch_data = inst.get_data()
    inst._data = epoch_data

    for epoch in epoch_data:
        for ch, data in enumerate(epoch):
            coeffs = np.polyfit(t[mask_interp], data[mask_interp], deg=order)
            poly = np.poly1d(coeffs)
            x_fit = poly(t[mask_artifact])

            epoch[ch, mask_artifact] = x_fit

    return inst

def read_bids_events(fname):

    events_file = np.recfromcsv(fname, delimiter='\t')

    events_name = np.unique(events_file['trial_type'])
    events_id = {k: j for j, k in enumerate(events_name)}

    events = list()
    for field in ['sample', 'duration', 'trial_type']:
        if field != 'trial_type':
            events.append(events_file[field])
        else:
            arr = [events_id[k] for k in events_file[field]]
            events.append(np.array(arr))

    events = np.int_(np.vstack(events).T)

    return events, events_id

def reject_electrodes(raw, method='kurtosis', threshold=5):
    """[summary]

    TODO: Insert the possibility to avoid normalization.

    Parameters
    ----------
    raw : [type]
        [description]
    method : str, optional
        [description], by default 'kurtosis'
    threshold : int, optional
        [description], by default 5

    Returns
    -------
    [type]
        [description]
    """

    _check_preload(raw, 'reject_electrodes')

    if method == 'kurtosis':
        metric = kurtosis(raw._data, axis=1)

    elif method == 'probability':
        metric = entropy(raw._data, axis=1)

    tmp_metric = np.sort(metric)
    idx = int(np.round(metric.shape[0] * .1))
    tmp_metric = tmp_metric[idx:-idx]

    metric = (metric - np.mean(tmp_metric)) / np.std(tmp_metric)

    ch_mask = np.abs(metric) > threshold

    # TODO: Check for multiple times that this function is called
    raw.info['bads'] = list(np.array(raw.info['ch_names'])[ch_mask])

    logger.info('Channels removed: '+' '.join(raw.info['bads']))

    return raw

def reject_epochs(epochs, method='jointprob', threshold=5):
    return

def reject_jointprob(epochs, selected=None,
                     local_threshold=5,
                     global_threshold=5):
    """[summary]

    Parameters
    ----------
    epochs : [type]
        [description]
    selected : [type], optional
        [description], by default None
    local_threshold : int, optional
        [description], by default 5
    global_threshold : int, optional
        [description], by default 5

    Returns
    -------
    [type]
        [description]
    """

    _check_preload(epochs, 'reject_jointprob')
    data = epochs._data
    nepochs, nchan, ntimes = data.shape

    if selected is None:
        # Channels from bads must be deleted
        selected = np.arange(nchan)

    channel_data = np.moveaxis(data, 0, -1)

    joint_prob_e, rejected_e = jointprob(channel_data, local_threshold, jp=None, normalize=True)
    _, rejected_tmp = jointprob(data[:, selected], local_threshold, jp=joint_prob_e[selected], normalize=True)

    rejected_e = np.zeros((nchan, nepochs))
    rejected_e[selected, :] = rejected_tmp

    epoch_data = data.reshape(nepochs, -1)
    joint_prob, rejected = jointprob(epoch_data, global_threshold, jp=None, normalize=True)

    rejected = np.logical_or(rejected, np.sum(rejected_e, axis=1) != 0)

    rejected = np.logical_or(rejected, np.sum(rejected_e[selected], axis=1) != 0)

    return rejected

def jointprob(data, threshold=0, jp=None, normalize=True, nbins=1000):

    nchan, ntimes, nevents = data.shape
    if jp is None:
        jp = np.zeros((nchan, nevents))

        for ch in range(nchan):
            data_prob, pdf = real_probability(data[ch], nbins)

            for e in range(nevents):

                data_ = data_prob[e*ntimes:(e+1)*ntimes]
                jp[ch, e] = -1 * np.sum(np.log(data_))

        if normalize:
            jp = (jp - np.mean(jp)) / np.std(jp)

    rejected = np.abs(jp) > threshold

    return jp, rejected

def real_probability(data, nbins):

    if nbins > 0:
        size = data.shape[0] * data.shape[1]
        histogram = np.zeros((nbins))
        max_ = np.max(data)
        min_ = np.min(data)
        data = np.floor((data - min_) / (max_ - min_) * (nbins - 1))
        data = np.int_(data.flatten())

        for i in range(size):
            histogram[data[i]] += 1

        data_prob = histogram[data] / size
        histogram /= size
        pl.plot(histogram)
    else:
        data = (data - data.mean()) / data.std()
        data_prob = np.exp(-.5 * data * data) / (2 * np.pi)
        data_prob /= np.sum(data_prob)
        histogram = data_prob

    return data_prob, histogram

def remove_data(epoch, tmin, tmax, replacement='average'):
    """Removes data between defined timepoints and replaces data with
    different approaches:

    Parameters
    ----------
    epoch : [type]
        [description]
    tmin : [type]
        [description]
    tmax : [type]
        [description]
    replacement : str, optional
        [description], by default 'average'
    """
    return


from keras.models import Model
from keras.regularizers import *
from keras.layers import *
from settings import *

from EqDense import EqDense
from ModulatedConv2D import ModulatedConv2D
from NoiseLayer import NoiseLayer
from BiasLayer import BiasLayer

from settings import *

def style_block(w, x, noise, filters):
	style = EqDense(x.shape[-1], bias_init_value=1)(w)
	x = ModulatedConv2D(filters, (KERNEL_SIZE, KERNEL_SIZE), use_demod=True)([x, style])
	cropped_noise = Cropping2D((noise.shape[1] - x.shape[1]) // 2)(noise)
	x = NoiseLayer()([x, cropped_noise])
	x = BiasLayer()(x)
	x = LeakyReLU(alpha=LEAKY_RELU_ALPHA)(x)
	return x

def to_rgb(w, x):
	style = EqDense(x.shape[-1], bias_init_value=1)(w)
	x = ModulatedConv2D(3, (KERNEL_SIZE, KERNEL_SIZE), use_demod=False)([x, style])
	x = BiasLayer()(x)
	return x

def const_input(x):
	x = Lambda(lambda x: tf.ones_like(x))(x)
	x = EqDense(IMAGE_MIN_SIZE * IMAGE_MIN_SIZE * FILTERS_MAX, use_bias=False)(x)
	x = Reshape((IMAGE_MIN_SIZE, IMAGE_MIN_SIZE, FILTERS_MAX))(x)
	return x

def get_filters(stage):
	return max(FILTERS_MIN, FILTERS_MAX // (2**stage))

def get_generator_model():
	input = Input(shape=(1,))
	w_inputs = [Input(shape=(LATENT_DIM,)) for _ in range(BLOCKS_COUNT)]
	noise_inputs = [Input(shape=(IMAGE_SIZE, IMAGE_SIZE, 1)) for _ in range(BLOCKS_COUNT * 2 + 1)]

	constant = const_input(input)

	x = style_block(w_inputs[0], constant, noise_inputs[0], FILTERS_MAX)
	last_skip_connection = to_rgb(w_inputs[0], x)

	for i in range(BLOCKS_COUNT):
		filters = get_filters(i)

		x = UpSampling2D(interpolation='bilinear')(x)
		x = style_block(w_inputs[i], x, noise_inputs[i * 2 + 1], filters)
		x = style_block(w_inputs[i], x, noise_inputs[i * 2 + 2], filters)

		skip_connection = to_rgb(w_inputs[i], x)
		last_skip_connection = UpSampling2D(interpolation='bilinear')(last_skip_connection)
		last_skip_connection = Add()([last_skip_connection, skip_connection])

	x = Activation('tanh')(last_skip_connection)
	return Model([input] + w_inputs + noise_inputs, x)


import pytest

from crossandra.common import *
from crossandra.rule import *

# ESC = ESCAPED
# UC = UPPERCASE
# LC = LOWERCASE
# POS = POSITIVE
# NEG = NEGATIVE
# USCORE = UNDERSCORE

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("'test'", ("'test'", 6)),  # CLASSIC
        ("'''", ("''", 2)),  # STRING CONTAINING QUOTE
        ("test", NOT_APPLIED),  # NO QUOTE
        ("test'", NOT_APPLIED),  # NO STARTING QUOTE
        ("'test", NOT_APPLIED),  # NO ENDING QUOTE
        ("\\'test'", NOT_APPLIED),  # ESC STARTING QUOTE
        ("'test\\'", NOT_APPLIED),  # ESC ENDING QUOTE
        ("''", ("''", 2)),  # EMPTY
    ],
)
def test_SINGLE_QUOTED_STRING(string, result):
    assert SINGLE_QUOTED_STRING.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ('"test"', ('"test"', 6)),  # CLASSIC
        ('"""', ('""', 2)),  # STRING CONTAINING QUOTE
        ("test", NOT_APPLIED),  # NO QUOTE
        ('test"', NOT_APPLIED),  # NO STARTING QUOTE
        ('"test', NOT_APPLIED),  # NO ENDING QUOTE
        ('\\"test"', NOT_APPLIED),  # ESC STARTING QUOTE
        ('"test\\"', NOT_APPLIED),  # ESC ENDING QUOTE
        ('""', ('""', 2)),  # EMPTY
    ],
)
def test_DOUBLE_QUOTED_STRING(string, result):
    assert DOUBLE_QUOTED_STRING.apply(string) == result

# test_STRING <=> test_SINGLE_QUOTED_STRING and test_DOUBLE_QUOTED_STRING

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("'t'", ("'t'", 3)),  # CLASSIC
        ("'''", NOT_APPLIED),  # SINGLE QUOTE CHAR
        ("t", NOT_APPLIED),  # NO QUOTE
        ("t'", NOT_APPLIED),  # NO STARTING QUOTE
        ("'t", NOT_APPLIED),  # NO ENDING QUOTE
        ("\\'t'", NOT_APPLIED),  # ESC STARTING QUOTE
        ("'t\\'", NOT_APPLIED),  # ESC ENDING QUOTE
        ("''", NOT_APPLIED),  # EMPTY
    ],
)
def test_CHAR(string, result):
    assert CHAR.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("A", ("A", 1)),  # UC LETTER
        ("a", ("a", 1)),  # LC LETTER
        ("!", NOT_APPLIED),  # ASCII CHAR BETWEEN UC AND LC
        ("@", NOT_APPLIED),  # ASCII CHAR BEFORE UC
        ("|", NOT_APPLIED),  # ASCII CHAR AFTER LC
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_LETTER(string, result):
    assert LETTER.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("word", ("word", 4)),  # CLASSIC
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_WORD(string, result):
    assert WORD.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("0", (0, 1)),  # CLASSIC
        ("/", NOT_APPLIED),  # CHAR BEFORE DIGITS IN ASCII TABLE
        (":", NOT_APPLIED),  # CHAR AFTER DIGITS IN ASCII TABLE
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_DIGIT(string, result):
    assert DIGIT.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("69", (69, 2)),  # CLASSIC
        ("069", (69, 3)),  # LEADING ZERO
        ("1_000_000", (1000000, 9)),  # USCORE SEP
        ("1__0", (10, 4)),  # TWO USCORES AS SEP
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_INT(string, result):
    assert INT.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("+69", (69, 3)),  # POS INT
        ("-69", (-69, 3)),  # NEG INT
        ("69", NOT_APPLIED),  # NOT SIGNED
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_SIGNED_INT(string, result):
    assert SIGNED_INT.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("3.14", (3.14, 4)),  # CLASSIC
        ("3.0", (3.0, 3)),  # POST-COMMA TRAILING ZERO
        ("69.42", (69.42, 5)),  # N-DIGIT INT BASE
        ("0.92", (0.92, 4)),  # ZERO-DIGIT
        (".92", (0.92, 3)),  # IMPLICIT ZERO-DIGIT
        ("3.", (3.0, 2)),  # IMPLICIT POST-COMMA ZERO
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_DECIMAL(string, result):
    assert DECIMAL.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("3", (3, 1)),  # CLASSIC: DIGIT
        ("D", (13, 1)),  # CLASSIC: UC LETTER
        ("a", (10, 1)),  # CLASSIC: LC LETTER
        ("g", NOT_APPLIED),  # INVALID HEX VALUE
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_HEXDIGIT(string, result):
    assert HEXDIGIT.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("W", ("W", 1)),  # ONE LETTER
        ("_", ("_", 1)),  # ONE USCORE
        ("word", ("word", 4)),  # ONE WORD
        ("two_words", ("two_words", 9)),  # TWO WORDS, USCORE SEP
        ("_word", ("_word", 5)),  # 'PRIVATE' ONE WORD
        ("_two_words", ("_two_words", 10)),  # 'PRIVATE' TWO WORDS, USCORE SEP
        ("0word", NOT_APPLIED),  # LEADING DIGIT
        ("word0", ("word0", 5)),  # TRAILING DIGIT
        ("_0word", ("_0word", 6)),  # 'PRIVATE' LEADING DIGIT
        ("_word0", ("_word0", 6)),  # 'PRIVATE' TRAILING DIGIT
        ("0", NOT_APPLIED),  # SINGLE DIGIT
        ("69420", NOT_APPLIED),  # N-DIGITS
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_C_NAME(string, result):
    assert C_NAME.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("\n", ("\n", 1)),  # LF NEWLINE
        ("\r\n", ("\r\n", 2)),  # CRLF NEWLINE
        ("\r", NOT_APPLIED),  # CR NEWLINE
        ("\\n", NOT_APPLIED),  # ESC LF NEWLINE
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_NEWLINE(string, result):
    assert NEWLINE.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("1e3", (1_000.0, 3)),  # INT, LC E, INT
        ("1e+3", (1_000.0, 4)),  # INT, E, POS INT
        ("1e-3", (0.001, 4)),  # INT, E, NEG INT
        ("1E3", (1_000.0, 3)),  # INT, UC E, INT
        ("1.0e3", (1_000.0, 5)),  # DECIMAL, E, INT
        ("1.0e+3", (1_000.0, 6)),  # DECIMAL, E, POS INT
        ("1.0e-3", (0.001, 6)),  # DECIMAL, E, NEG INT
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_FLOAT(string, result):
    assert FLOAT.apply(string) == result

@pytest.mark.parametrize(
    ["string", "result"],
    [
        ("+1e3", (1_000.0, 4)),  # POS INT, E, INT
        ("-1e3", (-1_000.0, 4)),  # NEG INT, E, INT
        ("+1e+3", (1_000.0, 5)),  # POS INT, E, POS INT
        ("+1e-3", (0.001, 5)),  # POS INT, E, NEG INT
        ("+1.0e3", (1_000.0, 6)),  # POS DECIMAL, E, INT
        ("-1.0e3", (-1_000.0, 6)),  # NEG DECIMAL, E, INT
        ("+1.0e+3", (1_000.0, 7)),  # POS DECIMAL, E, POS INT
        ("+1.0e-3", (0.001, 7)),  # POS DECIMAL, E, NEG INT
        ("", NOT_APPLIED),  # EMPTY
    ],
)
def test_SIGNED_FLOAT(string, result):
    assert SIGNED_FLOAT.apply(string) == result

# test_NUMBER <=> test_INT and test_FLOAT

# test_SIGNED_NUMBER <=> test_SIGNED_INT and test_SIGNED_FLOAT


with open("pe_6_2_kaartnummers.txt") as f:
    lines = []

    regelCount = 0
    hoogsteKaartnummer = 0
    regelHoogsteKaartnummer = 0

    for line in f:
        regelCount += 1
        kaartnummer = int(line.split(",")[0])
        if kaartnummer > hoogsteKaartnummer:
            hoogsteKaartnummer = kaartnummer
            regelHoogsteKaartnummer = regelCount

    print(f"Deze file telt {regelCount} regels")
    print(f"Het grootste kaartnummer is: {hoogsteKaartnummer} en dat staat op regel {regelHoogsteKaartnummer}")


import requests
import json

def get_all_info(company_name):
    url = "https://librebor.me/borme/api/v1/empresa/xxx-xxx-xxx/".replace("xxx-xxx-xxx", company_name)
    response = requests.get(url)
    if response.status_code == 200:
        converted = json.loads(response.text)
        return converted

def search_company(name):
    url = "https://libreborme.net/borme/api/v1/empresa/search/?q=xxx&page=1".replace("xxx", name)
    response = requests.get(url)
    if response.status_code == 200:
        converted = json.loads(response.text)
        return converted

print("Enter name to search for:")
name = input()
companies = search_company(name)
objects = companies["objects"]

if len(objects) == 0:
    print("No results found.")
else:
    company = objects[0]

    company_name = company["slug"]
    company_info = get_all_info(company_name)

    employees = company_info["cargos_actuales_p"]
    print("Number of employees is", len(employees))


#!/usr/bin/env python
"""
Countsubsets.

######################################################################
# @author      : Linus Fernandes (linusfernandes at gmail dot com)
# @file        : countsubsets
# @created     : Friday Mar 17, 2023 21:29:54 IST
# @description :
# -*- coding: utf-8 -*-'
######################################################################
"""
import bitset

def count_subsets(dataset, val):
    """Count subsets."""
    set_size = len(dataset)
    count = 0
    for element in range(2**set_size):
        total = 0
        for k in range(set_size):
            if bitset.isbitset(k, element):
                total = total + dataset[k]
        if total >= val:
            count = count + 1
    return count

A = [1, 2, 3]
print(count_subsets(A, 4))
A = [1, 2, 3, 4]
print(count_subsets(A, 4))


#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
@author RenMeng
@version 1.0
@since 2021-05-24
'''

from titles.tree import TreeNode
class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if root is None:
            return

        node = root
        stacks = []
        # 先序遍历
        while node or len(stacks) > 0:
            stacks.append(node)  # 先根
            while node.left is not None:
                stacks.append(node.left)  # 先根
                node = node.left
            parent = stacks.pop(-1)
            while parent.right is None and len(stacks) > 0:
                parent = stacks.pop(-1)
            node.left = parent.right
            node = parent.right

        node = root
        while node.left is not None or node.right is not None:
            if node.left is not None:
                node.right = node.left
                next_node = node.left
                node.left = None
                node = next_node


def simple_partition(df, train_proportion):
    '''
        Returns train and test pandas.DataFrames
    '''
    size = int(train_proportion * len(df))

    train_indexes = df.sample(size).index
    train_df = df.loc[train_indexes].copy()
    test_df = df[~df.index.isin(train_indexes)].copy()

    return train_df, test_df

if __name__ == "__main__":
    import pandas as pd

    df = pd.read_csv("../../../data/train_2016.csv")

    train, test = simple_partition(df, 0.7)

    print(len(df))
    print(len(train), len(train) / len(df))
    print(len(test), len(test) / len(df))


import tkinter as tk
from screens.widgets import ControllPanel, AnotherPanel
from multiprocessing import Pool
from collector.collector import NewsCollector
from collector.processing import DataProcessor
from api.news_service import NewsService
from utils.docker_utils import SplashContainer
import subprocess
import pathlib
import os
from datetime import datetime
from dateutil import parser
import time
import traceback
import sys
import pandas as pd
import requests
import numpy as np

SRC = pathlib.Path(__file__).parent
sys.path.append(SRC)

class MenuBar(tk.Menu):

    def __init__(self, parent):

        tk.Menu.__init__(self, parent)

        menu1 = tk.Menu(self, tearoff=0)
        menu1.add_command(label = 'Control Panel', command = lambda: parent.show_controll_panel())
        menu1.add_command(label = 'Another Panel', command = lambda: parent.show_another_panel())
        menu1.add_command(label = 'Option 3', command = lambda: print("Menu 1 Option 3 clicked"))
        menu1.add_separator()
        menu1.add_command(label = 'Option 4', command = lambda: print("Menu 1 Option 4 clicked"))

        self.add_cascade(label = "Menu 1", menu = menu1)

        menu2 = tk.Menu(self, tearoff=0)
        menu2.add_command(label = 'Option 1', command = lambda: print("Menu 2 Option 1 clicked"))
        menu2.add_command(label = 'Option 2', command = lambda: print("Menu 2 Option 2 clicked"))
        menu2.add_command(label = 'Option 3', command = lambda: print("Menu 2 Option 3 clicked"))
        menu2.add_separator()
        menu2.add_command(label = 'Option 4', command = lambda: print("Menu 2 Option 4 clicked"))

        self.add_cascade(label = "Menu 2", menu = menu2)

class MyApp(tk.Tk):
    CWD = pathlib.Path(__file__).parent.absolute()
    TRENDING_KEYWORDS_FILE = os.path.join(CWD,'collector','output','trending.txt')

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        self.main_frame = tk.Frame(self, bg = '#272727', height = 1000, width = 2000)
        self.main_frame.pack_propagate(0)
        self.main_frame.pack(fill='both', expand = 'true')
        self.main_frame.grid_columnconfigure(0, weight = 1)
        self.main_frame.grid_rowconfigure(0, weight = 1)
        self.now = datetime.now()

        menubar = MenuBar(self)
        tk.Tk.config(self, menu = menubar)

        #init news collector
        self.news_collector = NewsCollector()

        #init splash container
        self.splash_container = SplashContainer()

        self.splash_logs = list()

        #Init data processor
        self.data_processor = DataProcessor()

        #Init api
        self.api = NewsService()

        self.show_controll_panel()

        self.scraper_running = None
        self.current_keyword_index = None
        self.is_splash_running = None

        self.load_trending_keywords()

        self.spider_names = ['cnn_spider', 'market_watch_spider', 'reuters_spider']
        self.tasks_done = None

        self.scraping_hours = self._get_scraping_hours()
        self.is_scrapping = False

        self.main_frame.after(1000, self._loop)

    def load_trending_keywords(self):
        try:
            self._add_log_to_controll_panel("Updating trending logs")
            self.trending_keywords = self.data_processor.get_trending_keyword()
            self.control_panel.update_trending_keywords(self.trending_keywords)

        except FileNotFoundError as e:
            print("Trending keyword file is not found")
            traceback.print_exc()

    def show_controll_panel(self):
        print('showing control panel')
        self.control_panel = ControllPanel(self.main_frame, self)
        self._show_widget(self.control_panel)

        #Check health
        try:
            self.api.check_health()
            self._add_log_to_controll_panel("News Service API is healhty")
        except Exception as e:
            self._add_log_to_controll_panel("[ERROR] News Service API is not healthy")

    def show_another_panel(self):
        print("showing another panel")
        w = AnotherPanel(self.main_frame)
        self._show_widget(w)

    def _show_widget(self, widget):
        widget.grid(row = 0, column = 0, sticky = 'nsew')
        widget.tkraise()

    def _add_log_to_controll_panel(self, text):
        self.control_panel.add_log(text)

    def task_done(self, result):
        self.tasks_done.append(result)
        self._add_log_to_controll_panel(f'[ DONE ] {str(result)}')

        if self.check_all_tasks_done():
            self._add_log_to_controll_panel('All tasks done')

    def check_all_tasks_done(self):
        # Simple logic, if tasks done list has equal number of elements with spider_names then it's true
        if len(self.tasks_done) == len(self.spider_names):
            return True
        else:
            return False

    def stop_scraping(self):
        self.is_scrapping = False

    def _start_scraper_async(self, keyword):

        #CAUTION: self.tasks_done must be init to be a list(), not gonna handle error here

        #Clear tasks done

        self.tasks_done.clear()

        data = self.news_collector.get_spider_data(keyword, 'business', False, 'today', 1)
        pool = Pool()

        # init pool
        for spider_name in self.spider_names:
            self._add_log_to_controll_panel(f'[ CNN Spider ],args: {str(data)}')
            pool.apply_async(self.news_collector.start_search_process, (data, spider_name), callback=self.task_done)

        pool.close()
        print("end scraper")

    def _get_splash_container(self):
        return self.splash_container

    def _get_collector(self):
        return self.news_collector

    def start_splash(self):
        if self.splash_container.is_running() == False:
            self.control_panel.add_log("Splash container started by user")
            self.splash_container.start()
        else:
            self.control_panel.add_log("Splash container started by user but it's already running")

    def stop_splash(self):
        if self.splash_container.is_running() == True:
            print("Stopping splash ...")
            self.control_panel.add_log("Splash container stopped by user")
            # Using subprocess because Docker SDK has the following issue:
            # stop command sent but docker container not stopped,
            # it doesn't show up in 'docker ps' but you can
            # 'docker logs -f splash' and see it's running
            # self.splash_container.stop()
            # this is a temporary solution
            subprocess.run('docker rm -f splash'.split(" "))

    def _loop(self):
        is_running = self.splash_container.is_running()

        if is_running != self.is_splash_running:
            self.is_splash_running = is_running
            self.control_panel.toggle_docker_status(self.is_splash_running)

        #Prevent errors by skipping loop if docker splash container is not running
        if self.is_splash_running == False:
            self._add_log_to_controll_panel("Docker is not running, all scraping process will be hold")
            self.main_frame.after(1000, self._loop)
            return

        # scraping hours:
        # 6 A.M
        # 8 A.M
        # 10 A.M
        # 12 A.M
        # 2 P.M
        # 4 P.M
        # 6 P.M
        # 8 P.M
        # 10 P.M

        # now = datetime.now()

        # current_hour = now.hour

        # if current_hour in self.scraping_hours:
        #     self.is_scrapping = True

        if self.is_scrapping == True:
            #Initiate scraping process if is_scraping = True
            tick = time.time()
            if self.tasks_done == None:
                print("Starting from index 0")
                self.current_keyword_index = 0
                keywords = self.trending_keywords.most_common()
                keyword, rank = keywords[self.current_keyword_index]
                self.tasks_done = list()
                self._start_scraper_async(keyword)
                self.control_panel.update_scraping_keywords_index(self.current_keyword_index)
                self._add_log_to_controll_panel(f"Scraping with keyword: {keyword}")
            else:
                if self.check_all_tasks_done() == True:
                    if self.current_keyword_index < len(self.trending_keywords) - 1:
                        self.current_keyword_index += 1
                        keywords = self.trending_keywords.most_common()
                        keyword, rank = keywords[self.current_keyword_index]
                        self._start_scraper_async(keyword)
                        self.control_panel.update_scraping_keywords_index(self.current_keyword_index)
                        self._add_log_to_controll_panel(f"Scraping with keyword: {keyword}")
                    else:
                        self.tasks_done = None
                        self._add_log_to_controll_panel("Completely scraped all trending keywords")
                        tock = time.time() - tick
                        self._add_log_to_controll_panel(f"Elapsed time {tock} seconds")
                        self.is_scrapping = False

        self.main_frame.after(1000, self._loop)

    def start_scraping_trending_keywords(self):
        self.is_scrapping = True

    def _get_scraping_hours(self):
        return [7,10,13,16,18,21]

    def fetch_headlines(self):
        now = datetime.now()
        self._add_log_to_controll_panel(f"Fetching headlines for today {now}")
        try:
            self.news_collector._get_newsapi_headlines(True)
            self.news_collector.start_get_cnn_headlines(detach = False)
        except Exception as e:
            self._add_log_to_controll_panel(f"Oops! error occured, check below error")
            self._add_log_to_controll_panel(str(e))
            traceback.print_exc()

    def generate_trending_keywords(self):
        self._add_log_to_controll_panel("Generating trending keywords")
        self.data_processor.generate_trending_keywords()
        self._add_log_to_controll_panel("Generated trending keywords. Updated UI")
        self.trending_keywords = self.data_processor.get_trending_keyword()
        self.control_panel.update_trending_keywords(self.trending_keywords)

    def process_today_data(self):
        try:
            today_headlines_file = self.data_processor.get_today_headlines_file()
            self._add_log_to_controll_panel(f'Processing today data from {today_headlines_file} ...')
            self.data_processor.process_data(today_headlines_file)
            self._add_log_to_controll_panel(f"Processed data and saved to {today_headlines_file}")
            self.news_collector.reload_collected_data()
            self._add_log_to_controll_panel(f"Reload collected_data object")
        except FileNotFoundError as e:
            print(f"{today_headlines_file} is not found. Make sure to fetch the data first")
            self._add_log_to_controll_panel(f"Error! Couldn't find {today_headlines_file} to process")
            print(str(e))

    def save_headlines_to_db(self):
        df = self.news_collector.get_fetched_headlines()
        print(f'Saving {self.news_collector.HEADLINE_CSV_PATH} to database')

        for index, row in df.iterrows():
            print(row['title'])

            row['authors'] = str(row['authors'])
            row['keywords'] = str(row['keywords'])

            if row['authors'] == 'nan':
                row['authors'] = ''

            if row['keywords'] == 'nan':
                row['keywords'] = ''

            authors = row['authors'].split(",")
            for author in authors:
                author = author.strip()

            keywords = row['keywords'].split(",")
            for keyword in keywords:
                keyword = keyword.strip()

            try:
                response = self.api.save_news(
                    search_term = str(row['search_term']),
                    title= str(row['title']),
                    text = str(row['text']),
                    authors = authors,
                    source = str(row['source']),
                    url = str(row['url']),
                    image_url = str(row['image_url']),
                    date = parser.isoparse(row['date']),
                    summary = str(row['summary']),
                    keywords = keywords,
                    sentiment = str(row['sentiment'])
                )
                print(response.content)
            except requests.exceptions.HTTPError as e:
                print("###")
                print("Error while saving to db")
                print("data")
                print(row)
                print("###")
                print(e)

if __name__ == '__main__':
    root = MyApp()
    root.title('My app')
    root.mainloop()


from imutils.video import FPS
import numpy as np
import imutils
import dlib
import cv2
import argparse
import time

parser = argparse.ArgumentParser()
parser.add_argument("-s", "--scale", required=False, help="video frame scale factor",
                    default=2.25, type=float)
parser.add_argument("-m", "--mode", required=False, default='test',
                    type=str)
args = parser.parse_args()

resize_factor = args.scale
mode = args.mode

prototxt = "model/MobileNetSSD_deploy.prototxt"
caffeModel = "model/MobileNetSSD_deploy.caffemodel"
video = "testVideo/IMG_0330.MOV"

# initialize the list of class labels MobileNet SSD was trained to
# detect
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
           "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
           "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
           "sofa", "train", "tvmonitor"]

# load mobilenetSSD Caffe model from disk
print("loading model...")
net = cv2.dnn.readNetFromCaffe(prototxt, caffeModel)

# initialize the video stream
if mode == 'live':
    print("starting live webcam video stream...")
    vs = cv2.VideoCapture(0)
    time.sleep(1)
    grabbed, frame = vs.read()

    if frame is None:
        print("failed to start webcam video stream using testVideo instead")
        vs = cv2.VideoCapture(video)

else:
    print("starting test video stream...")
    vs = cv2.VideoCapture(video)

videoFPS = vs.get(cv2.CAP_PROP_FPS)
print("Video stream FPS: {:.2f}".format(videoFPS))

# calculating resize width
grabbed, frame = vs.read()
original_dim = frame.shape

print("Video Stream Original Dimensions: {}".format(original_dim))

resize = int(original_dim[0]/resize_factor)

# initialize the list of object trackers and class labels
labels = []

# frame count
n = 0

# start the timer
fps = FPS().start()

while True:
    # grab the next frame from the video file
    (grabbed, frame) = vs.read()

    if frame is None:
        break

    image_to_display = imutils.resize(frame, width=int(frame.shape[0]/1))
    # resize frame to scale factor
    frame = imutils.resize(frame, width=resize)
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # if frame count is 0 or is the 20th frame perform object detection
    if n == 0 or n % 20 == 0:

        # clear current trackers
        trackers = []

        # get height and width of frame to be used as arguments for pre-processing function
        (h, w) = frame.shape[:2]

        # image pre processing before passing to DNN model
        blob = cv2.dnn.blobFromImage(frame, 0.007843, (w, h), 127.5)

        # pass image to network input
        net.setInput(blob)

        # calculate inference time and run inference
        start = time.time()
        detections = net.forward()
        end = time.time()
        runtime = end - start
        print("detection runtime: {:.2f}".format(runtime))
        print("detection array type : {} & shape : {}".format(type(detections),detections.shape))

        # for each detection of class person with confidence > 0.5 add to object tracked list
        # and draw bounding box
        for i in np.arange(0, detections.shape[2]):

            confidence = detections[0, 0, i, 2]

            # get the index of the label of the detected object
            idx = int(detections[0, 0, i, 1])
            label = CLASSES[idx]

            if CLASSES[idx] is not "person":
                continue

            if confidence > 0.5:

                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])  # rescale detection box size to frame size
                (startX, startY, endX, endY) = box.astype("int")

                t = dlib.correlation_tracker()
                rect = dlib.rectangle(startX, startY, endX, endY)
                t.start_track(rgb, rect)

                labels.append(label)
                trackers.append(t)

                cv2.rectangle(image_to_display, (int(startX * resize_factor), int(startY * resize_factor)),
                              (int(endX * resize_factor), int(endY * resize_factor)), (0, 255, 0), 2)
                cv2.putText(image_to_display, label, (int(startX * resize_factor), int((startY * resize_factor) - 15)),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

    # otherwise detection already performed so track
    # objects in trackers list
    else:
        # loop over each of the trackers
        for (t, l) in zip(trackers, labels):
            # update the tracker and grab the position of the tracked
            # object
            t.update(rgb)
            pos = t.get_position()

            # unpack the position object
            startX = int(pos.left())
            startY = int(pos.top())
            endX = int(pos.right())
            endY = int(pos.bottom())

            cv2.rectangle(image_to_display, (int(startX * resize_factor), int(startY * resize_factor)),
                          (int(endX * resize_factor), int(endY * resize_factor)), (0, 255, 0), 2)
            cv2.putText(image_to_display, label, (int(startX * resize_factor), int((startY * resize_factor) - 15)),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

    # increment frame number
    n += 1

    # image_to_display = imutils.resize(image_to_display, width=720)

    # show the output frame
    cv2.imshow("Frame", image_to_display)
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

    # update the FPS counter
    fps.update()

# stop the timer and display FPS information
fps.stop()
print("elapsed time: {:.2f}".format(fps.elapsed()))
print("approx. FPS: {:.2f}".format(fps.fps()))

performanceDrop = ((videoFPS - fps.fps())/videoFPS) * 100

print("FPS performance drop: {:.2f} %".format(performanceDrop))

# do a bit of cleanup
cv2.destroyAllWindows()
vs.release()


import datetime
import re

import pandas as pd

import python.imports.utils as utils
from python.imports.init_params import *

_datetime_fmt = '%Y-%m-%d-%H-%M-%S'
_datetime_fmt1 = '%Y-%m-%dT%H:%M:%S'

def instrument_wind_code(code, instrument_id_list):
    for instrument_id in instrument_id_list:
        if instrument_id.find(code.upper() + '.') == 0:
            return instrument_id
    if re.match(r'[A-Z][A-Z]?\d+', code):
        temp_code = re.sub(r'[A-Z][A-Z]?\d', re.search(r'[A-Z][A-Z]?', code).group(), code, 1)
        for instrument_id in instrument_id_list:
            if instrument_id.find(temp_code + '.') == 0:
                return instrument_id
    return code

def get_all_instrument_dic(ip, headers):
    instrument_dic = {}
    try:
        instrument_list = utils.call('mktInstrumentsListPaged', {}, 'market-data-service', ip,
                                     headers)['page']
        for item in instrument_list:
            instrument_dic[item['instrumentId']] = item
        return instrument_dic
    except Exception as e:
        print("failed update market data for: " + ip + ",Exception:" + str(e))

def import_exchange_trades(ip, headers):
    # 获取bct所有标的物
    instruments_dic = get_all_instrument_dic(ip, headers)
    xinhu_exchange_trades = pd.read_csv(import_exchange_trade_excel_file, encoding="gbk").to_dict(orient='records')
    records = []
    for trade in xinhu_exchange_trades:
        underlyer = instrument_wind_code(trade['code'], instruments_dic.keys())
        if trade['code'].find('.') < 0 and underlyer == trade['code']:
            print('BCT不存在合约代码 {underlyer} '.format(underlyer=str(underlyer)))
            continue
        if not instruments_dic.get(underlyer):
            print('BCT不存在合约代码 {underlyer} '.format(underlyer=str(underlyer)))
            continue
        multiplier = instruments_dic.get(underlyer)['multiplier'] if instruments_dic.get(underlyer)[
            'multiplier'] else 1
        direction = "BUYER" if trade['direction'] == 1 else "SELLER"
        open_close = "OPEN" if trade['direction'] == 1 else "CLOSE"  # 开平
        deal_price = trade['price']  # 交易价格
        deal_amount = trade['amount']  # 交易数量
        # 2020 - 06 - 18 - 20 - 59 - 00
        day_str = trade['dayStr']
        deal_time = datetime.datetime.strptime(day_str, _datetime_fmt).strftime(_datetime_fmt1)
        trade_id = str(trade['order_sys_id']) + "-" + str(trade['trade_id'])

        trade_account = '新湖场内交易账号'  # 交易账户
        exchange_trade = {
            "bookId": book_name,
            "instrumentId": underlyer,
            "direction": direction,
            "openClose": open_close,
            "dealPrice": deal_price,
            "dealAmount": deal_amount,
            "dealTime": deal_time,
            "tradeId": trade_id,
            "tradeAccount": trade_account,
            "multiplier": multiplier
        }
        records.append(exchange_trade)

    for record in records:
        try:
            utils.call('exeTradeRecordSave', record, 'exchange-service', ip, headers)
        except Exception as e:
            print("场内流水导入失败 {tradeId} msg:{error}".format(tradeId=record['tradeId'], error=repr(e)))

# exeTradeRecordSave
if __name__ == '__main__':
    headers = utils.login(bct_login_ip, bct_login_body)
    import_exchange_trades(bct_login_ip, headers)


import random
import numpy as np
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QGridLayout, QMessageBox
from PyQt5.QtGui import QFont, QPalette
from PyQt5.QtCore import Qt

class Block(QLabel):
	def __init__(self, text):
		super().__init__()

		# Properties of the grids
		self.Text = text
		self.Size = 80
		self.Background = "orange"
		self.ZeroBackground = "gray"
		self.BorderRadius = "10px"

		#properties of text on the block
		self.Font = "Arial"
		self.FontSize = 30
		self.Bold = True
		self.Alignment = "center"
		self.initUI()

	def initUI(self):
		# Block
		self.setFixedSize(self.Size, self.Size)
		# Text
		font = QFont(self.Font, self.FontSize)
		font.setBold(self.Bold)
		self.setFont(font)

		# Set color of text
		pa = QPalette()
		pa.setColor(QPalette.WindowText, Qt.white)
		self.setPalette(pa)

		self.setStyleSheet("border-radius:" + self.BorderRadius)
		self.setAlignment(Qt.AlignCenter)

		# If number == 0, block background should be the same as window background
		if self.Text ==0:
			self.setStyleSheet("background-color:%s;" % self.ZeroBackground)
		else:
			self.setText(str(self.Text))
			self.setStyleSheet("background: %s;" % self.Background)

class Puzzle(QWidget):

	def __init__(self):
		# Basic stuff of the game
		super().__init__()
		self.Title = 'Puzzle Game'
		# Size of rows and columns
		self.PuzzleSize = 4
		self.background = 'gray'
		# create 2d array with random number from 0 to 15
		self.matrix = self.CreateMatrix()
		# layout of the window
		self.Top = 10
		self.Left = 10
		self.Size = 400

		self.ZeroRow, self.ZeroCol = self.ZeroPos()

		self.layout = QGridLayout()

		self.initUI()

	def initUI(self):
		self.setWindowTitle(self.Title)
		self.setGeometry(self.Left,self.Top, self.Size, self.Size)
		self.setStyleSheet("background:" + self.background)

		self.SetLayout()

	def CreateMatrix(self):

		# get an array with random int from 0 to 16
		blocks = list(range(0,16))
		# mess around the elements in array to make sure the number is random
		random.shuffle(blocks)
		# convert 1d array into 2d array
		matrix = [blocks[x:x+4] for x in range(0,len(blocks),4)]

		return matrix

	def ZeroPos(self):
		# find zero in the matrix
		for items in self.matrix: # go through every sub-list
			if 0 in items:
				zeroRow = self.matrix.index(items) #find out 0 in which sub list
				zeroCol = items.index(0)
		return zeroRow, zeroCol

	def SetLayout(self):

		for row in range(4):
			for col in range(4):
				self.layout.addWidget(Block(self.matrix[row][col]), row, col)
		self.setLayout(self.layout)
		self.show()

	def keyPressEvent(self, event):
		key = event.key()

		if (key == Qt.Key_Up or key == Qt.Key_W):
			self.move('up')
		elif (key == Qt.Key_Down or key == Qt.Key_S):
			self.move('down')
		elif (key == Qt.Key_Left or key == Qt.Key_A):
			self.move('left')
		elif (key == Qt.Key_Right or key == Qt.Key_D):
			self.move('right')

	def move(self, direction):
		ZeroRow = self.ZeroRow
		ZeroCol = self.ZeroCol
		if direction == 'up' and self.ZeroRow != 3:
			# swap position of 0 and the one below it
			self.matrix[ZeroRow][ZeroCol], self.matrix[ZeroRow+1][ZeroCol] = self.matrix[ZeroRow+1][ZeroCol], self.matrix[ZeroRow][ZeroCol]
			# update position of zero
			self.ZeroRow += 1

		if direction == 'down' and self.ZeroRow != 0:
			# swap position of 0 and the one below it
			self.matrix[ZeroRow][ZeroCol], self.matrix[ZeroRow-1][ZeroCol] = self.matrix[ZeroRow-1][ZeroCol], self.matrix[ZeroRow][ZeroCol]
			# update position of zero
			self.ZeroRow -= 1

		if direction == 'left' and self.ZeroCol != 3:
			# swap position of 0 and the one below it
			self.matrix[ZeroRow][ZeroCol], self.matrix[ZeroRow][ZeroCol+1] = self.matrix[ZeroRow][ZeroCol+1], self.matrix[ZeroRow][ZeroCol]
			# update position of zero
			self.ZeroCol+= 1

		if direction == 'right' and self.ZeroCol != 0:
			# swap position of 0 and the one below it
			self.matrix[ZeroRow][ZeroCol], self.matrix[ZeroRow][ZeroCol-1] = self.matrix[ZeroRow][ZeroCol-1], self.matrix[ZeroRow][ZeroCol]
			# update position of zero
			self.ZeroCol -= 1

		self.SetLayout()
		# After each move, check if use find the right solution
		# if they do, message box bumps up
		# click ok to restart another game
		if (self.CheckResult()):
			# message box bumps up
			# user click ok to restart the game
			print(self.matrix)
			if QMessageBox.Ok == QMessageBox.information(self, 'Congradulations!', 'You win!!!'):
				self.matrix = self.CreateMatrix()
				self.SetLayout()

	def CheckResult(self):
		# first check if 0 is the last
		if self.matrix[self.PuzzleSize-1][self.PuzzleSize-1] != 0:
			return False
		# check numbers are in right position
		for row in range(self.PuzzleSize):
			for col in range(self.PuzzleSize):
				if self.matrix[row][col] != row * self.PuzzleSize + col + 1:
					# user find the solution
					if row == 3 and col == 3:
						pass
					else:
						print(row,col)
						return False

		return True

if __name__ == '__main__':
	app = QApplication(sys.argv)
	ex = Puzzle()
	sys.exit(app.exec_())


from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from quote.models import Quote, QuoteForm
from quote.services import get_all_quotes, get_single_quote, create_job_with_quote, create_pdf
from job.services import get_single_job
from django.views.generic import DetailView, CreateView, UpdateView, DeleteView, ListView
from django.http import JsonResponse, HttpResponseRedirect
from django.core.paginator import Paginator
from django.urls import reverse_lazy, reverse
from user.models import User
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from job.models import Job
from django.core.exceptions import ValidationError
from django.core.mail import send_mail, EmailMessage
from smtplib import SMTPException
import os

@csrf_exempt
def create_job(request):
    if request.is_ajax():
        quote_id = request.POST.get('data')
        quote = get_single_quote(quote_id)

        job = create_job_with_quote(quote)

        try:
            job.full_clean()
            job.save()
            quote.associated_job = job._id
            quote.save()

            url = reverse('job-details', kwargs={'obj_id':job._id})
            data = {'success': url}
            name = quote.customer_first_name + ' ' + quote.customer_last_name
            messages.success(request, 'Job for ' + name + ' created')
            return JsonResponse(data)

        except ValidationError as err:
            data = {'error': err.message_dict}
            return JsonResponse(data)

@csrf_exempt
def send_quote(request):
    if request.is_ajax():
        quote_id = request.POST.get('data')
        quote = get_single_quote(quote_id)

        try:
            if quote.customer_email == None:
                raise ValidationError('Must have a customer email')
            elif quote.date_of_job == None:
                raise ValidationError('Must have a date of job')
            elif quote.materials == None:
                raise ValidationError('Must have materials')
            elif quote.price_of_materials == None:
                raise ValidationError('Must have price of materials')
            elif quote.price_of_labour == None:
                raise ValidationError('Must have price of labour')
            elif quote.quote_price == None:
                raise ValidationError('Must have quote price')

        except ValidationError as err:
            return JsonResponse( {'status': 'error'} )

        quote.issued_by_first_name = quote.issued_by.first_name
        quote.issued_by_last_name = quote.issued_by.last_name
        quote.issued_by_address = quote.issued_by.address
        quote.issued_by_number = quote.issued_by.phone_num
        quote_dict = vars(quote)

        pdf = create_pdf(quote_dict)

        email = EmailMessage(
            subject='Frenchay Fencing Quote',
            body='Please find attached your quote.\n\nPlease do not reply to this email. Instead, contact us using the details on your quote.',
            from_email=os.environ.get('EMAIL_USER'),
            to=[quote.customer_email],
            cc=[quote.issued_by.email]
        )
        email.attach('quote.pdf', pdf, 'application/pdf')
        try:
            email.send()
            quote.sent_quote = True
            quote.save()
            return JsonResponse( {'status': 'success'} )
        except SMTPException as err:
            return JsonResponse( {'status': 'error'} )

class QuoteListView(LoginRequiredMixin, ListView):
    model = Quote
    template_name = "quote/view_quotes.html"
    paginate_by = 10

    def get_queryset(self):
        quotes = get_all_quotes()
        q = self.request.GET.get("search", None)

        #if user enters search term
        if q is not None:
            quotes = quotes.filter(
                Q(customer_first_name__icontains=q) |
                Q(customer_last_name__icontains=q) |
                Q(address__icontains=q) |
                Q(customer_phone_num__icontains=q)
                )

        for item in quotes:
            item.id = item._id

        return quotes

class QuoteDetailView(LoginRequiredMixin, DetailView):
    model = Quote

    def get_object(self, queryset=None):
        quote = get_single_quote(self.kwargs.get('obj_id'))
        quote.id = quote._id
        return quote

    def render_to_response(self, context, **response_kwargs):
        # split the materials into an array to display differently on frontend
        context['object'].materials = context['object'].materials.splitlines()

        response_kwargs.setdefault('content_type', self.content_type)
        return self.response_class(
            request=self.request,
            template=self.get_template_names(),
            context=context,
            using=self.template_engine,
            **response_kwargs
        )

class QuoteCreateView(LoginRequiredMixin, CreateView):
    model = Quote
    form_class = QuoteForm

    def form_valid(self, form):
        form.instance.issued_by = self.request.user
        form.instance.address = form.cleaned_data['address']
        name = form.cleaned_data['customer_first_name'] +  ' ' + form.cleaned_data['customer_last_name']
        messages.success(self.request, 'Quote for ' + name + ' created')

        return super().form_valid(form)

class QuoteUpdateView(LoginRequiredMixin, UpdateView):
    model = Quote
    form_class = QuoteForm
    pk_url_kwarg = 'obj_id'

    def get_object(self, queryset=None):
        quote = get_single_quote(self.kwargs.get('obj_id'))
        quote.id = quote._id
        return quote

    def get_initial(self):
        quote = get_single_quote(self.kwargs.get('obj_id'))
        quote = vars(quote)
        address = quote['address']
        split_address = address.split(',')
        quote['street'] = split_address[0].lstrip()
        quote['city'] = split_address[1].lstrip()
        quote['post_code'] = split_address[2].lstrip()
        return quote

    def form_valid(self, form):
        form.instance.address = form.cleaned_data['address']
        name = form.cleaned_data['customer_first_name'] +  ' ' + form.cleaned_data['customer_last_name']
        messages.success(self.request, 'Quote for ' + name + ' updated')

        return super().form_valid(form)

class QuoteDeleteView(LoginRequiredMixin, DeleteView):
    model = Quote
    pk_url_kwarg = 'obj_id'
    success_url = reverse_lazy('view-quotes')

    def get_object(self, queryset=None):
        quote = get_single_quote(self.kwargs.get('obj_id'))
        quote.id = quote._id

        return quote

    def delete(self, request, *args, **kwargs):
        quote = get_single_quote(self.kwargs.get('obj_id'))

        # when quote is deleted also delete associated job
        if quote.associated_job != None:
            job = get_single_job(quote.associated_job)
            job.delete()

        name = quote.customer_first_name +  ' ' + quote.customer_last_name

        quote.delete()

        success_url = reverse_lazy('view-quotes')
        messages.success(self.request, 'Quote and associated job for ' + name + ' deleted')
        return HttpResponseRedirect(success_url)


class Solution:
  def largestRectangleArea(self, heights):
    """
    :type heights: List[int]
    :rtype: int
    """
    stack = []
    max_area = 0
    index = 0
    while index < len(heights):
      if not stack or heights[index] >= heights[stack[-1]]:
        stack.append(index)
        index += 1
      else:
        top = stack.pop()
        print(heights[top], index, stack[-1] if stack else index)
        area = heights[top] * (index - stack[-1] - 1 if stack else index)
        max_area = max(max_area, area)

    while stack:
      top = stack.pop()
      area = heights[top] * (index - stack[-1] - 1 if stack else index)
      max_area = max(max_area, area)

    return max_area


import re
import sys
from collections import defaultdict
from random import random

# Based on https://github.com/veekaybee/markovhn/blob/master/markov.py

lookback = 2

class Markov():

    def __init__(self, filename):
        self.filename = filename
        self.markov_map, self.titles = init(filename)

    def generate_sentence(self):
        sentence = []
        next_word = sample(self.markov_map[''].items())
        while next_word != '':
            sentence.append(next_word)
            next_word = sample(self.markov_map[' '.join(sentence[-lookback:])].items())
        sentence = ' '.join(sentence)
        for title in self.titles: #Prune titles that are substrings of actual titles
            if sentence in title:
                return self.generate_sentence()
        return sentence

    def get_sentences(self, count=10):
        sentences = []
        while len(sentences) < count:
            sentences.append(self.generate_sentence())
        for sentence in sentences:
            print (sentence)

def init(filename):
    archive = open(filename, encoding="utf-8")
    titles = archive.read().split("\n")
    archive.close()
    markov_map = defaultdict(lambda: defaultdict(int))

    #Generate map in the form word1 -> word2 -> occurences of word2 after word1
    for title in titles[:-1]:
        title = title.split()
        if len(title) > lookback:
            for i in range(len(title)+1):
                markov_map[' '.join(title[max(0,i-lookback):i])][' '.join(title[i:i+1])] += 1

    #Convert map to the word1 -> word2 -> probability of word2 after word1
    for _, following in markov_map.items():
        total = float(sum(following.values()))
        for key in following:
            following[key] /= total
    return markov_map, titles

#Typical sampling from a categorical distribution
def sample(items):
    next_word = None
    t = 0.0
    for k, v in items:
        t += v
        if t and random() < v/t:
            next_word = k
    return next_word