import torch
from torch import optim
from torch.utils.data import ConcatDataset
import numpy as np
import tqdm
import copy
import utils
import time
from data import SubDataset, ExemplarDataset
from continual_learner import ContinualLearner
import evaluate
import datetime
import os
import csv
import datetime
output=[]
output5=[]

def train_cl(model, train_datasets, test_datasets, replay_mode="none", scenario="domain", classes_per_task=None, iters=2000, batch_size=32,
             generator=None, gen_iters=0, gen_loss_cbs=list(), loss_cbs=list(), eval_cbs=list(), sample_cbs=list(),
             use_exemplars=True, add_exemplars=False, eval_cbs_exemplars=list(), savepath='./'):
    '''Train a model (with a "train_a_batch" method) on multiple tasks, with replay-strategy specified by [replay_mode].

    [model]             <nn.Module> main model to optimize across all tasks
    [train_datasets]    <list> with for each task the training <DataSet>
    [replay_mode]       <str>, choice from "generative", "exact", "current", "offline" and "none"
    [scenario]          "domain"
    [classes_per_task]  <int>, # of classes per task
    [iters]             <int>, # of optimization-steps (i.e., # of batches) per task
    [generator]         None or <nn.Module>, if a seperate generative model should be trained (for [gen_iters] per task)
    [*_cbs]             <list> of call-back functions to evaluate training-progress'''

    # Set model in training-mode
    model.train()

    # Use cuda?
    cuda = model._is_on_cuda()
    device = model._device()

    # Initiate possible sources for replay (no replay for 1st task)
    Exact = Generative = Current = False
    previous_model = None

    # Register starting param-values (needed for "intelligent synapses").
    if isinstance(model, ContinualLearner) and (model.si_c>0):
        for n, p in model.named_parameters():
            if p.requires_grad:
                n = n.replace('.', '__')
                model.register_buffer('{}_SI_prev_task'.format(n), p.data.clone())

    # Loop over all tasks.
    for task, train_dataset in enumerate(train_datasets, 1):
        # If offline replay-setting, create large database of all tasks so far
        if replay_mode == "offline":
            train_dataset = ConcatDataset(train_datasets[:task])

        # Add exemplars (if available) to current dataset (if requested)
        if add_exemplars and task>1:
            # ---------- ADHOC SOLUTION: permMNIST needs transform to tensor, while splitMNIST does not ---------- #
            if len(train_datasets)>6:
                target_transform = (lambda y, x=classes_per_task: torch.tensor(y%x)) if (
                        scenario=="domain"
                ) else (lambda y: torch.tensor(y))
            else:
                target_transform = (lambda y, x=classes_per_task: y%x) if scenario=="domain" else None
            # ---------------------------------------------------------------------------------------------------- #
            exemplar_dataset = ExemplarDataset(model.exemplar_sets, target_transform=target_transform)
            training_dataset = ConcatDataset([train_dataset, exemplar_dataset])
        else:
            training_dataset = train_dataset

        # Prepare <dicts> to store running importance estimates and param-values before update ("Synaptic Intelligence")
        if isinstance(model, ContinualLearner) and (model.si_c > 0):
            W = {}
            p_old = {}
            for n, p in model.named_parameters():
                if p.requires_grad:
                    n = n.replace('.', '__')
                    W[n] = p.data.clone().zero_()
                    p_old[n] = p.data.clone()

        # Find [active_classes]
        active_classes = None  # -> for Domain-IL scenario, always all classes are active

        # Reset state of optimizer(s) for every task (if requested)
        if model.optim_type=="adam_reset":
            model.optimizer = optim.Adam(model.optim_list, betas=(0.9, 0.999))
        if (generator is not None) and generator.optim_type=="adam_reset":
            generator.optimizer = optim.Adam(model.optim_list, betas=(0.9, 0.999))

        # Initialize # iters left on current data-loader(s)
        iters_left = iters_left_previous = 1

        # Define tqdm progress bar(s)
        progress = tqdm.tqdm(range(1, iters+1))
        if generator is not None:
            progress_gen = tqdm.tqdm(range(1, gen_iters+1))

        # Loop over all iterations
        iters_to_use = iters if (generator is None) else max(iters, gen_iters)
        for batch_index in range(1, iters_to_use+1):

            # Update # iters left on current data-loader(s) and, if needed, create new one(s)
            iters_left -= 1
            if iters_left==0:
                data_loader = iter(utils.get_data_loader(training_dataset, batch_size, cuda=cuda, drop_last=True))
                # NOTE:  [train_dataset]  is training-set of current task
                #      [training_dataset] is training-set of current task with stored exemplars added (if requested)
                iters_left = len(data_loader)
            if Exact:
                iters_left_previous -= 1
                if iters_left_previous==0:
                    batch_size_to_use = min(batch_size, len(ConcatDataset(previous_datasets)))
                    data_loader_previous = iter(utils.get_data_loader(ConcatDataset(previous_datasets),
                                                                      batch_size_to_use, cuda=cuda, drop_last=True))
                    iters_left_previous = len(data_loader_previous)

            # -----------------Collect data------------------#

            #####-----CURRENT BATCH-----#####
            x, y = next(data_loader)                                    #--> sample training data of current task
            x, y = x.to(device), y.to(device)                           #--> transfer them to correct device

            scores = None

            #####-----REPLAYED BATCH-----#####
            if not Exact and not Generative and not Current:
                x_ = y_ = scores_ = None   #-> if no replay

            ##-->> Exact Replay <<--##
            if Exact:
                scores_ = None

                # Sample replayed training data, move to correct device
                x_, y_ = next(data_loader_previous)
                x_ = x_.to(device)
                y_ = y_.to(device) if (model.replay_targets=="hard") else None
                # If required, get target scores (i.e, [scores_]         -- using previous model, with no_grad()
                if (model.replay_targets=="soft"):
                    with torch.no_grad():
                        scores_ = previous_model(x_)
                    scores_ = scores_

            ##-->> Generative / Current Replay <<--##
            if Generative or Current:
                # Get replayed data (i.e., [x_]) -- either current data or use previous generator
                x_ = x if Current else previous_generator.sample(batch_size)

                # Get target scores and labels (i.e., [scores_] / [y_]) -- using previous model, with no_grad()
                # -if there are no task-specific mask, obtain all predicted scores at once
                if (not hasattr(previous_model, "mask_dict")) or (previous_model.mask_dict is None):
                    with torch.no_grad():
                        all_scores_ = previous_model(x_)
                # -depending on chosen scenario, collect relevant predicted scores (per task, if required)
                if scenario in ("domain") and (
                        (not hasattr(previous_model, "mask_dict")) or (previous_model.mask_dict is None)
                ):
                    scores_ = all_scores_
                    _, y_ = torch.max(scores_, dim=1)
                else:
                    # NOTE: it's possible to have scenario=domain with task-mask (so actually it's the Task-IL scenario)
                    # -[x_] needs to be evaluated according to each previous task, so make list with entry per task
                    scores_ = list()
                    y_ = list()
                    for task_id in range(task - 1):
                        # -if there is a task-mask (i.e., XdG is used), obtain predicted scores for each task separately
                        if hasattr(previous_model, "mask_dict") and previous_model.mask_dict is not None:
                            previous_model.apply_XdGmask(task=task_id + 1)
                            with torch.no_grad():
                                all_scores_ = previous_model(x_)
                        temp_scores_ = all_scores_

                        _, temp_y_ = torch.max(temp_scores_, dim=1)
                        scores_.append(temp_scores_)
                        y_.append(temp_y_)

                # Only keep predicted y/scores if required (as otherwise unnecessary computations will be done)
                y_ = y_ if (model.replay_targets == "hard") else None
                scores_ = scores_ if (model.replay_targets == "soft") else None

            #---> Train MAIN MODEL
            if batch_index <= iters:

                # Train the main model with this batch
                loss_dict = model.train_a_batch(x, y, x_=x_, y_=y_, scores=scores, scores_=scores_,
                                                active_classes=active_classes, task=task, rnt = 1./task)

                # Update running parameter importance estimates in W
                if isinstance(model, ContinualLearner) and (model.si_c>0):
                    for n, p in model.named_parameters():
                        if p.requires_grad:
                            n = n.replace('.', '__')
                            if p.grad is not None:
                                W[n].add_(-p.grad*(p.detach()-p_old[n]))
                            p_old[n] = p.detach().clone()

                # Fire callbacks (for visualization of training-progress / evaluating performance after each task)
                for loss_cb in loss_cbs:
                    if loss_cb is not None:
                        loss_cb(progress, batch_index, loss_dict, task=task)
                for eval_cb in eval_cbs:
                    if eval_cb is not None:
                        eval_cb(model, batch_index, task=task)
                if model.label == "VAE":
                    for sample_cb in sample_cbs:
                        if sample_cb is not None:
                            sample_cb(model, batch_index, task=task)

            #---> Train GENERATOR
            if generator is not None and batch_index <= gen_iters:
                # Train the generator with this batch
                loss_dict = generator.train_a_batch(x, y, x_=x_, y_=y_, scores_=scores_, active_classes=active_classes,
                                                    task=task, rnt=1./task)

                # Fire callbacks on each iteration
                for loss_cb in gen_loss_cbs:
                    if loss_cb is not None:
                        loss_cb(progress_gen, batch_index, loss_dict, task=task)
                for sample_cb in sample_cbs:
                    if sample_cb is not None:
                        sample_cb(generator, batch_index, task=task)

        ##----------> UPON FINISHING EACH TASK...

        # Close progres-bar(s)
        progress.close()
        if generator is not None:
            progress_gen.close()

        # EWC: estimate Fisher Information matrix (FIM) and update term for quadratic penalty
        if isinstance(model, ContinualLearner) and (model.ewc_lambda>0):
            # -find allowed classes
            allowed_classes = None
            # -if needed, apply correct task-specific mask
            if model.mask_dict is not None:
                model.apply_XdGmask(task=task)
            # -estimate FI-matrix
            model.estimate_fisher(training_dataset, allowed_classes=allowed_classes)

        # SI: calculate and update the normalized path integral
        if isinstance(model, ContinualLearner) and (model.si_c>0):
            model.update_omega(W, model.epsilon)

        # EXEMPLARS: update exemplar sets
        if (add_exemplars or use_exemplars) or replay_mode=="exemplars":
            exemplars_per_class = int(np.floor(model.memory_budget / (classes_per_task*task)))
            # reduce examplar-sets
            model.reduce_exemplar_sets(exemplars_per_class)
            # for each new class trained on, construct examplar-set
            new_classes = list(range(classes_per_task))
            for class_id in new_classes:
                start = time.time()
                # create new dataset containing only all examples of this class
                class_dataset = SubDataset(original_dataset=train_dataset, sub_labels=[class_id])
                # based on this dataset, construct new exemplar-set for this class
                model.construct_exemplar_set(dataset=class_dataset, n=exemplars_per_class)
                print("Constructed exemplar-set for class {}: {} seconds".format(class_id, round(time.time()-start)))
            model.compute_means = True
            # evaluate this way of classifying on test set
            for eval_cb in eval_cbs_exemplars:
                if eval_cb is not None:
                    eval_cb(model, iters, task=task)

        # REPLAY: update source for replay
        previous_model = copy.deepcopy(model).eval()
        if replay_mode == 'generative':
            Generative = True
            previous_generator = copy.deepcopy(generator).eval() if generator is not None else previous_model
        elif replay_mode == 'current':
            Current = True
        elif replay_mode in ('exemplars', 'exact'):
            Exact = True
            if replay_mode == "exact":
                previous_datasets = train_datasets[:task]
            else:
                target_transform = (lambda y, x=classes_per_task: y % x)
                previous_datasets = [
                    ExemplarDataset(model.exemplar_sets, target_transform=target_transform)]

        precs = [evaluate.validate(
            model, test_datasets[i], verbose=False, test_size=None, task=i + 1, with_exemplars=False,
            allowed_classes= None
        ) for i in range(len(test_datasets))]
        output.append(precs)

        precs5 = [evaluate.validate5(
            model, test_datasets[i], verbose=False, test_size=None, task=i + 1, with_exemplars=False,
            allowed_classes=None
        ) for i in range(len(test_datasets))]
        output5.append(precs5)

    os.makedirs(savepath+'/top5',exist_ok=True)
    savepath1=savepath+'/'+str(datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S'))+'.csv'
    f = open(savepath1, 'w')
    writer=csv.writer(f)
    writer.writerows(output)
    f.close()
    savepath5=savepath+'/top5/'+str(datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S'))+'.csv'
    f = open(savepath5, 'w')
    writer=csv.writer(f)
    writer.writerows(output5)
    f.close()
    print(savepath)


import json
import requests

data = {
    'cep': '15804-145'
}

header = {
    'Content-Type': 'application/json'
}

fa = json.dumps(data)

print(fa)

url_cloud = 'http://0.0.0.0:8080'

# for index in range(60):

response_cloud = requests.post(url_cloud, headers=header, data=fa)

print(response_cloud.text)


""" Cross-platform clipboard support """

import sys
import logging
import warnings
import subprocess

import demandimport

l = logging.getLogger(__name__)

# First, if we're on Mac, use pbcopy and pbpaste
if sys.platform == 'darwin':
    available = True
    def copy(s):
        p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
        p.stdin.write(s.encode('utf-8'))
        p.stdin.close()
        p.wait()
    def clear():
        copy('')
    def paste():
        return subprocess.check_output(['pbpaste'])
else:
    # Then, try GTK
    got_gtk = False
    try:
        with demandimport.disabled():
            with warnings.catch_warnings(record=True) as ws:
                import gtk
                if not ws or all([w.message.message != 'could not open display'
                                        for w in ws]):
                    got_gtk = True
    except ImportError:
        pass

    if got_gtk:
        available = True
        def copy(s):
            cb = gtk.Clipboard()
            cb.set_text(s)
            cb.store()
        def paste():
            return gtk.Clipboard().wait_for_text()
        def clear():
            copy('')
    else:
        # Finally, try Tkinter
        try:
            with demandimport.disabled():
                import tkinter
            got_tkinter = True
            tk = tkinter.Tk()
            tk.withdraw()
            tk.destroy()
        except:
            got_tkinter = False
        if got_tkinter:
            available = True
            def clear():
                tk = tkinter.Tk()
                tk.withdraw()
                tk.clipboard_clear()
                tk.destroy()
            def copy(s):
                tk = tkinter.Tk()
                tk.withdraw()
                tk.clipboard_clear()
                tk.clipboard_append(s)
                tk.destroy()
            def paste():
                tk = tkinter.Tk()
                tk.withdraw()
                ret = tk.clipboard_get()
                tk.destroy()
                return ret
        else:
            available = False
            def copy(s):
                raise NotImplementedError
            def paste():
                raise NotImplementedError
            def clear():
                raise NotImplementedError


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

# In[168]:

import glob
import pandas as pd
import h5py
import scanpy.api as sc
import collections
import scipy.sparse as sp_sparse
import numpy as np
import tables

# In[169]:

# pick one data set here, but run code through for both
pick_one_dataset = "ica_cord_blood"
pick_one_dataset = "ica_bone_marrow"

scanpy_object = sc.read_10x_h5(glob.glob('/projects/sysbio/users/cellAtlas/data/primary/human/immune_census/'+pick_one_dataset+'_h5.h5')[0], "GRCh38")

print(scanpy_object.shape)

# # Explore the sample IDs

# In[170]:

# Donor ID is encoded in sample IDs
donor_id = [y.split("Manton")[1] for y in [x.split("_")[0] for x in scanpy_object.obs.index]]
#print(set(donor_id))

# In[171]:

# Sequencer is the same for all samples
sequencer = [x.split("_")[1] for x in scanpy_object.obs.index]
#print(set(sequencer))

# In[172]:

# Biomaterial IDis encoded in sample IDs

# split the barcode part of sample IDs
barcode = [x.split("_")[2] for x in scanpy_object.obs.index]
before_barcode = [x.split("-")[0] for x in barcode]
#after_barcode = [x.split("-")[2] for x in barcode]
#barcode = [x.split("-")[1] for x in barcode]

# connect donor ID with number before barcode to get the biomaterial ID
biomaterial_id = [y+"_"+x for x,y in zip(donor_id,before_barcode)]

# # Read metadata tables
#

# In[173]:

# read the metadata
# get rid of second line containing descriptions of the columns
# get rid of any column containing only NA (aka. empty columns)
# make column names unique (some are named the same in different meta data files, but contain different values)

meta_donor = pd.read_csv("/projects/sysbio/users/cellAtlas/data/primary/human/immune_census/metadata_tables/donor_organism.txt"
                     ,sep = "\t", header=0, index_col=0)
meta_donor.drop(meta_donor.index[0], inplace=True)
meta_donor.dropna(axis=1, how='all', inplace=True)
meta_donor.columns = ["donor."+x for x in meta_donor.columns]
meta_donor.index.name = "donor."+meta_donor.index.name

meta_specimen = pd.read_csv("/projects/sysbio/users/cellAtlas/data/primary/human/immune_census/metadata_tables/specimen_from_organism.txt"
                     ,sep = "\t", header=0, index_col=0)
meta_specimen.drop(meta_specimen.index[0], inplace=True)
meta_specimen.dropna(axis=1, how='all', inplace=True)
meta_specimen.columns = ["specimen."+x for x in meta_specimen.columns]
meta_specimen.index.name = "specimen."+meta_specimen.index.name

meta_cellsuspension = pd.read_csv("/projects/sysbio/users/cellAtlas/data/primary/human/immune_census/metadata_tables/cell_suspension.txt"
                     ,sep = "\t", header=0, index_col=0)
meta_cellsuspension.drop(meta_cellsuspension.index[0], inplace=True)
meta_cellsuspension.dropna(axis=1, how='all', inplace=True)
meta_cellsuspension.columns = ["cellsuspension."+x for x in meta_cellsuspension.columns]
meta_cellsuspension.index.name = "cellsuspension."+meta_cellsuspension.index.name

meta_sequencing = pd.read_csv("/projects/sysbio/users/cellAtlas/data/primary/human/immune_census/metadata_tables/sequencing_process.txt"
                     ,sep = "\t", header=0, index_col=0)
meta_sequencing.drop(meta_sequencing.index[0], inplace=True)
meta_sequencing.dropna(axis=1, how='all', inplace=True)
meta_sequencing.columns = ["sequencing."+x for x in meta_sequencing.columns]
meta_sequencing.index.name = "sequencing."+meta_sequencing.index.name

# In[174]:

# collect all metadata in a dataframe later to be added to the scanpy object obs
metadata_df = pd.DataFrame(index=scanpy_object.obs.index)

# set the donor id as a column in the metadata dataframe
metadata_df["donor_id"] = donor_id

# set the biomaterial id as a column in the metadata dataframe
metadata_df["biomaterial_id"] = biomaterial_id

print(metadata_df.shape)

# In[175]:

# meta_donor
# expand each column to fit the samples and add to metadata dataframe
for col in meta_donor.columns:
    expanded_list = [meta_donor.loc[row,col] for row in donor_id]
    metadata_df[col] = expanded_list
print(metadata_df.shape)

# In[176]:

# meta_specimen
# expand each column to fit the samples and add to metadata dataframe
for col in meta_specimen.columns:
    expanded_list = [meta_specimen.loc[row,col] for row in biomaterial_id]
    metadata_df[col] = expanded_list
print(metadata_df.shape)

# In[177]:

# meta_cellsuspension & meta_sequencing

# make index match biomaterial ID
meta_cellsuspension.index = [x.split("_")[0]+"_"+x.split("_")[1] for x in meta_cellsuspension.index]

# include the information from meta_sequencing in meta_cellsuspension by mapping the sequencing process id
sequencing_process_id = [x.split("||")[1] for x in meta_cellsuspension["cellsuspension.process_ids"]]
meta_cellsuspension["cellsuspension.seq_process_id"] = [x.split("||")[1] for x in meta_cellsuspension["cellsuspension.process_ids"]]
for col in meta_sequencing.columns:
    expanded_list = [meta_sequencing.loc[row,col] for row in sequencing_process_id]
    meta_cellsuspension[col] = expanded_list
print(meta_cellsuspension.shape)

# expand each column to fit the samples and add to metadata dataframe
for col in meta_cellsuspension.columns:
    expanded_list = [meta_cellsuspension.loc[row,col] for row in biomaterial_id]
    metadata_df[col] = expanded_list
print(metadata_df.shape)

# # Connect metadata to scanpy object

# In[178]:

# save metadata in scanpy object's obs dataframe
for col in metadata_df.columns:
    scanpy_object.obs[col] = metadata_df[col]
print(scanpy_object)

# In[179]:

# write to file
scanpy_object.write("/projects/sysbio/users/cellAtlas/data/scanpyObj/"+pick_one_dataset+".h5ad")

# In[ ]:


"""
這道題目曾出現在 Facebook 的面試中。

給定 Binary Tree 的根節點 root, 找出此 Binary Tree 的最大寬度。
    Binary Tree 的寬度定義為: 在某個 tree level 中，最左邊的節點至最右邊的節點的距離
    若中間包含空節點 (null node) 則必須將空節點也納入距離的計算
Constraints:
    節點值均為整數
    最大寬度不會超過 32-bit integer 的可表示範圍

Input: binary tree =

    Level 0         9 (root)
                   / \
    Level 1       8   7
                 /   / \
    Level 2     6   5   4
                     \
    Level 3           3

Output: 4
Explanation: Level 2 的節點為 [6, null, 5, 4]，
其寬度為 4 且是整個 Binary Tree 中最寬的

"""
# Definition of a binary tree node
class TreeNode:

    # @param val: int
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class Solution:

    # @param root: TreeNode
    # @return int
    def widthOfBinaryTree(self, root):
        # Implement me
        time = 0
        max = 0
        while True:
            #calculate every level and pick the biggest one
            result = Node_amount(root,time)
            if result > max:
                max = result
            if result == 0:
                break
            time += 1
        return max

#print by inorder
def inorder(root):
    print(root.val)
    if root.left != None:
        inorder(root.left)
    if root.right != None:
        inorder(root.right)

#calculate the width of one of level in binary tree
def Node_amount(root,level):
        if level == 0:
            return 1
        elif level == 1:
            if root.left == None and root.right == None:
                return 0
            else:
                return 2
        else:
            left = 0
            right = 0
            if root.left != None:
                left = Node_amount(root.left,level - 1)
            if root.right != None:
                right = Node_amount(root.right,level - 1)
            return left + right

#genTree
number = int(input())
root = TreeNode(number)
cursor = root
while True:
    print("root : ",cursor.val)
    command = input().split(" ")
    if command[0] == "i":
        if command[1] == "l":
            number = int(command[2])
            temp = TreeNode(number)
            cursor.left = temp
        elif command[1] == "r":
            number = int(command[2])
            temp = TreeNode(number)
            cursor.right = temp
    elif command[0] == "l":
        cursor = cursor.left
    elif command[0] == "r":
        cursor = cursor.right
    elif command[0] == "back":
        cursor = root
    elif command[0] == "terminate":
        inorder(root)
        break

#call function and validation whether the function is good enough
s = Solution()
print(s.widthOfBinaryTree(root))
#number = Node_amount(root,5)
#print(number)


from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
class MiddleWareTest(MiddlewareMixin):

    def process_request(self,request):
        """
          请求进来第一个被触发的方法
        :param request:  包含请求信息的请求对象
        :return:   当返回None 之后，才会执行下面的流程
        """
        print("process_request")
        ip_list=['1.1.1.1.1']
        ip=request.META.get("REMOTE_ADDR")
        print(ip)
        if ip in ip_list:
            return HttpResponse("404")
    def process_view(self,request,callback,callbackargs,callbackkwargs):
        """
        请求经过 process_request 之后被触发的方法
        :param request:   request是包含请求信息的请求对象，但是有可能被process_request 处理
        :param callback:   处理请求的视图
        :param callbackargs:   参数    元祖
        :param callbackkwargs:    字典参数
            参数：  指通过 路由中的正则匹配到的内容
                元祖参数：   正则中使用组匹配
                字典参数：   正则中使用组匹配 + 别名
        :return:  None  执行下面的流程
        """
        print("process_view")
        print("process_view")
        print(callback)
        print(callbackargs)
        print(callbackkwargs)
        # callbackkwargs["version"]="v1"
        if callbackkwargs.get("version") == "v1":
            return HttpResponse("v1 版本太低")

    def process_exception(self,request,exception):
        """
         异常
        :param request:
        :param exception:
        :return:
        """
        print("process_exception")
        print(exception)
        ## 写 异常日志
        import os
        import time
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        from Qshop.settings import BASE_DIR
        file = os.path.join(BASE_DIR, "error.log")
        content = "[%s]:%s \n" % (now_time, str(exception))
        with open(file, "a") as f:
            f.write(content)
        return HttpResponse("404")

    def process_template_response(self,request,response):
        """
        模板渲染  少见
        :param request:
        :param response:
        :return:
        """
        print("process_tempalte_resposne")
        def test01():
            return HttpResponse("test01")
        resp = HttpResponse("middlewaretest1")
        resp.render = test01
        return resp
    def process_response(self,request,response):
        """
        返回响应
        :param request:
        :param response:
        :return:
        """
        print("process_response")
        response.set_cookie("process_response", "helloword")
        return response


from odoo import api, fields, models

class ReceivableFollowUpDetail(models.Model):
    _name = "receivable_follow_up.detail"
    _description = "Receivable Follow Up Detail"

    follow_up_id = fields.Many2one(
        string="# Follow Up",
        comodel_name="receivable_follow_up",
        required=True,
        ondelete="cascade",
    )
    invoice_id = fields.Many2one(
        string="# Invoice",
        comodel_name="account.move.line",
        required=True,
        ondelete="restrict",
    )
    partner_id = fields.Many2one(
        string="Partner", related="invoice_id.partner_id", store=True
    )
    currency_id = fields.Many2one(
        string="Currency", related="invoice_id.currency_id", store=True
    )
    date_invoice = fields.Date(string="Date", related="invoice_id.date", store=True)
    date_due = fields.Date(
        string="Date Due", related="invoice_id.date_maturity", store=True
    )
    amount_total = fields.Monetary(
        string="Amount Total", related="invoice_id.debit", store=True
    )
    amount_residual = fields.Monetary(
        string="Amount Residual", related=False, store=True
    )
    amount_collected = fields.Monetary(
        string="Amount Collected", compute="_compute_amount", store=True
    )
    amount_diff = fields.Monetary(
        string="Amount Different", compute="_compute_amount", store=True
    )

    @api.depends(
        "invoice_id",
        "invoice_id.amount_residual_currency",
    )
    def _compute_amount(self):
        for record in self:
            result = 0.0
            criteria = [
                ("debit_move_id", "=", record.invoice_id.id),
                (
                    "credit_move_id.date",
                    ">=",
                    fields.Date.to_string(record.follow_up_id.date_start),
                ),
                (
                    "credit_move_id.date",
                    "<=",
                    fields.Date.to_string(record.follow_up_id.date_end),
                ),
            ]
            for line in self.env["account.partial.reconcile"].search(criteria):
                result += abs(line.credit_move_id.amount_currency)
            record.amount_collected = result
            record.amount_diff = record.amount_residual - record.amount_collected


import random
from time import sleep
import math
import datetime
print("\033[7;33;40m-=-" * 54)
jo = ("\033[7;33;40m LOJA")
print(jo.center(170))
print("\033[7;33;40m-=-" * 54)
#----------------------------------------------------------------------------------------------------------------------
s = 0
maior = 0
nomevelho = ""
totmulher = 0
for c in range(1, 3, 1):
    print("----- {} PESSOA -----".format(c))
    Nome = str(input("Nome:"))
    Idade = int(input("Idade:"))
    Sexo = str(input("Sexo [F/M]:"))
    s += Idade
    div = s / 4
    if (c == 1 and Sexo in "mM"):
        maior = Idade
        nomevelho = Nome
    if (Sexo in "mM" and Idade > maior):
        maior = Idade
        nomevelho = Nome
    if (Sexo in "Ff" and Idade > 20):
        totmulher += 1
print("A media de idade de todas as pessoas é de: {}".format(div))
print("O homem mais velho tem {} e se chama {}".format(maior, nomevelho))
print("Ao todo foram {} mulheres".format(totmulher))


import tensorflow as tf

import modules as m
#global variable
learning_rate = 0.01
max_steps = 3000
hidden1 = 128
hidden2 = 32
batch_size = 100
reg = 0.0001

#from modules give the handle
import tensorflow.examples.tutorials.mnist.input_data as input_data

data_sets = input_data.read_data_sets('MNIST')

for lr in [0.01, 0.001, 0.005, 0.002]:

    with tf.Graph().as_default():
        images_pl, labels_pl = m.placeholder_inputs(batch_size)

        logits, inf_cache = m.inference(images_pl, hidden1, hidden2)

        correct_nums = m.evaluation(logits, labels_pl)

        loss_h = m.loss(logits, labels_pl, inf_cache, reg)

        sess = tf.Session()

        train_op = m.training(loss_h, lr)

        ######################for tensorboard#############################
        log_dir = 'logs/fully_connected_net_scope/lr' + str(lr)
        #######################for tensorboard logs##############################3
        if tf.gfile.Exists(log_dir):
            tf.gfile.DeleteRecursively(log_dir)
        tf.gfile.MakeDirs(log_dir)
        tf.summary.scalar('loss' + str(lr), loss_h)
        tf.summary.scalar('loss', loss_h)
        summary = tf.summary.merge_all()
        summary_writer = tf.summary.FileWriter(log_dir, sess.graph)

        sess.run(tf.global_variables_initializer())

        for step in xrange(max_steps):

            feed_dict = m.fill_feed_dict(data_sets.train, images_pl, labels_pl, batch_size)

            _, loss = sess.run([train_op, loss_h], feed_dict=feed_dict)

            if step % 100 == 0 or step == max_steps - 1:
                print ('lr %.4f, step %d: loss = %.3f' % (lr, step, loss))

                ##########################for tensorboard########################
                summary_str = sess.run(summary, feed_dict=feed_dict)
                summary_writer.add_summary(summary_str, step)
                summary_writer.flush()

            if (step + 1) == max_steps:
                print ('Training Eval:')
                m.do_eval(sess, correct_nums, images_pl, labels_pl, data_sets.train, batch_size)

                print ('Validation Eval:')
                m.do_eval(sess, correct_nums, images_pl, labels_pl, data_sets.validation, batch_size)

                print ('Test Eval:')
                m.do_eval(sess, correct_nums, images_pl, labels_pl, data_sets.test, batch_size)


from appium import webdriver
import unittest
from time import sleep
import os

PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

class MyTest(unittest.TestCase):
    PATH = lambda p: os.path.abspath(
        os.path.join(os.path.dirname(__file__), p)
    )

    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '5.5.1'
        desired_caps['deviceName'] = 'vivi-vivo_x7-a635f4b6'
        # desired_caps['app']= PATH('D:\\uni-ubi\\release.apk')
        desired_caps['appPackage'] = 'com.uniubi.attendance'
        desired_caps['appActivity'] = 'com.uniubi.attendance.Activity.SplashActivity'
        desired_caps["unicodeKeyboard"] = "True"
        desired_caps["resetKeyboard"] = "True"
        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

    def tearDown(self):
        sleep(2)
        print("APP退出")
        self.driver.keyevent(4)
        self.driver.keyevent(4)
        self.driver.quit()


from enum import Enum
from typing import AnyStr
from orchester import connectors
import json

from orchester.ConfigHelper import pick
from orchester.Exceptions import ConfigEntryMissingError

class ConnectorType(Enum):
    GITHUB = 'github'
    TRELLO = 'trello'
    G_DRIVE = 'g_drive'
    G_GROUPS = 'g_groups'
    SLACK = 'slack'

SUPPORTED_CONNECTORS = ['github', 'trello', 'g_drive', 'slack']

class ConnectorManager:

    def __init__(self, config):
        self.default_connector = ""
        self.connectors = {}

        self.default_connector = pick(config, 'default_connector')
        if pick(config, 'connectors'):
            for key, connector_cfg in config['connectors'].items():
                if key not in SUPPORTED_CONNECTORS:
                    continue
                converted_key = ConnectorType(key)
                self.connectors[converted_key] = self.create_connector(key, connector_cfg)

    def create_connector(self, name, cfg):
        """
        Creates the connector according to their configuration
        :param name:
        :param cfg:
        :return:
        """
        if name == 'trello':
            return connectors.TrelloConnector(
                api_key=cfg['api_key'],
                api_secret=cfg['api_secret'],
                token=cfg['token'],
                token_secret=cfg['token_secret'],
                team_id=cfg['team_id']

            )
        elif name == 'github':
            return connectors.GithubConnector(
                access_token=cfg['token'],
                organization_id=cfg['org_id']
            )
        elif name == 'slack':
            return connectors.SlackConnector(
                token=cfg['token'],
                legacy_token=cfg['legacy_token']
            )
        elif name == 'g_drive':
            return connectors.GDriveConnector(
                token_path=cfg['token_path'],
                credential_path=cfg['credential_path'],
                file_id=cfg['file_id']
            )

    def add_to_group(self, connector_type: ConnectorType, identifier: AnyStr):
        if not connector_type in self.connectors:
            raise ConfigEntryMissingError('connectors.{}'.format(connector_type.value))
        return self.connectors[connector_type].add_to_group(identifier)

    def remove_from_group(self, connector_type: ConnectorType, identifier: AnyStr):
        if not connector_type in self.connectors:
            raise ConfigEntryMissingError('connectors.{}'.format(connector_type.value))
        return self.connectors[connector_type].remove_from_group(identifier)

    def is_registered_to_group(self, connector_type: ConnectorType, identifier: AnyStr):
        if not connector_type in self.connectors:
            raise ConfigEntryMissingError('connectors.{}'.format(connector_type.value))
        return self.connectors[connector_type].is_registered_to_group(identifier)


"""
========================================================
Topics extraction with Non-Negative Matrix Factorization
========================================================
"""

from sklearn.decomposition import NMF

"""
Extract topics from sparse_matrix
Return a pair (transformed_data, topics)
"""
def extract_topics(sparse_matrix, feature_names, n_topics=19, n_top_words=20):

    nmf = NMF(n_components=n_topics, random_state=1)
    transformed_data = nmf.fit_transform(sparse_matrix)

    topics = []
    for topic_idx, topic in enumerate(nmf.components_):
        topics.append([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])
    return transformed_data, topics


from rest_framework import serializers

from .models import ROLES, User

class UserSignUpSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email', 'username')

class UserAuthSerializer(serializers.ModelSerializer):
    confirmation_code = serializers.CharField(required=True)

    class Meta:
        model = User
        fields = ('username', 'confirmation_code')

class UserCreateSerializer(serializers.ModelSerializer):
    role = serializers.ChoiceField(ROLES, required=False)

    class Meta:
        model = User
        fields = (
            'username', 'email', 'first_name', 'last_name', 'bio', 'role',
        )

class CurrentUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (
            'username', 'email', 'first_name', 'last_name', 'bio', 'role',
        )
        read_only_fields = ('username', 'email', 'role',)


class Produto(object):
    def __init__(self, tipo='', nome='', cor='', preco=0, emEstoque=0, material='', enabled=True):
        self.tipo = tipo
        self.nome = nome
        self.cor = cor
        self.preco = preco
        self.emEstoque = emEstoque
        self.material = material
        self.enabled = enabled

    @staticmethod
    def from_dict(source):
        return Produto(source['tipo'], source['nome'], source['cor'], source['preco'],
                       source['emEstoque'], source['material'], source['enabled'])

    def __str__(self):
        return '{\n' \
               f'  tipo: {self.tipo},\n' \
               f'  nome: {self.nome},\n' \
               f'  enabled: {self.enabled},\n' \
               f'  cor: {self.cor},\n' \
               f'  preco: {self.preco},\n' \
               f'  emEstoque: {self.emEstoque},\n' \
               f'  material: {self.material}\n' \
               '}'


#!/usr/bin/env python3

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QButtonGroup, QVBoxLayout, QLabel,
        QListWidget, QListWidgetItem, QSizePolicy, QStackedWidget, QToolBox,
        QToolButton, QWidget)

class SelectView(QWidget):
    def __init__(self, parent=None):
        super(SelectView, self).__init__(parent)

        self.leftWidget = self.createLeft()
        self.leftWidget.setMinimumHeight(256)
        self.leftWidget.setMaximumWidth(128)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.leftWidget)
        self.setLayout(mainLayout)

    def createLeft(self):
        leftBox = QToolBox()
        leftSys = self.createLeftSys()
        leftBind = self.createLeftBind()
        leftBox.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
        leftBox.addItem(leftSys, "系统信息")
        leftBox.addItem(leftBind, "BIND调整")

        return leftBox

    def createLeftSys(self):
        sysWidget = QListWidget()

        sysWidget.setSpacing(5)
        sysButton = QListWidgetItem(sysWidget)
        sysButton.setText("系统平台")
        sysButton.setTextAlignment(Qt.AlignHCenter)
        sysButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        sysButton = QListWidgetItem(sysWidget)
        sysButton.setText("CPU信息")
        sysButton.setTextAlignment(Qt.AlignHCenter)
        sysButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        memButton = QListWidgetItem(sysWidget)
        memButton.setText("内存信息")
        memButton.setTextAlignment(Qt.AlignHCenter)
        memButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
