from __future__ import print_function
from . import operatornames
from . import taskdmrg
import numpy as np
import os
from scipy.interpolate import interp1d
from . import multioperator
from .edtk import timedependent as tded

def evolution_DC(self,mode="DMRG",**kwargs):
    if mode=="DMRG":  return evolution_dmrg_DC(self,**kwargs)
    if mode=="ED":
        edobj = self.get_ED_obj() # get the ED object
        return tded.evolution_DC(edobj,h=self.hamiltonian,**kwargs)

def evolution_dmrg_DC(self,name="XX",nt=10000,dt=0.1,restart=True,**kwargs):
    name = operatornames.str2MO(self,name,**kwargs)
    if self.fit_td: fittd = "true"
    else: fittd = "false"
    if self.tevol_custom_exp: tevol_custom_exp = "true"
    else: tevol_custom_exp = "false"
    fittd = "true"
    task = {"time_evolution":"true",
            "tevol_nt":str(nt),
            "tevol_fit":fittd,
            "tevol_custom_exp":tevol_custom_exp,
            "tevol_dt":str(dt),
            }
    self.task = task # override tasks
    if restart: # restart the calculation
      self.execute(lambda: os.system("cp psi_GS.mps psi_time_evolution.mps"))
    name[0] = name[0].get_dagger()
    self.execute(lambda: name[0].write(name="dc_multioperator_i.in"))
    self.execute(lambda: name[1].write(name="dc_multioperator_j.in"))
    self.execute( lambda : taskdmrg.write_tasks(self)) # write tasks
    self.execute( lambda : self.run()) # run calculation
    cs = self.get_file("TIME_EVOLUTION.OUT").transpose() # time evolution
    ts = np.array([dt*ii for ii in range(nt)]) # times
    return ts,cs[0].real-1j*cs[1] # return

def evolve_and_measure(self,mode="DMRG",**kwargs):
    """Evolve and measure"""
    if mode=="DMRG": return evolve_and_measure_dmrg(self,**kwargs)
    elif mode=="ED":
        edobj = self.get_ED_obj() # get the ED object
        h = self.hamiltonian # get the ED object
        return tded.evolve_and_measure(edobj,h,**kwargs)

def evolve_and_measure_dmrg(self,operator=None,nt=1000,h=None,
        dt=1e-2,wf=None,**kwargs):
    if h is None: h = self.hamiltonian # Hamiltonian
    if self.fit_td: fittd = "true"
    else: fittd = "false"
    if self.tevol_custom_exp: tevol_custom_exp = "true"
    else: tevol_custom_exp = "false"
    fittd = "true"
    task = {"evolution_measure":"true",
            "tevol_nt":str(int(nt)),
            "tevol_fit":fittd,
            "tevol_custom_exp":tevol_custom_exp,
            "tevol_dt":str(dt),
            }
    self.task = task # override tasks
    if wf is None: wf = self.wf0 # get ground state
    wf.write(name="psi_evolve_and_measure.mps") # copy wavefunction
    self.execute(lambda: h.write(name="hamiltonian.in"))
    self.execute(lambda: operator.write(name="time_evolution_multioperator.in"))
    self.execute( lambda : taskdmrg.write_tasks(self)) # write tasks
    self.execute( lambda : self.run()) # run calculation
    cs = self.get_file("TIME_EVOLUTION.OUT").transpose() # time evolution
    ts = np.array([dt*ii for ii in range(int(nt))]) # times
    return ts,cs[0].real-1j*cs[1] # return

def evolution_ABA(self,A=None,B=None,mode="DMRG",wf=None,**kwargs):
    """Apply an operator, evolve and measure"""
    if A is None: A = multioperator.identity()
    if B is None: B = multioperator.identity()
    if mode=="DMRG":
        if wf is None: wf = self.get_gs() # get ground state
        wfA = A*wf # apply the operator
        return evolve_and_measure_dmrg(self,wf=wfA,operator=B,**kwargs)
    elif mode=="ED":
        edobj = self.get_ED_obj() # get the ED object
        return tded.evolution_ABA(edobj,h=self.hamiltonian,A=A,B=B,wf=wf,
                **kwargs)

def dynamical_correlator(self,window=[-1,10],es=None,dt=0.1,
        nt=None,factor=1,delta=5e-2,**kwargs):
    """Compute a certain dynamical correlator"""
    self.get_gs() # get the ground state
    if nt is None: nt=int(100/delta/dt)
    (ts,cs) = evolution_DC(self,dt=dt,nt=nt,**kwargs) # get correlator
#    cs = cs*np.exp(-1j*self.e0*ts) # factor out the phase
    # interpolate the time evolution
    ftr = interp1d(ts,cs.real,fill_value=0.0,bounds_error=False)
    fti = interp1d(ts,cs.imag,fill_value=0.0,bounds_error=False)
    # interpolate the time evolution
    tnew = np.linspace(np.min(ts),np.max(ts),len(ts)*factor) # ten times
    cnew = ftr(tnew) + 1j*fti(tnew)
    ts = tnew.copy() # overwrite
    cs = cnew.copy() # overwrite
    dtnew = dt/factor
    # do the fourier transform
    ss = np.fft.fft(cs) # fourier transform
    ws = np.fft.fftfreq(len(cs),d=dtnew)*2.*np.pi # fourier frequencies
    fr = interp1d(ws,ss.real,fill_value=0.0,bounds_error=False)
    fi = interp1d(ws,ss.imag,fill_value=0.0,bounds_error=False)
    if es is None:
        es = np.linspace(window[0],window[1],800)
    gr = fr(es)+ 1j*fi(es) # advanced
    ga = np.conjugate(gr) # retarded
#    gp = fr(es) - fr(-es) + 1j*fi(es) + 1j*fi(-es)
    return (es,gr/np.sqrt(nt))

def generic_evolution(H,wf,normalize=True,dt=1e-2,nt=100,A=None):
    """Perform a time evolution and project onto itself,
    assuming U = e^tH """
    wf0 = wf.copy() # copy wavefunction
    wf1 = wf.copy() # copy wavefunction
    out = []
    for i in range(int(nt)): # loop
        wf1 = wf1 + dt*H*wf1
        if normalize:  wf1 = wf1*(1./np.sqrt(wf1.dot(wf1)))
  #      out.append(wf0.dot(wf1)) # compute
        out.append(wf1.dot(A*wf1)) # compute
        print(i)
    return np.array(range(int(nt)))*dt,np.array(out) # retunr result


import sys
input = sys.stdin.readline

N = [i for i in range(1, int(input())+1)]
ans = []
cnt = 1
while N:
    if cnt % 2 == 0:
        N.append(N[0])
        N.pop(0)
    else:
        ans.append(N[0])
        N.pop(0)
    cnt += 1

print(' '.join(map(str, ans)))


# %%
# draw graoh nx
import pandas as pd
from utils import Pipeline
import sys
import networkx as nx
from igraph import Graph

import datetime
file_tweets = '/Users/alessiogandelli/dev/internship/tweets-to-topic-network/data/toy.json'
file_user = '/Users/alessiogandelli/dev/internship/tweets-to-topic-network/data/toy_users.json'

# create toy dataframe
#
#######################

df = pd.DataFrame()
df.index = [1,2,3,4,5,6,7,8,9,10,11]
df['author'] = ['a','c','d','d','e','e','e','f','f','a','c']
df['author_name'] = ['anzio','crizio','danzio','danzio','enzio','enzio','enzio','fanzio','fanzio','anzio','crizio']
df['text'] = 'testo'
df['date'] = str(datetime.datetime.now())
df['referenced_type'] = [None, 'retweeted', None, None, 'retweeted', None, None, 'retweeted', 'retweeted', None, 'retweeted']
df['referenced_id'] = [None, 1, None, None, 4, None, None, 5, 7, None, 10]
df['mentions_id']= [['b'], [], [], ['b'], [], [], ['f'], [], [], [], []]
df['mentions_name']= [['bonzo'], [], [], ['bonzo'], [], [], ['fanzio'], [], [], [], []]
df['topic'] = [1,1,2,2,2,1,1,2,1,1,1]
df['referenced_id'] = df['referenced_id'].astype('Int64')
p = Pipeline(file_tweets, file_user)

g,a,b = p.create_network(df, 'test')
# %%

def plot_graph(g):
# draw with node color based on bipartite attribute
    color = ['#3498eb' if g.nodes[i]['bipartite']==0 else '#e5eb34' for i in g.nodes]

    color = []
    for i in g.nodes:
        if g.nodes[i]['bipartite']==0:
            color.append('#3498eb')
        else:
            print(g.nodes[i])
            if g.nodes[i]['topics']==1:
                color.append('#e5eb34')
            else:
                color.append('#eb3434')

    size = [600 if g.nodes[i]['bipartite']==0 else 200 for i in g.nodes]

    pos = nx.spring_layout(g, k=4)
    pos = nx.planar_layout(g)
    #pos = nx.shell_layout(g)
    nx.draw(g, with_labels=True,  node_color = color, width = 0.1, pos=pos, node_size=size)

plot_graph(g)

# %%
import uunet.multinet as ml
import pandas as pd

# get multiplayer network
path = '/Users/alessiogandelli/dev/internship/tweets-to-topic-network/data/networks/toy_test_ml.gml'
n = ml.read(path)
# %%
ml.plot(n, vertex_labels_bbox = {"boxstyle":'round4', "fc":'white'})
# %%


import os
import numpy as np
import healpy as hp
import datetime

from gbpipe import gbsim

def doit():
    t1 = "2020-09-01T00:00:00"
    #t2 = "2019-09-01T00:20:00" # 20 min for test
    t2 = "2020-09-04T00:00:00" # 1 day
    dtsec = 600   # seconds per file
    fsample = 1000  # sampling rate (sample per second)

    #cmbname   = "/home/klee_ext/kmlee/maps/cmb_rseed42_0_5deg.fits"
    mappath   = "/home/kmlee/cmb/forecast/maps/"
    #cmbname   = mappath + "cmb_toy.fits"
    fg145name = mappath + "fg_145_nside1024_fwhm1_equ.fits"
    fg220name = mappath + "fg_220_nside1024_fwhm1_equ.fits"
    dt = datetime.datetime.now()
    nproc = int(os.environ['OMP_NUM_THREADS'])
    nside = 1024
    nside_hitmap = 1024

    outpath = "/home/kmlee/cmb/data02/tod/GBsim_3day_test".format(dt.strftime("%Y-%m-%d"))

    """
    gbsim.GBsim_noise_long(t1, t2, dtsec=dtsec,
        fsample=fsample,
        wnl=310e-6, fknee=0.1, alpha=1, rseed=0,
        module_id=None, fprefix="GBtod_noise",
        outpath=outpath, nproc=nproc)

    gbsim.GBsim_noise_long(t1, t2, dtsec=dtsec,
        fsample=fsample,
        wnl=310e-6, fknee=0.0, alpha=1, rseed=0,
        module_id=None, fprefix="GBtod_wnoise",
        outpath=outpath, nproc=nproc)
    """

    """
    gbsim.GBsim_hpc_parallel_time(t1, t2, dtsec=dtsec,
        fsample=fsample, mapname=cmbname, module_id=(0, 1, 2, 3, 4, 5, 6),
        fprefix="GBtod_cmb", outpath=outpath,
        nside_hitmap=nside_hitmap, nproc=nproc)
    """

    gbsim.GBsim_hpc_parallel_time(t1, t2, dtsec=dtsec,
        fsample=fsample, mapname=fg145name, module_id=(1, 2, 3, 4, 5, 6),
        fprefix="fg145", outpath=outpath,
        nside=nside, nside_hitmap=False, nproc=nproc)

    gbsim.GBsim_hpc_parallel_time(t1, t2, dtsec=dtsec,
        fsample=fsample, mapname=fg220name, module_id=0,
        fprefix="fg220", outpath=outpath,
        nside=nside, nside_hitmap=False, nproc=nproc)

    return

