import pdb

import numpy as np
import math
import time

import chainer
import chainer.functions as F
import chainer.links as L
from chainer import cuda

from util import gaussian_kl_divergence_standard
from util import gaussian_logp

class VAE(chainer.Chain):
    def __init__(self, dim_in, dim_hidden, dim_latent, num_layers, temperature, num_zsamples=1):

        super(VAE, self).__init__()
        # initialise first encoder and decoder hidden layer separately because
        # the input and output dims differ from the other hidden layers
        self.qlin0 = L.Linear(dim_in, dim_hidden)
        self.plin0 = L.Linear(dim_latent, dim_hidden)
        self._children.append('qlin0')
        self._children.append('plin0')

        for i in range(num_layers-1):
            # encoder
            layer_name = 'qlin' + str(i+1)
            setattr(self, layer_name, L.Linear(2*dim_hidden, dim_hidden))
            self._children.append(layer_name)

            # decoder
            layer_name = 'plin' + str(i+1)
            setattr(self, layer_name, L.Linear(2*dim_hidden, dim_hidden))
            self._children.append(layer_name)

        # initialise the encoder and decoder output layer separately because
        # the input and output dims differ from the other hidden layers
        self.qlin_mu = L.Linear(2*dim_hidden, dim_latent)
        self.qlin_ln_var = L.Linear(2*dim_hidden, dim_latent)
        self.plin_ln_var = L.Linear(2*dim_hidden, dim_in)
        self.plin_mu = L.Linear(2*dim_hidden, dim_in)
        self._children.append('qlin_mu')
        self._children.append('qlin_ln_var')
        self._children.append('plin_mu')
        self._children.append('plin_ln_var')

        self.num_layers = num_layers
        self.temperature = temperature
        self.num_zsamples = num_zsamples
        self.epochs_seen = 0

    def encode(self, x):
        h = F.crelu(self.qlin0(x))

        for i in range(self.num_layers-1):
            layer_name = 'qlin' + str(i+1)
            h = F.crelu(self[layer_name](h))

        self.qmu = self.qlin_mu(h)
        self.qln_var = self.qlin_ln_var(h)

        return self.qmu, self.qln_var

    def decode(self, z):
        h = F.crelu(self.plin0(z))

        for i in range(self.num_layers-1):
            layer_name = 'plin' + str(i+1)
            h = F.crelu(self[layer_name](h))

        self.pmu = self.plin_mu(h)
        self.pln_var = self.plin_ln_var(h)

        return self.pmu, self.qln_var

    def __call__(self, x):
        # Compute q(z|x)
        encoding_time = time.time()
        self.encode(x)
        encoding_time = float(time.time() - encoding_time)

        decoding_time_average = 0.

        self.kl = gaussian_kl_divergence_standard(self.qmu, self.qln_var)
        self.logp = 0
        for j in xrange(self.num_zsamples):
            # z ~ q(z|x)
            z = F.gaussian(self.qmu, self.qln_var)

            # Compute p(x|z)
            decoding_time = time.time()
            self.decode(z)
            decoding_time = time.time() - decoding_time
            decoding_time_average += decoding_time

            # Compute objective
            self.logp += gaussian_logp(x, self.pmu, self.pln_var)

        current_temperature = min(self.temperature['value'],1.0)
        self.temperature['value'] += self.temperature['increment']
        # pdb.set_trace()
        decoding_time_average /= self.num_zsamples
        self.logp /= self.num_zsamples
        self.obj_batch = self.logp - (current_temperature*self.kl)
        self.timing_info = np.array([encoding_time,decoding_time_average])

        batch_size = self.obj_batch.shape[0]

        self.obj = -F.sum(self.obj_batch)/batch_size

        return self.obj


from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.preprocessing import sequence

from postag_eng.parser.EnglishNerParser import EnglishNerParser
from postag_eng.vectorizer.Vectorizer import Vectorizer
from keras.utils import np_utils
from postag_eng.recurrentneuralnetwork.RecurrentNeuralNetwork import RecurrentNeuralNetwork

import numpy as np

if __name__ == '__main__':

    print('Reading training data')
    documents = EnglishNerParser().read_file('F:/Utilisateur/Documents/ESGI/Cours/Traitement Automatique du Langage Naturel/eng_train.txt')

    print('Create features')
    vectorizer = Vectorizer(word_embedding_path='F:/Utilisateur/Documents/ESGI/Cours/Traitement Automatique du Langage Naturel/glove.6B.50d.txt')
    word, shape = vectorizer.encode_features(documents)
    labels = vectorizer.encode_annotations(documents)
    print('Loaded {} data samples'.format(len(word)))

    print('Split training/validation')
    max_length = 20
    # --------------- Features_word ----------------
    # 2. Padd sequences
    word = sequence.pad_sequences(word, maxlen=max_length)
    # --------------- Features_shape ----------------
    # 2. Padd sequences
    shape = sequence.pad_sequences(shape, maxlen=max_length)

    # --------------- Labels -------------------
    # 1. Convert to one-hot vectors
    labels = [np_utils.to_categorical(y_group, num_classes=len(vectorizer.labels)) for y_group in labels]
    # 2. (only for sequence tagging) Pad sequences
    labels = sequence.pad_sequences(labels, maxlen=max_length)

    to = int(len(word)*0.8)

    x_train = [np.asarray(word[:to]), np.asarray(shape[:to])]
    y_train = np.array(labels[:to])
    x_validation = [np.asarray(word[to+1:]), np.asarray(shape[to+1:])]
    y_validation = np.array(labels[to+1:])

    print(x_train[1].shape)
    print(x_validation[1].shape)

    print('Building network...')
    model = RecurrentNeuralNetwork.build_sequence(word_embeddings=vectorizer.word_embeddings,
                                          input_shape={'shape': (len(vectorizer.shape2index), 46)},
                                          out_shape=len(vectorizer.labels),
                                          units=100, dropout_rate=0.5)

    print('Train...')
    trained_model_name = 'ner_weights.h5'

    # Callback that stops training based on the loss fuction
    early_stopping = EarlyStopping(monitor='val_loss', patience=10)

    # Callback that saves the best model across epochs
    saveBestModel = ModelCheckpoint(trained_model_name, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')

    model.fit(x_train, y_train,
              validation_data=(x_validation, y_validation),
              batch_size=32,  epochs=50, callbacks=[saveBestModel, early_stopping])

    # # Load the best weights in the model
    # model.load_weights(trained_model_name)
    #
    # # Save the complete model
    # model.save('rnn.h5')


import os

aut = 'Phillip Massinger' #PUT NAME OF AUTHOR NEEDED HERE
nm = []

for root, dr, fl in os.walk('C:\\Users\\Artem\\Desktop\\pr\\outpt\\MORPH\\'): #or ('.') if in root
    if aut in root:
        for el in fl:
            if 'M_' not in el:
                nm.append(el)

print(nm)

for ln in nm:
    f = open('C://Users//Artem//Desktop//pr//outpt//MORPH//' + aut + '//' + ln, 'r').read().split()
    f_out = open('C://Users//Artem//Desktop//pr//outpt//MORPH//' + aut + '//M_' + ln, 'w')
    d = {}
    symb = '&/{'
    check = []
    for i in range(len(f)):
        #print(i)
        if f[i][0] not in symb and f[i] not in check:
            check.append(f[i])
            trig = False #dictionary += trigger
            #print('main el=', f[i])
            #print(check)
            for z in range(i+1, len(f)):
                #print('sub el', f[z])
                if f[z][0] == '+':
                    #print('addin')
                    if trig == False:
                       d[f[i]] = f[z] + ' '
                       trig = True
                    elif trig == True:
                        #print('trigerrin')
                        d[f[i]] += f[z] + ' '

                elif f[z][0] == '&':
                    #print('addin')
                    if trig == False:
                       d[f[i]] = f[z] #+ ' '
                       trig = True
                    elif trig == True:
                        #print('trigerrin')
                        d[f[i]] += f[z] #+ ' '

                elif f[z] == f[i]:
                    #print('equal')
                    continue
                elif f[z][0] not in symb:
                    #print('escape', 'escapin el=', f[z])
                    #d[f[i]] = d[f[i]].rstrip(' ')
                    break

    for el in d:
        #print(el + ':' , d[el], '\n')
        f_out.write(el.replace('\n', '') + ':' + d[el].rstrip(' ') + '\n')
    f_out.close()
    print('done')

print('final done')


import pickle, math, argparse
from pymuco import rhythm

from exposure import util
import numpy as np
import matplotlib.pyplot as plt

def correlation(X, Y):

    mean_x = sum(X) / len(X)
    mean_y = sum(Y) / len(Y)

    centered_X = [x - mean_x for x in X]
    centered_Y = [y - mean_y for y in Y]

    return (
        sum([x * y for x, y in zip(centered_X, centered_Y)]) /
        math.sqrt(sum([x ** 2 for x in centered_X]) * sum([y ** 2 for y in centered_Y]))
    )

def average_information_content(streams):

    ics = []

    model.reset()
    event_streams = [model.viewpoint.events(stream) for stream in streams]

    for events in zip(*event_streams):

        for time, event in events:

            ics.append(model.information_content(event))
            model.expose(time, event)

    return sum(ics) / len(ics)

def witek_to_grid(w, repetitions):

    def onsets_to_grid(onsets, repetitions):
        onsets_scaled = [o * model.resolution / 4.0 for o in onsets]
        return repetitions * rhythm.onset_times_to_grid(onsets_scaled)

    bass_grid, snare_grid, hihat_grid = [onsets_to_grid(w[stream], repetitions) for stream in ['bass-drum', 'snare-drum', 'hi-hat']]

    return (bass_grid, snare_grid, hihat_grid)

def convert_to_grid(iois):

    grid = rhythm.iois_to_grid(rhythm)

def correlation_povel_essens(model, data, repetitions=1):

    grids = [repetitions * rhythm.resample(rhythm.iois_to_grid(d['rhythm']), 8, model.resolution) for d in data]
    complexity_ratings = [d['complexity-rating'] for d in data]
    reproduction_errors = [d['reproduction-error'] for d in data]
    information_contents = [average_information_content((grid, )) for grid in grids]

    for x in (information_contents, ):
        for y in (complexity_ratings, reproduction_errors):
            print(correlation(x, y))
            plt.figure()
            plt.plot(x, y, 'bs')

def relation_witek(model, data, repetitions=1):

    rhythms = [witek_to_grid(w) for w in data]
    move_ratings = [w['move'] for w in data]
    pleasure_ratings = [w['pleasure'] for w in data]
    syncopation_ratings = [w['s'] for w in data]
    information_per_rhythm = [average_information_content(r) for r in rhythms]

    for x in (syncopation_ratings, information_per_rhythm):
        for y in (move_ratings, pleasure_ratings):
            plt.figure()
            plt.plot(x, y, 'bs')

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    util.require_model_file(parser)
    parser.add_argument('-r', '--repetitions',
        default=2,
        type=int,
    )
    args = parser.parse_args()
    model = util.load_model_file(**vars(args))

    povel_essens_data = pickle.load(open('../../musicloud/musicloud/povel_essens.pickle', 'rb'))
    witek_data = pickle.load(open('../../musicloud/musicloud/witek.pickle', 'rb'))

    correlation_povel_essens(model, povel_essens_data, repetitions=args.repetitions)
    #relation_witek(model, povel_essens_data, **vars(args))

    plt.show()


from __future__ import absolute_import, print_function
import os
import sys
import json
import time
import errno
import socket
import signal
import logging
import logging.config
import warnings
import threading
import traceback
import multiprocessing

from kuyruk import importer, signals
from kuyruk.task import get_queue_name
from kuyruk.exceptions import Reject, Discard, ConnectionError

logger = logging.getLogger(__name__)

class Worker(object):
    """Consumes tasks from a queue and runs them.

    :param app: An instance of :class:`~kuyruk.Kuyruk`
    :param args: Command line arguments

    """
    def __init__(self, app, args):
        self.kuyruk = app

        if not args.queues:
            raise ValueError("no queue given")

        self.queues = [get_queue_name(q, local=args.local) for q in args.queues]
        self.shutdown_pending = threading.Event()
        self._pause = False
        self._started = None
        self.consuming = False
        self._current_message = None
        self.current_task = None
        self.current_args = None
        self.current_kwargs = None
        self._heartbeat_exc_info = None
        if self.config.WORKER_MAX_LOAD is None:
            self.config.WORKER_MAX_LOAD = multiprocessing.cpu_count()

        self._pid = os.getpid()
        self._hostname = socket.gethostname()

        signals.worker_init.send(self.kuyruk, worker=self)

    @property
    def queue(self):
        warnings.warn("Worker.queue is deprecated. Use Worker.queues instead.")
        return self.queues[0]

    @property
    def config(self):
        return self.kuyruk.config

    def run(self):
        """Runs the worker and consumes messages from RabbitMQ.
        Returns only after `shutdown()` is called.

        """
        # Lazy import setproctitle.
        # There is bug with the latest version of Python with
        # uWSGI and setproctitle combination.
        # Watch: https://github.com/unbit/uwsgi/issues/1030
        from setproctitle import setproctitle
        setproctitle("kuyruk: worker on %s" % ','.join(self.queues))

        self._setup_logging()

        signal.signal(signal.SIGINT, self._handle_sigint)
        signal.signal(signal.SIGTERM, self._handle_sigterm)
        signal.signal(signal.SIGHUP, self._handle_sighup)
        signal.signal(signal.SIGUSR1, self._handle_sigusr1)
        signal.signal(signal.SIGUSR2, self._handle_sigusr2)

        self._started = os.times()[4]

        for f in (self._watch_load, self._shutdown_timer):
            t = threading.Thread(target=f)
            t.daemon = True
            t.start()

        signals.worker_start.send(self.kuyruk, worker=self)
        self._consume_messages()
        signals.worker_shutdown.send(self.kuyruk, worker=self)

        logger.debug("End run worker")

    def _setup_logging(self):
        if self.config.WORKER_LOGGING_CONFIG:
            logging.config.fileConfig(self.config.WORKER_LOGGING_CONFIG)
        else:
            level = getattr(logging, self.config.WORKER_LOGGING_LEVEL.upper())
            fmt = "%(levelname).1s " \
                  "%(name)s.%(funcName)s:%(lineno)d - %(message)s"
            logging.basicConfig(level=level, format=fmt)

    def _consume_messages(self):
        with self.kuyruk.channel() as ch:
            # Set prefetch count to 1. If we don't set this, RabbitMQ keeps
            # sending messages while we are already working on a message.
            ch.basic_qos(0, 1, True)

            self._declare_queues(ch)
            while not self.shutdown_pending.is_set():
                # Consume or pause
                if self._pause and self.consuming:
                    self._cancel_queues(ch)
                    logger.info('Consumer cancelled')
                    self.consuming = False
                elif not self._pause and not self.consuming:
                    self._consume_queues(ch)
                    logger.info('Consumer started')
                    self.consuming = True

                if self._heartbeat_exc_info:
                    break

                try:
                    ch.connection.send_heartbeat()
                    ch.connection.drain_events(timeout=1)
                except socket.error as e:
                    if isinstance(e, socket.timeout):
                        pass
                    elif e.errno == errno.EINTR:
                        pass  # happens when the process receives a signal
                    else:
                        raise
        logger.debug("End run worker")

    def _consumer_tag(self, queue):
        return "%s:%s@%s" % (queue, self._pid, self._hostname)

    def _declare_queues(self, ch):
        for queue in self.queues:
            logger.debug("queue_declare: %s", queue)
            ch.queue_declare(
                queue=queue, durable=True, auto_delete=False)

    def _consume_queues(self, ch):
        for queue in self.queues:
            logger.debug("basic_consume: %s", queue)
            ch.basic_consume(queue=queue,
                             consumer_tag=self._consumer_tag(queue),
                             callback=self._process_message)

    def _cancel_queues(self, ch):
        for queue in self.queues:
            logger.debug("basic_cancel: %s", queue)
            ch.basic_cancel(self._consumer_tag(queue))

    def _process_message(self, message):
        """Processes the message received from the queue."""
        if self.shutdown_pending.is_set():
            return

        try:
            description = json.loads(message.body)
        except Exception:
            message.channel.basic_reject(message.delivery_tag, requeue=False)
            logger.error("Cannot decode message. Dropping.")
        else:
            logger.info("Processing task: %r", description)
            self._process_description(message, description)

    def _process_description(self, message, description):
        try:
            task = importer.import_object(description['module'],
                                          description['function'])
            args, kwargs = description['args'], description['kwargs']
        except Exception:
            logger.error('Cannot import task')
            exc_info = sys.exc_info()
            signals.worker_failure.send(self.kuyruk, description=description,
                                        exc_info=exc_info, worker=self)
            message.channel.basic_reject(message.delivery_tag, requeue=False)
        else:
            self._process_task(message, description, task, args, kwargs)

    def _process_task(self, message, description, task, args, kwargs):
        try:
            self._current_message = message
            self.current_task = task
            self.current_args = args
            self.current_kwargs = kwargs
            stop_heartbeat = threading.Event()
            heartbeat_thread = threading.Thread(
                target=self._heartbeat_tick,
                args=(message.channel.connection, stop_heartbeat))
            heartbeat_thread.start()
            try:
                self._apply_task(task, args, kwargs)
            finally:
                self._current_message = None
                self.current_task = None
                self.current_args = None
                self.current_kwargs = None
                stop_heartbeat.set()
                heartbeat_thread.join()
        except Reject:
            logger.warning('Task is rejected')
            time.sleep(1)  # Prevent cpu burning
            message.channel.basic_reject(message.delivery_tag, requeue=True)
        except Discard:
            logger.warning('Task is discarded')
            message.channel.basic_reject(message.delivery_tag, requeue=False)
        except ConnectionError:
            pass
        except Exception:
            logger.error('Task raised an exception')
            exc_info = sys.exc_info()
            logger.error(''.join(traceback.format_exception(*exc_info)))
            signals.worker_failure.send(self.kuyruk, description=description,
                                        task=task, args=args, kwargs=kwargs,
                                        exc_info=exc_info, worker=self)
            message.channel.basic_reject(message.delivery_tag, requeue=False)
        else:
            logger.info('Task is successful')
            message.channel.basic_ack(message.delivery_tag)
        finally:
            logger.debug("Task is processed")

    @staticmethod
    def _apply_task(task, args, kwargs):
        """Logs the time spent while running the task."""
        if args is None:
            args = ()
        if kwargs is None:
            kwargs = {}

        start = time.time()
        try:
            task.apply(*args, **kwargs)
        finally:
            end = time.time()
            logger.info("%s finished in %i seconds." % (task.name, end - start))

    def _watch_load(self):
        """Pause consuming messages if lood goes above the allowed limit."""
        while not self.shutdown_pending.is_set():
            load = os.getloadavg()[0]
            if load > self.config.WORKER_MAX_LOAD:
                if self._pause is False:
                    logger.warning(
                        'Load is above the treshold (%.2f/%s), '
                        'pausing consumer', load, self.config.WORKER_MAX_LOAD)
                    self._pause = True
            else:
                if self._pause is True:
                    logger.warning(
                        'Load is below the treshold (%.2f/%s), '
                        'resuming consumer', load, self.config.WORKER_MAX_LOAD)
                    self._pause = False
            time.sleep(1)

    @property
    def uptime(self):
        if self._started is not None:
            return os.times()[4] - self._started

    def _shutdown_timer(self):
        """Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown
        gracefully.

        """
        if not self.config.WORKER_MAX_RUN_TIME:
            return

        while not self.shutdown_pending.is_set():
            remaining = self.config.WORKER_MAX_RUN_TIME - self.uptime
            if remaining > 0:
                time.sleep(remaining)
            else:
                logger.warning('Run time reached zero')
                self.shutdown()
                break

    def shutdown(self):
        """Exits after the current task is finished."""
        logger.warning("Shutdown requested")
        self.shutdown_pending.set()

    def _handle_sigint(self, signum, frame):
        """Shutdown after processing current task."""
        logger.warning("Catched SIGINT")
        self.shutdown()

    def _handle_sigterm(self, signum, frame):
        """Shutdown after processing current task."""
        logger.warning("Catched SIGTERM")
        self.shutdown()

    def _handle_sighup(self, signum, frame):
        """Used internally to fail the task when connection to RabbitMQ is
        lost during the execution of the task.

        """
        logger.warning("Catched SIGHUP")
        raise ConnectionError(self._heartbeat_exc_info)

    @staticmethod
    def _handle_sigusr1(signum, frame):
        """Print stacktrace."""
        print('=' * 70)
        print(''.join(traceback.format_stack()))
        print('-' * 70)

    def _handle_sigusr2(self, signum, frame):
        """Drop current task."""
        logger.warning("Catched SIGUSR2")
        if self._current_message:
            logger.warning("Dropping current task...")
            raise Discard

    def drop_task(self):
        os.kill(os.getpid(), signal.SIGUSR2)

    def _heartbeat_tick(self, connection, stop_event):
        while not stop_event.wait(1):
            try:
                connection.send_heartbeat()
            except socket.timeout:
                pass
            except Exception as e:
                logger.error(e)
                self._heartbeat_exc_info = sys.exc_info()
                os.kill(os.getpid(), signal.SIGHUP)
                break


from django import forms
from django.db import models
from .models import Image

class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = ('title', 'description', 'user', 'image')
        labels = {
            'user':'User'
        }

    def __init__(self, *args, **kwargs):
        super(ImageForm, self).__init__(*args, **kwargs)
        self.fields['user'].empty_label = "-- Keep Unselected for Anonymous --"


def students():
    nk = input().split()
    n = int(nk[0])
    k = int(nk[1])
    attendance = list(map(int, input().split()))
    late = []

    for i in attendance:
        if int(i) > 0:
            late.append(i)
    OnTime = n - len(late)

    if OnTime < k:
        print("YES")
    else:
        print("NO")

t = int(input())
for i in range(t):
    students()


import socket
import pickle
from random import randint

def cript(a1, key):
    a2 = [chr(ord(a1[i]) ^ key) for i in range(len(a1))]
    return ''.join(a2)

def sen(sock, msg, K):
    msg = cript(msg, K)
    sock.send(pickle.dumps(msg))

def rec(sock, K):
    msg = pickle.loads(sock.recv(1024))
    msg = cript(msg,K)
    return msg

HOST = '127.0.0.1'
PORT = 8080

sock = socket.socket()
sock.connect((HOST, PORT))

p, g, a = [randint(0,250) for i in range(3)]
A = g ** a % p
sock.send(pickle.dumps((p, g, A)))
B = pickle.loads(sock.recv(1024))
K = B ** a % p

print('Введите сообщение')
msg = input()

while msg != 'exit':
    sen(sock,msg, K)
    print(rec(sock,K))
    msg = input()

sock.close()


import asyncio
from tcp_tunnel.connection import Connection
from tcp_tunnel import logger

async def tcp_echo_client():
    for i in range(100):
        reader, writer = await asyncio.open_connection('127.0.0.1', 8889)
        gold_reader, gold_writer = await asyncio.open_connection('127.0.0.1', 8000)
        conn = Connection(reader, writer, gold_reader, gold_writer)
        loop.create_task(conn.run_writer())
        loop.create_task(conn.run_reader())
        logger.debug('create conn')

loop = asyncio.get_event_loop()
future = asyncio.ensure_future(tcp_echo_client())
try:
    loop.run_forever()
except KeyboardInterrupt:
    future.cancel()
    loop.run_until_complete(future)
finally:
    # 不管是什么异常，最终都要close掉loop循环
    loop.close()


import cgi
import os
from google.appengine.api import users
import webapp2
from google.appengine.ext import ndb
import json
from datetime import datetime
import jinja2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

MAIN_PAGE_HTML = """\

    <form action="/gwy/test_submitreading" method="post">

Gateway 1111111111111111111 Serial
<input type="text" name="gateway_serial">

ReadOut
<input type="text" name="readout">

      <input type="submit" value="POST RESULT">

    </form>

"""

class DoUpload(webapp2.RequestHandler):
  def post(self):
      fl = self.request.get('myfile')
      for contr in Contract.all():
          contr.delete()
      for prop in Property.all():
          prop.delete()
      for addr in Address.all():
          addr.delete()
      for pers in Person.all():
          pers.delete()

      self.response.write(fl.decode("latin-1")+"
Hallo Kris
" )
      reader = csv.reader(fl.decode("latin-1").splitlines(), delimiter=";")
      rownum = 0
      for row in reader:
         if (rownum > 0 ):
            self.response.write(row[0] + "
")
            addr = Address(street= row[2], postalCode = row[3], locality = row[4])
            addr.put()
            prop = Property(shortName = row[0], propertyType=int(row[1]), propertyOwner=int(row[5]), address=addr.key() )
            prop.put()
            pers = Person(name=row[6], language=row[8], aanspreekTittel =row[7])
            if row[15] != None and len(row[15])>1:
                addr = Address(street= row[15], postalCode = row[16], locality = row[17])
                addr.put()
                pers.address = addr.key()
            pers.put()
            contr = Contract(tenant = pers.key(), property= prop.key(), startDate = datetime.strptime(row[13],"%d/%m/%Y") , baseIndex=float(row[9]), baseIndexType=int(row[10]), baseRent=float(row[11]), provision=float(row[12]), indexMonth=int(row[14]))
            if row[15] != None and len(row[15])>1:
                contr.useTenantAddress = bool(True)
            else:
                contr.useTenantAddress = bool(False)

            contr.put()
         rownum += 1

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.write(MAIN_PAGE_HTML)

app = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/uploadFile.do', DoUpload)
], debug=True)


import csv
import math

past_games = 17          # Past Games to include in Pythagorean Win Projection (must be integer greater than 3) (~18 ?)
v_value = 4.1            # Rate at which previous seasons are discounted (~4 seems good)
wf = 1.39                # Exponential for Pythagorean calcs, default for football is 2.37(?) (must be a float) (~1.39 seems good)
HFA = 7.2                # home field advantage as percentage, default is 5.5 (~7.4 seems good)
HFA2 = HFA               # home field advantage for win chart
HFAE = 65.0              # elo hfa points
HFA_P_M = 1.59           # multiplier for home field advantage in playoffs (~1.6 seems good)
HFAP = HFA*HFA_P_M       # Pythag Win home field advantage for playoffs
HFA2P = HFA2*HFA_P_M     # win chart hfa for playoffs
HFAEP = HFAE*HFA_P_M     # elo hfa for playoffs
team_below_min = 32.25   # Expected win percentage by teams that have played 1 game (must be float) (32.25 seems good)
new_team = 27.5          # Expected win percentage by team in first game (must be float) (27.5 seems good)
a_factor = 2.45          # Exponential factor to compare Expected Wins Head to Head (2.465 seems good)
expect_points = 42.5     # Expected total points for calculating point differential (45.4 was 2016 league average points/game)
percent_mine = 40.0      # % using Pwin instead of Elo (must be float) (~40 seems good)
percent_win_chart = 3.25  # % using expected win chart (must be float) (~3.25 seems good)
b_factor = 0.9          # Exponential factor to compare Win Chart values Head to Head (0.9 seems good)
K = 20.7
REVERT = 1/2.97
y_factor  = 1.3          # Multiplier for points expectations (try 1.9?)
x_factor  = 1.2          # Root for points expectations (try 1.4?), this and the y_factor are used in compressing/expanding score predictions
backup_qb_loss = 2.3     # Expected point loss if backup QB is starting
backup_qb_percent = backup_qb_loss/(expect_points)

REVERSIONS = {'CBD1925': 1502.032, 'RAC1926': 1403.384, 'LOU1926': 1307.201, 'CIB1927': 1362.919, 'MNN1929': 1306.702, # Some between-season reversions of unknown origin
              'BFF1929': 1331.943, 'LAR1944': 1373.977, 'PHI1944': 1497.988, 'ARI1945': 1353.939, 'PIT1945': 1353.939, 'CLE1999': 1300.0}

class Combined4:

    @staticmethod
    def combined4(games):
        """ Generates win probabilities in the my_prob1 field for each game based on Pythagorean Win Theorem model """

        # Initialize team objects(?)
        teams = {}
        for row in [item for item in csv.DictReader(open("data/initial_elos.csv"))]:
            teams[row['team']] = {
                'name': row['team'],
                'season': 'season',
                'Pwin': float(new_team/100),
                'Pfor': [],
                'Pagainst': [],
                'elo': float(row['elo']),
                'Wfor' : [],
                'WforSum' : 0,
                'WinTable' : .5
            }

        for game in games:
            team1, team2 = teams[game['team1']], teams[game['team2']]

            # Revert teams at the start of seasons
            for team in [team1, team2]:
                if team['season'] and game['season'] != team['season']:
                    team['Wfor'] = []
                    # Revert Pythag Win points
                    team['Pfor'][:] = [n / v_value for n in team['Pfor']]
                    team['Pagainst'][:] = [n / v_value for n in team['Pagainst']]
                    k = "%s%s" % (team['name'], game['season'])
                    if k in REVERSIONS:
                        team['elo'] = REVERSIONS[k]
                    else:
                        team['elo'] = 1505.0 * REVERT + team['elo'] * (1 - REVERT)
                team['season'] = game['season']

            # My difference includes home field advantage
            my_diff = (team1['Pwin']+(0 if game['neutral'] == 1 else HFA/100)) - (team2['Pwin'])

            elo_diff = team1['elo'] - team2['elo'] + (0 if game['neutral'] == 1 else HFAE)

            # This is the most important piece, where we set my_prob1 to our forecasted probability
            if game['elo_prob1'] != None:
             #    game['my_prob1'] = .5+my_diff
                if game['playoff'] == 1:
                 elo_diff = team1['elo'] - team2['elo'] + (0 if game['neutral'] == 1 else HFAEP)
                 game['my_prob1'] = (team1['Pwin']+(HFAP/100))**a_factor/((team1['Pwin']+(HFAP/100))**a_factor+team2['Pwin']**a_factor)
                 game['my_prob2'] = 1.0 / (math.pow(10.0, (-elo_diff / 400.0)) + 1.0)
                 game['my_prob3'] = (((team1['WinTable']+(HFA2P/100))**b_factor)/(((team1['WinTable']+(HFA2P/100))**b_factor)+(team2['WinTable']**b_factor)))
                 game['my_prob1'] = (percent_mine/100)*game['my_prob1']+((percent_win_chart/100)*game['my_prob3'])+((1-((percent_mine/100)+(percent_win_chart/100)))*game['my_prob2'])
                 game['point_diff'] = round((expect_points * game['my_prob1']) - (expect_points / 2), 1)
                 game['point_diff2'] = round((y_factor * (abs(((expect_points * game['my_prob1']) - (expect_points / 2))))) ** ( 1 / x_factor), 1)
                else:
                 game['my_prob1'] = (team1['Pwin']+(0 if game['neutral'] == 1 else HFA/100))**a_factor/((team1['Pwin']+(0 if game['neutral'] == 1 else HFA/100))**a_factor+team2['Pwin']**a_factor)
                 game['my_prob2'] = 1.0 / (math.pow(10.0, (-elo_diff / 400.0)) + 1.0)
                 game['my_prob3'] = (((team1['WinTable']+(HFA2/100))**b_factor)/(((team1['WinTable']+(HFA2/100))**b_factor)+(team2['WinTable']**b_factor)))
                 game['my_prob1'] = (percent_mine/100)*game['my_prob1']+((percent_win_chart/100)*game['my_prob3'])+((1-((percent_mine/100)+(percent_win_chart/100)))*game['my_prob2'])
                 game['my_prob_qb1_out'] = game['my_prob1']-backup_qb_percent
                 game['my_prob_qb2_out'] = game['my_prob1']+backup_qb_percent
                 game['point_diff'] = ((expect_points * game['my_prob1']) - (expect_points / 2))
                 #game['point_diff2'] = round(((y_factor * (abs(((expect_points * game['my_prob1']) - (expect_points / 2))))) ** ( 1 / x_factor))*2,0)/2
                 game['point_diff2'] = (y_factor * (abs(((expect_points * game['my_prob1']) - (expect_points / 2))))) ** (1 / x_factor)
                 game['point_diff_qb1_out'] = round((y_factor * (abs(((expect_points * game['my_prob_qb1_out']) - (expect_points / 2))))) ** ( 1 / x_factor),1)
                 game['point_diff_qb2_out'] = round((y_factor * (abs(((expect_points * game['my_prob_qb2_out']) - (expect_points / 2))))) ** (1 / x_factor),1)
                 if game['point_diff'] < 0:
                    game['point_diff2'] = -game['point_diff2']
                    if game['my_prob_qb1_out'] < .5:
                       game['point_diff_qb1_out'] = -game['point_diff_qb1_out']
                    if game['my_prob_qb2_out'] < .5:
                       game['point_diff_qb2_out'] = -game['point_diff_qb2_out']

            # If game was played, maintain team Elo ratings
            if game['score1'] != None:

              #   Margin of victory is used as a K multiplier
                pd = abs(game['score1'] - game['score2'])
                mult = math.log(max(pd, 1) + 1.0) * (2.2 / (1.0 if game['result1'] == 0.5 else ((my_diff if game['result1'] == 1.0 else -my_diff) * 0.001 + 2.2)))

              # Elo shift based on K and the margin of victory multiplier
                shift = (K * mult) * (game['result1'] - game['my_prob1'])

              #  Elo shift based on K and the margin of victory multiplier
                Pwin = (K * mult) * (game['result1'] - game['my_prob1'])
              # Apply shift
                team1['elo'] += shift
                team2['elo'] -= shift

            # Add Points to team arrays
                team1['Pfor'].append(game['score1'])
                team1['Pagainst'].append(game['score2'])
                team2['Pfor'].append(game['score2'])
                team2['Pagainst'].append(game['score1'])

            # Add Wins to team arrays
                team1['Wfor'].append(game['result1'])
                team2['Wfor'].append(1-game['result1'])

            # Sum team all time points
                team1['PforSum']=(sum(team1['Pfor']))
                team1['PagainstSum'] = (sum(team1['Pagainst']))
                team2['PforSum']=(sum(team2['Pfor']))
                team2['PagainstSum'] = (sum(team2['Pagainst']))

                if len(team1['Pfor']) <= past_games and (team1['PforSum'] or team1['PagainstSum']) != 0:
                   team1['Pwin'] = ((team1['PforSum'])**wf)/((sum(team1['Pfor']))**wf+(sum(team1['Pagainst']))**wf)
                elif len(team1['Pfor']) > past_games and (team1['PforSum'] or team1['PagainstSum']) !=0:
                  #  print len(team1['Pfor'])
                    # Sum points for games in past_games range
                    team1['PforSumInRange'] = (sum(team1['Pfor'][len(team1['Pfor']) - past_games:]))
                    team1['PagainstSumInRange'] = (sum(team1['Pagainst'][len(team1['Pagainst']) - past_games:]))
                    team1['Pwin'] = (team1['PforSumInRange']**wf)/(((team1['PforSumInRange'])**wf)+((team1['PagainstSumInRange'])**wf))
                    #team1['Pwin'] = ((sum(team1['Pfor'][len(team1['Pfor'])-past_games:]))** wf)/(((sum(team1['Pfor'][len(team1['Pfor'])-past_games:]))**wf)+((sum(team1['Pagainst'][len(team1['Pagainst'])-past_games:]))**wf))
                    # print len(team1['Pfor'])
                else:
                   team1['Pwin'] = team_below_min/100
                if len(team1['Pfor']) <= past_games and (team2['PforSum'] or team2['PagainstSum']) != 0:
                   team2['Pwin'] = ((sum(team2['Pfor']))**wf)/(((sum(team2['Pfor']))**wf)+(sum(team2['Pagainst']))**wf)
                elif len(team2['Pfor']) > past_games and (team2['PforSum'] or team2['PagainstSum']) != 0:
                    # Sum points for games in past_games range
                    team2['PforSumInRange'] = (sum(team2['Pfor'][len(team2['Pfor']) - past_games:]))
                    team2['PagainstSumInRange'] = (sum(team2['Pagainst'][len(team2['Pagainst']) - past_games:]))
                    #
                    team2['Pwin'] = ((sum(team2['Pfor'][len(team2['Pfor'])-past_games:]))**wf)/(((sum(team2['Pfor'][len(team2['Pfor'])-past_games:]))**wf)+((sum(team2['Pagainst'][len(team2['Pagainst'])-past_games:]))**wf))
                else:
                    team2['Pwin'] = team_below_min/100

                # Check number of games played, find record, disregard playoffs
                if game['playoff'] == 1:
                    team1['WinTable'] = 0.0
                else:
                    team1['WforSum'] = sum(team1['Wfor'])
                    team1['LforSum'] = round(len(team1['Wfor'])-sum(team1['Wfor']),0)
                    team1['Games_played'] = len(team1['Wfor'])
                if game['playoff'] == 1:
                    team2['WinTable'] = 0.0
                else:
                    team2['WforSum'] = sum(team2['Wfor'])
                    team2['LforSum'] = round(len(team2['Wfor']) - sum(team2['Wfor']), 0)
                    team2['Games_played'] = len(team2['Wfor'])
               # print(team1['WforSum'])

                # Values for each possible record
                if   team1['Games_played']==0:
                     team1['WinTable'] = 0.5
                elif team1['Games_played'] == 1:
                    if  team1['WforSum'] == 1:
                        team1['WinTable'] = 0.54
                    else:
                        team1['WinTable'] = 0.46
                elif team1['Games_played'] == 2:
                    if  team1['WforSum'] == 2:
                        team1['WinTable'] = .564286
                    elif team1['WforSum'] == 1:
                        team1['WinTable'] = 0.514286
                    else:
                        team1['WinTable'] = 0.407143
                elif team1['Games_played'] == 3:
                    if  team1['WforSum'] == 3:
                        team1['WinTable'] = .592308
                    elif  team1['WforSum'] == 2:
                        team1['WinTable'] = .538462
                    elif team1['WforSum'] == 1:
                        team1['WinTable'] = 0.476923
                    else:
                        team1['WinTable'] = 0.376923
                elif team1['Games_played'] == 4:
                    if  team1['WforSum'] == 4:
                        team1['WinTable'] = .600833
                    elif team1['WforSum'] == 3:
                        team1['WinTable'] = .566667
                    elif  team1['WforSum'] == 2:
                        team1['WinTable'] = .508333
                    elif team1['WforSum'] == 1:
                        team1['WinTable'] = 0.433333
                    else:
                        team1['WinTable'] = 0.366667
                elif team1['Games_played'] == 5:
                    if  team1['WforSum'] == 5:
                        team1['WinTable'] = .645455
                    elif team1['WforSum'] == 4:
                        team1['WinTable'] = .6
                    elif team1['WforSum'] == 3:
                        team1['WinTable'] = .527273
                    elif  team1['WforSum'] == 2:
                        team1['WinTable'] = .463636
                    elif team1['WforSum'] == 1:
                        team1['WinTable'] = 0.409091
                    else:
                        team1['WinTable'] = 0.363636
                elif team1['Games_played'] == 6:
                    if  team1['WforSum'] == 6:
                        team1['WinTable'] = .66
                    elif team1['WforSum'] == 5:
                        team1['WinTable'] = .6
                    elif team1['WforSum'] == 4:
                        team1['WinTable'] = .55
                    elif team1['WforSum'] == 3:
                        team1['WinTable'] = .52
                    elif  team1['WforSum'] == 2:
                        team1['WinTable'] = .42
                    elif team1['WforSum'] == 1:
                        team1['WinTable'] = 0.39
                    else:
                        team1['WinTable'] = 0.32
                elif team1['Games_played'] == 7:
                    if  team1['WforSum'] == 7:
                        team1['WinTable'] = .688889
                    elif team1['WforSum'] == 6:
                        team1['WinTable'] = .63333
                    elif team1['WforSum'] == 5:
                        team1['WinTable'] = .577778
                    elif team1['WforSum'] == 4:
                        team1['WinTable'] = .522222
                    elif team1['WforSum'] == 3:
                        team1['WinTable'] = .477778
                    elif  team1['WforSum'] == 2:
                        team1['WinTable'] = .4
                    elif team1['WforSum'] == 1:
                        team1['WinTable'] = 0.38889
                    else:
                        team1['WinTable'] = 0.32222
                elif team1['Games_played'] == 8:
                    if team1['WforSum'] == 8.0:
                        team1['WinTable'] = .675
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .675
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .6
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .5875
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .4875
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .4375
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .3625
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .35
                    else:
                        team1['WinTable'] = .3125
                elif team1['Games_played'] == 9:
                    if team1['WforSum'] == 9.0:
                        team1['WinTable'] = .642857
                    elif team1['Wfor'] == 8.0:
                         team1['WinTable'] = .7
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .628571
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .6
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .557143
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .442857
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .414286
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .357142
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .314286
                    else:
                        team1['WinTable'] = .242857
                elif team1['Games_played'] == 10:
                    if team1['WforSum'] == 10.0:
                        team1['WinTable'] = .666667
                    elif team1['Wfor'] == 9.0:
                         team1['WinTable'] = .65
                    elif team1['Wfor'] == 8.0:
                         team1['WinTable'] = .65
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .616667
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .566667
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .516667
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .433333
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .4
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .3
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .3
                    else:
                        team1['WinTable'] = .283333
                elif team1['Games_played'] == 11:
                    if team1['WforSum'] == 11.0:
                        team1['WinTable'] = .68
                    elif team1['Wfor'] == 10.0:
                         team1['WinTable'] = .62
                    elif team1['Wfor'] == 9.0:
                         team1['WinTable'] = .7
                    elif team1['Wfor'] == 8.0:
                         team1['WinTable'] = .62
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .58
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .54
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .46
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .44
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .4
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .3
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .3
                    else:
                        team1['WinTable'] = .283333
                elif team1['Games_played'] == 12:
                    if team1['WforSum'] == 12.0:
                        team1['WinTable'] = .6
                    elif team1['Wfor'] == 11.0:
                         team1['WinTable'] = .575
                    elif team1['Wfor'] == 10.0:
                         team1['WinTable'] = .7
                    elif team1['Wfor'] == 9.0:
                         team1['WinTable'] = .65
                    elif team1['Wfor'] == 8.0:
                         team1['WinTable'] = .575
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .55
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .55
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .45
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .4
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .35
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .3
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .325
                    else:
                        team1['WinTable'] = .3
                elif team1['Games_played'] == 13:
                    if team1['WforSum'] == 13.0:
                        team1['WinTable'] = .466667
                    elif team1['Wfor'] == 12.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 11.0:
                         team1['WinTable'] = .633333
                    elif team1['Wfor'] == 10.0:
                         team1['WinTable'] = .666667
                    elif team1['Wfor'] == 9.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 8.0:
                         team1['WinTable'] = .566667
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .5
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .5
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .466667
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .333333
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .333333
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .333333
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .2
                    else:
                        team1['WinTable'] = .333333
                elif team1['Games_played'] == 14:
                    if team1['WforSum'] == 14.0:
                        team1['WinTable'] = .5
                    elif team1['Wfor'] == 13.0:
                         team1['WinTable'] = .55
                    elif team1['Wfor'] == 12.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 11.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 10.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 9.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 8.0:
                         team1['WinTable'] = .55
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .5
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .5
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .45
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .3
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .4
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .25
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .2
                    else:
                        team1['WinTable'] = 0.0
                elif team1['Games_played'] == 15:
                    if team1['WforSum'] == 15.0:
                        team1['WinTable'] = 1
                    elif team1['Wfor'] == 14.0:
                         team1['WinTable'] = .8
                    elif team1['Wfor'] == 13.0:
                         team1['WinTable'] = .4
                    elif team1['Wfor'] == 12.0:
                         team1['WinTable'] = .7
                    elif team1['Wfor'] == 11.0:
                         team1['WinTable'] = .7
                    elif team1['Wfor'] == 10.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 9.0:
                         team1['WinTable'] = .6
                    elif team1['Wfor'] == 8.0:
                         team1['WinTable'] = .5
                    elif team1['Wfor'] == 7.0:
                         team1['WinTable'] = .5
                    elif team1['WforSum'] == 6.0:
                         team1['WinTable'] = .4
                    elif team1['WforSum'] == 5.0:
                         team1['WinTable'] = .4
                    elif team1['WforSum'] == 4.0:
                         team1['WinforSum'] = .2
                    elif team1['WforSum'] == 3.0:
                         team1['WinTable'] = .4
                    elif team1['WforSum'] == 2.0:
                         team1['WinTable'] = .1
                    elif team1['WforSum'] == 1.0:
                         team1['WinTable'] = .2
                    else:
                        team1['WinTable'] = 0.0

                # Values for Team 2
                if   team2['Games_played']== 0:
                     team2['WinTable'] = 0.5
                elif team2['Games_played'] == 1:
                    if  team2['WforSum'] == 1:
                        team2['WinTable'] = 0.54
                    else:
                        team2['WinTable'] = 0.46
                elif team2['Games_played'] == 2:
                    if  team2['WforSum'] == 2:
                        team2['WinTable'] = .564286
                    elif team2['WforSum'] == 1:
                        team2['WinTable'] = 0.514286
                    else:
                        team2['WinTable'] = 0.407143
                elif team2['Games_played'] == 3:
                    if  team2['WforSum'] == 3:
                        team2['WinTable'] = .592308
                    elif  team2['WforSum'] == 2:
                        team2['WinTable'] = .538462
                    elif team2['WforSum'] == 1:
                        team2['WinTable'] = 0.476923
                    else:
                        team2['WinTable'] = 0.376923
                elif team2['Games_played'] == 4:
                    if  team2['WforSum'] == 4:
                        team2['WinTable'] = .600833
                    elif team2['WforSum'] == 3:
                        team2['WinTable'] = .566667
                    elif  team2['WforSum'] == 2:
                        team2['WinTable'] = .508333
                    elif team2['WforSum'] == 1:
                        team2['WinTable'] = 0.433333
                    else:
                        team2['WinTable'] = 0.366667
                elif team2['Games_played'] == 5:
                    if  team2['WforSum'] == 5:
                        team2['WinTable'] = .645455
                    elif team2['WforSum'] == 4:
                        team2['WinTable'] = .6
                    elif team2['WforSum'] == 3:
                        team2['WinTable'] = .527273
                    elif  team2['WforSum'] == 2:
                        team2['WinTable'] = .463636
                    elif team2['WforSum'] == 1:
                        team2['WinTable'] = 0.409091
                    else:
                        team2['WinTable'] = 0.363636
                elif team2['Games_played'] == 6:
                    if  team2['WforSum'] == 6:
                        team2['WinTable'] = .66
                    elif team2['WforSum'] == 5:
                        team2['WinTable'] = .6
                    elif team2['WforSum'] == 4:
                        team2['WinTable'] = .55
                    elif team2['WforSum'] == 3:
                        team2['WinTable'] = .52
                    elif  team2['WforSum'] == 2:
                        team2['WinTable'] = .42
                    elif team2['WforSum'] == 1:
                        team2['WinTable'] = 0.39
                    else:
                        team2['WinTable'] = 0.32
                elif team2['Games_played'] == 7:
                    if  team2['WforSum'] == 7:
                        team2['WinTable'] = .688889
                    elif team2['WforSum'] == 6:
                        team2['WinTable'] = .63333
                    elif team2['WforSum'] == 5:
                        team2['WinTable'] = .577778
                    elif team2['WforSum'] == 4:
                        team2['WinTable'] = .522222
                    elif team2['WforSum'] == 3:
                        team2['WinTable'] = .477778
                    elif  team2['WforSum'] == 2:
                        team2['WinTable'] = .4
                    elif team2['WforSum'] == 1:
                        team2['WinTable'] = 0.38889
                    else:
                        team2['WinTable'] = 0.32222
                elif team2['Games_played'] == 8:
                    if team2['WforSum'] == 8.0:
                        team2['WinTable'] = .675
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .675
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .6
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .5875
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .4875
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .4375
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .3625
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .35
                    else:
                        team2['WinTable'] = .3125
                elif team2['Games_played'] == 9:
                    if team2['WforSum'] == 9.0:
                        team2['WinTable'] = .642857
                    elif team2['Wfor'] == 8.0:
                         team2['WinTable'] = .7
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .628571
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .6
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .557143
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .442857
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .414286
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .357142
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .314286
                    else:
                        team2['WinTable'] = .242857
                elif team2['Games_played'] == 10:
                    if team2['WforSum'] == 10.0:
                        team2['WinTable'] = .666667
                    elif team2['Wfor'] == 9.0:
                         team2['WinTable'] = .65
                    elif team2['Wfor'] == 8.0:
                         team2['WinTable'] = .65
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .616667
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .566667
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .516667
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .433333
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .4
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .3
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .3
                    else:
                        team2['WinTable'] = .283333
                elif team2['Games_played'] == 11:
                    if team2['WforSum'] == 11.0:
                        team2['WinTable'] = .68
                    elif team2['Wfor'] == 10.0:
                         team2['WinTable'] = .62
                    elif team2['Wfor'] == 9.0:
                         team2['WinTable'] = .7
                    elif team2['Wfor'] == 8.0:
                         team2['WinTable'] = .62
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .58
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .54
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .46
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .44
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .4
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .3
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .3
                    else:
                        team2['WinTable'] = .283333
                elif team2['Games_played'] == 12:
                    if team2['WforSum'] == 12.0:
                        team2['WinTable'] = .6
                    elif team2['Wfor'] == 11.0:
                         team2['WinTable'] = .575
                    elif team2['Wfor'] == 10.0:
                         team2['WinTable'] = .7
                    elif team2['Wfor'] == 9.0:
                         team2['WinTable'] = .65
                    elif team2['Wfor'] == 8.0:
                         team2['WinTable'] = .575
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .55
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .55
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .45
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .4
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .35
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .3
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .325
                    else:
                        team2['WinTable'] = .3
                elif team2['Games_played'] == 13:
                    if team2['WforSum'] == 13.0:
                        team2['WinTable'] = .466667
                    elif team2['Wfor'] == 12.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 11.0:
                         team2['WinTable'] = .633333
                    elif team2['Wfor'] == 10.0:
                         team2['WinTable'] = .666667
                    elif team2['Wfor'] == 9.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 8.0:
                         team2['WinTable'] = .566667
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .5
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .5
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .466667
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .333333
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .333333
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .333333
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .2
                    else:
                        team2['WinTable'] = .333333
                elif team2['Games_played'] == 14:
                    if team2['WforSum'] == 14.0:
                        team2['WinTable'] = .5
                    elif team2['Wfor'] == 13.0:
                         team2['WinTable'] = .55
                    elif team2['Wfor'] == 12.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 11.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 10.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 9.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 8.0:
                         team2['WinTable'] = .55
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .5
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .5
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .45
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .3
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .4
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .25
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .2
                    else:
                        team2['WinTable'] = 0.0
                elif team2['Games_played'] == 15:
                    if team2['WforSum'] == 15.0:
                        team2['WinTable'] = 1
                    elif team2['Wfor'] == 14.0:
                         team2['WinTable'] = .8
                    elif team2['Wfor'] == 13.0:
                         team2['WinTable'] = .4
                    elif team2['Wfor'] == 12.0:
                         team2['WinTable'] = .7
                    elif team2['Wfor'] == 11.0:
                         team2['WinTable'] = .7
                    elif team2['Wfor'] == 10.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 9.0:
                         team2['WinTable'] = .6
                    elif team2['Wfor'] == 8.0:
                         team2['WinTable'] = .5
                    elif team2['Wfor'] == 7.0:
                         team2['WinTable'] = .5
                    elif team2['WforSum'] == 6.0:
                         team2['WinTable'] = .4
                    elif team2['WforSum'] == 5.0:
                         team2['WinTable'] = .4
                    elif team2['WforSum'] == 4.0:
                         team2['WinforSum'] = .2
                    elif team2['WforSum'] == 3.0:
                         team2['WinTable'] = .4
                    elif team2['WforSum'] == 2.0:
                         team2['WinTable'] = .1
                    elif team2['WforSum'] == 1.0:
                         team2['WinTable'] = .2
                    else:
                        team2['WinTable'] = 0.0


import backend
import tkinter
import ast

class WeatherApp(tkinter.Tk):

    def __init__(self, window_name, window_size):

        self.city = None
        self.date = None
        self.op_list = ["10-1-2018", "Wichita"]

        self.database = backend.Database("../data/weather.db")

        tkinter.Tk.__init__(self)

        self.frame = HomePage(master=self)
        self.frame.pack(fill="both", expand=True)

        self.title(window_name)
        self.geometry(window_size)

    def switchFrames(self, frame):

        if frame is SecondPage:
            try:
                self.op_list = self.frame.test
            except AttributeError:
                pass

        self.frame.destroy()

        initFrame = frame(master=self)
        self.frame = initFrame
        self.frame.pack(fill="both", expand=True)

    def getCity(self):
        return self.op_list[1]

    def getDate(self):
        return self.op_list[0]

    def getop(self):
        return self.op_list

    def run(self):
        self.mainloop()

class HomePage(tkinter.Frame):

    def __init__(self, master):
        self.master = master
        tkinter.Frame.__init__(self, master=master)

        self.set_background()

        self.config_grid()

        self.add_widgets()

    def update_current_spinbox_data(self, event):
        self.test = [self.date.get(), self.cities.get()]

    def add_widgets(self):

        self.home_label = tkinter.Label(master=self, text="Welcome to Fiesta Weather!", justify = "center", font = ("Tahoma", 20), bg="#FFFFFF")
        self.home_label.grid(row=0, column=2, pady = 20)

        self.city_label = tkinter.Label(master = self, text = "Pick Your City", font = ("Tahoma", 18), bg="#FFFFFF")
        self.city_label.grid(row = 2, column = 1)

        self.date_label = tkinter.Label(master = self, text = "Choose A Date", font = ("Tahoma", 18), bg="#FFFFFF")
        self.date_label.grid(row = 2, column = 3, pady = 20)

        self.run_button = tkinter.Button(master = self, text = "Run", font = ("Tahoma", 18), relief = "sunken", command = lambda: self.master.switchFrames(SecondPage))
        self.run_button.grid(row = 5, column = 2, pady = 20)

        selectCity = ("Wichita", "Chicago", "Miami")

        self.cities = tkinter.Spinbox(master = self, values = selectCity, font = ("Tahoma", 16))
        self.cities.grid(row = 3, column = 1)

        # Creating List of dates
        date_list = []

        date_string = "{_month}-{_day}-2018"

        for month in range(10,12):
            for day in range(1, 32):
                if month == 11 and day == 31:
                    break
                else:
                    date_list.append(date_string.format(_month=month, _day=day))

        self.date = tkinter.Spinbox(master = self, values = tuple(date_list), font = ("Tahoma", 14))
        self.date.grid (row = 3, column = 3)

        self.cities.bind("<Leave>", self.update_current_spinbox_data)
        self.date.bind("<Leave>", self.update_current_spinbox_data)

    def config_grid(self):

        self.columnconfigure(index = 0, weight = 1)
        self.columnconfigure(index = 4, weight = 1)

        self.rowconfigure(index = 1, weight = 1)
        self.rowconfigure(index = 7, weight = 1)
        self.rowconfigure(index = 6, weight = 2)

    def set_background(self):

        self.fname = "../images/party.gif"

        self.photo = tkinter.PhotoImage(file=self.fname)

        self.test_label = tkinter.Label(master=self, image=self.photo)
        self.test_label.image = self.photo
        self.test_label.place(x=0, y=0, relwidth=1, relheight=1)

class SecondPage(tkinter.Frame):

    def __init__(self, master):
        tkinter.Frame.__init__(self, master=master)

        """ This is the background color list of our jpgs """
        self.color_dict = {"snowyGIF": "#01ABF5", "cloudsGIF": {"header": "#878787", "body": "#141414"}, "rainingGIF": {"header": "#878787", "body": "#141414"}, "sunnyGIF": "#FEC327"}

        self._user_city = master.getCity()
        self._user_date = master.getDate()

        self.weather = master.database.get_weather(city_name=master.getCity(), user_date=master.getDate())

        condition = self.weather[3]

        # stored data into database as string representation of python native type (in this case a dict)
        # to easily extract the data out of the database (can't insert python dict into a sql database)
        # that's where ast's literal_eval saves the day

        condition = ast.literal_eval(self.weather[3])
        condition = condition["description"]

        self.insert_image(condition)

        self.add_widgets_colorized(condition)

        # the "back button" is not inside of add_widgets_colorized bc it doesn't need its background changed
        """BACK BUTTON"""
        self.back = tkinter.Button(master = self, text = "Back", font = ("Tahoma", 17), relief = "sunken", command = lambda: master.switchFrames(HomePage))
        self.back.grid(row = 7, column = 2)

        self.columnconfigure(index = 6, weight = 2)
        self.rowconfigure(index = 6, weight = 1)
        self.rowconfigure(index = 8, weight = 2)

    def insert_image(self, weather_condition):

        if weather_condition == "Cloudy" or weather_condition == "Partly Cloudy" or weather_condition == "Overcast" or weather_condition == "Mostly Cloudy" or weather_condition == "Scattered Clouds" or weather_condition == "Haze" or weather_condition == "overcast clouds":
            self.fname = "../images/{description}.gif".format(description="clouds")
        elif weather_condition == "Rainy" or weather_condition == "Rain" or weather_condition == "Light Rain" or weather_condition == "light rain":
            self.fname = "../images/{description}.gif".format(description="raining")
        elif weather_condition == "Snowy" or weather_condition == "Snow" or weather_condition == "light snow":
            self.fname = "../images/{description}.gif".format(description="snowy")
        else:
            self.fname = "../images/{description}.gif".format(description="sunny")

        self.photo = tkinter.PhotoImage(file=self.fname)

        self.test_label = tkinter.Label(master=self, image=self.photo)
        self.test_label.image = self.photo
        self.test_label.place(x=0, y=0, relwidth=1, relheight=1)

    def add_widgets_colorized(self, weather_condition):

        if weather_condition == "Cloudy" or weather_condition == "Partly Cloudy" or weather_condition == "Overcast" or weather_condition == "Mostly Cloudy" or weather_condition == "Scattered Clouds" or weather_condition == "Haze" or weather_condition == "overcast clouds":
            hex_color = self.color_dict["cloudsGIF"]
            header = hex_color["header"]
            body = hex_color["body"]

        elif weather_condition == "Rainy" or weather_condition == "Rain" or weather_condition == "light rain" or weather_condition == "Light Rain":
            hex_color = self.color_dict["rainingGIF"]
            header = hex_color["header"]
            body = hex_color["body"]

        elif weather_condition == "Snowy" or weather_condition == "Snow" or weather_condition == "light snow":
            hex_color = self.color_dict["snowyGIF"]

        else:
            hex_color = self.color_dict["sunnyGIF"]

        if type(hex_color) is dict:

            """SHOWS TITLE"""

            weatherString = "Weather for {city} on {date}".format(city = self._user_city, date = self._user_date)

            self.title_label = tkinter.Label(master = self, text = weatherString, font = ("Tahoma", 16), bg=header, fg="#ffffff")
            self.title_label.grid(row = 0, column = 2, pady=10)

            coord = self.weather[2]
            coord = ast.literal_eval(self.weather[2])
            lon = coord["lon"]
            lat = coord["lat"]

            self.columnconfigure(index = 0, weight = 2)

            """SHOWS COORDINATES"""
            coordString = "Coordinates ({la}, {lo})".format(la = lat, lo = lon)
            self.coord_label = tkinter.Label(master = self, text = coordString, font = ("Tahoma", 14), bg=body, fg="#ffffff")
            self.coord_label.grid(row = 1, column = 2)

            condition = self.weather[3]
            condition = ast.literal_eval(self.weather[3])
            condition = condition["description"]

            """SHOWS WEATHER DESCRIPTION"""

            descString = "Weather Description: {description}".format(description = condition.title())
            self.description = tkinter.Label(master = self, text = descString, font = ("Tahoma", 16), bg=body, fg="#ffffff")
            self.description.grid(row = 2, column = 1, padx = 20)

            """SHOWS VISABILITY"""
            vis = self.weather[4]
            if vis >= 10:
                visString = "Visability: {show_vis} miles".format(show_vis = vis)
            else:
                visString = "Visability: {show_vis} mile".format(show_vis = vis)

            self.visability = tkinter.Label(master = self, text = visString, font = ("Tahoma", 16), bg=body, fg="#ffffff")
            self.visability.grid(row = 3, column = 1, padx = 20)

            self.columnconfigure(index = 2, weight = 2)

            """SHOWS TEMPERATURE"""
            ave_temp = self.weather[5]
            tempString = "Average temperature: {temp} \u00b0F".format(temp = ave_temp)
            self.average = tkinter.Label(master = self, text = tempString, font = ("Tahoma", 16), bg=body, fg="#ffffff")
            self.average.grid(row = 2, column = 3, pady = 5, padx = 20)

            """SHOWS MIN TEMP"""
            min_temp = self.weather[6]
            mintempString = "Minimum temperature: {min} \u00b0F".format(min = min_temp)
            self.minimum = tkinter.Label(master = self, text = mintempString, font = ("Tahoma", 16), bg=body, fg="#ffffff")
            self.minimum.grid(row = 3, column = 3, pady = 5)

            """SHOWS MAX TEMP"""
            max_temp = self.weather[7]
            maxtempString = "Maximum temperature: {max} \u00b0F".format(max = max_temp)
            self.maximum = tkinter.Label(master = self, text = maxtempString, font = ("Tahoma", 16), bg=body, fg="#ffffff")
            self.maximum.grid(row = 4, column = 3, pady = 5)

            """SHOWS WIND SPEED"""
            windDes = self.weather[10]
            col_loc = windDes.find(":")
            com_loc = windDes.find(",")
            speed = windDes[col_loc+2:com_loc]

            wind_junior = windDes[com_loc+2:]
            jr_col_loc = wind_junior.find(":")
            direction = wind_junior[jr_col_loc+3:-2]

            _windSpeed = "Wind Speed: {_wind} mph".format(_wind = speed)
            self._windspeed = tkinter.Label(master = self, text = _windSpeed, font = ("Tahoma", 16), bg=body, fg="#ffffff")
            self._windspeed.grid(row = 4, column = 1, padx = 20)

            _windDeg = "Wind Direction: {_deg}".format(_deg = direction)
            self._windDeg = tkinter.Label(master = self, text = _windDeg, font = ("Tahoma", 16), bg=body, fg="#ffffff")
            self._windDeg.grid(row = 5, column = 1, padx = 20)

        else:

            """SHOWS TITLE"""

            weatherString = "Weather for {city} on {date}".format(city = self._user_city, date = self._user_date)

            self.title_label = tkinter.Label(master = self, text = weatherString, font = ("Tahoma", 17), bg=hex_color)
            self.title_label.grid(row = 0, column = 2, pady=10)

            coord = self.weather[2]
            coord = ast.literal_eval(self.weather[2])
            lon = coord["lon"]
            lat = coord["lat"]

            self.columnconfigure(index = 0, weight = 2)

            """SHOWS COORDINATES"""
            coordString = "Coordinates ({la}, {lo})".format(la = lat, lo = lon)
            self.coord_label = tkinter.Label(master = self, text = coordString, font = ("Tahoma", 14), bg=hex_color)
            self.coord_label.grid(row = 1, column = 2)

            condition = self.weather[3]
            condition = ast.literal_eval(self.weather[3])
            condition = condition["description"]

            """SHOWS WEATHER DESCRIPTION"""
            descString = "Weather Description: {description}".format(description = condition.title())
            self.description = tkinter.Label(master = self, text = descString, font = ("Tahoma", 16), bg=hex_color)
            self.description.grid(row = 2, column = 1, padx = 20)

            """SHOWS VISABILITY"""
            vis = self.weather[4]
            if vis >= 2:
                visString = "Visability: {show_vis} miles".format(show_vis = vis)
            else:
                visString = "Visability: {show_vis} mile".format(show_vis = vis)

            self.visability = tkinter.Label(master = self, text = visString, font = ("Tahoma", 16), bg=hex_color)
            self.visability.grid(row = 3, column = 1, padx = 20)

            self.columnconfigure(index = 2, weight = 2)

            """SHOWS TEMPERATURE"""
            ave_temp = self.weather[5]
            tempString = "Average temperature: {temp} \u00b0F".format(temp = ave_temp)
            self.average = tkinter.Label(master = self, text = tempString, font = ("Tahoma", 16), bg=hex_color)
            self.average.grid(row = 2, column = 3, pady = 5, padx = 20)

            """SHOWS MIN TEMP"""
            min_temp = self.weather[6]
            mintempString = "Minimum temperature: {min} \u00b0F".format(min = min_temp)
            self.minimum = tkinter.Label(master = self, text = mintempString, font = ("Tahoma", 16), bg=hex_color)
            self.minimum.grid(row = 3, column = 3, pady = 5)

            """SHOWS MAX TEMP"""
            max_temp = self.weather[7]
            maxtempString = "Maximum temperature: {max} \u00b0F".format(max = max_temp, )
            self.maximum = tkinter.Label(master = self, text = maxtempString, font = ("Tahoma", 16), bg=hex_color)
            self.maximum.grid(row = 4, column = 3, pady = 5)

            """SHOWS WIND SPEED"""
            windDes = self.weather[10]
            col_loc = windDes.find(":")
            com_loc = windDes.find(",")
            speed = windDes[col_loc+2:com_loc]

            wind_junior = windDes[com_loc+2:]
            jr_col_loc = wind_junior.find(":")
            direction = wind_junior[jr_col_loc+3:-2]

            _windSpeed = "Wind Speed: {_wind} mph".format(_wind = speed)
            self._windspeed = tkinter.Label(master = self, text = _windSpeed, font = ("Tahoma", 16), bg=hex_color)
            self._windspeed.grid(row = 4, column = 1, padx = 20)

            _windDeg = "Wind Direction: {_deg}".format(_deg = direction)
            self._windDeg = tkinter.Label(master = self, text = _windDeg, font = ("Tahoma", 16), bg=hex_color)
            self._windDeg.grid(row = 5, column = 1, padx = 20)

test = WeatherApp(window_name="Fiesta Weather", window_size="800x350")

test.run()


## Basic Python imports
import math
import random
from io import BytesIO

## PyTorch imports
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF

## Image / Array imports
from PIL import Image
from PIL import ImageFilter
import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt

class RotationTransform(object):
    """
    Rotates a PIL image by 0, 90, 180, or 270 degrees. Randomly chosen using a uniform distribution.
    """
    def __init__(self, angles=[0, 90, 180, 270]):
        self.angles = angles

    def __call__(self, image):
        angle = random.choice(self.angles)
        return TF.rotate(image, angle)

class GammaJitter(object):
    """
    Jitters the gamma of a PIL image between a uniform distribution of two values (low & high).
    Larger gammas make the shadows darker, smaller gammas make the shadows lighter.
    """
    def __init__(self, low=0.9, high=1.1):
        self.low = low
        self.high = high

    def __call__(self, image):
        gamma = np.random.uniform(self.low, self.high)
        return TF.adjust_gamma(image, gamma)

class BrightnessJitter(object):
    """
    Jitters the gamma of a PIL image between a uniform distribution of two values (low & high).
    Larger gammas make the shadows darker, smaller gammas make the shadows lighter.
    """
    def __init__(self, low=0.9, high=1.1):
        self.low = low
        self.high = high

    def __call__(self, image):
        factor = np.random.uniform(self.low, self.high)
        return TF.adjust_brightness(image, factor)

class RandomScale(object):
    """
    Scales a PIL image based on a value chosen from a uniform distribution of two values (low & high).
    """
    def __init__(self, low=1.0, high=1.1):
        self.low = low
        self.high = high

    def __call__(self, image):
        height = image.height
        width = image.width
        scale = np.random.uniform(self.low, self.high)
        image = TF.resize(image, (math.floor(height * scale), math.floor(width * scale)))
        return TF.center_crop(image, (height, width))

class Interpolate(object):
    """
    Resizes an image to a certain (square) size or by a scale factor.
    """
    def __init__(self, scale=1, size=0):
        self.scale = scale
        self.size = size

    def __call__(self, image):
        if self.size == 0:
            height = image.height
            width = image.width
            return image.resize(((width * self.scale) // 1, (height * self.scale) // 1), Image.BILINEAR)
        else:
            return image.resize((self.size, self.size), Image.BILINEAR)

class InterpolateTorch(object):
    """
    Resizes an image to a certain (square) size or by a scale factor.
    """
    def __init__(self, scale=1, size=0):
        self.scale = scale
        self.size = size

    def __call__(self, image):
        if self.size == 0:
            height = image.shape[1]
            width = image.shape[2]
            if len(image.shape) == 3:
                image = torch.unsqueeze(image, 0)
            return F.interpolate(image, scale_factor=self.scale, mode='bilinear', align_corners=True)
        else:
            return F.interpolate(image, size=(self.size, self.size), mode='bilinear', align_corners=True)

class MaxPool(object):
    """
    Performs Max Pooling on a PIL Image.
    """
    def __init__(self, kernel_size=2):
        self.kernel_size = kernel_size
        self.stride = kernel_size
        self.to_tensor = TF.to_tensor
        self.to_pil = TF.to_pil_image

    def __call__(self, image):
        image = self.to_tensor(image)
        image = F.max_pool2d(image, self.kernel_size, self.stride)
        image = self.to_pil(image)
        return image

class MaxPoolTorch(object):
    """
    Performs Max Pooling on a PyTorch tensor.
    """
    def __init__(self, kernel_size=2):
        self.kernel_size = kernel_size
        self.stride = kernel_size

    def __call__(self, image):
        image = F.max_pool2d(image, self.kernel_size, self.stride)
        return image

class AdaptiveCenterCrop(object):
    """
    Center crops the image to be a square of the smallest edge squared.
    """
    def __init__(self):
        pass

    def __call__(self, image):
        length = min(image.width, image.height)
        return TF.center_crop(image, (length, length))

class MedianFilter(object):
    """
    Randomly applies a median filter to an image.
    """
    def __init__(self, filter_size=3, p=0.1):
        self.filter_size = filter_size
        self.p = p

    def __call__(self, image):
        roll = random.random()
        if roll < self.p:
            return image.filter(ImageFilter.MedianFilter(self.filter_size))
        else:
            return image

class Squeeze(object):
    """
    Squeezes the given PyTorch Tensor object
    """
    def __init__(self):
        ...

    def __call__(self, image):
        if len(image.shape) == 4:
            return image.squeeze_(0)
        else:
            return image

class Unsqueeze(object):
    """
    Unsqueezes the given PyTorch Tensor object in axis=0
    """
    def __init__(self):
        ...

    def __call__(self, image):
        if len(image.shape) == 3:
            return image.unsqueeze_(0)
        else:
            return image

class JPEGCompression(object):
    """
    Compresses the image using jpeg compression and restores
    """
    def __init__(self, quality=75):
        self.quality = quality

    def __call__(self, image):
        save = BytesIO()
        image.save(save, 'JPEG', quality=self.quality)
        image = Image.open(save)
        return image

class JPEGCompressionTorch(object):
    """
    Compresses the image using jpeg compression and restores
    """
    def __init__(self, quality=75):
        self.quality = quality

    def __call__(self, image):
        assert torch.is_tensor(image)
        image = transforms.ToPILImage()(image.cpu().squeeze())
        save = BytesIO()
        image.save(save, 'JPEG', quality=self.quality)
        image = transforms.ToTensor()(Image.open(save))
        return (image.unsqueeze(0).cuda()).requires_grad_(True)

class RandomResizeAndPadTorch(object):
    """
    Randomly resizes and pads an image.
    """
    def __init__(self, initial_size, final_size):
        self.initial_size = initial_size
        self.final_size = final_size
        self.resize = F.interpolate
        self.pad = F.pad

    def __call__(self, image):
        # image = image.unsqueeze(0)

        # Resize the image
        resize_shape = random.randint(self.initial_size, self.final_size)
        image = self.resize(image, size=(resize_shape, resize_shape), mode='bilinear', align_corners=True)

        # Determine how much to pad and do it
        remainder = self.final_size - resize_shape
        left = random.randint(0, remainder)
        right = remainder - left
        top = random.randint(0, remainder)
        bottom = remainder - top
        image = self.pad(image, pad=(left, right, top, bottom), mode='constant', value=0)

        return image

class Normalize(object):
    """
    Normalizes a batch of RGB images [n, 3, H, W]
    """
    def __init__(self, mean, std):
        self.mean = mean
        self.std = std

    def __call__(self, image):
        if len(image.shape) == 3:
            image = image.unsqueeze(0)
        image[:, 0, :, :] = (image[:, 0, :, :] - self.mean[0]) / self.std[0]
        image[:, 1, :, :] = (image[:, 1, :, :] - self.mean[1]) / self.std[1]
        image[:, 2, :, :] = (image[:, 2, :, :] - self.mean[2]) / self.std[2]
        image = image.squeeze()
        return image


from flask import Flask, request
import logging
import json
import random

app = Flask(__name__)

logging.basicConfig(level=logging.INFO)

cities = {
    'москва': ['1540737/daa6e420d33102bf6947', '213044/7df73ae4cc715175059e'],
    'нью-йорк': ['1652229/728d5c86707054d4745f', '1030494/aca7ed7acefde2606bdc'],
    'париж': ['1540737/355c802a54c0d3c2ce38','965417/429d880b7c62324751f1']
}

sessionStorage = {}

@app.route('/post', methods=['POST'])
def main():

    logging.info('Request: %r', request.json)

    response = {
        'session': request.json['session'],
        'version': request.json['version'],
        'response': {
            'end_session': False
        }
    }

    handle_dialog(response, request.json)

    logging.info('Request: %r', response)

    return json.dumps(response)

def handle_dialog(res, req):

    user_id = req['session']['user_id']

    if req['session']['new']:

        res['response']['text'] = 'Привет! Назови свое имя!'
        sessionStorage[user_id] = {
            'first_name': None,
            'game_started': False
        }

        return

    first_name = get_first_name(req)

    if sessionStorage[user_id]['first_name'] is None:

        if first_name is None:
            res['response']['text'] = 'Не раслышала имя. Повтори!'
        else:
            sessionStorage[user_id]['first_name'] = first_name
            sessionStorage[user_id]['guessed_cities'] = []
            res['response']['text'] = 'Приятно познакомиться, ' + first_name.title() + '. Я Алиса. ' \
                                                                                'Отгадаешь город по фото?'
            res['response']['buttons'] = [
                {
                    'title': 'Да',
                    'hide': True

                },
                {
                    'title': 'Нет',
                    'hide': True

                },
                {
                    'title': 'Помощь',
                    'hide': True
                }
            ]

    else:

        if not sessionStorage[user_id]['game_started']:

            if 'да' in req['request']['nlu']['tokens']:

                if len(sessionStorage[user_id]['guessed_cities']) == 3:

                    res['response']['text'] = 'Ты отгадал все города!'
                    res['end_session'] = True

                else:

                    sessionStorage[user_id]['game_started'] = True
                    sessionStorage[user_id]['attempt'] = 1
                    play_game(res, req)

            elif 'нет' in req['request']['nlu']['tokens']:
                res['response']['text'] = 'Ну и ладно!'
                res['end_session'] = True
            elif req['request']['original_utterance'].lower() == 'помощь':
                res['response']['text'] = 'Это текст помомщи. Будь смелее и продолжи общение.'
            else:
                res['response']['text'] = 'Не понял ответа! Так да или нет?'
                res['response']['buttons'] = [
                    {
                        'title': 'Да',
                        'hide': True

                    },
                    {
                        'title': 'Нет',
                        'hide': True

                    },
                    {
                        'title': 'Помощь',
                        'hide': True
                    }
                ]
        elif req['request']['original_utterance'].lower() == 'помощь':
                res['response']['text'] = 'Это текст помомщи. Будь смелее и продолжи общение.'
        else:

            play_game(res, req)

def play_game(res, req):

    user_id = req['session']['user_id']
    attempt = sessionStorage[user_id]['attempt']

    if attempt == 1:

        city = list(cities.keys())[random.randint(0, 2)]

        while (city in sessionStorage[user_id]['guessed_cities']):
            city = list(cities.keys())[random.randint(0, 2)]

        sessionStorage[user_id]['city'] = city

        res['response']['card'] = {}
        res['response']['card']['type'] = 'BigImage'
        res['response']['card']['title'] = 'Что это за город?'
        res['response']['card']['image_id'] = cities[city][attempt - 1]
        res['response']['buttons'] = [
            {
                'title': 'Помощь',
                'hide': True
            }
        ]

    else:

        city = sessionStorage[user_id]['city']

        if get_city(req) == city:

            res['response']['text'] = 'Правильно! Сыграем еще?'
            res['response']['buttons'] = [
                {
                    'title': 'Да',
                    'hide': True

                },
                {
                    'title': 'Нет',
                    'hide': True

                },
                {
                    'title': 'Помощь',
                    'hide': True
                }
            ]
            sessionStorage[user_id]['guessed_cities'].append(city)
            sessionStorage[user_id]['game_started'] = False
            return

        else:

            res['response']['text'] = 'Неправильно'
            if attempt == 3:
                res['response']['text'] = 'Вы пытались. Это ' + city.title() + '. Сыграем еще?'
                res['response']['buttons'] = [
                    {
                        'title': 'Да',
                        'hide': True

                    },
                    {
                        'title': 'Нет',
                        'hide': True

                    },
                    {
                        'title': 'Помощь',
                        'hide': True
                    }
                ]
                sessionStorage[user_id]['game_started'] = False
                sessionStorage[user_id]['guessed_cities'].append(city)
                return
            else:
                res['response']['card'] = {}
                res['response']['card']['type'] = 'BigImage'
                res['response']['card']['title'] = 'Неправильно. Вот тебе дополнительное фото'
                res['response']['card']['image_id'] = cities[city][attempt - 1]
                res['response']['buttons'] = [
                    {
                        'title': 'Помощь',
                        'hide': True
                    }
                ]

    sessionStorage[user_id]['attempt'] += 1

def get_city(req):

    for entity in req['request']['nlu']['entities']:

        if entity['type'] == 'YANDEX.GEO':

            if 'city' in entity['value'].keys():
                return entity['value']['city']
            else:
                return None

    return None

def get_first_name(req):

    for entity in req['request']['nlu']['entities']:

        if entity['type'] == 'YANDEX.FIO':

            if 'first_name' in entity['value'].keys():
                return entity['value']['first_name']
            else:
                return None
    return None

if __name__ == '__main__':
    app.run()

Алиса/1 - Помощь с угадыванием.py

1 - Помощь с угадыванием.py


from os import walk, listdir, chdir
from os.path import join, getsize

path_original = "original"
path_medium = "medium"
path_small = "small"
path_thumb = "thumb"
path_unsorted = "unsorted"

for root, dirs, files in walk(path_unsorted):
    print(files)

#for dirpath, dirname, filenames in images_thumb:
    #files_thumb.extend(join(dirpath, filename) for filename in filenames)


"""
Класс для работы с файлом конфигурации
Конфигурация должна храниться в формате YAML.
В процессе работы объкет данного класса (с загруженной конфигурацией) передаётся на вход другим этапам пайплайна.
По-умолчанию yaml-файл хранится в директории config.
Config имплементирует класс dictionary питона
"""

import os
import yaml

class Config(dict):

    def __init__(self, path_to_configfile):
        """
        :param path_to_configfile: строка, путь до файла с конфигом
        :return None
        """
        assert os.path.isfile(path_to_configfile), \
            'No configuration file found: {}'.format(path_to_configfile)
        with open(path_to_configfile, "r") as file:
            self.config_ = yaml.safe_load(file)
        # на этом этапе сам объект конфигурации становится словарем
        super(Config, self).__init__(**self.config_)