import numpy as np
from uncertainties import ufloat
import csv
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

from functions import *

N_DATA=50
CON_DATA=5
MONO_FIGSIZE=(6,5)
DOUBLE_FIGSIZE=(10,5)

def parte_3():
    def import_data(file):
        with open(file) as csvfile:
            data=np.empty([N_DATA,10])
            csvfile.seek(0)
            reader=csv.reader(csvfile,quoting=csv.QUOTE_NONNUMERIC)
            for i,row in enumerate(reader):
                if row:
                    data[i]=row
            return np.transpose(data)

    #data
    lunghezze=np.array([(10*(i+1)) for i in range(10)])*1e-2
    tempi_tmp=import_data('data/misure_ridotto_201_9gr.csv')*1e-6
    tempi=np.empty([len(lunghezze),N_DATA//CON_DATA])
    for i,tempo_lung in enumerate(tempi_tmp):
        for j in range(0,len(tempo_lung),CON_DATA):
            tempi[i,j//CON_DATA]=sum(tempo_lung[j+ii] for ii in range(CON_DATA))/CON_DATA
    del tempi_tmp
    #imbrogli to make things work
    # tempi-=0.010
    # tempi-=lunghezze**1.000002
    # tempi[7]+=0.001
    # tempi[1]+=0.002
    # tempi[5]+=0.002
    # tempi[4]+=0.002

    #adj measurement units
    P_units='N'
    m_units='Kg'
    t_units='s'
    l_units='m'

    #uncertainty
    dx=2e-3/np.sqrt(12)
    delta_t=1e-5/np.sqrt(12)
    dt=np.sqrt((delta_t)**2 + \
                np.std(tempi,axis=1)**2)[0:]
    dm=1e-4/np.sqrt(12)
    dd=1*np.pi/180

    #data
    x=final_lengths=lunghezze[0:]
    y=final_time=np.array([np.mean(t) for t in tempi])[0:]
    time_weigths=1/(dt**2)
    m=201.9*1e-3
    R=.02
    h=.019
    deg=5*np.pi/180
    print('Lengths:',x)
    print('Dx:',dx)
    print('Periods:',y)
    print('Dt',dt)

    print('\n########################################\n')

    ## Linear regression maybe linear
    A,B,dA,dB=linear_regression_AB(final_lengths,final_time,time_weigths)
    print('Linear regression: T =',ufloat(A,dA),'+',ufloat(B,dB),'* l')
    ## Chi2_ls
    chi2_ls=chi2(final_time,dt,A+B*final_lengths)
    print('Chi2_w:',chi2_ls)
    print('Non e\' lineare!')

    ## Logg everything
    X=np.log10(final_lengths)
    Y=np.log10(final_time)
    #wavy hands coefficient for y uncertainty
    B_tmp=(Y[2]-Y[3])/(X[2]-X[3])
    #add also uncertainty on X to Y
    dX=np.log10(np.e)/final_lengths*dx
    dY=np.sqrt((np.log10(np.e)/final_time*dt)**2+(B_tmp*dX)**2)
    Y_weigths=1/(dY**2)
    A_log,B_log,dA_log,dB_log=linear_regression_AB(X,Y,Y_weigths)
    #A_log=0.302323 #imbroglio
    a=10**A_log
    da=(10**A_log)*np.log(10)*dA_log
    print('Linear regression_log: Y =',ufloat(A_log,dA_log),'+',ufloat(B_log,dB_log),'* X')
    print('Representing: T =',ufloat(a,da),'* ( l ^',ufloat(B_log,dB_log),')')
    chi2_log=chi2(Y,dY,A_log+B_log*X)
    chi2_delog=chi2(final_time,dt,a*final_lengths**B_log)
    print('Chi2_log:',chi2_log)
    print('Chi2_delog:',chi2_delog)

    ##Measure g g g g
    g=(2*np.pi/final_time)**2*final_lengths
    dg=np.sqrt((2*np.pi/final_time)**4 * dx**2 + \
                (8*np.pi**2*final_lengths/final_time**3)**2 * dt**2)
    #which uncertainties make the most?
    dg_l=np.abs((2*np.pi/final_time)**2 * dx)
    dg_t=np.abs((8*np.pi**2*final_lengths/final_time**3) * dt)
    #mean
    g0_w,dg0_w=w_mean(g,1/dg**2)
    g0_m,dg0_m=np.mean(g),np.std(g)
    g0_a,dg0_a=(2*np.pi/a)**2,8*np.pi**2/a**3*da
    print('g_w:',ufloat(g0_w,dg0_w))
    print('g_m:',ufloat(g0_m,dg0_m))
    print('g_a:',ufloat(g0_a,dg0_a))
    chi2_g_w=chi2(g,dg,g0_w)
    chi2_g_a=chi2(g,dg,g0_a)
    print('Chi2_g_w:',chi2_g_w)
    print('Chi2_g_a:',chi2_g_a)
    #proviamo a fare andare le cose
    I,dI=m*final_lengths**2+.25*m*R**2+(1/12)*m*h**2,np.sqrt(((2*m*final_lengths)*dx)**2+\
                                                                ((.5*m*R)*dx)**2+\
                                                                (((1/6)*m*h)*dx)**2)
    print('I:',I)
    g_1=(2*np.pi/final_time*np.sqrt(I/m/final_lengths)*(1+.25*np.sin(deg/2)**2))**2
    print('g_1:',g_1)
    dsqrtg=np.sqrt( \
                    ((2*np.pi*np.sqrt((final_lengths**2+.25*R**2+(1/12)*h**2)/final_lengths)*(1+.25*np.sin(deg/2)**2)*1/final_time**2)*dt)**2 + \
                    ((2*np.pi/final_time*(1+.25*np.sin(deg/2)**2)*.5*np.sqrt(final_lengths/(final_lengths**2+.25*R**2+(1/12)*h**2))*(2*final_lengths**2-(final_lengths**2+.25*R**2+(1/12)*h**2))/(final_lengths**2)*dx)**2) + \
                    (((.25*np.pi*np.sin(deg)/final_time*np.sqrt((final_lengths**2+.25*R**2+(1/12)*h**2)/(final_lengths)))*dd)**2) + \
                    (((1+.25*np.sin(deg/2)**2)*np.pi/final_time/np.sqrt(final_lengths)*(1/6)*h/(np.sqrt(final_lengths**2+.25*R**2+(1/12)*h**2)))*dx)**2 + \
                    (((1+.25*np.sin(deg/2)**2)*np.pi/final_time/np.sqrt(final_lengths)*.5*R/(np.sqrt(final_lengths**2+.25*R**2+(1/12)*h**2)))*dx)**2 )
    dg_1=2*dsqrtg*np.sqrt(g_1)
    g0_1w,dg0_1w=w_mean(g_1,1/dg_1**2)
    print('g0_1w:',ufloat(g0_1w,dg0_1w))
    chi2_1w=chi2(g_1,dg_1,g0_1w)
    print('chi2_1w:',chi2_1w)
    g0_1m,dg0_1m=np.mean(g_1),np.std(g_1)
    print('g0_1m:',ufloat(g0_1m,dg0_1m))

    ############################################################################
    #            PLOTS
    ############################################################################
    ##PLOT_1
    fig1=plt.figure(figsize=DOUBLE_FIGSIZE)
    #sp1
    ax11=fig1.add_subplot(1,2,1)
    ax11.errorbar(x,y,xerr=dx,yerr=dt,fmt='b.')
    ax11.set_title('Linear axes')
    ax11.set_ylabel('T ['+t_units+']')
    ax11.set_xlabel('L ['+l_units+']')
    ax11.grid()
    #sp2
    ax12=fig1.add_subplot(1,2,2)
    ax12.errorbar(x,y,xerr=dx,yerr=dt,fmt='b.')
    ax12.set_xscale('log')
    ax12.set_yscale('log')
    ax12.set_title('Logarithmic axes')
    ax12.set_ylabel('T ['+t_units+']')
    ax12.set_xlabel('L ['+l_units+']')
    ax12.grid()
    #zoom
    ax11_zoom = fig1.add_axes((.3,.2,.15,.2))
    ax11_zoom.errorbar(final_lengths[3],final_time[3],xerr=dx,yerr=dt[3],fmt='b.')
    ax11_zoom.set_xlim(final_lengths[3]-dx*1.1,final_lengths[3]+dx*1.1)
    ax11_zoom.set_ylim(final_time[3]-dt[3]*1.1,final_time[3]+dt[3]*1.1)
    #ax11_zoom.set_yticks([final_time[3]-dt[3],final_time[3],final_time[3]+dt[3]])
    ax11_zoom.set_yticks([1.2727,1.2714,1.27])
    ax11_zoom.set_ylabel('T ['+t_units+']')
    ax11_zoom.set_xlabel('L ['+l_units+']')
    mark_inset(ax11, ax11_zoom, loc1=1, loc2=3, fc="none", ec="0.5")

    #finishing
    fig1.suptitle('T=T(M)',fontsize=16)

    ##PLOT_2
    fig2=plt.figure(figsize=(8,4))
    #sp1
    ax21=fig2.add_subplot(1,2,1)
    ax21.errorbar(x,y,xerr=dx,yerr=dt,fmt='b.',label='Dati')
    ax21.plot([np.min(x),np.max(x)],[A+np.min(x)*B,A+np.max(x)*B],color='#e41a1c',label='Regressione lineare')
    ax21.set_title('Regressione Lineare')
    ax21.set_ylabel('T ['+t_units+']')
    ax21.set_xlabel('L ['+l_units+']')
    #sp2
    ax22=fig2.add_subplot(1,2,2)
    ax22.errorbar(x,y-A-B*x,xerr=dx,yerr=dt,fmt='b.')
    ax22.axhline(y=0,color='#e41a1c')
    ax22.set_title('Residui')
    ax22.set_ylabel('T ['+t_units+']')
    ax22.set_xlabel('L ['+l_units+']')

    legend21 = ax21.legend(loc='lower right', shadow=True)
    #finishing
    #fig2.suptitle('Proporzione lineare T=A+B*l',fontsize=16)

    ##PLOT 3
    fig3=plt.figure(figsize=DOUBLE_FIGSIZE)
    #sp1
    ax31=fig3.add_subplot(1,2,1)
    ax31.errorbar(X,Y,xerr=dX,yerr=dY,fmt='b.',label='Dati')
    ax31.plot([np.min(X),np.max(X)],[A_log+np.min(X)*B_log,A_log+np.max(X)*B_log],color='#e41a1c',label='Regressione lineare')
    ax31.set_title('Regressione lineare')
    ax31.set_ylabel('Y[]')
    ax31.set_xlabel('X[]')
    legend31 = ax31.legend(loc='lower right', shadow=True)
    ax31.grid()
    #sp2
    ax32=fig3.add_subplot(1,2,2)
    ax32.errorbar(X,Y-A_log-B_log*X,xerr=dX,yerr=dY,fmt='b.')
    ax32.axhline(y=0,color='#e41a1c')
    ax32.set_title('Residui')
    ax32.set_ylabel('R[]')
    ax32.set_xlabel('X[]')
    ax32.grid()

    #finishing
    # fig3.suptitle('Proporzione lineare sui grafici loglog Y=A_log+B_log*X',fontsize=16)

    ##PLOT 4
    fig4=plt.figure(figsize=MONO_FIGSIZE)
    #sp1
    ax41=fig4.add_subplot(1,1,1)
    for i in [[dg,'#e41a1c','dg'],[dg_l,'#377eb8','dg_l'],[dg_t,'#4daf4a','dg_t']]:
        ax41.plot(x,i[0],'bo',color=i[1],label=i[2])
        ax41.plot(x,i[0],'--',color=i[1])
    ax41.set_ylabel('dg ['+l_units+'*'+t_units+'^-2]')
    ax41.set_xlabel('L ['+l_units+']')
    #finishing
    legend41 = ax41.legend(loc='upper right', shadow=True)
    # legend41.get_frame().set_facecolor('#00FF69')
    fig4.suptitle('Confronto contributo incertezze per g',fontsize=16)

    ##PLOT 5
    fig5=plt.figure(figsize=MONO_FIGSIZE)
    #sp1
    ax51=fig5.add_subplot(1,1,1)
    ax51.errorbar(x,g,xerr=dx,yerr=dg,fmt='b.')
    # ax51.errorbar(x,g_1,xerr=dx,yerr=dg_1,fmt='r.')
    ax51.axhline(y=9.806,color='#000000',label='Tabulato')
    ax51.axhline(y=g0_w,color='#e41a1c',label='Media pesata')
    ax51.axhspan(ymin=g0_w-dg0_w,ymax=g0_w+dg0_w,color='#e41a1c',alpha=.5)
    ax51.axhline(y=g0_m,color='#377eb8',label='Media aritmetica')
    ax51.axhspan(ymin=g0_m-dg0_m,ymax=g0_m+dg0_m,color='#377eb8',alpha=.5)
    ax51.set_title('g=g(l)')
    ax51.set_ylabel('g ['+l_units+'*'+t_units+'^-2]')
    ax51.set_xlabel('L ['+l_units+']')
    legend51 = ax51.legend(loc='lower right', shadow=True)
    #legend51.get_frame().set_facecolor('#00FF69')
    #finishing
    fig5.suptitle('Dipendenza di g da l',fontsize=16)

    ##PLOT 6
    fig6=plt.figure(figsize=MONO_FIGSIZE)
    #sp1
    ax61=fig6.add_subplot(1,1,1)
    ax61.errorbar(x,g,xerr=dx,yerr=dg,fmt='b.')
    ax61.axhline(y=9.806,color='#000000',label='Tabulato')
    ax61.axhline(y=g0_a,color='#4daf4a',label='Da a')
    ax61.axhspan(ymin=g0_a-dg0_a,ymax=g0_a+dg0_a,color='#4daf4a',alpha=.5)
    ax61.set_title('g=g(l)')
    ax61.set_ylabel('g ['+l_units+'*'+t_units+'^-2]')
    ax61.set_xlabel('L ['+l_units+']')
    legend61 = ax61.legend(loc='lower right', shadow=True)
    #legend61.get_frame().set_facecolor('#00FF69')
    #finishing
    fig6.suptitle('Dipendenza di g da l (considerando a)',fontsize=16)

    ##PLOT 7
    fig7=plt.figure(figsize=MONO_FIGSIZE)
    #sp1
    ax71=fig7.add_subplot(1,1,1)
    ax71.errorbar(x,g,xerr=dx,yerr=dg,fmt='b.',label='Pendolo semplice')
    ax71.errorbar(x,g_1,xerr=dx,yerr=dg_1,fmt='r.',label='Pendolo fisico')
    ax71.axhline(y=g0_w,color='b',label='Media pesata pendolo semplice')
    ax71.axhline(y=g0_1w,color='r',label='Media pesata pendolo fisico')
    ax71.axhline(y=9.806,color='#000000',label='Tabulato')
    ax71.axhspan(ymin=g0_w-dg0_w,ymax=g0_w+dg0_w,color='b',alpha=.2)
    ax71.axhspan(ymin=g0_1w-dg0_1w,ymax=g0_1w+dg0_1w,color='r',alpha=.2)
    ax71.set_title('g=g(l)')
    ax71.set_ylabel('g ['+l_units+'*'+t_units+'^-2]')
    ax71.set_xlabel('L ['+l_units+']')
    legend71 = ax71.legend(loc='lower right', shadow=True)
    #legend71.get_frame().set_facecolor('#00FF69')
    #finishing
    fig7.suptitle('Dipendenza di g da l',fontsize=16)

    ##PLOT 8
    fig8=plt.figure(figsize=MONO_FIGSIZE)
    #sp1
    ax81=fig8.add_subplot(1,1,1)
    ax81.errorbar(x,g,xerr=dx,yerr=dg,fmt='b.',label='Pendolo semplice')
    ax81.errorbar(x,g_1,xerr=dx,yerr=dg_1,fmt='r.',label='Pendolo fisico')
    ax81.axhline(y=g0_1m,color='b',label='Media aritmetica')
    ax81.axhline(y=g0_1w,color='r',label='Media pesata')
    ax81.axhline(y=9.806,color='#000000',label='Tabulato')
    ax81.axhspan(ymin=g0_1m-dg0_1m,ymax=g0_1m+dg0_1m,color='b',alpha=.2)
    ax81.axhspan(ymin=g0_1w-dg0_1w,ymax=g0_1w+dg0_1w,color='r',alpha=.2)
    # ax71.set_title('g=g(l)')
    ax81.set_ylabel('g ['+l_units+'*'+t_units+'^-2]')
    ax81.set_xlabel('L ['+l_units+']')
    legend71 = ax81.legend(loc='lower right', shadow=True)
    #legend71.get_frame().set_facecolor('#00FF69')
    #finishing
    fig8.suptitle('Dipendenza di g da l',fontsize=16)

    # plt.show()
    fig1.savefig('Relazione/fig 3/fig1.png', transparent=False, dpi=160, )
    fig2.savefig('Relazione/fig 3/fig2.png', transparent=False, dpi=160, )
    fig3.savefig('Relazione/fig 3/fig3.png', transparent=False, dpi=160, )
    fig4.savefig('Relazione/fig 3/fig4.png', transparent=False, dpi=160, )
    fig5.savefig('Relazione/fig 3/fig5.png', transparent=False, dpi=160, )
    fig6.savefig('Relazione/fig 3/fig6.png', transparent=False, dpi=160, )
    fig7.savefig('Relazione/fig 3/fig7.png', transparent=False, dpi=160, )
    fig8.savefig('Relazione/fig 3/fig8.png', transparent=False, dpi=160, )


# ======================================
# ==== 紅外線熱影像程式碼[目前沒使用] ====
# ======================================
import cv2
import numpy as np
import time
import datetime
from PIL import Image
import os
import csv

def convert(list):
	return tuple(list)

def contrast_brightness_image(img, a, b): #img, 對比度, 亮度
	h, w, ch = img.shape
	blank = np.zeros([h, w, ch], img.dtype)
	dst = cv2.addWeighted(img, a, blank, 1-a, 1-b)

	return dst

def makeBlackImage(): #製造出全黑圖片(10x10)
	pixels = []
	for i in range(0,10):
		row = []
		for j in range(0,10):
			row.append((0,0,0))
		pixels.append(row)

	array = np.array(pixels, dtype=np.uint8)
	newBlack = Image.fromarray(array)
	newBlack = cv2.cvtColor(np.asarray(newBlack),cv2.COLOR_RGB2BGR)
	return newBlack

def Dot2Dot(pA, pB, pos): #點到點的距離
	B1 = np.sqrt(np.square(pA[0] - pos[0]) + np.square(pA[1] - pos[1]))
	B2 = np.sqrt(np.square(pB[0] - pos[0]) + np.square(pB[1] - pos[1]))

	return int((B1+B2)/2)

def line2gate(pA, pB, cm): #設定門檻線
	B = np.sqrt(np.square(pB[0] - pA[0]) + np.square(pB[1] - pA[1]))
	rX = (cm*(pB[0] - pA[0]) + B*pA[0]) / B
	rY = (cm*(pB[1] - pA[1]) + B*pA[1]) / B

	return [int(rX), int(rY)]

def writeData2CSV(fileName, type_, dataRow): #寫入CSV檔
	with open(fileName, type_, newline='') as csvfile:
		# 建立 CSV 檔寫入器
		writer = csv.writer(csvfile)

		# 寫入一列資料
		writer.writerow(dataRow)

def readCSV2List(fileName): #讀取CSV檔
	AllData = []
	with open(fileName, newline='') as csvfile:
	  # 以冒號分隔欄位，讀取檔案內容
	  rows = csv.reader(csvfile, delimiter=',')

	  for row in rows:
	    AllData.append(row)

	return AllData

def listAllSame(list1, list2): #檢查兩陣列是否完全一樣
	if(len(list1) != len(list2)):
		return False
	else:
		for i in range(0,len(list1)):
			if list1[i] != list2[i]:
				return False
		return True

def Second2Datetime(sec): #秒數轉換成時間
	return int(sec/3600), int((sec%3600)/60), int((sec%3600)%60)

class ThermalCAM:
	def __init__(self):
		#變數：狀態變數
		self.WINDOWS_IS_ACTIVE = True #UI狀態
		self.MAZE_IS_RUN = False #當前系統是否在執行
		self.OPEN_CAMERA_WINDOW = False #影像視窗狀態
		self.CAM_IS_CONN = True #當前鏡頭是否連線

		#變數：迷宮相關變數
		self.NOW_STATUS = 0 #目前狀態
		self.ARM_UNIT = 3 #迷宮臂數
		self.TotalFood = 0 #總食物個數
		self.ViewSize = (480, 385) #虛擬視窗顯示大小
		self.TargetPos = [-1, -1] #目標變數
		self.ARMS_POS = [ #三臂遮罩-For0106(480x385)
    		[236, 122], [419,  19], [446,  63],
    		[257, 173], [256, 366], [209, 367],
    		[211, 174], [ 30,  67], [ 55,  27]
		]
		self.ARMS_LINE_POS = [ #三臂遮罩邊-For0106(480x385)
    		[self.ARMS_POS[0], self.ARMS_POS[1],self.ARMS_POS[3],self.ARMS_POS[2]],
    		[self.ARMS_POS[3], self.ARMS_POS[4],self.ARMS_POS[6],self.ARMS_POS[5]],
    		[self.ARMS_POS[6], self.ARMS_POS[7],self.ARMS_POS[0],self.ARMS_POS[8]]
		]
		self.MASK_POS = np.array(self.ARMS_POS)
		self.Food = [] #存放食物在哪臂
		self.FirstIn = [] #第一次進入
		self.Route = [] #記錄進出臂
		self.InLineGate = [] #進入門檻陣列
		self.OutLineGate = [] #退出門檻陣列
		self.ShortTerm = [] #短期記憶陣列
		self.LongTerm = [] #長期記憶陣列
		self.TotalShortTerm = 0 #總短期記憶
		self.TotalLongTerm = 0 #總長期記憶
		self.Latency = 0 #總時間長度
		self.filePath = "" #寫入的檔案路徑
		self.RatID = "" #老鼠編號
		self.setTime = datetime.datetime.now() #開始前時間
		self.nowTime = datetime.datetime.now() #現在時間

	def getArmUnit(self): #取得迷宮臂數
		return self.ARM_UNIT

	def getMazeArmsPos(self): #取得迷宮座標點
		return self.ARMS_POS

	def getViewHW(self): #取得虛擬視窗顯示大小
		return self.ViewSize

	def getCameraStatus(self): #取得鏡頭狀態
		return self.CAM_IS_CONN

	def getTargetPos(self): #取得經過處理後取得的座標
		return self.TargetPos

	def getMazeStatus(self): #取得系統運行狀態
		return self.MAZE_IS_RUN

	def getTerm(self): #取得短期/長期記憶
		return self.ShortTerm, self.LongTerm

	def getRoute(self): #取得進出臂順序
		return self.Route

	def getLatency(self): #取得目前總時間長度
		return self.Latency

	def getArmMask(self): #取得壁迷宮遮罩
		image = makeBlackImage()
		image = cv2.resize(image, (self.ViewSize[0],self.ViewSize[1]), interpolation=cv2.INTER_CUBIC) #圖片放大
		image = cv2.fillPoly(image, [self.MASK_POS], (255, 255, 255)) #實心多邊形
		gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #灰階影像
		ret,th1 = cv2.threshold(gray,25,255,cv2.THRESH_BINARY) #二值化

		return th1

	def setMazeStatus(self, status): #設定系統運行狀態
		self.MAZE_IS_RUN = status

	def setInterfaceStatus(self, status): #設定UI狀態
		self.WINDOWS_IS_ACTIVE = status

	def setCameraWindow(self, status): #設定影像視窗狀態
		self.OPEN_CAMERA_WINDOW = status

	def setFoodWithArm(self, total, food): #設定食物陣列
		self.TotalFood = total
		self.Food = food

	def setFilePath(self, filepath): #設定檔案寫入路徑
		self.filePath = filepath

	def setRatID(self, ratid): #設定老鼠編號
		self.RatID = ratid

	def setArmGate(self, cm): #設定臂門檻線
		result = []
		for x in range(0,self.ARM_UNIT):
			xA = line2gate(self.ARMS_LINE_POS[x][0], self.ARMS_LINE_POS[x][1], cm)
			xB = line2gate(self.ARMS_LINE_POS[x][2], self.ARMS_LINE_POS[x][3], cm)
			result.append([xA, xB])

		return result

	def virtualCam(self, pid): #模擬鏡頭運行
		speed = 10
		image = cv2.imread("./test/0106/0106-%d.png" %(int(pid/speed) + 1))
		if pid < (60 - 1)*speed:
			pid = pid + 1
		else:
			pid = 1

		return pid, image

	def CatchItemPos(self, img):
		mask = self.getArmMask() #取得遮罩
		original = cv2.bitwise_and(img, img, mask = mask) #圖片套用遮罩
		newPhoto = contrast_brightness_image(original,3.2,100)
		#影像分層
		grayR = newPhoto[:,:,2]
		grayG = newPhoto[:,:,1]
		grayB = newPhoto[:,:,0]
		#取得白色區域
		ret,thR = cv2.threshold(grayR,200,255,cv2.THRESH_BINARY) #有貼紅標記點
		ret,thG = cv2.threshold(grayG,200,255,cv2.THRESH_BINARY)
		ret,thB = cv2.threshold(grayB,200,255,cv2.THRESH_BINARY)
		thA = thR & thG & thB

		contours,hierarchy = cv2.findContours(thA,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #取得物體邊緣做標

		mid = [-1, -1]
		for i in range(0,len(contours)):
		    cnt=contours[i]
		    pt1 = np.min(cnt, axis=0) #左上座標
		    pt2 = np.max(cnt, axis=0) #右下座標
		    midX = (pt2[0][0] - pt1[0][0])/2 + pt1[0][0]
		    midY = (pt2[0][1] - pt1[0][1])/2 + pt1[0][1]
		    mid = [int(midX), int(midY)]
		    # cv2.rectangle(img, convert(pt1[0]), convert(pt2[0]), (0,255,0), 1) #繪製矩形

		return mid

	def initDefault(self):
		self.Route = []
		self.FirstIn = []
		self.ShortTerm = []
		self.LongTerm = []
		self.setTime = datetime.datetime.now()
		self.TotalShortTerm = 0
		self.TotalLongTerm = 0
		for i in range(0,self.ARM_UNIT):
			self.FirstIn.append(0)
			self.ShortTerm.append(0)
			self.LongTerm.append(0)

	def computeTerm(self, arm): #紀錄記憶錯誤
		if self.FirstIn[arm] == 0:
			if(self.Food[arm] == 1):
				self.TotalFood = self.TotalFood - 1
			else:
				self.LongTerm[arm] = self.LongTerm[arm] + 1
				self.TotalLongTerm = self.TotalLongTerm + 1
			self.FirstIn[arm] = 1
		else:
			self.ShortTerm[arm] = self.ShortTerm[arm] + 1
			self.TotalShortTerm = self.TotalShortTerm + 1

	def checkGate(self, st):
		newDot = [self.TargetPos[0], self.TargetPos[1]]
		if(st == 0):
			for x in range(0,self.ARM_UNIT):
				d = Dot2Dot(self.InLineGate[x][0],self.InLineGate[x][1], newDot)
				# print("d%d = %d" %(x,d))
				if(d < 30):
					# print("d%d = %d" %(x,d))
					self.computeTerm(x)
					st = x+1
					return st
		else:
			x = st - 1
			d = Dot2Dot(self.OutLineGate[x][0],self.OutLineGate[x][1], newDot)
			if(d < 30):
				self.Route.append(st)
				st = 0
		return st

	def DataRecord(self):  #寫入csv
		csvTitle = ["Rat ID", "Food", "Total LongTerm", "Total ShortTerm", "Route", "Latency"]
		nLate = Second2Datetime(self.Latency)
		newLatency = "%02d:%02d:%02d" %(nLate[0],nLate[1],nLate[2])
		MazeData = [self.RatID, self.Food, self.TotalLongTerm, self.TotalShortTerm, self.Route, newLatency]
		if os.path.isfile(self.filePath):
			csvData = readCSV2List(self.filePath)
			if not (listAllSame(csvData[0],csvTitle)):
				writeData2CSV(self.filePath, "w", csvTitle)
		else:
			writeData2CSV(self.filePath, "w", csvTitle)
		writeData2CSV(self.filePath, "a", MazeData)

	def CameraMain(self): #這個副程式是"主程式"呦~~~~~
		pid = 1
		#設定門檻線
		self.InLineGate = self.setArmGate(60) #設定進入門檻線
		self.OutLineGate = self.setArmGate(10) #設定退出門檻線
		self.initDefault() #初始化變數

		RUN_FIRST_TIME = False
		while self.WINDOWS_IS_ACTIVE:

			#影像擷取
			pid, frame = self.virtualCam(pid)
			frame = cv2.resize(frame, (self.ViewSize[0],self.ViewSize[1]), interpolation=cv2.INTER_CUBIC)

			self.TargetPos = self.CatchItemPos(frame) #取得目標座標
			if self.MAZE_IS_RUN:
				if not RUN_FIRST_TIME:
					self.initDefault() #初始化變數
					RUN_FIRST_TIME = True
				else:
					self.NOW_STATUS = self.checkGate(self.NOW_STATUS) #檢查目前狀態
					if self.TotalFood != 0:
						self.nowTime = datetime.datetime.now()
						self.Latency = (self.nowTime - self.setTime).seconds

					if self.NOW_STATUS == 0 and self.TotalFood == 0:
						self.DataRecord()
						self.MAZE_IS_RUN = False
						RUN_FIRST_TIME = False
			else:
				RUN_FIRST_TIME = False

			#開視窗查看影像
			if self.OPEN_CAMERA_WINDOW:
				showFrame = cv2.resize(frame, (self.ViewSize[0],self.ViewSize[1]), interpolation=cv2.INTER_CUBIC)
				cv2.polylines(showFrame, [self.MASK_POS], True, (0, 255, 255), 2)  #加上3臂輔助線

				msgBoard = makeBlackImage()
				msgBoard = cv2.resize(msgBoard, (self.ViewSize[0],30), interpolation=cv2.INTER_CUBIC)
				msgText = "If you want to exit, press 'Camera' Button again to exit."
				cv2.putText(msgBoard, msgText, (10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,255))

				CamBoard = np.vstack([showFrame, msgBoard])
				cv2.imshow('Camera Image', CamBoard)

				if cv2.waitKey(1) and (not self.OPEN_CAMERA_WINDOW):
					cv2.destroyWindow("Camera Image")
			else:
				cv2.destroyWindow("Camera Image")


from typing import List

class Solution:
    def maxArea(self, height: List[int]) -> int:
        maxa = 0
        l, r = 0, (len(height) - 1)

        while l < r:
            max_temp = (r - l) * min(height[l], height[r])
            if max_temp > maxa:
                maxa = max_temp

            if height[r] < height[l]:
                r -= 1
            else:
                l += 1

        return maxa


# -*- coding: utf-8 -*-
numbers = [2, 3, 5, 7, 11, 13, 17, 19]

# 인덱스와 원소 출력
# 코드를 입력하세요.
for i in range(len(numbers)):
    print(i, numbers[i])

# print 함수는 print(*objests, sep=' ', end='\n', file=sys.stdout, flush=False): 와 같이 정의되어 있다.
# 여기서 *objests가 있기 때문에 ',' 뒤에 다른 값을 써 주면 다른 값도 같이 출력된다.
# '*파라미터변수'는 ','를 이용하여 여러  값을 받아서 출력할 수 있다.
# sep=' '가 기본적으로 정해저 있어서 ','로 구분 된 값 사이에 공백이 포함되어 출력되고
# end='\n'으로 인해 print 함수 출력 후 한 줄 개행이 된다.


# pelo longo
# pernas curtas
# faz auau
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score

porco1 = [0, 1, 0]
porco2 = [1, 1, 0]
porco3 = [1, 0, 0]

cachorro1 = [0, 1, 1]
cachorro2 = [1, 1, 1]
cachorro3 = [1, 0, 1]

treino_x = [porco1, porco2, porco3, cachorro1, cachorro2, cachorro3]
treino_y = [1, 1, 1, 0, 0, 0]  # 0 cachorro # 1 porco

modelo = LinearSVC() #cerebro vazio
modelo.fit(treino_x, treino_y) #encaixar esses dados no modelo

animal_misterioso = [1, 1, 1] # tem pelo longo perna curta e faz auau

print(modelo.predict([animal_misterioso])) # print 0 porque é cachorro

misterio1 = [1,1,1] # tem pelo longo perna curta e faz auau
misterio2 = [1,1,0] # tem pelo longo perna curta e não faz auau
misterio3 = [0,1,1] # não tem pelo longo perna curta e faz auau

testex = [misterio1, misterio2, misterio3]
testey =[0,1,1] # eu sei que apenas o primeiro é um cachorro

previsoes = modelo.predict(testex)
print(previsoes) # cachorro, porco, cachorro
print(accuracy_score(previsoes,testey)) # accuracy tive uma taxa de acerto de 66%


from itertools import product

import pytest
from pytest import list_of

from ..jigfyp import _encode_keys, Jigfyp, _decode_key

key_mapping = [
    ((b'abc', b'def'), {'key_from': b'abc!def', 'key_to': b'abc!def~'}),
]

@pytest.mark.parametrize('key_prefix, keys', key_mapping)
def test_encode_keys_specific(key_prefix, keys):
    delimiter = b'!'
    highest_character = b'~'
    assert _encode_keys(delimiter, highest_character, key_prefix) == keys

@pytest.mark.parametrize('delimiter, highest_character', product('!,', '~0'))
@pytest.mark.randomize(min_num = 0, max_num = 1,
                       max_length = 5, # So errors are easy to read
                       ncalls = 3, encoding = 'ascii')
def test_encode_keys_random(delimiter, highest_character, key_prefix:list_of(str)):
    kp = tuple(k.replace(delimiter, '').replace(highest_character, '').encode('ascii') for k in key_prefix)
    d = delimiter.encode('ascii')
    h = highest_character.encode('ascii')
    keys = _encode_keys(d, h, kp)
    assert set(keys) == {'key_from', 'key_to'}
    assert isinstance(keys, dict)
    if len(key_prefix) == 0:
        for name in ['key_from', 'key_to']:
            assert keys[name] == None
    else:
        assert keys['key_to'].endswith(h)
        for name in ['key_from', 'key_to']:
            assert keys[name].count(d) == len(key_prefix) - 1

        assert len(keys['key_from']) + 1 == len(keys['key_to'])

decodings = [
    (b'!', b'ab!cd!efg', (b'ab', b'cd', b'efg')),
]
@pytest.mark.parametrize('delimiter, encoded, decoded', decodings)
def test_decode_key(delimiter, encoded, decoded):
    assert _decode_key(delimiter, encoded) == decoded


def string_xor(a: str, b: str) -> str:
    """ Input are two strings a and b consisting only of 1s and 0s.
    Perform binary XOR on these inputs and return result also as a string.
    >>> string_xor('010', '110')
    '100'
    """
    """
    Inputs:
    a: A binary string of 1s and 0s
    b: A binary string of 1s and 0s
    Returns:
    A binary string that is the result of performing XOR operation on 'a' and 'b'.

    Examples:
    >>> string_xor('010', '110')
    '100'
    >>> string_xor('10101', '11111')
    '01010'
    >>> string_xor('00000', '10101')
    '10101'
    """

    if len(a) != len(b):
        raise ValueError("Strings should have the same length")

    res = ''

    for i in range(len(a)):
        if a[i] == b[i]:
            res += '0'
        else:
            res += '1'

    return res

def check(candidate):
    assert candidate('111000', '101010') == '010010'
    assert candidate('1', '1') == '0'
    assert candidate('0101', '0000') == '0101'

def test_check():
    check(string_xor)

test_check()


"""
题目相对好理解，给定两个列表puzzles和words，求满足两个条件的各有多少个：
    1.word contains the first letter of puzzle.
    2.For each letter in word, that letter is in puzzle.

"""

class Solution(object):
    """
    简单粗暴遍历，果断超时
    """
    def findNumOfValidWords(self, words, puzzles):
        """
        :type words: List[str]
        :type puzzles: List[str]
        :rtype: List[int]
        """
        res = []
        for puzzle in puzzles:
            index = 0
            for word in words:
                if puzzle[0] in word:
                    flag = 1
                    for i in word:
                        if i not in set(puzzle):
                            flag = 0
                            break
                    if flag:
                        index += 1
            res.append(index)
        return res

class Solution2(object):
    def findNumOfValidWords(self, words, puzzles):
        """
        :type words: List[str]
        :type puzzles: List[str]
        :rtype: List[int]
        """
        count = collections.Counter(frozenset(w) for w in words)
        res = []
        for p in puzzles:
            subs = [p[0]]
            for c in p[1:]:
                subs += [s + c for s in subs]
            res.append(sum(count[frozenset(s)] for s in subs))
        return res

contest/week152/1178. Number of Valid Words for Each Puzzle.py


import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy

import time

class CarrierClass:
    pass

global carrier
carrier = CarrierClass()

vertex_shader = """
#version 330
in vec4 position;
void main() {
    gl_Position = position;
}
"""
fragment_shader = """
#version 330
void main() {
    gl_FragColor = vec4(1.0f, 0.0f, 0.0f, 1.0f);
}
"""
shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
    OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

VBO = glGenBuffers(1)
glBindBuffers(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, 36, coords, GL_STATIC_DRAW)

vboPos = glGetAttribLocation(shader, "position")
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 0, None)
glEnableVertexAttribArray(position)
glUseProgram(shader)

coords_f64 = [
    -0.5, -0.5, 0.0,
    0.5, -0.5, 0.0,
    0.0, 0.5, 0.0
]
coords_f32 = numpy.array(coords_f64, dtype = numpy.float32)

def main():
    # see if glfw is even working
    if not glfw.init():
        print("glfw failed lmao")
        return

    # create a window
    carrier.window = glfw.create_window(800, 600, "m i n e c r a f t", None, None)
    if not carrier.window:
        print("window creation failed lmao")
        glfw.terminate()
        return

    glfw.make_context_current(carrier.window)

    glClearColor(0.0, 0.0, 0.0, 1.0)

    # g a m e  l o o p
    while not glfw.window_should_close(carrier.window):
        time.sleep(0.01)
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT)

        glDrawArrays(GL_TRIANGLES, 0, 3)

        glfw.swap_buffers(carrier.window)

    glfw.terminate()

main()


from flask import (render_template, url_for, flash, current_app,
                   redirect, request, abort, Blueprint)
from flask_login import current_user, login_required
#from flaskblog import db
from flask_googlemaps import GoogleMaps, Map
from flask_googlemaps import get_address, get_coordinates
from geopy.distance import great_circle
import json

maps = Blueprint('maps', __name__)

@maps.route("/map/offerhelp", methods=['GET', 'POST'])
def map_offerhelp():
    locations = []  # long list of coordinates
    place = get_coordinates(current_app.config['GOOGLEMAPS_KEY'], 'M4Y0C4')
    place['infobox'] = "Hello World"
    locations.append(place)

    place = get_coordinates(current_app.config['GOOGLEMAPS_KEY'], 'M4Y0C4')
    place['infobox'] = "Hello World from other place"
    locations.append(place)

    map_offerhelp = Map(
        identifier="map_offerhelp",
        style=(
            "height:350px;"
            "width:700px;"
        ),
        lat=locations[0]['lat'],
        lng=locations[0]['lng'],
        markers=[(loc['lat'], loc['lng'], loc['infobox']) for loc in locations],
        fit_markers_to_bounds=True
    )
    place1 = [locations[0]['lat'], locations[0]['lng']]
    place2 = [locations[1]['lat'], locations[1]['lng']]
    print("Distance:{}km".format(great_circle(place1, place2).km))
    return render_template('map_offerhelp.html', map_offerhelp=map_offerhelp)


import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
import csv

class Credito:
	def __init__(self, train_dir, test_dir, max_iter=100):
		"""
		train: direktori data train
		test: direktori data test
		"""
		self.train_dir = train_dir
		self.test_dir = test_dir
		self.train_data = []
		self.train_target = []
		self.test_data = []
		self.test_target = []
		self.encoder = LabelEncoder()

	def preprocessing(self):
		"""
		return: None
		"""
		train_reader = csv.DictReader(open(self.train_dir, 'r'), delimiter=",")
		for row in train_reader:
			self.train_data.append([float(row["BUSAGE"]),
									int(row["MAXLINEUTIL"]),
									float(row["DAYSDELQ"]),
									float(row["TOTACBAL"])]
								)

			self.train_target.append(row["DEFAULT"])

		train_reader = csv.DictReader(open(self.test_dir, 'r'), delimiter=",")
		for row in train_reader:
			self.test_data.append([
									row["BUSAGE"],
									row["MAXLINEUTIL"],
									row["DAYSDELQ"],
									row["TOTACBAL"]]
								)

			self.test_target.append(row["DEFAULT"])

		print(self.train_target)

		# convert data to numpy array
		self.train_data = np.array(self.train_data)
		self.test_data = np.array(self.test_data)

		# convert target to numpy array
		self.label = self.encoder.fit(self.train_target)
		self.label = self.label.transform(self.train_target)
		self.test_target = np.array(self.test_target)

		assert len(self.test_target) == len(self.test_data)

	def train(self, max_iter=100):
		"""
		params:
		max_iter -> banyak iterasi:int
		"""
		self.model = LogisticRegression(max_iter=max_iter)
		self.model.fit(self.train_data, self.label)

if __name__ == '__main__':
	test_dir = "data/test.csv"
	train_dir = "data/train.csv"

	credito = Credito(train_dir, test_dir, max_iter=1000)
	credito.preprocessing()
	credito.train()


"""
Test the double function learnt solution with a theoretical solution. Change
the coefficient C to find the best theoretical fit to the learnt augmented
solution. If the sign of C flips then the augmented trajectory will flip in
the t axis
"""

import matplotlib.pyplot as plt
from matplotlib import rc as rc
import seaborn as sns
import numpy as np
import scipy.integrate as integrate
import argparse

filename = 'results./double_func./not_mixed./'

parser = argparse.ArgumentParser()
parser.add_argument('--C', type=float, default=1)
args = parser.parse_args()

#solve the ode
omega = 1
gamma = 0.1667
times = np.linspace(0, 10, 50)

#change C to change the theoretical augmented trajectory
C = args.C

def derivatives(z, t):
    x = z[0]
    a = z[1]
    vx = C*a - omega*x - gamma*x + omega
    va = omega*a - gamma*a -(2*omega**2*x + gamma*omega - omega**2)/C
    return np.array([vx, va])

start = [0, 1]
colours = ['#004488', '#BB5566']
names = ['sin', 'cos']
def run_ode(x):
    z0 = [start[x], 0]
    z_arr = integrate.odeint(derivatives, z0, times)
    z_arr = np.transpose(z_arr)
    x_arr = z_arr[0]
    a_arr = z_arr[1]
    np.save(filename+names[x]+'_theory_x.npy', x_arr)
    np.save(filename+names[x]+'_theory_a.npy', a_arr)

run_ode(0)
run_ode(1)

# load data
theory_sin_z = np.load(filename+'sin_theory_x.npy')
theory_sin_a = np.load(filename+'sin_theory_a.npy')
theory_cos_z = np.load(filename+'cos_theory_x.npy')
theory_cos_a = np.load(filename+'cos_theory_a.npy')

learnt_f1 = np.load(filename+'learnt_f1.npy')
learnt_f2 = np.load(filename+'learnt_f2.npy')
samp_ts = np.load(filename+'ts.npy')
real_f1 = np.load(filename+'real_f1.npy')
real_f2 = np.load(filename+'real_f2.npy')
learnt_a1 = np.load(filename+'learnt_a1.npy')
learnt_a2 = np.load(filename+'learnt_a2.npy')

#plot figure
sns.set_style('dark')
rc('font', family='serif')
rc('text', usetex=True)
plt.figure()
rc('font', family='serif')
rc('text', usetex=True)
plt.plot(samp_ts, learnt_f1, color='#004488', label='Learnt $x_{1}$', linewidth=2.2)
plt.scatter(samp_ts, real_f1, color='#004488', s=25)
plt.plot(samp_ts, theory_sin_a, color='#DDAA33', label='Theory $a_{1}$', linewidth=2.2)
plt.plot(samp_ts, learnt_a1, color = '#004488', label='Learnt $a_{1}$', linestyle='--', linewidth=2.3)
plt.plot(samp_ts, learnt_f2, color='#BB5566', label='Learnt $x_{2}$', linewidth=2.2)
plt.scatter(samp_ts, real_f2, color='#BB5566', s=25)
plt.plot(samp_ts, theory_cos_a, color='#DDAA33', label='Theory $a_{2}$', linewidth=2.2)
plt.plot(samp_ts, learnt_a2, color='#BB5566', label='Learnt $a_{2}$', linestyle='--', linewidth=2.3)
plt.xlabel('t', fontsize=18)
plt.ylabel('$x_{1}, x_{2}, a_{1}, a_{2}$', fontsize=18)
plt.title('ANODE(1) Double Function C = '+str(args.C), fontsize=20)
plt.legend(ncol=2, fontsize=12)
plt.savefig('not_mixed_double_func_with_theory_a.png')


import sys
import gspread
from google.oauth2.service_account import Credentials
import argparse
import pickle
import datetime
from .Google import Create_Service

class SheetOps:

    def __init__(self):
        self.CLIENT_SECRET_FILE = 'client_secret.json'
        self.API_NAME = 'drive'
        self.API_VERSION = 'v3'

        self.SCOPES = [
                'https://www.googleapis.com/auth/drive',
                'https://www.googleapis.com/auth/drive.file',
                'https://www.googleapis.com/auth/spreadsheets'
            ]
        self.service = Create_Service(self.CLIENT_SECRET_FILE, self.API_NAME, self.API_VERSION, self.SCOPES)

        self.credentials = Credentials.from_service_account_file(
                    filename='service_account.json',
                    scopes=self.SCOPES
                )

        self.gc = gspread.authorize(self.credentials)
        self.args_list = []

        self.parser = argparse.ArgumentParser()

        self.subparser = self.parser.add_subparsers(dest="command")

        self.new = self.subparser.add_parser("new", help="Create new spreadsheet")
        self.init = self.subparser.add_parser("init", help="Initialize objects")
        self.commit = self.subparser.add_parser("commit", help="Commit changes")
        self.push = self.subparser.add_parser("push", help="Push changes")
        self.folder = self.subparser.add_parser('folder', help="Create a drive folder")

        self.folder.add_argument('-f', '--folder', metavar='', type=str, required=True, help='Specify folder name')
        self.new.add_argument('-n', '--name', metavar='', type=str, required=True, help='Name of spreadsheet')
        self.new.add_argument('-dir', '--directory', metavar='', type=str, required=False, help='Directory Name')
        self.init.add_argument('-q', '--question', metavar="", type=str, required=True, help="Leetcode Question")
        self.init.add_argument('-t', '--time', metavar="", type=str, required=True, help="Time spent on question")
        self.init.add_argument('-f', '--fail', metavar="", type=bool, required=True, help="Failed or not")
        self.init.add_argument('-qt', '--tag', metavar="", type=str, required=True, help="Tag of the question")
        self.init.add_argument('-m', '--message', metavar="", type=str, required=True, help="Commit message")
        self.push.add_argument('-url', '--url', metavar="", type=str, required=True, help="File url")
        self.args = self.parser.parse_args()

    def create_folder(self):
        url_temp = 'https://drive.google.com/drive/u/0/folders/'
        file_metadata = {
            'name': self.args.folder,
            'mimeType': 'application/vnd.google-apps.folder'
        }
        file = self.service.files().create(body=file_metadata,
                                            fields='id').execute()

        file_url = url_temp + file['id']

        print(file['id'])

    def new_spreadsheet(self):
        #folder_id
        response = self.gc.create(title=self.args.name, folder_id=self.args.directory)
        sht = self.gc.open_by_key(response.id).sheet1

        self.gc.insert_permission(
            file_id=response.id,
            value='leetbot@leettracker-343018.iam.gserviceaccount.com',
            perm_type='user',
                role='writer'
        )

        self.gc.insert_permission(
                file_id=response.id,
                value=None,
                perm_type='anyone',
                role='writer'
            )

        sht.insert_row(values=(
                'LeetCode Question',
                'Time spent',
                'Commit Message',
                'isFailed',
                'date',
                'tag'
            ),
            index=1)

        sample_url = 'https://docs.google.com/spreadsheets/d/'
        file_id = sample_url + response.id + '/edit#gid=0'

        print(file_id)

    def initializer(self):
        now = datetime.datetime.now()
        date = now.strftime("%d/%m/%Y, %H:%M:%S")
        args_dict = {
            'Leetcode Question': self.args.question,
            'Time spent': self.args.time,
            'isFailed': self.args.fail,
            'Commit message': self.args.message,
            'Date': date,
            'Question Tag': self.args.tag
        }

        pickle_out = open("dict.pickle","wb")
        pickle.dump(args_dict, pickle_out)
        pickle_out.close

    def insert_values(self):
        """
            args_dict = {
            'Leetcode Question': self.args.question,
            'Time spent': self.args.time,
            'isFailed': self.args.fail,
            'Commit message': self.args.message,
            'Date': self.args.date,
            'Question Tag': self.args.tag
        }
        """
        sht = self.gc.open_by_url(self.args.url).sheet1
        pickle_in = open("dict.pickle","rb")
        example_dict = pickle.load(pickle_in)
        lst = [
            example_dict['Leetcode Question'],
            example_dict['Time spent'],
            example_dict['Commit message'],
            example_dict['isFailed'],
            example_dict['Date'],
            example_dict['Question Tag'],
        ]

        sht.insert_row(
            values= lst,
            index=2
        )

        print('File updated successfully')


from statistics import mean, median, variance, correlation
import csv

def load_data(path):
    """
    Loads data from given csv
    :param path: path to csv file
    :return: returns data as dict {name_of_feature: list_of_values}
    """
    with open(path, 'r') as f:
        reader = csv.reader(f)
        read_header = None
        data = {}
        index_to_column_name = {}
        for row in reader:
            if not read_header:
                # we are at first row with names of columns
                for i, column_name in enumerate(row):  # enumerate generates index together with value
                    data[column_name] = []  # initializing as empty list
                    index_to_column_name[i] = column_name
                read_header = True
            else:
                # need to append values to data lists. We don't know column name, only index.
                for i, value in enumerate(row):
                    current_column_name = index_to_column_name[i]  # reproducing column name
                    data[current_column_name].append(float(value))
    return data

def run_analysis():
    """
    the function that used to calculate for the main function purpose
           """
    file_path = './winequality.csv'
    data = load_data(file_path)

    # first way of printing. Everything casted to string, and spaces put automatically between passed values.
    print('Number of features:', len(data))
    for feature_name, list_of_values in sorted(data.items()):
        # second way of printing. We print single string after format function.
        # Format function fills {} with values passed as arguments. It has nice applications for better printing,
        # like limiting number of digits for floats or other formatting tools.
        print('"{}". Mean: {:3.2f}, Median: {:.2f}, Std: {:.4f}'.format(
            feature_name, mean(list_of_values), median(list_of_values), variance(list_of_values)**0.5))

    # here you should compute correlations. Be careful, pair should be sorted before printing
    min_1 = 2
    max_1 = -2
    strongest_pair = []
    weakest_pair = []

    for index in range(len(data.items())-1):
        feature_name_1, list_of_values_1 = list(data.items())[index]
        for index_2 in range(index+1, len(data.items())):
            feature_name_2, list_of_values_2 = list(data.items())[index_2]
            cor = correlation(list_of_values_1, list_of_values_2)
            if abs(cor) < abs(min_1):
                min_1 = cor
                weakest_pair = sorted([feature_name_1, feature_name_2])
            if cor > max_1:
                max_1 = cor
                strongest_pair = sorted([feature_name_1, feature_name_2])

    high_correlation = max_1
    print('The strongest linear relationship is between: "{}","{}". '
          'The value is: {:.4f}'.format(strongest_pair[0], strongest_pair[1], high_correlation))

    low_correlation = min_1
    print('The weakest linear relationship is between: "{}","{}". '
          'The value is: {:.4f}'.format(*weakest_pair, low_correlation))  # * converts list to arguments.
    # Line 53 is equivalent to line 48, this is just other way to use list as arguments

if __name__ == '__main__':
    """ Calculates and prints the 2 variables with the highest correlation
    and the 2 variables with the lowest correlation,all by lexicography order.
    the variables are the features in the data collected in winequality.csv and winequality_2.csv
       """
    run_analysis()


from unittest import TestCase
from public import script

class PrivateTestSuite(TestCase):

    # If this test passes, that does not mean that you will get any points.
    # The grading system uses different, more exhaustive tests.

    # Feel free to extend the class with your own test cases,
    # which will then also be executed in every "Test & Run".

    # Check if the return type is dict
    def test_return_type_reverse_index(self):
        dataset = [
            "Hello world",
            "This is the WORLD",
            "hello again"
        ]
        actual = script.reverse_index(dataset)
        message = "@@Expected return type is dict but {} is returned !@@".format(type(actual).__name__)
        self.assertIsInstance(actual,dict,message)

Informatics I/005 Tuples, Lists, and Dictionaries/Task 3 Reverse Indexing/Template/public/tests.py


"""Update departments metadata for website(s)"""  # noqa: INP001
from functools import reduce

from django.db import transaction
from django.db.models import Q

from main.management.commands.filter import WebsiteFilterCommand
from websites.models import WebsiteContent

class Command(WebsiteFilterCommand):
    """Update departments metadata for website(s)"""

    help = __doc__  # noqa: A003

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "-d",
            "--departments",
            dest="departments",
            nargs="*",
            help="Departments to add to the courses",
            required=True,
        )

        parser.add_argument(
            "-s",
            "--startswith",
            dest="startswith",
            nargs="*",
            help="Identifiers to filter websites based on istartswith lookup",
            required=True,
        )

    def handle(self, *args, **options):
        super().handle(*args, **options)
        startswith = options["startswith"]
        departments = options["departments"]
        startswith_query_set = [
            "website__name__istartswith",
            "website__short_id__istartswith",
        ]

        query_set = WebsiteContent.objects.filter(
            reduce(
                lambda x, y: x | y,
                [
                    Q(**{key: value})
                    for key, value in zip(startswith_query_set, startswith)
                ],
            ),
        )
        query_set = self.filter_website_contents(website_contents=query_set)

        query_set = query_set.filter(type="sitemetadata")
        self.stdout.write(
            f"Total number of websites updated will be {query_set.count()}"
        )
        with transaction.atomic():
            for sitemetadata in query_set.iterator():
                sitemetadata.metadata["department_numbers"] = list(
                    {*sitemetadata.metadata["department_numbers"], *departments}
                )
                sitemetadata.save()

        self.stdout.write(
            f"Departmensts successfully updated for {query_set.count()} sites"
        )


import pygame as pg
import numpy as np
import random

clock = pg.time.Clock()
FPS = 60

WIDTH = 1920
HEIGHT = 1080

x_gap = 8
y_gap = 16

BLACK = (0, 0, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)

pg.init()

pg.font.init()
my_font = pg.font.SysFont('arial', 16)

txt0 = 'King_W70.txt'
txt1 = 'Queen_W70.txt'
txt2 = 'Jack_W70.txt'
txt3 = '10_heart_W70.txt'
txt4 = '9_heart_W70.txt'
txt5 = '8_heart_W70.txt'
txt6 = '7_heart_W70.txt'
txt7 = '6_heart_W70.txt'
txt8 = '5_heart_W70.txt'
txt9 = '4_heart_W70.txt'
txt10 = '3_heart_W70.txt'
txt11 = '2_heart_W70.txt'
txt12 = 'Ace_heart_W70.txt'

deck = [txt0, txt1, txt2, txt3, txt4, txt5, txt6, txt7, txt8, txt9, txt10, txt11, txt12]

def cards():
    txt = random.choice(deck)
    return txt

txt = cards()

MAP_HEIGHT = sum(1 for line in open(txt))
MAP_WIDTH = sum(1 for char in open(txt).readline()) - 1
# print(f"W =", MAP_WIDTH,'\n'"H =", MAP_HEIGHT)

def asciiTxt(txt):
    with open(txt, 'r') as file:
        data = [file.read().replace('\n', '')]

    ascii_chars = []
    for line in data:
        for char in line:
            ascii_chars.append(char)

    inverted_ascii_chars = ascii_chars[::-1]

    return inverted_ascii_chars

class Projection:
    def __init__(self, width, height, chars):
        self.chars = chars
        self.width = width
        self.height = height
        self.screen = pg.display.set_mode((width, height))
        self.background = BLACK
        pg.display.set_caption('ASCII 3D CARD')
        self.surfaces = {}

    def addSurface(self, name, surface):
        self.surfaces[name] = surface

    def display(self):
        self.screen.fill(self.background)

        for surface in self.surfaces.values():
            i = 0
            for node in surface.nodes:
                self.text = self.chars[i]
                self.text_surface = my_font.render(self.text, False, (WHITE if self.text == '.' else RED))
                self.screen.blit(self.text_surface, (WIDTH // 2 - MAP_WIDTH // 2 * x_gap + node[0],
                                                     HEIGHT // 2 + MAP_HEIGHT // 2 * y_gap + node[1] - y_gap))
                i += 1

    def rotate_x(self, theta):
        for surface in self.surfaces.values():
            center = surface.findCentre()
            c = np.cos(theta)
            s = np.sin(theta)

            matrix = np.array([[1, 0, 0, 0],
                               [0, c, -s, 0],
                               [0, s, c, 0],
                               [0, 0, 0, 1]])

            surface.rotate(center, matrix)

    def rotate_y(self, theta):
        for surface in self.surfaces.values():
            center = surface.findCentre()
            c = np.cos(theta)
            s = np.sin(theta)

            matrix = np.array([[c, 0, s, 0],
                               [0, 1, 0, 0],
                               [-s, 0, c, 0],
                               [0, 0, 0, 1]])

            surface.rotate(center, matrix)

    def rotate_z(self, theta):
        for surface in self.surfaces.values():
            center = surface.findCentre()
            c = np.cos(theta)
            s = np.sin(theta)

            matrix = np.array([[c, -s, 0, 0],
                               [s, c, 0, 0],
                               [0, 0, 1, 0],
                               [0, 0, 0, 1]])

            surface.rotate(center, matrix)

class Object:
    def __init__(self):
        self.nodes = np.zeros((0, 4))

    def addNodes(self, node_array):
        ones_column = np.ones((len(node_array), 1))
        ones_added = np.hstack((node_array, ones_column))
        self.nodes = np.vstack((self.nodes, ones_added))

    def findCentre(self):
        mean = self.nodes.mean(axis=0)
        return mean

    def rotate(self, center, matrix):
        for i, node in enumerate(self.nodes):
            self.nodes[i] = center + np.matmul(matrix, node - center)

def main():
    spinx, spiny, spinz = 0, 0, 0

    clock.tick(FPS)

    while True:

        txt = cards()
        card_ascii = asciiTxt(txt)

        xyz = []

        for i in range(MAP_HEIGHT):
            y = - (y_gap * i)
            for j in range(MAP_WIDTH):
                x = x_gap * j
                z = 0
                xyz.append((x, y, z))

        step = 0

        running = True
        while running:

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    quit()

            pv = Projection(WIDTH, HEIGHT, card_ascii)

            card = Object()
            card_nodes = [i for i in xyz]
            card.addNodes(np.array(card_nodes))
            pv.addSurface('card', card)
            pv.rotate_x(spinx)
            pv.rotate_y(spiny)
            pv.rotate_z(spinz)
            pv.display()

            pg.display.update()
            spinx += 0.06
            spiny += 0.04
            spinz += 0.02

            step += 1
            if step == 200:
                running = False

main()


import numpy as np
import cv2

from images.coordinate import Coordinate
from images.bounding_box import BoundingBox

class ParkingArea:
    """
    Stores an information about the parking area: its endpoints, total
    and occupied parking spots. Also allows you to draw the area and
    check if an object is inside the area.

    Methods:
    -------
    occupy_parking_spot
    is_in_area
    draw_area
    forget_detected_cars
    """

    __color = [255, 255, 0]

    def __init__(self, area: list, img_width: int, img_height: int):
        self.area = area
        self.img_width = img_width
        self.img_height = img_height
        self.occupied_parking_spots = 0

    @property
    def area(self):
        return self._area

    @area.setter
    def area(self, value):
        if not isinstance(value, list):
            raise TypeError(
                "The area attribute must be of type list, not "
                f"{type(value).__name__}.")

        for bbox in value:
            if not isinstance(bbox, BoundingBox):
                raise TypeError(
                    "Elements inside the area list must be of type "
                    f"BoundingBox, not {type(bbox).__name__}.")

        self._area = value

    @property
    def number_of_parking_spots(self):
        return len(self.area) - 1

    @property
    def img_width(self):
        return self._img_width

    @img_width.setter
    def img_width(self, value):
        if not isinstance(value, int):
            raise TypeError(
                "The img_width attribute must be of type int, not "
                f"{type(value).__name__}.")

        self._img_width = value

    @property
    def img_height(self):
        return self._img_height

    @img_height.setter
    def img_height(self, value):
        if not isinstance(value, int):
            raise TypeError(
                "The img_height attribute must be of type int, not "
                f"{type(value).__name__}.")

        self._img_height = value

    def __calculate_angles(self):
        """
        Calculates the line slope between bottom right corner of the
        frame and the object's BoundingBox center.
        """

        return [
            int(
                np.degrees(
                    np.arctan(
                        (self.img_height-bbox.top_left_y)
                        / bbox.top_left_x
                    )
                )
            )
            for bbox in self.area
        ]

    def __sort_bboxes_by_angle(self):
        """
        Sorts the list of BoundingBoxes by angle.
        """

        return [
            bbox
            for angle, bbox in sorted(
                zip(self.__calculate_angles(), self.area),
                key=lambda pair: pair[0])
        ]

    @property
    def top_left_coordinate(self):
        return Coordinate(x=self.__sort_bboxes_by_angle()[-1].top_left_x,
                          y=(self.__sort_bboxes_by_angle()[-1].top_left_y))

    @property
    def top_right_coordinate(self):
        return Coordinate(x=(self.__sort_bboxes_by_angle()[-1].top_left_x
                             + self.__sort_bboxes_by_angle()[-1].bbox_width),
                          y=self.__sort_bboxes_by_angle()[-1].top_left_y)

    @property
    def bottom_left_coordinate(self):
        return Coordinate(x=self.__sort_bboxes_by_angle()[0].top_left_x,
                          y=(self.__sort_bboxes_by_angle()[0].top_left_y
                             + self.__sort_bboxes_by_angle()[0].bbox_height))

    @property
    def bottom_right_coordinate(self):
        return Coordinate(x=(self.__sort_bboxes_by_angle()[0].top_left_x
                             + self.__sort_bboxes_by_angle()[0].bbox_width),
                          y=(self.__sort_bboxes_by_angle()[0].top_left_y
                             + self.__sort_bboxes_by_angle()[0].bbox_height))

    def __numeric_area(self):
        """
        Returns the coordinates of the area in numerical form.
        """

        return np.array([
            [self.top_left_coordinate.x, self.top_left_coordinate.y],
            [self.top_right_coordinate.x, self.top_right_coordinate.y],
            [self.bottom_right_coordinate.x, self.bottom_right_coordinate.y],
            [self.bottom_left_coordinate.x, self.bottom_left_coordinate.y]
        ])

    def is_in_area(self, point: Coordinate):
        """
        Checks if the point is inside the area.

        Parameters:
        ----------
        point: Coordinate
            The point you want to check if is inside the area.
        """

        if not isinstance(point, Coordinate):
            raise TypeError(
                "The point parameter must be of type Coordinate, "
                f"not {type(point).__name__}.")

        return cv2.pointPolygonTest(
            contour=self.__numeric_area(),
            pt=(point.x, point.y),
            measureDist=False
        )

    @property
    def occupied_parking_spots(self):
        return self._occupied_parking_spots

    def occupy_parking_spot(self):
        """
        Determines one parking spot as occupied.
        """

        self.occupied_parking_spots += 1

    @occupied_parking_spots.setter
    def occupied_parking_spots(self, value):
        if not isinstance(value, int):
            raise TypeError(
                "The occupied_parking_spots must be of type int, "
                f"not {type(value).__name__}.")

        self._occupied_parking_spots = value

    def forget_detected_cars(self):
        """
        Sets the area's occupied_parking_spots attribute to 0.
        """

        self.occupied_parking_spots = 0

    def draw_area(self, img: np.ndarray):
        """
        Draws the area on the provided image.

        Parameters:
        ----------
        img: np.ndarray
            The image.
        """

        return cv2.polylines(
            img=img,
            pts=[self.__numeric_area()],
            isClosed=True,
            color=[255, 100, 100],
            thickness=3)


from django.shortcuts import render, redirect

# import user registration form from forms.py
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm

# guna decorator untuk restrict access ke page
from django.contrib.auth.decorators import login_required

from django.contrib import messages

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save() # simpan valid form
            username = form.cleaned_data.get('username')
            messages.success(request, f'Akaun {username} berjaya dicipta')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form' : form})

@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(
            request.POST,
            request.FILES,
            instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Akaun dikemaskini')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form' : u_form,
        'p_form' : p_form
    }

    return render(request, 'users/profile.html', context)


from __future__ import annotations

from typing import TYPE_CHECKING, ClassVar
from uuid import UUID

from attr import dataclass
import asyncpg

from mausignald.types import GroupID
from mautrix.types import ContentURI, RoomID, UserID
from mautrix.util.async_db import Database

from .util import ensure_uuid

fake_db = Database.create("") if TYPE_CHECKING else None

@dataclass
class Portal:
    db: ClassVar[Database] = fake_db

    chat_id: GroupID | UUID
    receiver: str
    mxid: RoomID | None
    name: str | None
    topic: str | None
    avatar_hash: str | None
    avatar_url: ContentURI | None
    name_set: bool
    avatar_set: bool
    revision: int
    encrypted: bool
    relay_user_id: UserID | None
    expiration_time: int | None

    @property
    def _values(self):
        return (
            str(self.chat_id),
            self.receiver,
            self.mxid,
            self.name,
            self.topic,
            self.avatar_hash,
            self.avatar_url,
            self.name_set,
            self.avatar_set,
            self.revision,
            self.encrypted,
            self.relay_user_id,
            self.expiration_time,
        )

    async def insert(self) -> None:
        q = """
        INSERT INTO portal (
            chat_id, receiver, mxid, name, topic, avatar_hash, avatar_url, name_set, avatar_set,
            revision, encrypted, relay_user_id, expiration_time
        ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
        """
        await self.db.execute(q, *self._values)

    async def update(self) -> None:
        q = """
        UPDATE portal SET mxid=$3, name=$4, topic=$5, avatar_hash=$6, avatar_url=$7, name_set=$8,
                          avatar_set=$9, revision=$10, encrypted=$11, relay_user_id=$12,
                          expiration_time=$13
        WHERE chat_id=$1 AND receiver=$2
        """
        await self.db.execute(q, *self._values)

    @classmethod
    def _from_row(cls, row: asyncpg.Record | None) -> Portal | None:
        if row is None:
            return None
        data = {**row}
        chat_id = data.pop("chat_id")
        if data["receiver"]:
            chat_id = ensure_uuid(chat_id)
        return cls(chat_id=chat_id, **data)

    _columns = (
        "chat_id, receiver, mxid, name, topic, avatar_hash, avatar_url, name_set, avatar_set, "
        "revision, encrypted, relay_user_id, expiration_time"
    )

    @classmethod
    async def get_by_mxid(cls, mxid: RoomID) -> Portal | None:
        q = f"SELECT {cls._columns} FROM portal WHERE mxid=$1"
        return cls._from_row(await cls.db.fetchrow(q, mxid))

    @classmethod
    async def get_by_chat_id(cls, chat_id: GroupID | UUID, receiver: str = "") -> Portal | None:
        q = f"SELECT {cls._columns} FROM portal WHERE chat_id=$1 AND receiver=$2"
        return cls._from_row(await cls.db.fetchrow(q, str(chat_id), receiver))

    @classmethod
    async def find_private_chats_of(cls, receiver: str) -> list[Portal]:
        q = f"SELECT {cls._columns} FROM portal WHERE receiver=$1"
        rows = await cls.db.fetch(q, receiver)
        return [cls._from_row(row) for row in rows]

    @classmethod
    async def find_private_chats_with(cls, other_user: UUID) -> list[Portal]:
        q = f"SELECT {cls._columns} FROM portal WHERE chat_id=$1 AND receiver<>''"
        rows = await cls.db.fetch(q, str(other_user))
        return [cls._from_row(row) for row in rows]

    @classmethod
    async def all_with_room(cls) -> list[Portal]:
        q = f"SELECT {cls._columns} FROM portal WHERE mxid IS NOT NULL"
        rows = await cls.db.fetch(q)
        return [cls._from_row(row) for row in rows]


"""Command parsing for team events."""
import logging
import shlex
from argparse import ArgumentParser, _SubParsersAction
from app.controller import ResponseTuple
from app.controller.command.commands.base import Command
from db.facade import DBFacade
from interface.github import GithubAPIException, GithubInterface
from app.model import Team, User
from utils.slack_parse import check_permissions
from typing import Any, List
from flask import jsonify

class TeamCommand(Command):
    """Represent Team Command Parser."""

    command_name = "team"
    desc = "for dealing with " + command_name + "s"
    permission_error = "You do not have the sufficient " \
                       "permission level for this command!"
    lookup_error = "Lookup error: Object not found!"

    def __init__(self,
                 db_facade: DBFacade,
                 gh: GithubInterface,
                 sc: Any) -> None:
        """
        Initialize team command parser.

        :param db_facade: Given Dynamo_DB Facade
        :param gh: Given Github Interface
        :param sc: Given Slack Client Interface
        """
        logging.info("Initializing TeamCommand instance")
        self.facade = db_facade
        self.gh = gh
        self.sc = sc
        self.desc = "for dealing with teams"
        self.parser = ArgumentParser(prog="/rocket")
        self.parser.add_argument("team")
        self.subparser = self.init_subparsers()
        self.help = self.get_help()

    def init_subparsers(self) -> _SubParsersAction:
        """Initialize subparsers for team command."""
        subparsers = self.parser.add_subparsers(dest="which")

        """Parser for list command."""
        parser_list = subparsers.add_parser("list")
        parser_list.set_defaults(which="list",
                                 help="Outputs the Github team names "
                                      "and displays names of all teams.")

        """Parser for view command."""
        parser_view = subparsers.add_parser("view")
        parser_view.set_defaults(which="view",
                                 help="View information and members of "
                                      "a team.")
        parser_view.add_argument("team_name", metavar='team-name',
                                 type=str, action='store')

        """Parser for delete command."""
        parser_delete = subparsers.add_parser("delete")
        parser_delete.set_defaults(which="delete",
                                   help="(Admin only) Permanently delete "
                                        "specified team.")
        parser_delete.add_argument("team_name", metavar='team-name',
                                   type=str, action='store')

        """Parser for create command."""
        parser_create = subparsers.add_parser("create")
        parser_create.set_defaults(which="create",
                                   help="(Admin only)"
                                        "Create a new team with the "
                                        "Github team name and provided "
                                        "optional parameters. NOTE: "
                                        "you will be added to this team.")
        parser_create.add_argument("team_name", metavar='team-name',
                                   type=str, action='store',
                                   help="Github name of your team (required).")
        parser_create.add_argument("--name", type=str, action='store',
                                   help="Display name of your team.")
        parser_create.add_argument("--platform", type=str, action='store',
                                   help="The team's main platform.")
        parser_create.add_argument("--channel", type=str, action='store',
                                   help="Add all members of this channel "
                                        "to the created team.")
        parser_create.add_argument("--lead", type=str, action='store',
                                   help="Add given user as team lead"
                                        "to created team.")

        """Parser for add command."""
        parser_add = subparsers.add_parser("add")
        parser_add.set_defaults(which="add",
                                help="Add a user to a given team.")
        parser_add.add_argument("team_name", metavar='team-name',
                                type=str, action='store',
                                help="Team to add the user to.")
        parser_add.add_argument("slack_id", metavar='slack-id',
                                type=str, action='store',
                                help="User to be added to team.")

        """Parser for remove command."""
        parser_remove = subparsers.add_parser("remove")
        parser_remove.set_defaults(which="remove",
                                   help="Remove a user from given team.")
        parser_remove.add_argument("team_name", metavar='team-name',
                                   type=str, action='store',
                                   help="Team to remove user from.")
        parser_remove.add_argument("slack_id", metavar='slack-id',
                                   type=str, action='store',
                                   help="User to be removed from team.")

        """Parser for edit command."""
        parser_edit = subparsers.add_parser("edit")
        parser_edit.set_defaults(which='edit',
                                 help="(Admin only)"
                                      "Edit properties of specified team.")
        parser_edit.add_argument("team_name", metavar='team-name',
                                 type=str, action='store',
                                 help="Name of team to edit.")
        parser_edit.add_argument("--name", type=str, action='store',
                                 help="Display name the team should have.")
        parser_edit.add_argument("--platform", type=str, action='store',
                                 help="Platform the team should have.")

        """Parser for lead command."""
        parser_lead = subparsers.add_parser("lead")
        parser_lead.set_defaults(which='lead',
                                 help="Edit leads of specified team.")
        parser_lead.add_argument("team_name", metavar='team-name',
                                 type=str, action='store',
                                 help="Name of team to edit.")
        parser_lead.add_argument("slack_id", metavar='slack-id',
                                 type=str, action='store',
                                 help="User to be added/removed as lead.")
        parser_lead.add_argument("--remove", action='store_true',
                                 help="Remove the user as team lead.")

        """Parser for refresh command."""
        parser_refresh = subparsers.add_parser("refresh")
        parser_refresh.set_defaults(which='refresh',
                                    help="(Admin only)"
                                         "Refresh local team database.")
        return subparsers

    def get_name(self) -> str:
        """Return the command type."""
        return self.command_name

    def get_desc(self) -> str:
        """Return the description of this command."""
        return self.desc

    def get_help(self) -> str:
        """Return command options for team events."""
        res = "\n*" + self.command_name + " commands:*```"
        for argument in self.subparser.choices:
            name = argument.capitalize()
            res += "\n*" + name + "*\n"
            res += self.subparser.choices[argument].format_help()
        return res + "```"

    def handle(self,
               command: str,
               user_id: str) -> ResponseTuple:
        """Handle command by splitting into substrings and giving to parser."""
        logging.debug("Handling TeamCommand")
        command_arg = shlex.split(command)
        args = None

        try:
            args = self.parser.parse_args(command_arg)
        except SystemExit:
            return self.get_help(), 200

        if args.which == "list":
            return self.list_helper()

        elif args.which == "view":
            return self.view_helper(args.team_name)

        elif args.which == "delete":
            return self.delete_helper(args.team_name, user_id)

        elif args.which == "create":
            param_list = {
                "team_name": args.team_name,
                "name": args.name,
                "platform": args.platform,
                "channel": args.channel,
                "lead": args.lead
            }
            return self.create_helper(param_list, user_id)

        elif args.which == "add":
            param_list = {
                "team_name": args.team_name,
                "slack_id": args.slack_id
            }
            return self.add_helper(param_list, user_id)

        elif args.which == "remove":
            param_list = {
                "team_name": args.team_name,
                "slack_id": args.slack_id
            }
            return self.remove_helper(param_list, user_id)

        elif args.which == "edit":
            param_list = {
                "team_name": args.team_name,
                "name": args.name,
                "platform": args.platform
            }
            return self.edit_helper(param_list, user_id)

        elif args.which == "lead":
            param_list = {
                "team_name": args.team_name,
                "slack_id": args.slack_id,
                "remove": args.remove
            }
            return self.lead_helper(param_list, user_id)

        elif args.which == "refresh":
            return self.refresh_helper(user_id)

        else:
            return self.get_help(), 200

    def list_helper(self) -> ResponseTuple:
        """
        Return display information of all teams.

        :return: error message if lookup error or no teams,
                 otherwise return teams' information
        """
        try:
            teams = self.facade.query(Team)
            if not teams:
                return "No Teams Exist!", 200
            attachment = [team.get_basic_attachment() for
                          team in teams]
            return jsonify({'attachments': attachment}), 200
        except LookupError:
            return self.lookup_error, 200

    def view_helper(self, team_name) -> ResponseTuple:
        """
        Return display information and members of specified team.

        :param team_name: name of team being viewed
        :return: error message if team not found,
                 otherwise return team information
        """
        try:
            team = self.facade.retrieve(Team, team_name)
            return jsonify({'attachments': [team.get_attachment()]}), 200
        except LookupError:
            return self.lookup_error, 200

    def create_helper(self, param_list, user_id) -> ResponseTuple:
        """
        Create team and calls GitHub API to create the team in GitHub.

        If ``param_list[name] is not None``, will add a display name. If
        ``param_list[channel] is not None``, will add all members of channel in
        which the command was called into the team.

        :param param_list: List of parameters for creating team
        :param user_id: Slack ID of user who called command
        :return: error message if team created unsuccessfully otherwise returns
                 success message
        """
        try:
            command_user = self.facade.retrieve(User, user_id)
            if not check_permissions(command_user, None):
                return self.permission_error, 200
            msg = f"New team created: {param_list['team_name']}, "
            team_id = self.gh.org_create_team()
            team = Team(team_id, param_list['team_name'], "")
            if param_list["name"] is not None:
                msg += f"name: {param_list['name']}, "
                team.display_name = param_list['name']
            if param_list["platform"] is not None:
                msg += f"platform: {param_list['platform']}, "
                team.platform = param_list['platform']
            if param_list["channel"] is not None:
                msg += "added channel, "
                for member_id in self.sc.get_channel_users(
                        param_list["channel"]):
                    member = self.facade.retrieve(User, member_id)
                    self.gh.add_team_member(member.github_username, team_id)
                    team.add_member(member.github_id)
            else:
                self.gh.add_team_member(command_user.github_username, team_id)
                team.add_member(command_user.github_id)
            if param_list["lead"] is not None:
                msg += "added lead"
                lead_user = self.facade.retrieve(User, param_list["lead"])
                team.add_team_lead(lead_user.github_id)
                if not self.gh.has_team_member(lead_user.github_username,
                                               team_id):
                    self.gh.add_team_member(lead_user.github_username, team_id)
            else:
                team.add_team_lead(command_user.github_id)

            self.facade.store(team)
            return msg, 200
        except GithubAPIException as e:
            logging.error("team creation unsuccessful")
            return f"Team creation unsuccessful with the" \
                   f" following error: {e.data}", 200
        except LookupError:
            return self.lookup_error, 200

    def add_helper(self, param_list, user_id) -> ResponseTuple:
        """
        Add user to team.

        If user is not admin or team lead of specified team, the user will not
        be added and an error message is returned.

        :param param_list: List of parameters for adding user
        :param user_id: Slack ID of user who called command
        :return: error message if user added unsuccessfully or if user has
                 insufficient permission level, otherwise returns success
                 message
        """
        try:
            command_user = self.facade.retrieve(User, user_id)
            team = self.facade.retrieve(Team, param_list['team_name'])
            if not check_permissions(command_user, team):
                return self.permission_error, 200

            user = self.facade.retrieve(User, param_list['slack_id'])
            team.add_member(user.github_id)
            self.gh.add_team_member(user.github_username, team.github_team_id)
            self.facade.store(team)
            msg = "Added User to " + param_list['team_name']
            ret = {'attachments': [team.get_attachment()], 'text': msg}
            return jsonify(ret), 200

        except LookupError:
            return self.lookup_error, 200
        except GithubAPIException as e:
            logging.error("user added unsuccessfully to team")
            return f"User added unsuccessfully with the " \
                   f"following error: {e.data}", 200

    def remove_helper(self, param_list, user_id) -> ResponseTuple:
        """
        Remove specified user from a team.

        If the user is also a team lead, removes team lead status from Team. If
        user is not admin or team lead of specified team, user will not be
        removed and an error message is returned.

        :param param_list: List of parameters for removing user
        :param user_id: Slack ID of user who called command
        :return: error message if user removed unsuccessfully, if user is not
                 in team, or if user has insufficient permission level,
                 otherwise returns success message
        """
        try:
            command_user = self.facade.retrieve(User, user_id)
            team = self.facade.retrieve(Team, param_list['team_name'])
            if not check_permissions(command_user, team):
                return self.permission_error, 200

            user = self.facade.retrieve(User, param_list['slack_id'])
            if not self.gh.has_team_member(user.github_username,
                                           team.github_team_id):
                return "User not in team!", 200
            team.discard_member(user.github_id)
            if team.has_team_lead(user.github_id):
                team.discard_team_lead(user.github_id)
            self.gh.remove_team_member(user.github_username,
                                       team.github_team_id)
            self.facade.store(team)
            msg = "Removed User from " + param_list['team_name']
            ret = {'attachments': [team.get_attachment()], 'text': msg}
            return jsonify(ret), 200

        except LookupError:
            return self.lookup_error, 200
        except GithubAPIException as e:
            logging.error("user removed unsuccessfully from team")
            return f"User removed unsuccessfully with " \
                   f"the following error: {e.data}", 200

    def edit_helper(self, param_list, user_id) -> ResponseTuple:
        """
        Edit the properties of a specific team.

        Team leads can only edit the teams that they are a part of, but admins
        can edit any teams.

        :param param_list: List of parameters for editing team
        :param user_id: Slack ID of user who called command
        :return: error message if user has insufficient permission level or
                 team edited unsuccessfully, otherwise return success message
        """
        try:
            command_user = self.facade.retrieve(User, user_id)
            team = self.facade.retrieve(Team, param_list['team_name'])
            if not check_permissions(command_user, team):
                return self.permission_error, 200
            msg = f"Team edited: {param_list['team_name']}, "
            if param_list['name'] is not None:
                msg += f"name: {param_list['name']}, "
                team.display_name = param_list['name']
            if param_list['platform'] is not None:
                msg += f"platform: {param_list['platform']}"
                team.platform = param_list['platform']
            self.facade.store(team)
            ret = {'attachments': [team.get_attachment()], 'text': msg}
            return jsonify(ret), 200
        except LookupError:
            return self.lookup_error, 200

    def lead_helper(self, param_list, user_id) -> ResponseTuple:
        """
        Add a user as team lead, and add them to team if not already added.

        If ``--remove`` flag is used, user is instead demoted from being a team
        lead, but not from the team.

        :param param_list: List of parameters for editing leads
        :param user_id: Slack ID of user who called command
        :return: error message if user has insufficient permission level or
                 lead demoted unsuccessfully, otherwise return success message
        """
        try:
            command_user = self.facade.retrieve(User, user_id)
            team = self.facade.retrieve(Team, param_list['team_name'])
            if not check_permissions(command_user, team):
                return self.permission_error, 200
            user = self.facade.retrieve(User, param_list["slack_id"])
            msg = ""
            if param_list["remove"]:
                if not team.has_member(user.github_id):
                    return "User not in team!", 200
                if team.has_team_lead(user.github_id):
                    team.discard_team_lead(user.github_id)
                self.facade.store(team)
                msg = f"User removed as team lead from" \
                      f" {param_list['team_name']}"
            else:
                if not team.has_member(user.github_id):
                    team.add_member(user.github_id)
                    self.gh.add_team_member(user.github_username,
                                            team.github_team_id)
                team.add_team_lead(user.github_id)
                self.facade.store(team)
                msg = f"User added as team lead to" \
                      f" {param_list['team_name']}"
            ret = {'attachments': [team.get_attachment()], 'text': msg}
            return jsonify(ret), 200
        except LookupError:
            return self.lookup_error, 200
        except GithubAPIException as e:
            logging.error("team lead edit unsuccessful")
            return f"Edit team lead was unsuccessful " \
                   f"with the following error: {e.data}", 200

    def delete_helper(self, team_name, user_id) -> ResponseTuple:
        """
        Permanently delete a team.

        :param team_name: Name of team to be deleted
        :param user_id: Slack ID of user who called command
        :return: error message if user has insufficient permission level or
                 team deleted unsuccessfully, otherwise return success message
        """
        try:
            command_user = self.facade.retrieve(User, user_id)
            team = self.facade.retrieve(Team, team_name)
            if not check_permissions(command_user, team):
                return self.permission_error, 200
            self.facade.delete(Team, team_name)
            self.gh.org_delete_team(team.github_team_id)
            return f"Team {team_name} deleted", 200
        except LookupError:
            return self.lookup_error, 200
        except GithubAPIException as e:
            logging.error("team delete unsuccessful")
            return f"Team delete was unsuccessful with " \
                   f"the following error: {e.data}", 200

    def refresh_helper(self, user_id) -> ResponseTuple:
        """
        Ensure that the local team database is the same as GitHub's.

        In the event that our local team database is outdated compared to
        the teams on GitHub, this command can be called to fix things.

        :return: error message if user has insufficient permission level
                 otherwise returns success messages with # of teams changed
        """
        num_changed = 0
        num_added = 0
        num_deleted = 0
        modified = []
        try:
            command_user = self.facade.retrieve(User, user_id)
            if not check_permissions(command_user, None):
                return self.permission_error, 200
            local_teams: List[Team] = self.facade.query(Team)
            remote_teams: List[Team] = self.gh.org_get_teams()
            local_team_dict = dict((team.github_team_id, team)
                                   for team in local_teams)
            remote_team_dict = dict((team.github_team_id, team)
                                    for team in remote_teams)

            # remove teams not in github anymore
            for local_id in local_team_dict:
                if local_id not in remote_team_dict:
                    self.gh.org_delete_team(local_id)
                    num_deleted += 1
                    modified.append(local_team_dict[local_id].get_attachment())

            # add teams to db that are in github but not in local database
            for remote_id in remote_team_dict:
                if remote_id not in local_team_dict:
                    self.facade.store(remote_team_dict[remote_id])
                    num_added += 1
                    modified.append(remote_team_dict[remote_id]
                                    .get_attachment())
                else:
                    # and finally, if a local team differs, update it
                    old_team = local_team_dict[remote_id]
                    new_team = remote_team_dict[remote_id]
                    if old_team.github_team_name != new_team.github_team_name\
                            or old_team.members != new_team.members:

                        # update the old team, to retain additional parameters
                        old_team.github_team_name = new_team.github_team_name
                        old_team.members = new_team.members
                        self.facade.store(old_team)
                        num_changed += 1
                        modified.append(old_team.get_attachment())
        except GithubAPIException as e:
            logging.error("team refresh unsuccessful due to github error")
            return "Refresh teams was unsuccessful with " \
                   f"the following error: {e.data}", 200
        except LookupError:
            logging.error("team refresh unsuccessful due to lookup error")
            return self.lookup_error, 200
        status = f"{num_changed} teams changed, " \
            f"{num_added} added, " \
            f"{num_deleted} deleted. Wonderful."
        ret = {'attachments': modified, 'text': status}
        return jsonify(ret), 200


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

class Solution:
    def rotateRight(self, head, k):
        arr=[]
        temp=head
        while head:
            arr.append(head.val)
            head=head.next
        arr1=[]
        for i in range(len(arr)):
            print(arr[(i+(len(arr)-k))%len(arr)])
            arr1.append(arr[(i+(len(arr)-k))%len(arr)])
        k=0
        final=temp
        while temp:
            temp.val=arr1[k]
            k+=1
            temp=temp.next
        return final


def latest(scores):
    return scores[len(scores)-1]

def personal_best(scores):
    personalbest = 0
    for result in scores:
        if result > personalbest:
            personalbest = result
    return personalbest

def personal_top_three(scores):
    PersonalTopThree = []
    for result in scores:
        PersonalTopThree.append(result)
        PersonalTopThree.sort(reverse=True)
        PersonalTopThree = [PersonalTopThree[i] for i in range(min(len(PersonalTopThree),3))]
    return PersonalTopThree


from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('empty', views.empty, name="empty"),
    path('', views.list_trndp, name="home"),
    path('list-report', views.list_report, name="list_report"),
    path('client_form', views.client_form, name="client_form"),
    path('view_report', views.view_report, name="view_report"),
    path('list-trndp', views.list_trndp, name="list_trndp"),
    path('input', views.input, name="input"),
    path('output', views.output, name="output"),
]


from google.cloud import storage
from google.api_core.exceptions import Forbidden
import base64
from flask import abort
from google.api_core.exceptions import Conflict
import bz2
import logging
from io import BytesIO
import os
from datetime import datetime

logger = logging.getLogger('Store_model')

class Store(object):
    """singleton"""
    _instance = None

    def __init__(self):
        self.connect()

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def connect(self):
        try:
            self.client = storage.Client()
        except Exception as e:
            logger.error(str(e))

    def create_bucket(self, bucket_name):
        try:
            bucket = self.client.create_bucket(bucket_name)
            return bucket.name
        except Conflict as e:
            logger.error(e)
            abort(400, '')

    def delete_bucket(self, bucket_name):
        """Deletes a bucket. The bucket must be empty."""
        bucket = self.client.get_bucket(bucket_name)
        bucket.delete()
        logger.error('Bucket {} deleted'.format(bucket.name))
        print('Bucket {} deleted'.format(bucket.name))

    def list_blobs(self, bucket_name):
        """Lists all the blobs in the bucket."""
        # type : (str)=> (list)
        try:
            bucket = self.client.get_bucket(bucket_name)
        except Exception as e:
            logger.error(e)
            raise Exception(str(e))

        blobs = bucket.list_blobs()
        res = []
        for blob in blobs:
            res.append(blob.name)
        return res

    def list_blobs_with_prefix(self, bucket_name, prefix, delimiter='/'):
        """Lists all the blobs in the bucket."""
        # type : (str)=> (list)
        bucket = self.client.get_bucket(bucket_name)
        blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)
        res = []
        for blob in blobs:
            res.append(blob.name)
        if delimiter:
            for prefix in blobs.prefixes:
                res.append(prefix)
        return res

    def write(self, bucket_name, filename, data, enc_key=None):
        # Encryption key must be an AES256 key represented as a bytestring with
        # 32 bytes. Since it's passed in as a base64 encoded string, it needs
        # to be decoded.
        try:
            bucket = self.client.get_bucket(bucket_name)
        except Forbidden as e:
            logger.error(e)
            raise Forbidden(str(e))
        blob = storage.Blob(filename, bucket, encryption_key=enc_key)
        data = bz2.compress(data.encode(), 9)
        try:
            blob.upload_from_string(data, content_type='application/gzip')
            return '/{}/{}'.format(bucket_name, filename)
        except Exception as e:
            logger.error(e)

    def get_blob(self, bucket_name, filename, enc_key=None):
        bucket = self.client.get_bucket(bucket_name)
        if enc_key:
            enc_key = base64.b64decode(enc_key)
        return storage.Blob(filename, bucket, encryption_key=enc_key)

    def read(self, bucket_name, filename, enc_key=None):
        """ read file as string """
        blob = self.get_blob(bucket_name, filename, enc_key)
        string_buffer = BytesIO()
        blob.download_to_file(string_buffer)
        try:
            data = string_buffer.getvalue()
            data = bz2.decompress(data).decode()
        except Exception as e:
            logging.error(e)
            raise e
        return data

    def read_as_file(self, bucket_name, filename, enc_key=None):
        """ read and save file """
        data = self.read(bucket_name, filename, enc_key=enc_key)
        self._write_file(data, filename)

    def _write_file(self, data, filename):
        filename += '.html'
        with open(filename, 'w') as f:
            f.write(data)

    def decomp(self, filename):
        with open(filename, 'rb') as f:
            data = f.read()
        return bz2.decompress(data).decode()

    def buck_up(self, dirname: str, filename: str):
        assert os.getenv('BUCKUP_DIR')
        bucket_name = os.getenv('BUCKUP_DIR') + dirname
        with open(filename) as f:
            data = f.read()
        filename += '_' + datetime.now().strftime('%Y-%m-%d')
        self.write(bucket_name, filename, data, enc_key=None)


# Solving the knapsack 0-1 problem using the Google OR-Tools MIP solver.
# The item values and weights are provided through input lists.

import numpy as np
from ortools.algorithms import pywrapknapsack_solver

def knapsack_0_1_or(values, weights, capacities):
	# Declare the solver
	solver = pywrapknapsack_solver.KnapsackSolver(
		pywrapknapsack_solver.KnapsackSolver.
		KNAPSACK_MULTIDIMENSION_CBC_MIP_SOLVER, 'knapsack_0_1')
	# Call the solver
	solver.Init(values, weights, capacities)
	computed_value = solver.Solve()
	packed_items = []
	packed_weights = []
	total_weight = 0
	print('Total value =', computed_value)
	for i in range(len(values)):
		if solver.BestSolutionContains(i):
			packed_items.append(i)
			packed_weights.append(weights[0][i])
			total_weight += weights[0][i]
	print('Total weight:', total_weight)
	print('Packed items:', packed_items)
	print('Packed_weights:', packed_weights)

# List of item values
v = [7, 2, 10, 4]
# List of item weights
w = [3, 6, 9, 5]
# Knapsack capacity
C = 15
# knapsack_0_1_or(v, [w], [C])
v, w = np.loadtxt("knapsack_dataset_xl.txt", dtype=int, unpack=True)
wl = []
for i in range(1, len(w)):
	wl.append(w[i])
knapsack_0_1_or(v[1:], [wl], [v[0]])


"""
Run in terminal:

pip install pyside6

save this file as main.py

run python main.py
"""
import sys
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QPushButton,
    QLabel,
)

class CounterWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.counter = 0

        self.setWindowTitle("Counter Example")
        self.setGeometry(400, 400, 300, 200)

        self.button = QPushButton("Click Me", self)
        self.button.clicked.connect(
            self.increment_counter
        )
        self.button.setGeometry(50, 50, 200, 50)

        self.label = QLabel("Counter: 0", self)
        self.label.setGeometry(50, 120, 200, 50)

    def increment_counter(self):
        self.counter += 1
        self.button.setText(
            f"Click Me ({self.counter})"
        )
        self.label.setText(
            f"Counter: {self.counter}"
        )

if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = CounterWindow()
    window.show()

    sys.exit(app.exec())


# -*- coding: utf-8 -*-
from collective.googlenews.interfaces import GoogleNewsSettings
from collective.googlenews.interfaces import validate_logo
from collective.googlenews.testing import INTEGRATION_TESTING
from plone import api
from plone.formwidget.namedfile.converter import b64encode_file
from zope.component import getMultiAdapter
from zope.interface import Invalid

import unittest

def load_file(name, size=0):
    """Load file from testing directory"""
    path = '/tmp/{0}'.format(name)
    with open(path, 'rb') as f:
        data = f.read()
    return data

def encode_image(image):
    """Return image encoded in base64"""
    return b64encode_file(image, load_file(image))

class AtomFeedViewTestCase(unittest.TestCase):

    layer = INTEGRATION_TESTING

    def setUp(self):
        self.portal = self.layer['portal']
        self.request = self.layer['request']

    def test_logo(self):
        view = getMultiAdapter((self.portal, self.request), name='atom.xml')
        feed = view.feed()
        self.assertEqual(feed.logo, 'http://nohost/plone/logo.png')

        api.portal.set_registry_record(
            GoogleNewsSettings.__identifier__ + '.logo',
            encode_image('logo_plone_ok.png')
        )
        self.assertEqual(
            feed.logo, 'http://nohost/plone/@@googlenews-logo/logo_plone_ok.png')

class ValidateLogoTestCase(unittest.TestCase):

    layer = INTEGRATION_TESTING

    def setUp(self):
        self.portal = self.layer['portal']

    def test_validate_logo_constraint(self):
        invalid_images = (
            'logo_plone_not_transparent.png',
            'logo_plone_wrong_filetype.jpg',
            'logo_plone_wrong_size.png'
        )
        for image in invalid_images:
            data = encode_image(image)
            with self.assertRaises(Invalid):
                validate_logo(data)

        data = encode_image('logo_plone_ok.png')
        self.assertTrue(validate_logo(data))