if __name__ == "__main__":
    doit()


#! /usr/bin/python
# charPictureGrid.py - Draws the picture with text characters in a list

def tMatrix(matrix):
    newMatrix = []
    for y in range(len(matrix[0])):
        r = []
        for x in range(len(matrix)):
            r.append(matrix[x][y])
        newMatrix.append(r)
    return newMatrix

def printMatrix(matrix):
    r = []
    for i in range(len(matrix)):
        r.append(''.join(matrix[i]))
    newMatrix = '\n'.join(r)
    print(newMatrix)

gridList = [['a0', 'a1', 'a2', 'a3'], ['b0', 'b1', 'b2', 'b3'], ['c0', 'c1', 'c2', 'c3'], ['d0', 'd1', 'd2', 'd3']]
grid = tMatrix(gridList)
printMatrix(grid)


import numpy as np
from matplotlib import pyplot as plt
from astropy.io import fits as p
from sklearn.mixture import GaussianMixture as GMM
from sklearn.neighbors import KernelDensity as KDE
from itertools import combinations as comb

catalog_name="../Catalogues/Coma_matched_compact_test.fits"
#catalog_name="../Catalogues/Coma_matched_compact.fits"
c_hdu=p.open(catalog_name)
cdata=c_hdu[1].data

def gauss_function(x, amp, x0, sigma):
    return amp * np.exp(-(x - x0) ** 2. / (2. * sigma ** 2.))

plt.clf()
filters="ugiH"

combs=[cc for cc in comb(filters,2)]
aics=[]
bics=[]
ncompsmax=2
for nc in range(2,ncompsmax+1):
	gmm = GMM(n_components=nc, covariance_type="full", tol=0.001)
	ax1=plt.subplot2grid((3,3),(0,0))
	ax2=plt.subplot2grid((3,3),(0,1))
	ax3=plt.subplot2grid((3,3),(0,2))
	ax4=plt.subplot2grid((3,3),(1,1))
	ax5=plt.subplot2grid((3,3),(1,2))
	ax6=plt.subplot2grid((3,3),(2,2))
	axes=[ax1,ax2,ax3,ax4,ax5,ax6]
	for i,c in enumerate(combs):
		colour=cdata[c[0]]-cdata[c[1]]
		gmm=gmm.fit(np.expand_dims(colour,1))
		gmm_x=np.sort(colour)
		gmm_y=np.exp(gmm.score_samples(gmm_x.reshape(-1,1)))
		kde=KDE(bandwidth=(gmm_x[-1]-gmm_x[0])/30,kernel="epanechnikov")
		kde.fit(colour[:,np.newaxis])
		#axes[i].hist(colour, bins=np.linspace(gmm_x[0],gmm_x[-1],20), normed=True, alpha=0.5, color="blue")
		axes[i].fill(gmm_x,np.exp(kde.score_samples(gmm_x[:,np.newaxis])),ec="blue",fc="blue",alpha=.5)
		axes[i].plot(gmm_x, gmm_y, color="black", lw=2, label="GMM")
		axes[i].set_xlabel(c[0]+" - "+c[1],weight="heavy")
		for m, cc, w in zip(gmm.means_.ravel(), gmm.covariances_.ravel(), gmm.weights_.ravel()):
			gauss = gauss_function(x=gmm_x, amp=1, x0=m, sigma=np.sqrt(cc))
			gauss = gauss / np.trapz(gauss, gmm_x) * w
			axes[i].plot(gmm_x,gauss,color="grey")
		bic=gmm.bic(np.expand_dims(colour,1))
		aic=gmm.aic(np.expand_dims(colour,1))
		aics.append(aic); bics.append(bic)
		#axes[i].set_title("BIC,AIC = "+str(bic)+", "+str(aic),fontsize=10)

	plt.show()
plt.clf()
aics=np.reshape(aics,(ncompsmax,6))
bics=np.reshape(bics,(ncompsmax,6))
fig=plt.figure()
for i in range(6):
	fig.add_subplot(2,3,i+1)
	plt.plot(range(1,ncompsmax+1),bics[:,i],"red",label="BIC")
	plt.plot(range(1,ncompsmax+1),bics[:,i],"ro")
	plt.plot(range(1,ncompsmax+1),aics[:,i],"blue",label="AIC")
	plt.plot(range(1,ncompsmax+1),aics[:,i],"bo")
	plt.title(str(combs[i][0]) + " - "+str(combs[i][1]))
	plt.yscale("symlog")
	plt.legend()
plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from refinery.lib.mscrypto import CRYPTOKEY
from refinery.units import Unit

class kblob(Unit):
    """
    Extracts a key from a Microsoft Crypto API BLOB structure.
    """

    def process(self, data):
        blob = CRYPTOKEY(data)
        try:
            return self.labelled(
                bytes(blob.key),
                type=blob.header.type.name,
                algorithm=blob.header.algorithm.name
            )
        except AttributeError as A:
            raise ValueError(F'unable to derive key from {blob.header.type!s}') from A


import os
import time
from tqdm import tqdm

import subprocess
import numpy as np
import cv2
import filterpy

import torch
import super_gradients as sg
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = (20, 10)
from super_gradients.training import models

model = models.get("yolo_nas_s", pretrained_weights="coco").cuda()
model.eval();
video_path = './test1.mp4'

cap = cv2.VideoCapture(video_path)
if (cap.isOpened() == False):
    print("Error opening video file")

while(cap.isOpened()):

  # read each video frame
  ret, frame = cap.read()
  frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

  break

cap.release()
del cap

from super_gradients.training.models.detection_models.customizable_detector import CustomizableDetector
from super_gradients.training.pipelines.pipelines import DetectionPipeline

# make sure to set IOU and confidence in the pipeline constructor
pipeline = DetectionPipeline(
            model=model,
            image_processor=model._image_processor,
            post_prediction_callback=model.get_post_prediction_callback(iou=0.25, conf=0.30),
            class_names=model._class_names,
        )

def get_prediction(image_in, pipeline):
  # Preprocess
  preprocessed_image, processing_metadata = pipeline.image_processor.preprocess_image(image=image_in.copy())

  # Predict
  with torch.no_grad():
      torch_input = torch.Tensor(preprocessed_image).unsqueeze(0).to('cuda')
      model_output = model(torch_input)
      prediction = pipeline._decode_model_output(model_output, model_input=torch_input)

  # Postprocess
  return pipeline.image_processor.postprocess_predictions(predictions=prediction[0], metadata=processing_metadata)

from ocsort import ocsort

tracker = ocsort.OCSort(det_thresh=0.25)

import colorsys

def get_color(number):
    """ Converts an integer number to a color """
    # change these however you want to
    hue = number*30 % 180
    saturation = number*103 % 256
    value = number*50 % 256

    # expects normalized values
    color = colorsys.hsv_to_rgb(hue/179, saturation/255, value/255)

    return [int(c*255) for c in color]

# get frame info for tracker and video saving
h, w = (720, 1280)
h2, w2 = h//2, w//2
# h2, w2 = 640, 640 # this degrades performance

# OCSORT automatically rescales bboxes if we inference with a diff img size
img_info = (h, w)
img_size = (h2, w2)

tracker = ocsort.OCSort(det_thresh=0.60, max_age=10, min_hits=10)

cap = cv2.VideoCapture(video_path)

if (cap.isOpened() == False):
    print("Error opening video file")

frames = []
i = 0
counter, fps, elapsed = 0, 0, 0
start_time = time.perf_counter()
track_ids_op = []
track_bbox_op = []
track_hits_op = []
while(cap.isOpened()):

  # read each video frame (read time is about 0.006 sec)
  ret, frame = cap.read()

  if ret == True:

    # read image and resize by half for inference
    og_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame = cv2.resize(og_frame,
                       (w2, h2), interpolation=cv2.INTER_LINEAR)

    # perform inference on small frame and get (x1, y1, x2, y2, confidence)
    pred = get_prediction(frame, pipeline)
    xyxyc = np.hstack((pred.bboxes_xyxy,
                      np.c_[pred.confidence]))

    # update tracker
    tracks = tracker.update(xyxyc, img_info, img_size)

    # draw tracks on frame
    for track in tracker.trackers:

        track_id = track.id
        hits = track.hits
        color = get_color(track_id*15)
        x1,y1,x2,y2 = np.round(track.get_state()).astype(int).squeeze()
        if (track_id not in track_ids_op) and (hits>10):

            crop_img = og_frame[y1:y2, x1:x2].copy()
            if(crop_img.shape[0]<32 or crop_img.shape[1]<32):
                print(';dibg')
            else:
                track_ids_op.append(track_id)
                track_hits_op.append(hits)
                print(crop_img.shape)
                filename = './images/' + str(track_id) + '.jpg'
                crop_img = cv2.cvtColor(crop_img, cv2.COLOR_RGB2BGR)
                cv2.imwrite(filename , crop_img)
        else:
            if(hits>10):
                track_hits_op[track_ids_op.index(track_id)] = hits

        cv2.rectangle(og_frame, (x1,y1),(x2,y2), color, 2)
        cv2.putText(og_frame,
                  f"{track_id}-{hits}",
                  (x1+10,y1-5),
                  cv2.FONT_HERSHEY_SIMPLEX,
                  0.5,
                  color,
                  1,
                  cv2.LINE_AA)

    # update FPS and place on frame
    current_time = time.perf_counter()
    elapsed = (current_time - start_time)
    counter += 1
    if elapsed > 1:
      fps = counter / elapsed;
      counter = 0;
      start_time = current_time;

    cv2.putText(og_frame,
                f"FPS: {np.round(fps, 2)}",
                (10,h - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                1,
                (255,255,255),
                2,
                cv2.LINE_AA)

    # append to list
    frames.append(og_frame)

  # Break the loop
  else:
    break

# release video capture object
cap.release()
del cap

video_savepath = 'output_video.mp4'
from moviepy.editor import VideoFileClip

videoclip = VideoFileClip(video_path)
video_fps = videoclip.fps

out = cv2.VideoWriter(video_savepath,
                      cv2.VideoWriter_fourcc(*'mp4v'),
                      video_fps,
                      (w, h))

for frame in frames:
    out.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))

out.release()
del out

with open('track_ids.txt', 'w') as f:
    for tio in track_ids_op:
        f.write(str(tio)+"\n")
with open('track_hits.txt', 'w') as f:
    for tho in track_hits_op:
        f.write(str(tho)+"\n")

#
p1=subprocess.Popen(["python","gui.py"],shell=True)
p1.wait()


from pygame.sprite import Sprite
import pygame

class Explosion(Sprite):
    """
    Create a new explosion animation

    :param int duration: number of ticks for which to display the explosion animation
    :param images: array of animation frames
    :type images: [:py:class:`pygame.Surface`]
    """

    def __init__(self, duration, images, *group):
        Sprite.__init__(self,*group)
        #: number of ticks for animation
        self.duration = duration

        #: size of explosion sprite
        self.size = 48,48

        #: rectangle containing the surface of the sprite
        self.rect = pygame.Rect((0,0),self.size)

        #: Animation frames passed from `images`
        self.images = images

        #: Current frame step in animation
        self.current_frame = 0

        #: Current displayed image
        self.image = self.images[self.current_frame]

    def update_frame(self):
        """
        Updates :py:attr:`image` to the next frame of the animation, looping around once the final frame is reached.
        """

        self.current_frame += 1
        if self.current_frame >= len(self.images):
            self.current_frame = 0
        self.image = self.images[self.current_frame]

    def get_draw(self):
        """
        Gets the current animation image if duration is non-zero.

        :returns: :py:attr:`image` or `None`
        :rtype: :py:class:`pygame.Surface`
        """

        if self.duration == 0:
            return None
        self.update_frame()
        self.duration -= 1
        return self.image


