from math import floor
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import tensorflow as tf

import fuzzy_ART
import AE_class_2

fuzzy_ART_MODE = "TRAIN"
results_dir = "results/fuzzyART_w_AE-2/"

################################ Helper Functions #############################

def get_data():
    mnist = pd.read_csv("datasets/MNIST/mnist_test.csv").values
    data = {}
    for i in range(0,10):
        mask = mnist[:,0]==i
        temp = mnist[mask]
        temp = temp/255
        np.random.shuffle(temp)
        temp = temp[0:5, 1:]      # 5 images of each digit
        data[str(i)] = temp
    return data

def preprocess_for_AE(data_dict):
    data_array = []
    for i in range(0,10):
        data_array.append( data_dict[str(i)] )
    data_array = np.array(data_array).reshape(10*data_dict[str(i)].shape[0], 784)

    data_array = AE_class_2.data_preprocess(data_array)

    return data_array

def preprocess_for_ART(data_array):
    data_array = data_array.reshape(-1,32)
    return data_array

def train_fuzzy_ART(model, data_array, shuffle_data=False):
    if shuffle_data:
        np.random.shuffle(data_array)

    for i in range(data_array.shape[0]):
        Z, k = model.train(data_array[i])

        enc_learned_wts = Z[:32].reshape(4,8)
        plt.imshow(enc_learned_wts) #display learned expectations
        plt.title("Viz. of learned encoded digit: {}, sample:{}".format(str( floor( i/(data_array.shape[0]/10) ) ),
                                                                        str( i%(data_array.shape[0]/10) + 1)) )
        #plt.savefig( results_dir+"encoded_wts/"+"{}_{}.png".format(str(floor(i/5)),str(i%5 + 1)) )
        plt.show()

        print("CLASS: ", k)

    return model

def test(model):
    test_data = pd.read_csv("datasets/MNIST/mnist_test.csv").values
    np.random.shuffle(test_data)
    test_data = test_data[:1001, :]
    test_data_labels = np.array(test_data[:,0])
    test_data = test_data[:,1:]

    test_data = test_data.reshape(-1, 28, 28)
    test_data = np.expand_dims(test_data, 3)

    test_data = AE_class_2.data_preprocess(test_data)
    encoded_test_data = AE_model.autoencode(test_data, True)

    encoded_test_data = preprocess_for_ART(encoded_test_data)

    ART_output = []
    for i in range(0,encoded_test_data.shape[0]):
        op = ART_model.infer( encoded_test_data[i] )
        #if op[0] is None and op[1] is None:
            #op = [0, ART_model.N]

        ART_output.append(op[1])
    ART_output = np.array(ART_output)

    accuracy = np.mean( np.equal(test_data_labels, ART_output) ) * 100

    return accuracy, ART_output, test_data_labels

def Purity(model):
    _,  ART_output, test_data_labels = test(ART_model)

    #combined = np.vstack([ART_output, test_data_labels]).T
    categories = {}
    purity_list = []
    for i in range(np.max(ART_output)+1):

        mask = ART_output==i
        temp = test_data_labels[mask]  # labels of data belonging to category i

        categories[str(i)] = temp
        if temp.shape[0] > 0:
            most_freq_label = np.argmax( np.bincount(temp) )
            purity_for_curr_category = np.mean( temp==most_freq_label ) *100
        else:
            purity_for_curr_category = 0
        purity_list.append( purity_for_curr_category)

    purity = np.mean( np.array(purity_list) )
    return purity, categories

############### Load pre-trained Tensorflow AutoEncoder model #################
AE_model = AE_class_2.AutoEncoder()
AE_model.load_model("models/TF-AE/")

#####################################  TEST  ##################################

if fuzzy_ART_MODE is "TEST":
    # Load pre-trained fuzzy art model
    ART_rho = 0.95  # vigilance parameter
    ART_model = fuzzy_ART.fuzzy_ART(32,
                                    c_max=20,
                                    rho=ART_rho,
                                    alpha=0.00001,
                                    beta=1)
    ART_model.load_params("models/fuzzyART_w_AE-2_weights")

    accuracy, _, _ = test(ART_model)
    print("Test accuracy: ", accuracy)

################################# or TRAIN ####################################

elif fuzzy_ART_MODE is "TRAIN":
    '''
    In this case, the fuzzy ART model will be trained on the data encoded by the
    pretrained Autoencoder
    '''
    np.random.seed(0)
    #initialize a fuzzy ART model for training
    ART_rho = 0.999830 # vigilance parameter
    ART_model = fuzzy_ART.fuzzy_ART(32,
                                    c_max=20,
                                    rho=ART_rho,
                                    alpha=0.000001,
                                    beta=1)

    ART_train_data = get_data()

    preprocessed_data =  preprocess_for_AE(ART_train_data)
    encoded_train_data = AE_model.autoencode(preprocessed_data, True)

    encoded_train_data = preprocess_for_ART(encoded_train_data)

    n_epochs = 1
    #acc_list = []
    purity_list = []
    for e in range(n_epochs):
        ART_model = train_fuzzy_ART(ART_model, encoded_train_data, shuffle_data=False)
        #accuracy, _, _ = test(ART_model)
        purity, Categories = Purity(ART_model)

        #print("Test accuracy at epoch {}: {}".format(e+1, accuracy))
        print("Purity at epoch {}: {}".format(e+1, purity))
        #acc_list.append(accuracy)
        purity_list.append(purity)

    if n_epochs > 1:
        plt.plot(purity_list)
        plt.show()

    '''
    n = np.random.randint(encoded_train_data.shape[0])
    sample = encoded_train_data[n]
    inference = ART_model.infer(sample)
    '''
    #ART_model.save_params("models/fuzzyART_w_AE-2_weights")

    ######################### save preprocessed_data ##########################
    '''
    for i in range(preprocessed_data.shape[0]):
        img = preprocessed_data[i].squeeze()
        plt.imshow(img) #display learned expectations
        plt.title("ART train data -- digit: {}, sample:{}".format(str(floor(i/5)),str(i%5 + 1)))
        plt.savefig( results_dir+"ART_train_data/"+"{}_{}.png".format(str(floor(i/5)),str(i%5 + 1)) )
        plt.show()
    '''

    '''

    #ART_rho_list = [0.99978, 0.9997048, 0.9997052, 0.9997054, 0.9997055, 0.9997057, 0.9997058, 0.999706, 0.9997065, 0.9997068]
    ART_rho_list = ( np.random.rand(5)*2 - 1 )*0.00001 + 0.999817
    ART_rho_list = np.sort(ART_rho_list)
    #ART_rho_list = [0.99983, 0.999831, 0.999832]
    #alpha_list = ( np.random.rand(5)*2 - 1 )*0.07 +0.1
    purity_list=[]
    #n_epochs = 1

    np.random.seed(0)

    for rho in ART_rho_list:
        ART_model = fuzzy_ART.fuzzy_ART(32,
                                    c_max=20,
                                    rho=rho,
                                    alpha=0.0001,
                                    beta=1)

        ART_model = train_fuzzy_ART(ART_model, encoded_train_data, shuffle_data=False)

        purity, Categories = Purity(ART_model)

        print("Purity for rho={}:  {} ".format(rho, purity))

        purity_list.append(purity)

    plt.plot(ART_rho_list, purity_list)
    plt.show()

    '''


