from typing import List, Optional

import torch
from deepclustering.loss import KL_div, Union, assert_list, simplex
from deepclustering.loss.kl_losses import _check_reduction_params
from torch import nn, Tensor

# def computeWeight(preds, psueduo, labm):
#     Kl_loss = KL_div()
#     loss_list = []
#     wk = []
#     for i in range(len(preds)):
#         loss_s = torch.zeros((preds[i].shape[0]))
#         loss = (Kl_loss(preds[i], psueduo)).data
#         for i in range(len(loss)):
#             loss_s[i] = loss[i].sum()
#         loss_list.append(loss_s)
#     for loss_one in loss_list:
#         ori_wk = (1 - 1 / labm * loss_one).to('cpu')
#         wk_one = torch.where(ori_wk.data < 0, torch.tensor([1e-16], dtype=torch.float).to('cpu'), ori_wk)
#         wk.append(wk_one)
#     return wk

# class KL_div(nn.Module):
#
#     def __init__(self, eps=1e-16, weight: Union[List[float], Tensor] = None, verbose=True):
#         super().__init__()
#         self._eps = eps
#         self._weight: Optional[Tensor] = weight
#         if weight is not None:
#             assert isinstance(weight, (list, Tensor)), type(weight)
#             if isinstance(weight, list):
#                 assert assert_list(lambda x: isinstance(x, (int, float)), weight)
#                 self._weight = torch.Tensor(weight).float()
#             else:
#                 self._weight = weight.float()
#             # normalize weight:
#             self._weight = self._weight / self._weight.sum()
#
#     def forward(self, prob: Tensor, target: Tensor, **kwargs) -> Tensor:
#         if not kwargs.get("disable_assert"):
#             assert prob.shape == target.shape
#             assert simplex(prob), prob
#             assert not target.requires_grad
#             assert prob.requires_grad
#         b, c, *hwd = target.shape
#         kl = (-target * torch.log((prob + self._eps) / (target + self._eps)))
#         if self._weight is not None:
#             assert len(self._weight) == c
#             weight = self._weight.expand(b, *hwd, -1).transpose(-1, 1).detach()
#             kl *= weight.to(kl.device)
#         kl = kl.sum(0)
#         return kl

def computeWeight(preds, psueduo, labm):
    Kl_loss = KL_div()
    wk = []
    for i in range(len(preds)):
        loss_wk = (Kl_loss(preds[i], psueduo)).data
        wk.append(loss_wk)
    wklist = []
    for i in range(len(wk)):
        wk_one = torch.where(wk[i] == 0, torch.tensor([1e-3], dtype=torch.float).to('cpu'), wk[i])
        wklist.append(wk_one)
    wwk = []
    for i in range(len(wklist)):
        ori_wk = (1 - 1 / labm * wklist[i]).to('cpu')
        wwk.append(ori_wk)
    wk_total = []
    for i in range(len(wwk)):
        wk_1 = torch.where(wwk[i] < 0, torch.tensor([1e-5], dtype=torch.float).to('cpu'), wwk[i])
        wk_total.append(wk_1)
    return wk_total

class KL_div(nn.Module):
    def __init__(self, eps=1e-16, weight: Union[List[float], Tensor] = None, verbose=True):
        super().__init__()
        self._eps = eps
        self._weight: Optional[Tensor] = weight
        if weight is not None:
            assert isinstance(weight, (list, Tensor)), type(weight)
            if isinstance(weight, list):
                assert assert_list(lambda x: isinstance(x, (int, float)), weight)
                self._weight = torch.Tensor(weight).float()
            else:
                self._weight = weight.float()
            # normalize weight:
            self._weight = self._weight / self._weight.sum()

    def forward(self, prob: Tensor, target: Tensor, **kwargs) -> Tensor:
        if not kwargs.get("disable_assert"):
            assert prob.shape == target.shape
            assert simplex(prob), prob
            assert not target.requires_grad
            assert prob.requires_grad
        b, c, *hwd = target.shape
        kl = (-target * torch.log((prob + self._eps) / (target + self._eps))).sum(1)
        return kl


class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []
        self.permuteRecursive(nums, 0, result)
    def permuteRecursive(self, nums, begin, result):
        if begin >= len(nums):
            result.append(nums[:])
            return
        for i in range(begin, len(nums)):
            nums[begin], nums[i] = nums[i], nums[begin]
            self.permuteRecursive(nums, begin + 1, result)
            nums[begin], nums[i] = nums[i], nums[begin]