"""
Amicable numbers

Problem 21

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000."""

def find_divisors(number):
    #note, the result of the smallest divisor will also be the max
    divisor_candiate = 2
    max_value = number
    i = divisor_candiate
    divisor_list = [1]
    while i < max_value:
        a,b = divmod(number,i)
        if b == 0:
            divisor_list.append(i)
            divisor_list.append(a)
            max_value = a
        i += 1

    return divisor_list

def is_amicable(number):
    sum_test = sum(find_divisors(number))
    if sum_test != number and number == sum(find_divisors(sum_test)):
        return True
    else:
        return False

def solution():
    solution = 0
    for x in range(1,10000):
        if is_amicable(x):
            solution += x

    print("The sum of all the amicable numbers under 10000 is",solution)

if __name__ == '__main__':
    a = find_divisors(220)
    a.sort()
    print(a,is_amicable(220))
    solution()


# Number Guessing Game

import random

print("------------------------------------")
print("Welcome to the Number Guessing Game!")
print("------------------------------------")
print()

running = True
while running:
    number = random.randint(1, 10)

    guess = input("Guess a number between 1 and 10: ")
    print()

    if int(guess) == number:
        print("Congratulations! You guessed the correct number!")
        guess2 = 0
    elif int(guess) < number:
        guess2 = input("Your guess was too low, try again: ")
    elif int(guess) > number:
        guess2 = input("Your guess was too high, try again: ")
    else:
        guess2 = 0

    if int(guess2) == number and int(guess2) != 0:
        print("Congratulations! You guessed the correct number!")
    else:
        print("Sorry. Better luck next time. The number was %d." % number)

    print()
    again = input("Do you want to play again? (Type 'yes' or 'no') ")
    again = again.lower()
    if again != "yes":
        running = False
    else:
        print()


#Domnika Popov
#Home scene file
#10/10/19

import lsystem as ls
import shapes as s
import turtle_interpreter as ti
import tree as t

def main():
	'''creates the home scene by calling shape functions at different line styles'''
	terp = ti.TurtleInterpreter()

	r = s.Rectangle(50)
	r.setStyle('jitter3')
	r.setJitter(3)
	r.setColor('lawn green')
	r.draw(-400,-400, 1.5, 90)

	r = s.Rectangle(50)
	r.setStyle('jitter3')
	r.setJitter(3)
	r.setColor('light sky blue')
	r.draw(-400,0, 1.5, 90)

	r = s.Rectangle(20)
	r.setStyle('jitter')
	r.setJitter(3)
	r.setColor('light slate blue')
	r.draw(-250,-180, 6, 90)

	sq = s.Square(180)
	sq.setStyle('jitter')
	sq.setJitter(3)
	sq.setColor('light slate blue')
	sq.draw(-250,120)

	rt = s.Rectangle(20)
	rt.setStyle('jitter')
	rt.setJitter(2)
	rt.setColor('grey')
	rt.draw(-240,210)

	tr = s.Triangle(45)
	tr.setStyle('jitter')
	tr.setJitter(3)
	tr.setColor('dark slate blue')
	tr.draw(-250,120, 4, 60)

	rt = s.Rectangle(40)
	rt.setStyle('jitter')
	rt.setJitter(2)
	rt.setColor('dark slate blue')
	rt.draw(-220,-20)

	sq = s.Square(80)
	sq.setStyle('jitter')
	sq.setJitter(3)
	sq.setColor('slate blue')
	sq.draw(-220,100)

	sq = s.Square(90)
	sq.setStyle('jitter')
	sq.setJitter(3)
	sq.setColor('slate blue')
	sq.draw(100,30)

	sq = s.Square(90)
	sq.setStyle('jitter')
	sq.setJitter(3)
	sq.setColor('slate blue')
	sq.draw(-40,30)

	t.Tree1 = t.Tree(distance = 10, color = (0.1, 0.5, 0.3), filename = 'systemDL.txt')
	t.Tree1.draw(290,-90 )
	t.Tree2 = t.Tree(distance = 15, color = (0.1, 0.5, 0.3), filename = 'systemFL.txt')
	t.Tree2.draw(-320,-90)

	terp.hold()

if __name__ == "__main__":
	main()


from .model_cache import CachedModel
from django.db.models.signals import post_save, pre_delete, post_migrate
from django.core.cache import cache
from django.dispatch import receiver
from .model_cache import cache_key, clear_cache_sig

def model_pre_delete(sender, instance, **kwargs):
    instance.delete_cache()

def model_saved(sender, instance, created, **kwargs):
    instance.delete_cache()

for subclass in CachedModel.__subclasses__():
    post_save.connect(model_saved, subclass)
    pre_delete.connect(model_pre_delete, subclass)
    post_migrate.connect(model_saved, subclass)

@receiver(clear_cache_sig)
def clear_cache(sender, **kwargs):
    filter_key = cache_key(sender, kwargs['key'])
    cache.delete(filter_key)


from __future__ import annotations

import abc
import colorsys
import math
import typing as ta
from contextlib import contextmanager

import bpy
from bl_math import clamp
from mathutils import Matrix, Vector

if ta.TYPE_CHECKING:
    from . import Color, ColorComponent

class Transform:
    def __init__(
        self,
        matrix: ta.Optional[Matrix] = None,
        color: Color = (0.0, 0.0, 1.0, 1.0),
    ):
        self._matrix = matrix or Matrix()
        self._color = color

    @contextmanager
    def scale(
        self,
        x: ta.Optional[float] = None,
        y: ta.Optional[float] = None,
        z: ta.Optional[float] = None,
        xyz: float = 1.0,
    ):
        """Scale specified dimension. xyz is a shortcut for scaling all
        dimensions equally
        """
        matrix = self._matrix
        self._matrix = self._matrix @ Matrix.Diagonal(
            (x or xyz, y or xyz, z or xyz, 1.0)
        )
        yield
        self._matrix = matrix

    @contextmanager
    def translate(self, x: float = 0.0, y: float = 0.0, z: float = 0.0):
        matrix = self._matrix
        self._matrix = self._matrix @ Matrix.Translation((x, y, z))
        yield
        self._matrix = matrix

    @contextmanager
    def rotate(self, angle: float, axis: ta.Union[ta.Literal["X", "Y", "Z"], Vector]):
        """Rotate angle radians around axis"""
        matrix = self._matrix
        self._matrix = self._matrix @ Matrix.Rotation(angle, 4, axis)
        yield
        self._matrix = matrix

    @property
    def matrix(self) -> Matrix:
        return self._matrix

    @property
    def color_rgba(self) -> Color:
        return hsva_to_rgba(self._color)

    @contextmanager
    def color(
        self,
        hue: ta.Optional[ColorComponent] = None,
        saturation: ta.Optional[ColorComponent] = None,
        value: ta.Optional[ColorComponent] = None,
        alpha: ta.Optional[ColorComponent] = None,
        color: ta.Optional[Color] = None,
    ):
        """Transform color

        If color is specified, it is used as the new base color
        hue increments the hue value, and wraps around.
        saturation, value and alpha are multipliers and clamp to 0..1
        """
        current_color = self._color
        base_color = color or self._color
        self._color = (
            base_color[0] if hue is None else math.modf(base_color[0] + hue)[0],
            base_color[1] if saturation is None else clamp(base_color[1] * saturation),
            base_color[2] if value is None else clamp(base_color[2] * value),
            base_color[3] if alpha is None else clamp(base_color[3] * alpha),
        )
        yield
        self._color = current_color

    def apply(self, transformer: Transformer):
        transformer.transform(self)

class Transformer(abc.ABC):
    """Base transformer, applies matrix but not color"""

    def transform(self, xfm: Transform):
        self.apply_matrix(xfm.matrix)
        self.apply_color(xfm.color_rgba)

    @abc.abstractmethod
    def apply_matrix(self, matrix: Matrix):
        """Apply transformation matrix to object"""

    def apply_color(self, color: Color):
        """Apply color to object"""
        pass

class ObjectTransformer(Transformer):
    def __init__(self, obj: bpy.types.Object):
        self._obj = obj

    @property
    def obj(self) -> bpy.types.Object:
        return self._obj

    def apply_matrix(self, matrix: Matrix):
        """Apply transformation matrix to object"""
        self.obj.matrix_world = matrix

def hsva_to_rgba(color: Color) -> Color:
    """Convert color from HSVA to RGBA"""
    return (*colorsys.hsv_to_rgb(*color[:3]), color[3])


import urllib.request
from bs4 import BeautifulSoup
import html
import json
import re
import time

### Season Info ###
seasonID = "F3C6D619-32F6-4C2A-8506-798D7493D668"
teamInfo = [[499, 23], [500, 22], [501, 44], [502, 43], [503, 42], [504, 74],
            [505, 73], [506, 89], [507, 135], [508, 153]]
teamDict = {"Hillegom BC 1": [499, 23],
            "Hillegom BC 2": [500, 22],
            "Hillegom BC 3": [501, 44],
            "Hillegom BC 4": [502, 43],
            "Hillegom BC 5": [503, 42],
            "Hillegom BC 6": [504, 74],
            "Hillegom BC 7": [505, 73],
            "Hillegom BC 8": [506, 89],
            "Hillegom BC 9": [507, 135],
            "Hillegom BC 10": [508, 153]}
#teamInfo = [[499, 23]]
### Season Info ###
Requests = 0

def get_webpage(link):
    """
    Takes as input a weblink link and returns
    a BeautifulSoup object.
    """
    req = urllib.request.urlopen(link)
    bytes = req.read()

    string = bytes.decode('utf8')
    req.close()

    global Requests
    Requests += 1
    return BeautifulSoup(string, 'html.parser')

def get_matches(soup):
    """
    Takes as input a BeautifulSoup object and Retrieves
    all matches found in the object in a dictionary.
    """

    # Get the rows containing the information
    rows = soup.table.findAll('tr')
    matches = []

    # For each row strip the important information.
    for row in rows[1:]:
        matches.append(strip_match_col(row))

    return {"matches": matches}

# Retrieves ranking from a soup.
def get_ranking(soup):
    """
    Takes as input a BeautifulSoup object and Retrieves
    the ranking found in the object in a dictionary.
    """

    # Find all rows that represent the ranking.
    rows = soup.find('table', {"class": "ruler"}).findAll('tr')
    division = " ".join(soup.findAll("div", {"class":"title"})[0].get_text().split()[:2])

    teamname = ""
    teamrank = ""
    ranking = []

    # Loop trough every row and strip the right information.
    for row in rows[1:]:
        r = strip_rank_col(row)
        ranking.append(r)

        if "hillegom" in r['team'].lower():
            teamname = prettify_teamname(r['team'])
            teamrank = r['rank']

    return {"division": division, "name": teamname, "table": ranking, 'teamrank': teamrank}

def strip_match_col(rows):
    """
    Takes as input a match row and Retrieves the information. Output
    is a dictionary which contains the information ordered.
    """

    time = rows.find('td', {"class":"plannedtime"}).get_text()
    home = lower_layout(rows.findAll('a', {"class":"teamname"})[0].get_text())
    away = lower_layout(rows.findAll('a', {"class":"teamname"})[1].get_text())

    # Retrieves location id
    location_link = rows.findAll('a')[2]['href']
    locID = 0

    # Because comments can screw up the format of the match row,
    # there are two possible situations.
    try:
        regexl = re.search("lid=[\d]+", str(location_link))
        locID = regexl.group().split("=")[-1]
    except:
        location_link = rows.findAll('a')[-2]['href']
        regexl = re.search("lid=[\d]+", str(location_link))
        locID = regexl.group().split("=")[-1]

    # Retrieves game id
    regex = re.search("match=[\d]+", str(rows))
    gameID = regex.group().split("=")[-1]

    # Tries to find a score, if there ain't any, keep it empty.
    try:
        score = rows.find('span', {"class":"score"}).get_text()
    except:
        score = ""

    return {"time": time, "home": home,"away": away,
            "score": score,"locationid": locID, "gameid":gameID}