# Zaimplementuj klasę Employee umożliwiającą rejestrowanie czasu
# pracy oraz wypłacanie pensji na podstawie zadanej stawki
# godzinowej. Jeżeli pracownik będzie pracował więcej niż 8 godzin
# (podczas pojedynczej rejestracji czasu) to kolejne godziny policz
# jako nadgodziny (z podwójną stawką godzinową).
# Przykład użycia:
# >>> employee = Employee('Jan', 'Nowak', 100.0)
# >>> employee.register_time(5)
# >>> employee.pay_salary()
# 500.0
# >>> employee.pay_salary()
# 0.0
# >>> employee.register_time(10)
# >>> employee.pay_salary()
# 1200.0
class Pracownik:
    def __init__(self, imie, nazwisko, stawka):
        self.imie = imie
        self.nazwisko = nazwisko
        self.stawka = stawka
        self.przepracowane_godziny = 0

    def rejestruj_czas(self, czas):
        self.przepracowane_godziny += czas
        if czas > 8:
            self.przepracowane_godziny += czas - 8

    def wyplata(self):
        wyplata = self.przepracowane_godziny * self.stawka
        self.przepracowane_godziny = 0
        return wyplata

p = Pracownik("Jan", "Nowak", 100)
p.rejestruj_czas(5)
print(p.wyplata())
p.rejestruj_czas(5)
p.rejestruj_czas(5)
print(p.wyplata())
print(p.wyplata())
p.rejestruj_czas(10)
print(p.wyplata())


"""
Actual helper script to execute code.
It takes care of proper error handling (e.g. if you press CTRL+C) and the difference between
running code on the robot vs. in simulation.

Usage:
  python3 run.py --sim lab1 [for simulation]
  python3 run.py lab1 [to run on a robot]
"""

import sys
import argparse
import importlib

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("run", help="run specified module")
    parser.add_argument("--sim", help="Run using VREP simulation", action="store_true")
    args = parser.parse_args()
    clientID = None
    if args.sim:
        from factory import FactorySimulation
        factory = FactorySimulation()
    else:
        from factory import FactoryCreate
        factory = FactoryCreate()
    try:
        if args.run.endswith(".py"):
            args.run = args.run[:-3]
        mod = importlib.import_module(args.run)
        Run = getattr(mod, "Run")
        r = Run(factory)
        r.run()
    except KeyboardInterrupt:
        pass
    except:
        factory.close()
        raise

    factory.close()

    # quit
    sys.exit()


import pandas as pd
import numpy as np
file="SCW Check - BurstFound 4U 1323-62.csv"
convertfile="scwtosec.csv"
df=pd.read_csv(file)
N=len(df)

#len(df)
df.iloc[:,7]=0
converter=pd.read_csv(convertfile)
for j in range(N):
    for i in range(len(converter)):
        if int(converter.iloc[i,1]) == int(df.iloc[j,1]):
            df.iloc[j,7]=converter.iloc[i,2]

if df.empty:
    print("No data")
else:
    df.to_csv("withsec"+file, sep=',', encoding="utf-8" , index=False)

#2000130010
#23701060010
#2390011001
#23900120010
#100400140010


from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
from usertemplates import models, forms

class TemplateEditorView(TemplateView):
    http_method_names = ['get', 'post', ]
    template_name = 'templateEditorView.html'

    def get(self, request, template_id=None, *args, **kwargs):
        context = self.get_context_data()
        context['page_title'] = 'Template Editor'

        if template_id is None:
            context['template_form'] = forms.TemplateForm()
        else:
            template = models.Template.objects.get(pk=template_id)
            context['template_form'] = forms.TemplateForm(instance=template)
            context['template_id'] = template_id
        return self.render_to_response(context=context)

    def post(self, request, template_id=None, *args, **kwargs):
        if template_id is None:
            form = forms.TemplateForm(request.POST)
        else:
            template = models.Template.objects.get(pk=template_id)
            form = forms.TemplateForm(request.POST,
                                      instance=template)
        if form.is_valid():
            form.clean()
            form.save()
            return HttpResponse(content="Tudo certo...")
        else:
            return HttpResponse(content="Verifique os campos...")


import RPi.GPIO as GPIO
from time import sleep
from datetime import datetime

# Pins
light = 22 # Pin for light relay control

mp_in1 = 24 # Direction control for main pump
mp_in2 = 23 # Direction control for main pump
mp_en = 25 # main pump

np_in1 = 17 # nutrients direction 1
np_in2 = 27 # nutrients direction 2
np_en = 18 # nutrients enable

GPIO.setmode(GPIO.BCM) # Chooses board

# Setup output pins for pumps and relays
GPIO.setup(mp_in1,GPIO.OUT)
GPIO.setup(mp_in2,GPIO.OUT)
GPIO.setup(mp_en,GPIO.OUT)
GPIO.setup(light,GPIO.OUT)
GPIO.setup(np_in1,GPIO.OUT)
GPIO.setup(np_in2,GPIO.OUT)
GPIO.setup(np_en,GPIO.OUT)

# intialize output pin states
GPIO.output(light,GPIO.LOW)
GPIO.output(mp_in1,GPIO.HIGH)
GPIO.output(mp_in2,GPIO.LOW)
GPIO.output(np_in1,GPIO.LOW)
GPIO.output(np_in2,GPIO.HIGH)

# Run main pump at normal rate
p=GPIO.PWM(mp_en,500)
p.start(35)

