import os

os.environ["PYOPENGL_PLATFORM"] = "egl"
import os.path as osp
import sys
import torch
import argparse
import time

import setproctitle
import cv2
import mmcv
import numpy as np
from tqdm import tqdm
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import BoxMode

cur_dir = osp.abspath(osp.dirname(__file__))
PROJ_ROOT = osp.join(cur_dir, "../../../..")
sys.path.insert(0, PROJ_ROOT)
from lib.egl_renderer.egl_renderer_v3 import EGLRenderer
from lib.vis_utils.image import grid_show
from lib.pysixd import misc
from lib.pysixd import inout, misc, transform

from lib.utils.mask_utils import cocosegm2mask
from core.gdrn_modeling.datasets.dataset_factory import register_datasets
from core.utils.data_utils import crop_resize_by_warp_affine, read_image_mmcv
from core.utils.camera_geometry import adapt_image_by_K
from lib.vis_utils.image import vis_image_bboxes_cv2
from core.utils.camera_geometry import get_K_crop_resize
import ref

target_H = 540
target_W = 720
near = 0.01
far = 6.5
new_K_list = [1075.65091572, 0.0, 360.0, 0.0, 1073.90347929, 270.0, 0.0, 0.0, 1.0]
new_K = np.array([1075.65091572, 0.0, 360.0, 0.0, 1073.90347929, 270.0, 0.0, 0.0, 1.0], dtype=np.float32).reshape(3, 3)

data_dir = osp.normpath(osp.join(PROJ_ROOT, "datasets/BOP_DATASETS/tless/test_primesense"))
out_data_dir = osp.normpath(osp.join(PROJ_ROOT, "datasets/BOP_DATASETS/tless/test_primesense_alignK"))
ref_key = "tless"
data_ref = ref.__dict__[ref_key]
model_paths = data_ref.model_paths
objects = data_ref.objects
scene_ids = [f"{i:06d}" for i in range(1, 21)]

class ResizeTless(object):
    def __init__(self) -> None:
        self.models = []
        for model_path in model_paths:
            model = inout.load_ply(model_path, vertex_scale=0.001)
            self.models.append(model)

    def main(self):
        for scene_id in tqdm(scene_ids):
            scene_root = osp.join(data_dir, scene_id)
            new_scene_root = osp.join(out_data_dir, scene_id)

            new_rgb_dir = osp.join(new_scene_root, "rgb")
            new_depth_dir = osp.join(new_scene_root, "depth")
            new_mask_dir = osp.join(new_scene_root, "mask")
            new_visib_dir = osp.join(new_scene_root, "mask_visib")

            mmcv.mkdir_or_exist(new_rgb_dir)
            mmcv.mkdir_or_exist(new_depth_dir)
            mmcv.mkdir_or_exist(new_mask_dir)
            mmcv.mkdir_or_exist(new_visib_dir)

            gt_dict_path = osp.join(scene_root, "scene_gt.json")
            gt_dict = mmcv.load(osp.join(scene_root, "scene_gt.json"))
            gt_info_dict = mmcv.load(osp.join(scene_root, "scene_gt_info.json"))
            cam_dict = mmcv.load(osp.join(scene_root, "scene_camera.json"))

            # copy scene_gt dict
            new_gt_path = osp.join(new_scene_root, "scene_gt.json")
            new_gt_info_dict_path = osp.join(new_scene_root, "scene_gt_info.json")
            new_cam_dict_path = osp.join(new_scene_root, "scene_camera.json")
            os.system(f"cp {gt_dict_path} {new_gt_path}")

            new_gt_info_dict = {}
            new_cam_dict = {}

            for str_im_id in tqdm(gt_dict, postfix=f"{scene_id}"):
                int_im_id = int(str_im_id)
                rgb_path = osp.join(scene_root, "rgb/{:06d}.png").format(int_im_id)
                new_rgb_path = osp.join(new_scene_root, "rgb/{:06d}.png").format(int_im_id)

                depth_path = osp.join(scene_root, "depth/{:06d}.png".format(int_im_id))
                new_depth_path = osp.join(new_scene_root, "depth/{:06d}.png".format(int_im_id))

                scene_im_id = f"{scene_id}/{str_im_id}"
                K = np.array(cam_dict[str_im_id]["cam_K"], dtype=np.float32).reshape(3, 3)

                depth_scale = cam_dict[str_im_id]["depth_scale"]  # 0.1

                new_cam_dict[str_im_id] = {"cam_K": new_K_list, "depth_scale": depth_scale}

                # adjust
                raw_img = read_image_mmcv(rgb_path, format="BGR")
                adapt_img = adapt_image_by_K(raw_img, K_old=K, K_new=new_K, height=target_H, width=target_W)
                mmcv.imwrite(adapt_img, new_rgb_path)

                raw_depth = mmcv.imread(depth_path, "unchanged")
                adapt_depth = adapt_image_by_K(raw_depth, K_old=K, K_new=new_K, height=target_H, width=target_W)
                mmcv.imwrite(adapt_depth, new_depth_path)

                for i, anno in enumerate(gt_dict[str_im_id]):
                    obj_id = anno["obj_id"]

                    R = np.array(anno["cam_R_m2c"], dtype="float32").reshape(3, 3)
                    t = np.array(anno["cam_t_m2c"], dtype="float32") / 1000.0
                    pose = np.hstack([R, t.reshape(3, 1)])

                    mask_path = osp.join(scene_root, "mask/{:06d}_{:06d}.png").format(int_im_id, i)
                    mask_visib_path = osp.join(scene_root, "mask_visib/{:06d}_{:06d}.png").format(int_im_id, i)

                    new_mask_path = osp.join(new_scene_root, "mask/{:06d}_{:06d}.png").format(int_im_id, i)
                    new_mask_visib_path = osp.join(new_scene_root, "mask_visib/{:06d}_{:06d}.png").format(int_im_id, i)

                    raw_mask = mmcv.imread(mask_path, "unchanged")
                    adapt_mask = adapt_image_by_K(raw_mask, K_old=K, K_new=new_K, height=target_H, width=target_W)
                    mmcv.imwrite(adapt_mask, new_mask_path)

                    raw_mask_visib = mmcv.imread(mask_visib_path, "unchanged")
                    adapt_mask_visib = adapt_image_by_K(
                        raw_mask_visib, K_old=K, K_new=new_K, height=target_H, width=target_W
                    )
                    mmcv.imwrite(adapt_mask_visib, new_mask_visib_path)

                    # NOTE: gen bbox from pose, not reliable !!!
                    bbox_visib = bbox_obj = misc.compute_2d_bbox_xywh_from_pose(
                        self.models[obj_id - 1]["pts"], pose, K, width=target_W, height=target_H, clip=True
                    ).tolist()
                    if str_im_id not in new_gt_info_dict:
                        new_gt_info_dict[str_im_id] = []
                    new_gt_info_dict[str_im_id].append(gt_info_dict[str_im_id][i])
                    new_gt_info_dict[str_im_id][i]["bbox_obj"] = bbox_obj
                    new_gt_info_dict[str_im_id][i]["bbox_visib"] = bbox_visib

            # save
            inout.save_json(new_gt_info_dict_path, new_gt_info_dict)
            inout.save_json(new_cam_dict_path, new_cam_dict)

if __name__ == "__main__":
    import argparse
    import time

    import setproctitle
    import torch

    parser = argparse.ArgumentParser(description="None")
    parser.add_argument("--gpu", type=str, default="0", help="gpu")
    parser.add_argument("--vis", default=False, action="store_true", help="vis")
    args = parser.parse_args()

    VIS = args.vis

    device = torch.device(int(args.gpu))
    dtype = torch.float32
    tensor_kwargs = {"device": device, "dtype": dtype}

    T_begin = time.perf_counter()
    setproctitle.setproctitle("test_img_crop")
    func = ResizeTless()
    func.main()
    T_end = time.perf_counter() - T_begin
    print("total time: ", T_end)


import os
from functools import partial
from typing import List, Tuple, Optional, Callable, Dict, Any, Union

import albumentations as A
import cv2
import numpy as np
import pandas as pd
import torch
from pytorch_toolbelt.datasets import INPUT_IMAGE_KEY, INPUT_INDEX_KEY
from pytorch_toolbelt.utils.torch_utils import image_to_tensor
from sklearn.neighbors import BallTree
from sklearn.utils import compute_sample_weight
from torch.utils.data import Sampler, WeightedRandomSampler
from torch.utils.data.dataloader import default_collate
from tqdm import tqdm

from .bboxer import (
    MultilabelCircleNetCoder,
    MultilabelCircleNetEncodeResult,
)
from .constants import *
from ..constants import *

__all__ = [
    "MultilabelCircleNetDataModule",
    "MultilabelCircleNetFixedCropDataset",
    "MultilabelCircleNetRandomCropDataset",
    "centernet_collate",
]

from ..dataset import (
    RandomCropFromImageDataset,
    RandomCropAroundEachObjectDataset,
    XView3DataModule,
    KeypointsDataset,
    FixedCropFromImageDataset,
    read_multichannel_image,
)
from ..dataset.random_crop_dataset import encode_labels
from ..metric import get_shoreline_shoreline_contours

def centernet_collate(batch, channels_last=False):
    skip_keys = [
        TARGET_CENTERS_KEY,
        TARGET_FISHING_KEY,
        TARGET_VESSEL_KEY,
        TARGET_LABELS_KEY,
        TARGET_LENGTHS_KEY,
        INPUT_SCENE_ID_KEY,
        INPUT_SCENE_CROP_KEY,
        INPUT_CONFIDENCE_KEY,
        INPUT_LOCATION_ID_KEY,
        INPUT_IS_NEAR_SHORE_KEY,
    ]
    excluded_items = [dict((k, v) for k, v in b.items() if k in skip_keys) for b in batch]
    included_items = [dict((k, v) for k, v in b.items() if k not in skip_keys) for b in batch]

    batch: dict = default_collate(included_items)
    for k in skip_keys:
        out = [item[k] for item in excluded_items if k in item]
        if len(out):
            batch[k] = out

    # for key in [
    #     INPUT_IMAGE_KEY,
    #     CENTERNET_TARGET_OBJECTNESS_MAP,
    #     CENTERNET_OUTPUT_CLASS_MAP,
    #     CENTERNET_TARGET_OFFSET,
    #     CENTERNET_TARGET_SIZE,
    #     CENTERNET_TARGET_FISHING_MAP,
    #     CENTERNET_TARGET_VESSEL_MAP,
    # ]:
    #     if key in batch:
    #         batch[key] = batch[key].to(memory_format=torch.contiguous_format)

    if channels_last:
        batch[INPUT_IMAGE_KEY] = batch[INPUT_IMAGE_KEY].to(memory_format=torch.channels_last)
    return batch