def strip_rank_col(rows):
    """
    Takes as input a rank row and Retrieves the information. Output
    is a dictionary which contains the information ordered.
    """
    rank = rows.find('td', {"class":"standingsrank"}).get_text()
    team = lower_layout(rows.find('a').get_text())
    scores = rows.findAll('td', {"align":"center"})
    points = scores[0].get_text()
    played = scores[1].get_text()

    return {"rank": rank,"team": team,"points": points,"played": played}

def get_players(soup):
    """
    Takes soup of a player page as input and gives a list
    of surnames as output.
    (teamplayers.aspx)
    """
    players = soup.table.tr.findAll("tr")
    names = []

    for player in players:

        # Gets basic info for every person in a list
        info = player.get_text(" ").split(",")[-1].split(" ")[1:-1]

        # Discard player if not a regular player
        if info[-1] == "Ja":

            # Retrieve only the surname.
            name = info[0]
            names.append(name)

    return {"players": ", ".join(names)}

def get_games(json, team):
    """
    Takes as input json matches and teamname.
    Outputs all the home and away games from
    the given team.
    """
    result = []

    for dictionary in json['matches']:
        if team in dictionary["home"].lower() or team in dictionary["away"].lower():
            result.append(dictionary)

    return result

def get_last_game(json):
    """
    Takes as input json matches. Outputs the information
    from the last game.
    """
    result = []

    for dictionary in get_games(json, "hillegom"):
        if dictionary["score"] != "":

            # Remove teamnumber
            dictionary["home"] = teamname_only(dictionary["home"])
            dictionary["away"] = teamname_only(dictionary["away"])

            result.append(dictionary)

    return result[-1]

def next_x_games(json, x):
    result = []

    for dictionary in json['matches']:
        if dictionary["score"] == "":

            # Remove teamnumber
            dictionary["home"] = teamname_only(dictionary["home"])
            dictionary["away"] = teamname_only(dictionary["away"])

            result.append(dictionary)

    return result[:x]

def get_next_game(json):
    """
    Takes as input json matches. Outputs the information
    from the next game.
    """
    result = []

    for dictionary in get_games(json, "hillegom"):
        if dictionary["score"] == "":

            # Remove teamnumber
            dictionary["home"] = teamname_only(dictionary["home"])
            dictionary["away"] = teamname_only(dictionary["away"])

            return dictionary

def get_game_info(soup):
    s = soup.find("table", {"class":"ruler matches"}).findAll("tbody")
    games = []

    for x in s[0]:

        # Ignore whitespaces
        if len(x) > 2:

            # Make temporary list of information
            temp = []

            # Get every game played in the match
            for y in x.findAll("td"):
                temp.append(y.get_text())

            # Process the temp list. Make diffence between double and single.
            if "D" in temp[0]:
                game = [temp[0]] + temp[2:4] + temp[-3:]
            else:
                game = [temp[0], temp[2]] + temp[-2:]

            # Calculate winner per match
            try:
                game.append(who_wins(temp[-1]))
            except:
                game.append("undecided")

            games.append(game)
    return games

def who_wins(points):
    """
    Takes as input a string containing sets. Outputs home if
    the left side wins and away if the right side wins.
    """
    games = points.split(" ")

    if int(games[-1].split("-")[0]) > int(games[-1].split("-")[1]):
        return "home"
    else:
        return "away"

def lower_layout(string):
    """
    Takes as input an uppercase string and returns a string with
    only the first letter in uppercase.

    EXAMPLE -> Example.
    """
    end = string[1:].lower()
    return string[0] + end

def teamname_only(string):
    """
    Takes as input a full teamname and returns only the
    base.

    Team BC 5 -> Team.
    """
    return string.split(" ")[0]

def prettify_teamname(string):
    """
    Team bc 7 -> Team BC 7.
    """
    spl = string.split(" ")
    return spl[0] + " " + spl[1].upper() + " " + spl[2]

def match(team):
    """
    Helper returns soup from given matchlink, calling
    the correct function.
    """
    link = craftLink("drawmatches", seasonID, "&draw=", team[1])
    soup = get_webpage(link)
    return get_matches(soup)

def rank(team):
    """
    Helper returns soup from given ranklink, calling
    the correct function.
    """
    link = craftLink("draw", seasonID, "&draw=", team[1])
    soup = get_webpage(link)
    return get_ranking(soup)

def players(team):
    """
    Helper returns soup from given playerlink, calling
    the correct function.
    """
    link = craftLink("teamplayers", seasonID, "&tid=", team[0])
    soup = get_webpage(link)
    return get_players(soup)

def game(gameid):
    """
    Takes as input a gameid, crafts a link and Retrieves
    information about the game in a list:
    [["MD", "player 1", "player 2", "enemy 1", "enemey 2", sets, winner]]
    """
    link = craftLink("teammatch", seasonID, "&match=", gameid)
    soup = get_webpage(link)
    return get_game_info(soup)

def craftLink(info, seasonID, compare, cid):
    """
    Takes as input the information, seasonid, compare text
    and id. Outputs a correct structured link.

    """
    baseLink = "https://badmintonnederland.toernooi.nl/sport/"
    link = baseLink + info + ".aspx?id=" + seasonID + compare + str(cid)
    return link

def createFile(name, string):
    """
    Takes as input filename and a jsonstring,
    outputs the json into the filename.
    """
    with open(name, 'w', encoding='utf8') as jsonfile:
        json.dump(string, jsonfile, ensure_ascii=False, indent=4)

# Todo
# Make the functions modulair.

def init_data(team):
    """
    Crafts dictionary with all information for one specific team.
    A team has the form of [teamID, drawID].
    """
    # Online requests
    ranking = rank(team)
    matches = match(team)
    members = players(team)

    # Other calculations
    next_match = {"next":get_next_game(matches)}
    upcoming = {"upcoming":next_x_games(matches, 4)}
    previous_match = get_last_game(matches)
    previous_match["games"] = game(previous_match["gameid"])
    last_match = {"last": previous_match}

    combined_dict = {**ranking, **next_match, **last_match, **upcoming, **members}

    return combined_dict

# Todo:
#  Lookup every team
#  Automically move json file to github
#  Daily checks.
#  What if no internet connection?
#  Next match based on time, not on where score = ''
#  Scrape ID's and draw automatically.

def start(teamInfo):
    """
    Launches the program, and scrapes all information for the
    given team in list teamInfo. It dumps the result into data.json.
    """
    start_time = time.clock()
    total = []

    for team in teamInfo:
        print("Busy with team: %s --" % team, round(time.clock() - start_time, 2), "seconds passed so far.")
        teamdata = init_data(team)
        total.append(teamdata)

    print("Dumping into json file..")
    data = ({"Teams": total})
    jstr = json.dumps(data, indent=4)
    createFile("data.json", data)

def information(query):
    result = []
    global teamDict

    for teamname, values in query.items():
        init = {}
        if 'match' in values:
            ranking = rank(teamDict[teamname])
            matches = match(teamDict[teamname])

            # Calculations based on matches
            next_match = {"next":get_next_game(matches)}
            upcoming = {"upcoming":next_x_games(matches, 4)}

            # Only new information is possible if there has been played
            # a new game.
            if 'game' in values:
                previous_match = get_last_game(matches)

                previous_match["games"] = game(previous_match["gameid"])
                last_match = {"last": previous_match}

                init = {**init, **ranking, **next_match, **last_match, ** upcoming}
            else:
                init = {**init, **ranking, **next_match, **upcoming}

        if 'name' in values:
            members = players(teamDict[teamname])

            init = {**init, **members}

        result.append(init)
    return result

# Timing information
# start_time = time.clock()
# start(teamInfo)
# print("Finished in", round(time.clock() - start_time, 2), "seconds")
# print("In", Requests, "Requests")


import RPi.GPIO as GPIO
import time

#GPIO SETUP
sound = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(sound, GPIO.IN)

def callback(sound):
    if GPIO.input(sound):
        print("Sound Detected!")
    else:
        print("Sound Detected!")
    print(GPIO.input(sound))

# let us know when the pin goes HIGH or LOW
GPIO.add_event_detect(sound, GPIO.BOTH,callback, bouncetime=300)
# assign function to GPIO PIN, Run function on change
GPIO.add_event_callback(sound, callback)
##detect events
GPIO.event_detected(sound)

# infinite loop
while True:
    print(GPIO.event_detected(sound))
    time.sleep(1)


##For ordering a list into clusters of sequential values
##Serves as metaclass for specialized ordering functions

def successor (x,y):
    try:
        return y-x == 1
    except:
        return False

successor = (successor,)

def apply_all_funcs (value_tuple, funclist):

    """Returns True is any one of the functions
    in funclist returns True when applies to x and y
    """
    x = value_tuple[0][-1][-1]
    y = value_tuple[1]
    for f in funclist:
        if f(x,y):
            return True
    return False

class generic_orderer:

    """Orders integers.
       Specialize by specifying sortfunc and orderfuncs in
       derived class.
    """

    def __init__ (self,orderfuncs=successor,sortfunc=lambda x:x):

        if orderfuncs and isinstance(orderfuncs,(list,tuple,set)):
            self.orderfuncs = orderfuncs
        elif orderfuncs:
            self.orderfuncs = (orderfuncs,)
        self.sortfunc = sortfunc

        self.resultlist = []
        self.entrylist = []

    def is_sorted (self):

        if not isinstance(self.entrylist,(list,tuple)):
            self.entrylist = list(self.entrylist)
        for x in range(len(self.entrylist)-1):
            if not self.entrylist[x]<self.entrylist[x+1]:
                return False
        return True

    def order (self,entrylist=None):

        if entrylist:
            self.resultlist=[]
            self.entrylist = entrylist
        if not self.is_sorted():
            self.entrylist = sorted(self.entrylist,key=lambda x:self.sortfunc(x))

        for x in self.entrylist:
            if not self.resultlist:
                self.resultlist = [[x]]
            elif apply_all_funcs((self.resultlist,x),self.orderfuncs):
                self.resultlist[-1].append(x)
            else:
                self.resultlist.append([x])
        return self.resultlist

    def format (self,entrylist=None,breaker='; '):

        if entrylist:
            self.resultlist=[]
            self.order(entrylist)

        formattedlist = []
        for x in self.resultlist:
            if len(x)==1:
                formattedlist.append(str(x[0]))
            else:
                formattedlist.append(str(x[0])+'-'+str(x[-1]))

        return breaker.join(formattedlist)


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

import json
import os

import sys
import re
sys.path.append("../../../")

from KgAnswer import KgAnswer
from algorithm.kg_qa.config import NerConfig, SimConfig

