from django.http import HttpResponse
from django.shortcuts import redirect, render

from .forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from config.settings import RECIPIENTS_EMAIL, DEFAULT_FROM_EMAIL

# Create your views here.

def contact_view(request):
    if request.method == "GET":
        form = ContactForm()
    elif request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            full_name = form.cleaned_data['full_name']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(f'{full_name} от {from_email}',
                          message,
                          DEFAULT_FROM_EMAIL,
                          [DEFAULT_FROM_EMAIL],
                          RECIPIENTS_EMAIL)
            except BadHeaderError:
                return HttpResponse('Ошибка в теме письма.')
            return redirect('success')
    else:
        return HttpResponse('Неверный запрос.')
    return render(request, "email/contact.html", {'form': form})

def success_view(request):
    return render(request, "email/consuc.html")


import argparse
import os
import cv2
from wand.image import Image
import numpy as np

#ArgumentParser객체:명령행을 파이썬 데이터형으로 파싱하는데 필요한 모든 정보가 들어있음
#ArgumentParser객체 생성
ap=argparse.ArgumentParser()
ap.add_argument("-i","--images",required=True, help="absolute path to the input image")
ap.add_argument("-c","--cascade",default="C:/Users/cat7892/Documents/GitHub/catholic/catface_detection/haarcascade_frontalcatface.xml",help="absolute path to detector haar cascade")
#parse_args():문자열을 객체로 변환 후 namespace의 attribute로 설정
args=vars(ap.parse_args())
count=0

#imagefolder->only heic, jpg type images
imagefolder=args['images'].replace('\\','/')
for image in os.listdir(args["images"]):
    print(image)
    #If the image file format is 'heic', it is converted to 'jpg'.
    if image[-3:]!='jpg':
        img=Image(filename=imagefolder+'/'+image)
        img.format='jpg'
        image=image.replace('heic', 'jpg')
        img.save(filename=imagefolder+'/'+image)
        img.close()
        os.remove(imagefolder+'/'+image.replace('jpg','heic'))
'''
    # load image+convert grayscale
    color=cv2.imread(imagefolder+'/'+image)
    gray=cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)
    #load detector, then detect
    detector=cv2.CascadeClassifier(args["cascade"])
    rects=detector.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=10)

    #loop over detect and save file
    for (i, (x,y,w,h)) in enumerate(rects):
        roi=color[y:y+h,x:x+w].copy()
        print(x,y,w,h)
        cv2.imwrite('C:/Users/cat7892/Documents/GitHub/catholic/catface_detection/test_detect/'+str(count)+'.jpg',roi)
        cv2.waitKey()
        count+=1
'''


import os
import json
import pandas as pd
import numpy as np
import networkx as nx

#所有节点和边构成网络图
def form_graph(parent_path):
    every_pro_path = os.path.join(parent_path, r'dataset\secondExperiments\COVID_Node2Vec.csv')
    simGO_path = os.path.join(parent_path, r'dataset\secondExperiments\train_COVID_AllHuman_GoSim.xls')

    # 网络图的构建
    G = nx.Graph()
    pro_file = pd.read_csv(every_pro_path)
    pro = np.array(pro_file["name"])
    proList = []  # 每个蛋白质的索引
    for i in range(len(pro)):
        proList.append(pro[i])
        G.add_node(i)

    edges_df = pd.read_excel(simGO_path)
    source = np.array(edges_df["protein"])
    target = np.array(edges_df["neghbor_protein"])
    sim = np.array(edges_df["sim"])
    edgesList = []
    for j in range(len(source)):
        edgesList.append((source[j].split("_")[1], target[j].split("_")[1]))
        G.add_edge(int(source[j].split("_")[0]), int(target[j].split("_")[0]))
        G[int(source[j].split("_")[0])][int(target[j].split("_")[0])]['weight'] = sim[j]
    print("图形已构成")
    return G

#通过所有核数据
def readresultjson(parent_path, graph):
    result_corefile = os.path.join(parent_path, r'result\secondExperiments\train_COVID_result.json')
    with open(result_corefile, 'r', encoding='utf8')as fp:
        json_data = json.load(fp)

    seed = []
    for core_k, core_v in json_data.items():
        core = core_v[0]["cover"]
        seed.extend(core)
    seed = list(set(seed))
    return json_data,seed

#通过核获得一阶邻点
def getfirstneighbor(json_data,seed,graph):
    adj = graph._adj
    neighbordict = {}
    for k,v in json_data.items():
        allneighborNode = []
        neighborNode = []
        core = v[0]["cover"]
        for i in core:
            everyneigh = adj[int(i)].keys()
            neighborNode.extend(everyneigh)
        neighborNode = list(set(neighborNode))
        for i in neighborNode:
            if i not in seed:
                allneighborNode.append(i)
        neighbordict[k] = neighborNode
    return adj,neighbordict

#适应度函数
def fitness_function(adj,complex, core,graph):
    sum_degree_in = 0  # 所有顶点的入度之和
    sum_degree_out = 0  # 所有顶点的出度之和
    E = 0
    for i in range(len(complex)):
        degree_in = 0  # 每个节点的入度
        degree_out = 0  # 每个节点的出度
        i_adj = adj[complex[i]].keys()
        for z in i_adj:
            if z in complex:
                if (complex[i], int(z)) in graph.edges():
                    degree_in += graph[complex[i]][int(z)]['weight']
                else:
                    degree_in += graph[int(z)][complex[i]]['weight']
            else:
                if (complex[i], int(z)) in graph.edges():
                    degree_out += graph[complex[i]][int(z)]['weight']
                else:
                    degree_out += graph[int(z)][complex[i]]['weight']
        for j in range(len(complex)):
            if i < j:
                if (complex[i], complex[j]) in graph.edges() or (
                complex[j], complex[i]) in graph.edges():
                    E += 1
        sum_degree_in += degree_in
        sum_degree_out += degree_out
    a = 0.8
    modularity = (sum_degree_in - sum_degree_out) / (sum_degree_out + sum_degree_in)
    density = (2 * E) / (len(complex) * (len(complex) - 1))
    score = a*density+(1-a)*modularity
    return score

#通过分数形成核心-附件的形式
def core_accessories(json_data,neighbordict,adj,graph):
    resultDict = {}
    for k, v in json_data.items():
        complexjson = {}
        resultList = []
        core = [int(i) for i in v[0]["cover"]]
        complex = core+neighbordict[k]
        #求每个一阶邻点与core总的功能相似性
        score_neighbordict = {}
        for j in neighbordict[k]:
            score = 0
            for z in core:
                if (int(z), int(j)) in graph.edges():
                    score += graph[int(z)][int(j)]['weight']
                elif (int(j), int(z)) in graph.edges():
                    score += graph[int(j)][int(z)]['weight']
                else:
                    score += 0
            score_neighbordict[j] = score
        score_neighbordict = sorted(score_neighbordict.items(), key=lambda item: item[1])

        if len(complex) > 3:
            core_score = fitness_function(adj, complex, core, graph)
            for i in score_neighbordict:
                # for i in neighbordict[k]:
                if len(complex) > 3:
                    complex.remove(i[0])
                    complex_score = fitness_function(adj, complex, core, graph)
                    if complex_score >= core_score:
                        core_score = complex_score
                    else:
                        complex.append(i[0])
                else:
                    break

        elif len(complex) == 3:
            core_score = fitness_function(adj, complex, core, graph)
        else:
            # continue
            core_score = 0

        # if len(core) > 1:
        #     core_score = fitness_function(adj,core)
        # else:
        #     core_score = 0
        # complex = core
        # for i in neighbordict[k]:
        #     complex.append(i)
        #     complex_score = fitness_function(adj, complex)
        #     if complex_score >= core_score:
        #         core_score = complex_score
        #     else:
        #         complex.remove(i)
        complexjson["cover"] = complex
        complexjson["score"] = core_score
        resultList.append(complexjson)
        resultDict[k] = resultList
    return resultDict

def savecomplex(parent_path,complexjson):
    result_path = parent_path + r'\result\secondExperiments\train_COVID_resultComplex.json'
    with open(result_path, 'w') as fw:
        json.dump(complexjson, fw)

if __name__ == '__main__':
    ROOT_DIR = os.path.dirname(os.path.abspath('__file__'))
    parent_path = os.path.dirname(ROOT_DIR)
    graph = form_graph(parent_path)
    json_data,seed = readresultjson(parent_path, graph)
    adj,neighbordict = getfirstneighbor(json_data,seed,graph)
    complexjson = core_accessories(json_data,neighbordict,adj,graph)
    print(complexjson.__len__())
    savecomplex(parent_path,complexjson)


import pytest
import os
import shutil
import tngsdk.project.workspace as workspace
from tngsdk.project.workspace import Workspace
from tngsdk.project.project import Project

class TestProjectUnit:

    # create and return a temporary workspace 'test-ws'
    @pytest.fixture(scope='module')
    def workspace(self):
        # start clean without workspace
        if os.path.isdir('test-ws'):
            shutil.rmtree('test-ws')

        args = workspace.parse_args_workspace([
            '-w', 'test-ws',
            '--debug'
        ])
        workspace.init_workspace(args)
        assert os.path.isdir('test-ws')
        yield 'test-ws'
        shutil.rmtree('test-ws')

    # test descriptors of project 'example-project'
    def test_example_project_descriptors(self, workspace):
        ws = Workspace.load_workspace(workspace)
        example_project = Project.load_project('example-project', workspace=ws)
        example_project.status()

        vnfds = example_project.get_vnfds()
        assert vnfds == ['tango_vnfd0.yml']

        nsds = example_project.get_nsds()
        assert nsds == ['tango_nsd.yml']


# -*- coding: utf-8 -*-

import math
import numpy as np
from scipy.interpolate import interp1d

