from django.shortcuts import render, redirect
from django.db.models import Max
from .models import News, CountryData, CountryNews, DailyData

import requests
from os import path
from bs4 import BeautifulSoup
from datetime import datetime
from fbprophet import Prophet
import pandas as pd

country_dict = {"USA": "United States of America", "UK": "United Kingdom", "UAE": "United Arab Emirates",
                "S. Korea": "Korea South", "Czechia": "Czech Republic", "North Macedonia": "Macedonia",
                "Ivory Coast": "Cote d Ivoire", "DRC": "Democratic Republic of the Congo", "Taiwan": "Republic of China",
                "Réunion": "France", "Palestine": "Palestinian territory", "Congo": "Republic of the Congo",
                "Guinea-Bissau": "Guinea Bissau", "Faeroe Islands": "Faroe Islands", "Cabo Verde": "Cape Verde",
                "Eswatini": "Swaziland", "CAR": "Central African Republic", "Timor-Leste": "East Timor", "Curaçao": "Curacao",
                "St. Vincent Grenadines": "Saint Vincent and the Grenadines", "Turks and Caicos": "Turks and Caicos Islands",
                "British Virgin Islands": "Virgin Islands British", "St. Barth": "Saint Barthelemy", "Caribbean Netherlands": "Netherlands",
                "Saint Pierre Miquelon": "Saint Pierre and Miquelon"}

def scrape_world():
    source = requests.get('https://www.worldometers.info/coronavirus/').text
    soup = BeautifulSoup(source, 'lxml')

    totals = soup.find_all('div', class_='maincounter-number')
    world_data = []
    for total in totals:
        world_data.append(total.span.text)

    return world_data

def india_state_data():
    url_state = 'https://api.covid19india.org/data.json'
    request_state = requests.get(url_state)
    data_state = request_state.json()

    url_district = 'https://api.covid19india.org/v2/state_district_wise.json'
    request_district = requests.get(url_district)
    data_district = request_district.json()

    states = data_state['statewise'][1:]

    for state in states:
        district_raw = [obj for obj in data_district if obj['state'] == state['state']]
        districts = district_raw[0]['districtData']

        state['districts'] = districts

    return states

def state_data(state):
    url_state = 'https://api.covid19india.org/data.json'
    request_state = requests.get(url_state)
    data_state = request_state.json()

    states = data_state['statewise'][1:]
    x = [obj for obj in states if obj['state'] == state]
    return x

def district_data(state):
    url_district = 'https://api.covid19india.org/v2/state_district_wise.json'
    request_district = requests.get(url_district)
    data_district = request_district.json()

    district_raw = [obj for obj in data_district if obj['state'] == state]
    districts = district_raw[0]['districtData']

    return districts

def state_daily_data(state_code):
    url_daily = 'https://api.covid19india.org/states_daily.json'
    request_daily = requests.get(url_daily)
    data_daily = request_daily.json()['states_daily']

    date      = [x["date"] for x in data_daily if x["status"] == 'Confirmed']
    confirmed = [x[state_code] for x in data_daily if x['status'] == 'Confirmed']
    recovered = [x[state_code] for x in data_daily if x['status'] == 'Recovered']
    deceased  = [x[state_code] for x in data_daily if x['status'] == 'Deceased']

    return {'date': date, 'confirmed': confirmed, 'recovered': recovered, 'deceased': deceased}

def district_daily_data(state, district):
    url_daily = 'https://api.covid19india.org/districts_daily.json'
    request_daily = requests.get(url_daily)
    data_daily = request_daily.json()['districtsDaily'][state][district]

    date      = [x["date"] for x in data_daily]
    active    = [x["active"] for x in data_daily]
    confirmed = [x["confirmed"] for x in data_daily]
    recovered = [x["recovered"] for x in data_daily]
    deceased  = [x["deceased"] for x in data_daily]

    return {'date': date, 'active': active, 'confirmed': confirmed, 'recovered': recovered, 'deceased': deceased}

def predictions2(country):
    if country == 'World':
        world = DailyData.objects.filter(country='World')
        world_values = world.values('date','totalcase')
        country_data = pd.DataFrame.from_records(world_values)
        country = 'World'
    else:
        if country == 'United States':
            country='US'
        data = requests.get('https://pomber.github.io/covid19/timeseries.json').json()
        country_data = data[country]
        country = 'Other'

    df = pd.DataFrame(country_data)

    if country == 'World':
        df.rename(columns={'date': 'ds', 'totalcase': 'y'}, inplace=True)
    else:
        df.rename(columns={'date': 'ds', 'confirmed': 'y'}, inplace=True)

    m = Prophet(changepoint_prior_scale=5, interval_width=1)
    m.fit(df)

    future = m.make_future_dataframe(periods=15)
    forecast = m.predict(future)
    updated_forecast = forecast[['ds', 'yhat_upper']]

    tail_updated_forecast = updated_forecast.tail(15)

    tail_updated_forecast.set_index('ds', inplace=True)

    return tail_updated_forecast

def predict_country(country):
    url = "https://pomber.github.io/covid19/timeseries.json"
    countries = requests.get(url).json()
    countries['World'] = True
    countries['US'] = True

    x = country
    r = [country for country in countries if country == x]

    if len(r) != 0:
        df = predictions2(country)
        df.rename(columns={'ds':'dates','yhat_upper':'predictions'},inplace=True)
        df.reset_index(inplace=True)
        df = df.to_json()
        return {'data':df}

    else:
        return {'data':'failed'}

def home(request):
    world_data = scrape_world()

    recoveries=int(world_data[2].replace(',', ''))
    deaths = int(world_data[1].replace(',', ''))

    total_outcome = int(recoveries) + int(deaths)
    recovery_percent = round((int(recoveries) / int(total_outcome)) * 100, 2)
    death_percent = round(100 - recovery_percent, 2)

    worlddailydata = DailyData.objects.filter(country='World')
    return render(request, 'home.html',
                  {'world_total': world_data[0], 'world_death': world_data[1], 'world_recovery': world_data[2],
                   'world_daily_data': worlddailydata, 'closed_cases':total_outcome, 'recovery_percent':recovery_percent,
                   'death_percent':death_percent})

def graphs(request):
    #daily_data()
    world_daily_data = DailyData.objects.filter(country='World')

    countries_to_exclude = ['International']
    max_date = DailyData.objects.aggregate(Max('date'))['date__max']
    percentage_data = DailyData.objects.exclude(country__in=countries_to_exclude).filter(date__exact=str(max_date)).order_by('-totalcase')

    for data in world_daily_data:
        data.date = str(data.date)

    return render(request,'graphs.html', {'world_daily_data' : world_daily_data[32:], 'percentage_data': percentage_data})