class MultilabelCircleNetTargetsMixin:
    box_coder: MultilabelCircleNetCoder

    def build_centernet_sample(
        self,
        image,
        centers,
        confidences,
        lengths,
        is_vessel,
        is_fishing,
        index,
        image_id,
        is_near_shore,
        location,
        folder: str,
        crop_coords: Tuple[Tuple[int, int], Tuple[int, int]],
    ) -> Dict[str, Any]:
        # Mask NaN values
        image[~np.isfinite(image)] = 0

        result = {
            INPUT_INDEX_KEY: index,
            INPUT_IMAGE_KEY: image_to_tensor(image),
            TARGET_CENTERS_KEY: centers.tolist(),  # .tolist to prevent Catalyst converting it to Tensor and move to GPU
            TARGET_VESSEL_KEY: is_vessel.tolist(),
            TARGET_FISHING_KEY: is_fishing.tolist(),
            TARGET_LENGTHS_KEY: lengths.tolist(),
            INPUT_CONFIDENCE_KEY: confidences.tolist(),
            INPUT_IS_NEAR_SHORE_KEY: is_near_shore.tolist(),
            INPUT_LOCATION_ID_KEY: location,
            INPUT_FOLDER_KEY: folder,
            INPUT_SCENE_ID_KEY: image_id,
            TARGET_SAMPLE_WEIGHT: {"train": 0.25, "validation": 1.0, "valid": 1.0, "test": 0.1}[folder],
        }
        if crop_coords is not None:
            result[INPUT_SCENE_CROP_KEY] = crop_coords

        box_coder = self.box_coder.box_coder_for_image_size(image.shape)
        centernet_targets: MultilabelCircleNetEncodeResult = box_coder.encode(
            centers=centers, confidences=confidences, lengths=lengths, is_vessel=is_vessel, is_fishing=is_fishing
        )
        result[CENTERNET_TARGET_OBJECTNESS_MAP] = centernet_targets.heatmap
        result[CENTERNET_TARGET_VESSEL_MAP] = centernet_targets.is_vessel
        result[CENTERNET_TARGET_FISHING_MAP] = centernet_targets.is_fishing
        result[CENTERNET_TARGET_SIZE] = centernet_targets.lengths
        result[CENTERNET_TARGET_OFFSET] = centernet_targets.offset
        return result

class MultilabelCircleNetFixedCropDataset(FixedCropFromImageDataset, MultilabelCircleNetTargetsMixin):
    def __init__(
        self,
        scenes: List[str],
        centers: List[np.ndarray],
        locations: List[str],
        confidences: List[np.ndarray],
        is_vessel: List[np.ndarray],
        is_fishing: List[np.ndarray],
        is_near_shore: List[np.ndarray],
        lengths: List[np.ndarray],
        crop_coords: List[Tuple],
        scene_sizes: List[Tuple[int, int]],
        individual_transforms: Dict[str, A.Compose],
        normalization: Dict[str, A.ImageOnlyTransform],
        input_channels: List[str],
        transform: A.Compose,
        read_image_fn: Callable,
        box_coder: MultilabelCircleNetCoder,
        channels_last: bool = False,
    ):
        super().__init__(
            scenes=scenes,
            centers=centers,
            locations=locations,
            confidences=confidences,
            is_vessel=is_vessel,
            is_fishing=is_fishing,
            is_near_shore=is_near_shore,
            lengths=lengths,
            crop_coords=crop_coords,
            scene_sizes=scene_sizes,
            individual_transforms=individual_transforms,
            normalization=normalization,
            input_channels=input_channels,
            transform=transform,
            read_image_fn=read_image_fn,
            channels_last=channels_last,
        )
        self.box_coder = box_coder

    def build_sample(
        self,
        image,
        centers,
        confidences,
        is_vessel,
        is_fishing,
        lengths,
        index,
        folder: str,
        image_id,
        is_near_shore,
        location: str,
        crop_coords,
    ) -> Dict[str, Any]:
        return self.build_centernet_sample(
            image=image,
            centers=centers,
            confidences=confidences,
            is_vessel=is_vessel,
            is_fishing=is_fishing,
            lengths=lengths,
            index=index,
            image_id=image_id,
            is_near_shore=is_near_shore,
            location=location,
            folder=folder,
            crop_coords=crop_coords,
        )

    def get_collate_fn(self) -> Callable:
        return partial(centernet_collate, channels_last=self.channels_last)

class MultilabelCircleNetRandomCropDataset(RandomCropFromImageDataset, MultilabelCircleNetTargetsMixin):
    def __init__(
        self,
        scenes: List[str],
        shoreline_contours: List[np.ndarray],
        locations: List[str],
        centers: List[np.ndarray],
        confidences: List[np.ndarray],
        lengths: List[np.ndarray],
        is_vessel: List[np.ndarray],
        is_fishing: List[np.ndarray],
        is_near_shore: List[np.ndarray],
        scene_sizes: List[Tuple[int, int]],
        individual_transforms: Dict[str, A.Compose],
        normalization: Dict[str, A.ImageOnlyTransform],
        input_channels: List[str],
        transform: A.Compose,
        read_image_fn: Callable,
        crop_size: Tuple[int, int],
        box_coder: MultilabelCircleNetCoder,
        crop_around_ship_p=0.9,
        balance_near_shore: Union[None, bool, float] = None,
        balance_crowd=None,
        balance_by_type=False,
        channels_last=False,
    ):
        super().__init__(
            scenes=scenes,
            shoreline_contours=shoreline_contours,
            locations=locations,
            centers=centers,
            confidences=confidences,
            is_vessel=is_vessel,
            is_fishing=is_fishing,
            is_near_shore=is_near_shore,
            lengths=lengths,
            scene_sizes=scene_sizes,
            individual_transforms=individual_transforms,
            normalization=normalization,
            input_channels=input_channels,
            transform=transform,
            read_image_fn=read_image_fn,
            crop_size=crop_size,
            crop_around_ship_p=crop_around_ship_p,
            balance_near_shore=balance_near_shore,
            balance_crowd=balance_crowd,
            balance_by_type=balance_by_type,
            channels_last=channels_last,
        )
        self.box_coder = box_coder

    def build_sample(
        self,
        image,
        centers,
        confidences,
        is_vessel,
        is_fishing,
        lengths,
        index,
        folder: str,
        image_id,
        is_near_shore,
        location: str,
        crop_coords,
    ) -> Dict[str, Any]:
        return self.build_centernet_sample(
            image=image,
            centers=centers,
            confidences=confidences,
            is_vessel=is_vessel,
            is_fishing=is_fishing,
            lengths=lengths,
            index=index,
            folder=folder,
            image_id=image_id,
            is_near_shore=is_near_shore,
            location=location,
            crop_coords=crop_coords,
        )

    def get_collate_fn(self) -> Callable:
        return partial(centernet_collate, channels_last=self.channels_last)

class MultilabelCircleNetRandomCropAroundEachObjectDataset(RandomCropAroundEachObjectDataset, MultilabelCircleNetTargetsMixin):
    def __init__(
        self,
        scenes: List[str],
        locations: List[str],
        crop_centers: np.ndarray,
        centers: List[np.ndarray],
        confidences: List[np.ndarray],
        lengths: List[np.ndarray],
        is_vessel: List[np.ndarray],
        is_fishing: List[np.ndarray],
        is_near_shore: List[np.ndarray],
        scene_sizes: List[Tuple[int, int]],
        individual_transforms: Dict[str, A.Compose],
        normalization: Dict[str, A.ImageOnlyTransform],
        input_channels: List[str],
        transform: A.Compose,
        read_image_fn: Callable,
        crop_size: Tuple[int, int],
        box_coder: MultilabelCircleNetCoder,
        channels_last=False,
    ):
        super().__init__(
            scenes=scenes,
            locations=locations,
            crop_centers=crop_centers,
            centers=centers,
            confidences=confidences,
            is_vessel=is_vessel,
            is_fishing=is_fishing,
            is_near_shore=is_near_shore,
            lengths=lengths,
            scene_sizes=scene_sizes,
            individual_transforms=individual_transforms,
            normalization=normalization,
            input_channels=input_channels,
            transform=transform,
            read_image_fn=read_image_fn,
            crop_size=crop_size,
            channels_last=channels_last,
        )
        self.box_coder = box_coder

    def build_sample(
        self,
        image,
        centers,
        confidences,
        is_vessel,
        is_fishing,
        lengths,
        index,
        folder: str,
        image_id,
        is_near_shore,
        location: str,
        crop_coords,
    ) -> Dict[str, Any]:
        return self.build_centernet_sample(
            image=image,
            centers=centers,
            confidences=confidences,
            is_vessel=is_vessel,
            is_fishing=is_fishing,
            is_near_shore=is_near_shore,
            lengths=lengths,
            index=index,
            folder=folder,
            image_id=image_id,
            location=location,
            crop_coords=crop_coords,
        )

    def get_collate_fn(self) -> Callable:
        return partial(centernet_collate, channels_last=self.channels_last)

