# About -----------------------------------------------------------------------------------

# Creator:
# Logan Masters
# email: logan.masters@nxp.com
# alt email: logan.masters3@gmail.com

# Usage:
# python liveness_detect.py

# Import libraries ------------------------------------------------------------------------

# Standard
import pickle
import time

# Third party
import tensorflow as tf
import numpy as np
import cv2

# Module level
from tensorflow.python.platform import gfile

# Initialization --------------------------------------------------------------------------

# loads Caffe face detector
print("[INFO] loading face detector...")
protoPath = "face_detector/deploy.prototxt"
modelPath = "face_detector/res10_300x300_ssd_iter_140000.caffemodel"
net = cv2.dnn.readNetFromCaffe(protoPath, modelPath)

# Create TF session
sess = tf.compat.v1.Session()

# Load liveness TF model
print("[INFO] loading liveness model...")
live_model = gfile.FastGFile("./trained_models/tf_liveness.pb", "rb")
live_graph_def = tf.GraphDef()
live_graph_def.ParseFromString(live_model.read())
live_model.close()
sess.graph.as_default()
tf.import_graph_def(live_graph_def)

# Load Labels
print("[INFO] loading labels...")
le = pickle.loads(open("le.pickle", "rb").read())

# Load recognition model and encoder
# print("[INFO] loading recognition model...")
# rec_model = tf.saved_model.load("saved_model.pb", "./trained_models/")
# re = pickle.loads(open("re.pickle", "rb").read())

# Initialize video feed with warm up period
print("[INFO] starting video stream...")
vs = cv2.VideoCapture(0)
time.sleep(2.0)

# Camera ----------------------------------------------------------------------------------

