import os
import cv2
import numpy as np
import tensorflow as tf
import logging
import winsound

from time import time, sleep
from datetime import datetime

from darkflow.net.build import TFNet
from darkflow.defaults import argHandler
from darkflow.dark.darknet import Darknet
import utils

CURR_DIR = os.path.dirname(__file__)
BEEP_SOUND_FILE = os.path.join(CURR_DIR, 'beep.wav')

class TripWireDrawer(object):
    """ """
    def __init__(self, winname, image):
        self.done       = False
        self.drawing    = False
        self.start_pt   = (0,0)
        self.end_pt     = (0,0)
        self.color      = (0,192,0)
        self.line_width = 5
        self.frame      = image
        self.winname    = winname

    def draw_line(self, event, curr_pt):
        """ """
        if self.done == True:
            return
        # Start Drawing
        if event == cv2.EVENT_LBUTTONDOWN:
            self.drawing = True
            self.start_pt = curr_pt
        # Show the line while drawing
        elif event == cv2.EVENT_MOUSEMOVE:
            if self.drawing == True:
                cv2.line(self.frame, self.start_pt, curr_pt, self.color, self.line_width)
        # Drawing ends
        elif event == cv2.EVENT_LBUTTONUP:
            self.drawing = False
            self.end_pt  = curr_pt
            cv2.line(self.frame, self.start_pt, self.end_pt, self.color, self.line_width)

    def __call__(self):
        """ """
        def mouse_cb(event, x, y, flags, param):
            self.draw_line(event, (x,y))

        cv2.setMouseCallback(self.winname, mouse_cb)
        while True:
            cv2.imshow(self.winname, self.frame)
            if utils.is_key_pressed(utils.Enter_KEY):
                done = True
                break
        # Always set start point to lower y coordinate
        if self.end_pt[1] < self.start_pt[1]:
            tmp = self.start_pt
            self.start_pt = self.end_pt
            self.end_pt   = tmp
        return self.start_pt, self.end_pt

def draw_trip_wire(cam_hdl):
    """ """
    # Draw the trip-wire
    frame = cam_hdl.get_frame()
    self.h, self.w, c = frame.shape
    cv2.putText(frame, 'Draw the trip-wire and press ENTER',
                (10, self.h//2), 3, 0.5, (0, 255, 0), 1)
    drawer = TripWireDrawer(cam_hdl.name, frame)
    tw_start, tw_end = drawer()
    return tw_start, tw_end

def run_detector(frame):
    """ """

class TWD_Demo(object):
    """ """
    def __init__(self, cam_id=None, ip_cam=None, detector='yolo-voc'):
        if cam_id == None and ip_cam is None:
            raise ValueError('No Camera given')

        yolo_meta  = os.path.join(CURR_DIR, 'detector', detector + '.json')
        yolo_model = os.path.join(CURR_DIR, 'detector', detector + '.pb')
        yolo_args = argHandler()
        yolo_args.setDefaults()
        yolo_args['metaLoad'] = yolo_meta
        yolo_args['pbLoad']   = yolo_model
        yolo_args['gpu']      = 1.0
        yolo_args['threshold']= 0.
        self.yolo_args = yolo_args
        self.cam_name = 'Trip-Wire Detection'
        self.cam = utils.WebCam(cam_id, self.cam_name) if cam_id is not None else utils.IPCam(ip_cam, self.cam_name)

        self.tw_start = (0,0)
        self.tw_end   = (0,0)
        self.tw_slope = 0
        self.tw_color = (0, 200, 0)
        self._create_logger()

    def _create_logger(self):
        """ Create a Logger Instance."""
        # Create a new logger instance
        self.logger = logging.getLogger('TWD')
        # self.logger.setLevel(logging.INFO)

        ## Add a console handler
        hdlr = logging.StreamHandler()
        hdlr.setFormatter(logging.Formatter(fmt="(%(name)s)[%(levelname)s]%(message)s"))
        self.logger.addHandler(hdlr)
        self.logger.propagate = False

    def _slope(self, end_pt):
        x1, y1 = self.tw_start
        x2, y2 = end_pt
        d = (x2 - x1)
        if d == 0:
            d += 1e-8
        return (y2 - y1) / d

    def start_camera(self):
        """ Initialize the camera and define the trip-wire."""
        # Setup the scene of the camera
        frame = self.cam.setup_scene()

        # Draw the trip-wire
        self.tw_start, self.tw_end = draw_trip_wire(self.cam)
        frame = self.cam.get_frame()
        cv2.line(frame, self.tw_start, self.tw_end, self.tw_color, 2)
        cv2.imshow(self.cam_name, frame)

        # Get the line points
        self.tw_slope = self._slope(self.tw_end)
        self.h, w, c = frame.shape

        # Create a video writer object
        fourcc      = cv2.VideoWriter_fourcc(*'XVID')
        vid_file    = os.path.join(CURR_DIR, 'twd.avi')
        self.writer = cv2.VideoWriter(vid_file, fourcc, self.cam.fps, (w, self.h))

    def is_event_detected(self, box, rule):
        """ """
        event_detected = False
        obj_x1, obj_x2, obj_y1, obj_y2, _, __, ___ = box
        tw_xl, tw_y1 = self.tw_start
        s11 = self._slope((obj_x1, obj_y1))
        s12 = self._slope((obj_x1, obj_y2))
        s21 = self._slope((obj_x2, obj_y1))
        s22 = self._slope((obj_x2, obj_y2))
        if rule.lower() == 'bidirectional':
            if utils.is_rect_intersected((self.tw_start, self.tw_end),
                                         ((obj_x1, obj_y1), (obj_x2, obj_y2))) is True:
                if utils.in_frange(self.tw_slope, s11, s12) or \
                   utils.in_frange(self.tw_slope, s11, s21) or \
                   utils.in_frange(self.tw_slope, s22, s12) or \
                   utils.in_frange(self.tw_slope, s22, s21): event_detected = True

        elif rule.lower() == 'to_right':
            if (obj_x2 >= tw_xl): event_detected = True
        elif rule.lower() == 'to_left':
            if (obj_x1 <= tw_xl): event_detected = True

        self.logger.info('SLOPES  %.2f %.2f %.2f %.2f %.2f', s11, s12, s21, s22, self.tw_slope)
        self.logger.info('BOX     (%d,%d) , (%d,%d)', obj_x1, obj_y1, obj_x2, obj_y2)
        self.logger.info('Start Point  (%d,%d)', tw_xl, tw_y1)
        self.logger.info('TRUE' if event_detected is True else 'FALSE')
        return event_detected

    def run(self, rule='bidirectional', batch=1):
        """ """
        start_time = time()
        fps = 0
        self.detector = TFNet(self.yolo_args)
        colors        = self.detector.meta['colors']
        beep_on       = False
        while True:
            # Terminate if Esc is pressed
            if utils.Esc_key_pressed(): break

            # Read Frame and run the Object Detector
            frame = self.cam.get_frame()
            bboxes = self.detector.detect(frame)
            fps += 1
            if time() - start_time >= 1:
                print ('fps = ', fps / (time() - start_time))
                fps = 0
                start_time = time()

            beep_alarm = False
            f_idx = 0
            for box in bboxes:
                left, right, top, bot, mess, label, confidence = box
                rect_color = colors[label]
                rect_thick = 1
                if self.is_event_detected(box, rule) == True:
                    beep_alarm = True
                    rect_color = (0,0,255)
                    rect_thick = 3
                cv2.rectangle(frame, (left, top), (right, bot), rect_color, rect_thick)
                cv2.putText(frame, mess, (left, top - 18), 0, 1e-3 * self.h, rect_color, 2)

                # Always show the Trip-Wire line on each frame
                cv2.line(frame, self.tw_start, self.tw_end, self.tw_color, 3)
                cv2.line(frame, self.tw_start, self.tw_end, self.tw_color, 3)
                cv2.line(frame, self.tw_start, self.tw_end, self.tw_color, 3)
                cv2.imshow(self.cam_name, frame)
                writer.write(frame)

                # Play a beep Sound if the monitored event is detected
                if beep_alarm == True:
                    beep_alarm = False
                    if beep_on == False:
                        winsound.PlaySound(BEEP_SOUND_FILE, winsound.SND_ASYNC | winsound.SND_LOOP)
                        beep_on = True
                else:
                    if beep_on == True:
                        winsound.PlaySound(None, winsound.SND_ASYNC)
                        beep_on = False

        writer.release()

# Demo
demo_vid = os.path.join(CURR_DIR, 'demo3.mp4')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# tf.logging.set_verbosity(tf.logging.INFO)
demo = TWD_Demo(cam_id=demo_vid, detector='tiny-yolo-voc')
# demo = TWD_Demo(ip_cam='http://192.168.42.129:8080/shot.jpg', detector='tiny-yolo-voc')
demo.start_camera()
demo.run('bidirectional')
demo.cam.close()


import sys
import os
from os.path import join
import glob
import cv2
import pdb
import matplotlib.pyplot as plt
import numpy as np
from detection_utils import MaskRCNNDetector
from pathlib import Path
from tqdm import tqdm
import argparse

parser = argparse.ArgumentParser(description='Detect labels on PV images')
parser.add_argument("--recording_path",
                        required=True,
                        help="Path to base folder")
parser.add_argument("--valid_categories",
                        required=False,
                        default=None,#"tv,couch,dining table,chair",
                        help="Categories that are to be detected")
parser.add_argument("--detection_type",
                        required=True,
                        default="instance",
                        help="Choose between instance and panoptic")
args = parser.parse_args()

source = 'images'
dest = f'{args.detection_type}_labels'

basedir = args.recording_path
pv_dir = join(basedir, f'{source}')
Path(join(basedir, f'{dest}')).mkdir(exist_ok=True)

if args.valid_categories is not None:
	valid_categories = args.valid_categories.split(',')
else:
	valid_categories = None

detector = MaskRCNNDetector(args.detection_type, valid_categories=valid_categories)

# Collect colors of valid categories from COCO palette.
colors = []
for vc in detector.valid_categories:
	colors.append(detector.category_colors[detector.category_names.index(vc)])

image_files = glob.glob(join(pv_dir,'*.png'))
image_files = sorted(image_files)

for i, image_file in enumerate(tqdm(image_files)):
	output_file = image_file.replace(f'{source}',f'{dest}')
	img = cv2.imread(image_file)

	output_masks, output_category_names, output_scores, output_colors = detector.run_on_opencv_image(img)

	# set mask to zero
	if output_masks is None:
		cv2.imwrite(output_file,np.zeros_like(img)*255)
		continue

	num_detections = len(output_masks)

	masks = np.zeros((len(detector.valid_categories) + 1, img.shape[0], img.shape[1]))
	masks_colored = []

	# for each pixel, keep the label with maximum score
	for idx in range(0, num_detections):
		vc_idx = detector.valid_categories.index(output_category_names[idx]) + 1
		masks[vc_idx] = masks[vc_idx] + (output_masks[idx].astype(np.float))*np.array(output_scores[idx])
	masks = np.argmax(masks, axis=0)

	# color the masks according to COCO palette
	for vc_idx in range(0, len(detector.valid_categories)):
		idx = masks == vc_idx + 1
		masks_ = np.zeros((img.shape[0], img.shape[1],3))
		masks_[idx,0] = colors[vc_idx][0]; masks_[idx,1] = colors[vc_idx][1]; masks_[idx,2] = colors[vc_idx][2]
		masks_colored.append(masks_)
	masks_colored = np.array(masks_colored).sum(axis=0)

	cv2.imwrite(output_file,masks_colored)


import lex
import sys

tokens = [

    'T_Identifier',
    'T_DoubleConstant',
    'DOT',
    'PLUS',
    'MINUS',
    'DIVIDE',
    'MULTIPLY',
    'PERCENTAGE',
    'LESS',
    'GREATER',
    'EQL',
    'T_LessEqual',
    'T_GreaterEqual',
    'T_Equal',
    'T_NotEqual',
    'T_And',
    'T_Or',
    'NOT',
    'SEMICOLON',
    'COMMA',
    'LPAREN',
    'RPAREN',
    'LBRACE',
    'RBRACE',
    'T_IntConstant',
    'T_StringConstant',
    'T_BoolConstant'

]

reserved_list = {
    'void': 'T_Void',
    'string': 'T_String',
    'while': 'T_While',
    'break': 'T_Break',
    'int': 'T_Int',
    'null': 'T_Null',
    'if': 'T_If',
    'Print': 'T_Print',
    'double': 'T_Double',
    'for': 'T_For',
    'else': 'T_Else',
    'ReadInteger': 'T_ReadInteger',
    'bool': 'T_Bool',
    'return': 'T_Return',
    'ReadLine': 'T_ReadLine'

}

operator_list = {
    'PLUS' : '+',
    'MINUS': '-',
    'MULTIPLY': '*',
    'DIVIDE': '/',
    'PERCENTAGE': '%',
    'LESS': '<',
    'GREATER': '>',
    'EQL': '=',
    'NOT': '!',
    'SEMICOLON': ';',
    'COMMA': ',',
    'DOT': '.',
    'LPAREN': '(',
    'RPAREN': ')',
    'LBRACE': '{',
    'RBRACE': '}'
}

t_ignore  = ' \t'
t_EQL = r'='
t_PERCENTAGE = r'%'
t_LESS = r'<'
t_GREATER = r'>'
t_NOT = r'\!'
t_SEMICOLON = r';'
t_COMMA = r','
t_DOT = r'\.'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LBRACE = r'\{'
t_RBRACE = r'\}'

tokens += list(reserved_list.values())

def t_LessEqual(t):
    r'<='
    t.type = 'T_LessEqual'
    return t

def t_GreaterEqual(t):
    r'>='
    t.type = 'T_GreaterEqual'
    return t

def t_Equal(t):
    r'=='
    t.type = 'T_Equal'
    return t

def t_NotEqual(t):
    r'\!='
    t.type = 'T_NotEqual'
    return t

def t_And(t):
    r'\&\&'
    t.type = 'T_And'
    return t

def t_Or(t):
    r'\|\|'
    t.type = 'T_Or'
    return t

# r'[0-9]*\.[0-9]+(E?)\+?-?\d+'
def t_DoubleConstant(t):
    r'[0-9]+\.[0-9]*[Ee]?[+-]?\d+'
    t.type = 'T_DoubleConstant'
    return t

def t_BoolConstant(t):
    r'(true|false)'
    t.type = 'T_BoolConstant'
    return t

def t_COMMENT(t):
    r'(\/\*([^*]|[\r]|(\*+([^*\/]|[\r])))*\*+\/)|(\/\/.*)'
    line = t.value.count('\n')
    t.lexer.lineno += line
    pass
    # No return value. Token discarded

def t_IntConstant(t):
    r'(0[Xx][\da-fA-F]+|\d+)'
    t.type = 'T_IntConstant'
    return t

def t_PLUS(t):
    r'\+'
    t.type = 'PLUS'
    return t

def t_MINUS(t):
    r'\-'
    t.type = 'MINUS'
    return t

def t_DIVIDE(t):
    r'\/'
    t.type = 'DIVIDE'
    return t

def t_MULTIPLY(t):
    r'\*'
    t.type = 'MULTIPLY'
    return t

def t_IDENTIFIER(t):
    r'[a-zA-Z][a-zA-Z_0-9]*'
    size = len(t.value)
    #print("size is ", size)
    t.type = 'T_Identifier'
    if reserved_list.get(t.value) != None:
        t.type = reserved_list.get(t.value)
        return t
    if size > 31:
        t_error(t)
        return

    return t

def t_StringConstant(t):
    r'"[^\n|"]*(")?'
    #r'"[/d/D/w/W].*"'
    #r"^(?!\n).*$"
    #print("print in string ", t.value, " yoo bro!")
    t.type = 'T_StringConstant'
    if t.value[-1] != '\"' or (t.value[0] == '\"' and len(t.value) == 1):
        t_error(t)
        t.lexer.lineno += 1
        return

    return t

def t_newline(t):
    r'\n+'
    t.lexer.lineno += len(t.value)
    #print("new line found")
    #t.lexpos = 0

# Compute column.
#     input is the input text string
#     token is a token instance
def find_column(input, token):
    #print("lexpos ",token.lexpos)
    line_start = input.rfind('\n', 0, token.lexpos) + 1
    return (token.lexpos - line_start) + 1

# Error handling rule
def t_error(t):
    print("************ inside error in lex *******")
    #print("*** Error line",  t.lineno, "\nIllegal character '%s'" % t.value)
    if t.type == 'T_Identifier':
        redirect_to_file("\n*** Error line " +  str(t.lineno) + ".")
        redirect_to_file("*** Identifier too long: \"" + t.value + "\"\n")
        redirect_to_file(t.value + " line " + str(t.lineno) + " cols " + str(find_column(contents, t)) + "-" + str(find_column(contents, t)+len(t.value) - 1) + " is " + t.type + "( truncated to " + t.value[:31] + ")")
    elif t.type == 'T_StringConstant':
        redirect_to_file("\n*** Error line " + str(t.lineno) + ".")
        redirect_to_file("*** Unterminated string constant: " + t.value + "\n")
    else:
        redirect_to_file("*** Error line" +  str(t.lineno) + "\nUnrecognized char '%s'" % str(t.value[0]) + "\n\n")

    t.lexer.skip(1)

lexar = lex.lex()

#redirect print to outfile
def redirect_to_file(text):
    #original = sys.stdout
    #sys.stdout = open(outFileName, 'a+')
    #print('This is your redirected text:')
    print(text)
    #sys.stdout = original

#read from file

fileName = str(sys.argv[1])
#outFileName = str(sys.argv[2])

contents = ''
f=open(fileName, 'r')
if f.mode == 'r':
    contents = f.read()
#print(contents)
lines = contents.splitlines()
#print(lines)
lexar.input(contents)
#lexar.input("1.12e-6")

def getNextToken():
    return lexar.token()

"""
while True:

    tok = lexar.token()
    if not tok:
        break

    val = ""

    type = tok.type
    if(operator_list.get(tok.type) != None):
        type = operator_list.get(tok.type)
        type = "\'" + type + "\'"

    if tok.type == "T_DoubleConstant":

        val = str(float(tok.value))
        if(val[-2:] == ".0"):
            val = val[:-2]
        val = " (value = " + val + ")"

        #redirect_to_file(tok.value + "\t\tline " + str(tok.lineno) + "cols " + str(find_column(contents, tok)) + "-" + str(find_column(contents, tok) + len(tok.value) - 1) + " is" + type + "  (value =" + str(float(tok.value)) + ")")

    elif tok.type == "T_IntConstant":
        if tok.value[:2] == '0X' or tok.value[:2] == '0x':
            val = " (value = " +  str(int(tok.value, 16)) + ")"
        else:
            val = " (value = " +  str(int(tok.value))  + ")"

    elif tok.type == "T_StringConstant" or tok.type == "T_BoolConstant":
        val = " (value = " + str(tok.value )+ ")"
        #redirect_to_file(tok.value + "\t\tline " + str(tok.lineno) + "cols " + str(find_column(contents, tok)) + "-" + str(find_column(contents, tok) +len(tok.value) - 1) + " is" + type + "  (value =" + str(tok.value )+ ")")

    #else:
    redirect_to_file(tok.value + "\t\tline " + str(tok.lineno) + " cols " + str(find_column(contents, tok)) + "-" + str(find_column(contents, tok) + len(tok.value) - 1) + " is " + type + val)

"""

"""
print issues
handle string input(done)
handle error,
comment(done),
number.out/badDouble,(calculate exact values)
hexa(calculate value for hex)
program.decaf to rest all(done)

create shell script
python 2.7
fox server
input all files
"""

"""
if tok.type == "T_DoubleConstant":
        print(tok.value, "\t\tline ", tok.lineno, "cols ", find_column(contents, tok), "-", find_column(contents, tok)+len(tok.value) - 1, " is", type, "  (value =",str(float(tok.value)),")")

    elif tok.type == "T_IntConstant" or tok.type == "T_StringConstant" or tok.type == "T_BoolConstant":
        print(tok.value, "\t\tline ", tok.lineno, "cols ", find_column(contents, tok), "-", find_column(contents, tok)+len(tok.value) - 1, " is", type, "  (value =",tok.value,")")

    else:
        print(tok.value, "\t\tline ", tok.lineno, "cols ", find_column(contents, tok), "-", find_column(contents, tok)+len(tok.value) - 1, " is", type)
"""

"""
error print

if t.type == 'T_Identifier':
        print("*** Error line ", t.lineno,".")
        print("*** Identifier too long: \"", t.value, "\"\n")
        print(t.value, "line ", t.lineno, "cols ", find_column(contents, t), "-", find_column(contents, t)+len(t.value) - 1, " is", t.type, "( truncated to", t.value[:31], ")")
    elif t.type == 'T_StringConstant':
        print("*** Error line ", t.lineno,".")
        print("*** Unterminated string constant: ", t.value)
    else:
        print("*** Error line",  t.lineno, "\nUnrecognized char '%s'" % t.value[0], "\n\n")

"""


import cv2
from time import sleep
from image_processing.filters_code.filters import *
from opencv.detection.contour_detection import *
from os import listdir
from coordinates_helper.coords_calculations import is_near_enough, calc_dist
from functools import reduce

#path = '../../data_aug/x/'
path = '../../images/screen_with_x/'

for name in listdir(path):
    resize_value = 0.5
    #img = cv2.imread(path + name)
    img = cv2.imread("images/scenario1.png")

    height, width, _ = img.shape
    cnts_img = np.zeros(img.shape)

    gray = gray_scale(img)
    blurred = gaussian_blur(gray, 7)
    filtered = adaptive_threshold(blurred, threshold_block_size=7, threshold_c=5)
    aux_filtered = filtered.copy()
    contours, hierarchy = contour_detection(filtered, method=cv2.CHAIN_APPROX_NONE)
    print(f"Found {len(contours)} contours")

    filtered = bgr_scale(filtered)
    cv2.drawContours(filtered, contours, -1, (0, 255, 0), thickness=1)

    for _ in range(1):

        cv2.imshow('img', cv2.resize(img, (int(width * resize_value), int(height * resize_value))))
        cv2.imshow('filtered', cv2.resize(filtered, (int(width * resize_value), int(height * resize_value))))
        cv2.waitKey(10)

        for idx, cnt in zip(range(len(contours)), contours):
            # IMAGES
            show = bgr_scale(aux_filtered)

            # CALCULATIONS
            value = 0.04
            peri = cv2.arcLength(cnt, True)
            area = cv2.contourArea(cnt)
            hull_area = cv2.contourArea(cv2.convexHull(cnt))
            approx = cv2.approxPolyDP(cnt, value * peri, True)
            x, y, w, h = cv2.boundingRect(approx)
            if hull_area == 0:
                continue
            solidity = area / float(hull_area)

            box_left_top = (x, y)
            box_right_top = (x + w, y)
            box_left_bot = (x, y + h)
            box_right_bot = (x + w, y + h)

            box_middle_top = (x + int(w/2), y)
            box_middle_bot = (x + int(w/2), y + h)
            box_middle_left = (x, y + int(h/2))
            box_middle_right = (x + w, y + int(h/2))

            ext_left = tuple(cnt[cnt[:, :, 0].argmin()][0])
            ext_right = tuple(cnt[cnt[:, :, 0].argmax()][0])
            ext_top = tuple(cnt[cnt[:, :, 1].argmin()][0])
            ext_bot = tuple(cnt[cnt[:, :, 1].argmax()][0])

            center_x = x + int(w / 2)
            center_y = y + int(h / 2)

            moments = cv2.moments(cnt)
            if moments['m00'] == 0:
                continue
            mass_x = int(moments['m10'] / moments['m00'])
            mass_y = int(moments['m01'] / moments['m00'])

            # DEBUG CONTOUR
            def offset_x(value):
                return (value-x)*scale_value
            def offset_y(value):
                return (value-y)*scale_value
            cnt_img = np.zeros((h, w, 3))
            offset_cnt = list(map((lambda cont: [cont[0]-x, cont[1]-y]), cnt.squeeze()))
            scale_value = 6
            cnt_img = cv2.resize(cnt_img, (cnt_img.shape[1]*scale_value, cnt_img.shape[0]*scale_value))
            for coordinates in offset_cnt:
                cv2.circle(cnt_img, (coordinates[0]*scale_value, coordinates[1]*scale_value), 1, (255, 255, 255), 1)

            #cv2.imshow('cnt_img', cnt_img)
            #cv2.waitKey(25)

            # CONDITIONS
            # SIZE
            max_size = 6000
            min_size = 12
            if not(min_size < w < max_size and min_size < h < max_size):
                #aux = cnt_img.copy()
                #print(f"Size not satisfied: w:{w}, h:{h}")
                #cv2.imshow('cnt_img', aux)
                #cv2.waitKey(25)
                continue
                #pass
            # RATIO
            if not 0.9 <= max(h, w)/min(h, w) < 1.5:
                #aux = cnt_img.copy()
                #print(f"RATIO not satisfied: {max(h, w)/min(h, w)}")
                #cv2.imshow('cnt_img', aux)
                #cv2.waitKey(25)
                continue
                #pass
            # SOLIDITY
            if not 0.1 < solidity < 0.8:
                continue
            # CENTER OF MASS (must be centered)
            if not is_near_enough(mass_x, center_x, mass_y, center_y, 6):
                continue
            # BOUNDING BOX CORNER SURROUNDS (must have close contour points)
            corner_status = [False, False, False, False]
            # BOUNDING BOX MIDDLE SURROUNDS (must NOT have close contour points)
            middle_status = [False, False, False, False]
            colors = [(100, 255, 0), (100, 255, 0), (100, 255, 0), (100, 255, 0), (100, 255, 0), (100, 255, 0),
                      (100, 255, 0), (100, 255, 0)]
            for point_coords in cnt.squeeze():
                point_x = point_coords[0]
                point_y = point_coords[1]

                # CORNER
                dist_corner = int(min(h / 5, w / 5))
                if is_near_enough(point_x, box_right_bot[0], point_y, box_right_bot[1], dist_corner):
                    corner_status[0] = True
                    colors[0] = (0, 255, 0)
                if is_near_enough(point_x, box_left_bot[0], point_y, box_left_bot[1], dist_corner):
                    corner_status[1] = True
                    colors[1] = (0, 255, 0)
                if is_near_enough(point_x, box_right_top[0], point_y, box_right_top[1], dist_corner):
                    corner_status[2] = True
                    colors[2] = (0, 255, 0)
                if is_near_enough(point_x, box_left_top[0], point_y, box_left_top[1], dist_corner):
                    corner_status[3] = True
                    colors[3] = (0, 255, 0)
                # MIDDLE
                dist_middle = int(min(h / 7, w / 7))
                if is_near_enough(point_x, box_middle_top[0], point_y, box_middle_top[1], dist_middle):
                    middle_status[0] = True
                    colors[4] = (0, 0, 255)
                if is_near_enough(point_x, box_middle_bot[0], point_y, box_middle_bot[1], dist_middle):
                    middle_status[1] = True
                    colors[5] = (0, 0, 255)
                if is_near_enough(point_x, box_middle_left[0], point_y, box_middle_left[1], dist_middle):
                    middle_status[2] = True
                    colors[6] = (0, 0, 255)
                if is_near_enough(point_x, box_middle_right[0], point_y, box_middle_right[1], dist_middle):
                    middle_status[3] = True
                    colors[7] = (0, 0, 255)

                new_x = offset_x(point_x)
                new_y = offset_y(point_y)

                aux = cnt_img.copy()

                cv2.circle(aux, (new_x, new_y), 1, (255, 150, 0), 2)
                cv2.line(aux, (new_x, new_y), (offset_x(box_right_bot[0]), offset_y(box_right_bot[1])), colors[0])
                cv2.line(aux, (new_x, new_y), (offset_x(box_left_bot[0]), offset_y(box_left_bot[1])), colors[1])
                cv2.line(aux, (new_x, new_y), (offset_x(box_right_top[0]), offset_y(box_right_top[1])), colors[2])
                cv2.line(aux, (new_x, new_y), (offset_x(box_left_top[0]), offset_y(box_left_top[1])), colors[3])
                cv2.line(aux, (new_x, new_y), (offset_x(box_middle_top[0]), offset_y(box_middle_top[1])), colors[4])
                cv2.line(aux, (new_x, new_y), (offset_x(box_middle_bot[0]), offset_y(box_middle_bot[1])), colors[5])
                cv2.line(aux, (new_x, new_y), (offset_x(box_middle_left[0]), offset_y(box_middle_left[1])), colors[6])
                cv2.line(aux, (new_x, new_y), (offset_x(box_middle_right[0]), offset_y(box_middle_right[1])), colors[7])

                #cv2.putText(aux, str(abs(point_x - box_right_bot[0])) + ' ' + str(abs(point_y - box_right_bot[1])),
                #            (offset_x(box_right_bot[0] - 20), offset_y(box_right_bot[1]) - 20),
                #            cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 240, 0))

                #cv2.putText(aux, str(abs(point_x - box_left_bot[0])) + ' ' + str(abs(point_y - box_left_bot[1])),
                #            (offset_x(box_left_bot[0] + 20), offset_y(box_left_bot[1]) - 20),
                #            cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 240, 0))

                #cv2.putText(aux, str(abs(point_x - box_right_top[0])) + ' ' + str(abs(point_y - box_right_top[1])),
                #            (offset_x(box_right_top[0] - 20), offset_y(box_right_top[1]) - 20),
                #            cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 240, 0))

                cv2.putText(aux, str(int(calc_dist(point_x, point_y, box_left_top[0], box_left_top[1]))) + '-' + str(dist_corner),
                            (offset_x(box_left_top[0] + 20), offset_y(box_left_top[1]) + 20),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, colors[3])

                #cv2.putText(aux, str(abs(point_x - box_middle_top[0])) + ' ' + str(abs(point_y - box_middle_top[1])),
                #            (offset_x(box_middle_top[0] - 20), offset_y(box_middle_top[1]) - 20),
                #            cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 240, 0))

                #cv2.putText(aux, str(abs(point_x - box_middle_bot[0])) + ' ' + str(abs(point_y - box_middle_bot[1])),
                #            (offset_x(box_middle_bot[0] - 20), offset_y(box_middle_bot[1]) - 20),
                #            cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 240, 0))

                cv2.putText(aux, str(int(calc_dist(point_x, point_y, box_middle_left[0], box_middle_left[1]))) + '-' + str(dist_middle),
                            (offset_x(box_middle_left[0] + 15), offset_y(box_middle_left[1]) - 20),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, colors[6])

                #cv2.putText(aux, str(abs(point_x - box_middle_right[0])) + ' ' + str(abs(point_y - box_middle_right[1])),
                #            (offset_x(box_middle_right[0] - 20), offset_y(box_middle_right[1]) - 20),
                #            cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 240, 0))

                cv2.circle(aux, (0, 0), dist_corner * scale_value, (0, 255, 0), 1)
                cv2.circle(aux, (0, int(h / 2 * scale_value)), dist_middle * scale_value, (0, 255, 0), 1)
                cv2.imshow('cnt_img', aux)
                cv2.waitKey(1)
                #sleep(0.01)
            if not reduce((lambda bool1, bool2: bool1 and bool2), corner_status):
                continue
            if reduce((lambda bool1, bool2: bool1 or bool2), middle_status):
                continue

            # DRAWING
            cv2.putText(show, str(solidity), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))  # SOLIDITY
            cv2.drawContours(show, contours, idx, (0, 0, 255), thickness=2)  # CONTOUR
            cv2.drawContours(cnts_img, contours, idx, (0, 0, 255), thickness=2)

            cv2.line(show, box_left_top, box_right_top, (255, 150, 0))
            cv2.line(show, box_right_top, box_right_bot, (255, 150, 0))
            cv2.line(show, box_right_bot, box_left_bot, (255, 150, 0))
            cv2.line(show, box_left_bot, box_left_top, (255, 150, 0))

            for coordinates in [box_left_top, box_right_top, box_right_bot, box_left_bot]:
                cv2.circle(show, coordinates, 2, (255, 150, 0), 3)

            for coordinates in [box_middle_top, box_middle_bot, box_middle_left, box_middle_right]:
                cv2.circle(show, coordinates, 2, (255, 150, 0), 3)

            for coordinates in [ext_bot, ext_left, ext_right, ext_top]:
                cv2.circle(show, coordinates, 2, (255, 0, 0), 5)

            cv2.circle(show, (center_x, center_y), 5, (150, 255, 0), thickness=1)  # CENTER
            cv2.circle(show, (mass_x, mass_y), 2, (0, 255, 0), thickness=1)  # CENTER OF MASS

            # SHOWING
            cv2.imshow('show', cv2.resize(show, (int(width * resize_value), int(height * resize_value))))
            cv2.imshow('cnts_img', cv2.resize(cnts_img, (int(width * resize_value), int(height * resize_value))))
            cv2.waitKey(25)
            sleep(0.5)


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

from bs4 import BeautifulSoup
import requests as req
import time
import pdb

f = open('/home/xiaorui/Desktop/shangke.txt', 'a+')

headers = {
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36'
}

def get_links(url):
    wb_info = req.get(url, headers=headers)
    soup = BeautifulSoup(wb_info.text, 'lxml')
    domain = url
    links = soup.select('body > div:nth-of-type(1) > table > tr:nth-of-type(4) > td > table:nth-of-type(2) > tbody > tr > td > a')
    for link in links:
        href = link.get('href')
        href = domain + '/' + href
        get_info(href)
        time.sleep(0.5)

def get_info(url):
    wb_info = req.get(url, headers=headers)
    wb_info.encoding = 'gbk'
    soup = BeautifulSoup(wb_info.text, 'lxml')
    title1 = soup.find_all('font')
    title = soup.select('body > div > table:nth-of-type(4)> tr:nth-of-type(1) > td > strong > font')
    if len(title) == 1:
        f.write(title[0].get_text().encode('utf8')+'\n')
    content = soup.select('body > div > table:nth-of-type(5)  > tr > td:nth-of-type(2) > p')
    if len(content) == 1:
        f.write(content[0].get_text().encode('utf8') + '\n\n\n')

if __name__=='__main__':
    urls = ['https://www.kanunu8.com/book3/7540',]
    for url in urls:
        get_links(url)

f.close()


from credentials import Credentials
from user import User

# credentials:
def create_credentials(account, username, password):
    new_credentials = Credentials(account, username, password)
    return new_credentials

def save_credentials(credentials):
    credentials.save_credentials

def test_save_multiple_credentials(credentials):
    credentials.test_save_multiple_credentials

def delete_credentials(credentials):
    credentials.delete_credentials

# user data:
def create_user(fname, lname, email, username, password):
    '''
    This function creates a new account.
    '''
    new_user = User(fname, lname, email, username, password)
    return new_user

def save_user(user):
    '''
    This function saves an account.
    '''
    user.save_user()

def delete_user(user):
    '''
    This function deletes an account.
    '''
    user.delete_user()

def find_user(email):
    '''
    This function finds a user by their email address.
    '''
    return User.find_by_email(email)

def check_existing_user(email):
    '''
    This function checks if a user exists with that email and returns a Boolean.
    '''
    return User.user_exist(email)

def display_users():
    '''
    This function returns all saved users.
    '''
    return User.display_users()

def user_exists(email):
    '''
    This functions is to check if a user exists.
    '''
    return User.check_existing_user(email)

def main():
    print("Hello, welcome to your user data list. What is your name?")

    user_name = input()
    print("")

    print("Hello {user_name}. What would you like to do?")
    print("\n")

    while True:
        print(
            "Use these short codes : if - create new user data, ld - display user data, sh - find user data, ex - exit ")

        short_code = input().lower()

        if short_code == 'if':
            print("New User")
            print("-" * 10)

            print("First name ....")
            f_name = input()

            print("Last name ...")
            l_name = input()

            print("Username ...")
            u_name = input()

            print("Email address ...")
            e_address = input()

            save_user(create_user)
            print('\n')
            print("New User {f_name} {l_name} created")
            print('\n')

        elif short_code == 'ld':

            if display_user():
                print("Here is a list of all your user data")
                print('\n')

                for user in display_user():
                    print("{user.first_name} {user.last_name} .....{user.username}")

                print('\n')
            else:
                print('\n')
                print("You dont seem to have any user data saved yet")
                print('\n')

        elif short_code == 'sh':

            print("Enter the email you want to search for")

            search_email = input()
            if check_existing_user(search_email):
                search_user = find_user(search_email)
                print("{search_user.first_name} {search_user.last_name}")
                print('-' * 20)

                print("Username.......{search_user.username}")
                print("Email address.......{search_user.email}")
            else:
                print("That user data does not exist")

        elif short_code == "ex":
            print("Bye .......")
            break
        else:
             print("I really didn't get that. Please use the short codes")

if __name__ == '__main__':
    main()


from PyQt5 import QtCore
import sys

class AThread(QtCore.QThread):

    def run(self):
        for i in range(3):
            print("ping %d" % i)

app = QtCore.QCoreApplication([])
thread = AThread()
thread.finished.connect(app.exit)
thread.start()
sys.exit(app.exec_())


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

""" RDB most simple handler i could write """

import os
import time
import glob
import commentjson as json

# This Rethinkdb reference is already connected at app init
from rethinkdb import r, RqlDriverError

from flask import g  # , url_for, redirect
from flask.ext.restful import request  # , fields, marshal
from .connections import Connection
from ..base import ExtendedApiResource
from ... import htmlcodes as hcodes
from ...marshal import convert_to_marshal
from ... import get_logger

# Using docker, "**db**"" is my alias of the ReThinkDB container
RDB_HOST = "rdb"
RDB_PORT = 28015
# Models and paths
JSONS_PATH = 'models'
JSONS_EXT = '.json'
# Database and tables to use
APP_DB = "webapp"
DEFAULT_TABLE = "test"
TIME_COLUMN = 'latest_timestamp'
IP_COLUMN = 'latest_ipaddress'
USER_COLUMN = 'latest_user'

logger = get_logger(__name__)

###############################
def get_ip(ip=None):
    """ A quick (and dirty function) to get the IP from request """
# TO FIX
#   make one function/class from what you find in app.py
#   limit_remote_addr
#   Please fix me here:
# http://esd.io/blog/flask-apps-heroku-real-ip-spoofing.html
    if not request.headers.getlist("X-Forwarded-For"):
        ip = request.remote_addr
    else:
        ip = request.headers.getlist("X-Forwarded-For")[0]
    return ip

##########################################
# RethinkBD connection object
class RethinkConnection(Connection):
    """
    Connection for ReThinkDB.
    Based on the Borg design pattern, to optimize resources on
    opening connections for each request processed by Flask
    """

    def __init__(self, load_setup=False):
        """ My abstract method already connect by default """
        super(RethinkConnection, self).__init__(load_setup)

    # === Connect ===
    def make_connection(self, use_database):
        """
        This method implements the abstract interface
        of the Connection class which makes use of a **Singleton Borg**
        design pattern.
        See it yourself at: [[connections.py]]
        You will connect only once, using the same object.

        Note: authentication is provided with admin commands to server,
        after starting it up, using ssh from app container.
        Expecting the environment variable to contain a key.
        """
        params = {"host": RDB_HOST, "port": RDB_PORT}
        key = os.environ.get('KEYDBPASS') or None
        if key is not None:
            params["auth_key"] = key
            logger.info("Connection is pw protected")
        # else:
        #     logger.warning("Using no authentication")

        # Rethinkdb database connection
        try:
            # IMPORTANT! The chosen ORM library does not work if missing repl()
            # at connection time
            self._connection = r.connect(**params).repl()
            logger.debug("Created Connection")
        except RqlDriverError as e:
            logger.critical("Failed to connect RDB", e)
            return False

        logger.debug("Switching to database " + APP_DB)
        # Note: RDB db selection does not give error if the db does not exist
        self._connection.use(APP_DB)
        return self._connection

    def create_table(self, table=None, remove_existing=False):
        """ Creating a table if not exists,
        taking for Granted the DB already exists """

        if table in r.table_list().run():
            logger.debug("Table '" + table + "' already exists.")
            if remove_existing:
                r.table_drop(table).run()
                logger.info("Removed")
        else:
            r.table_create(table).run()
            logger.info("Table '" + table + "' created")

##########################################
# Need a pool of connections: http://j.mp/1yNP4p0
def try_to_connect():
    if g and "rdb" in g:
        return False
    try:
        logger.debug("Creating the rdb object")
        rdb = RethinkConnection()
        if g:
            g.rdb = rdb
    except Exception as e:
        logger.error("Cannot connect:\n'%s'" % e)
        return None
        # abort(hcodes.HTTP_INTERNAL_TIMEOUT,
        #     "Problem: no database connection could be established.")
    return True

##########################################
# RethinkBD base
class RDBdefaults(object):
    """ A class to apply defaults for rethinkdb operations """
    table = DEFAULT_TABLE
    db = APP_DB
    order = TIME_COLUMN

    def save_action_info(self, user=None):
        if user is None:
            user = 'UNKNOWN'
        return {
            TIME_COLUMN: time.time(),
            IP_COLUMN: get_ip(),
            USER_COLUMN: user
        }

##########################################
# RethinkBD class that can do queries
class RDBquery(RDBdefaults):
    """ An object to query Rethinkdb """

    schema = None
    template = None
    table_index = 'id'

    def get_query(self):
        return r.db(self.db)

    def get_table_query(self, table=None):
        if table is None:
            table = self.table
        # Build a base query: starting from default DB from RDBdefaults.
        base = r.db(self.db)
        # Create
        if table not in base.table_list().run():
            base.table_create(table).run()
        # Use the table
        return base.table(table)

    def execute_query(self, query, limit):
        count = 0
        data = {}

        if not query.is_empty().run():
            count = query.count().run()
            if limit > 0:
                query = query.limit(limit)
            # Note: fix time as i has to be converted if available
            # in original rethinkdb format
            data = query.run(time_format='raw')

        return count, list(data)

    def get_content(self, myid=None, limit=10, index='id'):
        """ For GET method, very simple """

        query = self.get_table_query()
        if self.table_index is not None:
            index = self.table_index

        # If need one element
        if myid is not None:
            query = query.get_all(myid, index=index)

        # Process
        return self.execute_query(query, limit)

    def insert(self, data, user=None):
#TOFIX:
# Find the user?
        # Prepare the query
        query = self.get_table_query()
        # Add extra info: (ip, timestamp, user)
        data['infos'] = self.save_action_info(user)
        # Execute the insert
        rdb_out = query.insert(data).run()
        # Get the id
#first_error?
        return rdb_out['generated_keys'].pop()

    def update(self, key, data, user=None):
        # Prepare the query
        query = self.get_table_query()
        # Add extra info: (ip, timestamp, user)
        data['infos'] = self.save_action_info(user)
        # Execute the insert
        rdb_out = query.update(key, data).run()
        print("\n\n\n", rdb_out, "\n\n\n")
        # Get the id
        return True

# # USELESS FOR REST MOCK API
#     def marshal(self, data, count=0):
#         return marshal(
#             {'data': data, 'count': count},
#             {'data': fields.Nested(self.schema), 'count': fields.Integer})

#     def nomarshal(self, data, count=0):
#         return OrderedDict({'data': data, 'count': count})
# # USELESS FOR REST MOCK API

##########################################
# Read model template
def load_models(extension=JSONS_EXT):
    """ How to look for json models for services API """
    return glob.glob(os.path.join(JSONS_PATH, "*") + extension)

##########################################
def schema_and_tables(fileschema):
    """
    This function can recover basic data for my JSON resources
    """
    template = None
    with open(os.path.join(JSONS_PATH, fileschema + JSONS_EXT)) as f:
        template = json.load(f)
    reference_schema = convert_to_marshal(template)
    label = os.path.splitext(
        os.path.basename(fileschema))[0].lower()

    return label, template, reference_schema

#####################################
# Base implementation for methods?
class BaseRethinkResource(ExtendedApiResource, RDBquery):
    """ The json endpoint in a rethinkdb base class """

    def get(self, data_key=None):
        """
        Obtain main data.
        Obtain single objects.
        Filter with predefined queries.
        """

        # Check arguments
        limit = self._args['perpage']
# // TO FIX: use it!
        current_page = self._args['currentpage']

        return self.get_content(data_key, limit)

    def get_input(self):
        """ Get JSON. The power of having a real object in our hand. """
        return request.get_json(force=True)

    def check_valid(self, json_data):
        """ Verify if the json data follows the schema """
        # Check if dictionary and not empty
        if not isinstance(json_data, dict) or len(json_data) < 1:
            return False
        # Check template
        for key, obj in json_data.items():
            if key not in self.schema:
                return False
        # All fine here
        return True

    def post(self):

        json_data = self.get_input()
        if not self.check_valid(json_data):
            logger.warning("Not a valid template")
            return self.template, hcodes.HTTP_BAD_REQUEST

        # marshal_data = marshal(json_data, self.schema, envelope='data')
        myid = self.insert(json_data)

        #####################
        # redirect to GET method of this same endpoint, with the id found
        #address = url_for(self.table, data_key=myid)
        #return redirect(address)
        # or return the key
        return myid
        #####################

    def put(self, id, index='id'):

        json_data = self.get_input()
        if 'id' in json_data:
            json_data.pop('id')

        if not self.check_valid(json_data):
            logger.warning("Not a valid template")
            return self.template, hcodes.HTTP_BAD_REQUEST

        changes = self.get_table_query().get_all(id, index=index) \
            .update(json_data, return_changes=True).run()
        # Contains all changes applied
        return changes

    def delete(self, id, index='id'):
        """ Remove an element from database (based on primary key) """

        out = self.get_table_query().get_all(id, index=index) \
            .delete().run()
        if out['deleted']:
            logger.debug("Removed record '%s'" % id)
        else:
            return id, hcodes.HTTP_SERVICE_UNAVAILABLE
        return True


'''
方法一：暴力破解法
空间复杂度O(1)，时间复杂度O((m-n)n)，m为haystack长度，n为needle长度
'''
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0
        elif len(haystack) < len(needle):
            return -1

        for i in range(len(haystack)):
            j = 0
            if haystack[i] == needle[j]:
                while True:
                    j += 1
                    if i + j >= len(haystack) and j < len(needle):
                        return -1
                    elif j >= len(needle):
                        return i
                    elif haystack[i + j] != needle[j]:
                        break
        return -1

'''
方法二：使用内置函数
'''
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)


# Definition for a binary tree node.
'''
no. 104
Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
'''
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):

    def maxDepth(self, root): #remember pass self to the member method
        """
        root type: TreeNode
        return type: int
        """
	#deal with boundary and exit conditions
        if root==None: return 0
        if root.left == None and root.right == None: return 1
        left=1
        right=1
        if root.left != None:
            left += self.maxDepth(root.left)  #self.maxDepth is for recursive member method call
        if root.right != None:
            right += self.maxDepth(root.right)
        return left if left>right else right
	# python expression for a>b?a:b in c++ or java


from .pages.main_page import MainPage
from .pages.login_page import LoginPage
from .pages.basket_page import BasketPage
import pytest

# тесты запускаем так: pytest -v --tb=line --language=en test_main_page.py

# Группировка тестов (step 4.3.11)
@pytest.mark.login_guest
class TestLoginFromMainPage():
    # 1 Тестируем возможность перейти на страницу логина (step 4.2.4, 4.2.9)
    def test_guest_go_to_login_page(self, browser):
        link = "http://selenium1py.pythonanywhere.com/"
        page = MainPage(browser,
                        link)  # инициализируем Page Object, передаем в конструктор экземпляр драйвера и url адрес
        page.open()  # открываем страницу
        page.go_to_login_page()  # выполняем метод страницы - переходим на страницу логина
        login_page = LoginPage(browser, browser.current_url)
        login_page.should_be_login_page()

    # 2 Тестируем наличие ссылки логина (step 4.2.5)
    def test_guest_should_see_login_link(self, browser):
        link = "http://selenium1py.pythonanywhere.com/"
        page = MainPage(browser, link)
        page.open()
        page.should_be_login_link()  # проверяем наличие ссылки на логин

# 3 Тестируем переход в корзину с гравной страницы и пустоту корзины (step 4.3.10)
def test_guest_cant_see_product_in_basket_opened_from_main_page(browser):
    link = "http://selenium1py.pythonanywhere.com"
    page = BasketPage(browser, link)
    page.open()
    page.guest_cant_see_product_in_basket_opened_from_another_page()
    page.guest_expect_basket_is_empty()
    page.guest_should_see_empty_basket_message()


from xai.brain.wordbase.nouns._rafter import _RAFTER

#calss header
class _RAFTERS(_RAFTER, ):
	def __init__(self,):
		_RAFTER.__init__(self)
		self.name = "RAFTERS"
		self.specie = 'nouns'
		self.basic = "rafter"
		self.jsondata = {}


from durgesh.transform import four_point_transform
from skimage.filters import threshold_local
import numpy as np
import argparse
import cv2
import imutils

def edgeDetect(image):
    # load the image and compute the ratio of the old height
    # to the new height, clone it, and resize it
    image = cv2.imread(image)
    ratio = image.shape[0] / 500.0
    orig = image.copy()
    image = imutils.resize(image, height = 500)

    # convert the image to grayscale, blur it, and find edges
    # in the image
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    edged = cv2.Canny(gray, 75, 200)

    # show the original image and the edge detected image
    print("STEP 1: Edge Detection")
    cv2.imshow("Image", image)
    cv2.imshow("Edged", edged)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return edged, image, ratio

def contours(edged,image):
    # find the contours in the edged image, keeping only the
    # largest ones, and initialize the screen contour
    cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

    # loop over the contours
    for c in cnts:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)

        # if our approximated contour has four points, then we
        # can assume that we have found our screen
        if len(approx) == 4:
            screenCnt = approx
            break

    # show the contour (outline) of the piece of paper
    print("STEP 2: Find contours of paper")
    cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
    cv2.imshow("Outline", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return image, screenCnt

def perspectiveTransform(orig, screenCnt, ratio):
    # apply the four point transform to obtain a top-down
    # view of the original image
    warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)

    # convert the warped image to grayscale, then threshold it
    # to give it that 'black and white' paper effect
    warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
    T = threshold_local(warped, 11, offset = 10, method = "gaussian")
    warped = (warped > T).astype("uint8") * 255

    # show the original and scanned images
    print("STEP 3: Apply perspective transform")
    cv2.imshow("Original", imutils.resize(orig, height = 650))
    cv2.imshow("Scanned", imutils.resize(warped, height = 650))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return imutils.resize(warped, height = 650)

def segmentation(img,x,y,weidth,height):
    img = img[y:y+height,x:x+weidth]
    cv2.imshow("segmented",img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return img

if __name__ == "__main__":

    image_path = r"C:\Users\durge\PycharmProjects\Checkbox_Detection\data\accident_forms\1566566729259.JPEG"

    original_image = cv2.imread(image_path)

    edged_image, original_resized_image, ratio= edgeDetect(image_path)
    contoured_image, screencnt= contours(edged_image, original_resized_image)
    perspectiveTransformed_image = perspectiveTransform(original_image, screencnt, ratio)

    x = 170
    y= 81
    weidth = 135
    height = 386

    middle_section = segmentation(perspectiveTransformed_image,x,y,weidth,height)
    cv2.rectangle(perspectiveTransformed_image,(x,y),(x+weidth,y+height),(0,255,0),2)
    cv2.putText(perspectiveTransformed_image,'Middle_section',(x+2,y+10),0,0.3,(0,255,0))

    x = 16
    y = 84
    weidth = 164
    height = 376

    A_section = segmentation(perspectiveTransformed_image,x,y,weidth,height)
    cv2.rectangle(perspectiveTransformed_image,(x,y),(x+weidth,y+height),(0,255,0),2)
    cv2.putText(perspectiveTransformed_image,'A_section',(x+2,y+10),0,0.3,(0,255,0))

    x = 296
    y = 84
    weidth = 163
    height = 379

    B_section = segmentation(perspectiveTransformed_image,x,y,weidth,height)
    cv2.rectangle(perspectiveTransformed_image,(x,y),(x+weidth,y+height),(0,255,0),2)
    cv2.putText(perspectiveTransformed_image,'B_section',(x+2,y+10),0,0.3,(0,255,0))

    x = 95
    y = 454
    weidth = 283
    height = 138

    Drawing = segmentation(perspectiveTransformed_image,x,y,weidth,height)
    cv2.rectangle(perspectiveTransformed_image,(x,y),(x+weidth,y+height),(0,255,0),2)
    cv2.putText(perspectiveTransformed_image,'Drawing',(x+2,y+10),0,0.3,(0,255,0))

    x = 155
    y = 586
    weidth = 179
    height = 49

    signature = segmentation(perspectiveTransformed_image,x,y,weidth,height)
    cv2.rectangle(perspectiveTransformed_image,(x,y),(x+weidth,y+height),(0,255,0),2)
    cv2.putText(perspectiveTransformed_image,'Signature',(x+2,y+10),0,0.3,(0,255,0))
    cv2.line(perspectiveTransformed_image, (x+(weidth//2),y), (x+(weidth//2),y+height), (0,255,0),2)

    x = 18
    y = 30
    weidth = 457
    height = 58

    top_sction = segmentation(perspectiveTransformed_image,x,y,weidth,height)
    cv2.rectangle(perspectiveTransformed_image,(x,y),(x+weidth,y+height),(0,255,0),2)
    cv2.putText(perspectiveTransformed_image,'Top section',(x+2,y+10),0,0.3,(0,255,0))

    cv2.imshow("boxed", perspectiveTransformed_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# server.py
from SimpleXMLRPCServer import SimpleXMLRPCServer
import os

server = SimpleXMLRPCServer(('localhost', 9000))

def server_receive_file(self,arg):
    with open("text.txt", "wb") as handle:
        handle.write(arg.data)
        return True

server.register_function(server_receive_file, 'receive file')
server.serve_forever()


import os
import io
from unittest.mock import patch

from google_classroom_client import GoogleClassroomClient
from googleapiclient.http import HttpMockSequence

def _read_http_fixture(response_json_path):
    abs_path = os.path.join(os.path.dirname(__file__), response_json_path)
    if os.path.exists(abs_path):
        return io.open(abs_path, "r", encoding='utf8').read()
    else:
        return response_json_path

def patch_google_api_http(*response_json_paths):
    http = HttpMockSequence(
        [({'status': 200}, _read_http_fixture(path)) for path in response_json_paths]
    )
    return patch.object(GoogleClassroomClient, 'http', http)

def patch_failed_api_http(error_json_path, status=400):
    failed_response = ({'status': status}, _read_http_fixture(error_json_path))
    http = HttpMockSequence(
        [
            # First call is always a discovery, patch it.
            ({'status': 200}, _read_http_fixture('data/discovery.json')),
            # Ignore failed API retries
            *[failed_response] * 3,
            # Subsequent call is made to a specific service after all retries failed.
            # That's the one we are interested in.
            failed_response,
        ]
    )
    return patch.object(GoogleClassroomClient, 'http', http)


import os
import sys

from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import (
    MessageEvent, PostbackEvent, UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent,
    TextMessage, TextSendMessage, StickerMessage, StickerSendMessage,
    ConfirmTemplate, ButtonsTemplate, CarouselTemplate, CarouselColumn, TemplateSendMessage,
    QuickReply, QuickReplyButton, MessageAction, PostbackAction, URIAction, DatetimePickerAction,
    LocationAction, CameraAction, CameraRollAction)

app = Flask(__name__)

channel_secret = os.getenv("LINE_CHANNEL_SECRET", None)
channel_access_token = os.getenv("LINE_CHANNEL_ACCESS_TOKEN", None)
if channel_secret is None:
    app.logger.error("LINE_CHANNEL_SECRET not found.")
    sys.exit(1)
if channel_access_token is None:
    app.logger.error("LINE_CHANNEL_ACCESS_TOKEN not found.")
    sys.exit(1)

line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)

@app.route("/callback", methods=["POST"])
def callback():
    signature = request.headers["X-Line-Signature"]
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return "OK"

@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
    text = event.message.text
    if text == "confirm":
        # Confirm Template
        template = ConfirmTemplate(text="confirm text",
                                   actions=[MessageAction(label="Yes", text="Yes"),
                                            MessageAction(label="No", text="No")])
        line_bot_api.reply_message(event.reply_token,
                                   TemplateSendMessage(alt_text="confirm alt_text", template=template))
    elif text == "buttons":
        # Buttons Template
        template = ButtonsTemplate(title="buttons title",
                                   text="buttons text",
                                   actions=[
                                       URIAction(label="uri action", uri="https://line.me"),
                                       PostbackAction(label="postback action", data="data",
                                                      text="postback_text"),
                                       MessageAction(label="message action", text="message action")])
        line_bot_api.reply_message(event.reply_token,
                                   TemplateSendMessage(alt_text="buttons alt_text", template=template))
    elif text == "carousel":
        # Carousel Template
        template = CarouselTemplate(columns=[
            CarouselColumn(text="text1", title="title1",
                           actions=[
                               DatetimePickerAction(label="date picker", data="date_postback", mode="date"),
                               DatetimePickerAction(label="time picker", data="time_postback", mode="time"),
                               DatetimePickerAction(label="datetime picker", data="datetime_postback",
                                                    mode="datetime")
                           ]),
            CarouselColumn(text="text2", title="title2",
                           actions=[
                               URIAction(label="uri action", uri="https://line.me"),
                               PostbackAction(label="postback action", data="postback_data",
                                              text="postback_text"),
                               MessageAction(label="message action", text="message action")
                           ])
        ])
        line_bot_api.reply_message(event.reply_token,
                                   TemplateSendMessage(alt_text="buttons alt_text", template=template))
    elif text == "quick_reply":
        # Quick Reply
        quick_reply = QuickReply(items=[
            QuickReplyButton(action=PostbackAction(label="postback", data="data1")),
            QuickReplyButton(action=MessageAction(label="message", text="text2")),
            QuickReplyButton(action=DatetimePickerAction(label="datetime", data="data3", mode="date")),
            QuickReplyButton(action=CameraAction(label="camera")),
            QuickReplyButton(action=CameraRollAction(label="camera roll")),
            QuickReplyButton(action=LocationAction(label="location"))])
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text="quick reply", quick_reply=quick_reply))
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=event.message.text))

