"""
Classes to be used when determining regularisation in unfolding
"""

from __future__ import print_function, division

from array import array
import numpy as np
import math
import os
from itertools import chain

import ROOT
from MyStyle import My_Style
from comparator import Contribution, Plot
My_Style.cd()

import common_utils as cu
import qg_common as qgc
import qg_general_plots as qgp

# This doesn't seem to work...sigh
np.set_printoptions(edgeitems=3,infstr='Infinity',
                    linewidth=75, nanstr='nan', precision=8,
                    suppress=False, threshold=1000, formatter=None)

ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch(1)
ROOT.TH1.SetDefaultSumw2()

class TauScanner(object):
    """Class to handle doing ScanTau on a TUnfoldBinning object,
    since it produces many associated objects & values.

    Can also plot results from scanning.
    """
    def __init__(self):
        self.scan_results = ROOT.MakeNullPointer(ROOT.TSpline)
        self.l_curve = ROOT.MakeNullPointer(ROOT.TGraph)
        self.log_tau_x = ROOT.MakeNullPointer(ROOT.TSpline)
        self.log_tau_y = ROOT.MakeNullPointer(ROOT.TSpline)
        self.tau = 0
        self.scan_mode = ""
        self.graph_all_scan_points = None
        self.graph_best_scan_point = None

    def scan_tau(self, tunfolder, n_scan, tau_min, tau_max, scan_mode, distribution, axis_steering):
        ind_best_point = tunfolder.ScanTau(n_scan,
                                            tau_min,
                                            tau_max,
                                            self.scan_results,
                                            scan_mode,
                                            distribution,
                                            axis_steering,
                                            self.l_curve,
                                            self.log_tau_x,
                                            self.log_tau_y)
        self.tau = tunfolder.GetTau()
        self._process_results(scan_mode, ind_best_point)
        print("scan_tau value is {}".format(self.tau))
        print("chi**2 A {:3.1f} + chi**2 L {:3.1f} / NDOF {:3.1f} ".format(tunfolder.GetChi2A(),
                                                                           tunfolder.GetChi2L(),
                                                                           tunfolder.GetNdf()))
        return self.tau

    def _process_results(self, scan_mode, ind_best_point):
        """Create graphs etc from ScanTau output

        User shouldn't call this, only internal
        """

        # Get best scan point & make graph of it
        # t here is log_10(tau)
        t, rho = array('d'), array('d')  # array obj needed to make TGraph
        t0 = ROOT.Double(0.0)
        rho0 = ROOT.Double(0.0)
        self.scan_results.GetKnot(ind_best_point, t0, rho0)
        t.append(t0)
        rho.append(rho0)
        self.graph_best_scan_point = ROOT.TGraph(1, t, rho)

        print("t[0] =", t[0])
        print("rho[0] =", rho[0])
        print("10^log_10(tau) = tau =", math.pow(10., float(t0)))

        # Make graph of all the points scanned
        t_all, rho_all = array('d'), array('d')
        n_scan = self.scan_results.GetNp()
        for i in range(n_scan):
            tt = ROOT.Double(0.0)
            rr = ROOT.Double(0.0)
            self.scan_results.GetKnot(i, tt, rr)
            t_all.append(tt)
            rho_all.append(rr)

        self.graph_all_scan_points = ROOT.TGraph(int(n_scan), t_all, rho_all)

        tau_mode_dict = {
            ROOT.TUnfoldDensity.kEScanTauRhoAvg: "average (stat+bgr) global correlation (#rho)",
            ROOT.TUnfoldDensity.kEScanTauRhoAvgSys: "average (stat+bgr+sys) global correlation (#rho)",
            ROOT.TUnfoldDensity.kEScanTauRhoMax: "maximum (stat+bgr) global correlation (#rho)",
            ROOT.TUnfoldDensity.kEScanTauRhoMaxSys: "maximum (stat+bgr+sys) global correlation (#rho)",
            ROOT.TUnfoldDensity.kEScanTauRhoSquareAvg: "average (stat+bgr) global correlation (#rho) squared",
            ROOT.TUnfoldDensity.kEScanTauRhoSquareAvgSys: "average (stat+bgr+sys) global correlation (#rho) squared",
        }
        self.graph_all_scan_points.SetTitle("Optimization of Regularization Parameter, #tau : Scan of {}".format(tau_mode_dict[scan_mode]))

    def plot_scan_tau(self, output_filename):
        """Plot graph of scan results, and optimum tau"""
        canv_tau_scan = ROOT.TCanvas("canv_tau_scan_"+str(self.tau), "canv_tau_scan_"+str(self.tau))

        self.graph_all_scan_points.SetLineColor(ROOT.kBlue+3)
        self.graph_all_scan_points.Draw()

        self.graph_best_scan_point.SetMarkerColor(ROOT.kRed)
        self.graph_best_scan_point.Draw("* same")

        self.graph_all_scan_points.GetXaxis().SetTitle("log_{10}(#tau)")
        self.graph_all_scan_points.GetYaxis().SetTitle(" #rho")

        leg = ROOT.TLegend(0.2, 0.6, 0.35, 0.89)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextSize(0.026)
        leg.AddEntry(self.graph_all_scan_points, 'Scan over #tau', 'l')
        leg.AddEntry(self.graph_best_scan_point, 'Chosen point: #tau = {}'.format(self.tau), 'P')
        leg.Draw()

        cu.check_dir_exists_create(os.path.dirname(os.path.abspath(output_filename)))
        canv_tau_scan.Print(output_filename)

    def save_to_tfile(self, tfile):
        tfile.WriteTObject(self.graph_all_scan_points, "regularize_all_scan_points")
        tfile.WriteTObject(self.graph_best_scan_point, "regularize_best_scan_point")

class LCurveScanner(object):
    """Class to handle doing ScanLcurve on a TUnfoldBinning object,
    since it produces many associated objects & values.

    Can also plot results from scanning.
    """
    def __init__(self):
        self.scanned_l_curve = ROOT.MakeNullPointer(ROOT.TGraph)
        self.log_tau_x = ROOT.MakeNullPointer(ROOT.TSpline3) # spline of L-curve x-coord as a func of log_10(tau)
        self.log_tau_y = ROOT.MakeNullPointer(ROOT.TSpline3) # spline of L-curve y-coord as a func of log_10(tau)
        self.log_tau_curvature = ROOT.MakeNullPointer(ROOT.TSpline3)
        self.graph_log_tau_curvature = None  # to hold graph of log_tau_curvature
        self.graph_log_tau_curvature_best = None
        self.tau = 0
        self.graph_best_scan_point = None # in terms of LcurveY vs LcurveX

    def scan_L(self, tunfolder, n_scan, tau_min, tau_max):
        ind_best_point = tunfolder.ScanLcurve(n_scan,
                                              tau_min,
                                              tau_max,
                                              self.scanned_l_curve,
                                              self.log_tau_x,
                                              self.log_tau_y,
                                              self.log_tau_curvature)
        self.tau = tunfolder.GetTau()
        self._process_results(ind_best_point)
        return self.tau

    def _process_results(self, ind_best_point):
        """Create graphs etc from ScanLcurve output

        User shouldn't call this, only internal
        """
        # Get best scan point & make graph of it
        t_0 = ROOT.Double(0.0)  # is log_10(tau)
        x_0 = ROOT.Double(0.0)
        y_0 = ROOT.Double(0.0)
        self.log_tau_x.GetKnot(ind_best_point, t_0, x_0)
        self.log_tau_y.GetKnot(ind_best_point, t_0, y_0)
        self.graph_best_scan_point = ROOT.TGraph(1, array('d', [x_0]), array('d', [y_0]))

        # Create graph of curvature
        t_all, c_all = array('d'), array('d')
        n_scan = self.log_tau_curvature.GetNp()
        for i in range(n_scan):
            t = ROOT.Double(0.0)  # is log_10(tau)
            c = ROOT.Double(0.0)
            self.log_tau_curvature.GetKnot(i, t, c)
            t_all.append(t)
            c_all.append(c)

        self.graph_log_tau_curvature = ROOT.TGraph(n_scan, t_all, c_all)

        # Get best scan point in terms of curvature vs log(tau)
        # you cannot use the index, it doesn't correspond to this graph
        c_0 = self.log_tau_curvature.Eval(t_0)
        self.graph_log_tau_curvature_best = ROOT.TGraph(1, array('d', [t_0]), array('d', [c_0]))

    def plot_scan_L_curve(self, output_filename):
        """Plot graph of scan results, and optimum tau"""
        canv_L_scan = ROOT.TCanvas("canv_L_scan_"+str(self.tau), "canv_L_scan_"+str(self.tau))

        self.scanned_l_curve.SetTitle("Optimization of Regularization Parameter, #tau : Scan of L curve")
        self.scanned_l_curve.SetLineColor(ROOT.kBlue+3)
        self.scanned_l_curve.Draw()

        self.graph_best_scan_point.SetMarkerColor(ROOT.kRed)
        self.graph_best_scan_point.Draw("* same")

        self.scanned_l_curve.GetXaxis().SetTitle("log_{10}(L_{1})")
        self.scanned_l_curve.GetYaxis().SetTitle("log_{10}(#frac{L_{2}}{#tau^{2}})")

        leg = ROOT.TLegend(0.5, 0.6, 0.85, 0.89)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextSize(0.026)
        leg.AddEntry(self.scanned_l_curve, 'Scan over #tau', 'l')
        leg.AddEntry(self.graph_best_scan_point, 'Chosen point: #tau = {}'.format(self.tau), 'P')
        leg.Draw()

        cu.check_dir_exists_create(os.path.dirname(os.path.abspath(output_filename)))
        canv_L_scan.Print(output_filename)

    def plot_scan_L_curvature(self, output_filename):
        """Plot graph of L curvature & optimum point"""
        canv_L_curvature = ROOT.TCanvas("canv_L_curvature_"+str(self.tau), "canv_L_curvature_"+str(self.tau))

        self.graph_log_tau_curvature.SetTitle("Optimization of Regularization Parameter, #tau : Scan of L curvature")
        self.graph_log_tau_curvature.SetLineColor(ROOT.kBlue+3)
        self.graph_log_tau_curvature.Draw()
        self.graph_log_tau_curvature.GetXaxis().SetTitle("log_{10}(#tau)")
        self.graph_log_tau_curvature.GetYaxis().SetTitle("L-curve curvature C")

        self.graph_log_tau_curvature_best.SetLineColor(ROOT.kRed)
        self.graph_log_tau_curvature_best.SetMarkerColor(ROOT.kRed)
        self.graph_log_tau_curvature_best.Draw("* same")

        leg = ROOT.TLegend(0.5, 0.6, 0.85, 0.89)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextSize(0.026)
        leg.AddEntry(self.graph_log_tau_curvature, 'Curvature', 'l')
        leg.AddEntry(self.graph_log_tau_curvature_best, 'Chosen point: #tau = {}'.format(self.tau), 'P')
        leg.Draw()

        cu.check_dir_exists_create(os.path.dirname(os.path.abspath(output_filename)))
        canv_L_curvature.Print(output_filename)

    def save_to_tfile(self, tfile):
        tfile.WriteTObject(self.scanned_l_curve, "scanned_l_curve")
        tfile.WriteTObject(self.graph_best_scan_point, "graph_best_scan_point")
        tfile.WriteTObject(self.graph_log_tau_curvature, "graph_log_tau_curvature")
        tfile.WriteTObject(self.graph_log_tau_curvature_best, "graph_log_tau_curvature_best")


black, white, empty, outer = 1, 2, 0, 3
directions = [-11, -10, -9, -1, 1, 9, 10, 11]