if __name__ == '__main__':
    os.environ["CUDA_VISIBLE_DEVICES"] = "0"
    NER_MODEL_PATH = NerConfig.model_out
    SIM_MODEL_PATH = SimConfig.model_out
    es_host = "10.2.13.150"
    # es_host = "127.0.0.1"
    es_port = "9200"
    kg = KgAnswer(NER_MODEL_PATH, SIM_MODEL_PATH, es_host, es_port)

    sentence = "NBA姚明学校在哪个地方啊?"
    print("question : ", sentence)
    ans = kg.answer(sentence)
    print("answer : ", ans[2] + '的' + ans[1] + '是' + ans[0] + '。')

    sentence = "NBA姚明学校所属地区是?"
    print("question : ", sentence)
    ans = kg.answer(sentence)
    print("answer : ", ans[2] + '的' + ans[1] + '是' + ans[0] + '。')

    sentence = "任宪韶的毕业院校是?"
    print("question : ", sentence)
    ans = kg.answer(sentence)
    print("answer : ", ans[2] + '的' + ans[1] + '是' + ans[0] + '。')

    sentence = "巫山县疾病预防控制中心的机构职能是什么?"
    print("question : ", sentence)
    ans = kg.answer(sentence)
    print("answer : ", ans[2] + '的' + ans[1] + '是' + ans[0] + '。')

    # print(kg.answer("NBA姚明学校在哪个地方啊？"))
    # print(kg.answer("NBA姚明学校所属地区是？"))
    # print(kg.answer("任宪韶的毕业院校是？"))
    # sentence = "巫山县疾病预防控制中心的机构职能是什么?"
    # print(kg.answer(sentence))

    # out_f = open("./kgclue_predict.txt", "w", encoding='utf-8')
    # with open(r"C:\Users\11943\Documents\GitHub\KgCLUEbench\raw_data\kgClue\test.json", 'r', encoding='utf-8') as f:
    #     count_number = 0
    #     while True:
    #
    #         line = f.readline()
    #         if line:
    #
    #             line = json.loads(line)
    #             sentence = line["question"]
    #             best_answer, best_attribute, entitys = kg.answer(sentence)
    #             tmp = dict()
    #             tmp["id"] = count_number
    #             tmp["answer"] = str(entitys) + " ||| " + str(best_attribute) + " ||| " + str(best_answer)
    #             x = json.dumps(tmp, ensure_ascii=False)
    #             out_f.write(x+"\n")
    #             # print(x)
    #             count_number += 1
    #             # break
    #             # {"id": 0, "answer": "刘质平 ||| 师从 ||| 李叔同"}
    #
    #         else:
    #             break
    # out_f.close()


#---------------------------------------------
# Possible GET command:
# - /test_http_conn
# - /edge_state
# - /capture_state
# - /image
#---------------------------------------------

from src.param import param_edge
from src.connection.HTTPS import https_server_fct
from src.utils import parser_json
from src.utils import io

def manage_get(self):
    command = str(self.path)
    if(command == '/test_http_conn'):
        self.send_response(200)
    elif(command == '/edge_state'):
        manage_edge_state(self)
    elif(command == '/capture_state'):
        manage_capture_state(self)
    elif(command == '/network_state'):
        manage_perf_state(self)
    elif(command == '/image'):
        manage_image(self)
    else:
        print("[error] HTTP GET command not known")

def manage_edge_state(self):
    data = parser_json.load_state_utf8(param_edge.path_state_edge_1)
    https_server_fct.send_get_response(self, data, "application/json")

def manage_capture_state(self):
    data = parser_json.load_state_utf8(param_edge.path_state_capture)
    https_server_fct.send_get_response(self, data, "application/json")

def manage_perf_state(self):
    data = parser_json.load_state_utf8(param_edge.path_state_network)
    https_server_fct.send_get_response(self, data, "application/json")

def manage_image(self):
    if(io.is_file_exist(param_edge.path_image)):
        try:
            data = io.load_binary(param_edge.path_image)
            https_server_fct.send_get_response(self, data, "image/bmp")
        except:
            pass


import numpy as np
from multiprocessing import Pool
from .util import flatten_array, ensure_numpy, check_common_input, make_output
from pyrepseq import levenshtein_neighbors, hamming_neighbors

AMINO_ACIDS = 'ACDEFGHIKLMNPQRSTVWY'

def generate_neighbors(query, max_edits, is_hamming):
    neighbor_func = hamming_neighbors if is_hamming else levenshtein_neighbors
    ans = {query: 0}
    for edit_distance in range(1, max_edits+1):
        for seq in ans.copy():
            for new_seq in neighbor_func(seq):
                if new_seq not in ans:
                    ans[new_seq] = edit_distance
    return ans

def build_index(seqs):
    ans = {}
    for index, seq in enumerate(seqs):
        if seq not in ans:
            ans[seq] = []
        ans[seq].append(index)
    return ans

def single_lookup(args):
    index, max_edits, limit, custom_distance, max_cust_dist = _params
    ans, (x_index, seq), is_hamming = [], args, custom_distance == 'hamming'
    neighbors = generate_neighbors(seq, max_edits, is_hamming)

    for possible_edit, edit_distance in neighbors.items():
        if possible_edit in index and edit_distance <= max_edits:
            for y_index in index[possible_edit]:
                if x_index == y_index:
                    continue
                if custom_distance in (None, 'hamming'):
                    ans.append((x_index, y_index, edit_distance))
                else:
                    dist = custom_distance(seq, possible_edit)
                    if dist <= max_cust_dist:
                        ans.append((x_index, y_index, dist))
    return ans if limit is None else ans[0:limit]

def lookup(index, seqs, max_edits, max_returns, n_cpu,
           custom_distance, max_cust_dist):
    global _params
    _params = (index, max_edits, max_returns, custom_distance, max_cust_dist)

    _loop = enumerate(seqs)
    if n_cpu == 1:
        result = map(single_lookup, _loop)
    else:
        with Pool(n_cpu) as p:
            chunk = int(len(seqs)/n_cpu)
            result = p.map(single_lookup, _loop, chunksize=chunk)
    return flatten_array(result)

def brute_lookup(seqs, max_edits=1, max_returns=None, n_cpu=1,
                 custom_distance=None, max_custom_distance=float('inf'),
                 output_type='triplets'):
    """
    List all neighboring CDR3B sequences efficiently for small edit distances.
    The idea is to list all possible sequences within a given distance and lookup the dictionary if it exists.

    Parameters
    ----------
    strings : iterable of strings
        list of CDR3B sequences
    max_edits : int
        maximum edit distance defining the neighbors
    max_returns : int or None
        maximum neighbor size
    n_cpu : int
        number of CPU cores running in parallel
    custom_distance : Function(str1, str2) or "hamming"
        custom distance function to use, must statisfy 4 properties of distance (https://en.wikipedia.org/wiki/Distance#Mathematical_formalization)
    max_custom_distance : float
        maximum distance to include in the result, ignored if custom distance is not supplied
    output_type: string
        format of returns, can be "triplets", "coo_matrix", or "ndarray"

    Returns
    -------
    neighbors : array of 3D-tuples, sparse matrix, or dense matrix
        neigbors along with their edit distances according to the given output_type
        if "triplets" returns are [(x_index, y_index, edit_distance)]
        if "coo_matrix" returns are scipy's sparse matrix where C[i,j] = distance(X_i, X_j) or 0 if not neighbor
        if "ndarray" returns numpy's 2d array representing dense matrix
    """

    # boilerplate
    check_common_input(seqs, max_edits, max_returns, n_cpu,
                       custom_distance, max_custom_distance, output_type)
    seqs = ensure_numpy(seqs)

    # algorithm
    index = build_index(seqs)
    triplets = lookup(index, seqs, max_edits,
                      max_returns, n_cpu, custom_distance, max_custom_distance)
    return make_output(triplets, output_type)


from graphics import *
win = GraphWin("keyboard",500,500)
s = Rectangle(Point(250,250),Point(285,285))
s.draw(win)
s.setFill('blue')
s2 = Rectangle(Point(250,450),Point(300,500))
s2.draw(win)
s2.setFill('red')
currXr = 285
currXl = 250
currYr = 285
currYl = 250
chX = 30
chY = 30
#c.move(30,0)
while True:
    currentKey=win.getKey() #Get input from keyboard
    #square --> add in shape code here
    xd = currXl-250
    yd = currYr-450
    if(currentKey == "Right"):
        #Do something here if the key has been pressed!
        chX = 30
        if currXr + 30 > 500:
            chX = 0
        s.move(chX,0)
        currXr = currXr + chX
        currXl = currXl + chX
    if(currentKey == "Left"):
    #Do something here if the key has been pressed!
        chX = -30
        if currXl -30 < 0:
            chX = 0
        s.move(chX,0)
        currXr = currXr + chX
        currXl = currXl + chX
    if(currentKey == "Up"):
        #Do something here if the key has been pressed!
        chY = -30
        if currYl - 30 < 0:
            chY = 0
        s.move(0,chY)
        currYl = currYl + chY
        currYr = currYr + chY
    if(currentKey == "Down"):
        #Do something here if the key has been pressed!
        chY = 30
        if currYr + 30 > 500:
            chY = 0
        s.move(0,chY)
        currYl = currYl + chY
        currYr = currYr + chY