while True:
    # Capture and resize video feed
    ret, frame = vs.read()

    # Convert frame to blob type
    h = frame.shape[0]
    w = frame.shape[1]
    blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,
                                 (300, 300), (104.0, 177.0, 123.0))

    # Have the NN analyze the blob
    net.setInput(blob)
    detections = net.forward()

    for i in range(0, detections.shape[2]):
        # Determine prediction confidence
        confidence = detections[0, 0, i, 2]

        # Filter poor detections
        if confidence > .8:
            # Compute ROI coordinates
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            # Make sure ROI is in frame
            startX = max(0, startX)
            startY = max(0, startY)
            endX = min(w, endX)
            endY = min(h, endY)

            # Pre-process the ROI data
            face = frame[startY:endY, startX:endX]
            face = cv2.resize(face, (32, 32))
            face = face.astype("float") / 255.0
            face = np.asarray(face)
            face = np.expand_dims(face, axis=0)

            # Pass ROI to liveness detector
            softmax_tensor = sess.graph.get_tensor_by_name("import/activation_5/Softmax:0")
            liveness_predictions = sess.run(softmax_tensor, {"import/conv2d_input:0": face})
            j = np.argmax(liveness_predictions)
            live_label = le.classes_[j]
            live_label_indicator = live_label

            # Draw box and confidence label
            if liveness_predictions[0, 1] > .8:
                live_label = "{}: {:.4f}".format(live_label, liveness_predictions[0, 1])
                cv2.putText(frame, live_label, (startX, startY - 10),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
                cv2.rectangle(frame, (startX, startY), (endX, endY),
                              (0, 255, 0), 2)
            else:
                live_label = "{}: {:.4f}".format(live_label, liveness_predictions[0, 0])
                cv2.putText(frame, live_label, (startX, startY - 10),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
                cv2.rectangle(frame, (startX, startY), (endX, endY),
                              (0, 0, 255), 2)
            # if live_label_indicator == "real":
            #     # Pass live ROI's to recognition
            #     recognition_predictions = rec_model.predict(face)[0]
            #     j = np.argmax(recognition_predictions)
            #     rec_label = re.classes_[j]
            #     rec_label_indicator = rec_label
            #     rec_label = "{}: {:.4f}".format(rec_label, recognition_predictions[j])
            #     # Label frames with user
            #     if rec_label_indicator == "Unknown":
            #         cv2.putText(frame, rec_label, (startX, startY - 10),
            #                     cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
            #         cv2.rectangle(frame, (startX, startY), (endX, endY),
            #                       (255, 0, 0), 2)
            #     else:
            #         cv2.putText(frame, rec_label, (startX, startY - 10),
            #                     cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
            #         cv2.rectangle(frame, (startX, startY), (endX, endY),
            #                       (0, 255, 0), 2)
            # else:

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(20)

    # Exit on q
    if key == 27:
        break
cv2.destroyAllWindows()
vs.release()


import os
import random
import time
import copy
import argparse

import numpy as np
import pandas as pd

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import models
import torch.optim as optim
from torch.optim import lr_scheduler

from data_helper import UnlabeledDataset
from helper import collate_fn, draw_box
from ResNet import ResNet

def worker_init_fn(worker_id):
    np.random.seed(np.random.get_state()[1][0] + worker_id)

def generate_rotation_data(images, post_transforms):

    images_tensor = []
    expected_outputs =[]
    for image in images:
        # perform rotation
        image = image.resize((64, 64))

        rot_class = np.random.randint(4)
        rot_angle = rot_class * 90

        rot_image = image.rotate(rot_angle)

        sample = post_transforms(rot_image)

        images_tensor.append(sample)

        expected_outputs.append(rot_class)

    images = torch.stack(images_tensor)
    expected_outputs = torch.LongTensor(expected_outputs)

    return images, expected_outputs

def train_model(model, dataloaders, data_generator, train_post_transforms, criterion, optimizer, device, checkpoint_path, f, verbIter, num_epochs=25, scheduler = None, save_freq = 1):
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        f.write('Epoch {}/{} \n'.format(epoch, num_epochs - 1))
        f.write('-' * 10)
        f.write('\n')
        f.flush()

        np.random.seed()

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0
            n_samples = 0

            end = time.time()

            # Iterate over data.
            for batch_num, (images, indexes) in enumerate(dataloaders[phase]):

                inputs, labels = data_generator(images, train_post_transforms)

                data_time = time.time() - end
                inputs = inputs.to(device)
                labels = labels.to(device)
                # zero the parameter gradients
                optimizer.zero_grad()
                batchSize = inputs.size(0)
                n_samples += batchSize

                # forward
                # track history if only in train
                forward_start_time  = time.time()
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()
                        if scheduler is not None:
                            scheduler.step()
                forward_time = time.time() - forward_start_time

                # statistics
                running_loss += loss.item() * inputs.size(0)
                pred_top_1 = torch.topk(outputs, k=1, dim=1)[1]
                running_corrects += pred_top_1.eq(labels.view_as(pred_top_1)).int().sum().item()

                if batch_num % verbIter == 0:
                    # Metrics
                    top_1_acc = running_corrects/n_samples
                    epoch_loss = running_loss / n_samples

                    f.write('{} Loss: {:.4f} Top 1 Acc: {:.4f} \n'.format(phase, epoch_loss, top_1_acc))
                    f.write('Full Batch time: {} , Data load time: {} , Forward time: {}\n'.format(time.time() - end, data_time, forward_time))
                    f.flush()

                end = time.time()

            # Metrics
            top_1_acc = running_corrects/n_samples
            epoch_loss = running_loss / n_samples

            f.write('{} Loss: {:.4f} Top 1 Acc: {:.4f} \n'.format(phase, epoch_loss, top_1_acc))
            f.flush()

            # deep copy the model
            if phase == 'val' and top_1_acc > best_acc:
                best_acc = top_1_acc
                best_model_wts = copy.deepcopy(model.state_dict())
                torch.save(model.state_dict(), '%s/best_rotation_net.pt' % (checkpoint_path))

        if (epoch + 1) % save_freq == 0:
            torch.save(model.state_dict(), '%s/rotation_net_epoch_%d.pt' % (checkpoint_path, epoch))

    time_elapsed = time.time() - since
    f.write('Training complete in {:.0f}m {:.0f}s \n'.format(time_elapsed // 60, time_elapsed % 60))
    f.write('Best val Acc: {:4f} \n'.format(best_acc))
    f.flush()

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

def get_args():
    parser 	= argparse.ArgumentParser(description="MonoLayout options")
    parser.add_argument("--data_path", type=str, default="../artifacts/data",
                         help="Path to the root data directory")
    parser.add_argument("--save_path", type=str, default="../artifacts/models/rotation_ssl",
                         help="Path to save models")
    parser.add_argument("--batch_size", type=int, default=16,
                         help="Mini-Batch size")
    parser.add_argument("--num_epochs", type=int, default=100,
                         help="Max number of training epochs")
    parser.add_argument("--save_freq", type=int, default=5,
                         help="Model saving frequency")
    parser.add_argument("--lr", type=float, default=0.003,
                         help="Model saving frequency")

    return parser.parse_args()

def main():

    opt = get_args()

    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

    data_dir = opt.data_path

    image_folder = data_dir
    annotation_csv = f'{data_dir}/annotation.csv'

    batch_size = opt.batch_size

    train_pre_transforms = torchvision.transforms.Compose([
        torchvision.transforms.RandomHorizontalFlip()
    ])

    val_pre_transforms = torchvision.transforms.Compose([
    ])

    train_post_transforms = torchvision.transforms.Compose([
        torchvision.transforms.ToTensor(),
        torchvision.transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
    ])

    val_post_transforms = torchvision.transforms.Compose([
        torchvision.transforms.ToTensor(),
        torchvision.transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
    ])

    train_set = UnlabeledDataset(
        image_folder = image_folder,
        scene_index = np.arange(0, 101),
        first_dim = 'image',
        transform = train_pre_transforms
    )

    train_loader = torch.utils.data.DataLoader(
        train_set,
        batch_size=batch_size,
        shuffle=True,
        num_workers=2,
        worker_init_fn=worker_init_fn,
        collate_fn=collate_fn
    )

    val_set = UnlabeledDataset(
        image_folder = image_folder,
        scene_index = np.arange(101, 106),
        first_dim = 'image',
        transform = val_pre_transforms
    )

    val_loader = torch.utils.data.DataLoader(
        val_set,
        batch_size=batch_size,
        shuffle=True,
        num_workers=2,
        worker_init_fn=worker_init_fn,
        collate_fn=collate_fn
    )

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

    fc_layer = nn.Sequential(nn.Linear(512, 512),
                                    nn.ReLU(),
                                    nn.Dropout(0.2),
                                    nn.Linear(512, 4),
                                    nn.LogSoftmax(dim=1))

    model = ResNet(pretrained = False, ssl_pretrained = False, ssl_pretrained_dict_path = '', fc_layer=fc_layer).model

    model = model.to(device)

    dataloaders = {}
    dataloaders['train'] = train_loader
    dataloaders['val'] = val_loader

    criterion = nn.NLLLoss()
    optimizer_conv = optim.Adam(model.parameters(), lr=opt.lr)

    f = open("{}/training_logs.txt".format('.'), "w+")

    if not os.path.isdir(opt.save_path):
        os.makedirs(opt.save_path)

    checkpoint_path = opt.save_path

    model_ft = train_model(model, dataloaders, generate_rotation_data, train_post_transforms, criterion, optimizer_conv, device, checkpoint_path, f, verbIter=100, num_epochs=opt.num_epochs, save_freq=opt.save_freq)

if __name__ == "__main__":
    main()


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

# Copyright 2017 CNRS and University of Strasbourg
#
# 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.

"""A set of tools for manipulating mapping file
"""

import json

from oslo_config import cfg
from oslo_log import log

CONF = cfg.CONF

LOG = log.getLogger(__name__)

class Mapping(object):
    """An object for managing the VO / project mapping
    """
    def __init__(self, default_domain_name='Default'):
        self.vo_mapping = {}
        self.project_mapping = {}
        self.domain_mapping = {}
        try:
            mapping = json.loads(open(CONF.mapping_file).read())
            for (vo_name, details) in mapping.items():
                if 'project' in details:
                    project_name = details['project']
                elif 'tenant' in details:
                    project_name = details['tenant']
                else:
                    LOG.error(
                        "The project for the %s VO is not defined " +
                        "in the %s mapping file" % (vo_name, CONF.mapping_file)
                    )
                    continue
                self.vo_mapping[vo_name] = project_name
                self.project_mapping[project_name] = vo_name
                if 'domain' in details:
                    self.domain_mapping[project_name] = details['domain']
                else:
                    self.domain_mapping[project_name] = default_domain_name
        except IOError:
            LOG.error("Failed to open mapping file.")

    def get_project_from_vo(self, vo_name):
        """Return the project associated to the VO
        """
        if vo_name in self.vo_mapping:
            return self.vo_mapping[vo_name]
        else:
            LOG.error("No such VO '%s' in the mapping file." % (vo_name))
            return None

    def get_domain_from_project(self, project_name):
        """Return the domain associated to the project
        """
        if project_name in self.domain_mapping:
            return self.domain_mapping[project_name]

    def get_vo_from_project(self, project):
        """Return the VO associated to the project
        """
        if project in self.project_mapping:
            return self.project_mapping[project]
        else:
            LOG.error("No such project '%s' in the mapping file." % (project))
            return None

    def get_vos(self):
        """Return the list of supported VOs
        """
        return self.vo_mapping.keys()

    def get_projects(self):
        """Return the list of VO-related project
        """
        return self.project_mapping.keys()


import torch
import torch.nn as nn

import torch
import torch.nn as nn

from torch.distributions.categorical import Categorical
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence

num_voices = 1
class Encoder(nn.Module):

    def __init__(self, vocab_size, hidden_size, latent_size, seq_size, num_layers):
        super(Encoder,self).__init__()
        self.RNN = nn.GRU(vocab_size, hidden_size, batch_first=True,
                        num_layers=num_layers, bidirectional = True)

        self.hidden_to_mu = nn.Linear(2*hidden_size, latent_size)
        self.hidden_to_sig = nn.Linear(2*hidden_size, latent_size)
        self.softplus = nn.Softplus()

        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.num_layers = num_layers
        self.one_hot = torch.eye(vocab_size).to(device)

    def forward(self,x):
        batch_size = x.shape[0]

        _, h = self.RNN(self.one_hot[x])

        h = h.view(self.num_layers, 2, batch_size, -1)[-1].view(batch_size,-1)
        mu = self.hidden_to_mu(h)
        sig = self.softplus(self.hidden_to_sig(h))
        return mu, sig

    def flatten_parameters(self):
        self.RNN.flatten_parameters()

class Decoder(nn.Module):

    def __init__(self, latent_size, hidden_size, vocab_size, num_layers, seq_size):
        super(Decoder, self).__init__()
        #self.latent_to_hidden = nn.Linear(latent_size, hidden_size)
        #self.hidden_to_P1_hidden = nn.Linear(hidden_size, num_voices*num_layers*hidden_size)
        self.latent_to_hidden = nn.Linear(latent_size, num_voices*num_layers*hidden_size)
        self.hidden_to_vocab = nn.Linear(hidden_size, vocab_size)
        #self.P2_to_vocab = nn.Linear(hidden_size, vocab_size)

        self.RNN = nn.GRU(vocab_size + latent_size, hidden_size, batch_first = True, num_layers=num_layers)
        self.tanh = nn.Tanh()

        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.one_hot = torch.eye(vocab_size).to(device)
        self.num_layers = num_layers
        self.vocab_size = vocab_size
        self.seq_size = seq_size

    def forward(self, latent, temp, x, teacher_forcing, logits=False):
        batch_size = latent.shape[0]
        # latent = latent[indices]
        #hidden = self.tanh(self.latent_to_hidden(latent))

        hidden = self.tanh(self.latent_to_hidden(latent))
        hidden = hidden.view(self.num_layers, batch_size, -1)

        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        zeros = torch.zeros(batch_size,1).long().to(device)

        input = torch.cat((latent.unsqueeze(1),self.one_hot[zeros]),2)
        result = []

        for i in range(self.seq_size):
            output, hidden = self.RNN(input, hidden)
            output = self.hidden_to_vocab(output)

            if temp:
                res = Categorical(logits=   output/temp).sample()
            else:
                res = torch.argmax(output, 2)
            if logits:
                result.append(output)
            else:
                result.append(res)
            if torch.rand(1) < teacher_forcing:
                input = self.one_hot[x[:,i].unsqueeze(1)]
            else:
                input =  self.one_hot[res]
            input = torch.cat((latent.unsqueeze(1), input),2)
        return torch.cat(result,1)

    def flatten_parameters(self):
        self.RNN.flatten_parameters()


from random import choice
import pygame
import pygame.freetype
from settings import Settings

class Text:
    """A class to manage the quote appearing on screen"""

    def __init__(self, t_game):
        """Initilize colour attributes and set text location"""

        # Assign screen to attribute of Text.
        # Getting screen rectangle from Typist.
        self.screen = t_game.screen
        self.screen_rect = t_game.screen.get_rect()
        self.settings = t_game.settings

        # Assigning RGB values to colours.
        self.white = (255, 255, 255)
        self.green = (0, 255, 0)
        self.grey = (128,128,128)

        # Creating a font instance. And setting text variables.
        self.font = pygame.freetype.Font('leorio.ttf', 32)
        self.font.origin = True
        self.reset_text()

    # 1. Getting a quote from a list.
    # 2. Setting curent index to zero to select 1st index.
    # 3. Calculate dimensions of the text.
    # 4. Find baseline. font.origin is set to true, so the baseline will
    # be the y-coordinate of the text origin. This function accesses the
    # 'y' attribute of the text rectangle.
    # 5. Create a surface to render the text on using the size of the
    # created rect.
    # 6. Fill created surface with background colour.
    # 7. Allign center of text rect with center of screen rect.
    # 8. Calculate width and other metrics of each letter of the text.
    # Glyph metrics are returned as a list of tuples , with each tuple
    # giving metrics of single character. Horizontal advance is position 4.
    def reset_text(self):
        self.text = self.get_random_quote()
        self.current_index = 0
        self.text_rect = self.font.get_rect(self.text) #1
        self.baseline = self.text_rect.y #2
        self.text_surf = pygame.Surface(self.text_rect.size) #3
        self.text_surf.fill(self.settings.bg_color) #4
        self.text_rect.center = self.screen_rect.center #5
        self.metrics = self.font.get_metrics(self.text) #6

    def get_random_quote(self):
        """Returns a random quote from a list of quotes."""
        filename = 'quotes.txt'
        with open(filename, 'r', encoding = 'UTF-8') as f:
            lines = f.readlines()
            quote = choice(lines).strip()

        return f'"{quote}"'

    def correct_key_press_colours(self):
        """Causes text on screen to be rendered a certain colour depending on
        what the current index is"""
        x = 0
        for (idx, (letter, metric)) in enumerate(zip(self.text, self.metrics)):
            if idx == self.current_index:
                color = self.white
            elif idx < self.current_index:
                color = self.green
            else:
                color = self.grey
            self.font.render_to(
                    self.text_surf,
                    (x, self.baseline),
                    letter, color, self.settings.bg_color)
            x += metric[4]

    def blitme(self):
        """Draws text to screen"""
        self.correct_key_press_colours()
        # Blitting text suface to text rectangle size
        self.screen.blit(self.text_surf, self.text_rect)


# -*- coding: utf-8 -*-
from rest_framework.test import APITransactionTestCase
from tiny_urls.users.models import User

class TestUserRetrieve(APITransactionTestCase):
    def setUp(self):
        self.user = User.objects.create(email='williandmorais@gmail.com')
        self.client.force_authenticate(self.user)

    def test_retrieve(self):
        response = self.client.get(
            '/users/{}/'.format(self.user.id)
        )

        self.assertDictEqual(response.json(), {'email': 'williandmorais@gmail.com', 'id': 41})
        self.assertEqual(response.status_code, 200)

    def test_retrieve_not_found(self):
        response = self.client.get(
            '/users/100/'
        )

        self.assertDictEqual(response.json(), {'detail': 'Not found.'})
        self.assertEqual(response.status_code, 404)


from __future__ import print_function

import json
import os.path
import pickle
from pprint import pprint

import discord
from discord.ext import commands
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

with open('ids.json') as json_file:
    data = json.load(json_file)

SCOPES = ['https://www.googleapis.com/auth/spreadsheets/']
SPREADSHEET_ID = data['spreadsheetID']
BOT_TOKEN = data['botToken']
SPREADSHEETS_CONNECTED = False

# init Google Spreadsheets API
print('Connecting to Google Sheets API...')
creds = None
try:
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', 'https://www.googleapis.com/auth/spreadsheets')
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('sheets', 'v4', credentials=creds)
    sheet = service.spreadsheets()
    SPREADSHEETS_CONNECTED = True
    print('Connected to Google Sheets API')

except Exception as e:
    print('Unable to connected to Google Sheets')
    print(f'Error occured: {e}')

# init Discord bot API

print('Connecting to Discord bot API...')
bot = commands.Bot(command_prefix='?')

@bot.event
async def on_ready():
    print(f'Logged in as:\n{bot.user.name}\n{bot.user.id}\n------')

# bot commands

#init bot command for spreadsheet
if SPREADSHEETS_CONNECTED:
    @bot.command()
    async def mapwr(ctx, map: str):
        result = sheet.values().batchGet(spreadsheetId=SPREADSHEET_ID, ranges=['Sheet1!H6:H26','Sheet1!L6:L26']).execute()
        mdata = result.get('valueRanges',[])
        maps = [''.join(x) for x in mdata[0]['values']]
        winrates = [''.join(x) for x in mdata[1]['values']]
        mapwr_dict = dict(zip(maps, winrates))
        try:
            winrate = mapwr_dict[map.upper()]
            if winrate == '-':
                await ctx.send('No data')
            else:
                await ctx.send(f'{map}:{winrate}')
        except:
            await ctx.send('Invalid map')

    @bot.command()
    async def addmap(ctx, *args):
        if len(args) == 0:
            await ctx.send('Format(quotes are required): "Date", "Team", "Result", "Map", "Score", "Notes"')
        elif len(args) == 6:
            response = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range='Sheet1!A6:A', valueRenderOption='UNFORMATTED_VALUE').execute()
            offset = len(response['values']) + 6
            response = sheet.values().append(spreadsheetId=SPREADSHEET_ID, range=f'Sheet1!A{offset}', insertDataOption='INSERT_ROWS', valueInputOption='RAW', body={'majorDimension': 'ROWS', 'values':[[date, team, result, map, score, notes]]}).execute()
        else:
            await ctx.send('Invalid number of arguments')

@bot.command()
async def patchnotes(ctx):
    await ctx.send('https://www.esportstales.com/overwatch/list-all-hero-updates-and-balance-changes')

bot.run(BOT_TOKEN)


DOB = 2000
age = 2017 - DOB
name = "Haziz"
ageMessage = "hey! your age is {}".format(age)
greetingsWithAge = "Hey! {}, your age is {}".format(name, age);
l = upper(greetingsWithAge)
print(DOB)
print(age)
print(ageMessage)
print(greetingsWithAge)


# Given an array of integers, return indices of the two numbers such that they add up to a specific target.
#
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
#
# Example:
#
#
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
#
#

#
# @lc app=leetcode id=1 lang=python3
#
# [1] Two Sum
#
# https://leetcode.com/problems/two-sum/description/
#
# algorithms
# Easy (44.25%)
# Likes:    11020
# Dislikes: 372
# Total Accepted:    1.9M
# Total Submissions: 4.2M
# Testcase Example:  '[2,7,11,15]\n9'
#
# Given an array of integers, return indices of the two numbers such that they
# add up to a specific target.
#
# You may assume that each input would have exactly one solution, and you may
# not use the same element twice.
#
# Example:
#
#
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
#
#
#
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if not nums or len(nums) < 2:
            return nums

        hashtable = {}
        count = 0
        for number in nums:
            if target - number not in hashtable:
                hashtable[number] = count
            else:
                return [hashtable[target - number] , count]
            count += 1
        return []


from bs4 import BeautifulSoup

"""

define meats, herbs, and sauces dictionary

"""
non_chinese_herbs = ['asafoetida', 'achiote', 'allspice', 'cardamom', 'cayenne',\
                'gochugaru', 'grains of paradise', 'kaffir', 'loomi', 'mace', 'mahlab',\
                'nutmeg', 'paprika', 'saffron', 'suman', 'tumeric', 'chervil',\
                'dill', 'fenugreek', 'lovage', 'marjoram', 'mint',\
                'oregano', 'thyme', 'bay leaves', 'rosemary', 'sage', \
                'parsley', 'chili powder', 'chili flakes', 'garlic',\
                'sumemr savory','shiso', 'tarragon', 'baharat', 'bebere', 'bouquet garni', \
                'chili powder', 'dukkah', 'garam masala', 'herbes de provence', 'old bay', \
                'pickling spice', 'ras el hanout', 'shichimi togarashi', "za'atar", "taco seasoning"]

non_chinese_fish = ['salmon', 'tuna','sardine','herring','tilapia','catfish','trout','mackerel','anchovy','perch','pike']
non_chinese_sauces = ['ginger','salsa','guacamole','picante','tomato','alfredo','mushroom','steak','barbecue','marinara','mayonnaise','tartar','garlic']
non_chinese_lipids = ['butter','olive oil','coconut oil','avocado oil','canola oil','vegetable oil']
non_chinese_peppers = ['jalapeno','habanero','chipotle']
non_chinese_noodles = ['spaghetti noodle','fettuccine noodle','fettuccini noodle','capellini noodle','angel hair noodle','tagliatelle noodle','linguine noodle']
non_chinese_grains = ['penne','orzo','farfelle','macaroni','rotini','rigatoni','gnocchi']
non_chinese_vinegar = ['balsamic vinegar','red wine vinegar','sherry vinegar','apple cider vinegar']

# create dictionary
chinese_dict = dict.fromkeys(non_chinese_sauces[:4], 'soy sauce')
chinese_dict.update(dict.fromkeys(non_chinese_fish[4:8], 'hoison sauce'))
chinese_dict.update(dict.fromkeys(non_chinese_fish[8:], 'sweet and sour sauce'))
chinese_dict['browning sauce'] = 'soy sauce'
chinese_dict['pinto beans'] = 'soybeans'
chinese_dict['black beans'] = 'soybeans'
chinese_dict['refried beans'] = 'soybeans'
chinese_dict['chive'] = 'chinese chive'
chinese_dict['basil'] = 'thai basil'
chinese_dict['bison'] = 'beef'
chinese_dict.update(dict.fromkeys(non_chinese_vinegar[:], 'rice vinegar'))
chinese_dict.update(dict.fromkeys(non_chinese_grains[:], 'white rice'))
chinese_dict.update(dict.fromkeys(non_chinese_noodles[:], 'wheat noodle'))
chinese_dict.update(dict.fromkeys(non_chinese_peppers[:], 'chili'))
chinese_dict.update(dict.fromkeys(non_chinese_lipids[:], 'sesame oil'))
chinese_dict.update(dict.fromkeys(non_chinese_fish[:4], 'sea bass'))
chinese_dict.update(dict.fromkeys(non_chinese_fish[4:8], 'cod'))
chinese_dict.update(dict.fromkeys(non_chinese_fish[8:], 'haddock'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[:5], 'coriander'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[5:10], 'thai basil'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[10:15], 'lemongrass'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[15:20], 'star anise'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[20:25], 'fenugreek'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[25:30], 'galangal'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[30:35], 'cloves'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[35:40], 'turmeric'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[40:45], 'five-spice'))
chinese_dict.update(dict.fromkeys(non_chinese_herbs[45:], 'cumin'))

"""

helper functions for making recipe chinese

"""
def check_corn_beef(string):
    words = string.lower().split()
    idx = words.index('beef')
    if words[idx - 1] == 'corn':
        return 1
    if words[idx - 1] == 'corned':
        return 2
    else:
        return 0

def check_sauce(string):
    words = string.lower().replace(",", "").split()
    if words.count('sauce') > 1:
        idx = words.index('sauce')
        del words[idx]
        s = " "
        return s.join(words)
    else:
        return string

"""

make recipe chinese

"""

def chinese(recipe):
    directions = recipe['directions']
    ingredients = recipe['ingredients']
    sub_keys = chinese_dict.keys()

    i = 0
    for base_ing in ingredients:
        base_ing = base_ing.lower()
        corn = 0
        for sub_ing in sub_keys:
            if sub_ing in base_ing:
                if sub_ing is 'beef':
                    corn = check_corn_beef(base_ing)
                if corn == 1:
                    ingredients[i] = ingredients[i].replace('corn beef', chinese_dict[sub_ing])
                    break
                if corn == 2:
                    ingredients[i] = ingredients[i].replace('corned beef', chinese_dict[sub_ing])
                    break
                else:
                    ingredients[i] = ingredients[i].lower().replace(sub_ing, chinese_dict[sub_ing])

        # remove second 'sauce'
        if 'sauce' in ingredients[i].lower().replace(",", ""):
            ingredients[i] = check_sauce(ingredients[i])

        i += 1

    i = 0
    for step in directions:
        step = step.lower()
        for sub_ing in sub_keys:
            s = step.lower().replace(".", "")
            if sub_ing in s:
                directions[i] = directions[i].lower().replace(sub_ing, chinese_dict[sub_ing])

        # remove second 'sauce'
        if 'sauce' in directions[i].lower():
            directions[i] = check_sauce(directions[i])
        i += 1

    return directions, ingredients


print('##' * 10)
print('\033[36mCALCULADORA DE JUROS\033[m')
print('##' * 10)

preco = float(input('Digite o preço do produto: '))
formadepag = int(input('''Forma de pagamento?
1 para dinheiro ou cheque
2 para à vista no cartão
3 para parcelado no cartão
'''))
if formadepag == 3:
    parcelas = int(input('Qual a quantidade de parcelas?'))

print('#' * 9)
print('\033[7mRESULTADO\033[m')
print('#' * 9)

if formadepag == 1:
    print('O preço a ser pago à vista é de \033[0;32mR${:.2f}\033[m.'.format(preco * 0.90))
elif formadepag == 2:
    print('O preço a ser pago à vista no cartão é de \033[0;32mR${:.2f}\033[m.'.format(preco * 0.95))
elif formadepag == 3:
    if parcelas == 2:
        print('O preço a ser pago em duas parcelas é de \033[0;32mR${:.2f}\033[m , totalizando  \033[0;32mR${:.2f}\033[m.'
              .format(preco / parcelas, preco))
    elif parcelas >= 3:
        totaljuros = preco * 1.20
        parcelajuros = totaljuros / parcelas
        print('O preço a ser pago em {} parcelas é de \033[0;32mR${:.2f}\033[m , totalizando \033[0;32mR${:.2f}\033[m.'
            .format(parcelas, parcelajuros, totaljuros))


"""
np.atan and its derivative have been replaced by methods in the class. They can
now be extedned and overloaded. See bottom for my overload with ReLU.
"""

import numpy as np
import mlutilities as ml
import matplotlib.pyplot as plt
from copy import copy
import time

class NeuralNetwork:

    def __init__(self, ni, nhs, no):

        if isinstance(nhs, list) or isinstance(nhs, tuple):
            if len(nhs) == 1 and nhs[0] == 0:
                nihs = [ni]
                nhs = []
            else:
                nihs = [ni] + list(nhs)
        else:
            if nhs > 0:
                nihs = [ni, nhs]
                nhs = [nhs]
            else:
                nihs = [ni]
                nhs = []

        if len(nihs) > 1:
            self.Vs = [1/np.sqrt(nihs[i]) *
                       np.random.uniform(-1, 1, size=(1 + nihs[i], nihs[i + 1])) for i in range(len(nihs) - 1)]
            self.W = 1/np.sqrt(nhs[-1]) * np.random.uniform(-1, 1, size=(1 + nhs[-1], no))
        else:
            self.Vs = []
            self.W = 1 / np.sqrt(ni) * np.random.uniform(-1, 1, size=(1 + ni, no))
        self.ni, self.nhs, self.no = ni, nhs, no
        self.Xmeans = None
        self.Xstds = None
        self.Tmeans = None
        self.Tstds = None
        self.trained = False
        self.reason = None
        self.errorTrace = None
        self.numberOfIterations = None
        self.trainingTime = None

    def __repr__(self):
        str = 'NeuralNetwork({}, {}, {})'.format(self.ni, self.nhs, self.no)
        # str += '  Standardization parameters' + (' not' if self.Xmeans == None else '') + ' calculated.'
        if self.trained:
            str += '\n   Network was trained for {} iterations that took {:.4f} seconds. Final error is {}.'.format(self.numberOfIterations, self.getTrainingTime(), self.errorTrace[-1])
        else:
            str += '  Network is not trained.'
        return str

    def _standardizeX(self, X):
        result = (X - self.Xmeans) / self.XstdsFixed
        result[:, self.Xconstant] = 0.0
        return result

    def _unstandardizeX(self, Xs):
        return self.Xstds * Xs + self.Xmeans

    def _standardizeT(self, T):
        result = (T - self.Tmeans) / self.TstdsFixed
        result[:, self.Tconstant] = 0.0
        return result

    def _unstandardizeT(self, Ts):
        return self.Tstds * Ts + self.Tmeans

    def _pack(self, Vs, W):
        return np.hstack([V.flat for V in Vs] + [W.flat])

    def _unpack(self, w):
        first = 0
        numInThisLayer = self.ni
        for i in range(len(self.Vs)):
            self.Vs[i][:] = w[first:first + (1 + numInThisLayer) *
                              self.nhs[i]].reshape((1 + numInThisLayer, self.nhs[i]))
            first += (numInThisLayer+1) * self.nhs[i]
            numInThisLayer = self.nhs[i]
        self.W[:] = w[first:].reshape((1 + numInThisLayer, self.no))

    def _objectiveF(self, w, X, T):
        self._unpack(w)
        # Do forward pass through all layers
        Zprev = X
        for i in range(len(self.nhs)):
            V = self.Vs[i]
            Zprev = self.activation(Zprev @ V[1:, :] + V[0:1, :])  # handling bias weight without adding column of 1's
        Y = Zprev @ self.W[1:, :] + self.W[0:1, :]
        return 0.5 * np.mean((T - Y)**2)

    def _gradientF(self, w, X, T):
        self._unpack(w)
        # Do forward pass through all layers
        Zprev = X
        Z = [Zprev]
        for i in range(len(self.nhs)):
            V = self.Vs[i]
            Zprev = self.activation(Zprev @ V[1:, :] + V[0:1, :])
            Z.append(Zprev)
        Y = Zprev @ self.W[1:, :] + self.W[0:1, :]
        # Do backward pass, starting with delta in output layer
        delta = -(T - Y) / (X.shape[0] * T.shape[1])
        dW = np.vstack((np.ones((1, delta.shape[0])) @ delta,
                        Z[-1].T @ delta))
        dVs = []
        delta = (self.activation_derivative(Z[-1])) * (delta @ self.W[1:, :].T)
        for Zi in range(len(self.nhs), 0, -1):
            Vi = Zi - 1  # because X is first element of Z
            dV = np.vstack((np.ones((1, delta.shape[0])) @ delta,
                            Z[Zi-1].T @ delta))
            dVs.insert(0, dV)
            delta = (delta @ self.Vs[Vi][1:, :].T) * (1 - Z[Zi-1]**2)
        return self._pack(dVs, dW)

    def train(self, X, T, nIterations=100, verbose=False,
              weightPrecision=0, errorPrecision=0, saveWeightsHistory=False):

        if self.Xmeans is None:
            self.Xmeans = X.mean(axis=0)
            self.Xstds = X.std(axis=0)
            self.Xconstant = self.Xstds == 0
            self.XstdsFixed = copy(self.Xstds)
            self.XstdsFixed[self.Xconstant] = 1
        X = self._standardizeX(X)

        if T.ndim == 1:
            T = T.reshape((-1, 1))

        if self.Tmeans is None:
            self.Tmeans = T.mean(axis=0)
            self.Tstds = T.std(axis=0)
            self.Tconstant = self.Tstds == 0
            self.TstdsFixed = copy(self.Tstds)
            self.TstdsFixed[self.Tconstant] = 1
        T = self._standardizeT(T)

        startTime = time.time()

        scgresult = ml.scg(self._pack(self.Vs, self.W),
                            self._objectiveF, self._gradientF,
                            X, T,
                            xPrecision=weightPrecision,
                            fPrecision=errorPrecision,
                            nIterations=nIterations,
                            verbose=verbose,
                            ftracep=True,
                            xtracep=saveWeightsHistory)
        self._unpack(scgresult['x'])
        self.reason = scgresult['reason']
        self.errorTrace = np.sqrt(scgresult['ftrace']) # * self.Tstds # to _unstandardize the MSEs
        self.numberOfIterations = len(self.errorTrace)
        self.trained = True
        self.weightsHistory = scgresult['xtrace'] if saveWeightsHistory else None
        self.trainingTime = time.time() - startTime
        return self

    def use(self, X, allOutputs=False):
        Zprev = self._standardizeX(X)
        Z = [Zprev]
        for i in range(len(self.nhs)):
            V = self.Vs[i]
            Zprev = self.activation(Zprev @ V[1:, :] + V[0:1, :])
            Z.append(Zprev)
        Y = Zprev @ self.W[1:, :] + self.W[0:1, :]
        Y = self._unstandardizeT(Y)
        return (Y, Z[1:]) if allOutputs else Y

    def getNumberOfIterations(self):
        return self.numberOfIterations

    def getErrors(self):
        return self.errorTrace

    def getTrainingTime(self):
        return self.trainingTime

    def getWeightsHistory(self):
        return self.weightsHistory

    def draw(self, inputNames=None, outputNames=None, gray=False):
        ml.draw(self.Vs, self.W, inputNames, outputNames, gray)

    def activation(self, weighted_sum):
        return np.tanh(weighted_sum)

    def activation_derivative(self, activation_value):
        return 1 - activation_value * activation_value

class NeuralNetwork_relu(NeuralNetwork):
    """Inherit from NeuralNetwork to overload some of its methods."""

    def activation(self, weighted_sum):
        """
        This is the definition of relu. We use numpy's max so it works with vectors.
        Plus, it can broadcast the zero, so it looks clean.
        """
        return np.maximum(weighted_sum, 0)

    def activation_derivative(self, activation_value):
        """
        ReLU(x) = max(x, 0), so ReLU'(x) = 1 for x > 0, 0 for x < 0. Technically, undefined at x = 0.

        Also, ReLU(x) > 0 => x > 0, so ReLU'(x) = ReLU'(ReLU(x)). This is weird, but helps with the programming
        since ReLU(x) is what's passed.
        """
        yp = np.zeros_like(activation_value) # build a vector, or scalar, like what was passed
        yp[activation_value > 0] = 1 # where ReLU(x) > 0, set derivative to 1 (see math above).
        return yp


import pytest
#import unittest.mock as mock
#from woqlclient import WOQLQuery
#from woqlclient import WOQLClient
import woqlclient as woql
from woqlclient.woqlDataframe import EmptyException
#import woqlClient as woql
import numpy as np

MOCK_RESULT = {'bindings': [{'http://terminusdb.com/woql/variable/Product': {'@type': 'http://www.w3.org/2001/XMLSchema#string',
    '@value': 'STRAWBERRY CANDY'},
   'http://terminusdb.com/woql/variable/Qty': {'@type': 'http://www.w3.org/2001/XMLSchema#decimal',
    '@value': 10},
   'http://terminusdb.com/woql/variable/Stock': 'http://195.201.12.87:6365/rational_warehouse/document/Stock110_101752_2019-12-22T00%3A00%3A00',
   'http://terminusdb.com/woql/variable/Warehouse': {'@language': 'en',
    '@value': 'Pittsburg'},
   'http://terminusdb.com/woql/variable/buyers_buy_product': 'http://195.201.12.87:6365/rational_warehouse/document/Product101752',
   'http://terminusdb.com/woql/variable/stockDate': {'@type': 'http://www.w3.org/2001/XMLSchema#dateTime',
    '@value': '2019-12-22T00:00:00'},
   'http://terminusdb.com/woql/variable/warehouseCode': 'http://195.201.12.87:6365/rational_warehouse/document/Warehouse110'},
], "graphs": []}

TEST_TYPE=[('http://www.w3.org/2001/XMLSchema#string', np.unicode_),
('http://www.w3.org/2001/XMLSchema#integer', np.int),
('http://www.w3.org/2001/XMLSchema#dateTime', np.datetime64),
('http://www.w3.org/2001/XMLSchema#decimal', np.double),
]

TEST_TYPE_VALUE=[('http://www.w3.org/2001/XMLSchema#string', '10',  '10'),
('http://www.w3.org/2001/XMLSchema#integer', '10', 10),
('http://www.w3.org/2001/XMLSchema#dateTime', '2019-12-22T00:00:00', np.datetime64('2019-12-22T00:00:00')),
('http://www.w3.org/2001/XMLSchema#decimal', '10.10', 10.1),
]

class TestWoqlDataFrame:

    def test_extract_header_method(self):
        df_header = woql.extract_header(MOCK_RESULT)
        assert df_header == [('Product', 'http://www.w3.org/2001/XMLSchema#string'), ('Qty', 'http://www.w3.org/2001/XMLSchema#decimal'), ('Stock', 'http://www.w3.org/2001/XMLSchema#string'), ('Warehouse', 'http://www.w3.org/2001/XMLSchema#string'), ('buyers_buy_product', 'http://www.w3.org/2001/XMLSchema#string'), ('stockDate', 'http://www.w3.org/2001/XMLSchema#dateTime'), ('warehouseCode', 'http://www.w3.org/2001/XMLSchema#string')]

    def test_extract_header_method_empty(self):
        with pytest.raises(EmptyException):
            df_header = woql.extract_header({'bindings': []})

    def test_extract_column_method(self):
        df_column = woql.extract_column(MOCK_RESULT, 'Product',
        'http://www.w3.org/2001/XMLSchema#string')
        assert df_column == ['STRAWBERRY CANDY']

    @pytest.mark.parametrize("data_type,expected", TEST_TYPE)
    def test_type_map_method(self, data_type, expected):
        assert woql.type_map(data_type) == expected

    def test_type_map_method_unknown(self):
        with pytest.raises(Exception, match=r"Unknown rdf type! .*"):
            woql.type_map("some type that cause error")

    @pytest.mark.parametrize("data_type, value, expected", TEST_TYPE_VALUE)
    def test_type_value_map_method(self, data_type, value, expected):
        assert woql.type_value_map(data_type, value) == expected

    def test_type_value_map_method_unknown(self):
        with pytest.raises(Exception, match=r"Unknown rdf type! .*"):
            woql.type_value_map("some type that cause error","some val")

    def test_query_to_df_method(self):
        df = woql.query_to_df(MOCK_RESULT)
        assert df.shape == (1,7)


# Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# 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.
# ==============================================================================

"""Provides data from semantic segmentation datasets.

The SegmentationDataset class provides both images and annotations (semantic
segmentation and/or instance segmentation) for TensorFlow.

"""
import tensorflow as tf
from tensorflow.contrib import slim

dataset = slim.dataset
tfexample_decoder = slim.tfexample_decoder

KEY_NAME = 'name'
KEY_IMAGE = 'image'
KEY_IMAGE_FORMAT = 'image_format'
KEY_HEIGHT = 'height'
KEY_WIDTH = 'width'
KEY_MASK = 'mask'
KEY_MASK_FORMAT = 'mask_format'
KEY_DEPTH = 'depth'
KEY_DEPTH_FORMAT = 'depth_format'
KEY_LABEL = 'label'
KEY_LABEL_NAME = 'label_name'
KEY_OBJ_BOX = 'object_box'
KEY_OBJ_LABEL = 'object_label'
KEY_OBJ_LABEL_NAME = 'object_label_name'
KEY_OBJ_AREA = 'object_area'
KEY_OBJ_CROWD = 'object_is_crowd'
KEY_OBJ_DIFFICULT = 'object_difficult'
KEY_OBJ_GROUP = 'object_group_of'
KEY_OBJ_WEIGHT = 'object_weight'
KEY_OBJ_MASK = 'object_mask'

_ITEMS_TO_DESCRIPTIONS = {
    'image': 'A color image of varying height and width.',
    'mask': ('A semantic segmentation mask whose size matches image.'
             'Its value per pixel range from 0 (background) to num_classes.'),
    'depth': ('A depth image whose size matches image.'
              'Its value per pixel is depth range from 0~255.'),
}

def get_dataset(tfrecord_path, num_samples,
                include_classify=False,
                include_detect=False,
                include_segment=False,
                include_depth=False):
  """Gets an instance of slim Dataset.

  Args:
    tfrecord_path: Tfrecord file path corresponding to list.

  Returns:
    An instance of slim Dataset.

  """
  # Specify how the TF-Examples are decoded.
  keys_to_features = {
      # Base content.
      'image/encoded':
          tf.FixedLenFeature((), tf.string, default_value=''),
      'image/filename':
          tf.FixedLenFeature((), tf.string, default_value=''),
      'image/format':
          tf.FixedLenFeature((), tf.string, default_value='jpeg'),
      'image/height':
          tf.FixedLenFeature((), tf.int64, default_value=0),
      'image/width':
          tf.FixedLenFeature((), tf.int64, default_value=0),
      # Image-level labels.
      'image/class/label':
          tf.VarLenFeature(tf.int64),
      'image/class/text':
          tf.VarLenFeature(tf.string),
      # Object boxes and classes.
      'image/object/bbox/xmin':
          tf.VarLenFeature(tf.float32),
      'image/object/bbox/xmax':
          tf.VarLenFeature(tf.float32),
      'image/object/bbox/ymin':
          tf.VarLenFeature(tf.float32),
      'image/object/bbox/ymax':
          tf.VarLenFeature(tf.float32),
      'image/object/class/label':
          tf.VarLenFeature(tf.int64),
      'image/object/class/text':
          tf.VarLenFeature(tf.string),
      'image/object/area':
          tf.VarLenFeature(tf.float32),
      'image/object/is_crowd':
          tf.VarLenFeature(tf.int64),
      'image/object/difficult':
          tf.VarLenFeature(tf.int64),
      'image/object/group_of':
          tf.VarLenFeature(tf.int64),
      'image/object/weight':
          tf.VarLenFeature(tf.float32),
      'image/object/mask':
          tf.VarLenFeature(tf.string),
      # Segmentation mask.
      'image/segmentation/class/encoded':
          tf.FixedLenFeature((), tf.string, default_value=''),
      'image/segmentation/class/format':
          tf.FixedLenFeature((), tf.string, default_value='png'),
      # Depth.
      'image/depth/encoded':
          tf.FixedLenFeature((), tf.string, default_value=''),
      'image/depth/format':
          tf.FixedLenFeature((), tf.string, default_value='png'),
  }

  items_to_handlers = {
      KEY_NAME: tfexample_decoder.Tensor('image/filename'),
      KEY_HEIGHT: tfexample_decoder.Tensor('image/height'),
      KEY_WIDTH: tfexample_decoder.Tensor('image/width'),
      KEY_IMAGE: tfexample_decoder.Image(
              image_key='image/encoded',
              format_key='image/format',
              channels=3),
      KEY_IMAGE_FORMAT: tfexample_decoder.Tensor('image/format')
  }

  if include_classify:
      items_to_handlers[KEY_LABEL] = tfexample_decoder.Tensor(
              'image/class/label')
      items_to_handlers[KEY_LABEL_NAME] = tfexample_decoder.Tensor(
              'image/class/text', default_value='')

  if include_detect:
      items_to_handlers[KEY_OBJ_BOX] = tfexample_decoder.BoundingBox(
              keys=['ymin', 'xmin', 'ymax', 'xmax'],
              prefix='image/object/bbox/')
      items_to_handlers[KEY_OBJ_LABEL] = tfexample_decoder.Tensor(
              'image/object/class/label')
      items_to_handlers[KEY_OBJ_LABEL_NAME] = tfexample_decoder.Tensor(
              'image/object/class/text', default_value='')

  if include_segment:
      items_to_handlers[KEY_MASK] = tfexample_decoder.Image(
              image_key='image/segmentation/class/encoded',
              format_key='image/segmentation/class/format',
              channels=1)
      items_to_handlers[KEY_MASK_FORMAT] = tfexample_decoder.Tensor(
              'image/segmentation/class/format')

  if include_depth:
      items_to_handlers[KEY_DEPTH] = tfexample_decoder.Image(
              image_key='image/depth/encoded',
              format_key='image/depth/format',
              channels=1)
      items_to_handlers[KEY_DEPTH_FORMAT] = tfexample_decoder.Tensor(
              'image/depth/format')

  decoder = tfexample_decoder.TFExampleDecoder(
      keys_to_features, items_to_handlers)

  return dataset.Dataset(
      data_sources=tfrecord_path,
      reader=tf.TFRecordReader,
      decoder=decoder,
      num_samples=num_samples,
      items_to_descriptions=_ITEMS_TO_DESCRIPTIONS)


"""Tests for asttools module.

- TestGetIdentifiers
- TestGetSize
- TestGetConstExpr
- TestConstFolding
- TestReplaceBitwiseOp
- TestReplaceBitwiseFunctions
- TestGetConstMod
- TestComparator
- TestLeveling
"""
# pylint: disable=relative-import

import ast
import astunparse
import unittest

from sspam import pre_processing
from sspam.tools import asttools
import templates

class TestGetIdentifiers(unittest.TestCase):
    """
    Test ast visitor GetIdentifiers.
    """

    def generic_test(self, tests):
        'Generic test for GetIdentifiers class'
        geti = asttools.GetIdentifiers()
        for instring, varref, funref in tests:
            geti.reset()
            inast = ast.parse(instring)
            geti.visit(inast)
            self.assertEquals(geti.variables, varref)
            self.assertEquals(geti.functions, funref)

    def test_basics_vars(self):
        'Simple tests for variables of GetIdentifiers'
        tests = [("x", {"x"}, set()), ("3*(x & 45) + x", {"x"}, set()),
                 ("x + 2*y", {"y", "x"}, set()),
                 ("bla - azerty + 2*(azerty + bla)", {"azerty", "bla"}, set())]
        self.generic_test(tests)

    def test_novariable(self):
        'Test when there is no variable'
        self.generic_test([('(3 + 34)*2', set(), set())])

    def test_basics_funs(self):
        'Simple tests for functions of GetIdentifiers'
        tests = [("a()", set(), {"a"}),
                 ("foo(a, b, c)", {'a', 'b', 'c'}, {'foo'})]
        self.generic_test(tests)

class TestGetSize(templates.AstVisitorCase):
    """
    Test ast visitor GetSize.
    """

    def test_basics(self):
        'Simple tests for GetSize'
        corresp = [("x", 0), ("x & 3", 2), ("x - 5", 4), ("x + 250", 8),
                   ("x*(-0x1325)", 16),
                   ("0xFFFFFFFE*x", 32), ("(0x123456789876543 | x) + 12", 64)]
        self.generic_AstVisitorTest(corresp, asttools.GetSize())

class TestGetConstExpr(templates.AstVisitorCase):
    """
    Test ast visitor GetConstExpr.
    """

    def test_GetConstExpr(self):
        'Simple tests for GetConstExpr'
        hooks = asttools.apply_hooks()
        corresp = [("3", set([ast.Num(3)])),
                   ("2 + 456", set([ast.Num(2),
                                    ast.Num(456),
                                    ast.BinOp(ast.Num(2), ast.Add(),
                                              ast.Num(456))])),
                   ("(3 + x) + 45", set([ast.Num(3), ast.Num(45)])),
                   (("x + y"), set())]
        self.generic_AstVisitorTest(corresp, asttools.GetConstExpr())
        asttools.restore_hooks(hooks)

class TestConstFolding(unittest.TestCase):
    """
    Test constant folding transformer.
    """

    def generic_ConstFolding(self, origstring, refstring, nbits, lvl=False):
        'Generic test for ConstFolding transformer'
        orig = ast.parse(origstring)
        ref = ast.parse(refstring)
        if lvl:
            orig = asttools.LevelOperators().visit(orig)
            ref = asttools.LevelOperators().visit(orig)
        orig = asttools.ConstFolding(orig, nbits).visit(orig)
        self.assertTrue(asttools.Comparator().visit(orig, ref))

    def test_basics(self):
        'Simple tests for ConstFolding'
        corresp = {"45 + 2": ["47", 8], "(3 + 2 + x)": ["(5 + x)", 16],
                   "2*230": ["204", 8], "2 - 4": ["254", 8],
                   "- (3*45)": ["4294967161", 32],
                   "(3 + x)*2 + 4": ["(3 + x)*2 + 4", 64]}
        for origstring, [refstring, nbits] in corresp.iteritems():
            self.generic_ConstFolding(origstring, refstring, nbits)

    def test_leveled_ast(self):
        'Simple tests for ConstFolding on custom BoolOps'
        corresp = {"(x + 3) + 2": ["x + 5", 8],
                   "((x ^ 14) ^ 234) ^ 48": ["x ^ 212", 8],
                   "42*34*y*z": ["1428*y*z", 16]}
        for origstring, [refstring, nbits] in corresp.iteritems():
            self.generic_ConstFolding(origstring, refstring, nbits, True)

class TestReplaceBitWiseOp(templates.AstCompCase):
    """
    Test behaviour of ast transformer ReplaceBitwiseOp.
    """

    def test_basics(self):
        'Simple tests for ReplaceBitwiseOp'
        corresp = [("x ^ y", "mxor(x, y)"), ("x & y", "mand(x, y)"),
                   ("x | y", "mor(x,y)"), ("(x ^ y) & 45",
                                           "mand(mxor(x,y), 45)"),
                   ("~x", "mnot(x)"), ("x + y", "x + y"),
                   ("(x & 3)*2 + ~(x - 3)", "mand(x, 3)*2 + mnot(x - 3)")]
        self.generic_AstCompTest(corresp, asttools.ReplaceBitwiseOp())

class TestReplaceBitwiseFunctions(templates.AstCompCase):
    """
    Test ast transformer class ReplaceBitwiseFunction.
    """

    def test_basics(self):
        'Simple tests for ReplaceBitwiseFunctions'
        corresp = [("mand(x, y)", "x & y"), ("mor(x, y)", "x | y"),
                   ("mxor(x ,y)", "x ^ y"), ("mnot(x)", "~x"),
                   ("mand(mor(x, 45), y) + 3", "((x | 45) & y) + 3")]
        self.generic_AstCompTest(corresp, asttools.ReplaceBitwiseFunctions())

class TestGetConstMod(templates.AstCompCase):
    """
    Test GetContMod.
    """

    def test_basics(self):
        'Simple tests for GetConstMod'
        corresp = {"34": ["2", 4], "356 + x": ["100 + x", 8],
                   "75901*y + 456": ["10365*y + 456", 16]}
        for origstring, [refstring, nbits] in corresp.iteritems():
            transformer = asttools.GetConstMod(nbits)
            self.generic_AstCompTest(origstring, refstring, transformer)

class TestComparator(unittest.TestCase):
    """
    Some tests for comparator because it's used in a lot in other tests.
    """

    def test_comp(self):
        'Basic tests for comparison'
        comp = asttools.Comparator()

        add_a = ast.parse('x + y')
        add_b = ast.parse('x + y')
        self.assertTrue(comp.visit(add_a, add_b))
        add_c = ast.parse('y + x')
        self.assertTrue(comp.visit(add_a, add_c))

        sub_a = ast.parse('x - y')
        self.assertFalse(comp.visit(add_a, sub_a))
        sub_b = ast.parse('y - x')
        self.assertFalse(comp.visit(sub_a, sub_b))

        expr_a = ast.parse('2*(x & y) + ((a - 3) ^ 45)')
        expr_b = ast.parse('2*(x & y) + ((a - 3) ^ 45)')
        self.assertTrue(comp.visit(expr_a, expr_b))
        expr_c = ast.parse('2*(y & x) + (45 ^ (a - 3))')
        self.assertTrue(comp.visit(expr_a, expr_c))
        expr_d = ast.parse('3*(y & x) + (45 ^ (a - 3))')
        self.assertFalse(comp.visit(expr_b, expr_d))

        expr_a = ast.parse('(3*x) + 57 - (x | (-2))')
        expr_b = ast.parse('3*x + 57 - (x | (-2))')
        self.assertTrue(comp.visit(expr_a, expr_b))

    def test_onBoolOp(self):
        'Tests on BoolOp'

        expr_a = ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.Num(3)])
        expr_b = ast.BoolOp(ast.Add(), [ast.Num(3), ast.Num(2), ast.Num(1)])
        self.assertTrue(asttools.Comparator().visit(expr_a, expr_b))

        expr_a = ast.BoolOp(ast.Add, [ast.Num(1), ast.BoolOp(ast.Mult(),
                                                             [ast.Num(5),
                                                              ast.Num(6)]),
                                      ast.Num(4)])
        expr_b = ast.BoolOp(ast.Add, [ast.BoolOp(ast.Mult(), [ast.Num(6),
                                                              ast.Num(5)]),
                                      ast.Num(4),
                                      ast.Num(1)])
        self.assertTrue(asttools.Comparator().visit(expr_a, expr_b))

class TestLeveling(unittest.TestCase):
    """
    Test that leveling produce expected ast.
    """

    def generic_leveling(self, refstring_list, result):
        'Test matching of leveled AST and ref AST'
        for refstring in refstring_list:
            ref = ast.parse(refstring, mode="eval").body
            ref = asttools.LevelOperators().visit(ref)
            self.assertTrue(asttools.Comparator().visit(ref, result))

    def test_basics(self):
        'Simple tests with matching of AST'
        corresp = [(["a + b + c", "a + (b + c)", "b + c + a"],
                    ast.BoolOp(ast.Add(),
                               [ast.Name('a', ast.Load()),
                                ast.Name('b', ast.Load()),
                                ast.Name('c', ast.Load())])),
                   (["a + b + c + d", "(a + b) + (c + d)",
                     "a + (b + c + d)", "a + (b + (c + d))"],
                    ast.BoolOp(ast.Add(),
                               [ast.Name('a', ast.Load()),
                                ast.Name('b', ast.Load()),
                                ast.Name('c', ast.Load()),
                                ast.Name('d', ast.Load())])),
                   (["a + b + c*d", "a + c*d + b"],
                    ast.BoolOp(ast.Add(),
                               [ast.Name('a', ast.Load()),
                                ast.Name('b', ast.Load()),
                                ast.BinOp(ast.Name('c', ast.Load()),
                                          ast.Mult(),
                                          ast.Name('d', ast.Load()))])),
                   (["a*b*c"],
                    ast.BoolOp(ast.Mult(),
                               [ast.Name('a', ast.Load()),
                                ast.Name('b', ast.Load()),
                                ast.Name('c', ast.Load())])),
                   (["a + c*d*e"],
                    ast.BinOp(ast.Name('a', ast.Load()), ast.Add(),
                              ast.BoolOp(ast.Mult(),
                                         [ast.Name('c', ast.Load()),
                                          ast.Name('d', ast.Load()),
                                          ast.Name('e', ast.Load())]))),
                   (["a + b + c + c*d", "a + c*d + b + c"],
                    ast.BoolOp(ast.Add(),
                               [ast.Name('a', ast.Load()),
                                ast.Name('b', ast.Load()),
                                ast.Name('c', ast.Load()),
                                ast.BinOp(ast.Name('c', ast.Load()),
                                          ast.Mult(),
                                          ast.Name('d', ast.Load()))])),
                   (["a + b + c*d*e", "a + c*d*e + b", "b + e*c*d + a"],
                    ast.BoolOp(ast.Add(),
                               [ast.Name('a', ast.Load()),
                                ast.Name('b', ast.Load()),
                                ast.BoolOp(ast.Mult(),
                                           [ast.Name('c', ast.Load()),
                                            ast.Name('d', ast.Load()),
                                            ast.Name('e', ast.Load())])])),
                   (["a + c*d*e + b + c"],
                    ast.BoolOp(ast.Add(),
                               [ast.Name('a', ast.Load()),
                                ast.Name('b', ast.Load()),
                                ast.Name('c', ast.Load()),
                                ast.BoolOp(ast.Mult(),
                                           [ast.Name('c', ast.Load()),
                                            ast.Name('d', ast.Load()),
                                            ast.Name('e', ast.Load())])]))]
        for refstring, result in corresp:
            self.generic_leveling(refstring, result)

    def test_astform(self):
        'Tests with different types of ast'
        t1 = ast.parse("1 + 2 + 3", mode="eval").body
        t1_ref = ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.Num(3)])
        t2 = ast.parse("1 + 2 + 3", mode="eval")
        t3 = ast.parse("1 + 2 + 3").body[0]
        tests = [(t1, t1_ref), (t2, ast.Expression(t1_ref)),
                 (t3, ast.Expr(t1_ref))]
        for test, ref in tests:
            ltest = asttools.LevelOperators().visit(test)
            self.assertTrue(asttools.Comparator().visit(ltest, ref))

    def test_afterSubMult(self):
        'Tests after SubToMult pre-processing'

        tests = [("1 + 2 - 3", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2),
                                                      ast.BinOp(ast.Num(-1),
                                                                ast.Mult(),
                                                                ast.Num(3))])),
                 ("1 + 2 - 3 + 4", ast.BoolOp(ast.Add(),
                                              [ast.Num(1),
                                               ast.Num(2),
                                               ast.BinOp(ast.Num(-1),
                                                         ast.Mult(),
                                                         ast.Num(3)),
                                               ast.Num(4)])),
                 ("(1 + 2) - (3 + 4)",
                  ast.BoolOp(ast.Add(),
                             [ast.Num(1), ast.Num(2),
                              ast.BinOp(ast.Num(-1), ast.Mult(),
                                        ast.BinOp(ast.Num(3), ast.Add(),
                                                  ast.Num(4)))]))]
        for teststring, ref_ast in tests:
            test_ast = ast.parse(teststring, mode="eval").body
            test_ast = pre_processing.all_preprocessings(test_ast)
            test_ast = asttools.LevelOperators(ast.Add).visit(test_ast)
            self.assertTrue(asttools.Comparator().visit(test_ast, ref_ast))

    def test_differentops(self):
        'Test with other types of operators'
        tests = [("(3 & 5 & 6)",
                  ast.BoolOp(ast.BitAnd(),
                             [ast.Num(3), ast.Num(5), ast.Num(6)])),
                 ("(1 ^ 2 ^ 3) - 4",
                  ast.BinOp(ast.BoolOp(ast.BitXor(),
                                       [ast.Num(1), ast.Num(2), ast.Num(3)]),
                            ast.Add(),
                            ast.BinOp(ast.Num(-1), ast.Mult(), ast.Num(4)))),
                 ("((1 + 2 + 3) & (4 + 5))",
                  ast.BinOp(ast.BoolOp(ast.Add(),
                                       [ast.Num(1), ast.Num(2), ast.Num(3)]),
                            ast.BitAnd(),
                            ast.BinOp(ast.Num(4), ast.Add(), ast.Num(5)))),
                 ("(1 & 2 & 3) - (4 & 5)",
                  ast.BinOp(ast.BoolOp(ast.BitAnd(),
                                       [ast.Num(1), ast.Num(2), ast.Num(3)]),
                            ast.Add(),
                            ast.BinOp(ast.Num(-1), ast.Mult(),
                                      ast.BinOp(ast.Num(4), ast.BitAnd(),
                                                ast.Num(5))))),
                 ("(1 & 2 & 3) << (4 & 5)",
                  ast.BinOp(ast.BoolOp(ast.BitAnd(),
                                       [ast.Num(1), ast.Num(2), ast.Num(3)]),
                            ast.LShift(),
                            ast.BinOp(ast.Num(4), ast.BitAnd(), ast.Num(5))))]
        for teststring, ref_ast in tests:
            test_ast = ast.parse(teststring, mode="eval").body
            test_ast = pre_processing.all_preprocessings(test_ast)
            test_ast = asttools.LevelOperators().visit(test_ast)
            self.assertTrue(asttools.Comparator().visit(test_ast, ref_ast))

    def test_withUnaryOp(self):
        'Test with UnaryOp involved'
        tests = [("5 + (-(6 + 2)) + 3",
                  ast.BoolOp(ast.Add(),
                             [ast.Num(5),
                              ast.UnaryOp(ast.USub(), ast.BinOp(ast.Num(6),
                                                                ast.Add(),
                                                                ast.Num(2))),
                              ast.Num(3)]))]
        for teststring, ref_ast in tests:
            test_ast = ast.parse(teststring, mode="eval").body
            test_ast = asttools.LevelOperators(ast.Add).visit(test_ast)
            self.assertTrue(asttools.Comparator().visit(test_ast, ref_ast))

    def test_with_funcs(self):
        'Tests with functions'
        tests = [
            ("f(1 + 1 + 1)",
             ast.Call(ast.Name('f', ast.Load()),
                      [ast.BoolOp(ast.Add(),
                                  [ast.Num(n) for n in [1, 1, 1]])],
                      [],
                      None,
                      None)),
            ("f(1 + 1 + g(2 + 2 + 2))",
             ast.Call(ast.Name('f', ast.Load()),
                      [ast.BoolOp(ast.Add(),
                                  [ast.Num(1),
                                   ast.Num(1),
                                   ast.Call(ast.Name('g', ast.Load()),
                                            [ast.BoolOp(ast.Add(),
                                                        [ast.Num(2),
                                                         ast.Num(2),
                                                            ast.Num(2)])],
                                            [],
                                            None,
                                            None)])],
                      [],
                      None,
                      None))]
        for teststring, ref_ast in tests:
            test_ast = ast.parse(teststring, mode="eval").body
            test_ast = asttools.LevelOperators(ast.Add).visit(test_ast)
            self.assertTrue(asttools.Comparator().visit(test_ast, ref_ast))

    def test_noleveling(self):
        'Tests where nothing should be leveled'
        corresp = [(["a + b", "b + a"],
                   ast.BinOp(ast.Name('a', ast.Load()),
                             ast.Add(),
                             ast.Name('b', ast.Load()))),
                   (["c*d", "d*c"],
                    ast.BinOp(ast.Name('c', ast.Load()),
                              ast.Mult(),
                              ast.Name('d', ast.Load()))),
                   (["a + c*d", "d*c + a"],
                    ast.BinOp(ast.Name('a', ast.Load()), ast.Add(),
                              ast.BinOp(ast.Name('c', ast.Load()), ast.Mult(),
                                        ast.Name('d', ast.Load()))))]
        for refstring, result in corresp:
            self.generic_leveling(refstring, result)

    def test_unleveling(self):
        'Tests to see if unleveling is correct'

        tests = [("x + (3 + y)", "3 + (y + x)"),
                 ("x*(2*z)", "2*(z*x)"),
                 ("x + (y + (z*(5*var)))", "y + (5*(var*z) + x)")]

        for test, ref in tests:
            ref_ast = ast.parse(ref)
            ast_test = ast.parse(test)
            asttools.LevelOperators().visit(ast_test)
            asttools.Unleveling().visit(ast_test)
            self.assertTrue(asttools.Comparator().visit(ast_test, ref_ast))
            self.assertFalse('BoolOp' in astunparse.unparse(ast_test))

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


