import re
import logging

import aiohttp

from ...abc.service import Service
from ...config import Config

from .tenant import Tenant

#

L = logging.getLogger(__name__)

#

# "tenant_url" is used to periodically refresh tenants from, expecting "_id" inside a JSON structure,
# which is compatible with SeaCat Auth product
Config.add_defaults({
	'tenants': {
		'ids': '',  # List of tenant ids, entries can be separated by comma or newline
		'tenant_url': '',  # f. e. http://seacat-auth:8080/tenant
		'trusted': 0,  # makes sure the tenants are implicitly trusted, even though they are not located in IDs or tenant URL
	}
})

class TenantService(Service):

	def __init__(self, app, service_name="asab.TenantService"):
		super().__init__(app, service_name)
		self.App = app
		self.TenantWebHandler = None
		self.TenantsTrusted = int(Config['tenants']['trusted'])
		self.Tenants = {}

		# Load tenants from configuration
		for tenant_id in re.split(r"[,\s]+", Config['tenants']['ids'], flags=re.MULTILINE):
			tenant_id = tenant_id.strip()
			if len(tenant_id) == 0:
				continue
			if tenant_id[0] == '#':
				continue
			if tenant_id[0] == ';':
				continue

			section = 'tenant:params:{}'.format(tenant_id)
			if Config.has_section(section):
				params = dict(Config.items(section))
				self.Tenants[tenant_id] = Tenant(tenant_id, params)
			else:
				self.Tenants[tenant_id] = Tenant(tenant_id)

		# Load tenants from URL
		self.TenantUrl = Config["tenants"]["tenant_url"]

	async def initialize(self, app):
		if len(self.TenantUrl) > 0:
			await self._update_tenants()
			# TODO: Websocket persistent API should be added to seacat auth to feed these changes in realtime (eventually)
			app.PubSub.subscribe("Application.tick/300!", self._update_tenants)

	@property
	def TenantIds(self):
		'''
		This is here for a backward compatibility.
		Remove after Jan 2022
		'''
		L.warning("The TenantService.TenantIds is deprecated, use TenantService.get_tenant_ids()")
		return self.get_tenant_ids()

	def locate_tenant(self, tenant_id):
		tenant = self.Tenants.get(tenant_id)
		if tenant is None and self.TenantsTrusted > 0:
			tenant = {"_id": tenant_id}
			self.Tenants[tenant_id] = tenant
		return tenant

	def get_tenant_ids(self):
		return list(self.Tenants.keys())

	def get_tenants(self):
		tenants = []
		for tenant in self.Tenants.values():
			tenants.append(tenant.to_dict())
		return tenants

	def add_web_api(self, web_container):
		from .web import TenantWebHandler
		self.TenantWebHandler = TenantWebHandler(self.App, self, web_container)

	async def _update_tenants(self, message_name=None):
		async with aiohttp.ClientSession() as session:
			async with session.get(self.TenantUrl) as resp:
				if resp.status == 200:
					tenants_list = await resp.json()
					for tenant in tenants_list:
						self.Tenants[tenant["_id"]] = tenant


# THIS IS FILE EXIST WITH THE LOOSE SCRIPTS TO CHANGE/CONTROL THINGS
# FILE IS MADE TO TRAIN MODELS
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
# Imports for connections
from config.connectMongo import db

# Uncommented when to use the other set
dataSetRaw = db.readingDataRaw.find({}, {'_id': False})

df = pd.DataFrame(dataSetRaw)

# dataSetRaw=db.trainDataNew.find({}, {'_id': False})

print(df)

# zip_path = tf.keras.utils.get_file(
#     origin='https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip',
#     fname='jena_climate_2009_2016.csv.zip',
#     extract=True)
# csv_path, _ = os.path.splitext(zip_path)

# df = pd.read_csv(csv_path)

# TODO: FIND OUT WHAT THIS DOES AND REWRITE FOR MYSELF

print(df.isna().sum())

def normalizeData(dataset, start_index, end_index, history_size, target_size):
    data = []
    labels = []

    start_index = start_index + history_size

    if end_index is None:
        end_index = len(dataset) - target_size

    for i in range(start_index, end_index):
        indices = range(i-history_size, i)
        # RESHAPE THE DATA
        data.append(np.reshape(dataset[indices], (history_size, 1)))
        labels.append(dataset[i + target_size])

    return np.array(data), np.array(labels)

train_split = 22000

tf.random.set_seed(13)

uni_data = df['soil_moisture_10']
uni_data.index = df['unixTimestampReading']
uni_data.head()

plt.figure('Overview')
uni_data.plot(subplots=True)
plt.show()

uni_data = uni_data.values

uniTrainMean = uni_data[:train_split].mean()
# Mean is the avd
uniTrainStd = uni_data[:train_split].std()
# STD is het verschil tussen alle cijfers

uni_data = (uni_data - uniTrainMean) / uniTrainMean

pastHistory = 20
futureTarget = 0

x_train_uni, y_train_uni = normalizeData(uni_data, 0, train_split,
                                         pastHistory, futureTarget)
x_val_uni, y_val_uni = normalizeData(uni_data, train_split, None,
                                     pastHistory, futureTarget)

# Print extra data
print('Single window of past history')
print(x_train_uni[0])
print('\n Target soil moisture to predict')
print(y_train_uni[0])

def createTimeSteps(lenght):
    return list(range(-lenght, 0))

def showPlot(plotData, delta, title):
    labels = ['History', 'True Future', 'Model Predictinos']
    marker = ['.-', 'rx', 'go']
    timeSteps = createTimeSteps(plotData[0].shape[0])

    if delta:
        future = delta
    else:
        future = 0

    plt.title(title)

    for i, testing in enumerate(plotData):
        if i:
            plt.plot(future, plotData[i], marker[i], markersize=10, label=labels[i])
        else:
            plt.plot(timeSteps, plotData[i], marker[i], label=labels[i])

    plt.legend()
    plt.xlim([timeSteps[0], (future+5)*2])
    plt.xlabel('Time-Step')

    return plt.show()

# Plot for example
# showPlot([x_train_uni[0], y_train_uni[0]], 0, 'Sample Example')

def baseline(history):
    return np.mean(history)

#  Plot for testing
# showPlot([x_train_uni[0], y_train_uni[0], baseline(x_train_uni[0])], 0,  'Baseline Prediction Example')

batchSize = 256
bufferSize = 10000

trainUnivariate = tf.data.Dataset.from_tensor_slices((x_train_uni, y_train_uni))
trainUnivariate = trainUnivariate.cache().shuffle(bufferSize).batch(batchSize).repeat()

valUnivariate = tf.data.Dataset.from_tensor_slices((x_val_uni, y_val_uni))
valUnivariate = valUnivariate.batch(batchSize).repeat()

lstmModel = tf.keras.models.Sequential([
    tf.keras.layers.LSTM(8, input_shape=x_train_uni.shape[-2:]),
    tf.keras.layers.Dense(1)
])

lstmModel.compile(optimizer='adam', loss='mae')

for x, y in valUnivariate.take(1):
    print(lstmModel.predict(x).shape)

interval = 200
epochs = 10
print(valUnivariate)
lstmModel.fit(trainUnivariate, epochs=epochs, steps_per_epoch=interval, validation_data=valUnivariate, validation_steps=50)
# Uncomment to see first plot
for x, y in trainUnivariate.take(3):
    plot = showPlot([x[0].numpy(), y[0].numpy(), lstmModel.predict(x)[0]], 0, 'Simple LSTM model')
    pass

# ADDING MORE DATAPOINTS SINGLE STEP
features_considered = ['temp', 'airPressure', 'windSpeed', 'rain', 'humidity', 'windBearing', 'cloudCover',
                       'dewPoint', 'soil_moisture_10', 'sensorId', 'unixTimestampReading', 'lat', 'long', 'soilTypeId']
features = df[features_considered]
features.index = df['unixTimestampReading']
features.head()

features.plot(subplots=True)

dataset = features.values
data_mean = dataset[: train_split].mean(axis=0)
data_std = dataset[: train_split].std(axis=0)

dataset = (dataset-data_mean)/data_std

def multiStepData(dataset, target, startIndex, endIndex, historySize, targetSize, step, singleStep=False):
    data = []
    labels = []

    startIndex = startIndex + historySize
    if endIndex is None:
        endIndex = len(dataset) - targetSize

    for i in range(startIndex, endIndex):
        indices = range(i-historySize, i, step)
        data.append(dataset[indices])

        if singleStep:
            labels.append(target[i+targetSize])
        else:
            labels.append(target[i: i+targetSize])

    return np.array(data), np.array(labels)

pastHistory = 72
futureTarget = 8
step = 6

x_train_single, y_train_single = multiStepData(dataset, dataset[:, 1], 0, train_split, pastHistory, futureTarget, step, singleStep=True)
x_val_single, y_val_single = multiStepData(dataset, dataset[:, 1], train_split, None, pastHistory, futureTarget, step, singleStep=True)

print('Single window of past history : {}'.format(x_train_single[0].shape))

trainSingleData = tf.data.Dataset.from_tensor_slices((x_train_single, y_train_single))
trainSingleData = trainSingleData.cache().shuffle(bufferSize).batch(batchSize).repeat()

valDataSingle = tf.data.Dataset.from_tensor_slices((x_val_single, y_val_single))
valDataSingle = valDataSingle.batch(batchSize).repeat()
# Setting up the singlestep model
singleStepModel = tf.keras.models.Sequential()
singleStepModel.add(tf.keras.layers.LSTM(32, input_shape=x_train_single.shape[-2:]))
singleStepModel.add(tf.keras.layers.Dense(1))
singleStepModel.compile(optimizer=tf.keras.optimizers.RMSprop(), loss='mae')

for x, y in valDataSingle.take(1):
    print(singleStepModel.predict(x).shape)

# Train model
singleStepHistory = singleStepModel.fit(trainSingleData, epochs=epochs, steps_per_epoch=interval, validation_data=valDataSingle, validation_steps=50)

def plotTrainHistory(history, title):
    loss = history.history['loss']
    valLoss = history.history['val_loss']

    epochs = range(len(loss))

    plt.figure()

    plt.plot(epochs, loss, 'b', label='Training Loss')
    plt.plot(epochs, valLoss, 'r', label='Validation Loss')
    plt.title(title)
    plt.legend()

    plt.show()

# plotTrainHistory(singleStepHistory, 'Single Step Training and Validation Loss')

# Predict one step in the future
for x, y in valDataSingle.take(3):
    plot = showPlot([x[0][:, 1].numpy(), y[0].numpy(),
                     singleStepModel.predict(x)[0]], 12,
                    'Single Step Prediction')

# MULTE STEP
futureTarget = 72

x_train_multi, y_train_multi = multiStepData(dataset, dataset[:, 1], 0, train_split, pastHistory, futureTarget, step)
x_val_multi, y_val_multi = multiStepData(dataset, dataset[:, 1], train_split, None, pastHistory, futureTarget, step)

print('Single window of past history : {}'.format(x_train_multi[0].shape))
print('\n Target temperature to predict : {}'.format(y_train_multi[0].shape))

trainMultiData = tf.data.Dataset.from_tensor_slices((x_train_multi, y_train_multi))
trainMultiData = trainMultiData.cache().shuffle(bufferSize).batch(batchSize).repeat()

valDataMulti = tf.data.Dataset.from_tensor_slices((x_val_multi, y_val_multi))
valDataMulti = valDataMulti.batch(batchSize).repeat()

def multiStepPlot(history, trueFuture, predicition):
    plt.figure(figsize=(12, 6))
    num_in = createTimeSteps(len(history))
    num_out = len(trueFuture)

    plt.plot(num_in, np.array(history[:, 1]), label='History')
    plt.plot(np.arange(num_out) / step, np.array(trueFuture), 'bo',
             label='True Future')

    if predicition.any():
        plt.plot(np.arange(num_out)/step, np.array(predicition), 'ro',
                 label='Predicted Future')
    plt.legend(loc='upper left')
    plt.show()

for x, y in trainMultiData.take(1):
    multiStepPlot(x[0], y[0], np.array([0]))

multiStepModel = tf.keras.models.Sequential()
multiStepModel.add(tf.keras.layers.LSTM(32,  return_sequences=True, input_shape=x_train_multi.shape[-2:]))
multiStepModel.add(tf.keras.layers.LSTM(16, activation='relu'))
multiStepModel.add(tf.keras.layers.Dense(72))

multiStepModel.compile(optimizer=tf.keras.optimizers.RMSprop(clipvalue=1.0), loss='mae')

for x, y in valDataMulti.take(1):
    print(multiStepModel.predict(x).shape)
    pass