class TreeNode:
	val = None
	left = None
	right = None
	def __init__(self, val, left, right):
		self.val = val
		self.left = left
		self.right = right
	def setLeft(l):
		self.left = l
	def setRight(r):
		self.right = r
	def setVal(v):
		self.val = v
	def getLeft():
		return left
	def getRight():
		return right
	def getVal():
		return val

def mobility(board,player):
	return len(get_legal_moves(board,opponent_color(player)))

def stableCount(board, player):
	count = 0
	for square in board:
		if isStable(board, player, square):
			count = count + 1
	return count

def isStable(board, player, square):
	opp = opponent_color(player)
	for d in directions:
		k = square + d
		while board[k] != 3:
			if board[k] == 0 or board[k] == opp:
				test = k-d
				while board[test] != 3:
					if board[test] == 0 or board[test] == opp:
						return False
					test = test-d
			k = k + d
	return True

def bracket(board, player, square):
	opp = opponent_color(player)
	for d in directions:
		k = square + d
		if board[k] is not opp:
			continue
		while board[k] is opp:
			k = k + d
		if board[k] is player:
			k = k - d
			while k != square:
				board[k] = player
				k = k - d

def would_bracket(board, player, square):
	opp = opponent_color(player)
	for d in directions:
		k = square + d
		if board[k] is not opp:
			continue
		while board[k] is opp:
			k = k + d
		if board[k] is player:
			return True
	return False

def get_legal_moves(board, player):
	possible = []
	for row in range(10, 90, 10):
		for col in range(1, 9):
			square = row + col
			if board[square] is not empty:
				continue
			if would_bracket(board, player, square):
				possible.append(square)
	return possible

def opponent_color(player):
	if player is black:
		return white
	return black

def pick(board,player):
	poss = get_legal_moves(board,player)
	maxscore = 0
	from random import choice
	if len(poss) < 1:
		return None
	move = choice(poss)
	for child in poss:
		test = board
		test[child] = player
		bracket(test, player, child)
		h = minimax(test,player,10,stableCount)
		if h > maxscore:
			maxscore = h
			move = child
	if h == 0:
		for child in poss:
			test = board
			test[child] = player
			bracket(test, player, child)
			h = minimax(test,player,10,mobility)
			if h > maxscore:
				maxscore = h
				move = child
	return move

def minimax(board,player,depth,score):
	if depth == 0:
		return score(board,player)
	else:
		h = -9999
		poss = get_legal_moves(board,player)
		for child in poss:
			a = 0
			if child in [12,16,21,22,27,28,71,72,77,78,82,87]:
				a = -1
			test = board
			test[child] = player
			bracket(test, player, child)
			h = max(h+a, -minimax(test,opponent_color(player),depth-1,score))
		return h


#!/usr/bin/env python3

#/*
# Terminal User input
# Manual Mode where the coordinate and orientation variables are input
# Doesn't use accelerometer
#*/

# Import essential libraries
import requests #type: ignore
import numpy as np #type: ignore
import imutils #type: ignore
import time
import math
from datetime import datetime
import adafruit_adxl34x # type: ignore
import sys
import cv2 #type: ignore
import os
import RPi.GPIO as GPIO #type: ignore
import serial #type: ignore
import matplotlib.pyplot as plt #type: ignore

sys.path.append('/home/pi/Chromebook-projects/projects/proj_Hexclaw')

from IK_module import *
from h2_module import *

from board import SCL, SDA # type: ignore
import busio # type: ignore

from adafruit_motor import servo # type: ignore
from adafruit_servokit import ServoKit # type: ignore
from adafruit_pca9685 import PCA9685 # type: ignore

i2c = busio.I2C(SCL, SDA)
pca = PCA9685(i2c)
pca.frequency = 50

servo = [servo.Servo(pca.channels[0]),
         servo.Servo(pca.channels[1]),
         servo.Servo(pca.channels[2]),
         servo.Servo(pca.channels[3]),
         servo.Servo(pca.channels[4]),
         servo.Servo(pca.channels[5]),
         ]

for i in range(6):
    servo[i].set_pulse_width_range(500, 2500)

sendToServo(servo,[135,45,180,45,180,90],0,mode=0)
time.sleep(1)

GPIO.setmode(GPIO.BCM) # GPIO Numbers instead of board numbers

ledRelay = 23
GPIO.setup(ledRelay, GPIO.OUT) # GPIO Assign mode
GPIO.output(ledRelay, GPIO.LOW) # out
GPIO.output(ledRelay, GPIO.HIGH) # on

time.sleep(0.75)
sendToServo(servo,[90,115,135,90,115,90],1,mode=2)

if False:
    for _ in range(4):
        GPIO.output(ledRelay, False)
        time.sleep(0.03)
        GPIO.output(ledRelay, True)
        time.sleep(0.03)

    time.sleep(1.5)
    GPIO.output(ledRelay, False)
    time.sleep(0.25)
    GPIO.output(ledRelay, True)
    time.sleep(0.5)
    GPIO.output(ledRelay, False)
    time.sleep(0.1)
    GPIO.output(ledRelay, True)
    time.sleep(2)
    GPIO.output(ledRelay, False)

print("------")
time.sleep(2)

GPIO.output(ledRelay, True)

diagnostics = False

if diagnostics:
    ard_port = '/dev/ttyUSB0'
    ser_arduino = serial.Serial(ard_port, 9600, timeout=0.1)
    ser_arduino.reset_input_buffer()
    x_Values = [] #time/seconds passed since start of program

    y0_Values = [] #voltage
    y1_Values = 6*[[]] #absolute rotation difference/jump for each *individual motor*
    y2_Values = [] #total absolute rotation difference (i.e. the "jump" in movement for that iteration)
    y3_Values = 6*[[]] #*estimated* stagnant load on each motor (Nm)
    GraphTitles = ["Voltage","new rotation","total new rotation","torque per motor"]
    Graph_yLabel = ["Voltage [V]","Angle [degrees]","Angle [degrees]","Torque [Nm]"]

axisFilter = 0.7 #On the new value end
xScaling, yScaling, zScaling = 0.8, 0.8, 1.2
brightVal = 75
diffCheck = 100
showImage = False
globalPrint = True
endAnglePrint = False
firstAnglePrint = False
posOption = '-'

q = [0]*6 #NOTE: q = q[0] = servo[0]
s = [0, 0, 0, 0, 0, 0, 0] #The variables that are sent to the servos

zMax = 300
a, b, Y = toRadians(0), toRadians(-45), toRadians(90)
PP = [0, 200, 200]
coord = ""

drawing = False # true if mouse is pressed
buttonPressed = False
x1,y1,x2,y2 = -1,-1,-1,-1
windowRes = (600,300)
# mouse callback function
def mouseTrack(event,x,y,flags,param):
    global x1,y1,x2,y2,drawing,buttonPressed,img,temp
    x2,y2 = x,y
    if drawing:
      img = np.zeros((windowRes[1],windowRes[0],3), np.uint8)
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        x1,y1 = x2,y2
    elif event == cv2.EVENT_MOUSEMOVE:
        buttonPressed = True
        if drawing == True:
            cv2.line(img,(0,y2),(windowRes[0],y2),(255,255,255),1)
            cv2.line(img,(x2,0),(x2,windowRes[1]),(255,255,255),1)
            cv2.circle(img,(x2,y2),10,(0,0,255),1)
            cv2.putText(img,"("+str(int(x2-windowRes[0]*0.5))+","+str(int(windowRes[1]-y2))+")",(x2+10,y2),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))
            cv2.circle(img,(int(windowRes[0]*0.5),int(windowRes[1])),50,(255,255,255),1)
            cv2.circle(img,(int(windowRes[0]*0.5),int(windowRes[1])),100,(255,255,255),1)
            cv2.circle(img,(int(windowRes[0]*0.5),int(windowRes[1])),150,(255,255,255),1)
            cv2.circle(img,(int(windowRes[0]*0.5),int(windowRes[1])),200,(255,255,255),1)
            cv2.putText(img,str(PP),(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))
            temp = img
    elif event == cv2.EVENT_LBUTTONUP:
        buttonPressed = False
        drawing = False
        img = temp #type: ignore
        # cv2.line(img,(0,y2),(windowRes[0],y2),(255,255,255),1)
        # cv2.line(img,(x2,0),(x2,windowRes[1]),(255,255,255),1)
        # cv2.circle(img,(x2,y2),10,(0,0,255),1)
        # cv2.putText(img,"("+str(int(x2-windowRes[0]*0.5))+","+str(int(windowRes[1]-y2))+")",(x2+10,y2),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))