class MultilabelCircleNetDataModule(XView3DataModule):
    @classmethod
    def get_keypoint_params(cls):
        return A.KeypointParams(format="xys", label_fields=["confidences", "is_vessel", "is_fishing", "is_near_shore"])

    @classmethod
    def get_random_crop_each_object_dataset(
        cls,
        train_df: pd.DataFrame,
        train_image_size: Tuple[int, int],
        input_channels: List[str],
        box_coder: MultilabelCircleNetCoder,
        normalization: Dict[str, A.ImageOnlyTransform],
        num_samples: int = 1024,
        individual_augmentations: Optional[Dict] = None,
        augmentations: Optional[List[A.BasicTransform]] = None,
        balance_crowd=False,
        balance_per_scene=True,
        balance_near_shore=None,
        balance_vessel_type=False,
        balance_fishing_type=False,
        balance_by_type=False,
        balance_location=False,
        channels_last=False,
        read_image_fn=read_multichannel_image,
    ) -> Tuple[KeypointsDataset, Optional[Sampler]]:
        scene_sizes = dict(
            [
                (row["scene_id"], (row["rows"], row["cols"]))
                for i, row in pd.read_csv(os.path.join(os.path.dirname(__file__), "..", "scene_sizes.csv")).iterrows()
            ]
        )

        all_images = []
        all_coordinates = []
        all_confidences = []
        all_lengths = []
        all_size = []
        all_is_vessel = []
        all_is_fishing = []
        all_is_near_shore = []

        all_scenes = []
        all_locations = []

        center_near_shore = []
        center_neighbors = []
        center_coordinates = []
        center_is_vessel = []
        center_is_fishing = []
        center_is_near_shore = []

        for scene_id in tqdm(train_df.scene_id.unique(), desc="Preparing training dataset"):
            # Get detections only for current scene
            scene_df = train_df[train_df.scene_id == scene_id]
            num_instances_in_scene = len(scene_df)
            scene_size = scene_sizes[scene_id]
            scene_path = scene_df.scene_path.values[0]
            location_id = scene_df.location.values[0]

            targets = cls.get_multilabel_targets_from_df(scene_df)
            distance_from_shore_km = scene_df.distance_from_shore_km
            near_shore = (distance_from_shore_km < 2).values

            tree = BallTree(targets.centers, leaf_size=8, metric="chebyshev")
            neighbors = tree.query_radius(targets.centers, r=max(train_image_size) // 2, count_only=True)

            all_scenes.extend([scene_id] * num_instances_in_scene)
            all_locations.extend([location_id] * num_instances_in_scene)
            all_images.extend([scene_path] * num_instances_in_scene)

            center_coordinates.extend(targets.centers)
            center_is_vessel.extend(targets.is_vessel)
            center_is_fishing.extend(targets.is_fishing)
            center_is_near_shore.extend(targets.is_near_shore)
            center_near_shore.extend(near_shore)
            center_neighbors.extend(neighbors)

            all_coordinates.extend([targets.centers] * num_instances_in_scene)
            all_confidences.extend([targets.confidences] * num_instances_in_scene)
            all_is_vessel.extend([targets.is_vessel] * num_instances_in_scene)
            all_is_fishing.extend([targets.is_fishing] * num_instances_in_scene)
            all_lengths.extend([targets.lengths] * num_instances_in_scene)
            all_is_near_shore.extend([targets.is_near_shore] * num_instances_in_scene)

            all_size.extend([scene_size] * num_instances_in_scene)

        if augmentations is None:
            augmentations = []

        transform = A.Compose(
            augmentations
            + [
                A.PadIfNeeded(
                    train_image_size[0],
                    train_image_size[1],
                    value=float("nan"),
                    border_mode=cv2.BORDER_CONSTANT,
                ),
            ],
            keypoint_params=cls.get_keypoint_params(),
        )
        train_ds = MultilabelCircleNetRandomCropAroundEachObjectDataset(
            scenes=all_images,
            locations=all_locations,
            centers=all_coordinates,
            confidences=all_confidences,
            crop_centers=np.array(center_coordinates),
            lengths=all_lengths,
            is_vessel=all_is_vessel,
            is_fishing=all_is_fishing,
            is_near_shore=all_is_near_shore,
            scene_sizes=all_size,
            individual_transforms=individual_augmentations,
            input_channels=input_channels,
            transform=transform,
            normalization=normalization,
            read_image_fn=read_image_fn,
            box_coder=box_coder,
            crop_size=train_image_size,
            channels_last=channels_last,
        )

        # weights = np.ones(len(all_coordinates), dtype=np.float64)
        # num_balancing = 0
        #
        # if balance_location:
        #     location_balance_weights = compute_sample_weight("balanced", all_locations)
        #     weights *= location_balance_weights
        #     num_balancing += 1
        #
        # if balance_crowd:
        #     inv_frequency = np.reciprocal(np.array(center_neighbors).astype(np.float32))
        #     crowd_balance_weights = np.sqrt(inv_frequency)  # Slightly dampen inverse proportional weight
        #     weights *= crowd_balance_weights
        #     num_balancing += 1
        #
        # if balance_per_scene:
        #     scene_balance_weights = compute_sample_weight("balanced", all_scenes)
        #     weights *= scene_balance_weights
        #     num_balancing += 1
        #
        # if balance_vessel_type:
        #     vessel_type_weights = compute_sample_weight({0: 0.45, 1: 0.45, IGNORE_LABEL: 0.1}, center_is_vessel)
        #     weights *= vessel_type_weights
        #     num_balancing += 1
        #
        # if balance_fishing_type:
        #     fishing_weights = compute_sample_weight({0: 0.45, 1: 0.45, IGNORE_LABEL: 0.1}, center_is_fishing)
        #     weights *= fishing_weights
        #     num_balancing += 1
        #
        # if balance_near_shore and len(np.bincount(center_near_shore)) > 1:
        #     shore_balance_weights = compute_sample_weight("balanced", center_near_shore)
        #     weights *= shore_balance_weights
        #     num_balancing += 1
        #
        # if num_balancing:
        #     weights **= 1.0 / num_balancing
        #

        weights = np.ones(len(all_coordinates), dtype=np.float64)
        num_balancing = 0

        if balance_location:
            location_balance_weights = compute_sample_weight("balanced", all_locations)
            weights += location_balance_weights
            num_balancing += 1

        if balance_crowd:
            inv_frequency = np.reciprocal(np.array(center_neighbors).astype(np.float32))
            crowd_balance_weights = inv_frequency
            if not np.all(np.isfinite(crowd_balance_weights)):
                raise RuntimeError()
            weights += crowd_balance_weights
            num_balancing += 1

        if balance_per_scene:
            scene_balance_weights = compute_sample_weight("balanced", all_scenes)
            weights += scene_balance_weights
            num_balancing += 1

        if balance_vessel_type:
            center_is_vessel = np.array(center_is_vessel)
            vessel_type_weights = compute_sample_weight(
                {
                    0: len(center_is_vessel) / (2.0 * np.sum(center_is_vessel == 0)),
                    1: len(center_is_vessel) / (2.0 * np.sum(center_is_vessel == 1)),
                    IGNORE_LABEL: 0,
                },
                center_is_vessel,
            )
            if not np.all(np.isfinite(vessel_type_weights)):
                raise RuntimeError()

            weights += vessel_type_weights
            num_balancing += 1

        if balance_fishing_type:
            center_is_fishing = np.array(center_is_fishing)
            fishing_weights = compute_sample_weight(
                {
                    0: len(center_is_fishing) / (2.0 * np.sum(center_is_fishing == 0)),
                    1: len(center_is_fishing) / (2.0 * np.sum(center_is_fishing == 1)),
                    IGNORE_LABEL: 0,
                },
                center_is_fishing,
            )
            if not np.all(np.isfinite(fishing_weights)):
                raise RuntimeError()
            weights += fishing_weights
            num_balancing += 1

        if balance_by_type:
            class_labels = encode_labels(center_is_vessel, center_is_fishing)
            type_balance_weights = compute_sample_weight("balanced", class_labels)
            weights += type_balance_weights
            num_balancing += 1

        if balance_near_shore and len(np.bincount(center_near_shore)) > 1:
            shore_balance_weights = compute_sample_weight("balanced", center_near_shore)
            weights += shore_balance_weights
            num_balancing += 1

        if num_balancing:
            weights /= float(num_balancing)

        train_sampler = WeightedRandomSampler(weights.astype(np.float32), num_samples=num_samples, replacement=True)
        return train_ds, train_sampler

    @classmethod
    def get_random_crop_training_dataset(
        cls,
        train_df: pd.DataFrame,
        train_image_size: Tuple[int, int],
        input_channels: List[str],
        box_coder: MultilabelCircleNetCoder,
        crop_around_ship_p: float,
        normalization: Dict[str, A.ImageOnlyTransform],
        shore_root: str,
        num_samples: int = 1024,
        individual_augmentations: Optional[Dict] = None,
        augmentations: Optional[List[A.BasicTransform]] = None,
        balance_near_shore=None,
        balance_crowd=None,
        balance_location=False,
        balance_by_type=False,
        balance_folder=False,
        channels_last=False,
        read_image_fn=read_multichannel_image,
    ) -> Tuple[KeypointsDataset, Optional[Sampler]]:
        scene_sizes = dict(
            [
                (row["scene_id"], (row["rows"], row["cols"]))
                for i, row in pd.read_csv(os.path.join(os.path.dirname(__file__), "..", "scene_sizes.csv")).iterrows()
            ]
        )

        all_images = []
        all_centers = []
        all_confidences = []
        all_lengths = []
        all_size = []
        all_is_vessel = []
        all_is_fishing = []
        all_is_near_shore = []
        all_near_shore = []
        all_locations = []
        all_shoreline_contours = []
        all_folders = []

        for scene_id in tqdm(train_df.scene_id.unique(), desc="Preparing training dataset"):
            # Get detections only for current scene
            scene_df = train_df[train_df.scene_id == scene_id]
            scene_size = scene_sizes[scene_id]
            scene_path = scene_df.scene_path.values[0]
            location_id = scene_df.location.values[0]
            folder_id = scene_df.folder.values[0]

            shoreline_contours = get_shoreline_shoreline_contours(shore_root, scene_id)

            targets = cls.get_multilabel_targets_from_df(scene_df)
            distance_from_shore_km = scene_df.distance_from_shore_km
            near_shore = (distance_from_shore_km < 2).values

            all_images.append(scene_path)
            all_shoreline_contours.append(shoreline_contours)

            all_centers.append(targets.centers)
            all_confidences.append(targets.confidences)
            all_is_vessel.append(targets.is_vessel)
            all_is_fishing.append(targets.is_fishing)
            all_is_near_shore.append(targets.is_near_shore)
            all_lengths.append(targets.lengths)
            all_size.append(scene_size)
            all_near_shore.append(near_shore)

            all_locations.append(location_id)
            all_folders.append(folder_id)

        if augmentations is None:
            augmentations = []

        transform = A.Compose(
            augmentations
            + [
                A.PadIfNeeded(
                    train_image_size[0],
                    train_image_size[1],
                    value=float("nan"),
                    border_mode=cv2.BORDER_CONSTANT,
                ),
            ],
            keypoint_params=cls.get_keypoint_params(),
        )
        train_ds = MultilabelCircleNetRandomCropDataset(
            scenes=all_images,
            shoreline_contours=all_shoreline_contours,
            locations=all_locations,
            centers=all_centers,
            confidences=all_confidences,
            lengths=all_lengths,
            is_vessel=all_is_vessel,
            is_fishing=all_is_fishing,
            is_near_shore=all_near_shore,
            scene_sizes=all_size,
            individual_transforms=individual_augmentations,
            input_channels=input_channels,
            transform=transform,
            normalization=normalization,
            read_image_fn=read_image_fn,
            box_coder=box_coder,
            crop_size=train_image_size,
            crop_around_ship_p=crop_around_ship_p,
            balance_near_shore=balance_near_shore,
            balance_crowd=balance_crowd,
            balance_by_type=balance_by_type,
            channels_last=channels_last,
        )

        weights = len(train_df)
        num_balancing = 0

        if balance_location:
            location_balance_weights = compute_sample_weight("balanced", all_locations)
            weights *= location_balance_weights
            num_balancing += 1

        if balance_folder:
            folder_balance_weights = compute_sample_weight("balanced", all_folders)
            weights *= folder_balance_weights
            num_balancing += 1

        if num_balancing:
            weights **= 1.0 / num_balancing

        train_sampler = WeightedRandomSampler(np.ones(len(train_ds)), num_samples=num_samples, replacement=True)
        return train_ds, train_sampler

    @classmethod
    def get_validation_dataset(
        cls,
        valid_df: pd.DataFrame,
        valid_crop_size: Tuple[int, int],
        input_channels: List[str],
        box_coder: MultilabelCircleNetCoder,
        normalization: Dict[str, A.ImageOnlyTransform],
        channels_last=False,
        read_image_fn=read_multichannel_image,
    ) -> KeypointsDataset:
        """
        For validation dataset we apply sliding crops
        :param valid_df:
        :param kwargs:
        :return:
        """

        all_images = []
        all_centers = []
        all_confidences = []
        all_lengths = []
        all_crop_coords = []
        all_is_vessel = []
        all_is_fishing = []
        all_scene_sizes = []
        all_locations = []
        all_is_near_shore = []

        scene_sizes = dict(
            [
                (row["scene_id"], (row["rows"], row["cols"]))
                for i, row in pd.read_csv(os.path.join(os.path.dirname(__file__), "..", "scene_sizes.csv")).iterrows()
            ]
        )

        for scene_id in tqdm(valid_df.scene_id.unique(), desc="Preparing validation dataset"):
            # Get detections only for current scene
            scene_df = valid_df[valid_df.scene_id == scene_id]
            scene_path = scene_df.scene_path.values[0]
            scene_size = scene_sizes[scene_id]
            location = scene_df.location.values[0]

            targets = cls.get_multilabel_targets_from_df(scene_df)
            for crop_coords in cls.iterate_crops(scene_size, valid_crop_size, valid_crop_size):
                all_images.append(scene_path)
                all_locations.append(location)
                all_centers.append(targets.centers)
                all_confidences.append(targets.confidences)
                all_is_vessel.append(targets.is_vessel)
                all_is_fishing.append(targets.is_fishing)
                all_is_near_shore.append(targets.is_near_shore)
                all_lengths.append(targets.lengths)
                all_crop_coords.append(crop_coords)
                all_scene_sizes.append(scene_size)

        individual_transforms = {}
        transform = A.Compose(
            [
                A.PadIfNeeded(
                    valid_crop_size[0],
                    valid_crop_size[1],
                    value=float("nan"),
                    border_mode=cv2.BORDER_CONSTANT,
                ),
            ],
            keypoint_params=cls.get_keypoint_params(),
        )
        valid_ds = MultilabelCircleNetFixedCropDataset(
            scenes=all_images,
            locations=all_locations,
            centers=all_centers,
            confidences=all_confidences,
            lengths=all_lengths,
            crop_coords=all_crop_coords,
            is_vessel=all_is_vessel,
            is_fishing=all_is_fishing,
            is_near_shore=all_is_near_shore,
            scene_sizes=all_scene_sizes,
            individual_transforms=individual_transforms,
            normalization=normalization,
            input_channels=input_channels,
            transform=transform,
            read_image_fn=read_image_fn,
            box_coder=box_coder,
            channels_last=channels_last,
        )
        return valid_ds


import csv
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

def readCsv():
    value_dict = {}
    minval = -1
    maxChunk = 0
    chunkDifference = -1

    with open('C:\\Users\\targe\\Documents\\hpx\\build\\examples\\quickstart\\exclusiveOutputAlterAvg.csv') as csvfile:
        valueReader = csv.reader(csvfile)
        for row in valueReader:
            if int(row[0]) == 0:
                seqTime = row
                continue

            if minval == -1:
                minval = int(float(row[3]))
            else:
                minval = min(minval, int(float(row[3])))

            if chunkDifference == -1:
                chunkDifference = int(row[2])-int(row[1])
            maxChunk = max(maxChunk, int(row[2]))
            chunk_key = (int(row[1]), int(row[2]))

            if chunk_key not in value_dict:
                value_dict[chunk_key] = []

            value_dict[chunk_key].append([int(row[0]), int(float(row[3])), int(float(row[4]))])

    fig, ax = plt.subplots()
    ax.set_yticks(range(0, maxChunk+1, chunkDifference))
    ax.set_ylabel("Chunk extent")
    ax.set_xlabel("Time")

    functocolor = {
        1 : 'red',
        2 : (0.0, 1.0, 0.0, 0.1),
        3 : 'orange'
    }
    handles = [mpatches.Patch(color='red', label='Stage 1'),
        mpatches.Patch(color='blue', label='Stage 2'),
        mpatches.Patch(color='orange', label='Stage 3')]
    plt.legend(loc="upper right", handles=handles)

    for key in value_dict:
        for val in value_dict[key]:
            if val[1] == 0 or val[2] == 0:
                continue

            start = val[1] - minval
            width = val[2]
            ax.broken_barh([(start, width)], (key[0], key[1]-key[0]), facecolor=functocolor[val[0]], edgecolor='black')

    # calculate seq width
    print(int(float(seqTime[4])))
    rect = mpatches.Rectangle((0, 0), int(float(seqTime[4])), 1000, linewidth=1, edgecolor='black', facecolor='brown')
    ax.add_patch(rect)

    plt.gca().invert_yaxis()
    plt.show()

if __name__ == "__main__":
    readCsv()


from db.mysql import sqlMgr

sql = sqlMgr('localhost', 'root', '861217', 'football')

def getResultAll():
    data = sql.queryByTypeAll("k_rate_euro")

    main_win = 0
    client_win = 0
    tie_win = 0
    if len(data) == 0 :
        return

    rate = 0
    rate = 3

    for one in data :
        if one[4] == 1 :
            main_win += one[6+rate] - 1
            client_win += -1
            tie_win += -1
        elif one[4] == -1 :
            main_win += - 1
            client_win += one[7+rate] -1
            tie_win += -1
        else :
            main_win += - 1
            client_win += -1
            tie_win += one[8+rate] -1

    mainResult = main_win/len(data)
    clientResult = client_win/len(data)
    tieResult = tie_win/len(data)
    gameSize = len(data)
    print(str(main_win/len(data)), "    ",str(client_win/len(data)),"    ",str(tie_win/len(data)),"    ",str(len(data)))

# getResultAll()

def getResult(name, value):
    data = sql.queryByType(name, "k_rate_euro")

    main_win = 0
    client_win = 0
    tie_win = 0
    if len(data) == 0 :
        return

    rate = 0
    rate = 3

    for one in data :
        if one[4] == 1 :
            main_win += one[6+rate] - 1
            client_win += -1
            tie_win += -1
        elif one[4] == -1 :
            main_win += - 1
            client_win += one[7+rate] -1
            tie_win += -1
        elif one[4] == 0:
            main_win += - 1
            client_win += -1
            tie_win += one[8+rate] -1

    mainResult = main_win/len(data)
    clientResult = client_win/len(data)
    tieResult = tie_win/len(data)
    gameSize = len(data)
    if (mainResult > value or clientResult > value or tieResult > value)  and gameSize > 30:
        # print("")
        print(str(round(main_win/len(data),2)), "    ",str(round(client_win/len(data),2)),"    ",str(round(tie_win/len(data),2)),"    ",str(len(data)),"    ",name)
        return True
    return False

def getResult_v2(name, value):
    data = sql.queryByType(name, "k_rate_euro")

    main_win = 0
    client_win = 0
    tie_win = 0
    size = 0
    if len(data) == 0 :
        return
    for one in data :
        offset = 3
        rate_win = one[6]
        rate_win_first = one[6+ offset]
        rate_lost = one[7]
        rate_lost_first = one[7+ offset]
        rate_tie = one[8]
        rate_tie_first = one[8+ offset]

        if rate_win_first == 0 or rate_lost_first == 0 :
            return
        change_min = abs(rate_win_first - rate_win)/rate_win_first
        change = abs(rate_lost_first - rate_lost)/rate_lost_first
        if change_min > change :
            change_min = change

        if change_min < value :
            continue
        size += 1
        if one[4] == 1 :
            main_win += one[6] - 1
            client_win += -1
            tie_win += -1
        elif one[4] == -1 :
            main_win += - 1
            client_win += one[7] -1
            tie_win += -1
        else :
            main_win += - 1
            client_win += -1
            tie_win += one[8] -1

    if size < 30 :
        return
    if main_win/size < 0.1 and client_win/size < 0.1 and tie_win/size < 0.1:
        return
    if main_win >0 or client_win >0 or tie_win >0 :
        print(str(round(main_win/size, 2)), "   ",str(round(client_win/size, 2)),"    ",str(round(tie_win/size, 2)),"    ",str(size),"    ",name, value)

def compare(name):

    if getResult(name, 0.03) == False :
        return
    # getResult_v2(name, 0.15)

# def compare(name):
#     getResult_v2(name, 0.1)
#     for index in range(20):
        # getResult_v2(name, 0.01*index)

compare("美职业")
# compare("阿甲")
# compare("英超")
# compare("英甲")
# compare("英冠")
# compare("英乙")
# compare("意甲")
# compare("德甲")
# compare("德乙")
# compare("西甲")
# compare("葡超")
# compare("法甲")
# compare("法乙")
# compare("荷甲")
# compare("荷乙")
# compare("日职联")
# compare("日职乙")
# compare("苏超")
# compare("比甲")
# compare("俄超")
# compare("挪超")
# compare("瑞典超")
# compare("巴西甲")
# compare("澳洲甲")


class Solution:
    def letterCasePermutation(self, S: str) -> List[str]:
        def backtrack(S, step, curr, res):
            # already go through the entire string, S
            if step == len(S):
                res.append(curr)
                return

            # not alphabets => one backtrack case
            if S[step].lower() == S[step].upper():
                backtrack(S, step+1, curr+S[step], res)

            # having upper and lower letters => two backtrack cases
            else:
                backtrack(S, step+1, curr+S[step].lower(), res)
                backtrack(S, step+1, curr+S[step].upper(), res)

        res = []
        backtrack(S, 0, "", res)
        return res


class Node:
  """
 node class to store data
 pointer to the next value
  """

  def __init__(self, data, next_=None):
    self.data = data
    self.next = next_

class LinkedList:
  """
  linked list class
  need to include head value
  should create empty linked list
  this class should containe 3 method(insert,includes,toString)
  """

  def __init__(self):
    self.head = None

  def insert(self, value):
    """"
    input: 1 value
    output:❌
    action:insert new value to the head of the list
    """
    self.head = Node(value, self.head)

  def includes(self, value):
    """
    input: 1 value
    output:true
    action:to check if the value exist in the
    """
    current = self.head
    while current != None:
      if current.data == value:
        return True
      else:
        current = current.next
    return False

  def toString(self):
   '''
  input:none
  output:{ a } -> { b } -> { c } -> NULL
  action:return formated string represent list value
  '''
   string = ""
   current=self.head
   while current != None:
       value = current.data
       if current.next is None:
          string +="{"+f' {value} '+"}" + " -> NULL"
          break

       else:
          string +="{"+f' {value} '+"} -> "
          current = current.next
   return string


import csv
import matplotlib.pyplot as plt
from matplotlib import rcParams

rcParams['font.family'] ='Malgun Gothic'
rcParams['axes.unicode_minus'] =False

ride_sort = []
off_sort = []
total_sort = []

def readCsv(filename) :
	f = open(filename, 'r', encoding='cp949')
	data = csv.reader(f, delimiter=',')

	#호선명,역ID,지하철역,07:00:00~07:59:59,,08:00:00~08:59:59,
	#,,,승차,하차,승차,하차

	next(data)
	next(data)
	# 0 호선명, 1 역ID, 2 서울역, 3 43763, 4 112497, 5 74004, 6 237172
	for row in data :
		total_sum = 0
		ride_sum = 0
		off_sum = 0

		for i in range(0, 7) :
			if row[i] == '' :
				continue
		station = row[2] + f"\n({row[0]})"

		range78_ride = int(row[3])
		range78_off = int(row[4])

		range89_ride = int(row[5])
		range89_off = int(row[6])

		total_sum += range78_ride + range78_off + range89_ride + range89_off
		ride_sum += range78_ride + range89_ride
		off_sum += range78_off + range89_off

		ride_sort.append([ride_sum, station])
		off_sort.append([off_sum, station])
		total_sort.append([total_sum, station])

	f.close()

def analyze() :
	ride_sort.sort()
	off_sort.sort()
	total_sort.sort()
	plt.figure(figsize=(16, 6))
	plt.rc('font', size=3)
	addPlt(ride_sort, 1, "ride")
	addPlt(off_sort, 2, "off")
	addPlt(total_sort, 3, "total")
	plt.savefig("q4-1.png", dpi = 500)
	plt.tight_layout()
	plt.show()

def addPlt(sorted_result, idx, title) :
	plt.subplot(3, 1, idx)
	plt.title(f"Top 30 Stations in '{title}'")
	stations = []
	cnt = []
	for i in range(len(sorted_result) - 1, len(sorted_result) - 31, -1) :
		if title == "total" :
			print(-(i - len(sorted_result)), sorted_result[i][1], sorted_result[i][0])
		stations.append(sorted_result[i][1])
		cnt.append(sorted_result[i][0])
	plt.bar(stations, cnt)
	plt.ylabel("population count")

	for i, v in enumerate(stations):
		plt.text(v, cnt[i], cnt[i],
				fontsize = 4,
				color='black',
				horizontalalignment='center',
				verticalalignment='bottom')

def main() :
	readCsv("q4.csv")
	analyze()

if __name__ == "__main__" :
	main()


import requests
import neopixel
import board
import time
import random

total_pixels = 550
lower_bank_start = 250
inactivity_timeout = []
last_known_state = [[] for x in range(total_pixels)]
all_pixels = neopixel.NeoPixel(
    board.D18,
    total_pixels,
    brightness=1,
    auto_write=False,
    pixel_order=neopixel.RGB)

def flash_bank(upper=True, num_times=3, delay=0.2):
    if upper:
        pixel_bank = range(0, lower_bank_start - 1)
    else:
        pixel_bank = range(lower_bank_start, total_pixels - 1)
    for _ in range(0, num_times):
        for i in pixel_bank:
            all_pixels[i] = [255, 255, 255]
        all_pixels.show()
        for i in pixel_bank:
            all_pixels[i] = [0, 0, 0]
        all_pixels.show()
        time.sleep(delay)

def wigwag_vertical(num_times=10, delay=1):
    primary = [255, 255, 255]
    secondary = [0, 0, 0]
    lower = range(0, lower_bank_start - 1)
    upper = range(lower_bank_start, total_pixels - 1)
    for _ in range(0, num_times):
        for i in upper:
            all_pixels[i] = primary
        for i in lower:
            all_pixels[i] = secondary
        all_pixels.show()
        time.sleep(delay)
        for i in upper:
            all_pixels[i] = secondary
        for i in lower:
            all_pixels[i] = primary
        all_pixels.show()
        time.sleep(delay)

def get_led_array():
    """Return the LED array"""
    url = "https://lights.rydercalmdown.com/state/"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()

def blue_white():
    """ """
    for i in range(0, lower_bank_start):
        all_pixels[i]

def flash_leds(num_times=5, delay=0.1):
    """Flashes all the LEDs"""
    for _ in range(0, num_times):
        all_pixels.fill((255, 255, 255))
        all_pixels.show()
        time.sleep(delay)
        all_pixels.fill((0, 0, 0))
        all_pixels.show()
        time.sleep(delay)

def get_standard_colours():
    """Returns a dictionary of colours"""
    return {
        'red': (255, 0, 0),
        'yellow': (255, 150, 0),
        'green': (0, 255, 0),
        'cyan': (0, 255, 255),
        'blue': (0, 0, 255),
        'purple': (180, 0, 255),
    }

def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    if pos < 0 or pos > 255:
        r = g = b = 0
    elif pos < 85:
        r = int(pos * 3)
        g = int(255 - pos * 3)
        b = 0
    elif pos < 170:
        pos -= 85
        r = int(255 - pos * 3)
        g = 0
        b = int(pos * 3)
    else:
        pos -= 170
        r = 0
        g = int(pos * 3)
        b = int(255 - pos * 3)
    return (r, g, b)

def rainbow_cycle(num_times=1):
    for _ in range(0, num_times):
        for j in range(255):
            for i in range(0, lower_bank_start - 1):
                pixel_index = (i * 256 // lower_bank_start - 1) + j
                all_pixels[i] = wheel(pixel_index & 255)
            all_pixels.show()

def explode_from_centre(num_times=1):
    """Explode from the centre"""

    def set_pixel_colour(rgb, halfway_point, i, extra=0):
        try:
            diminisher = round(1-(extra*0.1), 1)
            rgb_calc = [int(round(x*diminisher)) for x in rgb]
            if extra >= 9:
                rgb_calc = [0, 0, 0]
            all_pixels[halfway_point + i - extra] = rgb_calc
            all_pixels[halfway_point - i + extra] = rgb_calc
        except IndexError:
            pass

    for color, rgb in get_standard_colours().items():
        halfway_point = round(total_pixels / 2)
        all_pixels[halfway_point] = rgb
        all_pixels.show()
        for i in range(0, halfway_point):
            for x in range(1, 10):
                set_pixel_colour(rgb, halfway_point, i, x)
            all_pixels.show()

def rainbow_chase(num_times=1):
    """Rainbow chase"""
    original_standard = [value for key, value in get_standard_colours().items()]
    standard_colours = []
    multiplier = 2
    for x in range(0, 1):
        for x in original_standard:
            standard_colours.append(x)

    def set_pixel_colour(rgb, offset, i, extra=0):
        """Determine's the pixels colour"""
        try:
            factor = extra
            diminisher = round(1-(factor*0.1), 1)
            rgb_calc = [int(round(x*diminisher)) for x in rgb]
            if extra >= 9:
                rgb_calc = [0, 0, 0]
            all_pixels[offset + i - extra] = rgb_calc
        except IndexError:
            pass

    for i in range(0, total_pixels - 1):
        for offset in range(0, len(standard_colours) - 1):
            for extra in range(1, 10):
                rgb = standard_colours[offset]
                set_pixel_colour(rgb, offset*20, i, extra)
        all_pixels.show()

def fast_chase(bar_size=5):
    for i in range(0, total_pixels):
        if (i % 2 == 0):
            rgb = [255, 255, 255]
            all_pixels[i] = rgb
            if i != 0:
                all_pixels[i - 1] = rgb
                all_pixels[i - 2] = [0, 0, 0]
                all_pixels[i - 3] = [0, 0, 0]
            all_pixels.show()

def get_lighting_sections(num_sections):
    pixels_per_section = int(total_pixels / num_sections)
    sections = []
    for i in range(0, num_sections):
        section_lower = i * pixels_per_section
        section_upper = (i+1) * pixels_per_section
        s = range(section_lower, section_upper)
        sections.append(s)
    return sections

def pinwheel(num_times=4, delay=0.01, num_sections=10):
    """Pinwheel across quadrants"""
    sections = get_lighting_sections(num_sections)
    for _ in range(num_times):
        current = 0
        rgb = random.choice([v for k, v in get_standard_colours().items()])
        for _ in sections:
            all_pixels.fill([0, 0, 0])
            for i in sections[current]:
                all_pixels[i] = rgb
            all_pixels.show()
            time.sleep(delay)
            current += 1

def call_the_police(num_times=5):
    """Red, blue, white flashes"""
    delay = 0.01
    sections = get_lighting_sections(10)
    colours = [[255, 0, 0], [0, 0, 255], [150, 150, 150]]
    for _ in range(num_times):
        for colour in colours:
            for i in sections[1]:
                all_pixels[i] = colour
            all_pixels.show()
            time.sleep(delay)
        all_pixels.fill([0, 0, 0])
        all_pixels.show()
        time.sleep(delay)
        for colour in colours:
            for i in sections[4]:
                all_pixels[i] = colour
            all_pixels.show()
            time.sleep(delay)
        all_pixels.fill([0, 0, 0])
        all_pixels.show()
        time.sleep(delay)

def colour_flash(num_times=2):
    upper_bank = range(0, lower_bank_start - 1)
    lower_bank = range(lower_bank_start, total_pixels - 1)
    for _ in range(0, num_times):
        for _, rgb in get_standard_colours().items():
            for i in upper_bank:
                all_pixels[i] = rgb
            for i in lower_bank:
                all_pixels[i] = [0, 0, 0]
            all_pixels.show()
            temp_bank = upper_bank
            upper_bank = lower_bank
            lower_bank = temp_bank
            time.sleep(0.15)
    all_pixels.fill([0, 0, 0])

def twinkle(num_times=50, delay=0.01, num_choices=10):
    """Explode from the centre"""
    all_pixels.fill([0, 0, 0])
    all_pixels.show()
    for _ in range(0, num_times):
        choices = [random.randint(0, total_pixels - 1) for x in range(0, num_choices)]
        for i in choices:
            brightness = random.randint(1, 255)
            all_pixels[i] = [brightness, brightness, brightness]
        all_pixels.show()
        time.sleep(delay)
        for i in choices:
            all_pixels[i] = [0, 0, 0]
        all_pixels.show()
        time.sleep(delay)

def shuffle(num_times=20):
    rgb = [0, 0, 255]
    rgb_opposite = [0, 0, 0]
    for _ in range(0, num_times):
        for i in range(0, total_pixels):
            if i % 2 == 0:
                all_pixels[i] = rgb
            else:
                all_pixels[i] = rgb_opposite
        all_pixels.show()
        time.sleep(0.2)
        rgb_temp = rgb
        rgb = rgb_opposite
        rgb_opposite = rgb_temp

def fade_out_all_pixels():
    """Fades out current pixels from their current value"""
    fade_cycles = 12
    for cycle in range(0, fade_cycles):
        for i in range(0, total_pixels):
            all_pixels[i] = [int(x*0.8) for x in all_pixels[i]]
        all_pixels.show()
    for i in range(0, total_pixels):
        all_pixels[i] = [0, 0, 0]
    all_pixels.show()
    time.sleep(0.5)

def do_feature(feature):
    """Entrypoint for doing a custom feature of the lights"""
    print('custom feature: {}'.format(feature))
    fade_out_all_pixels()
    if feature == 'flash':
        colour_flash()
    elif feature == 'chase':
        rainbow_chase()
    elif feature == 'twinkle':
        twinkle()
    elif feature == 'pinwheel':
        pinwheel()

def pulse(num_times=20):
    # TODO - fix
    """Pulses randomly"""
    for _ in range(num_times):
        num_choices = random.randint(5, 25)
        choices = [random.randint(0, total_pixels - 1) for x in range(0, num_choices)]
        # fade block up
        for p in range(1, 255):
            rgb = [p, p, p]
            for i in choices:
                all_pixels[i] = rgb
            all_pixels.show()
        # fade block down
        for p in list(range(1, 255)).reverse():
            rgb = [p, p, p]
            for i in choices:
                all_pixels[i] = rgb
            all_pixels.show()
        time.sleep(0.1)

def run_default():
    """Runs a short default animation while waiting"""
    print('timeout reached, running default')
    shuffle(5)
    print('finished')

def main():
    """Runs the application"""
    led_array = get_led_array()
    if led_array.get('feature'):
        do_feature(led_array['feature'])
        return
    has_state_changed = False
    for i, rgb in led_array.items():
        i = int(i)
        rgb = list(rgb)
        if last_known_state[i] != rgb:
            has_state_changed = True
        last_known_state[i] = rgb
    if has_state_changed:
        for i, rgb in led_array.items():
            i = int(i)
            rgb = list(rgb)
            all_pixels[i] = rgb
        all_pixels.show()
        inactivity_timeout.clear()
    else:
        inactivity_timeout.append(1)
        if len(inactivity_timeout) > 300:
            run_default()
    print(len(inactivity_timeout))

if __name__ == '__main__':
    try:
        while True:
            main()
    except KeyboardInterrupt:
        print('exiting')


#!/home/aubbwc/usr/bin/python3

# ABOUT-----------------------------------------------------------------------
# setting up jobs for Ewald alternative calculations.
# CATIONS =
#   Imidazolium based:  MMIM, EMIM, BMIM, HMIM, OMIM
#   Pyridinum based:    MPYR, EPYR, BPYR, HPYR, OPYR
# ANIONS =
#   BF4, PF6, Cl, AlCl4, Al2Cl4, NO3, TfO
#
# Going to have different values for solvent-solvent cutoffs:
#   9A, 12A, 15A
#
# Alternative methods to Ewald summations:
#   Shifted Force (SF)      : may scale by 0.1, 0.2, 0.3
#   Shifted Potential (SP)  : may also scale
#   Shifted Force Gradient (SFG)
#   (DC)
#   CHARMM
#-------------------------------------------------------------------------------

import os,sys, shutil
import subprocess
from glob import glob
from time import time

starttime = time()

# important file paths
homedir =   os.getcwd()
datafiles = os.path.join(homedir, 'datafiles')
infiles =   os.path.join(datafiles, 'infiles')
slvzmats =  os.path.join(datafiles, 'slvzmats')

# list of cations
imid_cations = ['MMIM', 'EMIM', 'BMIM', 'HMIM', 'OMIM']
pyr_cations =  ['MPYR', 'EPYR', 'BPYR', 'HPYR', 'OPYR']

# NOTE: OMIM and OPYR do not have infiles for ACL's.
# NOTE: BMIM_ACL, EMIM_ACL, and HMIM_ACL are cases which need to be handled
# differently.  The OPLS_IL.par file must be changed.

# methods, scaling factors, cutoffs
methods = ['EWALD_equil', 'NOEWALD','SF', 'SF_0.1', 'SF_0.2', 'SF_0.3','SP',
            'SP_0.1','SP_0.2', 'SP_0.3', 'SFG', 'DC', 'CHARMM']

cutoffs = ['9A', '12A', '15A']

def filesToCopy(cation, anion):

    infile  =   glob(str( infiles + '/' + cation + '+' + anion + '-'))[0]
    dummy   =   os.path.join(datafiles,'dummy.z')
    liqpar  =   os.path.join(datafiles,'liqpar')
    liqcmd  =   os.path.join(datafiles,'liqcmd')
    # need to handle (EMIM|BMIM|HMIM) + ACLs appropriately
    liqzmat =   glob(str(slvzmats + '/' + cation + '_liqzmat'))[0]
    if cation == 'EMIM' or cation == 'BMIM' or cation == 'HMIM':
        if anion == 'ACL4' or anion == 'ACL7':
            liqzmat = glob(str(slvzmats +'/'+ cation +'-ACL_liqzmat'))[0]

    cshfile =   os.path.join(datafiles, 'IL_ewald.csh')
    ILpar   =   os.path.join(datafiles, 'IL-OPLS.par')
    ILsb    =   os.path.join(datafiles, 'IL-OPLS.sb')

    return [infile, dummy, liqpar, liqcmd, liqzmat, cshfile, ILpar, ILsb]

def sed(textToReplace, replacementText, filename):
    filecontents = open(filename, 'r').read()
    newcontents = filecontents.replace(textToReplace, replacementText)
    file = open(filename, 'w')
    file.write(newcontents)
    file.close()

# ICUTAS ARRAYS
icutas = {'EMIM':'  0  0  5 17  6 10  0  0',
          'MMIM':'  0  0  6 11  6 10  0  0',
          'BMIM':'  0  0  5 24 11  6 10  0',
          'HMIM':'  0  0  5 30 21 11  6 10',
          'OMIM':'  0  0  5 36 27 11  6 10',
          'BPYR':'  0  0  6 23 17  6  3  0',
          'EPYR':'  0  0  6 17  6  3  0  0',
          'HPYR':'  0  0  6 23 17  6  3  0',
          'MPYR':'  0  0  6 14  6  3  0  0',
          'OPYR':'  0  0  6 23 17  6  3  0',
          }

for cation in pyr_cations:
    # list of anions
    anions = ['BF4', 'PF6', 'Cl', 'NO3', 'TFO', 'ACL4', 'ACL7']

    if cation == 'OMIM' or cation == 'OPYR':
        # cations OMIM and OPYR do not have ACL anions associated with them
        anions = ['BF4', 'PF6', 'Cl', 'TFO']
    if cation == 'HPYR' or cation == 'OPYR':
        anions = ['BF4', 'PF6', 'Cl']

    for anion in anions:
        for cutoff in cutoffs:
            for method in methods:
                pathname = os.path.join(homedir, cation, anion, cutoff, method)
                print("\tBeginning %s.%s.%s.%s." %(cation, anion, cutoff,
                    method))
                os.makedirs(pathname)
                #copy all files into relevant directory
                files = filesToCopy(cation,anion)
                [ shutil.copy(file, pathname) for file in files ]
                [ print("\t\t%s copied." % file) for file in files ]

                # set the correct pathname for files
                infile  = os.path.join(pathname, files[0].split('/')[-1])
                dummy   = os.path.join(pathname, files[1].split('/')[-1])
                liqpar  = os.path.join(pathname, files[2].split('/')[-1])
                liqcmd  = os.path.join(pathname, files[3].split('/')[-1])
                liqzmat = os.path.join(pathname, files[4].split('/')[-1])
                cshfile = os.path.join(pathname, files[5].split('/')[-1])
                ILpar   = os.path.join(pathname, files[6].split('/')[-1])
                ILsb    = os.path.join(pathname, files[7].split('/')[-1])

                # edit files accordingly
                # liqpar: set icutas array and cutoff
                # anions Cl, NO3, and TFO need - sign in the principal solvent
                if anion == 'Cl' or anion == 'NO3' or anion == 'TFO':
                    sed('ANION', str(anion + '-'), liqpar)
                else:
                    sed('ANION', anion, liqpar)

                sed('icutas', icutas[cation], liqpar)
                sed('XX', cutoff[:-1], liqpar)
                # csh file
                cshstring = str(cation +'.'+ anion +'.'+ cutoff +'.' + method)
                sed('TYPE', cshstring, cshfile)
                sed('LOCAL', pathname, cshfile)
                sed('ANION', anion, cshfile)
                # liqcmd
                sed('ANION', anion, liqcmd)

                # move file names to those specified in par and cmd files
                # csh file
                shutil.move(cshfile, os.path.join(pathname, str(cshstring +
                    '.csh')))
                #infile
                shutil.move(infile, os.path.join(pathname, 'liqin'))
                # slvzmat
                shutil.move(liqzmat, os.path.join(pathname, 'liqzmat'))

                # OMIM and OPYR with ACL must have IL_OPLS.par params edited
                if cation == 'EMIM' or cation == 'BMIM ' or cation == 'HMIM':
                    if anion == 'ACL4' or anion == 'ACL7':
                        sed('2711', '2811', ILpar)
                        sed('2712', '2812', ILpar)

                print("\tDone with %s.%s.%s.%s.\n" % (cation, anion, cutoff,
                        method))
                if "submit" in sys.argv:
                    currentdir = os.getcwd()
                    os.chdir(pathname)
                    submitcmd = glob('*csh')
                    subprocess.call(["/home/aubbwc/scripts/runboss", submitcmd[0]])
                    os.chdir(currentdir)

stoptime = time()
runtime = stoptime - starttime
print("Script" + sys.argv[0] + " completed in {x:.1f} seconds.".format( x =
    runtime))
sys.exit(0)


from gzip import READ
from turtle import st
from django.shortcuts import get_object_or_404, render
from django.urls import is_valid_path
from movies_app.models import *
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response

from .serializers import *

# Create your views here.
def get_movies_list(request: Request):
    movies_qs = Movie.objects.all()
    if "name" in request.query_params:
        movies_qs = movies_qs.filter(name__iexact=request.query_params["name"])
    if "duration_from" in request.query_params:
        movies_qs = movies_qs.filter(
            duration_in_min__gte=request.query_params["duration_from"]
        )
    if "duration_to" in request.query_params:
        movies_qs = movies_qs.filter(
            duration_in_min__lte=request.query_params["duration_to"]
        )
    if "description" in request.query_params:
        movies_qs = movies_qs.filter(
            description__icontains=request.query_params["description"]
        )

    if not movies_qs:
        return Response(status=status.HTTP_204_NO_CONTENT)

    serializer = MovieSerializer(movies_qs, many=True)
    return Response(serializer.data)

@api_view(["GET", "POST"])
def movies_list(request: Request):
    if request.method == "GET":
        return get_movies_list(request)
    elif request.method == "POST":
        serializer = MovieDetailsSerializer(data=request.data)  # type: ignore
        if serializer.is_valid(raise_exception=True):
            serializer.create(serializer.validated_data)
            return Response(status=status.HTTP_201_CREATED)

@api_view(["GET", "PATCH", "DELETE"])
def movie_details(request: Request, movie_id: int):
    movie = get_object_or_404(Movie, id=movie_id)
    if request.method == "GET":
        serializer = MovieDetailsSerializer(movie, many=False)
        return Response(serializer.data)
    elif request.method == "PATCH":
        serializer = MovieDetailsSerializer(
            movie,
            data=request.data,  # type: ignore
            many=False,
            partial=True,
        )
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(status=status.HTTP_200_OK)
    elif request.method == "DELETE":
        movie.delete()
        return Response(status=status.HTTP_200_OK)

@api_view(["GET"])
def ratings_list(request: Request):
    ratings_qs = Rating.objects.all()

    if (
        "rating" in request.query_params
        and ("rating_from" or "rating_to") in request.query_params
    ):
        return Response(status=status.HTTP_400_BAD_REQUEST)

    if "rating" in request.query_params:
        ratings_qs = ratings_qs.filter(rating=request.query_params["rating"])
    else:
        if "rating_from" in request.query_params:
            ratings_qs = ratings_qs.filter(
                rating__gte=request.query_params["rating_from"]
            )
        if "rating_to" in request.query_params:
            ratings_qs = ratings_qs.filter(
                rating__lte=request.query_params["rating_to"]
            )

    if (
        "date" in request.query_params
        and ("date_from" or "date_to") in request.query_params
    ):
        return Response(status=status.HTTP_400_BAD_REQUEST)

    if "date" in request.query_params:
        ratings_qs = ratings_qs.filter(rating_date=request.query_params["date"])
    else:
        if "date_from" in request.query_params:
            ratings_qs = ratings_qs.filter(
                rating_date__gte=request.query_params["date_from"]
            )
        if "date_to" in request.query_params:
            ratings_qs = ratings_qs.filter(
                rating_date__lte=request.query_params["date_to"]
            )

    if not ratings_qs:
        return Response(status=status.HTTP_204_NO_CONTENT)

    serializer = RatingSerializer(ratings_qs, many=True)
    return Response(serializer.data)

@api_view(["GET", "POST"])
def movie_actors(request: Request, movie_id: int):
    if request.method == "GET":
        movie_actors = MovieActor.objects.filter(movie_id=movie_id)
        if "main_roles" in request.query_params:
            is_true = request.query_params["main_roles"] == "1"
            if is_true:
                movie_actors = movie_actors.filter(main_role=True)
        if "salary_from" in request.query_params:
            movie_actors = movie_actors.filter(
                salary__gte=request.query_params["salary_from"]
            )
        if "salary_to" in request.query_params:
            movie_actors = movie_actors.filter(
                salary__lte=request.query_params["salary_to"]
            )
        serializer = MovieActorSerializer(movie_actors, many=True)
        return Response(serializer.data)
    elif request.method == "POST":
        get_object_or_404(Movie, id=movie_id)
        serializer = AddMovieActorSerializer(
            data=request.data,  # type: ignore
            context={"movie_id": movie_id, "request": request},
        )
        if serializer.is_valid(raise_exception=True):
            serializer.create(serializer.validated_data)
            return Response(status=status.HTTP_200_OK)

@api_view(["POST"])
def create_actor(request: Request):
    serializer = ActorSerializer(data=request.data)  # type: ignore
    if serializer.is_valid(raise_exception=True):
        serializer.create(validated_data=serializer.validated_data)
        return Response(status=status.HTTP_201_CREATED)

@api_view(["GET", "PATCH", "DELETE"])
def actor_details(request: Request, actor_id: int):
    actor = get_object_or_404(Actor, id=actor_id)
    if request.method == "GET":
        serializer = ActorSerializer(instance=actor, many=False)
        return Response(serializer.data)
    elif request.method == "PATCH":
        serializer = ActorSerializer(
            actor,
            data=request.data,  # type: ignore
            many=False,
            partial=True,
        )
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(status=status.HTTP_200_OK)
    elif request.method == "DELETE":
        actor.delete()
        return Response(status=status.HTTP_200_OK)

@api_view(["DELETE", "PATCH"])
def alter_movie_actor(request: Request, movie_id: int, actor_id: int):
    movieactor = get_object_or_404(MovieActor, movie_id=movie_id, actor_id=actor_id)
    if request.method == "DELETE":
        movieactor.delete()
        return Response(status=status.HTTP_200_OK)

    elif request.method == "PATCH":
        serializer = MovieActorPatchSerializer(
            movieactor,
            data=request.data,  # type: ignore
            many=False,
            partial=True,
        )
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(status=status.HTTP_200_OK)

@api_view(["POST", "GET"])
def movie_rating(request: Request, movie_id: int):
    if request.method == "POST":
        serializer = AddRatingSerializer(
            data=request.data,  # type: ignore
            context={
                "movie_id": movie_id,
                "request": request,
            },
        )
        if serializer.is_valid(raise_exception=True):
            serializer.create(validated_data=serializer.validated_data)
            return Response(status=status.HTTP_201_CREATED)

    if request.method == "GET":
        ratings = Rating.objects.filter(movie_id=movie_id)
        if not ratings:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = SpecificMovieRatingsSerializer(instance=ratings, many=True)
        return Response(serializer.data)

@api_view(["DELETE"])
def delete_movie_rating(request: Request, movie_id: int, rating_id: int):
    rating = get_object_or_404(Rating, movie_id=movie_id, id=rating_id)
    rating.delete()
    return Response(status=status.HTTP_200_OK)

def index(request):
    return render(request, "index.html")


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="iidfile",
    version="0.2.0",
    author="aeaeaeae",
    author_email="ouououou@aeaeaeae.io",
    description="File parser for .iid files, for storing labeled image segmentation data.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/aeaeaeaeaeae/iidformat",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
        "Operating System :: OS Independent",
        "Development Status :: 4 - Beta",
    ],
    python_requires='>=3.6',
)