class SpatialParameters:

    def __init__(self, signal, fs, window_size, running_step):

        self.time_steps, self.iacc, self.tiacc, self.wiacc = self.__get_xcorr_descriptors(
            signal, fs, window_size, running_step)

    def __get_xcorr_descriptors(self, signal, fs, window_size, running_step):
        w_samples = round(window_size * fs)
        rs_samples = round(running_step * fs)

        time_steps = np.array([])

        iacc = np.array([])
        tiacc = np.array([])
        wiacc = np.array([])
        wiacc_d = np.array([])
        wiacc_u = np.array([])

        max_delay = 1 # (ms)
        dT = math.floor(max_delay * 0.001 * fs)
        t_axis_length = (2*dT) + 1
        T_AXIS = np.linspace(-max_delay, max_delay, t_axis_length)
        delta = t_axis_length//2

        iD = 0
        iU = w_samples
        lim = math.ceil(t_axis_length/2)-1

        while iU < len(signal):

            c = 0
            idx = 0
            max_value = 0

            ts = np.round(iD / fs, 2)

            time_steps = np.append(time_steps,ts)

            cll0 = np.correlate(signal[iD:iU,0], signal[iD:iU,0])
            crr0 = np.correlate(signal[iD:iU,1], signal[iD:iU,1])

            if((cll0 == 0) or (crr0 == 0)):
                iacc = np.append(iacc, 0)
                wiacc = np.append(wiacc, 0)
                wiacc_d = np.append(wiacc_d, 0)
                wiacc_u = np.append(wiacc_u, 0)

                if((cll0 == 0) and (crr0 != 0)):
                    tiacc = np.append(tiacc, 1)
                if((cll0 != 0) and (crr0 == 0)):
                    tiacc = np.append(tiacc, -1)
                else:
                    tiacc = np.append(tiacc, 0)

            scale = math.sqrt(cll0*crr0)

            iacf = np.zeros([(2*delta)+1])

            for tau in range(2*delta, -1, -1):

                L = [0]
                R = [0]
                if(c < lim):
                    L = signal[iD+delta-c:iU, 0]
                    R = signal[iD:iU-delta+c, 1]
                elif(c == lim):
                    L = signal[iD:iU, 0]
                    R = signal[iD:iU, 1]
                else:
                    L = signal[iD:iU-c+delta, 0]
                    R = signal[iD+c-delta:iU, 1]

                xcorr = np.correlate(L, R) / scale

                #iacf[tau, step] = xcorr
                c += 1

                if(xcorr > max_value):
                    max_value = xcorr
                    idx = tau

            iacc = np.append(iacc, max_value)
            tiacc_window = T_AXIS[idx]
            tiacc = np.append(tiacc, tiacc_window)

            alpha = 0.9*max_value

            idx_minus = np.linspace(idx, 0, idx+1)
            idx_plus = np.linspace(idx, t_axis_length-1, t_axis_length-idx)

            t_minus = -1;
            t_plus = 1;
            i_m = 0
            i_p = 0

            m_found = False

            if(len(idx_minus) > 1):
                for i in idx_minus:
                    if(iacf[int(i)] < alpha):
                        i_m = int(i)
                        if(idx-i > 0):
                            m_found = True
                            x_m = iacf[i_m:idx+1]
                            y_m = T_AXIS[i_m:idx+1]
                            t_f = interp1d(x_m, y_m, kind='linear')
                            t_minus = t_f(alpha)
                        break

            p_found = False
            if(len(idx_plus) > 1):
                for i in idx_plus:
                    if(iacf[int(i)] < alpha):
                        i_p = int(i)
                        if(i-idx > 0):
                            p_found = True
                            x_p = iacf[idx:i_p+1]
                            y_p = T_AXIS[idx:i_p+1]
                            t_f = interp1d(x_p, y_p, kind='linear')
                            t_plus = t_f(alpha)
                        break

            wiacc_d = np.append(wiacc_d, t_minus)
            wiacc_u = np.append(wiacc_u, t_plus)
            if(not(m_found)):
                wiacc = np.append(wiacc, (t_plus - tiacc_window) * 2)
            elif(not(p_found)):
                wiacc = np.append(wiacc, (tiacc_window - t_minus) * 2)
            else:
                wiacc = np.append(wiacc, (t_plus - t_minus))

            iD += rs_samples
            iU += rs_samples

        return time_steps, iacc, tiacc, wiacc


import sys
sys.stdin = open('input.txt', 'r')

def check(L, i):
    c = 0
    cnt = 0
    for j in range(N):
        if L[i][j]:
            cnt += 1
        if not L[i][j] or j == N-1:
            if cnt == K:
                c += 1
            cnt = 0
    return c

for t in range(1, int(input())+1):
    N, K = map(int, input().split())
    box = [list(map(int, input().split())) for _ in range(N)]
    box_rev = list(zip(*box))
    total = 0
    for i in range(N):
        total += check(box, i)
        total += check(box_rev, i)

    print('#{} {}'.format(t, total))


import pygame
import sys
from random import randint

display = True

class snakeGame:

    snake = [(16, 16),(16,15)]
    apple = (18, 18)
    is_dead = False
    is_left = False
    is_right = False

    def move_left(self):
        self.is_left = True
        self.move_forward()
        self.is_left = False
        self.is_right = False

    def move_right(self):
        self.is_right = True
        self.move_forward()
        self.is_left = False
        self.is_right = False

    def move_forward(self):

        vect = (self.snake[0][0] - self.snake[1][0], self.snake[0][1] - self.snake[1][1])
        if self.is_right:
            vect = (-vect[1], vect[0])
        elif self.is_left:
            vect = (vect[1], -vect[0])

        dest_pos = (self.snake[0][0] + vect[0],self.snake[0][1]+ vect[1])

        if not(0 <= dest_pos[0] < 32 and 0 <= dest_pos[1] < 32):
            self.is_dead =True

        elif dest_pos in self.snake:
            self.is_dead = True

        elif dest_pos == self.apple:
            prev_tail = self.snake[-1]

            for i in range(len(self.snake) - 1,0,-1):
                self.snake[i] = self.snake[i-1]
            self.snake[0] = dest_pos
            self.snake.append(prev_tail)

            #APPLE CREATION
            self.apple = (randint(0,32), randint(0,32))
            flag = True
            while flag:
                flag = False
                for pos in self.snake:
                    if pos[0] == self.apple[0] and pos[1] == self.apple[1]:
                        self.apple = (randint(0,32), randint(0,32))
                        flag = True
        else:
            for i in range(len(self.snake) - 1,0,-1):
                self.snake[i] = self.snake[i-1]
            self.snake[0] = dest_pos

    def game(self):

        if display:
            pygame.init()
            DisplaySurface = pygame.display.set_mode((640, 640))
            # Game Name Pong
            pygame.display.set_caption("Pong")

        self.is_dead = False
        while not self.is_dead:

            # User Events;
            if display:
                pygame.display.update()
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.quit()
                        sys.exit()

            keys = pygame.key.get_pressed()

            if keys[pygame.K_RIGHT]:
                self.move_right()
            elif keys[pygame.K_LEFT]:
                self.move_left()

            self.move_forward()
            if display:
                DisplaySurface.fill((0,0,0))
                self.update(DisplaySurface)

            (pygame.time.Clock()).tick(16)

        pygame.quit()
        sys.exit()

    def update(self, surface):
        for elem in self.snake:
            pygame.draw.rect(surface, (255,255,255), (elem[0]*20,elem[1]*20,20,20))
        pygame.draw.rect(surface, (255, 0, 0), (self.apple[0] * 20,self.apple[1] * 20, 20, 20))

snakeGame().game()


from pathlib import Path
from argparse import ArgumentParser

# The path the project resides in
BASE_PATH = Path(__file__).parent.parent

# Alarm net dimensions
ALARM_HUGE = (5000, 2000, 500, 200)
ALARM_BIG = (1000, 500, 200, 75)
ALARM_SMALL = (100, 50, 25, 10)

# Standard arguments
def add_standard_arguments(parser: ArgumentParser):
    """
    Add basic arguments useful to all experiments
    :param parser: argument parser object
    :return: argument parser with standard arguments added
    """

    parser.add_argument(
        "random_seed", type=int, help="Seed to fix randomness"
    )
    parser.add_argument(
        "data_split", type=str, help="Data split on which to evaluate the performance (i.e. val or test)"
    )
    parser.add_argument(
        "--p_contamination", default=0.0, type=float,
        help="Fraction of contamination, i.e. anomalies in the training data"
    )
    parser.add_argument(
        "--n_train_anomalies", default=0, type=int,
        help="Number of known anomalies in the training set"
    )
    parser.add_argument(
        "--plot_freq", default=0, type=int,
        help="Plotting frequency to visualise the latent and image space"
    )
    parser.add_argument(
        "--n_epochs", default=500, type=int,
        help="Number of epochs"
    )
    parser.add_argument(
        "--learning_rate", default=.0001, type=float,
        help="Learning rate for adam"
    )
    parser.add_argument(
        "--sample_stddev", default=None, type=float,
        help="Standard deviation of the generated anomalies (in the code layer)"
    )
    parser.add_argument(
        "--model_path", default=BASE_PATH / "models", type=Path, help="Base output path for the models"
    )
    parser.add_argument(
        "--result_path", default=None, type=Path,
        help="Base output path for the results, if None use the model path"
        # default = BASE_PATH / "results"
    )
    parser.add_argument(
        "--is_override", default=False, type=bool,
        help="Override existing models"
    )

    return parser


import cv2

# loading the images
img1 = cv2.imread("png//yy.jpg")
img2 = cv2.imread("png//ra.jpg")

# resizing the both images in same resolution
scale_percent = 60 # percent of original size
width = int(img1.shape[1] * scale_percent / 90)
height = int(img2.shape[0] * scale_percent / 90)
dim = (width, height)
# resize image
reimg1 = cv2.resize(img1,dsize= dim, interpolation = cv2.INTER_AREA)
reimg2 = cv2.resize(img2, dsize=dim, interpolation = cv2.INTER_AREA)

#including face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gray1 = cv2.cvtColor(reimg1,cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(reimg2,cv2.COLOR_BGR2GRAY)

face1 = face_cascade.detectMultiScale(gray1,scaleFactor = 1.05, minNeighbors=5)
face2 = face_cascade.detectMultiScale(gray2,scaleFactor = 1.05 ,minNeighbors=5)

# putting the rectangle on the faces
for x,y ,w,h in face1:
    reimg1 = cv2.rectangle(reimg1, (x, y), (x+w, y+h),(255, 0, 0), 3)

for x,y ,w,h in face2:
    reimg2 = cv2.rectangle(reimg2, (x, y), (x+w, y+h), (0, 0, 250), 3)

# difference img of the images
diff = cv2.subtract(reimg1, reimg2)
cv2.imshow("diff",diff)
if cv2.waitKey(0) == ord('q'):
    cv2.destroyAllWindows()
print("Difference : ",diff)

# comparing the two images for exactly same of not
b, g, r = cv2.split(diff)
if cv2.countNonZero(b)==0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
    print("Both Images Are Identical !")
else:
    print("Images Are Not Identical")

# finding the similarities of two images
sift = cv2.xfeatures2d.SIFT_create()
kp1, desc1 = sift.detectAndCompute(reimg2, None) # key-points corresponds to the position
kp2, desc2 = sift.detectAndCompute(reimg1, None)

index_params = dict(algorithm=0, trees=5)
search_params = dict()

#  Fast Library for Approximate Nearest Neighbors
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(desc1, desc2, k=2) # to get the best matches

good_points = []  # correct matches
ratio = 0.6
for m, n in matches:
    if m.distance < ratio*n.distance:
        good_points.append(m)

# showing the both images (compare mode)
result = cv2.drawMatches(reimg1, kp1, reimg2, kp2, good_points, None)

cv2.imshow("result", result)
cv2.imshow("img1", reimg1)
cv2.imshow("img2", reimg2)
cv2.waitKey(0)
cv2.destroyAllWindows()
acc = len(good_points)*100/len(matches)
print("Good Points : {}".format(len(good_points)))
print("Total Matches : {}".format(len(matches)))
print("Accuracy : {}".format(acc))
if acc > 0:
    print("Both Are The same person")
else:
    print("Different Persons")


from enum import Enum, auto
from typing import Any, Tuple

from mesa import Model
from mesa.datacollection import DataCollector
from mesa.space import ContinuousSpace
from mesa.time import SimultaneousActivation

from autonomous_intersection.agents.direction import Direction
from autonomous_intersection.agents.visualcell import VisualCell
from autonomous_intersection.constants import PIXEL_PER_METER, STEPS_PER_SECOND
from autonomous_intersection.managers.advanced_reservation_manager import AdvancedReservationBasedManager
from autonomous_intersection.managers.prediction_manager import PredictionBasedManager
from autonomous_intersection.managers.reservation_manager import ReservationBasedManager
from autonomous_intersection.managers.traffic_light_manager import TrafficLightManager
from autonomous_intersection.rect import Rect