multiStepHistory = multiStepModel.fit(trainMultiData, epochs=epochs, steps_per_epoch=interval, validation_data=valDataMulti, validation_steps=50)

plotTrainHistory(multiStepHistory, 'Multi step history and loss')

print(valDataMulti)

for x, y in valDataMulti.take(3):
    multiStepPlot(x[0], y[0], multiStepModel.predict(x)[0])
    pass


#!/usr/bin/python3

from lilaclib import *

def pre_build():
    aur_pre_build(maintainers=['Airblader'])
    for line in edit_file('PKGBUILD'):
        if 'groups=' in line:
            print(line.replace("'i3' ",'',1))
        else:
            print(line)


import cmc
import onedWorld

class interpreter:
    def __init__(self):
        self.kernel = cmc.CMC("transition")
        # define initial state here:
        self.state = 0

    def getInitialSensor(self):
        sensor = state2sensor(self.state)
        return sensor

    def getSensor(self,motor):
        action = motor2action(motor)
        self.state = self.kernel.getNextState(self.state,action)
        sensor = state2sensor(self.state)
        return sensor

    def getBotPosition(self):
        return {
            0: [-50,0],
            1: [0,0],
            2: [50,0]
        }[self.state]

# def f(x):
#     return {
#         'a': 1,
#         'b': 2,
#         }.[get(x, 9)]

def state2sensor(state):
    return {
        0: [1,0],
        1: [0,0],
        2: [0,1]
    }[state]

# motor in:
# -1 -> -0.5: move left with high speed = action 0
# -0.5 -> 0: move left with low speed = action 1
# 0: stand still = action 2
# 0 - 0.5: move right = action 3
# 0.5 - 1: action 4
# to translate, motor * 2 is in -2 -> 2
# motor *2 + 2 is in 0 -> 4
# where each interval 0-1, 1-2, 2-3, 3-4 correspond to actions 0-4, except for 2 - 0
# if we disregard action 2 (stand still), we have:
#     int(motor*2+2) corresponds to action no.
def motor2action(motor):
    return{
        0: 0,
        1: 1,
        2: 3,
        3: 4
    }[int(motor*2.+2.)]

Simulator/1(one d three states)/interpreter.py


# -*- coding: UTF-8 -*-

# 运行etl，测试运行情况，检查运行结果

import requests
import json

job_url = 'http://localhost:31001/job/'
scheduler_url = 'http://localhost:31001/scheduler/'
run_url = 'http://localhost:31001/run'

DEBUG_START_AT = '1546272000000'  # 2019-01-01
DEBUG_END_AT = '1584892800000'  # 2020-03-23

def requests_get(url, params):
    response = requests.get(url, params=params)
    # response.encoding = "utf-8"
    print(response.status_code)
    print(response.text)
    return response.text

def add_job_1():
    url = job_url + 'add'
    param = {"timeField": "",
             "startAt": "",
             "endAt": "",
             "knowledgeType": "",
             "jobId": "1",
             "jobName": "dayTask",
             "timeInterval": 86400}
    result = requests_get(url, param)
    # print("1")
    # print(result)

def add_job_2():
    url = job_url + 'add'
    param = {"timeField": "2",
             "jobId": "2",
             "jobName": "22",
             "timeInterval": 5}
    result = requests_get(url, param)
    # print("2")
    # print(result)

def start():
    url = scheduler_url + 'start'
    param = {}
    result = requests_get(url, param)
    print("start")
    print(result)

def stop():
    url = scheduler_url + 'shutdown'
    param = {}
    result = requests_get(url, param)
    print("shutdown")
    print(result)

# [{"job_id": "1", "job_name": "11", "next_run_time": "2020-01-10 17:07:21"},
# {"job_id": "2", "job_name": "22", "next_run_time": "2020-01-10 17:07:23"}]
def query():
    url = job_url + 'query'
    param = {}
    result = requests_get(url, param)
    print("query")
    json_result = json.loads(result)
    print(json_result[0])  # {'job_id': '1', 'job_name': '11', 'next_run_time': '2020-01-14 10:45:56'}

def run(knowledge_type):
    param = {"startAt": DEBUG_START_AT,
             "endAt": DEBUG_END_AT,
             "timeField": "pubAt",
             "knowledgeType": knowledge_type}
    result = requests_get(run_url, param)
    print("run")

if __name__ == "__main__":
    # add_job_1()
    # add_job_2()
    # start()
    # query()
    # stop()
    # run("公司竞争优势")
    run("公司市场排名")
    # print(type('123'))


# coding: utf-8

import matplotlib.pyplot as plt
import numpy as np

from sklearn import linear_model

x = np.random.rand(100, 1)
x = x * 2 - 1

y = 4 * x**3 - 3 * x**2 + 2 * x - 1
y += np.random.randn(100, 1)

x_train = x[:30]
y_train = y[:30]

x_test = x[30:]
y_test = y[30:]

X_TRAIN = np.c_[x_train**9, x_train**8, x_train**7,
                x_train**6, x_train**5, x_train**4,
                x_train**3, x_train**2, x_train]

X_TEST = np.c_[x_test**9, x_test**8, x_test**7,
                x_test**6, x_test**5, x_test**4,
                x_test**3, x_test**2, x_test]

model = linear_model.Ridge()
model.fit(X_TRAIN, y_train)

print(model.coef_)
print(model.intercept_)
print(model.score(X_TEST, y_test))

plt.scatter(x_test, y_test, marker='+')
plt.scatter(x_test, model.predict(X_TEST))
plt.show()


"""Collection of pure-Numba functions for sampling & probability computation"""
from __future__ import annotations

from typing import Tuple

import numpy as np
from numba import boolean as nbool
from numba import float32 as nfloat
from numba import float64 as ndouble
from numba import int64 as nlong
from numba import njit
from numba import optional as maybe
from numba import prange, void
from numba.core.types import Tuple as NTuple
from numpy.typing import NDArray

MIN_RANDOM_VALUE = np.finfo(np.float64).tiny
MAX_RANDOM_VALUE = np.iinfo(np.int32).max

TREE_INFO_TYPE = NTuple((nlong[:], nlong[:], ndouble[:]))

class UtilityBoundsError(ValueError):
    pass

# region Sampling

@njit(nlong(ndouble[:], ndouble), nogil=True, cache=True)
def sample_once(p_array: NDArray, r: float) -> int:
    r = max(r, MIN_RANDOM_VALUE)
    cumsum = 0.0
    index = 0
    for p in p_array:
        cumsum += p
        if r <= cumsum:
            return index
        index += 1
    return len(p_array) - 1