import os
import csv
import unicodedata
import datetime
import eel

### 引数textの全角文字数カウント
def get_zen_count(text):
	count=0
	for c in text:
		if unicodedata.east_asian_width(c) in "FWA":
			count +=1
	return count

### 商品クラス
class Item:
	def __init__(self,code,name,price,cnt):
		self.item_code=code
		self.item_name=name
		self.item_price=price
		self.item_cnt=cnt

### 注文クラス
class Order:
	def __init__(self):
		self.order_list=[]
		self.order_cnt = 0
		self.order_price = 0

	def item_data_to_text(self,co,na,pr,n):
		na_width = 10-get_zen_count(na)
		pr_total = str( int(pr)*int(n) ).rjust(5)
		return co.ljust(4) + na.ljust(na_width) + str(pr).rjust(4)+"円" + str(n).rjust(3)+"個   = " + pr_total+"円\n"

	def add_order_list(self,code,name,price,cnt):
		add_flg = 0
		for item in self.order_list:
			if item.item_code == code:
				item.item_code = code
				item.item_name = name
				item.item_price = price
				item.item_cnt = str(int(item.item_cnt) + int(cnt))
				self.order_cnt += int(cnt)
				self.order_price += int(price)*int(cnt)
				add_flg = 1
			# JS に書き出し
			eel.order_list_add_write_js(self.item_data_to_text(item.item_code,item.item_name,item.item_price,item.item_cnt))

		if add_flg == 0:
			self.order_cnt += int(cnt)
			self.order_price += int(price)*int(cnt)
			self.order_list.append(Item(code,name,price,cnt))
			# JS に書き出し
			eel.order_list_add_write_js(self.item_data_to_text(code,name,price,cnt))
		eel.order_list_add_write_js("-------------------------------------\n")
		eel.order_list_add_write_js("合計                "+str(self.order_cnt).rjust(3)+"個     "+str(self.order_price).rjust(5)+"円\n")

	def del_order_list(self,code, name, price, cnt):
		del_flg = -1
		del_cnt = 0
		i = 0
		# price:str、cnt:str、item_price:str、item_cnt:str
		for item in self.order_list:
			if item.item_code == code:
				item.item_code = code
				item.item_name = name
				item.item_price = price
				if int(item.item_cnt) <= int(cnt):
					del_cnt = int(item.item_cnt)
					del_flg = i
				else:
					del_cnt = int(cnt)
					del_flg = -2
				item.item_cnt = str(int(item.item_cnt) - del_cnt)
				self.order_cnt -= del_cnt
				self.order_price -= int(price)*del_cnt
			# JS に書き出し
			if item.item_cnt != "0":
				eel.order_list_add_write_js(self.item_data_to_text(item.item_code,item.item_name,item.item_price,item.item_cnt))
			i += 1
		if del_flg == -1:
			i = name.find("　")
			eel.alert_js(f"「{name[:i]}」はかごに入っていません")
		if del_flg >= 0:
			self.order_list.pop(del_flg)
		if len(self.order_list) != 0:
			eel.order_list_add_write_js("-------------------------------------\n")
			eel.order_list_add_write_js("合計                "+str(self.order_cnt).rjust(3)+"個     "+str(self.order_price).rjust(5)+"円\n")

	def order_payment(self,cash):
		# print(type(cash))   str
		# print(type(self.order_cnt))   int
		# print(type(self.order_price))   int
		cash = int(cash)
		if cash < self.order_price:
			eel.payment_result_js(cash-self.order_price)
		else:
			# おつり計算と表示
			eel.order_list_add_write_js(f"お預かり                      {str(cash).rjust(5)}円\n")
			if cash == self.order_price:
				eel.alert_js(f"{cash}円丁度、お預かりします。")
			else:
				eel.order_list_add_write_js(f"おつり                        {str(int(cash) -self.order_price).rjust(5)}円\n")
				eel.alert_js(f"{cash}円お預かりし、{cash-self.order_price}円のおつりになります。")
			self.receipt_txt(cash)
			eel.payment_result_js(0)

	#レシートをファイルに出力
	def receipt_txt(self,cash):
		order_time = datetime.datetime.now()
		file_name = order_time.strftime("order_%Y-%m-%d_%H%M")
		if not os.path.isfile(file_name):
			with open( file_name+".txt", encoding="UTF-8", mode="w") as f:
				# ファイルに書き込む
				f.write("\n" + file_name+"\n")
				f.write("-------------------------------------\n")
				for item in self.order_list:                         #注文の合計を表示
					f.write(self.item_data_to_text(item.item_code,item.item_name,item.item_price,item.item_cnt))

				# 合計点数、合計金額の表示
				f.write("-------------------------------------\n")
				f.write(f"合計                "+str(self.order_cnt).rjust(3)+"個     "+str(self.order_price).rjust(5)+"円\n")
				f.write(f"お預かり                      {str(cash).rjust(5)}円\n")
				f.write(f"おつり                        {str(int(cash) -self.order_price).rjust(5)}円\n")
				f.write("-------------------------------------\n")
				f.write("\n「お買い上げありがとうございました。」\n")
				return file_name
		else:
			return "Error"

