import colorio
import math
from tabulate import tabulate

def ch_to_a(chroma, hue):
    return chroma * (math.cos(math.radians(hue)))

def ch_to_b(chroma, hue):
    return chroma * (math.sin(math.radians(hue)))

def jch_to_lab(jch):
    in_lightness, in_chroma, in_hue = jch

    a_coord = ch_to_a(in_chroma, in_hue)
    b_coord = ch_to_b(in_chroma, in_hue)

    jab = [in_lightness, a_coord, b_coord]

    return jab

def prompt_jch_to_ciecam16ucs():
    L_A = 64 / math.pi / 5
    cam16ucs = colorio.cs.CAM16UCS(0.69, 20, L_A)

    in_lightness = int(input("Lightness: "))
    in_chroma = int(input("Chroma: "))
    in_hue = int(input("Hue: "))

    in_jch = [in_lightness, in_chroma, in_hue]

    print(cam16ucs.to_rgb255(jch_to_lab(in_jch)))

def jch_diff(jch1, jch2):
    jab1 = jch_to_lab(jch1)
    jab2 = jch_to_lab(jch2)

    diff = jab_diff(jab1, jab2)

    return diff

def jab_diff(jab1, jab2):
    in_j1, in_a1, in_b1 = jab1
    in_j2, in_a2, in_b2 = jab2

    diff = math.sqrt((in_j2 - in_j1)**2 + (in_a2 - in_a1)**2 + (in_b2 - in_b1)**2)

    return diff

def prompt_color_diff():
    option = input("Jch or Jab input?\n\t1. Jch\n\t2. Jab\n")
    print("")

    in_j1 = int(input("J1: "))
    if option == "1":
        in_1_1 = float(input("c1: "))
        in_2_1 = float(input("h1: "))
    elif option == "2":
        in_1_1 = float(input("a1: "))
        in_2_1 = float(input("b1: "))
    color1 = [in_j1, in_1_1, in_2_1]

    in_j2 = int(input("J2: "))
    if option == "1":
        in_1_2 = float(input("c2: "))
        in_2_2 = float(input("h2: "))
    elif option == "2":
        in_1_2 = float(input("a2: "))
        in_2_2 = float(input("b2: "))
    color2 = [in_j2, in_1_2, in_2_2]

    if option == "1":
        print(jch_diff(color1, color2))
    elif option == "2":
        print(jab_diff(color1, color2))

def generate_palette():
    L_A = 64 / math.pi / 5
    cam16ucs = colorio.cs.CAM16UCS(0.69, 20, L_A)

    grey_range       = int(input("# of Greys: "))
    if (grey_range > 0):
        min_lightness    = float(input("Greys min lightness: "))
        max_lightness    = float(input("Greys max lightness: "))
    accent_range     = int(input("# of Accents: "))
    if (accent_range > 0):
        hue_offset    = input("Custom hue offset: ")
        if (hue_offset == ""):
            hue_offset = (360 / accent_range / 2)
        else:
            hue_offset = float(hue_offset)
        accent_lightness = float(input("Accents lightness: "))
        accent_chroma    = float(input("Accents chroma: "))

    table_result     = [["Name", "J", "h", "R", "G", "B", "a*", "b*"]]

    for g in range(grey_range):
        current_lightness = (max_lightness - min_lightness) / (grey_range - 1) * g + min_lightness
        derived_jch       = [current_lightness, 0, 0]
        result            = cam16ucs.to_rgb255(jch_to_lab(derived_jch))
        result_r          = result[0]
        result_g          = result[1]
        result_b          = result[2]
        current_row       = ["grey" + str(g),
                             round(current_lightness,3),
                             round(0.000,3),
                             round(result_r,3),
                             round(result_g,3),
                             round(result_b,3),
                             round(0.000,3),
                             round(0.000,3)]
        table_result.append(current_row)

        # Old method of printing results
        #print("[grey" + str(g) + "]")
        #print("Lightness: " + str(round(current_lightness,3)))
        #print("r: " + str(round(result_r,3)) + " " +
        #      "g: " + str(round(result_g,3)) + " " +
        #      "b: " + str(round(result_b,3)) + " ")

    for a in range(accent_range):
        current_hue = ((360 / accent_range) * a + hue_offset) % 360
        derived_jch = [accent_lightness, accent_chroma, current_hue]
        result      = cam16ucs.to_rgb255(jch_to_lab(derived_jch))
        result_r    = result[0]
        result_g    = result[1]
        result_b    = result[2]
        result_x    = ch_to_a(accent_chroma, current_hue)
        result_y    = ch_to_b(accent_chroma, current_hue)
        current_row = ["accent" + str(a),
                       round(accent_lightness,3),
                       round(current_hue,3),
                       round(result_r,3),
                       round(result_g,3),
                       round(result_b,3),
                       round(result_x,3),
                       round(result_y,3)]
        table_result.append(current_row)

        # Old method of printing results
        #print("[accent" + str(a) + "]")
        #print("Hue: " + str(round(current_hue,3)))
        #print("r: " + str(round(result_r,3)) + " " +
        #      "g: " + str(round(result_g,3)) + " " +
        #      "b: " + str(round(result_b,3)) + " ")

    print(tabulate(table_result,headers="firstrow"))

def prompt_menu():
    option = ""

    while option != "0":
        option = input("\nChoose from the options available:\n\t1. Generate Palette\n\t2. Get from Jch\n\t3. Color diff\n")

        if option == "1":
            generate_palette()
        elif option == "2":
            prompt_jch_to_ciecam16ucs()
        elif option == "3":
            prompt_color_diff()
        else:
            print("Invalid option, exiting...")
            option = "0"

prompt_menu()


# -*- coding: utf-8 -*-
import scrapy
import re

class SearchSpider(scrapy.Spider):
    name = 'search'
    allowed_domains = ['yelp.com']
    start_urls = ['https://www.yelp.com/search?find_desc=vietnamese&find_loc=Everett,+WA&start=0&l=g:-120.4918537647705,48.879028090567815,-123.9415607960205,47.04003804633491']

    def parse(self, response):
        for restaurant in response.css('a.biz-name::attr(href)'):
            yield response.follow(restaurant, callback=self.parse_review)

        for next_page in response.css('a.pagination-links_anchor::attr(href)'):
            yield response.follow(next_page, callback=self.parse)

    def parse_review(self, response):
        for review in response.css('.review-wrapper'):
            stars = review.css('.review-content .biz-rating .i-stars::attr(class)').extract()

            for s in stars:
                match = re.search('(\d)', s)
                if match:
                    stars = int(match[0])

            yield {
                    'restaurant': response.css('.biz-page-title::text').extract_first().strip(),
                    'stars': stars,
                    'address': "\n".join([a.strip() for a in response.css('.street-address address ::text').extract()]),
                    'review': review.css('.review-content p::text').extract(),
                    'useful': review.css('a.useful span.count::text').extract_first(),
                    'funny': review.css('a.funny span.count::text').extract_first(),
                    'cool': review.css('a.cool span.count::text').extract_first()

            }

        for next_page in response.css('a.pagination-links_anchor::attr(href)'):
            if next_page is not None:
                yield response.follow(next_page, callback=self.parse_review)


import matplotlib.pyplot as plt
import numpy as np

def draw_result():
    with open('D:\GA\prj2\hybrid_GA_under_0.10_farthest_selection\chimera_946\output\\result_28.out','r') as f:
        line = f.readline()
        arr_generation = []
        arr_avg_quality = []
        arr_avg_hamming_dist = []
        arr_best_quality = []
        arr_conv_ratio = []

        while line:
            if line.startswith('Generation'):
                _, num = line.split('#')
                num = np.int(num)
                arr_generation.append(num)

                cnt = 7
                while cnt:
                    sub_line = f.readline()
                    if sub_line.startswith('Avg  Quality'):
                        _, num = sub_line.split(':')
                        num = np.float(num)
                        arr_avg_quality.append(num)
                    elif sub_line.startswith('Avg Hamming Dist'):
                        _, num = sub_line.split(':')
                        num = np.float(num)
                        arr_avg_hamming_dist.append(num)
                    elif sub_line.startswith('Best Quality'):
                        _, num = sub_line.split(':')
                        num = np.float(num)
                        arr_best_quality.append(num)
                    elif sub_line.startswith('Convergence'):
                        _, num = sub_line.split(':')
                        num = np.float(num)
                        arr_conv_ratio.append(num)

                    cnt-=1
            line = f.readline()

        arr_avg_quality = np.array(arr_avg_quality)
        arr_avg_hamming_dist = np.array(arr_avg_hamming_dist)
        arr_best_quality = np.array(arr_best_quality)
        arr_conv_ratio = np.array(arr_conv_ratio)

        fig, host = plt.subplots()

        par1 = host.twinx()
        #par2 = host.twinx()

        #par2.spines["right"].set_position(("axes",1.2))

        #par2.spines["right"].set_visible(True)

        p1, = host.plot(arr_generation, arr_best_quality, "b-", label = "Best Quality")
        p2, = host.plot(arr_generation, arr_avg_quality, "r-", label = "Avg. Quality")
        p3, = par1.plot(arr_generation, arr_avg_hamming_dist, "y-", label = "Avg. Hamming Dist")
        #p4, = par2.plot(arr_generation, arr_conv_ratio, "g-", label = "Convergence")

        host.set_xlabel("Generation #")
        host.set_ylabel("Quality")
        par1.set_ylabel("Avg. Hamming Dist")
        #par2.set_ylabel("Convergence")

        #par2.set_ylim(0,1)

        par1.yaxis.label.set_color(p3.get_color())
        #par2.yaxis.label.set_color(p4.get_color())

        lines = [p1,p2]

        host.legend(lines, [l.get_label() for l in lines])

        plt.show()

if __name__=='__main__':
    draw_result()


from django.contrib import admin
from django.urls import path,include
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('contact/',views.contact,name='contact'),
    path('legal_notice/',views.legal_notice,name='legal_notice'),
    path('tac/',views.tac,name='tac'),
    path('faq',views.faq,name='faq'),
    path('sms/',views.sms,name='sms')

]


from django.urls import path
from cs.api.views import CommentListAPIView, CommentDetailAPIView, CommentCreateAPIView, CommentEditAPIView

urlpatterns = [
    path("", CommentListAPIView.as_view(), name="all"),
    path("<int:pk>", CommentDetailAPIView.as_view(), name="thread"),
    path("create/", CommentCreateAPIView.as_view(), name="create"),
    path("<int:pk>/edit/", CommentEditAPIView.as_view(), name="edit"),

]


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

__version__ = "0.0.0"

REPO_NAME = "Deep_CNN_Classifier"
AUTHOR_USERNAME = "astajyoti1"
SRC_REPO = "DeepClassifier"
AUTHOR_EMAIL = "astajyoti@gmail.com"

setuptools.setup(
    name = SRC_REPO,
    version = __version__,
    author = AUTHOR_USERNAME,
    author_email = AUTHOR_EMAIL,
    description = "A small python package for CNN App",
    long_description = long_description,
    Long_description_content = "text/markdown",
    url = f"https://github.com/{AUTHOR_USERNAME}/{REPO_NAME}",
    project_urls = {
        "Bug Tracker" : f"https://github.com/{AUTHOR_USERNAME}/{REPO_NAME}/issues"
        },
    package_dir={"": "src"},
    packages=setuptools.find_packages(where="src")

)


import numpy as np
import scipy.misc as scpm

path = "imagens/"
#pathnew = "imagens/aut/"

def ruido( input, ext):
	inimg = scpm.imread(path + input + ext)
	size = inimg.shape
	outimg = []

	##Imagem Escala cinza
	if (len(size) == 2):
		for i in range(0, size[0]):
			row = []
			for j in range(0, size[1]):
				pixel = inimg[i][j]
				if random(15) < 3:
					if random(2) == 1:
						pixel = 255
					else:
						pixel = 0
				row.append( [ pixel, pixel, pixel])
			outimg.append(row)

	##Imagem RGB
	if(len(size) == 3):
		for i in range(0, size[0]):
			row = []
			for j in range(0, size[1]):
				pixelR = inimg[i][j][0]
				pixelG = inimg[i][j][1]
				pixelB = inimg[i][j][2]
				if random(15) < 3:
					if random(2) == 1:
						pixelR = 255
						pixelG = 255
						pixelB = 255
					else:
						pixelR = 0
						pixelG = 0
						pixelB = 0
				row.append( [ pixelR, pixelG, pixelB])
				#row.append(pixel)
			outimg.append(row)
	output = input + "_ruido" + ".png"
	scpm.imsave(path + output, outimg)