@njit(nlong(ndouble, ndouble[:]), nogil=True, cache=True)
def logarithmic_search(r: float, cps: NDArray) -> int:
    """Logarithmic (binary) search algorithm for finding the greatest index whose cumulative probability is <= the
    random draw.

    Allows for cells with 0 probability.

    Args:
        r (float): The random draw to compare against.
        cps (float[]): The cumulative probabilities to search

    Returns:
        int: The found index.
    """

    # The check below is required to avoid a very specific edge case in which there is more than one 0-probability
    # choice at the start of the probability array, e.g. [0, 0, 0, 0.1, 0.3, 0.7, 1.0]. The randomizer draws on the
    # interval [0, 1), so it's a (very) small possibility, but nonetheless would yield potentially very wrong results
    if r == 0:
        r = MIN_RANDOM_VALUE

    ncols = len(cps)

    lower_bound, upper_bound = 0, ncols - 1
    while (upper_bound - lower_bound) > 1:
        mid_index = np.uint32((upper_bound + lower_bound) // 2)
        cp_at_mid = cps[mid_index]
        if r <= cp_at_mid:  # left branch
            upper_bound = mid_index
        else:  # right branch
            lower_bound = mid_index

    cp_at_left = cps[lower_bound]
    if r <= cp_at_left:
        return lower_bound
    else:
        return upper_bound

@njit(void(ndouble[:]), nogil=True, cache=True)
def nbf_cumsum(array: NDArray):
    accum = 0.0
    length = len(array)
    for i in range(length):
        accum += array[i]
        array[i] = accum

@njit(nlong[:](nlong, nlong), nogil=True, cache=True)
def generate_rand_ints_for_parallel(seed: int, n: int) -> NDArray:
    """Wrap random sampling in a separate function with parallel=False for stable results"""
    np.random.seed(seed)
    return np.random.randint(0, MAX_RANDOM_VALUE, n)

@njit(ndouble[:](nlong, nlong), nogil=True, cache=True)
def generate_rand_floats_for_parallel(seed: int, n: int) -> NDArray:
    """Wrap random sampling in a separate function with parallel=False for stable results"""
    np.random.seed(seed)
    return np.random.uniform(MIN_RANDOM_VALUE, 1, n)

@njit(nlong[:](ndouble[:], nlong, nlong, maybe(nlong[:])), nogil=True, cache=True)
def sample_multi(p_array: NDArray, n: int, random_seed: int, out_array: NDArray = None) -> NDArray:
    """Sample from a probability distribution multiple times using binary search"""
    np.random.seed(random_seed)

    nbf_cumsum(p_array)

    if out_array is None:
        out_array = np.zeros(n, dtype=np.int64)
    else:
        assert len(out_array) == n

    for i in range(n):
        r = np.random.uniform(MIN_RANDOM_VALUE, 1.0, 1)[0]
        out_array[i] = logarithmic_search(r, p_array)
    return out_array

# endregion

# region Probability Computation

@njit(ndouble[:](ndouble[:]), nogil=True, cache=True)
def simple_probabilities(weights: NDArray) -> NDArray:
    return weights / weights.sum()

@njit([
    NTuple((ndouble[:], ndouble, ndouble[:]))(ndouble[:], nbool),
    NTuple((ndouble[:], ndouble, ndouble[:]))(nfloat[:], nbool)
], nogil=True, cache=True)
def multinomial_probabilities(utilities: NDArray, check_infeasible: bool) -> Tuple[NDArray, float, NDArray]:
    """Computes probabilities given a multinomial logit model formulation."""
    n_cols = len(utilities)
    p = np.zeros(n_cols, dtype=np.float64)  # Return value
    ls_terms = np.zeros(n_cols, dtype=np.float64)

    total_ls = 0.0  # Logsum
    for i, u in enumerate(utilities):
        expu = np.exp(u)
        total_ls += expu
        p[i] = expu
        ls_terms[i] = expu

    if total_ls <= 0:
        if check_infeasible:
            raise UtilityBoundsError("MNL utilities all exceeded minimum value (Logsum == 0.0)")
        for i in range(n_cols):
            p[i] = 0  # ensure that `p` will return all zeros
    else:
        for i in range(n_cols):
            p[i] = p[i] / total_ls

    return p, total_ls, ls_terms

@njit([
    NTuple((ndouble[:], ndouble, ndouble[:]))(ndouble[:], nlong[:], nlong[:], ndouble[:], nbool[:], nbool, nbool),
    NTuple((ndouble[:], ndouble, ndouble[:]))(nfloat[:], nlong[:], nlong[:], ndouble[:], nbool[:], nbool, nbool)
], nogil=True, cache=True)
def nested_probabilities(utilities: NDArray, hierarchy, levels, logsum_scales, bottom_flags, scale_utilities: bool,
                         check_infeasible: bool) -> Tuple[NDArray, float, NDArray]:
    """Probability evaluation of a nested logit model, without needing a tree structure or any recursion."""

    n_cells = len(utilities)
    probabilities = utilities.astype(np.float64)
    top_logsum = 0
    grouped_logsums = np.zeros(n_cells, dtype=np.float64)
    final_logsums = np.zeros(n_cells, dtype=np.float64)

    # Step 1: Exponentiate the utilities and collect logsums
    max_level = levels.max()
    current_level = max_level
    for _ in range(max_level + 1):
        # Go through levels in reverse order (e.g. starting at the bottom)
        for index, level in enumerate(levels):
            if level != current_level:
                continue  # This is still faster than using np.where()

            parent = hierarchy[index]
            parent_ls_scale = 1.0 if not scale_utilities or parent < 0 else logsum_scales[parent]
            is_bottom = bottom_flags[index]

            if is_bottom:
                # If this node is at the bottom of the tree, no need to lookup the previously-stored logsum
                expu = np.exp(probabilities[index] / parent_ls_scale)
            else:
                existing_logsum = grouped_logsums[index]
                current_ls_scale = logsum_scales[index]

                # Note: It is deliberate to take the log of 0 in some cases. This can occur when all children in a nest
                # exponentiate to 0 (e.g. have very low utility, usually deliberately to disable some choices). The
                # function np.log() evaluates to -inf, which is exactly what we want it to be: the upper choice should
                # also get disabled.
                expu = np.exp((probabilities[index] + current_ls_scale * np.log(existing_logsum)) / parent_ls_scale)

            if parent >= 0:
                grouped_logsums[parent] += expu
            else:
                top_logsum += expu
            probabilities[index] = expu
            final_logsums[index] = expu
        current_level -= 1

    if top_logsum <= 0:
        if check_infeasible:
            raise UtilityBoundsError("Nested logit top-level logsum is 0.0")

    # Step 2: Use logsums to compute conditional probabilities
    for index, parent in enumerate(hierarchy):
        ls = top_logsum if parent == -1 else grouped_logsums[parent]

        # Logsums of 0 can happen sometimes when all choices in a nest are -inf, so just fix the probabilities to 0
        p = 0.0 if ls <= 0 else probabilities[index] / ls
        probabilities[index] = p

    # Step 3: Compute absolute probabilities for child nodes, collecting parent nodes
    for current_level in range(1, max_level + 1):
        for index, level in enumerate(levels):
            if level != current_level:
                continue
            parent = hierarchy[index]
            probabilities[index] *= probabilities[parent]

    # Step 4: Zero-out parent node probabilities
    # This does not use a Set because Numba sets are really slow
    for parent in hierarchy:
        if parent < 0:
            continue
        probabilities[parent] = 0.0

    return probabilities, top_logsum, final_logsums

# endregion

# region Middle functions

@njit(nlong(ndouble[:], ndouble), nogil=True, cache=True)
def simple_sample(weights: NDArray, r: float) -> int:
    """Samples once from an array of weights, from an existing random draw"""
    p_array = simple_probabilities(weights)
    return sample_once(p_array, r)

@njit(nlong[:](ndouble[:], nlong, nlong, maybe(nlong[:])), nogil=True, cache=True)
def simple_multisample(weights: NDArray, n: int, seed: int, out: NDArray = None) -> NDArray:
    """Samples multiple times from an array of weights, based on a random seed. Thread-safe."""
    p_array = simple_probabilities(weights)
    return sample_multi(p_array, n, seed, out)

@njit([
    NTuple((nlong, ndouble))(ndouble[:], ndouble),
    NTuple((nlong, ndouble))(nfloat[:], ndouble)
], nogil=True, cache=True)
def multinomial_sample(utilities: NDArray, r: float) -> Tuple[int, float]:
    """Samples once from an array of multinomial logit utilities, from an existing random draw"""
    p_array, ls, _ = multinomial_probabilities(utilities, True)  # Check infeasible req'd (for sampling)
    return sample_once(p_array, r), ls

@njit([
    NTuple((nlong[:], ndouble))(ndouble[:], nlong, nlong, maybe(nlong[:])),
    NTuple((nlong[:], ndouble))(nfloat[:], nlong, nlong, maybe(nlong[:]))
], nogil=True, cache=True)
def multinomial_multisample(utilities: NDArray, n: int, seed: int, out: NDArray = None) -> Tuple[NDArray, float]:
    """Samples multiple times from an array of multinomial logit utilities, based on a random seed. Thread-safe."""
    p_array, ls, _ = multinomial_probabilities(utilities, True)  # Check infeasible req'd (for sampling)
    return sample_multi(p_array, n, seed, out), ls

@njit([
    NTuple((nlong, ndouble))(ndouble[:], ndouble, nlong[:], nlong[:], ndouble[:], nbool[:], nbool),
    NTuple((nlong, ndouble))(nfloat[:], ndouble, nlong[:], nlong[:], ndouble[:], nbool[:], nbool)
], nogil=True, cache=True)
def nested_sample(utilities: NDArray, r: float, parents, levels, ls_scales, bottom_flags,
                  scale_utilities: bool) -> Tuple[int, float]:
    """Samples once from an array of nested logit utilities, from an existing random draw"""
    p_array, ls, _ = nested_probabilities(
        utilities, parents, levels, ls_scales, bottom_flags, scale_utilities, True  # Check infeasible req'd (for sampling)
    )
    return sample_once(p_array, r), ls

@njit([
    NTuple((nlong[:], ndouble))(ndouble[:], nlong[:], nlong[:], ndouble[:], nbool[:], nlong, nlong, nbool, maybe(nlong[:])),
    NTuple((nlong[:], ndouble))(nfloat[:], nlong[:], nlong[:], ndouble[:], nbool[:], nlong, nlong, nbool, maybe(nlong[:]))
], nogil=True, cache=True)
def nested_multisample(utilities: NDArray, parents, levels, ls_scales, bottom_flags, n: int, seed: int,
                       scale_utilities: bool, out: NDArray = None) -> Tuple[NDArray, float]:
    """Samples multiple times from an array of nested logit utilities, based on a random seed. Thread-safe."""
    p_array, ls, _ = nested_probabilities(
        utilities, parents, levels, ls_scales, bottom_flags, scale_utilities, True  # Check infeasible req'd (for sampling)
    )
    return sample_multi(p_array, n, seed, out), ls

# endregion

# region High level functions

@njit(nlong[:, :](ndouble[:, :], nlong, nlong), parallel=True, nogil=True, cache=True)
def worker_weighted_sample(weights: NDArray, n: int, seed: int) -> NDArray:
    n_rows = weights.shape[0]
    result = np.zeros((n_rows, n), dtype=np.int64)

    np.random.seed(seed)
    if n <= 1:
        r_array = np.random.uniform(MIN_RANDOM_VALUE, 1.0, n_rows)
        for i in prange(n_rows):
            weight_row = weights[i, :]
            r = r_array[i]
            result[i, 0] = simple_sample(weight_row, r)
    else:
        seed_array = np.random.randint(0, MAX_RANDOM_VALUE, n_rows)
        for i in prange(n_rows):
            weight_row = weights[i, :]
            seed_i = seed_array[i]
            _, ls = simple_multisample(weight_row, n, seed_i, result[i, :])
    return result

@njit([
    NTuple((nlong[:, :], ndouble[:]))(ndouble[:, :], nlong, nlong),
    NTuple((nlong[:, :], ndouble[:]))(nfloat[:, :], nlong, nlong)
], parallel=True, nogil=True, cache=True)
def worker_multinomial_sample(utilities: NDArray, n: int, seed: int) -> Tuple[NDArray, NDArray]:
    """Runs multinomial_sample or multinomial_multisample in parallel."""
    n_rows = utilities.shape[0]
    result = np.zeros((n_rows, n), dtype=np.int64)
    ls_array = np.zeros(n_rows, dtype=np.float64)

    if n <= 1:
        r_array = generate_rand_floats_for_parallel(seed, n_rows)
        for i in prange(n_rows):
            utility_row = utilities[i, :]
            r = r_array[i]
            result[i, 0], ls = multinomial_sample(utility_row, r)
            ls_array[i] = ls
    else:
        seed_array = generate_rand_ints_for_parallel(seed, n_rows)
        for i in prange(n_rows):
            utility_row = utilities[i, :]
            seed_i = seed_array[i]
            _, ls = multinomial_multisample(utility_row, n, seed_i, result[i, :])
            ls_array[i] = ls
    return result, ls_array

@njit([
    NTuple((ndouble[:, :], ndouble[:], ndouble[:, :]))(ndouble[:, :], nbool),
    NTuple((ndouble[:, :], ndouble[:], ndouble[:, :]))(nfloat[:, :], nbool)
], parallel=True, nogil=True, cache=True)
def worker_multinomial_probabilities(utilities: NDArray, check_infeasible: bool) -> Tuple[NDArray, NDArray, NDArray]:
    """Runs multinomial_probabilities in parallel"""
    n_rows, n_cols = utilities.shape
    result = np.zeros((n_rows, n_cols), dtype=np.float64)
    top_ls_array = np.zeros(n_rows, dtype=np.float64)
    nested_ls_terms = np.zeros((n_rows, n_cols), dtype=np.float64)

    for i in prange(n_rows):
        utility_row = utilities[i, :]
        p_array, top_ls, nested_ls = multinomial_probabilities(utility_row, check_infeasible)
        result[i, :] = p_array
        top_ls_array[i] = top_ls
        nested_ls_terms[i, :] = nested_ls

    return result, top_ls_array, nested_ls_terms

@njit([
    NTuple((nlong[:, :], ndouble[:]))(ndouble[:, :], nlong[:], nlong[:], ndouble[:], nbool[:], nlong, nlong, nbool),
    NTuple((nlong[:, :], ndouble[:]))(nfloat[:, :], nlong[:], nlong[:], ndouble[:], nbool[:], nlong, nlong, nbool)
], parallel=True, nogil=True, cache=True)
def worker_nested_sample(utilities: NDArray, parents, levels, ls_scales, bottom_flags, n: int, seed: int,
                         scale_utilities: bool) -> Tuple[NDArray, NDArray]:
    """Runs nested_sample or nested_multisample in parallel."""
    n_rows = len(utilities)
    result = np.zeros((n_rows, n), dtype=np.int64)
    ls_array = np.zeros(n_rows, dtype=np.float64)

    if n <= 1:
        r_array = generate_rand_floats_for_parallel(seed, n_rows)
        for i in prange(n_rows):
            utility_row = utilities[i, :]
            r = r_array[i]
            this_result, ls = nested_sample(
                utility_row, r, parents, levels, ls_scales, bottom_flags, scale_utilities
            )
            result[i, 0] = this_result
            ls_array[i] = ls
    else:
        seed_array = generate_rand_ints_for_parallel(seed, n_rows)
        for i in prange(n_rows):
            utility_row = utilities[i, :]
            seed_i = seed_array[i]
            _, ls = nested_multisample(
                utility_row, parents, levels, ls_scales, bottom_flags, n, seed_i, scale_utilities, out=result[i, :]
            )
            ls_array[i] = ls
    return result, ls_array

@njit([
    NTuple((ndouble[:, :], ndouble[:], ndouble[:, :]))(ndouble[:, :], nlong[:], nlong[:], ndouble[:], nbool[:], nbool, nbool),
    NTuple((ndouble[:, :], ndouble[:], ndouble[:, :]))(nfloat[:, :], nlong[:], nlong[:], ndouble[:], nbool[:], nbool, nbool)
], parallel=True, nogil=True, cache=True)
def worker_nested_probabilities(utilities: NDArray, parents, levels, ls_scales, bottom_flags, scale_utilities: bool,
                                check_infeasible: bool) -> Tuple[NDArray, NDArray, NDArray]:
    """Runs nested_probabilities in parallel"""
    n_rows, n_cols = utilities.shape
    result = np.zeros((n_rows, n_cols), dtype=np.float64)
    top_ls_array = np.zeros(n_rows, dtype=np.float64)
    nested_ls_terms = np.zeros((n_rows, n_cols), dtype=np.float64)

    for i in prange(n_rows):
        utility_row = utilities[i, :]
        p_array, top_ls, nested_ls = nested_probabilities(
            utility_row, parents, levels, ls_scales, bottom_flags, scale_utilities, check_infeasible
        )
        result[i, :] = p_array
        top_ls_array[i] = top_ls
        nested_ls_terms[i, :] = nested_ls

    return result, top_ls_array, nested_ls_terms

# endregion

# region Misc functions

def fast_indexed_add(out: NDArray, addition: NDArray, row_index: NDArray = None, col_index: NDArray = None):
    """Parallel "a += b" function for large matrices. Also allows "a[:, indexer] += b" for partial tables."""
    rows_a, cols_a = addition.shape
    rows_o, cols_o = out.shape

    if row_index is None:
        assert rows_a == rows_o
    else:
        assert len(row_index) == rows_a
        assert row_index.min() >= 0 and row_index.max() < rows_o

    if col_index is None:
        assert cols_a == cols_o
    else:
        assert len(col_index) == cols_a
        assert col_index.min() >= 0 and col_index.max() < cols_o

    ri_is_none, ci_is_none = row_index is None, col_index is None

    if ri_is_none and ci_is_none:
        _fast_indexed_add_n_n(out, addition)
    elif ri_is_none:
        _fast_indexed_add_n_i(out, addition, col_index)
    elif ci_is_none:
        _fast_indexed_add_i_n(out, addition, row_index)
    else:
        _fast_indexed_add_i_i(out, addition, row_index, col_index)

@njit(parallel=True, cache=True)
def _fast_indexed_add_n_n(out, addition):
    rows_a, cols_a = addition.shape
    for offset in prange(rows_a * cols_a):
        row, col = divmod(offset, cols_a)
        rowi, coli = int(row), int(col)
        out[rowi, coli] += addition[rowi, coli]

@njit(parallel=True, cache=True)
def _fast_indexed_add_n_i(out, addition, col_index):
    rows_a, cols_a = addition.shape
    for offset in prange(0, rows_a * cols_a):
        row, col = divmod(offset, cols_a)
        rowi, coli = int(row), int(col)
        target_col = col_index[coli]
        out[rowi, target_col] += addition[rowi, coli]

@njit(parallel=True, cache=True)
def _fast_indexed_add_i_n(out, addition, row_index):
    rows_a, cols_a = addition.shape
    for offset in prange(rows_a * cols_a):
        row, col = divmod(offset, cols_a)
        rowi, coli = int(row), int(col)
        target_row = row_index[rowi]
        out[target_row, coli] += addition[rowi, coli]

@njit(parallel=True, cache=True)
def _fast_indexed_add_i_i(out, addition, row_index, col_index):
    rows_a, cols_a = addition.shape
    for offset in prange(rows_a * cols_a):
        row, col = divmod(offset, cols_a)
        rowi, coli = int(row), int(col)
        target_row = row_index[rowi]
        target_col = col_index[coli]
        out[target_row, target_col] += addition[rowi, coli]

# endregion


inca=int(input("Da el valor de a: "))
incb=int(input("Da el valor de b: "))
incc=int(input("Da el valor de c: "))
discrimintante= (incb**2)-(4*inca*incc)
chicharronero1= (-incb + discrimintante) / 2*inca
chicharronero2= (-incb - discrimintante) / 2*inca
if chicharronero1 == 0:
    print("No tiene solucion")
elif chicharronero2 == 0:
    print ("No tiene solucion")
if discrimintante < 0:
    print("Raices complejas")
else :
    print ( chicharronero1 )
    print ( chicharronero2 )
if inca == 0 and incb != 0:
    x = (- incc / incb)
    print (x)


#!/usr/bin/env python
#-*- coding: utf-8 -*
import json
import numpy as np
import nltk
from nltk.stem.lancaster import LancasterStemmer

words = []  #to store the single words.
stemmer = LancasterStemmer()
classes = []
ERROR_THRESHOLD = 0.2
synapse_file = "/home/pi/ros/src/nlp/src/synapses.json"

with open(synapse_file,'r') as data_file:
      synapse = json.load(data_file)
      synapse_0 = np.asarray(synapse['synapse0'])
      synapse_1 = np.asarray(synapse['synapse1'])
      words = np.asarray(synapse['words'])
      classes = np.asarray(synapse['classes'])

#define some related functions
# compute sigmoid nonlinearity
def sigmoid(x):
    output = 1/(1+np.exp(-x))
    return output

# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
    return output*(1-output)

def clean_up_sentence(sentence):
    sentence_words = nltk.word_tokenize(sentence)
    sentence_words = [stemmer.stem(word.lower()) for word in sentence_words]
    return sentence_words

# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence
def bow(sentence, words, show_details=False):
    sentence_words = clean_up_sentence(sentence)
    bag = [0]*len(words)
    for s in sentence_words:
        for i,w in enumerate(words):
            if w == s:
                bag[i] = 1
                if show_details:
                    print ("found in bag: %s" % w)

    return(np.array(bag))

def think(sentence, show_details=False):
    x = bow(sentence.lower(), words, show_details)
    if show_details:
        print ("sentence:", sentence, "bow:", x)
    l0 = x
    l1 = sigmoid(np.dot(l0, synapse_0))
    l2 = sigmoid(np.dot(l1, synapse_1))
    return l2

def classify(sentence, show_details=False):

    results = think(sentence, show_details)

    results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD ]
    results.sort(key=lambda x: x[1], reverse=True)
    return_results =[[classes[r[0]],r[1]] for r in results]
    return return_results