def multiply_or_not():
    """Program with your number"""
    while True:
        try:
            number = int(input("Please, enter the number: "))
            if number <= 0:
                print('You must enter positive number')
            elif number % 2 == 0:
                print("multiply")
            elif number % 2 != 0:
                print("not multiply")
            else:
                print("I do not know you number")
        except Exception:
            print('you should enter number')

print("\n", "\n", "    ---------------------------------------------------------------------------------------------------", "\n")

def users_age():
    """Program with your number"""
    while True:
        try:
            age = int(input("Please, enter the age: "))
            if age <= 0:
                raise ValueError('That is not positive number')
            elif age % 2 == 0:
                print("multiply")
            elif age % 2 != 0:
                print("not multiply")
            else:
                print("I do not know you age")
        except ZeroDivisionError:
            break

print("\n", "\n", "    ---------------------------------------------------------------------------------------------------", "\n")

def fraction():
    inp = list(map(int, input('Please, enter two numbers: ').split(',')))
    if inp == inp[0] and inp[1]:
        try:
            result = inp[0] / inp[1]
            print('Your division is:', result)
        except ZeroDivisionError:
            print("division by zero!")
        except ValueError:
            print("Should be int")
        finally:
            print("End of the program")
    else:
        print("Your should enter two numbers")

