import pathlib

import matplotlib
import matplotlib.pyplot as plt

import palom

def align_he(
    p1: str | pathlib.Path,
    p2: str | pathlib.Path,
    out_dir: str | pathlib.Path,
    out_name: str = None,
    thumbnail_channel1: int = 1,
    thumbnail_channel2: int = 2,
    channel1: int = 0,
    channel2: int = 2,
    px_size1: float = None,
    px_size2: float = None,
    n_keypoints: int = 10_000,
    auto_mask=True,
    only_coarse: bool = False,
    only_qc: bool = False,
    viz_coarse_napari: bool = False,
    multi_res: bool = False,
    multi_obj: bool = False,
    multi_obj_kwarg: dict = None
):
    assert not (multi_res and multi_obj), (
    'setting both `multi_res` and `multi_obj` to `True` is not supported,'
    ' choose at most one'
    )
    out_dir, p1, p2 = pathlib.Path(out_dir), pathlib.Path(p1), pathlib.Path(p2)
    if out_name is None:
        out_name = f"{p2.stem}-registered.ome.tif"
    out_path = out_dir / out_name
    assert ''.join(out_path.suffixes[-2:]) in ('.ome.tif', '.ome.tiff')
    out_path.parent.mkdir(exist_ok=True, parents=True)
    set_matplotlib_font(font_size=8)

    r1 = get_reader(p1)(p1, pixel_size=px_size1)
    r2 = get_reader(p2)(p2, pixel_size=px_size2)

    LEVEL = 0
    aligner = palom.align.get_aligner(
        r1, r2,
        level1=LEVEL, level2=LEVEL,
        channel1=channel1, channel2=channel2,
        # make thumbnail level pair based on pixel_size
        thumbnail_level1=None,
        thumbnail_channel1=thumbnail_channel1, thumbnail_level2=thumbnail_channel2
    )

    aligner.coarse_register_affine(
        n_keypoints=n_keypoints,
        test_flip=True,
        test_intensity_invert=True,
        auto_mask=auto_mask
    )
    fig, ax = plt.gcf(), plt.gca()
    fig.suptitle(f"{p2.name} (coarse alignment)", fontsize=8)
    ax.set_title(f"{p1.name} - {p2.name}", fontsize=6)
    im_h, im_w = ax.images[0].get_array().shape
    set_subplot_size(im_w/288, im_h/288, ax=ax)
    ax.set_anchor('N')
    # use 0.5 inch on the top for figure title
    fig.subplots_adjust(top=1 - .5 / fig.get_size_inches()[1])
    save_all_figs(out_dir=out_dir / 'qc', format='jpg', dpi=144)

    if viz_coarse_napari:
        _ = viz_coarse(r1, r2, LEVEL, LEVEL, channel1, channel2, aligner.affine_matrix)

    if not only_coarse:
        # the default
        if not (multi_res or multi_obj):
            aligner.compute_shifts()

            fig = aligner.plot_shifts()
            fig.suptitle(f"{p2.name} (block shift distance)", fontsize=8)
            fig.axes[0].set_title(p1.name, fontsize=6)
            save_all_figs(out_dir=out_dir / 'qc', format='png')

            aligner.constrain_shifts()
            block_mx = aligner.block_affine_matrices_da
        elif multi_res:
            mr_aligner = palom.align_multi_res.MultiResAligner(
                r1, r2,
                level1=LEVEL,
                channel1=channel1, channel2=channel2,
                thumbnail_channel1=thumbnail_channel1,
                thumbnail_channel2=thumbnail_channel2,
                min_num_blocks=25
            )
            mr_aligner._coarse_affine_matrix = aligner.coarse_affine_matrix
            mr_aligner.align()
            mr_aligner.constrain_shifts()

            fig = mr_aligner.plot_shifts()
            fig.suptitle(f"{p2.name} (multi-res aligment)", fontsize=8)
            fig.axes[0].set_title(p1.name, fontsize=6)
            save_all_figs(out_dir=out_dir / 'qc', format='png', dpi=144)

            pickle_dir = out_dir / 'pickle'
            if not pickle_dir.exists():
                pickle_dir.mkdir(parents=True)
            import pickle
            with open(pickle_dir / f"{p2.name}-palom.pkl", 'wb') as f:
                pickle.dump(mr_aligner, f)

            aligner = mr_aligner.base_aligner
            block_mx = mr_aligner.base_aligner.block_affine_matrices_da
        elif multi_obj:
            mo_aligner = palom.align_multi_obj.MultiObjAligner(
                r1, r2,
                level1=LEVEL,
                channel1=channel1, channel2=channel2,
                thumbnail_channel1=thumbnail_channel1,
                thumbnail_channel2=thumbnail_channel2
            )
            mo_aligner._affine_matrix = aligner.affine_matrix
            mo_aligner._coarse_affine_matrix = aligner.coarse_affine_matrix
            if multi_obj_kwarg is None: multi_obj_kwarg = {}
            mo_aligner.run(**multi_obj_kwarg)
            save_all_figs(out_dir=out_dir / 'qc' / p2.stem, format='png', dpi=144, prefix=p2.name)
            block_mx = mo_aligner.block_affine_matrices_da

    if not only_qc:
        mx = aligner.affine_matrix
        if not only_coarse:
            mx = block_mx

        mosaic = palom.align.block_affine_transformed_moving_img(
            ref_img=aligner.ref_img,
            moving_img=r2.pyramid[LEVEL],
            mxs=mx
        )
        palom.pyramid.write_pyramid(
            mosaics=[mosaic],
            output_path=out_path,
            pixel_size=r1.pixel_size*r1.level_downsamples[LEVEL],
            channel_names=[list('RBG')],
            compression='zlib',
            downscale_factor=2,
            save_RAM=True,
            tile_size=1024,
            kwargs_tifffile=dict(photometric='rgb', planarconfig='separate')
        )
    return 0

def viz_coarse(r1, r2, level1, level2, channel1, channel2, mx):
    try:
        import napari
    except ImportError:
        return
    import dask.array as da
    v = napari.Viewer()
    is_bf1 = palom.img_util.is_brightfield_img(r1.pyramid[-1][channel1])
    is_bf2 = palom.img_util.is_brightfield_img(r2.pyramid[-1][channel2])
    inv = {True: da.invert, False: da.array}
    v.add_image(
        [inv[is_bf1](p[channel1]) for p in r1.pyramid[level1:]],
        colormap='bop orange', blending='additive'
    )
    v.add_image(
        [inv[is_bf2](p[channel2]) for p in r2.pyramid[level2:]],
        affine=palom.img_util.to_napari_affine(mx),
        colormap='bop blue', blending='additive'
    )
    return v

def get_reader(path):
    path = pathlib.Path(path)
    if path.suffix == '.svs':
        return palom.reader.SvsReader
    else:
        return palom.reader.OmePyramidReader

def set_matplotlib_font(font_size=12):
    font_families = matplotlib.rcParams['font.sans-serif']
    if font_families[0] != 'Arial':
        font_families.insert(0, 'Arial')
    matplotlib.rcParams['pdf.fonttype'] = 42
    matplotlib.rcParams.update({'font.size': font_size})

def save_all_figs(dpi=300, format='pdf', out_dir=None, prefix=None):
    figs = [plt.figure(i) for i in plt.get_fignums()]
    if prefix is not None:
        for f in figs:
            if f._suptitle:
                f.suptitle(f"{prefix} {f._suptitle.get_text()}")
            else:
                f.suptitle(prefix)
    names = [f._suptitle.get_text() if f._suptitle else '' for f in figs]
    out_dir = pathlib.Path(out_dir)
    out_dir.mkdir(exist_ok=True, parents=True)

    for f, n, nm in zip(figs, plt.get_fignums(), names):
        f.savefig(out_dir / f"{n}-{nm}.{format}", dpi=dpi, bbox_inches='tight')
        plt.close(f)

def set_subplot_size(w, h, ax=None):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)

if __name__ == '__main__':
    import fire
    import sys

    fire.Fire(align_he)

    if ('--viz_coarse_napari' in sys.argv) or ('-v' in sys.argv):
        try: import napari
        except ImportError: print("napari is not installed")
        else: napari.run()

    '''
    Example 1: inspect coarse alignment using napari
    python align_he.py \
        Z:\RareCyte-S3\P54_CRCstudy_Bridge\P54_S33_Full_Or6_A31_C90c_HMS@20221025_001610_632297.ome.tiff \
        "X:\crc-scans\histowiz scans\20230105-orion_2_cycles\22199$P54_33_HE$US$SCAN$OR$001 _104050.svs" \
        "X:\crc-scans\histowiz scans\20230105-orion_2_cycles\test" \
        --px_size1 0.325 --only_qc --only_coarse --viz_coarse_napari

    Example 2: process pair and output registered image
    python align_he.py \
        Z:\RareCyte-S3\P54_CRCstudy_Bridge\P54_S33_Full_Or6_A31_C90c_HMS@20221025_001610_632297.ome.tiff \
        "X:\crc-scans\histowiz scans\20230105-orion_2_cycles\22199$P54_33_HE$US$SCAN$OR$001 _104050.svs" \
        "X:\crc-scans\histowiz scans\20230105-orion_2_cycles\test" \
        --px_size1 0.325

    '''


"""Contains unittests for BOUT paths."""

from pathlib import Path
from typing import Callable

import pytest

from bout_runners.parameters.bout_paths import BoutPaths

def test_bout_path(
    yield_conduction_path: Path, copy_bout_inp: Callable[[Path, str], Path]
) -> None:
    """
    Test that BoutPath is copying files.

    Parameters
    ----------
    yield_conduction_path : Path
        Path to the BOUT++ conduction example
        See the yield_conduction_path for more details
    copy_bout_inp : function
        Function which copies BOUT.inp and returns the path to the temporary
        directory
        See the copy_bout_inp fixture for more details
    """
    project_path = yield_conduction_path
    tmp_path_name = "tmp_BoutPath_test"

    # NOTE: We use the fixture here to automatically remove the
    # directory after the test
    tmp_path_dir = copy_bout_inp(project_path, tmp_path_name)

    # We remove the BOUT.inp to verify that BoutPaths copied the file
    tmp_path_dir.joinpath("BOUT.inp").unlink()

    bout_paths = BoutPaths(project_path=project_path, bout_inp_dst_dir=tmp_path_name)

    assert project_path.joinpath(tmp_path_name, "BOUT.inp").is_file()

    # Test that an error is raised if the source dir is pointed to a directory
    # without BOUT.inp
    with pytest.raises(FileNotFoundError):
        # NOTE: type: ignore due to https://github.com/python/mypy/issues/3004
        bout_paths.bout_inp_src_dir = "dir_without_BOUT_inp"  # type: ignore


import cv2
import numpy as np

image = cv2.imread('lena.jpg')
'''FOR JOINING IMAGES THEY SHOULD HAVE SAME NUMBER OF CHANNELS'''
horizontal_stack = np.hstack((image, image, image))
vertical_stack = np.vstack((image, image, image))
cv2.imshow('Horizontally Stacked Image', horizontal_stack)
cv2.imshow('Vertically Stacked Image', vertical_stack)
cv2.waitKey(0)


import torch
from torch import nn

class NonLocalAttention(nn.Module):
    """
        Attention from all positions in object B to all positions in object A
    """
    def __init__(self, in_channels=256, inter_channels=None, bn_layer=True):
        super(NonLocalAttention, self).__init__()

        self.in_channels = in_channels
        self.inter_channels = inter_channels

        # Set default inter_channels
        if self.inter_channels is None:
            self.inter_channels = in_channels // 2
            if self.inter_channels == 0:
                self.inter_channels = 1

        self.g = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,
                         kernel_size=1, stride=1, padding=0)

        if bn_layer:
            self.W = nn.Sequential(
                nn.Conv2d(in_channels=self.inter_channels, out_channels=self.in_channels,
                        bias=False, kernel_size=1, stride=1, padding=0),
                nn.BatchNorm2d(self.in_channels)
            )
        else:
            self.W = nn.Conv2d(in_channels=self.inter_channels, out_channels=self.in_channels,
                    kernel_size=1, stride=1, padding=0)

        self.theta = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,
                             kernel_size=1, stride=1, padding=0)

        self.phi = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,
                           kernel_size=1, stride=1, padding=0)

        # Initialize weights
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight.data, mode="fan_in")
                if m.bias is not None:
                    m.bias.data.zero_()

    def forward(self, a, b):
        B, C, H, W = a.size()

        # Pairwise relationship
        theta_a = self.theta(a).reshape(B, self.inter_channels, -1).permute(0, 2, 1)
        phi_b = self.phi(b).reshape(B, self.inter_channels, -1)
        # Correlation of size (B, H * W, H * W)
        f = torch.matmul(theta_a, phi_b)
        f_div_C = f / f.size(-1)

        # Get representation of b
        g_b = self.g(b).view(B, self.inter_channels, -1)
        g_b = g_b.permute(0, 2, 1)

        # Combine
        y = torch.matmul(f_div_C, g_b)
        y = y.permute(0, 2, 1).contiguous()
        y = y.view(B, self.inter_channels, *a.size()[2:])
        W_y = self.W(y)

        return W_y