def news(request):
    #scrape_news()
    latest_news = News.objects.all().order_by('-id')
    return render(request, 'news.html', {'latest_news': latest_news})

def country(request):
    #scrape()
    countries = CountryData.objects.order_by('-totalcase')
    return render(request, 'country.html', {'countries': countries})

def country_detail(request, country_name):

    if country_name == 'India':
        return redirect('india')

    news = CountryNews.objects.filter(country=country_name).order_by('-id')[:9]
    #country_daily_data(country_name)

    dailydata = DailyData.objects.filter(country=country_name)

    country_data = CountryData.objects.get(name__iexact=f'{country_name}')
    return render(request, 'country_detail.html', {'country': country_data, 'latest_news': news, 'countrydailydata':dailydata[32:]})

def world(request):
    world_data = scrape_world()
    worlddailydata = DailyData.objects.filter(country='World')
    return render(request, 'world.html', {'world_total': world_data[0], 'world_death': world_data[1], 'world_recovery': world_data[2], 'worlddailydata' : worlddailydata})

def search(request):

    if request.method == "POST":
        data = request.POST['data']
        news = News.objects.filter(heading__contains=data).order_by('-id')
        return render(request,'news.html', {'latest_news':news})
    else:
        pass

    return redirect('/')

def news_detail(request, news_id):
    news = News.objects.filter(id=news_id)
    return render(request, 'news-detail.html', {'news': news})

def about(request):
    return render(request,'about.html')

def tips(request):
    return render(request,'tips.html')

def india(request):
    news = CountryNews.objects.filter(country="India").order_by('-id')
    # country_daily_data(country_name)

    states = india_state_data()

    dailydata = DailyData.objects.filter(country="India")

    country_data = CountryData.objects.get(name__iexact="India")
    return render(request, 'india.html',
                  {'country': country_data, 'latest_news': news, 'countrydailydata': dailydata[32:], 'states':states})

def state(request, state_name):
    states_data = state_data(state_name)

    state_code = states_data[0]['statecode'].lower()

    state_wise_data = state_daily_data(state_code)
    state_date = state_wise_data['date']
    state_data_confirmed = state_wise_data['confirmed']
    state_data_recovered = state_wise_data['recovered']
    state_data_deceased = state_wise_data['deceased']
    #print(state_wise_data)
    districts = district_data(state_name)

    '''df = pd.DataFrame(state_data_confirmed)
    print(df)
    df = df.cumsum()
    print(df)'''

    total_confirmed = []

    counter = 0

    for confirmed in state_data_confirmed:
        confirmed = int(confirmed)
        if counter == 0:
            total_confirmed.append(confirmed)
        else:
            day_total_confirmed = total_confirmed[counter-1] + confirmed
            total_confirmed.append(day_total_confirmed)
        counter+=1

    return render(request,'state.html',{'state':state_name , 'districts' : districts, 'states_data':states_data , 'state_confirmed':state_data_confirmed, 'state_date':state_date, 'state_recovered':state_data_recovered, 'total_confirmed':total_confirmed})

def predictions(request):
    countries = []

    for country in CountryData.objects.all():
        countries.append(country.name)

    return render(request,'predict.html',{'countries':countries})

def resources(request):
    return render(request, 'resource.html')


import os
import time
import math

import numpy as np
import torch
from metrics import averageMeter
# from evaluation.evaluation_tools import eval_log_likelihood

class BaseTrainer:
    """Trainer for a conventional iterative training of model for classification"""
    def __init__(self, optimizer, training_cfg, device):
        self.training_cfg = training_cfg
        self.device = device
        self.optimizer = optimizer

    def train(self, model, d_dataloaders, logger=None, logdir=""):
        cfg = self.training_cfg

        time_meter = averageMeter()
        train_loader, val_loader = (d_dataloaders["training"], d_dataloaders["validation"])
        kwargs = {'dataset_size': len(train_loader.dataset)}
        i_iter = 0
        best_val_loss = np.inf

        for i_epoch in range(1, cfg['n_epoch'] + 1):
            for x, w in train_loader:
                i_iter += 1
                if train_loader.dataset.augmentation:
                    x, w = train_loader.dataset.rand_aug(x, w)
                model.train()
                start_ts = time.time()
                if i_epoch < cfg['n_epoch'] * 0.2:
                    reg = False
                else:
                    reg = True
                d_train = model.train_step(x.to(self.device), w.to(self.device), optimizer=self.optimizer, reg=reg, **kwargs)
                time_meter.update(time.time() - start_ts)
                if logger is not None:
                    logger.process_iter_train(d_train)

                if i_iter % cfg.print_interval == 0:
                    if logger is not None:
                        d_train = logger.summary_train(i_iter)
                    else:
                        d_train['loss/train_loss_'] = d_train['loss']
                    print(
                        f"Epoch [{i_epoch:d}] \nIter [{i_iter:d}]\tAvg Loss: {d_train['loss/train_loss_']:.6f}\tElapsed time: {time_meter.sum:.4f}"
                    )
                    time_meter.reset()
                if i_epoch % cfg.save_epochs == 0:
                    self.save_model(model, logdir, i_epoch=i_epoch)
                model.eval()
                if i_iter % cfg.val_interval == 0:
                    # log_likelihood = eval_log_likelihood(model, train_loader, split=50)
                    # d_ll= {'log_likelihood_': log_likelihood.sum()}
                    # logger.add_val(i_iter, d_ll)
                    for x, w in val_loader:
                        d_val = model.validation_step(x.to(self.device), w.to(self.device))
                        if logger is not None:
                            logger.process_iter_val(d_val)
                    if logger is not None:
                        d_val = logger.summary_val(i_iter)
                        print(d_val['print_str'])
                    else:
                        d_val['loss/val_loss_'] = d_val['loss']
                        print(
                            f"Iter [{i_iter:d}]\tAvg Loss: {d_val['loss/val_loss_']:.6f}"
                        )
                    val_loss = d_val['loss/val_loss_']
                    best_model = val_loss < best_val_loss

                    if best_model:
                        print(f'Iter [{i_iter:d}] best model saved {val_loss:.6f} <= {best_val_loss:.6f}')
                        best_val_loss = val_loss
                        self.save_model(model, logdir, best=True)

                if cfg.visualization.type == 'none' or cfg.visualization.type == []:
                    pass
                else:
                    if i_iter % cfg.visualize_interval == 0:
                        d_vis = model.visualization_step(train_loader, val_loader, device=self.device, **cfg.visualization)
                        if logger is not None:
                            logger.add_val(i_iter, d_vis)

        self.save_model(model, logdir, i_iter="last")
        return model, best_val_loss

    def save_model(self, model, logdir, best=False, i_iter=None, i_epoch=None):
        if best:
            pkl_name = "model_best.pkl"
        else:
            if i_iter is not None:
                pkl_name = f"model_iter_{i_iter}.pkl"
            else:
                pkl_name = f"model_epoch_{i_epoch}.pkl"
        state = {"epoch": i_epoch, "iter": i_iter, "model_state": model.state_dict()}
        save_path = os.path.join(logdir, pkl_name)
        torch.save(state, save_path)
        print(f"Model saved: {pkl_name}")