import time
from selenium import webdriver

def main():
    driver = webdriver.Chrome(executable_path='chromedriver.exe')
    driver.get('https://www.w3schools.com/')
    time.sleep(1)
    links = driver.find_elements_by_tag_name('a')

    #Recorriendo la lista por el bucle for
    for l in links:
        print(l.text + ': ' + l.get_attribute('href')) #Nos da los parametros hacia que URL esta apuntando.

if __name__ == '__main__':
    main()
time.sleep(2)


from NetworkModule.Net import  *
import numpy as np
import math
import torch.nn as nn
from torch.autograd import variable
import torch.optim as optim
from tqdm import tqdm
import os

hist=dict()
def make_vec(word):
    global hist
    word_embedding=[]
    for ch in word:
        numeric=ord(ch)
        if(numeric not in hist):
            hist[numeric]=0
        hist[numeric]+=1
        word_embedding.append(numeric)
    word_embedding=np.fliplr([word_embedding])[0]

    input_size=40
    left_pad=0
    right_pad=0
    to_pad=input_size-len(word)
    left_pad=math.floor(to_pad/2)
    right_pad=math.ceil(to_pad/2)

    final_vec=np.pad(word_embedding,(left_pad,right_pad),'mean')
    return final_vec/1114112.0

def make_gender_vec(gender):
    if(gender=="male"):
        return torch.LongTensor([1])

    return torch.LongTensor([0])

f=open('testData.txt','r')
names=[]
genders=[]
for i,line in enumerate(f):

    name,gender=line.split(',')
    names.append(name)
    genders.append(make_gender_vec(gender.strip('\n')))

net=Net()

criterion=nn.CrossEntropyLoss()
epochs=100
optimizer=optim.SGD(net.parameters(),lr=0.0001,momentum=0.9)
from io import open
import glob
import unicodedata
import string

all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)
def unicodeToAscii(s):
    return ''.join(
        c for c in unicodedata.normalize('NFD', s)
        if unicodedata.category(c) != 'Mn'
        and c in all_letters
    )

for name in names[5:15]:
    print(unicodeToAscii(str(name.encode('utf-8'))),name)

# for epoch in range(epochs):
#     net.train()
#     epoch_sum=0
#     running_loss=0.0
#     for i,data in enumerate(tqdm(zip(names,genders))):
#         name,gender=data
#         optimizer.zero_grad()
#         input_vec=torch.from_numpy(make_vec(name))
#         input_vec=input_vec.unsqueeze(dim=0)
#         input_vec = variable(input_vec,requires_grad=True)
#
#         output=net(input_vec)
#
#         loss=criterion(output,gender)
#
#         loss.backward()
#         optimizer.step()
#         running_loss += loss.item()
#         epoch_sum+=loss.item()
#         if i % 10000 == 9999:  # print every 2000 mini-batches
#             print('[%d, %5d] loss: %.3f' %
#                   (epoch + 1, i + 1, running_loss / 10000))
#             running_loss = 0.0
#
#     print('Epoch loss:',epoch_sum)
#     torch.save(net,os.path.join('weights2',str(epoch)+'.pt'))
#     print('Model saved')

# import torch.nn as nn
#
# net=torch.load('weights/22.pt')
# correct=0
# total=len(names)
# for i,data in enumerate(tqdm(zip(names,genders))):
#     name,gender=data
#     input_vec=torch.from_numpy(make_vec(name))
#     input_vec=input_vec.unsqueeze(dim=0)
#     input = variable(input_vec,requires_grad=True)
#     output=net(input)
#     softmax=nn.Softmax()
#     output=softmax(output)
#
#     if(torch.argmax(output)==gender.item()):
#         correct+=1
#
#
# print('accuracy:',float(correct)/float(total))


from display import *
from draw import *
import random

screen = new_screen()
color = [105, 190, 105]
matrix = []

'''
#Tests for octants 1/5, 2/6, 4/8, 3/7
add_edge( matrix, 0, YRES - 1, 0, XRES - 1, 75, 0 )
add_edge( matrix, 0, YRES - 1, 0, XRES - 75, 0, 0 )
add_edge( matrix, 0, 0, 0, XRES - 1, YRES - 75, 0 )
add_edge( matrix, 0, 0, 0, XRES - 75, YRES - 1, 0 )
'''

random.seed(17)

for y in range(650):
    add_point(matrix, random.randint(0, YRES), y)
    add_point(matrix, random.randint(0,YRES), random.randint(0, XRES))

draw_lines( matrix, screen, color )

display(screen)


import numpy as np
#need to 'conda install flask' for this to work
from flask import Flask, abort, jsonify, request
import cPickle as pickle

yelp_logreg = pickle.load(open("yelplogit.pkl", "rb"))

app = Flask(__name__)

@app.route('/api', methods=['POST'])
def make_predict():
    #all kinds of error checking should go here
    data = request.get_json(force=True)
    #convert our json to a numpy array
    predict_request = [data['cool'],data['useful'],data['funny']]
    predict_request = np.array(predict_request)
    #np array goes into random forest, prediction comes out
    y_hat = yelp_logreg.predict(predict_request)
    #return our prediction
    output = [y_hat[0]]
    return jsonify(results=output)

if __name__ == '__main__':
    app.run(host='129.101.160.58', port = 5000, debug = True)


"""this module catches the important data from the api call"""
from server.db_connect import conn
from tables.insert_category import categories

class Products:

    def __init__(self, data):
        self.data = data

    def insert_api_data(self, category):
        """
        query to add every caracteristics
        to the products into the Products table
        """

        query = 'INSERT INTO Product'\
            '(product_code, product_name, category_id, product_brand'\
            ',product_net_weight, product_nutrition_grade, '\
            'openfoodfacts_link) VALUES(%s, %s, %s, %s, %s, %s, %s)'

        cursor = conn.cursor()
        my_list = self.data['products']

        for products in my_list:

            arg = (
                products.get(
                    'code', None
                    ),
                products.get(
                    'product_name_fr', 'NA'
                    ),
                str(
                    categories.index(category)+1
                ),
                products.get(
                    'brands', 'ND'
                    ),
                products.get(
                    'quantity', 'ND'
                    ),
                products.get(
                    'nutrition_grade_fr', 'ND'
                    ),
                products.get(
                    'url', None
                    )
            )
            cursor.execute(query, arg)

        conn.commit()
        cursor.close()


import time
import json
import base64
import numpy as np
from PIL import Image
from io import StringIO

import tornado.ioloop
import tornado.web
import cv2

class FallBackHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("404 - Not found")

class FaceDetectHandler(tornado.web.RequestHandler):
    def post(self):
        data = json.loads(self.request.body.decode('utf-8'))

        if not data["image"]:
            self.set_status(400)
            self.write("field 'image' was not informed")
            return

        decoded = base64.b64decode(data["image"])
        nparr = np.fromstring(decoded, dtype=np.uint8)
        img = cv2.imdecode(nparr, cv2.COLOR_BGR2GRAY)
        classifier = cv2.CascadeClassifier("./opencv/data/haarcascades/haarcascade_frontalface_alt.xml")

        scale_factor=1.1
        if "scale_factor" in data:
            scale_factor=data["scale_factor"]

        min_neighbors=1
        if "min_neighbors" in data:
            min_neighbors=data["min_neighbors"]

        min_size=(30,30)
        if "min_size" in data:
            min_size=(data["min_size"]["width"], data["min_size"]["heigth"])

        result = dict()
        time_before_classifier = time.time()
        faces = classifier.detectMultiScale(
                img,
                scaleFactor=scale_factor,
                minNeighbors=min_neighbors,
                minSize=min_size
        )
        time_after_classifier = time.time()

        result_faces = list()
        for (i, face) in enumerate(faces):
            value = dict()
            value["x"] = int(face[0])
            value["y"] = int(face[1])
            value["width"] = int(face[2])
            value["heigth"] = int(face[3])
            result_faces.append(value)

        result["faces"] = result_faces
        result["classifier_time"] = time_after_classifier - time_before_classifier
        result["scale_factor"] = scale_factor
        result["min_neighbors"] = min_neighbors
        result["min_size"] = min_size

        self.set_status(200)
        self.write(json.dumps(result))

def make_app():
    return tornado.web.Application([
        (r"/facedetect", FaceDetectHandler),
        (r".*", FallBackHandler),
    ], autoreload=True,
        debug=True,
        compress_response=True)

if __name__ == "__main__":
    app = make_app()
    app.listen(8080)
    tornado.ioloop.IOLoop.current().start()


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

import time
import psutil
import tensorflow as tf

from time import localtime