class Manager(Enum):
    TrafficLight = auto()
    BasicReservation = auto()
    AdvancedReservation = auto()
    Prediction = auto()

class Intersection(Model):
    def __init__(self, height=1000, width=1000, spawn_rate=10, manager: str = Manager.TrafficLight.name, *args: Any,
                 **parameters: Any):
        super().__init__(*args, **parameters)
        self.schedule = SimultaneousActivation(self)
        self.space = ContinuousSpace(height, width, False)
        self.width = width
        self.height = height
        self.road_width = 7 * PIXEL_PER_METER
        self.manager = self.get_manager(manager)(self.width, self.height, self.road_width, parameters, self)
        self.build_background()
        self.agent_id = 0
        self.running = True
        self.spawn_rate = spawn_rate / 100
        self.car_height = int(1.5 * PIXEL_PER_METER)
        self.data_collector = DataCollector(model_reporters={"Throughput [cars / min]": self.get_agent_rate})

    @staticmethod
    def get_manager(manager):
        if manager == Manager.TrafficLight.name: return TrafficLightManager
        if manager == Manager.BasicReservation.name: return ReservationBasedManager
        if manager == Manager.AdvancedReservation.name: return AdvancedReservationBasedManager
        return PredictionBasedManager

    def get_agent_id(self):
        self.agent_id += 1
        return self.agent_id

    def build_background(self):
        for cell in self.manager.build_background():
            self.space.place_agent(cell, (cell.x, cell.y))
            self.schedule.add(cell)

    def spawn_car(self, entry, width, height):
        cell = self.manager.create_new_car(entry, (width, height), self.get_agent_id())
        self.space.place_agent(cell, (cell.x, cell.y))
        self.schedule.add(cell)

    def add_new_agents(self):
        for entry in Direction:
            if not self.manager.is_entry_occupied(entry) and self.random.random() < self.spawn_rate:
                self.spawn_car(entry, *self.random_car_size(self.car_height))

    def random_car_size(self, height) -> Tuple[int, int]:
        return self.random.randint(round(height * 1.3), height * 2), height

    def step(self):
        self.add_new_agents()
        self.manager.remove_cars(self.space, self.schedule)
        self.manager.control_cars()
        self.schedule.step()
        self.data_collector.collect(self)

    def draw_debug_object(self, rect: Rect, color: str) -> VisualCell:
        cell = VisualCell((rect.left, rect.top), (rect.width, rect.height), self, color, 2)
        self.space.place_agent(cell, (cell.x, cell.y))
        self.schedule.add(cell)
        return cell

    def delete_debug_object(self, cell: VisualCell) -> None:
        self.space.remove_agent(cell)
        self.schedule.remove(cell)

    def get_agent_rate(self):
        if self.manager.first_step is None: return 0
        steps = self.manager.steps - self.manager.first_step + 1
        if steps < 50: return 0
        return ((STEPS_PER_SECOND * 60) * self.manager.agent_count) // steps


import networkx as nx
from node import Node

class Graph(nx.Graph):
    def __init__(self):
        super().__init__()
        self.arcs=[]
        self.nao_servido = 0

    def increment_nao_servido(self):
        self.nao_servido += 1

    def decrement_nao_serveido(self):
        self.nao_servido-=1

    def create_node(self, id: str) -> Node:
        node = Node(id)
        return node

    def create_nodes(self, matrix):
        listaN = []
        dict_ap = {}
        for i in range(1, len(matrix[0])):
            node_name = matrix[0][i]
            node = self.create_node(node_name)
            listaN.append(node)
            dict_ap[node_name] = node
        self.add_nodes_from(listaN)
        multiple = set()
        i = 0
        for i in range(1, len(matrix)):
            for j in range(1, len(matrix[i])):
                if matrix[i][j] == '1':
                    if(not (matrix[0][j], matrix[i][0]) in multiple):
                        dict_ap[matrix[0][j]].add_neighbor(
                            dict_ap[matrix[i][0]])
                        dict_ap[matrix[i][0]].add_neighbor(
                            dict_ap[matrix[0][j]])
                        self.add_edge(dict_ap[matrix[0][j]],
                                      dict_ap[matrix[i][0]])
                        multiple.add((matrix[0][j], matrix[i][0]))
                        multiple.add((matrix[i][0], matrix[0][j]))

    def create_arcs(self):
        for i in self.nodes:
            for j in i.vizinhos:
                if ((i.id, j.id) not in self.arcs) and ((j.id, i.id) not in self.arcs):
                    self.arcs.append((i, j))


"""
This file contains the 16-state EKF for INS/GNSS integration in direct configuration
The following states are estimated in three dimensions
position, velocity, orientation, accel bias, gyro bias

References
https://github.com/NorthStarUAS/insgnss_tools/blob/main/insgnss_tools/Kinematics.py
https://github.com/PX4/PX4-ECL/tree/master/EKF/python/ekf_derivation
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3812568/
"""

import math

import numpy as np

from ins_data_utilities.quaternion_utils import *

# Model Constants

def create_skew(w):
    """
    Create skew symmetric matrix from vector
    :param w:
    :return:
    """
    return np.array([
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0]])