class LatentTrainer(BaseTrainer):
    def __init__(self, optimizer, training_cfg, device):
        super().__init__(optimizer, training_cfg, device)


# coding=utf-8

"""
Module to display movie object, attributes and instances
main Python script to run
"""

import media
import fresh_tomatoes

# Movie Objects
I_am_legend = media.MovieTrailer(
    "I am legend",
    '''I_am_legend is a movie where a single man will
    smith finds solution to cure the zombies.''',
    "https://upload.wikimedia.org/wikipedia/en/d/df/I_am_legend_teaser.jpg",  # noqa
    "https://www.youtube.com/watch?v=ewpYq9rgg3w")

Winters_tale = media.MovieTrailer(
    "Winters tale",
    '''Polixenes, King of Bohemia, has been on a
    nine-month visit to the court of his childhood
    friend Leontes, King of Sicilia, and his wife,
    Queen Hermione. Groundlessly, Leontes becomes
    convinced that his heavily pregnant wife has
    been having an affair with Polixenes.''',
    "http://www.hans-zimmer.com/~hybrid/zimmer/WINTERSTALE.jpg",  # noqa
    "https://www.youtube.com/watch?v=DBSj1MKwx6A")

Alaipayuthae = media.MovieTrailer(
    "Alaipayuthae",
    '''Alaipayuthae is a dramatic and comedy movie
    in which the romance and marriage life of two
    peoples are show like a tale.''',
    "http://3.bp.blogspot.com/_WIFlbAzMDaQ/TJaDzGk-tLI/AAAAAAAAAyQ/u4T5NGVcrwg/w1200-h630-p-k-no-nu/Alaipayuthey_9.jpg",  # noqa
    "https://www.youtube.com/watch?v=BRFdGc3ku-k")

Men_in_black_3 = media.MovieTrailer(
    "Men in black 3",
    '''Men in black 3 is a action movie in which
    ajent J and K has been protecting the Earth
    from alien scum for many years. there arrived
    a new animal called boris, they way they find
    the animal is exciting.''',
    "https://www.dvdplanetstore.pk/wp-content/uploads/2014/08/Men-in-Black-3-2012dvdplanetstorepk.jpg",  # noqa
    "https://www.youtube.com/watch?v=aoyV49FfjOU")

Pele_Birth_of_legend = media.MovieTrailer(
    "Pele Birth of legend",
    '''Pele Birth of legend Under guidance from
    manager Vicente Feola (Vincent D'Onofrio), young
    Pelé (Kevin de Paula) utilizes his street soccer
    skills to lead Brazil to the World Cup in 1958.''',
    "https://vidamine.com/media/com_hwdmediashare/files/22/34/9e/95a45631b7368aad585040ece859e65f.jpg",  # noqa
    "https://www.youtube.com/watch?v=pwBXs2B2ZbI")

King_arthur_legend_of_sword = media.MovieTrailer(
    "King arthur legend of sword",
    '''King arthur legend of sword After the murder
    of his father, young Arthur's power-hungry uncle
    Vortigern seizes control of the crown. When fate
    leads him to pull the Excalibur sword from stone,
    Arthur embraces his true destiny to become a
    legendary fighter and leader.''',
    "https://cdn.flickeringmyth.com/wp-content/uploads/2017/04/king-arthur-charlie-hunnam-poster.jpg",  # noqa
    "https://www.youtube.com/watch?v=4luDtkC3Oy0")

# Creating list for movie objects
movies = [I_am_legend, Winters_tale, Alaipayuthae, Men_in_black_3, Pele_Birth_of_legend, King_arthur_legend_of_sword]  # noqa
fresh_tomatoes.open_movies_page(movies)


"""
Extracts a BERT archive from an existing model
"""

import logging
import argparse

from udify import util

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

parser = argparse.ArgumentParser()
parser.add_argument("archive_dir", type=str, help="The directory where model.tar.gz resides")
parser.add_argument("--output_path", default=None, type=str, help="The path to output the file")

args = parser.parse_args()

bert_config = "config/archive/bert-base-multilingual-cased/bert_config.json"
util.archive_bert_model(args.archive_dir, bert_config, args.output_path)


def split_and_join(line):
    # write your code here
    result = line.split()
    result = "-".join(result)
    print(result)
    return result

def funcao_maceteada(line):
    return line.replace(' ','-')

if __name__ == '__main__':
    print("Digite uma frase: ")
    line = input()
    result = split_and_join(line)
    print("Resultado substituindo espaco por traco")
    print(result)


from spack import *

class Metabat(SConsPackage):
    """MetaBAT, an efficient tool for accurately reconstructing single
    genomes from complex microbial communities."""

    homepage = "https://bitbucket.org/berkeleylab/metabat"
    url      = "https://bitbucket.org/berkeleylab/metabat/get/v2.12.1.tar.gz"

    version('2.12.1', 'c032f47a8b24e58a5a9fefe52cb6e0f8')

    depends_on('boost@1.55.0:', type=('build', 'run'))
    depends_on('perl', type='run')

    def setup_environment(self, spack_env, run_env):
        spack_env.set('BOOST_ROOT', self.spec['boost'].prefix)

    def install_args(self, spec, prefix):
        return ["PREFIX={0}".format(prefix)]

    @run_after('build')
    def fix_perl_scripts(self):
        filter_file(r'#!/usr/bin/perl',
                    '#!/usr/bin/env perl',
                    'aggregateBinDepths.pl')

        filter_file(r'#!/usr/bin/perl',
                    '#!/usr/bin/env perl',
                    'aggregateContigOverlapsByBin.pl')


import os
import cv2
import torch
import numpy as np
import pandas as pd
from glob import glob
from config import Config
import matplotlib.pyplot as plt
from scipy import stats as st
from torch.utils.data import DataLoader
from model.writerModel import BaseModel
from load_data import Read_patch, custom_collate
from sklearn.metrics import f1_score, roc_auc_score

# CRAFT
# ---------------------------------------------------- #
import time
import torch
import torch.backends.cudnn as cudnn
from craft_model.craft import CRAFT
from torch.autograd import Variable
import craft_model.craft_utils
import craft_model.imgproc
import craft_model.file_utils
from collections import OrderedDict

def copyStateDict(state_dict):
    if list(state_dict.keys())[0].startswith("module"):
        start_idx = 1
    else:
        start_idx = 0
    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        name = ".".join(k.split(".")[start_idx:])
        new_state_dict[name] = v
    return new_state_dict

