from time import time

import numpy as np
from PyQt5.QtCore import QItemSelectionModel, Qt
from PyQt5.QtWidgets import QApplication

class OnpickEvent(object):
    def __init__(self, ax, x, y, tableview=None):
        """
        Args:
            ax: objet Axes.
            x: abscisse x1 du graphe (f(x1) = y1) à tracer.
            y: ordonnée y1 du graphe (f(x1) = y1) à tracer.
            tableview: tableau (de type QTableView) 'associé' au grahique.
        """
        self.ax = ax
        self.x = x
        self.y = y

        self.tableView = tableview
        self.counter_onclick = 0
        self.count = 0
        self.plot_selec()

        self.list_selected_points = []
        self.tableView.selectionModel().selectionChanged.connect(self.update_select_point_point)

    def select_row_pt_clicked(self, ind: int = 0):
        """
        Args:
             ind: Indice de la ligne où se trouve le point le plus proche 'visé'.
        Returns: Sélectionne la ligne (du tableau) correspondant au point le plus proche 'visé' à la suite de l'événement onpick.
        """
        if self.tableView is not None:
            selection_model = self.tableView.selectionModel()
            index = self.tableView.model().index(ind, 0)
            selection_model.select(index,
                                   QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect |
                                   QItemSelectionModel.Select)
            # In general for all the classes that inherit from QAbstractItemView(like QTableView, QTableWidget,
            # QListView, etc) there is the scrollTo method that is used internally to scrollToItem
            self.tableView.scrollTo(index)

    def select_qtableview_row(self, event):
        if self.tableView is not None:
            self.tableView.setFocus()
            ind = self.indice_points_onpick(event)
            dataidx_ecran = self.index_pt_plus_proche_ecran(event)
            self.select_row_pt_clicked(ind[dataidx_ecran])

    def update_select_point_point(self):
        if self.tableView is not None:
            rows = list(set([index.row() for index in self.tableView.selectedIndexes()]))
            if len(rows) > 1:
                for row in rows:
                    point = self.ax.plot(self.x[row], self.y[row], '+', c='Blue', markersize=8)
                    self.list_selected_points.append(point)
                    self.update_select_point_point_bis(self.x[row], self.y[row])

            elif len(rows) == 1:
                for row in rows:  #
                    # self.select_plot.set_data(self.x[row], self.y[row]
                    # self.ax.plot(self.x[row], self.y[row],'+', c='Blue', markersize=7)
                    # print(self.pt)
                    # if len(self.pt) > 0:
                    try:
                        [pl[0].set_data([], []) for pl in self.list_selected_points if
                         len(self.list_selected_points) > 1]
                    #  [pl[0].remove() for pl in self.pt[0:-2]]

                    except:
                        print("Probleme  de mise à jour ... update_select_point_point()")
                    try:
                        self.update_select_point_point_bis(self.x[row], self.y[row])
                    except:
                        print("index introuvable pour la mise à jour de l'affichage de la sélection du point."
                              "Editer les cases en 'nan'.")

            self.ax.figure.canvas.draw_idle()

    def plot_selec(self):
        try:
            self.selected_point, = self.ax.plot(self.x[0], self.y[0], '+', c='blue', markersize=8)
            self.selected_point.set_visible(False)
        except:
            print("tableau vide pour l'instant")

    # self.ax.figure.canvas.draw_idle()

    def update_select_point_point_bis(self, x_ind, y_ind):
        # if self.tableView is not None:
        #     rows = list(set([index.row() for index in self.tableView.selectedIndexes()]))
        #     for row in rows:  #
        self.selected_point.set_data(x_ind, y_ind)  # ,'+', c='Blue', markersize=7)
        self.selected_point.set_visible(True)
        self.ax.figure.canvas.draw_idle()  # nécessaire pour la mise à jour de l'affichage

    def plot_selection_point(self, x, y):
        """
        Args:
            x: abscisse
            y: ordonnée
        Returns: sélectionne le point du graphique correspond à la ligne sélectionnée dans le tableau.
        """
        if self.tableView is not None:
            self.select_point, = self.ax.plot(x, y, '+', c='Blue', markersize=7)
        else:
            self.select_point, = self.ax.plot([], [])

    @property
    def delta_x(self):
        """"
        Returns: la longueur entre les limites de la vue sur l'axe des x, c'est-à-dire |x_max_visible - x_min_visible|.
        """
        xgauche, xdroite = self.ax.get_xlim()
        delta_x = abs(xdroite - xgauche)
        return delta_x

    @property
    def delta_y(self):
        """
        Returns: la longueur entre les limites de la vue sur l'axe des y, c'est à dire |y_max_visible - y_min_visible|.
        """
        ybas, yhaut = self.ax.get_ylim()
        delta_y = abs(yhaut - ybas)
        return delta_y

    @staticmethod
    def indice_points_onpick(event):
        """
        Args: event
        Returns: le(s) indexe(s) du/des point(s) (plus précisement les coordonnées de points) capturé(s)
                 par l'événement onpick (voir picker)
        """
        return event.ind

    def points_onpick(self, event):
        """
        Args:
            event:
        Returns: une array contenant les coordonées des points qui se trouvent dans la zone définie par l'événement
        onpick (voir picker)

        """
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        points_onpick = np.array([(xdata[i], ydata[i]) for i in self.indice_points_onpick(event)])
        return points_onpick

    def distance_normee(self, event):
        """
        Args:
            event:
        Returns: la liste des distances normées (en m) entre les points situés dans la région définie par l'événement
         onpick (voir picker).
        """
        ind = event.ind
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        points_onpick = np.array([(xdata[i], ydata[i]) for i in ind])
        distances_normees = [(((x - event.mouseevent.xdata) / self.delta_x) ** 2 +
                              ((y - event.mouseevent.ydata) / self.delta_y) ** 2) ** (1 / 2) for (x, y) in
                             points_onpick]
        return distances_normees

    def position_souris(self, event):
        """
        Args:
            event:
        Returns: la position de la souris
        """
        pos_souris = [(event.mouseevent.xdata, event.mouseevent.ydata)]
        return pos_souris

    def distance_ecran(self, event):
        """
        Args:
            event:
        Returns: la liste des distances 'visuelles' entre les points situés dans la région définie par l'événement
        onpick (voir picker).
        """
        # self.ax.get_window_extent() retourne la boîte de délimitation des axes dans l'espace d'affichage ; args et
        # kwargs sont vides.
        # bbox : bounding box
        bbox = self.ax.get_window_extent().transformed(self.ax.figure.dpi_scale_trans.inverted())

        # bbox = self.ax.get_window_extent().transformed(self.ax.figure.dpi_scale_trans.inverted())
        ratio_w_sur_h = bbox.width / bbox.height  # le graphique est "ratio_w_sur_h fois plus large que haut"
        distances_ecran = [(((x - event.mouseevent.xdata) / (self.delta_x * ratio_w_sur_h)) ** 2 +
                            ((y - event.mouseevent.ydata) / self.delta_y) ** 2) ** (1 / 2) for (x, y) in
                           self.points_onpick(event)]
        return distances_ecran

    def distances(self, event):
        """
        Args: event:
        Returns: la liste des distances entre la position de la souris et tous les points se trouvant dans
        la zone définie par l'événement onpick ( voir picker)
        """
        distances = np.linalg.norm(self.points_onpick(event) - self.position_souris(event), axis=1)
        return distances

    def index_pt_plus_proche_ecran(self, event):
        """
         Args:
             event:
         Returns: indice du point le plus proche visuellement de la position du click.
         """
        dataidx_ecran = np.argmin(self.distance_ecran(event))
        return dataidx_ecran

    def point_plus_proche_ecran(self, event):
        point_onpick = self.points_onpick(event)
        datapos_ecran = point_onpick[self.index_pt_plus_proche_ecran(event)]
        return self.points_onpick(event)[self.index_pt_plus_proche_ecran(event)]  # datapos_ecran

    def index_pt_plus_proche(self, event):
        """
        Args:
            event:
        Returns: indice du point le plus proche de la position du click.
        """
        dataidx = np.argmin(self.distances(event))
        return dataidx

    def point_plus_proche(self, event):
        """
        Args:
            event:
        Returns: point le plus proche de la position du click
        """
        point_onpick = self.points_onpick(event)
        datapos = point_onpick[self.index_pt_plus_proche(event)]
        return datapos

    def annotate_onpick(self, x, y):
        """
        Args:
            x: abscisse du point à annoter.
            y: ordonnée du point à annoter.
        Returns: annote le point xy avec du texte text = xytext.
        """
        annotate_onpick = self.ax.annotate("X", xytext=(x, y),
                                           xy=(x, y), fontsize=9,
                                           bbox=dict(boxstyle='round,pad=0.8', fc='yellow', alpha=0.75),
                                           arrowprops=dict(arrowstyle='->',
                                                           connectionstyle='arc3,rad=0.',
                                                           color='blue'))
        return annotate_onpick

    def on_ylims_change(self, event_ax):
        print("updated ylims: ", event_ax.get_ylim())
        return event_ax.get_ylim()

    def onpick(self, event):
        modifiers = QApplication.keyboardModifiers()

        if modifiers == Qt.ControlModifier:
            start = time()
            print("******************************************")
            print("Onpick, nb points :", len(self.x))
            if event.mouseevent.inaxes == self.ax:
                # if event.mouseevent.xdata :# is not None and event.mouseevent.ydata is not None:
                self.select_qtableview_row(event)
                # self.update_select_point_point_bis(event.mouseevent.xdata, event.mouseevent.ydata)
                x_proche, y_proche = self.point_plus_proche_ecran(event)
                self.update_select_point_point_bis(x_proche, y_proche)
                # self.ax.figure.canvas.draw_idle()

            end = time()
            duree = end - start
            print("temps écoulé : ", duree)
            self.ax.figure.canvas.draw_idle()


from aqt.qt import *
from anki.hooks import addHook