### csvファイルの読み込み
def set_item_master_csv(csv_file):
	with open(csv_file,encoding="utf_8",newline="") as items_csv:
		item_master = csv.reader(items_csv)
		next(item_master)

		# 商品リストを読み込む前にテキストエリアを空にする
		eel.item_list_add_item_js()
		for item in item_master:
			eel.item_list_add_item_js(item[0],item[1],item[2])


from django.shortcuts import render
from .models import *
import pandas as pd
import numpy as np
import json
from django.http import JsonResponse
from django.db.models import Sum
import itertools

# Create your views here.

def home(request):
    data=CooperativeSociety.objects.all()

    ##=====================Getting Totals of column distinct value=============================================##
    tot_society=data.count()
    df1 = CooperativeSociety.objects.all().values()
    df = pd.DataFrame.from_records(df1)
    total_society = df.shape[0]
    dist_state=df['sector_state'].unique()
    tot_state = np.unique(dist_state).size
    df1 = df[df['sector_district'].notna()]
    dist_district=df1['sector_district'].unique()
    tot_district = np.unique(dist_district).size

    ##====geting area of operation  =======
    df1=df
    df1['Column1'] = df['sector_area_of_operation'].str.split(',')

    # Explode the values into separate rows
    df1 = df1.explode('Column1')

    # Remove leading/trailing whitespaces
    df1['Column1'] = df1['Column1'].str.strip()

    # Get distinct values and skip blank values
    distinct_area = df1.loc[df1['Column1'] != '', 'Column1'].unique()
    distinct_area=distinct_area.size
    ##===================================

    ###++++++++++++++++++++++++++++++++++Bar chart+++++++++++++++++++++++++++++++++##

    queryset = CooperativeSociety.objects.values('sector_registration_date')
    # Convert the queryset to a pandas DataFrame
    df_year = pd.DataFrame.from_records(queryset)

    # Extract the year from the date_of_registration column
    df_year['Year'] = pd.to_datetime(df_year['sector_registration_date']).dt.year

    # Group the data by year and get the count
    countss = df_year['Year'].value_counts().sort_index()
    years = countss.index.astype(str).tolist()

    ##==================================End

    sector_state_counts = CooperativeSociety.objects.exclude(sector_state=None).values('sector_state').annotate(count=Count('sector_state'))

    # Convert the queryset to a pandas DataFrame
    df = pd.DataFrame.from_records(sector_state_counts)

    # Convert the DataFrame to a dictionary
    sector_state_counts_dict = df.set_index('sector_state')['count'].to_dict()
    print(sector_state_counts_dict)
    sector_state_dis = CooperativeSociety.objects.exclude(sector_district__isnull=True).values('sector_district').annotate(count=Count('sector_district'))
    df12 = pd.DataFrame.from_records(sector_state_dis)
    sector_state_counts_dict_dis = df12.set_index('sector_district')['count'].to_dict()

    colors = [
        '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF',
        '#FF00FF', '#800000', '#008000', '#000080', '#808000',
        '#800080', '#008080', '#808080', '#FFA500', '#FFC0CB',
        '#FFB6C1', '#FFD700', '#ADFF2F', '#00FF7F', '#87CEEB'
    ]
    color_cycle = itertools.cycle(colors)

    data_dict={
        'tot_society':total_society,
        'tot_state':tot_state,
        'tot_district':tot_district,
        'distinct_area':distinct_area,
        'years':years,
        'sector_state_counts':sector_state_counts_dict,
        'color_cycle':color_cycle,
        'sector_state_counts_dict_dis':sector_state_counts_dict_dis
         }

    return render(request,'home.html',data_dict)

