"""Convert COLMAP-style SfM results to NeRF input format

Ref: https://github.com/NVlabs/instant-ngp/blob/master/scripts/colmap2nerf.py

This is a truncated version edited by Ren Liu.
"""

import argparse
import json
import math
import os
from typing import Tuple

import cv2
import numpy as np

def parse_args() -> argparse.Namespace:
    """Parse arguments from user input
    Returns:
        parsed arguments
    """
    parser = argparse.ArgumentParser(
        description="convert a text colmap export to nerf format transforms.json; optionally convert video to images, \
            and optionally run colmap in the first place"
    )

    parser.add_argument("--images", default="images", help="input path to the images")
    parser.add_argument(
        "--text",
        default="colmap_text",
        help="input path to the colmap text files (set automatically if run_colmap is used)",
    )
    parser.add_argument(
        "--aabb_scale",
        default=16,
        choices=["1", "2", "4", "8", "16"],
        help="large scene scale factor. 1=scene fits in unit cube; power of 2 up to 16",
    )
    parser.add_argument("--skip_early", default=0, help="skip this many images from the start")
    parser.add_argument("--out", default=".", help="output path")
    return parser.parse_args()

def variance_of_laplacian(image: cv2.Mat) -> float:
    """compute the variance of laplacian of the input image

    Args:
        image: input image, in shape of (H, W)
    Returns:
        the variance of laplacian
    """
    return cv2.Laplacian(image, cv2.CV_64F).var()

def sharpness(imagePath: str) -> float:
    """compute the sharpness of the input image

    Args:
        imagePath: input image path
    Returns:
        the sharpness of laplacian
    """
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    fm = variance_of_laplacian(gray)
    return fm

def qvec2rotmat(qvec: np.ndarray) -> np.ndarray:
    """Convert quaternion rotation vector to 3x3 rotation matrix

    Args:
        qvec: a quaternion rotation vector, in shape of (4,)

    Returns:
        the corresponding 3x3 rotation matrix
    """
    return np.array(
        [
            [
                1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2,
                2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
                2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2],
            ],
            [
                2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
                1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2,
                2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1],
            ],
            [
                2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
                2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
                1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2,
            ],
        ]
    )