def str2bool(v):
    return v.lower() in ("yes", "y", "true", "t", "1")

def test_net(net, image, text_threshold, link_threshold, low_text, cuda, poly, refine_net=None):

    # resize
    img_resized, target_ratio, size_heatmap = craft_model.imgproc.resize_aspect_ratio(image, 1280, interpolation=cv2.INTER_LINEAR, mag_ratio=1.5)
    ratio_h = ratio_w = 1 / target_ratio

    # preprocessing
    x = craft_model.imgproc.normalizeMeanVariance(img_resized)
    x = torch.from_numpy(x).permute(2, 0, 1)    # [h, w, c] to [c, h, w]
    x = Variable(x.unsqueeze(0))                # [c, h, w] to [b, c, h, w]
    if cuda:
        x = x.cuda()

    # forward pass
    with torch.no_grad():
        y, feature = net(x)

    # make score and link map
    score_text = y[0,:,:,0].cpu().data.numpy()
    score_link = y[0,:,:,1].cpu().data.numpy()

    # refine link
    if refine_net is not None:
        with torch.no_grad():
            y_refiner = refine_net(y, feature)
        score_link = y_refiner[0,:,:,0].cpu().data.numpy()

    # Post-processing
    boxes, polys = craft_model.craft_utils.getDetBoxes(score_text, score_link, text_threshold, link_threshold, low_text, poly)

    # coordinate adjustment
    boxes = craft_model.craft_utils.adjustResultCoordinates(boxes, ratio_w, ratio_h)
    polys = craft_model.craft_utils.adjustResultCoordinates(polys, ratio_w, ratio_h)
    for k in range(len(polys)):
        if polys[k] is None: polys[k] = boxes[k]

    # render results (optional)
    render_img = score_text.copy()
    render_img = np.hstack((render_img, score_link))
    ret_score_text = craft_model.imgproc.cvt2HeatmapImg(render_img)

    return boxes, polys, ret_score_text

# Global definition
# Load Craft Model
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
device = torch.device('mps')

net = CRAFT()     # initialize

print('Loading weights from checkpoint (' + 'craft_model/craft_mlt_25k.pth' + ')')
net.load_state_dict(copyStateDict(torch.load('craft_model/craft_mlt_25k.pth', map_location=device)))

if torch.cuda.is_available():
    net = net.cuda()
    net = torch.nn.DataParallel(net)
    cudnn.benchmark = False

net.eval()
# LinkRefiner
refine_net = None

main_result = 'result/'
os.makedirs(main_result, exist_ok=True)

def store(image_path, result_folder):

    image = craft_model.imgproc.loadImage(image_path)

    bboxes, polys, score_text = test_net(net, image, 0.7, 0.4, 0.4, torch.cuda.is_available(), False, refine_net)

    # save score text
    filename, file_ext = os.path.splitext(os.path.basename(image_path))
    mask_file = result_folder  + filename + '_mask.jpg'
    cv2.imwrite(mask_file, score_text)

    craft_model.file_utils.saveResult(image_path, image[:,:,::-1], polys, dirname=result_folder)
    # print()

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

def obtain_transform(im, points):
    x1,y1, x2,y2, x3,y3, x4,y4 = points
    length = round(abs(x2 - x1))
    width = round(abs(y3 - y2))

    source_vertices = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]], dtype='float32')
    target_vertices = np.array([[0, 0], [0, length], [width, length], [width, 0]], dtype='float32')
    M = cv2.getPerspectiveTransform(source_vertices, target_vertices)

    output_size = (width, length)
    blank_image = np.zeros((width, length), dtype=np.uint8)
    transformed_polygon = cv2.warpPerspective(im, M, output_size).T

    ret, thresh = cv2.threshold(transformed_polygon, 0, 255, cv2.THRESH_OTSU)
    thresh = 255-thresh

    return thresh

def get_save_patches(img1, img2, label):
    path1 = img1
    path2 = img2
    df1 = pd.read_csv(path1.split('.')[0] + '.txt', names=['x1','y1', 'x2','y2', 'x3','y3', 'x4','y4'])
    df2 = pd.read_csv(path2.split('.')[0] + '.txt', names=['x1','y1', 'x2','y2', 'x3','y3', 'x4','y4'])

    P1 = []
    P2 = []
    for i in range(len(df1)):
        p1_points = df1.iloc[np.random.randint(0,len(df1)), :].values
        path1 = path1.replace('all_result_test', f'{cfg.test_path}').replace('res_', '')
        img1 = cv2.imread(path1, 0)
        p1 = obtain_transform(img1, p1_points)
        P1.append(p1)

    for i in range(len(df2)):
        p2_points = df2.iloc[np.random.randint(0,len(df2)), :].values
        path2 = path2.replace('all_result_test', f'{cfg.test_path}').replace('res_', '')
        img2 = cv2.imread(path2, 0)
        p2 = obtain_transform(img2, p2_points)
        P2.append(p2)

    if len(P1) == 0 or len(P2) == 0:
        return 1

    counter = 1
    for p1 in P1:
        for p2 in P2:
            cv2.imwrite(f'result_test/data_1/img_{counter}_{label}.png', p1)
            cv2.imwrite(f'result_test/data_2/img_{counter}_{label}.png', p2)
            counter += 1
    # print(len(P1), len(P2), counter-1)
    return 0

def custom_sigmoid(z, threshold):
    denominator = 1 + np.exp( 10 * (threshold - z))
    return 1 / denominator

def predict(model, test_loader):
    threshold = 2.0
    pred_label = []
    for mask, x, y, indices in test_loader:
        x = x/255
        mask, x, y = mask.to(device), x.to(device), y.to(device)
        pred = model(x, mask, indices)
        D = (pred[:, 0, :] - pred[:, 1, :]).pow(2).sum(1).sqrt()

        pred_label.append(D.cpu().detach().numpy()[0])

    mode = np.mean(np.array(pred_label))
    proba = custom_sigmoid(mode, threshold)

    if mode > threshold:
        return 1, proba
    else:
        return 0, proba

def create_loader():
    cfg = Config().parse()
    dataset = Read_patch('result_test', cfg.patch_size)
    test_loader = DataLoader(dataset, collate_fn=custom_collate, batch_size=cfg.batch_size)
    return test_loader