n = GPIO.PWM(np_en,500)
n.start(40)

light_flag = False # initialize light state to off

# Constants
midnight = datetime(1,1,1,23,0,0).time()
morning = datetime(1,1,1,5,0,0).time()

while (1):
    time = datetime.now().time() # Get current time

    # Set lights to proper staet
    if light_flag == True and (time > midnight or time < morning):
        GPIO.output(light,GPIO.LOW)
        light_flag = False
    elif light_flag == False and not (time > midnight or time < morning):
        GPIO.output(light,GPIO.HIGH)
        light_flag = True


from selenium import webdriver
from bs4 import BeautifulSoup
import os
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from scrapy.selector import Selector
#import mysql入库 as mysqltool

def get_data(driver,name):
    data = Selector(text=driver.page_source)

    for res in data.xpath('//*[@id="poilist"]/div'):
        url=res.xpath('a/@href').extract_first()
        shopname=res.xpath('div[@class="content"]/*/div[1]/div/text()').extract_first()
        if 'None'==shopname:
            continue
        star=','.join(res.xpath('div[@class="content"]/*/div[2]/div[1]/i/@class').extract())
        shopsold=res.xpath('div[@class="content"]/*/div[2]/div[2]/text()').extract_first()
        shopright=res.xpath('div[@class="content"]/*/div[2]/i[1]/text()').extract_first()
        shoptime=res.xpath('div[@class="content"]/*/div[2]/i[3]/text()').extract_first()
        sendprice=''.join(res.xpath('div[@class="content"]/*/div[3]/span[1]/em/text()').extract())
        deliveryfee=''.join(res.xpath('div[@class="content"]/*/div[3]/span[2]/text()').extract())

        shopdata='%s[}%s[}%s[}%s[}%s[}%s[}%s[}%s[}%s' %(url,shopname,star,shopsold,shopright,shoptime,sendprice,deliveryfee,name)
        with open('C:/Users/Administrator/Desktop/美团外卖/shoplist_%s_1.txt' %name, 'a', encoding='utf-8') as f:
            f.write(shopdata)
            f.write('\n')

'''
    for i in range(0,9):
        driver.find_element_by_xpath('//*[@id="loading"]/div').click()
        time.sleep(5)

    data=driver.page_source
    soup=BeautifulSoup(data,"html.parser")
    list_data=soup.find('ul',attrs={'class':'list clearfix'}).find_all('li',attrs={'class':'fl rest-li'})
    for res in list_data:
        shop_id=res.find('a',attrs={'class':'rest-atag'}).get('href')
        with open('C:/Users/Administrator/Desktop/list.txt', 'a', encoding='utf-8') as f:
            f.write(shop_id)
            f.write('\n')

#url='http://i.waimai.meituan.com/home?lat=30.541111&lng=104.059155'
urllist=[#'http://i.waimai.meituan.com/home?lat=30.627222&lng=104.06055,玉林',
         #'http://i.waimai.meituan.com/home?lat=30.634774&lng=104.031921,紫荆',
         #'http://i.waimai.meituan.com/home?lat=30.619286&lng=104.075643,科华',
         #'http://i.waimai.meituan.com/home?lat=30.622109&lng=104.098407,锦华',
         #'http://i.waimai.meituan.com/home?lat=30.632749&lng=104.029313,红牌楼',
         #'http://i.waimai.meituan.com/home?lat=30.645977&lng=104.033134,双楠',
         #'http://i.waimai.meituan.com/home?lat=30.670267&lng=103.978478,光华',
         #'http://i.waimai.meituan.com/home?lat=30.681726&lng=104.012659,金沙',
         #'http://i.waimai.meituan.com/home?lat=30.705653&lng=104.013817,茶店子',
         #'http://i.waimai.meituan.com/home?lat=30.690691&lng=104.047379,老会展',
         #'http://i.waimai.meituan.com/home?lat=30.697218&lng=104.073694,北站',
         #'http://i.waimai.meituan.com/home?lat=30.677707&lng=104.096474,府青',
         #'http://i.waimai.meituan.com/home?lat=30.669313&lng=104.11071,建设路',
         #'http://i.waimai.meituan.com/home?lat=30.644231&lng=104.119188,万年场',
         'http://i.waimai.meituan.com/home?lat=30.646149&lng=104.109381,双桥',
        ]

url='http://waimai.meituan.com/home/wm6n2ev4q1x5'
chrome_driver = os.path.abspath(r"C:/Program Files (x86)/Google/Chrome/Application/chromedriver2.30.exe")
os.environ["webdriver.chrome.driver"] = chrome_driver
driver = webdriver.Chrome(chrome_driver)
driver.get(url)
get_data(driver)
driver.quit()

file_name='shoplist_%s' %urllist[0].split(',')[1]
for url in urllist:
        mobileEmulation = {'deviceName': 'iPhone 6 Plus'}
        options = webdriver.ChromeOptions()
        options.add_experimental_option('mobileEmulation', mobileEmulation)
        driver = webdriver.Chrome(executable_path='C:/Program Files (x86)/Google/Chrome/Application/chromedriver2.30.exe', chrome_options=options)
        driver.set_page_load_timeout(100)
        driver.set_script_timeout(100)
        driver.get(url.split(',')[0])
        time.sleep(5)
        #driver.maximize_window()
        driver.find_element_by_xpath('//*[@id="primary_item_bar_new"]/a[1]/img').click()
        time.sleep(5)
        for i in range(80):
            #driver.execute_script("window.scrollBy(0,200)", "")  # 向下滚动200px
            driver.execute_script("window.scrollBy(0,document.body.scrollHeight)","")#向下滚动到页面底部
            time.sleep(3)
        get_data(driver,url.split(',')[1])
        driver.quit()

#sql='insert into meituanshop(url,shopname,star,shopsold,shopright,shoptime,startprice,deliveryfee,CBD) values'
#mysqltool.get_sql(sql,file_name)
'''
def get_img(driver,line):
    id = line.split('[}')[1].replace('\n', '')
    url = 'http://www.dianping.com/shop/%s' % str(id)
    time.sleep(1)
    driver.get(url)
    data=Selector(text=driver.page_source)
    id = url.split('/')[-3]
    id1 = line.split('[}')[0].replace('\n', '')
    name = line.split('[}')[2].replace('\n', '')
    imglist = []
    try:
        for sel in data.xpath('//div[@class="shop-tab-recommend J-panel"]/ul/li'):
            imglist.append(sel)
        for sel in imglist:
            imgurl = sel.xpath('img/@src').extract_first()
            goods = sel.xpath('img/@alt').extract_first()
            if goods == None:
                continue
            img = '%s_photo_%d.jpg' % (name, imglist.index(sel))
            print(goods, imgurl)
            imgdata = '%s[}%s[}%s[}%s[}%s' % (id1, id, name, goods,img)
            print(imgdata)
            # tool.GetImg(imgdir3, imgurl, img)
            # with open('C:/Users/Administrator/Desktop/shangping_20171106.txt', 'a', encoding='utf-8') as f:
            #    f.write(imgdata)
            #    f.write('\n')
    except:
        print(url)

