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

from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

import logging
from math import floor

from db.rewards import Rewards
from db.mongodb_manager import MongoDBManager

class Customers(object):
    """Class to get rewards information from the database."""

    logger = logging.getLogger("Customers")

    @staticmethod
    def delete(email):
        """Deletes a customers data from the database.

        :param str email: The customer's email.
        """
        try:
            # Python 2
            if not isinstance(email, (unicode, str)):
                raise TypeError('email is not of type unicode or str.')
        except NameError:
            # Python 3
            if not isinstance(email, str):
                raise TypeError('email is not of type str.')

        Customers.logger.debug(
            "Customers.delete(%s)",
            email)
        client = MongoDBManager().get_client()
        database = client["Customers"]
        sel_cust = database.customers.find_one({"email_address": email})
        database.customers.delete_one({"_id": sel_cust})

    @staticmethod
    def get(email):
        """Gets information about a customer from the database.

        :param str email: The customer's email.
        :return: A dictionary containing information about the customer.
        :rtype: dict
        """

        Customers.logger.debug(
            "Customers.delete(%s)",
            email)
        client = MongoDBManager().get_client()
        database = client["Customers"]

        if email is None:
            sel_cust = database.customers.find({})
        else:
            sel_cust = database.customers.find_one({"email_address": email})

        if sel_cust is not None:
            return sel_cust
        else:
            return None

    @staticmethod
    def _clone_customer(db_object):
        return Customers._create_customer(
            db_object["email_address"],
            db_object["reward_points"])

    @staticmethod
    def _create_customer(email, total_spent=0.0):
        """Creates a customer dict.

        :param str email: The customer's email.
        :param float total_spent: The amount of money the customer has spent.
        :return: A dictionary containing information about the customer.
        :rtype: dict
        """
        try:
            # Python 2
            if not isinstance(email, (unicode, str)):
                raise TypeError('email is not of type unicode or str.')
        except NameError:
            # Python 3
            if not isinstance(email, str):
                raise TypeError('email is not of type str.')
        if not isinstance(total_spent, float):
            try:
                total_spent = float(total_spent)
            except ValueError:
                raise TypeError('total_spent is not of type float.')

        current_tier, next_tier = Rewards.get_tier(floor(total_spent))

        reward_tier, reward_tier_name, reward_tier_points = \
            Rewards.get_tier_info(current_tier)
        next_reward_tier, next_reward_tier_name, next_reward_tier_points = \
            Rewards.get_tier_info(next_tier)

        if reward_tier_points is None:
            progress = floor(total_spent) / next_reward_tier_points
        elif next_tier is None:
            progress = None
        else:
            progress = (
                floor(total_spent) - reward_tier_points) / (
                next_reward_tier_points - reward_tier_points)

        customer = {
            "email_address": email,
            "reward_points": floor(total_spent),
            "reward_tier": reward_tier,
            "reward_tier_name": reward_tier_name,
            "next_reward_tier": next_reward_tier,
            "next_reward_tier_name": next_reward_tier_name,
            "next_reward_tier_progress": progress
        }

        return customer

    @staticmethod
    def update(email, total_spent=0.0):
        """Updates an existing database record for a customer.
        The total_spent value is added to the existing total.

        :param str email: The customer's email.
        :param float total_spent: The amount of money the customer has spent.
        :return: A dictionary containing information about the customer.
        :rtype: dict
        """
        try:
            # Python 2
            if not isinstance(email, (unicode, str)):
                raise TypeError('email is not of type unicode or str.')
        except NameError:
            # Python 3
            if not isinstance(email, str):
                raise TypeError('email is not of type str.')
        if not isinstance(total_spent, float):
            try:
                total_spent = float(total_spent)
            except ValueError:
                raise TypeError('total_spent is not of type float.')

        client = MongoDBManager().get_client()
        database = client["Customers"]

        sel_cust = database.customers.find_one({"email_address": email})
        total_spent += sel_cust["reward_points"]

        customer = Customers._create_customer(email, total_spent)

        database.customers.update_one(
            {"_id": sel_cust["_id"]},
            {"$set": customer})
        return customer

    @staticmethod
    def insert(email, total_spent=0.0):
        """Creates a database record for a new customer.

        :param str email: The customer's email.
        :param float total_spent: The amount of money the customer has spent.
        :return: A dictionary containing information about the customer.
        :rtype: dict
        """
        try:
            # Python 2
            if not isinstance(email, (unicode, str)):
                raise TypeError('email is not of type unicode or str.')
        except NameError:
            # Python 3
            if not isinstance(email, str):
                raise TypeError('email is not of type str.')
        if not isinstance(total_spent, float):
            try:
                total_spent = float(total_spent)
            except ValueError:
                raise TypeError('total_spent is not of type float.')

        Customers.logger.debug(
            "Customers.insert(%s, %s)",
            email,
            total_spent)
        client = MongoDBManager().get_client()
        database = client["Customers"]
        customer = Customers._create_customer(email, total_spent)
        database.customers.insert(customer)
        return customer

    @staticmethod
    def auto_insert_update(email, total_spent=0.0):
        """Either creates or updates a database record for a customer.

        :param str email: The customer's email.
        :param float total_spent: The amount of money the customer has spent.
        :return: A dictionary containing information about the customer.
        :rtype: dict
        """
        try:
            # Python 2
            if not isinstance(email, (unicode, str)):
                raise TypeError('email is not of type unicode or str.')
        except NameError:
            # Python 3
            if not isinstance(email, str):
                raise TypeError('email is not of type str.')
        if not isinstance(total_spent, float):
            try:
                total_spent = float(total_spent)
            except ValueError:
                raise TypeError('total_spent is not of type float.')

        client = MongoDBManager().get_client()
        database = client["Customers"]
        search_query = database.customers.find({"email_address": email})
        customer = None
        if search_query is None or search_query.count() == 0:
            customer = Customers.insert(email, total_spent)
        else:
            if search_query.count() > 1:
                Customers.logger.warning(
                    "Multiple database entries found for \"%s\", "
                    "still attempting to update.",
                    email)
            customer = Customers.update(email, total_spent)

        return customer


import unittest

from abc import ABC, abstractmethod

import os
import yaml
import torch

from experiments.student_teacher_parameters import StudentTeacherParameters
from experiments.config_templates import ConfigTemplate, MNISTDataTemplate, \
    TrainedMNISTTemplate, PureMNISTTemplate

from components.data_modules.mnist_stream_data \
    import MNISTStreamData

from constants import Constants

FILE_PATH = os.path.dirname(os.path.realpath(__file__))

class _MNISTStreamTest(unittest.TestCase, ABC):
    """
    Test class for mnist_stram.MNISTStreamData
    in components.data_modules.
    """
    @abstractmethod
    def _get_config_path(self):
        raise NotImplementedError

    def setUp(self):
        config_path = self._get_config_path()

        test_model_yaml_path = \
            os.path.join(
                FILE_PATH, "mnist_stream_configs", config_path
                )

        with open(test_model_yaml_path, 'r') as yaml_file:
            params = yaml.load(yaml_file, yaml.SafeLoader)

        self.sample_config = StudentTeacherParameters(
            params, root_config_template=ConfigTemplate,
            mnist_data_config_template=MNISTDataTemplate,
            trained_mnist_config_template=TrainedMNISTTemplate,
            pure_mnist_config_template=PureMNISTTemplate
        )

        self.sample_config.set_property("device", torch.device("cpu"))

        self.mnist_stream_class = MNISTStreamData(self.sample_config)

    def test_init(self):
        """
        This method tests that one each of train and
        test iterators are instantiated.
        """
        self.assertIsInstance(
            self.mnist_stream_class.training_data_iterator,
            torch.utils.data.dataloader._SingleProcessDataLoaderIter
            )
        self.assertIsInstance(
            self.mnist_stream_class.test_data_iterator,
            torch.utils.data.dataloader._SingleProcessDataLoaderIter
            )

    def test_test_set_batching(self):
        """
        This method tests that the test set iterator produces the whole
        test dataset
        """
        test_batch = next(self.mnist_stream_class.test_data_iterator)
        self.assertEqual(len(test_batch[0]), Constants.MNIST_TEST_SET_SIZE)
        self.assertRaises(
            StopIteration, next, self.mnist_stream_class.test_data_iterator
            )

    def test_train_set_batching(self):
        """
        This method tests whether the training iterator is producing the
        correct batch sizes
        """
        train_batch_size = \
            self.sample_config.get(["training", "train_batch_size"])

        expected_num_batches = \
            Constants.MNIST_TRAIN_SET_SIZE // train_batch_size

        for _ in range(expected_num_batches):
            batch = next(self.mnist_stream_class.training_data_iterator)
            self.assertEqual(len(batch[0]), train_batch_size)
            self.assertEqual(len(batch[1]), train_batch_size)

            self.assertEqual(
                batch[0].shape,
                (train_batch_size, Constants.MNIST_FLATTENED_DIM)
                )
            self.assertEqual(len(batch[1]), 1)

        self.assertRaises(
            StopIteration, next, self.mnist_stream_class.training_data_iterator
            )

    def test_get_test_data(self):
        """
        This method tests that the get_test_data method produces
        the whole test set and has the right return format
        """
        test_data = self.mnist_stream_class.get_test_data()

        self.assertIsInstance(test_data, dict)
        self.assertEqual(list(test_data.keys()), ['x'])

        self.assertIsInstance(test_data['x'], torch.Tensor)

        self.assertEqual(
            test_data['x'].shape,
            (Constants.MNIST_TEST_SET_SIZE, Constants.MNIST_FLATTENED_DIM)
            )

    def test_get_batch(self):
        """
        This method tests that the get_batch_method returns
        training batches of the correct dimensions and resets
        the iterator correctly after a cycle through the data.
        """
        train_batch_size = \
            self.sample_config.get(["training", "train_batch_size"])

        expected_num_batches = \
            Constants.MNIST_TRAIN_SET_SIZE // train_batch_size

        for b in range(expected_num_batches):
            batch = self.mnist_stream_class.get_batch()

            self.assertEqual(len(batch['x']), train_batch_size)

            self.assertEqual(
                batch['x'].shape,
                (train_batch_size, Constants.MNIST_FLATTENED_DIM)
                )

        self.assertEqual(
            len(list(
                self.mnist_stream_class.training_data_iterator
                )),
            Constants.MNIST_TRAIN_SET_SIZE
            - expected_num_batches * train_batch_size
            )

        next_cycle_batch = self.mnist_stream_class.get_batch()

        self.assertEqual(len(next_cycle_batch['x']), train_batch_size)

        self.assertEqual(
            next_cycle_batch['x'].shape,
            (train_batch_size, Constants.MNIST_FLATTENED_DIM)
            )

class MNISTStreamTest1(_MNISTStreamTest):

    def _get_config_path(self):
        return "mnist_stream_config_1.yaml"

def get_suite():
    model_tests = [
        'test_init', 'test_test_set_batching', 'test_train_set_batching',
        'test_get_test_data', 'test_get_batch'
        ]
    return unittest.TestSuite(map(MNISTStreamTest1, model_tests))

runner = unittest.TextTestRunner(buffer=True, verbosity=3)
runner.run(get_suite())


from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient, Recipe
from recipe.serializers import IngredientSerializer

INGREDIENTS_URL = reverse('recipe:ingredient-list')

class PublicIngredientAPITest(TestCase):
    """Tests public available ingredients APIs."""

    def setUp(self):
        self.client = APIClient()

    def test_login_required(self):
        """Tests login is required to access the endpoint."""
        res = self.client.get(INGREDIENTS_URL)

        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