def main():
    global PP, a, b, Y
    mode = 0
    mod_code = "q4"

    print(" Different modes for tracking/moving:")
    print(" 0. Run movement commands from .dat file")
    print(" 1. Enter position and orientation in terminal")
    print(" 2. Mouse position tracking on window")
    print(" 3. Move end-effector in a pattern")
    option = input(" input: ")
    if option == "exit": return
    else: mode = int(option)

    # "under" = given < 0
    # "over" = given < 180
    servoExceeded = False
    whichServoExceeded = 6*[False]
    typeOfExceeded = 6*["null"]

    start_time = time.time()
    x = 1 # displays the frame rate every 1 second
    counter = 0

    while True:
        # os.system("clear")
        print("\n ---Enter mode_(n) to change mode to (n)--- ")
        print(" - \"debug\" to enter debug-mod menu")
        print(" - \"mode_(n)\" to change mode to n")
        PP = [0, 200, 200]
        while True:
            isReachable = [True]
            if mode==0:
                tempInput_1 = input("Enter file path:")
                if tempInput_1 == "exit": return
                elif tempInput_1[:4] == "mode": mode=int(tempInput_1[5:])
                else:
                    movCommPath = tempInput_1
                    runFromFile(movCommPath, servo)
                break
            if mode==1:
                tempInput_1 = input("Enter coordinates [x y z] in mm: ").split()
                if tempInput_1[0] == "exit": return
                elif tempInput_1[0][:4] == "mode": mode=int(tempInput_1[0][5:])
                elif tempInput_1[0] == "debug": debug_mod_menu(mod_dict)
                else:
                    PP[0] = (float(tempInput_1[0])) # type: ignore
                    PP[1] = (float(tempInput_1[1])) # type: ignore
                    PP[2] = (float(tempInput_1[2])) # type: ignore
                    break
            if mode==2:
                tempInput_1 = input("Enter z-value in mm: ")
                if tempInput_1 == "exit": return
                elif tempInput_1[:4] == "mode": mode=int(tempInput_1[5:])
                elif tempInput_1 == "debug": debug_mod_menu(mod_dict)
                else:
                    PP[2] = float(tempInput_1) # type: ignore
                    break
            if mode==3:
                patternOpt = 1
                print("Options:")
                print(" 0.run a custom program/course of motions")
                print(" 1.choose a pre-defined pattern from a dictionary")
                print(" 2.move end-effector along an axis")
                print(" 3.move end-effector orientation with a fixed position")
                tempInput_1 = input("input: ")
                if tempInput_1 == "exit": return
                elif tempInput_1[:4] == "mode": mode=int(tempInput_1[5:])
                elif tempInput_1 == "debug": debug_mod_menu(mod_dict)
                else:
                    patternOpt = int(tempInput_1)
                    break

        if mode==1:
            tempInput_2 = input("Enter orientation values [a b Y] in degrees: ").split()
            a,b,Y = toRadians(float(tempInput_2[0])), toRadians(float(tempInput_2[1])), toRadians(float(tempInput_2[2]))
            if diagnostics: print("x:", PP[0], " y:", PP[1], " z:", PP[2], " a:", toDegrees(a), " b:", toDegrees(b), " Y:", toDegrees(Y), sep='')
            q = getAngles(PP,a,b,Y,'-', debug=mod_dict, positionIsReachable=isReachable)
            # print(q)
            print("read:",[toDegrees(q) for q in q], "posIsReachable:", isReachable)
            if isReachable[0]:
                # custom_sendToServo(servo,[toDegrees(angle) for angle in q],0,True)
                sendToServo(servo,[toDegrees(joint) for joint in q],0,useDefault=True,mode=2,printResult=True)
        elif mode==2:
            tempInput_2 = input("Enter orientation values [a b Y] in degrees: ").split()
            a,b,Y = toRadians(float(tempInput_2[0])), toRadians(float(tempInput_2[1])), toRadians(float(tempInput_2[2]))
            img = np.zeros((windowRes[1],windowRes[0],3), np.uint8)
            cv2.namedWindow('tracking_window')
            cv2.setMouseCallback('tracking_window',mouseTrack)
            temp = img
            print("\n 'Esc' - change z-value and orientation\n")
            while True:
                cv2.imshow('tracking_window', img) #use this if the previous drawings are not to be used
                k = cv2.waitKey(1) & 0xFF
                if k == 27: break
                elif k == 119: PP[2]+=10 #type: ignore
                elif k == 115: PP[2]-=10 #type: ignore
                if drawing:
                    PP[0], PP[1] = x2-windowRes[0]*0.5,windowRes[1]-y2 # type: ignore
                    q = getAngles(PP,a,b,Y,'-',positionIsReachable=isReachable, debug=mod_dict)
                    # print(q)
                    if isReachable[0]: sendToServo(servo,[toDegrees(joint) for joint in q],0,useDefault=True,mode=0)
                counter+=1
                if (time.time() - start_time) > x :
                    print("FPS: ", counter / (time.time() - start_time))
                    counter = 0
                    start_time = time.time()
            cv2.destroyAllWindows()
        elif mode==3:
            if patternOpt==0: #type: ignore
                print("Pick any of these programs")
                for key,_ in mov_Programs.items(): print(" - \"",key,"\"", sep='')
                key = input("input the program name: ")
                if key=="exit": break
                presetAngles = 6*[0]
                for joint in range(6): presetAngles[joint] = servo[joint].angle / constants_q[joint]["fixed"]
                if key=="axisTest" and diagnostics:
                    mov_Programs[key](
                        servo,
                        [diagnostics,x_Values,
                        [y0_Values,y1_Values,y2_Values,y3_Values],ser_arduino]
                        )
                else: mov_Programs[key](servo)
                sendToServo(servo,presetAngles,0,mode=2)
                if diagnostics and key=="axisTest":
                    fig = plt.figure(figsize=(19, 6))
                    ax = [0,0,0,0]
                    y_Values = [y0_Values,y1_Values,y2_Values,y3_Values]
                    for axis in range(len(ax)):
                        ax[axis] = fig.add_subplot(1,4,axis+1) #type: ignore
                        ax[axis].set_xlim(0,round(x_Values[-1])) #type: ignore
                        ax[axis].set_title(GraphTitles[axis]) #type: ignore
                        ax[axis].set_xlabel("time [seconds]") #type: ignore
                        ax[axis].set_ylabel(Graph_yLabel[axis]) #type: ignore
                        ax[axis].grid() #type: ignore

                        if axis==1 or axis==3:
                            for j in range(6):
                                ax[axis].plot(x_Values,y_Values[axis][j],linestyle='solid',label='q'+str(j+1)) #type: ignore
                        else:
                            ax[axis].plot(x_Values,y_Values[axis],linestyle='solid') #type: ignore
                            if axis==0:
                                ax[axis].axhline( #type: ignore
                                    y=(sum(y_Values[axis])/len(y_Values[axis])),
                                    color='red',linestyle='-',
                                    label=f"avg:{round(sum(y_Values[axis])/len(y_Values[axis]))}V"
                                    )
                        ax[axis].legend(loc='upper right',framealpha=0.3) #type: ignore
                    fig.tight_layout(pad=5.0)
                    fig.suptitle("")

                    currentDate = str(datetime.now()).replace(" ", ";")
                    relativePath = "/home/pi/Chromebook-projects/projects/proj_Hexclaw/hexclaw_files/voltage_readings/media/"
                    fileTitle = "mov_Voltage_"
                    plt.savefig(relativePath+fileTitle+currentDate+".png") #type: ignore
                    plt.show()

            if patternOpt==1: #type: ignore
                print("Pick any of these patterns")
                for key,_ in mov_Patterns.items(): print(" - \"",key,"\"", sep='')
                key = input("input a key:")
                if key=="exit": break
                for i in range(len(mov_Patterns[key])):
                    q = getAngles(
                        [mov_Patterns[key][i][0],mov_Patterns[key][i][1],mov_Patterns[key][i][2]],
                        toRadians(mov_Patterns[key][i][3]),
                        toRadians(mov_Patterns[key][i][4]),
                        toRadians(mov_Patterns[key][i][5]),
                        '-',
                        positionIsReachable=isReachable,
                        debug=mod_dict
                        )
                    print(mov_Patterns[key][i])
                    if isReachable[0]: sendToServo(servo,[toDegrees(joint) for joint in q],0,useDefault=True,mode=2)
                    time.sleep(1)
            elif patternOpt==2: #type: ignore
                axis = input("\nEnter what axis to move [x, y or z] [unit: mm]:")
                if axis=="exit": break
                orientToUse = input("\nEnter orientation for axis test [a, b and Y]:").split()
                fullPos = [0,link[4]+link[5]+120,150]
                presetAngles = [0,0,0,0,0,0]
                for joint in range(6): presetAngles[joint] = servo[joint].angle / constants_q[joint]["fixed"]
                prevSent=False
                for direction in range(1, -2, -2):
                    for pos in range(-200, 200):
                        if axis == "x": fullPos[0] = direction*pos*0.75  #type: ignore #300
                        if axis == "y": fullPos[1] = direction*pos*0.5+100 #type: ignore #200
                        if axis == "z": fullPos[2] = direction*pos*0.5+200 #type: ignore #200
                        q = getAngles(
                            fullPos,
                            toRadians(int(orientToUse[0])),toRadians(int(orientToUse[1])),toRadians(int(orientToUse[2])),
                            '-', positionIsReachable=isReachable,
                            debug=mod_dict
                        )
                        if isReachable[0]:
                            if prevSent: sendToServo(servo,[toDegrees(joint) for joint in q],0,useDefault=True,mode=0)
                            else:
                                sendToServo(servo,[toDegrees(joint) for joint in q],2,useDefault=True,mode=2)
                                time.sleep(1)
                                prevSent=True
                        if axis == "x": time.sleep(0.005)
                        else: time.sleep(0.001)
                time.sleep(1.5)
                sendToServo(servo,presetAngles,0,mode=2)
            elif patternOpt==3: #type: ignore
                orientToUse = input("\nEnter what orientation to test [a, b or Y] [unit: degrees]:")
                posToUse = input("\nEnter coordinate for position test [x, y and z]:").split()
                for _ in range(3): posToUse[_] = int(posToUse[_]) #type: ignore
                fullOrient = [0,0,0]
                presetAngles = [0,0,0,0,0,0]
                for joint in range(6): presetAngles[joint] = servo[joint].angle / constants_q[joint]["fixed"]
                for direction in range(1, -2, -2):
                    for angle in range(-90, 90):
                        if orientToUse == "a": fullOrient[0] = direction*angle
                        if orientToUse == "b": fullOrient[1] = direction*angle
                        if orientToUse == "Y": fullOrient[2] = direction*angle
                        q = getAngles(posToUse,toRadians(fullOrient[0]),toRadians(int(fullOrient[1])),toRadians(int(fullOrient[2])),
                        '-',positionIsReachable=isReachable,
                        debug=mod_dict
                        )
                        if isReachable[0]: sendToServo(servo,[toDegrees(joint) for joint in q],0,useDefault=True,mode=0)
                        time.sleep(0.01)
                time.sleep(1.5)
                sendToServo(servo,presetAngles,0,mode=2)

        # input("\npaused. Press enter to continue...")

if __name__ == "__main__":
    main()
    sendToServo(servo,[135,45,180,45,180,90],1,mode=2)
    GPIO.output(ledRelay, False)
    pca.deinit()


"""
文件名: Code/Chapter09/C05_FastText/main.py
创建时间: 2023/7/22 10:31 上午
作 者: @空字符
公众号: @月来客栈
知 乎: @月来客栈 https://www.zhihu.com/people/the_lastest
"""

import logging
from gensim.models import KeyedVectors
import fasttext
from fasttext.util import reduce_model
import sys
import os

sys.path.append('../../')
from utils import DATA_HOME

def load_fasttext_model():
    path_to_model = os.path.join(DATA_HOME, 'Pretrained', 'fasttext', 'cc.zh.300.bin')
    # path_to_model = os.path.join(DATA_HOME, 'Pretrained', 'fasttext', 'cc.zh.300.vec.gz')
    # model = KeyedVectors.load_word2vec_format(path_to_model, binary=False)
    ft = fasttext.load_model(path_to_model)
    logging.info(f"词向量的维度: {ft.get_dimension()}")
    logging.info(f"中国: {ft.get_word_vector('中国')}")
    logging.info(f"与中国最相似的5个词为: {ft.get_nearest_neighbors('中国', k=5)}")
    logging.info(ft.get_subwords("跟我一起学深度学习"))
    reduce_model(ft, 100)  # 降维
    logging.info(f"词向量的维度: {ft.get_dimension()}")
    path_to_model = os.path.join(DATA_HOME, 'Pretrained', 'fasttext', 'cc.zh.100.bin')
    ft.save_model(path_to_model)

def get_get_analogies():
    ft = fasttext.load_model(os.path.join(DATA_HOME, 'Pretrained', 'fasttext', 'cc.zh.300.bin'))
    logging.info('有凤来仪' in ft.words)
    logging.info(f"与东坡居士最相似的5个词为: {ft.get_nearest_neighbors('有凤来仪', k=5)}")
    logging.info(ft.get_analogies("柏林", "德国", "法国", k=5))

    # False
    # 与有凤来仪最相似的5个词为: [(0.457183, 'Viscosity'), (0.454175, 'viscosity'), (0.361536, 'thb'), (0.343013, 'kg/m2'), (0.335760, 'Dirham')]
    # [(0.743810, '巴黎'), (0.583832, '里昂'), (0.555544, '法國'), (0.547275, '斯特拉斯堡'), (0.536760, '坎城')]

    ft = fasttext.load_model(os.path.join(DATA_HOME, 'Pretrained', 'fasttext', 'cc.en.300.bin'))
    logging.info('accomodtion' in ft.words)
    logging.info(f"与accomodtion最相似的5个词为: {ft.get_nearest_neighbors('accomodation', k=5)}")
    logging.info(ft.get_analogies("berlin", "germany", "france", k=5))
    # False
    # 与accomodtion最相似的5个词为: [(0.858731, 'accomadation'), (0.828016, 'acommodation'), (0.822644, 'accommodation'), (0.821873, 'accomdation'), (0.793275, 'Accomodation')]
    # [(0.730373, 'paris'), (0.640853, 'france.'), (0.639331, 'avignon'), (0.631667, 'paris.'), (0.589559, 'montpellier')]

if __name__ == '__main__':
    # load_fasttext_model()
    get_get_analogies()


import threading

import time

def worker():
    count = 0

    while True:
        if (count >= 5):
            # raise RuntimeError()
          break
        time.sleep(1)
        print("I'm working")
        count += 1

t = threading.Thread(target=worker, name='worker')  # 线程对象.

t.start()  # 启动.

print("==End==")


import threading
import socket