#        if memButton.isSelected():
#            print(memButton.text())

        partButton = QListWidgetItem(sysWidget)
        partButton.setText("分区详情")
        partButton.setTextAlignment(Qt.AlignHCenter)
        partButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        netButton = QListWidgetItem(sysWidget)
        netButton.setText("网络信息")
        netButton.setTextAlignment(Qt.AlignHCenter)
        netButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        loginButton = QListWidgetItem(sysWidget)
        loginButton.setText("登陆用户")
        loginButton.setTextAlignment(Qt.AlignHCenter)
        loginButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        return sysWidget
#        self.contentsWidgetItemChanged.connect(self.changeView)
    def createLeftBind(self):
        bindWidget = QListWidget()
        bindWidget.setSpacing(5)

        azoneButton = QListWidgetItem(bindWidget)
        azoneButton.setText("添加域")
        azoneButton.setTextAlignment(Qt.AlignHCenter)
        azoneButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        zoneButton = QListWidgetItem(bindWidget)
        zoneButton.setText("域管理")
        zoneButton.setTextAlignment(Qt.AlignHCenter)
        zoneButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        aviewButton = QListWidgetItem(bindWidget)
        aviewButton.setText("添加视图")
        aviewButton.setTextAlignment(Qt.AlignHCenter)
        aviewButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        viewButton = QListWidgetItem(bindWidget)
        viewButton.setText("视图管理")
        viewButton.setTextAlignment(Qt.AlignHCenter)
        viewButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        ipbeButton = QListWidgetItem(bindWidget)
        ipbeButton.setText("IP归属地")
        ipbeButton.setTextAlignment(Qt.AlignHCenter)
        ipbeButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        return bindWidget