from numpy import complex128
import streamlit as st
from recorder import recordVideo
import json
import os

st.title("SECURITY RECORDING USING OPENCV")
st.image('hero.jpg', use_column_width=True)
sidebar = st.sidebar
config = {}
try:
    with open('settings.json', 'r') as f:
        config = json.load(f)
except Exception as e:
    print(e)
    st.error('Error Loading Settings')
sidebar.title('User Options')

def introduction():
    st.title("COMPUTER VISION ")
    st.markdown("""
     As computer vision has become a part of our daily life.
      Using smartphones features like face recognition is all a part of computer vision.
      In this paper, we will talk aboutCV or Computer Vision which is preferably used to
       read and display a video stream in real time through which one can access the web camera
        and using machine learning one can let their system learn through data sent by user or
        through datasets which is easily available on the internet and then system trains itself. After training part it is ready to solve the real life problems

    """)
    st.image('cv.jpg', use_column_width=True)

    st.title("OPENCV")
    st.markdown("""
    As computer vision has become a part of our daily life.
      Using smartphones features like face recognition is all a part of computer vision.
      In this paper, we will talk aboutCV or Computer Vision which is preferably used to
       read and display a video stream in real time through which one can access the web camera
        and using machine learning one can let their system learn through data sent by user or
        through datasets which is easily available on the internet and then system trains itself. After training part it is ready to solve the real life problems

    """)

    st.image('opencv.jpg', use_column_width=True)
    st.image_size=(300,300)
    c1, c2 = st.columns(2)

    c1.header("FEATURE")

    st.markdown("""2.Fast Speed. Since the OpenCV library is originally written in C/C++, it is fast and efficient.

    """)
    st.markdown("""3.Easy to Integrate.
                   """)
    st.markdown("""4.Read and write images.""")

def execute():
    st.subheader('project working here')
    st.title("security recorder")
    video_name = st.text_input("Enter video name")
    record = st.checkbox('Record Video')
    if video_name and record:
        recordVideo(video_name.replace(' ', '_'), config)
        sidebar = st.sidebar
    st.title("USAGE")
    st.markdown("""This system  has  a  wide range  of  uses in  various  fields,
    such  as banking,  forensic  department,  etc…  The  reason  this system  is
    quiet  useful  is  due  to  the  fact  that  it  is  highly compact  and  it
     provides  face  detection  and  recognition  at once.
""")
    st.markdown("""Peace of mind.
    """)
    st.markdown("""Deterrent and crime prevention.
    """)
    st.markdown("""
    Prosecution.
    """)
def setting():
    st.title("OPTION")
    c1, c2, c3 = st.columns(3)

    height = c1.text_input("Hight")

    width = c2.text_input("width")

    fps = c3.text_input("fps")

    save_btn = st.button('Save Settings')

    if save_btn:
        with open('settings.json', 'r') as f:
            config = json.load(f)
            config = {"width": width, "height": height, "fps": fps}

            with open('settings.json', 'w') as f:
                json.dump(config, f)
            st.success('Settings Saved...')

def viewVideos():

    videos = os.listdir('recordedVideos')
    selVideo = st.selectbox('Select Video to View', videos)

    if selVideo:
        st.video(f'recordedVideos/{selVideo}', format="video/mp4")
        st.video('video.mkv')

print(config)

options = ['Project Introduction','Execution','setting', 'View Recorded Videos']
selOption = sidebar.selectbox("Select an Option", options)

if selOption == options[0]:
    introduction()
elif selOption == options[1]:
    execute()
elif selOption == options[2]:
    setting()
elif selOption == options[3]:
    viewVideos()


# -*- coding: utf-8 -*-
"""
Created on Fri Aug  5 10:29:08 2022

@author: user
"""

import sys
import cv2
import datetime

cap = cv2.VideoCapture(0)
# cap = cv2.VideoCapture(0, cv2.CAP_V4L2)

if not cap.isOpened():
    print("Cannot open camera")
    sys.exit()

#cv2.namedWindow("live", cv2.WINDOW_AUTOSIZE); # 命名一個視窗，可不寫
idx = 1
today = datetime.date.today()

# cap.set(cv2.CAP_PROP_GAIN, 0)
cap.set(cv2.CAP_PROP_EXPOSURE, -4.0) # diable auto exposure

try:
    while(True):
        # 擷取影像
        ret, frame = cap.read()
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break

        # 彩色轉灰階
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Cropped
        # topx = 200 #80
        # topy = 120 #40
        # bottomx = 380 #125
        # bottomy = 540 #310
        # Cropped = gray[topx:bottomx+1, topy:bottomy+1]

        # 顯示圖片
        cv2.imshow('live', gray)
        #cv2.imshow('live', gray)

        # 按下 q 鍵離開迴圈
        if cv2.waitKey(1) == ord('c'):
            filename = "./{}_Catupre_{}.png".format(today.strftime('%Y_%m_%d'), idx)
            # saving image in local storage
            cv2.imwrite(filename, frame)
            idx = idx + 1

        elif cv2.waitKey(1) == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            break

except KeyboardInterrupt:
    # 釋放該攝影機裝置
    cap.release()
    cv2.destroyAllWindows()


import init
from tile import *

class Singleton(type):
    __instance = {}

    def __call__(cls, *args, **kwargs):
        if cls not in Singleton.__instance:
            Singleton.__instance[cls] = cls.__new__(cls)
            Singleton.__instance[cls].__init__(*args, **kwargs)
        return Singleton.__instance[cls]

class TileTable(metaclass=Singleton):
    def __init__(self):
        self.table = []
        for idx1 in range(4):
            four_tiles = []
            for idx2 in range(4):
                four_tiles.append(Tile(init.all_sprites, idx1 * 4 + idx2))
                four_tiles[idx2].set_place(((idx2 + 1) * 280, (idx1 + 1) * 140))
            self.table.append(four_tiles)
        self.clicked_tile = []
        self.void_tile = (0, 0)

    def clear(self):
        for idx1 in range(4):
            for idx2 in range(4):
                self.table[idx1][idx2].kill()
        self.table.clear()

    def repair(self):
        for idx1 in range(4):
            four_tiles = []
            for idx2 in range(4):
                four_tiles.append(Tile(init.all_sprites, idx1 * 4 + idx2))
                four_tiles[idx2].set_place(((idx2 + 1) * 280, (idx1 + 1) * 140))
            self.table.append(four_tiles)
        self.clicked_tile = []
        self.void_tile = (0, 0)
        self.shuffle()

    def shuffle(self):
        for times in range(4):
            for idx1 in range(4):
                for idx2 in range(4):
                    pos1 = random.randint(0, 3)
                    pos2 = random.randint(0, 3)
                    if (pos1, pos2) == self.void_tile:
                        self.void_tile = (idx1, idx2)
                    elif (idx1, idx2) == self.void_tile:
                        self.void_tile = (pos1, pos2)
                    self.swap((idx1, idx2), (pos1, pos2))

    def check(self):
        for idx1 in range(4):
            for idx2 in range(4):
                if self.table[idx1][idx2].key != idx1 * 4 + idx2:
                    return False
        return True

    def swap(self, pos1, pos2):
        first_pos = self.table[pos1[0]][pos1[1]].place
        second_pos = self.table[pos2[0]][pos2[1]].place
        self.table[pos1[0]][pos1[1]].set_place(second_pos)
        self.table[pos2[0]][pos2[1]].set_place(first_pos)
        self.table[pos1[0]][pos1[1]], self.table[pos2[0]][pos2[1]] = self.table[pos2[0]][pos2[1]], self.table[pos1[0]][pos1[1]]

    def tile_clicked(self, click):
        if len(self.clicked_tile) == 0:
            for idx1 in range(4):
                for idx2 in range(4):
                    if self.table[idx1][idx2].rect.collidepoint(click.pos):
                        x = click.pos[0]
                        y = click.pos[1]
                        self.table[idx1][idx2].clicked = True
                        self.table[idx1][idx2].offset = (x - self.table[idx1][idx2].rect.x, y - self.table[idx1][idx2].rect.y)
                        self.clicked_tile.append((idx1, idx2))
            init.drag_flag = True

    def tile_unclicked(self):
        if len(self.clicked_tile) > 0:
            idx = self.clicked_tile[0]
            self.table[idx[0]][idx[1]].clicked = False
            if abs(idx[0] - self.void_tile[0]) == 1 and idx[1] == self.void_tile[1] or abs(idx[1] - self.void_tile[1]) == 1\
                    and idx[0] == self.void_tile[0] and \
                    init.rect_intersection(self.table[idx[0]][idx[1]].rect, self.table[self.void_tile[0]][self.void_tile[1]].rect):
                self.table[idx[0]][idx[1]].rect.center = self.table[idx[0]][idx[1]].place
                self.swap(idx, self.void_tile)
                self.void_tile = idx
            else:
                self.table[idx[0]][idx[1]].rect.center = self.table[idx[0]][idx[1]].place
            self.clicked_tile.clear()
        init.drag_flag = False

    def tile_dragging(self):
        if len(self.clicked_tile) > 0:
            for idx in self.clicked_tile:
                if self.table[idx[0]][idx[1]].clicked:
                    pos = pygame.mouse.get_pos()
                    self.table[idx[0]][idx[1]].rect.x = pos[0] - self.table[idx[0]][idx[1]].offset[0]
                    self.table[idx[0]][idx[1]].rect.y = pos[1] - self.table[idx[0]][idx[1]].offset[1]


from collections import deque
def solution(msg):
    dic_idx, answer, msg = list(" ABCDEFGHIJKLMNOPQRSTUVWXYZ"), [], deque(msg)
    tmp = msg.popleft()
    while msg:
        temp = tmp + msg[0]
        if temp not in dic_idx:
            answer.append(dic_idx.index(tmp))
            dic_idx.append(temp)
            tmp = msg.popleft()
        else:
            tmp += msg.popleft()
    answer.append(dic_idx.index(tmp))
    return answer

프로그래머스/lv2/17684. ［3차］ 압축/［3차］ 압축.py


'''
##### DO Not Touch your face ver.0.2

### Medical Imaging & Intelligent Reality Lab (MI2RL) @ Asan Medical Center(AMC)
# MI2RL website : https://www.mi2rl.co/
# AMC : http://www.amc.seoul.kr/asan/main.do

### Developer
# Sungman Cho : dev.sungman@gmail.com
# Minjee Kim : minjeekim00@gmail.com
# Taehyeong Kim : kimtaehyeong62@gmail.com
# Junmyung Choi : jm5901@gmail.com
# Namkug Kim : namkugkim@gmail.com

### Data contributor
# MI2RL researchers
# Dongwoo Seo, Emergency Medicine@AMC
# Namkug Kim, Convergence Medicine@AMC

### references
# I3D Network (https://github.com/hassony2/kinetics_i3d_pytorch)

#####
'''

import cv2
import sys

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

from render_thread import RenderThread