class Estatisticas:
    def __init__(self):
        self.questoes = {}

    def atualizar_estatisticas(self, num_questao, acertos, erros):
        self.questoes[num_questao] = {'acertos': acertos, 'erros': erros}

    def obter_estatisticas(self):
        return self.questoes

def tratar_conexao(conn, addr, estatisticas):
    print("Cliente conectado:", addr)
    while True:
        data = conn.recv(1024).decode()
        if not data:
            break

        num_questao, _, respostas = data.split(";")
        acertos, erros = calcular_acertos_erros(respostas)
        estatisticas.atualizar_estatisticas(num_questao, acertos, erros)

        resposta = f"Questão: {num_questao}; Acertos: {acertos}; Erros: {erros}"
        conn.send(resposta.encode())

    print("Cliente desconectado:", addr)
    conn.close()

def calcular_acertos_erros(respostas):
    acertos = respostas.count('V')
    erros = respostas.count('F')
    return acertos, erros

def iniciar_servidor(host, port):
    estatisticas = Estatisticas()
    servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    servidor.bind((host, port))
    servidor.listen(5)
    print("Servidor iniciado. Aguardando conexões...")

    while True:
        conn, addr = servidor.accept()
        thread = threading.Thread(target=tratar_conexao, args=(conn, addr, estatisticas))
        thread.start()

if __name__ == "__main__":
    host = "127.0.0.1"
    port = 8888
    iniciar_servidor(host, port)


import os
import json
from botocore.exceptions import ClientError
from unittest import TestCase
from unittest.mock import patch
from exceptions import YahooOauthError
from login_yahoo_authorization_url import LoginYahooAuthorizationUrl

class TestLoginYahooAuthorizationUrl(TestCase):
    @classmethod
    def setUpClass(cls):
        os.environ['YAHOO_CLIENT_ID'] = 'fake_yahoo_consumer_key'
        os.environ['YAHOO_SECRET'] = 'fake_yahoo_consumer_secret'
        os.environ['YAHOO_OAUTH_CALLBACK_URL'] = 'http://localhost'

    def test_exec_main_ok(self):
        with patch('login_yahoo_authorization_url.YahooUtil') as yahoo_mock:
            yahoo_mock.return_value.get_authorization_url.return_value = 'oauth_url'
            response = LoginYahooAuthorizationUrl({}, {}).main()
            self.assertEqual(response['statusCode'], 200)
            self.assertEqual(
                json.loads(response['body']),
                {'url': 'oauth_url'}
            )

    def test_exec_main_ng_with_clienterror(self):
        with patch('login_yahoo_authorization_url.YahooUtil') as yahoo_mock:
            yahoo_mock.return_value.generate_auth_url.side_effect = ClientError(
                {'Error': {'Code': 'UserNotFoundException'}},
                'operation_name'
            )
            response = LoginYahooAuthorizationUrl({}, {}).main()
            self.assertEqual(response['statusCode'], 500)
            self.assertEqual(
                json.loads(response['body']),
                {'message': 'Internal server error: LoginYahooAuthorizationUrl'}
            )

    def test_exec_main_ng_with_yahoo(self):
        with patch('login_yahoo_authorization_url.YahooUtil') as yahoo_mock:
            yahoo_mock.return_value.generate_auth_url.side_effect = YahooOauthError(
                endpoint='http://example.com',
                status_code=400,
                message='error'
            )
            response = LoginYahooAuthorizationUrl({}, {}).main()
            self.assertEqual(response['statusCode'], 500)
            self.assertEqual(
                json.loads(response['body']),
                {'message': 'Internal server error: LoginYahooAuthorizationUrl'}
            )


import multiprocessing
from time import ctime

def consumer(input_q):
    print("Into consumer:",ctime())
    while True:
        # 处理项
        item = input_q.get()
        print ("pull",itemm,"out of q")#此处代替为有用的工作
        input_q.tast_done()#发出信号通知任务完成
    print("Out of consumer:",ctime())##此句末执行，因为q.join()信号后，主进程启动，为等到print此语句完

def prodeuce(sequence,out_q):
    print("Inpo producer ",ctime())
    for item in sequence:
        output_q.put(item)
        print("put",item,"into q")
    print("Out of producer",ctime())

if __name__ == '__main__':
    q = multiprocessing.JoinableQueue()
    #运行消费者进程
    cons_p = multiprocessing.Process(target= consumer, args = (q,1))
    cons_p.daemon = True
    cons_p.start()

    #在生产多个项，sqeuence代表要发送个消费者的项的序列
    #在实践中，这可能是生成器的输出或通过一些其他生产方式出来
    sequence = [1,2,3,4]
    prodeuce(sequence,q)
    q.join()


from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import json
from pathlib import Path
from time import sleep
from selm.gales import settings

class Gale():

    def __init__(self, implicitly_wait=12):
        option = webdriver.ChromeOptions()
        # 防止打印一些无用的日志
        option.add_experimental_option(
            "excludeSwitches", ['enable-automation', 'enable-logging'])
        # 初始化driver
        self.driver = webdriver.Chrome(options=option)
        # 设置浏览器窗口大小
        # self.driver.maximize_window()
        self.driver.set_window_rect(-7, 0, 1190, 1047)
        # 设置隐性等待时间
        self.driver.implicitly_wait(implicitly_wait)

    def get_url(self, url: str):
        '''页面访问

        Args:
            url (str): url地址
        '''
        self.driver.get(url)

    def get_url_by_cookies(self, url: str, cookies_path: Path):
        '''带cookies的页面访问

        Args:
            url (str): 登录网址
            cookies_path (Path): cookies储存地址
        '''

        self.get_url(url)
        cookies = json.loads(open(cookies_path).read())
        for c in cookies:
            self.driver.add_cookie(c)
        self.get_url(url)
        # self.driver.refresh()

    def get_cookies(self, url: str, file_path: Path, user_data: dict, input_time: int = 12):
        '''获取cookies

        Args:
            url (str): 登录网址
            file_path (Path): cookies储存路径
            user_data (dict): 用户登录数据
            {
                "账号":(css_selector, str),
                "密码":(css_selector, str),
                ...
                "login": css_selector
            }
            input_time (int, optional): Defaults to 12. 用户输入验证码的时间
        '''

        self.get_url(url)
        for i in user_data:
            if i == 'login':
                continue
            for selector, content in user_data[i]:
                self.find_by_selector(selector).send_keys(content)
                # button_cache.send_keys(content)
        # 等待用户手动输入验证码
        sleep(input_time)
        self.find_by_selector(user_data["login"]).click()
        cookies = self.driver.get_cookies()
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(json.dumps(cookies))

    def find_by_id(self, id):
        '''通过id查找元素

        Args:
            id (str): id路径

        Returns:
            WebElement: WebElement对象
        '''

        return self.driver.find_element_by_id(id)

    def find_by_selector(self, selector):
        '''通过css属性查找webelement元素

        Args:
            selector (str): css属性

        Returns:
            WebElement: WebElement对象
        '''

        return self.driver.find_element_by_css_selector(selector)

    def find_by_xpath(self, xpath):
        '''通过xpath查找元素

        Args:
            xpath (str): xpath路径

        Returns:
            WebElement: WebElement对象
        '''

        return self.driver.find_element_by_xpath(xpath)

    def wait_clickable(self, ele_path, by="selector", time=10):
        '''等待元素可以被点击
        '''

        if by == "selector":
            return WebDriverWait(self.driver, time).until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, ele_path)))
        elif by == "xpath":
            return WebDriverWait(self.driver, time).until(EC.element_to_be_clickable(
                (By.XPATH, ele_path)))
        else:
            raise TypeError(f"not type {by}")

    def wait_presence(self, ele_path, by="selector", time=10):
        '''显性等待元素出现,如果元素在规定时间内出现就返回该元素

        Args:
            ele_path (str): 与by对应的属性路径
            by (str, optional): Defaults to "selector". [还可以是xpath等]
            time (int, optional): Defaults to 10. [默认的显性等待时间]

        Raises:
            TypeError: 不存在的by方法

        Returns:
            WebElement: 如果元素在规定时间内被查找到则返回该元素WebElement对象
        '''

        if by == "selector":
            return WebDriverWait(self.driver, time).until(EC.presence_of_element_located(
                (By.CSS_SELECTOR, ele_path)))
        elif by == "xpath":
            return WebDriverWait(self.driver, time).until(EC.presence_of_element_located(
                (By.XPATH, ele_path)))
        else:
            raise TypeError(f"not type {by}")

    def wait_not_presence(self, ele_path, by="selector", time=10):
        '''等待元素不存在
        '''

        if by == "selector":
            return WebDriverWait(self.driver, time).until_not(EC.presence_of_element_located(
                (By.CSS_SELECTOR, ele_path)))
        elif by == "xpath":
            return WebDriverWait(self.driver, time).until_not(EC.presence_of_element_located(
                (By.XPATH, ele_path)))
        else:
            raise TypeError(f"not type {by}")

    def wait_visibility(self, ele_path, by="selector", time=10):
        '''等待元素对用户可见
        '''

        if by == "selector":
            return WebDriverWait(self.driver, time).until(EC.visibility_of_element_located(
                (By.CSS_SELECTOR, ele_path)))
        elif by == "xpath":
            return WebDriverWait(self.driver, time).until(EC.visibility_of_element_located(
                (By.XPATH, ele_path)))
        else:
            raise TypeError(f"not type {by}")

    def wait_invisibility(self, ele_path, by="selector", time=10):
        '''等待元素对用户不可见
        '''

        if by == "selector":
            return WebDriverWait(self.driver, time).until(EC.invisibility_of_element_located(
                (By.CSS_SELECTOR, ele_path)))
        elif by == "xpath":
            return WebDriverWait(self.driver, time).until(EC.invisibility_of_element_located(
                (By.XPATH, ele_path)))
        else:
            raise TypeError(f"not type {by}")

    def save2png(self, file_name):
        '''获取当前浏览器窗口屏幕截图

        Args:
            file_name (str): 图片名(图片默认存放到data目录下)
        '''

        file_path = settings.DATA_DIR / file_name
        self.driver.get_screenshot_as_file(str(file_path))
        sleep(1)

    def close(self):
        '''关闭当前窗口
        '''

        self.driver.close()

    def quit(self):
        '''关闭整个浏览器
        '''

        self.driver.quit()

    def refresh(self):
        '''刷新
        '''
        self.driver.refresh()


from __future__ import division
from __future__ import absolute_import
#typing

#overrides

from allennlp.common import squad_eval
from allennlp.training.metrics.metric import Metric

class SquadEmAndF1(Metric):
    u"""
    This :class:`Metric` takes the best span string computed by a model, along with the answer
    strings labeled in the data, and computed exact match and F1 score using the official SQuAD
    evaluation script.
    """
    def __init__(self)        :
        self._total_em = 0.0
        self._total_f1 = 0.0
        self._count = 0

    #overrides
    def __call__(self, best_span_string, answer_strings):
        u"""
        Parameters
        ----------
        value : ``float``
            The value to average.
        """
        exact_match = squad_eval.metric_max_over_ground_truths(
                squad_eval.exact_match_score,
                best_span_string,
                answer_strings)
        f1_score = squad_eval.metric_max_over_ground_truths(
                squad_eval.f1_score,
                best_span_string,
                answer_strings)
        self._total_em += exact_match
        self._total_f1 += f1_score
        self._count += 1

    #overrides
    def get_metric(self, reset       = False)                       :
        u"""
        Returns
        -------
        Average exact match and F1 score (in that order) as computed by the official SQuAD script
        over all inputs.
        """
        exact_match = self._total_em / self._count if self._count > 0 else 0
        f1_score = self._total_f1 / self._count if self._count > 0 else 0
        if reset:
            self.reset()
        return exact_match, f1_score

    #overrides
    def reset(self):
        self._total_em = 0.0
        self._total_f1 = 0.0
        self._count = 0

    def __str__(self):
        return "SquadEmAndF1(em={self._total_em}, f1={self._total_f1})"