def verifyed_model_value():
    """ 이 모듈은 학습된 모델의 메모리 사용량 예측 값의 결과를 검증하는데 사용합니다.
    Args:
        None

    Returns:
        None
    """
    cur_time = str(localtime(time.time()).tm_min) + ":" + "0" + str(localtime(time.time()).tm_sec)

    train_path = str()
    if len(cur_time.split(":")[0]) == 1:
        train_path = "/saved0/saved0.cpkt"
    elif len(cur_time.split(":")[0]) == 2:
        if int(cur_time.split(":")[0][0]) == 1:
            train_path = "/saved1/saved1.cpkt"
        elif int(cur_time.split(":")[0][0]) == 2:
            train_path = "/saved2/saved2.cpkt"
        elif int(cur_time.split(":")[0][0]) == 3:
            train_path = "/saved3/saved3.cpkt"
        elif int(cur_time.split(":")[0][0]) == 4:
            train_path = "/saved4/saved4.cpkt"
        elif int(cur_time.split(":")[0][0]) == 5:
            train_path = "/saved5/saved5.cpkt"

    model_path = "../Models" + train_path

    for _ in range(0, 6):

        print(model_path)

        init = tf.compat.v1.global_variables_initializer()
        sess = tf.compat.v1.Session()
        sess.run(init)

        saver = tf.compat.v1.train.Saver()
        saver.restore(sess, model_path)

        all_process = [x.pid for x in psutil.process_iter()]
        thread_count = 0
        for x in range(0, len(all_process)): thread_count += psutil.Process(pid=all_process[x]).num_threads()
        data = [thread_count]

        # _X1 : 프로세스 ( 1차원 데이터)
        _X1_process = [len(all_process)]
        # _X2 : 쓰레드 수 ( 1차원 데이터)
        _X2_threads = data

        print(_X1_process, _X2_threads)

        memory_usage = psutil.virtual_memory()

        # _X1 과 _X2를 입력 값으로 하여 메모리 사용량 예측하기 위함
        predict_memory_usage = sess.run(H, feed_dict={X1: _X1_process, X2: _X2_threads})

        print("\n Predict :",sess.run(H, feed_dict={X1: _X1_process, X2: _X2_threads}),"Current Usage: [", memory_usage.percent, "]" )
        print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")

if __name__ == '__main__':
    """ Google Style Docstring
    Attributes :
        X1 (tensorflow placeholder) : 텐서플로우 모델에서 전체 프로세스 수를 학습하기 위한 변인입니다.
        X2 (tensorflow placeholder) : 텐서플로우 모델에서 전체 쓰레드 수를 학습하기 위한 변인입니다.

        Y (tensorflow placeholder)  : 텐서플로우 모델에서 메모리 사용량을 학습하기 위한 변입입니다.

        W1 (tensorflow Variable)    : 가설식에서 X1에 적용되는 가중치입니다.
        W2 (tensorflow Variable)    : 가설식에서 X2에 적용되는 가중치입니다.

        H (Hypothesis)              : 선형회귀 모델에 적용할 가설식입니다.

        cost (tensoflow.reduce)     : 선형회귀 모델에서 쓰일 최소 비용 값 입니다.
        optimizer(tensorflow model) : 선형회귀 (경사하강법) 모델로써 learning_rate는 0.000000001 로 주어집니다.

        train(tensorflow minimize)  : optimizer 객체에서 minimize() 메서드를 사용해 최소 비용값을 초기화 합니다.
        init (tensorflow iniailzed) : W1,W2의 .Variable()를 초기화 하는 데 사용합니다.

        sess (tensorflow Session)   : 위에 설정된 tensorflow 속성을 이용하여 tensorflow Sessions을 생성합니다.
    """

    X1 = tf.compat.v1.placeholder(tf.float32, shape=[None])
    X2 = tf.compat.v1.placeholder(tf.float32, shape=[None])

    Y = tf.compat.v1.placeholder(tf.float32, shape=[None])

    W1 = tf.Variable(tf.random_normal([1], seed=1))
    W2 = tf.Variable(tf.random_normal([1], seed=1))

    b = tf.Variable(tf.random_normal([1], seed=1))

    H = (X1 * W1 + X2 * W2) * b

    verifyed_model_value()


import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import vtk
import math
import numpy as np
import time
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
import socket
import traceback
import QtrCalc as QC
#from scipy.spatial.transform import Rotation as R