class PrivateIngredientAPITest(TestCase):
    """Tests private ingredients APIs."""

    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            'test@test.com',
            'Test123'
        )
        self.client.force_authenticate(self.user)

    def test_retrieve_ingredients_list(self):
        """Tests retrieving a list of ingredients."""

        Ingredient.objects.create(user=self.user, name='abóbra')
        Ingredient.objects.create(user=self.user, name='tangerina')

        res = self.client.get(INGREDIENTS_URL)

        ingredients = Ingredient.objects.all().order_by('-name')
        serializer = IngredientSerializer(ingredients, many=True)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

    def test_ingredients_limited_to_user(self):
        """Tests listing ingredients for authenticated user only."""

        user2 = get_user_model().objects.create_user(
            'other@test.com',
            'Test321'
        )

        Ingredient.objects.create(user=user2, name='cabotiá')
        ingredient = Ingredient.objects.create(user=self.user, name='limão')

        res = self.client.get(INGREDIENTS_URL)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 1)
        self.assertEqual(res.data[0]['name'], ingredient.name)

    def test_create_ingredient_successful(self):
        """Tests creating a new ingredient."""
        payload = {'name': 'cenoura'}
        self.client.post(INGREDIENTS_URL, payload)

        exists = Ingredient.objects.filter(
            user=self.user,
            name=payload['name']
        ).exists()

        self.assertTrue(exists)

    def test_create_ingredient_invalid(self):
        """Tests creating invalid ingredient."""
        payload = {'name': ''}
        res = self.client.post(INGREDIENTS_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_retrieve_ingredients_assigned_to_recipes(self):
        """Tests filtering ingredients assigned to recipes."""
        ingredient1 = Ingredient.objects.create(
            user=self.user,
            name='ingredient 1'
        )
        ingredient2 = Ingredient.objects.create(
            user=self.user,
            name='ingredient 2'
        )
        recipe = Recipe.objects.create(
            user=self.user,
            title='recipe 1',
            time_minutes=1,
            price=1.00
        )
        recipe.ingredients.add(ingredient1)

        res = self.client.get(INGREDIENTS_URL, {'assigned_only': 1})

        serializer1 = IngredientSerializer(ingredient1)
        serializer2 = IngredientSerializer(ingredient2)

        self.assertIn(serializer1.data, res.data)
        self.assertNotIn(serializer2.data, res.data)

    def test_retrieve_ingredients_assigned_unique(self):
        """Tests retrieving one instance of ingredient when its assigned to \
            more than one recipe."""
        ingredient = Ingredient.objects.create(
            user=self.user,
            name='ingredient 1'
        )
        Ingredient.objects.create(
            user=self.user,
            name='ingredient 2'
        )
        recipe1 = Recipe.objects.create(
            user=self.user,
            title='recipe 1',
            time_minutes=1,
            price=1.00
        )
        recipe1.ingredients.add(ingredient)
        recipe2 = Recipe.objects.create(
            user=self.user,
            title='recipe 2',
            time_minutes=1,
            price=1.00
        )
        recipe2.ingredients.add(ingredient)

        res = self.client.get(INGREDIENTS_URL, {'assigned_only': 1})

        self.assertEqual(len(res.data), 1)


# Minimal HTTP server
#
# Usage:
#
#   from httpserver import senffile, Server, CONNECTION_CLOSE
#
#   app = Server()

#   @app.route("GET", "/")
#   def root(conn, request):
#       conn.write(b"HTTP/1.1 200 OK\r\n")
#       conn.write(b"Connection: close\r\n")
#       conn.write(b"Content-Type: text/html\r\n")
#       conn.write(b"\r\n")
#       sendfile(conn, "index.html")
#       return CONNECTION_CLOSE
#
#   app.run()
#
# Handlers for the (method, path) combinations must be decrorated with
# @route, and declared before the server is started (via a call to run).
# Every handler receives the connection socket and a dict with all the
# details from the request (see url.py for exact content).
# When leaving the handler the connection is expected to be closed,
# unless the return code of the handler is CONNECTION_KEEP_ALIVE.
# Any combination of (method, path) which has not been declared using
# @route will, when received by the server, result in a 404 HTTP error.
# The server cannot be stopped unless an alert is raised. If a Handler
# wants to stop the server it should use 'raise Exception("Stop Server")'.
# Only this exception will cause a reasonably graceful exit.
#
# Copyright 2021 (c) Erik de Lange
# Released under MIT license

import socket
import errno

import httpserver.url as url

from micropython import const

CONNECTION_CLOSE = const(0)
CONNECTION_KEEP_ALIVE = const(1)

class HTTPServerError(Exception):
    pass

class Server:

    def __init__(self, host="0.0.0.0", port=80, backlog=5, timeout=30):
        self.host = host
        self.port = port
        self.backlog = backlog
        self.timeout = timeout
        self._routes = dict()  # stores link between (method, path) and function to execute

    def route(self, method="GET", path="/"):
        """ Decorator which connects method and path to the decorated function. """

        if (method, path) in self._routes:
            raise HTTPServerError("route{} already registered".format((method, path)))

        def wrapper(function):
            self._routes[(method, path)] = function

        return wrapper

    def start(self):
        serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        serversocket.bind((self.host, self.port))
        serversocket.listen(self.backlog)

        print("HTTP server started on {}:{}".format(self.host, self.port))

        while True:
            try:
                conn, addr = serversocket.accept()
                conn.settimeout(self.timeout)

                request_line = conn.readline()
                if request_line is None:
                    raise OSError(errno.ETIMEDOUT)

                print("request line", request_line, "from", addr[0])

                if request_line in [b"", b"\r\n"]:
                    print("malformed request line")
                    conn.close()
                    continue

                header = dict()

                while True:
                    # read header fields and add name / value to dict 'header'
                    line = conn.readline()
                    if request_line is None:
                        raise OSError(errno.ETIMEDOUT)

                    if line in [b"", b"\r\n"]:
                        break
                    else:
                        semicolon = line.find(b":")
                        if semicolon != -1:
                            name = line[0:semicolon].decode("utf-8")
                            value = line[semicolon + 1:-2].lstrip().decode("utf-8")
                            header[name] = value

                try:
                    request = url.request(request_line)
                except url.InvalidRequest as e:
                    conn.write(b"HTTP/1.1 400 Bad Request\r\n")
                    conn.write(b"Connection: close\r\n")
                    conn.write("Content-Type: text/html\r\n")
                    conn.write(b"\r\n")
                    conn.write(bytes(repr(e), "utf-8"))
                    conn.close()
                    continue

                request["header"] = header

                # Search function which is connected to (method, path)
                func = self._routes.get((request["method"], request["path"]))
                if func:
                    if func(conn, request) != CONNECTION_KEEP_ALIVE:
                        # close connection unless explicitly kept alive
                        conn.close()
                else:  # no function found for (method, path) combination
                    conn.write(b"HTTP/1.1 404 Not Found\r\n")
                    conn.write(b"Connection: close\r\n")
                    conn.write(b"\r\n")
                    conn.close()

            except Exception as e:
                conn.close()
                if e.args[0] == errno.ETIMEDOUT:  # communication timeout
                    pass
                elif e.args[0] == errno.ECONNRESET:  # client reset the connection
                    pass
                elif e.args[0] == "Stop Server":  # magic exception to stop server
                    break
                else:
                    serversocket.close()
                    serversocket = None
                    raise e

        serversocket.close()
        serversocket = None
        print("HTTP server stopped")


'''
Created on Sep 19, 2013

@author: I072190
'''

'''
It can be shown that the polynomial n4 + 4n3 + 2n2 + 5n is a multiple of 6 for every integer n. It can also be shown that 6 is the largest integer satisfying this property.

Define M(a, b, c) as the maximum m such that n4 + an3 + bn2 + cn is a multiple of m for all integers n. For example, M(4, 2, 5) = 6.

Also, define S(N) as the sum of M(a, b, c) for all 0 < a, b, c ≤ N.

We can verify that S(10) = 1972 and S(10000) = 2024258331114.

Let Fk be the Fibonacci sequence:
F0 = 0, F1 = 1 and
Fk = Fk-1 + Fk-2 for k ≥ 2.

Find the last 9 digits of Σ S(Fk) for 2 ≤ k ≤ 1234567890123.
'''

import math
import pe_fibo

def gcd(a, b, *c):
    while b:
        a, b = b, a%b
    if len(c)==0:
        return a
    else:
        g = a
        for i in c:
            g = gcd(g, i)
        return g

# print(gcd(10, 15, 20, 25))

def divisors(n):
    l = [1]
    if n==1:
        return l
    for i in range(2, math.floor(math.sqrt(n))+1):
        if n%i == 0:
            l.append(i)
            d = n//i
            if d != i:
                l.append(d)
    l.append(n)
    return sorted(l)

print(divisors(24))

def M(a, b, c):
    Gd = gcd(24, 6*a + 36)
    Gc = gcd(50 + 12*a + 2*b, Gd)
    Gb = gcd(7*a + 3*b + c + 15, Gc)
    Ga = gcd(a+b+c+1, Gb)
    return Gb
#     return gcd(a+b+c+1, 2*b + 2, 6*a + 12, 24)

print(M(4, 2, 5))

def S(N):
    dv = divisors(24)
    stat = {}
    for d in dv:
        stat[d] = 0
    s = 0
    for a in range(1, N+1):
        for b in range(1, N+1):
            for c in range(1, N+1):
                v = M(a, b, c)
                s += v
                stat[v] += 1
#                 print(a, b, c, v)
    print(stat)
    return s

def S1(N):
    non_trvl_count = 0

    for k1 in range(1, (N+2)//4 + 1):
        for k2 in range(1, (N+1)//12 + 1):
            non_trvl_count + 1

print(S(10))
print(S(20))
print(S(30))
print(S(40))
print(S(50))
print(S(60))
print(S(70))
print(S(80))


class Solution:
    def max_amount_to_order(self, onHand, supplier, demand):
        supplier.sort()

        left = 0
        right = len(supplier)

        while left + 1 < right:
            mid = (left + right) // 2
            if self.is_valid(onHand, supplier, demand, mid):
                left = mid
            else:
                right = mid

        if self.is_valid(onHand, supplier, demand, right):
            return right
        return left

    def is_valid(self, on_hand, supplier, demand, mid):
        new_on_hand = on_hand + supplier[-mid:]
        new_on_hand.sort()

        i = 0
        days = 0
        for i in range(0,len(new_on_hand), demand):
            for j in range(0, min(demand, len(new_on_hand) - i)):
                if new_on_hand[i + j] - days < 0:
                    return False
            days += 1
        return True

s = Solution()
onHand = [1,0,1]
supplier = [2,0,2,0,0,2]
demand = 2
print(s.max_amount_to_order(onHand, supplier, demand))


#!/usr/bin/env python
from site import *
from egginfo import *
from ospath import *
from public import *

@public
def isegg(path):
    """Check package is egg

    Args:
        object (str, types.ModuleType): package name or instance

    Returns:
        true - if egg, false - if no egg
    """
    #path = find_module(object)
    if path:
        return path.find(".egg")>0
    #return ext(pkgfilename(object))=="egg"

@public
class Egg(Dir):
    @property
    def egginfo(self):
        path = self.join("EGG-INFO")
        if exists(path):
            return EggInfo(path)

    @property
    def pkginfo(self):
        egginfo = self.egginfo
        if egginfo:
            return egginfo.pkginfo

    @property
    def sources(self):
        egginfo = self.egginfo
        if egginfo:
            return egginfo.sources

    @property
    def requires(self):
        egginfo = self.egginfo
        if egginfo:
            return egginfo.requires

    @property
    def top_level(self):
        egginfo = self.egginfo
        if egginfo:
            return egginfo.top_level

@public
def eggs(path=None):
    if not path:
        path = getsitepackages()
    matches = dirs(path,"*.egg")
    return map(Egg,matches)


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

from questions_birth import *
from tkinter import *
from PIL import ImageTk, Image
import winsound
import time

class Game:

    total_sums = []
    themes = []
    rec_to_press = []
    all_pressed = []
    players = []
    text_sc = []

    def __init__(self, master):

        self.round = 1
        self.cur_player = 0
        self.scores = [0 for i in range(3)]
        self.master = master
        self.fon = ImageTk.PhotoImage(file='fon_dr.jpg')
        #self.cat = 0
        self.greeting()

    def greeting(self):
        self.start_win = Frame(self.master, width=200, height=250)
        self.start_win.pack()
        greet = Label(self.start_win)
        greet.configure(text='Начинаем свою игру!\n Введите имена игроков (названия команд)', font = "Arial 14")
        greet.pack(side=TOP, expand=YES, fill=X, ipadx=10)
        self.names = []
        for i in range(3):
            name = StringVar()
            ent = Entry(self.start_win, width=30, textvariable=name)
            name.set('Игрок %d' % (i+1))
            ent.pack(pady=50)
            self.names.append(name)
        but = Button(self.start_win, text='Начинаем игру!', command=self.start_game)
        but.pack()

    def start_game(self):
        self.start_win.destroy()

        self.canv = Canvas(bg="#636467", width=1300, height=700)
        self.canv.pack()
        self.canv.focus_set()

        self.canv.create_image(0,0, image=self.fon, anchor=NW)
        self.title = self.canv.create_text(650, 130, text=TITLE[self.round], font="Arial 30 bold", fill="White")
        for i in range(3):
            player = self.canv.create_text(350*i + 300, 30, text=self.names[i].get(), font="Verdana 30 bold", fill='White')
            self.players.append(player)
            score = self.canv.create_text(350*i + 300, 80, text=str(self.scores[i]), font="Verdana 25 bold", fill='White')
            self.text_sc.append(score)
        self.canv.itemconfig(self.players[self.cur_player], fill='#DC143C')

        shiftx = 120
        shifty = 80
        for i in range(6):
            sums = []
            press = []
            self.canv.create_rectangle(60, 200 + shifty*i, 500, 250 + shifty*i, fill="#cfc6bd")
            theme = self.canv.create_text(280, 225 + shifty*i, text=THEMES[self.round][i], font="Arial 18", fill="Black")
            for j in range(5):
                rec = self.canv.create_rectangle(650 + shiftx*j, 200 + shifty*i, 730 + shiftx*j, 250 + shifty*i, fill="#cfc6bd", tags=("dis", "press"))
                sum = self.canv.create_text(690 + shiftx*j, 225 + shifty*i, text=SUMS[self.round][i][j], font="Arial 18", fill="Black", tag="dis")
                sums.append(sum)
                press.append(rec)
            self.total_sums.append(sums)
            self.themes.append(theme)
            self.rec_to_press.append(press)

        self.canv.bind("<KeyPress>", self.upgrade_score)
        self.canv.tag_bind("press", "<Button-1>", self.show_quest, "+")
        self.canv.tag_bind("quest", "<Button-1>", self.cont, "+")
        #self.canv.tag_bind("quest", "<KeyPress>", lambda _: self.add_score())
        #self.canv.tag_bind("cat", "<Double-Button-1>", self.cat)

    def next_round(self):
        "Turns game to the next round"
        self.round += 1
        self.canv.itemconfig(self.title, text = TITLE[self.round])
        for item in self.all_pressed:
            self.canv.itemconfig(item, fill="#cfc6bd")
        self.all_pressed = []
        for i in range(6):
            self.canv.itemconfig(self.themes[i], text=THEMES[self.round][i])
            for j in range(5):
                self.canv.itemconfig(self.total_sums[i][j], text=SUMS[self.round][i][j])

    def show_quest(self, event):
        "Shows the question under the chosen sum"
        pressed = self.canv.find_closest(event.x, event.y)[0]
        sum = self.canv.find_above(pressed)[0]
        self.cur_sum = self.canv.itemcget(sum, 'text')
        for i in range(6):
            for j in range(5):
                var = self.rec_to_press[i][j]
                if var == pressed:
                    dum_i = i
                    dum_j = j
                    break
        hidden = self.canv.bbox("dis")
        centerx = hidden[0] + ((hidden[2] - hidden[0])/2)
        centery = hidden[1] + ((hidden[3] - hidden[1])/2)
        self.canv.create_rectangle(hidden, fill = "#cfc6bd", tag="quest")
        if type(QUEST[self.round][dum_i][dum_j]) == type([]):
            self.canv.create_text(centerx, centery, font="Arial 26", width=450,
                                  justify=CENTER, text=QUEST[self.round][dum_i][dum_j][0], tag="quest")
            winsound.PlaySound(QUEST[self.round][dum_i][dum_j][1], winsound.SND_FILENAME)
            """try:
                self.canv.create_text(centerx, centery-100, font="Arial 26", width=450,
                                    justify=CENTER, text=QUEST[self.round][dum_i][dum_j][0], tag="quest")
                img = Image.open(QUEST[self.round][dum_i][dum_j][1])
                photoimg = ImageTk.PhotoImage(img)
                self.canv.create_image(0, 0, image=photoimg, tag="quest")
            except IOError:
                self.canv.create_text(centerx, centery, font="Arial 26", width=450,
                                    justify=CENTER, text=QUEST[self.round][dum_i][dum_j][0], tag="quest")
                winsound.PlaySound(QUEST[self.round][dum_i][dum_j][1], winsound.SND_FILENAME)"""
        else:
            self.canv.create_text(centerx, centery, font="Arial 26", width=450,
                                  justify=CENTER, text=str(QUEST[self.round][dum_i][dum_j]), tag="quest")
        self.canv.itemconfig(pressed, fill="#ffb28e")
        if pressed not in self.all_pressed:
            self.all_pressed.append(pressed)

    def cont(self, event):
        self.ch_player()
        self.canv.delete("quest")
        if len(self.all_pressed) == 30:
            if self.round < 4:
                self.next_round()
            else:
                self.end_of_game()

    def ch_player(self):
        self.canv.itemconfig(self.players[self.cur_player], fill='White')
        self.cur_player = (self.cur_player+1) % 3
        self.canv.itemconfig(self.players[self.cur_player], fill='#DC143C')

    def upgrade_score(self, event):
        if event.char == '=':
            self.scores[self.cur_player] += int(self.cur_sum)
        elif event.char == '-':
            self.scores[self.cur_player] -= int(self.cur_sum)
        self.canv.itemconfig(self.text_sc[self.cur_player], text = self.scores[self.cur_player])

    def cat(self, event):
        self.canv.delete("quest")
        self.canv.create_text(centerx, centery, font="Arial 26", width=300,
                                  justify=CENTER, text=CATS[self.cat], tag="cat_quest")
        self.cat += 1
        time.sleep(4)
        self.canv.delete("cat_quest")

    def end_of_game(self):
        self.canv.delete(ALL)
        self.canv.create_text(650, 350, text="Конец игры", font="Arial 50", fill="#bfdecc")

root =  Tk()

new_game = Game(root)

mainloop()


# -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from django.db.models import Q
from HandCorrect.field.R import R
from HandCorrect.enum import enum_ip_state

from models.IpModel.models import Ip
from HandCorrect.tools import self_process

# 查询所有当前用户的ip
def query_ips(request):
    r = R()
    if not request.session.get("login"):
        return HttpResponse(r.error_result("Permission denied!"))

    user_id = request.session.get("user_id", '')

    ip_res = Ip.objects.filter(userId=user_id)
    ips = []
    for ip in ip_res:
        ips.append({
            "id": ip.id,
            "ip": ip.ip,
            "state": ip.state
        })

    return HttpResponse(r.succ(ips))

def change_ip_state(request):
    r = R()
    user_id = request.session.get("user_id")
    id = request.POST.get("id", None)
    result = "unknow error"
    if not id:
        return r.error()

    ips = Ip.objects.filter(id=id, userId=user_id)
    if len(ips) <= 0:
        return HttpResponse(r.error())

    # 更新
    # 选择未连接
    if ips[0].state == enum_ip_state.IpState.WAITING:
        un_ips = Ip.objects.filter(~Q(id=id), userId=user_id)
        # 删除正在运行的进程
        for un_ip in un_ips:
            # 如果有正在使用的IP
            if un_ip.state == enum_ip_state.IpState.USING:
                # 杀死进程
                # 成功
                if self_process.do_kill_process(user_id, un_ip.ip):
                    Ip.objects.filter(id=un_ip.id).update(state=enum_ip_state.IpState.WAITING)
                else:
                    return HttpResponse(r.succ("更新失败"))

        if self_process.do_create_process(user_id, ips[0].ip):
            ips.update(state=enum_ip_state.IpState.USING)
        else:
            return HttpResponse(r.succ("更新失败"))

    elif ips[0].state == enum_ip_state.IpState.USING:
        if self_process.do_kill_process(user_id, ips[0].ip):
            ips.update(state=enum_ip_state.IpState.WAITING)

    return HttpResponse(r.succ("更新成功"))

#  查询当前用户当前连接ip
def query_linked_ip(request):
    r = R()
    user_id = request.session.get("user_id", '')
    if user_id == '':
        return HttpResponse(r.error_result("Permission denied!"))

    ip_res = Ip.objects.filter(userId=user_id, state=enum_ip_state.IpState.USING)
    ips = []
    for ip in ip_res:
        ips.append({
            "id": ip.id,
            "ip": ip.ip
        })

    return HttpResponse(r.succ(ips))

# 创建IP
def create_ip(request):
    r = R()
    user_id = request.session.get("user_id", '')
    if user_id == '':
        return HttpResponse(r.error_result("Permission denied!"))
    ip = request.POST.get("ip")+":"+request.POST.get("port")
    Ip.objects.create(
        userId=int(user_id),
        ip=ip,
        state=enum_ip_state.IpState.WAITING
    )
    return HttpResponse(r.succ("创建成功"))

# 删除IP
def delete_ip(request):
    r = R()
    user_id = request.session.get("user_id", '')
    if user_id == '':
        return HttpResponse(r.error_result("Permission denied!"))
    id = request.POST.get("id", "")
    if id == "":
        return HttpResponse(r.error_result("未填写参数"))

    ip = Ip.objects.get(id=id)
    if ip.userId == user_id:
        ip.delete()
        return HttpResponse(r.succ("删除成功"))
    else:
        return HttpResponse(r.error("错误，未能匹配"))


# https://github.com/CuteFwan/Koishi

import io
import math
import numpy
import discord

from PIL import Image, ImageFont, ImageDraw, ImageSequence

GREEN = (46, 204, 113)
YELLOW = (255, 228, 0)
RED = (237, 41, 57)
GRAY = (97, 109, 126)
BLUE = (10, 24, 34)
WHITE = (255, 255, 255)
PINK = (255, 196, 235)

statusmap = {"online": GREEN, "idle": YELLOW, "dnd": RED, "offline": GRAY}

def get_barstatus(title, statuses):
    highest = max(statuses.values())
    highest_unit = get_time_unit(highest)
    units = {stat: get_time_unit(value) for stat, value in statuses.items()}
    heights = {stat: (value / highest) * 250 for stat, value in statuses.items()}
    box_size = (400, 300)
    rect_x_start = {
        k: 64 + (84 * v)
        for k, v in {"online": 0, "idle": 1, "dnd": 2, "offline": 3}.items()
    }
    rect_width = 70
    rect_y_end = 275
    labels = {"online": "Online", "idle": "Idle", "dnd": "DND", "offline": "Offline"}
    base = Image.new(mode="RGBA", size=box_size, color=(0, 0, 0, 0))
    with Image.open("./data/assets/bargraph.png") as grid:
        font = ImageFont.truetype("./data/assets/Helvetica.ttf", 15)
        draw = ImageDraw.Draw(base)
        draw.text((0, 0), highest_unit[1], fill=WHITE, font=font)
        draw.text((52, 2), title, fill=WHITE, font=font)
        divs = 11
        for i in range(divs):
            draw.line(
                (
                    (50, 25 + ((box_size[1] - 50) / (divs - 1)) * i),
                    (box_size[0], 25 + ((box_size[1] - 50) / (divs - 1)) * i),
                ),
                fill=(*WHITE, 128),
                width=1,
            )
            draw.text(
                (5, 25 + ((box_size[1] - 50) / (divs - 1)) * i - 6),
                f"{highest_unit[0]-i*highest_unit[0]/(divs-1):.2f}",
                fill=WHITE,
                font=font,
            )
        for k, v in statuses.items():
            draw.rectangle(
                (
                    (rect_x_start[k], rect_y_end - heights[k]),
                    (rect_x_start[k] + rect_width, rect_y_end),
                ),
                fill=statusmap[k],
            )
            draw.text(
                (rect_x_start[k], rect_y_end - heights[k] - 13),
                f"{units[k][0]} {units[k][1]}",
                fill=WHITE,
                font=font,
            )
            draw.text(
                (rect_x_start[k], box_size[1] - 25), labels[k], fill=WHITE, font=font
            )
        del draw
        base.paste(grid, None, grid)
    buffer = io.BytesIO()
    base.save(buffer, "png")
    buffer.seek(0)
    return buffer

def get_time_unit(stat):
    word = ""
    if stat >= 604800:
        stat /= 604800
        word = "Week"
    elif stat >= 86400:
        stat /= 86400
        word = "Day"
    elif stat >= 3600:
        stat /= 3600
        word = "Hour"
    elif stat >= 60:
        stat /= 60
        word = "Minute"
    else:
        word = "Second"
    stat = float(f"{stat:.1f}")
    if stat > 1 or stat == 0.0:
        word += "s"
    return stat, word

def get_progress_bar(ratio, *, fname="progress", length=800, width=80):
    bar_length = ratio * length
    a = 0
    b = -1
    c = width / 2
    w = (width / 2) + 1

    shell = Image.new("RGB", (length, width), color=GRAY)
    imgsize = (int(bar_length), width)  # The size of the image
    image = Image.new("RGB", imgsize, color=GRAY)  # Create the image

    innerColor = BLUE  # Color at the center
    outerColor = [0, 0, 0]  # Color at the edge

    for y in range(imgsize[1]):
        for x in range(imgsize[0]):

            dist = (a * x + b * y + c) / numpy.sqrt(a * a + b * b)
            color_coef = abs(dist) / w

            if abs(dist) < w:
                red = outerColor[0] * color_coef + innerColor[0] * (1 - color_coef)
                green = outerColor[1] * color_coef + innerColor[1] * (1 - color_coef)
                blue = outerColor[2] * color_coef + innerColor[2] * (1 - color_coef)

                image.putpixel((x, y), (int(red), int(green), int(blue)))

    shell.paste(image)
    buffer = io.BytesIO()
    shell.save(buffer, "png")  # 'save' function for PIL
    buffer.seek(0)
    dfile = discord.File(fp=buffer, filename=f"{fname}.png")
    return (dfile, f"{fname}.png")

def resize_to_limit(data, limit):
    """
    Downsize it for huge PIL images.
    Half the resolution until the byte count is within the limit.
    """
    current_size = data.getbuffer().nbytes
    while current_size > limit:
        with Image.open(data) as im:
            data = io.BytesIO()
            if im.format == "PNG":
                im = im.resize([i // 2 for i in im.size], resample=Image.BICUBIC)
                im.save(data, "png")
            elif im.format == "GIF":
                durations = []
                new_frames = []
                for frame in ImageSequence.Iterator(im):
                    durations.append(frame.info["duration"])
                    new_frames.append(
                        frame.resize([i // 2 for i in im.size], resample=Image.BICUBIC)
                    )
                new_frames[0].save(
                    data,
                    save_all=True,
                    append_images=new_frames[1:],
                    format="gif",
                    version=im.info["version"],
                    duration=durations,
                    loop=0,
                    background=im.info["background"],
                    palette=im.getpalette(),
                )
            data.seek(0)
            current_size = data.getbuffer().nbytes
    return data

def extract_first_frame(data):
    with Image.open(data) as im:
        im = im.convert("RGBA")
        b = io.BytesIO()
        im.save(b, "gif")
        b.seek(0)
        return b

def quilt(images):
    xbound = math.ceil(math.sqrt(len(images)))
    ybound = math.ceil(len(images) / xbound)
    size = int(2520 / xbound)

    with Image.new(
        "RGBA", size=(xbound * size, ybound * size), color=(0, 0, 0, 0)
    ) as base:
        x, y = 0, 0
        for avy in images:
            if avy:
                im = Image.open(io.BytesIO(avy)).resize(
                    (size, size), resample=Image.BICUBIC
                )
                base.paste(im, box=(x * size, y * size))
            if x < xbound - 1:
                x += 1
            else:
                x = 0
                y += 1
        buffer = io.BytesIO()
        base.save(buffer, "png")
        buffer.seek(0)
        buffer = resize_to_limit(buffer, 8000000)
        return buffer


#!/bin/python3
import os
import sys

import setuptools

with open('README.rst', 'r') as fh:
    long_description = fh.read()
with open('requirements.txt', 'r') as fh:
    requirements = fh.readlines()

version = '0.9.27'

if sys.argv[-1] == 'publish':
    if os.system('python -m wheel version'):
        print('wheel not installed.\nUse `pip install wheel`.\nExiting.')
        sys.exit()
    if os.system('python -m twine --version'):
        print('twine not installed.\nUse `pip install twine`.\nExiting.')
        sys.exit()
    if os.system('tox -e check'):
        sys.exit()

    os.system('python setup.py sdist bdist_wheel')
    os.system('twine upload dist/*')
    os.system('rm -rf build && rm -rf dist && rm -rf DynamicForms.egg-info')
    print('You probably want to also tag the version now:')
    print('  git tag -a %s -m \'version %s\'' % (version, version))
    print('  git push --tags')
    sys.exit()

setuptools.setup(
    name="DynamicForms",
    version=version,
    author="Jure Erznožnik",
    author_email="jure@velis.si",
    description="DynamicForms performs all the visualisation & data entry of your DRF Serializers & ViewSets and adds "
                "some candy of its own: It is a django library that gives you the power of dynamically-shown form "
                "fields, auto-filled default values, dynamic record loading and similar candy with little effort. "
                "To put it differently: once defined, a particular ViewSet / Serializer can be rendered in multiple "
                "ways allowing you to perform viewing and authoring operations on the data in question.",
    long_description=long_description,
    long_description_content_type="text/x-rst",
    url="https://github.com/velis74/DynamicForms",
    packages=setuptools.find_packages(include=('dynamicforms',)),
    include_package_data=True,
    install_requires=requirements,
    python_requires='>=3.4',
    license='BSD-3-Clause',
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Framework :: Django",
    ],
)


from __future__ import absolute_import, division

import tensorflow as tf
from keras.layers import Dense, Input, Embedding, Lambda, Dropout, Activation, SpatialDropout1D, Reshape, GlobalAveragePooling1D, merge, Flatten, Bidirectional, CuDNNGRU, add, Conv1D, GlobalMaxPooling1D
from keras.layers.merge import concatenate
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras import optimizers
from keras import initializers
from keras.engine import InputSpec, Layer
from keras import backend as K

class AttentionWeightedAverage(Layer):
    """
    Computes a weighted average of the different channels across timesteps.
    Uses 1 parameter pr. channel to compute the attention value for a single timestep.
    """

    def __init__(self, return_attention=False, **kwargs):
        self.init = initializers.get('uniform')
        self.supports_masking = True
        self.return_attention = return_attention
        super(AttentionWeightedAverage, self).__init__(** kwargs)

    def build(self, input_shape):
        self.input_spec = [InputSpec(ndim=3)]
        assert len(input_shape) == 3

        self.W = self.add_weight(shape=(input_shape[2], 1),
                                 name='{}_W'.format(self.name),
                                 initializer=self.init)
        self.trainable_weights = [self.W]
        super(AttentionWeightedAverage, self).build(input_shape)

    def call(self, x, mask=None):
        # computes a probability distribution over the timesteps
        # uses 'max trick' for numerical stability
        # reshape is done to avoid issue with Tensorflow
        # and 1-dimensional weights
        logits = K.dot(x, self.W)
        x_shape = K.shape(x)
        logits = K.reshape(logits, (x_shape[0], x_shape[1]))
        ai = K.exp(logits - K.max(logits, axis=-1, keepdims=True))

        # masked timesteps have zero weight
        if mask is not None:
            mask = K.cast(mask, K.floatx())
            ai = ai * mask
        att_weights = ai / (K.sum(ai, axis=1, keepdims=True) + K.epsilon())
        weighted_input = x * K.expand_dims(att_weights)
        result = K.sum(weighted_input, axis=1)
        if self.return_attention:
            return [result, att_weights]
        return result

    def get_output_shape_for(self, input_shape):
        return self.compute_output_shape(input_shape)

    def compute_output_shape(self, input_shape):
        output_len = input_shape[2]
        if self.return_attention:
            return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]
        return (input_shape[0], output_len)

    def compute_mask(self, input, input_mask=None):
        if isinstance(input_mask, list):
            return [None] * len(input_mask)
        else:
            return None

class Capsule(Layer):
    def __init__(self, num_capsule, dim_capsule, routings=3, kernel_size=(9, 1), share_weights=True,
                 activation='default', **kwargs):
        super(Capsule, self).__init__(**kwargs)
        self.num_capsule = num_capsule
        self.dim_capsule = dim_capsule
        self.routings = routings
        self.kernel_size = kernel_size
        self.share_weights = share_weights
        if activation == 'default':
            self.activation = squash
        else:
            self.activation = Activation(activation)

    def build(self, input_shape):
        super(Capsule, self).build(input_shape)
        input_dim_capsule = input_shape[-1]
        if self.share_weights:
            self.W = self.add_weight(name='capsule_kernel',
                                     shape=(1, input_dim_capsule,
                                            self.num_capsule * self.dim_capsule),
                                     # shape=self.kernel_size,
                                     initializer='glorot_uniform',
                                     trainable=True)
        else:
            input_num_capsule = input_shape[-2]
            self.W = self.add_weight(name='capsule_kernel',
                                     shape=(input_num_capsule,
                                            input_dim_capsule,
                                            self.num_capsule * self.dim_capsule),
                                     initializer='glorot_uniform',
                                     trainable=True)

    def call(self, u_vecs):
        if self.share_weights:
            u_hat_vecs = K.conv1d(u_vecs, self.W)
        else:
            u_hat_vecs = K.local_conv1d(u_vecs, self.W, [1], [1])

        batch_size = K.shape(u_vecs)[0]
        input_num_capsule = K.shape(u_vecs)[1]
        u_hat_vecs = K.reshape(u_hat_vecs, (batch_size, input_num_capsule,
                                            self.num_capsule, self.dim_capsule))
        u_hat_vecs = K.permute_dimensions(u_hat_vecs, (0, 2, 1, 3))
        # final u_hat_vecs.shape = [None, num_capsule, input_num_capsule, dim_capsule]

        b = K.zeros_like(u_hat_vecs[:, :, :, 0])  # shape = [None, num_capsule, input_num_capsule]
        for i in range(self.routings):
            b = K.permute_dimensions(b, (0, 2, 1))  # shape = [None, input_num_capsule, num_capsule]
            c = K.softmax(b)
            c = K.permute_dimensions(c, (0, 2, 1))
            b = K.permute_dimensions(b, (0, 2, 1))
            outputs = self.activation(K.batch_dot(c, u_hat_vecs, [2, 2]))
            if i < self.routings - 1:
                b = K.batch_dot(outputs, u_hat_vecs, [2, 3])

        return outputs

    def compute_output_shape(self, input_shape):
        return (None, self.num_capsule, self.dim_capsule)

class KMaxPooling(Layer):
    """
    K-max pooling layer that extracts the k-highest activations from a sequence (2nd dimension).
    TensorFlow backend.
    """

    def __init__(self, k=1, **kwargs):
        super().__init__(**kwargs)
        self.input_spec = InputSpec(ndim=3)
        self.k = k

    def compute_output_shape(self, input_shape):
        return (input_shape[0], (input_shape[2] * self.k))

    def call(self, inputs):
        # swap last two dimensions since top_k will be applied along the last dimension
        shifted_input = tf.transpose(inputs, [0, 2, 1])

        # extract top_k, returns two tensors [values, indices]
        top_k = tf.nn.top_k(shifted_input, k=self.k, sorted=True, name=None)[0]

        # return flattened output
        return Flatten()(top_k)

def get_av_cnn(nb_words, embedding_dim, embedding_matrix, max_sequence_length, out_size):
    embedding_layer = Embedding(nb_words,
                                embedding_dim,
                                weights=[embedding_matrix],
                                input_length=max_sequence_length,
                                trainable=False)

    filter_nums = 300  # 500->375, 400->373, 300->

    comment_input = Input(shape=(max_sequence_length,), dtype='int32')
    embedded_sequences = embedding_layer(comment_input)
    embedded_sequences = SpatialDropout1D(0.25)(embedded_sequences)

    conv_0 = Conv1D(filter_nums, 1, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)
    conv_1 = Conv1D(filter_nums, 2, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)
    conv_2 = Conv1D(filter_nums, 3, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)
    conv_3 = Conv1D(filter_nums, 4, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)

    attn_0 = AttentionWeightedAverage()(conv_0)
    avg_0 = GlobalAveragePooling1D()(conv_0)
    maxpool_0 = GlobalMaxPooling1D()(conv_0)

    maxpool_1 = GlobalMaxPooling1D()(conv_1)
    attn_1 = AttentionWeightedAverage()(conv_1)
    avg_1 = GlobalAveragePooling1D()(conv_1)

    maxpool_2 = GlobalMaxPooling1D()(conv_2)
    attn_2 = AttentionWeightedAverage()(conv_2)
    avg_2 = GlobalAveragePooling1D()(conv_2)

    maxpool_3 = GlobalMaxPooling1D()(conv_3)
    attn_3 = AttentionWeightedAverage()(conv_3)
    avg_3 = GlobalAveragePooling1D()(conv_3)

    v0_col = merge([maxpool_0, maxpool_1, maxpool_2, maxpool_3], mode='concat', concat_axis=1)
    v1_col = merge([attn_0, attn_1, attn_2, attn_3], mode='concat', concat_axis=1)
    v2_col = merge([avg_1, avg_2, avg_0, avg_3], mode='concat', concat_axis=1)
    merged_tensor = merge([v0_col, v1_col, v2_col], mode='concat', concat_axis=1)
    output = Dropout(0.7)(merged_tensor)
    output = Dense(units=144)(output)
    output = Activation('relu')(output)
    output = Dense(units=out_size, activation='sigmoid')(output)

    model = Model(inputs=comment_input, outputs=output)
    adam_optimizer = optimizers.Adam(lr=1e-3, decay=1e-6)
    model.compile(loss='binary_crossentropy', optimizer=adam_optimizer, metrics=['accuracy'])
    model.summary()
    return model

def get_kmax_text_cnn(nb_words, embedding_dim, embedding_matrix, max_sequence_length, out_size):
    embedding_layer = Embedding(nb_words,
                                embedding_dim,
                                weights=[embedding_matrix],
                                input_length=max_sequence_length,
                                trainable=False)

    filter_nums = 180
    drop = 0.6

    comment_input = Input(shape=(max_sequence_length,), dtype='int32')
    embedded_sequences = embedding_layer(comment_input)
    embedded_sequences = SpatialDropout1D(0.2)(embedded_sequences)

    conv_0 = Conv1D(filter_nums, 1, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)
    conv_1 = Conv1D(filter_nums, 2, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)
    conv_2 = Conv1D(filter_nums, 3, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)
    conv_3 = Conv1D(filter_nums, 4, kernel_initializer="normal", padding="valid", activation="relu")(embedded_sequences)

    # conv_0 = Conv1D(filter_nums / 2, 1, kernel_initializer="normal", padding="valid", activation="relu")(conv_0)
    # conv_1 = Conv1D(filter_nums / 2, 2, kernel_initializer="normal", padding="valid", activation="relu")(conv_1)
    # conv_2 = Conv1D(filter_nums / 2, 3, strides=2, kernel_initializer="normal", padding="valid", activation="relu")(conv_2)

    maxpool_0 = KMaxPooling(k=3)(conv_0)
    maxpool_1 = KMaxPooling(k=3)(conv_1)
    maxpool_2 = KMaxPooling(k=3)(conv_2)
    maxpool_3 = KMaxPooling(k=3)(conv_3)

    merged_tensor = merge([maxpool_0, maxpool_1, maxpool_2, maxpool_3], mode='concat', concat_axis=1)
    output = Dropout(drop)(merged_tensor)
    output = Dense(units=144, activation='relu')(output)
    output = Dense(units=out_size, activation='sigmoid')(output)

    model = Model(inputs=comment_input, outputs=output)
    adam_optimizer = optimizers.Adam(lr=1e-3, decay=1e-7)
    model.compile(loss='binary_crossentropy', optimizer=adam_optimizer, metrics=['accuracy'])
    model.summary()
    return model

def get_rcnn(nb_words, embedding_dim, embedding_matrix, max_sequence_length, out_size):
    recurrent_units = 64
    filter1_nums = 128

    input_layer = Input(shape=(max_sequence_length,))
    embedding_layer = Embedding(nb_words,
                                embedding_dim,
                                weights=[embedding_matrix],
                                input_length=max_sequence_length,
                                trainable=False)(input_layer)

    embedding_layer = SpatialDropout1D(0.2)(embedding_layer)
    rnn_1 = Bidirectional(CuDNNGRU(recurrent_units, return_sequences=True))(embedding_layer)

    #conv_1 = Conv1D(filter1_nums, 1, kernel_initializer="uniform", padding="valid", activation="relu", strides=1)(rnn_1)
    #maxpool = GlobalMaxPooling1D()(conv_1)
    #attn = AttentionWeightedAverage()(conv_1)
    #average = GlobalAveragePooling1D()(conv_1)

    conv_2 = Conv1D(filter1_nums, 2, kernel_initializer="normal", padding="valid", activation="relu", strides=1)(rnn_1)
    maxpool = GlobalMaxPooling1D()(conv_2)
    attn = AttentionWeightedAverage()(conv_2)
    average = GlobalAveragePooling1D()(conv_2)

    concatenated = concatenate([maxpool, attn, average], axis=1)
    x = Dropout(0.5)(concatenated)
    x = Dense(120, activation="relu")(x)
    output_layer = Dense(out_size, activation="sigmoid")(x)

    model = Model(inputs=input_layer, outputs=output_layer)
    adam_optimizer = optimizers.Adam(lr=1e-3, clipvalue=5, decay=1e-5)
    model.compile(loss='binary_crossentropy', optimizer=adam_optimizer, metrics=['accuracy'])
    model.summary()
    return model

def get_siamese_av_rnn(nb_words, embedding_dim, embedding_matrix, max_sequence_length, out_size):
    recurrent_units = 60

    # -- Dual input part --
    print("Prepareing Inputs")
    input_layer_1 = Input(shape=(max_sequence_length,), name='first_sentences')
    input_layer_2 = Input(shape=(max_sequence_length,), name='second_sentences')
    embedding_layer = Embedding(nb_words,
                                embedding_dim,
                                weights=[embedding_matrix],
                                input_length=max_sequence_length,
                                trainable=False)

    # -- Denstify --
    embedded_1 = embedding_layer(input_layer_1)
    embedded_1 = SpatialDropout1D(0.25)(embedded_1)

    embedded_2 = embedding_layer(input_layer_2)
    embedded_2 = SpatialDropout1D(0.25)(embedded_2)

    # -- prepare network --
    rnn_1 = Bidirectional(CuDNNGRU(recurrent_units, return_sequences=True))
    rnn_2 = Bidirectional(CuDNNGRU(recurrent_units, return_sequences=True))
    last = Lambda(lambda t: t[:, -1], name='last')
    max_pool = GlobalMaxPooling1D()
    attn_pool = AttentionWeightedAverage()
    avg_pool = GlobalAveragePooling1D()

    ffn = Dense(72, activation='relu')

    sent_vectors = []
    for embedded in [embedded_1, embedded_2]:
        print("HUCK")
        rnn_1_out = rnn_1(embedded)
        rnn_2_out = rnn_2(rnn_1_out)
        rnn_out = concatenate([rnn_1_out, rnn_2_out], axis=2)

        last_vec = last(rnn_out)
        max_vec = max_pool(rnn_out)
        attn_vec = attn_pool(rnn_out)
        avg_vec = avg_pool(rnn_out)

        all_views = concatenate([last_vec, max_vec, attn_vec, avg_vec], axis=1)
        x = Dropout(0.5)(all_views)
        x = ffn(x)
        sent_vectors.append(x)

    sent_vectors_pairs = concatenate(sent_vectors, axis=1)
    x = Dense(72, activation="relu")(sent_vectors_pairs)
    output_layer = Dense(out_size, activation="sigmoid")(x)

    print("DONE")
    model = Model(inputs=[input_layer_1, input_layer_2], outputs=output_layer)
    adam_optimizer = optimizers.Adam(lr=1e-3, decay=1e-6, clipvalue=5)
    model.compile(loss='binary_crossentropy', optimizer=adam_optimizer, metrics=['accuracy'])
    model.summary()
    return model


import re
from java_variable import VarType
from skrutil.skr_logger import skr_log_warning

_JAVA_BR = '\n\n'
_JAVA_SPACE = '    '

def function_space(count):
    space = ''
    for i in range(1, count + 1):
        space += _JAVA_SPACE
    return space

class JavaManagerFetchCommand:
    def __init__(self, is_plural, where):
        self.is_plural = is_plural
        if where is not None:
            self.where = where
        else:
            self.where = ''

class JavaManager:
    def __init__(self, manager_name):
        self.manager_name = manager_name
        self.object_name = ''
        self.plural_object_name = ''
        self.java_variable_list = []
        self.fetch_commands = []

    def set_object_name(self, class_name, plural_class_name):
        self.object_name = class_name
        self.plural_object_name = plural_class_name

    def set_java_variable_list(self, java_variable_list):
        self.java_variable_list = java_variable_list

    def add_fetch_command(self, fetch_command):
        self.fetch_commands.append(fetch_command)

    def generate_fetch(self):
        fetch_function = ''
        for fetch_command in self.fetch_commands:
            by_list = []
            if fetch_command.where != '':
                by_list = re.split(',', fetch_command.where)

            if not fetch_command.is_plural:
                if len(by_list) == 0:
                    skr_log_warning('Singular often comes with at least one by parameter')
                fetch_function += function_space(1) + 'public {0} fetch{0}FromCache{1} {{\n' \
                    .format(self.__rename_object_name_if_list(), self.__convert_bys_to_string(by_list, False, False))
                fetch_function += function_space(2) + 'long handler = nativeFetch{0}FromCache{1};\n\n' \
                    .format(self.object_name, self.__convert_bys_to_string(by_list, False, True))
                fetch_function += function_space(2) + 'if (handler == JniHelper.sNullPointer) {\n'
                fetch_function += function_space(3) + 'return null;\n'
                fetch_function += function_space(2) + '}\n\n'
                fetch_function += function_space(2) + 'return new {0}(handler);\n'.format(self.__rename_object_name_if_list())
                fetch_function += function_space(1) + '}' + _JAVA_BR
            else:
                fetch_function += function_space(1) + 'public List<{0}> fetch{1}FromCache{2} {{\n' \
                    .format(self.__rename_object_name_if_list(), self.plural_object_name,
                            self.__convert_bys_to_string(by_list, False, False))
                fetch_function += function_space(2) + 'long[] handlers = nativeFetch{0}FromCache{1};\n\n'\
                    .format(self.plural_object_name, self.__convert_bys_to_string(by_list, False, True))
                fetch_function += function_space(2) + 'List<{0}> {1} = new ArrayList<>();\n'\
                    .format(self.__rename_object_name_if_list(), self.__to_object_name_java_style() + 's')
                fetch_function += function_space(2) + 'for (long handler: handlers) {\n'
                fetch_function += function_space(3) + '{0}.add(new {1}(handler));\n'\
                    .format(self.__to_object_name_java_style() + 's', self.__rename_object_name_if_list())
                fetch_function += function_space(2) + '}\n\n'
                fetch_function += function_space(2) + 'return {0};\n'\
                    .format(self.__to_object_name_java_style() + 's')
                fetch_function += function_space(1) + '}' + _JAVA_BR
        return fetch_function

    def generate_fetch_native(self):
        fetch_function = ''
        for fetch_command in self.fetch_commands:
            by_list = []
            if fetch_command.where != '':
                by_list = re.split(',', fetch_command.where)

            if not fetch_command.is_plural:
                if len(by_list) == 0:
                    skr_log_warning('Singular often comes with at least one by parameter')
                fetch_function += function_space(1) + 'private native {0} nativeFetch{1}FromCache{2};'\
                    .format('long', self.object_name, self.__convert_bys_to_string(by_list, True, False)) + _JAVA_BR
            else:
                fetch_function += function_space(1) + 'private native long[] nativeFetch{0}FromCache{1};'\
                    .format(self.plural_object_name, self.__convert_bys_to_string(by_list, True, False)) + _JAVA_BR
        return fetch_function

    # returns "ById(String id)" or "(String id, String username)" or "()"
    def __convert_bys_to_string(self, by_string_list, is_native_declaration, is_native_call):
        if len(by_string_list) == 0:  # ()
            return '()'
        elif len(by_string_list) == 1:  # "ById(String id)"
            by_string = by_string_list[0]
            java_var = self.__java_var_by_name(by_string)
            if java_var is not None:
                if is_native_declaration:
                    if java_var.var_type == VarType.java_enum:
                        return 'By{0}(long handler, {1} {2})'.format(java_var.get_set_name_str, 'int',
                                                                     java_var.name_str)
                    elif java_var.var_type == VarType.java_string_array:
                        return 'By{0}(long handler, {1} {2})'.format(java_var.get_set_name_str, 'String[]',
                                                                     java_var.name_str)
                    return 'By{0}(long handler, {1} {2})'.format(java_var.get_set_name_str,
                                                                 java_var.var_type.to_getter_setter_string(),
                                                                 java_var.name_str)
                elif is_native_call:
                    if java_var.var_type == VarType.java_enum:
                        return 'By{0}(mNativeHandler, {1}.getValue())'.format(java_var.get_set_name_str, java_var.name_str)
                    elif java_var.var_type == VarType.java_string_array:
                        return 'By{0}(mNativeHandler, new String[{1}.size()])'.format(java_var.get_set_name_str, java_var.name_str)
                    return 'By{0}(mNativeHandler, {1})'.format(java_var.get_set_name_str, java_var.name_str)
                else:
                    if java_var.var_type == VarType.java_enum:
                        return 'By{0}({1} {2})'.format(java_var.get_set_name_str, java_var.java_enum, java_var.name_str)
                    return 'By{0}({1} {2})'.format(java_var.get_set_name_str,
                                                   java_var.var_type.to_getter_setter_string(), java_var.name_str)
            else:
                print('Unknown "{0}" in "by"'.format(by_string))
                return ''
        else:  # "(String id, String username)"
            bys_string = '('
            index = 0
            for by_string in by_string_list:
                java_var = self.__java_var_by_name(by_string)
                if java_var is not None:
                    if is_native_declaration:
                        if index == 0:
                            bys_string += 'long handler, '
                        if java_var.var_type == VarType.java_enum:
                            bys_string += '{0} {1}, '.format('int', java_var.name_str)
                        elif java_var.var_type == VarType.java_string_array:
                            bys_string += '{0} {1}, '.format('String[]', java_var.name_str)
                        else:
                            bys_string += '{0} {1}, '.format(java_var.var_type.to_getter_setter_string(),
                                                             java_var.name_str)
                    elif is_native_call:
                        if index == 0:
                            bys_string += 'mNativeHandler, '
                        if java_var.var_type == VarType.java_enum:
                            bys_string += '{0}.getValue(), '.format(java_var.name_str)
                        elif java_var.var_type == VarType.java_string_array:
                            bys_string += 'new String[{0}.size()], '.format(java_var.name_str)
                        else:
                            bys_string += '{0}, '.format(java_var.name_str)
                    else:
                        if java_var.var_type == VarType.java_enum:
                            bys_string += '{0} {1}, '.format(java_var.java_enum, java_var.name_str)
                        else:
                            bys_string += '{0} {1}, '.format(java_var.var_type.to_getter_setter_string(),
                                                             java_var.name_str)
                else:
                    print('Unknown "{0}" in "by"'.format(by_string))
                    return ''
                index += 1
            bys_string = bys_string[:-2]  # remove last 2 chars
            bys_string += ')'
            return bys_string

    # returns None if not found
    def __java_var_by_name(self, name_string):
        for java_var in self.java_variable_list:
            if java_var.name_str == self.__by_string_to_java_field_style(name_string):
                return java_var
        return None

    def __by_string_to_java_field_style(self, by_string):
        name_splits = re.split('_', by_string)
        var_name_str = ''
        for index in (1, len(name_splits)):
            if index == 1:
                var_name_str = name_splits[index - 1]
            else:
                var_name_str += name_splits[index - 1].capitalize()
        return var_name_str

    def __rename_object_name_if_list(self):
        new_object_name = ''
        if self.object_name == 'List':
            new_object_name = 'com.lesschat.core.task.List'
        else:
            new_object_name = self.object_name
        return new_object_name

    def __to_object_name_java_style(self):
        new_object_name = ''
        new_object_name = self.object_name[0].lower() + self.object_name[1:]
        return new_object_name


#!/usr/bin/python
#Change ID.

from dxl_util import *

DXL_ID= 1  #Current ID
NEW_ID= 2  #New ID
BAUDRATE= 57600
#DXL_TYPE= 'XM430-W350'  #Finger robot
DXL_TYPE= 'XH430-V350'  #Dynamixel gripper

#Setup the device
dxl= TDynamixel1(DXL_TYPE,dev=DEV)
dxl.Id= DXL_ID
dxl.Baudrate= BAUDRATE
dxl.Setup()

#Change ID
dxl.Write('ID',NEW_ID)

dxl.Quit()


from calm.dsl.builtins import Package, CalmTask, action, ref

from services import DemoApp, Haproxy, Postgres

class DemoAppPackage(Package):
    """DemoApp package"""
    services = [ref(DemoApp)]

    @action
    def __install__(self):
        CalmTask.Exec.ssh(name='update centos', filename='scripts/centos_update.sh')
        CalmTask.Exec.ssh(name='install docker', filename='scripts/centos_install_docker.sh')
        CalmTask.Exec.ssh(name='run demoApp', filename='scripts/run_demo-app_container.sh')

class HaproxyPackage(Package):
    """HAProxy package"""
    services = [ref(Haproxy)]

    @action
    def __install__(self):
        CalmTask.Exec.ssh(name='update centos', filename='scripts/centos_update.sh')
        CalmTask.Exec.ssh(name='install haproxy', filename='scripts/centos_install_haproxy.sh')

class PostgresPackage(Package):
    """Postgres Package on ERA"""
    services = [ref(Postgres)]


# File Operations : Opening file, Writing into the file

from sys import argv

script, filename = argv

print(f"We're going to erase {filename}")
print("If you don't want that , hit CTRL-C(^C).")
print("If you do want that, hit RETURN.")

input("?")

print("Opeing the file...")
# Opening a file with write permission
target = open(filename, 'w+')

print("Truncating the file. GOODBYE!")
# Deleting the file target
target.truncate()

print("Now I'm going to ask you for three lines.")

# Asking user input to write into the file
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print("I'm going to write these to the file.")

# Writing into the file
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("And finally, we close it.")
# Closing the file
target.close()


import subprocess
import shlex

from ...plugins import PapersPlugin
from ...pubs_cmd import execute

class Alias(object):

    def __init__(self, name, definition):
        self.name = name
        self.definition = definition

    def parser(self, parser):
        self.parser = parser
        p = parser.add_parser(self.name, help='user defined command')
        p.add_argument('arguments', nargs='*',
            help="arguments to be passed to the user defined command")
        return p

    def command(self, conf, args):
        raise NotImplementedError

    @classmethod
    def create_alias(cls, name, definition):
        if len(definition) > 0 and definition[0] == '!':
            return ShellAlias(name, definition[1:])
        else:
            return CommandAlias(name, definition)

class CommandAlias(Alias):
    """Default kind of alias.
    - definition is used as a papers command
    - other arguments are passed to the command
    """

    def command(self, conf, args):
        raw_args = ([args.prog]
                    + shlex.split(self.definition
                    + ' '
                    + ' '.join(args.arguments)))
        execute(raw_args)

class ShellAlias(Alias):

    def command(self, conf, args):
        """Uses a shell function so that arguments can be used in the command
        as shell arguments.
        """
        subprocess.call(
                'papers_alias_fun () {{\n{}\n}}\npapers_alias_fun {}'.format(
                    self.definition, ' '.join(args.arguments)),
                shell=True)

class AliasPlugin(PapersPlugin):

    name = 'alias'

    def __init__(self, conf):
        self.aliases = []
        if 'alias' in conf['plugins']:
            for name, definition in conf['plugins']['alias'].items():
                self.aliases.append(Alias.create_alias(name, definition))

    def update_parser(self, subparsers):
        """Add subcommand to the provided subparser"""
        for alias in self.aliases:
            alias_parser = alias.parser(subparsers)
            alias_parser.set_defaults(func=alias.command)


#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import improc
import time
import fft

N = [100,1000,10000]
N1 = np.random.rand(100)
N2 = np.random.rand(1000)
N3 = np.random.rand(10000)

t0 = time.time()
N1_sel = improc.selectionsort(N1,100)
t1 = time.time()
N1_mer = improc.mergesort(N1,100)
t2 = time.time()
N2_sel = improc.selectionsort(N2,1000)
t3 = time.time()
N2_mer = improc.mergesort(N2,1000)
t4 = time.time()
N3_sel = improc.selectionsort(N3,10000)
t5 = time.time()
N3_mer = improc.mergesort(N3,10000)
t6 = time.time()

t_sel = [t1-t0,t3-t2,t5-t4]
t_mer = [t2-t1,t4-t3,t6-t5]
plt.figure()
plt.plot(N,t_sel,N,t_mer)
plt.legend(["selection sort","merge sort"])
plt.show()

tr100 = t_sel[0]/t_mer[0]
tr1000 = t_sel[1]/t_mer[1]
tr10000 = t_sel[2]/t_mer[2]
print(tr100,tr1000,tr10000)

#The data does appear to match the performance expectations for the two difference
#sorting methods.  Also, looking at the ratios we can see that the selection sort
#is actually faster for the size 100 array however it gets progressibely worse as
#the size of the array increases.

def Fibonacci(n):
  if n == 0:
    return 0
  elif n == 1:
    return 1
  else:
    return Fibonacci(n-1) + Fibonacci(n-2)

print(Fibonacci(24))

b = [4, 13, 28, 39, 50]
b = np.array(b)
N = 64
PI = 2*np.arcsin(1)
dx = 2*PI / (N-1)

x = np.zeros(N)
f = np.zeros(N)
y_1 = np.zeros(N)
y_2 = np.zeros(N)
y_3 = np.zeros(N)
y_4 = np.zeros(N)
y_5 = np.zeros(N)

for i in range(N):
  x[i] = i*dx
  f[i] = i
  y_1[i] = np.sin(x[i]) + np.sin(b[0]*x[i])
  y_2[i] = np.sin(x[i]) + np.sin(b[1]*x[i])
  y_3[i] = np.sin(x[i]) + np.sin(b[2]*x[i])
  y_4[i] = np.sin(x[i]) + np.sin(b[3]*x[i])
  y_5[i] = np.sin(x[i]) + np.sin(b[4]*x[i])

y_1 = fft.fft_slow(y_1,1.)
fft.plot_c(f[:0.5*N],y_1[:N])
y_2 = fft.fft_slow(y_2,1.)
fft.plot_c(f[:0.5*N],y_2[:N])
y_3 = fft.fft_slow(y_3,1.)
fft.plot_c(f[:0.5*N],y_3[:N])
y_4 = fft.fft_slow(y_4,1.)
fft.plot_c(f[:0.5*N],y_4[:N])
y_5 = fft.fft_slow(y_5,1.)
fft.plot_c(f[:0.5*N],y_5[:N])

#At the different spectra, the peaks moved to the higher frequencies until
#they reached b=39.


#!/usr/bin/env python
import pandas as pd
import numpy as np
import math
from scipy import stats
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error,r2_score,explained_variance_score
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import f1_score
from sklearn.metrics import classification_report,confusion_matrix
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score

class RegressionModels():
    def train_split(self,X,y,test_size=0.2,random_state=0):
        X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)
        #scalar = StandardScaler().fit(X_train)
        #X_train = scalar.transform(X_train)
        #X_test = scalar.transform(X_test)
        #print("Normalization done")
        print("Test train split done")
        return X_train,X_test,y_train,y_test

    def removeoutliers(self,data,inplace=False):
        prev_rows = len(data)
        data_copy = data.copy()
        z_score = np.abs(stats.zscore(data_copy))
        data_copy = data_copy[(z_score < 3).all(axis=1)]
        if inplace:
            data=data_copy
        print("Before removing outliers , rows - ", prev_rows)
        print("After removing outliers , rows -", len(data_copy))
        print("Number of records deleted - ", (prev_rows - len(data_copy)))
        return data_copy

    def scores(self,y_test,y_pred, model):
        print("Variance Score : " , explained_variance_score(y_test, y_pred))
        print("R2 Score : " ,r2_score(y_test,y_pred))
        print("Root Mean Square : ",math.sqrt(mean_squared_error(y_test, y_pred)))
        print("Best Parameters : ", model.best_params_ )

    def svmRegression(self, X_train, X_test, y_train, Y_test, params):
        print("-----------SVM Regression Starts------------\n\n ")
        clf = SVR()
        svm_grid = GridSearchCV(clf, params, verbose=False, cv=3,return_train_score=True)
        svm_grid.fit(X_train,y_train)
        svm_predict = svm_grid.predict(X_test)
        res = [svm_grid.score(X_train,y_train),svm_grid.score(X_test,Y_test),
              r2_score(Y_test,svm_predict),math.sqrt(mean_squared_error(Y_test, svm_predict))]
        print("Best Parameters : ", svm_grid.best_params_ )
        result = pd.DataFrame(np.array(res).reshape(-1,4))
        return result
        self.scores(Y_test, svm_predict, svm_grid)
        print("\n-----------SVM Regression ends------------\n\n ")

    def decisionTreeRegression(self, X_train, X_test, y_train, Y_test, params):
        print("-----------Decision Tree Regression Starts------------\n\n")
        DTregressor = DecisionTreeRegressor(random_state=0)
        DT_grid = GridSearchCV(DTregressor, params, verbose=False, cv=3,return_train_score=True)
        DT_grid.fit(X_train,y_train)
        DT_predict = DT_grid.predict(X_test)
        res = [DT_grid.score(X_train,y_train),DT_grid.score(X_test,Y_test),
              r2_score(Y_test,DT_predict),math.sqrt(mean_squared_error(Y_test, DT_predict))]
        result = pd.DataFrame(np.array(res).reshape(-1,4))
        return result
        self.scores(Y_test, DT_predict, DT_grid)
        print("\n-----------Decision Tree Regression Ends------------\n\n")

    def randomForestRegression(self, X_train, X_test, y_train, Y_test, params):
        print("-----------Random Forest Regression Starts------------\n\n")
        RFRegressor = RandomForestRegressor(random_state=0)
        RF_grid = GridSearchCV(RFRegressor, params, verbose=False, cv=3, return_train_score=True)
        RF_grid.fit(X_train,y_train)
        RF_predict = RF_grid.predict(X_test)
        res = [RF_grid.score(X_train,y_train),RF_grid.score(X_test,Y_test),
              r2_score(Y_test,RF_predict),math.sqrt(mean_squared_error(Y_test, RF_predict))]
        result = pd.DataFrame(np.array(res).reshape(-1,4))
        return result
        self.scores(Y_test, RF_predict, RF_grid)
        print("\n-----------Random Forest Regression Ends------------\n\n")

    def adaBoostRegression(self, X_train, X_test, y_train, Y_test, params):
        print("-----------AdaBoost Regression Starts------------\n\n")
        AdaRegressor = AdaBoostRegressor(random_state=0)
        adaBoost_grid = GridSearchCV(AdaRegressor, params, verbose=False, cv=3,return_train_score=True)
        adaBoost_grid.fit(X_train,y_train)
        adaBoost_predict = adaBoost_grid.predict(X_test)
        res = [adaBoost_grid.score(X_train,y_train),adaBoost_grid.score(X_test,Y_test),
              r2_score(Y_test,adaBoost_predict),math.sqrt(mean_squared_error(Y_test, adaBoost_predict))]
        result = pd.DataFrame(np.array(res).reshape(-1,4))
        return result
        self.scores(Y_test, adaBoost_predict, adaBoost_grid)
        print("\n-----------AdaBoost Regression Ends------------\n\n")

    def gaussianProcessRegression(self, X_train, X_test, y_train, Y_test, params):
        print("-----------GaussianProcess Regression Starts------------\n\n")
        GPRRegressor = GaussianProcessRegressor(random_state=0)
        GPR_grid = GridSearchCV(GPRRegressor, params, verbose=False, cv=3,return_train_score=True)
        GPR_grid.fit(X_train,y_train)
        GPR_predict = GPR_grid.predict(X_test)
        res = [GPR_grid.score(X_train,y_train),GPR_grid.score(X_test,Y_test),
              r2_score(Y_test,GPR_predict),math.sqrt(mean_squared_error(Y_test, GPR_predict))]
        result = pd.DataFrame(np.array(res).reshape(-1,4))
        return result
        self.scores(Y_test, GPR_predict, GPR_grid)
        print("\n-----------GaussianProcess Regression Ends------------\n\n")

    def LinearRegression(self, X_train, X_test, y_train, Y_test, params):
        print("-----------Linear Regression Starts------------\n\n")
        LinearRegressor = LinearRegression()
        linearRegression_grid = GridSearchCV(LinearRegressor, params, verbose=False, cv=3,return_train_score=True)
        linearRegression_grid.fit(X_train,y_train)
        linearRegression_predict = linearRegression_grid.predict(X_test)
        res = [linearRegression_grid.score(X_train,y_train),linearRegression_grid.score(X_test,Y_test),
              r2_score(Y_test,linearRegression_predict),math.sqrt(mean_squared_error(Y_test, linearRegression_predict))]
        result = pd.DataFrame(np.array(res).reshape(-1,4))
        return result
        self.scores(Y_test, linearRegression_predict, linearRegression_grid)
        print("\n-----------Linear Regression Ends------------\n\n")

    def mlpRegression(self, X_train, X_test, y_train, Y_test, params):
        print("-----------Neural Network Regression Starts------------\n\n")
        MLPRegressor_obj = MLPRegressor(random_state=0)
        MLPRegressor_grid = GridSearchCV(MLPRegressor_obj, params, verbose=False, cv=3,return_train_score=True)
        MLPRegressor_grid.fit(X_train,y_train)
        MLPRegressor_predict = MLPRegressor_grid.predict(X_test)
        res = [MLPRegressor_grid.score(X_train,y_train),MLPRegressor_grid.score(X_test,Y_test),
              r2_score(Y_test,MLPRegressor_predict),math.sqrt(mean_squared_error(Y_test, MLPRegressor_predict))]
        result = pd.DataFrame(np.array(res).reshape(-1,4))
        return result
        self.scores(Y_test, MLPRegressor_predict, MLPRegressor_grid)
        print("\n-----------Neural Network Regression Ends------------\n\n")

    def train_all__models(self, X, y,data):
        svm_regression_params =  { 'C' : np.logspace(0, 3, 4), 'gamma' : np.logspace(-2, 1, 4)}
        dt_params = {'max_depth' : np.arange(1, 10, 10),'min_samples_split': np.arange(0.1, 1.0, 10)}
        rd_params = {'n_estimators' : np.arange(10,100,10),'max_depth' : np.arange(1,6,2)}
        ada_params = {'n_estimators' : np.arange(10,100,10)}
        gpr_params = {'n_restarts_optimizer' : np.arange(1,10,1)}
        linear_params = {'n_jobs' : np.arange(1,5,1)}
        mlp_params = {'hidden_layer_sizes': np.arange(30,150,20),'learning_rate': ['constant','invscaling','adaptive'],'max_iter':           np.arange(20,200,50)}
        X_train,X_test,y_train,y_test = self.train_split(X,y)

        results = self.svmRegression(X_train,X_test,y_train,y_test, svm_regression_params)

        results = pd.concat([results,self.decisionTreeRegression(X_train,X_test,y_train,y_test, dt_params)])
        results = pd.concat([results,self.randomForestRegression(X_train,X_test,y_train,y_test, rd_params)])
        results = pd.concat([results,self.adaBoostRegression(X_train,X_test,y_train,y_test, ada_params)])
        results = pd.concat([results,self.gaussianProcessRegression(X_train,X_test,y_train,y_test, gpr_params)])
        results = pd.concat([results,self.LinearRegression(X_train,X_test,y_train,y_test, linear_params)])
        results = pd.concat([results,self.mlpRegression(X_train,X_test,y_train,y_test, mlp_params)])
        A=[data,data,data,data,data,data,data]
        B =['SVM Regression','Decision tree','Random forest','ADA boost','Gaussian process','Linear regression','MLP']
        C=['Train Accuracy','Test Accuracy','r2 score','Root mean square']
        results.index = [A,B]
        results.columns=C
        return results

    def wine_quality(self):
        df = pd.read_csv('winequality-red.csv',delimiter=';')
        df.dropna(axis=0,inplace=True)
        #print(df.corr()['quality'].drop('quality'))
        X = df[df.columns[0:11]]
        y = df[df.columns[11:12]]
        wine_quality_results = self.train_all__models(X, y.values.ravel(),'Wine_quality')
        print(wine_quality_results)
        return wine_quality_results

    def communities(self):
        columns_data = ['state','county','community','communityname','fold','population','householdsize','racepctblack','racePctWhite','racePctAsian','racePctHisp','agePct12t21',
                    'agePct12t29','agePct16t24','agePct65up','numbUrban','pctUrban','medIncome','pctWWage','pctWFarmSelf','pctWInvInc','pctWSocSec','pctWPubAsst','pctWRetire','medFamInc',
                    'perCapInc','whitePerCap','blackPerCap','indianPerCap','AsianPerCap','OtherPerCap','HispPerCap','NumUnderPov','PctPopUnderPov','PctLess9thGrade',
                    'PctNotHSGrad','PctBSorMore','PctUnemployed','PctEmploy','PctEmplManu','PctEmplProfServ','PctOccupManu','PctOccupMgmtProf','MalePctDivorce','MalePctNevMarr',
                    'FemalePctDiv','TotalPctDiv','PersPerFam','PctFam2Par','PctKids2Par','PctYoungKids2Par','PctTeen2Par','PctWorkMomYoungKids','PctWorkMom','NumIlleg','PctIlleg',
                    'NumImmig','PctImmigRecent','PctImmigRec5','PctImmigRec8','PctImmigRec10','PctRecentImmig','PctRecImmig5','PctRecImmig8','PctRecImmig10','PctSpeakEnglOnly','PctNotSpeakEnglWell'
                    ,'PctLargHouseFam','PctLargHouseOccup','PersPerOccupHous','PersPerOwnOccHous','PersPerRentOccHous','PctPersOwnOccup','PctPersDenseHous','PctHousLess3BR',
                    'MedNumBR','HousVacant','PctHousOccup','PctHousOwnOcc','PctVacantBoarded','PctVacMore6Mos','MedYrHousBuilt','PctHousNoPhone','PctWOFullPlumb','OwnOccLowQuart','OwnOccMedVal',
                    'OwnOccHiQuart','RentLowQ','RentMedian','RentHighQ','MedRent','MedRentPctHousInc','MedOwnCostPctInc','MedOwnCostPctIncNoMtg','NumInShelters','NumStreet','PctForeignBorn',
                    'PctBornSameState','PctSameHouse85','PctSameCity85','PctSameState85','LemasSwornFT','LemasSwFTPerPop','LemasSwFTFieldOps','LemasSwFTFieldPerPop','LemasTotalReq','LemasTotReqPerPop',
                    'PolicReqPerOffic','PolicPerPop','RacialMatchCommPol','PctPolicWhite','PctPolicBlack','PctPolicHisp','PctPolicAsian','PctPolicMinor','OfficAssgnDrugUnits','NumKindsDrugsSeiz',
                    'PolicAveOTWorked','LandArea','PopDens','PctUsePubTrans','PolicCars','PolicOperBudg','LemasPctPolicOnPatr','LemasGangUnitDeploy','LemasPctOfficDrugUn','PolicBudgPerPop',
                    'ViolentCrimesPerPop'
                    ]
        df = pd.read_csv('communities.data',delimiter=',',names=columns_data)

        df = df.replace('?',np.nan)

        df = df.drop(['fold','community','state','communityname','county'],axis=1)

        median_value = df.iloc[:,25].median(skipna = True)
        df.iloc[130,25] = median_value
        df = df.dropna(axis=1)
        X = df[df.columns[0:100]]
        y = df[df.columns[100:101]]

        results = self.train_all__models(X, y.values.ravel(),'communities')
        print(results)
        return results

    def speech_data(self):
        col = ['Subject_id','local_jitter','absolute_jitter','rap_jitter','ppq5_jitter','ddp_jitter','local_shimmer',
                       'db_shimmer','apq3_shimmer','apq5_shimmer','apq11_shimmer','dda_shimmer','AC','NTH','HTN','Median_pitch',
                       'Mean_pitch','Standard_deviation','Minimum_pitch','Maximum_pitch','Number_of_pulses','Number_of_periods',
                       'Mean_period','Standard_deviation_of_period','Fraction_of_locally_unvoiced_frames','Number_of_voice_breaks',
                       'Degree_of_voice_breaks','UPDRS','class_info']
        data = pd.read_csv("train_data.txt")
        data.columns=col

        data.columns = data.columns.str.lstrip()
        a = StandardScaler()
        X = data.drop(['class_info'],axis=1)
        X = a.fit_transform(X)
        y = data['class_info']
        results = self.train_all__models(X, y.values.ravel(),'speech data')
        print(results)
        return results

    def concrete_data(self):
        col = ['Cement','Blast Furnace Slag','Fly Ash','Water','Superplasticizer','Coarse Aggregate','Fine Aggregate',
                       'Age','Concrete compressive strength']

        data  = pd.read_excel("Concrete_Data.xls",skiprows=1)
        data.columns=col

        data.columns = data.columns.str.lstrip()
        a = StandardScaler()
        X = data.drop(['Concrete compressive strength'],axis=1)
        X = a.fit_transform(X)
        y = data['Concrete compressive strength']
        results = self.train_all__models(X, y.values.ravel(),'concrete_data')
        print(results)
        return results

    def student_data_train_G3(self):
        df1 = pd.read_csv("student-mat.csv",delimiter=";")
        df2 = pd.read_csv("student-por.csv",delimiter=";")

        data = pd.concat([df1,df2])

        categorical_columns = ['school','sex','famsize','address','famsize','Pstatus','Mjob','Fjob','reason','guardian','schoolsup',
                               'famsup','paid','activities','nursery','higher','internet','romantic']
        for i in categorical_columns:
            data[i] = pd.Categorical(data[i]).codes

        data.columns = data.columns.str.lstrip()
        a = StandardScaler()

        X = a.fit_transform(data)
        y = data['G3']
        results = self.train_all__models(X, y.values.ravel(),'student_data')
        print(results)
        return results

    def facebook(self):
        data = pd.read_csv('dataset_Facebook.csv',sep=';',error_bad_lines=False)
        data = data.dropna()
        data['Type'] = pd.Categorical(data['Type']).codes
        X = data[['Type','Category','Post Month','Post Weekday','Post Hour','Paid']]
        y = data['Lifetime People who have liked your Page and engaged with your post']
        results = self.train_all__models(X, y,'facebook')
        print(results)
        return results

    def qsar_aquatic_toxicity(self):
        col = ['TPSA(Tot)','SAacc','H-050','MLOGP','RDCHI','GATS1p','nN','C-040','quantitative response']
        data = pd.read_csv('qsar_aquatic_toxicity.csv',sep=';',error_bad_lines=False)
        data.columns = col
        data = data.dropna()
        X = data[['TPSA(Tot)','SAacc','H-050','MLOGP','RDCHI','GATS1p','nN','C-040']]
        y = data['quantitative response']
        results = self.train_all__models(X, y,'qsar_aquatic_toxicity')
        print(results)
        return results

    def bikesharing(self):
        data = pd.read_csv('hour.csv',error_bad_lines=False)
        data = data.dropna()
        X = data.drop(['instant','dteday','casual','registered','cnt'],axis=1,inplace=False)
        y = data['cnt']
        results = self.train_all__models(X, y,'bike_sharing')
        print(results)
        return results

    def merck_molecular_challenge(self):
        MERCK_FILE= '../Datasets/MerckActivity/TrainingSet/ACT2_competition_training.csv'
        with open(MERCK_FILE) as f:
            cols = f.readline().rstrip('\n').split(',') # Read the header line and get list of column names
            # Load the actual data, ignoring first column and using second column as targets.
            X = np.loadtxt(MERCK_FILE, delimiter=',', usecols=range(2, len(cols)), skiprows=1, dtype=np.uint8)
            y = np.loadtxt(MERCK_FILE, delimiter=',', usecols=[1], skiprows=1)

        MERCK_FILE2= '../Datasets/MerckActivity/TrainingSet/ACT4_competition_training.csv'
        with open(MERCK_FILE2) as f:
            cols = f.readline().rstrip('\n').split(',') # Read the header line and get list of column names
            # Load the actual data, ignoring first column and using second column as targets.
            X_ACT4 = np.loadtxt(MERCK_FILE2, delimiter=',', usecols=range(2, len(cols)), skiprows=1, dtype=np.uint8)
            y_ACT4 = np.loadtxt(MERCK_FILE2, delimiter=',', usecols=[1], skiprows=1)

        #saving into files ACT2
        from tempfile import TemporaryFile
        outfileACT2 = TemporaryFile()
        np.savez(outfileACT2, x_ACT2 = X, y_ACT2 = y)
        _ = outfileACT2.seek(0)

        #saving into files ACT4
        outfileACT4 = TemporaryFile()
        np.savez(outfileACT4, x_ACT4 = X_ACT4, y_ACT4 = y_ACT4)
        _ = outfileACT4.seek(0)

        # loading file ACT2
        npzfile_ACT2 = np.load(outfileACT2, allow_pickle=True)
        #print(npzfile_ACT2.files)

        # loading file ACT2
        npzfile_ACT4 = np.load(outfileACT4, allow_pickle=True)
        #print(npzfile_ACT4.files)

        # Dataframe
        X_ACT2 = pd.DataFrame(npzfile_ACT2['x_ACT2'])
        y_ACT2 = pd.DataFrame(npzfile_ACT2['y_ACT2'])

        X_ACT4 = pd.DataFrame(npzfile_ACT4['x_ACT4'])
        y_ACT4 = pd.DataFrame(npzfile_ACT4['y_ACT4'])

        results2 = self.train_all__models(X_ACT4, y_ACT4,'merk_molecular_challenge')

        return results2

    def SGEMM_GPU_kernel_performance(self):
        long_list = pd.read_csv("sgemm_product.csv",delimiter=',',nrows=0)
        long_list = ['MWG',	'NWG',	'KWG',	'MDIMC',	'NDIMC',	'MDIMA',	'NDIMB',	'KWI',	'VWM',	'VWN',	'STRM',	'STRN',	'SA',	'SB',	'Run1 (ms)',	'Run2 (ms)',	'Run3 (ms)',	'Run4 (ms)']
        data = pd.read_csv("sgemm_product.csv",delimiter = ',',skiprows=1,names=long_list)

        X = pd.DataFrame(data,columns=['MWG','NWG','KWG','MDIMC','NDIMC','MDIMA','NDIMB','KWI','VWM','VWN','STRM','STRN','SA','SB'])
        y = pd.DataFrame(data,columns=['Run1 (ms)'])
        results = self.train_all__models(X, y,'GPU_KERNEL_PERFORMANCE')
        print(results)
        return results

    def getbest(self,data,name):
        temp = data.xs(name)
        temp = temp[temp['r2 score'] == temp['r2 score'].max()]
        temp.index=[name+' - '+temp.index[0]]
        return temp

regressionModels = RegressionModels()
temp = regressionModels.wine_quality()
best_report = regressionModels.getbest(temp,'Wine_quality')
Final_report = temp
temp = regressionModels.communities()
best_report = pd.concat([best_report,regressionModels.getbest(temp,'communities')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.speech_data()
#best_report = pd.concat([best_report,regressionModels.getbest(temp,'speech data')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.concrete_data()
best_report = pd.concat([best_report,regressionModels.getbest(temp,'concrete_data')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.student_data_train_G3()
best_report = pd.concat([best_report,regressionModels.getbest(temp,'student_data')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.facebook()
best_report = pd.concat([best_report,regressionModels.getbest(temp,'facebook')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.qsar_aquatic_toxicity()
best_report = pd.concat([best_report,regressionModels.getbest(temp,'qsar_aquatic_toxicity')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.bikesharing()
#best_report = pd.concat([best_report,regressionModels.getbest(temp,'bike_sharing')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.merck_molecular_challenge()
best_report = pd.concat([best_report,regressionModels.getbest(temp,'merk_molecular_challenge')])
Final_report = pd.concat([Final_report,temp])
temp = regressionModels.SGEMM_GPU_kernel_performance()
best_report = pd.concat([best_report,regressionModels.getbest(temp,'GPU_KERNEL_PERFORMANCE')])
Final_report = pd.concat([Final_report,temp])

print("best_report")
print(best_report)
print("Final report")
print(Final_report)