SquadEmAndF1 = Metric.register(u"squad")(SquadEmAndF1)


'''Faça um programa que leia três numeros  e mostre qual é o maior e qual é o menor'''

n1 = int(input('Digite um número: '))
n2 = int(input('Digite um número: '))
n3 = int(input('Digite um número: '))

maior = n1

if n2 > n1:
    maior = n2

if n3 > maior:
    maior = n3

menor = n1

if n2 < n1:
    menor = 2

if n3 < menor:
    menor = n3

print('maior: {} \nmenor: {}'.format(maior,menor))

'''
outra forma

maior = menor = 0
numero = []

for n in range(0,3):
    numero.append(int(input(f'Digite o {n +1}º número: ')))
numero.sort()
print(f'Menor número: {numero[0]}')
print(f'Maior número: {numero[-1]}')'''


from bson.objectid import ObjectId
from flask import Blueprint, jsonify
from assets.extensions import mongo
from assets.decors import errorhandler, tokenrequired

accounts = Blueprint("accounts", __name__, url_prefix="/accounts")

# STATUS
@accounts.route("/<account_id>/status", methods=["GET"])
@tokenrequired
@errorhandler
def get_status(current_user, account_id):

    # query the user collection for account status
    accounts = mongo.db.users.find_one({"_id": ObjectId(current_user["_id"]["$oid"])})[
        "Accounts"]

    if account_id in accounts:

        status = accounts[account_id]["Active"]

        return jsonify({"account_status": status, "account_id": account_id}), 200

    return jsonify({"error": "invalid account id", "account_id": account_id}), 400

@accounts.route("/<account_id>/status", methods=["PUT"])
@tokenrequired
@errorhandler
def update_status(current_user, account_id):

    resp = mongo.db.users.update_one({"_id": ObjectId(current_user["_id"]["$oid"])},
                                     [{"$set": {f"Accounts.{account_id}.Active": {"$eq": [False, f"$Accounts.{account_id}.Active"]}}}])

    # if update did not occur because no account id found
    if resp.matched_count == 0 or resp.modified_count == 0:

        return jsonify({"error": "failed to update status", "account_id": account_id}), 400

    return jsonify({"success": "status updated", "account_id": account_id}), 201


'''
There are N network nodes, labelled 1 to N.

Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.

Example 1:

Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2

Note:

N will be in the range [1, 100].
K will be in the range [1, N].
The length of times will be in the range [1, 6000].
All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.
'''

# Dijkstra's heap O(E logE) time and O(N + E) space
from collections import defaultdict
from heapq import *

class Solution:
    def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
        graph = defaultdict(list)
        for u, v, w in times:
            graph[u].append((w,v))

        pq = [(0, K)]
        dist = {}
        while pq:
            d, node = heappop(pq)
            if node in dist:
                continue
            dist[node] = d

            for d2, nei in graph[node]:
                if nei not in dist:
                    heappush(pq, (d+d2, nei))

        return max(dist.values()) if len(dist) else -1

# Dijkstra's basic O(N**2 + E) and O(N + E) space
from collections import defaultdict

class Solution:
    def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
        graph = defaultdict(list)
        for u, v, w in times:
            graph[u].append((w,v))

        dist = {node: float('inf') for node in range(1, N+1)}
        seen = [False] * (N+1)
        dist[K] = 0

        while True:
            cand_node = -1
            cand_dist = float('inf')
            for i in range(1, N+1):
                if not seen[i] and dist[i] < cand_dist:
                    cand_dist = dist[i]
                    cand_node = i

            if cand_node < 0:
                break
            seen[cand_node] = True
            for d, nei in graph[cand_node]:
                dist[nei] = min(dist[nei], dist[cand_node] + d)

        ans = max(dist.values())

        return ans if ans < float('inf') else -1

# dfs O(N**N + ElogE) time and O(N + E) space
from collections import defaultdict

class Solution:
    def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
        graph = defaultdict(list)
        for u, v, w in times:
            graph[u].append((w,v))

        dist = {node: float('inf') for node in range(1, N+1)}

        def dfs(node, elapsed):
            if elapsed >= dist[node]:
                return
            dist[node] = elapsed
            for time, nei in sorted(graph[node]):
                dfs(nei, elapsed + time)

        dfs(K, 0)
        ans = max(dist.values())

        return ans if ans < float('inf') else -1


# import streamlit as st
# import threading
import time
# # 定义共享变量
# is_running = True

# # 定义线程函数
# def thread_function():
#     a = 0
#     st.text(f'in to thread')
#     global is_running
#     while is_running:
#         # 线程执行的逻辑
#         a += 1
#         st.text(a)
#         time.sleep(1)
#     st.text(f'out thread')

# def stop():
# # 当需要停止线程时
#     global is_running
#     if st.button('stop'):
#         is_running = False
#     if st.button('start'):
#         is_running = True

# if __name__ == "__main__":
#     # 创建线程并启动
#     thread = threading.Thread(target=thread_function)
#     thread.start()
#     stop()

import threading
# 定义共享变量
is_running = threading.Event()

# 定义线程函数
def thread_function():
    while not is_running.is_set():
        # 线程执行的逻辑
        print(1)

# 当需要停止线程时
def stop():
    is_running.set()

if __name__ == "__main__":

# 创建线程并启动
    thread = threading.Thread(target=thread_function)
    thread.start()
    time.sleep(1)
    stop()

stop_flag = threading.Event()

def receive_data():
    print(f'into receive data')
    while not stop_flag.is_set():
        ser = serial.Serial(port, baud_rate, timeout=1)
        received_data = []  # List to store received data
        start_time = time.time()  # Start time of data fetching
        inner_time = time.time()
        while not stop_flag.is_set():
            data = ser.readline().decode().strip()  # Read a line of data and remove whitespace
            elapsed_time = time.time() - start_time
            if data:
                print(data)
                received_data.append(data)
                inner_time = time.time()
            if time.time() - inner_time > timeout_seconds:
                print(f'Time out for: {elapsed_time}')
                break
        ser.close()
        end_time = time.time() - start_time  # duration of one cycle
        # Save received data as a text file only if it has been fetched for more than 10 seconds
        if end_time >= fetch_duration_threshold:
            file_name = f"./temp/received_data.txt"
            # Save received data to a new text file
            with open(file_name, 'w') as file:
                file.write('\n'.join(received_data))
            print('Finish one record')
        time.sleep(1)  # Wait for 1 second before restarting the loop
    print(f'end receive.')

def main():
    model = get_model()
    # your drinked
    if st.checkbox("start receive"):
        # 创建 Thread 实例
        t1 = Thread(target=receive_data)
        if st.button("start"):
            print(f'st')
            stop_flag.clear()
            # 启动线程运行
            t1.start()
        # 等待所有线程执行完毕
        if st.button("stop"):
            stop_flag.set()
            print(f'flag {stop_flag.is_set()}')


import typing

from pydantic import BaseModel, root_validator

from candid import CandidApiEnvironment
from candid.client import CandidApi, AsyncCandidApi
from candid.resources.auth.client import AuthClient, AsyncAuthClient
from candid.resources.auth.resources.v_2 import AuthGetTokenRequest
from candid.resources.billing_notes.client import BillingNotesClient, AsyncBillingNotesClient
from candid.resources.encounters.client import EncountersClient, AsyncEncountersClient
from candid.resources.expected_network_status.client import ExpectedNetworkStatusClient, \
    AsyncExpectedNetworkStatusClient
from candid.resources.payers.client import PayersClient, AsyncPayersClient

class CandidApiClientOptions(BaseModel):
    token: typing.Optional[str]
    client_id: typing.Optional[str]
    client_secret: typing.Optional[str]

    @root_validator(pre=False)
    def token_or_client_id_and_secret_present(cls, values):
        if values.get("token") is not None:
            return values
        elif values.get("client_id") is not None and values.get("client_secret") is not None:
            return values
        raise ValueError("Either token or client_id and client_secret must be provided")

def get_token_for_options(options: CandidApiClientOptions, environment: CandidApiEnvironment) -> str:
    if options.token is not None:
        return options.token
    else:
        unauthed_client = CandidApi(environment=environment, token=None)
        response = unauthed_client.auth.v_2.get_token(request=AuthGetTokenRequest(client_id=options.client_id, client_secret=options.client_secret))
        return response.access_token

class CandidApiClient:
    def __init__(
        self, *, options: CandidApiClientOptions, environment: CandidApiEnvironment = CandidApiEnvironment.PRODUCTION
    ):
        candid = CandidApi(token=get_token_for_options(options, environment), environment=environment)
        self.auth = candid.auth
        self.encounters = candid.encounters
        self.billing_notes = candid.billing_notes
        self.expected_network_status = candid.expected_network_status
        self.payers = candid.payers

class AsyncCandidApiClient:
    def __init__(
        self, *, options: CandidApiClientOptions, environment: CandidApiEnvironment = CandidApiEnvironment.PRODUCTION
    ):
        candid = AsyncCandidApi(token=get_token_for_options(options, environment), environment=environment)
        self.auth = candid.auth
        self.encounters = candid.encounters
        self.billing_notes = candid.billing_notes
        self.expected_network_status = candid.expected_network_status
        self.payers = candid.payers


from Logic.crud import add_cheltuiala, delete_cheltuiala
from Domain.cheltuiala import to_str
def new_menu():
    '''
    Meniu pentru consola noua
    :return:
    '''
    print('''
    Tasteaza comenzile separate prin ";". Comenzi acceptate: add, delete, showall, exit, help.
    Tasteaza "help" pentru a afla detalii despre comenzi.
    ''')

def help():
    '''
    Functie prin intermediul careia se definesc comenzile:
    add,
    :return:
    '''
    print('''
    help: arata meniu
    add, <id>,<nr_ap>,<suma>,<data>,<tipul>: adauga cheltuiala
    delete,<id>: sterge cheltuiala
    showall: arata toate cheltuielile
    exit: inchidere program
    ''')

def show_all(cheltuieli):
    for cheltuiala in cheltuieli:
        print(to_str(cheltuiala))

def run_comenzi(cheltuieli):
    while True:
        print(new_menu())
        exit = False
        comanda = input("Tastati comenzile despartite de ';': ").split(';')
        for i in range(len(comanda)):
            action = comanda[i].split(',')
            if action[0] == 'help':
                help()
            elif action[0] == 'add':
                try:
                    cheltuieli = add_cheltuiala(cheltuieli, action[1], action[2], action[3], action[4], action[5], [], [])
                except IndexError as ie:
                    print(f"Eroare: {ie}")
            elif action[0] == 'delete':
                cheltuieli = delete_cheltuiala(cheltuieli, action[1], [], [])
            elif action[0] == 'showall':
                show_all(cheltuieli)
            elif action[0] == 'exit':
                exit = True
                break
        if exit is True:
            print("Programul s-a oprit")
            break


from Atum.models.hpo import HPOManageService

if __name__ == '__main__':
    hpo_service = HPOManageService()
    config = dict()
    config['search_space'] = {
        'learning_rate': {'_type': 'uniform', '_value': [0.001, 0.005]},
        'batch_size': {'_type': 'choice', '_value': [32, 64, 128]}
    }
    config['parallel_search'] = 8
    config['gpu_number_per_task'] = 1
    config['optimize_mode'] = 'maximize'
    config['search_time'] = '1h'
    config['task_command'] = "python /mnt/beegfs/ssd_pool/docker/user/hadoop-automl/wengkaiheng/code/infra-mt-cvzoo-classification/tools/automl_tools/train_hpo.py /mnt/beegfs/ssd_pool/docker/user/hadoop-automl/wengkaiheng/code/infra-mt-cvzoo-classification/configs/custom/Res18_cifar.py --hpo"
    hpo_service.update_config(config)
    hpo_service.start()