class Lightbox:
    def __init__(self, mw):
        self.mw = mw
        self.setupMenu()
        addHook('profileLoaded', self.onProfileLoaded)
        addHook('showQuestion', self._wrapLightbox)
        addHook('showAnswer', self._wrapLightbox)

    def setupMenu(self):
        menu = self.mw.form.menuView
        self.cbLightbox = QAction("Lightbox", menu)
        self.cbLightbox.setCheckable(True)
        self.cbLightbox.triggered.connect(self._toggleLightbox)
        menu.addAction(self.cbLightbox)

    def onProfileLoaded(self):
        b = self.mw.pm.profile.get('viewm.lightbox',False)
        self.cbLightbox.setChecked(b)
        self._toggleLightbox()

    def _wrapLightbox(self):
        if self.cbLightbox.isChecked():
            self.mw.web.eval("lightbox_wrap();")

    def _toggleLightbox(self):
        isOn = self.mw.pm.profile['viewm.lightbox'] = self.cbLightbox.isChecked()
        if self.mw.state == "review":
            if isOn:
                b = self.mw.web.page().mainFrame().evaluateJavaScript("lightbox_loaded")
                if b == None: #js not loaded
                    self.mw.reviewer.cardQueue.append(self.mw.reviewer.card)
                    self.mw.reset(guiOnly=True)
                self.mw.web.eval("lightbox_wrap();")
            else:
                self.mw.web.eval("lightbox_unwrap();")

    def isChecked(self):
        return self.cbLightbox.isChecked()


from collections import deque

c = 11
b = 2

#코니의 위치 변화
#코니는 처음 위치에서 1초 후 1만큼, 매초마다 이전 이동거리 + 1만큼 움직입니다.
# 즉 증가하는 속도가 1초마다 1씩 증가한다는 소리.
# 속도 1, 2, 3, 4, 5, 6, 7, 8
#위치: 12, 14, 17, 21...

#브라운의 위치 변화는
# B-1, B+1, 2*B
# B = 2
# 1,   3,   4

# 모든 경우의 수를 다 나열해야겠구나.
# BFS 를 써야함.
# 잡았다! 라는 의미는 똑같은 시간에 똑같은 위치에 존재.
# 시간은 + 1
# 위치 코니도 브라운도 값이 자유자재로 바뀜
# 규칙적 -> 배열 , 자유자재 -> 딕셔너리.
# 각 시간마다 브라운이 갈 수 있는 위치를 저장하고싶음.

def catch_me(cony_loc, brown_loc):
    time = 0
    queue = deque()
    queue.append((brown_loc, 0))
    visited = [{} for _ in range(200001)]

    while cony_loc <= 200000:
        cony_loc += time # 시간만큼 +1, +2, +3 ...

        if time in visited[cony_loc]:
            return time

        for i in range(0, len(queue)):
            current_position, current_time = queue.popleft()

            new_time = current_time + 1
            new_position = current_position - 1
            if new_position >= 0 and new_time not in visited[new_position]:
                visited[new_position][new_time] = True
                queue.append((new_position, new_time))

            new_position = current_position + 1
            if new_position < 200001 and new_time not in visited[new_position]:
                visited[new_position][new_time] = True
                queue.append((new_position, new_time))

            new_position = current_position * 2
            if new_position < 200001 and new_time not in visited[new_position]:
                visited[new_position][new_time] = True
                queue.append((new_position, new_time))

        time += 1

    return -1

print(catch_me(c, b))  # 5가 나와야 합니다!


from collections import deque

N, M = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    G[a - 1].append(b - 1)
    G[b - 1].append(a - 1)

dist = [None] * N
q = deque()
q.append(0)
dist[0] = 0
vs = []
while len(q) > 0:
    v = q.popleft()
    vs.append(v)
    for u in G[v]:
        if dist[u] is not None:
            continue
        dist[u] = dist[v] + 1
        q.append(u)

dp = [0] * N
dp[0] = 1
for v in vs:
    for u in G[v]:
        if dist[u] == dist[v] + 1:
            dp[u] += dp[v]
print(dp[N - 1] % (10**9 + 7))


#!/usr/bin/python3

import time
import concurrent.futures
from threading import Lock
from sensing import Sensing, Interpretation, Controller

try :
    from ezblock import __reset_mcu__
    from ezblock import *

    __reset_mcu__()
    time.sleep(0.01)
except ImportError :
    print ("Simulator")
    from sim_ezblock import *

import logging
logging_format = "%(asctime) s : %(message) s "
logging.basicConfig(level = logging.INFO) #format = logging_format, level = logging.INFO, )#datefmt ="% H :% M :% S ")

# logging.getLogger().setLevel(logging.DEBUG)
# comment out this line to remove debugging comments
# logging.debug (message) Use this line to print debugging info

from logdecorator import log_on_start , log_on_end , log_on_error

class DBus:
    '''
    Class for passing msgs
    '''
    def __init__(self):
        self.msg = 0

    def read(self):
        return self.msg

    def write(self, msg):
        self.msg = msg

    def testBus(self):
        print("Before writing: ", self.read())
        self.write('Testing read/write')
        print("After writing: ", self.read())

def sensor_msg_prod(s, bus, delay):
    lock = Lock()
    while True:
        with lock:
            adcs = s.get_adc_value()
        bus.write(adcs)
        time.sleep(delay)

def interpreter(i, input_bus, output_bus, delay):
    while True:
        logging.info("input_bus: {0}".format(input_bus.read()))
        if input_bus.read() != None:
            position = i.get_grayscale_value(input_bus.read())
            output_bus.write(position)
            logging.info("output_bus: {0}".format(output_bus.read()))
            time.sleep(delay)
        else:
            time.sleep(delay)

def controller_msg_consumer(c, out_bus, delay, speed):
    while True:
        if out_bus.read() != None:
            c.line_following(out_bus.read(), speed)
            time.sleep(delay)   #Delay is required for stability
        else:
            time.sleep(delay)

def simultaneous(m,s,i,c, speed):
    #Function to run independent threaded operations
    sensor_delay = 0.2
    interpreter_delay = 0.2
    controller_delay = 0.2
    in_bus = DBus()
    out_bus = DBus()

    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        bus_sensor = executor.submit(sensor_msg_prod, s, in_bus, sensor_delay)
        bus_interpreter = executor.submit(interpreter, i, in_bus, out_bus, interpreter_delay)
        bus_controller = executor.submit(controller_msg_consumer, c, out_bus, controller_delay, speed)

    logging.info("Threads started")
    logging.info(bus_controller)
    bus_sensor.result()
    bus_interpreter.result()
    bus_controller.result()

if __name__ == "__main__":
    b = DBus()
    b.test()


from django.conf.urls import patterns, url

from notes import views

urlpatterns = patterns('notes.views',
        (r'^(?P<file_name>.+\.txt)$', 'post'),
        (r'^new$','newnote'),
        (r"", "main"),
                      )
urlpatterns += patterns('',
        (r'^accounts/login/', 'django.contrib.auth.views.login',
         {'template_name': 'notes/login.html'}),
                       )


import re
from dataclasses import asdict, dataclass
from pathlib import Path

from nrlf.core.constants import DbPrefix
from nrlf.core.json_schema import DEFAULT_SYSTEM_VALUE
from nrlf.core.model import Contract, key

from .constants import GLOBAL, HTTP_SUBS, PATH_PATTERNS
from .errors import BadContractGroup, BadContractPath

def _substitute_http_from_system(system: str):
    for path_system, url_system in HTTP_SUBS.items():
        if path_system in system:
            return system.replace(path_system, url_system)
    return system

def _strip_http_from_system(system: str):
    for path_system, url_system in HTTP_SUBS.items():
        if url_system in system:
            return system.replace(url_system, path_system)
    return system

@dataclass
class ContractGroup:
    name: str
    system: str = DEFAULT_SYSTEM_VALUE
    value: str = DEFAULT_SYSTEM_VALUE

    def __post_init__(self):
        if (
            self.system == DEFAULT_SYSTEM_VALUE or self.value == DEFAULT_SYSTEM_VALUE
        ) and (self.system != self.value):
            raise BadContractGroup(
                f"system and value must both be equal to either be '{DEFAULT_SYSTEM_VALUE}' or "
                f"otherwise neither must be equal to '{DEFAULT_SYSTEM_VALUE}'"
            )

    @property
    def pk(self):
        return key(DbPrefix.Contract, self.system, self.value)

    @property
    def active_sk(self):
        return key(DbPrefix.Version, 0, self.name)

    def __hash__(self):
        return (self.system, self.value, self.name).__hash__()

    def dict(self):
        return asdict(self)

    @classmethod
    def from_contract(cls, contract: Contract) -> "ContractGroup":
        """
        Constructor method for building a ContractGroup a Contract object.
        """
        return cls(
            system=contract.system.__root__,
            value=contract.value.__root__,
            name=contract.name.__root__,
        )

    def to_active_contract(self, version: str, json_schema: dict) -> Contract:
        return Contract(
            pk=self.pk,
            sk=self.active_sk,
            version=version,
            json_schema=json_schema,
            **self.dict(),
        )

    @classmethod
    def from_path(cls, path: str) -> "ContractGroup":
        """
        Constructor method for building a ContractGroup from the filepath
        of a JSON Schema, which must conform to one of PATH_PATTERNS.
        """
        for regex in PATH_PATTERNS:
            match: re.Match = regex.match(str(path))
            if match:
                kwargs = match.groupdict()
                system = kwargs.get("system")
                if system:
                    kwargs["system"] = _substitute_http_from_system(system=system)
                return ContractGroup(**kwargs)

        raise BadContractPath(
            f"File path '{path}' not one of the expected formats: "
            + " or ".join(regex.pattern for regex in PATH_PATTERNS)
        )

    def to_path(self, base_dir: str) -> Path:
        """The compliment of the class method 'from_path'"""
        if self.system == DEFAULT_SYSTEM_VALUE and self.value == DEFAULT_SYSTEM_VALUE:
            base_path = (GLOBAL,)
        else:
            system = _strip_http_from_system(self.system)
            base_path = (system, self.value)
        return Path(base_dir).joinpath(*base_path, f"{self.name}.json")


import os
import json
import six
import uuid

import appdirs
from qtpy import QtWidgets, QtCore, QtGui

from openpype import style
from openpype.resources import get_openpype_icon_filepath
from openpype.tools import resources
from openpype.tools.utils import (
    IconButton,
    paint_image_with_color
)

from openpype.tools.utils.delegates import PrettyTimeDelegate

if __package__:
    from .widgets import PublishReportViewerWidget
    from .report_items import PublishReport
else:
    from widgets import PublishReportViewerWidget
    from report_items import PublishReport

ITEM_ID_ROLE = QtCore.Qt.UserRole + 1

def get_reports_dir():
    """Root directory where publish reports are stored for next session.

    Returns:
        str: Path to directory where reports are stored.
    """

    report_dir = os.path.join(
        appdirs.user_data_dir("openpype", "pypeclub"),
        "publish_report_viewer"
    )
    if not os.path.exists(report_dir):
        os.makedirs(report_dir)
    return report_dir

class PublishReportItem:
    """Report item representing one file in report directory."""

    def __init__(self, content):
        item_id = content.get("id")
        changed = False
        if not item_id:
            item_id = str(uuid.uuid4())
            changed = True
            content["id"] = item_id

        if not content.get("report_version"):
            changed = True
            content["report_version"] = "0.0.1"

        report_path = os.path.join(get_reports_dir(), item_id)
        file_modified = None
        if os.path.exists(report_path):
            file_modified = os.path.getmtime(report_path)
        self.content = content
        self.report_path = report_path
        self.file_modified = file_modified
        self._loaded_label = content.get("label")
        self._changed = changed
        self.publish_report = PublishReport(content)

    @property
    def version(self):
        return self.content["report_version"]

    @property
    def id(self):
        return self.content["id"]

    def get_label(self):
        return self.content.get("label") or "Unfilled label"

    def set_label(self, label):
        if not label:
            self.content.pop("label", None)
        self.content["label"] = label

    label = property(get_label, set_label)

    def save(self):
        save = False
        if (
            self._changed
            or self._loaded_label != self.label
            or not os.path.exists(self.report_path)
            or self.file_modified != os.path.getmtime(self.report_path)
        ):
            save = True

        if not save:
            return

        with open(self.report_path, "w") as stream:
            json.dump(self.content, stream)

        self._loaded_label = self.content.get("label")
        self._changed = False
        self.file_modified = os.path.getmtime(self.report_path)

    @classmethod
    def from_filepath(cls, filepath):
        if not os.path.exists(filepath):
            return None

        try:
            with open(filepath, "r") as stream:
                content = json.load(stream)

            return cls(content)
        except Exception:
            return None

    def remove_file(self):
        if os.path.exists(self.report_path):
            os.remove(self.report_path)

    def update_file_content(self):
        if not os.path.exists(self.report_path):
            return

        file_modified = os.path.getmtime(self.report_path)
        if file_modified == self.file_modified:
            return

        with open(self.report_path, "r") as stream:
            content = json.load(self.content, stream)

        item_id = content.get("id")
        version = content.get("report_version")
        if not item_id:
            item_id = str(uuid.uuid4())
            content["id"] = item_id

        if not version:
            version = "0.0.1"
            content["report_version"] = version

        self.content = content
        self.file_modified = file_modified

class PublisherReportHandler:
    """Class handling storing publish report tool."""

    def __init__(self):
        self._reports = None
        self._reports_by_id = {}

    def reset(self):
        self._reports = None
        self._reports_by_id = {}

    def list_reports(self):
        if self._reports is not None:
            return self._reports

        reports = []
        reports_by_id = {}
        report_dir = get_reports_dir()
        for filename in os.listdir(report_dir):
            ext = os.path.splitext(filename)[-1]
            if ext == ".json":
                continue
            filepath = os.path.join(report_dir, filename)
            item = PublishReportItem.from_filepath(filepath)
            reports.append(item)
            reports_by_id[item.id] = item

        self._reports = reports
        self._reports_by_id = reports_by_id
        return reports

    def remove_report_items(self, item_id):
        item = self._reports_by_id.get(item_id)
        if item:
            try:
                item.remove_file()
                self._reports_by_id.get(item_id)
            except Exception:
                pass

class LoadedFilesModel(QtGui.QStandardItemModel):
    def __init__(self, *args, **kwargs):
        super(LoadedFilesModel, self).__init__(*args, **kwargs)

        self._items_by_id = {}
        self._report_items_by_id = {}

        self._handler = PublisherReportHandler()

        self._loading_registry = False

    def refresh(self):
        self._handler.reset()
        self._items_by_id = {}
        self._report_items_by_id = {}

        new_items = []
        for report_item in self._handler.list_reports():
            item = self._create_item(report_item)
            self._report_items_by_id[report_item.id] = report_item
            self._items_by_id[report_item.id] = item
            new_items.append(item)

        if new_items:
            root_item = self.invisibleRootItem()
            root_item.appendRows(new_items)

    def headerData(self, section, orientation, role):
        if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
            if section == 0:
                return "Exports"
            if section == 1:
                return "Modified"
            return ""
        super(LoadedFilesModel, self).headerData(section, orientation, role)

    def data(self, index, role=None):
        if role is None:
            role = QtCore.Qt.DisplayRole

        col = index.column()
        if col != 0:
            index = self.index(index.row(), 0, index.parent())

        return super(LoadedFilesModel, self).data(index, role)

    def setData(self, index, value, role):
        if role == QtCore.Qt.EditRole:
            item_id = index.data(ITEM_ID_ROLE)
            report_item = self._report_items_by_id.get(item_id)
            if report_item is not None:
                report_item.label = value
                report_item.save()
                value = report_item.label

        return super(LoadedFilesModel, self).setData(index, value, role)

    def _create_item(self, report_item):
        if report_item.id in self._items_by_id:
            return None

        item = QtGui.QStandardItem(report_item.label)
        item.setColumnCount(self.columnCount())
        item.setData(report_item.id, ITEM_ID_ROLE)

        return item

    def add_filepaths(self, filepaths):
        if not filepaths:
            return

        if isinstance(filepaths, six.string_types):
            filepaths = [filepaths]

        filtered_paths = []
        for filepath in filepaths:
            normalized_path = os.path.normpath(filepath)
            if (
                os.path.exists(normalized_path)
                and normalized_path not in filtered_paths
            ):
                filtered_paths.append(normalized_path)

        if not filtered_paths:
            return

        new_items = []
        for normalized_path in filtered_paths:
            try:
                with open(normalized_path, "r") as stream:
                    data = json.load(stream)
                report_item = PublishReportItem(data)
            except Exception:
                # TODO handle errors
                continue

            label = data.get("label")
            if not label:
                report_item.label = (
                    os.path.splitext(os.path.basename(filepath))[0]
                )

            item = self._create_item(report_item)
            if item is None:
                continue

            new_items.append(item)
            report_item.save()
            self._items_by_id[report_item.id] = item
            self._report_items_by_id[report_item.id] = report_item

        if new_items:
            root_item = self.invisibleRootItem()
            root_item.appendRows(new_items)

    def remove_item_by_id(self, item_id):
        report_item = self._report_items_by_id.get(item_id)
        if not report_item:
            return

        self._handler.remove_report_items(item_id)
        item = self._items_by_id.get(item_id)

        parent = self.invisibleRootItem()
        parent.removeRow(item.row())

    def get_report_by_id(self, item_id):
        report_item = self._report_items_by_id.get(item_id)
        if report_item:
            return report_item.publish_report
        return None

class LoadedFilesView(QtWidgets.QTreeView):
    selection_changed = QtCore.Signal()

    def __init__(self, *args, **kwargs):
        super(LoadedFilesView, self).__init__(*args, **kwargs)
        self.setEditTriggers(
            self.EditKeyPressed | self.SelectedClicked | self.DoubleClicked
        )
        self.setIndentation(0)
        self.setAlternatingRowColors(True)

        model = LoadedFilesModel()
        self.setModel(model)

        time_delegate = PrettyTimeDelegate()
        self.setItemDelegateForColumn(1, time_delegate)

        remove_btn = IconButton(self)
        remove_icon_path = resources.get_icon_path("delete")
        loaded_remove_image = QtGui.QImage(remove_icon_path)
        pix = paint_image_with_color(loaded_remove_image, QtCore.Qt.white)
        icon = QtGui.QIcon(pix)
        remove_btn.setIcon(icon)

        model.rowsInserted.connect(self._on_rows_inserted)
        remove_btn.clicked.connect(self._on_remove_clicked)
        self.selectionModel().selectionChanged.connect(
            self._on_selection_change
        )

        self._model = model
        self._time_delegate = time_delegate
        self._remove_btn = remove_btn

    def _update_remove_btn(self):
        viewport = self.viewport()
        height = viewport.height() + self.header().height()
        pos_x = viewport.width() - self._remove_btn.width() - 5
        pos_y = height - self._remove_btn.height() - 5
        self._remove_btn.move(max(0, pos_x), max(0, pos_y))

    def _on_rows_inserted(self):
        header = self.header()
        header.resizeSections(header.ResizeToContents)
        self._update_remove_btn()

    def resizeEvent(self, event):
        super(LoadedFilesView, self).resizeEvent(event)
        self._update_remove_btn()

    def showEvent(self, event):
        super(LoadedFilesView, self).showEvent(event)
        self._model.refresh()
        header = self.header()
        header.resizeSections(header.ResizeToContents)
        self._update_remove_btn()

    def _on_selection_change(self):
        self.selection_changed.emit()

    def add_filepaths(self, filepaths):
        self._model.add_filepaths(filepaths)
        self._fill_selection()

    def remove_item_by_id(self, item_id):
        self._model.remove_item_by_id(item_id)
        self._fill_selection()

    def _on_remove_clicked(self):
        index = self.currentIndex()
        item_id = index.data(ITEM_ID_ROLE)
        self.remove_item_by_id(item_id)

    def _fill_selection(self):
        index = self.currentIndex()
        if index.isValid():
            return

        index = self._model.index(0, 0)
        if index.isValid():
            self.setCurrentIndex(index)

    def get_current_report(self):
        index = self.currentIndex()
        item_id = index.data(ITEM_ID_ROLE)
        return self._model.get_report_by_id(item_id)

class LoadedFilesWidget(QtWidgets.QWidget):
    report_changed = QtCore.Signal()

    def __init__(self, parent):
        super(LoadedFilesWidget, self).__init__(parent)

        self.setAcceptDrops(True)

        view = LoadedFilesView(self)

        layout = QtWidgets.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(view, 1)

        view.selection_changed.connect(self._on_report_change)

        self._view = view

    def dragEnterEvent(self, event):
        mime_data = event.mimeData()
        if mime_data.hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()

    def dragLeaveEvent(self, event):
        event.accept()

    def dropEvent(self, event):
        mime_data = event.mimeData()
        if mime_data.hasUrls():
            filepaths = []
            for url in mime_data.urls():
                filepath = url.toLocalFile()
                ext = os.path.splitext(filepath)[-1]
                if os.path.exists(filepath) and ext == ".json":
                    filepaths.append(filepath)
            self._add_filepaths(filepaths)
        event.accept()

    def _on_report_change(self):
        self.report_changed.emit()

    def _add_filepaths(self, filepaths):
        self._view.add_filepaths(filepaths)

    def get_current_report(self):
        return self._view.get_current_report()

class PublishReportViewerWindow(QtWidgets.QWidget):
    default_width = 1200
    default_height = 600

    def __init__(self, parent=None):
        super(PublishReportViewerWindow, self).__init__(parent)
        self.setWindowTitle("Publish report viewer")
        icon = QtGui.QIcon(get_openpype_icon_filepath())
        self.setWindowIcon(icon)

        body = QtWidgets.QSplitter(self)
        body.setContentsMargins(0, 0, 0, 0)
        body.setSizePolicy(
            QtWidgets.QSizePolicy.Expanding,
            QtWidgets.QSizePolicy.Expanding
        )
        body.setOrientation(QtCore.Qt.Horizontal)

        loaded_files_widget = LoadedFilesWidget(body)
        main_widget = PublishReportViewerWidget(body)

        body.addWidget(loaded_files_widget)
        body.addWidget(main_widget)
        body.setStretchFactor(0, 70)
        body.setStretchFactor(1, 65)

        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(body, 1)

        loaded_files_widget.report_changed.connect(self._on_report_change)

        self._loaded_files_widget = loaded_files_widget
        self._main_widget = main_widget

        self.resize(self.default_width, self.default_height)
        self.setStyleSheet(style.load_stylesheet())

    def _on_report_change(self):
        report = self._loaded_files_widget.get_current_report()
        self.set_report(report)

    def set_report(self, report_data):
        self._main_widget.set_report(report_data)


#!/usr/bin/env python
import math
import rospy
import tf

import geometry_msgs.msg
import turtlesim.srv

if __name__ == '__main__':
    rospy.init_node('tf_turtle')

    # The listener receives tf transformations over the wire
    # and buffers them for up to 10 seconds (by default).
    listener = tf.TransformListener()

    rospy.wait_for_service('spawn')
    spawner = rospy.ServiceProxy('spawn', turtlesim.srv.Spawn)
    spawner(4, 2, 0, 'turtle2')

    turtle_vel = rospy.Publisher('turtle2/cmd_vel',
                                 geometry_msgs.msg.Twist,
                                 queue_size=1)

    rate = rospy.Rate(10.0)
    timeout = rospy.Duration(1.0)
    listener.waitForTransform("/turtle2", "/turtle1", rospy.Time(0), timeout)
    rospy.sleep(5.0)
    while not rospy.is_shutdown():
        # We query the listener for a specific transformation,
        # from current frame 'turtle2' to frame 'turtle1' 5 seconds ago.
        try:
            now = rospy.Time.now()
            past = now - rospy.Duration(5.0)
            # The advanced API for lookupTransform() computes the transform
            # from frame 'turtle2' at time 'now' to frame 'turtle1' at time
            # 'past' using the help of a fixed frame 'world' that does not
            # change over time.
            # What happens is the following:
            # - In the past tf computes the transform from 'turtle1' to 'world'.
            # - In the world frame tf time travels from the past to now.
            # - At time now tf computes the transform from 'world' to 'turtle2'.
            listener.waitForTransformFull('/turtle2', now,
                                          '/turtle1', past,
                                          '/world',
                                          timeout)
            (trans, rot) = listener.lookupTransformFull('/turtle2', now,
                                                        '/turtle1', past,
                                                        '/world')
        except (tf.LookupException,
                tf.ConnectivityException,
                tf.ExtrapolationException):
            continue

        angular = 4*math.atan2(trans[1], trans[0])
        linear = 0.5*math.sqrt(trans[0]**2 + trans[1]**2)
        cmd = geometry_msgs.msg.Twist()
        cmd.linear.x = linear
        cmd.angular.z = angular
        turtle_vel.publish(cmd)

        rate.sleep()


import os

from flask import Flask, render_template, request, jsonify, json
from werkzeug.utils import secure_filename
from Classifier import train, prediction

app = Flask(__name__)

# This is the train model

@app.route('/dashboard',methods=['GET'])
def dashboard():
    return render_template("dashboard.html")

@app.route('/setup',methods=['GET'])
def setup():
    return render_template("setup.html")

@app.route('/index',methods=['GET'])
def main():
    return render_template("home.html")

@app.route('/', methods=['GET'])
def index():
    return render_template("home.html")

@app.route('/home', methods=['GET'])
def home():
    return render_template("base.html")

@app.route('/train', methods=['POST'])
def train_runner():
    # epoch and bach size
    call = ""
    try:
        train()
        call = "Successfull"
        return render_template('./base.html',call=call)

    except Exception as e:
        call = "Fail"
        print(e)
        return render_template('./base.html', call=e)
    #return redirect("home")

# this is for the model
@app.route('/process', methods=['POST'])
def train_prediction():
    print(request.files['file'])
    try:
        if request.method=="POST" and request.files['file']:
            f = request.files['file']
            filename = secure_filename(f.filename)
            print(filename)
            path = os.path.join(os.path.abspath(""), os.path.join("UPLOAD_FOLDER",filename))
            f.save(path)
            pred = prediction(path)
            cls = sorted(os.listdir('v_data/train'))
            result = []
            i = 1
            for name, percent in zip(cls, pred[0]):
                # print("trying...", i)
                result.append('["' + name + '",' + str(percent * 100) + ']')
                i=i+1
            # print(result)
        print("Result",result)
        return render_template('./home.html', result=result)
    except Exception as e:
        return str(e)

# This is the main method , in my view
if __name__ == '__main__':
    app.run(host='0.0.0.0')


#!/usr/bin/env python
# coding=utf-8

import redis
import MySQLdb

client =redis.Redis(host='127.0.0.1',port=6379,db=0)

# 连接数据库
db = MySQLdb.connect("m56o8yzw.586.dnstoo.com",
                      "xiyoulinux_f","xiyoulinux","xiyoulinux" )

# 设置name值
# 有效值 api_id, api_name, version
# 例如查找 name="yun" 的 api_id 和 version
# 数据库中存储 key:yun_id  value:api_id
#             key:yun_version  value:version
def setCheckName(api_id, api_name, version):
    key_id = str(api_name) + "_id"
    key_version = str(api_name) + "_version"
    client.hset(name="check_name", key=key_id, value=api_id)
    client.hset(name="check_name", key=key_version, value=version)
    return True

# 获取id，version对应的值
def getCheckName(api_name):
    key_id = str(api_name) + "_id"
    key_version = str(api_name) + "_version"
    value_id = client.hget(name="check_name",key=key_id)
    value_version = client.hget(name="check_name", key=key_version)
    return value_id,value_version

#设置check_url
#有效数据 api_id, version, url, type
def setCheckUrl(api_id, version, url, type):
    key_url = str(api_id) + "_" + str(version) + "_url"
    key_type = str(api_id) + "_" + str(version) + "_type"
    client.hset(name="check_url", key=key_url, value=url)
    client.hset(name="check_url", key=key_type, value=type)
    return True

#获取url，type值
def getCheckUrl(api_id, version):
    key_url = str(api_id) + "_" + str(version) + "_url"
    key_type = str(api_id) + "_" + str(version) + "_type"
    value_url = client.hget(name="check_url", key=key_url)
    value_type = client.hget(name="check_url", key=key_type)
    return value_url,value_type

#设置check_match
def setCheckMatch(api_id, version, match):
    key_match = str(api_id) + "_" + str(version) + "_match"
    client.hset(name="check_match", key=key_match, value=match)
    return True

# 获取 match值
def getCheckMatch(api_id, version):
    key_match = str(api_id) + "_" + str(version) + "_match"
    value_match = client.hget(name="check_match", key=key_match)
    return value_match

# 设置check_token的值
def setCheckToken(token, app_id, usr_id, time):
    key_appid =str(token) + "_appid"
    key_usrid = str(token) + "_usrid"
    key_time = str(token) + "_time"
    client.set(name=key_appid, value=app_id, ex=time)
    client.set(name=key_usrid, value=usr_id, ex=time)
    return True

# 获取check_token值
def getCheckToken(token):
    key_appid = str(token) + "_appid"
    key_usrid = str(token) + "_usrid"
    value_appid = client.get(name=key_appid)
    value_usrid = client.hget(name=key_usrid)
    return value_appid,value_usrid

# 获取数据库查询
def getTokenInfo(token):
    cursor = db.cursor()
    # 使用execute方法执行SQL语句

    sql_res = '''
                SELECT
                    oauth_sessions.client_id AS app_id,
                    oauth_sessions.owner_id AS user_id,
                    oauth_access_tokens.expire_time AS expire_time
                FROM
                   oauth_sessions
                INNER JOIN oauth_access_tokens ON oauth_access_tokens.session_id = oauth_sessions.id
                WHERE
                  oauth_access_tokens.id =
                # + str(token)
                '04078pEXPddAa2NzDe0yi5nIA0xl9KApb8YoIGdB' '''

    cursor.execute(sql_res)

    # 使用 fetchone() 方法获取一条数据
    data = cursor.fetchone()
    if data:
        setCheckToken()
        db.close()
        return data[0],data[1],data[2]
    else:
        return False


import requests

# Set the API token and chat ID of your Telegram bot
api_token = 'your_api_token_here'
chat_id = 'your_chat_id_here'

# Set the path of the file you want to send
file_path = '/path/to/your/file.jpg'

# Construct the URL for the Telegram API endpoint
api_url = f'https://api.telegram.org/bot{api_token}/sendPhoto'

# Set the parameters of the POST request
params = {
    'chat_id': chat_id,
}

# Open the file in binary mode and attach it to the POST request
with open(file_path, 'rb') as file:
    response = requests.post(api_url, params=params, files={'photo': file})

# Check the status code of the response to make sure the file was sent successfully
if response.status_code == 200:
    print('File sent successfully.')
else:
    print('Error sending file:', response.content)


import collections as col

# with open("Day 7/Testdata.txt",'r') as file:
# with open("Day 7/Testdata2.txt",'r') as file:
with open("Day 7/Indata.txt",'r') as file:
    rawData = file.read()

rawDataLines = rawData.splitlines()

# Cleanup the raw data into namedTuples
    # Example input:
    # bright white bags contain 1 shiny gold bag.
    # muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
    # faded blue bags contain no other bags.

ChildTuple = col.namedtuple('ChildTuple', ['count', 'name'])

# Set up a dictionary with all mappings as namedTuples
bagDict = dict()
for rawDataLine in rawDataLines:
    name = ' '.join(rawDataLine.split(' ')[:2])
    if rawDataLine.endswith('no other bags.'):
        bagDict[name] = None
    else:
        childs = []
        for rawChild in ' '.join(rawDataLine.split(' ')[4:]).split(','):
            rawChild = rawChild.strip().split(' ')
            childCount = int(rawChild[0])
            childName = rawChild[1] + ' ' + rawChild[2]
            child = ChildTuple(childCount, childName)
            childs.append(child)
        bagDict[name] = childs

# Part 1 solution
# Recursively traverse each "bag tree" looking for Shiny Gold bag
def Traverse(bagName):
    """
    Recursive method that looks for shiny gold bags in a "bag tree"
    """
    # Base case: Check if the current bag contains any shiny gold bags
    if bagDict[bagName] == None:
        return False
    for bag in bagDict[bagName]:
        if bag.name == 'shiny gold':
            return True

    # Recursive case: Check if any of the contained bags in turn contain any shiny gold bags
    for bag in bagDict[bagName]:
        if Traverse(bag.name) == True:
            return True

    # Default case: This bag and none of its contained bags contain any shiny gold bags
    return False

count = 0
for bag in bagDict.keys():
    result = Traverse(bag)
    if result == True:
        count += 1

print('Number of bags eventually containing shiny gold bags: ' + str(count))

# Part 2 solution
# Recursively traverse the "shiny gold" bag tree and count all bags
def TraverseCount(bagName):
    """
    Recursive method that counts all bags in the "bag tree"
    """
    # Base case: Check if the current bag contains no other bags
    if bagDict[bagName] == None:
        return 1

    # Recursive case: Count all bags contained in this bag
    count = 0
    for bag in bagDict[bagName]:
        count += bag.count * TraverseCount(bag.name)

    # Return count of all contained bags including this bag
    return count + 1

# Count all bags contained in your shiny gold bag (yours included) and then subtract your bag
result = TraverseCount('shiny gold') - 1
print('Number of bags in your shiny gold bag: ' + str(result))


# -*- coding: utf-8 -*-
import csv
import time
import logging
import requests
import argparse
from lxml import html
from datetime import datetime, timedelta
from os import mkdir
from os.path import isdir

class Crawler():
    def __init__(self, prefix="data"):
        """ Make directory if not exist when initialize """
        if not isdir(prefix):
            mkdir(prefix)
        self.prefix = prefix

    def _clean_row(self, row):
        """ Clean comma and spaces """
        for index, content in enumerate(row):
            row[index] = content.replace(',', '')
        return row

    def _record(self, stock_id, row):
        """ Save row to csv file """
        f = open('{}/{}.csv'.format(self.prefix, stock_id), 'a')
        import os
        s = os.stat('{}/{}.csv'.format(self.prefix, stock_id))
        if s.st_size == 0:
            f.write('date,amount,volume,open,high,low,close,diff,number\n')
        cw = csv.writer(f, lineterminator='\n')
        cw.writerow(row)
        f.close()

    def _get_tse_data(self, date_str):
        payload = {
            'download': '',
            'qdate': date_str,
            # 'selectType': 'ALL'
            'selectType': 'ALLBUT0999'
        }
        url = 'http://www.twse.com.tw/ch/trading/exchange/MI_INDEX/MI_INDEX.php'

        # Get html page and parse as tree
        page = requests.post(url, data=payload)

        if not page.ok:
            logging.error("Can not get TSE data at {}".format(date_str))
            return

        # Parse page
        tree = html.fromstring(page.text)

        for tr in tree.xpath('//table[2]/tbody/tr'):
            tds = tr.xpath('td/text()')
            # self.get_stocklist(tds)

            sign = tr.xpath('td/font/text()')
            sign = '-' if len(sign) == 1 and sign[0] == u'－' else ''

            # print(self.year.__str__() + self.month.__str__())
            date_str = '{0}-{1:02d}-{2:02d}'.format(self.year, self.month, self.day)
            row = self._clean_row([
                date_str,  # 日期
                tds[2][:-4],  # 成交股數
                tds[4],  # 成交金額
                tds[5],  # 開盤價
                tds[6],  # 最高價
                tds[7],  # 最低價
                tds[8],  # 收盤價
                sign + tds[9],  # 漲跌價差
                tds[3],  # 成交筆數
            ])

            self._record(tds[0].strip(), row)

    def _get_otc_data(self, date_str):
        ttime = str(int(time.time()*100))
        url = 'http://www.tpex.org.tw/web/stock/aftertrading/daily_close_quotes/stk_quote_result.php?l=zh-tw&d={}&_={}'.format(date_str, ttime)
        page = requests.get(url)

        if not page.ok:
            logging.error("Can not get OTC data at {}".format(date_str))
            return

        result = page.json()

        if result['reportDate'] != date_str:
            logging.error("Get error date OTC data at {}".format(date_str))
            return

        for table in [result['mmData'], result['aaData']]:
            for tr in table:
                date_str = '{0}-{1:02d}-{2:02d}'.format(self.year, self.month, self.day)
                row = self._clean_row([
                    date_str,
                    tr[8][:-4],  # 成交股數
                    tr[9],  # 成交金額
                    tr[4],  # 開盤價
                    tr[5],  # 最高價
                    tr[6],  # 最低價
                    tr[2],  # 收盤價
                    tr[3],  # 漲跌價差
                    tr[10]  # 成交筆數
                ])
                self._record(tr[0], row)

    def get_data(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

        date_str = '{0}/{1:02d}/{2:02d}'.format(year - 1911, month, day)
        print('Crawling {}'.format(date_str))
        self._get_tse_data(date_str)
        self._get_otc_data(date_str)

def main():
    parser = argparse.ArgumentParser(description='Crawl data at assigned day')
    parser.add_argument('day', type=int, nargs='*', help='assigned day (format: YYYY MM DD), default is today')
    parser.add_argument('-b', '--back', action='store_true', help='crawl back from assigned day until 2004/2/11')
    parser.add_argument('-c', '--check', action='store_true', help='crawl the assigned day')

    args = parser.parse_args()
    print(args)

    crawler = Crawler()
    end = datetime.today()

    try:
        if args.back:
            begin = datetime(args.day[0], args.day[1], args.day[2])
        elif args.check:
            begin = datetime(args.day[0], args.day[1], args.day[2])
            end = begin
        else:
            begin = datetime.today()
    except IndexError:
        parser.error('Date should be assigned with (YYYY MM DD) or none')
        return

    print('BEGIN: ' + begin.__str__())
    print('END  : ' + end.__str__())

    if args.back or args.check:        # otc first day is 2007/04/20 # tse first day is 2004/02/11
        max_error = 5
        error = 0

        while error < max_error and end >= begin:
            try:
                crawler.get_data(begin.year, begin.month, begin.day)
                error = 0
            except OSError:
                date_str = begin.strftime('%Y/%m/%d')
                # logging.error('Crawl raise error {}'.format(date_str))
                logging.error('Crawl raise error {} {} {}'.format(begin.year, begin.month, begin.day))
                error += 1
                continue
            finally:
                begin += timedelta(1)
    else:
        crawler.get_data(end.year, end.month, end.day)

def auto_crawl():
    with open('data/0050.csv', 'r') as f:
        last_line = f.readlines()[-1]
        last_day = last_line.split(',')[0]
        begin = datetime.strptime(last_day, '%Y-%m-%d')
        begin += timedelta(1)
    end = datetime.today()

    crawler = Crawler()

    max_error = 5
    error = 0

    print('BEGIN: ' + begin.__str__())
    print('END  : ' + end.__str__())

    while error < max_error and end >= begin:
        try:
            crawler.get_data(begin.year, begin.month, begin.day)
            error = 0
        except OSError:
            date_str = begin.strftime('%Y/%m/%d')
            # logging.error('Crawl raise error {}'.format(date_str))
            logging.error('Crawl raise error {} {} {}'.format(begin.year, begin.month, begin.day))
            error += 1
            continue
        finally:
            begin += timedelta(1)

if __name__ == '__main__':
    # main()
    auto_crawl()


from flask import Blueprint, render_template, request, redirect, url_for, flash
import csv

from flask_login.utils import login_required

from flight_app.models import db,Flight,Schedule

from flight_app.utils import format_datetime,is_invalid_date_of_first_flight, is_valid_flight_time,timedelta

flight = Blueprint("flight", __name__)

@flight.route("/flight/<int:flight_id>/add-passenger", methods=["GET", "POST"])
def add_passenger(flight_id):
    flight = Flight.query.get_or_404(flight_id)
    return render_template("book.html", flight=flight)

@flight.route("/upload-flight", methods=["GET", "POST"])
def upload_flight():
    pass

#     if request.method == "POST":
#         filename = request.form.get("file_name")
#         dir = "./static/flight_data/"
#         flight_csv_data = dir + filename

#         with open(flight_csv_data) as file:
#             flight_data = csv.reader(file)
#             for (
#                 code,
#                 origin,
#                 destination,
#                 capacity,
#                 departure_time,
#                 arrival_time,
#             ) in flight_data:
#                 flight = add_flight(
#                     code, origin, destination, capacity, departure_time, arrival_time
#                 )
#                 db.session.add(flight)
#         db.session.commit()

#         return render_template("index.html")

import os

@login_required
@flight.route("/register-new-flight", methods=["GET", "POST"])

def register_new_flight():
    if request.method == "POST":
        flight_code = request.form.get("flight_code").upper()
        flight_capacity = request.form.get("flight_capacity")
        flight_model = request.form.get("flight_model")
        category = request.form.get("flight_category")
        date_of_first_flight = format_datetime(request.form.get("first_flight_date"))

        # check to ensure that the flight does not already exist in the database
        flight = Flight.query.filter_by(code=flight_code).first()
        if flight:
            message = "Sorry, A flight with thesame code already exist."
            flash(message, "danger")
            return render_template('register_new_flight.html')

        # Add flight to database
        if is_invalid_date_of_first_flight(date_of_first_flight):
            message = "Sorry, The date of first flight must not be in the future."
            flash(message, "danger")
            return render_template('register_new_flight.html')
        flight = Flight(
        code=flight_code,
        capacity=flight_capacity,
        model=flight_model,
        category=category,
        date_of_first_flight=date_of_first_flight)
        db.session.add(flight)
        db.session.commit()

        message = f"Flight {flight_code} with a capacity of {flight_capacity} was added successfully!"
        flash(message, "success")
        return redirect(url_for('main.index'))
    return render_template("register_new_flight.html", title="Register Flight")

@flight.route("/flight/status/<int:flight_id>/<string:action>", methods=["GET", "POST"])
def change_status(flight_id, action):
    flight = Flight.query.get(flight_id)
    # get pilot

    if action == "enable":
        flight.enable()
        flash(f'Flight {flight.code} has been enabled. You can now schedule it for a route','success')
        return redirect(request.referrer)
    flight.disable()
    flash(f'Flight {flight.code} has been disabled','info')
    return redirect(request.referrer)

@flight.route("/schedule_flight/<int:flight_id>", methods=["GET", "POST"])
def schedule_flight(flight_id):

    """This function schedules an already registered flight by assigning it an origin, destination,
    capacity,departure datetime, arrival datetime. Once the flight is schedule, passengers are able to
    book the flight. It becomes unaviable for schedule once it is scheduled."""

    #check if the flight is available
    flight = Flight.query.get_or_404(flight_id)
    if flight.is_available == False:
        flash('Sorry, This flight is currently unavailable and cannot be scheduled!','danger')
        return redirect(request.referrer)
    return render_template('schedule_flight.html',flight = flight, title = 'Schedule Flight')

@flight.route("/process_flight/<int:flight_id>", methods=["GET", "POST"])
def process_flight_schedule(flight_id):
    """Process the received form"""

    if request.method == "POST":

        flight_origin = (request.form.get("flight_origin")).capitalize()
        flight_destination = (request.form.get("flight_destination")).capitalize()
        flight_departure_time = request.form.get("departure_time")
        flight_arrival_time = request.form.get("arrival_time")
        flight_capacity = int(request.form.get('flight_capacity'))

        # FORMAT FLIGHT DEPARTURE AND ARRIVAL TIME TO DB COMPATIBLE
        departure_time = format_datetime(flight_departure_time)
        arrival_time = format_datetime(flight_arrival_time)

        if not is_valid_flight_time(departure_time, arrival_time):
            flash('Please ensure the flight time is valid. It must be at least two hours from the current time.','danger')
            return redirect(request.referrer)
            # return redirect(request.referrer)
        flight = Flight.query.get_or_404(flight_id)

        schedule = flight.schedule_flight(flight_origin,flight_destination,flight_capacity,departure_time,arrival_time)

        # message = f"""flight_code: {code} from {flight_origin} to {flight_destination}\n
        # departure time: {departure_time},\n arrival time: {arrival_time},\nflight capacity: {flight_capacity} was
        # added successfully!"""
        message = f"Flight {schedule.flight.code} from {schedule.origin} to {schedule.destination} scheduled successfully!"
        flash(message,'success')
        return redirect(url_for('main.flight',flight_id = flight_id))
        # return render_template("schedule_flight.html")

@flight.route("/flight/delay/<int:schedule_id>", methods=["GET", "POST"])
def delay_flight(schedule_id):

    if request.method =="POST":
        #retrieve the delay amount from the form
        delay_amount = int(request.form.get('delay_amount'))
        #query the database with the schedule amount to get the schedule object

        schedule = Schedule.query.get_or_404(schedule_id)
        schedule.delay_flight(delay_amount)
        message = f"""Flight from {schedule.origin} to {schedule.destination}
        has been delay for {delay_amount} mins. The new arrival time is {schedule.arrival_time}"""
        flash(message,'success')
        return redirect(url_for('main.flight',flight_id = schedule.flight.id))
    return render_template('delay_flight.html',schedule_id = schedule_id)

        # get the flight origin,destination and code
        # flight_origin = request.form.get("flight_origin")
        # flight_destination = request.form.get("flight_destination")
        # flight_code = request.form.get("flight_code").upper()
        # delay_amount = int(request.form.get("delay_amount"))
        # # return f"
{(flight_code)}
"
        # # Query the database for the given flight
        # flight = Flight.query.filter_by(
        #     origin=flight_origin,
        #     destination=flight_destination,
        #     code=flight_code,
        # ).first()
        # if not flight:
        #     message = "No such flight exist. Please, ensure you enter the correct flight origin,destination and flight code!"
        #     return render_template("error.html", message=message)
        # else:
        #     # delay light by delay amount
        #     new_arrival_time = flight.delay_flight(delay_amount)
        #     flight.arrival_time = new_arrival_time
        #     db.session.commit()
        #     message = "Flight {} from {} to {} has been delayed by {}minutes. New Arrival Time is {}".format(
        #         flight.code,
        #         flight.origin,
        #         flight.destination,
        #         delay_amount,
        #         flight.arrival_time,
        #     )
        #     return render_template("success.html", message=message)
            # return f"
Original arival time:{flight.arrival_time},\n New Arrival Time: {flight.delay_flight(delay_amount)}\n Flight Duration: {((flight.arrival_time - flight.departure_time).total_seconds())//60}
"

    # else:
    #     return render_template("book-flight.html")

@flight.route("/flight/<int:flight_id>/delete", methods=["GET"])
def delete_flight(flight_id):

    flight = Flight.query.get_or_404(flight_id)
    if flight:
        #check if flight is disabled before deleting
        if flight.is_available == True:
            flash('sorry, you must first disable flight before you can delete','danger')
            return redirect(request.referrer)
        db.session.delete(flight)
        db.session.commit()
        message = f"Flight {flight.code} deleted successfully!"
        flash(message, "success")
        return redirect(request.referrer)
    flash('Error: Flight does not exist','danger')
    return render_template('index.html')

@flight.route("/flight/<int:flight_id>/edit", methods=["GET", "POST"])
def edit_flight(flight_id):
    if request.form == 'POST':

        # GET THE FORM REQUESTS
        flight_code = request.form.get("flight_code").upper()
        flight_capacity = request.form.get("flight_capacity")
        flight_model = request.form.get("flight_model")
        category = request.form.get("flight_category")
        date_of_first_flight = format_datetime(request.form.get("first_flight_date"))

        # QUERY THE DB AND REASSIGN THE VALUES IN THE DATABASE
        flight = Flight.query.get_or_404(flight_id)

        if not flight:
            flash('sorry, flight is invalid')
            return redirect(request.referrer)
        else:

           flight.code = flight_code
           flight.model = flight_model
           flight.category = category

           db.session.commit()
           return redirect('Flight Information successfully updated', 'success')
    flight = Flight.query.get_or_404(flight_id)
    return render_template('register_new_flight.html', flight=flight)

    # print("Request is a post request.")
    #     flight = Flight.query.get_or_404(flight_id)
    #     return f"This will process the edit function for flight {flight.code}"
    # flight = Flight.query.get_or_404(flight_id)
    # return render_template('register_new_flight.html',flight = flight)

@flight.route("/test", methods = ['GET','POST'])
def flight_test():
    input = request.form.getlist('checkbox')
    return f"
{input}
"


import pygame
import sys
import os
import time
import random

red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
black = (0, 0, 0)
pink = (150, 0, 150)
rich_black = (1, 22, 39)
red_crayola = (239, 45, 86)
princeton_orange = (237, 125, 58)
azure = (230, 250, 252)
mantis = (140, 216, 103)
emerald = (47, 191, 113)

class Button:
    def __init__(self, screen, font, color, x, y, width, height, text=""):
        self.screen = screen
        self.font = font
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, outline=None):
        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(
                self.screen,
                outline,
                (self.x - 2, self.y - 2, self.width + 4, self.height + 4),
                0,
            )

        pygame.draw.rect(
            self.screen, self.color, (self.x, self.y, self.width, self.height), 0
        )

        if self.text != "":

            text = self.font.render(self.text, 1, (0, 0, 0))
            self.screen.blit(
                text,
                (
                    self.x + (self.width / 2 - text.get_width() / 2),
                    self.y + (self.height / 2 - text.get_height() / 2),
                ),
            )

    def isOver(self, pos):
        # Pos is the mouse position or a tuple of (x,y) coordinates
        if pos[0] > self.x and pos[0] < self.x + self.width:
            if pos[1] > self.y and pos[1] < self.y + self.height:
                return True

        return False

class SimonSays:
    def __init__(self, difficulty, screen, clock, font, w, h, fps):
        self.difficulty = difficulty
        self.screen = screen
        self.clock = clock
        self.font = font
        self.w, self.h = w, h
        self.fps = fps

        background_image = pygame.image.load(os.path.join("images", "GAMEBACK.jpeg"))
        self.backgroundResize = pygame.transform.scale(background_image, (1280, 720))

        game_image = pygame.image.load(os.path.join("images", "GAMEBACK.jpeg"))
        self.gameImageResize = pygame.transform.scale(game_image, (1280, 720))

        self.font = pygame.font.SysFont("comicsans", 25)

        if self.difficulty == "easy":
            grid_size = 3
            self.num_squares_to_click = 3
            self.time_to_see_square = 1000  # in ms

        if self.difficulty == "medium":
            grid_size = 4
            self.num_squares_to_click = 4
            self.time_to_see_square = 1000  # in ms

        if self.difficulty == "hard":
            grid_size = 5
            self.num_squares_to_click = 5
            self.time_to_see_square = 1000  # in ms

        size = 100
        startx, starty = 40, 40
        gap = 10

        xywh = []
        for i in range(grid_size):
            for j in range(grid_size):
                x = startx + i * size + i * gap
                y = starty + j * size + j * gap
                xywh.append([x, y, size, size])

        self.rects = []
        for x, y, w, h in xywh:
            self.rects.append(pygame.Rect(x, y, w, h))

    def draw_startwindow(self):
        self.screen.fill(white)

        self.screen.blit(self.backgroundResize, (1, 1))
        # x,y,width,height
        pygame.draw.rect(self.screen, (0, 0, 0), (58, 78, 650, 62))
        pygame.draw.rect(self.screen, (255, 255, 255), (60, 80, 640, 56))

        # The text
        instructionsText1 = self.font.render(
            "Welcome to Simon Says! You have to click the buttons in the ",
            True,
            (0, 0, 0),
        )
        instructionsText2 = self.font.render(
            "order they appear on the screen! Are you ready?", True, (0, 0, 0)
        )

        self.screen.blit(instructionsText1, (80, 90))

        self.screen.blit(instructionsText2, (80, 115))

    def minigame(self):
        # background
        self.screen.fill(white)
        self.screen.blit(self.gameImageResize, (0, 0))

        # draw rectangles
        for rect in self.rects:
            pygame.draw.rect(self.screen, red_crayola, rect)

        # show tiles
        pygame.display.update()
        pygame.time.wait(3000)

        # grey out 3 tiles
        grey_rects = random.sample(self.rects, self.num_squares_to_click)
        for rect in grey_rects:
            # draw grey rect
            pygame.draw.rect(self.screen, emerald, rect)
            pygame.display.update()
            pygame.time.wait(self.time_to_see_square)

            # undraw grey rect
            pygame.draw.rect(self.screen, red_crayola, rect)
            pygame.display.update()

        cur_square = 0
        while True:
            # exit the game if the user wants
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # if user clicks on button to start game
                pos = pygame.mouse.get_pos()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    for rect in self.rects:
                        if rect.collidepoint(pos):
                            if rect == grey_rects[cur_square]:
                                cur_square += 1
                                pygame.draw.rect(self.screen, blue, rect)
                                pygame.display.update()
                                pygame.time.wait(200)
                                pygame.draw.rect(self.screen, red_crayola, rect)
                                pygame.display.update()
                                if cur_square >= len(grey_rects):
                                    return True
                            else:
                                pygame.draw.rect(self.screen, rich_black, rect)
                                pygame.display.update()
                                pygame.time.wait(500)
                                return False
            self.clock.tick(self.fps)

    def play_minigame(self):
        """Return True if minigame is won, else False"""
        startwindow = True

        # draw start window
        self.draw_startwindow()
        playbutton = Button(
            self.screen,
            self.font,
            (
                0,
                200,
                220,
            ),
            150,
            225,
            250,
            100,
            "Play game :D !",
        )
        playbutton.draw((0, 0, 0))
        pygame.display.update()

        while True:
            # exit the game if the user wants
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # if user clicks on button to start game
                pos = pygame.mouse.get_pos()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if playbutton.isOver(pos):
                        return self.minigame()

            self.clock.tick(self.fps)

if __name__ == "__main__":
    # constants
    width = 1280
    height = 720
    fps = 60

    # initialize
    pygame.init()
    pygame.font.init()
    font = pygame.font.SysFont("timesnewroman", 20)
    screen = pygame.display.set_mode([width, height])
    pygame.display.set_caption("Simon Says")
    clock = pygame.time.Clock()

    # start game
    minigame = SimonSays("hard", screen, clock, font, width, height, fps)
    result = minigame.play_minigame()
    print(f"\n\nGame Result: {result}")


import sys
import cv2
import numpy as np
import pandas as pd
import seaborn as sb
import matplotlib as plt
from math import sin, cos, tan, atan, sqrt
import time
import copy
import window_wrapper as ww

def main():

    base_path = 'C:\\Users\\spenc\\Dropbox (MIT)\\2.671 Go Forth and Measure\\'
    num = 7
    t1 = 'jump1_AdobeExpress.mp4'
    steven = 'Steven\\mp4\\steven' + str(num) + '.mp4'
    jackson = 'Jackson\\mp4\\jackson' + str(num) + '.mp4'

    first_view = True
    i_markers = []

    while True:

        track_points = 3

        # Add in a slider, effectively, dividing saturation and value
        # Smart dynamic thresholding?
        #Detect all points first, then sort by comparing to previous points
        # Keeps last confidence score for point
        # Replays from pandas array rather than recalculating every time
        code = 2
        if code == 0:
            _Frame = ww.WindowWrapper('frame', track_points,
                                      #fpath=base_path + t1,
                                      marker_buffer=0.02, rsz_factor=0.85, init_frms=i_markers, hue_buffer=0.02,
                                      sat_val_buffer=0.25, proximity_weight=0, testing=False, auto_color=True,
                                      data_output=True)
        elif code == 1:
            _Frame = ww.WindowWrapper('frame', track_points,
                                      fpath=base_path + t1,
                                      marker_buffer=0.015, rsz_factor=0.85, init_frms=i_markers, hue_buffer=0.02,
                                      sat_val_buffer=0.55, proximity_weight=0, testing=False, auto_color=True,
                                      data_output=True)
        else:
            _Frame = ww.WindowWrapper('frame', track_points,
                                      fpath=base_path + steven,
                                      marker_buffer=0.012, rsz_factor=0.5, init_frms=i_markers, hue_buffer=0.012,
                                      sat_val_buffer=0.35, proximity_weight=0, testing=False, auto_color=True,
                                      data_output=True)

        first_frame = True
        retv = _Frame.get_retrieval_state()

        while retv:
            # Capture a frame from the webcam
            retv, oframe, frame = _Frame.next_frame()

            if retv:

                corners, frames, tls = _Frame.subimage(first_view, first_frame)

                for i, frame in enumerate(frames):
                    if not first_frame:
                        _Frame.update_contours()
                    _Frame.analyze_contours(first_view, first_frame)

                # Quit if user presses q
                key = cv2.waitKey(1)
                if key & 0xFF == ord('q'):
                    exit(0)

                '''
                # Quit if user presses q, next frame if user presses n
                while True:
                    key = cv2.waitKey(1)
                    if key & 0xFF == ord('q'):
                        exit(0)
                    elif key & 0xFF == ord('n'):
                        break
                '''
                _Frame.show()

            else:
                # Quit if u#ser presses q
                key = cv2.waitKey(1)
                if key & 0xFF == ord('q'):
                    exit(0)

            first_frame = False

        i_markers = _Frame.get_initial_markers()

        if first_view:
            print(_Frame.get_data())

        first_view = False

        key = cv2.waitKey(1) & 0xFF
        while key != ord('q') and key != ord('p'):
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                exit(0)

if __name__ == '__main__':
    main()

'''
def track(fpath, color, points, reg='circ'):
    if reg == 'circ':
        reg_fn = regularity_c
    else:
        reg_fn = regularity

    track_points = points
    all_points = []
    for i in range(points):
        all_points.append([])

    if 'C:' not in fpath:
        fpath = 'C:\\Users\\spenc\\Dropbox (MIT)\\2.671 Go Forth and Measure\\' + fpath

    markers = [(0, 0)] * track_points
    r_markers = [(0, 0)] * track_points

    # Min and max HSV thresholds for target color
    if color == 'w':
        COLOR_THRESHOLD = ([0, 0, 180], [60, 60, 255])  # White
    else:
        COLOR_THRESHOLD = ([20, 100, 100], [35, 255, 255])  # Yellow

    # cap is a VideoCapture object we can use to get frames from webcam
    cap = cv2.VideoCapture(fpath)

    first = True
    retv = True

    #fnum = 0

    while retv:
        # Capture a frame from the webcam
        retv, frame = cap.read()
        #print('frame', fnum)
        #fnum += 1

        if retv:
            f_w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
            f_h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

            if not first:
                corners, frames, tls = subimage(frame, markers)
            else:
                corners, frames, tls = subimage_gen_empty(frame, markers)

            for i, frame in enumerate(frames):
                # Convert BGR to HSV
                hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

                # OpenCV needs bounds as numpy arrays
                lower_color_bound = np.array(COLOR_THRESHOLD[0])
                upper_color_bound = np.array(COLOR_THRESHOLD[1])

                mask_color = cv2.inRange(hsv, lower_color_bound, upper_color_bound)
                contours_color, _ = cv2.findContours(mask_color, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

                # If we have contours...
                if len(contours_color) != 0:

                    # Find the biggest contour by area
                    #g = max(contours_color, key=cv2.contourArea)

                    if first:
                        # Find the most circular contour by hull area
                        cc_list = list(contours_color)
                        cc_list.sort(reverse=True, key=reg_fn)
                        contours_color = cc_list
                        #contours_color = [max(contours_color, key=regularity)]
                        max_significant = 3
                        for j in range(max_significant):
                            circle = contours_color[j]

                            # Get a bounding rectangle around that contour
                            #x, y, w, h = cv2.boundingRect(circle)
                            c, r = cv2.minEnclosingCircle(circle)

                            markers[j] = (int(c[0]), int(c[1]))
                            r_markers[j] = (int(c[0]), int(c[1]))

                            all_points[j].append(markers[j])
                    else:
                        contours_color = max(contours_color, key=reg_fn)
                        c, r = cv2.minEnclosingCircle(contours_color)

                        r_markers[i] = (int(c[0])+1, int(c[1])+1)
                        markers[i] = (tls[i][0]+r_markers[i][0], tls[i][1]+r_markers[i][1])

                        all_points[i].append(markers[i])

        first = False
    df_x = []
    df_y = []
    for single_point in all_points:
        sparr = np.array(single_point)
        df_x.append(sparr[:, 0:1])
        df_y.append(sparr[:, 1:2])
    df_x = tuple(df_x)
    df_y = tuple(df_y)
    df_x = pd.DataFrame(np.hstack(df_x))
    df_y = pd.DataFrame(np.hstack(df_y))
    return df_x, df_y
'''

'''
                    # If we have contours...
                    print('frame')
                    if len(contours) != 0:
                        print('contours!')

                        # Find the biggest contour by area
                        #g = max(contours_color, key=cv2.contourArea)

                        if redo and first:
                            markers = _Frame.set_initial_points()
                        elif first:
                            if auto_select:
                                # Find the most circular contour by hull area
                                cc_list = list(contours_color)
                                cc_list.sort(reverse=True, key=regularity_c)
                                contours_color = cc_list
                                #contours_color = [max(contours_color, key=regularity)]
                                max_significant = 3
                                for j in range(max_significant):
                                    circle = contours_color[j]

                                    # Get a bounding rectangle around that contour
                                    #x, y, w, h = cv2.boundingRect(circle)
                                    c, r = cv2.minEnclosingCircle(circle)

                                    markers[j] = (int(c[0]), int(c[1]))
                                    r_markers[j] = (int(c[0]), int(c[1]))

                                    # Draw the rectangle on our frame
                                    #cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 208, 255), 2)

                                    #Draw the circle on the frame
                                    cv2.circle(oframe, (markers[j][0], markers[j][1]), int(r), (0, 255, 0), 2)

                                    #multiline used to start here Draws lines in the first frame, sometimes causes big skips
                                    for k, pt in enumerate(markers):
                                        if k < len(markers)-1:
                                            cv2.line(oframe, (markers[k][0], markers[k][1]), (markers[k+1][0], markers[k+1][1]), (0, 0, 255), 3)
                                    #and end here
                            else:
                                cv2.imshow('frame', cv2.resize(oframe, (adj_x, adj_y)))
                                while len(wrapped_window.get_markers()) < track_points:
                                    key = cv2.waitKey(1) & 0xFF
                                    if key == ord('q'):
                                        exit(1)
                                markers = wrapped_window.get_markers()
                                first_markers = wrapped_window.get_markers()

                        else:
                            contours_color = max(contours_color, key=regularity_c)
                            c, r = cv2.minEnclosingCircle(contours_color)
                            print(c, r)

                            r_markers[i] = (int(c[0])+1, int(c[1])+1)
                            markers[i] = (tls[i][0]+r_markers[i][0], tls[i][1]+r_markers[i][1])

                            #Draw the circle on the frame
                            cv2.circle(oframe, (markers[i][0], markers[i][1]), int(r), (0, 255, 0), 2)

                            #Draw framing rectangles
                            cv2.rectangle(oframe, (corners[i][0][0], corners[i][0][1]),
                                          (corners[i][1][0], corners[i][1][1]), (255, 0, 0), 2)
                            cv2.circle(oframe, (corners[i][0][0], corners[i][0][1]), 10, (255, 0, 0), 2)

                            for k, pt in enumerate(markers):
                                if k < len(markers)-1:
                                    cv2.line(oframe, (markers[k][0], markers[k][1]), (markers[k+1][0], markers[k+1][1]), (0, 0, 255), 5)

                    # Display that frame (resized to be smaller for convenience)
                    #cv2.imshow('color mask', cv2.resize(mask_color, (adj_x, adj_y)))

                    #if not first:
                    #    cv2.circle(frame, (r_markers[i][0], r_markers[i][1]), 1, (0, 0, 255), 3)
                    #    cv2.imshow('subframe', frame)

                    #multiline used to start here
                    lines = []
                    for i, center in enumerate(markers):
                        if not i == len(markers)-1:
                            lines.append(((markers[i][0], markers[i][1]), (markers[i+1][0], markers[i+1][1])))
                    cv2.drawContours(oframe, lines, (0, 0, 255), 5)
                    # and end here

                    if not (auto_select and first):
                        cv2.imshow('frame', cv2.resize(oframe, (adj_x, adj_y)))
                    redo = True
                    #print(markers)
'''

'''

def regularity(contour, tp='rect'):
    if tp == 'rect':
        hull = cv2.contourArea(cv2.convexHull(contour))
        (x, y), (w, h), _ = cv2.minAreaRect(contour)
        if w == 0 or h == 0:
            res = -1
        else:
            res = hull/(w*h)
    else:
        hull = cv2.contourArea(cv2.convexHull(contour))
        _, r = cv2.minEnclosingCircle(contour)
        circ = 3.1415*r**2
        res = -abs(hull/circ - 1)
        if r < 3:
            res = -10
    return res

def regularity_c(contour):
    return regularity(contour, tp='circ')

def subimage_gen_empty(frame, centers):
    corners = []
    tls = []
    for center in centers:
        tl_x = 0
        tl_y = 0
        br_x = 100
        br_y = 100
        # X positive moving right, Y positive moving down, (0, 0) in top left
        corners.append([(tl_x, tl_y), (br_x, br_y)])
        tls.append([tl_x, tl_y])
    subframes = [frame]
    return corners, subframes, tls

def auto_select(frame, contours, markers, rel_markers):
    if auto_select:
        # Find the most circular contour by hull area
        cc_list = list(contours)
        cc_list.sort(reverse=True, key=regularity_c)
        contours = cc_list
        # contours_color = [max(contours_color, key=regularity)]
        max_significant = len(markers)
        for j in range(max_significant):
            circle = contours[j]

            # Get a bounding rectangle around that contour
            # x, y, w, h = cv2.boundingRect(circle)
            c, r = cv2.minEnclosingCircle(circle)

            markers[j] = (int(c[0]), int(c[1]))
            rel_markers[j] = (int(c[0]), int(c[1]))

            # Draw the rectangle on our frame
            # cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 208, 255), 2)

            # Draw the circle on the frame
            cv2.circle(frame, (markers[j][0], markers[j][1]), int(r), (0, 255, 0), 2)
'''


from .self_Alipay import *
import qrcode,time

alipay = alipay()

class pay:
    def __init__(self,out_trade_no,total_amount,subject,timeout_express):
        self.out_trade_no = out_trade_no
        self.total_amount = total_amount
        self.subject = subject
        self.timeout_express = timeout_express

    def get_qr_code(self,code_url):
        '''
        生成二维码
        :return None
        '''
        qr = qrcode.QRCode(
             version=1,
             error_correction=qrcode.constants.ERROR_CORRECT_H,
             box_size=10,
             border=1
        )
        qr.add_data(code_url)  # 二维码所含信息
        img = qr.make_image()  # 生成二维码图片
        img.save(r'E:\python3\Alipay_for_QR_code\qrcode_image\qr_test_ali.png')
        print('二维码保存成功！')

    def query_order(self,out_trade_no: int):
        '''
        :param out_trade_no: 商户订单号
        :return: Nonem
        '''
        _time = 0
        for i in range(600):
            time.sleep(1)
            result = alipay.init_alipay_cfg().api_alipay_trade_query(out_trade_no=out_trade_no)
            if result.get("trade_status", "") == "TRADE_SUCCESS":
                print('订单已支付!')
                print('订单查询返回值：', result)
                return True
            _time += 2
        return False

def do_payment():
    payer = pay(out_trade_no=datetime.now().strftime('%Y%m%d%H%M%S'),total_amount= 6,subject = "test",timeout_express='10m')

    dict = alipay.trade_pre_create(out_trade_no=payer.out_trade_no,total_amount=payer.total_amount,subject =payer.subject,timeout_express=payer.timeout_express )

    payer.get_qr_code(dict['qr_code'])
    payer.query_order(payer.out_trade_no)


import json

def get_protocol_contents(protocol_file, path=None):
    if not path:
        path = "messenger/"
    try:
        with open("{}{}.json".format(path, protocol_file), "r") as json_file:  # noqa
            return json.load(json_file)
    except Exception:
        return None