import cv2
import mediapipe as mp
import math
import numpy as np
import inspect, re
from trajectoryDataset import trajectoryData
from traj_model import simpleLSTM
from correction_func import *
from tensorflow.keras.models import Model
from image_based_recognition.img_predict import *

class Gesture(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.mp_drawing = mp.solutions.drawing_utils
        self.mp_hands = mp.solutions.hands
        self.hands = self.mp_hands.Hands(
            static_image_mode=False,
            max_num_hands=1,
            min_detection_confidence=0.75,
            min_tracking_confidence=0.75)

        self.video = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')
        self.video.set(cv2.CAP_PROP_FPS, 60)
        self.video.set(cv2.CAP_PROP_FRAME_WIDTH, 1440)
        self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 800)

        # variable
        self.gesture_str = 'None'       # Gesture recognition result
        self.rectangle_on = 0           # control rectangle show up if > 40 show rectangle
        self.rectangle_off = 0          # control rectangle show off if > 80 hide rectangle
        self.clear = 0                  # clear all writing
        self.save = 0                   # save all writing
        self.center = []                # handwriting center
        self.eraser = []                # eraser center

        self.end = 0  # end writing
        self.rec = 0  # start recognition
        self.text = 0  # show recognition result

        self.mode = 0                   # mode choose. 0 writing 1 select from corrected options
        self.predict = ''
        self.fst_rst = ''
        self.scd_rst = ''
        self.final = ''

        # self.breakpoint = []
        # self.breakdot = (1,1)

        self.trajectory = []            # trajectory recognition
        self.trajectory1 = []
        self.trajectory2 = []
        self.trajectory3 = []
        self.trajectory4 = []
        self.trajectory5 = []

        self.trajDataset =  trajectoryData(digit=False)
        model_path = './traj_model_checkpoints'

        self.trajModel = simpleLSTM(62, input_shape=(self.trajDataset.len_95,2))
        self.trajModel.load_weights(os.path.join(model_path, 'model_diff.h5'))

        ckpt = torch.load(f'./image_based_recognition/ckpt/CNN_model_0.pkl', map_location=torch.device('cuda'))
        self.imageModel = SimpleCNN(62)
        self.imageModel.load_state_dict(ckpt)

    def __del__(self):
        self.video.release()

    def vector_2d_angle(self, v1, v2):
        '''
            求解二维向量的角度
        '''
        v1_x = v1[0]
        v1_y = v1[1]
        v2_x = v2[0]
        v2_y = v2[1]
        try:
            angle_ = math.degrees(math.acos(
                (v1_x * v2_x + v1_y * v2_y) / (((v1_x ** 2 + v1_y ** 2) ** 0.5) * ((v2_x ** 2 + v2_y ** 2) ** 0.5))))
        except:
            angle_ = 65535.
        if angle_ > 180.:
            angle_ = 65535.
        return angle_

    def hand_angle(self, hand_):
        '''
            获取对应手相关向量的二维角度,根据角度确定手势
        '''
        angle_list = []
        # ---------------------------- thumb 大拇指角度
        angle_ = self.vector_2d_angle(
            ((int(hand_[0][0]) - int(hand_[2][0])), (int(hand_[0][1]) - int(hand_[2][1]))),
            ((int(hand_[3][0]) - int(hand_[4][0])), (int(hand_[3][1]) - int(hand_[4][1])))
        )
        angle_list.append(angle_)
        # ---------------------------- index 食指角度
        angle_ = self.vector_2d_angle(
            ((int(hand_[0][0]) - int(hand_[6][0])), (int(hand_[0][1]) - int(hand_[6][1]))),
            ((int(hand_[7][0]) - int(hand_[8][0])), (int(hand_[7][1]) - int(hand_[8][1])))
        )
        angle_list.append(angle_)
        # ---------------------------- middle 中指角度
        angle_ = self.vector_2d_angle(
            ((int(hand_[0][0]) - int(hand_[10][0])), (int(hand_[0][1]) - int(hand_[10][1]))),
            ((int(hand_[11][0]) - int(hand_[12][0])), (int(hand_[11][1]) - int(hand_[12][1])))
        )
        angle_list.append(angle_)
        # ---------------------------- ring 无名指角度
        angle_ = self.vector_2d_angle(
            ((int(hand_[0][0]) - int(hand_[14][0])), (int(hand_[0][1]) - int(hand_[14][1]))),
            ((int(hand_[15][0]) - int(hand_[16][0])), (int(hand_[15][1]) - int(hand_[16][1])))
        )
        angle_list.append(angle_)
        # ---------------------------- pink 小拇指角度
        angle_ = self.vector_2d_angle(
            ((int(hand_[0][0]) - int(hand_[18][0])), (int(hand_[0][1]) - int(hand_[18][1]))),
            ((int(hand_[19][0]) - int(hand_[20][0])), (int(hand_[19][1]) - int(hand_[20][1])))
        )
        angle_list.append(angle_)
        return angle_list

    def h_gesture(self, angle_list):
        '''
            # 二维约束的方法定义手势
            # fist five gun love one six three thumbup yeah
        '''
        thr_angle = 65.
        thr_angle_thumb = 53.
        thr_angle_s = 49.
        gesture_str = None
        if 65535. not in angle_list:
            if (angle_list[0] > thr_angle_s) and (angle_list[1] < thr_angle_s) and (angle_list[2] > thr_angle) and (
                    angle_list[3] > thr_angle) and (angle_list[4] > thr_angle):
                gesture_str = "One"
            elif (angle_list[0] > thr_angle_thumb) and (angle_list[1] < thr_angle_s) and (
                    angle_list[2] < thr_angle_s) and (angle_list[3] > thr_angle) and (angle_list[4] > thr_angle):
                gesture_str = "Two"
            elif (angle_list[0] > thr_angle_thumb) and (angle_list[1] < thr_angle_s) and (
                    angle_list[2] < thr_angle_s) and (angle_list[3] < thr_angle_s) and (angle_list[4] > thr_angle):
                gesture_str = "Three"
            elif (angle_list[0] > thr_angle_thumb) and (angle_list[1] > thr_angle_s) and (
                    angle_list[2] < thr_angle_s) and (angle_list[3] < thr_angle_s) and (angle_list[4] < thr_angle):
                gesture_str = "Three"
            elif (angle_list[0] > thr_angle_thumb) and (angle_list[1] < thr_angle_s) and (
                    angle_list[2] < thr_angle_s) and (angle_list[3] < thr_angle_s) and (angle_list[4] < thr_angle):
                gesture_str = "Four"
            elif (angle_list[0] < thr_angle_s) and (angle_list[1] < thr_angle_s) and (angle_list[2] < thr_angle_s) and (
                    angle_list[3] < thr_angle_s) and (angle_list[4] < thr_angle_s):
                gesture_str = "Five"
            elif (angle_list[0] < thr_angle_s) and (angle_list[1] > thr_angle) and (angle_list[2] > thr_angle) and (
                    angle_list[3] > thr_angle) and (angle_list[4] > thr_angle):
                gesture_str = "Thumb up"
            elif (angle_list[0] < thr_angle_s) and (angle_list[1] < thr_angle_s) and (angle_list[2] > thr_angle) and (
                    angle_list[3] > thr_angle) and (angle_list[4] > thr_angle):
                gesture_str = "L"
        return gesture_str

    def gesture_logic(self):
        if self.gesture_str == 'One':
            return 'One -- Write'
        elif self.gesture_str == 'Two':
            return 'Two -- Eraser'
        elif self.gesture_str == 'Three':
            return 'Three -- Clear'
        elif self.gesture_str == 'Four':
            return 'Four -- Start Writing'
        elif self.gesture_str == 'Five':
            return 'Five -- End Writing'
        elif self.gesture_str == 'Thumb up':
            return 'Thumb up -- Save'

    def rectangle_logic(self,frame):
        if self.gesture_str == 'Four':
            self.rectangle_on += 1

        if self.rectangle_on > 40:
            self.end = 1
            self.rectangle_show(frame)
            self.rec = 1
            self.text = 0
            self.mode = 0
            self.final = ''

        if self.gesture_str == 'Five':
            self.rectangle_off += 1

        if self.rectangle_off > 80:
            self.rectangle_on = 0
            self.rectangle_off = 0
            self.end = 0

            if self.rec == 1:
                # recognition result
                if len(self.trajectory) == 0:
                    print('Do not have any trajectory to predict')
                    return
                self.predict, self.fst_rst, self.scd_rst = self.predict_correct(self.trajectory)
                self.text = 1
                self.rec = 0
                self.trajectory = []
                self.final = ''

        if self.text == 1:
            self.mode = 1
            self.recognition(frame)

    def rectangle_show(self,frame):
        # list = [[40, 150, 200, 500, (0, 255, 255)],
        #         [290, 150, 200, 500, (0, 255, 255)],
        #         [540, 150, 200, 500, (0, 255, 255)],
        #         [790, 150, 200, 500, (0, 255, 255)],
        #         [1040, 150, 200, 500, (0, 255, 255)]]
        # for x, y, w, h, color in list:
        #     cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)

        y = 150
        w = 250
        h = 400
        color = (0,255,255)
        x = [40,340,640,940]
        for x in x:
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)

    def writing_show(self,frame):
        for i in range(len(self.center)):
            if self.center[i]:
                last = self.center[i]
                break
        for x,y in self.center:
            # if (150<y<650) and ((40<x<240) or (290<x<490) or (540<x<740) or (790<x<990) or (1040<x<1240)):
            if (150 < y < 550) and ((40 < x < 290) or (340 < x < 590) or (640 < x < 890) or (940 < x < 1190)):
                color = (255,0,0)
            else:
                color = (255,255,0)

            # if (x,y) in self.breakpoint:
            #     color = (0,0,255)

            cv2.circle(frame, (x, y), 10, color, -1)

            # if last not in self.breakpoint:
            #     cv2.line(frame,(x,y),last,color,20)
            #     last = (x,y)
            # else:
            #     last = (x,y)

    def Trajectory_get(self):
        for x, y in self.center:
            y = y - 150
            if 0 < y < 400:
                # if 40 < x < 240:
                #     x = x - 40
                #     self.trajectory1.append((x, y))
                # elif 290 < x < 490:
                #     x = x - 290
                #     self.trajectory2.append((x, y))
                # elif 540 < x < 740:
                #     x = x - 540
                #     self.trajectory3.append((x, y))
                # elif 790 < x < 990:
                #     x = x - 790
                #     self.trajectory4.append((x, y))
                # elif 1040 < x < 1240:
                #     x = x - 1040
                #     self.trajectory5.append((x, y))
                if 40 < x < 290:
                    x = x - 40
                    self.trajectory1.append((x, y))
                elif 340 < x < 590:
                    x = x - 340
                    self.trajectory2.append((x, y))
                elif 640 < x < 890:
                    x = x - 640
                    self.trajectory3.append((x, y))
                elif 940 < x < 1190:
                    x = x - 940
                    self.trajectory4.append((x, y))

        # trajectory = [self.trajectory1, self.trajectory2, self.trajectory3, self.trajectory4, self.trajectory5]
        trajectory = [self.trajectory1, self.trajectory2, self.trajectory3, self.trajectory4]

        for traj in trajectory:
            if len(traj) != 0:
                self.trajectory.append(traj)

        self.trajectory1 = []
        self.trajectory2 = []
        self.trajectory3 = []
        self.trajectory4 = []
        # self.trajectory5 = []

        self.Trajectory_save(self.trajectory)

    def Trajectory_save(self,trajectory):
        # addr_list = ['trajectory1','trajectory2','trajectory3','trajectory4','trajectory5']
        # addr_list = ['trajectory1','trajectory2','trajectory3','trajectory4']
        # i = 0
        # for traj in trajectory:
        #     traj_addr = 'C:/Users/Ying/Downloads/' + addr_list[i] + '.txt'
        #     with open(traj_addr, mode='w') as f:
        #         for k, v in traj:
        #             dict_2_lst = []
        #             dict_2_lst.append("(" + str(k) + "," + str(v) + ")")
        #             f.write(','.join(dict_2_lst))
        #             f.write('\n')
        #
        #     # recognition = np.zeros((500, 200, 3), np.uint8)
        #     recognition = np.zeros((500, 250, 3), np.uint8)
        #     recognition.fill(255)
        #
        #     for x, y in traj:
        #         cv2.circle(recognition, (x, y), 10, (255, 0, 0), -1)
        #
        #     recg_addr = 'C:/Users/Ying/Downloads/' + addr_list[i] + '.jpg'
        #     cv2.imwrite(recg_addr, recognition)
        #
        #     i = i+1
        np.save("trajectory.npy", self.trajectory)

    def recognition(self,frame):
        predict = 'Recognition result:  ' + self.predict
        first = '1  ' + self.scd_rst[0][0]
        second = '2  ' + self.scd_rst[1][0]
        third = '3  ' + self.scd_rst[2][0]
        cv2.putText(frame, predict, (100, 200), 0, 2, (0, 255, 0), 3)
        if self.mode == 1:
            cv2.putText(frame, predict, (100,200), 0, 2, (0, 255, 0), 3)
            cv2.putText(frame, 'You may want to write:', (100, 300), 0, 2, (255, 255, 0), 3)
            cv2.putText(frame, first, (100, 400), 0, 2, (255, 255, 0), 3)
            cv2.putText(frame, second, (100, 500), 0, 2, (255, 255, 0), 3)
            cv2.putText(frame, third, (100, 600), 0, 2, (255, 255, 0), 3)

            if self.gesture_str == 'One':
                self.final = self.scd_rst[0][0]
            if self.gesture_str == 'Two':
                self.final = self.scd_rst[1][0]
            if self.gesture_str == 'Three':
                self.final = self.scd_rst[2][0]
            if self.gesture_str == 'Thumb up':
                self.final = self.predict

            final = 'Final result:  ' + self.final
            cv2.putText(frame, final, (100, 700), 0, 2, (0, 255, 0), 3)

    def correction(self, frame, predict):
        pass

    def get_frame(self):
        success, image = self.video.read()

        frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        frame = cv2.flip(frame, 1)
        results = self.hands.process(frame)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.

        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                self.mp_drawing.draw_landmarks(frame, hand_landmarks, self.mp_hands.HAND_CONNECTIONS)
                hand_local = []
                for i in range(21):
                    x = hand_landmarks.landmark[i].x * frame.shape[1]
                    y = hand_landmarks.landmark[i].y * frame.shape[0]
                    hand_local.append((x, y))
                if hand_local:
                    # Index fingertip

                    #轨迹绘制
                    # print(hand_local[8][0])
                    center_x = math.floor(hand_local[8][0])
                    center_y = math.floor(hand_local[8][1])

                    eraser_x = math.floor((hand_local[8][0]+hand_local[12][0])/2)
                    eraser_y = math.floor((hand_local[8][1]+hand_local[12][1])/2)

                    angle_list = self.hand_angle(hand_local)
                    self.gesture_str = self.h_gesture(angle_list)

                    gesture_text = self.gesture_logic()

                    if self.end != 0:
                        cv2.putText(frame,gesture_text,(100,100),0,2,(0,0,255),3)

                        if (self.mode == 0) and self.gesture_str == 'One':
                            self.clear = 0
                            self.save = 0
                            self.center.append((center_x,center_y))
                        #     self.breakdot = (center_x,center_y)
                        # else:
                        #     if self.breakdot not in self.breakpoint:
                        #         self.breakpoint.append(self.breakdot)

                        if self.mode == 0 and self.gesture_str == 'Two':
                            self.eraser.append((eraser_x,eraser_y))
                            length = 20
                            cv2.rectangle(frame, (eraser_x-length, eraser_y-length), (eraser_x+length, eraser_y+length), (0,0,255), -1)

                            for i in range(eraser_x-length,eraser_x+length):
                                for j in range(eraser_y-length,eraser_y+length):
                                    if (i,j) in self.center:
                                        self.center.remove((i,j))

                    else:
                        warning_text = 'Use Gesture 4 to start writing'
                        cv2.putText(frame, warning_text, (100, 100), 0, 2, (0, 0, 255), 3)

        # show handwriting
        self.writing_show(frame)

        # show 5 rectangle
        self.rectangle_logic(frame)

        # Clear all handwriting
        if self.mode == 0 and self.gesture_str == 'Three':
            self.clear += 1
        if self.clear > 80:
            memory = self.center

            self.center = []
            self.eraser = []
            self.clear = 0

        if self.mode ==0 and self.gesture_str == 'Thumb up':
            self.save += 1
        if self.save > 80:
            self.Trajectory_get()
            self.center = []
            self.eraser = []
            self.save = 0

        ret, jpeg = cv2.imencode('.jpg', frame)

        return jpeg.tobytes(), self.gesture_str

    def predict_correct(self,traj_list,target_str='air',lambda_a=1,lambda_b=1):

        traj_predictions = self.pred_trajatory(traj_list)
        image_predictions = self.pred_image(traj_list)
        image_predictions = np.reshape(image_predictions,(image_predictions.shape[0],image_predictions.shape[-1]))
        image_predictions = max_min_normalization(image_predictions)
        predictions = lambda_a*traj_predictions+lambda_b*image_predictions
        pred = predictions.argmax(axis=-1)

        labels_cate = [str(i) for i in range(10)] + [chr(i) for i in range(65, 91)] + [chr(i) for i in range(97, 123)]
        label2id = dict(zip(labels_cate, [i for i in range(len(labels_cate))]))
        id2label = dict(zip([i for i in range(len(labels_cate))], labels_cate))

        predict_result = ''.join([id2label[i] for i in pred])
        print(predict_result)
        print([i[j] for i, j in zip(predictions, predictions.argmax(axis=-1))])

        true = [label2id[i] for i in target_str]
        print(true)
        print([i[j] for i, j in zip(predictions, true)])

        first_corr_result = correction_result(predictions, lambda_a=20)
        print(first_corr_result)
        best_word = first_corr_result[0][0]
        second_corr_result = word_correction(best_word, predictions)
        print(second_corr_result)

        return predict_result,first_corr_result,second_corr_result

    def pred_trajatory(self,traj_list):
        traj_list = [[list(e)[::-1] for e in f] for f in traj_list]
        print(traj_list)
        feature = [self.trajDataset.preprocess(i, standardization=True) for i in traj_list]
        feature = np.array([self.trajDataset.moving_ave(i, window_size=5) for i in feature])
        feature = np.array(feature)

        dense_layer_model = Model(inputs=self.trajModel.input,outputs=self.trajModel.get_layer('Dense_output').output)

        predictions = dense_layer_model.predict(feature)
        predictions = predictions + abs(np.min(predictions, axis=1, keepdims=True))

        predictions = predictions / np.sum(predictions, axis=1, keepdims=True)
        return predictions

    def pred_image(self,trajList):
        with torch.no_grad():
            self.imageModel.eval()
            # load mapping txt
            # dict_tmp = load_mapping_file('./mappings/emnist-byclass-mapping.txt')

            # load the trajectory-based test sets and model file
            # traj_dir = "../testData"
            # trajList = []
            # for files in os.listdir(traj_dir):
            #     if os.path.splitext(files)[1] == '.txt':
            #         trajList.append(files)
            final_result = []
            # trajList = os.listdir(traj_dir)
            # trajList.sort(key=lambda x: int(x.replace("trajectory", "").split('.')[0]))
            for idx in range(0, len(trajList)):
                # print(os.path.join(traj_dir, trajList[idx]))
                x, y= zip(*trajList[idx])
                t = np.linspace(0.0, 1.0, 25)
                plt.figure(figsize=(1, 1))
                data = gen_bezuer(x, y, t)
                ax = plt.gca()
                ax.invert_yaxis()
                plt.axis('off')
                im = plt.plot(data[0], data[1], 'bo-')
                save_pth = os.path.join('./image_based_recognition/bezier_imgs/', str(idx+1) + '.jpg')
                plt.savefig(save_pth)
                plt.close()
                im = Image.open(save_pth).resize((28, 28))
                im = im.convert('L')

                im_data = np.array(im)
                im_data = 255 - im_data
                im_data = torch.from_numpy(im_data).float()
                im_data = im_data.view(1, 1, 28, 28)
                out = self.imageModel(im_data)
                # print(out)
                # print(type(out))
                _, pred = torch.max(out, 1)
                # 62-dimensional features
                features = out.detach().numpy()
                min = features.min()
                # print(min)
                features -= min
                final_result.append(features)
        return np.array(final_result)
                # print('predict: {}'.format(chr(int(dict_tmp[int(pred)]))))
    #2021-10-24 16:01


#coding=utf-8
class Restaurant(object):
	"""docstring for Restaurant"""
	def __init__(self,restaurant_name,cuisine_type):
		self.restaurant_name=restaurant_name
		self.cuisine_type=cuisine_type

	def describe_restaurant(self):
		print('restaurant_name is '+self.restaurant_name.title())
		print('cuisine_type is '+self.cuisine_type.title())

	def open_restaurant(self):
		print('The restaurant is open')

restaurant=Restaurant("Yao","noddles")

restaurant.describe_restaurant()
restaurant.open_restaurant()

a_restaurant=Restaurant('a','aoddles')
a_restaurant.describe_restaurant()
b_restaurant=Restaurant('b','boddles')
b_restaurant.describe_restaurant()
c_restaurant=Restaurant('c','coddles')
c_restaurant.describe_restaurant()
print(" ")

class User(object):
	"""docstring for User"""
	def __init__(self,first_name,last_name,age,sex,height):
		self.first_name=first_name
		self.last_name=last_name
		self.age=age
		self.sex=sex
		self.height=height

	def describe_user(self):
		print("the user's message is "+
			"\nfirst_name:"+self.first_name.title()+
			"\nlast_name:"+self.last_name.title()+
			"\nage:"+self.age.title()+
			"\nsex:"+self.sex.title()+
			"\nheight:"+self.height.title()
			)
		pass

	def greet_user(self):
		print("hello "+self.first_name.title()+self.last_name.title())
		pass

user1=User("zhang","hang",'25','female','170')
user2=User("zhao","xiang","24","male","180")
user3=User("li","chen","29","male","180")
user1.describe_user()
user2.describe_user()
user3.describe_user()


import copy
import pytest
from efa.efa_common import efa_retrieve_hw_counter_value, get_efa_device_names
from common import ClientServerTest

# This test must be run in serial mode because it checks the hw counter
@pytest.mark.serial
@pytest.mark.functional
def test_efa_device_selection(cmdline_args):

    if cmdline_args.server_id == cmdline_args.client_id:
        pytest.skip("EFA device selection test requires 2 nodes")
        return

    server_device_names = get_efa_device_names(cmdline_args.server_id)
    client_device_names = get_efa_device_names(cmdline_args.client_id)

    server_num_devices = len(server_device_names)
    client_num_devices = len(server_device_names)

    for i in range(max(server_num_devices, client_num_devices)):
        server_device_idx = i % server_num_devices
        client_device_idx = i % client_num_devices

        server_device_name = server_device_names[server_device_idx]
        client_device_name = client_device_names[client_device_idx]

        for suffix in ["rdm", "dgrm"]:
            server_tx_bytes_before_test = efa_retrieve_hw_counter_value(cmdline_args.server_id, "tx_bytes", server_device_name)
            client_tx_bytes_before_test = efa_retrieve_hw_counter_value(cmdline_args.client_id, "tx_bytes", client_device_name)

            prefix_type = "wout_prefix"
            strict_fabtests_mode = True
            if suffix == "rdm":
                command = "fi_rdm_pingpong"
            else:
                prefix_type = "with_prefix"  # efa provider requires prefix mode for dgram provider, hence "-k"
                strict_fabtests_mode = False  # # dgram is unreliable
                command = "fi_dgram_pingpong"

            server_domain_name = server_device_name + "-" + suffix
            client_domain_name = client_device_name + "-" + suffix

            cmdline_args_copy = copy.copy(cmdline_args)
            cmdline_args_copy.additional_server_arguments = "-d " + server_domain_name
            cmdline_args_copy.additional_client_arguments = "-d " + client_domain_name
            cmdline_args_copy.strict_fabtests_mode = strict_fabtests_mode

            test = ClientServerTest(cmdline_args_copy, command, message_size="1000", prefix_type=prefix_type, timeout=300)
            test.run()

            server_tx_bytes_after_test = efa_retrieve_hw_counter_value(cmdline_args.server_id, "tx_bytes", server_device_name)
            client_tx_bytes_after_test = efa_retrieve_hw_counter_value(cmdline_args.client_id, "tx_bytes", client_device_name)

            # Verify EFA traffic
            assert server_tx_bytes_before_test < server_tx_bytes_after_test
            assert client_tx_bytes_before_test < client_tx_bytes_after_test


# swea 1865. 동철이의 일 분배 D4

T = int(input())

def work(idx, p):
    global ans
    if p <= ans: return #가지치기
    if idx >= N:
        ans = p
        return
    for i in range(N):
        if not v[i]:
            v[i]=1
            work(idx+1, p*(lst[idx][i])/100) #확률!!
            v[i]=0

for tc in range(1, T+1):
    N = int(input()) #1<=N<=16
    lst = [list(map(int, input().split())) for _ in range(N)]
    ans = 0
    v = [0]*N
    work(0,100)
    # print(f'#{tc} {round(ans,6)}') #round 하면 뒤에 0까지 나오지가 않음
    print('#{} {:6f}'.format(tc, ans))

동철이의 일 분배.py


class Movie:
    def __init__(self, title="", country="", release_year=0, genre="", description="", rating="", date_added="",
                 cast="", type_movie=""):
        self.title = title
        self.country = country
        self.release_year = release_year
        self.genre = genre
        self.description = description
        self.rating = rating
        self.date_added = date_added
        self.cast = cast
        self.type_movie = type_movie

    def __repr__(self):
        return f"title: {self.title} \
                country: {self.country} \
                release_year: {self.release_year} \
                genre: {self.genre} \
                rating: {self.rating} \
                description: {self.description}"


#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import logging
import argparse
import json

'''
1、参数--metrics 'node_cpu_usage{node="172.27.16.244"}'
2、执行curl -G 'http://172.27.16.194:30350/prometheus/api/v1/query?query=node_cpu_usage\{node="172.27.16.244"\}&timeout=5'
'''

parser = argparse.ArgumentParser(description='请输入对应的参数')
parser.add_argument('--metrics', help='判断能否通过prometheus获取指标', type=str, default='node_cpu_usage{}')
args = parser.parse_args()

LOG_FORMAT = "%(asctime)s    [%(levelname)s]    %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

def check_infrastore_metrics(metrics='node_cpu_usage{}'):
    cmd = "kubectl get nodes -A --no-headers|grep ' Ready'|awk '{print $1}'|head -n1"
    node = os.popen(cmd).read().lstrip().rstrip()
    cmd = "kubectl get svc -A|grep 11130|awk '{print $(NF-1)}'|awk -F ':' '{print $2}'|awk -F '/' '{print $1}'"
    port = os.popen(cmd).read().lstrip().rstrip()
    prom_api = "'" + "http://%s:%s/prometheus/api/v1/query" % (node, port)
    metrics = metrics.replace("{", "\{").replace("}", "\}")
    query = "?query=%s&timeout=5" % metrics + "'"
    url = "curl -G " + prom_api + query
    logging.info(url)
    ret_msg = json.loads(os.popen(url).read())
    logging.info(ret_msg)
    result = ret_msg.get("data").get("result")
    last_msg = "云哨查询数据正常,metrics为: %s" % (metrics)
    if not result:
        msg = "云哨查询数据失败,metrics为: %s" % (metrics)
        logging.error(msg)
        return 1
    logging.info(last_msg)
    return 0

if __name__ == '__main__':
    exit(check_infrastore_metrics(args.metrics))


from PyQt6.QtWidgets import *
from basvurular import Ui_MainWindow

class basvurular_sayfasi(QMainWindow):
    def __init__(self) -> None:
        super().__init__()
        self.basvuru=Ui_MainWindow()
        self.basvuru.setupUi(self)
        self.basvuru.TercihlerEkraniButtonBas.clicked.connect(self.TercihlerSayfasinaGit)
    def TercihlerSayfasinaGit(self):
        from tercihler_sayfasi import tercih_sayfasi
        self.close()
        self.tercih=tercih_sayfasi()
        self.tercih.show()


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import sys, argparse

ON = 255
OFF = 0
vals = [ON, OFF]

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-size", dest="num", required = False)
    parser.add_argument("-mov-file", dest="movfile", required=False)
    parser.add_argument("-v", action='store_true')
    args = parser.parse_args()
    if args.num:
        size = int(args.num)
    else:
        size = 100

    verbose = args.v

    grid = np.random.choice(vals, size*size, p=[0.2, 0.8]).reshape(size, size)
    fig, ax = plt.subplots()
    img = ax.imshow(grid, interpolation='nearest')
    ani = animation.FuncAnimation(fig, step, fargs=(img, grid, size, verbose), frames=1000, interval = 50 )
    if args.movfile:
        ani.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264'])
    plt.show()

def step( frameNum, img, grid, size, v ):
    newGrid = []
    if v and frameNum % 10 == 0:
        print("Up to frameNum = " + str(frameNum))

    for i in range(size):
        newGrid.append( [] )
        for j in range(size):
            total = int( (grid[i, (j + 1)%size] + grid[ i , (j - 1) % size ] + grid[ (i + 1) % size, j] + grid[ (i - 1) % size, j ] + grid[ (i + 1) % size, (j - 1) % size ] + grid[ (i - 1) % size, (j - 1) % size ] + grid[ (i + 1) % size, (j + 1) % size ] + grid[ (i - 1) % size, (j + 1) % size ]) / 255 )
            if( grid[i , j] == ON ):
                if( total < 2 or total > 3 ):
                    newGrid[i].append( OFF )
                else:
                    newGrid[i].append( ON )
            elif total == 3:
                newGrid[i].append( ON )
            else:
                newGrid[i].append( OFF )
    grid[:] = newGrid[:]
    img.set_data(newGrid)
    return img,

def verbose():
    print("Verbose mode")

if __name__ == '__main__':
    main()


import sys

sys.stdin = open("sample_input.txt",'r')

num_case = int(input())

for case in range(1, num_case +1):
    M, N = map(int,input().split())

    M_words = []
    N_words = []

    for words in range(M):
        M_words.append(str(input()))

    for words in range(N):
        N_words.append(str(input()))

    R = 0

    #Prefix compare algorithm
    for ref in M_words:
        for check in N_words:
            for idx in range(len(check)):
                if ref[idx] == check[idx]:
                    if idx == (len(check) - 1):
                        R = R + 1
                else:
                    break

    print(R)


import pytest

from hyperpack import HyperPack

from .utils import (
    SOLUTION_LOG_ITEMS_STRATEGY,
    SOLUTION_STRING_CONTAINER,
    SOLUTION_STRING_REMAINING_ITEMS,
)

DEFAULT_POTENTIAL_POINTS_STRATEGY = HyperPack.DEFAULT_POTENTIAL_POINTS_STRATEGY

@pytest.mark.parametrize(
    "containers,items,points_seq,solution_log_vars",
    [
        (
            ((2, 3), (2, 2)),
            ((2, 3), (1, 1)),
            ("A", "B"),
            {
                "prec_items_stored": 100,
                "best_strategy": ("A", "B"),
                "containers_vars": (("cont-0", 2, 3, 100), ("cont-1", 2, 2, 25)),
                "remaining_items": [],
            },
        ),
        (
            ((2, 3),),
            ((3, 3),),
            ("A", "B"),
            {
                "prec_items_stored": 0,
                "best_strategy": ("A", "B"),
                "containers_vars": (("cont-0", 2, 3, 0),),
                "remaining_items": ["i-0"],
            },
        ),
        (
            ((2, 4), (3, 3)),
            ((2, 2), (3, 3), (1, 4)),
            ("A", "B"),
            {
                "prec_items_stored": 66.6667,
                "best_strategy": ("A", "B"),
                "containers_vars": (("cont-0", 2, 4, 50), ("cont-1", 3, 3, 100)),
                "remaining_items": ["i-2"],
            },
        ),
    ],
)
def test_log_solution(containers, items, points_seq, solution_log_vars):
    settings = {"workers_num": 1}
    containers = {f"cont-{i}": {"W": c[0], "L": c[1]} for i, c in enumerate(containers)}
    items = {f"i-{i}": {"w": w, "l": l} for i, (w, l) in enumerate(items)}
    prob = HyperPack(containers=containers, items=items, settings=settings)
    prob._potential_points_strategy = points_seq
    prob.solve()

    solution_log = SOLUTION_LOG_ITEMS_STRATEGY.format(
        solution_log_vars["prec_items_stored"],
        solution_log_vars["best_strategy"],
    )
    for container in solution_log_vars["containers_vars"]:
        solution_log += SOLUTION_STRING_CONTAINER.format(*container)
    solution_log += SOLUTION_STRING_REMAINING_ITEMS.format(
        solution_log_vars["remaining_items"]
    )
    solution_log = solution_log.replace("\n", "").replace("\t", "")

    output = prob.log_solution().replace("\n", "").replace("\t", "")

    assert solution_log == output

def test_log_solution_no_solution_found(caplog, test_data):
    prob = HyperPack(**test_data)
    prob.log_solution()
    assert "No solving operation has been concluded." in caplog.text

def test_log_solution_emtpy_container_solution(caplog):
    containers = {"cont_id": {"W": 1, "L": 1}}
    items = {"test_id": {"w": 101, "l": 101}}
    prob = HyperPack(containers=containers, items=items)
    prob.solve()

    solution_log_vars = {
        "prec_items_stored": 0,
        "best_strategy": HyperPack.DEFAULT_POTENTIAL_POINTS_STRATEGY,
        "containers_vars": (("cont_id", 1, 1, 0),),
        "remaining_items": ["test_id"],
    }

    solution_log = SOLUTION_LOG_ITEMS_STRATEGY.format(
        solution_log_vars["prec_items_stored"],
        solution_log_vars["best_strategy"],
    )

    for container in solution_log_vars["containers_vars"]:
        solution_log += SOLUTION_STRING_CONTAINER.format(*container)

    solution_log += SOLUTION_STRING_REMAINING_ITEMS.format(
        solution_log_vars["remaining_items"]
    )

    solution_log = solution_log.replace("\n", "").replace("\t", "")
    output = prob.log_solution().replace("\n", "").replace("\t", "")

    assert solution_log == output


"""init

Revision ID: 653688f547a4
Revises:
Create Date: 2023-03-23 15:50:15.956944

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '653688f547a4'
down_revision = None
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('im_user',
    sa.Column('id', sa.BIGINT(), nullable=False),
    sa.Column('username', sa.String(length=256), nullable=False, comment='用户名'),
    sa.Column('password', sa.String(length=256), nullable=False, comment='用户账号密码'),
    sa.Column('email', sa.String(length=256), nullable=False, comment='账号邮箱'),
    sa.Column('telephone', sa.String(length=256), nullable=True, comment='用户电话'),
    sa.Column('avatar', sa.String(length=256), nullable=True, comment='用户头像'),
    sa.Column('age', sa.SMALLINT(), nullable=True, comment='用户年龄'),
    sa.Column('sex', sa.SMALLINT(), nullable=True, comment='用户性别'),
    sa.Column('created', sa.DateTime(timezone=True), nullable=False),
    sa.Column('last_update', sa.DateTime(timezone=True), nullable=False),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('email'),
    sa.UniqueConstraint('username')
    )
    op.create_table('im_friend_manager_record',
    sa.Column('id', sa.BIGINT(), nullable=False),
    sa.Column('msg_from', sa.BIGINT(), nullable=True),
    sa.Column('msg_to', sa.BIGINT(), nullable=True),
    sa.Column('request_time', sa.DateTime(), nullable=True, comment='发送时间'),
    sa.Column('deal_time', sa.DateTime(), nullable=True, comment='处理时间'),
    sa.Column('accept', sa.Boolean(), nullable=False, comment='是否通过'),
    sa.Column('check_info', sa.TEXT(), nullable=True, comment='验证消息描述'),
    sa.Column('created', sa.DateTime(timezone=True), nullable=False),
    sa.Column('last_update', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['msg_from'], ['im_user.id'], onupdate='CASCADE', ondelete='SET NULL'),
    sa.ForeignKeyConstraint(['msg_to'], ['im_user.id'], onupdate='CASCADE', ondelete='SET NULL'),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('im_group',
    sa.Column('id', sa.BIGINT(), nullable=False),
    sa.Column('group_name', sa.String(length=256), nullable=False, comment='群聊名称'),
    sa.Column('creator_id', sa.BIGINT(), nullable=True, comment='创建者'),
    sa.Column('created_time', sa.DateTime(), nullable=True),
    sa.Column('owner_id', sa.BIGINT(), nullable=True, comment='群主'),
    sa.Column('announcement', sa.TEXT(), nullable=True, comment='群公告'),
    sa.Column('created', sa.DateTime(timezone=True), nullable=False),
    sa.Column('last_update', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['creator_id'], ['im_user.id'], onupdate='CASCADE', ondelete='CASCADE'),
    sa.ForeignKeyConstraint(['owner_id'], ['im_user.id'], onupdate='CASCADE', ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('im_user_friends_ship',
    sa.Column('id', sa.BIGINT(), nullable=False),
    sa.Column('user_id', sa.BIGINT(), nullable=True, comment='用户ID'),
    sa.Column('friend_id', sa.BIGINT(), nullable=True, comment='好友ID'),
    sa.Column('friend_group', sa.String(length=256), nullable=True),
    sa.Column('current_contact_time', sa.DateTime(), nullable=True, comment='最近联系时间'),
    sa.Column('friend_nickname', sa.String(length=256), nullable=False, comment='好友昵称'),
    sa.Column('relationship', sa.SMALLINT(), nullable=False, comment='好友关系(1:好友 2:陌生人)'),
    sa.Column('created', sa.DateTime(timezone=True), nullable=False),
    sa.Column('last_update', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['friend_id'], ['im_user.id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['im_user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('im_message',
    sa.Column('id', sa.BIGINT(), nullable=False),
    sa.Column('msg_from', sa.BIGINT(), nullable=True),
    sa.Column('msg_to', sa.BIGINT(), nullable=True),
    sa.Column('group_id', sa.BIGINT(), nullable=True),
    sa.Column('msg_content', sa.TEXT(), nullable=True, comment='消息内容'),
    sa.Column('msg_type', sa.SMALLINT(), nullable=True, comment='消息类型'),
    sa.Column('send_time', sa.DateTime(), nullable=True, comment='发送时间'),
    sa.Column('created', sa.DateTime(timezone=True), nullable=False),
    sa.Column('last_update', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['group_id'], ['im_group.id'], onupdate='CASCADE', ondelete='SET NULL'),
    sa.ForeignKeyConstraint(['msg_from'], ['im_user.id'], onupdate='CASCADE', ondelete='SET NULL'),
    sa.ForeignKeyConstraint(['msg_to'], ['im_user.id'], onupdate='CASCADE', ondelete='SET NULL'),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('im_user_group_ship',
    sa.Column('id', sa.BIGINT(), nullable=False),
    sa.Column('user_id', sa.BIGINT(), nullable=True, comment='用户ID'),
    sa.Column('group_id', sa.BIGINT(), nullable=True, comment='群ID'),
    sa.Column('current_contact_time', sa.DateTime(), nullable=True, comment='最近更新时间'),
    sa.Column('group_nickname', sa.String(length=256), nullable=False, comment='群昵称'),
    sa.Column('created', sa.DateTime(timezone=True), nullable=False),
    sa.Column('last_update', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['group_id'], ['im_group.id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['im_user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('im_user_group_ship')
    op.drop_table('im_message')
    op.drop_table('im_user_friends_ship')
    op.drop_table('im_group')
    op.drop_table('im_friend_manager_record')
    op.drop_table('im_user')
    # ### end Alembic commands ###


"""
ARIADNE - Vis module

Functions for processing the ASCII visualization of origami structure.
"""

from collections import defaultdict, deque
import re

import seq_utils
import terms

def annotate_bases(vis_file, version):
    """
    Find base annotations from the ASCII visualization file.
    :return:
    """
    with open(vis_file) as f:
        contents = f.read()
    blocks = re.split("Vertex [0-9]+ \(top\) to [0-9]+ \(bottom\), Edge [0-9]+", contents)[1:]
    indexes = list()
    base_annotations = defaultdict(set)
    edges = list()
    for block in blocks:
        double_helices = [deque(), deque()]  # two double helices per edge
        block_lines = [line for line in block.strip().split("\n")[1: -1] if line.strip()]
        n_lines = len(block_lines)
        for i_line, line in enumerate(block_lines, start=1):
            assert len(line) == 26
            idx1 = int(line[0: 6])
            base1 = line[7]
            topo1 = line[9: 13]
            topo2 = line[13: 17]
            base2 = line[18]
            idx2 = int(line[20: 26])
            assert base1 in seq_utils.BASES and base2 in seq_utils.BASES
            indexes.append(idx1)
            indexes.append(idx2)
            num1 = idx1 + 1
            num2 = idx2 + 1
            double_helices[0].appendleft(num1)  # add to 5' side
            double_helices[1].append(num2)  # add to 3' side
            annot1, annot2 = None, None
            if i_line == 1:
                annot1 = terms.EDGE_TM, 3  # at the 3' end of an edge
                annot2 = terms.EDGE_TM, 5  # at the 5' end of an edge
            elif i_line == n_lines:
                annot1 = terms.EDGE_TM, 5  # at the 5' end of an edge
                annot2 = terms.EDGE_TM, 3  # at the 3' end of an edge
            else:
                if version == 1:
                    if topo1 == "| +>":
                        assert topo2 == ">+ |"
                        annot1 = terms.STAP_XO, 5  # lies just 5' of scaffold crossover
                        annot2 = terms.STAP_XO, 3  # lies just 3' of scaffold crossover
                    elif topo2 == ">+ |":
                        raise ValueError()
                    elif topo1 == "| +<":
                        assert topo2 == "<+ |"
                        annot1 = terms.STAP_XO, 3  # lies just 3' of scaffold crossover
                        annot2 = terms.STAP_XO, 5  # lies just 5' of scaffold crossover
                    elif topo2 == "<+ |":
                        raise ValueError()
                elif version == 2:
                    if topo1 == ">>|>":
                        annot1 = terms.SCAF_XO, 5  # lies just 5' of scaffold crossover
                    if topo2 == ">|>>":
                        annot2 = terms.SCAF_XO, 3  # lies just 3' of scaffold crossover
                    if topo1 == "<<|<":
                        annot1 = terms.SCAF_XO, 3  # lies just 3' of scaffold crossover
                    if topo2 == "<|<<":
                        annot2 = terms.SCAF_XO, 5  # lies just 5' of scaffold crossover
                else:
                    raise ValueError(version)
                if not (annot1 and annot2):
                    if topo1 == "| | ":
                        annot1 = terms.MIDDLE  # normal helix
                    elif topo1 == "| . ":
                        annot1 = terms.STAP_TM, 5  # 5' terminus of staple
                    elif topo1 == "| v ":
                        annot1 = terms.STAP_TM, 3  # 3' terminus of staple
                    elif topo1 == ". | ":
                        annot1 = terms.SCAF_TM, 3  # 5' terminus of scaffold
                    elif topo1 == "^ | ":
                        annot1 = terms.SCAF_TM, 3  # 3' terminus of scaffold
                    if topo2 == " | |":
                        annot2 = terms.MIDDLE  # normal helix
                    elif topo2 == " . |":
                        annot2 = terms.STAP_TM, 5  # 5' terminus of staple
                    elif topo2 == " ^ |":
                        annot2 = terms.STAP_TM, 3  # 3' terminus of staple
                    elif topo2 == " | .":
                        annot2 = terms.SCAF_TM, 5  # 5' terminus of scaffold
                    elif topo2 == " | v":
                        annot2 = terms.SCAF_TM, 3  # 3' terminus of scaffold
            assert annot1 and annot2
            base_annotations[annot1].add(num1)
            base_annotations[annot2].add(num2)
        edges.append(double_helices)
    assert sorted(indexes) == list(range(min(indexes), max(indexes))) + [max(indexes)]
    all_nums = sorted([num for annot, nums in base_annotations.items() for num in nums])
    assert all_nums == list(range(all_nums[0], all_nums[-1] + 1))
    edges = [sorted([list(helix1), list(helix2)], key=min) for helix1, helix2 in edges]
    edges = sorted([[helix1, list(reversed(helix2))] for helix1, helix2 in edges],
                   key=lambda x: min(map(min, x)))
    # Convert to dict.
    return dict(base_annotations), edges


from typing import Dict

INPUT = open("./input_files/input_19", "r").read().strip("\n")

X = 'x'
Y = 'y'
HORIZONTAL = '-'
VERTICAL = '|'
END = '+'

class RoutingDiagram:
    @staticmethod
    def north(position: Dict[str, int]) -> Dict[str, int]:
        return dict(x=position[X], y=position[Y] - 1)

    @staticmethod
    def east(position: Dict[str, int]) -> Dict[str, int]:
        return dict(x=position[X] + 1, y=position[Y])

    @staticmethod
    def south(position: Dict[str, int]) -> Dict[str, int]:
        return dict(x=position[X], y=position[Y] + 1)

    @staticmethod
    def west(position: Dict[str, int]) -> Dict[str, int]:
        return dict(x=position[X] - 1, y=position[Y])

    def new_direction(self):
        if self.direction in [RoutingDiagram.north, RoutingDiagram.south]:
            if self.get_value(RoutingDiagram.east(self.position)) == HORIZONTAL:
                self.direction = RoutingDiagram.east
            else:
                self.direction = RoutingDiagram.west
        elif self.direction in [RoutingDiagram.east, RoutingDiagram.west]:
            if self.get_value(RoutingDiagram.south(self.position)) == VERTICAL:
                self.direction = RoutingDiagram.south
            else:
                self.direction = RoutingDiagram.north
        else:
            self.direction = None

    def __init__(self, input: str):
        self.routing = input.split("\n")
        self.position = dict(x=self.routing[0].index('|'), y=0)
        self.direction = RoutingDiagram.south
        self.text = list()
        self.steps = 0

    def get_value(self, position: Dict[str, int] = None) -> str:
        position = self.position if position is None else position
        return self.routing[position[Y]][position[X]]

    def move(self):
        self.position = self.direction(self.position)
        value = self.get_value()
        self.steps += 1

        if value == END:
            self.new_direction()
        elif value == ' ':
            self.direction = None
        elif value in [HORIZONTAL, VERTICAL]:
            pass
        else:
            self.text.append(value)

    def get_text(self):
        return ''.join(self.text)

def run_1():
    rd = RoutingDiagram(INPUT)

    while rd.direction is not None:
        rd.move()
    return rd.get_text()

def run_2():
    rd = RoutingDiagram(INPUT)

    while rd.direction is not None:
        rd.move()
    return rd.steps

print(run_1())
print(run_2())


#!/usr/bin/env python3

import argparse
import igraph
import sys
sys.path.append(".")
sys.path.append("..")
from event_graph_analysis.utilities import read_graph

def main(graph_path):
    g = read_graph(graph_path)
    n_vertices = g.vcount()
    n_edges = g.ecount()
    print("# Vertices: {}".format(n_vertices))
    print("# Edges: {}".format(n_edges))

if __name__ == "__main__":
    desc = ""
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument("graph", help="")
    args = parser.parse_args()
    main(args.graph)


#!/usr/bin/env python
from pymongo import MongoClient
mongo_client = MongoClient()

#print(mongo_client)

db = mongo_client.test
col = db.test

n = 1000000

myarr = []

sum = 1
for counter in range(1,n):
    doc = {}
    doc["value"] = sum + counter
    myarr += [doc]

col.insert_many(myarr)

# get the total numbers of docs inserted
total_docs = len(result.inserted_ids)

print ("total inserted:", total_docs)
print ("inserted IDs:", result.inserted_ids, "\n\n")


from ethtx_ce.backend.models.semantics_model import (
    EventSemantics,
    ParameterSemantics,
    TransformationSemantics,
    FunctionSemantics,
)

erc20_transfer_event = EventSemantics(
    "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
    False,
    "Transfer",
    [
        ParameterSemantics("src", "address", [], True),
        ParameterSemantics("dst", "address", [], True),
        ParameterSemantics("value", "uint256", [], False),
    ],
)

erc20_transfer_event_transformation = {
    "__input2__": TransformationSemantics(
        transformation="__input2__ / 10**token_decimals(__contract__)"
    )
}

erc20_approval_event = EventSemantics(
    "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925",
    False,
    "Approval",
    [
        ParameterSemantics("src", "address", [], True),
        ParameterSemantics("dst", "address", [], True),
        ParameterSemantics("value", "uint256", [], False),
    ],
)

erc20_approval_event_transformation = {
    "__input2__": TransformationSemantics(
        transformation="__input2__ / 10**token_decimals(__contract__)"
    )
}

erc20_transfer_function = FunctionSemantics(
    "0xa9059cbb",
    "transfer",
    [
        ParameterSemantics("recipient", "address", []),
        ParameterSemantics("amount", "uint256", []),
    ],
    [ParameterSemantics("", "bool", [])],
)

erc20_transfer_function_transformation = {
    "__input1__": TransformationSemantics(
        transformation="__input1__ / 10**token_decimals(__contract__)"
    )
}

erc20_transferFrom_function = FunctionSemantics(
    "0x23b872dd",
    "transferFrom",
    [
        ParameterSemantics("sender", "address", []),
        ParameterSemantics("recipient", "address", []),
        ParameterSemantics("amount", "uint256", []),
    ],
    [ParameterSemantics("", "bool", [])],
)

erc20_transferFrom_function_transformation = {
    "__input2__": TransformationSemantics(
        transformation="__input2__ / 10**token_decimals(__contract__)"
    )
}

erc20_approve_function = FunctionSemantics(
    "0x095ea7b3",
    "approve",
    [
        ParameterSemantics("spender", "address", []),
        ParameterSemantics("amount", "uint256", []),
    ],
    [ParameterSemantics("", "bool", [])],
)

erc20_approve_function_transformation = {
    "__input1__": TransformationSemantics(
        transformation="__input1__ / 10**token_decimals(__contract__)"
    )
}

erc20_balanceOf_function = FunctionSemantics(
    "0x70a08231",
    "balanceOf",
    [ParameterSemantics("holder", "address", [])],
    [ParameterSemantics("", "uint256", [])],
)

erc20_balanceOf_function_transformation = {
    "__output0__": TransformationSemantics(
        transformation="__output0__ / 10**token_decimals(__contract__)"
    )
}

erc20_totalSupply_function = FunctionSemantics(
    "0x18160ddd", "totalSupply", [], [ParameterSemantics("", "uint256", [])]
)

erc20_totalSupply_function_transformation = {
    "__output0__": TransformationSemantics(
        transformation="__output0__ / 10**token_decimals(__contract__)"
    )
}

ERC20_EVENTS = {
    erc20_transfer_event.signature: erc20_transfer_event,
    erc20_approval_event.signature: erc20_approval_event,
}

ERC20_FUNCTIONS = {
    erc20_transfer_function.signature: erc20_transfer_function,
    erc20_transferFrom_function.signature: erc20_transferFrom_function,
    erc20_approve_function.signature: erc20_approve_function,
    erc20_balanceOf_function.signature: erc20_balanceOf_function,
    erc20_totalSupply_function.signature: erc20_totalSupply_function,
}

ERC20_TRANSFORMATIONS = {
    erc20_transfer_event.signature: erc20_transfer_event_transformation,
    erc20_approval_event.signature: erc20_approval_event_transformation,
    erc20_transfer_function.signature: erc20_transfer_function_transformation,
    erc20_transferFrom_function.signature: erc20_transferFrom_function_transformation,
    erc20_approve_function.signature: erc20_approve_function_transformation,
    erc20_balanceOf_function.signature: erc20_balanceOf_function_transformation,
    erc20_totalSupply_function.signature: erc20_totalSupply_function_transformation,
}


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

import argparse
import json
import logging
import os
import multiprocessing
import re
import shutil
import sys
import xml.etree.ElementTree as ET

import nibabel as nib
import numpy as np
from dipy.data import SPHERE_FILES
from dipy.io.utils import is_header_compatible
from fury import window
from PIL import Image
from scipy.io import loadmat
import six

from scilpy.io.streamlines import load_tractogram_with_reference
from scilpy.gradients.bvec_bval_tools import DEFAULT_B0_THRESHOLD
from scilpy.utils.filenames import split_name_with_nii

eddy_options = ["mb", "mb_offs", "slspec", "mporder", "s2v_lambda", "field",
                "field_mat", "flm", "slm", "fwhm", "niter", "s2v_niter",
                "cnr_maps", "residuals", "fep", "interp", "s2v_interp",
                "resamp", "nvoxhp", "ff", "ol_nstd", "ol_nvox", "ol_type",
                "ol_pos", "ol_sqr", "dont_sep_offs_move", "dont_peas"]

topup_options = ['out', 'fout', 'iout', 'logout', 'warpres', 'subsamp', 'fwhm',
                 'config', 'miter', 'lambda', 'ssqlambda', 'regmod', 'estmov',
                 "minmet", 'splineorder', 'numprec', 'interp', 'scale',
                 'regrid']

axis_name_choices = ["axial", "coronal", "sagittal"]

def get_acq_parameters(json_path, args_list):
    """
    Function to extract acquisition parameters from json file.

    Parameters
    ----------
    json_path   Path to the json file
    args_list   List of keys corresponding to parameters

    Returns
    ----------
    Returns a list of values matching the list of keys.
    """
    with open(json_path) as f:
        data = json.load(f)

    acq_parameters = []
    for parameter in args_list:
        acq_parameters.append(data[parameter])
    return acq_parameters

def redirect_stdout_c():
    sys.stdout.flush()
    newstdout = os.dup(1)
    devnull = os.open(os.devnull, os.O_WRONLY)
    os.dup2(devnull, 1)
    os.close(devnull)
    sys.stdout = os.fdopen(newstdout, 'w')

def link_bundles_and_reference(parser, args, input_tractogram_list):
    """
    Associate the bundle to their reference (if they require a reference).
    Parameters
    ----------
    parser: argparse.ArgumentParser object
        Parser as created by argparse.
    args: argparse namespace
        Args as created by argparse.
    input_tractogram_list: list
        List of tractogram paths.
    Returns
    -------
    list: List of tuples, each matching one tractogram to a reference file.
    """
    bundles_references_tuple = []
    for bundle_filename in input_tractogram_list:
        _, ext = os.path.splitext(bundle_filename)
        if ext == '.trk':
            if args.reference is None:
                bundles_references_tuple.append(
                    (bundle_filename, bundle_filename))
            else:
                bundles_references_tuple.append(
                    (bundle_filename, args.reference))
        elif ext in ['.tck', '.fib', '.vtk', '.dpy']:
            if args.reference is None:
                parser.error('--reference is required for this file format '
                             '{}.'.format(bundle_filename))
            else:
                bundles_references_tuple.append(
                    (bundle_filename, args.reference))
    return bundles_references_tuple

def check_tracts_same_format(parser, filename_list):
    _, ref_ext = os.path.splitext(filename_list[0])

    for filename in filename_list[1:]:
        if isinstance(filename, six.string_types) and \
                not os.path.splitext(filename)[1] == ref_ext:
            parser.error('All tracts file must use the same format.')

def assert_gradients_filenames_valid(parser, filename_list, gradient_format):
    """
    Validate if gradients filenames follow BIDS or MRtrix convention

    Parameters
    ----------
    parser: parser
        Parser.
    filename_list: list
        list of gradient paths.
    gradient_format : str
        Can be either fsl or mrtrix.

    Returns
    -------
    """

    valid_fsl_extensions = ['.bval', '.bvec']
    valid_mrtrix_extension = '.b'

    if isinstance(filename_list, str):
        filename_list = [filename_list]

    if gradient_format == 'fsl':
        if len(filename_list) == 2:
            filename_1 = filename_list[0]
            filename_2 = filename_list[1]
            basename_1, ext_1 = os.path.splitext(filename_1)
            basename_2, ext_2 = os.path.splitext(filename_2)

            if ext_1 == '' or ext_2 == '':
                parser.error('fsl gradients filenames must have extensions: '
                             '.bval and .bvec.')

            if basename_1 == basename_2:
                curr_extensions = [ext_1, ext_2]
                curr_extensions.sort()
                if curr_extensions != valid_fsl_extensions:
                    parser.error('Your extensions ({}) doesn\'t follow BIDS '
                                 'convention.'.format(curr_extensions))
            else:
                parser.error('fsl gradients filenames must have the same '
                             'basename.')
        else:
            parser.error('You should have two files for fsl format.')

    elif gradient_format == 'mrtrix':
        if len(filename_list) == 1:
            curr_filename = filename_list[0]
            basename, ext = os.path.splitext(curr_filename)
            if basename == '' or ext != valid_mrtrix_extension:
                parser.error('Basename: {} and extension {} are not '
                             'valid for mrtrix format.'.format(basename, ext))
        else:
            parser.error('You should have one file for mrtrix format.')
    else:
        parser.error('Gradient file format should be either fsl or mrtrix.')

def add_json_args(parser):
    g1 = parser.add_argument_group(title='Json options')
    g1.add_argument('--indent',
                    type=int, default=2,
                    help='Indent for json pretty print.')
    g1.add_argument('--sort_keys',
                    action='store_true',
                    help='Sort keys in output json.')

def add_processes_arg(parser):
    parser.add_argument('--processes', dest='nbr_processes',
                        metavar='NBR', type=int, default=1,
                        help='Number of sub-processes to start. \n'
                        'Default: [%(default)s]')

def add_reference_arg(parser, arg_name=None):
    if arg_name:
        parser.add_argument('--'+arg_name+'_ref',
                            help='Reference anatomy for {} (if tck/vtk/fib/dpy'
                                 ') file\n'
                                 'support (.nii or .nii.gz).'.format(arg_name))
    else:
        parser.add_argument('--reference',
                            help='Reference anatomy for tck/vtk/fib/dpy file\n'
                                 'support (.nii or .nii.gz).')

def add_sphere_arg(parser, symmetric_only=False, default='repulsion724'):
    spheres = sorted(SPHERE_FILES.keys())
    if symmetric_only:
        spheres = [s for s in spheres if 'symmetric' in s]
        if 'symmetric' not in default:
            raise ValueError("Default cannot be {} if you only accept "
                             "symmetric spheres.".format(default))

    parser.add_argument('--sphere', choices=spheres,
                        default=default,
                        help='Dipy sphere; set of possible directions.\n'
                             'Default: [%(default)s]')

def add_overwrite_arg(parser):
    parser.add_argument(
        '-f', dest='overwrite', action='store_true',
        help='Force overwriting of the output files.')

def add_force_b0_arg(parser):
    parser.add_argument('--force_b0_threshold', action='store_true',
                        help='If set, the script will continue even if the '
                             'minimum bvalue is suspiciously high ( > {})'
                        .format(DEFAULT_B0_THRESHOLD))

def add_verbose_arg(parser):
    parser.add_argument('-v', action='store_true', dest='verbose',
                        help='If set, produces verbose output.')

def add_bbox_arg(parser):
    parser.add_argument('--no_bbox_check', dest='bbox_check',
                        action='store_false',
                        help='Activate to ignore validity of the bounding '
                             'box during loading / saving of \n'
                             'tractograms (ignores the presence of invalid '
                             'streamlines).')

def add_sh_basis_args(parser, mandatory=False):
    """Add spherical harmonics (SH) bases argument.

    Parameters
    ----------
    parser: argparse.ArgumentParser object
        Parser.
    mandatory: bool
        Whether this argument is mandatory.
    """
    choices = ['descoteaux07', 'tournier07']
    def_val = 'descoteaux07'
    help_msg = 'Spherical harmonics basis used for the SH coefficients. ' +\
               '\nMustbe either \'descoteaux07\' or \'tournier07\'' +\
               ' [%(default)s]:\n' +\
               '    \'descoteaux07\': SH basis from the Descoteaux et al.\n' +\
               '                      MRM 2007 paper\n' +\
               '    \'tournier07\'  : SH basis from the Tournier et al.\n' +\
               '                      NeuroImage 2007 paper.'

    if mandatory:
        arg_name = 'sh_basis'
    else:
        arg_name = '--sh_basis'

    parser.add_argument(arg_name,
                        choices=choices, default=def_val,
                        help=help_msg)

def add_nifti_screenshot_default_args(
    parser, slice_ids_mandatory=True, transparency_mask_mandatory=True
):
    _mask_prefix = "" if transparency_mask_mandatory else "--"

    _slice_ids_prefix, _slice_ids_help = "", "Slice indices to screenshot."
    _output_help = "Name of the output image (e.g. img.jpg, img.png)."
    if not slice_ids_mandatory:
        _slice_ids_prefix = "--"
        _slice_ids_help += " If None are supplied, all slices inside " \
                           "the transparency mask are selected."
        _output_help = "Name of the output image(s). If multiple slices are " \
                       "provided (or none), their index will be append to " \
            "the name (e.g. volume.jpg, volume.png becomes " \
            "volume_slice_0.jpg, volume_slice_0.png)."

    # Positional arguments
    parser.add_argument(
        "in_volume", help="Input 3D Nifti file (.nii/.nii.gz).")
    parser.add_argument("out_fname", help=_output_help)

    # Variable arguments
    parser.add_argument(
        f"{_mask_prefix}in_transparency_mask",
        help="Transparency mask 3D Nifti image (.nii/.nii.gz).")
    parser.add_argument(
        f"{_slice_ids_prefix}slice_ids", nargs="+", type=int,
        help=_slice_ids_help)

    # Optional arguments
    parser.add_argument(
        "--volume_cmap_name", default=None,
        help="Colormap name for the volume image data. [%(default)s]")
    parser.add_argument(
        "--axis_name", default="axial", type=str, choices=axis_name_choices,
        help="Name of the axis to visualize. [%(default)s]")
    parser.add_argument(
        "--win_dims", nargs=2, metavar=("WIDTH", "HEIGHT"), default=(768, 768),
        type=int, help="The dimensions for the vtk window. [%(default)s]")
    parser.add_argument(
        "--display_slice_number", action="store_true",
        help="If true, displays the slice number in the upper left corner."
    )
    parser.add_argument(
        "--display_lr", action="store_true",
        help="If true, add left and right annotations to the images."
    )

def add_nifti_screenshot_overlays_args(
    parser, labelmap_overlay=True, mask_overlay=True,
    transparency_is_overlay=False
):
    if labelmap_overlay:
        parser.add_argument(
            "--in_labelmap",  help="Labelmap 3D Nifti image (.nii/.nii.gz).")
        parser.add_argument(
            "--labelmap_cmap_name", default="viridis",
            help="Colormap name for the labelmap image data. [%(default)s]")
        parser.add_argument(
            "--labelmap_alpha", type=ranged_type(float, 0., 1.), default=0.7,
            help="Opacity value for the labelmap overlay. [%(default)s].")

    if mask_overlay:
        if not transparency_is_overlay:
            parser.add_argument(
                "--in_masks", nargs="+",
                help="Mask 3D Nifti image (.nii/.nii.gz).")

        parser.add_argument(
            "--masks_colors", nargs="+", metavar="R G B",
            type=ranged_type(int, 0, 255), default=None,
            help="Colors for the mask overlay or contour")
        parser.add_argument(
            "--masks_as_contours", action='store_true',
            help="Create contours from masks instead "
                 "of overlays. [%(default)s].")
        parser.add_argument(
            "--masks_alpha", type=ranged_type(float, 0., 1.), default=0.7,
            help="Opacity value for the masks overlays. [%(default)s].")

def validate_nbr_processes(parser, args):
    """ Check if the passed number of processes arg is valid.
    Valid values are considered to be in the [0, CPU count] range:
        - Raises a parser.error if an invalid value is provided.
        - Returns the maximum number of cores retrieved if no value (or a value
        of 0) is provided.

    Parameters
    ----------
    parser: argparse.ArgumentParser object
        Parser as created by argparse.
    args: argparse namespace
        Args as created by argparse.

    Returns
    -------
    nbr_cpu: int
        The number of CPU to be used.
    """

    if args.nbr_processes:
        nbr_cpu = args.nbr_processes
    else:
        nbr_cpu = multiprocessing.cpu_count()

    if nbr_cpu < 0:
        parser.error('Number of processes must be > 0.')
    elif nbr_cpu > multiprocessing.cpu_count():
        parser.error('Max number of processes is {}. Got {}.'.format(
            multiprocessing.cpu_count(), nbr_cpu))

    return nbr_cpu

def validate_sh_basis_choice(sh_basis):
    """ Check if the passed sh_basis arg to a fct is right.

    Parameters
    ----------
    sh_basis: str
        Either 'descoteaux08' or 'tournier07'

    Raises
    ------
    ValueError
        If sh_basis is not one of 'descoteaux07' or 'tournier07'
    """
    if not (sh_basis == 'descoteaux07' or sh_basis == 'tournier07'):
        raise ValueError("sh_basis should be either 'descoteaux07' or"
                         "'tournier07'.")

def verify_compression_th(compress_th):
    """
    Verify that the compression threshold is between 0.001 and 1. Else,
    produce a warning.

    Parameters
    -----------
    compress_th: float, the compression threshold.
    """
    if compress_th:
        if compress_th < 0.001 or compress_th > 1:
            logging.warning(
                'You are using an error rate of {}.\nWe recommend setting it '
                'between 0.001 and 1.\n0.001 will do almost nothing to the '
                'tracts while 1 will higly compress/linearize the tracts.'
                .format(compress_th))

def assert_inputs_exist(parser, required, optional=None):
    """Assert that all inputs exist. If not, print parser's usage and exit.

    Parameters
    ----------
    parser: argparse.ArgumentParser object
        Parser.
    required: string or list of paths
        Required paths to be checked.
    optional: string or list of paths
        Optional paths to be checked.
    """
    def check(path):
        if not os.path.isfile(path):
            parser.error('Input file {} does not exist'.format(path))

    if isinstance(required, str):
        required = [required]

    if isinstance(optional, str):
        optional = [optional]

    for required_file in required:
        check(required_file)
    for optional_file in optional or []:
        if optional_file is not None:
            check(optional_file)

def assert_outputs_exist(parser, args, required, optional=None,
                         check_dir_exists=True):
    """
    Assert that all outputs don't exist or that if they exist, -f was used.
    If not, print parser's usage and exit.

    Parameters
    ----------
    parser: argparse.ArgumentParser object
        Parser.
    args: argparse namespace
        Argument list.
    required: string or list of paths to files
        Required paths to be checked.
    optional: string or list of paths to files
        Optional paths to be checked.
    check_dir_exists: bool
        Test if output directory exists.
    """
    def check(path):
        if os.path.isfile(path) and not args.overwrite:
            parser.error('Output file {} exists. Use -f to force '
                         'overwriting'.format(path))

        if check_dir_exists:
            path_dir = os.path.dirname(path)
            if path_dir and not os.path.isdir(path_dir):
                parser.error('Directory {}/ \n for a given output file '
                             'does not exists.'.format(path_dir))

    if isinstance(required, str):
        required = [required]

    if isinstance(optional, str):
        optional = [optional]

    for required_file in required:
        check(required_file)
    for optional_file in optional or []:
        if optional_file:
            check(optional_file)

def assert_output_dirs_exist_and_empty(parser, args, required,
                                       optional=None, create_dir=True):
    """
    Assert that all output directories exist.
    If not, print parser's usage and exit.
    If exists and not empty, and -f used, delete dirs.

    Parameters
    ----------
    parser: argparse.ArgumentParser object
        Parser.
    args: argparse namespace
        Argument list.
    required: string or list of paths to files
        Required paths to be checked.
    optional: string or list of paths to files
        Optional paths to be checked.
    create_dir: bool
        If true, create the directory if it does not exist.
    """
    def check(path):
        if not os.path.isdir(path):
            if not create_dir:
                parser.error(
                    'Output directory {} doesn\'t exist.'.format(path))
            else:
                os.makedirs(path, exist_ok=True)
        if os.listdir(path):
            if not args.overwrite:
                parser.error(
                    'Output directory {} isn\'t empty and some files could be '
                    'overwritten or even deleted. Use -f option if you want '
                    'to continue.'.format(path))
            else:
                for the_file in os.listdir(path):
                    file_path = os.path.join(path, the_file)
                    try:
                        if os.path.isfile(file_path):
                            os.unlink(file_path)
                        elif os.path.isdir(file_path):
                            shutil.rmtree(file_path)
                    except Exception as e:
                        print(e)

    if isinstance(required, str):
        required = [required]
    if isinstance(optional, str):
        optional = [optional]

    for cur_dir in required:
        check(cur_dir)
    for opt_dir in optional or []:
        if opt_dir:
            check(opt_dir)

def assert_overlay_colors(colors, overlays, parser):
    if colors is None:
        return

    if len(colors) % 3 != 0:
        parser.error(
            "Masks colors must be tuples of 3 ints in the range [0, 255]")

    if len(colors) > 3 and len(colors) // 3 != len(overlays):
        parser.error(f"Bad number of colors supplied for overlays "
                     f"({len(overlays)}). Either provide no color, a "
                     f"single mask color or as many colors as there is masks")

def assert_roi_radii_format(parser):
    """
    Verifies the format of the inputed roi radii.

    Parameters
    ----------
    parser: argument parser
        Will raise an error if the --roi_radii format is wrong.

    Returns
    -------
    roi_radii: int or numpy array
        Roi radii as a scalar or an array of size (3,).
    """
    args = parser.parse_args()
    if len(args.roi_radii) == 1:
        roi_radii = args.roi_radii[0]
    elif len(args.roi_radii) == 3:
        roi_radii = args.roi_radii
    else:
        parser.error('Wrong size for --roi_radii, can only be a scalar' +
                     'or an array of size (3,)')
    return roi_radii

def verify_compatibility_with_reference_sft(ref_sft, files_to_verify,
                                            parser, args):
    """
    Verifies the compatibility of a reference sft with a list of files.

    Params
    ------
    ref_sft: StatefulTractogram
        A tractogram to be used as reference.
    files_to_verify: List[str]
        List of files that should be compatible with the reference sft. Files
        can be either other tractograms or nifti files (ex: masks).
    parser: argument parser
        Will raise an error if a file is not compatible.
    args: Namespace
        Should contain a args.reference if any file is a .tck, and possibly a
        args.bbox_check (set to True by default).
    """
    save_ref = args.reference

    for file in files_to_verify:
        if file is not None:
            _, ext = os.path.splitext(file)
            if ext in ['.trk', '.tck', '.fib', '.vtk', '.dpy']:
                # Cheating ref because it may send a lot of warning if loading
                # many trk with ref (reference was maybe added only for some
                # of these files)
                if ext == '.trk':
                    args.reference = None
                else:
                    args.reference = save_ref
                mask = load_tractogram_with_reference(parser, args, file)
            else:  # should be a nifti file.
                mask = file
            compatible = is_header_compatible(ref_sft, mask)
            if not compatible:
                parser.error("Reference tractogram incompatible with {}"
                             .format(file))

def is_header_compatible_multiple_files(parser, list_files,
                                        verbose_all_compatible=False,
                                        reference=None):
    """
    Verifies the compatibility between the first item in list_files
    and the remaining files in list.

    Arguments
    ---------
    parser: argument parser
        Will raise an error if a file is not compatible.
    list_files: List[str]
        List of files to test
    verbose_all_compatible: bool
        If true will print a message when everything is okay
    reference: str
        Reference for any .tck passed in `list_files`
    """
    all_valid = True

    # Gather "headers" for all files to compare against
    # eachother later
    headers = []
    for filepath in list_files:
        _, in_extension = split_name_with_nii(filepath)
        if in_extension in ['.trk', '.nii', '.nii.gz']:
            headers.append(filepath)
        elif in_extension == '.tck':
            if reference:
                headers.append(reference)
            else:
                parser.error(
                    '{} must be provided with a reference.'.format(
                        filepath))
        else:
            parser.error('{} does not have a supported extension.'.format(
                filepath))

    for curr in headers[1:]:
        if not is_header_compatible(headers[0], curr):
            print('ERROR:\"{}\" and \"{}\" do not have compatible '
                  'headers.'.format(headers[0], curr))
            all_valid = False

    if all_valid and verbose_all_compatible:
        print('All input files have compatible headers.')
    elif not all_valid:
        parser.error('Not all input files have compatible headers.')

def read_info_from_mb_bdo(filename):
    tree = ET.parse(filename)
    root = tree.getroot()
    geometry = root.attrib['type']
    center_tag = root.find('origin')
    flip = [-1, -1, 1]
    center = [flip[0]*float(center_tag.attrib['x'].replace(',', '.')),
              flip[1]*float(center_tag.attrib['y'].replace(',', '.')),
              flip[2]*float(center_tag.attrib['z'].replace(',', '.'))]
    row_list = tree.iter('Row')
    radius = [None, None, None]
    for i, row in enumerate(row_list):
        for j in range(0, 3):
            if j == i:
                key = 'col' + str(j+1)
                radius[i] = float(row.attrib[key].replace(',', '.'))
            else:
                key = 'col' + str(j+1)
                value = float(row.attrib[key].replace(',', '.'))
                if abs(value) > 0.01:
                    raise ValueError('Does not support rotation, for now \n'
                                     'only SO aligned on the X,Y,Z axis are '
                                     'supported.')
    radius = np.asarray(radius, dtype=np.float32)
    center = np.asarray(center, dtype=np.float32)
    return geometry, radius, center

def load_matrix_in_any_format(filepath):
    _, ext = os.path.splitext(filepath)
    if ext == '.txt':
        data = np.loadtxt(filepath)
    elif ext == '.npy':
        data = np.load(filepath)
    elif ext == '.mat':
        # .mat are actually dictionnary. This function support .mat from
        # antsRegistration that encode a 4x4 transformation matrix.
        transfo_dict = loadmat(filepath)
        lps2ras = np.diag([-1, -1, 1])
        transfo_key = 'AffineTransform_double_3_3'
        if transfo_key not in transfo_dict:
            transfo_key = 'AffineTransform_float_3_3'

        rot = transfo_dict[transfo_key][0:9].reshape((3, 3))
        trans = transfo_dict[transfo_key][9:12]
        offset = transfo_dict['fixed']
        r_trans = (np.dot(rot, offset) - offset - trans).T * [1, 1, -1]

        data = np.eye(4)
        data[0:3, 3] = r_trans
        data[:3, :3] = np.dot(np.dot(lps2ras, rot), lps2ras)
    else:
        raise ValueError('Extension {} is not supported'.format(ext))

    return data

def save_matrix_in_any_format(filepath, output_data):
    _, ext = os.path.splitext(filepath)
    if ext == '.txt':
        np.savetxt(filepath, output_data)
    elif ext == '.npy':
        np.save(filepath, output_data)
    elif ext == '':
        np.save('{}.npy'.format(filepath), output_data)
    else:
        raise ValueError('Extension {} is not supported'.format(ext))

def assert_fsl_options_exist(parser, options_args, command):
    """
    Assert that all options for topup or eddy exist.
    If not, print parser's usage and exit.

    Parameters
    ----------
    parser: argparse.ArgumentParser object
        Parser.
    options_args: string
        Options for fsl command
    command: string
        Command used (eddy or topup).
    """
    if command == 'eddy':
        fsl_options = eddy_options
    elif command == 'topup':
        fsl_options = topup_options
    else:
        parser.error('{} command is not supported as fsl '
                     'command.'.format(command))

    options = re.split(r'[ =\s]\s*', options_args)
    res = [i for i in options if "--" in i]
    res = list(map(lambda x: x.replace('--', ''), res))

    for nOption in res:
        if nOption not in fsl_options:
            parser.error('--{} is not a valid option for '
                         '{} command.'.format(nOption, command))

def parser_color_type(arg):
    """
    Validate that a color component is between RBG values, else return an error
    From https://stackoverflow.com/a/55410582
    """

    MIN_VAL = 0
    MAX_VAL = 255
    try:
        f = float(arg)
    except ValueError:
        raise argparse.ArgumentTypeError("Color component must be a floating "
                                         "point number")
    if f < MIN_VAL or f > MAX_VAL:
        raise argparse.ArgumentTypeError(
            "Argument must be < " + str(MAX_VAL) + "and > " + str(MIN_VAL))
    return f

def snapshot(scene, filename, **kwargs):
    """ Wrapper around fury.window.snapshot
    For some reason, fury.window.snapshot flips the image vertically.
    This image unflips the image and then saves it.
    """
    out = window.snapshot(scene, **kwargs)
    image = Image.fromarray(out[::-1])
    image.save(filename)

def ranged_type(value_type, min_value, max_value):
    """Return a function handle of an argument type function for ArgumentParser
    checking a range: `min_value` <= arg <= `max_value`.

    Parameters
    ----------
    value_type : Type
        Value-type to convert the argument.
    min_value : scalar
        Minimum acceptable argument value.
    max_value : scalar
       Maximum acceptable argument value.

    Returns
    -------
    Function handle of an argument type function for ArgumentParser.

    Usage
    -----
        ranged_type(float, 0.0, 1.0)
    """

    def range_checker(arg: str):
        try:
            f = value_type(arg)
        except ValueError:
            raise argparse.ArgumentTypeError(f"must be a valid {value_type}")
        if f < min_value or f > max_value:
            raise argparse.ArgumentTypeError(
                f"must be within [{min_value}, {max_value}]")
        return f

    # Return handle to checking function
    return range_checker

def get_default_screenshotting_data(args):

    volume_img = nib.load(args.in_volume)

    transparency_mask_img = None
    if args.in_transparency_mask:
        transparency_mask_img = nib.load(args.in_transparency_mask)

    labelmap_img = None
    if args.in_labelmap:
        labelmap_img = nib.load(args.in_labelmap)

    mask_imgs, masks_colors = None, None
    if args.in_masks:
        mask_imgs = [nib.load(f) for f in args.in_masks]

        if args.masks_colors is not None:
            if len(args.masks_colors) == 3:
                masks_colors = np.repeat(
                    [args.masks_colors], len(args.in_masks), axis=0)
            elif len(args.masks_colors) // 3 == len(args.in_masks):
                masks_colors = np.array(args.masks_colors).reshape((-1, 3))

            masks_colors = masks_colors / 255.

    return volume_img, \
        transparency_mask_img, \
        labelmap_img, \
        mask_imgs, \
        masks_colors


"""Sphinx configuration file for an LSST stack package.