# -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 18:08:00 2015
A Set of utility functions for saving and loading classifiers
@author: Rupak Chakraborty
"""
import pickle
import math

def populateNumpyData(filename,train_set):
    train_file = open(filename,"r")
    data = train_file.read()
    train_data = data.split()
    c = 0
    for feature_row in train_data:
        features = feature_row.split(",")
        for i in range(len(features)):
            k = float(features[i])
            if math.isnan(k) or math.isinf(k):
                k = 0.01
            train_set[c][i] = k
        c = c + 1

def save_classifier(filename,classifier):

    save_file = open(filename,"wb")
    pickle.dump(classifier,save_file)
    save_file.close

def load_classifier(filename):
    classifier_file = open(filename,"rb")
    classifier = pickle.load(classifier_file)
    classifier_file.close()
    return classifier


from django.http import HttpResponse, JsonResponse
from processor import *
import json

def index(req):
    return HttpResponse('
Welcome to admin chatbot
')

def chatbot(req):
    if req.method == 'POST':
        data = json.loads(req.body)
        response = chatbot_response(data.get('question'))
    return JsonResponse({"response": response});


import datetime
import itertools
import os

import numpy as np
from path import Path
from tensorboardX import SummaryWriter
from torch.backends import cudnn
from torch.utils.data import DataLoader

from dvmvs.dataset_loader import MVSDataset
from dvmvs.losses import LossMeter, update_losses
from dvmvs.pairnet.model import *
from dvmvs.train import train
from dvmvs.utils import zip_code, print_number_of_trainable_parameters, calculate_cost_volume_by_warping

class TrainingHyperparameters:
    Config.train_subsequence_length = 2
    Config.train_predict_two_way = True
    batch_size = 14
    learning_rate = 1e-4
    momentum = 0.9
    beta = 0.999
    weight_decay = 0
    # loss_type = "Huber"
    # loss_type = "L1"
    loss_type = "L1-inv"
    # loss_type = "L1-rel"

    finetune_epochs = 2

    use_augmentation = True
    use_checkpoint = False

scaling = 0.5
x = np.linspace(0, Config.train_image_width * scaling - 1, num=int(Config.train_image_width * scaling))
y = np.linspace(0, Config.train_image_height * scaling - 1, num=int(Config.train_image_height * scaling))
ones = np.ones(shape=(int(Config.train_image_height * scaling), int(Config.train_image_width * scaling)))
x_grid, y_grid = np.meshgrid(x, y)
warp_grid = np.stack((x_grid, y_grid, ones), axis=-1)
warp_grid = torch.from_numpy(warp_grid).float()
warp_grid = warp_grid.view(-1, 3).t().cuda()

def main():
    # set the manual seed for reproducibility
    torch.manual_seed(Config.train_seed)

    # create the directory for this run of the training
    run_directory = os.path.join(Config.train_run_directory, datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
    os.mkdir(run_directory)

    # zip every code file
    zip_code(run_directory)

    summary_writer = SummaryWriter(run_directory)

    print("=> fetching scenes in '{}'".format(Config.dataset))
    train_set = MVSDataset(
        root=Config.dataset,
        seed=Config.train_seed,
        split="TRAINING",
        subsequence_length=Config.train_subsequence_length,
        scale_rgb=255.0,
        mean_rgb=[0.485, 0.456, 0.406],
        std_rgb=[0.229, 0.224, 0.225],
        geometric_scale_augmentation=True
    )

    val_set = MVSDataset(
        root=Config.dataset,
        seed=Config.train_seed,
        split="VALIDATION",
        subsequence_length=Config.train_subsequence_length,
        scale_rgb=255.0,
        mean_rgb=[0.485, 0.456, 0.406],
        std_rgb=[0.229, 0.224, 0.225]
    )

    print('{} samples found in {} train scenes'.format(len(train_set), len(train_set.scenes)))
    print('{} samples found in {} valid scenes'.format(len(val_set), len(val_set.scenes)))
    train_loader = DataLoader(dataset=train_set,
                              batch_size=TrainingHyperparameters.batch_size,
                              shuffle=True,
                              num_workers=Config.train_data_pipeline_workers,
                              pin_memory=True,
                              drop_last=True)

    val_loader = DataLoader(dataset=val_set,
                            batch_size=TrainingHyperparameters.batch_size,
                            shuffle=False,
                            num_workers=Config.train_data_pipeline_workers,
                            pin_memory=True,
                            drop_last=True)

    feature_extractor = FeatureExtractor()
    feature_shrinker = FeatureShrinker()
    cost_volume_encoder = CostVolumeEncoder()
    cost_volume_decoder = CostVolumeDecoder()
    feature_extractor = feature_extractor.cuda()
    feature_shrinker = feature_shrinker.cuda()
    cost_volume_encoder = cost_volume_encoder.cuda()
    cost_volume_decoder = cost_volume_decoder.cuda()
    model = [feature_extractor, feature_shrinker, cost_volume_encoder, cost_volume_decoder]

    if TrainingHyperparameters.use_checkpoint:
        for i in range(len(model)):
            try:
                checkpoint = Path(".").files("module_" + str(i) + "*")[0]
                weights = torch.load(checkpoint)
                model[i].load_state_dict(weights)
                print("Loaded weights for", checkpoint)
            except Exception as e:
                print(e)
                print("Skipping...")

    cudnn.benchmark = True

    best_loss = [np.inf, np.inf, np.inf, np.inf]

    # TRAIN MY PARTS
    parameters = itertools.chain(feature_shrinker.parameters(),
                                 cost_volume_encoder.parameters(),
                                 cost_volume_decoder.parameters())
    optimizer = torch.optim.Adam(parameters,
                                 lr=TrainingHyperparameters.learning_rate,
                                 betas=(TrainingHyperparameters.momentum, TrainingHyperparameters.beta),
                                 weight_decay=TrainingHyperparameters.weight_decay)
    print_number_of_trainable_parameters(optimizer)
    for epoch in range(TrainingHyperparameters.finetune_epochs):
        print("\n\nEPOCH:", epoch)
        train(train_loader=train_loader,
              val_loader=val_loader,
              model=model,
              optimizer=optimizer,
              summary_writer=summary_writer,
              epoch=epoch,
              best_loss=best_loss,
              run_directory=run_directory,
              forward_pass_function=forward_pass)

    # TRAIN EVERYTHING
    parameters = itertools.chain(feature_extractor.parameters(),
                                 feature_shrinker.parameters(),
                                 cost_volume_encoder.parameters(),
                                 cost_volume_decoder.parameters())
    optimizer = torch.optim.Adam(parameters,
                                 lr=TrainingHyperparameters.learning_rate,
                                 betas=(TrainingHyperparameters.momentum, TrainingHyperparameters.beta),
                                 weight_decay=TrainingHyperparameters.weight_decay)
    print_number_of_trainable_parameters(optimizer)
    for epoch in range(TrainingHyperparameters.finetune_epochs, Config.train_epochs):
        print("\n\nEPOCH:", epoch)
        train(train_loader=train_loader,
              val_loader=val_loader,
              model=model,
              optimizer=optimizer,
              summary_writer=summary_writer,
              epoch=epoch,
              best_loss=best_loss,
              run_directory=run_directory,
              forward_pass_function=forward_pass)

def forward_pass(images, depths, poses, K, model, is_training):
    feature_extractor = model[0]
    feature_shrinker = model[1]
    cost_volume_encoder = model[2]
    cost_volume_decoder = model[3]

    K[:, 0:2, :] = K[:, 0:2, :] * scaling
    K = K.cuda()

    images_cuda = []
    depths_cuda = []
    poses_cuda = []
    feature_halfs = []
    feature_quarters = []
    feature_one_eights = []
    feature_one_sixteens = []
    # Extract image features
    for i in range(0, len(images)):
        images_cuda.append(images[i].cuda())
        poses_cuda.append(poses[i].cuda())
        depths_cuda.append(depths[i].cuda())
        feature_half, feature_quarter, feature_one_eight, feature_one_sixteen = feature_shrinker(*feature_extractor(images_cuda[i]))
        feature_halfs.append(feature_half)
        feature_quarters.append(feature_quarter)
        feature_one_eights.append(feature_one_eight)
        feature_one_sixteens.append(feature_one_sixteen)

    optimizer_loss = 0
    predictions = None
    l1_meter = LossMeter()
    huber_meter = LossMeter()
    l1_inv_meter = LossMeter()
    l1_rel_meter = LossMeter()
    for i in range(1, len(images)):
        reference_index = i
        measurement_index = i - 1

        if Config.train_predict_two_way:
            iterations = [[measurement_index, reference_index],
                          [reference_index, measurement_index]]
        else:
            iterations = [[reference_index, measurement_index]]

        for [index1, index2] in iterations:
            initial_cost_volume = calculate_cost_volume_by_warping(image1=feature_halfs[index1],
                                                                   image2=feature_halfs[index2],
                                                                   pose1=poses_cuda[index1],
                                                                   pose2=poses_cuda[index2],
                                                                   K=K,
                                                                   warp_grid=warp_grid,
                                                                   min_depth=Config.train_min_depth,
                                                                   max_depth=Config.train_max_depth,
                                                                   n_depth_levels=Config.train_n_depth_levels,
                                                                   device=torch.device('cuda'),
                                                                   dot_product=True)
            flipped = False
            to_be_used_feature_one_sixteen = feature_one_sixteens[index1]
            to_be_used_feature_one_eight = feature_one_eights[index1]
            to_be_used_feature_quarter = feature_quarters[index1]
            to_be_used_feature_half = feature_halfs[index1]
            to_be_used_image = images_cuda[index1]
            to_be_used_depth = depths_cuda[index1]
            to_be_used_cost_volume = initial_cost_volume
            if is_training and TrainingHyperparameters.use_augmentation and np.random.random() > 0.5:
                to_be_used_feature_one_sixteen = torch.flip(feature_one_sixteens[index1], dims=[-1])
                to_be_used_feature_one_eight = torch.flip(feature_one_eights[index1], dims=[-1])
                to_be_used_feature_quarter = torch.flip(feature_quarters[index1], dims=[-1])
                to_be_used_feature_half = torch.flip(feature_halfs[index1], dims=[-1])
                to_be_used_image = torch.flip(images_cuda[index1], dims=[-1])
                to_be_used_depth = torch.flip(depths_cuda[index1], dims=[-1])
                to_be_used_cost_volume = torch.flip(initial_cost_volume, dims=[-1])
                flipped = True

            skip0, skip1, skip2, skip3, bottom = cost_volume_encoder(features_half=to_be_used_feature_half,
                                                                     features_quarter=to_be_used_feature_quarter,
                                                                     features_one_eight=to_be_used_feature_one_eight,
                                                                     features_one_sixteen=to_be_used_feature_one_sixteen,
                                                                     cost_volume=to_be_used_cost_volume)

            depth_full, depth_half, depth_quarter, depth_one_eight, depth_one_sixteen = cost_volume_decoder(to_be_used_image,
                                                                                skip0,
                                                                                skip1,
                                                                                skip2,
                                                                                skip3,
                                                                                bottom)

            predictions = [depth_one_sixteen, depth_one_eight, depth_quarter, depth_half, depth_full]

            weights = [1, 1, 1, 1, 1]
            optimizer_loss = optimizer_loss + update_losses(predictions=predictions,
                                                            weights=weights,
                                                            groundtruth=to_be_used_depth,
                                                            is_training=is_training,
                                                            l1_meter=l1_meter,
                                                            huber_meter=huber_meter,
                                                            l1_inv_meter=l1_inv_meter,
                                                            l1_rel_meter=l1_rel_meter,
                                                            loss_type=TrainingHyperparameters.loss_type)

            if flipped and index1 == len(images) - 1:
                depth_quarter = torch.flip(depth_quarter, dims=[-1])
                depth_half = torch.flip(depth_half, dims=[-1])
                depth_full = torch.flip(depth_full, dims=[-1])

            predictions = [depth_quarter, depth_half, depth_full]

    predictions_names = ["prediction_quarter", "prediction_half", "prediction_full"]

    return l1_meter, huber_meter, l1_inv_meter, l1_rel_meter, optimizer_loss, predictions, predictions_names

if __name__ == '__main__':
    main()


"""
SystemLab-Design 20.01.r3 19-Jun-20
Configuration port viewers file
"""

'''Port viewers plot settings==================================================
Update these settings to change the look & feel of port viewer
figures and plots.
Parameters include line colors/widths/styles, marker styles/sizes/colors,
figure/plot background colors, grid styles/widths/colors, label/axis colors.
'''
"""Optical port viewer---------------------------------------------------------
"""
optical_frame_background_color = '#f9f9f9'
# Time-domain tab (data plots)
optical_time_fig_back_color = '#f9f9f9'
optical_time_plot_back_color = '#f9f9f9'
optical_time_labels_axes_color = 'black'
optical_time_signal_color = 'b'
optical_time_signal_linestyle = '--'
optical_time_signal_linewidth = 0.8
optical_time_signal_marker = 'o'
optical_time_signal_markersize = 3
optical_time_noise_color = 'r'
optical_time_noise_linestyle = '--'
optical_time_noise_linewidth = 0.8
optical_time_noise_marker = 'o'
optical_time_noise_markersize = 3
optical_time_sig_noise_color = 'g'
optical_time_sig_noise_linestyle = '--'
optical_time_sig_noise_linewidth = 0.8
optical_time_sig_noise_marker = 'o'
optical_time_sig_noise_markersize = 3
optical_time_phase_color = 'y'
optical_time_phase_linestyle = '--'
optical_time_phase_linewidth = 0.8
optical_time_phase_marker = 'o'
optical_time_phase_markersize = 3
# Time-domain tab (background and grid settings)
optical_time_maj_grid_linestyle = ':'
optical_time_maj_grid_linewidth = 0.5
optical_time_maj_grid_color = 'gray'
optical_time_min_grid_linestyle = ':'
optical_time_min_grid_linewidth = 0.5
optical_time_min_grid_color = 'lightGray'
# Freq-domain tab (data plots)
optical_freq_fig_back_color = '#505050'
optical_freq_plot_back_color = '#000000'
optical_freq_labels_axes_color = 'white'
optical_freq_signal_color = 'y'
optical_freq_signal_linestyle = '--'
optical_freq_signal_linewidth = 0.5
optical_freq_signal_marker = 'o'
optical_freq_signal_markersize = 2
optical_freq_noise_color = 'r'
optical_freq_noise_linestyle = '--'
optical_freq_noise_linewidth = 0.5
optical_freq_noise_marker = 'o'
optical_freq_noise_markersize = 2
optical_freq_sig_noise_color = 'g'
optical_freq_sig_noise_linestyle = '--'
optical_freq_sig_noise_linewidth = 0.5
optical_freq_sig_noise_marker = 'o'
optical_freq_sig_noise_markersize = 2
optical_freq_psd_noise_color = 'orange'
optical_freq_psd_noise_linestyle = '--'
optical_freq_psd_noise_linewidth = 0.5
optical_freq_psd_noise_marker = 'o'
optical_freq_psd_noise_markersize = 2
# Freq-domain tab (background and grid settings)
optical_freq_maj_grid_linestyle = '-'
optical_freq_maj_grid_linewidth = 0.5
optical_freq_maj_grid_color = 'darkGray'
optical_freq_min_grid_linestyle = '-'
optical_freq_min_grid_linewidth = 0.5
optical_freq_min_grid_color = 'darkGray'
# Freq-data (all ch) tab (data plots)
opt_chnls_freq_fig_back_color = '#505050'
opt_chnls_freq_plot_back_color = '#000000'
opt_chnls_freq_labels_axes_color = 'white'
opt_chnls_freq_signal_color = 'y'
opt_chnls_freq_signal_linestyle = '--'
opt_chnls_freq_signal_linewidth = 0.5
opt_chnls_freq_signal_marker = 'o'
opt_chnls_freq_signal_markersize = 2
opt_chnls_freq_noise_color = 'r'
opt_chnls_freq_noise_linestyle = '--'
opt_chnls_freq_noise_linewidth = 0.5
opt_chnls_freq_noise_marker = 'o'
opt_chnls_freq_noise_markersize = 2
opt_chnls_freq_sig_noise_color = 'g'
opt_chnls_freq_sig_noise_linestyle = '--'
opt_chnls_freq_sig_noise_linewidth = 0.5
opt_chnls_freq_sig_noise_marker = 'o'
opt_chnls_freq_sig_noise_markersize = 2
opt_chnls_freq_psd_noise_color = 'orange'
opt_chnls_freq_psd_noise_linestyle = '--'
opt_chnls_freq_psd_noise_linewidth = 0.5
opt_chnls_freq_psd_noise_marker = 'o'
opt_chnls_freq_psd_noise_markersize = 2
# Freq-domain tab (background and grid settings)
opt_chnls_freq_maj_grid_linestyle = '-'
opt_chnls_freq_maj_grid_linewidth = 0.5
opt_chnls_freq_maj_grid_color = 'darkGray'
opt_chnls_freq_min_grid_linestyle = '-'
opt_chnls_freq_min_grid_linewidth = 0.5
opt_chnls_freq_min_grid_color = 'darkGray'

"""Electrical port viewer---------------------------------------------------"""
electrical_frame_background_color = '#f9f9f9'
# Time-domain tab (data plots)
electrical_time_fig_back_color = '#f9f9f9'
electrical_time_plot_back_color = '#f9f9f9'
electrical_time_labels_axes_color = 'black'
electrical_time_signal_color = 'b'
electrical_time_signal_linestyle = '--'
electrical_time_signal_linewidth = 0.8
electrical_time_signal_marker = 'o'
electrical_time_signal_markersize = 3
electrical_time_noise_color = 'r'
electrical_time_noise_linestyle = '--'
electrical_time_noise_linewidth = 0.8
electrical_time_noise_marker = 'o'
electrical_time_noise_markersize = 3
electrical_time_sig_noise_color = 'g'
electrical_time_sig_noise_linestyle = '--'
electrical_time_sig_noise_linewidth = 0.8
electrical_time_sig_noise_marker = 'o'
electrical_time_sig_noise_markersize = 3
electrical_time_sampling_color = 'r'
electrical_time_sampling_linestyle = 'None'
electrical_time_sampling_linewidth = 0.8
electrical_time_sampling_marker = 'o'
electrical_time_sampling_markersize = 3
# Time-domain tab (background and grid settings)
electrical_time_maj_grid_linestyle = ':'
electrical_time_maj_grid_linewidth = 0.5
electrical_time_maj_grid_color = 'gray'
electrical_time_min_grid_linestyle = ':'
electrical_time_min_grid_linewidth = 0.5
electrical_time_min_grid_color = 'lightGray'
# Freq-domain tab (data plots)
electrical_freq_fig_back_color = '#505050'
electrical_freq_plot_back_color = '#000000'
electrical_freq_labels_axes_color = 'white'
electrical_freq_signal_color = 'y'
electrical_freq_signal_linestyle = '--'
electrical_freq_signal_linewidth = 0.5
electrical_freq_signal_marker = 'o'
electrical_freq_signal_markersize = 2
electrical_freq_noise_color = 'r'
electrical_freq_noise_linestyle = '--'
electrical_freq_noise_linewidth = 0.5
electrical_freq_noise_marker = 'o'
electrical_freq_noise_markersize = 2
electrical_freq_sig_noise_color = 'g'
electrical_freq_sig_noise_linestyle = '--'
electrical_freq_sig_noise_linewidth = 0.5
electrical_freq_sig_noise_marker = 'o'
electrical_freq_sig_noise_markersize = 2
# Freq-domain tab (background and grid settings)
electrical_freq_maj_grid_linestyle = '-'
electrical_freq_maj_grid_linewidth = 0.5
electrical_freq_maj_grid_color = 'darkGray'
electrical_freq_min_grid_linestyle = '-'
electrical_freq_min_grid_linewidth = 0.5
electrical_freq_min_grid_color = 'darkGray'
# Eye tab (data plots)
electrical_eye_fig_back_color = '#505050'
electrical_eye_plot_back_color = '#000000'
electrical_eye_labels_axes_color = 'white'
electrical_eye_signal_color = 'orange'
electrical_eye_signal_linestyle = '-'
electrical_eye_signal_linewidth = 0.25
electrical_eye_signal_alpha = 0.3 # MV 20.01.r3 10-Jul-20
electrical_eye_signal_marker = 'o'
electrical_eye_signal_markersize = 1
electrical_eye_sig_noise_color = 'crimson'
electrical_eye_sig_noise_linestyle = '-'
electrical_eye_sig_noise_linewidth = 0.25
electrical_eye_sig_noise_alpha = 0.3 # MV 20.01.r3 10-Jul-20
electrical_eye_sig_noise_marker = 'o'
electrical_eye_sig_noise_markersize = 1
# Eye tab (background and grid settings)
electrical_eye_maj_grid_linestyle = ':'
electrical_eye_maj_grid_linewidth = 0.5
electrical_eye_maj_grid_color = 'darkGray'
electrical_eye_min_grid_linestyle = ':'
electrical_eye_min_grid_linewidth = 0.5
electrical_eye_min_grid_color = 'darkGray'
electrical_eye_hist_color = 'magenta' #MV 20.01.r3 18-Jun-20
electrical_eye_hist_alpha = 1.0 #MV 20.01.r3 18-Jun-20

"""Digital port viewer------------------------------------------------------"""
digital_frame_background_color = '#f9f9f9'
# Time-domain tab (data plots)
digital_time_fig_back_color = '#f9f9f9'
digital_time_plot_back_color = '#f9f9f9'
digital_time_labels_axes_color = 'black'
digital_time_signal_color = 'b'
digital_time_signal_linestyle = '--'
digital_time_signal_linewidth = 0.8
digital_time_signal_marker = 'o'
digital_time_signal_markersize = 3
# Time-domain tab (background and grid settings)
digital_time_maj_grid_linestyle = ':'
digital_time_maj_grid_linewidth = 0.5
digital_time_maj_grid_color = 'gray'
digital_time_min_grid_linestyle = ':'
digital_time_min_grid_linewidth = 0.5
digital_time_min_grid_color = 'lightGray'
# Freq-domain tab (data plots)
digital_freq_fig_back_color = '#f9f9f9'
digital_freq_plot_back_color = '#f9f9f9'
digital_freq_labels_axes_color = 'black'
digital_freq_signal_color = 'b'
digital_freq_signal_linestyle = '--'
digital_freq_signal_linewidth = 0.8
digital_freq_signal_marker = 'o'
digital_freq_signal_markersize = 3
# Freq-domain tab (background and grid settings)
digital_freq_maj_grid_linestyle = ':'
digital_freq_maj_grid_linewidth = 0.5
digital_freq_maj_grid_color = 'darkGray'
digital_freq_min_grid_linestyle = ':'
digital_freq_min_grid_linewidth = 0.5
digital_freq_min_grid_color = 'darkGray'

"""Analog port viewer-------------------------------------------------------"""
analog_frame_background_color = '#f9f9f9'
# Time-domain tab (data plots)
analog_time_fig_back_color = '#f9f9f9'
analog_time_plot_back_color = '#f9f9f9'
analog_time_labels_axes_color = 'black'
analog_time_signal_color = 'b'
analog_time_signal_linestyle = '--'
analog_time_signal_linewidth = 0.8
analog_time_signal_marker = 'o'
analog_time_signal_markersize = 3
# Time-domain tab (background and grid settings)
analog_time_maj_grid_linestyle = ':'
analog_time_maj_grid_linewidth = 0.5
analog_time_maj_grid_color = 'gray'
analog_time_min_grid_linestyle = ':'
analog_time_min_grid_linewidth = 0.5
analog_time_min_grid_color = 'lightGray'
# Freq-domain tab (data plots)
analog_freq_fig_back_color = '#f9f9f9'
analog_freq_plot_back_color = '#f9f9f9'
analog_freq_labels_axes_color = 'black'
analog_freq_signal_color = 'b'
analog_freq_signal_linestyle = '--'
analog_freq_signal_linewidth = 0.8
analog_freq_signal_marker = 'o'
analog_freq_signal_markersize = 3
# Freq-domain tab (background and grid settings)
analog_freq_maj_grid_linestyle = ':'
analog_freq_maj_grid_linewidth = 0.5
analog_freq_maj_grid_color = 'gray'
analog_freq_min_grid_linestyle = ':'
analog_freq_min_grid_linewidth = 0.5
analog_freq_min_grid_color = 'lightGray'

"""Electrical port viewer (multiple plots)----------------------------------"""
m_electrical_frame_background_color = '#f9f9f9'
# Time-domain tab (data plots)
m_electrical_time_fig_back_color = '#f9f9f9'
m_electrical_time_plot_back_color = '#f9f9f9'
m_electrical_time_labels_axes_color = 'black'
m_electrical_time_signal_color = ['b', 'b', 'b', 'b']
m_electrical_time_signal_linestyle = ['--','--', '--', '--']
m_electrical_time_signal_linewidth = [0.8, 0.8, 0.8, 0.8]
m_electrical_time_signal_marker = ['o', 's', 'd', '^']
m_electrical_time_signal_markersize = [3, 3, 3, 3]
m_electrical_time_noise_color = ['r', 'r', 'r', 'r']
m_electrical_time_noise_linestyle = ['--','--', '--', '--']
m_electrical_time_noise_linewidth = [0.8, 0.8, 0.8, 0.8]
m_electrical_time_noise_marker = ['o', 's', 'd', '^']
m_electrical_time_noise_markersize = [3, 3, 3, 3]
m_electrical_time_sig_noise_color = ['g', 'g', 'g', 'g']
m_electrical_time_sig_noise_linestyle = ['--','--', '--', '--']
m_electrical_time_sig_noise_linewidth = [0.8, 0.8, 0.8, 0.8]
m_electrical_time_sig_noise_marker = ['o', 's', 'd', '^']
m_electrical_time_sig_noise_markersize = [3, 3, 3, 3]
# Time-domain tab (background and grid settings)
m_electrical_time_maj_grid_linestyle = ':'
m_electrical_time_maj_grid_linewidth = 0.5
m_electrical_time_maj_grid_color = 'gray'
m_electrical_time_min_grid_linestyle = ':'
m_electrical_time_min_grid_linewidth = 0.5
m_electrical_time_min_grid_color = 'lightGray'
# Freq-domain tab (data plots)
m_electrical_freq_fig_back_color = '#f9f9f9'
m_electrical_freq_plot_back_color = '#f9f9f9'
m_electrical_freq_labels_axes_color = 'black'
m_electrical_freq_signal_color = ['b', 'b', 'b', 'b']
m_electrical_freq_signal_linestyle = ['--','--', '--', '--']
m_electrical_freq_signal_linewidth = [0.8, 0.8, 0.8, 0.8]
m_electrical_freq_signal_marker = ['o', 's', 'd', '^']
m_electrical_freq_signal_markersize = [3, 3, 3, 3]
m_electrical_freq_noise_color = ['r', 'r', 'r', 'r']
m_electrical_freq_noise_linestyle = ['--','--', '--', '--']
m_electrical_freq_noise_linewidth = [0.8, 0.8, 0.8, 0.8]
m_electrical_freq_noise_marker = ['o', 's', 'd', '^']
m_electrical_freq_noise_markersize = [3, 3, 3, 3]
m_electrical_freq_sig_noise_color = ['g', 'g', 'g', 'g']
m_electrical_freq_sig_noise_linestyle = ['--','--', '--', '--']
m_electrical_freq_sig_noise_linewidth = [0.8, 0.8, 0.8, 0.8]
m_electrical_freq_sig_noise_marker = ['o', 's', 'd', '^']
m_electrical_freq_sig_noise_markersize = [3, 3, 3, 3]
# Freq-domain tab (background and grid settings)
m_electrical_freq_maj_grid_linestyle = ':'
m_electrical_freq_maj_grid_linewidth = 0.5
m_electrical_freq_maj_grid_color = 'gray'
m_electrical_freq_min_grid_linestyle = ':'
m_electrical_freq_min_grid_linewidth = 0.5
m_electrical_freq_min_grid_color = 'lightGray'


import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

def second_task():
    # Выгрузка данных
    data_2015 = pd.read_csv("csv/2015.csv")

    # Чтение данных
    data_2015.head()

    # Проверка на наличие пропущенных значений
    for column in data_2015.columns:
        missing = np.mean(data_2015[column].isna() * 100)
        # print(f"{column} : {round(missing, 1)}%")

    # Статистика по данным
    data_2015.describe()

    # Построение матрицы корреляции по одной целевой переменной
    corr_matrix = data_2015.corr().Happiness_Score.to_frame().round(2)
    # print(corr_matrix)

    # Модель LinearRegression
    model = LinearRegression()

    # Переменные для модели
    x = data_2015[['Economy (GDP per Capita)']]
    y = data_2015['Happiness_Score']
    x = np.array(x, type(float))
    y = np.array(y, type(float))

    # Коэффициенты сдвига и наклона
    model.fit(x, y)
    print(model.coef_, model.intercept_)

second_task()


import warnings

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

warnings.filterwarnings(action="ignore")
torch.set_printoptions(sci_mode=True)

class MultiDAE(nn.Module):
    def __init__(self, p_dims, dropout_rate=0.5):
        super(MultiDAE, self).__init__()
        self.p_dims = p_dims
        self.q_dims = p_dims[::-1]

        self.dims = self.q_dims + self.p_dims[1:]
        self.layers = nn.ModuleList(
            [
                nn.Linear(d_in, d_out)
                for d_in, d_out in zip(self.dims[:-1], self.dims[1:])
            ]
        )
        self.drop = nn.Dropout(dropout_rate)

        self.init_weights()

    def forward(self, input):
        h = F.normalize(input)
        h = self.drop(h)

        for i, layer in enumerate(self.layers):
            h = layer(h)
            if i != len(self.layers) - 1:
                h = F.tanh(h)
        return h

    def init_weights(self):
        for layer in self.layers:
            # Xavier Initialization for weights
            size = layer.weight.size()
            fan_out = size[0]
            fan_in = size[1]
            std = np.sqrt(2.0 / (fan_in + fan_out))
            layer.weight.data.normal_(0.0, std)

            # Normal Initialization for Biases
            layer.bias.data.normal_(0.0, 0.001)


# How to run a celery task:
# 1. make sure RabbitMQ is running in the background
# 2. $ celery -A tasks worker --loglevel=info

from celery import Celery
from celery.schedules import crontab

from datetime import datetime
import pytz

app = Celery('tasks', broker='pyamqp://guest@localhost//')
app.conf.beat_schedule = {
    # Executes every 15-minute
    'execute-every-15-minute': {
        'task': 'cron_tasks.task_every_15_minutes',
        'schedule': crontab(minute='*/15'),
        'args': (16, 16),
    },
}
app.conf.timezone = 'UTC'
# app.conf.timezone = 'US/Pacific'

@app.task
def task_every_15_minutes():
    utc_now = datetime.now()


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

# Dependency imports

import numpy as np

from tensor2tensor.data_generators import problem_hparams
from tensor2tensor.models import transformer

import tensorflow as tf

BATCH_SIZE = 3
INPUT_LENGTH = 5
TARGET_LENGTH = 7
VOCAB_SIZE = 10

class TransformerTest(tf.test.TestCase):

  def getModel(self, hparams, mode=tf.estimator.ModeKeys.TRAIN, has_input=True):
    hparams.hidden_size = 8
    hparams.filter_size = 32
    hparams.num_heads = 1
    hparams.layer_prepostprocess_dropout = 0.0

    p_hparams = problem_hparams.test_problem_hparams(VOCAB_SIZE, VOCAB_SIZE)
    if not has_input:
      p_hparams.input_modality = {}
    hparams.problems = [p_hparams]

    inputs = -1 + np.random.random_integers(
        VOCAB_SIZE, size=(BATCH_SIZE, INPUT_LENGTH, 1, 1))
    targets = -1 + np.random.random_integers(
        VOCAB_SIZE, size=(BATCH_SIZE, TARGET_LENGTH, 1, 1))
    features = {
        "inputs": tf.constant(inputs, dtype=tf.int32, name="inputs"),
        "targets": tf.constant(targets, dtype=tf.int32, name="targets"),
        "target_space_id": tf.constant(1, dtype=tf.int32)
    }

    return transformer.Transformer(hparams, mode, p_hparams), features

  def testTransformer(self):
    model, features = self.getModel(transformer.transformer_small())
    logits, _ = model(features)
    with self.test_session() as session:
      session.run(tf.global_variables_initializer())
      res = session.run(logits)
    self.assertEqual(res.shape, (BATCH_SIZE, TARGET_LENGTH, 1, 1, VOCAB_SIZE))

  def testTransformerRelative(self):
    model, features = self.getModel(transformer.transformer_relative_tiny())
    logits, _ = model(features)
    with self.test_session() as session:
      session.run(tf.global_variables_initializer())
      res = session.run(logits)
    self.assertEqual(res.shape, (BATCH_SIZE, TARGET_LENGTH, 1, 1, VOCAB_SIZE))

  def testGreedyVsFast(self):
    model, features = self.getModel(transformer.transformer_small())

    decode_length = 2

    out_logits, _ = model(features)
    out_logits = tf.squeeze(out_logits, axis=[2, 3])
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=tf.reshape(out_logits, [-1, VOCAB_SIZE]),
        labels=tf.reshape(features["targets"], [-1]))
    loss = tf.reduce_mean(loss)
    apply_grad = tf.train.AdamOptimizer(0.001).minimize(loss)

    with self.test_session():
      tf.global_variables_initializer().run()
      for _ in range(100):
        apply_grad.run()

    model.set_mode(tf.estimator.ModeKeys.PREDICT)

    with tf.variable_scope(tf.get_variable_scope(), reuse=True):
      greedy_result = model._slow_greedy_infer(
          features, decode_length)["outputs"]
      greedy_result = tf.squeeze(greedy_result, axis=[2, 3])

      fast_result = model._greedy_infer(features, decode_length)["outputs"]

    with self.test_session():
      greedy_res = greedy_result.eval()
      fast_res = fast_result.eval()

    self.assertEqual(fast_res.shape, (BATCH_SIZE, INPUT_LENGTH + decode_length))
    self.assertAllClose(greedy_res, fast_res)

  def testSlowVsFastNoInput(self):
    model, features = self.getModel(
        transformer.transformer_small(), has_input=False)

    decode_length = 2

    out_logits, _ = model(features)
    out_logits = tf.squeeze(out_logits, axis=[2, 3])
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=tf.reshape(out_logits, [-1, VOCAB_SIZE]),
        labels=tf.reshape(features["targets"], [-1]))
    loss = tf.reduce_mean(loss)
    apply_grad = tf.train.AdamOptimizer(0.001).minimize(loss)

    with self.test_session():
      tf.global_variables_initializer().run()
      for _ in range(100):
        apply_grad.run()

    model.set_mode(tf.estimator.ModeKeys.PREDICT)

    with tf.variable_scope(tf.get_variable_scope(), reuse=True):
      slow_result = model._slow_greedy_infer(
          features, decode_length)["outputs"]
      slow_result = tf.squeeze(slow_result, axis=[2, 3])

      fast_result = model._greedy_infer(features, decode_length)["outputs"]

    with self.test_session():
      slow_res = slow_result.eval()
      fast_res = fast_result.eval()

    self.assertEqual(fast_res.shape, (BATCH_SIZE, decode_length))
    self.assertAllClose(slow_res, fast_res)

  def testBeamVsFast(self):
    model, features = self.getModel(transformer.transformer_small())

    decode_length = 2

    out_logits, _ = model(features)
    out_logits = tf.squeeze(out_logits, axis=[2, 3])
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=tf.reshape(out_logits, [-1, VOCAB_SIZE]),
        labels=tf.reshape(features["targets"], [-1]))
    loss = tf.reduce_mean(loss)
    apply_grad = tf.train.AdamOptimizer(0.001).minimize(loss)

    with self.test_session():
      tf.global_variables_initializer().run()
      for _ in range(100):
        apply_grad.run()

    model.set_mode(tf.estimator.ModeKeys.PREDICT)

    with tf.variable_scope(tf.get_variable_scope(), reuse=True):
      beam_result = model._beam_decode_slow(
          features,
          decode_length,
          beam_size=4,
          top_beams=1,
          alpha=1.0)["outputs"]

      fast_result = model._beam_decode(
          features,
          decode_length,
          beam_size=4,
          top_beams=1,
          alpha=1.0)["outputs"]

    with self.test_session():
      beam_res = beam_result.eval()
      fast_res = fast_result.eval()

    self.assertEqual(fast_res.shape, (BATCH_SIZE, INPUT_LENGTH + decode_length))
    self.assertAllClose(beam_res, fast_res)

  def testTransformerWithoutProblem(self):
    hparams = transformer.transformer_test()

    embedded_inputs = np.random.random_sample(
        (BATCH_SIZE, INPUT_LENGTH, 1, hparams.hidden_size))
    embedded_targets = np.random.random_sample(
        (BATCH_SIZE, TARGET_LENGTH, 1, hparams.hidden_size))

    transformed_features = {
        "inputs": tf.constant(embedded_inputs, dtype=tf.float32),
        "targets": tf.constant(embedded_targets, dtype=tf.float32)
    }

    model = transformer.Transformer(hparams)
    body_out, _ = model(transformed_features)

    self.assertAllEqual(
        body_out.get_shape().as_list(),
        [BATCH_SIZE, TARGET_LENGTH, 1, hparams.hidden_size])

  def testTransformerWithEncoderDecoderAttentionLoss(self):
    model, features = self.getModel(
        transformer.transformer_supervised_attention())
    expected_attention_weights = np.random.random_sample(
        size=(BATCH_SIZE, TARGET_LENGTH, INPUT_LENGTH))
    features["expected_attentions"] = tf.constant(
        expected_attention_weights, dtype=tf.float32)
    _, extra_loss = model(features)
    with self.test_session() as session:
      session.run(tf.global_variables_initializer())
      res = session.run(extra_loss["attention_loss"])
    self.assertEqual(res.shape, ())

if __name__ == "__main__":
  tf.test.main()