print("\n", "\n", "    ---------------------------------------------------------------------------------------------------", "\n")

def weekday():
    inp = input('Please, enter day of week: ')
    if inp == str(inp):
        try:
            if inp == 'Monday':
                print('Your day of week is:', inp)
            elif inp == 'Tuesday':
                print('Your day of week is:', inp)
            elif inp == 'Wednesday':
                print('Your day of week is:', inp)
            elif inp == 'Thursday':
                print('Your day of week is:', inp)
            elif inp == 'Friday':
                print('Your day of week is:', inp)
            elif inp == 'Saturday':
                print('Your day of week is:', inp)
            elif inp == 'Sunday':
                print('Your day of week is:', inp)
        except SyntaxError:
            print("Please enter the number correctly!")
        except ValueError:
            print("Should be in a word")
        finally:
            print("End of the program")
    else:
        print("Your should enter in a word")

print("\n", "\n", "    ---------------------------------------------------------------------------------------------------", "\n")

class Week:
    def __init__(self, day):
        self.day = day

    def __str__(self):
        return repr(self.day)

def weekday_second():
    days = {1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday',
            5: 'Thursday', 6: 'Friday', 7: 'Saturday'}
    day = int(input('Please, enter day of week: '))
    days.get(day)
    if day <= 0 or day >= 8:
        return print('Your day is', days[day])
    else:
        raise Exception(' ')