import pygame
import time, sys, os
sys.path.insert(0,"../")
from sound.SoundCte import *
'''
class GeneralSoundManager:

  def __init__(self, propertiesFile):
    # init all the submodules
    GAME_EFFECT =
    if propertiesFile is None
      propertiesFile = "DEFAULT_PROPERTIES_FILE.txt"
    effectSM = EffectSoundManager.init(propertiesFile)
    musicSM = MusicSoundManager.init(propertiesFile)
    menuSM = MenuSoundManager.init(propertiesFile)

  def manage(self, eventList):

    while True:
      for event in eventList:
        if event.type == GAME_EFFECT_EVENT: # o definir lista de eventos que corresponden a un efecto y ver si esta en ella
          effectSM.manage(event)
        if event.type == GAME_MUSIC_EVENT:
          musicSM.manage(event)
        if event.type == GAME_MENU_EVENT:
          menuSM.manage(event)
        if event.type == pygame.QUIT:
          pygame.quit()
          sys.exit()

  class EffectSoundManager
    def __init__(self, propertiesFile):
      #init sonidos de effectos
      # load sound files

      MAIN_CHARACTER_ATTACK_SOUND = pygame.mixer.Sound('test.ogg')
      # o para poder cargar desde archivo de texto
      MAIN_CHARACTER_ATTACK_SOUND = SoundResourceLoader.load(propertiesFile, "MAIN_CHARACTER_ATTACK")
      text_file = open("filename.dat", "r")
      lines = text_file.read().split(',')
      print lines
      print len(lines)
      text_file.close()

    def manage(event):
      if event.type == MAIN_CHARACTER_ATTACK:
          MAIN_CHARACTER_ATTACK_SOUND.play()
      if event.type == MAIN_CHARACTER_HIT:
          MAIN_CHARACTER_HIT_SOUND.play()
      if event.type == CURRENT_ENEMY_ATTACK:
          CURRENT_ENEMY_ATTACK_SOUND.play()
      if event.type == CURRENT_ENEMY_HIT:
          CURRENT_ENEMY_HIT_SOUND.play()
  class SoundResourceLoader
    def load(propertiesFile, soundName)
        properties = new Properties(propertiesFile)
        return pygame.mixer.Sound(properties.getPropertie(soundName))

'''
'''
import os
CONTEXT							= os.getcwd()
CONTEXT = '/home/miguel/Descargas/videojoco2d-master/'

EFFECT_PRIORITY = 1
MUSIC_PRIORITY = 1
MENU_PRIORITY = 1

EFFECT_CHANNEL = 0
EFFECT_CHANNEL2 = 4
MUSIC_CHANNEL = 1
MENU_CHANNEL = 2
MENU_CHANNEL2 = 3

if pygame.mixer.get_init() is None:
	pygame.mixer.init()

def load():

	#ambiente
	AMBIENTEAGUASPLASHS_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteAguaSplash.ogg'		)
	AMBIENTEANDARARENACORTO_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteAndarArenaCorto.ogg'	)
	AMBIENTEANDARRAMAS_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteAndarRamas.ogg'		)
	AMBIENTEBOSQUECORTO_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteBosqueCorto.ogg'		)
	AMBIENTECASCADA1_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteCascada1.ogg'			)
	AMBIENTECASCADA2_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteCascada2.ogg'			)
	AMBIENTECASCOTESCAIDA_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteCascotesCaida.ogg'		)
	AMBIENTECOLISEO_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteColiseo.ogg' 			)
	AMBIENTEFUEGO1_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteFuego1.ogg'			)
	AMBIENTEFUEGO2_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteFuego2.ogg'			)
	AMBIENTEFUEGONOLOOP_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteFuegoNoLoop.ogg'		)
	AMBIENTEGENTEPANICO_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteGentePanico.ogg'		)
	AMBIENTEGENTEPANICOCORTO_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteGentePanicoCorto.ogg'	)
	AMBIENTEGENTESUSURROS_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteGenteSusurros.ogg'		)
	AMBIENTEGRANJA_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteGranja.ogg'			)
	AMBIENTEHOJASMANIPULAR_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteHojasManipular.ogg'	)
	AMBIENTELLUVIA_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteLluvia.ogg'			)
	AMBIENTENOCHE_SOUND				= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteNoche.ogg'				)
	AMBIENTEPISARTIERRA_SOUND 		= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbientePisarTierra.ogg'		)
	AMBIENTERATA1_SOUND				= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteRata1.ogg'				)
	AMBIENTERATA2_SOUND				= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteRata2.ogg'				)
	AMBIENTERATA3_SOUND				= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteRata3.ogg'				)
	AMBIENTERATA4_SOUND				= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteRata4.ogg'				)
	AMBIENTERIO1_SOUND				= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteRio1.ogg'				)
	AMBIENTERIO2_SOUND				= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteRio2.ogg'				)
	AMBIENTEVIENTO_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Ambiente/AmbienteViento.ogg'			)

	#armas
	ARMADAGAIMPACTO_SOUND	 	= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaDagaImpacto.ogg'		)
	ARMAESPADAATAQUE1_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaEspadaAtaque1.ogg'	)
	ARMAESPADAATAQUE2_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaEspadaAtaque2.ogg'	)
	ARMAESPADAEQUIPAR_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaEspadaEquipar.ogg'	)
	ARMAESPADAIMPACTO_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaEspadaImpacto.ogg'	)
	ARMAFLECHAATAQUE1_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaFlechaAtaque1.ogg'	)
	ARMAFLECHAATAQUE2_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaFlechaAtaque2.ogg'	)
	ARMAFLECHAIMPACTO1_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaFlechaImpacto1.ogg'	)
	ARMAFLECHAIMPACTO2_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaFlechaImpacto2.ogg'	)
	ARMAHORCAATAQUE_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaHorcaAtaque.ogg' 		)
	ARMAHORCAIMPACTO_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaHorcaImpacto.ogg' 	)
	ARMAHORCAIMPACTO2_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaHorcaImpacto2.ogg' 	)
	ARMAMAGIAATAQUE_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaMagiaAtaque.ogg' 		)
	ARMAMANOTAZOIMPACTO_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaManotazoImpacto.ogg' 	)
	ARMAPUNHOIMPACTO_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Armas/ArmaPunhoImpacto.ogg' 	)

	#menu
	CLICK_SOUND 		= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/click.ogg'			)
	CLICK_2_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/click_2.ogg'		)
	LOAD_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/load.ogg'			)
	MISC_MENU_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/misc_menu.ogg'		)
	MISC_MENU_2_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/misc_menu_2.ogg'	)
	MISC_MENU_3_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/misc_menu_3.ogg'	)
	MISC_MENU_4_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/misc_menu_4.ogg'	)
	MISC_SOUND_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/misc_sound.ogg'	)
	NEGATIVE_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/negative.ogg'		)
	NEGATIVE_2_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/negative_2.ogg'	)
	POSITIVE_SOUND		= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/positive.ogg'		)
	SAVE_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/save.ogg'			)
	SHARP_ECHO_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Menu/sharp_echo.ogg'	)

	#musica

	MUSICA1_SOUND = pygame.mixer.music.load(CONTEXT+'res/sound/Musica/Musica1.ogg')
	MUSICA2_SOUND = pygame.mixer.music.load(CONTEXT+'res/sound/Musica/Musica2.ogg')
	MUSICA3_SOUND = pygame.mixer.music.load(CONTEXT+'res/sound/Musica/Musica3.ogg')

	MUSICA5_SOUND = pygame.mixer.music.load(CONTEXT+'res/sound/Musica/Musica5.ogg')

	MUSICA6_SOUND = pygame.mixer.music.load(CONTEXT+'res/sound/Musica/Musica6.ogg')

	MUSICA_PLAY = pygame.mixer.music.play()
	#personajes
	PERSONAJEGRITOSTANDARD_SOUND	= pygame.mixer.Sound(CONTEXT+'res/sound/Personajes/PersonajeGritoStandard.ogg'	)
	PERSONAJEVIDABAJA_SOUND			= pygame.mixer.Sound(CONTEXT+'res/sound/Personajes/PersonajeVidaBaja.ogg' 		)
	PERSONAJESGRITOHOMBRE_SOUND 	= pygame.mixer.Sound(CONTEXT+'res/sound/Personajes/PersonajesGritoHombre.ogg'	)
'''
class GeneralSoundManager():

	def __init__(self, context):

		self.CONTEXT	= context

		self.EFFECT_PRIORITY = 1
		self.MUSIC_PRIORITY = 1
		self.MENU_PRIORITY = 1

		if pygame.mixer.get_init() is None:
			pygame.mixer.init()

		#ambiente
		self.AMBIENTEAGUASPLASHS_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteAguaSplash.ogg'		)
		self.AMBIENTEANDARARENACORTO_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteAndarArenaCorto.ogg'	)
		self.AMBIENTEANDARRAMAS_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteAndarRamas.ogg'		)
		self.AMBIENTEBOSQUECORTO_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteBosqueCorto.ogg'		)
		self.AMBIENTECASCADA1_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteCascada1.ogg'			)
		self.AMBIENTECASCADA2_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteCascada2.ogg'			)
		self.AMBIENTECASCOTESCAIDA_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteCascotesCaida.ogg'		)
		self.AMBIENTECOLISEO_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteColiseo.ogg' 			)
		self.AMBIENTEFUEGO1_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteFuego1.ogg'			)
		self.AMBIENTEFUEGO2_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteFuego2.ogg'			)
		self.AMBIENTEFUEGONOLOOP_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteFuegoNoLoop.ogg'		)
		self.AMBIENTEGENTEPANICO_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteGentePanico.ogg'		)
		self.AMBIENTEGENTEPANICOCORTO_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteGentePanicoCorto.ogg'	)
		self.AMBIENTEGENTESUSURROS_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteGenteSusurros.ogg'		)
		self.AMBIENTEGRANJA_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteGranja.ogg'			)
		self.AMBIENTEHOJASMANIPULAR_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteHojasManipular.ogg'	)
		self.AMBIENTELLUVIA_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteLluvia.ogg'			)
		self.AMBIENTENOCHE_SOUND				= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteNoche.ogg'				)
		self.AMBIENTEPISARTIERRA_SOUND 		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbientePisarTierra.ogg'		)
		self.AMBIENTERATA1_SOUND				= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteRata1.ogg'				)
		self.AMBIENTERATA2_SOUND				= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteRata2.ogg'				)
		self.AMBIENTERATA3_SOUND				= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteRata3.ogg'				)
		self.AMBIENTERATA4_SOUND				= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteRata4.ogg'				)
		self.AMBIENTERIO1_SOUND				= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteRio1.ogg'				)
		self.AMBIENTERIO2_SOUND				= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteRio2.ogg'				)
		self.AMBIENTEVIENTO_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Ambiente/AmbienteViento.ogg'			)

		#armas
		self.ARMADAGAIMPACTO_SOUND	 	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaDagaImpacto.ogg'		)
		self.ARMAESPADAATAQUE1_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaEspadaAtaque1.ogg'	)
		self.ARMAESPADAATAQUE2_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaEspadaAtaque2.ogg'	)
		self.ARMAESPADAEQUIPAR_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaEspadaEquipar.ogg'	)
		self.ARMAESPADAIMPACTO_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaEspadaImpacto.ogg'	)
		self.ARMAFLECHAATAQUE1_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaFlechaAtaque1.ogg'	)
		self.ARMAFLECHAATAQUE2_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaFlechaAtaque2.ogg'	)
		self.ARMAFLECHAIMPACTO1_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaFlechaImpacto1.ogg'	)
		self.ARMAFLECHAIMPACTO2_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaFlechaImpacto2.ogg'	)
		self.ARMAHORCAATAQUE_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaHorcaAtaque.ogg' 		)
		self.ARMAHORCAIMPACTO_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaHorcaImpacto.ogg' 	)
		self.ARMAHORCAIMPACTO2_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaHorcaImpacto2.ogg' 	)
		self.ARMAMAGIAATAQUE_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaMagiaAtaque.ogg' 		)
		self.ARMAMANOTAZOIMPACTO_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaManotazoImpacto.ogg' 	)
		self.ARMAPUNHOIMPACTO_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Armas/ArmaPunhoImpacto.ogg' 	)

		#menu
		self.CLICK_SOUND 		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/click.ogg'			)
		self.CLICK_2_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/click_2.ogg'		)
		self.LOAD_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/load.ogg'			)
		self.MISC_MENU_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/misc_menu.ogg'		)
		self.MISC_MENU_2_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/misc_menu_2.ogg'	)
		self.MISC_MENU_3_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/misc_menu_3.ogg'	)
		self.MISC_MENU_4_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/misc_menu_4.ogg'	)
		self.MISC_SOUND_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/misc_sound.ogg'	)
		self.NEGATIVE_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/negative.ogg'		)
		self.NEGATIVE_2_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/negative_2.ogg'	)
		self.POSITIVE_SOUND		= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/positive.ogg'		)
		self.SAVE_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/save.ogg'			)
		self.SHARP_ECHO_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Menu/sharp_echo.ogg'	)

		#musica
		'''
		self.MUSICA1_SOUND = pygame.mixer.music.load(self.CONTEXT+'res/sound/Musica/Musica1.ogg')
		self.MUSICA2_SOUND = pygame.mixer.music.load(self.CONTEXT+'res/sound/Musica/Musica2.ogg')
		self.MUSICA3_SOUND = pygame.mixer.music.load(self.CONTEXT+'res/sound/Musica/Musica3.ogg')
		self.MUSICA4_SOUND = pygame.mixer.music.load(self.CONTEXT+'res/sound/Musica/Musica4.ogg')
		self.MUSICA5_SOUND = pygame.mixer.music.load(self.CONTEXT+'res/sound/Musica/Musica5.ogg')
		self.MUSICA6_SOUND = pygame.mixer.music.load(self.CONTEXT+'res/sound/Musica/Musica6.ogg')
		'''

		#personajes
		self.PERSONAJEGRITOSTANDARD_SOUND	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Personajes/PersonajeGritoStandard.ogg'	)
		self.PERSONAJEVIDABAJA_SOUND			= pygame.mixer.Sound(self.CONTEXT+'res/sound/Personajes/PersonajeVidaBaja.ogg' 		)
		self.PERSONAJESGRITOHOMBRE_SOUND 	= pygame.mixer.Sound(self.CONTEXT+'res/sound/Personajes/PersonajesGritoHombre.ogg'	)

	def generalSoundManage(self, event, repeat = 0):

		if event < GAME_SOUND_EFFECT_EVENT:
			self.effectManage(event, self.EFFECT_PRIORITY, repeat)
		elif event < GAME_SOUND_MUSIC_EVENT:
			self.musicManage(event, self.MUSIC_PRIORITY, repeat)
		elif event < GAME_SOUND_MENU_EVENT:
			self.menuManage(event, self.MENU_PRIORITY, repeat)
		else:
			print("evento desconocido")

	def effectManage(self, event, priority, repeat):

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEAGUASPLASHS:
			  self.AMBIENTEAGUASPLASHS_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEANDARARENACORTO:
			  self.AMBIENTEANDARARENACORTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEANDARRAMAS:
			  self.AMBIENTEANDARRAMAS_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEBOSQUECORTO:
			  self.AMBIENTEBOSQUECORTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTECASCADA1:
			  self.AMBIENTECASCADA1_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTECASCADA2:
			  self.AMBIENTECASCADA2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTECASCOTESCAIDA:
			  self.AMBIENTECASCOTESCAIDA_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTECOLISEO:
			  self.AMBIENTECOLISEO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEFUEGO1:
			  self.AMBIENTEFUEGO1_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEFUEGO2:
			  self.AMBIENTEFUEGO2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEFUEGONOLOOP:
			  self.AMBIENTEFUEGONOLOOP_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEGENTEPANICO:
			  self.AMBIENTEGENTEPANICO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEGENTEPANICOCORTO:
			  self.AMBIENTEGENTEPANICOCORTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEGENTESUSURROS:
			  self.AMBIENTEGENTESUSURROS_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEGRANJA:
			  self.AMBIENTEGRANJA_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEHOJASMANIPULAR:
			  self.AMBIENTEHOJASMANIPULAR_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTELLUVIA:
			  self.AMBIENTELLUVIA_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTENOCHE:
			  self.AMBIENTENOCHE_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEPISARTIERRA:
			  self.AMBIENTEPISARTIERRA_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTERATA1:
			  self.AMBIENTERATA1_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTERATA2:
			  self.AMBIENTERATA2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTERATA3:
			  self.AMBIENTERATA3_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTERATA4:
			  self.AMBIENTERATA4_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTERIO1:
			  self.AMBIENTERIO1_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTERIO2:
			  self.AMBIENTERIO2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_AMBIENTEVIENTO:
			  self.AMBIENTEVIENTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMADAGAIMPACTO:
			  self.ARMADAGAIMPACTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAESPADAATAQUE1:
			  self.ARMAESPADAATAQUE1_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAESPADAATAQUE2:
			  self.ARMAESPADAATAQUE2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAESPADAEQUIPAR:
			  self.ARMAESPADAEQUIPAR_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAESPADAIMPACTO:
			  self.ARMAESPADAIMPACTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAFLECHAATAQUE1:
			  self.ARMAFLECHAATAQUE1_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAFLECHAATAQUE2:
			  self.ARMAFLECHAATAQUE2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAFLECHAIMPACTO1:
			  self.ARMAFLECHAIMPACTO1_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAFLECHAIMPACTO2:
			  self.ARMAFLECHAIMPACTO2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAHORCAATAQUE:
			  self.ARMAHORCAATAQUE_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAHORCAIMPACTO:
			  self.ARMAHORCAIMPACTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAHORCAIMPACTO2:
			  self.ARMAHORCAIMPACTO2_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAMAGIAATAQUE:
			  self.ARMAMAGIAATAQUE_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAMANOTAZOIMPACTO:
			  self.ARMAMANOTAZOIMPACTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_ARMAPUNHOIMPACTO:
			  self.ARMAPUNHOIMPACTO_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_PERSONAJEGRITOSTANDARD:
			  self.PERSONAJEGRITOSTANDARD_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_PERSONAJEVIDABAJA:
			  self.PERSONAJEVIDABAJA_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_PERSONAJESGRITOHOMBRE:
			  self.PERSONAJESGRITOHOMBRE_SOUND.play()

		if event == GAME_SOUND_EFFECT_EVENT_STOP:
			pygame.mixer.stop()
		if event == GAME_SOUND_EFFECT_EVENT_PAUSE:
			pygame.mixer.pause()
		if event == GAME_SOUND_EFFECT_EVENT_RESUME:
			pygame.mixer.unpause()

	def musicManage(self, event, priority, repeat):

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_1:
			self.loadMusic('Musica1')
			pygame.mixer.music.play(repeat)

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_2:
			self.loadMusic('Musica2')
			pygame.mixer.music.play(repeat)

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_3:
			self.loadMusic('Musica3')
			pygame.mixer.music.play(repeat)

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_4:
			self.loadMusic('Musica4')
			pygame.mixer.music.play(repeat)

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_5:
			self.loadMusic('Musica5')
			pygame.mixer.music.play(repeat)

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_6:
			self.loadMusic('Musica6')
			pygame.mixer.music.play(repeat)

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_STOP:
			pygame.mixer.music.stop()

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_PAUSE:
			pygame.mixer.music.pause()

		if event == GAME_SOUND_MUSIC_EVENT_MUSIC_RESUME:
			pygame.mixer.music.unpause()

	def menuManage(self, event, priority, repeat):

		if event == GAME_SOUND_MENU:
			self.LOAD_SOUND.play()

		if event == GAME_SOUND_MENU_EVENT_MOVE_UP:
			self.MISC_MENU_SOUND.play()

		if event == GAME_SOUND_MENU_EVENT_MOVE_DOWN:
			self.MISC_MENU_SOUND.play()

		if event == GAME_SOUND_MENU_EVENT_MOVE_LEFT:
			self.MISC_MENU_SOUND.play()

		if event == GAME_SOUND_MENU_EVENT_MOVE_RIGHT:
			self.MISC_MENU_SOUND.play()

		if event == GAME_SOUND_MENU_EVENT_OK:
			self.POSITIVE_SOUND.play()

		if event == GAME_SOUND_MENU_EVENT_CANCEL:
			self.NEGATIVE_SOUND.play()

		if event == GAME_SOUND_MENU_EVENT_EXIT:
			self.SAVE_SOUND.play()

	def loadMusic(self, filename):
		pygame.mixer.music.load(self.CONTEXT+'res/sound/Musica/'+filename+'.ogg')