if __name__ == '__main__':
    inspect = False
    cfg = Config().parse()
    csv_path = cfg.csv_path
    test_path = cfg.test_path
    device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
    device = torch.device('mps')
    model = torch.load('model.pth', map_location=device)
    model.bs = cfg.batch_size
    df = pd.read_csv(csv_path)
    prob = []
    pred_labels = []
    true_label = []
    for i in range(len(df)):
        label = 0 #int(df.iloc[i, 2])
        path1 = os.path.join(test_path, df.iloc[i,0])
        path2 = os.path.join(test_path, df.iloc[i,1])

        os.system('rm -r result_test')
        os.makedirs('result_test', exist_ok=True)
        os.makedirs('result_test/data_1', exist_ok=True)
        os.makedirs('result_test/data_2', exist_ok=True)

        path1 = os.path.join('all_result_test', f'res_{df.iloc[i,0]}')
        path2 = os.path.join('all_result_test', f'res_{df.iloc[i,1]}')

        flag = get_save_patches(path1, path2, label)

        if flag:
            proba = np.random.rand()
            if proba >= 0.5:
                pred_label=1
            else:
                pred_label=0
        else:
            test_loader = create_loader()
            pred_label, proba = predict(model, test_loader)

        prob.append(proba)
        pred_labels.append(pred_label)
        # true_label.append(label)
        # f1 = f1_score(y_pred=np.array(pred_labels), y_true= np.array(true_label))
        # if i > 20:
        #     auc = roc_auc_score(y_score=np.array(prob), y_true=np.array(true_label))
        # else:
        #     auc = None

        print(f'Iteration: {i+1}, Prediction: {pred_label}')#, Actual: {label}, F1 Score: {f1}, AUC Score: {auc}')
        # if (label != pred_label) and inspect:
        #     plt.figure(figsize=(15,5))
        #     img1 = cv2.imread(path1, 0)
        #     img2 = cv2.imread(path2, 0)
        #     # print(files[i][0].shape)
        #     plt.subplot(1,2,1)
        #     plt.imshow(img1, cmap='gray')
        #     plt.axis('off')
        #     plt.subplot(1,2,2)
        #     plt.imshow(img2, cmap='gray')
        #     plt.axis('off')
        #     plt.show()

        print()
        print()
        # break
    prob = np.array(prob)
    pred_labels = np.array(pred_labels)
    # pred_labels =  np.where(prob >= 0.5, 1, 0)

    df['proba'] = prob
    df['label'] = pred_labels

    new_df = pd.DataFrame()
    new_df['id'] = df['img1_name'] + '_' + df['img2_name']
    new_df['proba'] = df['proba']
    new_df.to_csv('Single Vision_02.csv', index=False)


# Import homelessness counts for 2017-2019 by census tract
# Assemble and clip to City of LA

import numpy as np
import pandas as pd
import geopandas as gpd
import intake

catalog = intake.open_catalog('./catalogs/*.yml')
bucket_name = 's3://public-health-dashboard/'

y2017 = catalog.homeless_2017.read().to_crs({'init':'epsg:2229'})
y2018 = catalog.homeless_2018.read().to_crs({'init':'epsg:2229'})
y2019 = catalog.homeless_2019.read().to_crs({'init':'epsg:2229'})

city_boundary = catalog.city_boundary.read().to_crs({'init':'epsg:2229'})

# Number of square feet in one square mile
sqft_to_sqmi = 2.788e+7

# Make the 3 dfs uniform, then append into one df
raw_dfs = {'2017': y2017, '2018': y2018, '2019': y2019}

df = pd.DataFrame()

for key, value in raw_dfs.items():
    yr = f"{key}"
    new_df = value.copy()
    new_df['year'] = int(yr)
    # Rename columns
    keep = ['Tract', 'SPA', 'SD', 'CD', 'totUnshelt', 'totShelt', 'totPeople', 'year']
    if key == '2017':
        new_df.rename(columns = {'totSheltPe': 'totShelt'}, inplace = True)
    elif key == '2018':
        new_df.rename(columns = {'Tract_N': 'Tract'}, inplace = True)
    elif key == '2019':
        new_df.rename(columns = {'Tract_N': 'Tract', 'totUnshe_1': 'totUnshelt',
                                 'totShelt_1': 'totShelt', 'totPeopl_1': 'totPeople'}, inplace = True)
    # Just keep needed columns
    new_df = new_df[keep]
    # Append to existing df
    df = df.append(new_df)

# Make GEOID
df['GEOID'] = '06037' + df.Tract.astype(str)

# Only keep tracts that are in City of LA
df = df[df.CD != 0]

df = df.drop(columns = ['Tract'])
df.rename(columns = {'totPeople': 'tot_homeless', 'totUnshelt': 'unsheltered',
                    'totShelt': 'sheltered'}, inplace = True)

df = df.reindex(columns = ['GEOID', 'SPA', 'SD', 'CD', 'year',
                             'unsheltered', 'sheltered', 'tot_homeless'])

df = df.sort_values(['GEOID', 'year'])

# Export to S3
df.to_parquet(f'{bucket_name}gis/intermediate/homelessness_2017_2019.parquet')


import json
import os

class Configurator(object):
    configuration_filename = 'container_configuration_local.json'
    configuration_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), configuration_filename)

    def __init__(self) -> None:
        # read information about containers from config.json
        self._config = {}

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

    def init_configure(self):
        try:
            self._read_container_config()
        except FileNotFoundError:
            raise FileNotFoundError('Config file not found or not initialized. Please initialize configuration file')

    def display_containers(self):
        print('Containers information:')
        for container in self._config['containers']:
            print('\tname:', container['name'])
            print('\tcontainer name:', container['container_name'])
            print('\tdescription:', container['description'])
            print('\tbuild command:', container['build'])
            print('\trun command', container['run'])
            print()

    def parse(self, opened_file) -> None:
        """Parse an incoming file and write the config file local (create a copy)

        Args:
            opened_file (_io.TextIOWrapper): opened file from args with type=open
        Returns:
            None:
        Raises:
            SyntaxError: If configuration file is not valid
        """
        configure = json.load(opened_file)

        if not self._is_valid(configure):
            raise SyntaxError('Config file is not valid')

        with (open(self.configuration_path, 'w')) as fout:
            fout.write(json.dumps(configure))

    def clear(self) -> None:
        if os.path.exists(self.configuration_path):
            os.remove(self.configuration_path)

    def _read_container_config(self):
        with (open(self.configuration_path, 'r')) as fout:
            self._config = json.load(fout)

            if not self._is_valid(self._config):
                raise ValueError('Config file is not valid')

    def _is_valid(self, config) -> bool:
        try:
            for container in config.get('containers', None):
                if container.get('alias', None) is None \
                        or container.get('container_name', None) is None \
                        or container.get('build', None) is None \
                        or container.get('run', None) is None:
                    raise Exception(
                        f'Some of fields: name, container_name, run, build are not valid in record {container}')
            return True
        except Exception as e:
            print('validation error ->', e)
            return False


import requests