while True:
    try:
        weekday_second()
        break
    except ValueError:
        print('Your should enter number from1 to 7')
        break
    finally:
        print("End of program")


import locale

import django

from django.conf import settings
from django.contrib.admin.templatetags.admin_static import static
from django.core.urlresolvers import reverse
from django.forms.widgets import Select
from django.utils.safestring import mark_safe
from django.utils.encoding import force_text

from smart_selects.utils import unicode_sorter, sort_results

try:
    from django.apps import apps
    get_model = apps.get_model
except ImportError:
    from django.db.models.loading import get_model

if django.VERSION >= (1, 2, 0) and getattr(settings,
                                           'USE_DJANGO_JQUERY', True):
    USE_DJANGO_JQUERY = True
else:
    USE_DJANGO_JQUERY = False
    JQUERY_URL = getattr(settings, 'JQUERY_URL', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js')

URL_PREFIX = getattr(settings, "SMART_SELECTS_URL_PREFIX", "")

class ChainedSelect(Select):
    def __init__(self, app_name, model_name, chain_field, model_field,
                 foreign_key_app_name, foreign_key_model_name, foreign_key_field_name,
                 show_all, auto_choose, manager=None, view_name=None, *args, **kwargs):
        self.app_name = app_name
        self.model_name = model_name
        self.chain_field = chain_field
        self.model_field = model_field
        self.show_all = show_all
        self.auto_choose = auto_choose
        self.manager = manager
        self.view_name = view_name
        self.foreign_key_app_name = foreign_key_app_name
        self.foreign_key_model_name = foreign_key_model_name
        self.foreign_key_field_name = foreign_key_field_name
        super(Select, self).__init__(*args, **kwargs)

    class Media:
        extra = '' if settings.DEBUG else '.min'
        js = [
            'jquery%s.js' % extra,
            'jquery.init.js'
        ]
        if USE_DJANGO_JQUERY:
            js = [static('admin/js/%s' % url) for url in js]
        elif JQUERY_URL:
            js = [JQUERY_URL]

    def render(self, name, value, attrs=None, choices=()):
        if len(name.split('-')) > 1:  # formset
            chain_field = '-'.join(name.split('-')[:-1] + [self.chain_field])
        else:
            chain_field = self.chain_field
        if not self.view_name:
            if self.show_all:
                view_name = "chained_filter_all"
            else:
                view_name = "chained_filter"
        else:
            view_name = self.view_name
        kwargs = {
            'app': self.app_name,
            'model': self.model_name,
            'field': self.model_field,
            'foreign_key_app_name': self.foreign_key_app_name,
            'foreign_key_model_name': self.foreign_key_model_name,
            'foreign_key_field_name': self.foreign_key_field_name,
            'value': '1'
            }
        if self.manager is not None:
            kwargs.update({'manager': self.manager})
        url = URL_PREFIX + ("/".join(reverse(view_name, kwargs=kwargs).split("/")[:-2]))
        if self.auto_choose:
            auto_choose = 'true'
        else:
            auto_choose = 'false'
        iterator = iter(self.choices)
        if hasattr(iterator, '__next__'):
            empty_label = iterator.__next__()[1]
        else:
            empty_label = iterator.next()[1]  # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
        js = """
        <script type="text/javascript">
        //<![CDATA[
        (function($) {
            function fireEvent(element,event){
                if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
                }
                else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
                }
            }

            function dismissRelatedLookupPopup(win, chosenId) {
                var name = windowname_to_id(win.name);
                var elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    elem.value = chosenId;
                }
                fireEvent(elem, 'change');
                win.close();
            }

            $(document).ready(function(){
                function fill_field(val, init_value){
                    if (!val || val==''){
                        options = '<option value="">%(empty_label)s<'+'/option>';
                        $("#%(id)s").html(options);
                        $('#%(id)s option:first').attr('selected', 'selected');
                        $("#%(id)s").trigger('change');
                        return;
                    }
                    $.getJSON("%(url)s/"+val+"/", function(j){
                        var options = '<option value="">%(empty_label)s<'+'/option>';
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].value + '">' + j[i].display + '<'+'/option>';
                        }
                        var width = $("#%(id)s").outerWidth();
                        $("#%(id)s").html(options);
                        if (navigator.appVersion.indexOf("MSIE") != -1)
                            $("#%(id)s").width(width + 'px');
                        $('#%(id)s option:first').attr('selected', 'selected');
                        var auto_choose = %(auto_choose)s;
                        if(init_value){
                            $('#%(id)s option[value="'+ init_value +'"]').attr('selected', 'selected');
                        }
                        if(auto_choose && j.length == 1){
                            $('#%(id)s option[value="'+ j[0].value +'"]').attr('selected', 'selected');
                        }
                        $("#%(id)s").trigger('change');
                    })
                }

                if(!$("#id_%(chainfield)s").hasClass("chained")){
                    var val = $("#id_%(chainfield)s").val();
                    fill_field(val, "%(value)s");
                }

                $("#id_%(chainfield)s").change(function(){
                    var start_value = $("#%(id)s").val();
                    var val = $(this).val();
                    fill_field(val, start_value);
                })
            })
            if (typeof(dismissAddAnotherPopup) !== 'undefined') {
                var oldDismissAddAnotherPopup = dismissAddAnotherPopup;
                dismissAddAnotherPopup = function(win, newId, newRepr) {
                    oldDismissAddAnotherPopup(win, newId, newRepr);
                    if (windowname_to_id(win.name) == "id_%(chainfield)s") {
                        $("#id_%(chainfield)s").change();
                    }
                }
            }
        })(jQuery || django.jQuery);
        //]]>
        </script>

        """
        js = js % {"chainfield": chain_field,
                   "url": url,
                   "id": attrs['id'],
                   'value': value,
                   'auto_choose': auto_choose,
                   'empty_label': empty_label}
        final_choices = []
        if value:
            available_choices = self._get_available_choices(self.queryset, value)
            for choice in available_choices:
                final_choices.append((choice.pk, force_text(choice)))
        if len(final_choices) > 1:
            final_choices = [("", (empty_label))] + final_choices
        if self.show_all:
            final_choices.append(("", (empty_label)))
            self.choices = list(self.choices)
            self.choices.sort(key=lambda x: unicode_sorter(x[1]))
            for ch in self.choices:
                if not ch in final_choices:
                    final_choices.append(ch)
        self.choices = ()
        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained'
        else:
            final_attrs['class'] = 'chained'

        output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)
        output += js
        return mark_safe(output)

    def _get_available_choices(self, queryset, value):
        """
        get possible choices for selection
        """
        item = queryset.filter(pk=value).first()
        if item:
            try:
                pk = getattr(item, self.model_field + "_id")
                filter = {self.model_field: pk}
            except AttributeError:
                try:  # maybe m2m?
                    pks = getattr(item, self.model_field).all().values_list('pk', flat=True)
                    filter = {self.model_field + "__in": pks}
                except AttributeError:
                    try:  # maybe a set?
                        pks = getattr(item, self.model_field + "_set").all().values_list('pk', flat=True)
                        filter = {self.model_field + "__in": pks}
                    except:  # give up
                        filter = {}
            filtered = list(get_model(self.app_name, self.model_name).objects.filter(**filter).distinct())
            sort_results(filtered)
        else:
            # invalid value for queryset
            filtered = []

        return filtered