class vtpDrawScene:
    def SetQuatOrientation_old( self, quaternion, shift, i_actor ): #function to rotate one element around his own origine point
        if not self.iniOk_qt :
            raise Exception("vtpDrawScene not initialized. Call initScene() first")

        # Convert quat to the rotation matrix
        # self.mtxRot =  [[0,0,0],[0,0,0],[0,0,0]]

        #quat = QC.qtr_multiplication(quaternion,self.norm_qtr[i_actor])
        # self.mtxRot[i_actor] = self.modelActor[i_actor].GetMatrix()

        vtk.vtkMath().QuaternionToMatrix3x3(quaternion, self.mtxRot[i_actor])

        # mtxTr01 = self.modelActor[i_actor].GetMatrix()
        # mtx = np.identity(3)

        # for i in range(2):
        #     for j in range(2) :
        #         mtx[i][j] = mtxTr01.GetElement(i, j)

        # norm matrix
        # self.mtxRot[i_actor] = mtx.dot(np.array(self.mtxRot[i_actor])) #np.array(self.mtxRot[i_actor]).dot(np.array(self.norm_mat[i_actor]))
        # Rotation: convert 3x3 to 4x4 matrix
        # mtxTr2 = vtk.vtkMatrix4x4() # identity mtx

        mtxTr2 = vtk.vtkMatrix4x4() # identity mtx
        for i in range(3):
            for j in range(3):
                mtxTr2.SetElement(i, j, self.mtxRot[i_actor][i][j])
        # print(mtxTr02)

        # mtxTr01 = self.modelActor[i_actor].GetMatrix()
        # vtk.vtkMatrix4x4().Multiply4x4(mtxTr01, mtxTr02, mtxTr2)

        # three transforms:
        # 1. move the object so the rotation center is in the coord center
        tr = vtk.vtkTransform()
        origin = np.array(self.modelActor[i_actor].GetOrigin())

        position = np.array(self.modelActor[i_actor].GetPosition())

        # trans = origin
        # trans = origin + position
        trans = position
        # trans = np.array([0.,0.,0.])
        tr.Translate(-trans)
        mtxTr1 = tr.GetMatrix()

        # 2. rotate around coord center using mtxTr2
        mtxTr12 = vtk.vtkMatrix4x4()
        vtk.vtkMatrix4x4().Multiply4x4(mtxTr2, mtxTr1, mtxTr12)

        ## 3. move the object back
        tr = vtk.vtkTransform()

        tr.Translate(trans + np.array(shift))
        mtxTr3 = tr.GetMatrix()
        mtxTr123 = vtk.vtkMatrix4x4()
        vtk.vtkMatrix4x4().Multiply4x4(mtxTr3, mtxTr12, mtxTr123)

        tr = vtk.vtkTransform()
        tr.PreMultiply()
        tr.Concatenate(mtxTr123)
        self.modelActor[i_actor].SetUserTransform(tr)

    def initScene_qt(self, obj): #initialize alll actors
        reader = list()
        modelMapper = list()
        self.modelActor = list()
        self.modelActorsArrows = list()
        self.mtxRot = list()
        self.norm_qtr = list()

        self.pos_set = list()

        self.ren = vtk.vtkRenderer()

        self.mtxGlob = np.array([[1.,0.,0.],[0.,0.,-1.],[0.,1.,0.]])
        # self.mtxGlob[1,1] = 0
        # mtxGlob[2,1] = 1
        # mtxGlob[1,2] = -1
        # mtxGlob[2,2] = 0

        # renCornerR = vtk.vtkRenderer()
        # self.ren.AddRenderer(renCornerR)
        # renCornerR.SetViewport(0.8, 0, 1.0, 0.2)

        for i in range(0,len(obj)):
            # Read the object data
            filename = obj[i]
            if  filename[-4:] != '.vtp':
                continue
            reader.append(vtk.vtkXMLPolyDataReader())
            reader[i].SetFileName(filename)
            reader[i].Update()

            # make mapper for the data
            modelMapper.append(vtk.vtkPolyDataMapper())
            modelMapper[i].SetInputData(reader[i].GetOutput())
            # create actor, set its mapper
            self.modelActor.append(vtk.vtkActor())

            self.modelActor[i].SetMapper(modelMapper[i])
            # Add the actor to the renderer, set the background and size.
            self.ren.AddActor(self.modelActor[i])

            self.mtxRot.append([[1,0,0],[0,1,0],[0,0,1]])
            # Get center of the bounding box
            origin = self.modelActor[i].GetCenter()
            #  Set rotation center
            self.modelActor[i].SetOrigin(origin)

        for i in range(0,len(obj)):

            # make mapper for the data
            arrowSource = vtk.vtkArrowSource()
            arrowSource.SetShaftRadius(0.005)
            arrowSource.SetTipLength(0.5)
            arrowSource.SetTipRadius(0.01)

            # arrowSource = vtk.vtkSphereSource()
            # arrowSource.SetCenter(0,0,0)
            # arrowSource.SetRadius(0.01)

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(arrowSource.GetOutputPort())

            # create actor, set its mapper
            self.modelActorsArrows.append(vtk.vtkActor())

            self.modelActorsArrows[i].SetMapper(mapper)

            self.modelActorsArrows[i].SetScale([0.1,1,1])

            # Add the actor to the renderer, set the background and size.
            if (i != 7) and (i != 8) and (i != 13) and (i != 14) and (i != 15)  and (i != 16) and (i != 23)  and (i != 24) and (i != 27):
                self.ren.AddActor(self.modelActorsArrows[i])

            self.mtxRot.append([[1,0,0],[0,1,0],[0,0,1]])
            # Get center of the bounding box

            origin = self.modelActorsArrows[i].GetCenter()
            self.modelActorsArrows[i].SetOrigin(origin)
            self.pos_set.append(dict())

        #Initial conditions for bones
        self.initial_pos_actors = np.array([[0,0,0],[0,0,0],[0,0,0],[-0.016, -0.006, 0.163],[-0.016, -0.006, -0.163],[-0.01,  -0.312, -0.173],[-0.01,  -0.312, 0.173],[-0.01, 0.024, 0.166],[-0.01, 0.024, -0.166],[0,0,0],[-0.005, -0.296, -0.153],[-0.005, -0.296,  0.153],[ 0.08, -0.42,  0.0  ],[ 0.08,  -0.411,  0.0   ],[ 0.08,  -0.411,  0.0   ],[-0.001, -0.486,  0.072],[-0.001, -0.486,  -0.072],[ 0.027, -0.896, -0.081],[ 0.027, -0.896, 0.081],[ 0.006, -0.888,  0.077],[ 0.006, -0.888,  -0.077],[ 0.008, -1.312,  0.081],[ 0.008, -1.312,  -0.081],[-0.047, -1.358,  0.084],[-0.047, -1.358,  -0.084],[ 0.138, -1.358,  0.087],[ 0.138, -1.358,  -0.087]])
        self.initial_pos_actorsArrows = np.array([[0.063,-0.153,0],[0.062,0.191,0],[-0.019,0.06,0],[-0.016, -0.006, 0.163],[-0.016, -0.006, -0.163],[-0.01,  -0.544, -0.201],[-0.01,  -0.544, 0.201],[-0.01, 0.024, 0.166],[-0.01, 0.024, -0.166],[0,0,0],[-0.005, -0.296, -0.153],[-0.005, -0.296,  0.153],[ 0.06,  -0.400, 0.   ],[ 0.08,  -0.411,  0.   ],[ 0.08,  -0.411,  0.   ],[-0.001, -0.486,  0.072],[-0.001, -0.486,  -0.072],[ 0.041, -0.400,  -0.123],[ 0.041, -0.400,  0.123],[ 0.006, -0.888,  0.077],[ 0.006, -0.888,  -0.077],[ 0.008, -1.312,  0.081],[ 0.008, -1.312,  -0.081],[-0.047, -1.358,  0.084],[-0.047, -1.358,  -0.084],[ 0.138, -1.358,  0.087],[ 0.138, -1.358,  -0.087]])
        #28-9 elems self.initial_pos_actorsArrows = np.array([[0.063,-0.153,0],[0.062,0.191,0],[-0.019,0.06,0],[-0.016, -0.006, 0.163],[-0.016, -0.006, -0.163],[-0.01,  -0.544, -0.201],[-0.01,  -0.544, 0.201],[0,0,0],[-0.005, -0.296, -0.153],[-0.005, -0.296,  0.153],[ 0.06,  -0.400, 0.   ],[ 0.041, -0.400,  -0.123],[ 0.041, -0.400,  0.123],[ 0.006, -0.888,  0.077],[ 0.006, -0.888,  -0.077],[ 0.008, -1.312,  0.081],[-0.047, -1.358,  -0.084],[ 0.138, -1.358,  0.087]])

        for el in range(len(self.initial_pos_actors)):
            # self.norm_qtr.append(np.array([1.,0.,0.,0.]))
            self.modelActor[el].SetPosition(self.initial_pos_actors[el])
            self.modelActorsArrows[el].SetPosition(self.initial_pos_actorsArrows[el])
            self.pos_set[el][0] = self.initial_pos_actorsArrows[el]

        axes = vtk.vtkAxesActor()
        axes.SetNormalizedTipLength(0.05, 0.05, 0.05)
        axes.SetNormalizedShaftLength(1,1,1)
        self.ren.AddActor(axes)

        # arm_axes = vtk.vtkAxesActor()
        # arm_axes.SetNormalizedTipLength(0.05, 0.05, 0.05)
        # arm_axes.SetTotalLength(0.1,0.1,0.1)

        # transform = vtk.vtkTransform()
        # transform.Translate(-0.016,-0.006,-0.162)
        # arm_axes.SetUserTransform(transform)

        # self.ren.AddActor(arm_axes)

        #  The axes are positioned with a user transform
        transform = vtk.vtkTransform()
        transform.Translate(0.0, 0.0, 0.0)
        axes.SetUserTransform(transform)

        self.ren.SetBackground(0.1, 0.2, 0.4)

        camera = vtk.vtkCamera()
        camera.SetPosition(2, 0.2, 2)
        camera.SetFocalPoint(0, 0, 0)
        self.ren.SetActiveCamera(camera)

        # SetInteractorStyle(MyInteractorStyle())
        #ren.ResetCamera()
        # ren.Render()
        self.iniOk_qt = True
        return self.ren

    # def SetQuatOrientation( self, quaternion, shift, i_actor ): #function to rotate one element around his own origine point
    #     if not self.iniOk_qt :
    #         raise Exception("vtpDrawScene not initialized. Call initScene() first")

    #     vtk.vtkMath().QuaternionToMatrix3x3(quaternion, self.mtxRot[i_actor])
    #     # Rotation: convert 3x3 to 4x4 matrix
    #     mtxTr2 = vtk.vtkMatrix4x4() # identity mtx
    #     for i in range(3):
    #         for j in range(3) :
    #             mtxTr2.SetElement(i, j, self.mtxRot[i_actor][i][j])

    def addVector(self,quaternion):
        # make mapper for the data
        arrowSource = vtk.vtkArrowSource()

        arrowSource.SetShaftRadius(0.01)
        arrowSource.SetTipLength(.1)
        # arrowSource.SetNormalizedTipLength(0.05, 0.05, 0.05)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(arrowSource.GetOutputPort())

        # create actor, set its mapper
        self.modelActor.append(vtk.vtkActor())

        el = len(self.modelActor) - 1
        self.modelActor[el].SetMapper(mapper)

        # Add the actor to the renderer, set the background and size.
        self.ren.AddActor(self.modelActor[el])

        #
        self.mtxRot.append([[0,0,0],[0,0,0],[0,0,0]])
        # Get center of the bounding box

        origin = self.modelActor[el].GetCenter()

        #  Set rotation center
        self.modelActor[el].SetOrigin(origin)
        self.modelActor[el].SetPosition([-0.016,-0.006,-0.162])

        mtxRot = np.identity(3)
        vtk.vtkMath().QuaternionToMatrix3x3(quaternion, mtxRot)

        # Rotation: convert 3x3 to 4x4 matrix
        mtxTr = vtk.vtkMatrix4x4() # identity mtx
        for i in range(3):
            for j in range(3) :
                mtxTr.SetElement(i, j, mtxRot[i][j])

        tr = vtk.vtkTransform()
        tr.PreMultiply()
        tr.Concatenate(mtxTr)
        self.modelActor[el].SetUserTransform(tr)

    def SetRefQuatOrientation( self, quaternion, shift, i_actor, motion_flag ): #function to rotate all elements around origine
        if not self.iniOk_qt :
            raise Exception("vtpDrawScene not initialized. Call initScene() first")

        mtxRot = np.identity(3)
        vtk.vtkMath().QuaternionToMatrix3x3(quaternion, mtxRot)

        # rotation in vtk coordinates
        # mtxRot = mtxRot.dot(self.mtxGlob)

        # Rotation: convert 3x3 to 4x4 matrix
        mtxTr = vtk.vtkMatrix4x4() # identity mtx
        for i in range(3):
            for j in range(3) :
                mtxTr.SetElement(i, j, mtxRot[i][j])

        if (motion_flag[0] == 1):

            mtxRot = np.identity(3)
            vtk.vtkMath().QuaternionToMatrix3x3(motion_flag[1], mtxRot)

            # Rotation: convert 3x3 to 4x4 matrix
            mtxTr2 = vtk.vtkMatrix4x4() # identity mtx
            for i in range(3):
                for j in range(3) :
                    mtxTr2.SetElement(i, j, mtxRot[i][j])

            # three transforms:
            # 1. move the object so the rotation center is in the coord center
            tr = vtk.vtkTransform()
            # origin = np.array(self.modelActor[i_actor].GetOrigin()) # use if we need rotation in geometric centre
            position = np.array(self.modelActor[i_actor].GetPosition()) #use if we need rotation in local FOR
            # global_origin = np.array([0.,0.,0.]) #when we need rotation in global FOR
            # trans = origin
            # trans = origin + position
            trans = position
            # trans =  global_origin
            tr.Translate(-trans)
            mtxTr1 = tr.GetMatrix()

            # 2. rotate around coord center using mtxTr2
            mtxTr12 = vtk.vtkMatrix4x4()
            vtk.vtkMatrix4x4().Multiply4x4(mtxTr2, mtxTr1, mtxTr12)

            ## 3. move the object back
            tr = vtk.vtkTransform()
            tr.Translate(trans + np.array(shift))

            mtxTr3 = tr.GetMatrix()
            mtxTr123 = vtk.vtkMatrix4x4()
            vtk.vtkMatrix4x4().Multiply4x4(mtxTr3, mtxTr12, mtxTr123)
            # print('step 3', mtxTr)

            mtxTr0 = mtxTr
            mtxTr = vtk.vtkMatrix4x4()
            vtk.vtkMatrix4x4().Multiply4x4(mtxTr0, mtxTr123, mtxTr)

        tr = vtk.vtkTransform()
        tr.PreMultiply()
        tr.Concatenate(mtxTr)
        self.modelActor[i_actor].SetUserTransform(tr)

    def SetRefQuatOrientation_arrowshow( self, quaternion, shift, i_actor, motion_flag, ti, qtr_data ): #function to rotate all elements around origine
        if not self.iniOk_qt :
            raise Exception("vtpDrawScene not initialized. Call initScene() first")

        mtxRot = np.identity(3)
        vtk.vtkMath().QuaternionToMatrix3x3(quaternion, mtxRot)

        # Rotation: convert 3x3 to 4x4 matrix
        mtxTr = vtk.vtkMatrix4x4() # identity mtx
        for i in range(3):
            for j in range(3) :
                mtxTr.SetElement(i, j, mtxRot[i][j])

        if (motion_flag[0] == 1):
            mtxRot = np.identity(3)
            vtk.vtkMath().QuaternionToMatrix3x3(motion_flag[1], mtxRot)

            # Rotation: convert 3x3 to 4x4 matrix
            mtxTr2 = vtk.vtkMatrix4x4() # identity mtx
            for i in range(3):
                for j in range(3):
                    mtxTr2.SetElement(i, j, mtxRot[i][j])

            # three transforms:
            # 1. move the object so the rotation center is in the coord center
            tr = vtk.vtkTransform()
            # origin = np.array(self.modelActor[i_actor].GetOrigin()) # use if we need rotation in geometric centre

            # global_origin = np.array([0.,0.,0.]) #when we need rotation in global FOR
            # trans = origin
            # trans = origin + position

            position = np.array(self.modelActorsArrows[i_actor].GetPosition()) #use if we need rotation in local FOR
            trans = position

            # trans =  global_origin
            tr.Translate(-trans)
            mtxTr1 = tr.GetMatrix()

            # 2. rotate around coord center using mtxTr2
            mtxTr12 = vtk.vtkMatrix4x4()
            vtk.vtkMatrix4x4().Multiply4x4(mtxTr2, mtxTr1, mtxTr12)

            ## 3. move the object back
            tr = vtk.vtkTransform()
            tr.Translate(trans + np.array(shift))

            # self.pos_set[i_actor][ti] = position + shift

            mtxTr3 = tr.GetMatrix()
            mtxTr123 = vtk.vtkMatrix4x4()
            vtk.vtkMatrix4x4().Multiply4x4(mtxTr3, mtxTr12, mtxTr123)

            mtxTr0 = mtxTr
            mtxTr = vtk.vtkMatrix4x4()
            vtk.vtkMatrix4x4().Multiply4x4(mtxTr0, mtxTr123, mtxTr)

        tr = vtk.vtkTransform()
        tr.PreMultiply()
        tr.Concatenate(mtxTr)

        temp = tr.GetMatrix()
        temp = list(self.initial_pos_actorsArrows[i_actor])
        temp.append(0.0)

        depth_der = [512,424]
        color_der = [1920,1080]
        temp_pos = tr.GetMatrix().MultiplyPoint(temp)
        temp_depth = [temp_pos[0]*depth_der[0]/2 + depth_der[0]/2, temp_pos[2]*depth_der[1] + depth_der[1]/2]
        temp_color = [temp_pos[0]*color_der[0]/2 + color_der[0]/2, temp_pos[2]*color_der[1] + color_der[1]/2]
        temp_orientation = qtr_data

        trackingState = 0
        self.pos_set[i_actor][ti] = list(np.hstack((temp_pos,temp_depth,temp_color,temp_orientation)))
        # self.pos_set[i_actor][ti] = np.array(self.modelActorsArrows[i_actor].GetPosition())
        self.modelActorsArrows[i_actor].SetUserTransform(tr)

    def __init__(self):
        self.iniOk = False

    # def __del__(self):
    #     self.ren.Finalize()

    def init_pos_actor( self, i_actor, mov):
        # if not self.iniOk :
        #     raise Exception("vtpDrawScene not initialized. Call initScene() first")
        # set initial pos for hands

        # real_pos = np.array(self.modelActor[i_actor].GetPosition())
        # new_pos = real_pos + mov
        # self.modelActor[i_actor].SetPosition(new_pos)

        real_pos = np.array(self.modelActorsArrows[i_actor].GetPosition())
        new_pos = real_pos + mov
        self.modelActorsArrows[i_actor].SetPosition(new_pos)

        print(new_pos)

        # self.renWin.Render()
    # def reInitialize_actors(self, qtr):
    #     for el in range(len(self.modelActor)):
    #         # get matrix from vtk obj
    #         elemmtx = self.modelActor[el].GetMatrix()
    #         # temp_2 = np.array([0.,0.,0.,0.])
    #         # vtk.vtkMath().Matrix3x3ToQuaternion(self.modelActor[el].GetMatrix(), temp_2)
    #         temp = self.getRotFromVtkMtx(elemmtx)
    #         # print(temp_3, " ", temp_2)
    #         # get rotation that bring element in visualization to initial
    #         temp0 = QC.qtr_un_calculus(qtr,temp.as_quat())
    #         self.norm_qtr[el] = temp0
    #         #print(str(temp.as_quat()) + ' == ' + str(QC.qtr_multiplication(qtr,temp0)))

    # def getRotFromVtkMtx(self, vtkMtx):
    #     rotMtx = np.zeros((3,3))
    #     for i in range(3):
    #         for j in range(3):
    #             rotMtx[i, j] = vtkMtx.GetElement(i, j)
    #     # get rotation from matrix
    #     rot = R.from_dcm(rotMtx)

    # Автоматическое включение нужной сети
    # масштабирование сегментов
    # При отключении датчика увод его на перезагрузку
    # проверять закрытие сокетов и деструкторов
    # автоматическое кадрирование
    # оптимизация длинны звеньев
    #


# import the lib
import numpy as np
import pandas as pd
import random
import matplotlib as mpl
import matplotlib.pyplot as plt

# read the dataser iris
data = pd.read_csv('iris.data',header=None)

# set the seed
random.seed(17)

# mapping dataset
data[4] = data[4].map({'Iris-setosa':0,
                           'Iris-versicolor':1,
                           'Iris-virginica':2})

"""
process the dataset
"""
#Extract the data for each category
t0 = data[data[4] == 0]
t1 = data[data[4] == 1]
t2 = data[data[4] == 2]

# random the data
data = data.values
np.random.shuffle(data)

# test train verify data and use 5 cross validation

verify_1 =  data[0:30]
verify_2 =  data[30:60]
verify_3 =  data[60:90]
verify_4 =  data[90:120]
verify_5 =  data[120:150]

t0 = np.mat(t0)
t1 = np.mat(t1)
t2 = np.mat(t2)

train_0 = t0[0:30,:-1]
train_1 = t1[0:30,:-1]
train_2 = t2[0:30,:-1]
np.random.shuffle(train_0)
np.random.shuffle(train_1)
np.random.shuffle(train_2)