def main():
    id = "538"
    url = "https://restful-booker.herokuapp.com/booking/"
    full_url = url + id
    print(full_url)
    response_body = requests.get(full_url)
    assert response_body.status_code == 200  # If sc != 200 it error, else it will not give error

    data = response_body.json()
    print(type(data))

    # Assertions

    # Verification of Keys
    assert 'firstname' in data, "Incorrect firstName"
    assert 'lastname' in data, "LastName key is present"

    # Verification of Data
    assert data["firstname"] == "Josh", "Incorrect  FirstName is Amit"
    assert data["lastname"] == "Allen", "Incorrect LastName"
    assert data["bookingdates"]["checkin"] == "2018-01-01", "Incorrect Message"

if __name__ == '__main__':
    main()


import nltk
import re
import time
from sklearn.datasets import fetch_20newsgroups
from sklearn.decomposition import PCA
from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer
from string import digits
from sklearn.cluster import KMeans, Birch
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt

# 去除文本里面的符号
def pre_process(data):
    text_new = []
    for text in data:
        remove_digits = str.maketrans('', '', digits)
        res = text.translate(remove_digits)
        result = res.replace('_', '')
        result = result.replace('*', '')
        result = result.replace('/', '')
        result = result.replace('\\', '')
        result = result.replace('{', '')
        result = result.replace('}', '')
        result = result.replace('-', '')
        result = result.replace('(', '')
        result = result.replace(')', '')
        text_new.append(result)
    return text_new

# 载入nltk的英文停用词作为停用词变量
stopwords = nltk.corpus.stopwords.words('english')

# 载入nltk的SnowballStemmer作为词干化变量
stemmer = nltk.SnowballStemmer("english")

# 分句加分词，分词后检查单词正确性并还原单词原型
def tokenize_and_stem(text):
    # 首先分句，接着分词，而标点也会作为词例存在
    tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]
    filtered_tokens = ''
    # 过滤所有不含字母的词例（例如：数字、纯标点）
    for token in tokens:
        if re.search('[a-zA-Z]', token):
            if token not in stopwords:
                filtered_tokens += ' ' + stemmer.stem(token)
    return filtered_tokens

# 只分句分词，并都转换为小写
def tokenize_only(text):
    # 首先分句，接着分词，而标点也会作为词例存在
    tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]
    filtered_tokens = []
    # 过滤所有不含字母的词例（例如：数字、纯标点）
    for token in tokens:
        if re.search('[a-zA-Z]', token):
            filtered_tokens.append(token)
    return filtered_tokens

categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)

count_vect  = TfidfVectorizer(min_df=3)
X_train_counts = count_vect.fit_transform(twenty_train.data)

tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)

pca = PCA(n_components=2)  # 进行PCA降维
newdata = pca.fit_transform(X_train_tfidf.toarray())
plt.scatter(newdata[:, 0], newdata[:, 1])
plt.show()

# 进行kmeans聚类
num_clusters = 5
km = KMeans(n_clusters=num_clusters)
start = time.time()
result = km.fit_predict(newdata)
end = time.time()
print("k_means运行的时间是：", end-start)
plt.scatter(newdata[:, 0], newdata[:, 1], c=result)
plt.show()

# 进行dbscan聚类
start = time.time()
db = DBSCAN(eps=0.05, min_samples=30).fit_predict(newdata)
end = time.time()
print("DBscan运行的时间是：", end-start)
plt.scatter(newdata[:, 0], newdata[:, 1], c=db)
plt.show()

# 进行birch聚类
start = time.time()
result_birch = Birch(n_clusters=5).fit_predict(newdata)
end = time.time()
print("birch运行的时间是：", end-start)
plt.scatter(newdata[:, 0], newdata[:, 1], c=result_birch)
plt.show()


from itertools import starmap
from typing import Generator
import pytest

from sponge_networks.resource_networks import *
from sponge_networks.utils.utils import *

class ProtocolPair(TypedDict):
    result_protocol: pd.DataFrame
    standard_protocol: pd.DataFrame

def resourceDiGraph_from_array(arr: npt.ArrayLike) -> ResourceNetwork:
    ig = np.asarray(arr)
    rn = ResourceNetwork(nx.from_numpy_array(ig, create_using=nx.DiGraph))
    return rn

rns_with_simulations_raw = [
    {
        # если заменить 2 на 1 в первой строке, то аттрактором станет другая вершина!
        "rn": resourceDiGraph_from_array(
            [
                [0, 0, 2, 0],
                [0, 0, 0, 4],
                [3, 2, 0, 0],
                [1, 5, 0, 0],
            ]
        ),
        "simulations": [
            {
                "initial_state": [20, 10, 6, 12],
                "n_iters": 200,
                "correct_file": "g1.xlsx",
            },
        ],
    },
    {
        "rn": resourceDiGraph_from_array(
            [
                [1, 1, 1, 1, 1],
                [1, 1, 1, 1, 1],
                [3, 1, 1, 1, 1],
                [4, 1, 1, 1, 1],
                [5, 1, 1, 1, 1],
            ]
        ),
        "simulations": [
            {
                "initial_state": [0, 40, 0, 0, 0],
                "n_iters": 40,
                "correct_file": "g2.xlsx",
            },
        ],
    },
]

class _TestsProvider:
    def __init__(self, rns_with_simulations_raw) -> None:
        res = []
        for d in rns_with_simulations_raw:
            elt = {}
            elt["rn"] = d["rn"]
            elt["simulations"] = [
                {
                    "result_sim": d["rn"].run_simulation(
                        initial_state=it["initial_state"],
                        n_iters=it["n_iters"],
                    ),
                    "standard_protocol": pd.read_excel(
                        f"tests/data/{it['correct_file']}"
                    ).set_index("t", drop=True),
                }
                for it in d["simulations"]
            ]
            res.append(elt)
        self.rns_with_simulations = res

    def all_simulations(self) -> Generator[StateArray, None, None]:
        for d in self.rns_with_simulations:
            for sims in d["simulations"]:
                yield sims["result_sim"]

    def all_descriptor_pairs(self) -> Generator[DescriptorPair, None, None]:
        for d in self.rns_with_simulations:
            yield {
                "idx_descriptor": d["rn"].idx_descriptor,
                "node_descriptor": d["rn"].node_descriptor,
            }

    def all_protocol_pairs(
        self,
    ) -> Generator[ProtocolPair, None, None]:
        for d in self.rns_with_simulations:
            for sims in d["simulations"]:
                yield {
                    "result_protocol": sims["result_sim"].simple_protocol(),
                    "standard_protocol": sims["standard_protocol"],
                }

tests_provider = _TestsProvider(rns_with_simulations_raw)

@pytest.fixture(params=tests_provider.all_simulations())
def simulation(request):
    return request.param