### For viewing GUI
class GUIViewer(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()
        self.position = self._get_location()
        self.language = 'korean'

        # TODO : connect ConfigViewer to main GUIviewer
        self.config_window = ConfigboxViewer()
        self.video_viewer = VideoViewer()

        # Rendering Thread for getting Webcam's image
        self.render_thread = RenderThread(self)
        self.render_thread.action_result.connect(self.update_touching_status)
        self.render_thread.changePixmap.connect(self.setImage)

        self.render_thread.start()

    # GUI Position Setting
    def _get_location(self):
        ag = QDesktopWidget().availableGeometry()
        sg = QDesktopWidget().screenGeometry()
        fg = self.frameGeometry()

        widget = self.geometry()
        x = ag.width() - widget.width()
        y = 2 * ag.height() - sg.height() - widget.width()

        x = sg.width() - fg.width()
        y = sg.height() - fg.height()

        return (x,y, fg.width(), fg.height())

    def initUI(self):
        self.status_label = QLabel('행동 인식 기능: 꺼짐')
        self.touching_status = QLabel('알림 : ')

        ### Button Layout.
        #self.config_btn = QPushButton('설정')
        self.language_cb = QCheckBox('Translated in English', self)
        self.language_cb.stateChanged.connect(self.check_language)
        self.view_btn = QPushButton('카메라')
        self.start_btn = QPushButton('시작')
        self.pause_btn = QPushButton('중지')

        #self.config_btn.clicked.connect(self.config_clicked)
        self.view_btn.clicked.connect(self.view_clicked)
        self.start_btn.clicked.connect(self.start_clicked)
        self.pause_btn.clicked.connect(self.pause_clicked)
        ###

        v_layout = QtWidgets.QVBoxLayout()
        v_layout.addWidget(self.language_cb)
        v_layout.addWidget(self.status_label)
        v_layout.addWidget(self.touching_status)
        h_layout = QtWidgets.QHBoxLayout()
        h_layout.addWidget(self.start_btn)
        h_layout.addWidget(self.pause_btn)
        #h_layout.addWidget(self.config_btn)
        h_layout.addWidget(self.view_btn)
        v_layout.addLayout(h_layout)
        self.setLayout(v_layout)

        self.setGeometry(1440, 1030, 500, 50)

        self.setWindowTitle('DONT (20.03.17. ver.0.3)')

    def check_language(self):
        if self.language is 'korean':
            self.language = 'english'

            if self.render_thread.status is True:
                self.status_label.setText('Action Recognition Mode : OFF')
            else:
                self.status_label.setText('Action Recognition Mode : ON')

            self.touching_status.setText('Alarm : ')

            self.view_btn.setText('Camera')
            self.start_btn.setText('Start')
            self.pause_btn.setText('Pause')
        else:
            self.language = 'korean'
            if self.render_thread.status is True:
                self.status_label.setText('행동 인식 기능 : 꺼짐')
            else:
                self.status_label.setText('행동 인식 기능 : 켜짐')
            self.touching_status.setText('알림 : ')

            self.view_btn.setText('카메라')
            self.start_btn.setText('시작')
            self.pause_btn.setText('중지')

    def config_clicked(self):
        self.config_window.showModal()

    def view_clicked(self):
        self.video_viewer.showModal()

    def start_clicked(self):
        if self.language is 'korean':
            self.status_label.setText('행동 인식 기능: 켜짐')
        else:
            self.status_label.setText('Action Recognition Mode : ON')
        self.render_thread.setStatus(False)

    def pause_clicked(self):
        if self.language is 'korean':
            self.status_label.setText('행동 인식 기능: 꺼짐')
            self.touching_status.setText('알림 : ')
        else:
            self.status_label.setText('Action Recognition Mode : OFF')
            self.touching_status.setText('Alarm : ')

        self.render_thread.start()
        self.render_thread.setStatus(True)

    def closeEvent(self, event):

        if self.language is 'korean':
            reply = QMessageBox.question(self, '닫기', '프로그램을 종료하시겠습니까?',
                        QMessageBox.Yes | QMessageBox.No)
        else:
            reply = QMessageBox.question(self, 'Confirmation', 'Are tou sure you want to exit?',
                        QMessageBox.Yes | QMessageBox.No)

        if reply == QMessageBox.Yes:
            self.render_thread.exit(True)
            self.render_thread.wait()
            self.deleteLater()
            event.accept()

        else:
            event.ignore()

    @pyqtSlot(QImage)
    def setImage(self, image):
        self.video_viewer.image_label.setPixmap(QPixmap.fromImage(image))

    @pyqtSlot(str)
    def update_touching_status(self, message):
        if self.language is 'korean':
            self.touching_status.setText('알림 : {}'.format(message))
        else:
            if message == '얼굴을 만지지 마세요 !':
                message = 'DO Not Touch your face !'
            self.touching_status.setText('Alarm : {}'.format(message))

### For viewing webCAM
class VideoViewer(QDialog):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.isRun = False

    def initUI(self):
        self.setWindowTitle('카메라')

        # 추후 백그라운드 실행되도록 변경
        self.image_label = QLabel(self)
        v_layout = QtWidgets.QVBoxLayout()
        h_layout = QtWidgets.QHBoxLayout()
        h_layout.addWidget(self.image_label)
        v_layout.addLayout(h_layout)
        self.setLayout(v_layout)

        self.setGeometry(1440, 655, 480, 320)

    def showModal(self):
        return super().exec_()

### For viewing Config Box
class ConfigboxViewer(QDialog):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.language = 'korean'

    def initUI(self):
        self.setWindowTitle('설정')

        #self.label = QLabel('알람을 받을 행동을 선택해주세요')

        ### Button Layout

        self.korean_ver_cb = QCheckBox('Translated into English', self)
        self.korean_ver_cb.stateChanged.connect(self.check_translate_korean)
        self.check_btn = QPushButton('적용')
        self.check_btn.clicked.connect(self.apply_clicked)
        '''
        #self.mask_cb = QCheckBox('Wearing/Removing mask', self)
        #self.chin_cb = QCheckBox('Resting chin on hand', self)
        #self.eye_cb = QCheckBox('Rubbing eyes', self)
        #self.hair_cb = QCheckBox('Touching hairs', self)
        #self.phone_cb = QCheckBox('Touching phone', self)
        #self.call_cb = QCheckBox('Picking up phone', self)
        #self.eye_glass_cb = QCheckBox('Wearing glasses', self)
        #self.water_cb = QCheckBox('Drinking', self)
        #self.check_btn = QPushButton('Apply')

        ### English ver

        self.mask_cb.stateChanged.connect(self.check_mask)
        self.chin_cb.stateChanged.connect(self.check_chin)
        self.eye_cb.stateChanged.connect(self.check_eye)
        self.hair_cb.stateChanged.connect(self.check_hair)
        self.phone_cb.stateChanged.connect(self.check_phone)
        self.call_cb.stateChanged.connect(self.check_call)
        self.eye_glass_cb.stateChanged.connect(self.check_eye_glass)
        self.water_cb.stateChanged.connect(self.check_water)
        self.check_btn.clicked.connect(self.check_clicked)

        v_layout = QtWidgets.QVBoxLayout()
        v_layout.addWidget(self.korean_ver_cb)
        v_layout.addWidget(self.mask_cb)
        v_layout.addWidget(self.chin_cb)
        v_layout.addWidget(self.eye_cb)
        v_layout.addWidget(self.hair_cb)
        v_layout.addWidget(self.phone_cb)
        v_layout.addWidget(self.call_cb)
        v_layout.addWidget(self.eye_glass_cb)
        v_layout.addWidget(self.water_cb)
        v_layout.addWidget(self.check_btn)
        self.setLayout(v_layout)
        '''
        v_layout = QtWidgets.QVBoxLayout()
        v_layout.addWidget(self.korean_ver_cb)
        self.setLayout(v_layout)

        #self.setGeometry(1295, 660, 140, 450)
        self.setGeometry(1350, 850, 140, 50)

    def check_translate_korean(self):
        if self.language is 'english':
            self.language = 'korean'

            '''
            self.mask_cb.setText('마스크 쓰기/벗기')
            self.chin_cb.setText('턱 괴기')
            self.eye_cb.setText('눈 비비기')
            self.hair_cb.setText('머리 만지기')
            self.phone_cb.setText('핸드폰 만지기')
            self.call_cb.setText('전화 받기')
            self.eye_glass_cb.setText('안경 만지기')
            self.water_cb.setText('물마시기')
            self.check_btn.setText('적용')
            '''

        else:
            self.language = 'english'
            '''
            self.mask_cb.setText('Wearing/Removing mask')
            self.chin_cb.setText('Resting chin on hand')
            self.eye_cb.setText('Rubbing eyes')
            self.hair_cb.setText('Touching hairs')
            self.phone_cb.setText('Touching phone')
            self.call_cb.setText('Picking up phone')
            self.eye_glass_cb.setText('Wearing glasses')
            self.water_cb.setText('Drinking')
            self.check_btn.setText('Apply')
            '''

    def check_mask(self):
        print('check_mask clicked')

    def check_chin(self):
        print('check_chin clicked')

    def check_eye(self):
        print('check_eye clicked')

    def check_hair(self):
        print('check_hair clicked')

    def check_phone(self):
        print('check_phone clicked')

    def check_call(self):
        print('check_call clicked')

    def check_eye_glass(self):
        print('check_eye_glass clicked')

    def check_water(self):
        print('check_water clicked')

    def apply_clicked(self):
        self.accept()

    def showModal(self):
        return super().exec_()


from collections import defaultdict

class Solution:
    def findLeastNumOfUniqueInts(self, arr: [int], k: int) -> int:
        """
        O(n log(n)) time, O(n) space
        贪心的思路，把出现频率最小的先移除掉
        """
        mapping = defaultdict(int)
        for i in arr:
            mapping[i] += 1

        mapping = sorted(mapping.values())

        number_to_remove = 0
        for i in range(len(mapping)):
            number_to_remove += mapping[i]
            if number_to_remove > k:
                return len(mapping) - i

        return 0


from setuptools import setup, find_packages

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

setup(
    name='ChemistryPaperParser',
    version='0.0.1',
    author='Yinghao Li',
    author_email='yinghaoli@gatech.edu',
    license='MIT',
    url='https://github.com/Yinghao-Li/ChemistryHTMLPaperParser',
    description='Parsing HTML chemistry papers from certain publishers into plain text',
    long_description=long_description,
    long_description_content_type="text/markdown",
    keywords='data-mining natural-language-processing nlp parser chemistry',
    zip_safe=False,
    classifiers=[
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Topic :: Scientific/Engineering :: Chemistry',
        'Topic :: Scientific/Engineering :: Information Analysis'
    ],
    packages=find_packages(),
    python_requires=">=3.6",
)


from sys import stdin
N = int(stdin.readline())
D = [1,0,3,0]
if N > 3:
    for n in range(4, N+1):
        if n % 2 == 1:
            D.append(0)
        else:
            D.append(4 * D[n-2] - D[n-4])
print(D[N])

백준/Gold/2133. 타일 채우기/타일 채우기.py


#find an iterative solution for a factorial of a number

def factorial(num):
    res=1
    for i in range(2,num+1):
        res=res*i
    return res

num=int(input("Enter a Number:"))
print("Factorial of the given number is ",factorial(num))

#Time Complexity - O(n)
#Auxilary Space - O(1) better than Recursive.


class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # The O(n) solution involves using a hashset.
        # We use the xor operator for a O(1) memory complexity solution.
        # Note that 0 ^ n = 0 and n ^ n = 0.
        # This solution works because the xor operator cancels out the result
        # when operating on duplicate values, which there are an even number of.

        result = 0
        for n in nums:
            result = result ^ n
        return result


from matplotlib import pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
Players = 'Ankit', 'Dhoni', 'Rohit', 'Yuvraj'
Runs = [25, 30, 15, 10]
explode = (0, 0.1, 0, 0)  # it "explode" the 2nd slice
fig1, ax1 = plt.subplots()
ax1.pie(Runs, explode=explode, labels=Players, autopct='%1.1f%%', shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()

Matplotlib Exercises/Exercise 4 - Pie Chart/Pie Chart 1.py


from mosparo_django.config import FrontendConfig
from mosparo_django.widgets import MosparoWidget

def test_mosparo_widget():
    fc = FrontendConfig('https://test.local', 'test_uuid', 'test_public_key')

    mw = MosparoWidget()
    mw.set_frontend_config(fc)

    context = mw.get_context('test', {}, {})

    assert 'https://test.local' == context['mosparo_host']
    assert 'test_uuid' == context['mosparo_uuid']
    assert 'test_public_key' == context['mosparo_public_key']
    assert 'mosparo/box.html' == mw.template_name


# imports
import nextcord, asyncio, aiohttp, humanfriendly, datetime, typing
from humanfriendly import parse_timespan
from nextcord.ext import commands

class moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='kick', description='kicks member')
    @commands.has_permissions(kick_members = True)
    async def kick(self, ctx, member: nextcord.Member, reason: typing.Optional[str] = "None"):
        await ctx.guild.kick(member)
        await ctx.send(f"successfuly kicked {member.mention} because of {reason} :thumbsup:")

    @commands.command(name='ban', description='bans member')
    @commands.has_permissions(ban_members = True)
    async def ban(self, ctx, member: nextcord.Member, reason: typing.Optional[str] = "None"):
        await ctx.guild.ban(member)
        await ctx.send(f"successfuly banned {member.mention} becuase of {reason} :thumbsup:")

    @commands.command(name='unban', description='unbans member')
    @commands.has_permissions(ban_members = True)
    async def unban(self, ctx, member: nextcord.Member, reason: typing.Optional[str] = "None"):
        await ctx.guild.unban(member)
        await ctx.send(f"successfuly unbanned {member.mention} because of {reason} 👍")

    @commands.command(name='mute', description='mutes a member', aliases=['timeout'])
    @commands.has_permissions(moderate_members = True)
    async def mute(self, ctx, member: nextcord.Member, time, reason: typing.Optional[str] = "None"):
        time = humanfriendly.parse_timespan(time)
        await member.edit(timeout=nextcord.utils.utcnow()+datetime.timedelta(seconds=time))
        await ctx.send(f"successfuly muted {member.mention} for {time} because of {reason}")

    @commands.command(name='unmute', description='unmutes a member', aliases=['untimeout'])
    @commands.has_permissions(moderate_members = True)
    async def unmute(self, ctx, member: nextcord.Member, reason: typing.Optional[str] = "None"):
        await member.edit(timeout=None)
        await ctx.send(f"successfuly unmuted {member.mention} because of {reason}")

def setup(bot):
    bot.add_cog(moderation(bot))


import random
item_in_shop = {"soybean_sauce": 0, "milk": 4, "salt": 10, "soybean_milk": 3}
items = [item for item in item_in_shop.keys()]
cnt = 5

def buy(item):
    if (item_in_shop[item]==0):
        raise Exception
    else:
        item_in_shop[item]-=1
    print("Mommy! I've bought {} for you!".format(item))

while cnt:
    cnt -= 1
    index = random.randint(0,3)
    item = items[index]
    try:
        buy(item)
    except Exception:
        print(item,"is not on sale right now")


from random import randrange
def game():
    n = randrange(1, 20)
    no_of_guesses = 10
    attempt = 1
    print("Guess the number between 1 to 50\n")
    while (True):
        if no_of_guesses == 0:
            print("Game Over")
            break
        guess = int(input("Guess the number: "))
        if guess > n:
            print("Greater! Decrease Some")
            no_of_guesses = no_of_guesses - 1
            attempt = attempt + 1
            print("\n",no_of_guesses, "Attempt Left\n")
            continue
        if guess < n:
            print("Lesser! Increase some")
            no_of_guesses = no_of_guesses - 1
            attempt = attempt + 1
            print("\n",no_of_guesses, "Attempt Left\n")
            continue
        if guess == n:
            print("Congratulations! You guess the hidden number in just", attempt, "Attempt\n")
            break
        return guess
    again()
def again():
    play_again = input("Press \'y\'for Play Again: ")
    play_again.upper()
    if play_again == "y":
        game()
    else:
        exit()
game()


import os

app_name = "my-app"

while True:
    app_name = input("\n? Project/App name : ")
    if not input("Do you want to Edit?(y = Yes, Enter = No):").lower() == "y":
        break

os.system(f"npm create vite@latest {app_name}")
os.system(f"cd {app_name} && npm install -D tailwindcss@latest postcss@latest autoprefixer@latest")
os.system(f"cd {app_name} && npx tailwindcss init -p")

try:
    file_name = f"./{app_name}/tailwind.config.js"
    file_contents = None
    with open(file_name, 'r') as file:
        file_contents = file.read()
    file_contents = file_contents.replace(r"content: []", r'content: [ "./index.html", "./src/**/*.{js,ts,jsx,tsx}", ]')
    try:
        with open(file_name, 'w') as file:
            file.write(file_contents)
    except Exception as e:
        exit("Error:", str(e))
except:
    exit("Somthing went wrong!")

try:
    with open(f"./{app_name}/src/index.css", 'w') as file:
        file.write("\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n")
except Exception as e:
    exit("Error:", str(e))

try:
    file_name = f"./{app_name}/vite.config.js"
    file_contents = None
    with open(file_name, 'r') as file:
        file_contents = file.read()
    file_contents = file_contents.replace(
        r"})",
        r'''
  base: './',
  build: {
    outDir: "./dist"
  },
  // server: {
  //   host: ["localhost", "192.168.1.244", "192.168.1.243"],
  //   port: 80,
  // },
})''')
    try:
        with open(file_name, 'w') as file:
            file.write(file_contents)
    except Exception as e:
        exit("Error:", str(e))
except:
    exit("Somthing went wrong!")

os.system(f"cd {app_name} && npm run dev")


import numpy
import cv2
import os
import math

my_img=cv2.imread("c.tif",0)
r,c = numpy.shape(my_img)
print(r)
print(c)
label = 0
labellist = []
cclist = numpy.zeros((r,c), dtype = numpy.uint8)
cclist[0][0] = label
labellist.append(label)

for i in range (0,r): #labeling other rows with comparison to first row
    for j in range (0,c):
        if my_img[i,j] == my_img[i,j-1] and my_img[i-1,j] == my_img[i,j]: #
            if cclist[i,j-1] <= cclist[i-1,j]:
                cclist[i,j] = cclist[i,j-1]
                if cclist[i,j-1] != cclist[i-1,j]:
                    temp = cclist[i-1,j]
                    for y in range (0,r):
                        for z in range (0,c):
                            if cclist[y,z] == temp:
                                cclist[y,z]=cclist[i,j]
                    if temp in labellist:
                            labellist.remove(temp)
            elif cclist[i,j-1] > cclist[i-1,j]:
                cclist[i,j] = cclist[i-1,j]
                temp=cclist[i,j-1]
                for y in range(0,r):
                    for z in range(0,c):
                        if cclist[y][z] == temp:
                            cclist[y][z]=cclist[i][j]
                if temp in labellist:
                    labellist.remove(temp)
        if my_img[i][j-1] == my_img[i][j]: #
            cclist[i][j] = cclist[i][j-1]
        if my_img[i-1][j] == my_img[i][j]: #
            cclist[i][j] = cclist[i-1][j]
        if my_img[i-1][j-1] == my_img[i][j]: #
            cclist[i][j] = cclist[i-1][j-1]
        if j < c-1:
            if my_img[i-1][j+1] == my_img[i][j]: #
                cclist[i][j] = cclist[i-1][j+1]
        if my_img[i][j-1] == my_img[i][j] and my_img[i-1][j]!=my_img[i][j]: #
            cclist[i][j] = cclist[i][j-1]
        if my_img[i][j-1] != my_img[i][j] and my_img[i-1][j]==my_img[i][j]: #
            cclist[i][j] = cclist[i-1][j]
        if my_img[i][j-1]!=my_img[i][j] and my_img[i-1][j]!=my_img[i][j]: #
            label = label+1
            labellist.append(label)
            cclist[i][j] = label
del labellist[0]
print(len(labellist))

color = math.floor(256/(len(labellist)-1))

cclist = numpy.uint8(cclist)
cv2.imshow("a.jpg",cclist)
cv2.imwrite("a1.jpg",cclist)


import os

#Directory Listing
    # ./testdir
    # ./testdir/subdir1
    # ./testdir/subdir1/a.c
    # ./testdir/subdir1/a.h
    # ./testdir/subdir2
    # ./testdir/subdir2/.gitkeep
    # ./testdir/subdir3
    # ./testdir/subdir3/subsubdir1
    # ./testdir/subdir3/subsubdir1/b.c
    # ./testdir/subdir3/subsubdir1/b.h
    # ./testdir/subdir4
    # ./testdir/subdir4/.gitkeep
    # ./testdir/subdir5
    # ./testdir/subdir5/a.c
    # ./testdir/subdir5/a.h
    # ./testdir/t1.c
    # ./testdir/t1.h

def find_files(suffix, path):
    """
    Find all files beneath path with file name suffix.

    Note that a path may contain further subdirectories
    and those subdirectories may also contain further subdirectories.

    There are no limit to the depth of the subdirectories can be.

    Args:
      suffix(str): suffix if the file name to be found
      path(str): path of the file system

    Returns:
       a list of paths
    """

        # Iterate through entire directory
            #If isfile - file ends with suffix - append to filesList else do nothing
            #else- Join paths and call function recursively.

    filesList = []

    try:
         content = os.listdir(path)
    except FileNotFoundError:
        return "Directory does not exist"

    for item in content:
        if os.path.isfile("{}/{}".format(path,item)):

            try:
                if "{}/{}".format(path,item).endswith(suffix):
                    file_path = ("{}/{}".format(path,item))
                    filesList.append(file_path)
            except TypeError:
                return "Suffix must be of type str."

        else:
            new_path = "{}/{}".format(path,item)

            sub_compound = find_files(suffix,new_path)

            for file in sub_compound:
                filesList.append(file)

    return filesList

## Test Cases

print(find_files('.h','./testdir')) #Returns ['./testdir/subdir3/subsubdir1/b.h', './testdir/subdir5/a.h', './testdir/t1.h', './testdir/subdir1/a.h']
print(find_files('.h','./testdir/subdir3/subsubdir1')) #Returns ['./testdir/subdir3/subsubdir1/b.h']
print(find_files('.gitkeep','./testdir')) #Returns ['./testdir/subdir4/.gitkeep', './testdir/subdir2/.gitkeep']

## Edge Cases
print(find_files('.h','./testdirsdfs')) #Returns directory does not exist.
print(find_files('.py','./testdir')) #Returns []
print(find_files(-1,'./testdir')) #Returns TypeError: ends with first arg must be str or a tuple of str, not int


from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth import models, authenticate, login, logout
from core import models
from util import *
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.template import RequestContext

from django import forms
from django.core.validators import validate_email
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.db.models import Q
from django.core.mail import send_mail

from collections import OrderedDict

import json, unicodedata, urllib2

def index(request):
    data = {}
    data['user'] = request.user
    return render_to_response("index.html", data, context_instance=RequestContext(request))

def editor(request):
    data = {}
    user = request.user
    data['user'] = user
    feeds = models.Feed.objects.filter(owner=user).order_by('id')
    data['feedsData'] = getFeedData(feeds)
    data['sharedFeed'] = models.Feed.objects.filter(Q(view_permission="public") and ~Q(owner=user)).order_by('id')
    return render_to_response("editor.html", data, context_instance=RequestContext(request))

def editorUpload(request):
    response_data = {}
    user = request.user
    decoded = json.loads(request.POST['json'],object_pairs_hook=OrderedDict)

    toDelete = {}
    for feed in models.Feed.objects.filter(owner=user):
        # Mark feed to delete by default
        toDelete[feed] = True

    for feedData in decoded:
        feedData["feed-name"] = modifyFeedName(feedData["feed-name"], user)
        name = feedData['feed-name']
        view_permission = feedData.get('view-permission', "public")
        content = json.dumps(feedData, sort_keys=True)

        try:
            feed = models.Feed.objects.get(name=name, owner=user)
            if feed.content != content:
                feed.content = content
                feed.view_permission = view_permission
                feed.save()
                updateConsumers(feed)
            # Mark feed in order not to delete
            toDelete[feed] = False
        except ObjectDoesNotExist:
            new_feed = models.Feed.objects.create(name=name,
                                                  owner=user,
                                                  content=content,
                                                  view_permission=view_permission)
            new_feed.save()

    # Delete feeds
    for feed, delete in toDelete.iteritems():
        if delete:
            feed.delete()

    return HttpResponse(json.dumps(response_data), content_type="application-json")

def sendFeeds(request):
    response_data = {}
    user = request.user

    recipient = request.POST['recipient']
    feedsToSend = request.POST['feeds']

    if not validateEmail(recipient):
        response_data['result'] = 0;
    else:
        response_data['result'] = 1;

    links = ""
    for feed in json.loads(feedsToSend):
        feed = feed.replace(" ", "%20")
        feed = modifyFeedName(feed, user)
        links += "http://chelada-web.herokuapp.com/mobile/getfeed/feedname/%s\n\n" % (feed)
    subject = "%s is sharing Chelada feeds with you" % (user.first_name)
    message = """%s %s would like to share these Chelada Feeds with you: \n\n%s""" % (user.first_name, user.last_name, links)
    htmlmessage = "%s" % (message)

    send_mail(subject, message, 'Chelada Team', [recipient])

    return HttpResponse(json.dumps(response_data), content_type="application-json")

def browse(request):
    user = request.user
    data = {}
    feeds = models.Feed.objects.filter(view_permission="public").order_by('id')

    data['user'] = user
    data['feeds'] = feeds
    return render_to_response("browse.html", data, context_instance=RequestContext(request))

def browseLook(request, id):
    user = request.user
    data = {}
    feeds = models.Feed.objects.filter(id=id, view_permission="public").order_by('id')

    data['user'] = user
    data['feeds'] = feeds
    data['feedsData'] = getFeedData(feeds)
    return render_to_response("browseLook.html", data, context_instance=RequestContext(request))


from mbclient import mb
import shared
from random import choice
from datetime import datetime
import re

#for later maybe, need to redo how private notices are received for this
#who_will="who(?:\s+and\s+(?P<second>who))?(?P<plural>\s+are|\s+were|'re)?(?P<dowhat>.+)"
eightball=".+"
help="help(?:\s+with)?(?:\s+(?P<cat>\w+))?"
daddy="who'?s?\s+is\s+(?:ur|your)\s+daddy"
parent="who'?s?\s+\is\s+(?:ur|your)\s+(?:father|mother|dad|parent)"
save="save\s+(?P<thing>.+)\s+as\s+(?P<name>.+)"
get="(?:get|fetch|gimme|give)(?:\sme)?\s+(?P<name>.+)|(?:what\s+have\s+you\s+got)"
yiff="yiff\s+(?P<who>.+)"
coin = "choose\s+(?P<what>.+)$"
seen = "(?:have\s+you\s+)?seen\s+(?P<who>\S+)"
send_message="tell\s+(?P<who>\S+)\s+(?P<what>.+)"
time="time"

hi="(?:hi+|he+llo+|he+y|yo+)[!\s\.]*"

thank="(?:tha+nks?\s*(?:you)?)[!\s\.]*"

urwelc=["pay me","love u bb","you're welcome","that's it??? for all this hard work??","what would you boobs do without me"]
hello=["bye","shut up","go away","not you again","hi","hello","uh huh","sigh"]

def coin_func(nick,match,target):
	what = match.group('what')
	p=re.compile("\s*(?:and|or|\.|,)+\s*")
	options = p.split(what)

	mb.tell(nick+ ": "+choice(options),target)

def yiff_pick(match):
	string = match.group(1)
	quick = re.search("\|",string)
	if quick:
		options=string.split("|")
	else:
		options = mb.data['yiff'][string]
	res = choice(options)
	return res

def yiff_func(nick,match,target):
	who=match.group("who")
	if who == "me":
		who = nick
	elif who in ["yourself","urself"]:
		who = mb.nickname
	mb.data['yiff']['caller']=[nick];
	mb.data['yiff']['target']=[who];
	too_much=20
	pattern = re.compile("{([|\w_]+)}")
	yiff = choice(mb.data['yiff']['yiff'])
	while re.search("{",yiff) and too_much>0:
		too_much -= 1
		yiff=re.sub(pattern,yiff_pick,yiff)
	mb.tell(yiff,target,action=True)

def get_func(nick,match,target):
	name=match.group('name')
	if name:
		name=name.lower()
	else:
		name=".*"
	if name in mb.data['data']:
		mb.tell(nick+": "+mb.data['data'][name],target,True)
	else:
		results=[]
		for title, thing in mb.data['data'].items():
			if re.search(name,title+thing, flags=re.IGNORECASE):
				results.append(title)
		if results==[]:
			mb.tell(nick+": dunno anything like that",target)
		else:
			mb.tell(nick+": did you mean "+", ".join(results)+"? you shit? you dumbass?",target)

def save_func(nick,match,target):
	name=match.group('name').lower()
	thing=match.group('thing')
	mb.data['data'][name]=thing
	mb.tell(nick+": aight",target)
	mb.save('data')

def help_func(nick,match,target,param=None):
	category=match.group('cat')
	if category in mb.help:
		mb.tell(nick+": "+mb.help[category],target)
	else:
		mb.tell(nick+ ": help with "+", ".join(list(mb.help.keys())),target)
		pattern=re.compile("^(?P<cat>"+"|".join(list(mb.help.keys()))+")$",flags=re.IGNORECASE)
		response={'pattern':pattern,'nick':nick,'target':target,'func':help_func}
		mb.responses['help']=response

def eightball_func(nick,match,target):
	mb.tell(nick+": "+choice(mb.data['stuff']['premonition']),target)

def time_func(nick,match,target):
	mb.tell(nick+": "+str(datetime.now().time()),target)

def parent_func(nick,match,target):
	mb.tell("Glub is and it fills me with existential dread and urge to vomit",target)

def daddy_func(nick,match,target):
	mb.tell("ew what the fuck is wrong with you",target)

def hi_func(nick,match,target):
	mb.tell(nick+": "+choice(hello),target)

def thank_func(nick,match,target):
	mb.tell(nick+": "+choice(urwelc),target)

def seen_func(nick,match,target):
	who = match.group('who')

	if who in mb.data['logs']:
		date = datetime.now()
		when = mb.data['logs'][who]['date']
		now=shared.time_dict(date)

		time=shared.time_diff(now,when)
		mb.tell(nick+": "+who+" was here "+time+", saying '"+mb.data['logs'][who]['message']+"'",target)
	else:

		mb.tell(nick+": never heard of that douche",target)

def send_message_func(nick,match,target):
	who = match.group('who')
	date = datetime.now()
	when=shared.time_dict(date)

	message = match.group('what')
	if not who in mb.data['logs']:
		mb.data['logs'][who]={}

	if not 'messages' in mb.data['logs'][who]:
		mb.data['logs'][who]['messages']=[]

	mb.data['logs'][who]['messages'].append({'text':message, 'nick': nick,'date':when})

	mb.tell(nick+": jeez FINE I'll tell em",target)
	mb.save('logs')

mb.add_command(send_message,send_message_func)
mb.add_command(seen,seen_func)

mb.add_command(hi,hi_func)
mb.add_command(coin,coin_func)
mb.add_command(thank,thank_func)
#mb.add_command(daddy,daddy_func,priority=0)
#mb.add_command(parent,parent_func)
mb.add_command(yiff,yiff_func)
mb.add_command(get,get_func)
mb.add_command(save,save_func, level=1)
mb.add_command(help,help_func)
mb.add_command(time,time_func)
mb.add_command(eightball,eightball_func,priority=999)
mb.help['choice'] = "mb choose <list of things separated by , 'or' or 'and'>"
mb.help['seen'] = "mb seen <who>"
mb.help['tell'] = "mb tell <who> <what>"

mb.help['8ball']="anything that starts with mb and doesn't fit any other command is treated like an 8ball command"
mb.help['memos']="mb yiff <someone>, mb save <something> as <name> - saves some text under <name>, mb get <name> - retrieves it"
print("loaded misc")


import requests
from bs4 import BeautifulSoup
import csv

URL = "https://www.goodreads.com/quotes"
resp = requests.get(URL)

soup = BeautifulSoup(resp.content, 'html5lib')

quotes=[]  # a list to store quotes

table = soup.find('div', attrs = {'class':'quotes'})

for row in table.findAll('div',
                         attrs = {'class':'quoteDetails'}):
    quote = {}
    quote['image'] = row.a['href']
    quotes.append(quote)

filename = 'quote.csv'
with open(filename, 'w') as f:
    w = csv.DictWriter(f,['image'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)


import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

clear_sky_days = ['2019-09-02', '2019-09-03', '2019-09-24', '2019-09-25',
                  '2019-09-26', '2019-09-27', '2019-09-28', '2019-09-29',
                  '2019-10-04', '2019-10-09', '2019-10-13', '2019-10-15',
                  '2019-10-16', '2019-10-24', '2019-10-25', '2019-10-26',
                  '2019-10-29', '2019-11-04', '2019-11-05', '2019-11-18',
                  '2019-11-27', '2019-11-29', '2019-11-30']

len(clear_sky_days)
overcast_days = ['2019-10-22']

df = pd.read_csv('Chu_Data.csv', parse_dates=True , index_col='Forecating Starting Time UTC')

df['day'] = df.index.day
df['month'] = df.index.month
df_clear = pd.DataFrame()

for days in clear_sky_days:
    day = int(days.split('-')[2])
    month = int(days.split('-')[1])
    df_day = df[(df['day'] == day) & (df['month'] == month)]
    df_clear = df_clear.append(df_day)

df_clear['RM_diff'].hist(bins=1000)

x1 = np.sort(df_clear['RM_diff'])
N = len(df_clear['RM_diff'])
y = np.arange(N)/float(N)

q_95 = df_clear['RM_diff'].quantile(0.95)
q_75 = df_clear['RM_diff'].quantile(0.75)
q_99 = df_clear['RM_diff'].quantile(0.99)

plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"

f, ax = plt.subplots(figsize = (12, 8))
plt.plot(x1, y, marker='o', color="k", markersize=8)
plt.axhline(y=0.95 , color='red', ls = "--")
plt.axvline(q_95 ,color='red',  ls = "--")
plt.text(q_95, 0.99, "ThrB =(" + str(round(q_95,4)) + ", " + str(0.95) + ")", color = 'tab:green', fontsize=14)
plt.axhline(y=0.75 , color='red', ls = "--")
plt.axvline(q_75 ,color='red',  ls = "--")
plt.text(q_75, 0.77, "ThrA =(" + str(round(q_75,4)) + ", " + str(0.75) + ")", color = 'tab:green', fontsize=14)
plt.ylabel("F(x)", fontsize= 24, fontweight= 'bold')
plt.xlabel('RM_diff', fontsize= 24,style='italic', fontweight= 'bold')
plt.tick_params(axis='y', labelsize=20)
plt.tick_params(axis='x', labelsize=20)
plt.title('cleark-sky days', fontsize=25, style='italic', fontweight='bold', y=1.01)
plt.savefig("CDF_clr_days.png", format = "png", dpi = 150, bbox_inches = "tight")
plt.close()

plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"

for minute in df_clear['minute'].unique():

    f, ax = plt.subplots(figsize = (12, 8))
    plt.hist(df_clear['RM_diff'], bins=300)
    plt.ylabel("Counts", fontsize= 24, fontweight= 'bold')
    plt.xlabel('RM_diff', fontsize= 24,style='italic', fontweight= 'bold')
    plt.tick_params(axis='y', labelsize=20)
    plt.tick_params(axis='x', labelsize=20)
    plt.title('Clear-sky days', fontsize=25, style='italic', fontweight='bold', y=1.01)
    plt.savefig("Hist_clr_days.png", format = "png", dpi = 150, bbox_inches = "tight")
    plt.close()

plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"
thr = []
for minute in df_clear['minute'].unique():

    df_minute = df_clear['RM_diff'][df_clear['minute'] == minute]
    q_95 = df_minute.quantile(0.95)
    q_75 = df_minute.quantile(0.75)
    q_99 = df_minute.quantile(0.99)

    thr.append({'q75':q_75, 'q95':q_95,'q99':q_99})
thr = pd.DataFrame(thr, index = df_clear['minute'].unique())
thr.plot()

thr.to_csv('Thr_Chu.csv')

f, ax = plt.subplots(figsize = (12, 8))
plt.errorbar(thr.index, thr['q75'], thr['q75']*0.1, lw=2, label = 'q75')
plt.errorbar(thr.index, thr['q95'], thr['q95']*0.1, lw=2, label = 'q95')
plt.errorbar(thr.index, thr['q99'], thr['q99']*0.1, lw=2, label = 'q99')
plt.tick_params(axis='y', labelsize=20)
plt.tick_params(axis='x', labelsize=20)
plt.xticks(thr.index)
plt.legend(loc='upper left')
plt.savefig("Thr.png", format = "png", dpi = 150, bbox_inches = "tight")
plt.close()


from flask import Flask
from flask import render_template
from multiprocessing import Pool

# import alarm
import light
import danboard
import common
import logging

app = Flask(__name__)
pool = Pool()

state = 'rest'

@app.route("/alarm")
def alarm_page():
    common.play_mp3('./assets/warning_1.mp3')
    light.start_alarm()
    logging.warning('Alarm!')
    return "Alarm sent!"

@app.route("/portal")
def r2d2():
    common.play_mp3('./assets/portal.wav')
    light.start_speak()
    return "R2D2"

@app.route("/")
def index_page():
    logging.warning('Index!')
    return render_template('index.html')

if __name__ == "__main__":
    pool.apply_async(danboard.danboard, [])
    app.run(host='0.0.0.0')


import torch
import torch.nn as nn
import numpy as np
import sys

from model import model
from tqdm import tqdm
from utils.helpers import draw_seg_maps
from utils.helpers import save_model_dict
from utils.metrics import eval_metric
from utils.helpers import TensorboardWriter

class Trainer:
    def __init__(self, model, train_data_loader, train_dataset,
                 valid_data_loader, valid_dataset, classes_to_train,
                 epochs, device, lr, resume_training=None, model_path=None):
        super(Trainer, self).__init__()

        self.train_data_loader = train_data_loader
        self.train_dataset = train_dataset
        self.valid_data_loader = valid_data_loader
        self.valid_dataset = valid_dataset
        self.model = model
        self.num_classes = len(classes_to_train)
        self.epochs = epochs
        self.device = device
        self.lr = lr

        self.optimizer = torch.optim.Adam(model.parameters(), lr=self.lr)
        print('OPTIMIZER INITIALIZED')
        self.criterion = nn.CrossEntropyLoss()
        print('LOSS FUNCTION INITIALIZED')

        # initialize Tensorboard `SummaryWriter()`
        self.writer = TensorboardWriter()

        print(f"NUM CLASSES: {self.num_classes}")

        if resume_training == 'yes':
            print('RESUMING TRAINING')
            # load the model checkpoint
            checkpoint = torch.load(model_path)
            self.trained_epochs = checkpoint['epoch']
            self.train_iters = checkpoint['train_iters']
            self.valid_iters = checkpoint['valid_iters']
            print(f"PREVIOUSLY TRAINED EPOCHS: {self.trained_epochs}")
            if self.trained_epochs >= self.epochs:
                print('Current epochs less than previously trained epcochs...')
                print(f"Please provide greater number of epochs than {self.trained_epochs}")
                sys.exit()
            elif self.epochs > self.trained_epochs:
                #  load model weights state_dict
                 self.model.load_state_dict(checkpoint['model_state_dict'])
                 print('TRAINED MODEL WEIGHTS LOADED...')
                 # load trained optimizer state_dict
                 self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
                 print('TRAINED OPTIMIZER LOADED...')

        elif resume_training == 'no':
            self.train_iters = 0
            self.valid_iters = 0
            self.trained_epochs = 0
            print('TRAINING FROM BEGINNING')

    def get_num_epochs(self):
        return self.trained_epochs

    def fit(self):
        print('Training')
        model.train()
        train_running_loss = 0.0
        train_running_inter, train_running_union = 0, 0
        train_running_correct, train_running_label = 0, 0
        # calculate the number of batches
        num_batches = int(len(self.train_dataset)/self.train_data_loader.batch_size)
        prog_bar = tqdm(self.train_data_loader,
                        total=num_batches)
        counter = 0 # to keep track of batch counter
        for i, data in enumerate(prog_bar):
            counter += 1
            data, target = data[0].to(self.device), data[1].to(self.device)
            self.optimizer.zero_grad()
            outputs = self.model(data)
            outputs = outputs['out']

            ##### BATCH-WISE LOSS #####
            loss = self.criterion(outputs, target)
            train_running_loss += loss.item()
            ###########################

            ##### BATCH-WISE METRICS ####
            correct, labeled, inter, union = eval_metric(outputs,
                                                             target,
                                                             self.num_classes)
            # for IoU
            train_running_inter += inter
            train_running_union += union
            # for pixel accuracy
            train_running_correct += correct
            train_running_label += labeled
            #############################

            ##### BACKPROPAGATION AND PARAMETER UPDATION #####
            loss.backward()
            self.optimizer.step()
            ##################################################

            ##### TENSORBOARD LOGGING #####
            train_running_IoU = 1.0 * inter / (np.spacing(1) + union)
            train_running_mIoU = train_running_IoU.mean()
            train_running_pixacc = 1.0 * correct / (np.spacing(1) + labeled)
            self.writer.tensorboard_writer(
                loss, train_running_mIoU, train_running_pixacc, self.train_iters,
                phase='train'
            )
            ###############################

            prog_bar.set_description(desc=f"Loss: {loss:.4f} | mIoU: {train_running_mIoU:.4f} | PixAcc: {train_running_pixacc:.4f}")

            self.train_iters += 1

        ##### PER EPOCH LOSS #####
        train_loss = train_running_loss / counter
        ##########################

        ##### PER EPOCH METRICS ######
        # IoU and mIoU
        IoU = 1.0 * train_running_inter / (np.spacing(1) + train_running_union)
        mIoU = IoU.mean()
        # pixel accuracy
        pixel_acc = 1.0 * train_running_correct / (np.spacing(1) + train_running_label)
        ##############################
        return train_loss, mIoU, pixel_acc

    def validate(self, epoch):
        print('Validating')
        model.eval()
        valid_running_loss = 0.0
        valid_running_inter, valid_running_union = 0, 0
        valid_running_correct, valid_running_label = 0, 0
        # calculate the number of batches
        num_batches = int(len(self.valid_dataset)/self.valid_data_loader.batch_size)
        with torch.no_grad():
            prog_bar = tqdm(self.valid_data_loader,
                        total=num_batches)
            counter = 0 # to keep track of batch counter
            for i, data in enumerate(prog_bar):
                counter += 1
                data, target = data[0].to(self.device), data[1].to(self.device)
                outputs = self.model(data)
                outputs = outputs['out']

                # save the validation segmentation maps every...
                # ... last batch of each epoch
                if i == num_batches - 1:
                    draw_seg_maps(data, outputs, epoch, i)

                ##### BATCH-WISE LOSS #####
                loss = self.criterion(outputs, target)
                valid_running_loss += loss.item()
                ###########################

                ##### BATCH-WISE METRICS ####
                correct, labeled, inter, union = eval_metric(outputs,
                                                                target,
                                                                self.num_classes)
                valid_running_inter += inter
                valid_running_union += union
                # for pixel accuracy
                valid_running_correct += correct
                valid_running_label += labeled
                #############################

                ##### TENSORBOARD LOGGING #####
                valid_running_IoU = 1.0 * inter / (np.spacing(1) + union)
                valid_running_mIoU = valid_running_IoU.mean()
                valid_running_pixacc = 1.0 * correct / (np.spacing(1) + labeled)
                self.writer.tensorboard_writer(
                    loss, valid_running_mIoU, valid_running_pixacc, self.valid_iters,
                    phase='valid'
                )
                ###############################

                prog_bar.set_description(desc=f"Loss: {loss:.4f} | mIoU: {valid_running_mIoU:.4f} | PixAcc: {valid_running_pixacc:.4f}")

                self.valid_iters += 1

        ##### PER EPOCH LOSS #####
        valid_loss = valid_running_loss / counter
        ##########################

        ##### PER EPOCH METRICS ######
        # IoU and mIoU
        IoU = 1.0 * valid_running_inter / (np.spacing(1) + valid_running_union)
        mIoU = IoU.mean()
        # pixel accuracy
        pixel_acc = 1.0 * valid_running_correct / (np.spacing(1) + valid_running_label)
        ##############################
        return valid_loss, mIoU, pixel_acc

    def save_model(self, epochs):
        save_model_dict(self.model, epochs,
                        self.optimizer, self.criterion,
                        self.valid_iters, self.train_iters)


import logging
from copy import copy, deepcopy
from enum import IntEnum
from io import StringIO
from typing import NamedTuple

import numpy as np
import tableprint as tp

from smarts.core import gen_id
from smarts.core.utils.cache import cache, clear_cache
from smarts.core.utils.string import truncate

from .chassis import AckermannChassis, BoxChassis
from .controllers import ControllerState
from .sensors import SensorState
from .vehicle import Vehicle

VEHICLE_INDEX_ID_LENGTH = 128

def _2id(id_: str):
    separator = b"$"
    assert len(id_) <= VEHICLE_INDEX_ID_LENGTH - len(separator), id_

    if not isinstance(id_, bytes):
        id_ = bytes(id_.encode())

    return (separator + id_).zfill(VEHICLE_INDEX_ID_LENGTH - len(separator))

class _ActorType(IntEnum):
    Social = 0
    Agent = 1

class _ControlEntity(NamedTuple):
    vehicle_id: str
    actor_id: str
    actor_type: _ActorType
    shadow_actor_id: str
    # Applies to shadowing and controlling actor
    # TODO: Consider moving this to an _ActorType field
    is_boid: bool
    is_hijacked: bool
    position: np.ndarray

# TODO: Consider wrapping the controlled_by recarry into a sep state object
#       VehicleIndex can perform operations on. Then we can do diffs of that
#       recarray with subset queries.
class VehicleIndex:
    def __init__(self):
        self._log = logging.getLogger(self.__class__.__name__)
        self._controlled_by = VehicleIndex._build_empty_controlled_by()

        # Fixed-length ID to original ID
        # TODO: This quitely breaks if actor and vehicle IDs are the same. It assumes
        #       global uniqueness.
        self._2id_to_id = {}

        # {vehicle_id (fixed-length): <Vehicle>}
        self._vehicles = {}

        # {vehicle_id (fixed-length): <ControllerState>}
        self._controller_states = {}

        # {vehicle_id (fixed-length): <SensorState>}
        self._sensor_states = {}

    @classmethod
    def identity(cls):
        return cls()

    def __sub__(self, other: "VehicleIndex") -> "VehicleIndex":
        vehicle_ids = set(self._controlled_by["vehicle_id"]) - set(
            other._controlled_by["vehicle_id"]
        )

        vehicle_ids = [self._2id_to_id[id_] for id_ in vehicle_ids]
        return self._subset(vehicle_ids)

    def __and__(self, other: "VehicleIndex") -> "VehicleIndex":
        vehicle_ids = set(self._controlled_by["vehicle_id"]) & set(
            other._controlled_by["vehicle_id"]
        )

        vehicle_ids = [self._2id_to_id[id_] for id_ in vehicle_ids]
        return self._subset(vehicle_ids)

    def _subset(self, vehicle_ids):
        assert self.vehicle_ids().issuperset(
            vehicle_ids
        ), f"{', '.join(list(self.vehicle_ids())[:3])} ⊅ {', '.join(list(vehicle_ids)[:3])}"

        vehicle_ids = [_2id(id_) for id_ in vehicle_ids]

        index = VehicleIndex()
        indices = np.isin(
            self._controlled_by["vehicle_id"], vehicle_ids, assume_unique=True
        )
        index._controlled_by = self._controlled_by[indices]
        index._2id_to_id = {id_: self._2id_to_id[id_] for id_ in vehicle_ids}
        index._vehicles = {id_: self._vehicles[id_] for id_ in vehicle_ids}
        index._controller_states = {
            id_: self._controller_states[id_]
            for id_ in vehicle_ids
            if id_ in self._controller_states
        }
        index._sensor_states = {
            id_: self._sensor_states[id_]
            for id_ in vehicle_ids
            if id_ in self._sensor_states
        }
        return index

    def __deepcopy__(self, memo):
        result = self.__class__.__new__(self.__class__)
        memo[id(self)] = result

        dict_ = copy(self.__dict__)
        shallow = ["_2id_to_id", "_vehicles", "_sensor_states", "_controller_states"]
        for k in shallow:
            v = dict_.pop(k)
            setattr(result, k, copy(v))

        for k, v in dict_.items():
            setattr(result, k, deepcopy(v, memo))

        return result

    @cache
    def vehicle_ids(self):
        vehicle_ids = self._controlled_by["vehicle_id"]
        vehicle_ids = [self._2id_to_id[id_] for id_ in vehicle_ids]
        return set(vehicle_ids)

    @cache
    def agent_vehicle_ids(self):
        vehicle_ids = self._controlled_by[
            self._controlled_by["actor_type"] == _ActorType.Agent
        ]["vehicle_id"]

        vehicle_ids = [self._2id_to_id[id_] for id_ in vehicle_ids]
        return set(vehicle_ids)

    @cache
    def social_vehicle_ids(self):
        vehicle_ids = self._controlled_by[
            self._controlled_by["actor_type"] == _ActorType.Social
        ]["vehicle_id"]
        vehicle_ids = [self._2id_to_id[id_] for id_ in vehicle_ids]
        return set(vehicle_ids)

    @cache
    def vehicle_is_hijacked_or_shadowed(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)

        v_index = self._controlled_by["vehicle_id"] == vehicle_id
        if not np.any(v_index):
            return False, False

        vehicle = self._controlled_by[v_index]
        assert len(vehicle) == 1

        vehicle = vehicle[0]
        return bool(vehicle["is_hijacked"]), bool(vehicle["shadow_actor_id"])

    @cache
    def vehicle_ids_by_actor_id(self, actor_id, include_shadowers=False):
        """Returns all vehicles for the given actor ID as a list. This is most
        applicable when an agent is controlling multiple vehicles (e.g. with boids).
        """
        actor_id = _2id(actor_id)

        v_index = self._controlled_by["actor_id"] == actor_id
        if include_shadowers:
            v_index = v_index | (self._controlled_by["shadow_actor_id"] == actor_id)

        vehicle_ids = self._controlled_by[v_index]["vehicle_id"]
        return [self._2id_to_id[id_] for id_ in vehicle_ids]

    @cache
    def actor_id_from_vehicle_id(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)

        actor_ids = self._controlled_by[
            self._controlled_by["vehicle_id"] == vehicle_id
        ]["actor_id"]

        if actor_ids:
            return self._2id_to_id[actor_ids[0]]

        return None

    @cache
    def shadow_actor_id_from_vehicle_id(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)

        shadow_actor_ids = self._controlled_by[
            self._controlled_by["vehicle_id"] == vehicle_id
        ]["shadow_actor_id"]

        if shadow_actor_ids:
            return self._2id_to_id[shadow_actor_ids[0]]

        return None

    @cache
    def vehicle_position(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)

        positions = self._controlled_by[
            self._controlled_by["vehicle_id"] == vehicle_id
        ]["position"]

        return positions[0] if len(positions) > 0 else None

    def vehicles_by_actor_id(self, actor_id, include_shadowers=False):
        vehicle_ids = self.vehicle_ids_by_actor_id(actor_id, include_shadowers)
        return [self._vehicles[_2id(id_)] for id_ in vehicle_ids]

    def vehicle_is_hijacked(self, vehicle_id):
        is_hijacked, _ = self.vehicle_is_hijacked_or_shadowed(vehicle_id)
        return is_hijacked

    def vehicle_is_shadowed(self, vehicle_id):
        _, is_shadowed = self.vehicle_is_hijacked_or_shadowed(vehicle_id)
        return is_shadowed

    @property
    def vehicles(self):
        # XXX: Order is not ensured
        return list(self._vehicles.values())

    def vehicleitems(self):
        return map(lambda x: (self._2id_to_id[x[0]], x[1]), self._vehicles.items())

    def vehicle_by_id(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)
        return self._vehicles[vehicle_id]

    @clear_cache
    def teardown_vehicles_by_vehicle_ids(self, vehicle_ids):
        self._log.debug(f"Tearing down vehicle ids: {vehicle_ids}")

        vehicle_ids = [_2id(id_) for id_ in vehicle_ids]
        if len(vehicle_ids) == 0:
            return

        for vehicle_id in vehicle_ids:
            self._vehicles[vehicle_id].teardown()
            del self._vehicles[vehicle_id]

            # popping since sensor_states/controller_states may not include the
            # vehicle if it's not being controlled by an agent
            self._sensor_states.pop(vehicle_id, None)
            self._controller_states.pop(vehicle_id, None)

            # TODO: This stores actors/agents as well; those aren't being cleaned-up
            self._2id_to_id.pop(vehicle_id, None)

        remove_vehicle_indices = np.isin(
            self._controlled_by["vehicle_id"], vehicle_ids, assume_unique=True
        )

        self._controlled_by = self._controlled_by[~remove_vehicle_indices]

    def teardown_vehicles_by_actor_ids(self, actor_ids, include_shadowing=True):
        vehicle_ids = []
        for actor_id in actor_ids:
            vehicle_ids.extend(
                [v.id for v in self.vehicles_by_actor_id(actor_id, include_shadowing)]
            )

        self.teardown_vehicles_by_vehicle_ids(vehicle_ids)

        return vehicle_ids

    @clear_cache
    def sync(self):
        for vehicle_id, vehicle in self._vehicles.items():
            v_index = self._controlled_by["vehicle_id"] == vehicle_id
            entity = _ControlEntity(*self._controlled_by[v_index][0])
            self._controlled_by[v_index] = tuple(
                entity._replace(position=vehicle.position)
            )

    @clear_cache
    def teardown(self):
        self._controlled_by = VehicleIndex._build_empty_controlled_by()

        for vehicle in self._vehicles.values():
            vehicle.teardown(exclude_chassis=True)

        self._vehicles = {}
        self._controller_states = {}
        self._sensor_states = {}
        self._2id_to_id = {}

    @clear_cache
    def start_agent_observation(
        self, sim, vehicle_id, agent_id, agent_interface, mission_planner, boid=False
    ):
        original_agent_id = agent_id
        vehicle_id, agent_id = _2id(vehicle_id), _2id(agent_id)

        vehicle = self._vehicles[vehicle_id]
        Vehicle.attach_sensors_to_vehicle(
            sim, vehicle, agent_interface, mission_planner
        )

        self._2id_to_id[agent_id] = original_agent_id

        self._sensor_states[vehicle_id] = SensorState(
            agent_interface.max_episode_steps,
            mission_planner=mission_planner,
        )

        self._controller_states[vehicle_id] = ControllerState.from_action_space(
            agent_interface.action_space, vehicle.pose, sim
        )

        v_index = self._controlled_by["vehicle_id"] == vehicle_id
        entity = _ControlEntity(*self._controlled_by[v_index][0])
        self._controlled_by[v_index] = tuple(
            entity._replace(shadow_actor_id=agent_id, is_boid=boid)
        )

        # XXX: We are not giving the vehicle an AckermannChassis here but rather later
        #      when we switch_to_agent_control. This means when control that requires
        #      an AckermannChassis comes online, it needs to appropriately initialize
        #      chassis-specific states, such as tire rotation.

        return vehicle

    @clear_cache
    def switch_control_to_agent(
        self,
        sim,
        vehicle_id,
        agent_id,
        boid=False,
        hijacking=False,
        recreate=False,
        agent_interface=None,
    ):
        self._log.debug(f"Switching control of {agent_id} to {vehicle_id}")

        vehicle_id, agent_id = _2id(vehicle_id), _2id(agent_id)
        if recreate:
            # XXX: Recreate is presently broken for bubbles because it impacts the
            #      sumo traffic sim sync(...) logic in how it detects a vehicle as
            #      being hijacked vs joining. Presently it's still used for trapping.
            return self._switch_control_to_agent_recreate(
                sim, vehicle_id, agent_id, boid, hijacking
            )

        vehicle = self._vehicles[vehicle_id]
        chassis = None
        # change this to dynamic_action_spaces later when pr merged
        if agent_interface and agent_interface.action in sim.dynamic_action_spaces:
            chassis = AckermannChassis(pose=vehicle.pose, bullet_client=sim.bc)
        else:
            chassis = BoxChassis(
                pose=vehicle.pose,
                speed=vehicle.speed,
                dimensions=vehicle.state.dimensions,
                bullet_client=sim.bc,
            )

        vehicle.swap_chassis(chassis)

        v_index = self._controlled_by["vehicle_id"] == vehicle_id
        entity = _ControlEntity(*self._controlled_by[v_index][0])
        self._controlled_by[v_index] = tuple(
            entity._replace(
                actor_type=_ActorType.Agent,
                actor_id=agent_id,
                shadow_actor_id="",
                is_boid=boid,
                is_hijacked=hijacking,
            )
        )

        return vehicle

    @clear_cache
    def stop_agent_observation(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)

        vehicle = self._vehicles[vehicle_id]
        Vehicle.detach_all_sensors_from_vehicle(vehicle)

        v_index = self._controlled_by["vehicle_id"] == vehicle_id
        entity = self._controlled_by[v_index][0]
        entity = _ControlEntity(*entity)
        self._controlled_by[v_index] = tuple(entity._replace(shadow_actor_id=""))

        return vehicle

    @clear_cache
    def relinquish_agent_control(self, sim, vehicle_id, social_vehicle_id):
        self._log.debug(
            f"Relinquishing agent control v_id={vehicle_id} sv_id={social_vehicle_id}"
        )

        vehicle_id, social_vehicle_id = _2id(vehicle_id), _2id(social_vehicle_id)

        vehicle = self._vehicles[vehicle_id]
        box_chassis = BoxChassis(
            pose=vehicle.chassis.pose,
            speed=vehicle.chassis.speed,
            dimensions=vehicle.chassis.dimensions,
            bullet_client=sim.bc,
        )
        vehicle.swap_chassis(box_chassis)

        v_index = self._controlled_by["vehicle_id"] == vehicle_id
        entity = self._controlled_by[v_index][0]
        entity = _ControlEntity(*entity)
        self._controlled_by[v_index] = tuple(
            entity._replace(
                actor_type=_ActorType.Social,
                actor_id="",
                shadow_actor_id="",
                is_boid=False,
                is_hijacked=False,
            )
        )

        return vehicle

    @clear_cache
    def attach_sensors_to_vehicle(
        self, sim, vehicle_id, agent_interface, mission_planner
    ):
        vehicle_id = _2id(vehicle_id)

        vehicle = self._vehicles[vehicle_id]
        Vehicle.attach_sensors_to_vehicle(
            sim, vehicle, agent_interface, mission_planner
        )
        self._sensor_states[vehicle_id] = SensorState(
            agent_interface.max_episode_steps,
            mission_planner=mission_planner,
        )
        self._controller_states[vehicle_id] = ControllerState.from_action_space(
            agent_interface.action_space, vehicle.pose, sim
        )

    def _switch_control_to_agent_recreate(
        self, sim, vehicle_id, agent_id, boid, hijacking
    ):
        # XXX: vehicle_id and agent_id are already fixed-length as this is an internal
        #      method.
        agent_id = self._2id_to_id[agent_id]

        # TODO: There existed a SUMO connection error bug
        #       (https://gitlab.smartsai.xyz/smarts/SMARTS/-/issues/671) that occured
        #       during lange changing when we hijacked/trapped a SUMO vehicle. Forcing
        #       vehicle recreation seems to address the problem. Ideally we discover
        #       the underlaying problem and can go back to the preferred implementation
        #       of simply swapping control of a persistent vehicle.
        # Get the old state values from the shadowed vehicle
        agent_interface = sim.agent_manager.agent_interface_for_agent_id(agent_id)
        assert (
            agent_interface is not None
        ), f"Missing agent_interface for agent_id={agent_id}"
        vehicle = self._vehicles[vehicle_id]
        sensor_state = self._sensor_states[vehicle_id]
        controller_state = self._controller_states[vehicle_id]
        mission_planner = sensor_state.mission_planner

        # Create a new vehicle to replace the old one
        new_vehicle = Vehicle.build_agent_vehicle(
            sim,
            vehicle.id,
            agent_interface,
            mission_planner,
            sim.scenario.vehicle_filepath,
            sim.scenario.tire_parameters_filepath,
            # BUG: Both the TrapManager and BubbleManager call into this method but the
            #      trainable field below always assumes trainable=True
            True,
            sim.scenario.surface_patches,
            sim.scenario.controller_parameters_filepath,
        )

        # Apply the physical values from the old vehicle chassis to the new one
        new_vehicle.chassis.inherit_physical_values(vehicle.chassis)

        # Reserve space inside the traffic sim
        sim._traffic_sim.reserve_traffic_location_for_vehicle(
            vehicle.id, vehicle.chassis.to_polygon
        )

        # Remove the old vehicle
        self.teardown_vehicles_by_vehicle_ids([vehicle.id])
        # HACK: Directly remove the vehicle from the traffic provider
        sim._traffic_sim.remove_traffic_vehicle(vehicle.id)

        # Take control of the new vehicle
        self._enfranchise_actor(
            sim,
            agent_id,
            agent_interface,
            new_vehicle,
            controller_state,
            sensor_state,
            boid,
            hijacking,
        )

        return new_vehicle

    def build_agent_vehicle(
        self,
        sim,
        agent_id,
        agent_interface,
        mission_planner,
        filepath,
        tire_filepath,
        trainable,
        surface_patches,
        controller_filepath,
        initial_speed=None,
        boid=False,
    ):
        vehicle_id = f"{agent_id}-{gen_id()}"
        vehicle = Vehicle.build_agent_vehicle(
            sim,
            vehicle_id,
            agent_interface,
            mission_planner,
            filepath,
            tire_filepath,
            trainable,
            surface_patches,
            controller_filepath,
            initial_speed,
        )

        sensor_state = SensorState(
            agent_interface.max_episode_steps,
            mission_planner=mission_planner,
        )

        controller_state = ControllerState.from_action_space(
            agent_interface.action_space, vehicle.pose, sim
        )

        self._enfranchise_actor(
            sim,
            agent_id,
            agent_interface,
            vehicle,
            controller_state,
            sensor_state,
            boid,
            hijacking=False,
        )

        return vehicle

    @clear_cache
    def _enfranchise_actor(
        self,
        sim,
        agent_id,
        agent_interface,
        vehicle,
        controller_state,
        sensor_state,
        boid=False,
        hijacking=False,
    ):
        # XXX: agent_id must be the original agent_id (not the fixed _2id(...))
        original_agent_id = agent_id

        Vehicle.attach_sensors_to_vehicle(
            sim, vehicle, agent_interface, sensor_state.mission_planner
        )
        if sim.is_rendering:
            vehicle.create_renderer_node(sim.renderer)
            sim.renderer.begin_rendering_vehicle(vehicle.id, is_agent=True)

        vehicle_id = _2id(vehicle.id)
        agent_id = _2id(original_agent_id)

        self._sensor_states[vehicle_id] = sensor_state
        self._controller_states[vehicle_id] = controller_state
        self._vehicles[vehicle_id] = vehicle
        self._2id_to_id[vehicle_id] = vehicle.id
        self._2id_to_id[agent_id] = original_agent_id

        entity = _ControlEntity(
            vehicle_id=vehicle_id,
            actor_id=agent_id,
            actor_type=_ActorType.Agent,
            shadow_actor_id="",
            is_boid=boid,
            is_hijacked=hijacking,
            position=vehicle.position,
        )
        self._controlled_by = np.insert(self._controlled_by, 0, tuple(entity))

    @clear_cache
    def build_social_vehicle(
        self, sim, vehicle_state, actor_id, vehicle_type, vehicle_id=None
    ):
        if vehicle_id is None:
            vehicle_id = gen_id()

        vehicle = Vehicle.build_social_vehicle(
            sim, vehicle_id, vehicle_state, vehicle_type
        )

        vehicle_id, actor_id = _2id(vehicle_id), _2id(actor_id)
        if sim.is_rendering:
            vehicle.create_renderer_node(sim.renderer)
            sim.renderer.begin_rendering_vehicle(vehicle.id, is_agent=False)

        self._vehicles[vehicle_id] = vehicle
        self._2id_to_id[vehicle_id] = vehicle.id
        entity = _ControlEntity(
            vehicle_id=vehicle_id,
            actor_id=actor_id,
            actor_type=_ActorType.Social,
            shadow_actor_id="",
            is_boid=False,
            is_hijacked=False,
            position=vehicle.position,
        )
        self._controlled_by = np.insert(self._controlled_by, 0, tuple(entity))

        return vehicle

    def begin_rendering_vehicles(self, renderer):
        agent_ids = self.agent_vehicle_ids()
        for vehicle in self._vehicles.values():
            if not vehicle.renderer:
                vehicle.create_renderer_node(renderer)
                is_agent = vehicle.id in agent_ids
                renderer.begin_rendering_vehicle(vehicle.id, is_agent)

    def sensor_states_items(self):
        return map(lambda x: (self._2id_to_id[x[0]], x[1]), self._sensor_states.items())

    def sensor_state_for_vehicle_id(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)
        return self._sensor_states[vehicle_id]

    def controller_state_for_vehicle_id(self, vehicle_id):
        vehicle_id = _2id(vehicle_id)
        return self._controller_states[vehicle_id]

    @staticmethod
    def _build_empty_controlled_by():
        return np.array(
            [],
            dtype=[
                # E.g. [(<vehicle ID>, <actor ID>, <actor type>), ...]
                ("vehicle_id", f"|S{VEHICLE_INDEX_ID_LENGTH}"),
                ("actor_id", f"|S{VEHICLE_INDEX_ID_LENGTH}"),
                ("actor_type", "B"),
                # XXX: Keeping things simple, this is always assumed to be an agent.
                #      We can add an shadow_actor_type when needed
                ("shadow_actor_id", f"|S{VEHICLE_INDEX_ID_LENGTH}"),
                ("is_boid", "B"),
                ("is_hijacked", "B"),
                ("position", np.float64, (3,)),
            ],
        )

    def __repr__(self):
        io = StringIO("")
        n_columns = len(self._controlled_by.dtype.names)

        by = self._controlled_by.copy().astype(
            list(zip(self._controlled_by.dtype.names, ["O"] * n_columns))
        )

        by["position"] = [", ".join([f"{x:.2f}" for x in p]) for p in by["position"]]
        by["actor_id"] = [truncate(p, 20) for p in by["actor_id"]]
        by["vehicle_id"] = [truncate(p, 20) for p in by["vehicle_id"]]
        by["shadow_actor_id"] = [truncate(p, 20) for p in by["shadow_actor_id"]]
        by["is_boid"] = [str(bool(x)) for x in by["is_boid"]]
        by["is_hijacked"] = [str(bool(x)) for x in by["is_hijacked"]]
        by["actor_type"] = [str(_ActorType(x)).split(".")[-1] for x in by["actor_type"]]

        # XXX: tableprint crashes when there's no data
        if by.size == 0:
            by = [[""] * n_columns]

        tp.table(by, self._controlled_by.dtype.names, style="round", out=io)
        return io.getvalue()


# Nombre del programa: Diccionarios - Corredor formula 1. <<algortimos>> (Reto 4)
# Programador: Juan Esteban Alarcón Miranda.
# Fecha: 01/07/2021
# Versión: 1
# Condiciones: día 1: valor; nDía: (valor*2)+10; día valor%3=0: valor/2
import os
os.system("cls")
print("Reto 4 - Formula 1.\n")
try:
    num_kilometrosDiaUno = int(input("¿Cuántos kilómetros recorrió el día 1?: \n"))
except ValueError:
    print("Dato erróneo, intente de nuevo.\n")
    num_kilometrosDiaUno = int(input("¿Cuántos kilómetros recorrió el día 1?: "))
while num_kilometrosDiaUno < 0:
    try:
      num_kilometrosDiaUno = int(input("¿Cuántos kilómetros recorrió el día 1?: \n"))
    except ValueError:
     print("Dato erróneo, intente de nuevo.\n")
     num_kilometrosDiaUno = int(input("¿Cuántos kilómetros recorrió el día 1?: "))
try:
    num_dias = int(input("¿Cuántos días duró el entrenamiento?: \n"))
except ValueError:
    print("Dato erróneo, intente de nuevo.\n")
    num_dias = int(input("¿Cuántos días duró el entrenamiento?: "))
while num_dias <= 0:
    try:
     num_dias = int(input("¿Cuántos días duró el entrenamiento?: \n"))
    except ValueError:
     print("Dato erróneo, intente de nuevo.\n")
     num_dias = int(input("¿Cuántos días duró el entrenamiento?: "))

def recorrido_formulaUno(num_kilometrosDiaUno,num_dias):
    recorridoFormulaUno = {}
    acumulado = num_kilometrosDiaUno
    recorridoFormulaUno[1] = [num_kilometrosDiaUno,num_kilometrosDiaUno]
    kms_ = num_kilometrosDiaUno
    for _ in range(2,num_dias+1,1):
       dia = _
       if dia % 3 == 0:
           kmsRecorridos = (kms_ //2)
       else:
            kmsRecorridos = (kms_*2)+10
       kms_ = kmsRecorridos
       acumulado += kms_
       recorridoFormulaUno[_] = [kms_,acumulado]
    return recorridoFormulaUno

print("Impresión del diccionario <<recorridoFormulaUno>>.\n")
print("Día              kms Recorridos          Acumulado  ")
diccionario_recorridoFormulaUno = recorrido_formulaUno(num_kilometrosDiaUno,num_dias)
for clave,valor in diccionario_recorridoFormulaUno.items():
    print(clave,"                     ",valor[0],"                  ",valor[1],end="\t\n")


from django.contrib import admin
from django.urls import path, include
from django.conf import settings

urlpatterns = [
    path('', admin.site.urls),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

admin.site.site_header = 'Sistema de Cálculos'
admin.site.index_title = 'Administração'
admin.site.site_title = 'Sistema de Cálculos - CCH'


import signal
import sys
sys.path.append('../')
from request_client import RequestClient
import numpy as np

class GracefulKiller:

    kill_now = False

    def __init__(self):
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)

    def exit_gracefully(self, _, __):
        self.kill_now = True

if __name__ == "__main__":
    client = RequestClient(topic='request_reply')
    # client.send('Hello')
    msg = dict({
        'Client': 'Hello',
        'vector1': np.zeros(shape=(1, 4), dtype=np.float32)
                })
    client.send_pyobj(msg)


# based on:
# https://github.com/openai/baselines/blob/master/baselines/deepq/replay_buffer.py

from collections import deque

from segment_tree import MinSegmentTree, SumSegmentTree

import random

import numpy as np

class ReplayMemory:
    def __init__(self, max_mem):
        self.memory = []
        self.next_idx = 0
        self.max_mem = max_mem

    def add_mem(self, state, action, next_state, reward, done, next_state_valid):
        data = (state, action, next_state, reward, done, next_state_valid)
        if self.next_idx >= len(self.memory):
            self.memory.append(data)
        else:
            self.memory[self.next_idx] = data
        self.next_idx = (self.next_idx + 1) % self.max_mem

    def get_batch(self, size):
        return random.sample(self.memory, k=size)

class PriorityReplayMemory(ReplayMemory):
    def __init__(self, size, alpha):
        super().__init__(size)
        self.alpha = alpha

        tree_cap = 1
        while tree_cap < size:
            tree_cap *= 2

        self.sum_tree = SumSegmentTree(tree_cap)
        self.max_priority = 1.0

    def add_mem(self, *args, **kwargs):
        idx = self.next_idx
        super().add_mem(*args, **kwargs)
        prio = self.max_priority ** self.alpha
        self.sum_tree[idx] = prio

    def _sample_idxs(self, size):
        idxs = []
        for _ in range(size):
            mass = random.random() * self.sum_tree.sum(0, len(self.memory)-1)
            idx = self.sum_tree.find_prefixsum_idx(mass)
            idxs.append(idx)
        return idxs

    def get_batch(self, size, beta):
        assert beta > 0
        idxs = self._sample_idxs(size)

        # create weights:
        weights = []
        tot_sum = self.sum_tree.sum()

        #p_min = tot_min / tot_sum
        #max_w = (p_min * len(self.memory)) ** (-beta)

        for idx in idxs:
            p_sample = self.sum_tree[idx] / tot_sum
            weight = (p_sample * len(self.memory)) ** (-beta)
            weights.append(weight)

        #print(max_w)
        #print(weights)
        weights = np.array(weights)
        weights /= max(weights)

        batch = [self.memory[idx] for idx in idxs]
        return batch, weights, idxs

    def update_priorities(self, idxs, priorities):
        for idx, prio in zip(idxs, priorities):
            assert prio > 0
            prio_a = prio ** self.alpha
            self.sum_tree[idx] = prio_a

            self.max_priority = max(self.max_priority, prio)