# -*- coding: utf-8 -*-
#Pour plus d'informations, lisez le README.md sur notre page GitHub : https://github.com/Meteoriix/Sniper-VS-Thief
#JEU
import random
import pygame
import csv
from random import *
from pygame import *
from tkinter import *
from tkinter import messagebox

#Initialisations
x = 0
y = 0
tour = 0 #Tour = 0 = Tour voleur / Tour = 1 = Tour Sniper
Tk().wm_withdraw()

#Fonction de création des index de chaque case
def indexfind(index):
    y = index // 13 * 99
    x = (index * 99) - (1287 * (y/99))
    return([x,y])

#Fonction de sauvegarde dans le CSV
def saveincsv():
    with open("gamedata.csv", "w") as output:
        character_writer = csv.DictWriter(output, fieldnames=["A","B"])
        character_writer.writerow({"A" : "A", "B" : "B"})
        character_writer.writerow({"A" : "current", "B" : voleurindex})
        character_writer.writerow({"A" : "old", "B" : oldindex})

#Initalisation de PyGame
pygame.init()

#Fenêtre PyGame (Dimensions : 1278x684)
fenetre = pygame.display.set_mode((1278, 684))
pygame.display.set_caption("Sniper VS Thief")
icon = pygame.image.load("assets/images/diamond.png")
pygame.display.set_icon(icon)

#Génération aléatoire du plateau
MAP = []
walls = [0,13,26,39,52,65,78,12,25,38,51,64,77,90]

for row in range (0,7): #nombre de lignes
    for columns in range(0,13): #nombre de colonnes
        #Génération aléatoire des obstacles
        if (row * 13 + columns) in walls:
            obstacle = pygame.image.load("assets/images/obstacle.png")
            fenetre.blit(obstacle, (x, y))
            MAP.append(1)
        else:
            casetype = randint(1,5)
            if (columns != 1 or row != 3):
                if (columns != 11 or row != 3):
                    if casetype == 1:
                        obstacle = pygame.image.load("assets/images/obstacle.png")
                        fenetre.blit(obstacle, (x, y))
                        MAP.append(1)
                    elif casetype !=1:
                        case = pygame.image.load("assets/images/case.png")
                        fenetre.blit(case, (x, y))
                        casepos = case.get_rect()
                        MAP.append(0)
                else:
                    case = pygame.image.load("assets/images/case.png")
                    fenetre.blit(case, (x, y))
                    casepos = case.get_rect()
                    MAP.append(0)
            else:
                case = pygame.image.load("assets/images/case.png")
                fenetre.blit(case, (x, y))
                casepos = case.get_rect()
                MAP.append(0)
        x += 99
    x = 0
    y += 99
y = 0
for i in range (13):
    MAP.append(1)

#Chargement des images
diamond = pygame.image.load("assets/images/diamond.png").convert_alpha()
valid = pygame.image.load("assets/images/valid.png")
maybe = pygame.image.load("assets/images/maybe.png")
voleur = pygame.image.load("assets/images/voleur.png").convert_alpha()
oldvoleur = pygame.image.load("assets/images/oldvoleur.png").convert_alpha()
voleurindex = 40
oldindex = voleurindex
saveincsv()

#Chargement du sélecteur
selector = pygame.image.load("assets/images/selecteur.png")
selindex = 40
selpos = selector.get_rect()
selpos = selpos.move(indexfind(40))

IndexMatrice = {0 : -1 ,1 : -13,2 : 1,3 : 13,4 : 0,}

#Actualisation de la fenêtre
pygame.display.flip()

#BOUCLE PRINCIPALE
gameloop = 1 #Variable de la boucle de jeu
while gameloop: #Lancement de la boucle de jeu
    for event in pygame.event.get(): #Lancement des évènements
        #Fermeture améliorée de la fenêtre
        if event.type == QUIT:
            gameloop = 0
            pygame.quit()

        if event.type == KEYDOWN and event.key == K_LEFT: #Déplacement du selecteur vers la gauche
            if selpos.x != 0: #Vérification de la présence d'une bordure
                if MAP[selindex+ IndexMatrice.get(0)] == 0:
                    fenetre.blit(case, indexfind(selindex))
                    selpos = selpos.move(-99, 0)
                    selindex = selindex + IndexMatrice.get(0)

        if event.type == KEYDOWN and event.key == K_RIGHT: #Déplacement du sélecteur vers la droite
            if selpos.x < 1179: #Vérification de la présence d'une bordure
                if MAP[selindex+ IndexMatrice.get(2)] == 0:
                    fenetre.blit(case, indexfind(selindex))
                    selpos = selpos.move(99, 0)
                    selindex = selindex + IndexMatrice.get(2)

        if event.type == KEYDOWN and event.key == K_DOWN: #Déplacement du sélecteur vers le bas
            if selpos.y < 585: #Vérification de la présence d'une bordure
                if MAP[selindex+ IndexMatrice.get(3)] == 0:
                    fenetre.blit(case, indexfind(selindex))
                    selpos = selpos.move(0, 99)
                    selindex = selindex + IndexMatrice.get(3)

        if event.type == KEYDOWN and event.key == K_UP: #Déplacement du sélecteur vers le haut
            if selpos.y != 0: #Vérification de la présence d'une bordure
                if MAP[selindex+ IndexMatrice.get(1)] == 0:
                    fenetre.blit(case, indexfind(selindex))
                    selpos = selpos.move(0, -99)
                    selindex = selindex + IndexMatrice.get(1)

        if event.type == KEYDOWN and event.key == pygame.K_RETURN: #Validation du tour
            if tour == 0: #Validation du tour du Voleur
                if(selindex == 50): #Victoire du Voleur
                    messagebox.showinfo('Fin de partie','Le voleur a gagné')
                    gameloop = 0
                    pygame.quit()
                    exec(open("menu_end.py").read())
                else: #Passage au tour du Sniper
                    tour = 1
                    messagebox.showinfo('Tour suivant', "C'est au tour du Sniper")
                    if selindex in validcases:
                        input_file = csv.DictReader(open("gamedata.csv"))
                        for row in input_file:
                            old_type = row["A"]
                            csvindex = row["B"]
                            if old_type == "current":
                                oldindex = int(csvindex)
                        voleurindex = selindex
                        saveincsv()
                        selpos.x = 0
                        selpos.y = 0
                        selpos = selpos.move(indexfind(oldindex))
                        selindex = oldindex
                        for a in validcases:
                            fenetre.blit(case, indexfind(a))

            elif tour == 1: #Validation du tour du Sniper
                if selindex == voleurindex: #Victoire du Sniper
                    messagebox.showinfo('Fin de partie','Le sniper a gagné')
                    gameloop = 0
                    pygame.quit()
                    exec(open("menu_end.py").read())
                else: #Passage au tour du Voleur
                    if selindex in validcases:
                        tour = 0
                        selpos.x = 0
                        selpos.y = 0
                        selpos = selpos.move(indexfind(oldindex))
                        selindex = oldindex
                        messagebox.showinfo('Tour suivant', "C'est au tour du Voleur")
                        for a in validcases:
                            fenetre.blit(case, indexfind(a))

    validcases = []

    if tour == 0: #Affichage des cases possibles pour le voleur
        for u in range(0,5):
            if voleurindex + IndexMatrice.get(u) < -1 :
                validcases.append(voleurindex+ IndexMatrice.get(u))
            elif MAP[voleurindex+ IndexMatrice.get(u)] == 0:
                fenetre.blit(valid,indexfind(voleurindex+ IndexMatrice.get(u)))
                validcases.append(voleurindex+ IndexMatrice.get(u))
        fenetre.blit(diamond, indexfind(50))
        fenetre.blit(selector, indexfind(selindex))
        fenetre.blit(voleur, indexfind(voleurindex))

    if tour == 1: #Affichage des cases possibles pour le sniper
        for u in range(0,5):
            if oldindex + IndexMatrice.get(u) < -1 :
                validcases.append(oldindex+ IndexMatrice.get(u))
            elif MAP[oldindex+ IndexMatrice.get(u)] == 0:
                fenetre.blit(maybe,indexfind(oldindex+ IndexMatrice.get(u)))
                validcases.append(oldindex+ IndexMatrice.get(u))
        fenetre.blit(diamond, indexfind(50))
        fenetre.blit(selector, indexfind(selindex))
        fenetre.blit(oldvoleur, indexfind(oldindex))

    pygame.display.update()
    pygame.display.flip()


class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        cur=gas[0]-cost[0]
        res=0
        min=cur
        if sum(gas)<sum(cost):
            return -1
        else:
            for i in range(1,len(gas)):
                cur=cur+gas[i]-cost[i]
                if cur<min:
                    min=cur
                    res=i
            if res==len(gas)-1:
                return 0
            else:
                return res+1


import numpy as np
import torch
import cv2

print("PyTorch version:", torch.__version__)
print("CUDA version:", torch.version.cuda)
print("cuDNN version:", torch.backends.cudnn.version())

gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

import matplotlib.pyplot as plt
import matplotlib.patches as patches

def plot_detections(img, detections, with_keypoints=True):
    fig, ax = plt.subplots(1, figsize=(10, 10))
    ax.grid(False)
    ax.imshow(img)

    if isinstance(detections, torch.Tensor):
        detections = detections.cpu().numpy()

    if detections.ndim == 1:
        detections = np.expand_dims(detections, axis=0)

    print("Found %d faces" % detections.shape[0])

    for i in range(detections.shape[0]):
        ymin = detections[i, 0] * img.shape[0]
        xmin = detections[i, 1] * img.shape[1]
        ymax = detections[i, 2] * img.shape[0]
        xmax = detections[i, 3] * img.shape[1]

        rect = patches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,
                                 linewidth=1, edgecolor="r", facecolor="none",
                                 alpha=detections[i, 16])
        ax.add_patch(rect)

        if with_keypoints:
            for k in range(6):
                kp_x = detections[i, 4 + k*2    ] * img.shape[1]
                kp_y = detections[i, 4 + k*2 + 1] * img.shape[0]
                circle = patches.Circle((kp_x, kp_y), radius=0.5, linewidth=1,
                                        edgecolor="lightskyblue", facecolor="none",
                                        alpha=detections[i, 16])
                ax.add_patch(circle)

    plt.show()

from blazeface import BlazeFace

net = BlazeFace().to(gpu)
net.load_weights("blazeface.pth")
net.load_anchors("anchors.npy")

# Optionally change the thresholds:
net.min_score_thresh = 0.75
net.min_suppression_threshold = 0.3