def Barchart(request):

    queryset = CooperativeSociety.objects.values('sector_registration_date')
    # Convert the queryset to a pandas DataFrame
    df = pd.DataFrame.from_records(queryset)

    # Extract the year from the date_of_registration column
    df['Year'] = pd.to_datetime(df['sector_registration_date']).dt.year

    # Group the data by year and get the count
    counts = df['Year'].value_counts().sort_index()

    # Prepare the data for Chart.js
    chart_labels = counts.index.astype(str).tolist()
    chart_values = counts.values.tolist()

    data = {
        'labels': chart_labels,
        'data': chart_values,
    }

    return JsonResponse(data)
import json
import numpy as np

def barch(request):
    if request.GET.get('year', None) is not None:
        year = request.GET.get('year')
        queryset = CooperativeSociety.objects.values('sector_registration_date')
        # Convert the queryset to a pandas DataFrame
        df = pd.DataFrame.from_records(queryset)
        df['sector_registration_date'] = pd.to_datetime(df['sector_registration_date'])

        # Filter a specific year (e.g., 2022)
        year_to_filter = int(year)
        filtered_df = df[df['sector_registration_date'].dt.year == year_to_filter]

        # Get the count of each month for the filtered year
        month_counts = filtered_df['sector_registration_date'].dt.month.value_counts().sort_index()

        # Create a list of counts with zeros for missing months
        month_counts_list = [month_counts.get(month, 0) for month in range(1, 13)]
        month_word = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        chart_labels = month_word
        chart_values = [int(count) for count in month_counts_list]  # Convert int64 to int

        data = {
            'labels': chart_labels,
            'data': chart_values,
        }

        return JsonResponse(data)