def main():
	soundManager = main2()
	soundManager.generalSoundManage(GAME_SOUND_MENU_EVENT_OK)
	time.sleep(5)
	soundManager.generalSoundManage(GAME_SOUND_MENU_EVENT_CANCEL)
	time.sleep(5)
	soundManager.generalSoundManage(GAME_SOUND_MENU_EVENT_MOVE_LEFT)
	time.sleep(5)


import time
import re
import decimal

def remote_ping(request, message):
    """
    Sends ping to the server. Just so we know client is still alive. It also removes old locks. This is not the place to do it at all,
    but once we have normal scheduled calls, will put it there.

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type message: C{dict}
    @param message: Message object
    """

    import sputnik

    sputnik.addMessageToChannel(request, "/booki/", {})

    _now = time.time()

    try:
        locks = sputnik.rkeys("booki:*:locks:*")
    except:
        return

    for key in locks:

        lastAccess = sputnik.get(key)

        if type(lastAccess) in [type(' '), type(u' ')]:
            try:
                lastAccess = decimal.Decimal(lastAccess)
            except:
                continue

        if lastAccess and decimal.Decimal("%f" % _now) - lastAccess > 30:
            sputnik.rdelete(key)

            m = re.match("booki:(\d+):locks:(\d+):(\w+)", key)

            if m:
                sputnik.addMessageToChannel(request, "/booki/book/%s/" % m.group(1), {"command": "chapter_status",
                                                                                "chapterID": m.group(2),
                                                                                "status": "normal",
                                                                                "username": m.group(3)},
                                            myself = True)