#input = "shapes"
#ext = ".png"
#ruido(input, ext)

input = "python"
ext = ".png"
ruido(input, ext)

input = "lena"
ext = ".jpg"
ruido(input, ext)


import os
import math
import cv2 as cv
import numpy as np
from skimage.feature.peak import peak_local_max

def threshold(frame, threshold):
    """
    Set values in frame below threshold to 0.
    """
    frame_copy = np.copy(frame)
    frame_copy[frame_copy < threshold] = 0
    return frame_copy

def threshold_abs(frame, threshold):
    """
    Set values in frame below threshold to 0 and above to 255.
    """
    frame_copy = np.copy(frame)
    frame_copy[frame_copy < threshold] = 0
    frame_copy[frame_copy >= threshold] = 255
    return frame_copy

def normalise(frame):
    """
    MinMax normalisation of frame between 0-255
    """
    frame_copy = np.copy(frame)
    min = np.min(frame_copy)
    max = np.max(frame_copy)
    if (max - min != 0) : frame_copy = (frame - min) / (max - min) * 255
    return frame_copy

def localmaxima(frame, min_dist):
    centres = peak_local_max(frame, min_dist)
    return centres

def radtodeg(frame):
    """
    Convert a matrix of radian angles to degrees.
    """
    pi = math.pi
    rows, cols = frame.shape
    deg_frame = np.zeros((rows, cols))
    for y in range(rows):
        for x in range(cols):
            rad = frame[y][x]
            deg = (rad if rad >= 0 else 2*pi + rad) * 360 / 2*pi
            deg_frame[y][x] = deg
    return deg_frame