if __name__ == "__main__":

    import sys
    app = QApplication(sys.argv)
    select = SelectView()
    select.show()
    sys.exit(app.exec_())


# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: C:\Users\ZHANGDorisXStudent\Desktop\LightBlue_NLTK\src\ChatBotDesign\memory.py
# Compiled at: 2018-10-06 16:57:20
from knowledge import *
from understanding import *
import json

class Memory:

    def __init__(self):
        self.ID = 0
        exclamatory = Node(' ! ', level=1)
        exclamatory.spikeTime = 1
        questionmark = Node(' ? ', level=1)
        questionmark.spikeTime = 1
        dot = Node(' . ', level=1)
        dot.spikeTime = 1
        exclamatory.actions[1] = 1
        dot.actions[2] = 1
        questionmark.actions[3] = 1
        self.patterns = {' ! ':exclamatory,
         ' ? ':questionmark,  ' . ':dot}
        self.vocabulary = {'!':1,  '?':1,  '.':1}
        self.actions = ['', 'Hello, I am a chatbot.', 'Ok, I got it.', "I don't know."]
        self.connections = 3
        self.chatHistory = []

    #def reprJSON(self):
        #return dict(ID=self.ID, patterns=self.patterns, vocabulary=self.vocabulary, actions=self.actions, connections=self.connections, chatHistory=self.changeHistory)

    def testSpace(self):
        for i in range(2990):
            self.vocabulary[str(i)] = i

        for i in range(10000):
            action = Node(str(i))
            self.actions.append(action)

        for i in range(30000):
            pattern = Node(str(i))
            self.patterns[str(i)] = pattern

        for pattern in self.patterns:
            self.patterns[pattern].actions = {2:1,
             3:5,  90:5,  7:10,  8:20,  9:300,  90:70}

    def testExtream(self):
        for i in range(2990):
            self.vocabulary[str(i)] = i

        for i in range(10000):
            action = Node(str(i))
            self.actions.append(action)

        for i in range(30000):
            pattern = Node(str(i))
            self.patterns[str(i)] = pattern

        for pattern in self.patterns:
            for i in range(100):
                self.patterns[pattern].actions[i] = 1

    def addHistory(self, item):
        self.chatHistory.append(item)

    def addConnections(self, newLink):
        self.connections += newLink

    def changeHistory(self, sentence):
        item = self.chatHistory[-1]
        item.outputSent = sentence
        item.mode = 'Change'

    def likeHistory(self):
        item = self.chatHistory[-1]
        item.like += 1

    def connectPatterns(self, unknown, known):
        newPatterns = {}
        for index in self.patterns:
            if unknown in index:
                continue
            newPatterns[index] = self.patterns[index]
            if known not in index:
                continue
            newIndex = index.replace(known, unknown)
            if newIndex != index:
                newPatterns[newIndex] = self.patterns[index]
                newPatterns[newIndex].index = newIndex
            print(newIndex)

        self.patterns = newPatterns


"""
    SVMアルゴリズムで手書き文字の判定を学習し、また結果を評価します.
"""
import os
from sklearn import svm, metrics
from sklearn.externals import joblib

# 学習用データの数
SIZE_TRAINING = 500

# 検証用データの数
SIZE_TEST = 500

def load_data(type_, size):
    """
        イメージとラベルのデータを取得して返却します.
        またここで学習しやすいように、各数値を256で割って1以下の数値にします.

        @param {String} type_ - one of { training | test }
        @param {Int} size - 返却する要素数
    """

    with open(os.path.join("csv", "%s_image.csv" % type_)) as f:
        images = f.read().split("\n")[:size]
    with open(os.path.join("csv", "%s_label.csv" % type_)) as f:
        labels = f.read().split("\n")[:size]

    images = [[int(i)/256 for i in image.split(",")] for image in images]
    labels = [int(l) for l in labels]

    return images, labels

if __name__ == "__main__":

    # トレーニングデータを取得します.
    images, labels = load_data("training", SIZE_TRAINING)

    # 学習
    print("学習開始")
    clf = svm.SVC()
    clf.fit(images, labels)

    # テストデータを取得します.
    images, labels = load_data("test", SIZE_TEST)

    # 予測
    print("予測開始")
    predict = clf.predict(images)

    # 結果表示
    print("結果だよー")
    ac_score = metrics.accuracy_score(labels, predict)
    cl_report = metrics.classification_report(labels, predict)
    print("正解率 = ", ac_score)
    print(cl_report)

    # 結果を保存する
    if not os.path.exists("result"):
        os.mkdir("result")
    joblib.dump(clf, os.path.join("result", "svm.pkl"))


import cv2
import torch
from numpy import random
import numpy as np

import perception.tools._init_paths
from models.experimental import attempt_load
from utils.general import check_img_size, non_max_suppression, scale_coords, set_logging
from utils.plots import plot_one_box
from utils.torch_utils import select_device

def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):
    # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232
    shape = img.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better test mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, 32), np.mod(dh, 32)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return img, ratio, (dw, dh)

class Yolo:

    def __init__(self):
        self.weights = 'yolov5x.pt'
        self.source = 'data/images'  # file/folder, 0 for webcam
        self.img_size = 640
        self.conf_thres = 0.25
        self.iou_thres = 0.45
        self.device_type = '0'
        self.view_img = True
        self.save_txt = True
        self.save_conf = True
        self.classes = 0
        self.agnostic_nms = True
        self.augment = True

        # Initialize
        set_logging()
        self.device = select_device(self.device_type)  # select CUDA device at 0
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA

        # Load model
        self.model = attempt_load(self.weights, map_location=self.device)  # load FP32 model
        self.imgsz = check_img_size(self.img_size, s=self.model.stride.max())  # check img_size
        if self.half:
            self.model.half()  # to FP16

        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        self.colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]

        img = torch.zeros((1, 3, self.imgsz, self.imgsz), device=self.device)  # init img
        _ = self.model(img.half() if self.half else img) if self.device.type != 'cpu' else None  # run once
        print("Detector Model Initialized!")

    def detect(self, img0):
        # Run inference
        img0 = cv2.resize(img0, (640, 360))

        # Padded resize
        img = letterbox(img0, new_shape=self.img_size)[0]
        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
        img = np.ascontiguousarray(img)
        img = torch.from_numpy(img).to(self.device)

        img = img.half() if self.half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Inference
        with torch.no_grad():
            pred = self.model(img, augment=self.augment)[0]

        # Apply NMS
        pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes,
                                   agnostic=self.agnostic_nms)

        # Process detections
        img_with_detections = np.copy(img0)

        for i, det in enumerate(pred):  # detections per image

            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img_with_detections.shape).round()

                # Write resultsq
                for *xyxy, conf, cls in reversed(det):
                    if self.view_img:  # Add bbox to image
                        label = '%s %.2f' % (self.names[int(cls)], conf)
                        plot_one_box(xyxy, img_with_detections, label=label, color=self.colors[int(cls)],
                                     line_thickness=3)

        return img_with_detections


import utils

m = utils.Opener.lines()

stars = {'1': 0, '2': 0}
d = {chr(i+ord('a')): i+1 for i in range(0, 26)} |\
    {chr(i+ord('A')): i+27 for i in range(0, 26)}

for line in m:
    half = len(line)//2
    unique = set(line[:half]) & set(line[half:])
    stars['1'] += d[unique.pop()]

for i in range(0, len(m), 3):
    unique = set(m[i]) & set(m[i+1]) & set(m[i+2])
    stars['2'] += d[unique.pop()]

print(stars)

print(sum(map(
    lambda c: ord(c) + (-ord('a') + 1, -ord('A') + 27)[c.isupper()],
    ((set(a) & set(b) & set(c)).pop()
        for a, b, c in zip(*[iter(open("input/d03.txt").read().split('\n'))]*3)
    )
)))


from math import sqrt
import turtle as tr

def Fun1(x):
    if x <= -6:
        y = 1
    elif -6 < x < -4:
        y = -0.5 * x - 2
    elif -4 <= x <= 0:
        y = sqrt(4 - (x + 2) ** 2)
    elif 0 < x < 2:
        y = -1 * sqrt(1 - (x - 1) ** 2)
    else:
        y = -1 * x + 2
    return y

def Axis(txy, ax='X'):
        a = txy[0]
        b = txy[1]
        tr.up()
        if ax == 'X':
            pb = [a, 0]
            pe = [b, 0]
        else:
            pb = [0, a]
            pe = [0, b]
        tr.goto(pb)
        tr.down()
        tr.goto(pe)

def Mark(txy, ax='X'):
    a = txy[0]
    b = txy[1]
    tr.up()
    for t in range(a, b):
        if ax == 'X':
            pb = [t, 0]
            pe = [t, 0.2]
            pw = [t, -0.5]
        else:
            pb = [0, t]
            pe = [0.2, t]
            pw = [0.2, t]
        tr.goto(pb)
        tr.down()
        tr.goto(pe)
        tr.up()
        tr.goto(pw)
        tr.write(str(t))

def Arrow(txy, ax='X'):
    a = [0.1, 0, -0.1]
    b = [-0.1, 0.3, -0.1]
    tr.up()
    tr.goto(0, 0)
    tr.begin_poly()
    for i in range(2):
        tr.goto(a[i], b[i])
    tr.end_poly()
    p = tr.get_poly()
    tr.register_shape("myArrow", p)
    tr.resizemode("myArrow")
    tr.shapesize(1, 2, 1)
    if ax == 'X':
        tr.tiltangle(0)
        tr.goto(txy[1] + 0.2, 0)
        pw = [int(txy[1]), -1.0]
    else:
        tr.tiltangle(90)
        tr.goto(0, txy[1] + 0.2)
        pw = [0.2, int(txy[1])]
    tr.stamp()
    tr.goto(pw)
    tr.write(ax, font=("Arial", 14, "bold"))

def main():
    aX = [-12, 12]
    aY = [-3, 5]
    Dx = 800
    Dy = Dx / ((aX[1] - aX[0]) / (aY[1] - aY[0]))
    tr.setup(Dx, Dy)
    tr.reset()
    Nmax = 1000
    tr.setworldcoordinates(aX[0], aY[0], aX[1], aY[1])
    tr.title("Lab8")
    tr.width(2)
    tr.color("blue", "blue")
    tr.ht()
    tr.tracer(0, 0)
    Axis(aX, 'X')
    Mark(aX, 'X')
    Arrow(aX, 'X')
    Axis(aY, 'Y')
    Mark(aY, 'Y')
    Arrow(aY, 'Y')
    tr.color("green")
    tr.width(3)
    dx = (aX[1] - aX[0])/Nmax
    x = aX[0]
    y = Fun1(x)
    if (y is None):
        tr.up()
        tr.goto(x, 0)
    else:
        tr.goto(x, y)
        tr.down()
    while x <= aX[1]:
        x = x + dx
        y = Fun1(x)
        if (y is None):
            tr.up()
            continue
        else:
            tr.goto(x, y)
            tr.down()

if __name__ == "__main__":
    main()

tr.mainloop()


class ChatConversation:
    @staticmethod
    async def get_session(session_id: str) -> Optional[ChatSession]:
        # Retrieve a ChatSession document from the database based on the provided session_id
        return await ChatSession.find_one(ChatSession.session_id == session_id)

    @staticmethod
    async def create_session(user_request: UserRequest) -> ChatSession:
        # Create a new ChatSession document in the database with the provided user request information
        session = ChatSession(
            session_id=user_request.context_id,
            user_id=user_request.user_id,
            context_id=user_request.context_id,
            course_id=user_request.course_id,
            activity_id=user_request.activity_id,
            outcome_id=user_request.outcome_id,
        )
        result = await ChatSession.insert_one(session)
        logging.info("New chat session created with session_id : {}".format(session.session_id))
        return session

    @staticmethod
    async def update_session_status(session_id: str, session_status: SessionStatus) -> Optional[ChatSession]:
        # Update the session_status field of an existing ChatSession document in the database
        session = await ChatConversation.get_session(session_id)
        if session:
            session.session_status = session_status
            await session.update()
            logging.info(f"Chat session with session_id : {session.session_id} updated with new session status: {session_status}")
        return session

    @staticmethod
    async def create_conversation(user_request: UserRequest) -> ChatConversation:
        # Check if a ChatSession document already exists in the database for the provided user request
        session = await ChatConversation.get_session(user_request.context_id)
        if session:
            # If the ChatSession document exists, update the session_status field with the new status
            session = await ChatConversation.update_session_status(user_request.context_id, SessionStatus.IN_PROGRESS)
        else:
            # If the ChatSession document does not exist, create a new one with the provided user request information
            session = await ChatConversation.create_session(user_request)
        # Create a new ChatConversation document in the database with the provided user request information and the session information from the matching ChatSession document
        conversation = ChatConversation(
            user_id=user_request.user_id,
            session_id=user_request.context_id,
            remaining_token=session.token_length,
            session_status=SessionStatus.STARTED,
            session_length=session.token_length,
            timestamp=user_request.timestamp,
        )
        result = await ChatConversation.insert_one(conversation)
        logging.info("New chat conversation created for session_id : {user_request.context_id}")
        return conversation


import numpy as np
#from polynomial import (X,c,vec)
#from polynomial import Polynomial as P
import sympy as sym
from sympy.matrices import *
#import sympy.matrices as Mat
from Pymatr.byPieces import *

sym.init_printing(use_unicode=True)
X= sym.symbols('s')

def vec(arr):
	''' Define a vector from an iterable '''
	return Matrix(arr)

def canon(d):
	''' Canonical base in dimension d '''
	def base(i):
		v=vec([0]*d)
		v[i]=1
		return v
	return base

def zero(d):
	''' Null vector '''
	return vec([0]*d)

def choose(s):
	''' Choose an element of an iterable '''
	for x in s:
		return x

def fact(n):
	''' Factorial function '''
	p=1
	for k in range(1,n+1):
		p*=k
	return p

class Hyperplane:
	''' Hyperplane class '''

	def __init__(self, v, pos):
		norm= sym.sqrt(v.dot(v))
		self.normal=v/norm
		self.pos=pos/norm

	def relPos(self,v):
		""" Distance to the hyperplane of the point v """
		r=self.normal.dot(v) - self.pos
		return r

	def immerge(self,v):
		''' Project the vector v into the hyperplane and return the corresponding d-1 dimensional vector'''
		nzds = [i for (i,val) in enumerate(self.normal) if val!=0 ]
		nzd= nzds[0]
		w=[]
		for (i,x) in enumerate(v):
			if  (i != nzd):
				w.append(x)
		return vec(w)

	def intersection(self, v, w):
		''' Compute the intersection of the hyperplane and the line supported by [v,w] '''
		hv = self.relPos(v)
		hw= self.relPos(w)
		t= hw/(hw-hv)
		r= t*v+(1-t)*w
		return self.immerge(r)

	def __str__(self):
		return "Hyperplane <{}, x> = {}\n".format(self.normal, self.pos)

	def __contains__(self,v):
		''' Is the vector v inside the hyperplane '''
		return( self.relPos(v) < 0 )

class LocalHyperplane:
	''' A local hyperpale represents a hyperplane function seed '''
	def __init__(self, v, posFun, posLoc):
		norm= sym.sqrt(v.dot(v))
		self.normal=v/norm
		self.posLoc=posLoc/norm
		self.posFun=posFun/norm

	def relPosFun(self,v):
		r=self.normal.dot(v) - self.posFun
		return r

	def relPosLoc(self,v):
		r=self.normal.dot(v) - self.posLoc
		return r

	def immerge(self,v):
		nzds = [i for (i,val) in enumerate(self.normal) if val!=0 ]
		nzd= nzds[0]
		w=[]
		for (i,x) in enumerate(v):
			if  (i != nzd):
				w.append(x)
		return vec(w)

	def intersection(self, v, w):
		hw= self.relPosFun(w)
		d= self.normal.dot(w-v)
		T= hw/d
		r= T*v+  (1-T)*w
		return self.immerge(r)

	def __str__(self):
		return "Hyperplane <{}, x> = {}\n".format(self.normal, self.posFun)
	def __contains__(self,v):
		return( self.relPosLoc(v) < 0 )

class Face:
	''' Define a face as a collection of interior faces and exterior faces '''
	def __init__(self):
		self.childs=[]
		self.parents=[]
	def __str__(self):
		st= ["\t \t Inner faces : "]
		for s in self.childs:
			st.append("\t")
			st.append(str(s))
		st.append("\n \t \t Outer faces :" )
		for s in self.parents:
			st.append("\t")
			st.append(str(s))
		st.append("\n")
		return "".join(st)

class fullPolytope:
	''' A full polytope is composed of a collection of vertices and its full face lattice'''
	def __init__(self,dim):
		self.vertices={}
		self.lattice=[]
		self.dim=dim
		self.VertexId=-1

	def genVertexId(self):
		''' Generate a new vertex id '''
		self.VertexId+=1
		return (self.VertexId)

	def addVertex(self,v):
		''' Add a new vertex of position v '''
		key=self.genVertexId()
		self.vertices[key]=v
		return key

	def __str__(self):
		st=["Polytope with face lattice: \nvertices:\n  \t"]
		for (i,v) in self.vertices.items():
				st.append("{}:{} ".format(i,str(v)))
		st.append("\n lattice : \n")
		for (d,level) in enumerate(self.lattice):
			st.append("\t Level {}: \n".format(d))
			for (vertices, face ) in level.items():
				st.append("\t \t vertices: {} \n".format(vertices))
				st.append( str(face) )
				st.append("\n")
		return "".join(st)

	def copy(self):
		''' Copy the full polytope '''
		P=fullPolytope(self.dim)
		for v in self.vertices.values():
			P.addVertex(v)
		P.lattice= [dict(d) for d in self.lattice]
		return P

	def body(self):
		''' Return the simplicial chain '''
		[(v,B)]=self.lattice[self.dim].items()
		return (v,B)

	def vec(self,vId):
		''' Return the position of the vertice named vId '''
		return self.vertices[vId]

	def volumeX(self,loc):
		def tessel(path, level, vertices, face ):
			v0=choose(vertices)
			if (len(vertices)==level+1):
				allV= vertices.difference({v0}).union(path)
				d=len(allV)
				verts=[ self.vec(v)-self.vec(v0) for v in allV ]
				m=Matrix( [v.T for v in verts] )
				svol=m.berkowitz_det()/ fact(d)
				sign = svol.subs(X,loc)
				sign=sign/abs(sign)
				return sign*svol
			else:
				sublatt=self.lattice[level-1]
				sfaces= [ (s,sublatt[s]) for s in face.childs if v0 not in s]
				npath=path.union({v0})
				vol=0
				for (s,f) in sfaces:
					vol+=tessel(npath, level -1,s, f)
				return vol
		(v,B)=self.body()
		return tessel(frozenset({}),self.dim, v,B)

	def intersection( self, H):
		I=fullPolytope(self.dim-1) # Start with an empty polytope
		edges= self.lattice[1] # consider the edges at level 1
		collision={} # there was no collision until now
		for (s,f) in edges.items():
			vw= [ v for v  in s] # vw is the list of vertices of the face f
			v,w = self.vec(vw[0]),  self.vec(vw[1])  # [v,w] is an edge of the polytope self
			if ( (v in H) and (w not in H ))  or ( ( w in H) and (v not in H) ) : # if v and w are on opposite side of H
					n= H.intersection(v,w) # n is the intersection point of H and [v,w]
					key=I.addVertex(n) # We have found a vertex of I
					collision[s]= frozenset({key}) # There was also obviously a collision between the edge and H
		# The lattice of I at the vertice level is the set of vertices we have found
		nlattice={ s:Face() for s in collision.values() }
		I.lattice.append(nlattice)
		for level in self.lattice[2:]: # We construct iteratively the next lattice levels
			sublattice={}
			ncollision={}
			for (s,f) in level.items(): #Each face of Self at level d may generate a face of I at level d-1
				nf=Face()
				verts=frozenset({})
				for subfaces in f.childs:
				# We look if one of the subface of f intersected with H at the previous level
					if subfaces in collision.keys():
						# If that is the case, f also intersects with H.
						# The intersected face contains the intersected subface
						colSubF= collision[subfaces]
						nf.childs.append(colSubF)
						# We collect the set of the vertices of the new face nf
						verts=verts.union(colSubF)
				if len(verts) > 0 : # If the new face contains at least one vertice (and thus at least d)
					ncollision[s]=verts # Then the intersetion between H and f is non-empty
					sublattice[verts]=nf # And nf is a face of lattice at the current level.
			I.lattice.append(sublattice) # we add the new lattice level
			collision=ncollision # and move to the new set of collision
		I.repairParents() # Until now we have neglected to add back the link between child and parents.
		return I

	def repairParents(self):
		for (levelC,levelP) in zip(self.lattice[:-1], self.lattice[1:]):
			for (s,f) in levelP.items():
				for cs in f.childs:
					levelC[cs].parents.append(s)

def simplex(vertices):
	P=fullPolytope(len(vertices) - 1 )
	for v in vertices:
		P.addVertex(v)
	P.lattice=[]
	P.lattice.append({ frozenset([i]): Face() for i in P.vertices.keys()  })
	for ldim in range(1,P.dim+1):
		cLevel={}
		for vertex in P.vertices.keys():
			for (fvertices, face ) in P.lattice[ldim-1].items():
				if not(vertex in fvertices):
					nvertices=fvertices.union([vertex])
					face.parents.append(nvertices)
					if nvertices in cLevel:
						cLevel[nvertices].childs.append(fvertices)
					else:
						F=Face()
						F.childs=[fvertices]
						F.parents=[]
						cLevel[nvertices]=F
		P.lattice.append(cLevel)
	return P

def miror(s,t):
	s2=set({})
	for x in s:
		s2.add(x+t)
	return frozenset(s2)

def mirorFace(s,f,t):
	s2=miror(s,t)
	F2= Face ()
	F2.childs= [ miror(s,t) for s in f.childs  ]
	F2.parents= [ miror(s,t) for s in f.parents  ]
	return (s2,F2)

def lift(s,t):
	return s.union(miror(s,t))