# FIXME not implemented
def remote_disconnect(request, message):
    pass

def remote_subscribe(request, message):
    """
    Subscribes client to specific channels.

    Input:
     - chanels

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type message: C{dict}
    @param message: Message object
    """

    import sputnik

    for chnl in message["channels"]:
        if not sputnik.hasChannel(chnl):
            sputnik.createChannel(chnl)

        sputnik.addClientToChannel(chnl, request.sputnikID)

def remote_connect(request, message):
    """
    Initializes sputnik connection for this client. Creates clientID for this connection.

    Input:
     - chanels

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type message: C{dict}
    @param message: Message object
    @rtype: C{string}
    @return: Returns unique Client ID for this connection
    """

    import sputnik

    ret = {}

    # does this work ?
    try:
        clientID = sputnik.incr("sputnik:client_id")
    except:
        sputnik.rcon.connect()
        clientID = sputnik.incr("sputnik:client_id")

    ret["clientID"] = clientID
    request.sputnikID = "%s:%s" % (request.session.session_key, clientID)

    if not clientID:
        return

    # subscribe to this channels
    for chnl in message["channels"]:
        if not sputnik.hasChannel(chnl):
            sputnik.createChannel(chnl)

        sputnik.addClientToChannel(chnl, request.sputnikID)

    # set our username
    if request.user and request.user.username.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:username" % request.sputnikID, request.user.username)

    # set our last access
    if request.sputnikID and request.sputnikID.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())

    return ret


import json
import logging

import requests

logger = logging.getLogger(__name__)

# if there is no handler run this code
if not logger.handlers:
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    logger.addHandler(ch)

class PublicatorClientException(Exception):
    """
    Base Exception that publicator client raises
    """
    pass

class PublicatorClient(object):
    """
    Client objects that communicates with publicator server.
    """

    ALL = 'all'
    MESSAGE_ONLY = 'message_only'
    HEADERS = {'Content-type': 'application/json'}

    SESSION_URI = 'session/'

    def __init__(self, base_url, session_id=None, auth_info=None):
        self.base_url = '{0}{1}'.format(
            base_url,
            ('' if base_url[-1] == '/' else '/'))
        self.auth_info = auth_info
        if not session_id:
            session_id = self.get_session(auth_info)
        self.session_id = session_id

    def get_session(self, auth_info):
        """
        Creates a new session on publicator server
        """
        url = '{0}{1}'.format(self.base_url, self.SESSION_URI)
        data = {'auth_info': auth_info}
        logger.debug('Going to server %s to create a session with data %s',
                     url, data)
        response = requests.post(url,
                                 headers=self.HEADERS,
                                 data=json.dumps(data))
        response.raise_for_status()
        result = response.json()
        logger.debug('Session has response %s', result)
        return result['data']

    def _send_msg(self, msg, expected_return_type):
        url = '{0}{1}/http/'.format(self.base_url,
                                    self.session_id)
        logger.debug('Send a message to %s message %s', url, msg)

        response = requests.post(url,
                                 data=json.dumps(msg),
                                 headers=self.HEADERS)
        logger.debug('message successfully sent')
        response.raise_for_status()
        result = response.json()
        logger.debug('response_text = %s' % (result,))

        if isinstance(result, (list,)):
            return result
        else:
            if result.get('type') == 'error' \
                    and result.get('data') == 'consumer_not_found':
                logger.warning('Session is dead. Creating a new session')
                self.session_id = self.get_session(self.auth_info)
                result = self._send_msg(msg)

            if result.get('type') != expected_return_type:
                raise PublicatorClientException(
                    'Return type %s does not match with expected type %s' %
                    (result.get('type'), expected_return_type))
        return result

    def publish(self, channel, msg):
        """
        Publishes a message to given channel
        """

        msg_to_send = {'type': 'publish',
                       'data': {'channel_code': channel,
                                'message': msg}}
        result = self._send_msg(msg_to_send, 'response')
        return result['data']

    def subscribe(self, channel, subscribtion_type=MESSAGE_ONLY):
        """
        Subscribes to given channel
        """
        msg_to_send = {'type': 'subscribe',
                       'data': {'channel_code': channel,
                                'type': subscribtion_type}}
        result = self._send_msg(msg_to_send, 'subscribed')

        return {u'data': channel, u'type': u'subscribed'} == result

    def unsubscribe(self, channel):
        """
        Unsubscribes from given channel
        """
        msg_to_send = {'type': 'unsubscribe',
                       'data': channel}

        result = self._send_msg(msg_to_send, 'unsubscribed')
        return True

    def get_subscribtions(self):
        """
        Get list of subscribed channel list for current session.
        """
        msg_to_send = {'type': 'get_subscribtions'}
        result = self._send_msg(msg_to_send, 'subscribtions')
        return result['data']

    def get_consumers(self, channel):
        """
        Get list of consumer codes for given channel code.
        """
        msg_to_send = {'type': 'get_consumers',
                       'data': {'channel_code': channel}}
        result = self._send_msg(msg_to_send, 'consumers')
        return result['data']

    def get_messages(self):
        msg_to_send = {'type': 'get_messages',
                       'data': {}}
        result = self._send_msg(msg_to_send, 'messages')
        return result


def rc4crypt(data, key):
    x = 0
    box = range(256)
    for i in range(256):
        x = (x + box[i] + ord(key[i % len(key)])) % 256
        box[i], box[x] = box[x], box[i]
    x = 0
    y = 0
    out = []
    for char in data:
        x = (x + 1) % 256
        y = (y + box[x]) % 256
        box[x], box[y] = box[y], box[x]
        out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))

    return ''.join(out)


import datetime

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.views import LoginView, LogoutView
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.db.models import Q, Sum
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import CreateView, ListView, DetailView, UpdateView, \
    DeleteView, TemplateView
from django_datatables_view.base_datatable_view import BaseDatatableView
from django.contrib.auth import logout as auth_logout

from crm_accounting.models import Invoice, status_invoice
from crm_accounting import views as account_views
from crm_home.models import TariffService
from houses.models import House, Flat, Section, Floor
from users.forms import LoginUserForm, CustomUserForm, \
    OwnerUserForm, RequestForm, MessageForm, RequestUserForm, RegisterUserForm
from users.models import CustomUser, Role, Request, Message, MessageUsers
from users.utilites import send_activation_notification, signer

def handler403(request, exception):
    response = render(request, 'error403.html', context={}, status=403)
    return response

def handlers404(request, exception):
    response = render(request, 'error404.html', context={}, status=404)
    print(response)

    return response

class CabinetPermissionMixin(LoginRequiredMixin, UserPassesTestMixin):
    login_url = reverse_lazy('users:login')
    redirect_field_name = 'redirect_to'

    def test_func(self):
        if self.request.user.is_anonymous:
            return False
        elif not self.request.user.role:
            return True

    def handle_no_permission(self):
        if not self.request.user.is_authenticated:
            return super().handle_no_permission()
        elif self.request.user.role:
            return HttpResponseRedirect(reverse_lazy('houses:statistics'))