def testing(request):

    queryset = CooperativeSociety.objects.values('sector_registration_date')

    df = pd.DataFrame.from_records(queryset)

    # Extract the year from the date_of_registration column
    df['Year'] = pd.to_datetime(df['sector_registration_date']).dt.year

    # Group the data by year and get the count
    counts = df['Year'].value_counts().sort_index()
    chart_labels1 = counts.index.astype(str).tolist()

    return render(request,'testing.html',{'chart_labels1':chart_labels1})

def registered_mscs_by_location(request):
    # Query the database to get the count of registered MSCS by district
    counts = CooperativeSociety.objects.values('state_district').exclude(sector__isnull=True).annotate(count=models.Count('id'))

    # Extract the district names and their respective counts
    labels = [entry['state_district'] for entry in counts]
    data = [entry['count'] for entry in counts]

    # Prepare the data for the chart
    chart_data = {
        'labels': labels,
        'data': data,
    }

    return JsonResponse(chart_data)

def mscs_sector_pie_chart(request):

    # Retrieve the data from the CooperativeSociety table and calculate MSCS count in each sector
    # Retrieve the data from the CooperativeSociety table
    queryset = CooperativeSociety.objects.values('sector_sector_type')

    # Convert the queryset to a pandas DataFrame
    df = pd.DataFrame.from_records(queryset)

    # Drop rows with null values in the 'sector' column
    df = df.dropna(subset=['sector_sector_type'])

    # Calculate the count of MSCS in each sector
    sector_counts = df['sector_sector_type'].value_counts()

    # Calculate the percentage of each sector
    total_count = sector_counts.sum()
    sector_percentages = (sector_counts / total_count) * 100

    sector_percentages = sector_percentages.round(0)
    # Prepare the data for the pie chart
    labels = sector_counts.index.tolist()
    data = sector_percentages.values.tolist()
    chart_data = {
        'labels': labels,
        'data': data
    }

    return JsonResponse(chart_data)