print('Are you ready to play!')
start=input('Yes(or)No :').lower()
score=0
if start !='yes':
  quit()
print("let's play :)")
ans=input("which is the smallest ocean in the world? ").lower()
if ans=='arctic':
  print('correct!')
  score +=1
else:
  print('incorrect!')

ans=input("which is the oldest language in the world? ").lower()
if ans=='tamil':
  print('correct!')
  score +=1
else:
  print('incorrect!')

ans=input("brain of computer is? ").lower()
if ans=='cpu':
  print('correct!')
  score +=1
else:
  print('incorrect!')

ans=input("1024 kilobytes is equal to? ").lower()
if ans=='1 mb':
  print('correct!')
  score +=1
else:
  print('incorrect!')
print('your score: '+str(score))
print('your percentage :'+str((score/4)*100)+'%')


from django.urls import path, include
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path("", views.index, name='index'),
    path("news/<int:id>/", views.see_full_news),
    path("main_page/", views.main_page, name='main_page'),
    path("dataselect/", views.dataselect, name='dataselect'),
    path("station/", views.station, name='station'),
    path("geofrom", views.geoform, name='geofrom'), path('captcha/', include('captcha.urls')),
    path("req_form", views.requsets_list, name = 'req_form'),
    path("structure", views.struct, name= "structure"),
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [path('captcha/', include('captcha.urls')),]


import torch
import torch.nn as nn
from argparse import Namespace
from layers.Layers import DualAttenion, Transpose

class CARD(nn.Module):
    def __init__(self, args: Namespace) -> None:
        super(CARD, self).__init__()
        self.patch_len = args.patch_len
        self.stride = args.stride
        self.embed_dim = args.embed_dim
        self.task_name = args.task_name
        patch_num = int((args.seq_len - self.patch_len)/self.stride + 1)
        self.patch_num = patch_num
        self.pos_embed = nn.Parameter(
            torch.randn(patch_num, args.embed_dim)*1e-2)
        self.total_token_number = self.patch_num + 1
        args.total_token_number = self.total_token_number

        # embeding layer related
        self.input_projection = nn.Linear(self.patch_len, args.embed_dim)
        self.input_dropout = nn.Dropout(args.dropout)
        self.cls = nn.Parameter(torch.randn(1, args.embed_dim)*1e-2)

        # mlp decoder
        self.out_proj = nn.Linear(
            (patch_num+1+self.model_token_number)*args.embed_dim, args.pred_len)

        # dual attention encoder related
        self.Attentions_over_token = nn.ModuleList(
            [DualAttenion(args) for i in range(args.hiden_layer_num)])
        self.Attentions_over_channel = nn.ModuleList(
            [DualAttenion(args, over_channel=True) for i in range(args.hiden_layer_num)])
        self.Attentions_mlp = nn.ModuleList(
            [nn.Linear(args.embed_dim, args.embed_dim) for i in range(args.hiden_layer_num)])
        self.Attentions_dropout = nn.ModuleList(
            [nn.Dropout(args.dropout) for i in range(args.hiden_layer_num)])
        self.Attentions_norm = nn.ModuleList([nn.Sequential(Transpose(1, 2),
                                                            nn.BatchNorm1d(args.embed_dim,
                                                                           momentum=args.momentum),
                                                            Transpose(1, 2)) for i in range(args.hiden_layer_num)])

    def forward(self, z: torch.Tensor):
        b, c, s = z.shape
        # inputs nomralization
        z_mean = torch.mean(z, dim=(-1), keepdims=True)
        z_std = torch.std(z, dim=(-1), keepdims=True)
        z = (z - z_mean)/(z_std + 1e-4)
        # tokenization
        zcube = z.unfold(dimension=-1, size=self.patch_len, step=self.stride)
        z_embed = self.input_dropout(
            self.input_projection(zcube)) + self.pos_embed
        cls_token = self.cls.repeat(z_embed.shape[0], z_embed.shape[1], 1, 1)
        z_embed = torch.cat((cls_token, z_embed), dim=-2)
        # dual attention encoder
        inputs = z_embed
        b, c, t, h = inputs.shape
        for a_2, a_1, mlp, drop, norm in zip(self.Attentions_over_token, self.Attentions_over_channel, self.
                                             Attentions_mlp, self.Attentions_dropout, self.Attentions_norm):
            output_1 = a_1(inputs.permute(0, 2, 1, 3)).permute(0, 2, 1, 3)
            output_2 = a_2(output_1)
            outputs = drop(mlp(output_1+output_2))+inputs
            outputs = norm(outputs.reshape(b*c, t, -1)).reshape(b, c, t, -1)
            inputs = outputs
        # mlp decoder
        z_out = self.out_proj(outputs.reshape(b, c, -1))
        # denomrlaization
        z = z_out * (z_std+1e-4) + z_mean
        return z


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

from PIL import Image

def make_data_index(args, index):
    '''
    :param args:
    :param index:
    :return:
    '''
    # K is for K-fold cross-validation
    # k is The k-th fold used for test
    K = args.K_fold  # Here, we don't use this because we use 10-fold cross-validation in default
    k = args.k_test
    # print('The index is ', index, 'Length of Index', len(index))

    # Here we assume to use 10-fold Cross-validation, i.e., K = 10
    # Approximately 60% Training set, 20% Validation set, 20% Testing set
    num_test_ref = int(len(index) * 0.2)
    num_val_ref = int(len(index) * 0.2)
    num_train_ref = len(index) - num_test_ref - num_val_ref

    # Assume k = 1 : 10 for 10-fold Cross-validation
    threshold = int(len(index) / num_test_ref)

    if k < threshold:
        testindex = index[(k - 1) * num_test_ref: k * num_test_ref]
        valindex = index[k * num_val_ref: (k + 1) * num_val_ref]

    elif k == threshold:
        testindex = index[(k - 1) * num_test_ref: k * num_test_ref]
        # Check if the index num of validation set is less than num_val_ref
        valindex = index[k * num_val_ref: (k + 1) * num_val_ref]
        if len(valindex) < num_val_ref:
            valindex = valindex.tolist()
            for i in range(0, num_val_ref - len(valindex)):
                valindex.append(index[i])

    elif k == threshold + 1:
        testindex = index[k * num_test_ref: (k + 1) * num_test_ref]
        if len(testindex) < num_test_ref:
            testindex = testindex.tolist()
            for i in range(0, num_test_ref - len(testindex)):
                testindex.append(index[i])

        k -= threshold
        valindex = index[(k + 2) * num_val_ref: (k + 3) * num_val_ref]

    else:
        k -= threshold
        testindex = index[k * num_test_ref: (k + 1) * num_test_ref]
        if len(testindex) < num_test_ref:
            testindex = testindex.tolist()
            for i in range(0, num_test_ref - len(testindex)):
                testindex.append(index[i + num_test_ref])

        valindex = index[(k + 2) * num_val_ref: (k + 3) * num_val_ref]
        if len(valindex) < num_val_ref:
            valindex = valindex.tolist()
            for i in range(0, num_val_ref - len(valindex)):
                valindex.append(index[i])

    return valindex, testindex

def default_loader(path, channel=3):
    """
    :param path: image path
    :param channel: # image channel
    :return: image
    """
    if channel == 1:
        return Image.open(path).convert('L')
    else:
        assert (channel == 3)
        return Image.open(path).convert('RGB')


"""
MongoDB Interaction - A simple example for future developments
Fabio Bove | fabio.bove.dr@gmail.com
"""

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

# Imports
from pymongo import MongoClient

class MongoUtils:
    def __init__(self, auth_param: str, collection_name: str, database_name: str, data: dict) -> None:
        self.mongo_client       = None
        self.last_op_status     = None
        self.database           = None
        self.collection         = None
        self.database_list      = None
        self.collections_list   = None
        self.auth_param         = auth_param
        self.collection_name    = collection_name
        self.database_name      = database_name
        self.data               = data

    def get_last_op_status(self) -> str:
        """
        get_last_op_status, this method returns a string containing the status of the last operation made by this class

        param: None
        return: last_op_status: A string containing the status of the last operation made by this class
        """
        return self.last_op_status

    def connect_to_cluster(self) -> None:
        """
            connect_to_cluster, this method allow to instantiate a new cluster Connection using the pymongo lib

            pram: None
            return: None
        """
        try:
            self.mongo_client = MongoClient(self.auth_param)
            self.last_op_status = "Successfully connected to Mongo Cluster"
        except Exception as e:
            self.last_op_status = f"Something went wrong during cluster connection: \n {e}"
            self.mongo_client = None

    def init_dabase(self, database_name:str) -> None:
        """
            init_dabase method, creates (if don't exists yet) a new database with name <database_name>

            param: database_name: A string with the name of the new database
            return: Nothing
        """
        try: # Get the list of databases for the current cluster
            self.database_list = self.mongo_client.list_database_names()
            self.last_op_status = f"Got the list of active databases: \n {self.database_list}"
        except Exception as e:
            self.last_op_status = f"Can't get the list of databases: \n {e}"
            self.database_list = None

        try:
            if self.database_list is not None and database_name in self.database_list:
                self.last_op_status = f"Database {database_name} already exists."
                self.database = self.mongo_client.get_database(database_name)
            else:
                self.database = self.mongo_client[database_name]
                self.last_op_status = f"Database <{database_name}> created successfully."
        except Exception as e:
            self.last_op_status = f"Something went wrong during database creation: \n {e}"
            self.database = None

    def init_collection(self, collection_name:str):
        """
        init_collection method, initialize a collection if doesn't exists already otherwhise returns the existing one

        param: collection_name: The name of the collection
        return: Nothing
        """
        try:
            self.collections_list = self.database.list_collection_names()
        except Exception as e:
            self.last_op_status = f"Can't get the list of collection: \n {e}"
            self.collection = None
            self.collections_list = None
        try:
            if self.collections_list is not None and collection_name in  self.collections_list:
                self.last_op_status = f"Collection already exists."
                self.collection = self.database.get_collection(collection_name)
            else:
                self.collection = self.database[collection_name]
                self.last_op_status = f"Collection <{collection_name}> created successfully."
        except Exception as e:
            self.last_op_status = f"Something went wrong during collection creation: \n {e}"
            self.collection = None

    def init_documents(self, data:dict) -> None:
        """
        init_documents method, inserts the documents into our collection taken from the given data

        param: data: a dict containing all the data to load in the collection
        return: Nothing
        """
        try:
            self.collection.insert_many(data) # [self.collection.insert_one(elem) for elem in data]
            self.last_op_status = f"Documents loaded successfully."
        except Exception as e:
           self.last_op_status = f"Something went wrong during document insertion: \n {e}"

    def clean_collection(self, collection_name: str) -> None:
        """
        clean_collection method, remove all the documents of a collection

        param: collection_name: A string containing the name of the collection.
        return: Nothing
        """
        if collection_name is not None: # Load the desired collection, if collection_name is empty use the last collection connected to the class
            self.init_collection(collection_name)
        if self.collection is not None:
            if self.collection.count_documents({}) > 0:  # Remove the old documents
                self.collection.delete_many({})
                self.last_op_status = f"Removed old files from the collection."

    def init_cluster(self):
        self.connect_to_cluster()
        self.init_dabase(self.database_name)
        self.init_collection(self.collection_name)
        self.init_documents(self.data)


import socket
from _thread import *
import json