@pytest.fixture(params=tests_provider.all_descriptor_pairs())
def desc_pair(request):
    return request.param

@pytest.fixture(params=tests_provider.all_protocol_pairs())
def protocol_pair(request):
    return request.param

# @pytest.mark.parametrize(
#     "simulation",
#     [(1, 2), (3, 4)],
# )
def test_resource_is_preserved(simulation: StateArray):
    sim_sum = simulation.states_arr.sum(axis=1)
    assert np.allclose(sim_sum[0], sim_sum, atol=1e-7)

def test_descriptors_are_aligned(desc_pair: DescriptorPair):
    assert all(
        desc_pair["idx_descriptor"][v] == k
        for k, v in desc_pair["node_descriptor"].items()
    )

def test_node_descriptor_is_trivial(desc_pair: DescriptorPair):
    assert all(starmap(lambda k, v: k == v, desc_pair["node_descriptor"].items()))

def test_protocols_are_equal(protocol_pair: ProtocolPair):
    # print(protocol_pair["standard_protocol"].columns)
    assert np.allclose(
        protocol_pair["result_protocol"],
        protocol_pair["standard_protocol"],
    )


import discord
import requests
from json import loads

import time
import _thread
from threading import Thread
import asyncio

async def delayed(thread_name, delay):
    time.sleep(delay)
    return thread_name

async def print_time(threadName, delay):
    while 1:
        a = await delayed(threadName, delay)
        print(a + " " + time.ctime(time.time()))

# Create two threads as follows
try:
    _thread = Thread(target=asyncio.run, args=(print_time("1", 1),))
    _thread.start()
    _thread = Thread(target=asyncio.run, args=(print_time("2", 2),))
    _thread.start()

except:
    print("Error: unable to start thread")

while 1:
    time.sleep(10)
    print("main " + time.ctime(time.time()))


import requests
import urllib.request
from bs4 import BeautifulSoup

word='山东大学+港澳台+本科生+简章'#在百度上查关键词为‘梁左嘉懿’的网页
# url_values=urllib.parse.urlencode(data)#urlencode:把普通字符串转化为url格式
# 含中文需要用urllib.parse.quote防止报错
tw='edu.cn'
url = 'http://www.xmu.edu.cn/'
# url ='http://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd='+urllib.parse.quote(word)+'&oq=%25E5%25B1%25B1%25E4%25B8%259C%25E5%25A4%25A7%25E5%25AD%25A6%2520%25E6%25B8%25AF%25E6%25BE%25B3%25E5%258F%25B0%2520%25E7%25AE%2580%25E7%25AB%25A0&rsv_pq=b5ae7a5400006d82&rsv_t=ba48YGCqXRaRaMnbbZ030EzIWI4J%2FSRle0Cj2hE9uSOdStZa378EG%2FDf8iU&rqlang=cn&rsv_enter=0&inputT=7367&si=edu.cn&ct=2097152'

response = urllib.request.urlopen(url)
page = response.read()
print(page)
# headers = {
#     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#     'Accept-Encoding': 'gzip, deflate, compress',
#     'Accept-Language': 'en-us;q=0.5,en;q=0.3',
#     'Cache-Control': 'max-age=0',
#     'Connection': 'keep-alive',
#     'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'
# }
#
# all = open('D:\\111\\test.xlsx', 'a')
soup = BeautifulSoup(page,'lxml')
# print(soup)
href = soup.find_all('li', limit=1)
print(href)
# baidu_url =requests.get(url=href, headers=headers, allow_redirects=False)
# real_url = baidu_url.headers['Location']  #得到网页原始地址
# if real_url.startswith('http'):
#     all.write(real_url + '\n')


from local_settings import *
from views import *
from tornado.web import url

routers = [
    url(r"^/?$", IndexHandler, name="index"),
    url(r"^/qywx/?", WeiXinQYHandler, name="qywx"),
    url(r"^/sms/?", SMSHandler, name="sms"),
    url(r"^/mail/?", EmailHandler, name="mail"),
    url(r"^/ws/?", WebSocketHandler, name="websocket"),
]

appSettings = {
    "debug": False,
}


#!/usr/bin/python
import requests
import json

base_url='http://localhost:5000'

book_list = [
{"title" : "alfajor",
"publisher" : "planeta",
"editionYear" : 2010,
"editionCountry" : "argentina",
"price" : 100,
"isbn" : "2128629716",
"gender" : "fisica",
"reputationValue" : 6,
"loanType" : "REMOTE"},
{"title" : "harry potter",
"publisher" : "planeta",
"editionYear" : 2010,
"editionCountry" : "argentina",
"price" : 200,
"isbn" : "3029855590",
"gender" : "fisica",
"reputationValue" :  8,
"loanType" : "LOCAL"},
{"title" : "pacman trumpeter",
"publisher" : "emece",
"editionYear" : 2010,
"editionCountry" : "argentina",
"price" : 10.50,
"isbn" : "2332932199",
"gender" : "terror",
"reputationValue" : 4,
"loanType" : "REMOTE"},
{"title" : "gringos amigos",
"publisher" : "golondrina",
"editionYear" : 2010,
"editionCountry" : "argentina",
"price" : 10.50,
"isbn" : "1621017673",
"gender" : "terror",
"reputationValue" : 6,
"loanType" : "LOCAL"},
{"title" : "gefatura de bebe gloglo",
"publisher" : "salamndra",
"editionYear" : 2010,
"editionCountry" : "argentina",
"price" : 10.50,
"isbn" : "2649520825",
"gender" : "legislatura",
"reputationValue" : 3,
"loanType" : "REMOTE"},
]

book_id_list = []
for book in book_list:
        response = requests.post(base_url + "/books",
                   data = json.dumps(book),
                   headers={'Content-Type': 'application/json'})
        book_id_list.append(response.json()['id'])

author_list = [
{"firstName" : "pablo",
"lastName" : "professi",
"nationality" : "argentino"},
{"firstName" : "javier",
"lastName" : "anselmi",
"nationality" : "argentino"},
{"firstName" : "kuasimodo",
"lastName" : "borbonete",
"nationality" : "frances"},
{"firstName" : "quintaro",
"lastName" : "grindustre",
"nationality" : "holanda"},
{"firstName" : "gonzo",
"lastName" : "bonneli",
"nationality" : "hungria"},
{"firstName" : "ratimi",
"lastName" : "tripipio",
"nationality" : "kasajstan"},
]

author_id_list = []
for author in author_list:
        response = requests.post(base_url + "/authors",
                   data = json.dumps(author),
                   headers={'Content-Type': 'application/json'})
        author_id_list.append(response.json()['id'])