img = cv2.imread("test.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

detections = net.predict_on_image(img)
detections.shape

plot_detections(img, detections)


# Copyright Facebook, Inc. and its affiliates., UWr 2021
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import math
import logging
import os
import sys
import numpy as np

import torch
import torch.nn.functional as F
import torchaudio.compliance.kaldi as tk
import torchaudio.functional as AF

from .. import FairseqDataset
from . import raw_audio_dataset

logger = logging.getLogger(__name__)

class SpeechFeaturesDataset(FairseqDataset):
    def __init__(
        self,
        manifest_path,
        sample_rate,
        transform='fbank',
        transform_kwargs=None,
        add_deltas=True,
        max_sample_size=None,
        min_sample_size=None,
        shuffle=True,
        min_length=0,
        pad=False,
        pad_to_multiples_of=None,
        normalize=False,
    ):
        super().__init__()
        if transform_kwargs is None:
            transform_kwargs = {}
        else:
            transform_kwargs = dict(transform_kwargs)

        if transform_kwargs.get('sample_frequency', sample_rate) != sample_rate:
            logging.warn("Reseting sample frequency")
        transform_kwargs['sample_frequency'] = sample_rate
        transform_kwargs.setdefault('frame_shift', 10.0)
        stride = sample_rate * transform_kwargs['frame_shift'] * 1e-3

        self.fnames = []
        self.sample_rate = sample_rate
        self.sizes = []
        self.max_sample_size = (
            max_sample_size if max_sample_size is not None else sys.maxsize
        )
        self.min_sample_size = min_sample_size
        self.min_length = min_length
        self.pad = pad
        self.pad_to_multiples_of = pad_to_multiples_of
        self.add_deltas = add_deltas
        self.shuffle = shuffle
        self.normalize = normalize

        skipped = 0
        with open(manifest_path, "r") as f:
            self.root_dir = f.readline().strip()
            for line in f:
                items = line.strip().split("\t")
                assert len(items) == 2, line
                sz = int(math.ceil(int(items[1]) / stride))
                if min_length is not None and sz < min_length:
                    skipped += 1
                    continue
                self.fnames.append(items[0])
                self.sizes.append(sz)
        logger.info(f"{manifest_path}: loaded {len(self.fnames)}, skipped {skipped} samples")

        self.transform = getattr(tk, transform)
        self.transform_kwargs = transform_kwargs

    def __len__(self):
        return len(self.sizes)

    def postprocess(self, feats):
        if self.normalize:
            with torch.no_grad():
                # Normalize only across time
                feats = F.layer_norm(feats, feats.shape[-1:])
        return feats

    def __getitem__(self, index):
        import soundfile as sf

        fname = os.path.join(self.root_dir, self.fnames[index])
        wav, curr_sample_rate = sf.read(fname)
        if curr_sample_rate != self.sample_rate:
            raise Exception(f"sample rate: {curr_sample_rate}, need {self.sample_rate}")

        feats = torch.from_numpy(wav).float()
        if feats.dim() == 2:
            feats = feats.mean(-1)
        feats = feats.unsqueeze(0)  # C=1,L

        feats = self.transform(feats, **self.transform_kwargs)
        feats = feats.transpose(0, 1)  # Nmels  x Len
        feats = feats.unsqueeze(0)  # 1 x Nmels x Len

        if self.add_deltas:
            deltas = AF.compute_deltas(feats)
            ddeltas = AF.compute_deltas(deltas)
            feats = torch.cat([feats, deltas, ddeltas], dim=0)

        feats = self.postprocess(feats)
        return {"id": index, "source": feats}

    def crop_to_max_size(self, wav, target_size):
        size = wav.shape[2]
        diff = size - target_size
        if diff <= 0:
            return wav

        if self.shuffle:
            start = np.random.randint(0, diff + 1)
        else:
            # Deterministically pick the middle part
            start = (diff + 1) //2
        end = size - diff + start
        return wav[:, :, start:end]

    def collater(self, samples):
        samples = [s for s in samples if s["source"] is not None]
        if len(samples) == 0:
            return {}

        sources = [s["source"] for s in samples]
        sizes = [s.shape[2] for s in sources]
        heigths = [s.shape[1] for s in sources]
        chans = [s.shape[0] for s in sources]

        assert all([h==heigths[0] for h in heigths])
        assert all([h==chans[0] for h in chans])

        pad_to_multiples_of = self.pad_to_multiples_of
        if self.pad:
            target_size = min(max(sizes), self.max_sample_size)
            if pad_to_multiples_of:
                # round up to pad_to_multiples_of
                target_size = ((target_size + pad_to_multiples_of - 1) // pad_to_multiples_of) * pad_to_multiples_of
        else:
            target_size = min(min(sizes), self.max_sample_size)
            if pad_to_multiples_of:
                # round down to pad_to_multiples_of
                target_size = (target_size // pad_to_multiples_of) * pad_to_multiples_of

        collated_sources = sources[0].new_zeros((len(sources), chans[0], heigths[0], target_size))
        pad_shape = [len(sources), 1, target_size]
        padding_mask = (
            torch.BoolTensor(size=pad_shape).fill_(False) if self.pad else None
        )
        for i, (source, size) in enumerate(zip(sources, sizes)):
            diff = size - target_size
            if diff == 0:
                collated_sources[i] = source
            elif diff < 0:
                assert self.pad
                collated_sources[i] = torch.cat(
                    [source, source.new_full((chans[0], heigths[0], -diff,), 0.0)],
                    dim=2
                )
                padding_mask[i, :, diff:] = True
            else:
                collated_sources[i] = self.crop_to_max_size(source, target_size)

        input = {"source": collated_sources}
        if self.pad:
            input["padding_mask"] = padding_mask
        return {"id": torch.LongTensor([s["id"] for s in samples]), "net_input": input}

    def num_tokens(self, index):
        return self.size(index)

    def size(self, index):
        """Return an example's size as a float or tuple. This value is used when
        filtering a dataset with ``--max-positions``."""
        if self.pad:
            return self.sizes[index]
        return min(self.sizes[index], self.max_sample_size)

    def ordered_indices(self):
        """Return an ordered list of indices. Batches will be constructed based
        on this order."""

        if self.shuffle:
            order = [np.random.permutation(len(self))]
        else:
            order = [np.arange(len(self))]

        order.append(self.sizes)
        return np.lexsort(order)[::-1]


import queue
q = queue.Queue()

class BinaryTreeNode:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None

def printTreelevelOrder(root):

    if root is None:
        return

    q.put(root)
    q.put('null')

    while q.empty() is False:
        curr = q.get()

        if q.empty():
            break

        if curr == 'null':
            print()
            q.put('null')
        else:
            print(curr.data,end=' ')

            if curr.left != None:
                q.put(curr.left)

            if curr.right != None:
                q.put(curr.right)

def takeinputLevelwise(l):

    if len(l) == 0:
        return

    rootdata = l[0]
    del l[0]
    if rootdata == -1:
        return None
    root = BinaryTreeNode(rootdata)
    q.put(root)

    while not q.empty():
        curr = q.get()

        currleft = l[0]
        del l[0]
        currright = l[0]
        del l[0]

        if currleft != -1:
            curr.left = BinaryTreeNode(currleft)
            q.put(curr.left)
        if currright != -1:
            curr.right = BinaryTreeNode(currright)
            q.put(curr.right)

    return root

inputlist = [int(ele) for ele in input().split()]
root = takeinputLevelwise(inputlist)
printTreelevelOrder(root)


#!/usr/bin/env pypy

with open('proxy.pac', 'r') as f:
    content = f.read()

assert "'" not in content
from slimit import minify
#content = content.strip('\r\n')
content = minify(content, mangle=True)
assert "\n" not in content

content = "var naive_pac_data = '" + content + "';"

with open('pac_data.js', 'w') as f:
    f.write(content)


"""
Python code snippets vol 34:
Windows only
168-What browsers are installed
stevepython.wordpress.com

Source:
https://programtalk.com/python-examples/winreg.HKEY_LOCAL_MACHINE/?ipage=3
"""
import winreg

def find_windows_browsers():
    """ Access the windows registry to determine
    what browsers are on the system.
    """
    HKLM = winreg.HKEY_LOCAL_MACHINE
    subkey = r'Software\Clients\StartMenuInternet'
    read32 = winreg.KEY_READ | winreg.KEY_WOW64_32KEY
    read64 = winreg.KEY_READ | winreg.KEY_WOW64_64KEY
    key32 = winreg.OpenKey(HKLM, subkey, access=read32)
    key64 = winreg.OpenKey(HKLM, subkey, access=read64)

    # Return a list of browsers found in the registry
    # Check if there are any different browsers in the
    # 32 bit location instead of the 64 bit location.
    browsers = []
    i = 0
    while True:
        try:
            browsers.append(winreg.EnumKey(key32, i))
        except EnvironmentError:
            break
        i += 1

    i = 0
    while True:
        try:
            browsers.append(winreg.EnumKey(key64, i))
        except EnvironmentError:
            break
        i += 1

    winreg.CloseKey(key32)
    winreg.CloseKey(key64)
    print(browsers)
    return browsers

find_windows_browsers()

Python-code-snippets-101-200/168-what browsers are on the system.py


'''
MONTHS PROGRAM
--------------
Write a user-input statement where a user enters a month number 1-12.
Using the starting string below in your program, print the three month abbreviation
for the month number that the user enters. Keep repeating this until the user enters a non 1-12 number to quit.
Once the user quits, print "Goodbye!"

months = "JanFebMarAprMayJunJulAugSepOctNovDec"
'''
userinput = 1
while userinput <= 12 and userinput>0:
    userinput = int(input("Enter the number of the month youd like to abbreviate"))
    months = "JanFebMarAprMayJunJulAugSepOctNovDec"
    print("The abbreviation for that month is:", months[(userinput * 3)-3:userinput * 3])
print("Goodbye!")


#!/usr/bin/python
"""
Test Cases for the CyberQInterface Library

ChangeLog:
A00 - 11/04/2012 - Bryan Kemp - Initial release
"""

__author__ = "Bryan Kemp <bryan@thebrilliantidea.com>"
__version__ = "A00"
__date__ = '11/04/2012'
__license__ = "BSD New"
__license_text__ = """
Copyright (c) 2012, The Brilliant Idea
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the The Brilliant Idea, LLC. nor the names of its contributors may
   be used to endorse or promote products derived from this software without
   specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import unittest
import requests
from mock import patch
from cyberqinterface.cyberqinterface import CyberQInterface
from cyberqinterface.cyberqinterface_exceptions import *
TestCyberQInterfaceSuite = unittest.TestLoader()

class TestCyberQInterfaceInit(unittest.TestCase):
    """Test that the initializer works and gets all of the needed variables"""
    def setUp(self):
        pass

    def tearDown(self):
        """None"""
        pass

    def testProperInit(self):
        """Test host property is set to proper value"""
        cqi = CyberQInterface("localhost")
        self.assertEqual(cqi.host, "localhost")

    def testInitWithHeaders(self):
        """Test supplying custom headers"""
        cqi = CyberQInterface("localhost", {"Test-Header": "Test"})
        self.assertEqual(cqi.headers["Test-Header"], "Test")

TestCyberQInterfaceSuite.loadTestsFromTestCase(TestCyberQInterfaceInit)

class TestCyberQInterfaceValidateParameters(unittest.TestCase):
    """Test to make sure that the validate parameters function is working"""
    def setUp(self):
        """Setup: None"""

    def tearDown(self):
        """TearDown: None"""
        pass

    def testAllParameters(self):
        """Test the full set of parameters are correct"""
        cqi = CyberQInterface("127.0.0.1")
        assert cqi._validateParameters( {"COOK_NAME": 1, "COOK_SET": 1,
                                         "FOOD1_NAME": 1, "FOOD1_SET": 1,
                                         "FOOD2_NAME": 1, "FOOD2_SET": 1,
                                         "FOOD3_NAME": 1, "FOOD3_SET": 1,
                                         "_COOK_TIMER": 1, "COOK_TIMER": 1,
                                         "COOKHOLD": 1, "TIMEOUT_ACTION": 1,
                                         "ALARMDEV": 1, "COOK_RAMP": 1,
                                         "OPENDETECT": 1, "CYCTIME": 1,
                                         "PROPBAND": 1, "MENU_SCROLLING": 1,
                                         "LCD_BACKLIGHT": 1, "LCD_CONTRAST": 1,
                                         "DEG_UNITS": 1, "ALARM_BEEPS": 1,
                                         "KEY_BEEPS": 1}) == {}

    def testBadParameters(self):
        """Test parameters with 3 bad parameters"""
        cqi = CyberQInterface("127.0.0.1")
        assert len(cqi._validateParameters( {"COK_NAME": 1, "COOK_SET": 1,
                                             "FOOD1_NAME": 1, "FOOD1_SET": 1,
                                             "FOOD2_NAME": 1, "FOOD2_SET": 1,
                                             "FOOD3_NAME": 1, "FOOD3_SET": 1,
                                             "_COOK_TIMER": 1, "COOK_TIMER": 1,
                                             "COOKHOLD": 1, "TIEOUT_ACTION": 1,
                                             "ALARMDEV": 1, "COOK_RAMP": 1,
                                             "OPENDETECT": 1, "CYCTIME": 1,
                                             "PROPBAND": 1, "MNU_SCROLLING": 1,
                                             "LCD_BACKLIGHT": 1,
                                             "LCD_CONTRAST": 1, "DEG_UNITS": 1,
                                             "ALARM_BEEPS": 1,
                                             "KEY_BEEPS": 1})) == 3
TestCyberQInterfaceSuite.loadTestsFromTestCase(
    TestCyberQInterfaceValidateParameters)

class TestCyberQInterfaceRequests(unittest.TestCase):
    """
    Test the interaction with the CyberQ web interface and XML to object
    translation
    """

    def setUp(self):
        """Setup: None"""

    def tearDown(self):
        """TearDown: None"""

    def testInvalidReturnCode(self):
        """
        Test that the proper exception is thrown if the server returns bad
        status code
        """
        with patch.object(requests, 'get') as mockMethod:
            with self.assertRaises(ResponseHTTPException):
                cqi = CyberQInterface("127.0.0.1")
                mockMethod.return_value.status_code = 500
                cqi.getConfigXML()

    def testValidReturnCode(self):
        """Test that a 200 code returns a string"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = "testcase"
            xml = CyberQInterface("127.0.0.1").getConfigXML()
            self.assertEqual(xml, "testcase")

    def testGetStatusWithBadXML(self):
        """Test that the correct Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            with self.assertRaises(ResponseValidationException):
                mockMethod.return_value.status_code = 200
                mockMethod.return_value.text = """
<nutcstatus>
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<COOK_TEMP>3343</COOK_TEMP>
<FOOD1_TEMP>823</FOOD1_TEMP>
<FOOD2_TEM2_TEMP>
<FOOD3_TEMP>OPEN</FOOD3_TEMP>
<COOK_STATUS>0</COOKTUS>
<FOOD1_STATUS>0</FOOD1_STATUS>
<FOOD2_STATUS>4</FOOD2_STATUS>
<FOOD3_STATUS>4</FOOD3_STATUS>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcstatus>"""
                CyberQInterface("127.0.0.1").getStatus()

    def testGetStatus(self):
        """Test that the correct Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = """
<nutcstatus>
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<COOK_TEMP>3343</COOK_TEMP>
<FOOD1_TEMP>823</FOOD1_TEMP>
<FOOD2_TEMP>OPEN</FOOD2_TEMP>
<FOOD3_TEMP>OPEN</FOOD3_TEMP>
<COOK_STATUS>0</COOK_STATUS>
<FOOD1_STATUS>0</FOOD1_STATUS>
<FOOD2_STATUS>4</FOOD2_STATUS>
<FOOD3_STATUS>4</FOOD3_STATUS>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcstatus>"""
            status = CyberQInterface("127.0.0.1").getStatus()
            self.assertEqual(status.tag, "nutcstatus")

    def testGetAll(self):
        """Test that the All Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            with self.assertRaises(AttributeError):
                mockMethod.return_value.status_code = 200
                mockMethod.return_value.text = """
<nutcallstatus>
<!--this is similar to status.xml, but with more values-->
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<COOK>
  <COOK_NAME>Big Green Egg</COOK_NAME>
  <COOK_TEMP>3216</COOK_TEMP>
  <COOK_SET>4000</COOK_SET>
  <COOK_STATUS>0</COOK_STATUS>
</COOK>
<FOOD1>
  <FOOD1_NAME>Chicken Quarters</FOOD1_NAME>
  <FOOD1_TEMP>1482</FOOD1_TEMP>
  <FOOD1_SET>1750</FOOD1_SET>
  <FOOD1_STATUS>0</FOOD1_STATUS>
</FOOD1>
<FOOD2>
  <FOOD2_NAME>Food2</FOOD2_NAME>
  <FOOD2_TEMP>OPEN</FOOD2_TEMP>
  <FOOD2_SET>1000</FOOD2_SET>
  <FOOD2_STATUS>4</FOOD2_STATUS>
</FOOD2>
<FOOD3>
  <FOOD3_NAME>Food3</FOOD3_NAME>
  <FOOD3_TEMP>OPEN</FOOD3_TEMP>
  <FOOD3_SET>1000</FOOD3_SET>
  <FOOD3_STATUS>4</FOOD3_STATUS>
</FOOD3>
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcallstatus>
"""
                allObj = CyberQInterface("127.0.0.1").getAll()
                self.assertNotEqual(allObj.CONTROL.OPENDETECT, 1)

    def testGetConfig(self):
        """Test that the config Object is returned"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = """
<nutcallstatus>
<!--this is similar to all.xml, but with more values-->
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<COOK>
  <COOK_NAME>Big Green Egg</COOK_NAME>
  <COOK_TEMP>3220</COOK_TEMP>
  <COOK_SET>4000</COOK_SET>
  <COOK_STATUS>0</COOK_STATUS>
</COOK>
<FOOD1>
  <FOOD1_NAME>Chicken Quarters</FOOD1_NAME>
  <FOOD1_TEMP>1493</FOOD1_TEMP>
  <FOOD1_SET>1750</FOOD1_SET>
  <FOOD1_STATUS>0</FOOD1_STATUS>
</FOOD1>
<FOOD2>
  <FOOD2_NAME>Food2</FOOD2_NAME>
  <FOOD2_TEMP>OPEN</FOOD2_TEMP>
  <FOOD2_SET>1000</FOOD2_SET>
  <FOOD2_STATUS>4</FOOD2_STATUS>
</FOOD2>
<FOOD3>
  <FOOD3_NAME>Food3</FOOD3_NAME>
  <FOOD3_TEMP>OPEN</FOOD3_TEMP>
  <FOOD3_SET>1000</FOOD3_SET>
  <FOOD3_STATUS>4</FOOD3_STATUS>
</FOOD3>
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<TIMER_STATUS>0</TIMER_STATUS>
<SYSTEM>
  <MENU_SCROLLING>1</MENU_SCROLLING>
  <LCD_BACKLIGHT>47</LCD_BACKLIGHT>
  <LCD_CONTRAST>10</LCD_CONTRAST>
  <DEG_UNITS>1</DEG_UNITS>
  <ALARM_BEEPS>0</ALARM_BEEPS>
  <KEY_BEEPS>0</KEY_BEEPS>
</SYSTEM>
<CONTROL>
  <TIMEOUT_ACTION>0</TIMEOUT_ACTION>
  <COOKHOLD>2000</COOKHOLD>
  <ALARMDEV>500</ALARMDEV>
  <COOK_RAMP>0</COOK_RAMP>
  <OPENDETECT>1</OPENDETECT>
  <CYCTIME>6</CYCTIME>
  <PROPBAND>500</PROPBAND>
</CONTROL>
<WIFI>
  <IP>10.0.1.30</IP>
  <NM>255.255.255.0</NM>
  <GW>10.0.1.1</GW>
  <DNS>10.0.1.1</DNS>
  <WIFIMODE>0</WIFIMODE>
  <DHCP>0</DHCP>
  <SSID>Wireless Network</SSID>
  <WIFI_ENC>6</WIFI_ENC>
  <WIFI_KEY>SsecretKey</WIFI_KEY>
  <HTTP_PORT>80</HTTP_PORT>
</WIFI>
<SMTP>
  <SMTP_HOST>smtp.hostname.com</SMTP_HOST>
  <SMTP_PORT>0</SMTP_PORT>
  <SMTP_USER></SMTP_USER>
  <SMTP_PWD></SMTP_PWD>
  <SMTP_TO>destination@someplace.com</SMTP_TO>
  <SMTP_FROM>source@someplace.com</SMTP_FROM>
  <SMTP_SUBJ>Temperature Controller Status E-Mail</SMTP_SUBJ>
  <SMTP_ALERT>0</SMTP_ALERT>
</SMTP>
</nutcallstatus>
"""
            configObj = CyberQInterface("127.0.0.1").getConfig()
            self.assertEqual(configObj.CONTROL.OPENDETECT, 1)

    def testSendUpdate(self):
        """
        Test the ability to send a message to the CyberQ with good parameters
        """
        with patch.object(requests, 'post') as mockMethod:
            mockMethod.return_value.status_code = 200
            cqi = CyberQInterface("127.0.0.1")
            self.assertEqual(cqi.sendUpdate({'FOOD1_NAME' : "Tri-Tip Roast",
                                             'FOOD1_SET': '140',
                                             'COOK_SET' : '300'}),True)

    def testSendUpdateWithBadParameters(self):
        """
        Test the ability to send a message to the CyberQ with bad parameters
        """
        with patch.object(requests, 'post') as mockMethod:
            with self.assertRaises(ParameterValidationException):
                mockMethod.return_value.status_code = 200
                cqi = CyberQInterface("127.0.0.1")
                cqi.sendUpdate({'FOOD1_NME' : "Tri-Tip Roast",
                                'FOOD1_SET': '140', 'COOK_SET' : '300'})

    def testSendUpdateWithBadResponse(self):
        """
        Test the ability to send a message to the CyberQ with good parameters
        but a bad response
        """
        with patch.object(requests, 'post') as mockMethod:
            with self.assertRaises(ResponseHTTPException):
                mockMethod.return_value.status_code = 500
                cqi = CyberQInterface("127.0.0.1")
                cqi.sendUpdate({'FOOD1_NAME' : "Tri-Tip Roast",
                                'FOOD1_SET': '140', 'COOK_SET' : '300'})

TestCyberQInterfaceSuite.loadTestsFromTestCase(TestCyberQInterfaceRequests)

class TestCyberQInterfaceLookups(unittest.TestCase):
    """Test the lookup functionality for temperature, status, and ramp"""
    def setUp(self):
        """Setup: None"""
        pass

    def tearDown(self):
        """TearDown: None"""
        pass

    def testRampLookups(self):
        """Test that all known ramp codes work"""
        cqi = CyberQInterface("127.0.0.1")
        rampCodes = ["OFF", "FOOD1", "FOOD2", "FOOD3"]
        for code in range (0, len(rampCodes)-1):
            self.assertEqual(cqi.rampLookup(code), rampCodes[code])

    def testStatusLookups(self):
        """Test that all known status codes work"""
        cqi = CyberQInterface("127.0.0.1")
        statusCodes = ["OK", "HIGH", "LOW", "DONE", "ERROR", "HOLD", "ALARM",
                      "SHUTDOWN"]
        for code in range (0, len(statusCodes)-1):
            self.assertEqual(cqi.statusLookup(code), statusCodes[code])

    def testTemperatureLookups(self):
        """Test that all known temperature codes work"""
        cqi = CyberQInterface("127.0.0.1")
        temperatureCodes = ["CELSIUS", "FAHRENHEIT"]
        for code in range (0, len(temperatureCodes)-1):
            self.assertEqual(cqi.temperatureLookup(code),
                             temperatureCodes[code])

    def testBadTableName(self):
        """Test that an unknown table produces a known exception"""
        with self.assertRaises(LookupException):
            cqi = CyberQInterface("127.0.0.1")
            cqi._lookup("badtable", 0)

    def testInvalidCodeNumber(self):
        """Test that an index out of range is handled"""
        with self.assertRaises(LookupException):
            cqi = CyberQInterface("127.0.0.1")
            cqi._lookup("temperature", 4)

    def testLookupFromStatusObject(self):
        """Test that the code from an actual status object works properly"""
        with patch.object(requests, 'get') as mockMethod:
            mockMethod.return_value.status_code = 200
            mockMethod.return_value.text = """
<nutcstatus>
<!--all temperatures are displayed in tenths F, regardless of setting of unit-->
<!--all temperatures sent by browser to unit should be in F.  you can send-->
<!--tenths F with a decimal place, ex: 123.5-->
<OUTPUT_PERCENT>100</OUTPUT_PERCENT>
<TIMER_CURR>00:00:00</TIMER_CURR>
<COOK_TEMP>3343</COOK_TEMP>
<FOOD1_TEMP>823</FOOD1_TEMP>
<FOOD2_TEMP>OPEN</FOOD2_TEMP>
<FOOD3_TEMP>OPEN</FOOD3_TEMP>
<COOK_STATUS>0</COOK_STATUS>
<FOOD1_STATUS>0</FOOD1_STATUS>
<FOOD2_STATUS>4</FOOD2_STATUS>
<FOOD3_STATUS>4</FOOD3_STATUS>
<TIMER_STATUS>0</TIMER_STATUS>
<DEG_UNITS>1</DEG_UNITS>
<COOK_CYCTIME>6</COOK_CYCTIME>
<COOK_PROPBAND>500</COOK_PROPBAND>
<COOK_RAMP>0</COOK_RAMP>
</nutcstatus>"""
            cqi = CyberQInterface("127.0.0.1")
            status = cqi.getStatus()
            self.assertEqual(cqi.statusLookup(status.FOOD1_STATUS),"OK")

TestCyberQInterfaceSuite.loadTestsFromTestCase(TestCyberQInterfaceLookups)

if __name__ == '__main__':
    import nose
    nose.main()


#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import binascii
import os
import os.path
import pathlib
import platform
import re
import shutil
import subprocess
import textwrap

import distutils
from distutils import version
from distutils import extension as distutils_extension
from distutils.command import build as distutils_build
from distutils.command import build_ext as distutils_build_ext

import setuptools
from setuptools.command import develop as setuptools_develop

try:
    import setuptools_rust
except ImportError:
    setuptools_rust = None

RUNTIME_DEPS = [
    'asyncpg~=0.20.0',
    'click~=7.1',
    'httptools>=0.0.13',
    'immutables>=0.13',
    'parsing~=1.6.1',
    'prompt_toolkit==3.0.3',
    'psutil~=5.6.1',
    'Pygments~=2.3.0',
    'setproctitle~=1.1.10',
    'setuptools-rust==0.10.3',
    'setuptools_scm~=3.2.0',
    'typing_inspect~=0.5.0',
    'uvloop~=0.14.0',
    'wcwidth~=0.2.5',

    'graphql-core~=3.0.3',
    'promise~=2.2.0',

    'edgedb>=0.9.0a1',
]

CYTHON_DEPENDENCY = 'Cython==0.29.14'

DOCS_DEPS = [
    'Sphinx~=2.3.1',
    'lxml~=4.5.1',
    'sphinxcontrib-asyncio~=0.2.0',
]

BUILD_DEPS = [
    CYTHON_DEPENDENCY,
]

RUST_VERSION = '1.45.0'  # Also update docs/internal/dev.rst

EDGEDBCLI_REPO = 'https://github.com/edgedb/edgedb-cli'

EXTRA_DEPS = {
    'test': [
        # Depend on unreleased version for Python 3.8 support,
        'pycodestyle~=2.6.0',
        'pyflakes~=2.2.0',
        'black~=19.10b0',
        'flake8~=3.8.1',
        'flake8-bugbear~=20.1.4',
        'mypy==0.782',
        'coverage~=5.2.1',
        'requests-xml~=0.2.3',
        'lxml',
        # For rebuilding GHA workflows
        'Jinja2',
        'PyYAML',
    ] + DOCS_DEPS,

    'docs': DOCS_DEPS,
}

EXT_CFLAGS = ['-O2']
EXT_LDFLAGS = []

ROOT_PATH = pathlib.Path(__file__).parent.resolve()

if platform.uname().system != 'Windows':
    EXT_CFLAGS.extend([
        '-std=c99', '-fsigned-char', '-Wall', '-Wsign-compare', '-Wconversion'
    ])

def _compile_parsers(build_lib, inplace=False):
    import parsing

    import edb.edgeql.parser.grammar.single as edgeql_spec
    import edb.edgeql.parser.grammar.block as edgeql_spec2
    import edb.edgeql.parser.grammar.sdldocument as schema_spec

    for spec in (edgeql_spec, edgeql_spec2, schema_spec):
        spec_path = pathlib.Path(spec.__file__).parent
        subpath = pathlib.Path(str(spec_path)[len(str(ROOT_PATH)) + 1:])
        pickle_name = spec.__name__.rpartition('.')[2] + '.pickle'
        pickle_path = subpath / pickle_name
        cache = build_lib / pickle_path
        cache.parent.mkdir(parents=True, exist_ok=True)
        parsing.Spec(spec, pickleFile=str(cache), verbose=True)
        if inplace:
            shutil.copy2(cache, ROOT_PATH / pickle_path)

def _compile_build_meta(build_lib, version, pg_config, runstatedir,
                        shared_dir, version_suffix):
    from edb.common import verutils

    parsed_version = verutils.parse_version(version)
    vertuple = list(parsed_version._asdict().values())
    vertuple[2] = int(vertuple[2])
    if version_suffix:
        vertuple[4] = tuple(version_suffix.split('.'))
    vertuple = tuple(vertuple)

    content = textwrap.dedent('''\
        #
        # This source file is part of the EdgeDB open source project.
        #
        # Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
        #
        # Licensed under the Apache License, Version 2.0 (the "License");
        #
        # THIS FILE HAS BEEN AUTOMATICALLY GENERATED.
        #

        PG_CONFIG_PATH = {pg_config!r}
        RUNSTATE_DIR = {runstatedir!r}
        SHARED_DATA_DIR = {shared_dir!r}
        VERSION = {version!r}
    ''').format(
        version=vertuple,
        pg_config=pg_config,
        runstatedir=runstatedir,
        shared_dir=shared_dir,
    )

    directory = build_lib / 'edb' / 'server'
    if not directory.exists():
        directory.mkdir(parents=True)

    with open(directory / '_buildmeta.py', 'w+t') as f:
        f.write(content)

def _compile_postgres(build_base, *,
                      force_build=False, fresh_build=True,
                      run_configure=True, build_contrib=True):

    proc = subprocess.run(
        ['git', 'submodule', 'status', 'postgres'],
        stdout=subprocess.PIPE, universal_newlines=True, check=True)
    status = proc.stdout
    if status[0] == '-':
        print(
            'postgres submodule not initialized, '
            'run `git submodule init; git submodule update`')
        exit(1)

    proc = subprocess.run(
        ['git', 'submodule', 'status', 'postgres'],
        stdout=subprocess.PIPE, universal_newlines=True, check=True)
    revision, _, _ = proc.stdout[1:].partition(' ')
    source_stamp = proc.stdout[0] + revision

    postgres_build = (build_base / 'postgres').resolve()
    postgres_src = ROOT_PATH / 'postgres'
    postgres_build_stamp = postgres_build / 'stamp'

    if postgres_build_stamp.exists():
        with open(postgres_build_stamp, 'r') as f:
            build_stamp = f.read()
    else:
        build_stamp = None

    is_outdated = source_stamp != build_stamp

    if is_outdated or force_build:
        system = platform.system()
        if system == 'Darwin':
            uuidlib = 'e2fs'
        elif system == 'Linux':
            uuidlib = 'e2fs'
        else:
            raise NotImplementedError('unsupported system: {}'.format(system))

        if fresh_build and postgres_build.exists():
            shutil.rmtree(postgres_build)
        build_dir = postgres_build / 'build'
        if not build_dir.exists():
            build_dir.mkdir(parents=True)

        if run_configure or fresh_build or is_outdated:
            subprocess.run([
                str(postgres_src / 'configure'),
                '--prefix=' + str(postgres_build / 'install'),
                '--with-uuid=' + uuidlib,
            ], check=True, cwd=str(build_dir))

        subprocess.run(
            ['make', 'MAKELEVEL=0', '-j', str(max(os.cpu_count() - 1, 1))],
            cwd=str(build_dir), check=True)

        if build_contrib or fresh_build or is_outdated:
            subprocess.run(
                [
                    'make', '-C', 'contrib', 'MAKELEVEL=0', '-j',
                    str(max(os.cpu_count() - 1, 1))
                ],
                cwd=str(build_dir), check=True)

        subprocess.run(
            ['make', 'MAKELEVEL=0', 'install'],
            cwd=str(build_dir), check=True)

        if build_contrib or fresh_build or is_outdated:
            subprocess.run(
                ['make', '-C', 'contrib', 'MAKELEVEL=0', 'install'],
                cwd=str(build_dir), check=True)

        with open(postgres_build_stamp, 'w') as f:
            f.write(source_stamp)

def _check_rust():
    try:
        ver = subprocess.check_output(["rustc", '-V']).split()[1]
        ver = version.LooseVersion(ver.decode())
        if ver < version.LooseVersion(RUST_VERSION):
            raise RuntimeError(
                f'please upgrade Rust to {RUST_VERSION} to compile '
                f'edgedb from source')
    except FileNotFoundError:
        raise RuntimeError(
            f'please install rustc >= {RUST_VERSION} to compile '
            f'edgedb from source (see https://rustup.rs/)')

class build(distutils_build.build):

    user_options = distutils_build.build.user_options + [
        ('pg-config=', None, 'path to pg_config to use with this build'),
        ('runstatedir=', None, 'directory to use for the runtime state'),
        ('shared-dir=', None, 'directory to use for shared data'),
        ('version-suffix=', None, 'dot-separated local version suffix'),
    ]

    def initialize_options(self):
        super().initialize_options()
        self.pg_config = None
        self.runstatedir = None
        self.shared_dir = None
        self.version_suffix = None

    def finalize_options(self):
        super().finalize_options()

    def run(self, *args, **kwargs):
        super().run(*args, **kwargs)
        build_lib = pathlib.Path(self.build_lib)
        _compile_parsers(build_lib)
        if self.pg_config:
            _compile_build_meta(
                build_lib,
                self.distribution.metadata.version,
                self.pg_config,
                self.runstatedir,
                self.shared_dir,
                self.version_suffix,
            )

class develop(setuptools_develop.develop):

    def run(self, *args, **kwargs):
        _check_rust()
        build = self.get_finalized_command('build')
        rust_tmp = pathlib.Path(build.build_temp) / 'rust' / 'cli'
        build_base = pathlib.Path(build.build_base).resolve()
        rust_root = build_base / 'cli'
        env = dict(os.environ)
        env['CARGO_TARGET_DIR'] = str(rust_tmp)
        env['PSQL_DEFAULT_PATH'] = build_base / 'postgres' / 'install' / 'bin'

        subprocess.run(
            [
                'cargo', 'install',
                '--verbose', '--verbose',
                '--git', EDGEDBCLI_REPO,
                '--bin', 'edgedb',
                '--root', rust_root,
                '--features=dev_mode',
                '--locked',
                '--debug',
            ],
            env=env,
            check=True,
        )

        shutil.copy(
            rust_root / 'bin' / 'edgedb',
            ROOT_PATH / 'edb' / 'cli' / 'edgedb',
        )

        scripts = self.distribution.entry_points['console_scripts']
        patched_scripts = []
        for s in scripts:
            if 'rustcli' not in s:
                s = f'{s}_dev'
            patched_scripts.append(s)
        patched_scripts.append('edb = edb.tools.edb:edbcommands')
        self.distribution.entry_points['console_scripts'] = patched_scripts

        super().run(*args, **kwargs)

        _compile_parsers(build_base / 'lib', inplace=True)
        _compile_postgres(build_base)

class gen_build_cache_key(setuptools.Command):

    description = "generate a hash of build dependencies"
    user_options = []

    def run(self, *args, **kwargs):
        import edb as _edb
        from edb.server.buildmeta import hash_dirs

        parser_hash = hash_dirs([(
            os.path.join(_edb.__path__[0], 'edgeql/parser/grammar'),
            '.py')])

        proc = subprocess.run(
            ['git', 'submodule', 'status', 'postgres'],
            stdout=subprocess.PIPE, universal_newlines=True, check=True)
        postgres_revision, _, _ = proc.stdout[1:].partition(' ')

        print(f'{binascii.hexlify(parser_hash).decode()}-{postgres_revision}')

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

class build_postgres(setuptools.Command):

    description = "build postgres"

    user_options = [
        ('configure', None, 'run ./configure'),
        ('build-contrib', None, 'build contrib'),
        ('fresh-build', None, 'rebuild from scratch'),
    ]

    def initialize_options(self):
        self.configure = False
        self.build_contrib = False
        self.fresh_build = False

    def finalize_options(self):
        pass

    def run(self, *args, **kwargs):
        build = self.get_finalized_command('build')
        _compile_postgres(
            pathlib.Path(build.build_base).resolve(),
            force_build=True,
            fresh_build=self.fresh_build,
            run_configure=self.configure,
            build_contrib=self.build_contrib)

class build_ext(distutils_build_ext.build_ext):

    user_options = distutils_build_ext.build_ext.user_options + [
        ('cython-annotate', None,
            'Produce a colorized HTML version of the Cython source.'),
        ('cython-directives=', None,
            'Cython compiler directives'),
    ]

    def initialize_options(self):
        # initialize_options() may be called multiple times on the
        # same command object, so make sure not to override previously
        # set options.
        if getattr(self, '_initialized', False):
            return

        super(build_ext, self).initialize_options()

        if os.environ.get('EDGEDB_DEBUG'):
            self.cython_always = True
            self.cython_annotate = True
            self.cython_directives = "linetrace=True"
            self.define = 'PG_DEBUG,CYTHON_TRACE,CYTHON_TRACE_NOGIL'
            self.debug = True
        else:
            self.cython_always = False
            self.cython_annotate = None
            self.cython_directives = None
            self.debug = False

    def finalize_options(self):
        # finalize_options() may be called multiple times on the
        # same command object, so make sure not to override previously
        # set options.
        if getattr(self, '_initialized', False):
            return

        import pkg_resources

        # Double check Cython presence in case setup_requires
        # didn't go into effect (most likely because someone
        # imported Cython before setup_requires injected the
        # correct egg into sys.path.
        try:
            import Cython
        except ImportError:
            raise RuntimeError(
                'please install {} to compile edgedb from source'.format(
                    CYTHON_DEPENDENCY))

        cython_dep = pkg_resources.Requirement.parse(CYTHON_DEPENDENCY)
        if Cython.__version__ not in cython_dep:
            raise RuntimeError(
                'edgedb requires {}, got Cython=={}'.format(
                    CYTHON_DEPENDENCY, Cython.__version__
                ))

        from Cython.Build import cythonize

        directives = {
            'language_level': '3'
        }

        if self.cython_directives:
            for directive in self.cython_directives.split(','):
                k, _, v = directive.partition('=')
                if v.lower() == 'false':
                    v = False
                if v.lower() == 'true':
                    v = True

                directives[k] = v

        self.distribution.ext_modules[:] = cythonize(
            self.distribution.ext_modules,
            compiler_directives=directives,
            annotate=self.cython_annotate,
            include_path=["edb/server/pgproto/"])

        super(build_ext, self).finalize_options()

    def run(self):
        if self.distribution.rust_extensions:
            distutils.log.info("running build_rust")
            _check_rust()
            build_rust = self.get_finalized_command("build_rust")
            build_ext = self.get_finalized_command("build_ext")
            copy_list = []
            if not self.inplace:
                for ext in self.distribution.rust_extensions:
                    # Always build in-place because later stages of the build
                    # may depend on the modules having been built
                    dylib_path = pathlib.Path(
                        build_ext.get_ext_fullpath(ext.name))
                    build_ext.inplace = True
                    target_path = pathlib.Path(
                        build_ext.get_ext_fullpath(ext.name))
                    build_ext.inplace = False
                    copy_list.append((dylib_path, target_path))

                    # Workaround a bug in setuptools-rust: it uses
                    # shutil.copyfile(), which is not safe w.r.t mmap,
                    # so if the target module has been previously loaded
                    # bad things will happen.
                    if target_path.exists():
                        target_path.unlink()

                    target_path.parent.mkdir(parents=True, exist_ok=True)

            build_rust.debug = self.debug
            os.environ['CARGO_TARGET_DIR'] = (
                str(pathlib.Path(self.build_temp) / 'rust' / 'extensions'))
            build_rust.run()

            for src, dst in copy_list:
                shutil.copyfile(src, dst)

        super().run()

if setuptools_rust is not None:
    rust_extensions = [
        setuptools_rust.RustExtension(
            "edb._edgeql_rust",
            path="edb/edgeql-rust/Cargo.toml",
            binding=setuptools_rust.Binding.RustCPython,
        ),
        setuptools_rust.RustExtension(
            "edb._graphql_rewrite",
            path="edb/graphql-rewrite/Cargo.toml",
            binding=setuptools_rust.Binding.RustCPython,
        ),
    ]
else:
    rust_extensions = []

def custom_scm_version():
    from edb.server import buildmeta
    return {'version_scheme': buildmeta.scm_version_scheme}

setuptools.setup(
    setup_requires=RUNTIME_DEPS + BUILD_DEPS,
    use_scm_version=custom_scm_version,
    name='edgedb-server',
    description='EdgeDB Server',
    author='MagicStack Inc.',
    author_email='hello@magic.io',
    packages=['edb'],
    include_package_data=True,
    cmdclass={
        'build': build,
        'build_ext': build_ext,
        'develop': develop,
        'build_postgres': build_postgres,
        'gen_build_cache_key': gen_build_cache_key,
    },
    entry_points={
        'console_scripts': [
            'edgedb-old = edb.cli:cli',
            'edgedb-server = edb.server.main:main',
            'edgedb = edb.cli:rustcli',
        ]
    },
    ext_modules=[
        distutils_extension.Extension(
            "edb.testbase.protocol.protocol",
            ["edb/testbase/protocol/protocol.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.pgproto.pgproto",
            ["edb/server/pgproto/pgproto.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.dbview.dbview",
            ["edb/server/dbview/dbview.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.tokenizer",
            ["edb/server/tokenizer.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.mng_port.edgecon",
            ["edb/server/mng_port/edgecon.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.cache.stmt_cache",
            ["edb/server/cache/stmt_cache.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.pgcon.pgcon",
            ["edb/server/pgcon/pgcon.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.http.http",
            ["edb/server/http/http.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.http_edgeql_port.protocol",
            ["edb/server/http_edgeql_port/protocol.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.http_graphql_port.protocol",
            ["edb/server/http_graphql_port/protocol.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),

        distutils_extension.Extension(
            "edb.server.notebook_port.protocol",
            ["edb/server/notebook_port/protocol.pyx"],
            extra_compile_args=EXT_CFLAGS,
            extra_link_args=EXT_LDFLAGS),
    ],
    rust_extensions=rust_extensions,
    install_requires=RUNTIME_DEPS,
    extras_require=EXTRA_DEPS,
    test_suite='tests.suite',
)


from glob import glob
import json
import os.path as path
import matplotlib.pyplot as plt
import cv2
import keras
from keras.applications.mobilenet import MobileNet
from keras.layers import Dense,Flatten,Input,Dropout
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.models import Model
from keras.callbacks import EarlyStopping

BATCH_SIZE = 4

def get_data():
  return glob("./images/**/*.json")

def get_model():
  base = MobileNet(pooling = 'avg',weights='imagenet',include_top = True,dropout=.6)
  x = base.output
  x = Dense(1000,name='1000fc',bias_regularizer=keras.regularizers.l2(0.01),activation='relu')(x)
  x = Dropout(0.2,name='Dropout_1')(x)
  x = Dense(4, activation='softmax')(x)
  model = Model(inputs=[base.input],outputs=[x])

  return model

def generator(data_paths, batch_size):
  dest_size = (224,224)

  num_samples =  len(data_paths)
  while True:

    shuffle(data_paths)
    for offset in range(0, num_samples, batch_size):
      X=[]
      y=[]
      paths = data_paths[offset:offset+batch_size]
      for data_path in paths:
        with open(data_path,'r') as f:
          data = json.loads(f.read())
          y.append(data)

        img = cv2.imread('{}.jpg'.format(path.splitext(data_path)[0]))
        img = cv2.resize(img,dest_size)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = (img-127.5)/128.0
        X.append(img)

        h_flip = cv2.flip(img,1)
        X.append(h_flip)
        y.append(data)

      labels=[]
      for data in y:
        label = np.zeros(4)
        label[data['lightState']]=1
        labels.append(label)
      y=np.array(labels)
      X=np.array(X)

      yield X,y

def train():
  paths = get_data()
  print( 'Total samples: ' + str(len(paths)))

  train_paths, val_paths = train_test_split(paths, test_size= 0.2)

  train_steps = len(train_paths) // BATCH_SIZE
  val_steps = len(val_paths) // BATCH_SIZE

  print( 'val steps ' + str(val_steps))
  print( 'train steps ' + str(train_steps))

  train_gen = generator(train_paths, BATCH_SIZE)
  val_gen = generator(val_paths, BATCH_SIZE)
  model = get_model()
  model.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['acc'])

  # print summary of network architecture
  model.summary()
  early_stopping = EarlyStopping(monitor='val_loss',patience=3)
  history = model.fit_generator(
    train_gen,
    steps_per_epoch=train_steps,
    epochs=30,verbose=True,
    validation_data=val_gen,
    validation_steps=val_steps,
    callbacks=[early_stopping])

  model_base_name = 'models/mobilenet_sim_model'
  model_name = model_base_name + '.h5'
  model.save(model_name)

  model_json_arch_name = model_base_name + '.json'
  json_arch = model.to_json()
  with open(model_json_arch_name, 'w') as f:
    f.write(json_arch)

  model_weights_name = model_base_name + '.weights'
  model.save_weights(model_weights_name)

if __name__=='__main__':
   train()


import nltk
from newspaper import Article
from bs4 import BeautifulSoup

def fetch_data(url):

    url_webpage = url
    article_cnn=Article(url,language="en")
    article_cnn.download()
    article_cnn.parse()
    #article_cnn.nlp()
    print("The name of the Article :"+article_cnn.title)
    print("Body:"+article_cnn.text)
    #print("Summary:"+article_cnn.summary)
    #print("Keywords:")
    for keyword in article_cnn.keywords:
        print(keyword)

fetch_data('https://www.bbc.com/news/uk-45768848')
#quote_page = 'https://www.cnn.com/2018/10/06/politics/kavanaugh-final-confirmation-vote/index.html'
#page = urllib2.urlopen(quote_page)
#oup=BeautifulSoup(page,'html.parser')

#headline_box = soup.find('h1',attrs={'class':'pg-headline'})
#headline_name = headline_box.text.strip()
#print(headline_name)
#try:
   # import urllib.request as urllib2
#except ImportError:
 #   import urllib2


# -*- coding: ISO-8859-1 -*-
from django.shortcuts import get_object_or_404
from django.db.models import Q, Sum
from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView, UpdateView

from tsm.core.base.core_base_datatable import CoreBaseDatatableView
from tsm.core.mixins.core_mixin_login import CoreMixinLoginRequired
from tsm.core.mixins.core_mixin_json import JSONResponseMixin
from tsm.core.mixins.core_mixin_form import CoreMixinForm, CoreMixinDel
from tsm.core.mixins.core_mixin_json import JSONResponseMixin
from tsm.core.util import getParamByName, get_filiais, format_number
from tsm.core import constants

from tsm.acesso.models.usuario import Usuario
from tsm.equipe.models.membro import Membro
from tsm.equipe.models.membrometa import MembroMeta

from tsm.oportunidade.models.oportunidade import Oportunidade
from tsm.oportunidade.models.resposta import Resposta

class VisaoGerencial(CoreMixinLoginRequired, TemplateView):
    """
    Visão gerencial da oportunidade
    """
    template_name = 'visaogerencial_list.html'

class VisaoGerencialData(CoreMixinLoginRequired, CoreBaseDatatableView):
    """
    Json da lista
    """
    model = Oportunidade
    columns = [
        'cliente',
        'receita',
        'situacao',
        'valor',
        'ponderado',
        'temperatura_auto',
        'tipotemperatura',
        'responsavel',
        'lider',
        'dtFechamento',
        'respostas',
        'id',
    ]
    order_columns = [
        'cliente',
        'receita',
        'situacao',
        'valor',
        'ponderado',
        'temperatura_auto',
        'tipotemperatura',
        'responsavel',
        'lider',
        'dtFechamento',
    ]
    max_display_length = 500
    url_base_form = '/oportunidade/visaogerencial/'

    def render_column(self, row, column):
        if column == 'cliente':
            sReturn = row.cliente.nome
            return sReturn
        elif column == 'receita':
            sReturn = row.receita.nome
            return sReturn
        elif column == 'situacao':
            sReturn = row.situacao.nome
            return sReturn
        elif column == 'tipotemperatura':
            sReturn = row.tipotemperatura.nome
            return sReturn
        elif column == 'responsavel':
            sReturn = row.responsavel.first_name + ' ' + row.responsavel.last_name
            return sReturn
        elif column == 'lider':
            sReturn = row.lider.first_name
            return sReturn
        elif column == 'valor':
            sReturn = format_number(row.valor)
            return sReturn
        elif column == 'ponderado':
            sReturn = format_number(row.ponderado)
            return sReturn
        elif column == 'respostas':
            dictReturn = []
            respostas = Resposta.objects.filter(oportunidade__id=row.id).order_by('questao__ordem')
            for resposta in respostas:
                dictReturn.append({
                    "pergunta": resposta.questao.pergunta,
                    "resposta": "Sim" if resposta.resposta else "Não",
                })
            return dictReturn
        elif column == 'dtFechamento':
            sReturn = row.dtFechamento.strftime("%d/%m/%Y")
            return sReturn
        elif column == 'buttons' and self.url_base_form and self.use_buttons:
            sReturn = '
'
            sReturn +='     '
            sReturn +='
'
            return sReturn
        else:
            return super(VisaoGerencialData, self).render_column(row, column)

    def filter_queryset(self, qs):
        """
        Filtros da query baseado no datatable
        """
        qs_base_filter = None

        #Verifica pode ver todas oportunidades, senão só exibe as que ele pode ver
        if not self.request.user.has_perm('oportunidade.list_all_opportunities'):
            membros = Membro.objects.filter(usuario__id=self.request.user.id)
            if membros.exists():
                membro = membros[0]
                children = Membro.objects.filter(lider__id=membro.id)
                qs_base_filter = Q(responsavel__id=membro.usuario.id) | Q(lider__id=membro.usuario.id)

                if children:
                    while children:
                        for item in children:
                            qs_base_filter = qs_base_filter | Q(lider__id=item.usuario.id)

                        children = Membro.objects.filter(
                            lider__id__in = children.values_list('id', flat=True)
                        )
        else:
            qs_base_filter = Q(
                filial__id__in=Usuario.objects \
                                      .filter(id=self.request.user.id) \
                                      .values_list('filiais__id', flat=True)
            )

        sSearch = self.request.GET.get('sSearch', None)
        qs_params = None
        if sSearch:
            search_parts = sSearch.split('+')
            for part in search_parts:
                q = Q(cliente__nome__istartswith=part)| \
                    Q(receita__nome__istartswith=part)| \
                    Q(situacao__nome__istartswith=part)| \
                    Q(temperatura_auto__istartswith=part)| \
                    Q(tipotemperatura__nome__istartswith=part)| \
                    Q(responsavel__first_name__istartswith=part)|Q(responsavel__last_name__istartswith=part)| \
                    Q(lider__first_name__istartswith=part)|Q(lider__last_name__istartswith=part)

                qs_params = qs_params | q if qs_params else q

            qs = qs.filter(qs_params)

        if qs_base_filter:
            qs = qs.filter(qs_base_filter)

        return qs

class VisaoGerencialIndicador(CoreMixinLoginRequired, JSONResponseMixin, TemplateView):
    """
    Retorna os indicadores relativos a cada oportunidade
    """

    def get(self, request, *args, **kwargs):
        oportunidade = get_object_or_404(Oportunidade,id=self.kwargs.get('pk', None))

        #calcula percentual em relacao a todas as oportunidades ainda não fechadas
        valOportunidade = 0
        oportunidades = Oportunidade.objects.filter(tipotemperatura__tipo__isnull=True) \
                                            .aggregate(Sum('valor'))

        if oportunidades:
            valOportunidade = (oportunidade.valor * 100)/oportunidades['valor__sum']

        if valOportunidade == 100:
            valOportunidade = valOportunidade

        #percentual do responsavel em relacao a sua meta
        valResponsavel = 0
        membroMeta = MembroMeta.objects.filter(
                                    membro__usuario__id=oportunidade.responsavel.id,
                                    is_Visible=True,
                                    mesVigencia=oportunidade.dtFechamento.strftime("%m"),
                                    anoVigencia=oportunidade.dtFechamento.strftime("%Y"),
                                    tipometa__id=getParamByName(constants.PAR_TPMETA, request.user.id)
                     )

        if membroMeta:
            valResponsavel = (oportunidade.valor * 100)/ membroMeta[0].valor
            if valResponsavel > 100:
                valResponsavel = 100

        #percentual do lider em relacao a sua meta
        valLider = 0
        membroMeta = MembroMeta.objects.filter(
                                    membro__usuario__id=oportunidade.lider.id,
                                    is_Visible=True,
                                    mesVigencia=oportunidade.dtFechamento.strftime("%m"),
                                    anoVigencia=oportunidade.dtFechamento.strftime("%Y"),
                                    tipometa__id=getParamByName(constants.PAR_TPMETA, request.user.id)
                     )

        if membroMeta:
            valLider = (oportunidade.valor * 100)/ membroMeta[0].valor
            if valLider > 100:
                valLider = 100

        data = {
            "result" : "ok",
            "data" : {
                "oportunidade": oportunidade.id,
                "values":{
                    "oportunidade": round(valOportunidade,2),
                    "responsavel": round(valResponsavel,2),
                    "lider" : round(valLider,2)
                }
            }
        }
        context = data

        return self.render_to_response(context)

class VisaoGerencialIndicadorTop(CoreMixinLoginRequired, JSONResponseMixin, TemplateView):
    """
    Retorna os indicadores do topo da tela
    """

    def get(self, request, *args, **kwargs):
        from datetime import date
        from tsm.oportunidade.models.situacao import Situacao
        from tsm.oportunidade.models.tipotemperatura import TipoTemperatura

        if not self.request.user.has_perm('oportunidade.list_all_opportunities'):
            membros = Membro.objects.filter(usuario__id=request.user.id)
            if membros.exists():
                membro = membros[0]
                children = Membro.objects.filter(lider__id=membro.id)
                qs_base_filter = Q(responsavel__id=membro.usuario.id) | Q(lider__id=membro.usuario.id)

                if children:
                    while children:
                        for item in children:
                            qs_base_filter = qs_base_filter | Q(lider__id=item.usuario.id)

                        children = Membro.objects.filter(
                            lider__id__in = children.values_list('id', flat=True)
                        )
        else:
            qs_base_filter = Q(
                filial__id__in=Usuario.objects \
                                      .filter(id=request.user.id) \
                                      .values_list('filiais__id', flat=True)
            )

        oportunidades = Oportunidade.objects.filter(qs_base_filter)
        oportunidades.exclude(dtFechamento__lt=date(date.today().year, date.today().month, 1)) \
                     .exclude(tipotemperatura__tipo='P')

        #FCST Gross
        temperaturas = [
            [1,6], #Adiada + Alta
            [2], #Media
            [3], #Fechada
        ]
        totalGross = float(0)
        gross = []
        for item in temperaturas:
            temps = TipoTemperatura.objects.filter(id__in=item)
            strTitle = ''
            for temp in temps:
                if strTitle:
                    strTitle = strTitle + ' + '
                strTitle = strTitle + temp.nome

            gross.append({
                'id': item,
                'title': strTitle,
                'value': 0,
            })

        #lideres
        lideres = []
        for oportunidade in oportunidades:
            if not oportunidade.lider.id in lideres:
                lideres.append(oportunidade.lider.id);

        #FCST Ponderado
        totalPonderado = float(0)
        ponderado = []
        for item in lideres:
            ponderado.append({
                'id': item,
                'name': '',
                'value':0,
            })

        #FATOR Situacao (P/U)
        totalSituacao = 0
        situacoes = Situacao.objects.all()
        fatorSit = []
        for item in lideres:
            fatorSit.append({
                'id': item,
                'name': '',
                'situacoes':[],
            })

            for situacao in situacoes:
                fatorSit[len(fatorSit)-1]['situacoes'].append({
                    'id': situacao.id,
                    'name': situacao.nome,
                    'perc': situacao.perc,
                    'value': 0,
                })

        #FATOR Calculo (66)
        totalFator = float(0)
        fatorCal = []
        for item in lideres:
            fatorCal.append({
                'id': item,
                'name': '',
                'value': 0,
            })

        #Realiza calculo
        for oportunidade in oportunidades:
            #atualiza dados do Gross
            totalGross += oportunidade.valor
            i = 0
            for item in gross:
                if oportunidade.tipotemperatura.id in item['id']:
                    gross[i]['value'] += oportunidade.valor
                i += 1

            #atualiza dados do ponderado
            totalPonderado += oportunidade.ponderado
            i = 0
            for item in ponderado:
                if oportunidade.lider.id == item['id']:
                    ponderado[i]['value'] += oportunidade.ponderado
                    ponderado[i]['name'] = oportunidade.lider.first_name
                i += 1

            #atualiza dados do fator situacao
            totalSituacao += round((oportunidade.valor * oportunidade.situacao.perc)/100,2)
            i = 0
            for item in fatorSit:
                if oportunidade.lider.id == item['id']:
                    fatorSit[i]['name'] = oportunidade.lider.first_name

                    j = 0
                    for situacao in item['situacoes']:
                        if situacao['id'] == oportunidade.situacao.id:
                            fatorSit[i]['situacoes'][j]['value'] = round((oportunidade.valor * oportunidade.situacao.perc)/100,2)
                        j += 1
                i += 1

            #atualiza dados do cálculo 66
            fator = float(getParamByName(constants.PAR_POND66, request.user.id))
            totalFator += round(oportunidade.ponderado * fator,2)
            i=0
            for item in fatorCal:
                if oportunidade.lider.id == item['id']:
                    fatorCal[i]['value'] += round(oportunidade.ponderado * fator,2)
                    fatorCal[i]['name'] = oportunidade.lider.first_name
                i += 1

        data = {
            "result" : "ok",
            "data" : {
                "gross": {
                    "total" : totalGross,
                    "items" : gross,
                },
                "ponderado":{
                    "total": totalPonderado,
                    "items": ponderado,
                },
                "situacao":{
                    "total": totalSituacao,
                    "items": fatorSit,
                },
                "fator":{
                    "perc": fator,
                    "total": totalFator,
                    "items": fatorCal,
                },
            },
        }
        context = data

        return self.render_to_response(context)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('backend', '0006_detalle_venta_precio'),
    ]

    operations = [
        migrations.AddField(
            model_name='pedido',
            name='total',
            field=models.FloatField(default=0.0),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='venta',
            name='total',
            field=models.FloatField(default=0.0),
            preserve_default=False,
        ),
    ]


import math
import numpy as np
from numpy.linalg import solve
from scipy.stats import f, t
from functools import partial
from random import randint
from prettytable import PrettyTable

# *********** Змінні за варіантом ***********
m = 3
N = 8

X1max = 40
X1min = 10
X2max = 35
X2min = -15
X3max = 5
X3min = -15

Xmax_average = (X1max + X2max + X3max) / 3
Xmin_average = (X1min + X2min + X3min) / 3

y_max = round(200 + Xmax_average)
y_min = round(200 + Xmin_average)

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

def kriteriy_fishera(y, y_aver, y_new, n, m, d):
    """
    Функція для знаходження критерія фішера
    """
    S_kv_ad = (m / (n - d)) * sum([(y_new[i] - y_aver[i])**2 for i in range(len(y))])
    S_kv_b = s_kv(y, y_aver, n, m)
    S_kv_b_aver = sum(S_kv_b) / n

    return S_kv_ad / S_kv_b_aver

def s_kv(y, y_aver, n, m):
    """
    Функція для знаходження квадратної дисперсії
    """
    res = []
    for i in range(n):
        s = sum([(y_aver[i] - y[i][j])**2 for j in range(m)]) / m
        res.append(s)
    return res

def getDispersion(y_rows) -> list:
    disp_array = [0] * 8

    for k in range(len(disp_array)):
        for i in range(m):
            disp_array[k] += ((np.average(y_rows[k]) - y_rows[k][i])**2) / m

    return disp_array

def getCodableX(factorsArray):
    x1, x2, x3 = [], [], []
    for factorNumber in range(len(factorsArray)):
        factor = factorsArray[factorNumber]
        for i in factor:
            if i > 0:
                if factorNumber == 0:
                    x1.append(X1max)
                elif factorNumber == 1:
                    x2.append(X2max)
                else:
                    x3.append(X3max)
            else:
                if factorNumber == 0:
                    x1.append(X1min)
                elif factorNumber == 1:
                    x2.append(X2min)
                else:
                    x3.append(X3min)
    return x1, x2, x3

def getRandomY():
    y1, y2, y3 = [], [], []

    for _ in range(0, 8):
        y1.append(randint(y_min, y_max))
        y2.append(randint(y_min, y_max))
        y3.append(randint(y_min, y_max))

    return y1, y2, y3

def getYRows(y1, y2, y3):
    y_rows = []
    for i in range(8):
        y_rows.append([y1[i], y2[i], y3[i]])

    return y_rows

def getYAverage(y_rows) -> list:
    y_average_all = []

    for i in range(len(y_rows)):
        y_average_all.append(np.average(y_rows[i]))

    return y_average_all

def cohren(f1, f2, q=0.05):
    q1 = q / f1
    fisher_value = f.ppf(q=1 - q1, dfn=f2, dfd=(f1 - 1) * f2)
    return fisher_value / (fisher_value + f1 - 1)

def plan_matrix(n, m):
    """
    Функція для знаходження матриці планування
    """
    y = np.zeros(shape=(n,m))
    for i in range(n):
        for j in range(m):
            y[i][j] = randint(y_min, y_max)

    x_norm = np.array([[1, -1, -1, -1],
                       [1, -1,  1,  1],
                       [1,  1, -1,  1],
                       [1,  1,  1, -1],
                       [1, -1, -1,  1],
                       [1, -1,  1, -1],
                       [1,  1, -1, -1],
                       [1,  1,  1,  1]])
    x_norm = x_norm[:len(y)]

    x_range = [(X1min, X1max), (X1min, X1max), (X1min, X1max)]
    x = np.ones(shape=(len(x_norm), len(x_norm[0])))
    for i in range(len(x_norm)):
        for j in range(1, len(x_norm[i])):
            if x_norm[i][j] == -1:
                x[i][j] = x_range[j-1][0]
            else:
                x[i][j] = x_range[j-1][1]

    print('\nМатриця планування')
    matrix = np.concatenate((x,y),axis=1)
    table = PrettyTable()

    yFieldNames = []
    yFieldNames += (f'Y{i+1}' for i in range(m))

    fieldNames = ["X0c", "X1c", "X2c", "X3c"] + yFieldNames
    table.field_names = fieldNames

    for i in range(len(matrix)):
        table.add_row(matrix[i])

    print(table)

    return x, y

def find_coefficient(x, y_aver, n):
    """
    Функція для знаходження коефіціентів B
    """
    mx1 = sum(x[:, 1]) / n
    mx2 = sum(x[:, 2]) / n
    mx3 = sum(x[:, 3]) / n
    my = sum(y_aver) / n

    a12 = sum([x[i][1] * x[i][2] for i in range(len(x))]) / n
    a13 = sum([x[i][1] * x[i][3] for i in range(len(x))]) / n
    a23 = sum([x[i][2] * x[i][3] for i in range(len(x))]) / n
    a11 = sum([i ** 2 for i in x[:, 1]]) / n
    a22 = sum([i ** 2 for i in x[:, 2]]) / n
    a33 = sum([i ** 2 for i in x[:, 3]]) / n
    a1 = sum([y_aver[i] * x[i][1] for i in range(len(x))]) / n
    a2 = sum([y_aver[i] * x[i][2] for i in range(len(x))]) / n
    a3 = sum([y_aver[i] * x[i][3] for i in range(len(x))]) / n

    X = [[  1, mx1, mx2, mx3],
         [mx1, a11, a12, a13],
         [mx2, a12, a22, a23],
         [mx3, a13, a23, a33]]

    Y = [my, a1, a2, a3]
    # Вирішимо систему рівнянь для коефіціентів
    B = [round(i, 2) for i in solve(X, Y)]
    print('\nРівняння регресії')
    print(f'{B[0]} + {B[1]}*x1 + {B[2]}*x2 + {B[3]}*x3')

    return B

def main(m, effectVzaemodiy = False, isSetEffectVzaemodiy = False):
    N = 8
    fisher = partial(f.ppf, q=1-0.05)
    student = partial(t.ppf, q=1-0.025)

    # y
    y1, y2, y3 = getRandomY()

    # y_rows
    y_rows = getYRows(y1, y2, y3)

    # середнє значення y_rows
    y_average = getYAverage(y_rows)

    disp_list = []

    list_bi = []

    if effectVzaemodiy:
        # З Ефектом взаємодії

        x0_factor = [ 1,  1,  1,  1,  1,  1,  1,  1]
        x1_factor = [-1, -1,  1,  1, -1, -1,  1,  1]
        x2_factor = [-1,  1, -1,  1, -1,  1, -1,  1]
        x3_factor = [-1,  1,  1, -1,  1, -1, -1,  1]

        x1x2_factor = [a*b for a, b in zip(x1_factor, x2_factor)]
        x1x3_factor = [a*b for a, b in zip(x1_factor, x3_factor)]
        x2x3_factor = [a*b for a, b in zip(x2_factor, x3_factor)]
        x1x2x3_factor = [a*b*c for a, b, c in zip(x1_factor, x2_factor, x3_factor)]

        # Кодовані значення
        x1, x2, x3 = getCodableX([x1_factor, x2_factor, x3_factor])

        x1x2 = [a*b for a, b in zip(x1, x2)]
        x1x3 = [a*b for a, b in zip(x1, x3)]
        x2x3 = [a*b for a, b in zip(x2, x3)]
        x1x2x3 = [a*b*c for a, b, c in zip(x1, x2, x3)]

        list_for_solve_b = [x0_factor, x1_factor, x2_factor, x3_factor, x1x2_factor, x1x3_factor, x2x3_factor, x1x2x3_factor]
        list_for_solve_a = list(zip(x0_factor, x1, x2, x3, x1x2, x1x3, x2x3, x1x2x3))

        # Коефіцієнти регресії для нормованих значень факторів коефіцієнтів регресії для нормованих значень факторів
        list_bi = []
        for k in range(N):
            S = 0
            for i in range(N):
                S += (list_for_solve_b[k][i] * y_average[i]) / N
            list_bi.append(round(S, 5))

        # Список з дисперсіями
        disp_list = getDispersion(y_rows)

        # Округлені значення дисперсії та yAverage для таблиці
        dispListToTable = [round(i, 3) for i in disp_list]
        yAverageToTable = [round(i, 3) for i in y_average]

        # Створюємо 2 таблиці
        pt1 = PrettyTable()
        pt2 = PrettyTable()

        # Данні для наповняння таблиці
        column_names = ["X0", "X1", "X2", "X3", "X1X2", "X1X3", "X2X3", "X1X2X3", "Y1", "Y2", "Y3", "Y_aver", "S^2"]
        column_values1 = [x0_factor, x1_factor, x2_factor, x3_factor, x1x2_factor, x1x3_factor, x2x3_factor, x1x2x3_factor, y1, y2, y3, yAverageToTable, dispListToTable]
        column_values2 = [x0_factor, x1, x2, x3, x1x2, x1x3, x2x3, x1x2x3, y1, y2, y3, yAverageToTable, dispListToTable]

        # Наповнюємо першу таблицю
        for i in range(len(column_names)):
            pt1.add_column(column_names[i], column_values1[i])

        # Виводимо першу таблицю
        print(pt1, "\n")

        print("y = {} + {}*x1 + {}*x2 + {}*x3 + {}*x1x2 + {}*x1x3 + {}*x2x3 + {}*x1x2x3 \n".format(list_bi[0], list_bi[1],
                                                                                list_bi[2], list_bi[3],
                                                                                list_bi[4], list_bi[5],
                                                                                list_bi[6], list_bi[7]))                                                                                # list_bi[2], list_bi[3]))

        # Наповнюємо другу таблицю
        for i in range(len(column_names)):
            pt2.add_column(column_names[i], column_values2[i])

        # Виводимо педругуршу таблицю
        print(pt2, '\n')

        # Визначення коефіцієнтів рівняння регресії ПФЕ
        list_ai = [round(i, 5) for i in solve(list_for_solve_a, y_average)]

        print("y = {} + {}*x1 + {}*x2 + {}*x3 + {}*x1x2 + {}*x1x3 + {}*x2x3 + {}*x1x2x3".format(list_ai[0], list_ai[1], list_ai[2], list_ai[3], list_ai[4], list_ai[5], list_ai[6], list_ai[7]))

    else:
        # Без ефекту взаємодії
        x, y = plan_matrix(N, m)
        list_bi = find_coefficient(x, y_average, N)
        disp_list = getDispersion(y)

    # Теоретичне
    Gp = max(disp_list) / sum(disp_list)

    F1 = m-1
    N = len(y1)
    F2 = N

    # Табличне
    Gt = cohren(F1, F2)
    print("\nGp = ", Gp, " Gt = ", Gt)

    if Gp < Gt:
        print("Gp < Gt -> Дисперсія однорідна!\n")

        Dispersion_B = sum(disp_list) / N
        Dispersion_beta = Dispersion_B / (m * N)
        S_beta = math.sqrt(abs(Dispersion_beta))

        t_list = []

        for i in range(len(list_bi)):
            t_list.append(abs(list_bi[i]) / S_beta)

        F3 = F1 * F2
        d = 0
        T = student(df=F3)
        print("t стьюдента табличне = ", T)

        for i in range(len(t_list)):
            if t_list[i] < T:
                print("Коефіціент {} не є значущим, виключаємо його".format(t_list[i]))
                list_bi[i] = 0

            else:
                d += 1

        # Критерії які підходять
        Y_counted_for_Student = []

        for i in range(8):
            if effectVzaemodiy:
                Y_counted_for_Student.append(list_bi[0] + list_bi[1] * x1[i] + list_bi[2] * x2[i] + list_bi[3] * x3[i] + list_bi[4] * x1x2[i] \
                + list_bi[5]*x1x3[i] + list_bi[6]*x2x3[i] + list_bi[7]*x1x2x3[i])
            else:
                Y_counted_for_Student.append(list_bi[0] + list_bi[1] * x[i][1] + list_bi[2] * x[i][2] + list_bi[3] * x[i][3])

        # Табличне
        F4 = N - d
        Ft = fisher(dfn=F4, dfd=F3)

        # Практичне
        Fp = kriteriy_fishera(y_rows, y_average, Y_counted_for_Student, N, m, d)

        effectVzaemodiy = True

        if Fp > Ft:
            print("Модель не адекватна")
            m = 3

            # Якщо вже було спробувано ефект взаємодії повернутися на початок
            if isSetEffectVzaemodiy:
                main(m, False, False)
            else:
                print("Спробуємо ефект взаємодії")
                main(m, effectVzaemodiy, True)

        else:
            print("МОДЕЛЬ АДЕКВАТНА")

    else:
        print("Дисперсія неоднорідна. Спробуємо з m = {}".format(m + 1))
        m += 1
        main(m, effectVzaemodiy, isSetEffectVzaemodiy)

if __name__ == "__main__":
    main(m)


import numpy as np
from scipy.special import hyp2f1, gamma
from scipy.integrate import quad
from scipy.stats import beta as Beta
from scipy.linalg import block_diag
from . import wigner

class LongitudeIntegral(object):
    def __init__(self, ydeg, skip_nullspace=False):
        self.ydeg = ydeg
        self.ls = np.arange(self.ydeg + 1)
        if skip_nullspace:
            self.ls = np.append(self.ls[:3], self.ls[4::2])
        self.N = (ydeg + 1) ** 2
        self._R = wigner.R(ydeg, cos_alpha=1, sin_alpha=0, cos_gamma=1, sin_gamma=0)
        self.set_matrix(np.eye(self.N))
        self.set_vector(np.ones(self.N))
        self._precompute()

    @property
    def matrix(self):
        return self._matrix

    def set_matrix(self, matrix):
        self._matrix = matrix
        self._Q = wigner.MatrixDot(self._R, self._matrix)

    @property
    def vector(self):
        return self._vector

    def set_vector(self, vector):
        self._vector = vector
        self._q = wigner.VectorDot(self._R, self._vector)

    def _precompute(self):
        # TODO: Check for stability here.
        self._term = np.zeros((4 * self.ydeg + 1, 4 * self.ydeg + 1))
        for i in range(4 * self.ydeg + 1):
            for j in range(0, 4 * self.ydeg + 1, 2):
                self._term[i, j] = (
                    2
                    * gamma(0.5 * (i + 1))
                    * gamma(0.5 * (j + 1))
                    / gamma(0.5 * (2 + i + j))
                )

    def _test_term(self):
        def num_integrand(lam, i, j):
            return np.cos(lam / 2) ** i * np.sin(lam / 2) ** j

        for i in range(2 * self.ydeg + 1):
            for j in range(2 * self.ydeg + 1):
                result = quad(num_integrand, -np.pi, np.pi, (i, j))[0]
                assert np.allclose(result, self._term[i, j])

    def integral1(self, vector=None):
        """
        Return the integral of the first moment.

        """
        if vector is not None:
            self.set_vector(vector)
        L = np.zeros(self.N)
        for l in self.ls:
            term = np.diag(np.fliplr(self._term[: 2 * l + 1, : 2 * l + 1]))
            i = slice(l ** 2, (l + 1) ** 2)
            L[i] = 1.0 / (2 * np.pi) * self._q[i, : 2 * l + 1].dot(term)
        return L

    def _test_integral1(self):
        np.random.seed(1)
        vector = np.random.randn(self.N)
        ls = np.array(self.ls)
        self.ls = np.arange(self.ydeg + 1)
        L = self.integral1(vector=vector)
        self.ls = ls
        Lnum = np.zeros_like(L)
        lam_arr = np.linspace(-np.pi, np.pi, 10000)
        dlam = lam_arr[1] - lam_arr[0]
        for lam in lam_arr:
            R = wigner._R(
                self.ydeg, lam, cos_alpha=1, sin_alpha=0, cos_gamma=1, sin_gamma=0
            )
            Rs = block_diag(*R).dot(vector)
            Lnum += Rs * dlam / (2 * np.pi)
        assert np.allclose(Lnum, L, atol=1e-3)

    def integral2(self, matrix=None):
        """
        Return the integral of the second moment.

        """
        if matrix is not None:
            self.set_matrix(matrix)
        L = np.zeros((self.N, self.N))
        for l1 in self.ls:
            i = slice(l1 ** 2, (l1 + 1) ** 2)
            for l2 in self.ls:
                j = slice(l2 ** 2, (l2 + 1) ** 2)
                l = l1 + l2
                term = np.diag(np.fliplr(self._term[: 2 * l + 1, : 2 * l + 1]))
                L[i, j] = 1.0 / (2 * np.pi) * self._Q[i, j, : 2 * l + 1].dot(term)
        return L

    def _test_integral2(self):
        np.random.seed(1)
        matrix = np.tril(np.random.randn(self.N, self.N))
        matrix = np.dot(matrix, matrix.T)
        ls = np.array(self.ls)
        self.ls = np.arange(self.ydeg + 1)
        L = self.integral2(matrix=matrix)
        self.ls = ls
        Lnum = np.zeros_like(L)
        lam_arr = np.linspace(-np.pi, np.pi, 10000)
        dlam = lam_arr[1] - lam_arr[0]
        for lam in lam_arr:
            R = wigner._R(
                self.ydeg, lam, cos_alpha=1, sin_alpha=0, cos_gamma=1, sin_gamma=0
            )
            RPRT = block_diag(*R).dot(matrix).dot(block_diag(*R).T)
            Lnum += RPRT * dlam / (2 * np.pi)
        assert np.allclose(Lnum, L, atol=1e-2)

def test():
    integral = LongitudeIntegral(4)
    integral._test_term()
    integral._test_integral1()
    integral._test_integral2()


"""Prepare metric."""

# pylint: disable=R0903,R0912,W0212,E1101,R0201

# Standard lib import
import os
import re
# Mongoengine imports
from mongoengine.queryset.visitor import Q
# ISS Wikipedia actions
from src.actions import Mongo
from src.models import SpecialPage, Metrics
from src.utils.metrics import make_metric_short_name
from src.utils import get_usernames
from src.utils.mongo import make_bulk_update

# Globals
BASE_PATH = os.path.dirname(__file__)
DTYPE = os.path.basename(os.path.normpath(os.path.join(BASE_PATH, '..')))
NAME = os.path.basename(BASE_PATH)
MNAME = make_metric_short_name(NAME)
MODEL = SpecialPage

class Metric(Mongo):
    """Metric action."""

    base_url = 'https://en.wikipedia.org/wiki/'

    # Regular expressions
    rx_query1 = re.compile(r"/Questions/General/List", re.IGNORECASE)
    rx_query2 = re.compile(r"/Candidates/.*?/Questions", re.IGNORECASE)
    rx_question = re.compile(r"===+(.*?)===+", re.IGNORECASE)
    rx_user = re.compile(r"\[\[User.*?:(.*?)(?:[\|/].*)*\]\]", re.IGNORECASE)
    rx_from = re.compile(r"\s+from\s+", re.IGNORECASE)

    def __init__(self, *args, **kwargs):
        """Initilization method."""
        super().__init__(*args, **kwargs)
        self.users = { u: { MNAME: 0 } for u in get_usernames() }

    def processor(self):
        """Data processing method."""
        pages = self.coll.objects.aggregate(
            { '$match': {
                'prefix': 'Arbitration_Committee_Elections',
                'ns': 4,
                '$or': [
                    { 'title': self.rx_query1 },
                    { 'title': self.rx_query2 }
                ]
            } },
            { '$project': { '_id': 0, 'title': 1, 'source': 1 } }
        )
        # Compute
        for page in pages:
            src = page['source'].strip()
            questions = self.rx_question.findall(src)
            users = [ self.get_user(q) for q in questions ]
            for u in users:
                if u and u in self.users:
                    self.users[u][MNAME] += 1

        # Bulk update
        records = [ { 'user_name': k, **v } for k, v in self.users.items() ]
        bulk_ops = make_bulk_update(records, user_name='user_name')
        if bulk_ops:
            Metrics._get_collection().bulk_write(bulk_ops, ordered=False)

    def get_user(self, x):
        """Get user from question."""
        users = self.rx_user.findall(x)
        if users:
            user = users[-1].strip()
        else:
            user = self.rx_from.split(x)[-1].strip()
        return user

def data():
    """Make metric."""
    return Metric(
        out_name=NAME,
        out_dtype=DTYPE,
        coll=MODEL
    )


import os
import random

import bleach
import magic
from flask import Flask, render_template, request, session, \
    send_from_directory
from flask.ext.assets import Environment, Bundle
from flask.ext.login import current_user
from flask.json import dumps
from flask_wtf import CsrfProtect

from reactgur import database
from reactgur.api import user_api, media_api
from reactgur.api.user import login_manager, anonymous_user_data
from reactgur.mail import mail_session
from reactgur.models import Media
from reactgur.util import ExtensibleJSONEncoder

app = Flask(__name__)
app.json_encoder = ExtensibleJSONEncoder
try:
    app.config.from_object('config')
except:
    app.config.from_object('configdist')

app.register_blueprint(media_api)
app.register_blueprint(user_api)

csrf = CsrfProtect(app)

mail_session.init_app(app)

login_manager.init_app(app)

# Configure paths
root = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOAD_PATH'] = upload_path = os.path.join(root, '../uploads')
theme_path = os.path.join(root, 'static/theme')
try:
    theme_files = tuple([f for f in os.listdir(theme_path) \
                         if os.path.isfile(os.path.join(theme_path, f))])
except:
    theme_files = tuple()

assets = Environment(app)
assets.load_path = [
    root + '/../node_modules',
    root + '/../client/style',
    theme_path
]
js = Bundle(
    'isotope-layout/dist/isotope.pkgd.min.js',
    'isotope-packery/packery-mode.pkgd.min.js'
)
assets.register('js', js)
css = Bundle(
    'bootstrap/dist/css/bootstrap.min.css',
    'base.css',
    Bundle(*theme_files)
)
assets.register('css', css)

@app.teardown_appcontext
def shutdown_session(response):
    database.session.remove()

@app.route('/')
@app.route('/<path:filename>')
def index(filename=None):
    # Check if its an image to render
    if filename and os.path.exists(os.path.join(upload_path, filename)):
        return send_from_directory(upload_path, filename)
    context = dict(images=dumps(Media.get_latest()))
    context['app_name'] = app.config['APP_NAME']
    context['app_conf'] = dumps(dict(
        external_url=app.config['EXTERNAL_URL'],
        request_registration=app.config['REQUEST_REGISTRATION'],
        upload_requires_login=app.config['UPLOAD_REQUIRES_LOGIN']
    ))
    app_data = dict(
        user=anonymous_user_data,
        alerts=session.pop('alerts', [])
    )
    if current_user.is_authenticated():
        app_data['user'] = current_user
    context['app_data'] = dumps(app_data)
    return render_template('index.html', **context)