def global_logging(type_d, data):
    if type_d == "v":
        print("[*] VERBOSE :" + str(data))
    elif type_d == "i":
        print("[I] INFO :" + str(data))
    elif type_d == 'd':
        print("[D] DEBUG :" + str(data))
    elif type_d == "a":
        print("[A] AERLT :" + str(data))
    elif type_d == "e":
        print("[E] ERROR :" + str(data))
    else:
        print("로깅 예외")

class Menu:

    def __init__(self):
        self.menu = """Welcome, It's Server.\n\n 1. Start up server\n 2. Exit

        """
        self.choice = None

    def show_menu(self):
        print(self.menu)

    def select_menu(self):
        self.choice = input("> ")

    def return_choice(self):
        return self.choice

class Server:
    def __init__(self):
        self.SERVER_IP = '127.0.0.1'
        self.SERVER_PORT = 8820
        self.server_data_buffer_size = 1024
        self.server_socket = None

    def __del__(self):

        # Closing communication
        if self.server_socket is not None:
            self.server_socket.close()

    def start_server(self):
        global_logging("v", "Start up Server")
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        global_logging("v", "BIND IP")
        self.server_socket.bind((self.SERVER_IP, self.SERVER_PORT))
        self.server_socket.listen()
        global_logging("i", "Server State : listening")

    def thread_communication_main(self, client_socket, addr):
        global_logging("i", ("Connected by :" + str(addr[0]) + ":" + str(addr[1])))

        while True:
            try:
                data = client_socket.recv(self.server_data_buffer_size)
                if not data:
                    global_logging("i", ("Disconnected by " + str(addr[0]) + ":" + str(addr[1])))
                    break
                global_logging("i", ("Received from " + str(addr[0]) + ":" + str(addr[1]) + " data:" + data.decode()))

                client_socket.send(data)
            except ConnectionResetError as e:
                global_logging("i", ("Disconnected by " + str(addr[0]) + ":" + str(addr[1])))
                break
        client_socket.close()

    def run_loop(self):
        while True:
            global_logging("v", "Server State: Waiting for client")

            client_socket, addr = self.server_socket.accept()
            start_new_thread(self.thread_communication_main, (client_socket, addr))

    def received_data(self):
        pass

    def parsing_data(self):
        pass

if __name__ == "__main__":
    menu = Menu()
    server = Server()
    ch = None
    while True:
        menu.show_menu()
        menu.select_menu()
        ch = menu.return_choice()
        if ch == "1":
            server.start_server()
            server.run_loop()
        elif ch == "2":
            global_logging("v", "exit program bye!")
            break
        else:
            pass


"""TC:O(n*m),SC:O(m or n)"""