def check_remember_me_answer(self, form):
    remember_me = form.cleaned_data.get('remember_me')
    if not remember_me:
        self.request.session.set_expiry(0)
        self.request.session.modified = True

class LoginUser(LoginView):
    form_class = LoginUserForm
    template_name = 'users/login_user.html'

    @method_decorator(sensitive_post_parameters())
    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, request, *args, **kwargs):
        if self.request.user.is_authenticated and self.request.user.is_staff:
            return HttpResponseRedirect(reverse_lazy('users:message_list'))
        elif self.request.user.is_authenticated and not self.request.user.is_staff:
            return HttpResponseRedirect(reverse_lazy('users:user_profile'))
        return super().dispatch(request, *args, **kwargs)

    def get_success_url(self):
        return reverse_lazy('users:user_profile')

    def form_valid(self, form):
        ''' Check remember me checkbox from form'''
        check_remember_me_answer(self, form)
        return super(LoginUser, self).form_valid(form)

class RegisterUserView(CreateView):
    model = CustomUser
    form_class = RegisterUserForm
    template_name = 'users/registration_user.html'
    success_url = reverse_lazy('users:register_done')

    def get_context_data(self, **kwargs):
        context = super(RegisterUserView, self).get_context_data()
        confirmation = self.request.GET.get('notconfirm')
        if confirmation:
            context['confirm'] = 'Почта не подтверждена, поскольку ' \
                                 'использован нерпавильный ключ. ' \
                                 'Попробуйте еще раз'
        return context

    def post(self, request):
        form_class = self.form_class(request.POST)
        if form_class.is_valid():
            form_class.save()
            return HttpResponseRedirect(self.success_url)
        else:
            return render(request, self.template_name,
                          context={'form': form_class})

class RegisterDoneView(TemplateView):
    template_name = 'users/register_done.html'

class LoginAdminUser(LoginView):
    form_class = LoginUserForm
    template_name = 'users/login_admin_user.html'

    # redirect_authenticated_user = reverse_lazy('users:layout')

    @method_decorator(sensitive_post_parameters())
    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, request, *args, **kwargs):
        if self.request.user.is_authenticated and self.request.user.is_staff:
            return HttpResponseRedirect(reverse_lazy('users:message_list'))
        elif self.request.user.is_authenticated and not self.request.user. \
                is_staff:
            return HttpResponseRedirect(reverse_lazy('users:user_profile'))
        return super().dispatch(request, *args, **kwargs)

    def get_success_url(self):
        return reverse_lazy('users:users')

    def form_valid(self, form):
        ''' Check remember me checkbox from form'''
        check_remember_me_answer(self, form)
        return super(LoginAdminUser, self).form_valid(form)

class LogoutUser(LogoutView):

    def get_success_url(self):
        return reverse_lazy('content:main')

    @method_decorator(csrf_protect)
    def post(self, request, *args, **kwargs):
        """Logout may be done via POST."""
        auth_logout(request)
        return HttpResponseRedirect(reverse_lazy('content:main'))

class UsersListView(account_views.AdminPermissionMixin, ListView):
    model = CustomUser
    queryset = CustomUser.objects.filter(~Q(role=None)).order_by('id'). \
        select_related('role')
    context_object_name = 'users'
    check_permission_name = 'users'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['roles'] = Role.objects.all()
        return context

class AjaxUsersListView(BaseDatatableView):
    model = CustomUser
    columns = ['id', 'first_name', 'last_name',
               'role', 'phone', 'email', 'status']

    def get_initial_queryset(self):
        return self.model.objects.filter(~Q(role=None))

    def filter_queryset(self, qs):
        user_names = self.request.GET.get('user')
        role = self.request.GET.get('role')
        phone = self.request.GET.get('phone')
        email = self.request.GET.get('email')
        status = self.request.GET.get('status')
        if role:
            qs = qs.filter(role_id=role)
        if phone:
            qs = qs.filter(phone__icontains=phone)
        if email:
            qs = qs.filter(email__icontains=email)
        if status:
            qs = qs.filter(status=status)
        if user_names:
            qs = qs.filter(
                Q(first_name__icontains=user_names)|Q(
                    last_name__icontains=user_names))
        return qs

class UserCreateView(account_views.AdminPermissionMixin, CreateView):
    model = CustomUser
    form_class = CustomUserForm
    context_object_name = 'users'
    success_url = reverse_lazy('users:users')
    check_permission_name = 'users'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['label_suffix'] = ''
        return kwargs

    def get_context_data(self, **kwargs):
        context = super(UserCreateView, self).get_context_data()
        user_id = self.request.GET.get('user_id')
        if user_id:
            user = get_object_or_404(CustomUser, id=user_id)
            initial = {
                'first_name': user.first_name,
                'last_name': user.last_name,
                'role': user.role,
                'phone': user.phone
            }
            context['form'] = self.form_class(initial=initial)
        return context

class UserDetailView(account_views.AdminPermissionMixin, DetailView):
    model = CustomUser
    check_permission_name = 'users'

class UserUpdateView(account_views.AdminPermissionMixin, UpdateView):
    model = CustomUser
    form_class = CustomUserForm
    context_object_name = 'users'
    success_url = reverse_lazy('users:users')
    template_name = 'users/customuser_update_form.html'
    check_permission_name = 'users'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['label_suffix'] = ''
        return kwargs

    def post(self, request, *args, **kwargs):
        form_class = self.form_class(request.POST, instance=self.get_object())
        if form_class.is_valid():
            form_class.save(commit=False)

            form_class.save()
            return HttpResponseRedirect(reverse_lazy('users:users'))
        return render(request, self.template_name, self.get_context_data())

def delete_user(request, pk):
    user = CustomUser.objects.get(pk=pk)
    if not user.is_superuser:
        user.delete()
    else:
        messages.error(request, 'Вы не можете удалть суперпользователя')
    return HttpResponseRedirect(reverse_lazy('users:users'))

class OwnerListView(account_views.AdminPermissionMixin, ListView):
    model = CustomUser
    context_object_name = 'users'
    queryset = CustomUser.objects.filter(role=None).prefetch_related(
        'house_set',
        'flat_set__house__personalaccount_set',
        'flat_set__personal_account').order_by('date_joined')
    template_name = 'users/owners_list.html'
    check_permission_name = 'owner'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['houses'] = House.objects.all()
        return context

class OwnerCreateView(account_views.AdminPermissionMixin, CreateView):
    model = CustomUser
    form_class = OwnerUserForm
    context_object_name = 'users'
    success_url = reverse_lazy('users:owner_list')
    template_name = 'users/owner_create_form.html'
    check_permission_name = 'owner'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['label_suffix'] = ''
        return kwargs

    def post(self, request, *args, **kwargs):
        form_class = self.form_class(request.POST, request.FILES)
        if form_class.is_valid():
            messages.success(request, 'Владелец успешно добавлен')
        return super().post(self, request, *args, **kwargs)

class OwnerUpdateView(account_views.AdminPermissionMixin, UpdateView):
    model = CustomUser
    form_class = OwnerUserForm
    context_object_name = 'users'
    success_url = reverse_lazy('users:owner_list')
    template_name = 'users/owner_update_form.html'
    check_permission_name = 'owner'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['label_suffix'] = ''
        return kwargs

    def post(self, request, *args, **kwargs):
        form_class = self.form_class(request.POST, request.FILES,
                                     instance=self.get_object())
        if form_class.is_valid():
            form_class.save(commit=False)
            form_class.save()
            messages.success(request, 'Владелец успешно обновлен')
            return HttpResponseRedirect(reverse_lazy('users:owner_list'))
        return render(request, self.template_name,
                      context={'form': form_class})

class OwnerDetailView(account_views.AdminPermissionMixin, DetailView):
    model = CustomUser
    template_name = 'users/owner_detail.html'
    check_permission_name = 'owner'
    queryset = CustomUser.objects.all(). \
        prefetch_related('flat_set__house__personalaccount_set')

class RequestsCreateView(account_views.AdminPermissionMixin, CreateView):
    model = Request
    success_url = reverse_lazy('users:requests_list')
    form_class = RequestForm
    check_permission_name = 'application'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['masters'] = CustomUser.objects.filter(~Q(role=None))
        return context