def mscs_state_percentage_chart(request):
     # Retrieve the data from the CooperativeSociety table
    queryset = CooperativeSociety.objects.all()

    # Convert the queryset to a pandas DataFrame
    df = pd.DataFrame.from_records(queryset.values('sector_state'))

    # Drop rows with null values in the 'state' column
    df = df.dropna(subset=['sector_state'])

    # Calculate the percentage distribution of MSCS across states
    state_percentages = df['sector_state'].value_counts(normalize=True) * 100

    # Format the percentages with 1 decimal place
    state_percentages = state_percentages.round(1)

    # Prepare the data for the chart
    labels = state_percentages.index.tolist()
    data = state_percentages.values.tolist()

    chart_data = {
        'labels': labels,
        'data': data
    }

    return JsonResponse(chart_data)

def mscs_district_percentage_chart(request):
     # Retrieve the data from the CooperativeSociety table
    queryset = CooperativeSociety.objects.all()

    # Convert the queryset to a pandas DataFrame
    df = pd.DataFrame.from_records(queryset.values('sector_district'))

    # Drop rows with null values in the 'state' column
    df = df.dropna(subset=['sector_district'])

    # Calculate the percentage distribution of MSCS across states
    state_percentages = df['sector_district'].value_counts(normalize=True) * 100

    # Format the percentages with 1 decimal place
    state_percentages = state_percentages.round(1)

    # Prepare the data for the chart
    labels = state_percentages.index.tolist()
    data = state_percentages.values.tolist()

    chart_data = {
        'labels': labels,
        'data': data
    }

    return JsonResponse(chart_data)

import json
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from .models import CooperativeSociety

@require_GET
def registered_mscs_by_state(request):
    data = CooperativeSociety.objects.values('sector_state', 'sector_registration_date')
    processed_data = {}

    for entry in data:
        state = entry['sector_state']
        registration_date = entry['sector_registration_date'].strftime('%Y-%m-%d')

        if state not in processed_data:
            processed_data[state] = {}

        if registration_date not in processed_data[state]:
            processed_data[state][registration_date] = 0

        processed_data[state][registration_date] += 1

    return JsonResponse(processed_data)

import json
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render
from .models import CooperativeSociety

def stacked_area_chart_data_sector(request):
    sectors = CooperativeSociety.objects.values_list('sector_sector_type', flat=True).distinct()
    dates = CooperativeSociety.objects.values_list('sector_registration_date', flat=True).distinct().order_by('sector_registration_date')

    data = []
    for sector in sectors:
        sector_data = []
        for date in dates:
            count = CooperativeSociety.objects.filter(sector_sector_type=sector, sector_registration_date__lte=date).count()
            sector_data.append(count)
        data.append(sector_data)

    chart_labels = [date.strftime('%Y-%m-%d') for date in dates]
    chart_data = {
        'labels': chart_labels,
        'datasets': []
    }

    for i, sector in enumerate(sectors):
        dataset = {
            'label': sector,
            'data': data[i]
        }
        chart_data['datasets'].append(dataset)

    print(chart_data['datasets'].pop())
    return JsonResponse(chart_data)

def stacked_area_chart_data_state(request):
    sectors = CooperativeSociety.objects.values_list('sector_state', flat=True).distinct()
    dates = CooperativeSociety.objects.values_list('sector_registration_date', flat=True).distinct().order_by('sector_registration_date')

    data = []
    for sector in sectors:
        sector_data = []
        for date in dates:
            count = CooperativeSociety.objects.filter(sector_state=sector, sector_registration_date__lte=date).count()
            sector_data.append(count)
        data.append(sector_data)

    chart_labels = [date.strftime('%Y-%m-%d') for date in dates]
    chart_data = {
        'labels': chart_labels,
        'datasets': []
    }

    for i, sector in enumerate(sectors):
        dataset = {
            'label': sector,
            'data': data[i]
        }
        chart_data['datasets'].append(dataset)

    return JsonResponse(chart_data)

def treemap_data(request):
    data = CooperativeSociety.objects.all().values('sector_sector_type')
    df = pd.DataFrame.from_records(data)
    df = df.dropna(subset=['sector_sector_type'])
    registrations = df['sector_sector_type'].value_counts().reset_index()
    registrations.columns = ['sector_sector_type', 'count']
    treemap_data = []
    for index, row in registrations.iterrows():
        treemap_data.append({
            'id': row['sector_sector_type'],
            'name': row['sector_sector_type'],
            'parent': '',
            'value': row['count']
        })
    return JsonResponse(treemap_data, safe=False)

def bubble_map_view(request):
    cooperative_societies = CooperativeSociety.objects.all()
    return render(request, 'testing.html', {'cooperative_societies': cooperative_societies})

from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from .models import CooperativeSociety

from django.shortcuts import render
from .models import CooperativeSociety
def your_view(request):

    # Retrieve query parameters from the request
    search_query = request.GET.get('search_query', '')
    sector_state = request.GET.getlist('sector_state[]')
    sector_district = request.GET.getlist('sector_district[]')
    sector_area_of_operation = request.GET.getlist('sector_area_of_operation[]')
    sector_sector_type = request.GET.getlist('sector_sector_type[]')
    sector_registration_start_date = request.GET.get('sector_registration_start_date')
    sector_registration_end_date = request.GET.get('sector_registration_end_date')

    # Perform filtering based on the selected values
    queryset = CooperativeSociety.objects.all()

    if search_query:
        queryset = queryset.filter(sector_name__icontains=search_query) | queryset.filter(sector_address__icontains=search_query)

    if sector_state:
        queryset = queryset.filter(sector_state__in=sector_state)

    if sector_district:
        queryset = queryset.filter(sector_district__in=sector_district)

    if sector_area_of_operation:
        queryset = queryset.filter(sector_area_of_operation__in=sector_area_of_operation)

    if sector_sector_type:
        queryset = queryset.filter(sector_sector_type__in=sector_sector_type)

    if sector_registration_start_date:
        queryset = queryset.filter(sector_registration_date__gte=sector_registration_start_date)

    if sector_registration_end_date:
        queryset = queryset.filter(sector_registration_date__lte=sector_registration_end_date)

    # Pagination
    paginator = Paginator(queryset, 5)  # Assuming 10 objects per page
    page_number = request.GET.get('page')
    objects = paginator.get_page(page_number)

    # Retrieve distinct values for filter options
    states = CooperativeSociety.objects.values_list('sector_state', flat=True).distinct()
    districts = CooperativeSociety.objects.exclude(sector_district__isnull=True).values_list('sector_district', flat=True).distinct()
    sector_types = CooperativeSociety.objects.exclude(sector_sector_type__isnull=True).values_list('sector_sector_type', flat=True).distinct()

    areas = CooperativeSociety.objects.values_list('sector_area_of_operation', flat=True).distinct()

    # Prepare context data
    context = {
        'search_query': search_query,
        'sector_state': sector_state,
        'sector_district': sector_district,
        'sector_area_of_operation': sector_area_of_operation,
        'sector_sector_type': sector_sector_type,
        'sector_registration_start_date': sector_registration_start_date,
        'sector_registration_end_date': sector_registration_end_date,
        'states': states,
        'districts': districts,
        'areas': areas,
        'sector_types': sector_types,
        'objects': objects
    }

    return render(request, 'filter.html', context)


#!/usr/bin/env python3

import os
import sys
import manai
import argparse
import time

def loading_animation():
    animation_chars = ['-','\\','|','/']
    idx = 0

    while not animation_complete.is_set():
        print(animation_chars[idx % len(animation_chars)], end='\r')
        idx += 1
        time.sleep(0.1)

def parse_args():
    custom_usage = "manai [-c COMMAND] [-d DIALOG]"
    parser = argparse.ArgumentParser(description='manai command line tool', usage=custom_usage)
    #group = parser.add_mutually_exclusive_group(required=True)
    parser.add_argument('-c', '--command', help='Command or library you wish to get help with')
    parser.add_argument('-m', '--message', help='Message to send to manai')
    parser.add_argument('-l', '--login', help='Login or create account for manai', required=False, nargs='?')
    parser.add_argument('-d', '--dialog', help='Start a dialog with manai', required=False, nargs='?')
    parser.add_argument('command', nargs='?', help='Command or library you wish to get help with')
    return parser.parse_args()

def process_args(args):
    message = args.message
    login = args.login
    command = args.command
    dialog = args.dialog

    print(args)

    if login:
        # go to login stuff
        pass
    elif dialog:
        # start dialog
        pass
    elif command and message:

        response = manai.command_message(command, message)
        formatted_response = f"manai: \n{'='*100}\n{response}\n{'='*100}"
        print(formatted_response)
    elif command:
        response = manai.manai_command(command)
        formatted_response = f"manai: \n{'='*100}\n{response}\n{'='*100}"
        print(formatted_response)
    elif message:
        response = manai.manai_message(message)
        formatted_response = f"manai: \n{'='*100}\n{response}\n{'='*100}"
        print(formatted_response)
    else:
        print("Please use both -c and -m together to send a message to manai. Use '-h' for help.")

args = parse_args()
process_args(args)


##5. Дві матриці заповнюються введенням з клавіатури. В елементи третьої матриці
##такої ж розмірності записати більші з відповідних елементів перших двох.
row = int(input("Enter the count of rows: "))
col = int(input("Enter the count of columns: "))
lst1 = [[0] * col for i in range(row)]
##lst2 = list(lst1)     Чомусь таким способом після ініціалізації список 1
##                        вбирає в себе значення списку 2, хоча id у них різні, я перевіряв
lst2 = [[0] * col for i in range(row)]
for i in range(row):
    for j in range(col):
        lst1[i][j] = int(input("Enter the number in first list: "))
    print()
print()
for i in range(row):
    for j in range(col):
        lst2[i][j] = int(input("Enter the number in second list: "))
    print()
print()

print("List 1:\n", lst1)
print("List 2:\n", lst2)

lst3 = [[0] * col for i in range(row)]
print("List 3:")
for i in range(row):
    for j in range(col):
        if lst1[i][j] >= lst2[i][j]:
            lst3[i][j] = lst1[i][j]
        else:
            lst3[i][j] = lst2[i][j]
        print("%2d "%lst3[i][j], end = "")
    print()
print()