class Solution(object):
    def matrixReshape(self, mat, r, c):
        """
        :type mat: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        result = [[0 for _ in range(c)]for _ in range(r)]
        if (r*c)!=(len(mat)*len(mat[0])):
          return mat
        else:
          for i in range(r*c):
            result[i//c][i%c]=mat[i//len(mat[0])][i%len(mat[0])]
          return result

if __name__== "__main__":
    mat = [[1,2],[3,4]]
    r = 1
    c = 4
    a=Solution()
    ans=a.matrixReshape(mat,r,c)
    print(ans)


from selenium import webdriver
from ordered_set import OrderedSet
import time
import os
import csv

os.system("cls")

f=open("99acres.csv","w",encoding='utf-8')
csv_writer= csv.writer(f)
csv_writer.writerow(['Project', 'specification', 'area','Value'])

driver = webdriver.Chrome('D:/virtualenvs_muthu/selenium_twitter/chromedriver_win32/chromedriver.exe')

os.system("cls")

scroll_list=OrderedSet()

for x in range(1,3):

    driver.get(f"https://www.99acres.com/property-in-hadapsar-pune-ffid-page-{x}")
    try:
        mutiple_properties=driver.find_elements_by_class_name('srpTuple__tupleDetails')
        time.sleep(2)

        for elem in (mutiple_properties):
            scroll_list.add(elem.text)

    except:
        continue

temp=list(scroll_list)

my_actual_list=[]

for x in temp:

    xt=x.split("\n")

    print(xt)

    try:
        if xt!=['']:

            my_actual_list=[xt[2],xt[1],xt[4],xt[3]]

    except:
        temp_i=temp.index(x)

        os.system("cls")
        print("previous:")
        print(temp[temp_i-1])
        print("error:")
        print(xt)

    print(my_actual_list)

    csv_writer.writerow(my_actual_list)
    my_actual_list.clear()

f.close()


from collections import namedtuple

from backend.DBEntry import DBEntry, to_db_obj_name
from backend.Ingredient import Ingredient

class Recipe(DBEntry):
    """A recipe of a dish. Consists of ingredients with optional amount (in optional units)."""
    table_main = "recipes"
    associations = [
        ("user_meals","recipe_id", False),
        ("recipe_contents","recipe_id", True)
    ]

    def __init__(self, name, instructions="", contents=set(), db=None, id=None):
        """Constructor. Returns functional object.

        :param name: Inherits from DBEntry.
        :param instructions: A string, instructios on how to cook the dish.
        :param contents: A set of Content namedtuples - ingredients and their amounts
            that comprise the dish.
        :param db: Inherits from DBEntry.
        :param id: Inherits from DBEntry.
        """
        super().__init__(name=name, db=db, id=id)
        self.instructions = instructions
        self.contents = contents

    @classmethod
    def from_db(cls, db, id=None, name=None):
        """Search db for recipe entry by id or name (in that priority) and return constructed
        object. Returns None if id is not found.
        """
        recipe = super().from_db(db=db, id=id, name=name)

        if not recipe:
            return None
        id = recipe.id

        # Constructing contents set
        needle = (id,)
        db.c.execute(
            'SELECT ingredient_id, amount, units FROM recipe_contents '
            'WHERE recipe_id = ?',
            needle
        )
        rows = db.c.fetchall()
        contents = set()
        for row in rows:
            ingredient = Ingredient.from_db(db, row["ingredient_id"])
            content = Content(ingredient, row["amount"], row["units"])
            contents.add(content)

        recipe.contents = contents
        return recipe

    def new_to_db(self):
        """Write a new recipe entry to the DB. Return id assigned by the DB."""
        table_main = to_db_obj_name(self.table_main)

        # Inserting values to the main table
        recipe = (self.name, self.instructions)
        self.db.c.execute(f'INSERT INTO "{table_main}" (name, instructions) VALUES (?, ?)',
                          recipe)

        # Remembering id assigned by the DB
        new_row_id = (self.db.c.lastrowid,)
        self.db.c.execute(f'SELECT id FROM "{table_main}" WHERE rowid = ?', new_row_id)
        row = self.db.c.fetchone()
        id = row["id"]

        # inserting contents to the associative table
        contents = {(id, c.ingredient.id, c.amount, c.units) for c in self.contents}
        self.db.c.executemany(
            'INSERT INTO recipe_contents (recipe_id, ingredient_id, amount, units) '
            '  VALUES (?, ?, ?, ?)',
            contents
        )

        return id

    def edit_in_db(self):
        """Edit existing DB recipe to match current object state. Return number of
        affected rows.
        """
        table_main = to_db_obj_name(self.table_main)
        rows_affected = 0

        # Updating values to the main table
        recipe = (self.name, self.instructions, self.id)
        self.db.c.execute(f'UPDATE "{table_main}" SET name = ?, instructions = ? WHERE id = ?',
                          recipe)
        rows_affected += self.db.c.rowcount

        # Constructing sets of the recipe's old and new contents' ingredient ids
        new_ingredient_ids = {c.ingredient.id for c in self.contents}
        needle = (self.id,)
        old_contents = self.db.c.execute('SELECT ingredient_id as id FROM recipe_contents WHERE '
                                         'recipe_id = ?', needle).fetchall()
        old_ingredient_ids = {c["id"] for c in old_contents}

        # Removing contents missing in the new set
        to_remove = {(self.id, i_id) for i_id in old_ingredient_ids - new_ingredient_ids}
        self.db.c.executemany('DELETE FROM recipe_contents WHERE recipe_id = ? AND ingredient_id = ?',
                              to_remove)
        rows_affected += self.db.c.rowcount

        # Adding contents missing in the old set
        new_contents = {c for c in self.contents
                        if c.ingredient.id in new_ingredient_ids - old_ingredient_ids}
        to_add = {(self.id, c.ingredient.id, c.amount, c.units) for c in new_contents}
        self.db.c.executemany(
            'INSERT INTO recipe_contents (recipe_id, ingredient_id, amount, units) '
            '  VALUES (?, ?, ?, ?)',
            to_add
        )
        rows_affected += self.db.c.rowcount

        # Updating contents present in both the old and the new sets
        updated_contents = self.contents - new_contents
        to_update = {(c.amount, c.units, self.id, c.ingredient.id) for c in updated_contents}
        self.db.c.executemany(
            'UPDATE recipe_contents SET amount = ?, units = ? '
            '  WHERE recipe_id = ? AND ingredient_id = ?',
            to_update
        )

        return rows_affected

    @classmethod
    def get_summary(cls, db, name_sort=False):
        """"Return summary table for Recipe objects in DB as dictionary list.
        id: recipe db_id.
        name: recipe name.
        instructions: instructions on how to prepare the dish.
        contents: list of contents (ingredient name, amount, units).
        dependents: number of other class entries referencing this id as a foreign key.

        param name_sort: A boolean. If True, summary will be recursively sorted by
            object name ascending.
        """
        summary = []

        # Get main table data
        db.c.execute('SELECT id, name, instructions '
                     'FROM recipes '
                     'ORDER BY id ASC'
        )
        for db_row in db.c.fetchall():
            row = {x: y for x, y in zip(db_row.keys(), db_row)}
            summary.append(row)

        # Get content lists
        db.c.execute(
            'SELECT recipe_contents.recipe_id, ingredients.name as ingredient, '
            '  recipe_contents.amount, recipe_contents.units '
            'FROM recipe_contents '
            'LEFT JOIN ingredients ON recipe_contents.ingredient_id = ingredients.id '
            'ORDER BY recipe_id ASC'
        )
        db_rows = db.c.fetchall()
        if db_rows:
            it_summary = iter(summary)
            s_row = next(it_summary)
            for db_row in db_rows:
                while not db_row["recipe_id"] == s_row["id"]:
                    # Ensure at least an empty 'cell' exists for this recipe before moving to next
                    try:
                        s_row["contents"]
                    except KeyError:
                        s_row["contents"] = []
                    s_row = next(it_summary)

                content = {
                    "ingredient": db_row["ingredient"],
                    "amount"    : db_row["amount"],
                    "units"     : db_row["units"],
                }
                try:
                    s_row["contents"].append(content)
                except KeyError:
                    s_row["contents"] = [content]

            # Fill remaining rows with empty content lists
            finished = False
            while not finished:
                try:
                    s_row = next(it_summary)
                    s_row["contents"] = []
                except StopIteration:
                    finished = True

        # Get dependents
        db.c.execute(
            'SELECT recipe_id, COUNT(user_id) as dependents FROM user_meals '
            'GROUP BY recipe_id '
            'ORDER BY recipe_id ASC'
        )
        db_rows = db.c.fetchall()
        if db_rows:
            it_summary = iter(summary)
            s_row = next(it_summary)
            for db_row in db_rows:
                while not db_row["recipe_id"] == s_row["id"]:
                    # Set dependents = 0 for ingredients that don't exist in recipe_contents table
                    try:
                        s_row["dependents"]
                    except KeyError:
                        s_row["dependents"] = 0

                    s_row = next(it_summary)

                s_row["dependents"] = db_row["dependents"]

            # Fill remaining rows with dependents = 0
            finished = False
            while not finished:
                try:
                    s_row = next(it_summary)
                    s_row["dependents"] = 0
                except StopIteration:
                    finished = True

        if name_sort:
            summary.sort(key=lambda x: x["name"].lower())
            for row in summary:
                try:
                    row["contents"].sort(key=lambda x: x["ingredient"].lower())
                except KeyError:
                    pass

        return summary

    def toJSONifiable(self):
        dct = super().toJSONifiable()
        contents_list = [item._asdict() for item in self.contents]
        dct["contents"] = contents_list
        return dct

# constructor validation from kindall"s answer at
# https://stackoverflow.com/a/42146452
ContentTuple = namedtuple("ContentTuple", "ingredient amount units")
class Content(ContentTuple):
    """Represents quantity or amount of a specific ingredient in a dish"""
    __slots__ = ()
    def __new__(cls, ingredient, amount, units=None):
        try:
            if not amount >= 0:
                raise ValueError("amount must be a positive number")
        except TypeError:
            raise RuntimeError("amount must be a positive number")

        return ContentTuple.__new__(cls, ingredient, amount, units)

    def _replace(self, **kwargs):
        try:
            if not kwargs["amount"] >= 0:
                raise ValueError("amount must be a positive number")
        except ValueError:
            raise RuntimeError("amount must be a positive number")
        except KeyError:
            pass

        return super()._replace(**kwargs)

    def toJSONifiable(self):
        return self._asdict()


def plot_sine_1D(amp,wavelength,phase):
    x = np.arange(-500, 501, 1)
    y = np.sin((2 * np.pi * x / wavelength)+phase)
    plt.plot(x, y)
    plt.show()
plot_sine_1D(1,300,0)

def plot_sine_2D(amp,wavelength,phase,angle):
    x = np.arange(-500, 501, 1)
    X, Y = np.meshgrid(x, x)
    wavelength = 100
    sine_2D = np.sin(
        2*np.pi*(X*np.cos(angle) + Y*np.sin(angle)) / wavelength
    )
    plt.set_cmap("gray")
    plt.imshow(sine_2D)
plot_sine_2D(1,200,0,np.pi)

def compute_fft(f):
    ft = np.fft.fft2(f)
    ft = np.fft.fftshift(ft)
    return ft

sin = plot_sine_2D(1,200,0,np.pi,False)
ft = compute_fft(sin)
plt.xlim([480,520])
plt.ylim([520,480])
plt.imshow(abs(ft))

sin = plot_sine_2D(1,200,0,np.pi/6,False)
ft = compute_fft(sin)
plt.xlim([480,520])
plt.ylim([520,480])
plt.imshow(abs(ft))

f,ax = plt.subplots(1,2,figsize=(15,20))
ax = ax.flatten()
im = cv2.imread('/kaggle/input/randomimages/pic2.jpeg',-1)
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ax[0].imshow(im,cmap='gray')
ax[1].imshow(20*np.log(abs(compute_fft(im))),cmap='gray')

# Plotting image and its blurred version
f,ax = plt.subplots(1,2,figsize=(15,20))
ax = ax.flatten()
im = cv2.imread('../input/randomimages/pic1.jpeg',-1)
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_blur = cv2.GaussianBlur(im,(7,7), 5, 5)
ax[0].imshow(im,cmap='gray')
ax[1].imshow(im_blur,cmap='gray')

def gaussian_filter(kernel_size,img,sigma=1, muu=0):
    x, y = np.meshgrid(np.linspace(-1, 1, kernel_size),
                       np.linspace(-1, 1, kernel_size))
    dst = np.sqrt(x**2+y**2)
    normal = 1/(((2*np.pi)**0.5)*sigma)
    gauss = np.exp(-((dst-muu)**2 / (2.0 * sigma**2))) * normal
    gauss = np.pad(gauss, [(0, img.shape[0] - gauss.shape[0]), (0, img.shape[1] - gauss.shape[1])], 'constant')
    return gauss

def fft_deblur(img,kernel_size,kernel_sigma=5,factor='wiener',const=0.002):
    gauss = gaussian_filter(kernel_size,img,kernel_sigma)
    img_fft = np.fft.fft2(img)
    gauss_fft = np.fft.fft2(gauss)
    weiner_factor = 1 / (1+(const/np.abs(gauss_fft)**2))
    if factor!='wiener':
        weiner_factor = factor
    recon = img_fft/gauss_fft
    recon*=weiner_factor
    recon = np.abs(np.fft.ifft2(recon))
    return recon

recon = fft_deblur(im_blur,7,5,factor=1)
plt.subplots(figsize=(10,8))
plt.imshow(recon,cmap='gray')

noise = np.random.rand(100,100)
noise_fft = np.fft.fft2(noise)
noise_fft = np.fft.fftshift(noise_fft)
f,ax = plt.subplots(1,2,figsize=(15,20))
ax = ax.flatten()
ax[0].imshow(noise,cmap='gray')
ax[0].set_title('Original Image')
ax[1].imshow(20*np.log(abs(compute_fft(noise_fft))),cmap='gray')
ax[1].set_title('Fourier Transform')

gauss = gaussian_filter(7,im,5)
gauss_fft = np.fft.fft2(gauss)
gauss_fft = np.fft.fftshift(gauss_fft)
f,ax = plt.subplots(1,2,figsize=(15,20))
ax = ax.flatten()
ax[0].imshow(gauss,cmap='gray')
ax[0].set_title('Original Image')
ax[1].imshow(np.abs(gauss_fft),cmap='gray')
ax[1].set_title('Fourier Transform')

f,ax = plt.subplots(1,2,figsize=(15,20))
recon = fft_deblur(im_blur,7,5,factor='wiener')
ax[0].imshow(im_blur,cmap='gray')
ax[1].imshow(recon)
ax[0].set_title('Blurry Image')
ax[1].set_title('Image reconstruction')
plt.show()

f,ax = plt.subplots(1,2,figsize=(15,20))
recon = fft_deblur(im_blur,7,5,factor='wiener',const=0.5)
ax[0].imshow(im_blur,cmap='gray')
ax[1].imshow(recon)
ax[0].set_title('Blurry Image')
ax[1].set_title('Image reconstruction')
plt.show()


from os import path

from .dictbuilder import DictBuilder

# Dictionary is an in-memory representation of the dictionary of terms for a given corpus
# Internally, we represent the volume as a set, since that gives us O(1) access, which makes
# constructing an index much faster.
class Dictionary:
    # key = dictionary path, value = set of terms
    dictionary = {}

    class __Dictionary:
        def __init__(self, ctx):
            self.ctx = ctx
            self.terms = set()
            if not path.exists(ctx.dict_path()):
                DictBuilder(ctx).build()
            with open(self.ctx.dict_path(), "r") as terms:
                for term in terms:
                    self.terms.add(term.rstrip())  # remove trailing newline

        def add(self, term):
            self.terms.add(term)

        def contains(self, term):
            return term in self.terms

    def __init__(self, ctx):
        self.ctx = ctx
        if ctx.dict_path() not in Dictionary.dictionary:
            Dictionary.dictionary[ctx.dict_path()] = Dictionary.__Dictionary(ctx)


import os
from glob import glob
from pathlib import Path

SOURCE_DIRECTORY = "CSVdatabases"
TARGET_DIRECTORY = "cleaned_databases"
CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
DATABASES_FOLDER = f"{CURRENT_DIRECTORY}/{SOURCE_DIRECTORY}"
CLEANED_FOLDER = f"{CURRENT_DIRECTORY}/{TARGET_DIRECTORY}"

def clean_file_contents(contents: list[str]):
    return contents[4:-2]

def clean_all_databases():
    database_files = glob(f"{DATABASES_FOLDER}/**/*.csv")
    for raw_data_file in database_files:
        target_directory = os.path.dirname(raw_data_file).replace(
            SOURCE_DIRECTORY, TARGET_DIRECTORY)
        target_file = raw_data_file.replace(SOURCE_DIRECTORY, TARGET_DIRECTORY)
        if not os.path.exists(target_directory):
            os.makedirs(target_directory)
        with open(raw_data_file, 'r') as source:
            with open(target_file, 'w') as destination:
                destination.writelines(clean_file_contents(source.readlines()))

def remove_empty_databases():
    cleaned_data_files = glob(f"{CLEANED_FOLDER}/**/*.csv")
    for cleaned_data_file in cleaned_data_files:
        delete = False
        with open(cleaned_data_file, 'r') as f:
            if len(f.readlines()) < 2:
                delete = True
        if delete:
            Path(cleaned_data_file).unlink()

if __name__ == '__main__':
    clean_all_databases()
    remove_empty_databases()


import torch
from experiment import Experiment, AutoDateSet, train, get_args
from model.Tree import Tree

from dataset.criteo import CriteoDataset

def get_model(args):
    model = Tree(args)
    return model

def get_dataset(args):
    dataset = CriteoDataset(dataset_path=args.dataset_paths[0])
    train_length = int(len(dataset) * 0.9)
    valid_length = len(dataset) - train_length
    train_dataset, valid_dataset = torch.utils.data.random_split(dataset, (train_length, valid_length))
    test_dataset = CriteoDataset(dataset_path=args.dataset_paths[1])
    return [train_dataset, valid_dataset, test_dataset], dataset.field_dims

def main():
    args = get_args()
    args.hidden= [1024,512,256,128,64]
    args.embed_dim = 16
    args.activation='relu'
    args.label='y'
    args.num_class = 2
    args.dataset_paths= ['data/criteo/train.txt', 'data/criteo/test.txt']
    datasets, field_dims= get_dataset(args)
    print(field_dims)
    args.field_dims = field_dims
    model = get_model(args)

    experiment = Experiment(model=model, args=args)
    data = AutoDateSet(datasets, args.batch_size, args.batch_size, args.num_workers, args.pin_memory)
    train(args, experiment, data)

if __name__ == "__main__":
    main()


# Ten program dzieli jedną liczbę przez drugą.

def main():
    # Pobranie dwóch liczb.
    num1 = int(input('Podaj liczbę : '))
    num2 = int(input('Podaj następną liczbę: '))

    # Jeżeli wartość num2 jest inna niż 0, następuje
    # podzielenie num1 przez num2 i wyświetlenie wyniku.
    if num2 != 0:
        result = num1 / num2
        print(num1, 'dzielone przez', num2, 'daje', result)
    else:
        print('Nie można dzielić przez zero.')

# Wywołanie funkcji main().
main()


from __future__ import annotations
from .base import BaseDAO
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
    from dto import PlayerDTO

class PlayerDAO(BaseDAO):
    def create(self, data: PlayerDTO) -> None:
        self._db_gateway.cursor.execute("INSERT INTO profiles (phone, username, description, age, height, weight) "
                                        "VALUES (?, ?, ?, ?, ?, ?);",
                                        (data.profile.phone, data.profile.username, data.profile.description,
                                         data.profile.age, data.profile.height, data.profile.weight))
        profile_id = self._db_gateway.cursor.lastrowid
        self._db_gateway.cursor.execute("INSERT INTO players (email, name, surname, country_id, sport_type_id, "
                                        "team_id, profile_id) VALUES (?, ?, ?, ?, ?, ?, ?);",
                                        (data.email, data.name, data.surname, data.country_id, data.sport_type_id,
                                         data.team_id, profile_id))
        self._db_gateway.connection.commit()

    def get_ids_list(self) -> list[int]:
        result = self._db_gateway.cursor.execute("SELECT id FROM players;")
        return result.fetchall()

    def get_list(self) -> list[tuple]:
        result = self._db_gateway.cursor.execute("SELECT players.id, players.name, players.surname, profiles.age, countries.name, teams.name "
                                                 "FROM players JOIN profiles ON players.profile_id = profiles.id JOIN countries ON "
                                                 "players.country_id = countries.id JOIN teams ON players.team_id = teams.id;")
        return result.fetchall()