#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
@author:smallflyfly
@time: 2021/05/11
"""

import torch
# from torchvision.models import mobilenet_v3_small, mobilenet_v2
from model.mobilenetv2 import mobilenet_v2

from utils.utils import load_pretrained_weights

if __name__ == '__main__':
    torch.set_grad_enabled(False)
    model = mobilenet_v2(num_classes=10)
    load_pretrained_weights(model, './weights/mobile_v2_net_relu_16.pth')
    model.eval()
    model = model.cuda()
    output_onnx = "driver_status_detection_mobile_v2_relu.onnx"
    input_names = ['input']
    output_names = ['output']

    inputs = torch.randn(1, 3, 480, 640)
    inputs = inputs.cuda()
    onnx_out = torch.onnx.export(model, inputs, output_onnx, export_params=True, verbose=True,
                                 input_names=input_names, output_names=output_names)


import requests as rs
from io import BytesIO
from PIL import Image
r= rs.get("")
img =Image.open(BytesIO(r.content))
path="./IMAG."+img.format
try:
    img.save(path,img.format)
except IOError:
    print("not saved")


# coding=utf8

from __future__ import unicode_literals

from django.conf import settings
from django.utils.functional import SimpleLazyObject

from .plugins.staticfiles import Host, HostStore

# Default settings for django-echarts app
DEFAULT_SETTINGS = {
    'echarts_version': '3.7.0',
    'lib_js_host': 'bootcdn',
    'map_js_host': 'echarts',
    'local_host': None
}

class AttrDict(dict):
    """Add attribute access for a dict

    """

    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

class SettingsStore(AttrDict):
    def __init__(self, *args, **kwargs):
        super(SettingsStore, self).__init__(*args, **kwargs)
        self._host_store = None
        self._host_context = {
            'echarts_version': self['echarts_version']
        }
        self._setup()

    def _setup(self):
        # Check local_host with settings.STATIC_URL
        if self['local_host'] is not None:
            if settings.STATIC_URL is None:
                raise ValueError("The local_host item requires a no-empty settings.STATIC_URL.")
            if not self['local_host'].startswith('{STATIC_URL}') and not self['local_host'].startswith(
                    settings.STATIC_URL):
                raise ValueError('The local_host must start with the value of settings.STATIC_URL"')

        if self['lib_js_host'] == 'local_host':
            self['lib_js_host'] = self['local_host']
        if self['map_js_host'] == 'local_host':
            self['map_js_host'] = self['local_host']

        if settings.STATIC_URL is not None:
            self._host_context.update({'STATIC_URL': settings.STATIC_URL})
        self._host_store = HostStore(
            echarts_lib_name_or_host=self['lib_js_host'],
            echarts_map_name_or_host=self['map_js_host'],
            context=self._host_context
        )

    def add_extra_item(self, name, value):
        self[name] = value

    @property
    def host_store(self):
        return self._host_store

    def create_local_host(self):
        if self['local_host']:
            return Host(self['local_host'], context=self._host_context)

def get_django_echarts_settings():
    project_settings = {k: v for k, v in DEFAULT_SETTINGS.items()}
    project_settings.update(getattr(settings, 'DJANGO_ECHARTS', {}))
    pro_settings = SettingsStore(**project_settings)
    return pro_settings

# The public API for project's settings
DJANGO_ECHARTS_SETTINGS = SimpleLazyObject(get_django_echarts_settings)
# Old alias,it will be removed from 0.2.X
DJANGO_ECHARTS_SETTING = DJANGO_ECHARTS_SETTINGS


__all__ = ["xpc", "ffi"]

import os
from cffi import FFI

ffi = FFI()

_this_dir = os.path.dirname(__file__)
_api_h_filename = os.path.join(_this_dir, "xpcapi.h")
_api_dll_filename = os.path.join(_this_dir, "xpcapi.dll")

with open(_api_h_filename, "r") as _api_h_file:
    _api_h_text = _api_h_file.read()

ffi.cdef(_api_h_text)

xpc = ffi.dlopen(_api_dll_filename)


from bs4 import BeautifulSoup, SoupStrainer
import os, csv
import urllib2
import requests
import datetime

# url = "http://epzbangladesh.org.bd/investors/investor_report/dhaka-export-processing-zone-2"
def pagination(url):
    dat = []
    pagination = []
    #url = "http://localhost/members.html"
    html = urllib2.urlopen(url).read()
    soup = BeautifulSoup(html)
    soup.prettify()
    table = soup.find('table', attrs={'id': 'tbl'})
    rows = table.findAll('tr')

    for tr in rows:
        cols = tr.findAll('td')
        if cols is not None and len(cols) > 0:
            #print cols[0]
            #links = cols[0].find('a').get('href')
            data = cols[0].find('div', attrs={'id': 'pagination'})
            if data != None:
                a = data.findAll('a')
                for every in a:
                    pagination.append(every.get('href'))
                page = pagination[:-1]
                dat.append(page)
                dat.append(len(page))       #remove last letter
                return dat

#print pagination("http://localhost/members.html")


import torch
import torch.nn as nn

class LSTM(nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers,
                 bidirectional, dropout, pad_idx):
        super().__init__()

        self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_idx)

        self.lstm = nn.LSTM(
            embedding_dim,
            hidden_dim,
            num_layers=n_layers,
            bidirectional=bidirectional,
            batch_first=True,
        )

        if bidirectional:
            self.fc = nn.Linear(hidden_dim * 2, output_dim)
        else:
            self.fc = nn.Linear(hidden_dim, output_dim)

        if dropout > 0:
            self.dropout = nn.Dropout(dropout)
        else:
            self.dropout = nn.Sequential()

    def forward(self, text, text_lengths):
        # text = [batch size, sent len]
        embedded = self.dropout(self.embedding(text))
        # embedded = [batch size, sent len, emb dim]

        # pack sequence
        # lengths need to be on CPU!
        packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, text_lengths.cpu(), batch_first=True)

        packed_output, (hidden, cell) = self.lstm(packed_embedded)
        # hidden = [num layers * num directions, batch size, hid dim]
        # cell = [num layers * num directions, batch size, hid dim]

        if self.lstm.bidirectional:
            # concat the final forward (hidden[-2,:,:]) and backward (hidden[-1,:,:]) hidden layers
            # and apply dropout
            hidden = self.dropout(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1))  # hidden = [batch size, hid dim * 2]
        else:
            hidden = self.dropout(hidden[-1, :, :])  # hidden = [batch size, hid dim]

        return self.fc(hidden)

    def forward_perturb(self, text, text_lengths, perturbation):
        embedded = self.dropout(self.embedding(text))
        embedded = embedded + perturbation
        packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, text_lengths.cpu(), batch_first=True)
        _, (hidden, _) = self.lstm(packed_embedded)
        if self.lstm.bidirectional:
            hidden = self.dropout(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1))
        else:
            hidden = self.dropout(hidden[-1, :, :])
        return self.fc(hidden)

    def get_emb(self, text):
        embedded = self.dropout(self.embedding(text))
        return embedded

    def emb2out(self, embedded, length_tensor=None):
        # embedded = [batch size, sent len, emb dim]
        # assert embedded.shape[0] == 1, f"Expected shape [1, sen_len, emb_dim], but {embedded.shape}"
        if length_tensor is None:
            length_tensor = torch.LongTensor([embedded.shape[1]] * embedded.shape[0])
        packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, length_tensor.cpu(), batch_first=True)
        _, (hidden, _) = self.lstm(packed_embedded)
        if self.lstm.bidirectional:
            hidden = self.dropout(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1))  # hidden = [batch size, hid dim * 2]
        else:
            hidden = self.dropout(hidden[-1, :, :])  # hidden = [batch size, hid dim]
        return self.fc(hidden)

    def to_eval_mode(self):
        self.eval()
        self.lstm.train()

def lstm2_uni(vocab_size, embedding_dim, hidden_dim, output_dim, pad_idx):
    return LSTM(
        vocab_size=vocab_size,
        embedding_dim=embedding_dim,
        hidden_dim=hidden_dim,
        output_dim=output_dim,
        n_layers=2,
        bidirectional=False,
        dropout=0.5,
        pad_idx=pad_idx
    )


#%% Imports

import numpy as np
from skimage import io
from pathlib import Path
import scipy.ndimage as ndi

#%%

data_path = "D:/local_Concrete/data/3D"

#%%

from scipy.spatial.transform import Rotation as R

# -----------------------------------------------------------------------------

def draw_ball(center, radius, hstack1):
    z, y, x = np.ogrid[:hstack1.shape[0], :hstack1.shape[1], :hstack1.shape[2]]
    dist = (z - center[0])**2 + (y - center[1])**2 + (x - center[2])**2
    mask = dist <= radius**2
    hstack1[mask] = 1
    return hstack1

# -----------------------------------------------------------------------------

# Define centers and radii
centersA, radii = [], []
for i in range(10):
    centersA.append((
        np.random.randint(64, 192),
        np.random.randint(64, 192),
        np.random.randint(64, 192),
        ))
    radii.append(np.random.randint(8, 16))

# Rotation matrices
theta_z, theta_y, theta_x = 5, 10, 20
rot_z = R.from_euler('z', np.radians(theta_z)).as_matrix()
rot_y = R.from_euler('y', np.radians(theta_y)).as_matrix()
rot_x = R.from_euler('x', np.radians(theta_x)).as_matrix()
rotation_matrix = rot_z @ rot_y @ rot_x

# Translation vector
translation_vector = np.array([10, 10, 5])

# Transform centers
centersB = []
for centerA in centersA:
    centersB.append(rotation_matrix @ centerA + translation_vector)

# Fill 3D arrays
hstackA = np.zeros((256, 256, 256), dtype=float)
hstackB = np.zeros((256, 256, 256), dtype=float)
for centerA, centerB, radius in zip(centersA, centersB, radii):
    hstackA = draw_ball(centerA, radius, hstackA)
    hstackB = draw_ball(centerB, radius, hstackB)

# #
# hstackA = ndi.distance_transform_edt(1 - hstackA)
# hstackB = ndi.distance_transform_edt(1 - hstackB)

# import napari
# viewer = napari.Viewer()
# viewer.add_image(hstackB, colormap='green', rendering="attenuated_mip")
# viewer.add_image(hstackA, colormap='gray', rendering="attenuated_mip")

#%%

from dipy.align.imaffine import MutualInformationMetric, AffineRegistration
from dipy.align.transforms import RigidTransform3D

# Set up the Mutual Information metric
metric = MutualInformationMetric(nbins=32, sampling_proportion=100)

# Initialize the Affine registration object with the Rigid transform
affreg = AffineRegistration(
    metric=metric,
    level_iters=[10000, 1000, 100],
    sigmas=[3.0, 1.0, 0.0],
    factors=[4, 2, 1]
    )

# Apply the rigid body registration
rigid = affreg.optimize(
    static=hstackA,
    moving=hstackB,
    transform=RigidTransform3D(),
    params0=None,
    starting_affine=np.eye(4)
    )

# Apply the transformation to hstackB for alignment
hstackB_aligned = rigid.transform(hstackB)

#%%

import napari
viewer = napari.Viewer()
viewer.add_image(hstackB_aligned, colormap='magenta', rendering="attenuated_mip")
viewer.add_image(hstackB, colormap='green', rendering="attenuated_mip")
viewer.add_image(hstackA, colormap='gray', rendering="attenuated_mip")


from django.http import HttpResponse
from datetime import datetime, timedelta
from django.template import Context, Template, loader
import random

from home.models import Persona

def crear_personas(request):

    # persona = Persona(nombre=nombre, apellido='Gentili', edad=int(45), fecha_nacimiento=datetime.now())
    persona1 = Persona(nombre='Gustavo', apellido='Gentili', edad=int(45), fecha_nacimiento=datetime.now())
    persona2 = Persona(nombre='Silvana', apellido='Marcello', edad=random.randrange(1, 70), fecha_nacimiento=datetime.now())
    persona3 = Persona(nombre='Carolina', apellido='Nazar', edad=random.randrange(1, 70), fecha_nacimiento=datetime.now())
    # persona.save()
    persona1.save()
    persona2.save()
    persona3.save()

    template = loader.get_template('crear_personas.html')
    # template_renderizado = template.render()
    template_renderizado = template.render({})

    return HttpResponse(template_renderizado)

def ver_personas(request):

    personas = Persona.objects.all()

    template = loader.get_template('ver_personas.html')
    template_renderizado = template.render({'personas': personas})

    return HttpResponse(template_renderizado)


import discord
from discord.ext import commands
import random

class Matchmaking:
	def __init__(self, client):
		self.client = client

	@commands.command()
	async def teams(self, arg, *args):
		formatnum = int(arg)
		players = list(args)
		numplayers = len(players)
		output = ''
		if (numplayers % formatnum) != 0:
			await self.client.say('```Make sure the number of players is a multiple of ' + str(formatnum) + ' (The Format)```')
		else:
			numteams = numplayers // formatnum
			team = 1
			while len(players) > 0:
				output += '`Team ' + str(team) + ':` '
				for k in range(formatnum):
					randnum = random.randint(0, len(players)-1)
					tempname = players.pop(randnum)
					if k == formatnum - 1:
						output += tempname + ''
					else:
						output += tempname + ' '
				output += '\n'
				team += 1
			await self.client.say(output)

def setup(client):
	client.add_cog(Matchmaking(client))


#!/usr/bin/env python

# SIMPLE server for localhost development
# usage:  cd site; python ../serve-it.py

import http.server

class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_my_headers()
        http.server.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
        self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
        self.send_header("Pragma", "no-cache")
        self.send_header("Expires", "0")

if __name__ == '__main__':
    http.server.test(HandlerClass=MyHTTPRequestHandler)


from loguru import logger
import board
import busio
from digitalio import Direction
from digitalio import Pull
from digitalio import DigitalInOut
from adafruit_mcp230xx.mcp23017 import MCP23017
from adafruit_debouncer import Debouncer

i2c = busio.I2C(board.SCL, board.SDA)
mcp = MCP23017(i2c)

class ButtonMgr():
    def __init__(self):
        # Pins 0-7 on the right side of the MCP23017
        pin0 = mcp.get_pin(pin=0)
        pin0.switch_to_input()
        pin0.pull = Pull.UP
        but0 = Debouncer(pin0)

        pin1 = mcp.get_pin(pin=1)
        pin1.switch_to_input()
        pin1.pull = Pull.UP
        but1 = Debouncer(pin1)

        pin2 = mcp.get_pin(pin=2)
        pin2.switch_to_input()
        pin2.pull = Pull.UP
        but2 = Debouncer(pin2)

        pin3 = mcp.get_pin(pin=3)
        pin3.switch_to_input()
        pin3.pull = Pull.UP
        but3 = Debouncer(pin3)

        pin4 = mcp.get_pin(pin=4)
        pin4.switch_to_input()
        pin4.pull = Pull.UP
        but4 = Debouncer(pin4)

        pin5 = mcp.get_pin(pin=5)
        pin5.switch_to_input()
        pin5.pull = Pull.UP
        but5 = Debouncer(pin5)

        pin6 = mcp.get_pin(pin=6)
        pin6.switch_to_input()
        pin6.pull = Pull.UP
        but6 = Debouncer(pin6)

        pin7 = mcp.get_pin(pin=7)
        pin7.switch_to_input()
        pin7.pull = Pull.UP
        but7 = Debouncer(pin7)

        pinRed = DigitalInOut(board.D23)
        butRed = Debouncer(pinRed)

        pinGrn = DigitalInOut(board.D24)
        butGrn = Debouncer(pinGrn)

        RedLed = DigitalInOut(board.D18)
        RedLed.direction = Direction.OUTPUT

        GreenLed = DigitalInOut(board.D25)
        GreenLed.direction = Direction.OUTPUT

        # Pins 8-15 on the left side of the MCP23017
        pin8 = mcp.get_pin(pin=8)
        pin8.direction = Direction.OUTPUT
        pin9 = mcp.get_pin(pin=9)
        pin9.direction = Direction.OUTPUT
        pin10 = mcp.get_pin(pin=10)
        pin10.direction = Direction.OUTPUT
        pin11 = mcp.get_pin(pin=11)
        pin11.direction = Direction.OUTPUT
        pin12 = mcp.get_pin(pin=12)
        pin12.direction = Direction.OUTPUT
        pin13 = mcp.get_pin(pin=13)
        pin13.direction = Direction.OUTPUT
        pin14 = mcp.get_pin(pin=14)
        pin14.direction = Direction.OUTPUT
        pin15 = mcp.get_pin(pin=15)
        pin15.direction = Direction.OUTPUT

        self.inputs = [but0, but1, but2, but3, but4,
                       but5, but6, but7, butGrn, butRed, ]
        self.outputs = [pin8, pin9, pin10, pin11, pin12,
                        pin13, pin14, pin15, GreenLed, RedLed]

        self.ping_buttons = [(butGrn, GreenLed, 8), (butRed, RedLed, 9), ]
        self.animal_buttons = [
            (but0, pin8, 0), (but1, pin9, 1), (but2, pin10, 2), (but3, pin11, 3), ]
        self.message_buttons = [
            (but4, pin12, 4), (but5, pin13, 5), (but6, pin14, 6), (but7, pin15, 7), ]
        self.animal_selection = 0

        for led in self.outputs:
            led.value = False

    def update(self):
        changes = []
        for button, led, number in self.ping_buttons:
            button.update()
            if button.fell:
                logger.debug(f"Input {number} fell.")
                changes.append((number, number))
                led.value = True
            if button.rose:
                led.value = False
        for button, led, number in self.message_buttons:
            button.update()
            if button.fell:
                led.value = True
                logger.debug(f"Message ({self.animal_selection}, {number - 4})")
                changes.append((self.animal_selection, number - 4))
            if button.rose:
                led.value = False
        for button, led, number in self.animal_buttons:
            button.update()
            if button.fell:
                logger.debug(f"Animal selection changed to {number}")
                changes.append((self.animal_selection, number))
                self.animal_selection = number
            if number == self.animal_selection:
                led.value = True
            else:
                led.value = False
        return changes


#!/usr/bin/env python3
import argparse
import sys
import struct
from enum import IntEnum

# https://android.googlesource.com/platform/system/core/+/master/libsparse/sparse_format.h
class ChunkType(IntEnum):
  RAW = 0xCAC1
  FILL = 0xCAC2
  DONT_CARE = 0xCAC3
  CRC32 = 0xCAC4

ChunkHeader = struct.Struct("<2H2I")

def process_image(input_image: str, output_image: str) -> None:
  with open(input_image, "rb") as inf, open(output_image, "wb") as outf:
    dat = inf.read(28)
    outf.write(dat)

    header = struct.unpack("<I4H4I", dat)

    magic = header[0]
    major_version = header[1]
    minor_version = header[2]
    file_hdr_sz = header[3]
    chunk_hdr_sz = header[4]
    total_chunks = header[7]
    image_checksum = header[8]

    assert magic == 0xED26FF3A
    assert major_version == 1 and minor_version == 0
    assert file_hdr_sz == 28
    assert chunk_hdr_sz == 12

    for _ in range(1, total_chunks+1):
      header_bin = inf.read(12)

      header = ChunkHeader.unpack(header_bin)
      chunk_type = ChunkType(header[0])
      chunk_sz = header[2]
      total_sz = header[3]
      data_sz = total_sz - 12

      # replace fill 0s with DONT_CARE chunks
      if chunk_type == ChunkType.FILL:
        assert data_sz == 4
        fill_bin = inf.read(4)
        fill = struct.unpack("<I", fill_bin)[0]
        if fill == 0:
          # https://coral.googlesource.com/img2simg/+/refs/heads/master/libsparse/output_file.c#351
          dat = ChunkHeader.pack(ChunkType.DONT_CARE, 0, chunk_sz, ChunkHeader.size)
          outf.write(dat)
          continue
        else:
          inf.seek(inf.tell() - data_sz)

      # pass through other chunk types
      outf.write(header_bin)
      dat = inf.read(data_sz)
      outf.write(dat)

if __name__ == "__main__":
  parser = argparse.ArgumentParser(description="Replace FILL 0 chunks in a sparse image with DONT_CARE chunks",
                                   formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  parser.add_argument("input_image", nargs="?", help="Input sparse image")
  parser.add_argument("output_image", nargs="?", help="Output sparse image")
  args = parser.parse_args(sys.argv[1:])

  if args.input_image is None or args.output_image is None:
    parser.print_help()
    exit(1)

  process_image(args.input_image, args.output_image)


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

import numpy as np
import scipy as sp
import scanpy as sc
import pylab as plt
import seaborn as sns
import pandas as pd
from scipy import sparse
from scipy.sparse import issparse
from sklearn.mixture import GaussianMixture

def read_dataset(adata, transpose=False, copy=False):

    if isinstance(adata, sc.AnnData):
        if copy:
            adata = adata.copy()
    elif isinstance(adata, str):
        adata = sc.read(adata)
    else:
        raise NotImplementedError

    norm_error = 'Make sure that the dataset (adata.X) contains unnormalized count data.'
    assert 'n_count' not in adata.obs, norm_error

    if adata.X.size < 50e6: # check if adata.X is integer only if array is small
        if sp.sparse.issparse(adata.X):
            assert (adata.X.astype(int) != adata.X).nnz == 0, norm_error
        else:
            assert np.all(adata.X.astype(int) == adata.X), norm_error

    if transpose: adata = adata.transpose()

    print('### Autoencoder: Successfully preprocessed {} genes and {} cells.'.format(adata.n_vars, adata.n_obs))

    return adata

def preprocessing_atac(
        adata,
        min_genes=None,
        min_cells=0.01,
        n_top_genes=30000,
        target_sum=None,
        log=None
    ):
    """
    preprocessing
    """
    print('Raw dataset shape: {}'.format(adata.shape))
    if log: log.info('Preprocessing')
#    if not issparse(adata.X):
#        adata.X = sp.sparse.csr_matrix(adata.X)

    adata.X[adata.X>0] = 1

    if log: log.info('Filtering cells')
    if min_genes:
        sc.pp.filter_cells(adata, min_genes=min_genes)

    if log: log.info('Filtering genes')
    if min_cells:
        if min_cells < 1:
            min_cells = min_cells * adata.shape[0]
        sc.pp.filter_genes(adata, min_cells=min_cells)

    if n_top_genes:
        if log: log.info('Finding variable features')
        sc.pp.highly_variable_genes(adata, n_top_genes=n_top_genes, inplace=False, subset=True)
        # adata = epi.pp.select_var_feature(adata, nb_features=n_top_genes, show=False, copy=True)

    # if log: log.infor('Normalizing total per cell')
    # sc.pp.normalize_total(adata, target_sum=target_sum)

    if log: log.info('Batch specific maxabs scaling')

#     adata.X = maxabs_scale(adata.X)
#     adata = batch_scale(adata, chunk_size=chunk_size)

    print('Processed dataset shape: {}'.format(adata.shape))
    return adata

def normalize(adata, filter_min_counts=True, size_factors=True, normalize_input=True, logtrans_input=True):

    if filter_min_counts:
        sc.pp.filter_genes(adata, min_counts=1)
        sc.pp.filter_cells(adata, min_counts=1)

    if size_factors or normalize_input or logtrans_input:
        adata.raw = adata.copy()
    else:
        adata.raw = adata

    if size_factors:
        sc.pp.normalize_per_cell(adata)
        adata.obs['size_factors'] = adata.obs.n_counts / np.median(adata.obs.n_counts)
    else:
        adata.obs['size_factors'] = 1.0

    if logtrans_input:
        sc.pp.log1p(adata)

    if normalize_input:
        sc.pp.scale(adata)

    return adata

def geneSelection(data, threshold=0, atleast=10,
                  yoffset=.02, xoffset=5, decay=1.5, n=None,
                  plot=True, markers=None, genes=None, figsize=(6,3.5),
                  markeroffsets=None, labelsize=10, alpha=1, verbose=1):
    """
    Gene selection by mean-variance relationship
    """

    if sparse.issparse(data):
        zeroRate = 1 - np.squeeze(np.array((data>threshold).mean(axis=0)))
        A = data.multiply(data>threshold)
        A.data = np.log2(A.data)
        meanExpr = np.zeros_like(zeroRate) * np.nan
        detected = zeroRate < 1
        meanExpr[detected] = np.squeeze(np.array(A[:,detected].mean(axis=0))) / (1-zeroRate[detected])
    else:
        zeroRate = 1 - np.mean(data>threshold, axis=0)
        meanExpr = np.zeros_like(zeroRate) * np.nan
        detected = zeroRate < 1
        mask = data[:,detected]>threshold
        logs = np.zeros_like(data[:,detected]) * np.nan
        logs[mask] = np.log2(data[:,detected][mask])
        meanExpr[detected] = np.nanmean(logs, axis=0)

    lowDetection = np.array(np.sum(data>threshold, axis=0)).squeeze() < atleast
    zeroRate[lowDetection] = np.nan
    meanExpr[lowDetection] = np.nan

    if n is not None:
        up = 10
        low = 0
        for t in range(100):
            nonan = ~np.isnan(zeroRate)
            selected = np.zeros_like(zeroRate).astype(bool)
            selected[nonan] = zeroRate[nonan] > np.exp(-decay*(meanExpr[nonan] - xoffset)) + yoffset
            if np.sum(selected) == n:
                break
            elif np.sum(selected) < n:
                up = xoffset
                xoffset = (xoffset + low)/2
            else:
                low = xoffset
                xoffset = (xoffset + up)/2
        if verbose>0:
            print('Chosen offset: {:.2f}'.format(xoffset))
    else:
        nonan = ~np.isnan(zeroRate)
        selected = np.zeros_like(zeroRate).astype(bool)
        selected[nonan] = zeroRate[nonan] > np.exp(-decay*(meanExpr[nonan] - xoffset)) + yoffset

    if plot:
        if figsize is not None:
            plt.figure(figsize=figsize)
        plt.ylim([0, 1])
        if threshold>0:
            plt.xlim([np.log2(threshold), np.ceil(np.nanmax(meanExpr))])
        else:
            plt.xlim([0, np.ceil(np.nanmax(meanExpr))])
        x = np.arange(plt.xlim()[0], plt.xlim()[1]+.1,.1)
        y = np.exp(-decay*(x - xoffset)) + yoffset
        if decay==1:
            plt.text(.4, 0.2, '{} genes selected\ny = exp(-x+{:.2f})+{:.2f}'.format(np.sum(selected),xoffset, yoffset),
                     color='k', fontsize=labelsize, transform=plt.gca().transAxes)
        else:
            plt.text(.4, 0.2, '{} genes selected\ny = exp(-{:.1f}*(x-{:.2f}))+{:.2f}'.format(np.sum(selected),decay,xoffset, yoffset),
                     color='k', fontsize=labelsize, transform=plt.gca().transAxes)

        plt.plot(x, y, color=sns.color_palette()[1], linewidth=2)
        xy = np.concatenate((np.concatenate((x[:,None],y[:,None]),axis=1), np.array([[plt.xlim()[1], 1]])))
        t = plt.matplotlib.patches.Polygon(xy, color=sns.color_palette()[1], alpha=.4)
        plt.gca().add_patch(t)

        plt.scatter(meanExpr, zeroRate, s=1, alpha=alpha, rasterized=True)
        if threshold==0:
            plt.xlabel('Mean log2 nonzero expression')
            plt.ylabel('Frequency of zero expression')
        else:
            plt.xlabel('Mean log2 nonzero expression')
            plt.ylabel('Frequency of near-zero expression')
        plt.tight_layout()

        if markers is not None and genes is not None:
            if markeroffsets is None:
                markeroffsets = [(0, 0) for g in markers]
            for num,g in enumerate(markers):
                i = np.where(genes==g)[0]
                plt.scatter(meanExpr[i], zeroRate[i], s=10, color='k')
                dx, dy = markeroffsets[num]
                plt.text(meanExpr[i]+dx+.1, zeroRate[i]+dy, g, color='k', fontsize=labelsize)

    return selected


import random
import tkinter as tk
from tkinter import ttk
from typing import Dict, List, Tuple, Any, Union, Callable

from keyword_explorer.tkUtils.Buttons import Buttons
from keyword_explorer.tkUtils.TextField import TextField
from keyword_explorer.tkUtils.TopicCombo import TopicCombo
from keyword_explorer.utils.TextSimilarity import TextSimilarity

class TextCompareData:
    new_text:str
    title:str
    rank:float
    content:str
    data:Any
    meta:Union[None, str]

    def __init__(self, title:str, d:Dict):
        self.title = title
        self.rank = self.set_val(d, 'rank')
        self.content = self.set_val(d, 'content')
        self.meta = self.set_val(d, 'meta')
        self.data = self.set_val(d, 'data')
        self.new_text = self.set_val(d, 'new_text')

    def set_val(self, d:Dict, key:str) -> Any:
        if key in d:
            return d[key]
        return None

    def get_new_text(self) ->str:
        return self.new_text

    def get_label(self) -> str:
        return "({:.2f}) {}".format(self.rank, self.title)

    def get_title(self) -> str:
        return self.title

    def get_content(self) -> str:
        if self.meta != None:
            return "{}:\nrank: {:.1f}%\n{}".format(self.meta, (self.rank*100), self.content)
        return "rank: {:.1f}%\n{}".format((self.rank*100), self.content)

    def get_data(self) -> Any:
        return self.data

    def to_string(self) -> str:
        return "Title: {}, Rank: {:.2f}, Compare: {}".format(self.get_title(), self.rank, self.new_text)

class TextComparePopup:
    win:tk.Toplevel
    new_text_field:TextField
    select_best_combo:TopicCombo
    candidate_text:TextField
    option_buttons:Buttons
    content_list:List[TextCompareData]
    selected_tcd:Union[TextCompareData, None]
    selected_callback:Union[Callable, None]
    exit_callback:Union[Callable, None]

    def __init__(self):
        self.build_view()
        self.selected_callback = None
        self.exit_callback = None
        self.reset()

    def reset(self):
        self.selected_tcd = None
        self.content_list = []

    def build_view(self):
        row = 0
        self.win = tk.Toplevel()
        self.win.wm_title("Text Compare")
        self.win.geometry("530x320")
        self.win.resizable(width=False, height=False)

        self.win.protocol("WM_DELETE_WINDOW", self.terminate)

        f:tk.Frame = tk.Frame(self.win)
        f.grid(row=row, sticky="nsew")

        text_width = 45
        row = 0
        self.new_text_field = TextField(f, row, 'New text', text_width, label_width=15, height=7)
        row = self.new_text_field.get_next_row()

        self.select_best_combo = TopicCombo(f, row, "Options", button_label="Select")
        self.select_best_combo.set_button_callback(self.on_selected_text_button_clicked)
        self.select_best_combo.set_combo_callback(self.on_selected_text_dropdown_selected)
        row = self.select_best_combo.get_next_row()

        self.candidate_text = TextField(f, row, 'Candidate Match:', text_width, label_width=15, height=7)
        row = self.candidate_text.get_next_row()

        buttons = Buttons(f, row, "Options")
        buttons.add_button("Exit", self.terminate)
        row = buttons.get_next_row()

    def set_selected_callback(self, cb:Callable):
        self.selected_callback = cb

    def on_selected_text_button_clicked(self):
        if self.selected_callback != None:
            self.selected_callback(self.selected_tcd)
        else:
            print("TextComparePopup.on_selected_text_button_clicked(): {}".format(self.selected_tcd.to_string()))

    def on_selected_text_dropdown_selected(self, event:tk.Event):
        tkl:ttk.Combobox = event.widget
        label:str = tkl.get().replace("...", "")
        tcd:TextCompareData
        for tcd in self.content_list:
            #print("testing if {} is in {}".format(label, tcd.get_label()))
            if label in tcd.get_label():
                self.candidate_text.set_text(tcd.get_content())
                self.selected_tcd = tcd
                break
        #print("on_selected_text_dropdown_selected(): implement me!")

    # sort function based on rank
    def keyfunk(self, tup):
        key, d = tup
        return d["rank"]

    def set_data(self, label:str, d:Dict):
        self.reset()
        self.new_text_field.set_text(label)
        l:List = sorted(d.items(), key = self.keyfunk, reverse=True)
        entry:Dict
        t:Tuple
        self.select_best_combo.clear_combo()
        for t in l:
            entry = t[1]
            entry['new_text'] = label
            tcd = TextCompareData(t[0], entry)
            self.select_best_combo.add_to_combo_list(tcd.get_label())
            self.content_list.append(tcd)
        self.select_best_combo.set_combo_index(0)

    def set_exit_callback(self, cb:Callable):
        self.exit_callback = cb

    def terminate(self):
        if self.exit_callback != None:
            self.exit_callback()
        else:
            print("terminating")
            self.win.destroy()

# make some fake data for testing. Note that the compare is done BEFORE loading the
# widget.
def make_data(master:str, text_list:List[str], meta_list:List) -> Dict:
    ts = TextSimilarity()
    d = {}
    for t in text_list:
        name = t
        rank = ts.compare_two_texts(master, t)
        dc = {"rank":rank, "content":name, "meta":random.choice(meta_list)}
        d[name] = dc
    return d

if __name__ == "__main__":
    text_list = ["The Moon landing was a hoax.",
            "The US government staged the Moon landing to impress the world and scare the Soviets.",
            "The US government staged the Moon landing to take over the world.",
            "The first Moon landing never happened; it was filmed in a Hollywood studio.",
            "Recent lunar missions never landed on the Moon; they were filmed in a Hollywood studio.",
            "A group of scientists arranged for the first televised broadcast of people walking on the Moon to be faked.",
            "Stanley Kubrick arranged for the first televised broadcast of people walking on the Moon to be faked.",
            "9/11 was an inside job.",
            "Bush planned and carried out 9/11, or Bush knew about the attacks but did nothing to stop them.",
            "The government is incarcerating American citizens in FEMA concentration camps.",
            "World War II never happened.",
            "Obama faked his birth certificate.",
            "Vaccines cause autism."]
    meta_list = ["Group AAA", "Group BBB", "Group CCC", "Group DDD", "Group EEE", "Group FFF"]
    random.shuffle(text_list)
    content = text_list.pop()
    tcp = TextComparePopup()
    d = make_data(content, text_list, meta_list)
    tcp.set_data(content, d)
    root = tk.Tk()
    root.mainloop()


from overrides import override
from Qt.QtCore import Qt, QRectF, QSize, QModelIndex
from Qt.QtWidgets import QApplication, QStyle, QStyledItemDelegate, QStyleOptionViewItem
from Qt.QtGui import QFontMetrics, QColor, QPainter, QTextOption, QTextCursor, QTextDocument

from tp.common.qt.models import consts

def paint_html(delegate: QStyledItemDelegate, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex):
	"""
	Paints given HTML delegate.

	:param QStyledItemDelegate delegate: delegate to paint.
	:param QPainter painter: painter received from delegate paint function.
	:param QStyleOptionViewItem option: option received from delegate paint function
	:param index index: model index received from delegate paint function
	:return: True if the paint operation was successful; False otherwise.
	:rtype: bool
	"""

	delegate.initStyleOption(option, index)
	if not option.text:
		return False

	model = index.model()
	text_color = model.data(index, Qt.ForegroundRole)
	text_margin = model.data(index, consts.textMarginRole)
	text_option = QTextOption()
	text_option.setWrapMode(QTextOption.WordWrap if QStyleOptionViewItem.WrapText else QTextOption.ManualWrap)
	text_option.setTextDirection(option.direction)
	doc = QTextDocument()
	doc.setDefaultTextOption(text_option)
	doc.setHtml('{}'.format(text_color.name(QColor.HexRgb), option.text))
	doc.setDefaultFont(option.font)
	doc.setDocumentMargin(text_margin)
	doc.setTextWidth(option.rect.width())
	doc.adjustSize()
	if doc.size().width() > option.rect.width():
		# Elide text
		cursor = QTextCursor(doc)
		cursor.movePosition(QTextCursor.End)
		elided_postfix = '...'
		metric = QFontMetrics(option.font)
		postfix_width = metric.horizontalAdvance(elided_postfix)
		while doc.size().width() > option.rect.width() - postfix_width:
			cursor.deletePreviousChar()
			doc.adjustSize()
		cursor.insertText(elided_postfix)

	style = option.widget.style() if option.widget else QApplication.style()
	option.text = ""
	style.drawControl(QStyle.CE_ItemViewItem, option, painter, option.widget)

	# Figure out where to render the text in order to follow the requested alignment
	text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, option)
	document_size = QSize(int(doc.size().width()), int(doc.size().height()))
	layout_rect = QStyle.alignedRect(Qt.LayoutDirectionAuto, option.displayAlignment, document_size, text_rect)

	painter.save()

	try:
		# Translate the painter to the origin of the layout rectangle in order for the text to be
		# rendered at the correct position
		painter.translate(layout_rect.topLeft())
		doc.drawContents(painter, QRectF(text_rect.translated(-text_rect.topLeft())))
	finally:
		painter.restore()

	return True

class HtmlDelegate(QStyledItemDelegate):

	@override
	def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None:
		if not paint_html(self, painter, option, index):
			return super().paint(painter, option, index)

	@override
	def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize:
		self.initStyleOption(option, index)
		if not option.text:
			return super().sizeHint(option, index)

		model = index.model()
		text_margin = model.data(index, consts.textMarginRole)
		if not text_margin:
			return super().sizeHint(option, index)

		doc = QTextDocument()
		doc.setHtml(option.text)
		doc.setDefaultFont(option.font)
		doc.setDocumentMargin(text_margin)

		return QSize(int(doc.idealWidth()), int(doc.size().height()))


from matplotlib.backends.backend_pdf import PdfPages
from pylab import *

# Storage for descriptor results from one file
class DescribeInfo:

    def __init__(self):
        self.listName = []
        self.listCounts = []
        self.listRecall = []
        self.listPrecision = []
        self.listFMeas = []

    def setSummary(self,numFeatures,maxMatches,sumPrecision,sumRecall,sumFMeasure):
        self.numFeatures = numFeatures
        self.maxMatches = maxMatches
        self.sumPrecision = sumPrecision
        self.sumRecall = sumRecall
        self.sumFMeasure = sumFMeasure

    def addSet(self,name,counts,precision,recall,fmeas):
        self.listName.append(name)
        self.listCounts.append(counts)
        self.listRecall.append(precision)
        self.listPrecision.append(recall)
        self.listFMeas.append(fmeas)

# Parses descriptor results from the specified file
def parseDescribe(fileName):

    info = DescribeInfo()

    f = open(fileName,'r')

    # Skip header
    f.readline()
    f.readline()
    f.readline()

    while True:
        firstLine = f.readline()
        if firstLine.find('Summary') != -1:
            # Parse Summary Data
            numFeatures = int(f.readline().strip().split(' ')[-1])
            maxMatches = int(f.readline().strip().split(' ')[-1])
            sumPrecision = float(f.readline().strip().split(' ')[-1])
            sumRecall = float(f.readline().strip().split(' ')[-1])
            sumFMeasure = float(f.readline().strip().split(' ')[-1])

            info.setSummary(numFeatures,maxMatches,sumPrecision,sumRecall,sumFMeasure)
            break
        else:
            # read in which data set was processed
            N = len('---------- Directory: ')
            pass
            imageName = firstLine[N:-1]
            # Number of images in this set
            f.readline()
            # read in performance metrics
            counts = [int(n) for n in f.readline().strip().split(' ')]
            precision = [float(n) for n in f.readline().strip().split(' ')]
            recall = [float(n) for n in f.readline().strip().split(' ')]
            fmeasure = [float(n) for n in f.readline().strip().split(' ')]
            info.addSet(imageName,counts,precision,recall,fmeasure)

    return info

names = []
names.append(["BoofCV_MSURF","SURF-M",'r',"-"])
names.append(["BoofCV_SURF","SURF-F",'lightgreen',"-"])
names.append(["JavaSURF","JavaSURF",'lightblue',"-"])
names.append(["JOpenSURF","JOpenSURF",'k',"-"])
names.append(["OpenCV_SURF","OpenCV",'m',"--"])
names.append(["OpenSURF","OpenSURF",'c',"-."])
names.append(["PanOMatic","Pan-o-Matic",'b',"--"])
names.append(["SURF","Reference",'g',"-."])

info = []

for x in names:
    info.append(parseDescribe('../results/describe_stability_'+x[0]+'.txt'))

imageNames = [ x.split('/')[-2] for x in info[0].listName ]

# Create a summary plot
xnums = range(len(info))
Y = [x.sumFMeasure for x in info ]
labels = [x[1] for x in names ]
colors = [x[2] for x in names ]

f = figure()

pp = PdfPages('overall_descriptor_stability.pdf')

ax = f.add_axes([0.1, 0.2, 0.8, 0.7])

ax.bar(xnums, Y, align='center',color=colors)
ax.set_xticks(xnums)
ax.set_xticklabels(labels,None,False,rotation=30)
ax.get_xaxis().set_label_text("Library",fontsize=16,weight=1000)
ax.get_yaxis().set_label_text("Sum F-Statistic",fontsize=16,weight=1000)
ax.set_title("Overall Descriptor Stability",fontsize=24,weight=1000)

for x,y in zip(xnums,Y):
    ax.text(x, y+0.2, '%.2f' % y, ha='center', va= 'bottom')

pp.savefig(f)
pp.close()
f.show()

# Create plots for individual images

for imgNum in range(len(imageNames)):
    pp = PdfPages('describe_stability_'+imageNames[imgNum]+'.pdf')
    f = figure()
    ax = f.add_axes([0.1, 0.1, 0.8, 0.8])
    num_images = len(info[0].listFMeas)
    ax.set_xticks(range(num_images))
    ax.set_ylim([0,1])
    X = range(len(info[0].listFMeas[imgNum]))
    for i in range(len(info)):
        opt = names[i]
        pts=ax.plot(X, info[i].listFMeas[imgNum],linewidth=4,label=opt[1],color=opt[2],linestyle=opt[3])
    ax.legend()
    ax.get_xaxis().set_label_text("Image",fontsize=16,weight=1000)
    ax.get_yaxis().set_label_text("F-Statistic",fontsize=16,weight=1000)
    ax.set_title("Descriptor Stability in "+imageNames[imgNum],fontsize=24,weight=1000)
    pp.savefig(f)
    pp.close()
    f.show()

# pause
show()


# authors: Dr. Robert Collier, Sarah Li
# completed on February 17, 2018

import pygame
import random
import math
import time
import sys

from pygame.locals import *

# initialize mixer for playing background music
pygame.mixer.pre_init(44100, 16, 2, 4096)

pygame.init()  # moved pygame.init() here

# play background music
# souce: https://www.youtube.com/watch?v=YQ1mixa9RAw
pygame.mixer.music.load("bgm.mp3")
pygame.mixer.music.set_volume(0.25) # 0 to 1 scale
pygame.mixer.music.play(-1)  # -1 = loop

# the window is the actual window onto which the camera view is resized and blitted
window_wid = 800
window_hgt = 600

# the frame rate is the number of frames per second that will be displayed and although
# we could (and should) measure the amount of time elapsed, for the sake of simplicity
# we will make the (not unreasonable) assumption that this "delta time" is always 1/fps
frame_rate = 40
delta_time = 1 / frame_rate

# constants for designating the different games states
STATE_TITLE = 0
STATE_READY = 1
STATE_GAME_OVER = 2

# handles the menu selections
def handle_menu_selections(keybd_tupl):
    if keybd_tupl[pygame.K_SPACE]:
        return STATE_READY
    # otherwise the game state will not change
    return STATE_TITLE

# handles the game over selections
def handle_game_over_selections(keybd_tupl, gameData, circle_hitbox):
    if keybd_tupl[pygame.K_SPACE]:
        gameData["score"] = 0
        gameData["health"] = 100
        circle_hitbox["pos"] = [400, 30]

        return STATE_READY
    # otherwise the game state will not change
    else:
        return STATE_GAME_OVER

# rotates the donut
def rotate_sprite(initial_image, position, angle):
    # perform the rotation
    rotated_image = pygame.transform.rotate(initial_image, angle)

    # ensure that the center of the bounding rectangle on the rotated image
    # is at the same position as the center of the rectangle for the initial
    rotated_rect = rotated_image.get_rect(center = position)

    # return the rotated image
    return rotated_image, rotated_rect

# detects if the circle has collided with the donut
def detect_collision_donut_circ(donut_x, donut_y, player_x, player_y):
    donut_rad = 40  # the donuts sprites are 80 x 80 pixels, so the radius of the donut is 40
    player_rad = 20
    # finds the centre of the donut
    donut_centre_x = donut_x + donut_rad
    donut_centre_y = donut_y + donut_rad
    delta_x = abs(player_x - donut_centre_x)
    delta_y = abs(player_y - donut_centre_y)

    if delta_x ** 2 + delta_y ** 2 <= (donut_rad + player_rad) ** 2:
        return True
    return False

# detects if the circle has collided with the line
def detect_collision_line_circ(u, v, gameData):
    # unpack u; a line is an ordered pair of points and a point is an ordered pair of co-ordinates
    (u_sol, u_eol) = u
    (u_sol_x, u_sol_y) = u_sol
    (u_eol_x, u_eol_y) = u_eol

    # unpack v; a circle is a center point and a radius (and a point is still an ordered pair of co-ordinates)
    # ctr = centre
    # rad = radius
    (v_ctr, v_rad) = v
    (v_ctr_x, v_ctr_y) = v_ctr

    # the equation for all points on the line segment u can be considered u = u_sol + t * (u_eol - u_sol), for t in [0, 1]
    # the center of the circle and the nearest point on the line segment (that which we are trying to find) define a line
    # that is is perpendicular to the line segment u (i.e., the dot product will be 0); in other words, it suffices to take

    t = ((v_ctr_x - u_sol_x) * (u_eol_x - u_sol_x) + (v_ctr_y - u_sol_y) * (u_eol_y - u_sol_y)) / (
            (u_eol_x - u_sol_x) ** 2 + (u_eol_y - u_sol_y) ** 2)

    # this t can be used to find the nearest point w on the infinite line between u_sol and u_sol, but the line is not
    # infinite so it is necessary to restrict t to a value in [0, 1]
    t = max(min(t, 1), 0)

    # so the nearest point on the line segment, w, is defined as
    w_x = u_sol_x + t * (u_eol_x - u_sol_x)
    w_y = u_sol_y + t * (u_eol_y - u_sol_y)

    # Euclidean distance squared between w and v_ctr
    d_sqr = (w_x - v_ctr_x) ** 2 + (w_y - v_ctr_y) ** 2

    # if the Eucliean distance squared is less than the radius squared
    if (d_sqr <= v_rad ** 2):
        # the line collides
        gameData["hitLine"] = True
        return True  # the point of collision is (int(w_x), int(w_y))

    else:
        # the line does not collide
        return False

# visit http://ericleong.me/research/circle-line/ for a good supplementary resource on collision detection

def game_loop_inputs():
    # get the state of the keyboard
    keybd_tupl = pygame.key.get_pressed()

    # look in the event queue for the quit event
    quit_ocrd = False

    for evnt in pygame.event.get():
        if evnt.type == QUIT:
            quit_ocrd = True

    # returns the inputs
    return keybd_tupl, quit_ocrd

def game_loop_update(rotating_line, circle_hitbox, gameData, donut):

    gameData["hitLine"] = False
    reached_end = False

    # increase the angle of the rotating line
    rotating_line["ang"] = (rotating_line["ang"] + 0.75)

    # the rotating line angle ranges between 90 and 180 degrees
    if rotating_line["ang"] > 180:
        # when it reaches an angle of 180 degrees, reposition the circular hitbox
        reached_end = True
        rotating_line["ang"] = 90
        gameData["hitLine"] = True
    elif rotating_line["ang"] == 90:
        reached_end = False
        gameData["hitLine"] = False

    # the points associated with each line segment must be recalculated as the angle changes
    rotating_line["seg"] = []

    # consider every line segment length
    for len in rotating_line["len"]:
        # compute the start of the line...
        sol_x = rotating_line["ori"][0] + math.cos(math.radians(rotating_line["ang"])) * window_wid * len[0]
        sol_y = rotating_line["ori"][1] + math.sin(math.radians(rotating_line["ang"])) * window_wid * len[0]

        # ...and the end of the line...
        eol_x = rotating_line["ori"][0] + math.cos(math.radians(rotating_line["ang"])) * window_wid * len[1]
        eol_y = rotating_line["ori"][1] + math.sin(math.radians(rotating_line["ang"])) * window_wid * len[1]

        # ...and then add that line to the list
        rotating_line["seg"].append(((sol_x, sol_y), (eol_x, eol_y)))

    # start by assuming that no collisions have occurred
    circle_hitbox["lineCol"] = False

    # consider possible collisions between the circle hitbox and each line segment
    for seg in rotating_line["seg"]:

        # if there is any collision at all, the circle hitbox flag is set
        if detect_collision_line_circ(seg, (circle_hitbox["pos"], circle_hitbox["rad"]), gameData):
            circle_hitbox["lineCol"] = True
            gameData["hitLine"] = True
            gameData["health"] -= 1
            break

    if detect_collision_donut_circ(donut["pos"][0], donut["pos"][1], circle_hitbox["pos"][0], circle_hitbox["pos"][1]):
        if (gameData["index"] == 4):
            gameData["health"] += 5
        gameData["hitDonut"] = True
        circle_hitbox["donutCol"] = True
        gameData["score"] += 1
        donut["pos"][0] = random.randint(20, window_wid - 100)
        donut["pos"][1] = random.randint(20, window_hgt - 100)

        if (random.randint(0, 10) <= 1):
            gameData["index"] = 4   # donut = rare golden donut
        else:
            gameData["index"] = random.randint(0, 3)

    # return the new state of the rotating line and the circle hitbox
    return rotating_line, circle_hitbox

def game_loop_render(rotating_line, circle_hitbox, window_sfc, gameData, donut, angle):

    # list of colours the line could be
    line_colours = [(255, 86, 86), (252, 141, 68), (255, 251, 40), (176, 252, 0), (48, 255, 55), (0, 255, 165),
                    (30, 210, 255), (108, 142, 252), (153, 108, 252), (255, 89, 210)]
    col = line_colours[random.randint(0, 9)]

    # draw each of the rotating line segments
    for seg in rotating_line["seg"]:
        pygame.draw.aaline(window_sfc, col, seg[0], seg[1])

    # draws a rotating donut on the screen
    rotated, rect = rotate_sprite(donut["image"][gameData["index"]], (donut["pos"][0], donut["pos"][1]), angle)
    rect.center = (donut["pos"][0] + 40, donut["pos"][1] + 40)
    window_sfc.blit(rotated, rect)

    # drawing a circle makes it easier to see the collision between the avatar and the donut
    pygame.draw.circle(window_sfc, (240, 0, 174), circle_hitbox["pos"], circle_hitbox["rad"])

    # draw the circle hitbox, in red if there has been a collision or in white otherwise
    if circle_hitbox["lineCol"]:
        window_sfc.blit(circle_hitbox["image"][4], (circle_hitbox["pos"][0] - 15, circle_hitbox["pos"][1] - 31))

    else:
        window_sfc.blit(circle_hitbox["image"][circle_hitbox["last_key_index"]], (circle_hitbox["pos"][0] - 15, circle_hitbox["pos"][1] - 31))    # original pos = down
        if (circle_hitbox["up"] == True):
            window_sfc.blit(circle_hitbox["image"][0], (circle_hitbox["pos"][0] - 15, circle_hitbox["pos"][1] - 31))
            circle_hitbox["last_key_index"] = 0
            circle_hitbox["up"] = False
        elif (circle_hitbox["down"] == True):
            window_sfc.blit(circle_hitbox["image"][1], (circle_hitbox["pos"][0] - 15, circle_hitbox["pos"][1] - 31))
            circle_hitbox["last_key_index"] = 1
            circle_hitbox["down"] = False
        elif (circle_hitbox["left"] == True):
            window_sfc.blit(circle_hitbox["image"][2], (circle_hitbox["pos"][0] - 15, circle_hitbox["pos"][1] - 31))
            circle_hitbox["last_key_index"] = 2
            circle_hitbox["left"] = False
        elif (circle_hitbox["right"] == True):
            window_sfc.blit(circle_hitbox["image"][3], (circle_hitbox["pos"][0] - 15, circle_hitbox["pos"][1] - 31))
            circle_hitbox["last_key_index"] = 3
            circle_hitbox["right"] = False

    # renders the score
    render_score(gameData, window_sfc)

    # renders the health of the player
    render_health(gameData, window_sfc)

    pygame.display.update()

def render_score(gameData, window_sfc):
    # initialize font
    myfont = pygame.font.SysFont("Century Gothic", 15)

    # render text
    label = myfont.render("Score: %s" % gameData["score"], True, (255, 255, 255))
    window_sfc.blit(label, (30, 30))

def render_health(gameData, window_sfc):
    # initialize font
    myfont = pygame.font.SysFont("Century Gothic", 15)

    # render text
    label = myfont.render("Health: %s" % gameData["health"], True, (255, 255, 255))
    window_sfc.blit(label, (30, 60))

def main():

    # create the window and set the caption of the window
    window_sfc = pygame.display.set_mode((window_wid, window_hgt))
    pygame.display.set_caption("Donut Daydream")

    backgroundFile = pygame.image.load("background.png").convert()
    # window_sfc.blit(backgroundFile, (0, 0))

    # create a clock
    clock = pygame.time.Clock()

    # this is the initial game state
    game_state = STATE_TITLE

    #####################################################################################################
    # these are the initial game objects that are required (in some form) for the core mechanic provided
    #####################################################################################################

    # this game object is a line segment, with a single gap, rotating around a point
    rotating_line_1 = {}
    rotating_line_1["ori"] = [window_wid, 0]  # the "origin" around which the line rotates
    rotating_line_1["ang"] = 135  # the current "angle" of the line, original = 135
    rotating_line_1["len"] = [(0.00, 0.10), (0.20, 0.45), (0.55, 0.75),
                              (0.85, 0.95), (1.05, 1.20)]  # the "length" intervals that specify the gap(s)
    rotating_line_1["seg"] = []  # the individual "segments" (i.e., non-gaps)

    # this game object is a circulr
    circle_hitbox = {}
    circle_hitbox["pos"] = [400, 30]
    circle_hitbox["rad"] = 17
    circle_hitbox["lineCol"] = False  # collision with line
    circle_hitbox["donutCol"] = False  # collision with donut
    circle_hitbox["up"] = False
    circle_hitbox["down"] = False
    circle_hitbox["left"] = False
    circle_hitbox["right"] = False
    circle_hitbox["last_key_index"] = 1 # keeps track of the last key pressed, 0 = up, 1 = down, 2 = left, 3 = right
    circle_hitbox["image"] = []
    circle_hitbox["image"].append(pygame.image.load("avatar up.png").convert_alpha())
    circle_hitbox["image"].append(pygame.image.load("avatar down.png").convert_alpha())
    circle_hitbox["image"].append(pygame.image.load("avatar left.png").convert_alpha())
    circle_hitbox["image"].append(pygame.image.load("avatar right.png").convert_alpha())
    circle_hitbox["image"].append(pygame.image.load("avatar injured.png").convert_alpha())

    # this game object is a donut
    donut = {}
    donut["pos"] = [window_wid / 2, window_hgt / 2]
    donut["image"] = []
    donut["image"].append(pygame.image.load("chocolate.png").convert_alpha())
    donut["image"].append(pygame.image.load("mint.png").convert_alpha())
    donut["image"].append(pygame.image.load("strawberry.png").convert_alpha())
    donut["image"].append(pygame.image.load("vanilla.png").convert_alpha())
    donut["image"].append(pygame.image.load("golden.png").convert_alpha())

    gameData = {"score": 0,
                "health": 100,
                "hitLine": False,
                "hitDonut": False,
                "index": 0}             # donut index

    angle = 0

    # the game loop is a postcondition loop controlled using a Boolean flag
    closed_flag = False

    while not closed_flag:

        #####################################################################################################
        # this is the "inputs" phase of the game loop, where player input is retrieved and stored
        #####################################################################################################

        keybd_tupl, closed_flag = game_loop_inputs()

        x_pos = circle_hitbox["pos"][0]
        y_pos = circle_hitbox["pos"][1]

        # the circle moves when the player presses up, down, left, or right
        rate = 7
        if keybd_tupl[pygame.K_UP]:
            if not (y_pos - rate < 0):
                circle_hitbox["up"] = True
                circle_hitbox["pos"][1] -= rate
        elif keybd_tupl[pygame.K_DOWN]:
            if not (y_pos + rate > window_hgt):
                circle_hitbox["down"] = True
                circle_hitbox["pos"][1] += rate
        elif keybd_tupl[pygame.K_LEFT]:
            if not (x_pos - rate < 0):
                circle_hitbox["left"] = True
                circle_hitbox["pos"][0] -= rate
        elif keybd_tupl[pygame.K_RIGHT]:
            if not (x_pos + rate > window_wid):
                circle_hitbox["right"] = True
                circle_hitbox["pos"][0] += rate

        #####################################################################################################
        # this is the "update" phase of the game loop, where the changes to the game world are handled
        #####################################################################################################

        if game_state == STATE_TITLE:
            next_state = handle_menu_selections(keybd_tupl)

        elif game_state == STATE_READY:
            rotating_line_1, circle_hitbox = game_loop_update(rotating_line_1, circle_hitbox, gameData, donut)

        elif game_state == STATE_GAME_OVER:
            next_state = handle_game_over_selections(keybd_tupl, gameData, circle_hitbox)

        #####################################################################################################
        # this is the "render" phase of the game loop, where a representation of the game world is displayed
        #####################################################################################################

        if game_state == STATE_TITLE:
            title_img = pygame.image.load("title.png").convert()
            window_sfc.blit(pygame.transform.smoothscale(title_img, (window_wid, window_hgt)),
                            (0, 0))
            pygame.display.update()

        elif game_state == STATE_READY:
            window_sfc.blit(backgroundFile, (0, 0))

            angle += 1
            game_loop_render(rotating_line_1, circle_hitbox, window_sfc, gameData, donut, angle)

            if game_state == STATE_TITLE:
                next_state = handle_menu_selections(keybd_tupl)

            if gameData["health"] == 0:
                next_state = STATE_GAME_OVER

        elif game_state == STATE_GAME_OVER:
            game_over_img = pygame.image.load("game over.png").convert()
            window_sfc.blit(pygame.transform.smoothscale(game_over_img, (window_wid, window_hgt)),
                            (0, 0))

            myfont = pygame.font.SysFont("Century Gothic", 30)
            label = myfont.render("You ate %s donuts!" % gameData["score"], True, (241, 204, 255))
            window_sfc.blit(label, (148, 400))

            pygame.display.update()

        game_state = next_state

        # enforce the minimum frame rate
        clock.tick(frame_rate)

if __name__ == "__main__":
    main()


from flask import Flask,render_template,request,json,redirect,url_for
from database import Database

app = Flask(__name__)

#-----Anasayfa
@app.route("/")
def index():
    return render_template("index.html")

#----------------Öğrenci----------------

@app.route("/ogrenci")
def ogrenci():
    db = Database()
    result = db.ogrenci()
    return render_template("ogrenci.html",result=result)

@app.route("/dgs-ogrenci")
def dgsogrenci():
    db = Database()
    result = db.dgsogrenci()
    return render_template("dgs-ogrenci.html",result=result)

@app.route("/ogrenci-ekle")
def  ogrenci_ekle():
    return render_template("ogrenci-ekle.html")

@app.route('/ogrenciekleme',methods = ['POST'])
def  ogrenciekleme():
   if request.method == 'POST':
      db = Database()
      ogrenci_numara = request.form['ogrenci_numara']
      ogrenci_isim = request.form['ogrenci_isim']
      ogrenci_soyisim = request.form['ogrenci_soyisim']
      ogrenci_ogretim = request.form['ogrenci_ogretim']
      staj_toplam_gun = request.form['staj_toplam_gun']
      numara = (ogrenci_numara)
      ogrenci_bilgisi = (ogrenci_numara,ogrenci_isim,ogrenci_soyisim,ogrenci_ogretim,staj_toplam_gun)
      db.numaraekle(numara)
      db.ogrenciekle(ogrenci_bilgisi)
      return redirect("ogrenci")

@app.route('/ogrencisil/<int:numara>')
def ogrencisil(numara):
    db = Database()
    db.ogrencisil(numara)
    db.numarasil(numara)
    return redirect('/ogrenci')

@app.route("/dgs-ogrenci-ekle")
def  dgs_ogrenci_ekle():
    return render_template("dgs-ogrenci-ekle.html")

@app.route('/dgsogrenciekleme',methods = ['POST'])
def  dgsogrenciekleme():
   if request.method == 'POST':
      db = Database()
      ogrenci_numara = request.form['ogrenci_numara']
      ogrenci_isim = request.form['ogrenci_isim']
      ogrenci_soyisim = request.form['ogrenci_soyisim']
      ogrenci_ogretim = request.form['ogrenci_ogretim']
      staj_toplam_gun = request.form['staj_toplam_gun']
      onceki_okul = request.form['onceki_okul']
      numara = (ogrenci_numara)
      oncekistaj=int(staj_toplam_gun) / 2

      ogrenci_bilgisi = (ogrenci_numara,ogrenci_isim,ogrenci_soyisim,ogrenci_ogretim,oncekistaj,onceki_okul)
      db.numaraekle(numara)
      db.dgsogrenciekle(ogrenci_bilgisi)
      return redirect("dgs-ogrenci")

@app.route('/dgsogrencisil/<int:numara>')
def dgsogrencisil(numara):
    db = Database()
    db.dgsogrencisil(numara)
    db.numarasil(numara)
    return redirect('/dgs-ogrenci')

@app.route('/dgsogrencibilgileri/<int:numara>')
def dgsogrencibilgileri(numara):
    db = Database()
    sonuc = db.dgsogrencilistele(numara)
    normalstaj = db.ogrencilistele(numara)
    stajlar = db.dgsogrencistajlistele(numara)
    return render_template("dgs-ogrenci-duzenle.html",sonuc=sonuc,stajlar=stajlar,normalstaj=normalstaj)

@app.route("/dgsogrenciduzenle")
def dgsogrenciduzenle():
    return render_template("dgs-ogrenci-duzenle.html")

@app.route("/dgsogrenciduzenleme/",methods=['POST'])
def dgsogrenciduzenleme():
    if request.method == 'POST':
      db = Database()
      ogrenci_numara = request.form['ogrenci_numara']
      ogrenci_isim = request.form['ogrenci_isim']
      ogrenci_soyisim = request.form['ogrenci_soyisim']
      ogrenci_ogretim = request.form['ogrenci_ogretim']
      onceki_okul = request.form['onceki_okul']

      ogrenci_bilgisi = (ogrenci_isim,ogrenci_soyisim,ogrenci_ogretim,onceki_okul,ogrenci_numara)
      db.ogrenciduzenle(ogrenci_bilgisi)

    return redirect("dgs-ogrenci")

@app.route('/ogrencibilgileri/<int:numara>')
def ogrencibilgileri(numara):
    db = Database()
    sonuc = db.ogrencilistele(numara)
    stajlar= db.ogrencistajlistele(numara)

    return render_template("ogrenciduzenle.html",sonuc=sonuc,stajlar=stajlar)

@app.route("/ogrenciduzenle")
def ogrenciduzenle():
    return render_template("ogrenciduzenle.html")

@app.route("/ogrenciduzenleme",methods=['POST'])
def ogrenciduzenleme():
    if request.method == 'POST':
      db = Database()
      ogrenci_numara = request.form['ogrenci_numara']
      ogrenci_isim = request.form['ogrenci_isim']
      ogrenci_soyisim = request.form['ogrenci_soyisim']
      ogrenci_ogretim = request.form['ogrenci_ogretim']
      staj_toplam_gun = request.form['staj_toplam_gun']
      ogrenci_bilgisi = (ogrenci_isim,ogrenci_soyisim,ogrenci_ogretim,staj_toplam_gun,ogrenci_numara)
      db.ogrenciduzenle(ogrenci_bilgisi)

    return redirect("ogrenci")

# --------------------------------Komisyon--------------------------------------

@app.route("/komisyon")
def komisyon():
     db = Database()
     result = db.akademisyen()
     return render_template("komisyon.html",result=result)

@app.route("/komisyon-ekle")
def komisyon_ekle():
     return render_template("komisyon-ekle.html")

@app.route('/komisyonekleme',methods = ['POST'])
def komisyonekleme():
   if request.method == 'POST':
      db = Database()
      komisyon_numara = request.form['komisyon_numara']
      komisyon_isim = request.form['komisyon_isim']
      komisyon_soyisim = request.form['komisyon_soyisim']
      komisyon_unvan = request.form['komisyon_unvan']
      akademisyen_bilgisi = (komisyon_numara,komisyon_isim,komisyon_soyisim,komisyon_unvan)
      db.akademisyenekle(akademisyen_bilgisi)
      return redirect("komisyon")

@app.route('/komisyonbilgileri/<int:numara>')
def komisyonbilgileri(numara):
    db = Database()
    sonuc = db.komisyonlistele(numara)
    return render_template("komisyonduzenle.html",sonuc=sonuc)

@app.route("/komisyonduzenle")
def komisyonduzenle():
    return render_template("komisyonduzenle.html")

@app.route("/komisyonduzenleme",methods=['POST'])
def komisyonduzenleme():
    if request.method == 'POST':
      db = Database()
      komisyon_numara = request.form['komisyon_numara']
      komisyon_isim = request.form['komisyon_isim']
      komisyon_soyisim = request.form['komisyon_soyisim']
      komisyon_unvan = request.form['komisyon_unvan']
      komisyon_bilgisi = (komisyon_isim,komisyon_soyisim,komisyon_unvan,komisyon_numara)
      db.komisyonduzenle(komisyon_bilgisi)

    return redirect("komisyon")

@app.route('/komisyonsil/<int:numara>')
def komisyonsil(numara):
    db = Database()
    db.komisyonsil(numara)
    return redirect('/komisyon')

#------------------------------------Staj---------------------------------------

@app.route("/staj")
def staj():
     db = Database()
     result = db.staj()
     return render_template("staj.html",result=result)

@app.route("/staj-ekle")
def staj_ekle():
     db = Database()
     result = db.ogrenci()
     komisyon = db.akademisyen()
     staj_kurum = db.stajkurumlistele()
     staj_konu = db.stajkonulistele()
     dgs_ogrenci = db.dgsogrenci()
     return render_template("staj-ekle.html",result=result,komisyon=komisyon,staj_kurum=staj_kurum,dgs_ogrenci=dgs_ogrenci,staj_konu=staj_konu)

@app.route('/stajsil/<int:numara>/<string:baslangic>')
def stajsil(numara,baslangic):
    db = Database()
    data=(numara, baslangic)
    db.stajsil(data)
    return redirect('/dgs-ogrenci')

@app.route("/kurumekleme", methods = ['POST'])
def kurum_ekle():
     db = Database()

     if request.method == 'POST':
          kurum_adi = request.form['kurum_adi']
          db.kurumekle(kurum_adi)
     return redirect("/staj-ekle")

@app.route("/konuekleme", methods = ['POST'])
def konu_ekle():
     db = Database()

     if request.method == 'POST':
          konu_isim = request.form['konu_isim']
          db.konuekle(konu_isim)
     return redirect("/staj-ekle")

@app.route('/stajekleme', methods=['GET', 'POST'])
def stajekleme():
    db = Database()

    if request.method == 'POST':
        ogrenci_numara = request.form['ogrenci_numara']
        staj_baslama_tarihi = request.form['staj_baslama_tarihi']
        staj_bitis_tarihi = request.form['staj_bitis_tarihi']
        staj_kurum = request.form['staj_kurum']
        staj_sehir = request.form['staj_sehir']
        staj_konu = request.form['staj_konu']
        staj_toplam_gun = request.form['staj_toplam_gun']
        mulakat_kontrol = request.form['mulakat_kontrol']
        staj_sinif = request.form['staj_sinif']
        mulakat_tarih = request.form['mulakat_tarih']
        mulakat_saat = request.form['mulakat_saat']
        komisyon_uye_1 = request.form['komisyon_uye_1']
        komisyon_uye_2 = request.form['komisyon_uye_2']
        devam = request.form['devam']
        caba_ve_calisma = request.form['caba_ve_calisma']
        amire_karsi_davranis = request.form['amire_karsi_davranis']
        is_arkadasina_karsi_davranis = request.form['is_arkadasina_karsi_davranis']
        isi_vaktinde_yapma = request.form['isi_vaktinde_yapma']
        proje = request.form['proje']
        duzen = request.form['duzen']
        sunum = request.form['sunum']
        icerik = request.form['icerik']
        mulakat = request.form['mulakat']
        staj_kabul_edilen_gun = request.form['staj_kabul_edilen_gun']
        if (int(staj_sinif == 2) and int(staj_toplam_gun) > 25) :
             hata = "2. Sınıf Öğrencisi Maksimum 25 Gün Staj Yapabilir."
             return render_template("staj.html",hata=hata)
        if  (int(staj_toplam_gun) < 15) :
             hata = "15 günden az staj Yapılamaz"
             return render_template("staj.html",hata=hata)
        else:
          data = (ogrenci_numara, staj_baslama_tarihi, staj_bitis_tarihi,staj_sehir,staj_konu,staj_kurum,staj_toplam_gun,staj_sinif,staj_kabul_edilen_gun,mulakat_kontrol,mulakat_tarih,mulakat_saat,komisyon_uye_1,komisyon_uye_2,devam,caba_ve_calisma,isi_vaktinde_yapma,amire_karsi_davranis,is_arkadasina_karsi_davranis,proje,duzen,sunum,icerik,mulakat)
          db.stajekle(data)

    return redirect('/staj')

@app.route("/ayarlar")
def ayarlar():

     return render_template("ayarlar.html")

if __name__ == "__main__":
   app.run(debug = True)


from django.urls import re_path
from pretalx.event.models.event import SLUG_CHARS

from .views import UpstreamSettings

urlpatterns = [
    re_path(
        rf"^orga/event/(?P<event>[{SLUG_CHARS}]+)/settings/p/upstream/$",
        UpstreamSettings.as_view(),
        name="settings",
    )
]


"""
Serialization means persist storage to disk
storing data between ex
Relational storage writes data to tables
Object-based storage stores objects as they are used in code (Object databases)
Object-relational mappings can mediate between the two
Unlike pickle, json is readable by humans and uses "" and , to separate
"""
import json
with open('backup_config.json') as fh:
    conf = json.load(fh)

conf['newinputs'] = 5.0005

with open('backup_config.json','w') as fh:
    json.dump(conf,fh)

# more readable
with open('backup_config.json','w') as fh:
    json.dump(conf,fh, indent = 4, separators=(',',': '))

print(conf)
print(type(conf))

#%%
import json
x_dict = {'a':[1,2,3], 'c':[7,8,9], 'b':[4,5,6]}
x = json.dumps(x_dict)
mystruct = json.loads(x)
for key, val in mystruct.items():
    print(key,val)


#!/usr/bin/python3

from collections import namedtuple

Complex = namedtuple('Complex', ['r', 'i']) #criar tuplo Complex, novo tipo de dados, neste caso com dois campos, um r e um i

def addComplex(x, y):
    # Complex number addition: (a+b*i) + (c+d*i) = (a+c) + (b+d)*i
    a= x.r  #a é a parte real do primeiro numero
    b= x.i  #a é a parte imaginaria do primeiro numero
    c= y.r #c é a parte real do segundo numero
    d= y.i #d é a parte imaginaria do segundo numero
    return Complex(a+c, b+d) #valor real e imaginario da soma pela formula da soma de numeros complexos
    #IMPORTANTE: adicionar o Complex, para que o resultado da adição dos valores dos tuplos seja retornado também como um tuplo
def multiplyComplex(x, y):
    # Complex number multiplication: (a+b*i) x (c+d*i) = (a*c-b*d) + (a*d+b*c)*i
    a = x.r  # a é a parte real do primeiro numero
    b = x.i  # a é a parte imaginaria do primeiro numero
    c = y.r  # c é a parte real do segundo numero
    d = y.i  # d é a parte imaginaria do segundo numero
    return Complex(a*c-b*d, a*d+b*c )  # valor real e imaginario da multiplicação pela formula da multiplicação de numeros complexos

def printComplex(x, prefix=''):  #prefixo vazio por defeito, mas pode ser editado

    r = x.r #parte real é a primeira posição (0) do numero x
    i = x.i #parte imag é a segunda posição (1) do numero x
    print(prefix + str(r) + '+' + str(i) + 'i')

def main():

    # define two complex numbers as tuples of size two
    c1 = Complex(5, 3)
    c2 = Complex(-2, 7)

    printComplex(c1, prefix='c1= ')
    printComplex(c2, prefix='c2= ')

    # Test add
    c3 = addComplex(c1, c2)
    printComplex(c3,prefix='Addition: c3= ')

    # test multiply
    c3 = multiplyComplex(c1, c2)
    printComplex(c3,prefix='Multiplication: c3= ')

if __name__ == '__main__':
    main()


from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.AllPost.as_view(), name='home'),
    path('view/<int:pk>', views.ViewPost.as_view(), name="view-post"),
    path('new/', views.CreatePost.as_view(), name="create-post"),
    path('update/<int:pk>', views.UpdatePost.as_view(), name="update-post"),
]


import datetime
from datetime import date

def years(age):
    n = 100 - age
    after_hundred_years = date.today().year+n
    after = after_hundred_years
    return after

def main():
    name = input("What's your name? ")
    age = int(input("How old are you? "))
    number = int(input("Type a number pls: "))
    years(age)
    after = years(age)
    print((name+", you will be 100 years old in: " + str(after)+" ")*number)
    for i in range(number):
        print(name+", you will be 100 years old in:", str(after) )

    return

if __name__ == '__main__':
    main()


import os
import shutil
import pandas as pd
import librosa
import numpy as np

path_howjsay = "full_data/howjsay/"
list_howjsay = []
for word_dir in os.listdir(path_howjsay):
    path_file = path_howjsay + word_dir
    print(path_file)
    L = os.listdir(path_file)
    for i in L:
        if i.endswith('.wav'):
            list_howjsay.append(i.lower())

path_shabadkosh = "full_data/shabadkosh/"
list_shabadkosh = []
for word_dir in os.listdir(path_shabadkosh):
    path_file = path_shabadkosh + word_dir
    print(path_file)
    L = os.listdir(path_file)
    for i in L:
        if i.endswith('.wav'):
            i.split('_')
            only_word = i.split('_')[0]+'.wav'
            list_shabadkosh.append(only_word.lower())

def common_words(list1, list2):
    list1_set = set(list1)
    # print(len(list_set))
    intersection = list1_set.intersection(set(list2))
    # print(intersection)
    intersection = list(intersection)
    intersection.sort()
    return intersection

intersection = common_words(list_shabadkosh, list_howjsay)
base_path = [path_howjsay, path_shabadkosh]
train_path = []
train_label = []

test_path = []
test_label = []
def making_csvs():
    for word_name in intersection:
        if len(word_name.split('.')[0])>=3:
            for source in base_path:
                folder_name = word_name.split('.')[-2]
                middle_path = str(word_name.split('.')[0][0])+ 'words' +'/'
                if 'shabadkosh' in source.split('/') :
                    for id_number in range(1, 5):
                        filename_id = word_name.split('.')[0] + '_pid' + str(id_number) + '.' + word_name.split('.')[1]
                        scr = source + middle_path + filename_id
                        label = str(word_name.split('.')[0])
                        train_path.append(scr)
                        train_label.append(label)
                else:
                    scr = source + middle_path + word_name
                    label = str(word_name.split('.')[0])
                    test_path.append(scr)
                    test_label.append(label)
    return train_path, train_label, test_path, test_label

def sorting_dataframe_by_shape(data_dataframe):
    count = 0
    spectograms_dataframe = []
    for file_path in data_dataframe['file_path']:
        y, sr = librosa.load(file_path)
        count = count + 1
        print("iteration---->", count)
        mel = librosa.feature.melspectrogram(y=y, sr=sr)
        # print('mel1----->', mel.shape)
        mel = np.transpose(mel, [1, 0])
        # mel = np.expand_dims(mel, -1)
        # print("mel2nd shape----->", mel.shape)
        spectograms_dataframe.append(mel)
    # print(spectograms)
    spectograms_dataframe = np.array(spectograms_dataframe)
    print('done with spectograms dataframe')
    shape_dataframe = []
    for array in spectograms_dataframe:
        shape_dataframe.append(array.shape[0])
    data_dataframe['shape'] = shape_dataframe
    data_dataframe = data_dataframe.sort_values(by=['shape'])
    return data_dataframe

train_path, train_label, test_path, test_label = making_csvs()
# arsh_train_path = train_path[0:400]
# arsh_train_label = train_label[0:400]
# arsh_test_path = test_path[0:100]
# arsh_test_label = test_label[0:100]
train_csv_arsh = pd.DataFrame(data = {'file_path' : train_path, 'lable' : train_label})
sorted_train = sorting_dataframe_by_shape(train_csv_arsh)
sorted_train.to_csv("train_new.csv", index = False)
test_csv_arsh = pd.DataFrame(data = {'file_path' : test_path, 'lable' : test_label})
sorted_test = sorting_dataframe_by_shape(test_csv_arsh)
sorted_test.to_csv("test_new.csv", index = False)
# mohit_train_path = train_path[-400:]
# mohit_train_label = train_label[-400:]
# train_csv_mohit = pd.DataFrame(data = {'file_path' : mohit_train_path, 'lable' : mohit_train_label})
# train_csv_mohit.to_csv("train_mohit.csv", index = False)

# mohit_test_path = test_path[-100:]
# mohit_test_label = test_label[-100:]

# test_csv_mohit = pd.DataFrame(data = {'file_path' : mohit_test_path, 'lable' : mohit_test_label})
# test_csv_mohit.to_csv("test_mohit.csv", index = False)


from pyathena import connect
from dataall.base.aws.sts import SessionHelper

class AthenaClient:
    """ Makes requests to AWS Athena """

    @staticmethod
    def run_athena_query(aws_account_id, env_group, s3_staging_dir, region, sql=None):
        base_session = SessionHelper.remote_session(accountid=aws_account_id)
        boto3_session = SessionHelper.get_session(base_session=base_session, role_arn=env_group.environmentIAMRoleArn)
        creds = boto3_session.get_credentials()
        connection = connect(
            aws_access_key_id=creds.access_key,
            aws_secret_access_key=creds.secret_key,
            aws_session_token=creds.token,
            work_group=env_group.environmentAthenaWorkGroup,
            s3_staging_dir=s3_staging_dir,
            region_name=region,
        )
        cursor = connection.cursor()
        cursor.execute(sql)

        return cursor

    @staticmethod
    def convert_query_output(cursor):
        columns = []
        for f in cursor.description:
            columns.append({'columnName': f[0], 'typeName': 'String'})

        rows = []
        for row in cursor:
            record = {'cells': []}
            for col_position, column in enumerate(columns):
                cell = {}
                cell['columnName'] = column['columnName']
                cell['typeName'] = column['typeName']
                cell['value'] = str(row[col_position])
                record['cells'].append(cell)
            rows.append(record)
        return {
            'error': None,
            'AthenaQueryId': cursor.query_id,
            'ElapsedTime': cursor.total_execution_time_in_millis,
            'rows': rows,
            'columns': columns,
        }


# pip install openpyxl, pandas, unicodecsv

import pandas as pd
import unicodecsv

# reads a CSV file
def read_csv(path):
    with open(path, "rb") as f:
        reader = list(unicodecsv.DictReader(f, delimiter=";"))
        return reader

def getZerokWhCharges(path):
    # converts excel .xlsx file into a pandas.Dataframe
    data = pd.DataFrame(read_csv(path))
    # cleanses every null value in the "Energy consumed (wh)" column
    zero = data[data['Energy consumed (wh)'].astype('int64') == 0]
    whitespace = data[data['Energy consumed (wh)'].astype('str') == '']
    null = data[data['Energy consumed (wh)'].isnull()]

    data = zero.append(whitespace).append(null)

    # saving to an excel file
    data.to_excel(path[:path.rindex("/") + 1] + '0kWh charges.xlsx', index=False, sheet_name='Without Null Values')

def returnZerokWhCharges(data):
    # converts excel .xlsx file into a pandas.Dataframe
    # cleanses every null value in the "Energy consumed (wh)" column
    zero = data[data['Energy consumed (wh)'].astype('int64') == 0]
    whitespace = data[data['Energy consumed (wh)'].astype('str') == '']
    null = data[data['Energy consumed (wh)'].isnull()]

    data = zero.append(whitespace).append(null)
    data['Reason'] = '0KWh'
    return data


import datetime
from django.shortcuts import render_to_response
from django.template import Context
from django.template.loader import get_template

__author__ = 'alexey'
from django.http import HttpResponse, Http404

def hello(request):
    return HttpResponse("Hello World - This is response!")

def current_time(request):
    #result = "Current time is %s." % datetime.datetime.now()
    #return HttpResponse(result)
    return render_to_response('CurrentTime.html', {'current_time': datetime.datetime.now()})

def shifted_time(request, hour_shift, minute_shift):
    try:
        hours = int(hour_shift)
        minutes = int(minute_shift)
    except ValueError:
        raise Http404()
    time = datetime.datetime.now()+datetime.timedelta(hours=hours, minutes=minutes)
    #return HttpResponse("Shifted time is %s. Hour shift = %s, minute shift = %s" % (time, hour_shift, minute_shift))
    return render_to_response('ShiftedTime.html', locals())

def template_time(request):
    now = datetime.datetime.now()
    #template = get_template("TestTemplate.html")
    #return HttpResponse(template.render(Context({'current_date': now})))

    return render_to_response('TestTemplate.html',{'current_date': now})


#!/usr/bin/env python
# coding: utf-8

# In[1]:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
get_ipython().run_line_magic('matplotlib', 'inline')

# In[2]:

customers = pd.read_csv("Ecommerce Customers")

# In[3]:

customers.head()

# In[4]:

customers.describe()

# In[5]:

customers.info()

# In[7]:

sns.set_palette("GnBu_d")
sns.set_style('whitegrid')

# In[8]:

sns.jointplot(x='Time on Website',y='Yearly Amount Spent',data=customers)

# In[9]:

sns.jointplot(x='Time on App',y='Yearly Amount Spent',data=customers)

# In[10]:

sns.jointplot(x='Time on App',y='Length of Membership',kind = 'hex',data=customers)

# In[11]:

sns.pairplot(customers)

# In[13]:

sns.lmplot(x = 'Length of Membership',y='Yearly Amount Spent', data = customers)

# # Training and Testing Data

# In[15]:

customers.nunique()

# In[16]:

X = customers[['Avg. Session Length', 'Time on App', 'Time on Website', 'Length of Membership']]
y = customers['Yearly Amount Spent']

# In[17]:

from sklearn.model_selection import train_test_split

# In[18]:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=101)

# # Training

# In[19]:

from sklearn.linear_model import LinearRegression

# In[20]:

lm = LinearRegression()

# In[21]:

lm.fit(X_train,y_train)

# In[22]:

print('Coefficients: \n', lm.coef_)

# # Predicting the Data

# In[23]:

predictions = lm.predict(X_test)

# In[24]:

plt.scatter(y_test,predictions)
plt.xlabel('Y Test')
plt.ylabel('Predicted Y')

# In[26]:

##Evaluating the Model

# In[27]:

from sklearn import metrics

# In[28]:

print('MAE:', metrics.mean_absolute_error(y_test, predictions))
print('MSE:', metrics.mean_squared_error(y_test, predictions))
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))

# In[29]:

sns.distplot((y_test-predictions),bins=50);

# In[30]:

coeffecients = pd.DataFrame(lm.coef_,X.columns)
coeffecients.columns = ['Coeffecient']
coeffecients

# Interpreting the coefficients:
#
# Holding all other features fixed, a 1 unit increase in Avg. Session Length is associated with an increase of 25.98 total dollars spent.
# Holding all other features fixed, a 1 unit increase in Time on App is associated with an increase of 38.59 total dollars spent.
# Holding all other features fixed, a 1 unit increase in Time on Website is associated with an increase of 0.19 total dollars spent.
# Holding all other features fixed, a 1 unit increase in Length of Membership is associated with an increase of 61.27 total dollars spent.

# In[ ]: