from models.gnn import GNN
from models.rephine_linear_model import RephineLinearClassifier
from models.topo_gnn import TopoGNN

def get_model(args):
    if args.gnn == "linear":
        model = RephineLinearClassifier(
            n_classes=args.num_classes,
            num_node_features=args.num_node_features,
            n_graph_features=args.n_graph_features,
            n_filtrations=args.num_filtrations,
            filtration_hidden=args.filtration_hidden,
            out_dim=args.out_dim,
            diagram_type=args.diagram_type,
            dim1=args.dim1,
            sig_filtrations=args.sig_filtrations,
        )
    elif args.gnn in ["gcn", "gin"]:
        if args.diagram_type in ["rephine", "standard"]:
            model = TopoGNN(
                hidden_dim=args.hidden_dim,
                depth=args.depth,
                num_node_features=args.num_node_features,
                num_classes=args.num_classes,
                gnn=args.gnn,
                num_filtrations=args.num_filtrations,
                filtration_hidden=args.filtration_hidden,
                out_ph_dim=args.out_dim,
                diagram_type=args.diagram_type,
                ph_pooling_type=args.ph_pooling_type,
                dim1=args.dim1,
                sig_filtrations=args.sig_filtrations,
                global_pooling=args.global_pooling,
                batch_norm=args.bn,
            )
        else:
            model = GNN(
                hidden_dim=args.hidden_dim,
                depth=args.depth,
                num_node_features=args.num_node_features,
                num_classes=args.num_classes,
                gnn=args.gnn,
                global_pooling=args.global_pooling,
                batch_norm=args.bn,
            )
    else:
        print("I dont know what to do with this combination of diagrams and GNN")

    return model


import os
from Bio import AlignIO
from Bio import Phylo
import shutil

names = []
with open("clean_aligned.phylip", "r") as infile:
    data = AlignIO.read(infile, "phylip")
    for record in data:
        if len(record.name) > 10:
            record.name = record.name[0:10]
        names.append(record.name)

os.chdir("..")
tree = Phylo.read("prune_tree/radseq_cpdna_stage2.tre", "nexus") # had to rename rigidum to rugosum
print(tree.get_terminals())
for tree_tip in tree.get_terminals():
    FOUND = False
    for name in names:
        if name in tree_tip.name:
            tree_tip.name = name
            FOUND = True
    if FOUND == False:
        print("Pruning", tree_tip.name)
        tree.prune(target = tree_tip.name)

Phylo.draw_ascii(tree)
Phylo.write(tree, "prune_tree/radseq_pruned.tre", "newick")
shutil.copyfile("prune_tree/radseq_pruned.tre", "paml/radseq_pruned.tre")


def measure_time(func):
    import timeit

    def wrapper(*args, **kwargs):
        time_start = timeit.default_timer()
        func(*args, **kwargs)
        print(timeit.default_timer() - time_start, 'seconds')

    return wrapper

@measure_time
def search(s, n):
    for i in n:
        if i in s:
            pass

def get_random_stack_needles(stack_size):
    stack_list = [random.random() for _ in range(stack_size)]
    needles_list = [random.choice(stack_list) for _ in range(500)]
    needles_list.extend([random.random() for _ in range(500)])

    return stack_list, needles_list

def get_dict_stack(stack_list):
    return dict(zip(stack_list, range(len(stack_list))))

if __name__ == '__main__':
    import random

    size_stack = [1000, 10000, 100000, 1000000]

    for size in size_stack:
        print('Size of stack: ', size)
        stack, needles = get_random_stack_needles(size)

        print('Search in list takes:', end=' ')
        search(stack, needles)

        print('Search in tuple takes:', end=' ')
        search(tuple(stack), needles)

        print('Search in dict takes:', end=' ')
        search(get_dict_stack(stack), needles)


import json
import jsonlines
import os

pdf_dir = '~/testdata'
summary_dir = '~/testdata.pages1'
pdf_dir = os.path.expanduser(pdf_dir)
summary_dir = os.path.expanduser(summary_dir)
print('pdf_dir=%s' % pdf_dir)
print('summary_dir=%s' % summary_dir)

def load_json(path):
    with open(path, 'r') as f:
        obj = json.load(f)
    return obj

def save_json(path, obj):
    with open(path, 'w') as f:
        json.dump(obj, f, indent=4, sort_keys=True)

def load_jsonl(path):
    with jsonlines.open(path, mode='r') as r:
       return list(r)

def save_jsonl(path, obj):
    with jsonlines.open(path, mode='w') as w:
        w.write_all(obj)

def base_name(path):
    base = os.path.basename(path)
    return os.path.splitext(base)[0]


from mediapipe import solutions
from mediapipe.framework.formats import landmark_pb2
import numpy as np
import matplotlib.pyplot as plt
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
import cv2

class MediapipeDetector:

    def __init__(self):
        '''
        初始化 MP_Detector 类别。

        初始化模型参数并创建脸部和姿势侦测器。

        参数:
        无

        返回:
        无
        '''
        # 初始化函式，设置模型参数
        self.input_image_width, self.input_image_height = 1, 1
        self.input_image = None
        # 建立脸部侦测器
        base_options_face = python.BaseOptions(model_asset_path='task/face_landmarker.task')
        options_face = vision.FaceLandmarkerOptions(base_options=base_options_face,
                                                    output_face_blendshapes=True,
                                                    output_facial_transformation_matrixes=True,
                                                    num_faces=1)
        self.detector_face = vision.FaceLandmarker.create_from_options(options_face)

        # 建立姿势侦测器
        base_options_pose = python.BaseOptions(model_asset_path='task/pose_landmarker_heavy.task')
        options_pose = vision.PoseLandmarkerOptions(
            base_options=base_options_pose,
            output_segmentation_masks=True)
        self.detector_pose = vision.PoseLandmarker.create_from_options(options_pose)

    def draw_face_landmarks_on_image(self, input_image, detection_result: str):
        '''
        在图像上绘制脸部标志点。

        在输入图像上绘制脸部标志点。

        参数:
        input_image (numpy.ndarray): 要绘制标志点的输入图像。
        detection_result (str): 包含脸部标志点的侦测结果。

        返回:
        numpy.ndarray: 带有绘制脸部标志点的图像。
        '''
        # 绘制脸部关键点于图像上
        face_landmarks_list = detection_result.face_landmarks

        for idx in range(len(face_landmarks_list)):
            face_landmarks = face_landmarks_list[idx]

            face_landmarks_proto = landmark_pb2.NormalizedLandmarkList()
            face_landmarks_proto.landmark.extend([
                landmark_pb2.NormalizedLandmark(x=landmark.x, y=landmark.y, z=landmark.z) for landmark in face_landmarks
            ])

            solutions.drawing_utils.draw_landmarks(
                image=input_image,
                landmark_list=face_landmarks_proto,
                connections=mp.solutions.face_mesh.FACEMESH_TESSELATION,
                landmark_drawing_spec=None,
                connection_drawing_spec=mp.solutions.drawing_styles.get_default_face_mesh_tesselation_style())
            solutions.drawing_utils.draw_landmarks(
                image=input_image,
                landmark_list=face_landmarks_proto,
                connections=mp.solutions.face_mesh.FACEMESH_CONTOURS,
                landmark_drawing_spec=None,
                connection_drawing_spec=mp.solutions.drawing_styles.get_default_face_mesh_contours_style())
            solutions.drawing_utils.draw_landmarks(
                image=input_image,
                landmark_list=face_landmarks_proto,
                connections=mp.solutions.face_mesh.FACEMESH_IRISES,
                landmark_drawing_spec=None,
                connection_drawing_spec=mp.solutions.drawing_styles.get_default_face_mesh_iris_connections_style())

        return input_image

    def draw_pose_landmarks_on_image(self, input_image, detection_result):
        '''
        在图像上绘制姿态标志点。

        在输入图像上绘制姿态标志点。

        参数:
        input_image (numpy.ndarray): 要绘制标志点的输入图像。
        detection_result (str): 包含姿态标志点的侦测结果。

        返回:
        numpy.ndarray: 带有绘制姿态标志点的图像。
        '''
        # 绘制姿势关键点于图像上
        pose_landmarks_list = detection_result.pose_landmarks

        for idx in range(len(pose_landmarks_list)):
            pose_landmarks = pose_landmarks_list[idx]

            pose_landmarks_proto = landmark_pb2.NormalizedLandmarkList()
            pose_landmarks_proto.landmark.extend([
                landmark_pb2.NormalizedLandmark(x=landmark.x, y=landmark.y, z=landmark.z) for landmark in pose_landmarks
            ])
            solutions.drawing_utils.draw_landmarks(
                input_image,
                pose_landmarks_proto,
                solutions.pose.POSE_CONNECTIONS,
                solutions.drawing_styles.get_default_pose_landmarks_style())

        return input_image

    def run_all(self, input_image):
        '''
        在输入图像上运行脸部和姿态侦测。

        在提供的输入图像上运行脸部和姿态侦测。

        参数:
        input_image (numpy.ndarray): 进行侦测的输入图像。

        返回:
        tuple: 包含两个元素的元组 - 脸部识别座标信息和姿态识别座标信息。
        '''
        # 执行所有侦测
        ImageFormat = mp.solutions.mediapipe.ImageFormat.SRGB
        image_file = mp.Image(image_format=ImageFormat.SRGB, data=input_image)
        detection_result_face = self.detector_face.detect(image_file)
        detection_result_pose = self.detector_pose.detect(image_file)
        self.input_image_width, self.input_image_height = input_image.shape[1], input_image.shape[0]
        self.input_image = input_image
        return detection_result_face, detection_result_pose

    def run_pose(self, input_image):
        '''
        在输入图像上运行姿态侦测。

        在提供的输入图像上运行姿态侦测。

        参数:
        input_image (numpy.ndarray): 进行侦测的输入图像。

        返回:
        str: 姿态识别座标信息。
        '''
        # 执行姿势侦测
        ImageFormat = mp.solutions.mediapipe.ImageFormat.SRGB
        image_file = mp.Image(image_format=ImageFormat.SRGB, data=input_image)
        detection_result_pose = self.detector_pose.detect(input_image)
        self.input_image_width, self.input_image_height = input_image.shape[1], input_image.shape[0]
        self.input_image = input_image
        return detection_result_pose

    def run_face(self, input_image):
        '''
        在输入图像上运行脸部侦测。

        在提供的输入图像上运行脸部侦测。

        参数:
        input_image (numpy.ndarray): 进行侦测的输入图像。

        返回:
        str: 脸部识别座标信息。
        '''
        # 执行脸部侦测
        ImageFormat = mp.solutions.mediapipe.ImageFormat.SRGB
        image_file = mp.Image(image_format=ImageFormat.SRGB, data=input_image)
        detection_result_face = self.detector_face.detect(self.input_image)
        self.input_image_width, self.input_image_height = input_image.shape[1], input_image.shape[0]
        self.input_image = input_image
        return detection_result_face

    def draw_blank(self, face, pose):
        '''
        在空白图像上绘制标志点。

        在具有相同尺寸的空白图像上绘制标志点，尺寸与输入图像相同。

        参数:
        face (str): 脸部识别座标信息。
        pose (str): 姿态识别座标信息。

        返回:
        numpy.ndarray: 带有绘制标志点的空白图像。
        '''
        # 绘制空白图像并添加关键点
        input_image_width, input_image_height = self.input_image_width, self.input_image_height
        blank_image = np.zeros((input_image_height, input_image_width, 3), dtype=np.uint8)
        blank_image_with_landmarks = self.draw_pose_landmarks_on_image(blank_image, pose)
        blank_image_with_landmarks = self.draw_face_landmarks_on_image(blank_image_with_landmarks, face)
        return blank_image_with_landmarks

    def draw_overlay(self, face, pose):
        '''
        在原始图像上叠加标志点。

        在原始输入图像上叠加标志点。

        参数:
        face (str): 脸部识别座标信息。
        pose (str): 姿态识别座标信息。

        返回:
        numpy.ndarray: 带有叠加标志点的原始图像。
        '''
        # 将关键点添加到原始图像上
        image_with_landmarks = self.draw_pose_landmarks_on_image(self.input_image, pose)
        image_with_landmarks = self.draw_face_landmarks_on_image(image_with_landmarks, face)
        return image_with_landmarks

    def draw_both(self, face, pose):
        '''
        在空白和原始图像上绘制标志点。

        在空白图像和原始输入图像上绘制标志点。

        参数:
        face (str): 脸部识别座标信息。
        pose (str): 姿态识别座标信息。

        返回:
        tuple: 包含两个元素的元组 - 带有绘制标志点的空白图像和带有绘制标志点的原始图像。
        '''
        # 绘制空白图像和原始图像上的关键点
        input_image_width, input_image_height = self.input_image_width, self.input_image_height
        blank_image = np.zeros((input_image_height, input_image_width, 3), dtype=np.uint8)
        blank_image_with_landmarks = self.draw_pose_landmarks_on_image(blank_image, pose)
        blank_image_with_landmarks = self.draw_face_landmarks_on_image(blank_image_with_landmarks, face)
        image_with_landmarks = self.draw_pose_landmarks_on_image(self.input_image, pose)
        image_with_landmarks = self.draw_face_landmarks_on_image(image_with_landmarks, face)
        return blank_image_with_landmarks, image_with_landmarks


from django.shortcuts import render
import json
from django.http import HttpResponse
import numpy as np
from collections import Counter, defaultdict
from django.contrib.staticfiles.templatetags.staticfiles import static
import os

from FindMe.settings import PROJECT_ROOT

def occurrences(list1):
    no_of_examples = len(list1)
    prob = dict(Counter(list1))
    for key in prob.keys():
        prob[key] = prob[key] / float(no_of_examples)
    return prob

def naive_bayes(training, outcome, new_sample):
    classes = np.unique(outcome)
    rows, cols = np.shape(tuple(training))
    likelihoods = {}
    for cls in classes:
        likelihoods[cls] = defaultdict(list)
    #
    class_probabilities = occurrences(outcome)

    for cls in classes:
        row_indices = np.where(outcome == cls)[0]
        subset = training[row_indices, :]
        r, c = np.shape(subset)
        for j in range(0, c):
            likelihoods[cls][j] += list(subset[:, j])

    for cls in classes:
        for j in range(0, cols):
            likelihoods[cls][j] = occurrences(likelihoods[cls][j])

    results = {}
    for cls in classes:
        class_probability = class_probabilities[cls]
        for i in range(0, len(new_sample)):
            relative_values = likelihoods[cls][i]
            if new_sample[i] in relative_values.keys():
                class_probability *= relative_values[new_sample[i]]
            else:
                class_probability *= 0
            results[cls] = class_probability
    print(results)
    print(results[0])
    print(results[1])
    try:
        ans = str(results[1] / (results[0] + results[1]) * 100)
    except ZeroDivisionError:
        ans = "NULL"
    return ans

# if __name__ == "__main__":
#     myarray = np.genfromtxt(r'training_dataset.csv', delimiter=',', dtype=None)
#     print(myarray)
#     outcome = np.genfromtxt(r'training_outcome.csv', delimiter=',', dtype=None)
#     # training   = np.asarray(((1,0,1,1),(1,1,0,0),(1,0,2,1),(0,1,1,1),(0,0,0,0),(0,1,2,1),(0,1,2,0),(1,1,1,1)));
#     # print(training)
#     # outcome    = np.asarray((0,1,1,1,0,1,0,1))
#     new_sample = np.asarray((3, 5, 1, 1))
#     naive_bayes(myarray, outcome, new_sample)

def index(request):
    q1 = int(request.GET.get('q1', 1))
    q2 = int(request.GET.get('q2', 1))
    q3 = int(request.GET.get('q3', 1))
    q4 = int(request.GET.get('q4', 1))
    print(q1)
    print(q2)
    print(q3)
    print(q4)
    myarray = np.genfromtxt(open(os.path.join(PROJECT_ROOT, 'training_dataset.csv')), delimiter=',', dtype=None)
    print(myarray)
    outcome = np.genfromtxt(open(os.path.join(PROJECT_ROOT, 'training_outcome.csv')), delimiter=',', dtype=None)
    # training   = np.asarray(((1,0,1,1),(1,1,0,0),(1,0,2,1),(0,1,1,1),(0,0,0,0),(0,1,2,1),(0,1,2,0),(1,1,1,1)));
    # print(training)
    # # outcome    = np.asarray((0,1,1,1,0,1,0,1))
    new_sample = np.asarray((q1, q2, q3, q4))
    result = naive_bayes(myarray, outcome, new_sample)
    data = {"data": result}
    json_data = json.dumps(data)
    return HttpResponse(json_data)


class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """

        nums = str(x)
        if x > 0:
            rev = nums[::-1]
            revString = rev.lstrip('0')
            if -2147483648 <= int(revString) <= 2147483647:
                return revString
            else:
                return 0
        elif x < 0:
            rev = nums[:0:-1]
            revStripped = rev.lstrip('0')
            revString = ('-' + revStripped)
            if -2147483648 <= int(revString) <= 2147483647:
                return revString
            else:
                return 0
        else:
            return 0


import threading
import logging
import sys
import traceback
from lpdm_event import LpdmInitEvent, LpdmKillEvent, LpdmRunTimeErrorEvent, LpdmBaseEvent
from simulation_logger import message_formatter

class DeviceThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None,
            device_id=None, DeviceClass=None, device_config=None, queue=None, supervisor_queue=None):
        threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
        self.args = args
        self.kwargs = kwargs

        self.device_id = device_id
        self.DeviceClass = DeviceClass
        self.device_config = device_config
        self.queue = queue
        self.supervisor_queue = supervisor_queue
        self.device = None

        self.logger = logging.getLogger("lpdm")

    def build_message(self, message="", tag="", value=""):
        """Build the log message string"""
        return message_formatter.build_message(
            message=message,
            tag=tag,
            value=value,
            time_seconds=None,
            device_id="device_thread"
        )

    def run(self):
        self.logger.debug(self.build_message("run the device thread for device id {}".format(self.device_id)))

        the_event = None
        # loop until a kill event is received
        while not isinstance(the_event, LpdmKillEvent):
            the_event = self.queue.get()

            try:
                if isinstance(the_event, LpdmInitEvent):
                    self.logger.debug(self.build_message("found an init event {}".format(the_event)))
                    self.init_device()
                elif not the_event is None:
                    self.device.process_supervisor_event(the_event)
                self.queue.task_done()
            except Exception as e:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                tb = traceback.format_exception(exc_type, exc_value, exc_traceback)
                self.logger.error("\n".join(tb))
                self.supervisor_queue.put(LpdmRunTimeErrorEvent("\n".join(tb)))
                self.queue.task_done()

    def init_device(self):
        """initialize the device"""
        # add the supervisor callback to the config dictionary
        self.add_supervisor_callback(self.device_config)
        self.device = self.DeviceClass(self.device_config)
        self.device.init()
        self.device.set_initialized(True)

    def add_supervisor_callback(self, config):
        config["broadcast"] = self.supervisor_callback

    def supervisor_callback(self, broadcast_message):
        """Broadcast a message from a device to the supervisor/other devices"""
        # put the message in the supervisor's queue
        if not isinstance(broadcast_message, LpdmBaseEvent):
            raise Exception(
                "Attempt to pass a non BroadcastMessage object to the supervisor ({})".format(broadcast_message)
            )
        self.supervisor_queue.put(broadcast_message)


import json
import logging
import os
import time
from datetime import date, timedelta

import boto3
import botocore
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

# Initialize and Connect to the AWS EC2 Service
try:
    ec2_client = boto3.client("ec2")
except Exception as e:
    logging.error("Error creating boto3 client: " + str(e))

try:
    s3 = boto3.client("s3")
except Exception as e:
    logging.error("Error creating boto3 client for s3: " + str(e))

try:
    ssm_client = boto3.client("ssm")
except Exception as e:
    logging.error("Error creating boto3 client for ssm:" + str(e))

def get_region_names():
    """
    Retrieves the region names dictionary from AWS Systems Manager Parameter Store.

    Returns:
    - dict: The region names dictionary.
    """
    region_path = os.environ["region_names_path"]

    try:
        response = ssm_client.get_parameter(Name=region_path)
        region_names = json.loads(response["Parameter"]["Value"])
        return region_names
    except Exception as e:
        logging.error("Error retrieving region names from Parameter Store: " + str(e))
        raise

# Get the region names dictionary
region_names = get_region_names()

def get_cost_and_usage_data(client, start, end, region, account_id):
    """
    Retrieves the unblended cost of a given account within a specified time period
    using the AWS Cost Explorer API.
    Args:
        client: A boto3.client object for the AWS Cost Explorer API.
        account_id: A string representing the AWS account ID to retrieve
        cost data for.
        region: A string representing the AWS Regionto retrieve cost data for.
        start_date: A string representing the start date of the time period to
        retrieve cost data for in YYYY-MM-DD format.
        end_date: A string representing the end date of the time period to
        retrieve cost data for in YYYY-MM-DD format.

    Returns:
        A dictionary representing the response from the AWS Cost Explorer API,
        containing the unblended cost of the specified account in specific AWS
        Region for the specified time period.
    Raises:
        ValueError: If there is a problem with the input data format,
        or if the calculation fails.
    """
    while True:
        try:
            response = client.get_cost_and_usage(
                TimePeriod={"Start": start, "End": end},
                Granularity="MONTHLY",
                Metrics=["UnblendedCost"],
                GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
                Filter={
                    "And": [
                        {"Dimensions": {"Key": "REGION", "Values": [region]}},
                        {
                            "Dimensions": {
                                "Key": "LINKED_ACCOUNT",
                                "Values": [account_id],
                            }
                        },
                    ]
                },
            )
            return response
        except client.exceptions.LimitExceededException:
            # Sleep for 5 seconds and try again
            time.sleep(5)
        except ValueError as ve:
            raise ValueError(
                f"ValueError occurred: {ve}.\nPlease check the input data format."
            )

def lambda_handler(event, context):

    """
    List 5 top most expensive services in provided aws region.
    Args:
        Account ID: AWS account id.
    Returns:
        It pushes the 5 most expensive services name and cost with AWS region
        to Prometheus using push gateway.
    Raises:
        KeyError: Raise error if data not pushed to prometheus.
    """

    account_id = event["account_id"]
    account_detail = event["account_detail"]
    # Cost of last 14 days
    cost_by_days = 14
    end_date = str(date.today())
    start_date = str(date.today() - timedelta(days=cost_by_days))

    # Initializing the list
    top_5_resources = []
    parent_list = []
    try:
        # Get the list of all regions
        regions = [
            region["RegionName"] for region in ec2_client.describe_regions()["Regions"]
        ]

    except Exception as e:
        logging.error("Error getting response from ec2 describe region api : " + str(e))
    # Loop through each region
    for region in regions:
        try:
            # region_name = region_names.get(region, "unknown region name")
            ce_region = boto3.client("ce", region_name=region)
        except Exception as e:
            logging.error("Error creating boto3 client: " + str(e))

        # Retrieve the cost and usage data for the defined time period
        try:
            cost_and_usage = get_cost_and_usage_data(
                ce_region, start_date, end_date, region, account_id
            )
        except Exception as e:
            logging.error("Error getting response from cost and usage api: " + str(e))

        # Extract the cost data
        cost_data = cost_and_usage["ResultsByTime"][0]["Groups"]

        # Sort the cost data in descending order
        sorted_cost_data = sorted(
            cost_data,
            key=lambda x: x["Metrics"]["UnblendedCost"]["Amount"],
            reverse=True,
        )

        # Get the top 5 most expensive resources
        top_5_resources = sorted_cost_data[:5]

        # Print the top 5 most expensive resources and their costs
        for resource in top_5_resources:
            resourcedata = {
                "Account": account_detail,
                "Region": f"{region} ({region_names.get(region, 'unknown region name')})",
                "Service": resource["Keys"][0],
                "Cost": resource["Metrics"]["UnblendedCost"]["Amount"],
            }
            parent_list.append(resourcedata)

        logging.info(parent_list)

    # Creating an empty list to store the data
    data_list = []

    # Adding the extracted cost data to the Prometheus
    # gauge as labels for service, region, and cost.
    try:
        registry = CollectorRegistry()
        gauge = Gauge(
            "Expensive_Services_Detail",
            "AWS Services Cost Detail",
            labelnames=["service", "cost", "region", "account_id"],
            registry=registry,
        )
        for i in range(len(parent_list)):
            service = parent_list[i]["Service"]
            region = parent_list[i]["Region"]
            cost = parent_list[i]["Cost"]
            account_id = parent_list[i]["Account"]
            data_dict = {"Service": service, "Region": region, "Cost": cost}

            # add the dictionary to the list
            data_list.append(data_dict)
            gauge.labels(service, cost, region, account_id).set(cost)

            # Push the metric to the Prometheus Gateway
            push_to_gateway(
                os.environ["prometheus_ip"], job=account_id, registry=registry
            )
        # convert data to JSON
        json_data = json.dumps(data_list)

        # upload JSON file to S3 bucket
        bucket_name = os.environ["bucket_name"]
        key_name = f'{os.environ["expensive_service_prefix"]}/{account_id}.json'
        try:
            s3.put_object(Bucket=bucket_name, Key=key_name, Body=json_data)
        except botocore.exceptions.ClientError as e:
            if e.response["Error"]["Code"] == "NoSuchBucket":
                raise ValueError(f"Bucket not found: {os.environ['bucket_name']}")
            elif e.response["Error"]["Code"] == "AccessDenied":
                raise ValueError(
                    f"Access denied to S3 bucket: {os.environ['bucket_name']}"
                )
            else:
                raise ValueError(f"Failed to upload data to S3 bucket: {str(e)}")
    except Exception as e:
        logging.error("Error initializing Prometheus Registry and Gauge: " + str(e))
        return {"statusCode": 500, "body": json.dumps({"Error": str(e)})}
    # Return the response
    return {"statusCode": 200, "body": json.dumps(parent_list)}


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

# Copyright (c) 2016 Victor Nea, Morvan Lassauzay, Matthieu Dien, Marwan Ghanem
# This file is part of dotEd.
#
# dotEd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# dotEd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with dotEd.  If not, see <http://www.gnu.org/licenses/>.

from PyQt5.Qt import QFile, QIODevice, QByteArray, QFileDialog
from PyQt5.QtWidgets import QMessageBox

class MainWindowController(object):
    '''The MainWindowController class defines the controller to manage
    a Doted (app)/MainWindow (view).

    Argument(s):
    model (Model): Model of the controller
    view (View): View of the controller
    textGraphController (TextGraphController): Ref to the TextGraphController

    Attribute(s):
    model (Model): Model of the controller
    view (View): View of the controller
    textGraphController (TextGraphController): Ref to the TextGraphController
    dotFilter (str): Filter to only show dot files
    '''

    dotFilter = "Dot files (*.dot)"

    def __init__(self, model, view, textGraphController):
        self.view = view
        self.view.controller = self
        self.model = model

        self.textGraphController = textGraphController

    def onImportFile(self):
        '''Import a file which contains a graph and build or rebuild the model
        with this graph.'''
        # Load graph from file with pydot_ng
        result = QFileDialog.getOpenFileName(None, "Import", None,
                                             MainWindowController.dotFilter)

        # Check if Open button has been pressed
        if len(result[0]) > 0:
            # Load dot file into a pydot graph
            # pydotGraph = graph_from_dot_file(result[0])

            # Clear graph (ask to save before importing here in a future
            # extension)
            self.onClearGraph()

    # Nodes and edges are send to the model in importGraph() in TextGraphView
    # If importGraph() is clean or change you could remove comments of theses
    # lines to build the model
#             # Create nodes from pydot nodes
#             for node in pydotGraph.get_nodes():
#                 self.model.addNode(node.get_name(), node.get_attributes())
#
#             # Create edges from pydot edges
#             for edge in pydotGraph.get_edges():
#                 self.model.addEdge(edge.get_source(), edge.get_destination())

            # Send graph's textual representation to the textual controller
            with open(result[0], "r") as file:
                self.textGraphController.importGraph(file.read())

    def onSaveFile(self):
        '''Save in a file the text description of the graph.'''
        # Export dialog
        result = QFileDialog.getSaveFileName(None, "Export", None,
                                             MainWindowController.dotFilter)

        # Check if Save button has been pressed
        if len(result[0]) > 0:
            filePath = result[0]

            # Create file
            dotFile = QFile(filePath)

            if (not dotFile.open(QIODevice.WriteOnly | QIODevice.Text)):
                QMessageBox.warning(None, "Export", "Export failed.")
            else:
                # Write the text from the TextGraphView into the file
                dotFile.write(QByteArray(self.textGraphController.view
                                             .getText().encode("utf_8")))
            dotFile.close()

    def onClearGraph(self):
        '''Clear the graph.'''
        self.model.clear()


class DM:
    """
    Discernibility Metric implementation based on definition from
    http://www.tdp.cat/issues11/tdp.a169a14.pdf
    """
    def __init__(self, anon_data, qi_index, k) -> None:
        self.anon_data = anon_data
        self.num_records = len(anon_data)
        self.qi_index = qi_index
        self.k = k
        self.num_qi = len(self.qi_index)

    def compute_eq(self):
        self.eq_count = {}
        for record in self.anon_data.values:
            qi_values = []
            for idx, qi_id in enumerate(self.qi_index):
                value = record[qi_id]
                qi_values.append(value)

            # Make set, because set is hashable
            eq = tuple(qi_values)

            # Count set of qi values
            if eq not in self.eq_count.keys():
                self.eq_count[eq] = 1
            else:
                self.eq_count[eq] += 1

    """
    The simplest kind of quality measure is based on the size of the equivalence classes.
    The discernibility metric assigns to each tuple t a penalty, which is determined by the size of the
    equivalence class containing t.
    """
    def compute_score(self):
        self.compute_eq()
        dm = 0
        for eq in self.eq_count.keys():
            eq_count = self.eq_count[eq]
            if eq_count >= self.k:
                dm += (eq_count * eq_count)
            else:
                dm += (eq_count * self.num_records)

        return dm


#!/usr/bin/env python

ans = 0;
cur = 0;
with open("input.txt") as file:
    for line in file:
        if line.rstrip() == "":
            cur = 0
            continue
        cur += int(line.rstrip())
        ans = max(cur, ans)

    print(ans)


from typing import Any
from dataStructure.binarySearchTree import Node

class AVLNode(Node):
    def __init__(self, key: Any):
        Node.__init__(self, key)
        self.depth = 0

    def update_depth(self):
        self.depth = max(self.left_depth(), self.right_depth()) + 1

    def left_depth(self) -> int:
        return self.left.depth if self.left else 0

    def right_depth(self) -> int:
        return self.right.depth if self.right else 0

    def __str__(self) -> str:
        return str(self.key)

def ll_rotation(node: AVLNode) -> AVLNode:
    if node is None:
        return None

    left = node.left
    node.left = left.right
    left.right = node

    node.update_depth()
    left.update_depth()

    return left

def rr_rotation(node: AVLNode) -> AVLNode:
    if node is None:
        return None

    right = node.right
    node.right = right.left
    right.left = node

    node.update_depth()
    right.update_depth()

    return right

def lr_rotation(node: AVLNode) -> AVLNode:
    if node is None:
        return None

    node.left = rr_rotation(node.left)
    return ll_rotation(node)

def rl_rotation(node: AVLNode) -> AVLNode:
    if node is None:
        return None

    node.right = ll_rotation(node.right)
    return rr_rotation(node)

class AVLTree(object):
    def __init__(self):
        self.root: AVLTree = None

    def __insert_node(self, tree: AVLNode, key: Any) -> AVLNode:
        if tree is None:
            tree = AVLNode(key)
        elif key < tree.key:
            tree.left = self.__insert_node(tree.left, key)
            if tree.left_depth() - tree.right_depth() == 2:
                if key < tree.left.key:
                    tree = ll_rotation(tree)
                else:
                    tree = lr_rotation(tree)
        elif key > tree.key:
            tree.right = self.__insert_node(tree.right, key)
            if tree.right_depth() - tree.left_depth() == 2:
                if key > tree.right.key:
                    tree = rr_rotation(tree)
                else:
                    tree = rl_rotation(tree)

        tree.update_depth()
        return tree

    def insert(self, key: Any):
        if self.root is None:
            self.root = AVLNode(key)
            return
        self.root = self.__insert_node(self.root, key)

    def __delete_node(self, tree: AVLNode, z: AVLNode) -> AVLNode:
        if tree is None or z is None:
            return None

        if z.key < tree.key:
            tree.left = self.__delete_node(tree.left, z)
            if tree.right_depth() - tree.left_depth() == 2:
                r: AVLNode = tree.right
                if r.left_depth() > r.right_depth():
                    tree = rl_rotation(tree)
                else:
                    tree = rr_rotation(tree)
        elif z.key > tree.key:
            tree.right = self.__delete_node(tree.right, z)
            if tree.left_depth() - tree.right_depth() == 2:
                l: AVLNode = tree.left
                if l.right_depth() > l.left_depth():
                    tree = lr_rotation(tree)
                else:
                    tree = ll_rotation(tree)
        else:
            if tree.left and tree.right:
                if tree.left_depth() > tree.right_depth():
                    max_node = tree.left.maximum()
                    tree.key = max_node.key
                    tree.left = self.__delete_node(tree.left, max_node)
                else:
                    min_node = tree.right.minimum()
                    tree.key = min_node.key
                    tree.right = self.__delete_node(tree.right, min_node)
            else:
                tree = tree.left if tree.left else tree.right

        return tree

    def delete(self, key: Any):
        node = self.search(key)
        if node is None:
            return

        self.__delete_node(self.root, node)

    def search(self, key: Any) -> AVLNode:
        if key is None or self.root is None:
            return None

        return self.root.search(key)


import requests
import time
import os
import threading

def fetcher(session, url):
    print(
        f"{os.getpid()} process | {threading.get_ident()} url : {url}"
    )  # getpid() : 현재 프로세스 id , get_ident() :
    with session.get(url) as response:
        return response.text

def main():
    # urls = ["https://naver.com", "https://google.com", "https://instagram.com"] * 50
    urls = ["https://google.com", "https://apple.com"] * 50

    with requests.session() as session:
        result = [fetcher(session, url) for url in urls]
        print(result)

if __name__ == "__main__":
    start = time.time()
    main()
    end = time.time()
    print("걸린 시간 : ", end - start)  # 20.22초


from os import error
from flask import Flask, request, render_template
# from loader import makeTokens
import loader

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def check():
    message = None
    website = None
    is_good = None
    is_bad = None
    if request.method == "POST":
        url_data = request.form.get("url_data")
        y = loader.check_is_pissing(url_data)
        message = y[0]
        website = url_data
        if message == "good":
            is_good = "True"
        else:
            is_bad = "True"

    return render_template("authentication.html",website = website, message = message, is_good= is_good, is_bad=is_bad)

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


## Script (Python) "browser_verificar_pysc"
##bind container=container
##bind context=context
##bind namespace=_
##bind script=script
##bind subpath=traverse_subpath
##parameters=user_agent
##title=
##
import string
a=-1
if string.rfind(user_agent, "MSIE")==a:
   return 0
else:
   return 1


import unittest
from unittest.mock import patch

import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')

from main import create_app, db
from main.models import Pokemon
from main.config import config

class RoutesTest(unittest.TestCase):
	def setUp(self):
		self.app = create_app(config['testDB'])
		self.app_context = self.app.app_context()
		self.app_context.push()
		db.create_all()
		self.client = self.app.test_client(use_cookies=True)

	def tearDown(self):
		db.session.remove()
		db.drop_all()
		self.app_context.pop()

	def test_home_page(self):
		response = self.client.get('/')
		self.assertEqual(response.status_code, 200)
		bad_response = self.client.get('/some_page')
		self.assertEqual(bad_response.status_code, 404)

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


# import libraries
import cv2
import mediapipe as mp
import time

# Class that will be used for tracking
class face_meshTracker():
    # init basic parameters that make face_mesh function
    def __init__(self, staticMode=False, maxFaces=1, refine_landmarks=False, minDetectionCon=0.5, minTrackCon=0.5):

        self.staticMode = staticMode
        self.maxFaces = maxFaces
        self.refine_landmarks = refine_landmarks
        self.minDetectionCon = minDetectionCon
        self.minTrackCon = minTrackCon

        # initialize mediapipe

        self.mpFaceMesh = mp.solutions.face_mesh
        self.faceMesh = self.mpFaceMesh.FaceMesh(self.staticMode, self.maxFaces, self.refine_landmarks, self.minDetectionCon, self.minTrackCon)
        self.mpDraw = mp.solutions.drawing_utils
        # DrawingSpec() allows us to customize how mediapipe draws detected face landmarks
        self.DrawSpec = self.mpDraw.DrawingSpec(thickness=1, circle_radius=1)

    # method to locate face mesh
    def facemeshFinder(self, img, draw=True):
        self.imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.faceMesh.process(self.imgRGB)
        faces = []
        if self.results.multi_face_landmarks:
            for faceLms in self.results.multi_face_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, faceLms, self.mpFaceMesh.FACEMESH_CONTOURS,
                        self.DrawSpec, self.DrawSpec)
                face = []
                for id,lm in enumerate(faceLms.landmark):
                #print(lm)
                    ih, iw, ic = img.shape
                    x,y = int(lm.x*iw), int(lm.y*ih)
                    # circle hand points detected
                    cv2.circle(img, (x, y), 1, (255, 0, 255), cv2.FILLED)

                    face.append([x,y])
                faces.append(face)
        return img, faces

# define main method to identify and track face mesh
def main():
    cap = cv2.VideoCapture(0)
    pTime = 0
    tracker = face_meshTracker(maxFaces=2)
    while True:
        success, img = cap.read()
        img, faces = tracker.facemeshFinder(img)
        if len(faces)!= 0:
            print(faces[0])

        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime
        cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
                (255, 0, 255), 3)

        cv2.imshow('Video', img)
        k = cv2.waitKey(1)
        if k == 27:
            break

# execute main method to identify and track
if __name__ == '__main__':
    main()


import matplotlib.pyplot as plt
import numpy as np
import requests
from img_utility import *
from pseudo_utility import *

data = np.load('tiny_nerf_data.npz')
images = data['images']
log_images = []
#images = np.array(logify_image(images)) #logify crude
for img in images:
    img1 = srgb_to_xyz(img, max_val=255)
    img1 = float_to_tiff(img1)
    #img1 = bgr_to_rgb(img1)
    img1 = tiff_to_log(img1)
    log_images.append(img1)
images = np.array(log_images)
poses = data['poses']
focal = data['focal']
H, W = images.shape[1:3]

print(images.shape, poses.shape, focal)

testimg, testpose = images[101], poses[101]
images = images[:100,...,:3]
poses = poses[:100]

plt.imshow(testimg)
plt.show()

print(testimg.shape)
print(testimg[50])
"""# Optimize NeRF"""
#Introducing, Heather's code

# img = testimg
# img = srgb_to_xyz(img, max_val=1)
# img = float_to_tiff(img)
# img = bgr_to_rgb(img)
# #img = float_to_tiff(img)
# #img = srgb_to_xyz(img, max_val=1)
# max_16_bit_val = 65535
# sixteen_bit_image = img# (np.floor_divide((img * max_16_bit_val), 1)).astype(np.uint16)
# plt.imshow(img)
# plt.title('linear')
# plt.show()
#
# #logify
# #def tiff_to_log(sixteen_bit_image):
# # sixteen_bit_image = sixteen_bit_image.astype(np.float32)
# # sixteen_bit_image[sixteen_bit_image!=0] = np.log(sixteen_bit_image[sixteen_bit_image!=0])
# #return sixteen_bit_image
# img = tiff_to_log(sixteen_bit_image)
# plt.imshow(sixteen_bit_image)
# plt.title('log image')
# plt.show()
#Introducing, Heather's code
#icecream float
max_val = np.max(testimg)
# max_val = 255/max_val
# print(max_val)
# new_image = (np.floor_divide((testimg * max_val), 1)).astype(np.uint8)
# plt.imshow(new_image)
# plt.title('new image')
# plt.show()
logdiv = 11.4
displog_image = (testimg / logdiv) * 255
displog_image = displog_image.astype("uint8")
#displog_image = cv2.cvtColor(displog_image, cv2.COLOR_BGR2RGB)
plt.imshow(displog_image)
plt.title('log view new')
plt.show()


import IPython.display as display
from PIL import Image
import os
import pathlib
import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt
import pdb

print("TensorFlow Version: {}".format(tf.__version__))

AUTOTUNE = tf.data.experimental.AUTOTUNE

image_dir = "/Users/thibaultdesfontaines/data/leaf-classification/new_images"
image_dir = pathlib.Path(image_dir)

CLASS_NAMES = [x for x in sorted(os.listdir(str(image_dir))) if x[0] != '.']
CLASS_NAMES = np.array(CLASS_NAMES)
print("Number of classes: {}".format(len(CLASS_NAMES)))

image_count = 0
for class_ in [x for x in os.listdir(image_dir) if x[0]!='.']:
    for image_ in os.listdir(os.path.join(image_dir, class_)):
        image_count += 1
print("Image count:", image_count)

image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)

BATCH_SIZE = 32
IMG_HEIGHT = 224
IMG_WIDTH = 224
STEPS_PER_EPOCH = np.ceil(image_count/BATCH_SIZE)

train_data_gen = image_generator.flow_from_directory(
        directory=str(image_dir),
        batch_size=BATCH_SIZE,
        shuffle=True,
        target_size=(IMG_HEIGHT, IMG_WIDTH),
        classes=list(CLASS_NAMES))

def get_label(file_path):
    # convert the path to a list of path components
    parts = tf.strings.split(file_path, os.path.sep)
    # The second to last is the class-directory
    return parts[-2] == CLASS_NAMES

def decode_img(img):
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_jpeg(img, channels=1)
    # Use `convert_image_dtype` to convert to floats in the [0,1] range.
    img = tf.image.convert_image_dtype(img, tf.float32)
    # resize the image to the desired size.
    return tf.image.resize(img, [IMG_WIDTH, IMG_HEIGHT])

def process_path(file_path):
    label = get_label(file_path)
    # load the raw data from the file as a string
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img, label

def process_test_path(file_path):
    # load the raw data from the file as a string
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img

list_ds = tf.data.Dataset.list_files(str(image_dir/'*/*'))
# Set `num_parallel_calls` so multiple images are loaded/processed in parallel.
labeled_ds = list_ds.map(process_path, num_parallel_calls=AUTOTUNE)

def prepare_for_training(ds, cache=True, shuffle_buffer_size=1000):
    if cache:
        if isinstance(cache, str):
            ds = ds.cache(cache)
        else:
            ds = ds.cache()
    ds = ds.shuffle(buffer_size=shuffle_buffer_size)
    ds = ds.repeat()
    ds = ds.batch(BATCH_SIZE)
    ds = ds.prefetch(buffer_size=AUTOTUNE)
    return ds

train_ds = prepare_for_training(labeled_ds)

image_batch, label_batch = next(iter(train_ds))
train_images = tf.squeeze(image_batch)
# images_batch is TensorShape([32, 224, 224, 1])

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(224, 224)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(99)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(train_images, tf.where(label_batch)[:, 1:], epochs=20)

# Test on new images
test_dir = pathlib.Path("/Users/thibaultdesfontaines/data/leaf-classification/test_images")

test_data_gen = image_generator.flow_from_directory(
        directory=str(test_dir),
        batch_size=BATCH_SIZE,
        shuffle=True,
        target_size=(IMG_HEIGHT, IMG_WIDTH),
        classes=list(CLASS_NAMES))

test_ds = tf.data.Dataset.list_files(str(test_dir/'*'))
test_ds = test_ds.map(process_test_path, num_parallel_calls=AUTOTUNE)
test_ds = prepare_for_training(test_ds)

test_batch = next(iter(test_ds))
test_batch = tf.squeeze(test_batch)

predictions = np.array(model.apply(test_batch))

755-Image classification/555-Prototype an image classification model in keras/keras_prototype.py


from six.moves.BaseHTTPServer import BaseHTTPRequestHandler
from six.moves.urllib_parse import parse_qsl, urlparse

def parse_auth_response_url(url):
    query_s = urlparse(url).query
    form = dict(parse_qsl(query_s))
    return tuple(form.get(param) for param in ["state", "code"])

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.server.auth_code = self.server.error = None
        try:
            state, auth_code = parse_auth_response_url(self.path)
            self.server.state = state
            self.server.auth_code = auth_code
        except Exception as err:
            self.server.state = err.state
            self.server.error = err.error

        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.end_headers()

        if self.server.auth_code:
            status = "successful"
        elif self.server.error:
            status = "failed ({})".format(self.server.error)
        else:
            self._write("
Invalid request
")
            return

        self._write(f"""

Authentication status: {status}

This window can be closed.

""")

    def _write(self, text):
        return self.wfile.write(text.encode("utf-8"))

    def log_message(self, format, *args):
        return


from itertools import groupby

def removeDuplicates(s):
    stack = []
    for c in s:
        if stack and stack[-1] == c:
            stack.pop()
        else:
            stack.append(c)
    return "".join(stack)
# Runtime: 107 ms, faster than 55.27% of Python3 online submissions for Remove All Adjacent Duplicates In String.
# Memory Usage: 14.9 MB, less than 47.44% of Python3 online submissions for Remove All Adjacent Duplicates In String.

s = "abbaca"
print(removeDuplicates(s))  # "ca"
s = "azxxzy"
print(removeDuplicates(s))  # "ay"


import time
from multiprocessing import Pool, cpu_count

def factorize(number):
    factors = []
    for i in range(1, number + 1):
        if number % i == 0:
            factors.append(i)
    return factors

def factorize_parallel(number):
    factors = []
    for i in range(1, number + 1):
        if number % i == 0:
            factors.append(i)
    return factors

if __name__ == "__main__":
    numbers = [128, 255, 99999, 10651060]

    # Синхронно
    start_time = time.time()
    result_sync = [factorize(number) for number in numbers]
    end_time = time.time()

    print("Синхронна версія:")
    for i, number in enumerate(numbers):
        print(f"Число {number} розкладається на: {result_sync[i]}")
    print(f"Час виконання: {end_time - start_time:.4f} секунд")

    # Паралельно
    num_cores = cpu_count()
    start_time = time.time()
    with Pool(num_cores) as pool:
        result_parallel = pool.map(factorize_parallel, numbers)
    end_time = time.time()

    print("\nПаралельна версія:")
    for i, number in enumerate(numbers):
        print(f"Число {number} розкладається на: {result_parallel[i]}")
    print(f"Час виконання: {end_time - start_time:.4f} секунд")


from django.db.models.query import QuerySet
from django.shortcuts import render,get_object_or_404,redirect
from django.db.models import Q
from django.urls import reverse_lazy
from django.http import HttpResponseRedirect
from .forms import CommentForm
from django.views import View
from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin
from django_searchbar.mixins import SearchBarViewMixin
from django.views.generic.edit import UpdateView, DeleteView
from django.views.generic import ListView
from .models import Post, Comment,UserProfile, Basic, ControlFlow
from django.core.paginator import Paginator

#This is about me view
class AboutMe(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'blog/about_me.html')

#This is python-content view
class TableOfContent(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'blog/python_content.html')

class SearchView(View):
    def get(self, request, *args, **kwargs):
        query = self.request.GET.get('query')
        post_list = Post.objects.filter(
            Q(title__icontains=query) | Q(content__icontains=query)
        )

        context ={
            'query':query,
            'post_list':post_list,

        }
        return render(request, 'blog/search_post.html', context)
'''
class SearchView(ListView):
    Model = Post
    template_name = 'blog/search_post.html'

    def get_queryset(self): # new
        query = self.request.GET.get('query')
        post_list = Post.objects.filter(
            Q(title__icontains=query)  #Q(title__icontains=query) | Q(author__icontains=query)
        )
        return post_list
 '''

#This is for postlist
class PostListView(View):
    def get(self, request, *args, **kwargs):
        posts = Post.objects.all().order_by('-created_on')
        paginator = Paginator(posts, 4)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)

        context = {
            'page_obj': page_obj,

        }
        return render(request, 'blog/index.html', context)

   #This detail view and comments
class PostDetailView(View):
    def get(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)
        template_name = 'blog/post_detail.html'
        form = CommentForm()

        comments = Comment.objects.filter(post=post).order_by('-created_on')
        context = {
            'post':post,
            'form': form,
            'comments': comments,

        }

        return render(request, template_name, context)

    def post(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)
        template_name = 'blog/post_detail.html'
        form = CommentForm(request.POST)
        new_comment = None

        if form.is_valid:
            new_comment = form.save(commit=False)
            new_comment.author = request.user
            new_comment.post = post
            new_comment.save()

        comments = Comment.objects.filter(post=post).order_by('-created_on')

        context = {
            'post': post,
            'form': form,
            'comments': comments,
        }

        return render(request, template_name, context)

#View for replying comment
class ReplyCommentView(View):
    def post(self, request, pk, post_pk, *args, **kwargs):
        post = Post.objects.get(pk=post_pk)
        parent_comment = Comment.objects.get(pk=pk)
        form = CommentForm(request.POST)

        if form.is_valid:
            new_comment = form.save(commit=False)
            new_comment.author = request.user
            new_comment.post = post
            new_comment.parent = parent_comment
            new_comment.save()

        return redirect ('post_detail', pk=post_pk )

#This view is for profile
class ProfileView(View):
    def get(self, request, pk, *args, **kwargs):
        profile = UserProfile.objects.get(pk=pk)
        user = profile.user
        posts = Post.objects.filter(author=user).order_by('-created_on')

        '''followers = profile.followers.all()

        if len(followers) == 0:
            is_following = False
        for follower in followers:
            if follower == request.user:
                is_following = True
                break
            else:
                is_following = False

        number_of_followers = len(followers)'''

        context = {
            'user': user,
            'profile': profile,
            'posts': posts,
           # 'number_of_followers':number_of_followers,
            #'is_following': is_following,
        }

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

 # this for Editing profile
class ProfileEditView(UpdateView):
    model = UserProfile
    fields = ['name','birth_date','bio','location','picture']
    template_name = 'blog/profile_edit.html'

    def get_success_url(self):
        pk = self.kwargs['pk']
        return reverse_lazy('profile', kwargs={'pk': pk})

    def test_func(self):
        profile = self.get_object()
        return self.request.user == profile.user

class AddLike(LoginRequiredMixin,View):
    def post(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)

        is_dislike = False
        #1..iterate through loop
        for dislike in post.dislikes.all():
            if dislike == request.user:
                is_dislike = True
                break

        if is_dislike:
            post.dislikes.remove(request.user)
        #for likes
        is_like = False

        for like in post.likes.all():
            if like == request.user:
                is_like = True
                break
        if not is_like:
            post.likes.add(request.user)

        if is_like:
            post.likes.remove(request.user)

        next = request.POST.get('next', '/')
        return HttpResponseRedirect(next)

class DisLike(LoginRequiredMixin,View):
    def post(self, request, pk, *args, **Kwargs):
        post = Post.objects.get(pk=pk)

        is_like = False

        for like in post.likes.all():
            if like == request.user:
                is_like = True
                break

        if is_like:
            post.likes.remove(request.user)

        is_dislike = False

        for dislike in post.dislikes.all():
            if dislike == request.user:
                is_dislike = True
                break

        if not is_dislike:
            post.dislikes.add(request.user)

        if is_dislike:
            post.dislikes.remove(request.user)

        next = request.POST.get('next', '/')
        return HttpResponseRedirect(next)

class BasicView(View):
     def get(self, request, *args, **kwargs):
         basics = Basic.objects.all()
         context = {
             'basics': basics
         }
         return render(request, 'blog/basics_of_programming.html', context)

class ControlFlowView(View):
    def get(self, request, *args, **kwargs):
        controlflows = ControlFlow.objects.all()
        context = {
            'controlflows': controlflows
        }
        return render(request, 'blog/control_flow.html', context)

'''
class Postlist(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'blog/index.html'

#class PostDetail(generic.DetailView):
   # model = Post
   # template_name = 'post_detail.html'

def post_detail(request, slug):
    template_name = 'blog/post_detail.html'
    post = get_object_or_404(Post, slug=slug)
    comments = post.comments.filter(active=True).order_by("-created_on") #queryset retrives all the approved comments from the database
    new_comment = None # initializing new comments

    #Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST) # holds the input data from user while commenting
        if comment_form. is_valid():

            #Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            #Assign the current post to the comment
            new_comment.post = post
            #save the comment to the database
            new_comment.save()

    else:
        comment_form = CommentForm()

    return render(request, template_name, {"post": post, "comments": comments, 'new_comment': new_comment, 'comment_form': comment_form})

    '''


#!/usr/bin/env python

import json

def main():
    d = json.load(open('good_api.json'))
    entries = d['entries']

    print('books by Frank Herbert written before 1980')
    for entry in entries:
        if entry['copyright'] < 1980:
            if entry['author'] == 'Frank Herbert':
                print(entry['book'])

    print([entry for entry in entries if
     entry['author'] == 'Frank Herbert' and
     entry['copyright'] < 1980])

if __name__ == "__main__":
    main()


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

# @Time    : 2018/12/26 19:47
# @Author  : WangKang

import os
import time

def TimeStampToTime(timestamp):
    timeStruct = time.localtime(timestamp)
    return time.strftime('%Y-%m-%d %H:%M:%S',timeStruct)

def file_size(file_path):
    # 获取文件大小 获取到的文件大小为：字节（B）千字节（KB）
    size = os.path.getsize(file_path)
    if size < 1024:
        size = str(size) + "byte"
    elif size >= 1024 and size < 1024 ** 2:
        size = str(round(size / float(1024), 2)) + "K"
    elif size >= 1024 ** 2 and size < 1024 ** 3:
        size = str(round(size / float(1024 ** 2), 2)) + "M"
    else:
        size = str(round(size / float(1024 ** 3), 2)) + "G"
    return size

def file_info(file):
    create_time = TimeStampToTime(os.path.getctime(file))
    size = file_size(file)
    return [create_time, size, 'admin']

if __name__ == "__main__":
    file_info('upload/123.txt')


from src.build import cowgol
from src.toolchains import TOOLCHAINS
from build.ab2 import export

PROGRAMS = [
    "argv",
    "file",
    "filetester",
    "helloworld",
    "icando",
    "mandel",
]

items = {}
for toolchain in TOOLCHAINS:
    toolchain.materialise()
    for prog in PROGRAMS:
        t = cowgol(
            name=prog + "-for-" + toolchain.localname,
            srcs="./" + prog + ".cow",
            toolchain=toolchain,
        )

        items[
            f"bin/examples/{prog}-for-{toolchain.localname}{toolchain.binext}"
        ] = t

export(name="examples", items=items)


from flask import abort, redirect, render_template
from http import HTTPStatus
from yacut import app
from yacut.forms import URLForm
from yacut.models import URLMap
from yacut.error_handlers import ShortAnFound

@app.route('/', methods=['GET', 'POST'])
def index_view():
    """View-функция главной страницы."""
    form = URLForm()
    if not form.validate_on_submit():
        return render_template(
            'index.html',
            form=form
        )
    short = form.custom_id.data
    return render_template(
        'index.html',
        form=form,
        short_link=URLMap.create(
            original=form.original_link.data,
            short=short,
            validation_required=False,
        ).get_absolute_short_url()
    )

@app.route('/<string:short>', methods=['GET'])
def redirect_to_original_url(short):
    """Переадресация."""
    try:
        return redirect(
            URLMap.get_original_url(short),
            code=HTTPStatus.FOUND
        )
    except ShortAnFound:
        abort(HTTPStatus.NOT_FOUND)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 16:49:40 2018

@author: zeba
"""
"""
The Button widget is used to add buttons in a Python application.
These buttons can display text or images that convey the purpose of the buttons.
You can attach a function or a method to a button, which is called automatically when you click the button.

Syntax: w = Button ( master, option=value, ... )

Parameters:
    master: This represents the parent window.
    options: There are many options for this widget. These options can be used as key-value pairs separated by commas
"""
import tkinter as  tk
from tkinter import messagebox as msg
root = tk.Tk()
def hello():
    msg.showinfo("Hello", "Hello World")
    root.destroy()
B1 = tk.Button(root, text = "Hello", command = hello)
label = tk.Label(root,text="Hello World!")
B1.pack()
label.pack()
root.mainloop()

module 13- GUI Programming with Tkinter/tkinter_button.py


import logging
import socket
import sys
import zeroconf

def init_logger():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    handler = logging.StreamHandler(sys.stderr)
    formatter = logging.Formatter(
        '%(asctime)s [%(levelname)s] %(message)s (at %(filename)s:%(lineno)d)')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger

class Util:

    @classmethod
    def pretty(cls, x):
        if isinstance(x, zeroconf.ServiceInfo):
            try:
                srv = x.server
                addr = socket.inet_ntoa(x.address)
                return '<ServiceInfo server=%s, address=%s>' % (srv, addr)
            except Exception:
                return str(x)
        else:
            return str(x)


from django.shortcuts import render
from django.http import HttpResponse
import requests

# Create your views here.

def myMovie(request):
    # 获取城市信息
    #
    if request.method == 'GET':
        response = requests.get('https://api.map.baidu.com/location/ip?ak=KHkVjtmfrM6NuzqxEALj0p8i1cUQot6Z')

        response_dic = response.json()
        city = response_dic['content']['address_detail']['city']
    else:
        # 如果发现请求方式是post方式  就可以认为是form表单发送的请求
        # 那么直接获取form表单里面name值为city的input标签里面的内容
        city = request.POST['city']
    # 拼接url 获取全部电影信息
    movieUrl = 'http://api.map.baidu.com/telematics/v3/movie?qt=hot_movie&location={}&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&output=json'.format(city)
    movieData = requests.get(movieUrl).json()
    # 判断电影信息是否请求成功
    if movieData['error'] == 0:
        all_movies = movieData['result']['movie']
        context = {
            'city':city,
            'allMovies':all_movies
        }
    else:
        context = {
            'city':city,
            'error':'无法获取当前城市的电影信息'
        }
    return render(request,'index.html',context)


import asyncio
import asqlite
import logging
import config
import logging.handlers
import os

from typing import List, Optional

import discord
from discord.ext import commands
from aiohttp import ClientSession

initial_extensions = config.initial_extensions

class FileManager(commands.Bot):

    def __init__(self, *args, db_pool):
        allowed_mentions = discord.AllowedMentions(roles=False, everyone=True, users=True)
        intents = discord.Intents(
            guilds=True,
            members=True,
            bans=True,
            emojis=True,
            voice_states=True,
            messages=True,
            reactions=True,
            message_content=True,
        )
        super().__init__(
            command_prefix="-",
            description="Gestion des CER pour la A2 Informatique",
            pm_help=None,
            help_attrs=dict(hidden=True),
            chunk_guilds_at_startup=False,
            heartbeat_timeout=150.0,
            allowed_mentions=allowed_mentions,
            intents=intents,
            enable_debug_events=True,

        )

        self.db_pool = db_pool

    async def setup_hook(self) -> None:

        for extension in initial_extensions:
            print(f"loading {extension}")
            await self.load_extension(extension)

async def main():

    logger = logging.getLogger('discord')
    logger.setLevel(logging.INFO)

    handler = logging.handlers.RotatingFileHandler(
        filename='discord.log',
        encoding='utf-8',
        maxBytes=32 * 1024 * 1024,  # 32 MiB
        backupCount=5,  # Rotate through 5 files
    )
    dt_fmt = '%Y-%m-%d %H:%M:%S'
    formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    async with asqlite.connect('databases/filemanager.db') as pool:
        async with FileManager(commands.when_mentioned, db_pool=pool) as bot:
            await bot.start(config.token)

# For most use cases, after defining what needs to run, we can just tell asyncio to run it:
asyncio.run(main())


from django.urls import path
from .views import *

from management.views import Statistic, Shop_info, Shop_stat, Prod_info, Prod_stat, Comments_info

urlpatterns = [
    path('', Manage.as_view(), name='manage_url'),
    path('statistics/', Statistic.as_view(), name='statistics_url'),
    path('shop_info/<str:id>/', Shop_info.as_view(), name='shop_info_url'),
    path('shop_stat/<str:id>/', Shop_stat.as_view(), name='shop_stat_url'),
    path('prod_info/<str:id>/', Prod_info.as_view(), name='prod_info_url'),
    path('prod_stat/<str:id>/', Prod_stat.as_view(), name='prod_stat_url'),
    path('comments_info/<str:id>/', Comments_info.as_view(), name='comments_stat_url')
]


# код работы с БД
# суть заключается изменении data полученной из внешнего кода здесь и запись в файл уже в коде извне
import json
from datetime import datetime  # для доступа к дате и времени сейчас
import datetime as delta  # для доступа к переменной delta time

# запись в лог
def write_logs(mes):
    with open("Logs.txt", 'a', encoding='utf-8') as logs:
        logs.writelines(mes + "\n")

# удаление дедлайна под именем name, принимает также data из внешнего кода
def delete_deadline(name, data, user_id):
    count = 0  # счетчик для имитации цикла for с индексами, требуется для pop
    mes = ""  # сообщение об исходе операции
    found = False  # найден ли дедлайн с данным именем
    for x in data['Deadlines']:
        if x['name'] == name and x['userId'] == user_id:
            item = data['Deadlines'].pop(count)  # достаем дедлайн из словаря, тем самым красиво удаляя его
            found = True
            break
        count += 1
    if found:
        mes = 'Дедлайн успешно завершен!'
        # лог об успешном удалении
        log = datetime.now().strftime("%d.%m.%Y %H:%M:%S") + " user " + str(item['userId']) + " deleted deadline: " \
              + name + "\n"
        write_logs(log)
    else:  # если дедлайн не найден
        mes = "Введённого Вами дедлайна не существует!"
    # записываем данные в файл на всякий пожарный
    with open('Database.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    return mes, data

# удаление просроченного дедлайна
def delete_exp_deadline(name, data, user_id):
    # суть работы такая же как в обычном удалении
    count = 0
    for x in data['Deadlines']:
        if x['name'] == name and x['userId'] == user_id:
            data['Deadlines'].pop(count)
            break
        count += 1
    with open('Database.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    return data

# добавление дедлайна, аргументами принимает id дедлайна, имя, id пользователя, описание, дату окончания,
# время уведомления, саму БД
def add_deadline(id, name, userId, description, expDate, alarmTime, data):
    notific = datetime.now().strftime("%d.%m.%Y")  # ставим дату, когда бот в след. раз уведомит пользователя (сегодня)
    if datetime.now().time() > datetime.strptime(alarmTime, "%H:%M:%S").time():  # если время уведомления сегодня уже
        # прошло, то следующее уведомление переносится на завтра
        notific = (datetime.now() + delta.timedelta(days=1)).strftime("%d.%m.%Y")
    # добавляем запись в словарь
    data['Deadlines'].append(
        {
            "id": id,
            "name": name,
            "userId": userId,
            "description": description,
            "expDate": expDate,
            "alarmTime": alarmTime,
            "lastNotificationDate": notific
        }
    )
    return data

# добавление пользователя, принимает id пользователя, его имя в телеграмме (зачем оно вообще хз) и БД
def add_user(id, name, data):
    isok = True                        # новый ли пользователь
    for x in data["Users"]:
        if x["id"] == id:              # проверяем есть ли пользователь в БД
            isok = False
    if isok:
        data["Users"].append(
            {
                "id": id,
                "name": name
            }
        )
        # добавляем список флагов для пользователя
        data["UsersFlags"][str(id)] = {
            "isAddingDeadline": False,
            "choosingWhatToDelete": False
        }
        log = datetime.now().strftime("%d.%m.%Y %H:%M:%S") + " user " + str(id) + " is added. Name: " + name + "\n"
        write_logs(log)
        with open('Database.json', 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
    return data


""""Hit the target
given a matrix n x n (2-7), determine if the arrow is directed to the target (x).
There will be only 1 arrow '>' and 1 target 'x'
An empty spot will be denoted by a space " ", the target with a cross "x", and the scope ">"
Examples:
given matrix 4x4:
[
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '], --> return true
[' ', '>', ' ', 'x'],
[' ', ' ', ' ', ' ']
]
given matrix 4x4:
[
[' ', ' ', ' ', ' '],
[' ', '>', ' ', ' '], --> return false
[' ', ' ', ' ', 'x'],
[' ', ' ', ' ', ' ']
]

given matrix 4x4:
[
[' ', ' ', ' ', ' '],
[' ', 'x', '>', ' '], --> return false
[' ', '', ' ', ' '],
[' ', ' ', ' ', ' ']
]

In this example, only a 4x4 matrix was used, the problem will have matrices of dimensions from 2 to 7
Happy hacking as they say!

Tests:
    >>> solution([['>', ' '], [' ', 'x'],])
    False

    >>> solution([[' ', ' ', ' ', ' ', ' '],[' ', ' ', ' ', ' ', ' '],[' ', ' ', ' ', ' ', ' '],[' ', ' ', '>', ' ', 'x'],[' ', ' ', '', ' ', ' ']])
    True

    >>>
"""

def solution(mtrx):
    # 1. iterate through each item in the nested lists
    # 2. Find location of target
    # 3. Compare location of target to location of pointer
    # 4. If the location of target is greater than pointer, return True

    # MISSED CONSIDERATIONS:
        # Pointer and target need to be in the same list

    for lst in mtrx:
        if 'x' in lst and '>' in lst:
            print('both')
        else:
            print('nope')

    #         for item in lst:
    #             if item == 'x':
    #                 target_idx = lst.index('x')
    #             elif item == '>':
    #                 pointer_idx = lst.index('>')

    # if target_idx > pointer_idx:
    #     return True
    # return False

if __name__ == '__main__':
    import doctest
    if doctest.testmod().failed == 0:
        print('\n On Target ðŸŽ¯ \n')


from ._experiment import *
from ._train import *
from ._load import *
from ._deploy import *

__author__ = 'Marko van Treeck'
__copyright__ = 'Copyright 2021, Kather Lab'
__credits__ = [
        'Amelie Echle',
        'Céline Nicole Heinz',
        'Chiara Loeffler',
        'Didem Cifci',
        'Jakob Nikolas Kather',
        'Marko van Treeck',
        'Oliver Lester Saldanha',
        'Tobias Paul Seraphin',
        'Hannah Sophie Muti',
    ]
__license__ = 'MIT'
__version__ = '0.10.0rc0'
__maintainer__ = 'Marko van Treeck'
__email__ = 'markovantreeck@gmail.com'


def getNode(head, position):
    count=0
    p = head
    while head.next:
        head=head.next
        count+=1
    i=0
    while i<count-position:
        p=p.next
        i+=1
    return p.data


from __future__ import annotations

import os

from lsst.ci.middleware.scons import PipelineCommands, python_cmd, tar_repo_cmd
from lsst.sconsUtils import state

# Ensure we can run butler CLI extension in build scripts by propagating the
# necessary envvar.
state.env.Append(ENV={"DAF_BUTLER_PLUGINS": os.environ["DAF_BUTLER_PLUGINS"]})

# Set up a list of all build targets produced in this subdir.
state.targets["data"] = []

# Make a tarred-up repo with dimension records,skymap, and input datasets
# common to most mock pipelines (raws, calibs, refcats, etc.).
base_repo = state.env.Command(
    "base-repo.tgz",
    state.targets["version"],
    [
        python_cmd("-m", "lsst.ci.middleware", "make-base-repo", "--clobber", "${TARGET.base}"),
        tar_repo_cmd("${TARGET.base}", "${TARGET}"),
    ],
)
state.targets["data"].extend(base_repo)

# ci_hsc is run as a full pipeline with no steps, with a constraint limiting
# it to a single patch.  This leads to "tract slicing", in which detectors
# that don't overlap that patch are dropped from steps that normally expect
# complete visits.  We don't care here because the most important tasks that
# care about tract slicing are not run in this pipeline, and for the remainder
# we just live with any slight degradation in the quality of the results.
ci_hsc = (
    PipelineCommands(
        "ci_hsc", os.path.join(os.environ["DRP_PIPE_DIR"], "pipelines", "HSC", "DRP-ci_hsc.yaml"), base_repo
    )
    .add(where="skymap='ci_mw' AND tract=0 AND patch=1")
    .finish()
)
state.targets["data"].extend(ci_hsc)

# RC2 is run in steps, with the target of the real pipeline being outputs for
# just a few non-overlapping tracts.  We do care here about giving full visits
# to steps that expect full visits (no "tract slicing"), and that's the main
# reason for splitting up into steps.  For the mock version, we process just
# one tract (0), and deliberately leave out the two visits here (18202, 96980)
# that doesn't overlap it.
rc2 = (
    PipelineCommands(
        "RC2", os.path.join(os.environ["DRP_PIPE_DIR"], "pipelines", "HSC", "DRP-RC2.yaml"), base_repo
    )
    .add("step1", where="instrument='HSC' AND exposure NOT IN (18202, 96980)")
    # Add side runs (later runs do not build on these) to check --extend-run
    # and --clobber-outputs.
    .add_side_run(
        "test-clobber-without-skip",
        ["calibrate", "consolidatePreSourceTable"],
        where="skymap='ci_mw'",
        extend_run=True,
        clobber_outputs=True,
    )
    .add_side_run(
        "test-skip-and-clobber",
        ["calibrate", "consolidatePreSourceTable"],
        skip_existing_in_last=True,
        extend_run=True,
        clobber_outputs=True,
    )
    .add("step2a", where="skymap='ci_mw'")
    .add("step2b", where="skymap='ci_mw' AND tract=0")
    .add("step2cde")
    .add("step3", where="skymap='ci_mw' AND tract=0")
    .add("step4")
    .add("step5", where="skymap='ci_mw' AND tract=0")
    .add("step6")
    .add("step7")
    # Test fail-and-rescue workflow by configuring one task fail on the first
    # try, and then recover from that with a new run and --skip-existing-in.
    .add("step8", group="attempt1", fail=['''analyzeObjectTableCore::"skymap='ci_mw' AND tract=0"'''])
    .add("step8", group="attempt2", skip_existing_in_last=True)
    .finish()
)
state.targets["data"].extend(rc2)

# The Prod pipeline is run in steps on very large amounts of data, in which we
# expect each step to have to be split up into multiple submissions to keep QG
# and workflow size under control.  We process all data in the input
# repository, and split up steps into groups where appropriate.  We process
# independent groups in serial - which is not realistic, but a useful
# simplification - in order to keep up the practice of making a new repo for
# each run, with no need to merge them.
prod = (
    PipelineCommands(
        "Prod", os.path.join(os.environ["DRP_PIPE_DIR"], "pipelines", "HSC", "DRP-Prod.yaml"), base_repo
    )
    # Using band for grouping here is just a convenient to split our visits up
    # into two groups, not a reflection of expected real pipeline usage.
    .add("step1", group="r", where="band='r'")
    .add(
        "step1",
        group="i-attempt1",
        where="band='i'",
        fail=['''calibrate::"instrument='HSC' AND visit=18202"'''],
    )
    .add("step1", group="i-attempt2", where="band='i'", skip_existing_in_last=True)
    .add("step2a", group="r", where="band='r'")
    .add("step2a", group="i", where="band='i'")
    .add("step2b", group="even", where="skymap='ci_mw' AND tract IN (0, 2)")
    .add("step2b", group="odd", where="skymap='ci_mw' AND tract IN (1, 3)")
    .add("step2c")
    .add("step2d", group="r", where="band='r'")
    .add("step2d", group="i", where="band='i'")
    .add("step2e")
    .add("step3", group="even", where="skymap='ci_mw' AND tract IN (0, 2)")
    .add("step3", group="odd", where="skymap='ci_mw' AND tract IN (1, 3)")
    .add("step4", group="r", where="band='r'")
    .add("step4", group="i", where="band='i'")
    .add("step7")
    # step8 in DRP-Prod is not actually valid, because it has tasks that should
    # be partitioned in different ways in order to scale up.  This is DM-39314.
    .finish()
)
state.targets["data"].extend(prod)

state.env.CleanTree([], ["ci_hsc", "RC2", "Prod"])


N, M    = map(int, input().split())
A, B, D = map(int, input().split())

d = [[0]*M for _ in range(N)]
d[A][B] = 1
position = [A, B]
maps = []

dx = [-1, 0, 1, 0] # 북0 동1 남2 서3
dy = [0, 1, 0, -1]

cnt = 1
turn_time = 0

for i in range(N):
    maps.append(list(map(int, input().split())))

def Turn_left():
    global D
    D -=1
    if D == -1:
        D = 3

while True:
    Turn_left()
    maps[A][B] = 1
    nA = A + dx[D]
    nB = B + dy[D]
    if maps[nA][nB] == 0 and d[nA][nB] == 0:
        d[nA][nB] = 1
        A = nA
        B = nB
        cnt += 1
        turn_time = 0
        continue
    else:
        turn_time +=1
    if turn_time == 4:
        nA = A - dx[D]
        nB = B - dy[D]
        if maps[nA][nB] == 0:
            A = nA
            B = nB
        else:
            break
        turn_time = 0

print("cnt : ",cnt)


# Example 1:
#
# Input: [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
#
# Input: [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] and [4,5] are considered overlapping.

class Solution:
    def merge(self, intervals):
        intervals.sort(key=lambda x: x.start)

        merged = []
        for interval in intervals:
            # if the list of merged intervals is empty or if the current
            # interval does not overlap with the previous, simply append it.
            if not merged or merged[-1].end < interval.start:
                merged.append(interval)
            else:
            # otherwise, there is overlap, so we merge the current and previous
            # intervals.
                merged[-1].end = max(merged[-1].end, interval.end)

        return merged

if __name__ == '__main__':
    a = Solution()
    rst = a.merge([[1,3],[2,6],[8,10],[15,18]])
    print(rst)


#
##########################################################################################
## README
#
# This simple script can be used to convert single VHACD meshes into multiple geometries
# that can be used with MuJoCo. The input file can be any mesh that has already been split
# up into components (either with a VHACD tool or manually with Blender or similar), although
# it has been tested only with .obj files. The output will be a series of .stl files containing
# the mesh components, plus two .xml that can be read by MuJoCo. The .xml files can be imported
# into other MuJoCo files as: '<include file="my_complex_obj_geom.xml"/>'
#
##########################################################################################
#
## To use pymesh (via docker):
# docker pull pymesh/pymesh
#
## To run the docker file (change 'carlo' with any directory name that you need to access from the docker image):
# sudo docker run -it --mount type=bind,source=/home/carlo,target=/carlo -w /carlo pymesh/pymesh bash
#
## To cut objects in Blender
# 1) Press K, Z, C (C optional), then drag a perfect vertical line.
# 2) Menu: Select > Select Loop Inner Region, to select one side of the cut result (F6 > Select Bigger to select the other side).
# 3) In edit mode, press P, then Selected to create a new object with the current selection
#
## Useful links:
# https://pymesh.readthedocs.io/en/latest/installation.html#docker
# https://wiki.nexusmods.com/index.php/Splitting_meshes_in_Blender
# https://blender.stackexchange.com/a/7156
# http://www.mujoco.org/forum/index.php?threads/how-to-grasp-precisely-when-object-is-a-non-convex-hull.3917/
#

import pymesh
import numpy as np

def vhacd_to_mujoco(vhacd_file_path: str, output_dir: str, object_name: str,
					file_prefix: str=None, scale: float=1.0):

	file_prefix = file_prefix or object_name
	scale_str = " ".join([str(scale) for _ in range(3)])

	mesh_xml_f = '<mesh name="{mesh_name}" scale="{scale}" file="{file_name}"/>'
	geom_xml_f = '<geom type="mesh" mesh="{mesh_name}" rgba="{rgba}"/>'

	all_geom_xmls = []
	all_mesh_xmls = []

	mesh = pymesh.load_mesh(vhacd_file_path)
	components = pymesh.separate_mesh(mesh, connectivity_type='vertex')
	print(f'Found {len(components)} components.')

	for i, c in enumerate(components):
		mesh_name = f'{object_name}_part{i}'
		file_name = f'{file_prefix}_part{i}.stl'
		rgba = list(np.random.uniform(0.2, 1.0, 3)) + [1.0]
		rgba = " ".join([str(x) for x in rgba])
		mesh_xml = mesh_xml_f.format(mesh_name=mesh_name, scale=scale_str, file_name=file_name)
		geom_xml = geom_xml_f.format(mesh_name=mesh_name, rgba=rgba)
		all_mesh_xmls.append(mesh_xml)
		all_geom_xmls.append(geom_xml)
		file_path = output_dir + "/" + file_name
		pymesh.save_mesh(file_path, c)

	mj_geom_xml = '\n\t'.join(all_geom_xmls)
	mj_geom_xml = f"<mujoco>\n\t{mj_geom_xml}\n</mujoco>"

	mj_mesh_xml = '\n\t'.join(all_mesh_xmls)
	mj_mesh_xml = f"<mujoco>\n\t{mj_mesh_xml}\n</mujoco>"

	mj_geom_xml_path = output_dir + f"/{file_prefix}_geom.xml"
	with open(mj_geom_xml_path, 'w+') as f:
		f.write(mj_geom_xml)

	mj_mesh_xml_path = output_dir + f"/{file_prefix}_mesh.xml"
	with open(mj_mesh_xml_path, 'w+') as f:
		f.write(mj_mesh_xml)

if __name__ == '__main__':
	vhacd_to_mujoco(
		vhacd_file_path='./teapot_vhacd_manual.obj',
		output_dir='./',
		object_name='object_mesh:teapot_vhacd_m',
		file_prefix='teapot_vhacd_m',
	)


# input
# -9 -9 -9 1 1 1
# 0 -9 0 4 3 2
# -9 -9 -9 1 2 3
# 0 0 8 6 6 0
# 0 0 0 -2 0 0
# 0 0 1 2 4 0

N = 6
TN = 3
RN = 4
tempA = list()

for i in range(N):
    t = [int(s) for s in input().split()]
    tempA.append(t)

arr = [[tempA[j][i] for i in range(N)] for j in range(N)]
# https://stackoverflow.com/questions/2397141/how-to-initialize-a-two-dimensional-array-in-python

ncount = [4, 6]
resarr = [[None for i in range(RN)] for j in range(RN)]
# https://stackoverflow.com/questions/9459337/assign-value-to-an-individual-cell-in-a-two-dimensional-python-array/15778885

maxv = {'val': None, 'x': 0, 'y': 0}

for y in range(RN):
    for x in range(RN):
        maxx = x + 2
        maxy = y + 2

        s = 0
        midx = int((x + maxx) / 2)
        midy = int((y + maxy) / 2)

        for ty in range(y, maxy + 1):
            for tx in range(x, maxx + 1):
                if ty == midy and tx != midx:
                    continue
                else:
                    s = s + arr[ty][tx]

        if maxv['val'] == None or maxv['val'] < s:
            maxv['val'] = s
            maxv['x'] = x
            maxv['y'] = y

        resarr[y][x] = s

print(maxv['val'])


import bobo
import json
from random import choice
from itertools import product

SUITS = ['spades', 'hearts', 'clubs', 'diamonds']
PIPS = ('2','3','4','5','6','7','8','9','10','J','Q','K','A')

def new_deck():
    return ['%s of %s' % (p, s) for p in PIPS for s in SUITS]

@bobo.subroute('/cards', scan=True)
class Deck:
    current_deck = new_deck()

    def __init__(self, bobo_request):
        pass

    @bobo.query('')
    def redirect(self, bobo_request):
        return bobo.redirect(bobo_request.url+'/')

    @bobo.query('/')
    def reset(self, bobo_request):
        Deck.current_deck = new_deck()
        return 'Deck reset to 52 cards.'

    @bobo.query('/:quantity?')
    def get_cards(self, bobo_request, quantity=1):
        num_left = len(Deck.current_deck)
        qty = int(quantity)
        if num_left < qty:
            return 'Could not fulfill request, %d cards left.' % num_left
        draw = list()
        for i in range(qty):
            card = choice(Deck.current_deck)
            s = set(Deck.current_deck)
            s.remove(card)
            Deck.current_deck = list(s)
            draw.append(card)
        return json.dumps({'drawn_cards':draw})

application = bobo.Application(bobo_resources=__name__)


__author__ = 'onion_bass'

from flask import Flask, request, render_template
from sentiment_classifier import SentimentClassifier

import webbrowser

app = Flask(__name__)
classifier = SentimentClassifier()
print("Done")

@app.route("/", methods=["POST", "GET"])
def index(text="", prediction_message=""):
    if request.method == "POST":
        text = request.form["text"]
    print(text)
    prediction_message = classifier.get_prediction_message(text)
    return render_template('index.html', text=text,
                           prediction_message=prediction_message)

if __name__ == "__main__":
    webbrowser.open("http://localhost:5000/")
    app.run(debug=False)


import os
import subprocess
import unittest

from graphwalker import planning
from graphwalker import halting
from graphwalker import reporting
from graphwalker import execution
from graphwalker import graph

class TestInteraction(unittest.TestCase):
    def setUp(self):
        here = os.path.normpath(os.path.join(__file__, '..', '..'))
        self.argl = ['python', os.path.join(here, 'cli.py')]
        self._old_pythonpath = os.environ.get('PYTHONPATH', None)
        os.environ['PYTHONPATH'] = '.'

    def tearDown(self):
        old = getattr(self, '_old_pythonpath', None)
        if old is not None:
            os.environ['PYTHONPATH'] = old
        else:
            del os.environ['PYTHONPATH']

    def test_cli_models_only(self):
        ex = "graphwalker/test/examples/%s.tgf"
        argl = self.argl + [ex % w for w in ("first", "second", "third")]
        self.assertEqual(subprocess.call(argl), 0)

    def test_cli_models_with_actor(self):
        ex = "graphwalker/test/examples/%s.tgf"
        argl = self.argl + [ex % w for w in ("first", "second", "third")]
        argl = argl + ['graphwalker.dummy.Mute']
        self.assertEqual(subprocess.call(argl), 0)

    def test_by_interaction(self):
        r"""Interaction self-test.

        For comparison, try this:

            PYTHONPATH=. python graphwalker/cli.py --reporter=Print \
              graphwalker/test/examples/selftest.graphml \
              graphwalker.test.interactor.Interactor
        """
        outer = self

        class HijackReporter(reporting.ReportingPlugin):
            def finalize(self, failure=False):
                outer.assertFalse(failure)

        reporter = HijackReporter()
        plan = planning.build(['Random'])
        stop = halting.build('Coverage')
        model = graph.Graph.read('graphwalker/test/examples/selftest.graphml')
        actor = 'graphwalker.test.interactor.Interactor'
        exe = execution.Executor(actor, reporter)

        context = {
            'plan': plan, 'stop': stop, 'actor': actor,
            'reporter': reporter, 'executor': exe, 'model': model}

        stop.start(model, context)
        path = plan(model, stop, 'Start', context)

        exe.run('inner', path, context)