verify_1_X = verify_1[0:30,:-1]
verify_1_Y = verify_1[0:30,-1]
verify_2_X = verify_2[0:30,:-1]
verify_2_Y = verify_2[0:30,-1]
verify_3_X = verify_3[0:30,:-1]
verify_3_Y = verify_3[0:30,-1]
verify_4_X = verify_4[0:30,:-1]
verify_4_Y = verify_4[0:30,-1]
verify_5_X = verify_5[0:30,:-1]
verify_5_Y = verify_5[0:30,-1]

"""
calculate
"""

# calculate ∅
def get_phi(x, xi, h):
    phi = 0
    x = np.mat(x)

    xi = np.mat(xi)
    phi =  np.exp(-(x - xi) * (x - xi).T / (2 * h * h))

    return phi

# Calculate the overall formula
def get_px(x, xi, h):
    px = 0
    phi = 0

    for T_t in xi:
        phi += get_phi(x, T_t, h)

    px = phi  / ( len(xi) * np.power(h, 3))

    return px

# Parzen
def parzen(h, test):

    # Define an array for comparison
    px_0 = []
    px_1 = []
    px_2 = []
    result = []
    result_X = []

    for x in test:

        # Calculate the distance separately
        px_0 = get_px(x, train_0,h)
        px_1 = get_px(x, train_1, h)
        px_2 = get_px(x, train_2, h)

        # Find the largest index and sort
        result_X = np.argmax([px_0, px_1, px_2])
        result.append(result_X)

    return result

result_re_1 = []
result_re_2 = []
result_re_3 = []
result_re_4 = []
result_re_5 = []
aaa = []
result = []

for h in np.arange(0.1, 1, 0.01):

    """
    Calculate the accuracy of each cross-validation
    """
    test = verify_1_X
    t = parzen(h, test)
    t = np.array(t)
    result_re_1.append(np.sum(t == verify_1_Y.T) / len(t))

    test = verify_2_X
    t = parzen(h, test)
    t = np.array(t)
    result_re_2.append(np.sum(t == verify_2_Y.T) / len(t))

    test = verify_3_X
    t = parzen(h, test)
    t = np.array(t)
    result_re_3.append(np.sum(t == verify_3_Y.T) / len(t))

    test = verify_4_X
    t = parzen(h, test)
    t = np.array(t)
    result_re_4.append(np.sum(t == verify_4_Y.T) / len(t))

    test = verify_5_X
    t = parzen(h, test)
    t = np.array(t)
    result_re_5.append(np.sum(t == verify_5_Y.T) / len(t))

aaa = np.vstack((result_re_1,result_re_2,result_re_3,result_re_4,result_re_5))

for  i in range(40):
    bbb = 0
    bbb = aaa[0,i]+aaa[1,i]+aaa[2,i]+aaa[3,i]+aaa[4,i]
    result.append(bbb/5)

# Calculate the final accuracy rate and save it in the array
aaa = np.vstack((result_re_1,result_re_2,result_re_3,result_re_4,result_re_5))

for  i in range(40):
    bbb = 0
    bbb = aaa[0,i]+aaa[1,i]+aaa[2,i]+aaa[3,i]+aaa[4,i]
    result.append(bbb/5)

plt.title('Parzen Windows with cross-fold validation')
plt.plot(result)
plt.xlabel("h")
plt.ylabel("accuracy")
plt.show


def collatz(i):
    if i % 2 == 0:
        # if i is even...
        return i // 2
    else:
        # otherwise, it's odd, and...
        return 3 * i + 1

s = input('Enter an integer: ')
try:
    # if this statement...
    i = int(s)
except ValueError:
    # throws a ValueError exception
    print('You must enter an integer.')
else:
    # otherwise...
    while i != 1:
        print(i)
        i = collatz(i)
    print(i)


"""Messages for AMQP
"""
from . import spec
from amqpy.serialization import AMQPReader, AMQPWriter

__all__ = ['Message']

class GenericContent:
    """Base class for AMQP content

    Subclasses should override :attr:`PROPERTIES`.
    """
    PROPERTIES = []

    def __init__(self, properties):
        """Save the properties appropriate to this AMQP content type in a 'properties' dictionary

        :param dict properties: content properties
        """
        #: Content properties
        #:
        #: :type: dict[str, str|dict]
        self.properties = properties

    def __eq__(self, other):
        """Check if this object has the same properties as another content object
        """
        return self.properties == other.properties

    def load_properties(self, raw_bytes):
        """Load raw bytes into :attr:`self.properties`

        The `raw_bytes` are the payload of a `FrameType.HEADER` frame, starting at a byte-offset
        of 12.
        """
        r = AMQPReader(raw_bytes)

        # read 16-bit shorts until we get one with a low bit set to zero
        flags = []
        while True:
            flag_bits = r.read_short()
            flags.append(flag_bits)
            if flag_bits & 1 == 0:
                break

        shift = 0
        d = {}
        flag_bits = None
        for key, proptype in self.PROPERTIES:
            if shift == 0:
                if not flags:
                    break
                flag_bits, flags = flags[0], flags[1:]
                shift = 15
            if flag_bits & (1 << shift):
                d[key] = getattr(r, 'read_' + proptype)()
            shift -= 1

        self.properties = d

    def serialize_properties(self):
        """Serialize :attr:`self.properties` into raw bytes suitable to append to the payload of
        `FrameType.HEADER` frames
        """
        shift = 15
        flag_bits = 0
        flags = []
        raw_bytes = AMQPWriter()
        for key, proptype in self.PROPERTIES:
            val = self.properties.get(key, None)
            if val is not None:
                if shift == 0:
                    flags.append(flag_bits)
                    flag_bits = 0
                    shift = 15

                flag_bits |= (1 << shift)
                if proptype != 'bit':
                    getattr(raw_bytes, 'write_' + proptype)(val)

            shift -= 1

        flags.append(flag_bits)
        result = AMQPWriter()
        for flag_bits in flags:
            result.write_short(flag_bits)
        result.write(raw_bytes.getvalue())

        return result.getvalue()

class Message(GenericContent):
    """A Message for use with the `Channel.basic_*` methods
    """
    CLASS_ID = spec.Basic.CLASS_ID

    # instances of this class have these attributes, which are passed back and forth as message
    # properties between client and server
    PROPERTIES = [
        ('content_type', 'shortstr'),
        ('content_encoding', 'shortstr'),
        ('application_headers', 'table'),
        ('delivery_mode', 'octet'),
        ('priority', 'octet'),
        ('correlation_id', 'shortstr'),
        ('reply_to', 'shortstr'),
        ('expiration', 'shortstr'),
        ('message_id', 'shortstr'),
        ('timestamp', 'timestamp'),
        ('type', 'shortstr'),
        ('user_id', 'shortstr'),
        ('app_id', 'shortstr'),
        ('cluster_id', 'shortstr')
    ]

    def __init__(self, body='', channel=None, **properties):
        """
        If `body` is a `str`, then `content_encoding` will automatically be set to 'UTF-8', unless
        explicitly specified.

        Example::

            msg = Message('hello world', content_type='text/plain', application_headers={'foo': 7})

        :param body: message body
        :param channel: associated channel
        :param properties:
            * content_type (shortstr): MIME content type
            * content_encoding (shortstr): MIME content encoding
            * application_headers: (table): Message header field table:
              dict[str, str|int|Decimal|datetime|dict]
            * delivery_mode: (octet): Non-persistent (1) or persistent (2)
            * priority (octet): The message priority, 0 to 9
            * correlation_id (shortstr) The application correlation identifier
            * reply_to (shortstr) The destination to reply to
            * expiration (shortstr): Message expiration specification
            * message_id (shortstr): The application message identifier
            * timestamp (datetime.datetime): The message timestamp
            * type (shortstr): The message type name
            * user_id (shortstr): The creating user id
            * app_id (shortstr): The creating application id
            * cluster_id (shortstr): Intra-cluster routing identifier
        :type body: bytes or str
        :type channel: amqpy.channel.Channel
        """
        super().__init__(properties)

        #: Message body (bytes or str)
        self.body = body

        #: Associated channel, set after receiving a message (amqpy.channel.Channel)
        self.channel = channel

        #: Delivery info, set after receiving a message (dict)
        self.delivery_info = {}

        if isinstance(body, str):
            self.properties['content_encoding'] = properties.get('content_encoding', 'UTF-8')

    def __eq__(self, other):
        """Check if the properties and bodies of this Message and another Message are the same

        Received messages may contain a 'delivery_info' attribute, which isn't compared.
        """
        try:
            return super().__eq__(other) and self.body == other.body
        except AttributeError:
            return False

    @property
    def application_headers(self):
        """Get application headers

        :return: application headers
        :rtype: dict
        """
        return self.properties.get('application_headers')

    @property
    def delivery_tag(self):
        """Get delivery tag

        :return: delivery tag
        :rtype: int
        """
        return self.delivery_info.get('delivery_tag')

    def ack(self):
        """Acknowledge message

        This is a convenience method which calls :meth:`self.channel.basic_ack()`
        """
        dt = self.delivery_tag
        if dt is not None:
            self.channel.basic_ack(dt)
        else:
            raise Exception('No delivery tag')

    def reject(self, requeue):
        """Reject message

        This is a convenience method which calls :meth:`self.channel.basic_reject()`

        :param bool requeue: requeue if True else discard the message
        """
        dt = self.delivery_tag
        if dt is not None:
            self.channel.basic_reject(dt, requeue)
        else:
            raise Exception('No delivery tag')


#!/usr/bin/python3
"""
W3C validator for a software development program

For HTML and CSS files.

Based on 2 APIs:

- https://validator.w3.org/nu/
- http://jigsaw.w3.org/css-validator/validator

Usage:

Simple file:

```
./w3c_validator.py index.html
```

Multiple files:

```
./w3c_validator.py index.html header.html styles/common.css
```

All errors are printed in `STDERR`

Return:
Exit status is the # of errors, 0 on Success

References

https://developer.mozilla.org/en-US/

"""
import sys
import requests

def __print_stdout(msg):
    """Print message in STDOUT
    """
    sys.stdout.write(msg)

def __print_stderr(msg):
    """Print message in STDERR
    """
    sys.stderr.write(msg)

def __analyse_html(file_path):
    """Start analyse of HTML file
    """
    h = {'Content-Type': "text/html; charset=utf-8"}
    d = open(file_path, "rb").read()
    u = "https://validator.w3.org/nu/?out=json"
    r = requests.post(u, headers=h, data=d)
    res = []
    messages = r.json().get('messages', [])
    for m in messages:
        res.append("[{}:{}] {}".format(file_path, m['lastLine'], m['message']))
    return res

def __analyse_css(file_path):
    """Start analyse of CSS file
    """
    d = {'output': "json"}
    f = {'file': (file_path, open(file_path, 'rb'), 'text/css')}
    u = "http://jigsaw.w3.org/css-validator/validator"
    r = requests.post(u, data=d, files=f)
    res = []
    errors = r.json().get('cssvalidation', {}).get('errors', [])
    for e in errors:
        res.append("[{}:{}] {}".format(file_path, e['line'], e['message']))
    return res

def __analyse(file_path):
    """Start analyse of a file and print the result
    """
    nb_errors = 0
    try:
        result = None
        if file_path.endswith('.css'):
            result = __analyse_css(file_path)
        else:
            result = __analyse_html(file_path)

        if len(result) > 0:
            for msg in result:
                __print_stderr("{}\n".format(msg))
                nb_errors += 1
        else:
            __print_stdout("{}: OK\n".format(file_path))

    except Exception as e:
        __print_stderr("[{}] {}\n".format(e.__class__.__name__, e))
    return nb_errors

def __files_loop():
    """Loop that analyses for each file from input arguments
    """
    nb_errors = 0
    for file_path in sys.argv[1:]:
        nb_errors += __analyse(file_path)

    return nb_errors

if __name__ == "__main__":
    """Main
    """
    if len(sys.argv) < 2:
        __print_stderr("usage: w3c_validator.py file1 file2 ...\n")
        exit(1)

    """execute tests, then exit. Exit status = # of errors (0 on success)
    """
    sys.exit(__files_loop())


from django.conf.urls import url
from . import views

app_name = 'shop'

urlpatterns = [
  url('^$', views.product_list, name='product_list'),
  url(r'^add_product/$', views.AddProduct.as_view(), name='add_product'),
  url('^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'),
  url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'),
  url(r'^api/category/$', views.CategoryList.as_view(), name='list_category_api'),
  url(r'^api/category/(?P<category_slug>[-\w]+)/(?P<pk>[0-9]+)/$', views.CategoryDetail.as_view(), name='detail_category_api'),
  url(r'^api/product/$', views.ProductList.as_view(), name='list_product_api'),
  url(r'^api/product/(?P<pk>\d+)/(?P<slug>[-\w]+)/$', views.ProductDetail.as_view(), name='detail_product_api'),
]