def liftFace(s,f,t):
	s2=lift(s,t)
	f2=Face()
	f2.parents= [ lift(s,t) for s in f.parents ]
	f2.childs= [ lift(s,t) for s in f.childs ]
	f2.childs.append(s)
	f2.childs.append(miror(s,t))
	return(s2,f2)

def Point(z):
	P=fullPolytope(0)
	P.addVertex(z)
	level0= { frozenset({0}) : Face() }
	P.lattice.append(level0)
	P.dim=0
	return P

def rCube(d ,base , dext):
	if d==0:
		z=zero(dext)
		return Point(z)
	else:

		Cr=rCube(d-1,base,dext)
		C=Cr.copy()
		vt=base(d-1)
		t=2**(d-1)
		for v in Cr.vertices.values():
			C.addVertex(vt+v)
		for (level,levelN) in  zip(Cr.lattice,C.lattice):
			for (s,f) in level.items():
				(s2,f2)= mirorFace(s,f,t)
				levelN[s2]=f2
		C.lattice.append({})
		for (levelD,levelU) in zip(Cr.lattice,C.lattice[1:]):
			for (s,f) in levelD.items():
				(s2,f2)=liftFace(s,f,t)
				levelU[s2]=f2
		C.dim=d
	return C

def Cube(d):
	return rCube(d,canon(d),d)

def SimplexRect(d):
	z=zero(d)
	base=canon(d)
	l= [base(i) for i in range(d) ]
	l.append(z)
	return simplex( l  )

def SimplexStd(d):
	base=canon(d+1)
	l= [base(i) for i in range(d+1) ]
	return simplex( l  )

def VolIntersectionSimplex( normal, offset ):
	d= len(normal)
#	print("Dimension: {}".format(d))
	base=canon(d)
	verts=[base(i) for i in range(0,d)]
	verts.append(zero(d))
	S=simplex(verts)
#	print("Normal: {}, vertices : {}".format(normal, verts ) )
	inters = sorted( set( [ normal.dot(v)-offset for v in verts ]) )
	locs = [ (v + w)/2 for (v,w) in zip(inters[1:],inters) ]
	def volumeLoc(loc):
		H = LocalHyperplane ( normal, X + offset, loc+offset)
		HnS= S.intersection(H)
#		print(HnS)
		V= sym.simplify( HnS.volumeX(loc) )
		return V
	vols = [sym.Rational(0)]
	vols.extend( [volumeLoc(loc) for loc in locs])
	vols.append(0)
	bpP = byPieces (inters, vols )
	bpP.normalize()
	return bpP


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

from xlwt import Workbook,easyxf

start_pos = 9   # НЕ ставити менше 3! Установка початкової комірки

day_style = easyxf(
	'font: bold on;'
	'align: vertical center, horizontal center, rotation 90;'
	'borders: left 2, right 2, top 2, bottom 2;'
	)

pair_style = easyxf(
	'font: bold on;'
	'align: vertical center, horizontal center;'
	'borders: left 2, right 2, top 2, bottom 2;'
	)

sybject_style1 = easyxf(
	'font: height 220;'
	'align: horizontal center;'
	'borders: left 1, right 1, top 1;'
	)

sybject_style2 = easyxf(
	'font: height 220;'
	'align: vertical top, horizontal center;'
	'borders: left 1, right 1, bottom 1;'
	)

groups_style = easyxf(
	'font: bold on;'
	'align: vertical center, horizontal center;'
	'borders: left 2, right 2, top 2, bottom 2;'
	)

group_pair_style = easyxf(
	'font: height 160;'
	'borders: left 1, right 1, top 1, bottom 1;'
	)

def SetDays():					#Фунція установки розмітки днів і пар
	st_pos_days = start_pos
	st_pos_pairs = start_pos
	days = [u'Понеділок', u'Вівторок', u'Середа', u'Четвер', u'Пятниця']
	pairs = [u'I', u'II', u'III', u'IV', u'V', u'VI']
	ws.col(0).width = 0x470
	ws.col(1).width = 0x470
	for day in range(5):
		ws.write_merge(st_pos_days, st_pos_days+23, 0, 0, days[day], day_style)
		for pair in range(6):
			ws.write_merge(st_pos_pairs, st_pos_pairs+3, 1, 1, pairs[pair], pair_style)
			st_pos_pairs += 4
		st_pos_days += 24

def SetGroups(groups):			#Функція установки розмітки груп
	st_pos_row = start_pos
	st_pos_col = 2
	ws.write(st_pos_row-2, 1, u'групи', group_pair_style)
	ws.write(st_pos_row-1, 1, u'пари', group_pair_style)
	for group in range(len(groups)):
		ws.write_merge(st_pos_row-2, st_pos_row-1, st_pos_col, st_pos_col, unicode(groups[group]), groups_style)
		ws.col(st_pos_col).width = 0x1950
		st_pos_col += 1

def SetSubject(day, pair, group, pairtype, sybject, audience):		#Фуккція запису предмету в розклад
	st_pos = start_pos
	start_day_pos = st_pos + day*24
	start_pair_pos = pair*4
	start_subj_pos = 0

	start_subj_pos = 0 if pairtype == (1 or 3) else 2

	if pairtype == 1 or pairtype == 2:
		ws.write(start_day_pos+start_pair_pos+start_subj_pos, group, sybject, sybject_style1)
		ws.write(start_day_pos+start_pair_pos+start_subj_pos+1, group, audience, sybject_style2)
	elif pairtype == 3:
		ws.write_merge(start_day_pos+start_pair_pos, start_day_pos+start_pair_pos+1, group, group, sybject, sybject_style1)
		ws.write_merge(start_day_pos+start_pair_pos+2, start_day_pos+start_pair_pos+3, group, group, audience, sybject_style2)


def linear_search(array: list, query: int or float) -> int:
    """Linear Search Algorithm
    In computer science, a linear search or sequential search is a method for finding an element within a list. It sequentially checks each
    element of the list until a match is found or the whole list has been searched
    In this algorithm if the value is found then it returns index of the target as a value and if not found returns -1.
    Time Taken in worse case : O(n)
    Space Taken in worse case : O(n)
    """

    try:
        return array.index(query)
    except ValueError:
        return -1


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('polls', '0003_auto_20160202_1530'),
    ]

    operations = [
        migrations.AddField(
            model_name='pollresultspluginmodel',
            name='ordering',
            field=models.CharField(default='pk', max_length=8, choices=[('natural', 'pk'), ('descending', '-votes'), ('ascending', 'votes')]),
        ),
    ]


import discord
import json
import os
import requests
from discord.ext import tasks
from datetime import datetime
from stayonline import keep_alive

data = open('bdays.json')
check = (json.load(data))

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Logged in as {0.user}', format(client))
    send_message.start()

#date and loop part start here:
@tasks.loop(hours=3)
async def send_message():
    now = datetime.now()
    tdate = now.strftime("%d-%m")

    for i in range(0, 30):
        if check[i]['Bday'] == tdate:
            channel = client.get_channel(1014507327497437267)
            await channel.send(
                f"@everyone Its {check[i]['Name']} ,{check[i]['Roll']}'s Birthday"
            )

#chat part start here:
@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.author != client.user:
        if str(message.content) == "hello":
            print(str(message))
            await message.channel.send("works")
            return
        if str(message.content) == "/json":
          await message.channel.send(check)
          return
        if str(message.content) == "/joke" or "tell me a joke":
          req = requests.get("https://v2.jokeapi.dev/joke/Programming")
          joke = req.json()
          if joke['type'] == 'twopart':
            await message.channel.send(joke['setup'])
            await message.channel.send(joke['delivery'])
          else:
            await message.channel.send(joke['joke'])
keep_alive()
token = os.environ.get('code')
client.run(token)


from os import linesep
from pickle import NONE
from matplotlib import lines
from matplotlib.pyplot import errorbar, fignum_exists
import numpy as np
from numpy.core.numeric import indices
import torch
import scipy.spatial
import random, logging, time

#from qpsolvers import solve_qp
from numpy import linalg as LA
from scipy.linalg import qr
from torch import t

start_learning_rate = 1.0

def quad_solver(Q, b):
    """
    Solve min_a  0.5*aQa + b^T a s.t. a>=0
    """
    K = Q.shape[0]
    alpha = np.zeros((K,))
    g = b
    Qdiag = np.diag(Q)
    for i in range(20000):
        delta = np.maximum(alpha - g/Qdiag,0) - alpha
        idx = np.argmax(abs(delta))
        val = delta[idx]
        if abs(val) < 1e-7:
            break
        g = g + val*Q[:,idx]
        alpha[idx] += val
    return alpha

def sign(y):
    """
    y -- numpy array of shape (m,)
    Returns an element-wise indication of the sign of a number.
    The sign function returns -1 if y < 0, 1 if x >= 0. nan is returned for nan inputs.
    """
    y_sign = np.sign(y)
    y_sign[y_sign==0] = 1
    return y_sign