This configuration only affects single-package Sphinx documentation builds.
"""

import lsst.ts.m2  # type: ignore # noqa
from documenteer.conf.pipelinespkg import *  # type: ignore # noqa

project = "ts_m2"
html_theme_options["logotext"] = project  # type: ignore # noqa
html_title = project
html_short_title = project
doxylink = {}  # type: ignore # noqa

intersphinx_mapping["ts_xml"] = ("https://ts-xml.lsst.io", None)  # type: ignore # noqa
intersphinx_mapping["ts_salobj"] = ("https://ts-salobj.lsst.io", None)  # type: ignore # noqa

# Support the sphinx extension of plantuml
extensions.append("sphinxcontrib.plantuml")  # type: ignore # noqa

# Put the path to plantuml.jar
plantuml = "java -jar /home/saluser/plantuml.jar"


from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from tasklist.models import tasklist
from tasklist.serializers import tasklistSerializer

class TasklistViewSet(viewsets.ModelViewSet):
    model = tasklist
    queryset = model.objects.all()
    serializer_class = tasklistSerializer
    # authentication_classes = [JSONWebTokenAuthentication]
    # permission_classes = [IsAuthenticated]

    def list(self, request, *args, **kwargs):
        data = tasklist.objects.all()
        serializer = tasklistSerializer(data, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        task = tasklist.objects.create(
            task_name=request.data['task_name'],
            task_id=request.data['task_id'],
            is_checked=request.data['is_checked']
        )
        serialized_task = tasklistSerializer(instance=task)
        response = {
            'task': serialized_task.data
        }
        return Response(data=response)

    def delete(self, request, pk=None):
        task = self.get_object(pk)
        task.delete()
        response = {
            'message': 'Task deleted successfully'
        }
        return Response(data=response)


#!C:\Python27\python.exe
import string
from twitchbot.connection import send_message

def join_room(s):
    read_buffer = ""
    loading = True
    while loading:
        read_buffer = read_buffer + s.recv(1024)
        temp = string.split(read_buffer, "\n")
        read_buffer = temp.pop()

        for line in temp:
            print(line)
            loading = loading_complete(line)
    # send_message(s, "/me Hello everyone. How are you guys doing today?")

def loading_complete(line):
    if "End of /NAMES list" in line:
        return False
    else:
        return True


import string

"""
Текст сообщений, используемый в ответах чат-бота на запросы пользователя
"""

# Сообщения кнопок для пользователя
TODAY = "Занятия сегодня"
TOMOROW = "Занятия завтра"
THIS_WEEK = "Занятия на этой неделе"
NEXT_WEEK = "Занятия на следующей неделе"
GREETINGS = "Привет!\nВведи число и получишь фамилию одного из преподавателей"

# Сообщение об ошибке запроса
SOMETHING_BROKEN = "Упс, что-то сломалось, повторите запрос"

# Сообщения об отсутствии занятий
NO_TODAY = "Сегодня занятий нет"
NO_TOMORROW = "Завтра занятий нет"
NO_THIS_WEEK = "На этой неделе занятий нет"
NO_NEXT_WEEK = "На следующей неделе занятий нет"

NO_LESSONS = "Занятий в расписании нет"

# Шаблоны для занятий
LESSON = string.Template(f"$lesson_type\n"
                         f"Время: $lesson_time\n"
                         f"Аудитория: $auditorium\n"
                         f"Проводит: $teacher\n\n")


import argparse
import logging
import os
import sys

from shipmaster.core.plugins import Platform, PluginManager
from shipmaster.core.builder import Builder
from shipmaster.core.config import BuildConfig

logger = logging.getLogger('shipmaster')

def run_command(args):
    config = BuildConfig.from_workspace(os.getcwd())
    builder = Builder(config, args, commit_info={})

def run_parser(parsers):
    p = parsers.add_parser("run", help="Run build stages.")
    p.add_argument('stage', help="Stage to build.")
    p.add_argument('--editable', help="Mount local sources instead of uploading a copy to container.", action='store_true')
    p.add_argument("--script", help="Output run script and exit.", action="store_true")
    p.add_argument("--run-all", help="Build parent layers if they don't exist.", action="store_true")
    p.add_argument("--rerun", help="Rerun this layer.", action="store_true")
    p.add_argument("--rerun-all", help="Rerun this layer and all parent layers.", action="store_true")
    p.set_defaults(command=run_command)
    return p

def argument_parser():

    parser = argparse.ArgumentParser(
        prog="shipmaster"
    )

    subparsers = parser.add_subparsers(dest='command')
    subparsers.required = True

    commands = {
        'run': run_parser(subparsers)
    }

    for plugin in PluginManager.plugin_classes:
        plugin.contribute_to_argparse(subparsers, commands)

    return parser

def parse_args(args):
    return argument_parser().parse_args(args)

def main():
    PluginManager.load(Platform.cli)
    parser = argument_parser()
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO)
    if hasattr(args, 'command'):
        config = BuildConfig.from_workspace(os.getcwd())
        args.command(args, config)
    else:
        parser.print_help()


"""users_table