@handler.add(MessageEvent, message=StickerMessage)
def handle_sticker_message(event):
    line_bot_api.reply_message(event.reply_token,
                               StickerSendMessage(package_id=event.message.package_id,
                                                  sticker_id=event.message.sticker_id))

@handler.add(PostbackEvent)
def handle_postback(event):
    line_bot_api.reply_message(event.reply_token,
                               TextSendMessage(text="postback: " + event.postback.data))

@handler.add(FollowEvent)
def handle_follow(event):
    line_bot_api.reply_message(event.reply_token,
                               TextSendMessage(text="Got follow event"))

@handler.add(UnfollowEvent)
def handle_unfollow():
    app.logger.info("Got Unfollow event")

@handler.add(JoinEvent)
def handle_join(event):
    line_bot_api.reply_message(event.reply_token,
                               TextSendMessage(text="Joined this " + event.source.type))

@handler.add(LeaveEvent)
def handle_leave():
    app.logger.info("Got leave event")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080, debug=False)


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 20:32:16 2018
@author: Tao Lin

Training and Predicting with the W-Net unsupervised segmentation architecture
"""

import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import torch
from torchvision import datasets, transforms
from scipy.special import softmax
import matplotlib.pyplot as plt

import sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
import WNet
from utils.crf import dense_crf

parser = argparse.ArgumentParser(description='PyTorch Unsupervised Segmentation with WNet')
parser.add_argument('--model', metavar='C', default="model_20210415210220", type=str,
                    help='name of the saved model')
parser.add_argument('--image', metavar='C', default=None, type=str,
                    help='path to the image')
parser.add_argument('--squeeze', metavar='K', default=20, type=int,
                    help='Depth of squeeze layer')

def show_image(image):
    img = image.numpy().transpose((1, 2, 0))
    plt.imshow(img)
    plt.show()

def show_gray(image):
    image = image.numpy()
    arr = np.asarray(image)
    plt.imshow(arr, cmap='gray', vmin=0, vmax=1)
    plt.show()

def main():
    args = parser.parse_args()
    model = WNet.WNet(args.squeeze)

    model.load_state_dict(torch.load(args.model, map_location=torch.device('cpu')))
    model.eval()

    transform = transforms.Compose([transforms.Resize((224, 224)),
                                transforms.ToTensor()])

    image = Image.open(args.image).convert('RGB')
    x = transform(image)[None, :, :, :]

    enc, dec = model(x)
    show_image(x[0])
    plt.imshow(torch.argmax(enc, dim = 1).detach()[0])
    plt.show()
    show_image(dec[0, :, :, :].detach())

if __name__ == '__main__':
    main()

# python .\enc_hidden_test.py --image="data/JPEGImages/2008_006002.jpg"