class OPT_attack_sign_SGD_lf(object):
    def __init__(self, model, k=200, train_dataset=None):
        self.model = model
        self.k = k
        self.train_dataset = train_dataset

    def attack_untargeted(self, x0, y0, alpha = 0.2, beta = 0.001, iterations = 1000, query_limit=80000,
                          distortion=None, stopping=1e-8):
        """ Attack the original image and return adversarial example
            model: (pytorch model)
            train_dataset: set of training data
            (x0, y0): original image
        """
        model = self.model
        y0 = y0[0]
        query_count = 0
        ls_total = 0

        if (model.predict_label(x0) != y0):
            logging.info("Fail to classify the image. No need to attack.")
            return x0, 0, True, 0, None

        #### init theta by Gaussian: Calculate a good starting point.
        num_directions = 100
        best_theta, g_theta = None, float('inf')
        init_thetas, init_g_thetas = [], []

        for i in range(num_directions):
            query_count += 1
            theta = np.random.randn(*x0.shape)

            if model.predict_label(x0+torch.tensor(theta, dtype=torch.float).cuda()) != y0:
                initial_lbd = LA.norm(theta.flatten(), np.inf)
                theta /= initial_lbd

                lbd, count = self.fine_grained_binary_search(model, x0, y0, theta, initial_lbd, g_theta)
                query_count += count

                if lbd < g_theta:
                    best_theta, g_theta = theta, lbd
                    init_thetas.append(best_theta)
                    init_g_thetas.append(g_theta)

        logging.info("Best initial distortion: {:.3f}".format(g_theta))

        ## fail if cannot find a adv direction within 200 Gaussian
        if g_theta == float('inf'):
            logging.info("Couldn't find valid initial, failed")
            return x0, 0, False, query_count, None

        for g_theta, best_theta in zip(init_g_thetas, init_thetas): # successful attack upon initialization
            if distortion is None or g_theta < distortion:
                x_adv = x0 + torch.tensor(g_theta*best_theta, dtype=torch.float).cuda()
                target = model.predict_label(x_adv)
                logging.info("\nSucceed: distortion {:.4f} target"
                    " {:d} queries {:d} LS queries {:d}".format(g_theta, target, query_count, 0))
                return x0 + torch.tensor(x_adv, dtype=torch.float).cuda(), g_theta, True, query_count, best_theta

        #### begin attack
        init_thetas = list(reversed(init_thetas))
        init_g_thetas = list(reversed(init_g_thetas))
        query_count_init = query_count
        ls_total_init = ls_total
        alpha_init = alpha
        beta_init = beta
        for init_id in range(1):
            best_theta = init_thetas[init_id]
            g_theta = init_g_thetas[init_id]
            ls_total = ls_total_init
            query_count = query_count_init
            alpha = alpha_init
            beta  = beta_init

            #### Begin Gradient Descent.
            xg, gg = best_theta, g_theta
            distortions = [gg]
            for i in range(iterations):
                sign_gradient, grad_queries = self.sign_grad_v1(x0, y0, xg, initial_lbd=gg, h=beta)

                ## Line search of the step size of gradient descent)
                min_theta, min_g2, alpha, ls_count = self.line_search(model, x0, y0, gg, xg, alpha, sign_gradient, beta)

                if alpha < 1e-6:
                    alpha = 1.0
                    logging.info("Warning: not moving, beta is {0}".format(beta))
                    beta = beta * 0.1
                    if (beta < 1e-8):
                        break

                xg, g2 = min_theta, min_g2
                gg = g2

                query_count += (grad_queries + ls_count)
                ls_total += ls_count
                distortions.append(gg)

                if query_count > query_limit:
                    break

                if i % 5 == 0:
                    logging.info("Iteration {:3d} distortion {:.6f} num_queries {:d}".format(i+1, gg, query_count))

                if distortion is not None and gg < distortion:
                    logging.info("Success: required distortion reached")
                    break

            ## check if successful
            if distortion is None or gg < distortion:
                target = model.predict_label(x0 + torch.tensor(gg*xg, dtype=torch.float).cuda())
                logging.info('Succeed at init {}'.format(init_id))
                logging.info("Succeed distortion {:.4f} target"
                             " {:d} queries {:d} LS queries {:d}\n".format(gg, target, query_count, ls_total))
                return x0 + torch.tensor(gg*xg, dtype=torch.float).cuda(), gg, True, query_count, xg

        return x0, 0, False, query_count, xg

    def line_search(self, model, x0, y0, gg, xg, alpha, sign_gradient, beta):
        ls_count = 0
        min_theta = xg
        min_g2 = gg
        for _ in range(15):
            new_theta = xg - alpha * sign_gradient
            new_theta /= LA.norm(new_theta.flatten(), np.inf)
            new_g2, count = self.fine_grained_binary_search_local(model, x0, y0, new_theta, initial_lbd = min_g2, tol=beta/500)
            ls_count += count
            alpha = alpha * 2
            if new_g2 < min_g2:
                min_theta = new_theta
                min_g2 = new_g2
            else:
                break

        if min_g2 >= gg:
            for _ in range(15):
                alpha = alpha * 0.25
                new_theta = xg - alpha * sign_gradient
                new_theta /= LA.norm(new_theta.flatten(), np.inf)
                new_g2, count = self.fine_grained_binary_search_local(
                    model, x0, y0, new_theta, initial_lbd = min_g2, tol=beta/500)
                ls_count += count
                if new_g2 < gg:
                    min_theta = new_theta
                    min_g2 = new_g2
                    break
        return min_theta, min_g2, alpha, ls_count

    def sign_grad_v1(self, x0, y0, theta, initial_lbd, h=0.001, lr=5.0, D=4, target=None,
                     sample_type='gaussian'):
        """
        Evaluate the sign of gradient by formulat
        sign(g) = 1/Q [ \sum_{q=1}^Q sign( g(theta+h*u_i) - g(theta) )u_i$ ]
        """
        K = self.k
        sign_grad = np.zeros(theta.shape)
        queries = 0

        for iii in range(K):
            if sample_type == 'gaussian':
                u = np.random.randn(*theta.shape)
            else:
                logging.info('ERROR: UNSUPPORTED SAMPLE_TYPE: {}'.format(sample_type)); exit(1)
            u /= LA.norm(u.flatten(), np.inf)

            new_theta = theta + h*u;
            new_theta /= LA.norm(new_theta.flatten(), np.inf)
            sign = 1

            # Targeted case.
            if (target is not None and
                self.model.predict_label(x0+torch.tensor(initial_lbd*new_theta, dtype=torch.float).cuda()) == target):
                sign = -1

            # Untargeted case
            if (target is None and
                self.model.predict_label(x0+torch.tensor(initial_lbd*new_theta, dtype=torch.float).cuda()) != y0): # success
                sign = -1
            queries += 1
            sign_grad += u*sign
        sign_grad /= K

        return sign_grad, queries

    ##########################################################################################

    def fine_grained_binary_search_local(self, model, x0, y0, theta, initial_lbd = 1.0, lin_search_ratio=0.01, tol=1e-5):
        nquery = 0
        lbd = initial_lbd
        tol = max(tol, 2e-9)
        if model.predict_label(x0+torch.tensor(lbd*theta, dtype=torch.float).cuda()) == y0:
            lbd_lo = lbd
            lbd_hi = lbd*(1 + lin_search_ratio)
            nquery += 1
            while model.predict_label(x0+torch.tensor(lbd_hi*theta, dtype=torch.float).cuda()) == y0:
                lbd_hi = lbd_hi*(1 + lin_search_ratio)
                nquery += 1
                if lbd_hi > 20:
                    return float('inf'), nquery
        else:
            lbd_hi = lbd
            lbd_lo = lbd*(1 - lin_search_ratio)
            nquery += 1
            while model.predict_label(x0+torch.tensor(lbd_lo*theta, dtype=torch.float).cuda()) != y0 :
                lbd_lo = lbd_lo*(1 - lin_search_ratio)
                nquery += 1

        while (lbd_hi - lbd_lo) > tol:
            lbd_mid = (lbd_lo + lbd_hi)/2.0
            nquery += 1
            if model.predict_label(x0 + torch.tensor(lbd_mid*theta, dtype=torch.float).cuda()) != y0:
                lbd_hi = lbd_mid
            else:
                lbd_lo = lbd_mid
        return lbd_hi, nquery

    def fine_grained_binary_search_local(self, model, x0, y0, theta, initial_lbd = 1.0, lin_search_ratio=0.01, tol=1e-5):
        nquery = 0
        lbd = initial_lbd
        tol = max(tol, 2e-9)
        if model.predict_label(x0+torch.tensor(lbd*theta, dtype=torch.float).cuda()) == y0:
            lbd_lo = lbd
            lbd_hi = lbd*(1 + lin_search_ratio)
            nquery += 1
            while model.predict_label(x0+torch.tensor(lbd_hi*theta, dtype=torch.float).cuda()) == y0:
                lbd_hi = lbd_hi*(1 + lin_search_ratio)
                nquery += 1
                if lbd_hi > 20:
                    return float('inf'), nquery
        else:
            lbd_hi = lbd
            lbd_lo = lbd*(1 - lin_search_ratio)
            nquery += 1
            while model.predict_label(x0+torch.tensor(lbd_lo*theta, dtype=torch.float).cuda()) != y0 :
                lbd_lo = lbd_lo*(1 - lin_search_ratio)
                nquery += 1

        while (lbd_hi - lbd_lo) > tol:
            lbd_mid = (lbd_lo + lbd_hi)/2.0
            nquery += 1
            if model.predict_label(x0 + torch.tensor(lbd_mid*theta, dtype=torch.float).cuda()) != y0:
                lbd_hi = lbd_mid
            else:
                lbd_lo = lbd_mid
        return lbd_hi, nquery

    def fine_grained_binary_search(self, model, x0, y0, theta, initial_lbd, current_best, tol=1e-5):
        nquery = 0
        if initial_lbd > current_best:
            if model.predict_label(x0+torch.tensor(current_best*theta, dtype=torch.float).cuda()) == y0:
                nquery += 1
                return float('inf'), nquery
            lbd = current_best
        else:
            lbd = initial_lbd

        lbd_hi = lbd
        lbd_lo = 0.0
        while (lbd_hi - lbd_lo) > tol:
            lbd_mid = (lbd_lo + lbd_hi)/2.0
            nquery += 1
            if model.predict_label(x0 + torch.tensor(lbd_mid*theta, dtype=torch.float).cuda()) != y0:
                lbd_hi = lbd_mid
            else:
                lbd_lo = lbd_mid
        return lbd_hi, nquery

    def __call__(self, input_xi, label_or_target, targeted=False, distortion=None,
                 stopping=1e-8, query_limit=80000, args=None):
        self.args = args

        if targeted:
            raise NotImplementedError
            # adv = self.attack_targeted(input_xi, label_or_target, targeted, distortion=distortion,
            #                            svm=svm, stopping=stopping, query_limit=query_limit)
        else:
            adv = self.attack_untargeted(input_xi, label_or_target, distortion=distortion,
                                         stopping=stopping, query_limit=query_limit)
        return adv


M1 = [2,4]
M2 = [3,5]
def repeatByList(a,b):
    M3 = []
    for i in range (len(M1)):
        e =[M1[i]]*M2[i]
        M3.append(e)
    print(M3)
repeatByList(M1,M2)


# PROGRAMMER: Steve M
# DATE CREATED: 31.07.20
# REVISED DATE:
# PURPOSE: Utility functions to load data and process images

# Import necessary libraries
import torchvision.models as models

## Get model
def get_model(arch):
    if arch == 'vgg19': #setting model based on vgg19
        model = models.vgg19(pretrained=True)
    elif arch == 'alexnet': #setting model based on alexnet
        model = models.alexnet(pretrained = True)
    return model

########

6. Neural Networks/2. Image Classifier Part 2/1. Work In Progress/util_get_model.py