# Copyright (c) 2018 WeFindX Foundation, CLG.
# All Rights Reserved.

from setuptools import find_packages, setup

with open('README.md', 'r') as f:
    long_description = f.read()

setup(
    name='gpgrecord',
    version='0.0.5',
    description='Encrypt/Decrypt interface for GPG record compatiable with JSON via base64.',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/wefindx/gpgrecord',
    author='Mindey',
    author_email='mindey@qq.com',
    license='MIT',
    packages = find_packages(exclude=['docs', 'tests*']),
    install_requires=[
        'python-gnupg>=0.4.4',
    ],
    extras_require = {
        'test': ['coverage', 'pytest', 'pytest-cov'],
    },
    zip_safe=False
)


from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views import generic
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from core.models import Cliente, Veiculo, Parametro, \
                        Movimento, Mensalista
from core.forms import FormCliente, FormVeiculo, \
    FormParametro, FormMovimento, FormMensalista
# Create your views here.

def home(request):
    return render(request, 'core/index.html', {'acao': 'G4car - Estacionamentos'})

class Registrar(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/register.html'

@login_required
def cadastro_cliente(request):
    form = FormCliente(request.POST or None, request.FILES or None)
    contexto = {'form': form, 'acao': 'Cadastro do cliente', 'titulo': 'Cadastrar cliente'}
    if form.is_valid():
        form.save()
        messages.success(request, "Cliente cadastrado com sucesso!")
        return redirect('url_listagem_clientes')
    else:
        return render(request, 'core/cadastro_cliente.html', contexto)

@login_required
def listagem_clientes(request):
    if request.POST:
        if request.POST['nome']:
            clientes = Cliente.objects.filter(nome=request.POST['nome'])
        else:
            clientes = Cliente.objects.all()
    else:
        clientes = Cliente.objects.all()
    contexto = {'clientes': clientes, 'acao': 'Lista de clientes'}
    return render(request, 'core/listagem_clientes.html', contexto)

@login_required
def cadastro_veiculo(request):
    form = FormVeiculo(request.POST or None, request.FILES or None)
    contexto = {'form': form, 'acao': 'Cadastro de veiculo', 'titulo': 'Atualizar cadastro'}
    if form.is_valid():
        form.save()
        messages.success(request, "Veiculo cadastrado com sucesso!")
        return redirect('url_listagem_veiculos')
    else:
        return render(request, 'core/cadastro_veiculo.html', contexto)

@login_required
def listagem_veiculos(request):
    if request.POST:
        if request.POST['modelo']:
            veiculos = Veiculo.objects.filter(modelo=request.POST['modelo'])
        else:
            veiculos = Veiculo.objects.all()
    else:
        veiculos = Veiculo.objects.all()
    contexto = {'veiculos': veiculos, 'acao': 'Lista de veiculos'}
    return render(request, 'core/listagem_veiculos.html', contexto)

@login_required
def atualiza_cliente(request, id):
    cliente_selecionado = Cliente.objects.get(id=id)
    form = FormCliente(request.POST or None, request.FILES or None, instance=cliente_selecionado)
    contexto = {'form': form, 'acao': 'Atualizar o cadastro do cliente', 'titulo': 'Atualizar cadastro'}
    if form.is_valid():
        form.save()
        messages.success(request, "Cliente atualizado com sucesso!")
        return redirect('url_listagem_clientes')
    else:
        return render(request, 'core/cadastro_cliente.html', contexto)

@login_required
def atualiza_veiculo(request, id):
    veiculo_selecionado = Veiculo.objects.get(id=id)
    form = FormVeiculo(request.POST or None, request.FILES or None, instance=veiculo_selecionado)
    contexto = {'form': form, 'acao': 'Atualizar o cadastro de veiculo', 'titulo': 'Atualizar cadastro'}
    if form.is_valid():
        form.save()
        messages.success(request, "Veiculo atualizado com sucesso!")
        return redirect('url_listagem_veiculos')
    else:
        return render(request, 'core/cadastro_veiculo.html', contexto)

@login_required
def exclui_cliente(request, id):
    try:
        cliente_selecionado = Cliente.objects.get(id=id)
        contexto = {'acao': cliente_selecionado.nome, 'redirect': '/listagem_clientes/'}
        if request.POST:
            cliente_selecionado.delete()
            return redirect('url_listagem_clientes')
        else:
            return render(request, 'core/confirma_exclusao.html', contexto)
    except:
        redirect('url_listagem_clientes')

@login_required
def exclui_veiculo(request, id):
    try:
        veiculo_selecionado = Veiculo.objects.get(id=id)
        if request.POST:
            veiculo_selecionado.delete()
            return redirect('url_listagem_veiculos')
        else:
            return render(request, 'core/confirma_exclusao.html', {'acao': veiculo_selecionado.modelo, 'redirect': '/listagem_veiculos/'})
    except:
        return redirect('url_listagem_veiculos')

@login_required
def cadastro_parametro(request):
    form = FormParametro(request.POST or None)
    contexto = {'form': form, 'acao': 'Cadastro de Parametro', 'titulo': 'Cadastro de Parametro'}
    if form.is_valid():
        form.save()
        messages.success(request, "Parametro cadastrado com sucesso!")
        return redirect('url_listagem_parametros')
    else:
        return render(request, 'core/cadastro_parametro.html', contexto)

@login_required
def listagem_parametros(request):
    if request.POST:
        if request.POST['codigo']:
            parametros = Parametro.objects.filter(id=request.POST['codigo'])
        else:
            parametros = Parametro.objects.all()
    else:
        parametros = Parametro.objects.all()
    contexto = {'parametros': parametros, 'acao': 'Tabela de preços'}
    return render(request, 'core/listagem_parametros.html', contexto)

@login_required
def cadastro_mensalista(request):
    form = FormMensalista(request.POST or None)
    contexto = {'form': form, 'acao': 'Cadastro de mensalista', 'titulo': 'Cadastro de mensalista'}
    if form.is_valid():
        form.save()
        messages.success(request, "Mensalista cadastrado com sucesso!")
        return redirect('url_listagem_mensalistas')
    else:
        return render(request, 'core/cadastro_mensalista.html', contexto)

@login_required
def listagem_mensalistas(request):
    if request.POST:
        if request.POST['codigo']:
            mensalista = Mensalista.objects.filter(id=request.POST['codigo'])
        else:
            mensalista = Mensalista.objects.all()
    else:
        mensalista = Mensalista.objects.all()
    contexto = {'mensalistas': mensalista, 'acao': 'Lista de mensalistas'}
    return render(request, 'core/listagem_mensalistas.html', contexto)

@login_required
def atualiza_mensalista(request, id):
    if request.user.is_staff:
        try:
            obj = Mensalista.objects.get(id=id)
            form = FormMensalista(request.POST or None, instance=obj)
            contexto = {'form': form, 'acao': 'Atualização de Mensalistas',
                        'titulo': 'Atualiza Mensalista - G4car'}
            if form.is_valid():
                form.save()
                messages.success(request, "Mensalista atualizado com sucesso!")
                return redirect('url_listagem_mensalistas')
            else:
                return render(request, 'core/cadastro_mensalista.html', contexto)
        except:
            return redirect('url_listagem_mensalistas')
    else:
        contexto = {'erro': 'Você não tem permissão para executar este procedimento, '
                            'procure o seu gerente.'}
        return render(request, 'core/erro.html', contexto)

@login_required
def exclui_mensalista(request, id):
    obj = Mensalista.objects.get(id=id)
    contexto = {'acao': obj.id_veiculo, 'redirect': '/listagem_mensalistas/'}
    if request.method == 'POST':
        obj.delete()
        return redirect('url_listagem_mensalistas')
    else:
        return render(request, 'core/confirma_exclusao.html', contexto)

@login_required
def atualiza_parametro(request, id):
    try:
        obj = Parametro.objects.get(id=id)
        form = FormParametro(request.POST or None, instance=obj)
        contexto = {'form': form, 'acao': 'Atualização de parametro'}
        if form.is_valid():
            form.save()
            messages.success(request, "Parametro atualizado com sucesso!")
            return redirect('url_listagem_parametros')
        else:
            return render(request, 'core/cadastro_parametro.html', contexto)
    except:
        return redirect('url_listagem_parametros')

@login_required
def exclui_parametro(request, id):
    obj = Parametro.objects.get(id=id)
    contexto = {'acao': obj.descricao, 'redirect': '/listagem_parametros/'}
    if request.method == 'POST':
        obj.delete()
        return redirect('url_listagem_parametros')
    else:
        return render(request, 'core/confirma_exclusao.html', contexto)

@login_required
def cadastro_movimento(request):
    if request.user.is_staff:
        form = FormMovimento(request.POST or None)
        contexto = {'form': form, 'titulo': 'Cadastro de movimento', 'acao': 'Cadastro de Movimento'}
        if form.is_valid():
            form.save()
            messages.success(request, "Movimento cadastrado com sucesso!")
            return redirect('url_listagem_movimentos')
        return render(request, 'core/cadastro_movimento.html', contexto)
    else:
        contexto = {'erro': 'Você não tem permissão para executar este procedimento, '
                            'procure o seu gerente.'}
        return render(request, 'core/erro.html', contexto)

@login_required
def listagem_movimentos(request):
    if request.POST:
        if request.POST['placa']:
            movimento = Movimento.objects.filter(id_veiculo__placa=request.POST['placa'])
        else:
            movimento = Movimento.objects.all()
    else:
        movimento = Movimento.objects.all()
    contexto = {'movimentos': movimento, 'acao': 'Lista de movimentos'}
    return render(request, 'core/listagem_movimentos.html', contexto)

@login_required
def atualiza_movimento(request, id):
    if request.user.is_staff:
        try:
            obj = Movimento.objects.get(id=id)
            form = FormMovimento(request.POST or None, instance=obj)
            contexto = {'form': form, 'acao': 'Atualização de Movimento',
                        'titulo': 'Atualiza Movimento - G4car'}
            if form.is_valid():
                retorno = obj.calcula_total()
                if retorno == 'erro':
                    contexto = {'erro': 'Valor de data de saída menor que de entrada,'
                                        ' favor realizar novamente'}
                    return render(request, 'core/erro.html', contexto)
                form.save()
                messages.success(request, "Movimento atualizado com sucesso!")
                return redirect('url_listagem_movimentos')
            else:
                return render(request, 'core/cadastro_movimento.html', contexto)
        except:
            return redirect('url_listagem_movimentos')
    else:
        contexto = {'erro': 'Você não tem permissão para executar este procedimento, '
                            'procure o seu gerente.'}
        return render(request, 'core/erro.html', contexto)

@login_required
def exclui_movimento(request, id):
    obj = Movimento.objects.get(id=id)
    contexto = {'acao': obj.id_veiculo, 'redirect': '/listagem_movimentos/'}
    if request.method == 'POST':
        obj.delete()
        return redirect('url_listagem_movimentos')
    else:
        return render(request, 'core/confirma_exclusao.html', contexto)