requests.post(base_url + "/books/" + book_id_list[0] + "/authors/" + author_id_list[0], data = json.dumps({}),headers={'Content-Type': 'application/json'})
requests.post(base_url + "/books/" + book_id_list[0] + "/authors/" + author_id_list[1], data = json.dumps({}),headers={'Content-Type': 'application/json'})
requests.post(base_url + "/books/" + book_id_list[1] + "/authors/" + author_id_list[2], data = json.dumps({}),headers={'Content-Type': 'application/json'})
requests.post(base_url + "/books/" + book_id_list[1] + "/authors/" + author_id_list[3], data = json.dumps({}),headers={'Content-Type': 'application/json'})
requests.post(base_url + "/books/" + book_id_list[2] + "/authors/" + author_id_list[4], data = json.dumps({}),headers={'Content-Type': 'application/json'})
requests.post(base_url + "/books/" + book_id_list[2] + "/authors/" + author_id_list[2], data = json.dumps({}),headers={'Content-Type': 'application/json'})
requests.post(base_url + "/books/" + book_id_list[2] + "/authors/" + author_id_list[0], data = json.dumps({}),headers={'Content-Type': 'application/json'})

#response = requests.post(base_url + "/members",
#            data = json.dumps({'firstName' : 'pabloide',
#                               'lastName' : 'profelmi',
#                               'dni' :  '35666666',
#                               'nationality' :
#                               'Argentina','cuil' :
#                               '20356666662','phone' :
#                               '0540111557781234',
#                               'email' : 'asdasd@gmail.com',
#                               'zipCode' : '1602',
#                               'city' : 'vicente lopez',
#                               'state' : 'buenos aires',
#                               'enabled' : 'True',
#                               'reputation' : '7'}),
#            headers={'Content-Type': 'application/json'})
#id_member_A_created = response.json()['id']
#response = requests.post(base_url + "/members",
#            data = json.dumps({'firstName' : 'javioide',
#                               'lastName' : 'profelmi',
#                               'dni' :  '357777777',
#                               'nationality' : 'Argentina',
#                               'cuil' : '203577777772',
#                               'phone' : '0540111557666666',
#                               'email' : 'wwwwwwwwwwww@gmail.com',
#                               'zipCode' : '1632',
#                               'city' : 'vicente lopez',
#                               'state' : 'buenos aires',
#                               'enabled' : 'True',
#                               'reputation' : '8'}),
#            headers={'Content-Type': 'application/json'})
#id_member_B_created = response.json()['id']

#response = requests.post(base_url + "/samples",
#            data = json.dumps({"bookId": "1",
#                               "barCode":"1234567890",
#                               "acquisitionDate": "2016-10-06",
#                               "discardDate": "2016-10-13"}),
#            headers={'Content-Type': 'application/json'})
#id_sample_A_created = response.json()['id']
#response = requests.post(base_url + "/samples",
#            data = json.dumps({"bookId": "1" ,
#                               "barCode":"000000000",
#                               "acquisitionDate": "2016-10-23"}),
#            headers={'Content-Type': 'application/json'})
#id_sample_B_created = response.json()['id']
#response = requests.post(base_url + "/samples",
#            data = json.dumps({"bookId": "1",
#                               "barCode":"1111111111",
#                               "acquisitionDate": "2016-10-23"}),
#            headers={'Content-Type': 'application/json'})
#id_sample_C_created = response.json()['id']

#response = requests.post(base_url + "/loans",
#            data = json.dumps({'agreedReturnDate' : '2016-10-24',
#                               'withdrawDate' : '2016-10-24',
#                               'loanType': 'REMOTE',
#                               'sampleId': "2",
#                               'memberId': "1"}),
#            headers={'Content-Type': 'application/json'})
#print(response.text)
#response = requests.post(base_url + "/loans",
#            data = json.dumps({'agreedReturnDate' :  "2016-10-19",
#                               'withdrawDate' : "2016-10-24",
#                               "loanType": "REMOTE",
#                               'sampleId': "3",
#                               'memberId': "1"}),
#            headers={'Content-Type': 'application/json'})
#response = requests.post(base_url + "/loans",
#            data = json.dumps({'agreedReturnDate' : '2016-10-24',
#                               'returnDate': None,
#                               'withdrawDate' : '2016-10-22',
#                               'comment' : 'soy de atlanta y q?',
#                               'loanType': 'LOCAL',
#                               'sampleId': id_sample_B_created,
#                               'memberId': id_member_A_created}),
#            headers={'Content-Type': 'application/json'})
#response = requests.post(base_url + "/loans",
#            data = json.dumps({'agreedReturnDate' :  "2016-10-24",
#                               'returnDate': "2016-10-22",
#                               'withdrawDate' : "2016-10-04",
#                               'comment' : "gol gol gol",
#                               "loanType": "LOCAL",
#                               'sampleId': id_sample_B_created,
#                               'memberId': id_member_B_created}),
#            headers={'Content-Type': 'application/json'})


# -*- coding: utf-8 -*-
'''
Created on 2020.

@author: aon
'''
from tools.DC import DCC, well, toWell
from api.formTools import style, _div, pyramid, pyramidInit, _mainPage, _field
from api.classPage import Page

# *** *** ***

class t__list(Page):

    def __init__(self, dcUK):
        self.noCaching = True
        self.jsCssUrl = [
            'jsv?api/react/_pyramid.js',
            'jsv?api/pages/t__list/t__list.js',
            'jsv?api/pages/t_lesson/t_lesson.js',
            'jsv?api/react/view.css']

        self.cats = {
            'Курсы': DCC(condition='True', sort='docNo', reverse=True,
                fixedSubCats=[
                    DCC(subCat='По\xa0названию', condition='True', sort='trackName'),
                ]
            ),
            'По\xa0категории': DCC(condition='True', sort='trackName', subCat="d.cat or '-'"),
            'По\xa0кураторам': DCC(condition='True', sort='trackName', subCat="d.curator or '-'"),
        }

        super().__init__(dcUK)

    # *** *** ***

    def page(self, dcUK):
        self.title = f"Курс {dcUK.dbAlias.rpartition('_')[2]}"

        dcVP = DCC(cats=self.cats, form='t_lesson', dbAlias=dcUK.dbAlias)

        dcVP['checkBox'] = _div(
            **style(width=380, verticalAlign='middle'), children=
            [
                _field('active', 'chb3', ['активные', 'ожидание'], **style(letterSpacing=1))
            ]
        )

        view = self.getViewObject('ViewLessons', dcVP, 'ViewLessons')

        return _mainPage(className='page51', children=[
            pyramid(),

            _div(**style(maxWidth=1000, margin='auto'), className='cellbg-green', children=
                view.make()  # вид с кнопками слева  и тулбаром
            )
        ])

    def queryOpen(self, dcUK):
        dcUK.doc._page_ = '1'
        pyramidInit(dcUK)

# *** *** ***