class NavEKF16:
    """
    16-state EKF for INS/GNSS integration in direct configuration
    """
    gravity_const = 9.81  # Acceleration due to gravity

    _I2 = np.identity(2)
    _I3 = np.identity(3)
    _I5 = np.identity(5)
    _I16 = np.identity(16)

    def __init__(self):
        # Sensor variances (as standard deviation) and models (tau)
        self.aNoiseSigma_mps2 = 0.5  # Std dev of Accelerometer Wide Band Noise (m/s^2)
        self.aMarkovSigma_mps2 = 0.1  # Std dev of Accelerometer Markov Bias
        self.tau_acc_bias = 300.0  # Correlation time or time constant

        self.wNoiseSigma_rps = math.radians(0.1)  # Std dev of rotation rate output noise (rad/s)
        self.wMarkovSigma_rps = math.radians(0.015)  # Std dev of correlated rotation rate bias (rad/s)
        # self.tau_angular_acc_bias = 1000.0  # Correlation time or time constant

        # TODO: Figure out hhy does it not work when using real GNSS noise is decreased to correct values 2.5 cm?
        # Seems to velocity is updated wrongly
        self.rNoiseSigma_NE_m = 3  # GPS measurement noise std dev (m)
        self.rNoiseSigma_U_m = 1  # GPS measurement noise std dev (m)

        self.vNoiseSigma_NE_mps = 0.5  # GPS measurement noise std dev (m/s)
        self.vNoiseSigma_D_mps = 1.0  # GPS measurement noise std dev (m/s)

        # Initial set of covariance
        self.pErrSigma_Init_m = 10.0  # Std dev of initial position error (m)
        self.vErrSigma_Init_mps = 1.0  # Std dev of initial velocity error (m/s)
        self.attErrSigma_Init_rad = math.radians(20)  # Std dev of initial attitude (phi and theta) error (rad)
        self.hdgErrSigma_Init_rad = math.radians(90)  # Std dev of initial Heading (psi) error (rad)
        self.aBiasSigma_Init_mps2 = 0.1 * self.gravity_const  # Std dev of initial acceleration bias (m/s^2)
        self.wBiasSigma_Init_rps = math.radians(1)  # Std dev of initial rotation rate bias (rad/s)

        # Kalman Matrices
        self.H = np.zeros((6, 16))  # Observation matrix
        self.R = np.zeros((6, 6))  # Covariance of the Observation Noise (associated with MeasUpdate())
        self.Rw = np.zeros((6, 6))  # Covariance of the Sensor Noise (associated with TimeUpdate())
        self.S = np.zeros((6, 6))  # Innovation covariance
        self.P = np.zeros((16, 16))  # Covariance estimate
        self.K = np.zeros((16, 6))  # Kalman gain
        self.Q = np.zeros((16, 16))  # Process noise covariance
        self.Fx = self._I16  # State transition matrix

        # State estimates
        self.est_pos = np.zeros(3)  # Estimated position in ENU
        self.est_vel = np.zeros(3)  # Estimated velocity in ENU
        self.est_ori = np.zeros(4)  # Quaternion of B wrt Local
        self.est_acc_bias = np.zeros(3)  # acceleration bias
        self.est_rate_of_rot_bias = np.zeros(3)  # rotation rate bias

        # Estimates from previous data
        self.est_acc = np.zeros(3)  # Estimated acceleration in Body
        self.est_rate_rotation = np.zeros(3)  # Bias free rate of rotation

        self._configure()

    def _configure(self):
        # Observation matrix (H)
        self.H[0:5, 0:5] = self._I5

        # Covariance of the Process Noise (associated with TimeUpdate())
        self.Rw[0:3, 0:3] = self.aNoiseSigma_mps2 ** 2 * self._I3
        self.Rw[3:6, 3:6] = self.wNoiseSigma_rps ** 2 * self._I3
        # self.Rw[6:9, 6:9] = 2 / self.tau_acc_bias * self.aMarkovSigma_mps2 ** 2 * self._I3  # TODO: Check this
        # self.Rw[9:12, 9:12] = 2 / self.tau_angular_acc_bias * self.wMarkovSigma_rps ** 2 * self._I3

        # Covariance of the Observation Noise (associated with MeasUpdate())
        self.R[0:2, 0:2] = self.rNoiseSigma_NE_m ** 2 * self._I2
        self.R[2, 2] = self.rNoiseSigma_U_m ** 2
        self.R[3:5, 3:5] = self.vNoiseSigma_NE_mps ** 2 * self._I2
        self.R[5, 5] = self.vNoiseSigma_D_mps ** 2

        # Initial Innovation Covariance Estimate (S)
        # Zeros

        # Initial Covariance Estimate (P)
        self.P[0:3, 0:3] = self.pErrSigma_Init_m ** 2 * self._I3
        self.P[3:6, 3:6] = self.vErrSigma_Init_mps ** 2 * self._I3
        self.P[6:8, 6:8] = self.attErrSigma_Init_rad ** 2 * self._I2
        self.P[8, 8] = self.hdgErrSigma_Init_rad ** 2
        self.P[9:12, 9:12] = self.aBiasSigma_Init_mps2 ** 2 * self._I3
        self.P[12:15, 12:15] = self.wBiasSigma_Init_rps ** 2 * self._I3

    def get_euler_angles(self):
        # Euler angles from quaternion
        return quaternion_to_euler(self.est_ori)

    def initialize(self, r0, v0, s0):
        # Initialize Position and Velocity
        self.est_pos = r0  # Position in ENU
        self.est_vel = v0  # Velocity in ENU
        # Euler to quaternion
        self.est_ori = euler_to_quaternion(s0)

    def create_state_transition_matrix(self, dt) -> np.ndarray:
        q0, q1, q2, q3 = self.est_ori
        dvx, dvy, dvz = self.est_acc  # delta velocity
        dax, day, daz = self.est_rate_rotation  # delta angle
        dvx_b, dvy_b, dvz_b = self.est_acc_bias  # Accelerometer bias
        dax_b, day_b, daz_b = self.est_rate_of_rot_bias
        g = self.gravity_const
        # tau_dvb = self.tau_acc_bias
        # tau_dab = self.tau_angular_acc_bias
        return np.array(
            [[1, 0, 0, dt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, dt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             [0, 0, 1, 0, 0, dt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 1, 0, 0, dt * (2 * q2 * (dvz - dvz_b - g) - 2 * q3 * (dvy - dvy_b)),
              dt * (2 * q2 * (dvy - dvy_b) + 2 * q3 * (dvz - dvz_b - g)),
              dt * (2 * q0 * (dvz - dvz_b - g) + 2 * q1 * (dvy - dvy_b) - 4 * q2 * (dvx - dvx_b)),
              dt * (-2 * q0 * (dvy - dvy_b) + 2 * q1 * (dvz - dvz_b - g) - 4 * q3 * (dvx - dvx_b)), 0, 0, 0,
              dt * (2 * q2 ** 2 + 2 * q3 ** 2 - 1), dt * (2 * q0 * q3 - 2 * q1 * q2),
              dt * (-2 * q0 * q2 - 2 * q1 * q3)],
             [0, 0, 0, 0, 1, 0, dt * (-2 * q1 * (dvz - dvz_b - g) + 2 * q3 * (dvx - dvx_b)),
              dt * (-2 * q0 * (dvz - dvz_b - g) - 4 * q1 * (dvy - dvy_b) + 2 * q2 * (dvx - dvx_b)),
              dt * (2 * q1 * (dvx - dvx_b) + 2 * q3 * (dvz - dvz_b - g)),
              dt * (2 * q0 * (dvx - dvx_b) + 2 * q2 * (dvz - dvz_b - g) - 4 * q3 * (dvy - dvy_b)), 0, 0, 0,
              dt * (-2 * q0 * q3 - 2 * q1 * q2), dt * (2 * q1 ** 2 + 2 * q3 ** 2 - 1),
              dt * (2 * q0 * q1 - 2 * q2 * q3)],
             [0, 0, 0, 0, 0, 1, dt * (2 * q1 * (dvy - dvy_b) - 2 * q2 * (dvx - dvx_b)),
              dt * (2 * q0 * (dvy - dvy_b) - 4 * q1 * (dvz - dvz_b - g) + 2 * q3 * (dvx - dvx_b)),
              dt * (-2 * q0 * (dvx - dvx_b) - 4 * q2 * (dvz - dvz_b - g) + 2 * q3 * (dvy - dvy_b)),
              dt * (2 * q1 * (dvx - dvx_b) + 2 * q2 * (dvy - dvy_b)), 0, 0, 0, dt * (2 * q0 * q2 - 2 * q1 * q3),
              dt * (-2 * q0 * q1 - 2 * q2 * q3), dt * (2 * q1 ** 2 + 2 * q2 ** 2 - 1)],
             [0, 0, 0, 0, 0, 0, 1, -0.5 * dax + 0.5 * dax_b, -0.5 * day + 0.5 * day_b, -0.5 * daz + 0.5 * daz_b,
              0.5 * q1, 0.5 * q2, 0.5 * q3, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0.5 * dax - 0.5 * dax_b, 1, 0.5 * daz - 0.5 * daz_b, -0.5 * day + 0.5 * day_b,
              -0.5 * q0, 0.5 * q3, -0.5 * q2, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0.5 * day - 0.5 * day_b, -0.5 * daz + 0.5 * daz_b, 1, 0.5 * dax - 0.5 * dax_b,
              -0.5 * q3, -0.5 * q0, 0.5 * q1, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0.5 * daz - 0.5 * daz_b, 0.5 * day - 0.5 * day_b, -0.5 * dax + 0.5 * dax_b, 1, 0.5 * q2,
              -0.5 * q1, -0.5 * q0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]]
        )

    def create_process_update_matrix(self, dt):
        q0, q1, q2, q3 = self.est_ori
        return np.array(
            [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
             [0, 0, 0, dt * (-2 * q2 ** 2 - 2 * q3 ** 2 + 1), dt * (-2 * q0 * q3 + 2 * q1 * q2),
              dt * (2 * q0 * q2 + 2 * q1 * q3)],
             [0, 0, 0, dt * (2 * q0 * q3 + 2 * q1 * q2), dt * (-2 * q1 ** 2 - 2 * q3 ** 2 + 1),
              dt * (-2 * q0 * q1 + 2 * q2 * q3)],
             [0, 0, 0, dt * (-2 * q0 * q2 + 2 * q1 * q3), dt * (2 * q0 * q1 + 2 * q2 * q3),
              dt * (-2 * q1 ** 2 - 2 * q2 ** 2 + 1)], [-0.5 * q1, -0.5 * q2, -0.5 * q3, 0, 0, 0],
             [0.5 * q0, -0.5 * q3, 0.5 * q2, 0, 0, 0], [0.5 * q3, 0.5 * q0, -0.5 * q1, 0, 0, 0],
             [-0.5 * q2, 0.5 * q1, 0.5 * q0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
        )

    def predict(self, measured_angular_vel, measured_acc, dt):
        # A-priori accel and rotation rate estimate
        self.est_acc = measured_acc - self.est_acc_bias
        self.est_rate_rotation = measured_angular_vel - self.est_rate_of_rot_bias

        # Kalman Time Update (Prediction)
        # Compute DCM (Body to/from ENU) Transformations from Quaternion
        local_to_body_trans = quaternion_to_dcm(self.est_ori)
        body_to_local_trans = local_to_body_trans.T

        # Attitude Update
        attitude_delta = np.hstack((1, 0.5 * dt * self.est_rate_rotation))
        self.est_ori = quaternion_mult(self.est_ori, attitude_delta)

        # Avoid quaternion flips sign
        if self.est_ori[0] < 0:
            self.est_ori = -self.est_ori

        # Velocity Update
        gravity_vector = np.array([0.0, 0.0, -self.gravity_const])
        self.est_vel += (body_to_local_trans @ self.est_acc + gravity_vector) * dt

        # Position Update
        self.est_pos += (dt * self.est_vel)

        self.Fx = self.create_state_transition_matrix(dt)

        # Process Noise Covariance (Discrete approximation)
        Fu = self.create_process_update_matrix(dt)

        # Discrete Process Noise
        self.Q = Fu @ self.Rw @ Fu.T
        self.Q = 0.5 * (self.Q + self.Q.T)

        # Covariance Time Update
        self.P = self.Fx @ self.P @ self.Fx.T + self.Q
        self.P = 0.5 * (self.P + self.P.T)

    def correct(self, measured_position, measured_velocity, measured_angular_vel, measured_acc):
        # Kalman Measurement Update
        # Position Error
        pos_err = measured_position - self.est_pos

        # Velocity Error
        vel_err = measured_velocity - self.est_vel

        # Create measurement Y, as Error between Measures and Outputs
        y = np.zeros(6)
        y[0:3] = pos_err
        y[3:6] = vel_err

        # Innovation covariance
        self.S = self.H @ self.P @ self.H.T + self.R

        # Kalman gain
        self.K = self.P @ self.H.T @ np.linalg.inv(self.S)

        # Covariance update
        I_KH = self._I16 - self.K @ self.H
        self.P = I_KH @ self.P @ I_KH.T + self.K @ self.R @ self.K.T

        # State update, x = K * y
        x = self.K @ y

        # Pull apart x terms to update the Position, velocity, orientation, and sensor biases

        # Position update
        pos_delta = x[0:3]  # Position Deltas in ENU
        self.est_pos += pos_delta

        # Velocity update
        vel_delta = x[3:6]  # Velocity Deltas in ENU
        self.est_vel += vel_delta

        # Attitude correction
        quat_delta = x[6:10]  # Quaternion Delta
        attitude_delta = np.array([quat_delta[0], quat_delta[1], quat_delta[2], quat_delta[3]])
        self.est_ori = quaternion_mult(self.est_ori, attitude_delta)

        # Update biases from states
        acc_bias_delta = x[10:13]  # Accel Bias Deltas
        self.est_acc_bias += acc_bias_delta
        w_bias_delta = x[13:16]  # Rotation Rate Bias Deltas
        self.est_rate_of_rot_bias += w_bias_delta

        # Post-priori accel and rotation rate estimate, biases updated in MeasUpdate()
        self.est_acc = measured_acc - self.est_acc_bias  # only for users convenience
        self.est_rate_rotation = measured_angular_vel - self.est_rate_of_rot_bias  # only for users convenience


from tkinter import IntVar
from tkinter.constants import N, NE, S, TRUE, W
from controllers.edocsController import *
from helpers import helper
import json

class view:

    def __init__(self, program):

        self.program = program
        self.frame_bgc = "#f5f5f5"
        self.controller = edocsController()

    def index(self):

        try:

            self.program.header("Configuracion de cuenta EDOC's")

            general_info_frame =  self.program.newFrame(Row = 0 , Col = 0, Pos='NW', Margin = 5, Bg=self.frame_bgc)

            self.program.newLabel(  LabelName = "API URL:", Row = 0, Col = 0, Bg=self.frame_bgc , into_frame = general_info_frame)
            self.program.newEntry(  Row = 0, Col = 1, Pos = 'W', Long = 80 , Data = self.controller.val1 , into_frame = general_info_frame)

            self.program.newLabel(  LabelName = "Usuario:", Row = 1, Col = 0, Bg=self.frame_bgc , into_frame = general_info_frame)
            self.program.newEntry(  Row = 1, Col = 1, Pos = 'W', Long = 20 , Data = self.controller.val2 , into_frame = general_info_frame)

            self.program.newLabel(  LabelName = "Contraseña:", Row = 2, Col = 0, Bg=self.frame_bgc , into_frame = general_info_frame)
            self.program.newEntry(  Row = 2, Col = 1, Pos = 'W', Long = 20 , Data = self.controller.val3 , into_frame = general_info_frame , mask = True)

            self.program.newLabel(  LabelName = "Token:", Row = 3, Col = 0, Bg=self.frame_bgc , into_frame = general_info_frame)
            self.program.newEntry(  Row = 3, Col = 1, Pos = 'W', Long = 50 , Data = self.controller.val4 , into_frame = general_info_frame , mask = True)

            self.program.newButton( Name = "Conectar", Row = 4 , Col = 0, Pos = 'W', Command= lambda : self.controller.save()  , into_frame = general_info_frame )

        except Exception as e :

            messagebox.showerror(message=str(e) , title="Error")


import random
import torchvision
from torchvision import datasets, transforms
from data.RPSLS.types import *

transformations = transforms.Compose([
    transforms.ToTensor(),
])
dataset = datasets.ImageFolder(
    root='../../../data/RPSLS/rock-paper-scissors-lizard-spock',
    transform = transformations
)

def generate_data(dataset):
    examples = list()
    i = list(range(len(dataset)))
    random.shuffle(i)
    i = iter(i)
    while True:
        try:
            examples.append(next_example(i,dataset))
        except StopIteration:
            break

def next_example(i,dataset):
    x1, x2 = next(i), next(i)
    y = winner(x1, x2,dataset)
    return x1, x2, y

generate_data(dataset)


from django import forms
from .models import Producto
from django.forms import ModelForm

class ProductosForm(forms.ModelForm):

    class Meta:
        model = Producto
        fields = ('nombre','material','cantidad','categoria')
        labels = {
            'nombre':'Nombre',
            'cantidad':'n. cantidad'
        }

    def __init__(self, *args, **kwargs):
        super(ProductosForm,self).__init__(*args, **kwargs)
        self.fields['categoria'].empty_label = "Select"
        self.fields['cantidad'].required = False


"""
Tests for the petl.fluent module.

"""

from __future__ import absolute_import, print_function, division

from tempfile import NamedTemporaryFile
import csv
from nose.tools import eq_

import petl
import petl.interactive as etl
from petl.testutils import ieq

def test_basics():

    t1 = (('foo', 'bar'),
         ('A', 1),
         ('B', 2))
    w1 = etl.wrap(t1)

    eq_(('foo', 'bar'), w1.header())
    eq_(petl.header(w1), w1.header())
    ieq((('A', 1), ('B', 2)), w1.data())
    ieq(petl.data(w1), w1.data())

    w2 = w1.cut('bar', 'foo')
    expect2 = (('bar', 'foo'),
               (1, 'A'),
               (2, 'B'))
    ieq(expect2, w2)
    ieq(petl.cut(w1, 'bar', 'foo'), w2)

    w3 = w1.cut('bar', 'foo').cut('foo', 'bar')
    ieq(t1, w3)

def test_staticmethods():

    f = NamedTemporaryFile(delete=False)
    writer = csv.writer(f, delimiter='\t')
    table = (('foo', 'bar'),
             ('a', 1),
             ('b', 2),
             ('c', 2))
    for row in table:
        writer.writerow(row)
    f.close()

    actual = etl.fromcsv(f.name, delimiter='\t')
    expect = (('foo', 'bar'),
              ('a', '1'),
              ('b', '2'),
              ('c', '2'))
    ieq(expect, actual)
    ieq(expect, actual) # verify can iterate twice

def test_container():
    table = (('foo', 'bar'),
             ('a', 1),
             ('b', 2),
             ('c', 2))
    actual = etl.wrap(table)[0]
    expect = ('foo', 'bar')
    eq_(expect, actual)
    actual = len(etl.wrap(table))
    expect = 4
    eq_(expect, actual)

def test_repr_html():
    table = (('foo', 'bar'),
             ('a', 1),
             ('b', 2),
             ('c', 2))
    expect = u"""

foo
bar

a
1

b
2

c
2

"""
    actual = etl.wrap(table)._repr_html_()
    for l1, l2 in zip(expect.split('\n'), actual.split('\r\n')):
        eq_(l1, l2)

def test_repr_html_limit():
    table = (('foo', 'bar'),
             ('a', 1),
             ('b', 2),
             ('c', 2))

    # lower repr limit
    etl.repr_html_limit = 2

    expect = u"""

foo
bar

a
1

b
2

...

"""
    actual = etl.wrap(table)._repr_html_()
    for l1, l2 in zip(expect.split('\n'), actual.split('\r\n')):
        eq_(l1, l2)


__author__ = 'Vivek'

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

    # @param A : head node of linked list
    # @return the head node in the linked list
def mergeTwoLists(self, A, B):
        curA, curB = A, B
        if A == None :
            return B
        elif B == None :
            return A
        if curA.val <= curB.val :
            C = curA
            curA = curA.next
        else :
            C = curB
            curB = curB.next
        curC = C
        while curA != None and curB != None :
            if curA.val <= curB.val :
                curC.next = curA
                curA = curA.next
                curC = curC.next
            else :
                curC.next = curB
                curB = curB.next
                curC = curC.next

        while curA != None :
            curC.next = curA
            curA = curA.next
            curC = curC.next

        while curB != None :
            curC.next = curB
            curB = curB.next
            curC = curC.next
        return C
def split(self, start) :
        if start == None or start.next == None :
            first = start
            second = None
        else :
            slow = start
            fast = start
            while fast != None and fast.next != None :
                slow = slow.next
                fast = fast.next.next
            first = start
            second = slow.next
            slow.next = None
        return first, second

def sortList(self, A):
        if A == None or A.next == None :
            return A
        firstHalf = None
        secondHalf = None
        firstHalf, secondHalf = self.split(A)
        self.sortList(firstHalf)
        self.sortList(secondHalf)
        #self.mergeTwoLists(firstHalf, secondHalf)
        return  self.mergeTwoLists(firstHalf, secondHalf)


from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware

from app.auth import main as auths
from app.users import main as users
from app.blogs import main as blogs, sub as blogs_sub

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(auths.app)
app.include_router(users.app)
app.include_router(blogs.app)
app.include_router(blogs_sub.app)


from typing import Callable, Any, Type

from lyrid import Address
from lyrid.base import ActorSystemBase
from lyrid.core.node import NodeSpawnProcessMessage
from lyrid.core.process import Process
from lyrid.core.system import Placement
from tests.factory.system import create_actor_system
from tests.mock.messenger import MessengerMock
from tests.mock.placement_policy import PlacementPolicyMatcherMock, PlacementPolicyMock
from tests.mock.randomizer import RandomizerMock

def assert_pass_process_type_to_policy_matcher(spawn_process: Callable[[ActorSystemBase], Any], type_: Type[Process]):
    matcher = PlacementPolicyMatcherMock()
    system = create_actor_system(placements=[Placement(match=matcher, policy=PlacementPolicyMock())],
                                 node_addresses=[Address("#node0"), Address("#node1"), Address("#node2")])

    spawn_process(system)

    assert matcher.match__type == type_

def assert_send_node_spawn_process_message_to_the_address_from_policy(spawn_process: Callable[[ActorSystemBase], Any]):
    messenger = MessengerMock()
    policy = PlacementPolicyMock(get_placement_node__return=Address("#node1"))
    system = create_actor_system(messenger=messenger,
                                 placements=[Placement(PlacementPolicyMatcherMock(match__return=True), policy)],
                                 node_addresses=[Address("#node0"), Address("#node1"), Address("#node2")])

    spawn_process(system)

    assert messenger.send__receiver == Address("#node1") and \
           isinstance(messenger.send__message, NodeSpawnProcessMessage)

def assert_use_node_address_from_first_matched_policy(spawn_process: Callable[[ActorSystemBase], Any]):
    messenger = MessengerMock()
    placements = [
        Placement(
            match=PlacementPolicyMatcherMock(match__return=False),
            policy=PlacementPolicyMock(get_placement_node__return=Address("#node0")),
        ),
        Placement(
            match=PlacementPolicyMatcherMock(match__return=True),
            policy=PlacementPolicyMock(get_placement_node__return=Address("#node1")),
        ),
        Placement(
            match=PlacementPolicyMatcherMock(match__return=True),
            policy=PlacementPolicyMock(get_placement_node__return=Address("#node2")),
        ),
    ]

    # noinspection DuplicatedCode
    system = create_actor_system(messenger=messenger, placements=placements,
                                 node_addresses=[Address("#node0"), Address("#node1"), Address("#node2")])

    spawn_process(system)

    assert messenger.send__receiver == Address("#node1") and \
           isinstance(messenger.send__message, NodeSpawnProcessMessage)

def assert_use_random_node_when_no_matched_policy(spawn_process: Callable[[ActorSystemBase], Any]):
    messenger = MessengerMock()
    placements = [
        Placement(
            match=PlacementPolicyMatcherMock(match__return=False),
            policy=PlacementPolicyMock(get_placement_node__return=Address("#node0")),
        ),
        Placement(
            match=PlacementPolicyMatcherMock(match__return=False),
            policy=PlacementPolicyMock(get_placement_node__return=Address("#node1")),
        ),
    ]
    randomizer = RandomizerMock(randrange__return=2)

    system = create_actor_system(messenger=messenger, placements=placements, randomizer=randomizer,
                                 node_addresses=[Address("#node0"), Address("#node1"), Address("#node2")])

    spawn_process(system)

    assert messenger.send__receiver == Address("#node2") and \
           isinstance(messenger.send__message, NodeSpawnProcessMessage)


def read_file(fileName):
	content = []
	with open(fileName, 'r', encoding='utf-8-sig') as f:
		for line in f:
			content.append(line.strip())
		return content

def convert(textContent):
	output = []
	person = None
	for line in textContent:
		if line == 'Allen':
			person = 'Allen'
			continue
		elif line == 'Tom':
			person = 'Tom'
			continue
		if person:
			output.append(person + ": " + line)
	return output

def write_file(fileName, lines):
	with open(fileName, 'w') as f:
		for line in lines:
			f.write(line + '\n')

def main():
	lines = read_file('input.txt')
	lines = convert(lines)
	write_file('output.txt', lines)

main()


from .piece import Piece

class King(Piece):

    """
    Class that represents a king.
    """

    def __init__(self, color, row, column, board, rooks):
        Piece.__init__(self, color, row, column, board)
        self.offsets = [(1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1)]
        self.rooks = rooks

    def generate_legal_moves(self, king, prev_move):
        #glitch where king can take a defended piece
        end_squares = self.threatened_squares()
        possible_moves = [(self.row, self.column, square[0], square[1]) for square in end_squares]
        opposite_color = "B" if self.color == "W" else "W"

        #maybe make this more efficient
        enemy_threatened_squares = self.board.get_threatened_squares(opposite_color)
        legal_moves = self.filter_checks_and_pins(king, possible_moves)

        if not (self.row, self.column) in enemy_threatened_squares and not king.get_has_moved():
            self.castle(king, legal_moves, enemy_threatened_squares)

        return legal_moves

    def castle(self, king, legal_moves, enemy_threatened_squares):
        for rook in self.rooks:
            if rook.get_has_moved() or rook.is_killed():
                continue

            rook_row = rook.get_row()
            rook_column = rook.get_column()
            king_column = king.get_column()
            king_row = king.get_row()
            exceptions = [(rook_row, rook_column), (king_row, king_column)]
            can_castle = True

            #adapted for chess 960
            #queenside
            if king_column < rook_column:
                #make sure can't castle into check
                #check [?][5] and [?][4] for not being occupied - exception of occupied by
                #   king or correct rook
                #4 = rook, 5 = king
                if (self.row, 5) in enemy_threatened_squares: #make sure can't castle into check
                    continue
                #make sure final squares for rook and king are not occupied by other pieces
                if self.board.is_occupied(self.row, 4) and (self.row, 4) not in exceptions:
                    continue
                elif self.board.is_occupied(self.row, 5) and (self.row, 5) not in exceptions:
                    continue
                #make sure no pieces are inbetween king and rook
                for column in range(king_column + 1, rook_column):
                    if self.board.is_occupied(self.row, column):
                        can_castle = False
                        break
                #make sure all squares king has to move over aren't attacked
                for column in range(king_column, 6):
                    if (king_row, column) in enemy_threatened_squares:
                        can_castle = False
                        break
                if can_castle:
                    legal_moves.append((self.row, self.column, self.row, rook_column))
                    for column in range(king_column + 2, rook_column):
                        legal_moves.append((self.row, self.column, self.row, column))
            #kingside
            else:
                #make sure can't castle into check
                # check [?][1] and [?][2] for not being occupied
                #2 = rook, 1 = king
                if (self.row, 1) in enemy_threatened_squares:
                    continue
                elif self.board.is_occupied(self.row, 1) and (self.row, 1) not in exceptions:
                    continue
                elif self.board.is_occupied(self.row, 2) and (self.row, 2) not in exceptions:
                    continue
                for column in range(king_column - 1, rook_column, -1):
                    if self.board.is_occupied(self.row, column):
                        can_castle = False
                        break
                for column in range(king_column, 0, -1):
                    if (king_row, column) in enemy_threatened_squares:
                        can_castle = False
                        break
                if can_castle:
                    legal_moves.append((self.row, self.column, self.row, rook_column))
                    for column in range(king_column - 2, rook_column, -1):
                        legal_moves.append((self.row, self.column, self.row, column))

    def threatened_squares(self):
        possible_moves = []

        for row_offset, col_offset in self.offsets:
            curr_row, curr_column = self.row + row_offset, self.column + col_offset

            if curr_row < 0 or curr_row >= 8 or curr_column < 0 or curr_column >= 8:
                continue
            elif self.board.is_occupied(curr_row, curr_column):
                if self.board.get_piece_color(curr_row, curr_column) != self.color:
                    possible_moves.append((curr_row, curr_column))
            else:
                possible_moves.append((curr_row, curr_column))

        return possible_moves

    def is_attacked(self):
        # opposite_color = "B" if self.color == "W" else "W"
        # threatened_squares = self.board.get_threatened_squares(opposite_color)

        # if (self.row, self.column) in threatened_squares:
        #     return True
        # return False
        king_row, king_column = self.row, self.column

        straight_offsets = [(1, 0), (0, 1), (0, -1), (-1, 0)]
        for row_offset, column_offset in straight_offsets:
            curr_row, curr_column = king_row + row_offset, king_column + column_offset
            while curr_row >= 0 and curr_row < 8 and curr_column >= 0 and curr_column < 8:
                square = self.board.get_square(curr_row, curr_column)
                if square:
                    if square.get_color() == self.color:
                        break
                    else:
                        if square.get_symbol()[1] == "k":
                            if abs(king_row - curr_row) <= 1 and abs(king_column - curr_column) <= 1:
                                return True
                        #if opposite color and its a piece that can attack vertically
                        elif square.get_symbol()[1] in "rq":
                            return True
                        else:
                            break
                curr_row, curr_column = curr_row + row_offset, curr_column + column_offset

        diagonal_offsets = [(1, 1), (1, -1),(-1, 1), (-1, -1)]
        for row_offset, column_offset in diagonal_offsets:
            curr_row, curr_column = king_row + row_offset, king_column + column_offset
            while curr_row >= 0 and curr_row < 8 and curr_column >= 0 and curr_column < 8:
                square = self.board.get_square(curr_row, curr_column)
                if square:
                    if square.get_color() == self.color:
                        break
                    else:
                        #if opposite color and its a piece that can attack vertically
                        if square.get_symbol()[1] == "k":
                            if abs(king_row - curr_row) <= 1 and abs(king_column - curr_column) <= 1:
                                return True
                        elif square.get_symbol()[1] == "p":
                            if self.color == "W":
                                if curr_row == king_row + 1 and abs(curr_column - king_column) == 1:
                                    return True
                                else:
                                    break
                            else:
                                if curr_row == king_row - 1 and abs(curr_column - king_column) == 1:
                                    return True
                                else:
                                    break

                        elif square.get_symbol()[1] in "kbq":
                            return True
                        else:
                            break
                curr_row, curr_column = curr_row + row_offset, curr_column + column_offset

        knight_offsets =  [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (-1, 2), (1, -2), (-1, -2)]
        for row_offset, column_offset in knight_offsets:
            curr_row, curr_column = king_row + row_offset, king_column + column_offset
            if curr_row >= 0 and curr_row < 8 and curr_column >= 0 and curr_column < 8:
                square = self.board.get_square(curr_row, curr_column)
                if square:
                    if square.get_color() != self.color:
                        #if opposite color and its a knight
                        if square.get_symbol()[1] == "n":
                            return True
                        else:
                            continue

        return False

    def get_rooks(self):
        return self.rooks

    def __str__(self):
        return f"""
        King. Coordinates: [{self.row}][{self.column}]
        """

    def get_symbol(self):
        return self.color + "k"


import unittest
from Soda import Soda

class TestSoda(unittest.TestCase):

    def test_valid_no_tasty(self):
        self.soda = Soda('')
        self.assertEqual(self.soda.show_my_drink(), 'Обычная газировка')

    def test_valid_add_tasty(self):
        self.soda = Soda('клубника')
        self.assertEqual(self.soda.show_my_drink(), 'Газировка и клубника')

if __name__ == '__main__':
    unittest.main()


#!/usr/bin/env python

from __future__ import print_function

import sys
import os

if sys.version_info >= (3, 0):
    import tkinter
else:
    import Tkinter as tkinter

import interaction
import canvas
import FigureManager

# The size of the button (width, height) for buttons in root gui.
SIZE_BUTTON = (18, 4)

def find_show_image():
    """Search, open and show an pmg image.
    """
    filename = interaction.find_pmg()
    if filename:
        FigureManager.g_figure_manager.add_pmg(filename)
        canvas.show_figure_from_manager(
            FigureManager.g_figure_manager,
            title=os.path.basename(filename))

def main():
    """The main entry of the program.
    """
    root = tkinter.Tk()
    root.title('Pytena')

    tkinter.Button(
        root,
        text='Script',
        height=SIZE_BUTTON[1],
        width=SIZE_BUTTON[0],
        command=interaction.load_python_script).pack(side=tkinter.TOP)

    tkinter.Button(
        root,
        text='Image',
        height=SIZE_BUTTON[1],
        width=SIZE_BUTTON[0],
        command=find_show_image).pack(side=tkinter.TOP)

    tkinter.Button(
        root,
        text='Command',
        height=SIZE_BUTTON[1],
        width=SIZE_BUTTON[0],
        command=interaction.start_text_box).pack(side=tkinter.TOP)

    tkinter.Button(
        root,
        text='Help',
        height=SIZE_BUTTON[1],
        width=SIZE_BUTTON[0],
        command=interaction.show_help_box).pack(side=tkinter.TOP)

    root.mainloop()

if __name__ == '__main__':
    main()


from neo4j import GraphDatabase

# neo4j connection
driver = GraphDatabase.driver("bolt://127.0.0.1:7687", auth=("neo4j", "neo4j"))
# random walk
k = 10  # Number of neighbors
pre_weight = 2  # Weight of return
n = -1  # number of users to use, -1 means using all the users.
batch_size = 1000  # batchsize to save
cores = 12  # Multi threads
# Neo4j SQL to sample the motif.
motif_sql = '''
        match (a:User {{user_id: {id} }})<-[:msg|click]-(m)-[:msg|click]->(f) return "RESPOND" as r1, m.user_id as middle, f.user_id as final, 2 as weight limit {n1}
        union
        match (a:User {{user_id: {id} }})-[:msg|click]->(m)<-[:msg|click]-(f)  return "DOUBLE" as r1, m.user_id as middle, f.user_id as final, 2 as weight limit {n2}
        '''
"""
        match (a:User {{user_id: {id} }})<-[:msg|click]-(m)-[:msg|click]->(f) return "RESPOND" as r1, m.user_id as middle, f.user_id as final, 2 as weight limit {n1}
        union
        match (a:User {{user_id: {id} }})<-->(m)-[:msg|click]->(f) return "SEND" as r1, m.user_id as middle, f.user_id as final, 3 as weight limit {n1}
        union
        match (a:User {{user_id: {id} }})<-[:msg|click]-(m)<-->(f) return "DOUBLE" as r1, m.user_id as middle, f.user_id as final, 3 as weight limit {n2}
        union
        match (a:User {{user_id: {id} }})-[:msg|click]->(m)<-[:msg|click]-(f)  return "DOUBLE" as r1, m.user_id as middle, f.user_id as final, 2 as weight limit {n2}
        union
        match (a:User {{user_id: {id} }})<-->(m)<-[:msg|click]-(f) return "DOUBLE" as r1, m.user_id as middle, f.user_id as final, 2 as weight limit {n2}
        union
        match (a:User {{user_id: {id} }})-[:msg|click]->(m)<-->(f) return "DOUBLE" as r1, m.user_id as middle, f.user_id as final, 3 as weight limit {n2}
        union
        match (a:User {{user_id: {id} }})<-->(m)<-->(f) return "DOUBLE" as r1, m.user_id as middle, f.user_id as final, 4 as weight limit {n2}
"""
raw_walk_path = "../data/sjjy_data/motif_random_walk_path_M1+M4_b_{}.txt".format(pre_weight)  # Path of the raw random walk sequences
raw_emb_path = "../model/sjjy_motif_walk_M1+M4_b_{}.emb".format(pre_weight)  # Path of the raw embedding path
emb_save_path = "../model/sjjy_motif_walk_M1+M4_b_{}.emb".format(pre_weight)  # No need for data Sjjy
# motif random walk
raw_train_data_path = "../data/sjjy_data/train_data_v4.csv"  # train user pairs file path 原始的用户对id
raw_test_data_path = ""'../data/sjjy_data/test_data_v4.csv'  # test file path

train_data_path = "../data/sjjy_data/rec_data_train_M1+M4_b_{}.csv".format(pre_weight)  # train user pairs with neighbors
test_data_path = "../data/sjjy_data/rec_data_train_test_M1+M4_b_{}.csv".format(pre_weight)

# train
uid2idx_path = "../data/uid_2_idx.pkl" # user_id to id
model_save_path = "../model/recommend_M1+M4_b_{}.pb".format(pre_weight)  # final model save path
check_point_path = "../checkpoint/recommend_M1+M4_b_{}.pth".format(pre_weight)  # checkpoint path
feature_dict_path = "../data/sjjy_data/enc_feature_dict.pkl"


import random

import pyxel

import utils
import stage

TYPE_AGGRESSIVE = 0
TYPE_MILD = 1
TYPE_RANDOM_SLOW = 2
TYPE_RANDOM_FAST = 3

TYPES = [
    TYPE_AGGRESSIVE,
    TYPE_MILD,
    TYPE_RANDOM_SLOW,
    TYPE_RANDOM_FAST
]

TICKS_PER_FRAME = 10
MAX_FRAME = 4

MAX_SPEED = 0.4
MAX_RESPAWN_TICKS = 300 # 5 secs

class Spinner:
    def __init__(self, x, y, type):
        self.x = x
        self.y = y
        self.type = 2
        if type in TYPES:
            self.type = type

        self.vx = random.choice([-MAX_SPEED, MAX_SPEED])
        self.vy = random.choice([-MAX_SPEED, MAX_SPEED])

        self.radius = 4

        self.frame = 0
        self.frame_ticks = 0

        self.is_dead = False

        self.respawn_ticks = MAX_RESPAWN_TICKS

    def _set_new_position(self, stageObj):
        px = stageObj.player.x
        py = stageObj.player.y
        loc = None
        loclist = [
            stage.SPAWN_SECTOR_TOPLEFT,
            stage.SPAWN_SECTOR_BOTTOMLEFT,
            stage.SPAWN_SECTOR_TOPRIGHT,
            stage.SPAWN_SECTOR_BOTTOMRIGHT
        ]
        if px < 80:
            if py < 75:
                loclist.remove(stage.SPAWN_SECTOR_TOPLEFT)
            else:
                loclist.remove(stage.SPAWN_SECTOR_BOTTOMLEFT)
        else:
            if py < 75:
                loclist.remove(stage.SPAWN_SECTOR_TOPRIGHT)
            else:
                loclist.remove(stage.SPAWN_SECTOR_BOTTOMRIGHT)

        loc = stageObj.get_random_spawn_loc(random.choice(loclist))
        self.x = loc[0]
        self.y = loc[1]

    def kill(self):
        self.is_dead = True
        self.respawn_ticks = MAX_RESPAWN_TICKS

    def _do_collisions(self, stage):
        new_x = self.x + self.vx

        for b in stage.solid_rects:
            if utils.circle_rect_overlap(new_x, self.y, self.radius,
                b[0], b[1], b[2], b[3]):
                if self.x > b[0] + b[2]: # was prev to right of border.
                    new_x = b[0] + b[2] + self.radius
                elif self.x < b[0]: # was prev to left of border.
                    new_x = b[0] - self.radius

                self.vx *= -1
                break

        new_y = self.y + self.vy

        for b in stage.solid_rects:
            if utils.circle_rect_overlap(self.x, new_y, self.radius,
                b[0], b[1], b[2], b[3]):
                if self.y > b[1] + b[3]: # was prev below border.
                    new_y = b[1] + b[3] + self.radius
                elif self.y < b[1]: # was prev above border.
                    new_y = b[1] - self.radius

                self.vy *= -1
                break

        self.x = new_x
        self.y = new_y

    def respawn(self):
        self.is_dead = False

    def update(self, stage):
        if self.is_dead:
            self.respawn_ticks -= 1
            if self.respawn_ticks == 0:
                self.respawn()
            elif self.respawn_ticks == 30:
                self._set_new_position(stage)
        else:
            self._do_collisions(stage)

            self.frame_ticks += 1
            if self.frame_ticks == TICKS_PER_FRAME:
                self.frame_ticks = 0
                self.frame += 1
                if self.frame == MAX_FRAME:
                    self.frame = 0

    def draw(self, shake_x, shake_y):
        if self.is_dead:
            framex = None
            if self.respawn_ticks < 10:
                framex = 42
            elif self.respawn_ticks < 20:
                framex = 63
            elif self.respawn_ticks < 30:
                framex = 84
            if framex is not None:
                pyxel.blt(
                    self.x + shake_x - 10,
                    self.y + shake_y - 10,
                    0,
                    framex,
                    231,
                    21, 21,
                    8
                )
        else:
            pyxel.blt(
                self.x + shake_x - 4,
                self.y + shake_y - 4,
                0,
                160 + self.frame*9,
                8,
                9, 9,
                8
            )


#mark ericson
#9/12/2022
#This program creates a cubic grid

import rhinoscriptsyntax as rs
from random import uniform

def cubic_grid(x_number, y_number, z_number, cell_size):
    rs.EnableRedraw(False)
    point_list = []
    for i in range(0, x_number,cell_size):
        x = i
        for j in range(0, y_number, cell_size):
            y = j
            for p in range(0, z_number, cell_size):
                z = p
                point = (x,y,z)
                point_list.append(point)

                rs.AddPoint(point)
    return(point_list)

x_value = rs.GetInteger("Please provide the number of units in the x direction.")
y_value = rs.GetInteger("Please provide the number of units in the y direction.")
z_value = rs.GetInteger("Please provide the number of units in the z direction.")
cell_value = rs.GetInteger("Please provide a unit size for the grid.")

points = cubic_grid(x_value, y_value,z_value, cell_value)

for i in points:
    radius = uniform(1,5)
    rs.AddSphere(i,radius)
print (points)


from collections import Counter

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        s_len = len(s)
        t_len = len(t)
        begin = 0
        win_freq = {}
        t_freq = dict(Counter(t))

        min_len = s_len + 1
        distance = 0
        left = 0
        right = 0
        while right < s_len:
            if s[right] in t_freq and t_freq[s[right]] == 0:
                right += 1
                continue
            win_freq.setdefault(s[right], 0)
            if s[right] in t_freq and win_freq[s[right]] < t_freq[s[right]]:
                distance += 1
            win_freq[s[right]] += 1
            right += 1

            # 满足条件时，进行左边缘移动
            while distance == t_len:
                # win_freq.setdefault(s[left], 0)
                if right - left < min_len:
                    min_len = right - left
                    begin = left
                if s[left] not in t_freq:
                    left += 1
                    continue
                if s[left] in t_freq and win_freq[s[left]] == t_freq[s[left]]:
                    distance -= 1
                win_freq[s[left]] -= 1
                left += 1

        if min_len == s_len + 1:
            return ""

        return s[begin:begin + min_len]

so = Solution()
print(so.minWindow(s="ADOBECODEBANC", t="ABC"))

76. 最小覆盖子串.py


from flask import Flask, render_template, request
import pypandoc

app = Flask(__name__)

@app.route('/')
def home():
  return render_template('index.html')

@app.route('/convert', methods=['POST'])
def convert():
  input_markup = request.form['input_markup']
  output_markup = pypandoc.convert(input_markup, format='mediawiki', to='markdown_github')
  return render_template('index.html',
                         input_markup=input_markup,
                         output_markup=output_markup)

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


import os
from dotenv import load_dotenv
from minio import Minio
from io import BytesIO

from data_pipeline.classes.data_loader.DataLoader import DataLoader

class MinIOLoader(DataLoader):

    def __init__(self, endpoint, bucket_name):
        super().__init__(endpoint)
        self._bucket_name = bucket_name
        self._create_bucket()

    def _open_connection(self):
        load_dotenv()
        access_key = os.getenv("MINIO_USER")
        secret_key = os.getenv("MINIO_PASSWORD")

        return Minio(self._endpoint, access_key=access_key, secret_key=secret_key, secure=False)

    def _create_bucket(self):
        bucket_exists = self._connection.bucket_exists(self._bucket_name)
        if not bucket_exists:
            return self._connection.make_bucket(f"{self._bucket_name}")
        else:
            print(f"Bucket {self._bucket_name} already exists")

    def load_from_csv(self, upload_filepath, file_name, file_type='csv'):
        self._load_file(upload_filepath, file_name, file_type)

    def load_from_dataframe(self, dataframe, file_name, file_type='csv'):
        csv_file = dataframe.to_csv().encode('utf-8')
        csv_buffer = BytesIO(csv_file)

        self._connection.put_object(
            self._bucket_name,
            file_name,
            csv_buffer,
            length=len(csv_file),
            content_type=f'application/{file_type}'
        )

    def load_from_json(self, upload_filepath, file_name, file_type='json'):
        self._load_file(upload_filepath, file_name, file_type)

    def _load_file(self, upload_filepath, file_name, file_type):
        self._connection.fput_object(
            self._bucket_name,
            file_name,
            upload_filepath,
            content_type=f'application/{file_type}'
        )


import json
from warnings import warn

# def init_from_config(meas_cls, config: dict):
#     arg_str = ''
#
#     for key, value in config.items():
#         arg_str = key+'='+value

def export_measurement_config(obj, attr_keys=None):
    if attr_keys is None:
        attr_keys = obj.__init__.__code__.co_varnames

    params = {}
    for key in attr_keys:
        flag = 0
        if isinstance(obj, dict):
            if key in obj.keys():
                param = obj[key]
                flag = 1
        else:
            if key != 'self' and hasattr(obj, key):
                param = obj.__getattribute__(key)
                flag = 1

        if flag:
            if param.__class__.__name__ in ['dict', 'list', 'tuple', 'str', 'int',
                                            'float', 'bool', 'NoneType']:
                params[key] = param
            else:
                warn('The parameter \'%s\' of type \'%s\' is not JSON serializable and is skipped.' %
                     (key, param.__class__.__name__))

    return params

def save_config(config, filename):
    with open(filename, 'w') as fp:
        json.dump(config, fp, indent='\t')

def load_config(filename):
    with open(filename, 'r') as fp:
        config = json.load(fp)

    return config


from torchvision.models.detection import maskrcnn_resnet50_fpn

from rigl_torch.models import ModelFactory

@ModelFactory.register_model_loader(model="maskrcnn", dataset="coco")
def get_maskrcnn(*args, **kwargs):
    return maskrcnn_resnet50_fpn(
        weights=None, weights_backbone=None, trainable_backbone_layers=5
    )

if __name__ == "__main__":
    model = get_maskrcnn()
    print(model)


# 字典 values() 方法返回一个迭代器，可以使用 list() 来转换为列表，列表为字典中的所有值。

# dict.values()

# 返回值  返回迭代器。

Object = {
    "name": "Tom",
    "age": 18,
    "other": "其他"
}

print(Object.values()) # dict_values(['Tom', 18, '其他'])

for value in Object.values():
    print('value', value) # value Tom\value 18\value 其他

print(list(Object.values())) # ['Tom', 18, '其他']


#import bpy
from random import seed
from random import uniform
import numpy as np
import cv2
# seed random number generator
seed(1)
"""
def test1():

    # make mesh
    vertices = [(1, 0, 0),(1,0,5),(0,1,0)]
    edges = []
    faces = []
    faces.append([0,1,2])
    faces.append([2,0,3])

    #new_mesh = bpy.data.meshes.new('new_mesh')
    #new_mesh.from_pydata(vertices, edges, faces)
    #knew_mesh.update()
    # make object from mesh
    #new_object = bpy.data.objects.new('new_object', new_mesh)
    # make collection
    #new_collection = bpy.data.collections.new('new_collection')
    #bpy.context.scene.collection.children.link(new_collection)
    # add object to scene collection
    #new_collection.objects.link(new_object)

def add_mesh(name, verts, faces, edges=None, col_name="Collection"):
    if edges is None:
        edges = []
    mesh = bpy.data.meshes.new(name)
    obj = bpy.data.objects.new(mesh.name, mesh)
    col = bpy.data.collections.get(col_name)
    col.objects.link(obj)
    bpy.context.view_layer.objects.active = obj
    mesh.from_pydata(verts, edges, faces)
"""
def get_translation_between_points(pt1,pt2):
    transl = (pt2[0] - pt1[0], pt2[1] - pt1[1])
    return transl

class Geometry2d:
    def __init__(self, points=[]):
        self.points = points

    def reverse(self):
        self.points.reverse()

    def get_last_point(self):
        return self.points[-1]

    def get_first_point(self):
        return self.points[0]

    def remove_first_element(self):
        self.points.pop(0)

    def remove_last_element(self):
        self.points.pop()

    def translate_points(self, transl):
        points = self.points
        for i,p in enumerate(points):
            p = (p[0]+transl[0], p[1]+transl[1])
            points[i] = p

        return Geometry2d(points)

    def scale_points(self, scale):
        points = self.points
        for i,p in enumerate(points):
            p = (p[0]*scale, p[1]*scale)
            points[i] = p
        return Geometry2d(points)

    def flip_y(self):
        points = self.points
        for i,p in enumerate(self.points):
            points[i] = (p[0],-p[1])
        return Geometry2d(points)

    def draw(self):
        width = 300
        height = 300
        img = np.zeros((300,300))
        scale_obj = self.scale_points(30)
        draw_obj = scale_obj.flip_y()
        draw_obj = draw_obj.translate_points((int(width/2), int(height/2)))
        for point in draw_obj.points:
            print(point)
            point = (int(point[0]), int(point[1]))
            cv2.circle(img, point, 2, (255,0,0), 2)
        cv2.imshow("img", img)
        cv2.waitKey(0)

    def combine_at_first(self, geo2d_obj):
        new_geo2d_obj = Geometry2d()
        first_pt_obj1 = self.get_first_point()
        print("first_pt")
        print(first_pt_obj1)
        first_pt_obj2 = geo2d_obj.get_first_point()
        print("last pt")
        print(first_pt_obj2)
        transl = get_translation_between_points(first_pt_obj2, first_pt_obj1)

        print("transl")
        print(transl)
        transl_obj = geo2d_obj.translate_points(transl)
        print("translated points")
        print(transl_obj.points)
        transl_obj.points.pop(0)
        transl_obj.points = self.points + transl_obj.points
        return transl_obj

    def combine_at_last(self, geo2d_obj):
        first_pt_obj1 = self.get_last_point()
        print("first_pt")
        print(first_pt_obj1)
        first_pt_obj2 = geo2d_obj.get_first_point()
        print("last pt")
        print(first_pt_obj2)
        transl = get_translation_between_points(first_pt_obj2, first_pt_obj1)

        print("transl")
        print(transl)
        transl_obj = geo2d_obj.translate_points(transl)
        print("translated points")
        print(transl_obj.points)
        transl_obj.points.pop(0)
        transl_obj.points = self.points + transl_obj.points
        return transl_obj

"""

def generate_2d_corner(height, width, corner_point):
    p1 = (corner_point[0] + width, corner_point[1])
    p2 = corner_point
    p3 = (corner_point[0], corner_point[1]+height)

    verts = []
    # create bottom vertices
    for i in range(num_points):
        i = i/num_points*x_stop
        x = i+uniform(-step,step)
        y = -width/2
        z = uniform(0,z_limit)
        point = (x,y,z)
        verts.append(point)
        y = width/2
        point = (x,y,z)
        verts.append(point)

    faces = []

    for point in verts:
        print(point)

    # create faces
    num_points = len(verts)
    print(f'num points: {num_points}')
    for i in range(0,num_points-2, 2):
        faces.append([i+1, i, i+2, i+3])

    print("Faces:")
    print(faces)

    for face in faces:
        print(face)

    add_mesh("testsets", verts, faces)

    #verts = [( 1.0,  1.0,  0.0),
     #    ( 1.0, -1.0,  0.0),
      #   (-1.0, -1.0,  0.0),
        # (-1.0,  1.0,  0.0),
         #]
    #faces = [[0, 1, 2, 3]]
    #add_mesh("myBeautifulMesh_1", verts, faces)

    #verts = [( 3.0,  1.0,  0.0),
     #    ( 3.0, -1.0,  0.0),
      #   ( 2.0, -1.0,  0.0),
       #  ( 2.0,  1.0,  0.0),
        # ]
    #add_mesh("myBeautifulMesh_2", verts, faces)
"""

if __name__ == '__main__':
    geo2d_obj = Geometry2d([(1,0), (0,0),(0,1),(0,2), (0,3)])
    geo2d_obj1 = Geometry2d([(0,0), (1,0), (1,2), (2,1.5),(3,2), (3,0), (4,0)])
    geo2d_obj1 = geo2d_obj1.translate_points((4,4))
    geo_comb = geo2d_obj.combine_at_last(geo2d_obj1)
    geo_comb.draw()


from typing import Union
import numpy as np
from numpy import typing as npt
from .outlier_removal_interface import OutlierRemovalInterface

class AbsoluteOutlierRemoval(OutlierRemovalInterface):
    def __init__(self, top: float=None, bottom= None) -> None:
        super().__init__(top, bottom)

    def fit(self, X: npt.ArrayLike):
        self.lower_filter_ = self._bottom if self._bottom is not None else np.min(X)
        self.top_filter_ = self._top if self._top is not None else np.max(X)
        return self

    def transform(self, X: npt.ArrayLike) -> npt.ArrayLike:
        return np.where(
            (X >= self.lower_filter_) &
            (X <= self.top_filter_)
        )

if __name__ == '__main__':
    a = np.asarray([1, 2, 1, 2, 3, 2, 20, 30])
    iqr_removal = AbsoluteOutlierRemoval(bottom=2)
    iqr_removal.fit(a)

    print(a)
    print(a[iqr_removal.transform(a)])


#!/usr/bin/env python

import random

def merge(left, right):
    res = []
    while True:
        if len(left) == 0:
            res += right
            break
        elif len(right) == 0:
            res += left
            break
        elif left[0] > right[0]:
            res += [ right.pop(0) ]
        else:
            res += [ left.pop(0) ]
        if len(left) == 0 and len(right) == 0:
            break
    #print(res)
    return res

def merge_sort(a):
    N = len(a)
    if N == 1:
        return a
    else:
        m = N//2
        left = a[0:m]
        right = a[m:]
        #print('%s %s' % (left, right))
        left = merge_sort(left)
        right = merge_sort(right)
        return merge(left, right)

N = 100
a = []
for i in range(N):
    a.append(random.randint(0, 10000))
b = merge_sort(a)

s = True
c = sorted(a)
for i in range(len(a)):
    if b[i] != c[i]:
        s = False
print(s)


import pyrealsense2 as rs
import numpy as np
import cv2

WIDTH = 640
HEIGHT = 480
FPS = 30
# file name which you want to open
FILE = './data/stairs.bag'

def main():
    # stream(Depth/Color) setting
    config = rs.config()
    config.enable_stream(rs.stream.color, WIDTH, HEIGHT, rs.format.rgb8, FPS)
    config.enable_stream(rs.stream.depth, WIDTH, HEIGHT, rs.format.z16, FPS)
    config.enable_device_from_file(FILE)

    # Start streaming
    pipeline = rs.pipeline()
    pipeline.start(config)

    try:
        while True:
            # Wait for frames(Color/Depth)
            frames = pipeline.wait_for_frames()
            depth_frame = frames.get_depth_frame()
            color_frame = frames.get_color_frame()
            if not depth_frame or not color_frame:
                continue

            # Convert images to numpy arrays
            depth_image = np.asanyarray(depth_frame.get_data())
            depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.08), cv2.COLORMAP_JET)
            color_image = np.asanyarray(color_frame.get_data())
            # Show images
            color_image_s = cv2.resize(color_image, (WIDTH, HEIGHT))
            depth_colormap_s = cv2.resize(depth_colormap, (WIDTH, HEIGHT))
            images = np.hstack((color_image_s, depth_colormap_s))
            cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
            cv2.imshow('RealSense', images)

            INTERVAL = 10
            if cv2.waitKey(INTERVAL) & 0xff == 27:  # End with ESC
                cv2.destroyAllWindows()
                break

    finally:
        # Stop streaming
        pipeline.stop()

if __name__ == '__main__':
    main()


from locale import windows_locale
import turtle
import tkinter as tk
from tkinter import ttk

"""
Koch Snowflake Program
Author: Katherine Butt

This program uses a recursive algorithm to draw a koch snowflake
The user is able to use a slider and button to control the number of times the recursion occurs
Depending on how many times the recursion occurs different orders of the snowflake building process are drawn
"""

"""
The main purpose of this function is the recursion required to to produce the snowflake
This function is called from the drawSnowflake function once the user input has been gained
This function runs for as many order given by the user
"""
def snowflake(sidelength, i):
    if i == 0:
        t.forward(sidelength)
        return
    sidelength /= 3.0
    snowflake(sidelength, i-1)
    t.left(60)
    snowflake(sidelength, i-1)
    t.right(120)
    snowflake(sidelength, i-1)
    t.left(60)
    snowflake(sidelength, i-1)

check = "True"

"""
This function is responsible for getting the user input and initating the snowflake drawing
This function holds all the commands to get the turtle element of the program to begin running
"""
def drawsnowflake():
    global size
    t.clear()
    order = (inputval.get()-1)
    while(check == "True"):
        size = root.winfo_width()/2
        t.penup()
        t.pendown()
        screen.tracer(0)
        for i in range(3):
            snowflake(size, order)
            t.right(120)
        screen.tracer(1)
        resizechecker()

def resizechecker():
    if(size != root.winfo_width()/2):
        t.clear()
        drawsnowflake()

"""
The following code produces the gui window and allows for the tkinter and turtle modules to be on the same window
It sets all the defaults required fro the gui window and the interation that allow it to be resizeable
"""
root = tk.Tk()
root.geometry("500x500")#This sets the base size of the window
root.minsize(300,300)
root.resizable(True,True) #This allows the window to be resizeable by both the width and the height
canvas = tk.Canvas(master = root) #Adding the canvas to the root window
canvas.pack(fill = tk.BOTH, expand=tk.YES) #Allowing the canvas to be expanded
root.update()

"""
This section of code adds all the elements required to the gui window
This means that all element are shown to the user
"""
screen = turtle.TurtleScreen(canvas)
t = turtle.RawTurtle(screen)
t.hideturtle() #This line hides the drawing icon
inputval = tk.DoubleVar()
s = tk.Scale(master = root, label='Pick your order', from_=1, to=10, orient=tk.HORIZONTAL,
 length=200, showvalue=0,tickinterval=1, variable=inputval).pack(side=tk.LEFT, anchor="sw")
tk.Button(master = root, text = "Next", command = drawsnowflake).pack(side=tk.LEFT, anchor="sw")

tk.mainloop()
root.mainloop()


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

import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
REQUIREMENTS = open(os.path.join(os.path.dirname(__file__), 'requirements.txt')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-hooks',
    version='0.2.0-pre',
    description='A plugin system for django.',
    author='Esteban Castro Borsani',
    author_email='ecastroborsani@gmail.com',
    long_description=README,
    url='https://github.com/nitely/django-hooks',
    packages=[
        'hooks',
        'hooks.templatetags',
    ],
    include_package_data=True,
    zip_safe=False,
    install_requires=REQUIREMENTS,
    license='MIT License',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


import queue, time
import threading
'''This is a basic reference script that shows how to use Queues & different types of Queues in python
   There are basically 3 types of Queues :-
   1. FIFO (default)
   2. LIFO
   3. Priority
'''

# q = queue.Queue()
# q.put(5)

# print(q.get()) # to fetch the items in the Queue

# print(q.empty()) # once we fetch the object from the queue the item is removed automatically from the queue

# for i in range(1,5):
#     print('inserting inside queue ....{} \n'.format(i))
#     q.put(i)

# while not q.empty():
#     '''Always use q.empty() otherwise if you are using single thread only then if there are no items in the queue then your queue will
#        get freezed and it will wait till next items comes in the queue. So , ALWAYS USE DIFFERENT THEREADS TO ACCESS THE 1 QUEUE
#     '''
#     print(q.get(), end=' ')

def putting_thread(q):
    while True:
        print('Starting thread \n')
        time.sleep(5)
        q.put(5)
        print('put something \n')

q = queue.Queue()
t = threading.Thread(target=putting_thread, args=(q,), daemon=True) # make it a daemon thread so main func finished automatically daemon thread will also finish
t.start()

q.put(55)
print('first item gotten \n')
# print(q.get())
while True:
    print(q.get())
    print('finished')