chrome_driver = os.path.abspath(r"C:/Program Files (x86)/Google/Chrome/Application/chromedriver2.30.exe")
os.environ["webdriver.chrome.driver"] = chrome_driver
driver = webdriver.Chrome(chrome_driver)
driver.get('http://www.dianping.com/citylist')

start_urls=[]
with open('C:/Users/Administrator/Desktop/20171103.txt', 'r', encoding='utf-8') as f:
    for line in f:
        start_urls.append(line.replace('\n', ''))

get_img(driver,'183[}10333429[}MorningHouse')


from __future__ import annotations

from typing import TYPE_CHECKING

from cleo.io.null_io import NullIO
from packaging.utils import canonicalize_name
from poetry.core.packages.package import Package

from poetry.factory import Factory
from tests.helpers import get_package
from tests.mixology.helpers import add_to_repo
from tests.mixology.helpers import check_solver_result
from tests.mixology.version_solver.conftest import Provider

if TYPE_CHECKING:
    from poetry.core.packages.project_package import ProjectPackage

    from poetry.repositories import Repository
    from poetry.repositories import RepositoryPool

def test_with_compatible_locked_dependencies(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", "*"))

    add_to_repo(repo, "foo", "1.0.0", deps={"bar": "1.0.0"})
    add_to_repo(repo, "foo", "1.0.1", deps={"bar": "1.0.1"})
    add_to_repo(repo, "foo", "1.0.2", deps={"bar": "1.0.2"})
    add_to_repo(repo, "bar", "1.0.0")
    add_to_repo(repo, "bar", "1.0.1")
    add_to_repo(repo, "bar", "1.0.2")

    locked = [get_package("foo", "1.0.1"), get_package("bar", "1.0.1")]
    provider = Provider(root, pool, NullIO(), locked=locked)

    check_solver_result(
        root,
        provider,
        result={"foo": "1.0.1", "bar": "1.0.1"},
    )

def test_with_incompatible_locked_dependencies(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", ">1.0.1"))

    add_to_repo(repo, "foo", "1.0.0", deps={"bar": "1.0.0"})
    add_to_repo(repo, "foo", "1.0.1", deps={"bar": "1.0.1"})
    add_to_repo(repo, "foo", "1.0.2", deps={"bar": "1.0.2"})
    add_to_repo(repo, "bar", "1.0.0")
    add_to_repo(repo, "bar", "1.0.1")
    add_to_repo(repo, "bar", "1.0.2")

    locked = [get_package("foo", "1.0.1"), get_package("bar", "1.0.1")]
    provider = Provider(root, pool, NullIO(), locked=locked)

    check_solver_result(
        root,
        provider,
        result={"foo": "1.0.2", "bar": "1.0.2"},
    )

def test_with_unrelated_locked_dependencies(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", "*"))

    add_to_repo(repo, "foo", "1.0.0", deps={"bar": "1.0.0"})
    add_to_repo(repo, "foo", "1.0.1", deps={"bar": "1.0.1"})
    add_to_repo(repo, "foo", "1.0.2", deps={"bar": "1.0.2"})
    add_to_repo(repo, "bar", "1.0.0")
    add_to_repo(repo, "bar", "1.0.1")
    add_to_repo(repo, "bar", "1.0.2")
    add_to_repo(repo, "baz", "1.0.0")

    locked = [get_package("baz", "1.0.1")]
    provider = Provider(root, pool, NullIO(), locked=locked)

    check_solver_result(
        root,
        provider,
        result={"foo": "1.0.2", "bar": "1.0.2"},
    )

def test_unlocks_dependencies_if_necessary_to_ensure_that_a_new_dependency_is_satisfied(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", "*"))
    root.add_dependency(Factory.create_dependency("newdep", "2.0.0"))

    add_to_repo(repo, "foo", "1.0.0", deps={"bar": "<2.0.0"})
    add_to_repo(repo, "bar", "1.0.0", deps={"baz": "<2.0.0"})
    add_to_repo(repo, "baz", "1.0.0", deps={"qux": "<2.0.0"})
    add_to_repo(repo, "qux", "1.0.0")
    add_to_repo(repo, "foo", "2.0.0", deps={"bar": "<3.0.0"})
    add_to_repo(repo, "bar", "2.0.0", deps={"baz": "<3.0.0"})
    add_to_repo(repo, "baz", "2.0.0", deps={"qux": "<3.0.0"})
    add_to_repo(repo, "qux", "2.0.0")
    add_to_repo(repo, "newdep", "2.0.0", deps={"baz": ">=1.5.0"})

    locked = [
        get_package("foo", "2.0.0"),
        get_package("bar", "1.0.0"),
        get_package("baz", "1.0.0"),
        get_package("qux", "1.0.0"),
    ]
    provider = Provider(root, pool, NullIO(), locked=locked)

    check_solver_result(
        root,
        provider,
        result={
            "foo": "2.0.0",
            "bar": "2.0.0",
            "baz": "2.0.0",
            "qux": "1.0.0",
            "newdep": "2.0.0",
        },
    )

def test_with_compatible_locked_dependencies_use_latest(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", "*"))
    root.add_dependency(Factory.create_dependency("baz", "*"))

    add_to_repo(repo, "foo", "1.0.0", deps={"bar": "1.0.0"})
    add_to_repo(repo, "foo", "1.0.1", deps={"bar": "1.0.1"})
    add_to_repo(repo, "foo", "1.0.2", deps={"bar": "1.0.2"})
    add_to_repo(repo, "bar", "1.0.0")
    add_to_repo(repo, "bar", "1.0.1")
    add_to_repo(repo, "bar", "1.0.2")
    add_to_repo(repo, "baz", "1.0.0")
    add_to_repo(repo, "baz", "1.0.1")

    locked = [
        get_package("foo", "1.0.1"),
        get_package("bar", "1.0.1"),
        get_package("baz", "1.0.0"),
    ]
    provider = Provider(root, pool, NullIO(), locked=locked)

    check_solver_result(
        root,
        provider,
        result={"foo": "1.0.2", "bar": "1.0.2", "baz": "1.0.0"},
        use_latest=[canonicalize_name("foo")],
    )

def test_with_compatible_locked_dependencies_with_extras(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", "^1.0"))

    package_foo_0 = get_package("foo", "1.0.0")
    package_foo_1 = get_package("foo", "1.0.1")
    bar_extra_dep = Factory.create_dependency(
        "bar", {"version": "^1.0", "extras": "extra"}
    )
    for package_foo in (package_foo_0, package_foo_1):
        package_foo.add_dependency(bar_extra_dep)
        repo.add_package(package_foo)

    bar_deps = {"baz": {"version": "^1.0", "extras": ["extra"]}}
    add_to_repo(repo, "bar", "1.0.0", bar_deps)
    add_to_repo(repo, "bar", "1.0.1", bar_deps)
    add_to_repo(repo, "baz", "1.0.0")
    add_to_repo(repo, "baz", "1.0.1")

    locked = [
        get_package("foo", "1.0.0"),
        get_package("bar", "1.0.0"),
        get_package("baz", "1.0.0"),
    ]
    provider = Provider(root, pool, NullIO(), locked=locked)

    check_solver_result(
        root,
        provider,
        result={"foo": "1.0.0", "bar": "1.0.0", "baz": "1.0.0"},
    )

def test_with_yanked_package_in_lock(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", "*"))

    add_to_repo(repo, "foo", "1")
    add_to_repo(repo, "foo", "2", yanked=True)

    # yanked version is kept in lock file
    locked_foo = get_package("foo", "2")
    assert not locked_foo.yanked
    provider = Provider(root, pool, NullIO(), locked=[locked_foo])
    result = check_solver_result(
        root,
        provider,
        result={"foo": "2"},
    )
    assert result is not None
    foo = result.packages[0]
    assert foo.yanked

    # without considering the lock file, the other version is chosen
    provider = Provider(root, pool, NullIO())
    check_solver_result(
        root,
        provider,
        result={"foo": "1"},
    )

def test_no_update_is_respected_for_legacy_repository(
    root: ProjectPackage, repo: Repository, pool: RepositoryPool
) -> None:
    root.add_dependency(Factory.create_dependency("foo", "^1.0"))

    foo_100 = Package(
        "foo", "1.0.0", source_type="legacy", source_url="http://example.com"
    )
    foo_101 = Package(
        "foo", "1.0.1", source_type="legacy", source_url="http://example.com"
    )
    repo.add_package(foo_100)
    repo.add_package(foo_101)

    provider = Provider(root, pool, NullIO(), locked=[foo_100])
    check_solver_result(
        root,
        provider,
        result={"foo": "1.0.0"},
    )


import csv
import pandas as pd
from _datetime import datetime as dt
#print(dt.now())
tsv_file=f"Required Data/paths_finished.tsv"
dict_paths={}
dict_shortest_path={}
shortestpath_file=f"Required Data/shortest-path-distance-matrix.txt"
#file1 = open("myfile.txt","w")
articles=pd.DataFrame(pd.read_csv('article-ids.csv'))
articles_idlist=articles['Article_ID'].values.tolist()
data_file = open('finished-paths-no-back.csv', 'w+',newline='',encoding='utf-8')
csv_writer = csv.writer(data_file)
header=['Human_Path_Length','Shortest_Path_Length','Ratio']
csv_writer.writerow([header[0],header[1],header[2]])
data_file1 = open('own_ref.csv', 'w+',newline='',encoding='utf-8')
csv_writer1 = csv.writer(data_file1)
header=['Actual_path','Interpreted_path','Human_Path_Length','Shortest_Path_Length','Ratio']
csv_writer1.writerow([header[0],header[1],header[2],header[3],header[4]])
def remove_backspace(path_str):
    temp=path_str.split(';')
    new_str=[]
    ret_str=''
    for i in temp:
        if i=='<':
            new_str.pop()
            new_str.pop()
        else:
            new_str.append(i)
            new_str.append(';')
    len_new_str=len(new_str)
    if new_str[len_new_str-1]==';':
        new_str.pop()
    for i in new_str:
        ret_str+=i
    #print(ret_str)
    return ret_str

with open(shortestpath_file) as sf:
    i=0
    for line in sf:
        #dict_shortest_path[articles_idlist[i]]=[]
        if '#' in line[0]:
            #print('Hi')
            continue
        elif line=='\n':
            continue
        else:
            sentence=line
            for j in range(len(sentence)-1):
                if sentence[j]=='_':
                    if articles_idlist[i] in dict_shortest_path:
                        dict_shortest_path[articles_idlist[i]].append('99999')
                    else:
                        dict_shortest_path[articles_idlist[i]]=['99999']

                else:
                    if articles_idlist[i] in dict_shortest_path:
                        dict_shortest_path[articles_idlist[i]].append(sentence[j])
                    else:
                        dict_shortest_path[articles_idlist[i]]=[sentence[j]]
                    #print(i,j)
                    #dict_shortest_path[articles_idlist[i]].append(sentence[j])
            i+=1

#print(dict_shortest_path['A0001'][13])
with open(tsv_file, 'r') as f:
    reader = csv.reader(f, delimiter='\t')
    for row in reader:
        #print(row)
        try:
            if '#' in row[0] or row=='\n':
               # print(row)
                continue
            else:
                path_temp=row[3]
                #print(row[1]," ",row[2]," ",row[3])
                #print(path_temp)

                if '<;' in path_temp:
                    path_temp1 = remove_backspace(path_temp)
                    # path_temp = path_temp.replace('<;', '')
                    path_length = path_temp1.count(';') #+ 1
                    shortest_path = path_temp1.split(';')
                    article_id_source = articles.loc[articles['Article_Name'] == shortest_path[0], 'Article_ID'].iloc[0]
                    # print(path_temp," ",path_length," ",article_id_source)
                    shortest_path_length = 0
                    article_id_dest = articles.loc[articles['Article_Name'] == shortest_path[-1], 'Article_ID'].iloc[0]
                    article_id_index = articles_idlist.index(article_id_dest)
                    shortest_path_length += int(dict_shortest_path[article_id_source][article_id_index])
                    if shortest_path_length == 99999:
                        continue
                    else:
                        csv_writer.writerow(
                            [ path_length, shortest_path_length,
                             round(path_length / shortest_path_length, 2)])
                        csv_writer1.writerow([path_temp, path_temp1,path_length, shortest_path_length,
                             round(path_length / shortest_path_length, 2)])
                    continue
                elif ';' not in path_temp:
                    continue
                else:
                #path_temp = path_temp.replace('<;', '')
                    path_length = path_temp.count(';') #+ 1
                    shortest_path=path_temp.split(';')
                    article_id_source = articles.loc[articles['Article_Name'] == shortest_path[0], 'Article_ID'].iloc[0]
                    shortest_path_length=0
                    article_id_dest=articles.loc[articles['Article_Name'] == shortest_path[-1], 'Article_ID'].iloc[0]
                    article_id_index = articles_idlist.index(article_id_dest)
                    shortest_path_length += int(dict_shortest_path[article_id_source][article_id_index])
                    if shortest_path_length==99999:
                        continue
                    else:
                        csv_writer.writerow(
                        [ path_length, shortest_path_length, round(path_length / shortest_path_length, 2)])
                        csv_writer1.writerow([path_temp, path_temp, path_length, shortest_path_length,
                                              round(path_length / shortest_path_length, 2)])

        except:
            continue
data_file.close()


"""Creates alerts from a csv"""

import csv
import irflow_client
import pprint
import logging
from time import gmtime, strftime

pp = pprint.PrettyPrinter(indent=4)

irflowAPI = irflow_client.IRFlowClient(config_file="./api.conf")
if irflowAPI.debug:
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.INFO)

logger = logging.getLogger('IR-Flow: CSV Example')

if irflowAPI.debug:
    irflowAPI.dump_settings()

alert_type = 'ds_test'
description = 'New CSV Alert on ' + strftime("%Y-%m-%d %H:%M:%S", gmtime())

with open('sample_csv_of_alerts.csv', 'rb') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        result = irflowAPI.create_alert(row, description=description, incoming_field_group_name=alert_type)
        if result['success']:
            logger.info('Created Alert_Num: ' + str(result['data']['alert']['alert_num']))
        else:
            logger.error('Failed to create alert')
            logger.error('Success == ' + str(result['success']))
            pp.pprint(result)


'''
Escribe una función que calcule el área de un triángulo, recibiendo la altura
y la base como parámetros y otra función que calcule el área de un círculo
recibiendo el radio del mismo.
'''
import math
def area_triangulo(base, altura):
    area = float((base * altura)/2)
    return area

def area_circulo(radio):
    area = float(math.pi * radio**2)
    return area

base = float(input('Introduzca la medida de la base del triángulo: '))
altura = float(input('Introduzca la medida de la altura del triángulo: '))
area_t = area_triangulo(base, altura)
print(f'El área del triángulo con base {base} cm y altura {altura} cm es de {area_t} cm^2')

radio = (input('Introduzca la medida del radio del círculo: '))
area_c = area_circulo(float(radio))
print(f'El área del círculo con radio {radio} cm es de {area_c} cm^2')


# スクリプトモジュールを実行できるようにするためのファイル

from flask_script import Manager
from show_data import app

from show_data.scripts.db import InitDB, DropDB, InsertDummy, SelectAll

if __name__ == "__main__":
    manager = Manager(app)
    # init_dbコマンドを実行できるようにする
    manager.add_command('init_db', InitDB())
    # drop_dbコマンドを実行できるようにする
    manager.add_command('drop_db', DropDB())
    # insert_dummyコマンドを実行できるようにする
    manager.add_command('insert_dummy', InsertDummy())
    manager.add_command('select_all', SelectAll())

    manager.run()


import h5py
import matplotlib.pyplot as plt
import numpy as np
import argparse
from scipy.optimize import curve_fit

fig_dict={0:(0,0),1:(0,1),2:(0,2),3:(0,3),4:(0,4),5:(0,5),6:(0,6),7:(0,7),
        8:(1,0),9:(1,1),10:(1,2),11:(1,3),12:(1,4),13:(1,5),14:(1,6),15:(1,7),
        16:(2,0),17:(2,1),18:(2,2),19:(2,3),20:(2,4),21:(2,5),15:(2,6),16:(2,7),
        24:(3,0),25:(3,1),26:(3,2),27:(3,3),28:(3,4),29:(3,5),30:(3,6),31:(3,7),
        32:(4,0),33:(4,1),34:(4,2),35:(4,3),36:(4,4),37:(4,5),38:(4,6),39:(4,7),
        40:(5,0),41:(5,1),42:(5,2),43:(5,3),44:(5,4),45:(5,5),46:(5,6),47:(5,7),
        48:(6,0),49:(6,1),50:(6,2),51:(6,3),52:(6,4),53:(6,5),54:(6,6),55:(6,7),
        56:(7,0),57:(7,1),58:(7,2),59:(7,3),60:(7,4),61:(7,5),62:(7,6),63:(7,7)}
ch_dict={7:(0,0),11:(0,1),15:(0,2),23:(0,3),
         27:(1,0),30:(1,1),39:(1,2),43:(1,3),
         45:(2,0),55:(2,1),59:(2,2),60:(2,3)}

def gauss(x, A, mu, sigma): return A*np.exp(-(x-mu)**2/(2*sigma**2))

def basic_parsing(f):
    parity_mask=f['packets'][:]['valid_parity']==1
    data_mask=f['packets'][:]['packet_type']==0
    mask = np.logical_and(parity_mask,data_mask)
    return f['packets'][mask]

def plot_adc_dist(p, nrows=3, ncols=4):
    unique_channels = np.unique(p['channel_id'])
    fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(24,12))
    bins=np.linspace(0,255,256)
    for uc in unique_channels:
        mask = p['channel_id']==uc
        adc=p[mask]['dataword']
        ax[ch_dict[uc][0]][ch_dict[uc][1]].hist(adc,bins=bins)
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_xlabel('ADC')
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_ylabel('Packet Count')
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_yscale('log')
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_title('Channel '+str(uc))
    plt.tight_layout()
    plt.show()

def plot_timestamp_vs_adc(p, nrows=3, ncols=4):
    unique_channels = np.unique(p['channel_id'])
    fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(24,12))
    for uc in unique_channels:
        mask = p['channel_id']==uc
        adc=p[mask]['dataword']
        timestamp = p[mask]['timestamp']
        ax[ch_dict[uc][0]][ch_dict[uc][1]].scatter(timestamp,adc)
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_xlabel('Timestamp')
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_ylabel('ADC')
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_title('Channel '+str(uc))
    plt.tight_layout()
    plt.show()

def find_extrema(l, out):
    temp = max(l)
    if abs(min(l))>temp: temp=abs(min(l))
    out.append(temp)
    return

def find_static_linearity(p, nrows=3, ncols=4):
    fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, sharey=True, figsize=(30,22))
    fig1, ax1 = plt.subplots(nrows=1, ncols=2, figsize=(12,6))
    fig2, ax2 = plt.subplots(nrows=1, ncols=2, figsize=(10,4))
    fig3, ax3 = plt.subplots(nrows=1, ncols=2, figsize=(10,4))
    dnl_extrema, inl_extrema = [[] for i in range(2)]
    unique_channels = np.unique(p['channel_id'])
    for uc in unique_channels:
        mask = p['channel_id']==uc
        adc=p[mask]['dataword']
        vals, bin_edges = np.histogram(adc, bins=256, range=(0,256))

        meanDict, runningSum = [{} for k in range(2)]
        dnl_val, dnl_adc, inl_val = [{} for k in range(3)]
        for k in range(1,255): # exclude first and last ADC bins
            meanDict[k]=0; runningSum[k]=0
            dnl_val[k]=[]; dnl_adc[k]=[]; inl_val[k]=[]

        for k in range(1,255): # exclude first and last ADC bins
            for l in range(1,255):
                if l>=k: meanDict[l] += vals[k]

        for key in meanDict.keys(): meanDict[key] = meanDict[key]/key

        for k in range(1,255):
            for l in range(1,255):
                if l>=k:
                    dnl = (vals[k]-meanDict[l])/meanDict[l]
                    dnl_val[l].append( dnl )
                    runningSum[l]+=dnl
                    inl_val[l].append( runningSum[l] )
                    dnl_adc[l].append(k)

        find_extrema(dnl_val[254], dnl_extrema)
        find_extrema(inl_val[254], inl_extrema)

        ax[ch_dict[uc][0]][ch_dict[uc][1]].plot(dnl_adc[254],dnl_val[254])
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_xlabel('ADC')
        if ch_dict[uc][1]==0:
            ax[ch_dict[uc][0]][ch_dict[uc][1]].set_ylabel('DNL [LSB]', \
                                                          color='tab:blue', \
                                                          fontweight='bold')
        ax[ch_dict[uc][0]][ch_dict[uc][1]].legend(title='Channel '+str(uc), loc='upper center')
        ax[ch_dict[uc][0]][ch_dict[uc][1]].grid(True)
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_xlim(0,255)
        ax[ch_dict[uc][0]][ch_dict[uc][1]].set_ylim(-0.5,0.5)
        axtwin = ax[ch_dict[uc][0]][ch_dict[uc][1]].twinx()
        axtwin.plot(dnl_adc[254],inl_val[254], color='k')
        if ch_dict[uc][1]==3:
            axtwin.set_ylabel('INL [LSB]', fontweight='bold')
        axtwin.set_ylim(-4,4)
        if ch_dict[uc][1]!=3:
            axtwin.set_yticklabels([])
        if uc==7:
            ax2[0].plot(dnl_adc[254], dnl_val[254])
            ax3[0].plot(dnl_adc[254], inl_val[254])

    fig.subplots_adjust(wspace=0, hspace=0)
#    fig.tight_layout()
    bins=np.linspace(0.2,0.4,21)
    hist, bin_edges = np.histogram(dnl_extrema, bins=20, \
                                   range=(0.2,0.4))
    params, cov = curve_fit(gauss, bin_edges[:-1], hist, \
                            p0=[max(hist), np.mean(dnl_extrema),
                                np.std(dnl_extrema)])
    ax1[0].hist(dnl_extrema, bins=bins)
    ax1[0].plot(bin_edges[:-1], gauss(bin_edges[:-1], *params), \
                '-', label=r'Fit'+'\n'+'$\mu$={:.2f}$\pm${:.2f}'.format(params[1], np.sqrt(cov[1][1]))+'\n'+'$\sigma$={:.2f}$\pm${:.2f}'.format(params[2], np.sqrt(cov[2][2])))

    ax1[0].set_xlabel('DNL Extrema')
    ax1[0].set_ylabel('Channel Count / 0.01 LSB')
    ax1[0].grid(True)
    ax1[0].set_xlim(0.2,0.4)
    ax1[0].legend()

    ax2[1].hist(dnl_extrema, bins=bins)
    ax2[1].plot(bin_edges[:-1], gauss(bin_edges[:-1], *params), \
                '-', label=r'Fit'+'\n'+'$\mu$={:.2f}$\pm${:.2f}'.format(params[1], np.sqrt(cov[1][1]))+'\n'+'$\sigma$={:.2f}$\pm${:.2f}'.format(params[2], np.sqrt(cov[2][2])))

    bins=np.linspace(2,4,21)
    hist, bin_edges = np.histogram(inl_extrema, bins=20, \
                                   range=(2,4))
    params, cov = curve_fit(gauss, bin_edges[:-1], hist, \
                            p0=[max(hist), np.mean(inl_extrema),
                                np.std(inl_extrema)])
    ax1[1].hist(inl_extrema, bins=bins)
    ax1[1].plot(bin_edges[:-1], gauss(bin_edges[:-1], *params), \
                '-', label=r'Fit'+'\n'+'$\mu$={:.2f}$\pm${:.2f}'.format(params[1], np.sqrt(cov[1][1]))+'\n'+'$\sigma$={:.2f}$\pm${:.2f}'.format(params[2], np.sqrt(cov[2][2])))
    ax1[1].set_xlabel('INL Extrema')
    ax1[1].set_ylabel('Channel Count / 0.1 LSB')
    ax1[1].grid(True)
    ax1[1].set_xlim(2,4)
    ax1[1].legend()

    ax3[1].hist(inl_extrema, bins=bins)
    ax3[1].plot(bin_edges[:-1], gauss(bin_edges[:-1], *params), \
                '-', label=r'Fit'+'\n'+'$\mu$={:.2f}$\pm${:.2f}'.format(params[1], np.sqrt(cov[1][1]))+'\n'+'$\sigma$={:.2f}$\pm${:.2f}'.format(params[2], np.sqrt(cov[2][2])))
#    fig1.tight_layout()

    for i in range(2):
        ax2[i].grid(True)
        ax3[i].grid(True)
    ax2[0].set_xlabel('ADC')
    ax2[0].set_ylabel('DNL [LSB]')
    ax3[0].set_xlabel('ADC')
    ax3[0].set_ylabel('INL [LSB]')
    ax2[0].set_xlim(0,255)
    ax2[0].set_ylim(-0.5,0.5)
    ax3[0].set_xlim(0,255)
    ax3[0].set_ylim(-3,3)
    ax2[1].set_xlabel('DNL Extrema')
    ax3[1].set_xlabel('INL Extrema')
    ax2[1].set_ylabel('Channel Count')
    ax2[1].set_xlim(0.2,0.4)
    ax3[1].set_ylabel('Channel Count')
    ax3[1].set_xlim(2,4)
    ax2[1].legend()
    ax3[1].legend()

    plt.show()

def main(**kwargs):
    f = h5py.File('/home/russell/LArPix/v2_ASIC_paper/data/v2a/adc-linearity/f.h5','r');
    p = basic_parsing(f)
#    plot_adc_dist(p)
#    plot_timestamp_vs_adc(p)
    find_static_linearity(p)
    return

if __name__=='__main__':
    parser = argparse.ArgumentParser()
    args = parser.parse_args()
    main(**vars(args))


while True:
    elements = []
    light = int(input())
    if light == 0:
            break

    for i in range(1, light+1):

        if light % i == 0:
            elements.append(i)

    if len(elements) % 2 ==0:
        print("no")
    else:
        print("yes")


from rest_framework import generics, permissions
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from transformers import pipeline, AutoTokenizer
from optimum.onnxruntime import ORTModelForSequenceClassification
from .models import Video
from .youtube_data import get_comments_for_video, advanced_get_comments_for_video, get_video_details
from googleapiclient.model import HttpError
from .serializers import VideoSerializer, UserSerializer
from django.contrib.auth.models import User
import random
import dateutil.parser
from django.shortcuts import get_object_or_404

MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = ORTModelForSequenceClassification.from_pretrained("rest_api/onnx")
troberta = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer, max_length=512, truncation=True)

def preprocess(comments):
    new_comments = []
    for comment in comments:
        new_text = []
        for t in comment.split(" "):
            t = '@user' if t.startswith('@') and len(t) > 1 else t
            t = 'http' if t.startswith('http') else t
            new_text.append(t)
        new_comments.append(" ".join(new_text))
    return new_comments

def get_percentages(preds):
    pos_count = 0
    neg_count = 0
    neu_count = 0
    for pred in preds:
        if pred['label'] == 'positive':
            pos_count += 1
        elif pred['label'] == 'negative':
            neg_count += 1
        else:
            neu_count += 1
    total = pos_count + neg_count + neu_count

    def to_percentage(count):
        return round(count / total * 100, 1)

    return {'Positive': to_percentage(pos_count), 'Negative': to_percentage(neg_count),
            'Neutral': to_percentage(neu_count)}

def match_comments_preds(comments, preds):
    matched = []
    for comment, pred in zip(comments, preds):
        if pred['label'] == 'positive':
            matched.append([comment, 'Pos'])
        elif pred['label'] == 'negative':
            matched.append([comment, 'Neg'])
        else:
            matched.append([comment, 'Neu'])
    return matched

# noinspection PyMethodMayBeStatic
class GetSentiment(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        video_id = request.query_params.get('video_id')
        if video_id is None:
            return Response({"detail": "video_id parameter not supplied"})
        priority = request.query_params.get('priority')
        if priority:
            comment_count = int(request.query_params.get('comment_count'))
            like_count = int(request.query_params.get('like_count'))
            min_max_like_count = True if request.query_params.get('min_max_like_count') == 'min' else False
            date = dateutil.parser.isoparse(request.query_params.get('date'))
            try:
                comments = advanced_get_comments_for_video(video_id, priority, comment_count, like_count,
                                                           min_max_like_count, date)
            except HttpError:
                return Response({"detail": "one or more parameter is missing/invalid"})
        else:
            try:
                comments = get_comments_for_video(video_id)
            except HttpError:
                return Response({"detail": "video has disabled comments"})
        if len(comments) == 0:
            return Response({"detail": "video has no comments"})
        output = get_percentages(troberta(preprocess(comments)))
        output['CommentCount'] = len(comments)
        example_comments = random.sample(comments, min(len(comments), 10))
        example_preds = troberta(preprocess(example_comments))
        output['analysedCommentExamples'] = match_comments_preds(example_comments, example_preds)
        video_details = get_video_details(video_id)
        video = Video(
            title=video_details['title'],
            channel_title=video_details['channel_title'],
            category=video_details['category'],
            published_date=video_details['date'],
            thumbnail=video_details['thumbnailUrl'],
            comment_count=output['CommentCount'],
            pos_pct=output['Positive'],
            neu_pct=output['Neutral'],
            neg_pct=output['Negative'],
            analyzed_comment_examples=output['analysedCommentExamples'],
            user=self.request.user
        )
        video.save()
        video_details['date'] = video_details['date'].strftime("%B %d, %Y")
        output['videoDetails'] = video_details
        return Response(output)

class VideoList(generics.ListAPIView):
    queryset = Video.objects.all()
    serializer_class = VideoSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return super().get_queryset().filter(
            user=self.request.user
        )

class UserCreate(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.AllowAny]

# noinspection PyMethodMayBeStatic
class GetUser(APIView):
    permission_classes = [permissions.AllowAny]

    def get(self, request, email):
        user = get_object_or_404(User, email__exact=email)
        serializer = UserSerializer(user)
        return Response(serializer.data)

# noinspection PyMethodMayBeStatic
class ApiRoot(APIView):
    permission_classes = [permissions.AllowAny]

    def get(self, request):
        return Response({
            'get-sentiment': reverse('get-sentiment', request=request),
            'user-create': reverse('user-create', request=request),
            'videos': reverse('video-list', request=request)
        })