class AjaxUserFlatsList(View):

    @staticmethod
    def get(request, *args, **kwargs):
        owner_id = request.GET.get('owner_id')
        query_flats = Flat.objects.filter(owner=owner_id)
        flat_list = list()
        for flat in query_flats:
            item = {
                'id': flat.id,
                'number': flat.number,
                'house': flat.house.title
            }
            flat_list.append(item)
        return JsonResponse({'flats': flat_list})

class RequestListView(account_views.AdminPermissionMixin, ListView):
    model = Request
    queryset = model.objects.all().select_related('flat__house', 'owner')
    check_permission_name = 'application'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['owners'] = CustomUser.objects.filter(role=None)
        context['masters'] = CustomUser.objects.filter(~Q(role=None)). \
            select_related('role')
        return context

class RequestGetViewAjax(BaseDatatableView):
    model = Request
    columns = ['id', 'date', 'time', 'type_master',
               'description', 'flat', 'flat.house', 'flat.id',
               'owner', 'owner.id', 'owner.phone', 'master',
               'master.id', 'status']
    order_columns = ['id', 'date', 'type_master']

    def get_initial_queryset(self):
        return self.model.objects.all().select_related('flat__house',
                                                       'owner')

    def filter_queryset(self, qs):
        id = self.request.GET.get('id')
        date_range = self.request.GET.get('date_range')
        type_master = self.request.GET['type_master']
        description = self.request.GET.get('description')
        flat = self.request.GET.get('flat')
        owner = self.request.GET.get('owner')
        phone = self.request.GET.get('phone')
        master = self.request.GET.get('master')
        status = self.request.GET.get('status')
        if date_range:
            date_start = datetime.datetime.strptime(date_range.split(' - ')[0],
                                                    '%m/%d/%Y')
            date_end = datetime.datetime.strptime(date_range.split(' - ')[1],
                                                  '%m/%d/%Y')
            qs = qs.filter(Q(date__gt=date_start), Q(date__lt=date_end))
        if id:
            qs = qs.filter(id=id)
        if type_master:
            qs = qs.filter(type_master=type_master)
        if description:
            qs = qs.filter(description__contains=description)
        if flat:
            qs = qs.filter(
                Q(flat__contains=flat) | Q(flat__house__contains=flat))
        if owner:
            qs = qs.filter(owner=owner)
        if phone:
            qs = qs.filter(flat__owner__phone__contains=phone)
        if master:
            qs = qs.filter(master=master)
        if status:
            qs = qs.filter(status=status)
        return qs

class RequestDeleteAjax(DeleteView):

    def post(self, request, *args, **kwargs):
        if request.user.is_superuser or request.user.is_staff:
            request_id = request.POST.get('id')
            request_instance = get_object_or_404(Request, id=request_id)
            request_instance.delete()
            return JsonResponse({'success': 'success'})
        else:
            return JsonResponse(
                {'success': "У Вас недостаточно прав для удаления."}
            )

class RequestDetailView(account_views.AdminPermissionMixin, DetailView):
    model = Request
    check_permission_name = 'application'
    queryset = model.objects.all().select_related('flat__house',
                                                  'owner', 'master')

class RequestUpdateView(account_views.AdminPermissionMixin, UpdateView):
    model = Request
    template_name = 'users/request_update_form.html'
    success_url = reverse_lazy('users:requests_list')
    form_class = RequestForm
    check_permission_name = 'application'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['masters'] = CustomUser.objects.filter(~Q(role=None))
        return context

class MessageListView(account_views.AdminPermissionMixin, ListView):
    model = Message
    check_permission_name = 'message'

    def get_context_data(self, *, object_list=None, **kwargs):
        return {}

class MessageAjaxList(BaseDatatableView):
    model = Message
    columns = ['id', 'title', 'text', 'date',
               'message_address_house_id',
               'message_address_section_id', 'message_address_floor_id',
               'message_address_flat_id']

    def get_initial_queryset(self):
        return self.model.objects.all().order_by('-date')

    def filter_queryset(self, qs):
        search_field = self.request.GET.get('search')
        if search_field:
            qs = qs.filter(Q(title__icontains=search_field)
                           | Q(text__icontains=search_field))
        return qs

class MessageCreateView(account_views.AdminPermissionMixin, CreateView):
    model = Message
    form_class = MessageForm
    template_name = 'users/message_form.html'
    check_permission_name = 'message'

    def post(self, request, *args, **kwargs):
        form_class = self.form_class(request.POST or None)
        if form_class.is_valid():
            form_class.save(commit=False)
            form_class.instance.sender = request.user
            form_class.save()
            users = CustomUser.objects.all().prefetch_related(
                'owner__personal_account__account_flat')
            message_for_deptors = request.POST.get('message_for_deptors')
            if message_for_deptors:
                users = users.filter(flat__personalaccount__balance__lt=0)
            house = request.POST.get('message_address_house_id')
            if house:
                users = users.filter(flat__house=house)
                section = request.POST.get('message_address_section_id')
                if section:
                    users = users.filter(flat__section=section)
                    floor = request.POST.get('message_address_floor_id')
                    if floor:
                        users = users.filter(flat__floor=floor)
                        flat = request.POST.get('message_address_flat_id')
                        if flat:
                            users = users.filter(flat=flat)
            MessageUsers.objects.bulk_create([MessageUsers(
                user=user, message=form_class.instance) for user in users])
            messages.success(request, 'Сообщение отправлено!')
            return HttpResponseRedirect(reverse_lazy('users:message_list'))
        else:
            return render(request, self.template_name, context={
                'form': form_class
            })

class MessageAjaxHouseInfo(View):
    @staticmethod
    def get(request):
        house = request.GET.get('house')
        sections = Section.objects.filter(house_id=house)
        floors = Floor.objects.filter(house_id=house)
        flats = Flat.objects.filter(house_id=house)
        section_list = list()
        floor_list = list()
        flat_list = list()
        for section in sections:
            instance = {
                'id': section.id,
                'title': section.title
            }
            section_list.append(instance)
        for floor in floors:
            instance = {
                'id': floor.id,
                'title': floor.title
            }
            floor_list.append(instance)
        for flat in flats:
            instance = {
                'id': flat.id,
                'title': flat.number
            }
            flat_list.append(instance)
        return JsonResponse({'section': section_list,
                             'floor': floor_list,
                             'flat': flat_list})

class MessageAjaxSectionInfo(View):
    @staticmethod
    def get(request):
        section = request.GET.get('section')
        floor = request.GET.get('floor')
        flats = Flat.objects.filter(section=section)
        if floor:
            flats = flats.filter(floor=floor)
        flat_list = list()
        for flat in flats:
            instance = {
                'id': flat.id,
                'title': flat.number
            }
            flat_list.append(instance)
        return JsonResponse({'flat': flat_list})

class MessageDetailView(account_views.AdminPermissionMixin, DetailView):
    model = Message
    check_permission_name = 'message'

    def get_queryset(self):
        return self.model.objects.filter(sender=self.request.user)

class MessageAjaxDelete(DeleteView):
    model = Message

    def post(self, request, *args, **kwargs):
        if request.user.is_superuser or request.user.is_staff:
            if request.POST.get('id'):
                message = get_object_or_404(Message, id=request.POST.get('id'))
                message.delete()
                return JsonResponse({'success': 'success'})
            messages_id = request.POST.get('deleted_list').split(',')
            messages = self.model.objects.filter(id__in=messages_id)
            messages.delete()
            return JsonResponse({'success': 'success'})
        else:
            return JsonResponse(
                {'success': "У Вас недостаточно прав для удаления."}
            )

class CabinetStatisticView(CabinetPermissionMixin, TemplateView):
    template_name = 'users/cabinet/statistics_for_flat.html'

    def get_context_data(self, **kwargs):
        context = dict()
        flat = get_object_or_404(Flat.objects.filter(owner=self.request.user).
                                 select_related('personal_account'),
                                 id=self.request.GET.get('flat_id'))
        context['personal_account'] = flat.personal_account
        context['flat'] = flat
        month_list = [number for number in range(1, 13)]
        payed_per_month = [Invoice.objects.
                           filter(flat=flat,
                                  date__month=number,
                                  status='Оплачена').
                           aggregate(Sum('amount'))
                           for number in month_list]
        payed_per_month_value = []
        for month in payed_per_month:
            if month.get('amount__sum'):
                payed_per_month_value.append(int(month.get('amount__sum')))
        if payed_per_month_value:
            context['average_per_month'] = sum(payed_per_month_value) / \
                                           len(payed_per_month_value)
        return context

class CabinetInvoicesListView(CabinetPermissionMixin, ListView):
    model = Invoice
    template_name = 'users/cabinet/invoice_users.html'

    def get_queryset(self):
        return self.model.objects.filter(flat__owner=self.request.user)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = dict()
        context['status'] = status_invoice
        if self.request.GET.get('flat_id'):
            context['flat_id'] = self.request.GET.get('flat_id')
        return context

class CabinetInvoicesAjaxList(BaseDatatableView):
    model = Invoice
    columns = ['id', 'number', 'date', 'status', 'amount']
    order_columns = ['date']

    def get_initial_queryset(self):
        flat_id = self.request.GET.get('flat')
        user_id = self.request.GET.get('user')
        qs = self.model.objects.filter(flat__owner=self.request.user)
        if flat_id:
            qs = qs.filter(flat_id=flat_id)
        if user_id:
            qs = qs.filter(flat__owner__id=user_id)
        return qs

    def filter_queryset(self, qs):
        date = self.request.GET.get('date')
        status = self.request.GET.get('status')
        if status:
            qs = qs.filter(status=status)
        if date:
            date_formatting = datetime.datetime.strptime(date, '%m/%d/%Y')
            qs = qs.filter(date=date_formatting)
        return qs

class CabinetInvoicesDetail(CabinetPermissionMixin, DetailView):
    model = Invoice
    template_name = 'users/cabinet/invoice_users_detail.html'

    def get_queryset(self):
        return Invoice.objects.filter(flat__owner=self.request.user). \
            prefetch_related('invoiceservice_set__service__unit')

class CabinetTariffForFlatView(CabinetPermissionMixin, TemplateView):
    model = TariffService
    template_name = 'users/cabinet/tariff_for_flat.html'

    def get_queryset(self):
        qs = get_object_or_404(
            TariffService.objects
            .filter(tariff__flat__owner=self.request.user)
            .select_related(''),
            tariff=self.request.GET.get('flat_id'))
        return qs

    def get_context_data(self, **kwargs):
        context = dict()
        context['object'] = \
            get_object_or_404(Flat.objects.filter(owner=self.request.user)
                              .select_related('house'),
                              id=self.request.GET.get('flat_id'))
        context['tariff_services'] = \
            self.model.objects. \
                filter(tariff__flat=self.request.GET.get('flat_id')). \
                select_related('service__unit')
        return context

class MessageUserList(CabinetPermissionMixin, TemplateView):
    template_name = 'users/cabinet/message_users_list.html'

class MessageUserAjaxList(BaseDatatableView):
    model = MessageUsers
    columns = ['id', 'message.text', 'message.title', 'message.date',
               'message.sender', 'read']

    def get_initial_queryset(self):
        return self.model.objects.filter(user=self.request.user). \
            select_related('message').order_by('-message_id')

    def filter_queryset(self, qs):
        search_field = self.request.GET.get('search')
        if search_field:
            qs = qs.filter(Q(message__title__icontains=search_field)
                           | Q(message__text__icontains=search_field))
        return qs

class MessageUserAjaxDelete(CabinetPermissionMixin, DeleteView):
    model = MessageUsers

    def post(self, request, *args, **kwargs):
        if request.POST.get('id'):
            message = get_object_or_404(MessageUsers.objects
                                        .filter(user=self.request.user),
                                        id=request.POST.get('id'))
            if message.user is request.user:
                message.delete()
                return JsonResponse({'success': 'success'})
            else:
                return JsonResponse({'success': 'Это не ваше сообщение'})
        messages_id = request.POST.get('deleted_list').split(',')
        messages = self.model.objects.filter(id__in=messages_id)
        for message in messages:
            if message.user is request.user:
                message.delete()
        return JsonResponse({'success': 'success'})

class MessageUserDetailView(CabinetPermissionMixin, DetailView):
    template_name = 'users/cabinet/message_user_detail.html'

    def get_queryset(self):
        qs = MessageUsers.objects.filter(user=self.request.user). \
            select_related('message')
        return qs

    def get_context_data(self, **kwargs):
        message = self.object
        if not message.read:
            message.read = True
            message.save()
        return super().get_context_data()

class RequestUserListView(CabinetPermissionMixin, TemplateView):
    template_name = 'users/cabinet/request_user_list.html'

class RequestUserAjaxListView(BaseDatatableView):
    model = Request
    columns = ['id', 'type_master', 'description', 'date', 'time',
               'status']

    def get_initial_queryset(self):
        return self.model.objects.filter(owner_id=self.request.user.id) \
            .order_by('-id')

class RequestUserAjaxDelete(CabinetPermissionMixin, DeleteView):
    model = Request

    def post(self, request, *args, **kwargs):
        master_request_id = request.POST.get('id')
        master_request = get_object_or_404(Request, id=master_request_id)
        if any([master_request.owner is request.user,
                request.user.is_superuser]):
            master_request.delete()
            return JsonResponse({'success': 'success'})
        else:
            return JsonResponse({'success': 'Это не ваш запрос!'})

class RequestUserCreateView(CabinetPermissionMixin, CreateView):
    model = Request
    template_name = 'users/cabinet/request_user_form.html'
    form_class = RequestUserForm

    def post(self, request, *args, **kwargs):
        form_class = self.form_class(request.POST or None)
        if form_class.is_valid():
            form_class.save(commit=False)
            form_class.instance.owner = request.user
            form_class.save()
            return HttpResponseRedirect(
                reverse_lazy('users:request_user_view'))
        else:
            return render(request, self.template_name,
                          context={'form': form_class})

class ProfileUserView(CabinetPermissionMixin, TemplateView):
    template_name = 'users/cabinet/profile_user_view.html'

    def get_context_data(self, **kwargs):
        context = dict()
        context['flats'] = Flat.objects.filter(owner=self.request.user). \
            select_related('floor', 'house', 'section')
        return context

class ProfileUserUpdate(CabinetPermissionMixin, UpdateView):
    template_name = 'users/cabinet/profile_user_update_form.html'
    form_class = OwnerUserForm
    success_url = reverse_lazy('users:user_profile')

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

def confirm_register(request, sign):
    email = signer.unsign((sign))
    user = CustomUser.objects.filter(email=email)
    if user.exists():
        user = user.first()
        user.is_active = True
        user.status = 'Новый'
        user.save()
        return HttpResponseRedirect(reverse_lazy('users:login'))
    else:
        return HttpResponseRedirect(
            f"{reverse_lazy('users:register')}?notconfirm=True")


from sys import exit, argv
import os
import csv
import re

def main():
    if len(argv) != 3:
        print("Usage: python dna.py CSVSTR TXTDNA")
        exit()

    dnaFile = argv[1]
    sequenceFile = argv[2]

    validateFileType(dnaFile, '.csv')
    validateFileType(sequenceFile, '.txt')

    openSequence = open(sequenceFile, 'r')
    sequenceContent = openSequence.read()
    openSequence.close()

    with open(dnaFile, "r") as file:
        csvReader = csv.DictReader(file)
        result = {}
        for row in csvReader:
            result[row['name']] = []
            for key in row:
                if key != "name":
                    if maximumStrRepeats(sequenceContent, key) == str(row[key]):
                        result[row['name']].append(True)
                    else:
                        result[row['name']].append(False)

    finalResult = 'No Match'

    for key in result:
        if all(result[key]):
            finalResult = key

    print(finalResult)

def validateFileType(file, expectedExtension):
    name, extension = os.path.splitext(file)
    if extension != expectedExtension:
        print("Invalid file type")
        exit()

def maximumStrRepeats(sequence, dnaPattern):
    p = rf'({dnaPattern})\1*'
    pattern = re.compile(p)
    match = [match for match in pattern.finditer(sequence)]
    max = 0
    for i in range(len(match)):
        if match[i].group().count(dnaPattern) > max:
            max = match[i].group().count(dnaPattern)
    return str(max)

    '''
    I don't know where it's wrong, ever has 1 of difference in some sequences.txt.
    lengthPattern = len(dnaPattern)
    totalSequence = 0
    maxSequence = 0
    for i in range(len(sequence)):
        if sequence[i : i + lengthPattern] == dnaPattern:
            while sequence[i - lengthPattern : i] == dnaPattern:
                totalSequence += 1
                i+=1
        elif totalSequence > maxSequence:
                    maxSequence = totalSequence
    #print(maxSequence, totalSequence, 'x')
    return str(maxSequence + 1)
    '''