Revision ID: d8314c4d9cc2
Revises: 249d63936022
Create Date: 2023-02-23 20:22:42.097435

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'd8314c4d9cc2'
down_revision = None
branch_labels = None
depends_on = None

def upgrade() -> None:
    op.create_table('users',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('name', sa.String(), nullable=True),
    sa.Column('created_at', sa.DateTime(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
    op.create_index(op.f('ix_users_name'), 'users', ['name'], unique=False)

def downgrade() -> None:
    op.drop_index(op.f('ix_users_name'), table_name='users')
    op.drop_index(op.f('ix_users_id'), table_name='users')
    op.drop_table('users')


# Faça um programa que leia 3 valores e diga se é possível que elas formem um triângulo ou não
cor = {'limpa': '\033[m',
       'vermelho': '\033[1;31m',
       'verde': '\033[1;32m'}
print('-=-' * 20)
print('Analisador de triângulos')
print('-=-' * 20)
r1 = float(input('Primeiro Segmento: '))
r2 = float(input('Segundo Segmento: '))
r3 = float(input('Terceiro Segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
    print('Os Segmentos acima {}PODEM{} formar um triângulo!'.format(cor['verde'], cor['limpa']))
else:
    print('Os Segmentos acima {}NÃO PODEM{} formar um triângulo!'.format(cor['vermelho'], cor['limpa']))


from PIL import ImageDraw, ImageFont, Image
import images2gif

font = ImageFont.truetype('fonts/IMFeENrm28P.ttf', 16)

def draw_text(text, fill, step):
	frames = []
	im = Image.new('RGBA', (32, 32), (0, 0, 0, 0))
	draw = ImageDraw.Draw(im)
	size = draw.textsize(text, font=font)
	count = int((size[0] + 32) / step)
	offset = 32

	for i in range(count):
		im = Image.new('RGBA', (32, 32), (0,0,0,0))
		draw = ImageDraw.Draw(im)
		draw.text((offset, 8), text, font=font, fill=fill)
		offset -= step
		frames.append(im)

	return frames

frames = draw_text('last year was better', (255, 255, 0), 3)
images2gif.writeGif("test.gif", frames)


from osgeo import gdal
import argparse
import sys

usage = '''
This is a Python wrapper of some of the options for http://www.gdal.org/gdal_translate.html
This is not intended to replace gdal_translate, but to help you learn how Python bindings work with GDAL

Example,
  gdal_translate.py -of VRT ../tiff/MY1DMM_CHLORA_2002-07.TIFF  output.vrt
  gdal_translate.py -of PNG ../tiff/MY1DMM_CHLORA_2002-07.TIFF  output.png

'''

parser = argparse.ArgumentParser(description='converts raster data between different formats', epilog = usage, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('src_dataset')
parser.add_argument('dst_dataset')
parser.add_argument('-of', '--format', help='Select the output format. The default is GeoTIFF (GTiff). Use the short format name.', required=False)
args = parser.parse_args()

if __name__ == '__main__':

  src_dataset = gdal.Open( args.src_dataset )
  if src_dataset is None:
      print('Could not open %s' % args.src_dataset)
      sys.exit( 1 )

  if args.format is None:
    format = 'GTiff'
  else:
    format = args.format
  driver = gdal.GetDriverByName( format )

  dst_dataset = driver.CreateCopy( args.dst_dataset, src_dataset, 0 )
  # Make sure any file handles are flushed to ensure file is written and closed
  dst_dataset = None