def rotmat(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    """calculate the 3x3 rotation matrix from vector a to vector b

    Args:
        a: orginal vector, in shape of (3,)
        b: target vector, in shape of (3,)

    Returns:
        result rotation matrix, in shape of (3, 3)
    """
    a, b = a / np.linalg.norm(a), b / np.linalg.norm(b)
    v = np.cross(a, b)
    c = np.dot(a, b)
    s = np.linalg.norm(v)
    kmat = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
    return np.eye(3) + kmat + kmat.dot(kmat) * ((1 - c) / (s ** 2 + 1e-10))

def closest_point_2_lines(oa: np.ndarray, da: np.ndarray, ob: np.ndarray, db: np.ndarray) -> Tuple[np.ndarray, float]:
    """returns point closest to both rays of form o+t*d, and a weight factor that goes to 0 if the lines are parallel

    Args:
        oa: origin of the first ray, in shape of (3, )
        da: direction of the first ray, in shape of (3, )
        ob: origin of the second ray, in shape of (3, )
        db: direction of the second ray, in shape of (3, )

    Returns:
        1. the point closest to both rays of form o+t*d, in shape of (3, )
        2. a weight factor that goes to 0 if the lines are parallel
    """
    da = da / np.linalg.norm(da)
    db = db / np.linalg.norm(db)
    c = np.cross(da, db)
    denom = np.linalg.norm(c) ** 2
    t = ob - oa
    ta = np.linalg.det([t, db, c]) / (denom + 1e-10)
    tb = np.linalg.det([t, da, c]) / (denom + 1e-10)
    if ta > 0:
        ta = 0
    if tb > 0:
        tb = 0
    return (oa + ta * da + ob + tb * db) * 0.5, denom

if __name__ == "__main__":
    args = parse_args()

    AABB_SCALE = int(args.aabb_scale)
    SKIP_EARLY = int(args.skip_early)
    IMAGE_FOLDER = args.images
    TEXT_FOLDER = args.text
    OUT_PATH = args.out
    print(f"outputting to {OUT_PATH}...")
    with open(os.path.join(TEXT_FOLDER, "cameras.txt"), "r") as f:
        angle_x = math.pi / 2
        for line in f:
            # 1 SIMPLE_RADIAL 2048 1536 1580.46 1024 768 0.0045691
            # 1 OPENCV 3840 2160 3178.27 3182.09 1920 1080 0.159668 -0.231286 -0.00123982 0.00272224
            # 1 RADIAL 1920 1080 1665.1 960 540 0.0672856 -0.0761443
            if line[0] == "#":
                continue
            els = line.split(" ")
            w = float(els[2])
            h = float(els[3])
            fl_x = float(els[4])
            fl_y = float(els[4])
            k1 = 0
            k2 = 0
            p1 = 0
            p2 = 0
            cx = w / 2
            cy = h / 2
            if els[1] == "SIMPLE_PINHOLE":
                cx = float(els[5])
                cy = float(els[6])
            elif els[1] == "PINHOLE":
                fl_y = float(els[5])
                cx = float(els[6])
                cy = float(els[7])
            elif els[1] == "SIMPLE_RADIAL":
                cx = float(els[5])
                cy = float(els[6])
                k1 = float(els[7])
            elif els[1] == "RADIAL":
                cx = float(els[5])
                cy = float(els[6])
                k1 = float(els[7])
                k2 = float(els[8])
            elif els[1] == "OPENCV":
                fl_y = float(els[5])
                cx = float(els[6])
                cy = float(els[7])
                k1 = float(els[8])
                k2 = float(els[9])
                p1 = float(els[10])
                p2 = float(els[11])
            else:
                print("unknown camera model ", els[1])
            # fl = 0.5 * w / tan(0.5 * angle_x);
            angle_x = math.atan(w / (fl_x * 2)) * 2
            angle_y = math.atan(h / (fl_y * 2)) * 2
            fovx = angle_x * 180 / math.pi
            fovy = angle_y * 180 / math.pi

    print(f"camera:\n\tres={w,h}\n\tcenter={cx,cy}\n\tfocal={fl_x,fl_y}\n\tfov={fovx,fovy}\n\tk={k1,k2} p={p1,p2} ")

    with open(os.path.join(TEXT_FOLDER, "images.txt"), "r") as f:
        i = 0
        bottom = np.array([0.0, 0.0, 0.0, 1.0]).reshape([1, 4])
        out = {
            "camera_angle_x": angle_x,
            "camera_angle_y": angle_y,
            "fl_x": fl_x,
            "fl_y": fl_y,
            "k1": k1,
            "k2": k2,
            "p1": p1,
            "p2": p2,
            "cx": cx,
            "cy": cy,
            "w": w,
            "h": h,
            "aabb_scale": AABB_SCALE,
            "frames": [],
        }

        up = np.zeros(3)
        for line in f:
            line = line.strip()
            if line[0] == "#":
                continue
            i = i + 1
            if i < SKIP_EARLY * 2:
                continue
            if i % 2 == 1:
                elems = line.split(
                    " "
                )  # 1-4 is quat, 5-7 is trans, 9ff is filename (9, if filename contains no spaces)
                # name = str(PurePosixPath(Path(IMAGE_FOLDER, elems[9])))
                # why is this requireing a relitive path while using ^
                image_rel = os.path.relpath(IMAGE_FOLDER)
                name = str(f"./{image_rel}/{'_'.join(elems[9:])}")
                b = sharpness(name)
                print(name, "sharpness=", b)
                image_id = int(elems[0])
                qvec = np.array(tuple(map(float, elems[1:5])))
                tvec = np.array(tuple(map(float, elems[5:8])))
                R = qvec2rotmat(-qvec)
                t = tvec.reshape([3, 1])
                m = np.concatenate([np.concatenate([R, t], 1), bottom], 0)
                c2w = np.linalg.inv(m)
                c2w[0:3, 2] *= -1  # flip the y and z axis
                c2w[0:3, 1] *= -1
                c2w = c2w[[1, 0, 2, 3], :]  # swap y and z
                c2w[2, :] *= -1  # flip whole world upside down

                up += c2w[0:3, 1]

                frame = {"file_path": name, "sharpness": b, "transform_matrix": c2w}
                out["frames"].append(frame)
    nframes = len(out["frames"])
    up = up / np.linalg.norm(up)
    print("up vector was", up)
    R = rotmat(up, [0, 0, 1])  # rotate up vector to [0,0,1]
    R = np.pad(R, [0, 1])
    R[-1, -1] = 1

    for f in out["frames"]:
        f["transform_matrix"] = np.matmul(R, f["transform_matrix"])  # rotate up to be the z axis

    # find a central point they are all looking at
    print("computing center of attention...")
    totw = 0.0
    totp = np.array([0.0, 0.0, 0.0])
    for f in out["frames"]:
        mf = f["transform_matrix"][0:3, :]
        for g in out["frames"]:
            mg = g["transform_matrix"][0:3, :]
            p, w = closest_point_2_lines(mf[:, 3], mf[:, 2], mg[:, 3], mg[:, 2])
            if w > 0.01:
                totp += p * w
                totw += w
    totp /= totw
    print(totp)  # the cameras are looking at totp
    for f in out["frames"]:
        f["transform_matrix"][0:3, 3] -= totp

    avglen = 0.0
    for f in out["frames"]:
        avglen += np.linalg.norm(f["transform_matrix"][0:3, 3])
    avglen /= nframes
    print("avg camera distance from origin", avglen)
    for f in out["frames"]:
        f["transform_matrix"][0:3, 3] *= 4.0 / avglen  # scale to "nerf sized"

    for f in out["frames"]:
        f["transform_matrix"] = f["transform_matrix"].tolist()
    print(nframes, "frames")
    print(f"writing {OUT_PATH}/transforms.json")
    if not os.path.exists(OUT_PATH):
        os.makedirs(OUT_PATH)
    with open(os.path.join(OUT_PATH, "transforms.json"), "w") as outfile:
        json.dump(out, outfile, indent=2)


"""
leetcode problem 16.

find the 3 numbers in a list that sum clostest to the target

Brute force:
iterate through the list in 3 nested loops
O(n^3) - time
O(n) - space

Better #1:
sort array O(nlogn)
fix one point and use pointers to find the best solution O(n^2)

O(nlogn) + O(n^2) = O(n^2 + nlogn) = O(n^2)

"""

def sum3close(nums: list, t: int) -> int:
    nums.sort()
    res = nums[0] + nums[1] + nums[2]
    for i, e in enumerate(nums):
        if i >= len(nums)-2: break
        j, k = i+1, len(nums)-1
        while j < k:
            s = nums[i] + nums[j] + nums[k]
            if s == t:
                return s
            if abs(s - t) < abs(res-t):
                res = s
            if s < t:
                j += 1
            else:
                k -= 1
    return res

if __name__ == "__main__":
    a = [-1, 2, 1, -4]

    print(sum3close(a, 1))


def readFromFile(fileName):
    file = open(fileName)
    lst = []
    for line in file:
        lst.append(line.strip())
    return lst

# PART 1:
def checkSum(fileName):
    lst = readFromFile(fileName)

    twice = 0
    thrice = 0
    for i in lst:
        counted_twice = False
        counted_thrice = False
        d = {}
        for j in i:
            if j in d:
                d[j] += 1
            else:
                d[j] = 1
        for k in d:
            if d[k] == 2 and not counted_twice:
                counted_twice = True
                twice += 1
            elif d[k] == 3 and not counted_thrice:
                counted_thrice = True
                thrice += 1
    return twice * thrice
# print(checkSum("test.txt"))
# print(checkSum("input.txt"))

# Part 2:

def checkString(stringA, stringB):
    unMatchingIndex = 0
    if stringA == stringB or len(stringA) != len(stringB):
        return False, unMatchingIndex

    numMatching = 0
    for i in range(0, len(stringA)):
        if stringA[i] == stringB[i]:
            numMatching += 1
        else:
            unMatchingIndex = i
    if numMatching == len(stringA) - 1:
        return True, unMatchingIndex
    return False, unMatchingIndex

def matchIDs(fileName):
    lst = readFromFile(fileName)
    for i in range(0, len(lst)):
        for j in range(0, len(lst)):
            checked, strIDX = checkString(lst[i], lst[j])
            if checked:
                s = lst[i]
                sA = s[0:strIDX]
                sB = s[strIDX + 1:]
                return sA + sB

print(matchIDs("input.txt"))


#Q2. Write a program which contains one function named as ChkNum() which accept one
#parameter as number. If number is even then it should display “Even number” otherwise
#display “Odd number” on console.
#Input : 11 Output : Odd Number
#Input : 8 Output : Even Number

#Solution:
def ChkNum(Value):
    if Value%2 == 0:
        return "Even Number"
    else:
        return "Odd Number"

def main():
    print("Enter a Number for checking whether it is Even or Odd")
    Num = int(input())
    Ans = ChkNum(Num)
    print(f"{Num} is: ",Ans)

# Code starter
if __name__ == "__main__":
    main()


import torch

class Corpus():
    """ Transform words to index then to tensors."""
    def __init__(self, path):
        self.encoding = Encoding()
        self.train = self.process(path + 'train.txt')
        self.val = self.process(path + 'valid.txt')
        self.test = self.process(path + 'test.txt')

    def process(self, path):
        with open(path, 'r') as f:
            all = []
            for line in f:
                words = line.split() + ['<eos>']
                ids = []
                for w in words:
                    ids.append(self.encoding.encode(w))
                all.append(torch.tensor(ids).type(torch.int64))
            res = torch.cat(all)

        return res

class Encoding():
    """ Encode word to index"""
    def __init__(self):
        self.word2index = {}
        self.index2word = []

    def encode(self, word):
        if word not in self.word2index:
            self.index2word.append(word)
            self.word2index[word] = len(self.index2word) - 1

        return self.word2index[word]


from cell import *   #personal file

class Grid:
	def __init__(self, rows, cols, width, height, margin_width, margin_height, cell_size):
		self.cells = []
		self.rows = rows
		self.cols = cols
		self.width = width
		self.height = height
		self.cell_size = cell_size

		# creating cells
		for i in range(rows):
			self.cells.append([])
			for j in range(cols):
				self.cells[i].append(Cell(margin_width + cell_size * j, margin_height + cell_size * i))

	def draw(self, _canvas):
		# draws actual grid
		for n in range(self.rows - 1):
			_canvas.create_line(self.cells[n][0].x, self.cells[n][0].y + self.cell_size, self.cells[n][0].x + self.width, self.cells[n][0].y + self.cell_size, fill = "#0DA192", width = self.height/(10 * self.rows))
			_canvas.create_line(self.cells[0][n].x + self.cell_size, self.cells[0][n].y, self.cells[0][n].x + self.cell_size, self.cells[0][n].y + self.height, fill = "#0DA192", width = self.height/(10 * self.rows))

		# draws cell contents
		for i in range(self.rows):
			for j in range(self.cols):
				currentCell = self.cells[i][j]

				currentCellOccupationColor = "black" if currentCell.occupiedBy == 'x' else "#f2EBD3"

				_canvas.create_text(currentCell.x + self.cell_size/2, currentCell.y + self.cell_size/2.5, text = currentCell.occupiedBy, fill = currentCellOccupationColor, font = ("Helvetica {} bold".format(int(self.cell_size))))


from django.urls import path
from wish_list import views

urlpatterns = [
    path('',views.index),
    path('register',views.register),
    path('login',views.login),
    path('dashboard',views.dashboard),
    path('logout',views.logout),
    path('home',views.home),
    path('create',views.create),
    path('wishes',views.wishes),
    path('add_item',views.add_item),
    path('addwish/<int:wish_id>', views.addwish),
    path('removewish/<int:wish_id>', views.removewish),
    path('wish/<int:wish_id>',views.wishInfo)
]


# from txt to html
# install wkthtml
import os
import pdfkit

with open("text.txt") as file:
	with open ("text.html", "w") as output:
		file = file.read()
		file = file.replace("\n", "<br>")
		output.write(file)

#os.startfile("text.txt")
#os.startfile("text.html")
pdfkit.from_file("text.html", "output.pdf")

os.startfile("output.pdf")


import numpy as np
import matplotlib.pylab as plt
from scipy import signal as dsp
from scipy.fft import fft, fftfreq
from enum import Enum

def dB_to_normal(val):
    return 10.0 ** (val/20)

def normal_to_dB(val):
    return 20*np.log10(val)

def filter_plotter(w_hz, mag, cutoff_freq_hz, amplitude_axis='normal', amplitude_input_unit='normal', freq_unit='Hz', freq_axis='linear'):
    '''
    Plots the frequency response of a filter

    Parameters
    -----------

    w_hz: frequency vector in Hz
    mag: amplitude vector
    cutoff_freq_hz: cutoff frequency in Hz
    amplitude_unit: unit for plotting amplitude (normal or dB)
    freq_unit: unit for plotting frequency (Hz or rad/s)
    freq_axis: 'linear' or 'log'

    Returns
    ---------
    '''

    fig = plt.figure(figsize=(8, 3))

    # frequency axis
    freq_vec = None

    if freq_unit=='Hz':
        freq_vec = w_hz
        cutoff_freq = cutoff_freq_hz
        plt.xlabel("Frequency (Hz)")

    elif freq_unit=='rad_per_sec':
        freq_vec = hz_to_rad_per_sec(w_hz)
        cutoff_freq = hz_to_rad_per_sec(cutoff_freq_hz)
        plt.xlabel("Frequency (rad/sec)")

    else:
        raise Exception('Unknown frequency unit')

    #  Amplitude input unit
    if amplitude_input_unit =='normal':
        mag_dB = normal_to_dB(mag)
        mag_normal = mag
    elif amplitude_input_unit == 'dB':
        mag_normal = dB_to_normal(mag)
        mag_dB = mag
    else:
        raise Exception('Unknown amplitude input unit')

    #  Amplitude axis
    if amplitude_axis == 'normal':
        mag_plot = mag_normal
        plt.ylabel("Amplitude (normal)")

    elif amplitude_axis=='dB':
        mag_plot = mag_dB
        plt.ylabel("Amplitude (dB)")

    else:
        raise Exception('Unknown amplitude axis unit')

    # frequency axis
    if freq_axis=='linear':
        plt.plot(freq_vec, mag_plot)

    elif freq_axis=='log':
        plt.semilogx(freq_vec, mag_plot)
    else:
        raise Exception('Unknown frequency axis type')

    # plot the cutoff frequency
    plt.axvline(x = cutoff_freq, color = 'b', label = 'cutoff freq', linestyle=':')
    ax_list = fig.axes
    ax = ax_list[0]
    ax.text(cutoff_freq + 1 , +0.2, 'f_c',
            fontsize = 10, color ="green", transform=ax.get_xaxis_transform())

    plt.grid()
    plt.show()

## bode magnitude plot

def plot_bode_magn(h_n, fs):

    '''
    Plots the bode magnitude of a discrete time transfer function

    Parameters
    -----------

    h_n: impulse response
    fs: sampling rate in Hz

    Returns
    ---------
    '''

    plt.figure()

    N = h_n.size
    dt = 1 / fs

    # frequency points
    x = np.linspace(0,fs, N)
    xf = fftfreq(N, dt)[:N//2]

    #perform fft
    yf = fft(h_n)

    # compute bode magnitude plot values
    magn = np.abs(yf[0:N//2])

    # plotting
    plt.plot(xf, magn)
    plt.grid()
    plt.show()


# Задача №19. Решение в группах Дана последовательность из N целых чисел и число K. Необходимо сдвинуть всю последовательность (сдвиг - циклический) на K элементов вправо,  K – положительное число. Input:   [1, 2, 3, 4, 5] k = 3 Output:  [4, 5, 1, 2, 3]

list_num = [1, 2, 3, 4, 5]
k = 3

print(list_num)
for i in range(k):
    list_num.insert(0, list_num.pop())

print(list_num)

# list_num = [1, 2, 3, 4, 5]
# k = 3
# print(list_num[:k])
# print(list_num[k:])

# print(list_num[k:] + list_num[:k])

# list_1 = [45, 23, 1, 5, 31] # len()
# k = int(input("Введите кол-во сдвигов: ")) % len(list_1)
# # int.Parse(Console.ReadLine()!) % array.Length;
# # print(list_1[begin=0:end=обязательный_парамет:step=+1])
# if k == 0:
#     print(list_1)
# else:
#     print(list_1[-k:] + list_1[:len(list_1) - k])


from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login/", views.login_view, name="login"),
    path("logout/", views.logout_view, name="logout"),
    path("register/", views.register, name="register"),
    path("create/", views.create, name="create"),
    path("listing/<int:id>/", views.listing, name="listing"),
    path("category/", views.category, name="category"),
    path("watchlist/", views.watchlist, name="watchlist"),
    path("delete/<int:listing_id>", views.delete, name="delete"),
    path("comments/", views.comments, name="comments"),
    path("add_bid/", views.add_bid, name="add_bid"),
    path("close_bid/", views.close_bid, name="close_bid")

]


import numpy as np
import cv2
import time
import random
import collections
from edgetpu.detection.engine import DetectionEngine
from edgetpu.utils import dataset_utils
from PIL import Image
from matplotlib import cm
import os
import urllib.request

class StopSignDetector(object):
    '''
    Requires an EdgeTPU for this part to work

    This part will run a EdgeTPU optimized model to run object detection to detect a stop sign.
    We are just using a pre-trained model (MobileNet V2 SSD) provided by Google.
    '''

    def download_file(self, url, filename):
        if not os.path.isfile(filename):
            urllib.request.urlretrieve(url, filename)

    def __init__(self, min_score, show_bounding_box, max_reverse_count=0, reverse_throttle=-0.5, debug=False):
        MODEL_FILE_NAME = "ssd_mobilenet_v2_coco_quant_postprocess_edgetpu.tflite"
        LABEL_FILE_NAME = "coco_labels.txt"

        MODEL_URL = "https://github.com/google-coral/edgetpu/raw/master/test_data/ssd_mobilenet_v2_coco_quant_postprocess_edgetpu.tflite"
        LABEL_URL = "https://dl.google.com/coral/canned_models/coco_labels.txt"

        self.download_file(MODEL_URL, MODEL_FILE_NAME)
        self.download_file(LABEL_URL, LABEL_FILE_NAME)

        self.last_5_scores = collections.deque(np.zeros(5), maxlen=5)
        self.engine = DetectionEngine(MODEL_FILE_NAME)
        self.labels = dataset_utils.read_label_file(LABEL_FILE_NAME)

        self.STOP_SIGN_CLASS_ID = 12
        self.min_score = min_score
        self.show_bounding_box = show_bounding_box
        self.debug = debug

        # reverse throttle related
        self.max_reverse_count = max_reverse_count
        self.reverse_count = max_reverse_count
        self.reverse_throttle = reverse_throttle
        self.is_reversing = False

    def convertImageArrayToPILImage(self, img_arr):
        img = Image.fromarray(img_arr.astype('uint8'), 'RGB')

        return img

    '''
    Return an object if there is a traffic light in the frame
    '''
    def detect_stop_sign (self, img_arr):
        img = self.convertImageArrayToPILImage(img_arr)

        ans = self.engine.detect_with_image(img,
                                          threshold=self.min_score,
                                          keep_aspect_ratio=True,
                                          relative_coord=False,
                                          top_k=3)
        max_score = 0
        traffic_light_obj = None
        if ans:
            for obj in ans:
                if (obj.label_id == self.STOP_SIGN_CLASS_ID):
                    if self.debug:
                        print("stop sign detected, score = {}".format(obj.score))
                    if (obj.score > max_score):
                        print(obj.bounding_box)
                        traffic_light_obj = obj
                        max_score = obj.score

        # if traffic_light_obj:
        #     self.last_5_scores.append(traffic_light_obj.score)
        #     sum_of_last_5_score = sum(list(self.last_5_scores))
        #     # print("sum of last 5 score = ", sum_of_last_5_score)

        #     if sum_of_last_5_score > self.LAST_5_SCORE_THRESHOLD:
        #         return traffic_light_obj
        #     else:
        #         print("Not reaching last 5 score threshold")
        #         return None
        # else:
        #     self.last_5_scores.append(0)
        #     return None

        return traffic_light_obj

    def draw_bounding_box(self, traffic_light_obj, img_arr):
        xmargin = (traffic_light_obj.bounding_box[1][0] - traffic_light_obj.bounding_box[0][0]) *0.1

        traffic_light_obj.bounding_box[0][0] = traffic_light_obj.bounding_box[0][0] + xmargin
        traffic_light_obj.bounding_box[1][0] = traffic_light_obj.bounding_box[1][0] - xmargin

        ymargin = (traffic_light_obj.bounding_box[1][1] - traffic_light_obj.bounding_box[0][1]) *0.05

        traffic_light_obj.bounding_box[0][1] = traffic_light_obj.bounding_box[0][1] + ymargin
        traffic_light_obj.bounding_box[1][1] = traffic_light_obj.bounding_box[1][1] - ymargin

        cv2.rectangle(img_arr, tuple(traffic_light_obj.bounding_box[0].astype(int)),
                        tuple(traffic_light_obj.bounding_box[1].astype(int)), (0, 255, 0), 2)

    def run(self, img_arr, throttle, debug=False):
        if img_arr is None:
            return throttle, img_arr

        # Detect traffic light object
        traffic_light_obj = self.detect_stop_sign(img_arr)

        if traffic_light_obj or self.is_reversing:
            if self.show_bounding_box and traffic_light_obj != None:
                self.draw_bounding_box(traffic_light_obj, img_arr)

            # Set the throttle to reverse within the max reverse count when detected the traffic light object
            if self.reverse_count < self.max_reverse_count:
                self.is_reversing = True
                self.reverse_count += 1
                return self.reverse_throttle, img_arr
            else:
                self.is_reversing = False
                return 0, img_arr
        else:
            self.is_reversing = False
            self.reverse_count = 0
            return throttle, img_arr


from __future__ import absolute_import, division, print_function, unicode_literals

import argparse
import configparser as cfg
import datetime
from lxml import etree as ET
import multiprocessing as mp
import os
import sys

import cnes.common.lib.my_tools as my_tools
import cnes.common.lib.my_timer as my_timer
import cnes.common.lib_lake.lake_db as lake_db
import cnes.common.lib_lake.locnes_filenames as locnes_filenames

import pge_lake_avg

class MultiLakeAvg(object):
    """
    Class MultiLakeAvg
    Main class to run many SAS LakeAvg processes
    """

    def __init__(self, in_params):
        """
        Constructor: initialize variables

        :param in_params: input parameters to run the processor
        :type in_params: dictionary
        """
        print("[multiLakeAvgProcessing] == INIT ==")

        # Directories
        self.param_file = in_params["param_file"]  # Parameter file
        self.lakesp_dir = in_params["lakesp_dir"]  # LakeSP_Prior files directory
        self.output_dir = in_params["output_dir"]  # Output directory

        # PLD infos
        self.lake_db = in_params["LAKE_DB"]
        self.lake_db_id = in_params["LAKE_DB_ID"]

        # Cycle number and basin code
        self.cycle_num = my_params["cycle_num"]  # Cycle number
        self.basin_code = my_params["basin_code"]  # Basin code

        # Options
        self.flag_inc_file_counter = in_params["flag_inc_file_counter"]
        self.flag_write_full_path = in_params["flag_write_full_path"]
        self.nb_proc = in_params["nb_proc"]

        # Log level
        self.error_file = in_params["errorFile"]
        self.log_file = in_params["logFile"]
        self.log_file_level = in_params["logfilelevel"]
        self.log_console = in_params["logConsole"]
        self.log_console_level = in_params["logconsolelevel"]

        # File information
        self.institution = in_params["institution"]
        self.product_version = in_params["product_version"]
        self.crid_lakesp = in_params["crid_lakesp"]
        self.crid_lakeavg = in_params["crid_lakeavg"]
        self.pge_version = in_params["pge_version"]
        self.contact = in_params["contact"]

        # List of input files
        self.list_cycle_basin = dict()  # List of cycles and basin_code to handle
        self.cmd_file_path_list = []  # List of command files

        # Nb_proc parameter
        self.nb_proc = in_params["nb_proc"]
    # -------------------------------------------

    def run_preprocessing(self):
        """
        Retrieve the list of input files, i.e. L2_HR_LakeSP_Prior files
        """

        print("")
        print("")
        print("[multiLakeAvgProcessing] PRE-PROCESSING...")
        print("")

        # 1 - Test existence of directories
        print("[multiLakeAvgProcessing] > 1 - Testing existence of working directories...")
        # 1.1 - LakeSP_Prior directory
        print("[multiLakeAvgProcessing]   INPUT DIR for LakeSP_Prior files = %s" % self.lakesp_dir)
        my_tools.test_dir(self.lakesp_dir)
        # 1.2 - Output directory
        print("[multiLakeAvgProcessing]   OUTPUT DIR = %s" % self.output_dir)
        my_tools.test_dir(self.output_dir)
        print("")

        # 2 - Get input files
        print("[multiLakeAvgProcessing] > 2 - Retrieving input files...")

        # 2.1 - Compute file prefix regarding cycle condition and basin_code in LakeSP_Prior.shp.xml files
        lakesp_prefix = locnes_filenames.LAKE_SP_PREFIX["prior"]
        lakesp_suffix = locnes_filenames.LAKE_SP_SHP_SUFFIX
        cond_prefix = lakesp_prefix  # Deal with all LakeSP_Prior files in self.lakesp_dir

        flag_list = False
        cond_continent = None
        if (self.cycle_num is None) or (self.cycle_num == "-1"):
            flag_list = True

            if (self.basin_code is None) or (self.basin_code == "-1"):
                print("[multiLakeAvgProcessing]   All LakeSP_Prior files in the input directory")

            else:  # Deal with LakeSP_Prior files with basin_code = self.basin_code
                continent = lake_db.compute_continent_id_from_basin_code(str(self.basin_code)[0])
                cond_continent = "_%s_" % continent
                if self.basin_code < 10:  # Manage all basins of continent
                    print("[multiLakeAvgProcessing]   LakeSP_Prior files with continent=%s (digit=%s)" % (continent, str(self.basin_code)[0]))

                else:
                    print("[multiLakeAvgProcessing]   LakeSP_Prior files with basin_code=%02d (continent=%s)" % (self.basin_code, continent))

        else:  # Deal with LakeSP_Prior files with cycle = self.cycle_num
            cond_prefix += "%03d" % self.cycle_num
            if (self.basin_code is None) or (self.basin_code == "-1"):
                print("[multiLakeAvgProcessing]   LakeSP_Prior files with cycle=%03d" % self.cycle_num)
                flag_list = True
            else:  # Deal with LakeSP_Prior files with cycle = self.cycle_num and basin_code = self.basin_code
                continent = lake_db.compute_continent_id_from_basin_code(str(self.basin_code)[0])
                cond_continent = "_%s_" % continent
                if self.basin_code < 10:  # Manage all basins of continent
                    print("[multiLakeAvgProcessing]   LakeSP_Prior files with cycle=%03d and continent=%s (digit=%s)" % (self.cycle_num, continent, str(self.basin_code)[0]))
                    flag_list = True
                else:
                    self.list_cycle_basin[self.cycle_num] = {self.basin_code}
                    print("[multiLakeAvgProcessing]   LakeSP_Prior files with cycle=%03d and basin_code=%02d (continent=%s)" % (self.cycle_num, self.basin_code, continent))

        if flag_list:

            # 2.2 - List all files in self.lakesp_dir
            tmp_list_lakesp_files = os.listdir(self.lakesp_dir)

            # 2.3 - For each listed file, select LakeSP_Prior shapefiles corresponding to specified cycle number and basin code
            for cur_file in tmp_list_lakesp_files:

                # Test if file meets the conditions
                flag_ok = False
                if cond_continent is None:
                    if cur_file.startswith(cond_prefix) and cur_file.endswith(lakesp_suffix):
                        flag_ok = True
                else:
                    if cur_file.startswith(cond_prefix) and cur_file.endswith(lakesp_suffix) and (cond_continent in cur_file):
                        flag_ok = True

                # Process if yes
                if flag_ok:

                    # 2.4 - Retrieve cycle number
                    cycle_num = int(cur_file.split("_")[5])
                    if cycle_num not in self.list_cycle_basin.keys():
                        self.list_cycle_basin[cycle_num] = set()

                    # 2.5 - Get basin_code list from LakeSP_Prior metadata file (ie .shp.xml)
                    metadata = ET.parse(os.path.join(self.lakesp_dir, cur_file + ".xml"))
                    # Retrieve basin_code
                    cur_basin_code_txt = metadata.xpath("//swot_product/global_metadata/basin_code")[0].text
                    if not cur_basin_code_txt:
                        cur_basin_code_list = [""]
                    else:
                        cur_basin_code_list = cur_basin_code_txt.split(";")

                    # 2.6 - Add CB basins to list of selected basins for the cycle
                    for cur_basin_code in cur_basin_code_list:
                        if cur_basin_code != "":
                            self.list_cycle_basin[cycle_num].add(int(cur_basin_code[0:2]))

        # Print some numbers
        tmp_print = "[multiLakeAvgProcessing]   * Cycle numbers to process = "
        for cycle_num in self.list_cycle_basin.keys():
            tmp_print += "%03d - " % cycle_num
        print(tmp_print)
        for cycle_num, cycle_basins in self.list_cycle_basin.items():
            tmp_print = "[multiLakeAvgProcessing]   * Cycle number %03d => basin IDs = " % cycle_num
            for basin_code in cycle_basins:
                tmp_print += "%02d - " % basin_code
            print(tmp_print)
        print("")

        # 3 - Writing command files
        print("[multiLakeAvgProcessing] > 3 - Writing command files...")
        for cycle_num, cycle_basins in self.list_cycle_basin.items():
            for basin_code in cycle_basins:
                print("[multiLakeAvgProcessing]   * Writing command file cycle_num=%03d / basin_code=%02d" %(cycle_num, basin_code))
                cmd_file_path = self.create_cmd_file(cycle_num, basin_code)
                self.cmd_file_path_list.append(cmd_file_path)
        print("")

    def create_cmd_file(self, in_cycle_num, in_basin_code):
        """
        Create command file for PGE_L2_HR_LakeAvg with CYCLE_NUM=in_cycle_num and BASIN_CODE=in_basin_code

        :param in_cycle_num: cycle number to write in command file
        :type in_cycle_num: int
        :param in_basin_code: basin code to write in command file
        :type in_basin_code: int

        :return: out_cmd_file = command file full path
        :rtype: string
        """

        # 0.1 - Init error log filename (without date because it is computed in pge_lake_tile.py)
        if self.error_file is None:
            error_file = os.path.join(self.output_dir,
                                      "ErrorFile_%03d_%02d.log" % (in_cycle_num, in_basin_code))
        else:
            error_file = "%s_%03d_%02d%s" % (os.path.splitext(self.error_file)[0],
                                             in_cycle_num, in_basin_code,
                                             os.path.splitext(self.error_file)[1])
        # 0.2 - Init log filename (without date because it is computed in pge_lake_tile.py)
        if self.log_file is None:
            log_file = os.path.join(self.output_dir,
                                    "LogFile_%03d_%02d.log" % (in_cycle_num, in_basin_code))
        else:
            log_file = "%s_%03d_%02d%s" % (os.path.splitext(self.log_file)[0],
                                           in_cycle_num, in_basin_code,
                                           os.path.splitext(self.log_file)[1])

        # 1 - Init command filename
        cmd_filename = "lake_avg_command_%03d_%02d.cfg" % (in_cycle_num, in_basin_code)
        out_cmd_file = os.path.join(self.output_dir, cmd_filename)

        # 2 - Open command file
        writer_cmd_file = open(out_cmd_file, "w")  # Open file in writing mode

        # 3 - Write command file

        # 3.1 - Fill PATHS section
        writer_cmd_file.write("[PATHS]\n")
        if self.param_file is None:
            # Needed by Jenkins script
            writer_cmd_file.write("param_file = %s\n" % os.path.join(sys.path[0], "lake_avg_param.cfg"))
        else:
            writer_cmd_file.write("param_file = %s\n" % self.param_file)
        writer_cmd_file.write("LakeSP_Prior directory = %s\n" % self.lakesp_dir)
        writer_cmd_file.write("Output directory = %s\n\n" % self.output_dir)

        # 3.2 - Fill DATABASES section
        if self.lake_db is not None:
            writer_cmd_file.write("[DATABASES]\n")
            writer_cmd_file.write("LAKE_DB = " + self.lake_db + "\n")
            if self.lake_db.endswith(".shp"):
                if self.lake_db_id is not None:
                    writer_cmd_file.write("LAKE_DB_ID = " + self.lake_db_id + "\n")
            writer_cmd_file.write("\n")

        # 3.3 - Fill PASS_INFOS section
        writer_cmd_file.write("[PASS_INFOS]\n")
        writer_cmd_file.write("Cycle number = %03d\n" % in_cycle_num)
        writer_cmd_file.write("Basin code = %02d\n\n" % in_basin_code)

        # 3.4 - Fill OPTIONS section
        writer_cmd_file.write("[OPTIONS]\n")
        writer_cmd_file.write("Increment file counter = " + str(self.flag_inc_file_counter) + "\n")
        writer_cmd_file.write("Write full path = " + str(self.flag_write_full_path) + "\n")
        writer_cmd_file.write("Nb_proc = " + str(self.nb_proc) + "\n\n")

        # 3.5 - Fill LOGGING section
        writer_cmd_file.write("[LOGGING]\n")
        writer_cmd_file.write("errorFile = " + error_file + "\n")
        writer_cmd_file.write("logFile = " + log_file + "\n")
        writer_cmd_file.write("logfilelevel = " + self.log_file_level + "\n")
        writer_cmd_file.write("logConsole = " + str(self.log_console) + "\n")
        writer_cmd_file.write("logconsolelevel = " + self.log_console_level + "\n\n")

        # 3.6 - Fill FILE_INFORMATION section
        writer_cmd_file.write("[FILE_INFORMATION]\n")
        writer_cmd_file.write("INSTITUTION = " + self.institution + "\n")
        writer_cmd_file.write("PRODUCT_VERSION = " + self.product_version + "\n")
        writer_cmd_file.write("CRID_LAKESP = " + self.crid_lakesp + "\n")
        writer_cmd_file.write("CRID_LAKEAVG = " + self.crid_lakeavg + "\n")
        writer_cmd_file.write("PGE_VERSION = " + self.pge_version + "\n")
        writer_cmd_file.write("CONTACT = " + self.contact + "\n")

        # 4 - Close command file
        writer_cmd_file.close()

        return out_cmd_file

    # -------------------------------------------

    def run_processing(self, cmd_file=None):
        """
        Process SAS_L2_HR_LakeAvg for each input command file corresponding to cycle number / basin code pairs
        """

        print("")
        print("")
        print("[multiLakeAvgProcessing] PROCESSING...")
        print("")
        print("")

        timer_proc = my_timer.Timer()
        timer_proc.start()  # Init timer

        if not cmd_file:
            for indf, cmd_file in enumerate(self.cmd_file_path_list):
                print("")
                print("")
                print("***********************************************")
                print("***** Dealing with command file %d / %d *****" % (indf+1, len(self.cmd_file_path_list)))
                print("***********************************************")
                print("")
                print("")

                # 1 - Init
                my_lake_avg = pge_lake_avg.PGELakeAvg(cmd_file)

                # 2 - Run
                my_lake_avg.start()

                # 3 - Stop
                my_lake_avg.stop()

        else:
            print("")
            print("")
            print("***********************************************")
            print("***** Dealing with command file %s *****" % cmd_file)
            print("***********************************************")
            print("")
            print("")

            # 1 - Init
            my_lake_avg = pge_lake_avg.PGELakeAvg(cmd_file)

            # 2 - Run
            my_lake_avg.start()

            # 3 - Stop
            my_lake_avg.stop()

        print("")
        print("")
        print(timer_proc.stop())  # Print tile process duration
        print("")
        print("")

    def run_multiprocessing(self):
        """
        Multiprocess SAS_L2_HR_LakeAvg
        """
        n_cores = int(mp.cpu_count())
        pool = mp.Pool(n_cores)
        with pool:
            print('Running map')
            print("[multiLakeAvgProcessing] PROCESSING...")
            tmp_result = pool.map(self.run_processing, self.cmd_file_path_list)
            pool.close()
            pool.join()

#######################################

def read_command_file(in_filename):
    """
    Read the command file in input and store parameters in a dictionary

    :param in_filename: parameter file full path
    :type in_filename: string

    :return: out_params = dictionary containing parameters
    :rtype: dict
    """
    print("[multiLakeAvgProcessing] == read_command_file = %s ==" % in_filename)

    # 0 - Init output dictionary
    out_params = {}
    # Default values
    out_params["param_file"] = None
    out_params["LAKE_DB"] = None
    out_params["LAKE_DB_ID"] = None
    out_params["cycle_num"] = None
    out_params["basin_code"] = None
    out_params["flag_inc_file_counter"] = True
    out_params["flag_write_full_path"] = False
    out_params["nb_proc"] = 1
    out_params["errorFile"] = None
    out_params["logFile"] = None
    out_params["logfilelevel"] = "DEBUG"
    out_params["logConsole"] = True
    out_params["logconsolelevel"] = "DEBUG"
    out_params["institution"] = "CNES"
    out_params["product_version"] = "0.0"
    out_params["crid_lakesp"] = "Dx0000"
    out_params["crid_lakeavg"] = "Dx0000"
    out_params["pge_version"] = "0.0"
    out_params["contact"] = "test@cnes.fr"

    # 1 - Read parameter file
    config = cfg.ConfigParser()
    config.read(in_filename)

    # 2 - Retrieve PATHS
    list_paths = config.options("PATHS")
    if "param_file" in list_paths:
        out_params["param_file"] = config.get("PATHS", "param_file")
    out_params["lakesp_dir"] = config.get("PATHS", "LakeSP_Prior directory")
    out_params["output_dir"] = config.get("PATHS", "Output directory")

    # 3 - Retrieve DATABASES
    if "DATABASES" in config.sections():
        list_db = config.options("DATABASES")
        # Prior lake database
        if "lake_db" in list_db:
            out_params["LAKE_DB"] = config.get("DATABASES", "LAKE_DB")
        if "lake_db_id" in list_db:
            out_params["LAKE_DB_ID"] = config.get("DATABASES", "LAKE_DB_ID")

    # 4 - Retrieve PASS_INFOS
    if "PASS_INFOS" in config.sections():
        list_options = config.options("PASS_INFOS")
        # Cycle number
        if "cycle number" in list_options:
            out_params["cycle_num"] = config.getint("PASS_INFOS", "Cycle number")
        # Basin code
        if "basin code" in list_options:
            out_params["basin_code"] = config.getint("PASS_INFOS", "Basin code")

    # 5 - Retrieve OPTIONS
    if "OPTIONS" in config.sections():
        list_options = config.options("OPTIONS")
        # Flag to increment the file counter in the output filenames (=True, default); else=False
        if "increment file counter" in list_options:
            out_params["flag_inc_file_counter"] = config.get("OPTIONS", "Increment file counter")
        # To write full path in global attributes (=True); to write only basename=False (default)
        if "write full path" in list_options:
            out_params["flag_write_full_path"] = config.get("OPTIONS", "Write full path")
        # Number of processors to use (default=1)
        if "nb_proc" in list_options:
            out_params["nb_proc"] = config.get("OPTIONS", "Nb_proc")
        else:
            out_params["nb_proc"] = 1

    # 6 - Retrieve LOGGING
    if "LOGGING" in config.sections():
        list_options = config.options("LOGGING")
        if "errorFile" in list_options:
            out_params["errorFile"] = config.get("LOGGING", "errorFile")
            if out_params["errorFile"] is not None:
                out_params["errorFile"] = out_params["errorFile"].replace("<date>", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
        if "logFile" in list_options:
            out_params["logFile"] = config.get("LOGGING", "logFile")
            if out_params["logFile"] is not None:
                out_params["logFile"] = out_params["logFile"].replace("<date>", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
        if "logfilelevel" in list_options:
            out_params["logfilelevel"] = config.get("LOGGING", "logfilelevel")
        if "logConsole" in list_options:
            out_params["logConsole"] = config.get("LOGGING", "logConsole")
        if "logconsolelevel" in list_options:
            out_params["logconsolelevel"] = config.get("LOGGING", "logconsolelevel")

    # 7 - Retrieve FILE_INFORMATION
    if "FILE_INFORMATION" in config.sections():
        list_options = config.options("FILE_INFORMATION")
        if "institution" in list_options:
            out_params["institution"] = config.get("FILE_INFORMATION", "INSTITUTION")
        if "product_version" in list_options:
            out_params["product_version"] = config.get("FILE_INFORMATION", "PRODUCT_VERSION")
        if "crid_lakesp" in list_options:
            out_params["crid_lakesp"] = config.get("FILE_INFORMATION", "CRID_LAKESP")
        if "crid_lakeavg" in list_options:
            out_params["crid_lakeavg"] = config.get("FILE_INFORMATION", "CRID_LAKEAVG")
        if "pge_version" in list_options:
            out_params["pge_version"] = config.get("FILE_INFORMATION", "PGE_VERSION")
        if "contact" in list_options:
            out_params["contact"] = config.get("FILE_INFORMATION", "CONTACT")

    return out_params

#######################################

if __name__ == '__main__':

    # 0 - Parse inline parameters
    parser = argparse.ArgumentParser(description="Compute SWOT LakeAvg products from multiple LakeSP_Prior files.")
    parser.add_argument("command_file", help="command file (*.cfg)")
    parser.add_argument("-mp", "--multiproc", help="if true, CB basins will be computed in parallel", nargs='?', type=bool,
                        default=False, const=True)
    args = parser.parse_args()

    print("===== multiLakeAvgProcessing = BEGIN =====")
    print("")
    timer = my_timer.Timer()
    timer.start()

    # 1 - Read command file
    print("WORKING VARIABLES")
    print()
    my_tools.test_file(args.command_file, in_extent=".cfg")  # Test existance and extension
    my_params = read_command_file(args.command_file)  # Read variables in command file

    # 2 - Initialization
    multi_lake_avg = MultiLakeAvg(my_params)
    print(timer.info(0))

    # 3 - Run pre-processing
    multi_lake_avg.run_preprocessing()
    print(timer.info(0))

    # 4 - Run processing
    if args.multiproc:
        multi_lake_avg.run_multiprocessing()
    else:
        multi_lake_avg.run_processing()

    print(timer.info(0))

    print("")
    print(timer.stop())
    print("===== multiLakeAvgProcessing = END =====")


#pressing button or in case applying high voltage to any of this outputs can run its function
#this is a sound player that gives you ability to play, next, previus, stop, pause, unpause the sound.
#Only .wav files can be handeled
# we are supposed to use it to give surgery instructions.
import pygame.mixer
from time import sleep
import RPi.GPIO as GPIO
from sys import exit
import glob
import os
GPIO.setmode(GPIO.BCM)
#previous button
GPIO.setup(23, GPIO.IN)
#play button
GPIO.setup(24, GPIO.IN)
#next button
GPIO.setup(25, GPIO.IN)
#pause button
GPIO.setup(13, GPIO.IN)
#Unpause button
GPIO.setup(19, GPIO.IN)
#stop button
GPIO.setup(16, GPIO.IN)
#buzzer button
GPIO.setup(12, GPIO.IN)

pygame.mixer.init(48000, -16, 1, 1024)

soundChannelA = pygame.mixer.Channel(1)
soundChannelBuzzer = pygame.mixer.Channel(2)

dirname="/home/pi/Documents/sound_sample/"
print("Sampler Ready.")
pattern = '*.wav'
files = glob.glob(os.path.join(dirname, pattern))
files = sorted(files) # sort in alphabetical order
print(files)
count=0
#btnPlay = Button("Play", 23, __onPlayButtonChanged) # GPIO header pin 22
#btnPrevious = Button("Previous", 24, __onPreviousButtonChanged) # GPIO header pin 16
#btnNext = Button("Next", 25, __onNextButtonChanged) # GPIO header pin 18

input_pin = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(input_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def my_function_play(channel):
    global count
    if GPIO.input(24)==GPIO.HIGH:
        print("I was called Play!")

        print("count",count)
        if count>0 and count <len(files):
         print("index",count)
         soundChannelA.play(pygame.mixer.Sound(files[count]))
        else:
          count=0
          print("index",count)
          soundChannelA.play(pygame.mixer.Sound(files[count]))

input_pin = 24
GPIO.setmode(GPIO.BCM)
GPIO.setup(input_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def my_function_previous(channel):
    global count
    if GPIO.input(23)==GPIO.HIGH:
        global count
        print("I was called Previous!")
        print("count",count)
        if count>0:
                  count=count-1
        else:
                  count=0
        print("index",count)
        soundChannelA.play(pygame.mixer.Sound(files[count]))

input_pin = 25
GPIO.setmode(GPIO.BCM)
GPIO.setup(input_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def my_function_Next(channel):
    global count
    if GPIO.input(25)==GPIO.HIGH:

        print("I was called Next!")
        print("count",count)
        if count<len(files):
              count=count+1

        else:
              count=0
        print("index",count)
        soundChannelA.play(pygame.mixer.Sound(files[count]))

def paused(channel):
    if GPIO.input(13)==GPIO.HIGH:
        ############
        print("I was called pause!")
        pygame.mixer.pause()
        #############
def unpause(channel):
    if GPIO.input(19)==GPIO.HIGH:
        global pause
        print("I was called unpause!")
        #################
        pygame.mixer.unpause()
        #################
        #pause = False
def stoped(channel):
    if GPIO.input(16)==GPIO.HIGH:
        print("I was called stop!")
        global pause
        #################
        pygame.mixer.stop()
    #################
    #pause = False
GPIO.setup(21,GPIO.OUT)
def buzzer_play(channel):
        if GPIO.input(12)==GPIO.HIGH:
            print("I was called buzzer!")
            soundChannelBuzzer.play(pygame.mixer.Sound("/home/pi/Documents/sound_sample/Buzzer-Sound.wav"))
            GPIO.output(21,GPIO.HIGH)
        else:
            GPIO.output(21,GPIO.LOW)
GPIO.setmode(GPIO.BCM)
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setmode(GPIO.BCM)
GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#while True:
##    #GPIO.add_event_detect(12, GPIO.RISING, callback=lambda x:buzzer_play(count), bouncetime=2)
#GPIO.add_event_detect(23, GPIO.FALLING, callback=lambda x: my_function_previous(count), bouncetime=200)
#GPIO.add_event_detect(24, GPIO.FALLING, callback=lambda x:my_function_play(count), bouncetime=20)
#GPIO.add_event_detect(25, GPIO.FALLING, callback=lambda x:my_function_Next(count), bouncetime=200)
#GPIO.add_event_detect(13, GPIO.FALLING, callback=lambda x:paused(count), bouncetime=200)
#GPIO.add_event_detect(19, GPIO.FALLING, callback=lambda x:unpause(count), bouncetime=200)
#GPIO.add_event_detect(16, GPIO.FALLING, callback=lambda x:stoped(count), bouncetime=200)
##GPIO.add_event_detect(12, GPIO.FALLING, callback=lambda x:buzzer_play(count), bouncetime=200)
#GPIO.add_event_detect(12, GPIO.FALLING, callback=lambda x:buzzer_play(count), bouncetime=2)
#    if GPIO.input(23)==GPIO.HIGH:
GPIO.add_event_detect(23, GPIO.RISING, callback=lambda x: my_function_previous(count), bouncetime=200)

#        my_function_previous(count)

#    if GPIO.input(24)==GPIO.HIGH:
GPIO.add_event_detect(24, GPIO.RISING, callback=lambda x:my_function_play(count), bouncetime=20)

#    if GPIO.input(25)==GPIO.HIGH:
#        my_function_Next(count)
GPIO.add_event_detect(25, GPIO.RISING, callback=lambda x:my_function_Next(count), bouncetime=200)

#    if GPIO.input(13)==GPIO.HIGH:
GPIO.add_event_detect(13, GPIO.RISING, callback=lambda x:paused(count), bouncetime=200)

#    if GPIO.input(19)==GPIO.HIGH:
GPIO.add_event_detect(19, GPIO.RISING, callback=lambda x:unpause(count), bouncetime=200)

#    if GPIO.input(16)==GPIO.HIGH:
GPIO.add_event_detect(16, GPIO.RISING, callback=lambda x:stoped(count), bouncetime=200)

while True:

#    GPIO.add_event_detect(12, GPIO.FALLING, callback=lambda x:buzzer_play(count), bouncetime=2)
    if GPIO.input(12)==GPIO.HIGH:
        buzzer_play(12)
    else:
            GPIO.output(21,GPIO.LOW)

print("done")
    #while True:
#
#
#        #GPIO.cleanup()
##drill sound clip
##https://www.soundsnap.com/tags/drill
#
#


import sqlite3
import csv

conexion = sqlite3.connect('usuarios.db')
cursor = conexion.cursor()

archivo = open(r'/home/tomi/Python-/datos_db.txt', encoding = 'latin1')

filas = csv.reader(archivo)

#cursor.executemany('INSERT INTO estudiantes VALUES (?,?,?,?)', filas)

cursor.execute('SELECT * FROM estudiantes')
print(cursor.fetchall())

conexion.commit()
conexion.close()


import numpy as np
import matplotlib.pyplot as plt
import SVM_algorithm
def init_plot(X, Y):
    pos1 = np.argwhere(Y==1)
    pos2 = np.argwhere(Y==-1)
    data1 = X[pos1[:,0]]
    data2 = X[pos2[:,0]]
    plt.plot(data1[:,0], data1[:,1], 'ro', data2[:, 0], data2[:, 1], 'bs')
    plt.axis()
    plt.show()

def result_plot(w, b, alpha, X, Y, kernel, order, linesize=0.3):
    pos1 = np.argwhere(Y == 1)
    pos2 = np.argwhere(Y == -1)
    data1 = X[pos1[:, 0]]
    data2 = X[pos2[:, 0]]
    up0 = max(X[:,0]) *1.1
    low0 = min(X[:,0]) *1.1
    up1 = max(X[:, 1]) * 1.1
    low1 = min(X[:, 1]) * 1.1
    if kernel=='linear':
        x = np.arange(low0, up0, linesize)
        y = (-w[0, 0] * x - b) / w[0, 1]
        plt.plot(data1[:, 0], data1[:, 1], 'ro', data2[:, 0], data2[:, 1], 'bs', x, y, 'g--')
        plt.axis()
        plt.show()
    else:
        x1 = np.linspace(low0, up0, 300)
        x2 = np.linspace(low1, up1, 300)
        X_grid, Y_grid = np.meshgrid(x1, x2)
        vals = np.zeros_like(X_grid)
        for i in range(X_grid.shape[1]):
            this_X = np.vstack((X_grid[:, i], Y_grid[:, i]))
            this_X = this_X.T
            vals[:, i] = SVM_algorithm.predict(X, Y, this_X, w, b, alpha, kernel, order)
        plt.contour(X_grid, Y_grid, vals)
        plt.plot(data1[:, 0], data1[:, 1], 'ro')
        plt.plot(data2[:, 0], data2[:, 1], 'bs')
    plt.xticks(())
    plt.yticks(())
    plt.show()


from typing import List
import math

def memorized_matrix_chain(p: List) -> None:
    n = len(p)-1
    m = [[None]*n for i in range(n)]
    for i in range(n):
        for j in range(i, n):
            m[i][j] = math.inf
    return lookup_chain(m,p,1,n)

def lookup_chain(m,p,i,j):
    if m[i][j]<math.inf:
        return m[i][j]
    if i==j:
        m[i][j]=0
    else :
        NotImplemented


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('zones', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='RoutersModel',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('create_datetime', models.DateTimeField(auto_now_add=True)),
                ('update_datetime', models.DateTimeField(auto_now=True)),
                ('delete_datetime', models.DateTimeField(null=True, blank=True)),
                ('deleted', models.BooleanField(default=False)),
                ('router_id', models.CharField(unique=True, max_length=20)),
                ('uuid', models.CharField(max_length=60, null=True)),
                ('name', models.CharField(max_length=60)),
                ('enable_gateway', models.BooleanField(default=False)),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=django.db.models.deletion.PROTECT)),
                ('zone', models.ForeignKey(to='zones.ZoneModel', on_delete=django.db.models.deletion.PROTECT)),
            ],
            options={
                'db_table': 'routers',
            },
        ),
    ]


a,b = input().split()
a = int(a)
b= int(b)
s=input().split()
for i in range(a):
    s[i]=int(s[i])
    if s[i]<b:
        print(s[i],end=' ')


from account import Account
from transaction import Transaction
import csv

class ATM:
    def __init__(self):
        self.accounts = {}
        self.transactions = []
        self.load_accounts()

    def add_account(self, account):
        self.accounts[account.name] = account

    def remove_account(self, name):
        del self.accounts[name]

    def get_account(self, name):
        return self.accounts[name] if name in self.accounts else None

    def get_accounts(self, name=None):
        if name:
            return [self.get_account(name)]
        else:
            return list(self.accounts.values())

    def deposit(self, name, pin, amount):
        account = self.get_account(name)
        if account and account.check_pin(pin):
            account.deposit(amount)
            transaction = Transaction(name, amount, "deposited")
            self.transactions.append(transaction)
            self.save_accounts()
        else:
            print("Account not found or incorrect PIN")

    def withdraw(self, name, pin, amount):
        account = self.get_account(name)
        if not account:
            return "Account not found"
        elif not account.check_pin(pin):
            return "Invalid PIN"
        elif account.withdraw(amount, pin):
            account.balance -= amount
            transaction = Transaction(name, -amount, "withdrawn")
            self.transactions.append(transaction)
            self.save_accounts()
            return "Transaction successful"
        else:
            return "Insufficient balance"

    def check_balance(self, name, pin):
        account = self.get_account(name)
        if account and account.check_pin(pin):
            return account.check_balance()
        else:
            print("Account not found or incorrect PIN")

    def print_transactions(self):
        for transaction in self.transactions:
            print(f"{transaction.account_name}: {transaction.amount} "
                  f"({transaction.transaction_type}) on {transaction.timestamp}")

    def save_accounts(self):
        with open("database.csv", mode="w", newline="") as file:
            writer = csv.writer(file)
            for account in self.get_accounts():
                writer.writerow([account.name, account.pin, account.balance])

    def load_accounts(self):
        try:
            with open("database.csv") as file:
                reader = csv.DictReader(file)
                for row in reader:
                    if "balance" in row:
                        self.add_account(
                            Account(row["name"], int(row["pin"]),
                                    float(row["balance"])))
                    else:
                        self.add_account(Account(row["name"], row))
        except FileNotFoundError:
            print("File not found.")
        except ValueError:
            print("Error loading accounts from file.")

    def check_pin(self, name, pin):
        account = self.get_account(name)
        if account and account.check_pin(pin):
            return True
        else:
            return False


#!/usr/bin/python3
""" Day 5: Binary Boarding """
from aocd import get_data

def parse_input(puzzle_data):
    """ Return puzzle in structured data form """
    structured_puzzle = list()
    for line in puzzle_data.split("\n"):
        row = int(line[:7].replace("F", "0").replace("B", "1"), 2)
        column = int(line[7:].replace("L", "0").replace("R", "1"), 2)
        seat_id = row * 8 + column
        structured_puzzle.append(seat_id)
    return structured_puzzle

def highest_seat_id(seat_list):
    """ Find highest seat ID from binary form """
    highest_id = 0
    for seat_id in seat_list:
        if highest_id < seat_id:
            highest_id = seat_id

    return highest_id

def find_missing_id(seat_list):
    """ Find missing ID by looking for gap """
    highest_id = highest_seat_id(seat_list)
    print(highest_id)
    possible_id = list(set(range(1, highest_id)) - set(seat_list))
    for seat_id in possible_id:
        if seat_id - 1 not in seat_list:
            continue
        if seat_id + 1 not in seat_list:
            continue
        return seat_id

def main():
    """ Solve the puzzle """
    puzzle_input = parse_input(get_data(day=5))
    print(find_missing_id(puzzle_input))

if __name__ == "__main__":
    main()


# Entropy

def entropy(class_probabilities):
    """given a list of class probabilities, compute the entropy"""
    return sum(-p * math.log(p, 2)
               for p in class_probabilities
               if p) # ignore zero probabilities

def class_probabilities(labels):
    total_count = len(labels)
    return [count / total_count
            for count in Counter(labels).values()]

def data_entropy(labeled_data):
    labels = [label for _, label in labeled_data]
    probabilities = class_probabilities(labels)

    return entropy(probabilities)

# The entropy of a partition

def partition_entropy(subsets):
    """Find the entropy from this partition of data into subsets
    subsets is a list of labeled data"""
    total_count = sum(len(subset) for subset in subsets)

    return sum(data_entropy(subset) * len(subset) / total_count
               for subset in subsets)

inputs = [
    ({'level': 'Senior', 'lang': 'Java', 'tweets': 'no', 'phd': 'no'}, False),
    ({'level': 'Senior', 'lang': 'Java', 'tweets': 'no', 'phd': 'yes'}, False),
    ({'level': 'Mid', 'lang': 'Python', 'tweets': 'no', 'phd': 'no'}, True),
    ({'level': 'Junior', 'lang': 'Python', 'tweets': 'no', 'phd': 'no'}, True),
    ({'level': 'Junior', 'lang': 'R', 'tweets': 'yes', 'phd': 'no'}, True),
    ({'level': 'Junior', 'lang': 'R', 'tweets': 'yes', 'phd': 'yes'}, False),
    ({'level': 'Mid', 'lang': 'R', 'tweets': 'yes', 'phd': 'yes'}, True),
    ({'level': 'Senior', 'lang': 'Python', 'tweets': 'no', 'phd': 'no'}, False),
    ({'level': 'Senior', 'lang': 'R', 'tweets': 'yes', 'phd': 'no'}, True),
    ({'level': 'Junior', 'lang': 'Python', 'tweets': 'yes', 'phd': 'no'}, True),
    ({'level': 'Senior', 'lang': 'Python', 'tweets': 'yes', 'phd': 'yes'}, True),
    ({'level': 'Mid', 'lang': 'Python', 'tweets': 'no', 'phd': 'yes'}, True),
    ({'level': 'Mid', 'lang': 'Java', 'tweets': 'yes', 'phd': 'no'}, True),
    ({'level': 'Junior', 'lang': 'Python', 'tweets': 'no', 'phd': 'yes'}, False),
]


# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
from name_ui import *
from name_190105 import *

class MyForm(QtGui.QMainWindow):
  def __init__(self, parent=None):
    QtGui.QWidget.__init__(self, parent)
    self.ui = Ui_Form()
    self.ui.setupUi(self)

  def form_start(self):
    firstName = self.ui.lineEdit.text()

    try:
      firstName = int(firstName)
    except:
      QtGui.QMessageBox.question(
        self,
        u'확인',
        u"사용할 성의 한자 획수(숫자)를 입력해주세요",
        QtGui.QMessageBox.Ok
      )

    good_name_result = ""
    for i in suri_ohang(good_name(firstName)):
      # print("%02d + %02d + %02d = %02d" %(i[0],i[1],i[2],i[3]))
      good_name_result += "%02d + %02d + %02d = %02d\n" %(i[0],i[1],i[2],i[3])

    rich_name_result = ""
    for i in suri_ohang(rich_name(firstName)):
      # print("%02d + %02d + %02d = %02d" %(i[0],i[1],i[2],i[3]))
      rich_name_result += "%02d + %02d + %02d = %02d\n" %(i[0],i[1],i[2],i[3])

    self.ui.textEdit.setText(good_name_result)
    self.ui.textEdit_2.setText(rich_name_result)

    return

  def form_exit(self):
    QtCore.QCoreApplication.instance().quit()
    return

def main():
  app = QtGui.QApplication(sys.argv)
  myapp = MyForm()
  myapp.show()
  app.exec_()

if __name__=='__main__':
  main()


from math import *

class Ball:
    def __init__(self, x, y, size):
        self.x, self.y, self.size = x, y, size
        self.mass = 1
        self.vx, self.vy, self.fx, self.fy = 0, 0, 0, 0

    def apply_force(self, fx, fy):
        self.fx += fx
        self.fy += fy

    def draw(self, window):
        window.drawCircle(self.x, self.y, self.size, 0, 0, 0, 0.25)
        window.drawCircle(self.x, self.y, self.size - 2, 1.0, 0, 0, 0.75)

    def update(self, dt):
        # Compute acceleration using a = F / m (Newton's second law)
        accel_x = self.fx / self.mass
        accel_y = self.fy / self.mass

        # Update velocity with acceleration
        # NOTE : It is important that we do this *before* we updating position!
        #        Updating velocity *first* gives us significantly more accurate
        #        results!
        self.vx += dt * accel_x
        self.vy += dt * accel_y

        # Update position with velocity
        self.x += dt * self.vx
        self.y += dt * self.vy

        # Reset force accumulators
        self.fx = 0
        self.fy = 0

        # Check for collision with ground
        if self.y + self.size > 700:
            self.y = 700 - self.size
            self.vy *= -0.9

        # Check for collision with right side
        if self.x + self.size > 800:
            self.x = 800 - self.size
            self.vx *= -0.9

        # Check for collision with left side
        if self.x - self.size < 0:
            self.x = self.size
            self.vx *= -0.9


from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from EBA.models import Location_Restaurant, Restaurant_Food_New
from .forms import Location
from django.contrib.auth.forms import UserCreationForm
from .forms import UserForm,CustomerForm

# VIEW is the core of django, if there is no view, there will be no web page in django

#Taking input from user about what restaurants are all needed to show up
def get_location(request):
    if request.method == 'POST':
        form = Location(request.POST)
        loc = form['location'].value()

        if form.is_valid():
            # return redirect('rlist',{'location':loc})
            rd_url = reverse('rlist', kwargs={'loc': loc})
            print(rd_url)
            return HttpResponseRedirect(rd_url)
    else:
        form = Location()

    return render(request, 'location.html', {'form': form})

#Showing up restaurants based on the input given by user from FORM Location
def Restaurant_List(request, loc):
  RL = Location_Restaurant.objects.filter(Location=loc)
  return render(request,'res_list.html',{'rl':RL})

#After showing up location based restaurants, a particular restaurant was shown and food they are having will be shown up
def Food_List(request, r_id):
  FL = Restaurant_Food_New.objects.filter(Restaurant_Id__Restaurant_Id=r_id)
  return render(request,'food.html',{'fl':FL})

#User Details getting registered using this view
def register(request):
  if request.method == 'POST':
    user_form = UserForm(request.POST)
    customer_form = CustomerForm(request.POST)

    if user_form.is_valid() and customer_form.is_valid():
      user_form.save()
      customer_form.save()
      return redirect('location')

  else:
    user_form = UserForm()
    customer_form = CustomerForm()

  context = {
    'user_form': user_form,
    'customer_form': customer_form
  }

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


from flask import Flask, render_template, request
from bin.archive_downloader import download_archive
from bin.xml_reader import read_xml_file
from bin.create_year_data import create_raw_array
from bin.create_year_averages import yearly_average_constructor
from bin.sorting import *
from bin.generate_statistics import *
from dotenv import load_dotenv
import calendar, json, time, os, requests
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration

load_dotenv()

sentry_sdk.init(
    dsn="https://" + os.getenv("SENTRY_DSN_URL"),
    integrations=[FlaskIntegration()]
)

app = Flask(__name__)

@app.route('/')
def home():
   return render_template('input.html', key = os.getenv("GOOGLE_MAPS_API_KEY"))

@app.route('/results',methods = ['POST', 'GET'])
def result():
   start = time.time()
   months_abbr = []
   months_full = []
   essence_types = ['gazole', 'sp98', 'e10', 'e85', 'gplc']

   for i in range(1, 13):
      months_abbr.append(calendar.month_abbr[i])
      months_full.append(calendar.month_name[i])

   if request.method == 'POST':
      location = request.form['location']

      key = os.getenv("GOOGLE_MAPS_API_KEY")

      postcode_request_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + str(location) + "&key=" + key

      postcode_geosearch = requests.get(postcode_request_url)
      data = postcode_geosearch.json()

      postcode = [int(address["long_name"]) for address in data['results'][0]["address_components"] if "postal_code" in address["types"]][0]

      # files = download_archive(os.getenv("DATA_ARCHIVE_NAME"), os.getenv("S3_BUCKET_NAME"))

      xml_data = read_xml_file(os.getenv("PATH_TO_DATA") + os.getenv("DATA_ARCHIVE_NAME") + '.xml')

      raw_array = create_raw_array(xml_data, postcode, location, key)

      pumps_infos = build_pump_list_infos(raw_array)

      now_time = time.strftime('%d/%m/%Y @ %T')

      results_length = len(raw_array)
      essence_types_length = len(essence_types)

      avg_minimums_by_essence_type = avg_minimums(raw_array)
      average_by_essence_type = avg_by_essence_type(raw_array)
      average_by_essence_type_totalb = avg_by_essence_type_totalb(raw_array)
      sorted_by_essence_type = sort_by_essence_type(raw_array)
      sorted_by_essence_type_totalb = sort_by_essence_type_totalb(raw_array)
      totalb_average = get_total_monthly_average(raw_array)
      non_totalb_average = get_non_total_monthly_average(raw_array)
      getback = yearly_average_constructor(raw_array)

      del raw_array
      # getback_json = json.dumps(getback)

      end = time.time()
      process_time = end - start
      return render_template("results.html",
                             getback = getback,
                             months_abbr = months_abbr,
                             months_full = months_full,
                             pumps_infos = pumps_infos,
                             totalb_average = totalb_average,
                             non_totalb_average = non_totalb_average,
                             sorted_by_essence_type = sorted_by_essence_type,
                             sorted_by_essence_type_totalb = sorted_by_essence_type_totalb,
                             postcode = postcode,
                             time = now_time,
                             address = location,
                             results_length = results_length,
                             essence_types_length = essence_types_length,
                             essence_types = essence_types,
                             average_by_essence_type = average_by_essence_type,
                             average_by_essence_type_totalb = average_by_essence_type_totalb,
                             avg_minimums_by_essence_type = avg_minimums_by_essence_type,
                             process_time = process_time
                             )

if __name__ == '__main__':
   app.run(host='0.0.0.0', debug = True)


#In[]
'''
LeNet,上世纪80年代的产物,最初为了手写识别设计
'''

import torch
from torch import nn
from torch.nn.modules.loss import CrossEntropyLoss

from torch.utils import data
import torchvision
from torchvision import transforms

import Common_functions

'''
LeNet:
两个卷积层,两个池化层,三个线性层
假定为MNIST设计,输入为(batch_size,1,28,28)
'''
net = nn.Sequential(
    nn.Conv2d(in_channels=1,out_channels=6,kernel_size=(5,5),padding=2),nn.Sigmoid(), #输出:(6,28,28)
    nn.AvgPool2d(kernel_size=(2,2)), #不指定stride默认不重叠 输出(6,14,14)
    nn.Conv2d(6,16,kernel_size=(5,5)),nn.Sigmoid(),#输出(16,10,10)
    nn.AvgPool2d(kernel_size=(2,2)),#输出(16,5,5)
    nn.Flatten(),
    nn.Linear(16*5*5,120),nn.Sigmoid(),#
    nn.Linear(120,84),nn.Sigmoid(),
    nn.Linear(84,10)
)

#In[]

#加载数据
trans = transforms.ToTensor() #class,将PIL图片或numpy.ndarray格式转为tensor的类

mnist_train = torchvision.datasets.FashionMNIST('datasets/FashionMnist/',train=True,transform=trans,download=False)
mnist_test = torchvision.datasets.FashionMNIST('datasets/FashionMnist/',train=False,transform=trans,download=False)

batch_size = 256

train_iter = data.DataLoader(mnist_train,batch_size,shuffle=True)
test_iter = data.DataLoader(mnist_test,batch_size,shuffle=True)

#训练
if torch.cuda.is_available():
    device = "cuda:0"
else:
    device = "cpu"
device = torch.device(device)

Common_functions.train_device(net,train_iter,test_iter,lr=0.9,device=device)
# %%


import os
import subprocess
from tempfile import NamedTemporaryFile

from torch.distributed import get_rank
from torch.distributed import get_world_size
from torch.utils.data.sampler import Sampler
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import torch.nn as nn

import librosa
import numpy as np
import scipy.io.wavfile as wav
import torch
import torchaudio
import math

def get_spectrogram(wavs, audio_conf):
    window_size = audio_conf['window_size']
    sample_rate = audio_conf['sample_rate']
    window_stride = audio_conf['window_stride']
    n_fft = int(window_size * sample_rate)
    win_length = n_fft
    hop_length = int(sample_rate * window_stride)
    batch_size = len(wavs)
    spects = torch.zeros(batch_size,1,(1+n_fft/2),410) #what the hell is t????? okay I'm hardcoding it.
    for i in range(batch_size):
        wav = wavs[i]
        wav = wav.cpu().data
        wav = wav.numpy()
        spec_model = librosa.stft(wav, n_fft=n_fft, hop_length=hop_length, win_length=win_length)
        spect, phase = librosa.magphase(spec_model)
        spect = np.log1p(spect)
        spect = torch.FloatTensor(spect).cuda()
        mean = spect.mean()
        std = spect.std()
        spect = (spect - mean) / std
        spect = torch.unsqueeze(spect,0)
        #print('spect size:', spect.size())
        spects[i].copy_(spect)       #hello bug

    return spects

def _collate_fn(batch):
    batch_size = len(batch)
    audios = torch.zeros(batch_size,2**16)
    transcripts = []
    for i in range(batch_size):
        data = batch[i]
        audio = data[0]
        target = data[1]
        audios[i].copy_(audio)
        transcripts.extend(target)
    return audios, transcripts

class audioLoader(DataLoader):
    def __init__(self, *args, **kwargs):
        super(audioLoader,self).__init__(*args, **kwargs)
        self.collate_fn = _collate_fn

class audioDataset(Dataset):
    def __init__(self, filepath, audio_conf):
        self.path = filepath
        # if load timit dataset -> parse file first
        with open(self.path) as file:
            tokens = file.readlines()
        tokens = [x.strip().split(',') for x in tokens]
        self.tokens = tokens
        self.size = len(tokens)
        self.config = audio_conf
        super(audioDataset,self).__init__()

    def __getitem__(self, index):
        sample = self.tokens[index]
        audio_path, transcript_path = sample[0], sample[1]
        print('audio:' , audio_path, 'transcript:' , transcript_path)
        audio = self.get_audio(audio_path)
        audio = audio.unsqueeze(0)
        with open(transcript_path, 'r', encoding='utf8') as transcript_file:
            transcript = transcript_file.read().replace('\n', '')
        return audio, transcript

    def __len__(self):
        return self.size

    def get_audio(self, file_path):
        audio, sample_rate = torchaudio.load(file_path)
        audio = audio.squeeze()
        size = int(audio.size()[0])
        #print('original size: ', size)
        if size > 2**16:
            target = audio[:2**16]
        else:
            padding_left = (2**16 - size)//2
            padding_right = 2**16 - size - padding_left
            target = torch.zeros(2**16)
            target[padding_left:2**16-padding_right] = audio
        #pad = nn.ReplicationPad1d((padding_left,padding_right))
        #audio = pad(audio)
        #print('padded size: ', target.size())
        #audio = np.pad(audio, n_fft//2, mode='reflect')
        #audio = torch.from_numpy(audio)
        #audio = audio.unsqueeze(0)
        return Variable(target)


class Info:
    def __init__(self, first_name, last_name, address, age):
         self.first_name = first_name
         self.last_name = last_name
         self.address = address
         self.age = age

    def __repr__(self):
            return '({}, {}, {}, {})'.format(self.first_name, self.last_name, self.address, self.age)

infos = [
     Info("Mehadi", "Hasan", "Bogra", 28),
     Info("Mehadi", "Hasan", "Bogra", 25),
     Info("Kousar", "Rahman", "Dhaka", 30)
]

sorted_infos = sorted(infos, key = lambda i: (i.first_name, i.last_name, i.address, i.age))

print("Object sorted: ", sorted_infos)


#!/usr/bin/python

import sys
import re
import os
import ConfigParser

DEBUG=0

def log(msg):
    sys.stderr.write('backend (%s): %s\n' % (os.getpid(), msg))

def write(*l):
    args=len(l)
    c = 0
    for a in l:
        c += 1
        if DEBUG: log('writing: %s' % a)
        sys.stdout.write(a)
        if c < args:
            if DEBUG: log('writetab')
            sys.stdout.write('\t')
    if DEBUG: log('writenewline')
    sys.stdout.write('\n')
    sys.stdout.flush()

def get_next():
    if DEBUG: log('reading now')
    l = sys.stdin.readline()
    if DEBUG: log('read line: %s' % l)
    return l.strip().split('\t')

class DynamicBackend:
    def __init__(self):
        self.id = ''
        self.soa = ''
        self.domain = ''
        self.ip_address = ''
        self.ttl = ''
        self.name_servers = {}

    def configure(self):
        fname = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'backend.conf')
        if not os.path.exists(fname):
            log('%s does not exist' % fname)
            sys.exit(1)

        fp = open(fname)
        config = ConfigParser.ConfigParser()
        config.readfp(fp)
        fp.close()

        self.id = config.get('soa', 'id')
        self.soa = '%s %s %s' % (config.get('soa', 'ns'), config.get('soa','hostmaster'), self.id)
        self.domain = config.get('main', 'domain')
        self.ip_address = config.get('main', 'ipaddress')
        self.ttl = config.get('main', 'ttl')

        for entry in config.items('nameservers'):
            self.name_servers[entry[0]] = entry[1]

        log('Name servers: %s' % self.name_servers)
        log('ID: %s' % self.id)
        log('TTL %s' % self.ttl)
        log('SOA: %s' % self.soa)
        log('IP Address: %s' % self.ip_address)
        log('DOMAIN: %s' % self.domain)

    def run(self):
        log('starting up')
        handshake = get_next()
        if handshake[1] != '1':
            log('Not version 1: %s' % handshake)
            sys.exit(1)
        write('OK', 'We are good')
        log('Done handshake')

        while True:
            cmd = get_next()
            if DEBUG: log(cmd)

            if len(cmd) < 6:
                log('did not understand: %s' % cmd)
                write('FAIL')
                continue

            qname = cmd[1].lower()
            qtype = cmd[3]

            if (qtype == 'A' or qtype == 'ANY') and qname.endswith(self.domain):
                if qname == self.domain:
                    self.handle_self(self.domain)
                elif qname in self.name_servers:
                    self.handle_nameservers(qname)
                else:
                    self.handle_subdomains(qname)
            elif qtype == 'SOA' and qname.endswith(self.domain):
                self.handle_soa(qname)
            else:
                self.handle_unknown(qtype, qname)

    def handle_self(self, name):
        write('DATA', name, 'IN', 'A', self.ttl, self.id, self.ip_address)
        self.write_name_servers(name)
        write('END')

    def handle_subdomains(self, qname):
        subdomain = qname[0:qname.find(self.domain)-1]

        subparts = subdomain.split('.')
        if len(subparts) < 4:
            if DEBUG: log('subparts less than 4')
            self.handle_self(qname)
            return

        ipaddress = subparts[-4:]
        if DEBUG: log('ip: %s' % ipaddress)
        for part in ipaddress:
            if re.match('^\d{1,3}$', part) is None:
                if DEBUG: log('%s is not a number' % part)
                self.handle_self(qname)
                return
            parti = int(part)
            if parti < 0 or parti > 255:
                if DEBUG: log('%d is too big/small' % parti)
                self.handle_self(qname)
                return

        write('DATA', qname, 'IN', 'A', self.ttl, self.id, '%s.%s.%s.%s' % (ipaddress[0], ipaddress[1], ipaddress[2], ipaddress[3]))
        self.write_name_servers(qname)
        write('END')

    def handle_nameservers(self, qname):
        ip = self.name_servers[qname]
        write('DATA', qname, 'IN', 'A', self.ttl, self.id, ip)
        write('END')

    def write_name_servers(self, qname):
        for nameServer in self.name_servers:
            write('DATA', qname, 'IN', 'NS', self.ttl, self.id, nameServer)

    def handle_soa(self, qname):
        write('DATA', qname, 'IN', 'SOA', self.ttl, self.id, self.soa)
        write('END')

    def handle_unknown(self, qtype, qname):
        write('LOG', 'Unknown type: %s, domain: %s' % (qtype, qname))
        write('END')

if __name__ == '__main__':

    backend = DynamicBackend()
    backend.configure()
    backend.run()


from random import shuffle

def bogo_sort(array):
    a = False
    while not a:
        shuffle(array)
        i = 0
        a = all(array[i] <= array[i + 1] for i in range(len(array) - 1))
    return array


import datetime
from datetime import timedelta

import numpy as np

__author__ = "Marcelo Ferreira da Costa Gomes"
"""
Return Brazilian epidemiological week from passed date
"""

def extractweekday(x=datetime.datetime):
    # Extract weekday as [Sun-Sat] |-> [0-6]
    # isoweekday() returns weekday with [Mon-Sun] as [1-7]
    w = x.isoweekday() % 7
    return w

def firstepiday(year=int):
    day = datetime.datetime.strptime("%s-01-01" % year, "%Y-%m-%d")

    day_week = extractweekday(day)

    # Whe want day1 to correspond to the first day of the first epiweek.
    # That is, we need the Sunday corresponding to epiweek=%Y01
    # If first day of the year is between Sunday and Wednesday,
    # epiweek 01 includes it. Otherwise, it is still the last epiweek
    # of the previous year
    if day_week < 4:
        day = day - datetime.timedelta(days=day_week)
    else:
        day = day + datetime.timedelta(days=(7 - day_week))

    return day

def lastepiday(year=int):
    day = datetime.datetime.strptime("%s-12-31" % year, "%Y-%m-%d")

    day_week = extractweekday(day)

    # Whe want day to correspond to the last day of the last epiweek.
    # That is, we need the corresponding Saturday
    # If the last day of the year is between Sunday and Tuesday,
    # epiweek 01 of the next year includes it.
    # Otherwise, it is still the last epiweek of the current year
    if day_week < 3:
        day = day - datetime.timedelta(days=(day_week + 1))
    else:
        day = day + datetime.timedelta(days=(6 - day_week))

    return day

def episem(x, sep="W", out="YW"):

    """
    Return Brazilian corresponding epidemiological week from x.

    :param x: Input date. Can be a string in the format %Y-%m-%d or
      datetime.datetime
    :param sep: Year and week separator.
    :param out: Output format. 'YW' returns sep.join(epiyear,epiweek).
     'Y' returns epiyear only. 'W' returns epiweek only.
    :return: str
    """

    def out_format(year, week, out, sep="W"):
        if out == "YW":
            return "%s%s%02d" % (year, sep, week)
        if out == "Y":
            return "%s" % (year)
        if out == "W":
            return "%02d" % week

    if type(x) != datetime.datetime:
        if str(x) == "" or x is None or (type(x) != str and np.isnan(x)):
            return None
        x = datetime.datetime.strptime(x, "%Y-%m-%d")

    epiyear = x.year
    epiend = lastepiday(epiyear)

    if x > epiend:
        epiyear += 1
        return out_format(epiyear, 1, out, sep)

    epistart = firstepiday(epiyear)

    # If current date is before its year first epiweek,
    # then our base year is the previous one
    if x < epistart:
        epiyear -= 1
        epistart = firstepiday(epiyear)

    epiweek = int(((x - epistart) / 7).days) + 1

    return out_format(epiyear, epiweek, out, sep)

def episem2date(epi_year_week: str, weekday: int = 0):
    r"""
    Function to obtain first day of corresponding Brazilian epidemiological
    week provided

    Function \code{episem2date} uses the Brazilian definition of
    epidemiological
    week and returns the date of the corresponding o the provided epi. week,
    using week day requested. Uses Sunday as default, the first week day by
    Brazilian epi.
    week definition.
    @see https://github.com/marfcg/leos.opportunity.estimator/
        blob/master/R/episem2date.R

    @name episem2date
    @param epiyearweek Epidemiological week in the format "%Y\[*\]%W"
        where Y and W defined by the Brazilian epidemiological week system.
        The separator between Y and W is irrelevant. Ex.: 2014W02
    @param weekday Week day to be used as representative of the epi. week.
        Uses Date week day classification. 0: Sunday, 6:Saturday. Default: 0

    @return Date corresponding to the Sunday of epiyearweek
    @export

    @examples
    epiyearweek <- '2014W02'
    episem2date(epiyearweek)

    Test:

    dt = datetime.datetime.now()

    yw1 = int(episem(dt, sep=''))
    dt1 = episem2date(yw1)
    yw2 = int(episem(dt1, sep=''))

    assert yw1 == yw2

    :param epi_year_week:
    :param weekday:
    :return:
    """
    # force str format
    epi_year_week = str(epi_year_week)
    # Separate year and week:
    if len(epi_year_week) not in [6, 7]:
        raise Exception("Epi Year Week not valid.")

    epiyear = int(epi_year_week[:4])
    epiweek = int(epi_year_week[-2:])

    # Obtain sunday of first epiweek of epiyear
    # day.one
    date_1 = datetime.datetime.strptime("%s-01-01" % epiyear, "%Y-%m-%d")
    # day.one.week
    date_1_w = int(date_1.strftime("%w"))

    # Check wether week day of Jan 1st was before or after a Wednesday
    # and set the start of the epiyear accordingly
    epiweek_day_1 = (
        date_1 - timedelta(days=date_1_w)
        if date_1_w <= 3
        else date_1 + timedelta(days=7 - date_1_w)
    )
    return epiweek_day_1 + timedelta(days=7 * (epiweek - 1) + weekday)


# From my Fibonacci bash script, converted into Python.
smlFib = input('First number:')
bigFib = input('Second number:')
fibRep = input('Number of repeats:')

times = 1
repeat = int(fibRep) + 1

while times <= repeat:
    newFib = int(smlFib) + int(bigFib)
    smlFib = bigFib
    bigFib = newFib
    times = times + 1

print(smlFib, bigFib)


import numpy as np
import pickle
import os
import subprocess
import math

islets = pickle.load(open('far_unmatched_islets.p', 'rb'))

#Note: Perturb only cells in ad-graph from geom loops

is_sorted = lambda a: np.all(a[:-1] <= a[1:])

stochastic_dirr = 'stochastic'
if not os.path.isdir(stochastic_dirr):
    os.mkdir(stochastic_dirr)

thresh_dirr = 'Thresholds'
data_dirr = 'DevData/all_islets'

n_pert = 50

fcount = 0

for max_pert in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]:

    for fprefix in islets:

        print(fprefix)

        islet_dirr = stochastic_dirr + '/' + fprefix
        if not os.path.isdir(islet_dirr):
            os.mkdir(islet_dirr)

        ad_vert_PH_file = '../VerticesEdges/' + fprefix + '_advertices_PH.csv'
        b_vert_PH_file = '../VerticesEdges/' + fprefix + '_bvertices_PH.csv'

        ad_edge_file = '../VerticesEdges/' + fprefix + '_adedges_PH.csv'
        b_edge_file = '../VerticesEdges/' + fprefix + '_bedges_PH.csv'

        ad_verts = np.loadtxt(ad_vert_PH_file, delimiter=',')
        b_verts = np.loadtxt(b_vert_PH_file, delimiter=',')

        ad_edges = np.loadtxt(ad_edge_file, delimiter=',')
        b_edges = np.loadtxt(b_edge_file, delimiter=',')

        #####################################################################
        ## ad-mantles
        #####################################################################

        if ad_edges.shape[0] < 3:
            continue

        pert_dirr = islet_dirr + '/Perturbations_ad'
        if not os.path.isdir(pert_dirr):
            os.mkdir(pert_dirr)

        max_pert_dirr = pert_dirr + '/Perturbation'+str(max_pert)
        if not os.path.isdir(max_pert_dirr):
            os.mkdir(max_pert_dirr)

        # Perturb ad vertices
        n_pts = ad_verts.shape[0]

        # Cluster pts are not perturbed
        cluster_pts_file = '../VerticesEdges/' + fprefix + '_bvertices_PH.csv'

        for pert in range(n_pert):

            print(pert, end='\r')

            this_pert_dirr = max_pert_dirr + '/Perturbation' + str(pert)
            if not os.path.isdir(this_pert_dirr):
                os.mkdir(this_pert_dirr)

            this_rand_perts = np.random.uniform(size=(n_pts, 2))
            delta_x = this_rand_perts[:,0] * max_pert * np.cos(2*math.pi*this_rand_perts[:,1])
            delta_y = this_rand_perts[:,0] * max_pert * np.sin(2*math.pi*this_rand_perts[:,1])

            new_locs = np.copy(ad_verts)
            new_locs[:,0] += delta_x
            new_locs[:,1] += delta_y

            new_vert_file = this_pert_dirr + '/advertices_PH.csv'
            np.savetxt(new_vert_file, new_locs, delimiter=',', fmt='%.2f')

            new_edge_file = this_pert_dirr + '/adedges_PH.csv'

            new_edges = np.copy(ad_edges)
            if new_edges.ndim == 1:
                new_edges = np.reshape(new_edges, (1, 2))
            edge_lengths = np.zeros(new_edges.shape[0],)
            for idx, edge in enumerate(new_edges):
                v1, v2 = edge

                x1, y1 = new_locs[int(v1)]
                x2, y2 = new_locs[int(v2)]

                dist = (x1-x2)**2 + (y1-y2)**2

                edge_lengths[idx] = dist

            sort_idxs = np.argsort(edge_lengths)
            new_edges = new_edges[sort_idxs]

            # Save sorted edges
            np.savetxt(new_edge_file, new_edges, delimiter=',', fmt='%d')

            # Save triangles
            new_triangles_file = this_pert_dirr + '/adtriangles_PH.csv'

            loop_verts_file = new_vert_file
            loop_edges_file = new_edge_file
            cluster_pts_file = b_vert_PH_file

            subprocess.run(["../get_triangles.o"\
                            , loop_verts_file\
                            , loop_edges_file\
                            , cluster_pts_file\
                            , new_triangles_file\
                            ])

            #subprocess.run(["../get_triangles.o"\
            #                , loop_vertices\
            #                , loop_edges\
            #                , cluster_pts\
            #                , new_triangles_file\
            #                ])

            # Save undead
            pert_undead_file = this_pert_dirr + '/adundead_PH.csv'

            subprocess.run(["../get_undead.o"\
                        , loop_edges_file\
                        , new_triangles_file\
                        , pert_undead_file\
                        , cluster_pts_file\
                        , loop_verts_file\
                        ])


import os
import argparse
import warnings
import utils
import networks
from grad_cam import GradCAM
from plot_utils import apply_mask

def get_args():
    parser = argparse.ArgumentParser(
        prog="GradCAM on Chest X-Rays",
        description="Overlays given label's CAM on a given Chest X-Ray."
    )
    parser.add_argument(
        '-i', '--image-path', type=str, default='./assets/original.jpg',
        help='Path to chest X-Ray image.'
    )
    parser.add_argument(
        '-l', '--label', type=str, default=None,
        choices=['covid_19', 'lung_opacity', 'normal', 'pneumonia'],
        help='Choose from covid_19, lung_opacity, normal & pneumonia,\n'
        'to get the corresponding CAM.\n'
        'If not mentioned, the highest scoring label is considered.'
    )
    parser.add_argument(
        '-m', '--model', type=str, required=True,
        choices=['vgg16', 'resnet18', 'densenet121'],
        help='Choose from vgg16, resnet18 or densenet121.'
    )
    parser.add_argument(
        '-o', '--output-path', type=str, default='./outputs/output.jpg',
        help='Format: "<path> + <file_name> + .jpg"'
    )

    args = parser.parse_args()

    return args

if __name__ == '__main__':
    args = get_args()

    # get path of the pretrained model checkpoint
    path = {
        'vgg16': './models/lr3e-5_vgg_cuda.pth',
        'resnet18': './models/lr3e-5_resnet_cuda.pth',
        'densenet121': './models/lr3e-5_densenet_cuda.pth'
    }
    path = path[args.model]

    if not os.path.exists(path):
        raise Exception(
            f'{path} not found.\n'
            'Download the required model from the following link.\n'
            'https://drive.google.com/drive/folders/'
            '14L8wd-d2a3lvgqQtwV-y53Gsnn6Ud2-w'
        )

    # load the model using pretrained weights
    model = eval(
        f'networks.get_{args.model}(out_features=4, path="{path}")'
    ).cpu()

    # set target layer for CAM
    if args.model == 'vgg16' or args.model == 'densenet121':
        target_layer = model.features[-1]
    elif args.model == 'resnet18':
        target_layer = model.layer4[-1]

    # get given label's index
    label = {
        'covid_19': 0,
        'lung_opacity': 1,
        'normal': 2,
        'pneumonia': 3
    }
    idx_to_label = {v: k for k, v in label.items()}
    if args.label is not None:
        label = label[args.label]
    else:
        label = None

    # load and preprocess image
    image = utils.load_image(args.image_path)

    warnings.filterwarnings("ignore", category=UserWarning)
    # pass image through model and get CAM for the given label
    cam = GradCAM(model=model, target_layer=target_layer)
    label, mask = cam(image, label)
    print(f'GradCAM generated for label "{idx_to_label[label]}".')

    # deprocess image and overlay CAM
    image = utils.deprocess_image(image)
    image = apply_mask(image, mask)

    # save the image
    utils.save_image(image, args.output_path)