class Solution:
    def Fibonacci(self, n):
        # write code here

        # # 递归
        # if n <= 1:
        #     return n
        # return self.Fibonacci(n-1) + self.Fibonacci(n-2)

        if n <= 1:
            return n
        a = 0
        b = 1
        for i in range(n):
            temp = b
            b = a + b
            a = temp
        return a

if __name__ == '__main__':
    print(Solution().Fibonacci(4))


#import multiprocessing as mp
#import logging
import socket
import time
import signal
import errno
import os
import threading
import subprocess
import sys
import eventlet

from datetime import datetime
from collections import namedtuple
from pathlib import Path
from threading import Lock

#thread_lock = Lock()

MaxProcesses = 20
Processes = []

SERVER_ADDRESS = (HOST, PORT) = '', 9100
REQUEST_QUEUE_SIZE = 1024
#logger = mp.log_to_stderr(logging.DEBUG)

def _handle_timeout(signum, frame):
    raise TimeoutError
def get_date():
    now = datetime.now()
    curr_date = now.strftime("%c") + ' (GMT+3)'
    return curr_date

def grim_reaper(signum, frame):
    while True:
        try:
            pid, status = os.waitpid(
                -1,
                 os.WNOHANG
            )
        except OSError as e:
            return

        if pid == 0:
            return

META = namedtuple('META', [
    'method',
    'path',
    'query_string',
    'http_version',
    'headers',
    'user_agent',
])

def chunks(f):
    while True:
        data = f.read(65536)
        if not data:
            break
        yield data

class RESP_METH:
    response_phrases = {
        b'200': b'OK',
        b'400': b'Bad Request',
        b'404': b'Not Found',
        b'408': b'Request Timeout',
        b'500': b'Internal Server Error',
        b'502': b'Bad Gateway',
        b'503': b'Service Unavailable',
        b'413': b'Request Entity Too Large',
    }

def set_environment(*args, **kwargs):
    try:
        SERVER_PROTOCOL = kwargs['protocol']
        os.environ['SERVER_PORT'] = kwargs.get('server_port', '')
        os.environ['REQUEST_METHOD'] = kwargs.get('protocol','')
        os.environ['QUERY_STRING'] = kwargs.get('arguments', '')
        os.environ['SCRIPT_NAME'] = kwargs.get('path', '')
        os.environ['CONTENT_TYPE'] = kwargs.get('headers').get(b'Content-Type',b'').decode('utf-8')
        os.environ['CONTENT_LENGTH'] = kwargs.get('headers').get(b'Content-Length',b'').decode('utf-8')
        os.environ['REMOTE_ADDR'] = kwargs.get('client_address', '')
        os.environ['HTTP_ACCEPT'] = kwargs.get('headers').get(b'Accept',b'').decode('utf-8')
    except Exception as e:
        print(e)
        # exc_type, exc_obj, exc_tb = sys.exc_info()
        # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        # logging.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))

def parse_http_request(request):
    try:
        assert len(request) == 2,"Bad request"
        split_response = request
        start_line_and_headers = split_response[0].split(b'\r\n')
        assert len(start_line_and_headers) > 0,"Bad length for start_line_and_headers"
        request_line = start_line_and_headers[0]
        start_line_parts = request_line.split(b' ')
        assert len(start_line_parts) == 3
        method = start_line_parts[0]
        path = start_line_parts[1].decode()
        assert isinstance(path, str)
        if '?' in path:
            target_query_part = path.split('?', 1)[1]
            if len(target_query_part) > 0:
                query_string = target_query_part
            else:
                query_string = ''
        else:
            query_string = ''
        headers = {}
        for header_field in start_line_and_headers[1:]:
            header_field_split = header_field.split(b':', 1)
            field_name = header_field_split[0]
            field_value = header_field_split[1].strip()
            headers[field_name] = field_value
        if method == b'POST':
            body = split_response[1]

        else:
            body = b''
        if 'User-Agent' in headers:
            user_agent = headers['User-Agent']
        else:
            user_agent = None
        result = META(
            method=method,
            path=path.split('?', 1)[0],
            headers=headers,
            query_string=query_string,
            http_version=start_line_parts[2],
            user_agent=user_agent,
        )

        return [result,body]
    except Exception as e:
        print(e)
        # exc_type, exc_obj, exc_tb = sys.exc_info()
        # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        # print(e, fname, exc_tb.tb_lineno)
        return None

def gen_res(status_code, headers={}, body=b''):
    result = (b'HTTP/1.0 ' + status_code + b' ' +
              RESP_METH.response_phrases[status_code])
    assert len(headers)>0
    for field_name, field_value in headers.items():
        if field_name != b'Connection':
            result += (b'\r\n' + field_name + b': ' + field_value)

    result += (b'\r\n\r\n' + body)
    return result

def recvall(sock):
    try:
        BUFF_SIZE = 8192
        while True:
            part = sock.recv(BUFF_SIZE)
            if b'\r\n\r\n' in part:
                headers = part.split(b'\r\n\r\n', 1)[0]
                body =  part.split(b'\r\n\r\n', 1)[1]
                return [headers,body]
            else:
                return 1
    except Exception as e:
        return -1

def CheckRunning():
   global Processes
   try:
       for p in reversed(range(len(Processes))):
          if Processes[p].poll() is not None:
             del Processes[p]
   except:
       pass

def handle_request(client_connection,client_address):
    global Processes
    client_connection.settimeout(10)
    request = recvall(client_connection)
    assert isinstance(request,(list,int))
    if request == -1:
        return
    elif request == 1:
        code_response(b'413',client_connection)
        return
    parsed_request = parse_http_request(request)
    if parsed_request == None:
        try:
            code_response(b'501',client_connection)
            #if len(client_writer.get_extra_info('peername')[0])>0:
                #logger.warning("Client: {} Error with request".format(client_writer.get_extra_info('peername')[0]))
            return
        except Exception as e:
            print(e)
            #logger.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))
            return
    res = gen_res(b'200',parsed_request[0].headers,parsed_request[1])
    assert isinstance(res,(bytes, bytearray))
    try:
        path =  Path("./{path}".format(path=parsed_request[0].path))
        assert isinstance(path,Path)
        ext = Path("./{path}".format(path=parsed_request[0].path)).suffix
        assert isinstance(ext,str)
    except Exception as e:
        print(e)
        # exc_type, exc_obj, exc_tb = sys.exc_info()
        # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        # logging.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))

    if path.exists():
        if path.is_dir():
            try:
                if parsed_request[0].method==b'GET':
                    try:
                        send_file(res,"/index.html",client_connection)
                    except Exception as e:
                        print(e)
                        code_response(b'501',client_connection)
                        #else:
                            #logging.debug("Client: {}, User-Agent: {}".format(client_address[0],parsed_request[0].headers[b'User-Agent'].decode('utf-8')))
                            #logging.info("Client IP Address: {}, File Extension: {}, Method: {}, Path: {}".format(client_address[0],ext,parsed_request[0].method.decode('utf-8'),parsed_request[0].path))
            except Exception as e:
                print(e)
                # exc_type, exc_obj, exc_tb = sys.exc_info()
                # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                # logging.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))
        if path.is_file():
            if str(path).startswith("cgi-bin") and ext == '.py':
                executable = sys.executable
                assert isinstance(executable,str)
                if executable:
                    try:
                        assert len(parsed_request) == 2
                        assert isinstance(parsed_request[0].headers,dict)
                        assert len(client_address) == 2
                        set_environment(headers = parsed_request[0].headers,
                        arguments = parsed_request[0].query_string,
                        path=str(path),
                        protocol=parsed_request[0].http_version.decode('utf-8'),
                        client_address=client_address[0],
                        server_port='9100'
                        )
                    except Exception as e:
                        print(e)
                        # exc_type, exc_obj, exc_tb = sys.exc_info()
                        # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                        # logging.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))
                    script_args = [executable,str(path)]
                    while (len(Processes) >= MaxProcesses):
                        CheckRunning()

                    process = subprocess.Popen(script_args, stdin=subprocess.PIPE,
                                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    Processes.append(process)
                    try:
                        if parsed_request[0].method == b'POST':
                            if parsed_request[1] != b'':
                                process.stdin.write(parsed_request[1])
                            if int(parsed_request[0].headers[b'Content-Length'].decode('utf-8')) - len(request[1]) > 0:
                                while True:
                                    part = client_connection.read(8192)
                                    if len(part) < 8192:
                                        break
                                    process.stdin.write(part)
                                    process.stdin.flush()
                            line = None
                            data = 'HTTP/1.0 200 OK\rDate: {}\rConnection: keep-alive\r'.format(get_date()).encode()
                            client_connection.send(data)
                            try:
                                stdout, stderr = process.communicate(timeout = 15)
                                client_connection.send(stdout)
                                client_connection.close()
                            except Exception as e:
                                print(e)
                                process.kill()

                            # for line in process.stdout:
                            #     client_connection.send(line)
                            # if line == None:
                            #     return
                            #else:
                                #logging.debug("Client: {}, User-Agent: {}".format(client_address[0],parsed_request[0].headers[b'User-Agent'].decode('utf-8')))
                                #ogging.info("Client IP Address: {}, File Extension: {}, Method: {}, Path: {}, Body: {}".format(client_address[0],ext,parsed_request[0].method.decode('utf-8'),parsed_request[0].path,parsed_request[1]))

                        elif parsed_request[0].method == b'GET':
                            line = None
                            data = 'HTTP/1.0 200 OK\rDate: {}\rConnection: keep-alive\r'.format(get_date()).encode()
                            client_connection.send(data)
                            stdout, stderr = process.communicate(timeout = 15)
                            client_connection.send(stdout)
                            client_connection.close()

                            if line == None:
                                return
                            else:
                                pass
                                #logging.info("Client IP Address: {}, File Extension: {}, Method: {}, Path: {}, Query: {}".format(client_address[0],ext,parsed_request[0].method.decode('utf-8'),parsed_request[0].path,parsed_request[0].query_string))
                                #logging.debug("Client: {}, User-Agent: {}".format(client_address[0],parsed_request[0].headers[b'User-Agent'].decode('utf-8')))
                        else:
                            return
                    except TimeoutError:
                            code_response(b'408',client_connection)
                            return

                        # exc_type, exc_obj, exc_tb = sys.exc_info()
                        # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                        # logging.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))
            else:
                try:
                    send_file(res,parsed_request[0].path,client_connection)
                        #if chunk != None:
                            #logging.debug("Client: {}, User-Agent: {}".format(client_address[0],parsed_request[0].headers[b'User-Agent'].decode('utf-8')))
                            #logging.info("Client IP Address: {}, File Extension: {}, Method: {}, Path: {}".format(client_address[0],ext,parsed_request[0].method.decode('utf-8'),parsed_request[0].path))
                except Exception as e:
                    print(e)
                    return
                    # exc_type, exc_obj, exc_tb = sys.exc_info()
                    # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                    # logging.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))
    else:
        try:
            code_response(b'404',client_connection)
            #logging.warning("Client: {} Requested Non Existent File\Path: {}".format(client_address[0],parsed_request[0].path))
        except Exception as e:
            print(e)
            # exc_type, exc_obj, exc_tb = sys.exc_info()
            # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            # logging.error("{} {} {} ".format(e, fname, exc_tb.tb_lineno))

def worker(serversocket):
    while True:
        client_connection, client_address = serversocket.accept()
        #logger.debug("{u} connected".format(u=client_address))
        #thread_lock.acquire()
        handle_request(client_connection,client_address)
        #thread_lock.release()
        #client_connection.send(b"OK")
        client_connection.close()

def code_response(status_code,client_connection):
    response = "HTTP/1.0 {0} {1}\r\n".format(status_code.decode('utf-8'),RESP_METH.response_phrases[status_code].decode())+"\r\n\r\nError {0} \r\n{1}".format(status_code.decode('utf-8'),RESP_METH.response_phrases[status_code].decode())
    client_connection.sendall(response.encode())
    client_connection.close()

def send_file(res,path,client_connection):
    client_connection.send(res)
    with open("."+path, "rb") as f:
        for chunk in chunks(f):
            client_connection.send(chunk)
    client_connection.close()

def serve_forever():
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.bind(SERVER_ADDRESS)
    serversocket.listen(REQUEST_QUEUE_SIZE)

    signal.signal(signal.SIGCHLD, grim_reaper)
    try:
        pool = eventlet.GreenPool(size=5)
        for _ in range(5):
            pool.spawn_n(worker, serversocket)
    except Exception as e:
        print(e)

    while True:
        try:
            eventlet.sleep()
        except:
            break

if __name__ == '__main__':
    serve_forever()