if __name__ == "__main__":
    main()


from tkinter import CASCADE
from .db import db, environment, SCHEMA, add_prefix_for_prod
from datetime import datetime

class Comment(db.Model):
    __tablename__ = 'comments'
    if environment == "production":
        __table_args__ = {'schema': SCHEMA}

    id = db.Column(db.Integer, primary_key=True)
    post_id = db.Column(db.Integer, db.ForeignKey(add_prefix_for_prod('posts.id')), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey(add_prefix_for_prod('users.id')), nullable=False)
    body = db.Column(db.String)
    created_at = db.Column(db.DateTime, default=datetime.now())
    updated_at = db.Column(db.DateTime, default=datetime.now())

    posts = db.relationship('Post', back_populates="comments")
    users = db.relationship('User', back_populates="comments")

    def to_dict(self):
        return {
            "id": self.id,
            "post_id": self.post_id,
            "user_id": self.user_id,
            "body": self.body,
            "createdAt": self.created_at,
            "updatedAt": self.updated_at,
            "user": self.users.to_dict()
        }

    def comment_content(self):
        return {
            "id": self.id,
            "post_id": self.post_id,
            "user_id": self.user_id,
            "body": self.body,
            "createdAt": self.created_at,
            "updatedAt": self.updated_at,
        }


'''Example to illustrate Quantile Regression

Author: Josef Perktold

polynomial regression with systematic deviations above

'''

import numpy as np
import matplotlib.pyplot as plt

from scipy import stats
import statsmodels.api as sm

from statsmodels.regression.quantile_regression import QuantReg

sige = 0.1
nobs, k_vars = 500, 3
x = np.random.uniform(-1, 1, size=nobs)
x.sort()
exog = np.vander(x, k_vars+1)[:,::-1]
mix = 0.1 * stats.norm.pdf(x[:,None], loc=np.linspace(-0.5, 0.75, 4), scale=0.01).sum(1)
y = exog.sum(1) + mix + sige * (np.random.randn(nobs)/2 + 1)**3

p = 0.5
res_qr = QuantReg(y, exog).fit(p)
res_qr2 = QuantReg(y, exog).fit(0.1)
res_qr3 = QuantReg(y, exog).fit(0.75)
res_ols = sm.OLS(y, exog).fit()

params = [res_ols.params, res_qr2.params, res_qr.params, res_qr3.params]
labels = ['ols', 'qr 0.1', 'qr 0.5', 'qr 0.75']

plt.figure()
plt.plot(x, y, '.', alpha=0.5)
for lab, beta in zip(['ols', 'qr 0.1', 'qr 0.5', 'qr 0.75'], params):
    print('%-8s' % lab, np.round(beta, 4))
    fitted = np.dot(exog, beta)
    lw = 2
    plt.plot(x, fitted, lw=lw, label=lab)
plt.legend()
plt.title('Quantile Regression')

plt.show()


import logging
logger = logging.getLogger("webapi")

import socorro.webapi.webapiService as webapi
import socorro.lib.util as util

import collections as col
import functools as ft
import urllib2

class CurrentVersions(webapi.JsonServiceBase):
    def __init__(self, configContext):
        super(CurrentVersions, self).__init__(configContext)
        logger.debug('CurrentVersions __init__')

    # curl 'http://socorro-api/bpapi/current/versions'
    uri = '/current/versions/'

    def get(self, *args):
        convertedArgs = webapi.typeConversion([str], args)
        parameters = util.DotDict(zip(['orderby'], convertedArgs))
        connection = self.database.connection()
        cursor = connection.cursor()

        # use the last date that we have data for as the end
        currentVersions = """
                        /* socorro.services.CurrentVersions currentVersions */
                       SELECT
                           product_name, product_version_id,
                           version_string, is_featured,
                           start_date, end_date, build_type, throttle
                       FROM product_info
                       ORDER BY
                           product_name, version_sort DESC
                       """
        cursor.execute(currentVersions)

        result = []
        for (product, product_id, version, featured, start,
             end, build_type, throttle) in cursor.fetchall():
            releases = {'id': product_id,
                        'product': product,
                        'version': version,
                        'featured': featured,
                        'start_date': str(start),
                        'end_date': str(end),
                        'release': build_type,
                        'throttle': str(throttle) }

            result.append(releases)

        return {'currentversions': result}


import os

def get_key():
    # modify to the directory where the text document containing your key is stored
    # modify to the document's name
    file_dir = r"C:\Users\Osamudiamen\Documents\Vscode Projects"

    file_name = r"\googleAPIkey.txt"

    doc = open(file_dir + file_name, mode='r')
    key = doc.read()
    doc.close()
    return key


while True:
    s=int(input("miktar giriniz:"))
    b=[200,100,50,20,10]

    if s%10==0:
        for i in range (len(b)):
            if s>=b[i]:
                adet=s//b[i]
                s=s%b[i]
                print(f"{adet} adet {b[i]}")
        break
    else:
     print("10'un katını giriniz!!")


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

r"""Implementation of the bi-fidelity Branin function as defined in:

    Dong, H., Song, B., Wang, P. et al. Multi-fidelity information
    fusion based on prediction of kriging. Struct Multidisc Optim
    51, 1267–1280 (2015) doi:10.1007/s00158-014-1213-9

Function definitions:

.. math::

    f_b(x_1, x_2) = \Bigg(x_2 - (5.1\dfrac{x_1^2}{4\pi^2}) + \dfrac{5x_1}{\pi} -
                    6\Bigg)^2 + \Bigg(10\cos(x_1) (1 - \dfrac{1}{8\pi}\Bigg) + 10

.. math::

    f_h(x_1, x_2) = f_b(x_1, x_2) - 22.5x_2

.. math::

    f_l(x_1, x_2) = f_b(0.7x_1, 0.7x_2) - 15.75x_2 + 20(0.9 + x_1)^2 - 50
"""

import numpy as np

from .multi_fidelity_function import MultiFidelityFunction

_four_pi_square = 4*np.pi**2
_eight_pi = 8*np.pi

def branin_base(xx):
    """
    BRANIN FUNCTION

    INPUT:
    xx = [x1, x2]
    """
    xx = np.atleast_2d(xx)

    x1, x2 = xx.T

    term1 = x2 - (5.1 * (x1**2 / _four_pi_square)) + ((5*x1) / np.pi) - 6
    term2 = (10 * np.cos(x1)) * (1 - (1/_eight_pi))

    return term1**2 + term2 + 10

def branin_hf(xx):
    """
    BRANIN FUNCTION, HIGH FIDELITY CODE
    Calls: branin_base
    This function, from Dong et al. (2015), is used as the "high-accuracy code"
    version of the function based on the 'traditional' branin function.

    INPUT:
    xx = [x1, x2]
    """
    xx = np.atleast_2d(xx)

    _, x2 = xx.T
    return branin_base(xx) - 22.5*x2

def branin_lf(xx):
    """
    BRANIN FUNCTION, LOWER FIDELITY CODE
    Calls: branin_base
    This function, from Dong et al. (2015), is used as the "low-accuracy code"
    version of the function branin_hf.

    INPUT:
    xx = [x1, x2]
    """
    xx = np.atleast_2d(xx)

    x1, x2 = xx.T

    term1 = branin_base(np.hstack([0.7*x1.reshape(-1,1), 0.7*x2.reshape(-1,1)]))
    term2 = 15.75*x2
    term3 = 20*(.9+x1)**2
    term4 = 50

    return term1 - term2 + term3 - term4

#: Lower bound for Branin function
l_bound = [-5,  0]
#: Upper bound for Branin function
u_bound = [10, 15]

x_opt = [-3.786088705282203, 15]

#: 2D Branin function with fidelities 'high' and 'low'
branin = MultiFidelityFunction(
    "branin",
    u_bound, l_bound,
    [branin_hf, branin_lf],
    fidelity_names=['high', 'low'],
    x_opt=x_opt,
)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This script is to merge all the Blast files into one file named blastfile.txt

import os

mergefiledir = os.getcwd()
# print(mergefiledir)

filenames = os.listdir(mergefiledir)
print(filenames)

file = open('blastfile.txt', 'w')

for filename in filenames :
	if filename.startswith('gain_OG') :
		print(filename)
		filepath = mergefiledir+'/'+filename
		print(filepath)
		for line in open(filepath) :
			file.writelines(line)
		# file.write('\n')

file.close()