from flask import Blueprint, flash
from flask import Flask, render_template, redirect, request, url_for
from flask_sqlalchemy  import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import new_user_credentials as nuc
from werkzeug.security import generate_password_hash, check_password_hash
from flask import current_app as app
from models import individual,labs,doctor
from flask_mail import Mail, Message

register_bp = Blueprint('register_bp', __name__)

login_manager = LoginManager()
login_manager.init_app(app)
mail = Mail(app)

db = SQLAlchemy(app)
db.create_all()
SQLALCHEMY_TRACK_MODIFICATIONS = False

@login_manager.user_loader
def load_user(user_id):
	return individual.query.get(user_id)

@register_bp.route('/individual_form_submit', methods = ['GET' , 'POST'])
def sub():
	if request.method == 'POST':
		try:
			fname = request.form['fname']
			lname = request.form['lname']
			email = request.form['email']
			mob = request.form['mob']
			dob = str(request.form['dob'])
			gender = request.form['gender']
			aadhaar = request.form['aadhaar']
			blood = request.form['blood']
			state = request.form['state']
			city = request.form['city']
			district = request.form['district']
			pin = request.form['pincode']
			addr1=request.form['add1']
			addr2=request.form['add2']

			nu = nuc.New_user(city, dob)
			h_id, pasw = nu.create_user()
			temp = individual(id=h_id, pasw=generate_password_hash(pasw) ,
				fname=fname, lname =lname, email=email, mob =mob, dob=dob,gender=gender,aadhaar=aadhaar, blood=blood,
				state=state, city=city, district=district, pin=pin, addr1=addr1, addr2=addr2 )
			temp.send_pdf_indi()
			db.session.add(temp)
			db.session.commit()

			thank_msg = "Record successfully added"
			message = "Hi "+fname+" " +lname+"\nThank You for registering with National Digital Health Portal.\nYour login credentials are - \nUsername - " + h_id + "\nPassword - " + pasw
			msg = Message('NDHP Registration', sender = 'ndhp.gov@gmail.com', recipients = [email])
			msg.body = message
			path = "C:\\minor_project\\static\\"
			with app.open_resource("GFG.pdf") as fp:
				msg.attach("GFG.pdf", "file/pdf", fp.read())
			mail.send(msg)
			return render_template('thank.html',namee=thank_msg)

		except Exception as e:
			msg = e
			return render_template('thank.html',namee=msg)

#############################################################################      doctor
@register_bp.route('/doctor_form_submit', methods = ['GET' , 'POST'])
def doctor_reg_sub():
	if request.method == 'POST':
		try:
			indi_id = request.form['uid']
			fname = request.form['fname']
			lname = request.form['lname']
			email = request.form['email']
			mob = request.form['mob']
			dob = str(request.form['dob'])
			gender = request.form['gender']
			regnum = request.form['regnum']
			Specialization = request.form['Specialization']
			##add3=request.form['add3']  Please remove this
			state = request.form['state']
			city = request.form['city']
			district = request.form['district']
			pin = request.form['pincode']
			addr1=request.form['add1']
			addr2=request.form['add2']

			h_id="D"+indi_id[1:]
			y,m,d = dob.split("-")
			pasw = d+m+y

			temp = doctor(id=h_id, pasw=generate_password_hash(pasw) ,
				fname=fname, lname =lname, email=email, mob =mob, dob=dob,gender=gender,regnum=regnum, Specialization=Specialization,
				state=state, city=city, district=district, pin=pin, addr1=addr1, addr2=addr2 )

			db.session.add(temp)
			db.session.commit()

			thank_msg = "Record successfully added"
			message = "Hi "+fname+" " +lname+"\nThank You for registering with National Digital Health Portal.\nYour login credentials are - \nUsername - " + h_id + "\nPassword - " + pasw
			msg = Message('NDHP Registration', sender = 'ndhp.gov@gmail.com', recipients = [email])
			msg.body = message
			path = "C:\\minor_project\\static\\"
			#with app.open_resource("GFG.pdf") as fp:
				#msg.attach("GFG.pdf", "file/pdf", fp.read())
			mail.send(msg)
			return render_template('thank.html',namee=thank_msg)

		except Exception as e:
			msg = e
			return render_template('thank.html',namee=msg)
###########################################################################

@register_bp.route('/labs_form_submit', methods = ['GET' , 'POST'])
def lab_form_sub():
	if request.method == 'POST':
		try:
			lab_name = request.form['lab_name']
			tests_avlbl = request.form['tests_avlbl']
			email = request.form['email']
			mob = request.form['mob']
			licenseno = request.form['licenseno']
			owner_name=request.form['owner_name']
			state = request.form['state']
			city = request.form['city']
			district = request.form['district']
			pin = request.form['pincode']
			addr1=request.form['add1']
			addr2=request.form['add2']

			#nu = lc.Labs(city, dob)
			nu = nuc.New_user(city, owner_name)
			h_id, pasw = nu.create_user()
			temp = labs(id = id, licenseno=licenseno, pasw=generate_password_hash(pasw) ,
				labname=lab_name, tests_avlbl =tests_avlbl, email=email, mob =mob, owner_name=owner_name,
				state=state, city=city, district=district, pin=pin, addr1=addr1, addr2=addr2 )
			db.session.add(temp)
			db.session.commit()

			thank_msg = "Record successfully added"
			message = "Hi "+lab_name+"\nThank You for registering with National Digital Health Portal.\nYour login credentials are - \nUsername - " + h_id + "\nPassword - " + pasw
			msg = Message('NDHP Registration', sender = 'ndhp.gov@gmail.com', recipients = [email])
			msg.body = message
			path = "C:\\minor_project\\static\\"
			with app.open_resource("GFG.pdf") as fp:
				msg.attach("GFG.pdf", "file/pdf", fp.read())
			mail.send(msg)
			return render_template('thank.html',namee=thank_msg)

		except Exception as e:
			msg = e
			return render_template('thank.html',namee=msg)
			mail.send(msg)
			return render_template('thank.html',namee=thank_msg)

@register_bp.route('/doctor_indi_check', methods = ['GET' , 'POST'])
def doctor_indi_check():
	if request.method == 'POST':
		try:
			indi_id = request.form['indi']
			if(indi_id[0]=="I"):
					temp = individual.query.filter_by(id = indi_id).first()
					if temp:
						return render_template('doctor_register.html', temp_obj=temp)
					else:
						msg = "User not registered"
						flash("User not registered!")
						return redirect(url_for('register_bp.doctor_indi_check'))

			else:
				msg = "Invalid User ID!"
				flash("Invalid User ID!")
				return redirect(url_for('register_bp.doctor_indi_check'))

		except Exception as e:
			flash(e)
			return render_template('doctor_indi_check.html')
			#msg = "Error in insert operation"


from string import ascii_lowercase as alphabet
from itertools import permutations

superscript = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']

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

def multinomialCoefficient(n, *k):
	ans = factorial(n)

	for i in k:
		ans //= factorial(i)

	return ans

while True:
	try:
		m = int(input('Please enter an amount of nomials to include (: '))

		if m > len(alphabet):
			raise ValueError

		selectedLetters = alphabet[:m]
		break
	except ValueError:
		print('Please ensure that you choose a valid amount of nomials (less than or equal to 26 please [:)')
		continue

while True:
	try:
		n = int(input('Please enter a power to put (%s) to! ' % ' + '.join(selectedLetters)))
		break
	except ValueError:
		print('The power must be a valid integer!')
		continue

# [{ letter: power }]
nomials = []
currentPower = {}

# Filter the power combinations for only where they add up to n
powerCombinations = list(set(permutations([i for i in range(0, n + 1)] * m, m)))

for combo in powerCombinations:
	if sum(combo) != n:
		continue

	powers = {}

	for i in range(len(combo)):
		letter = selectedLetters[i]
		powers[letter] = combo[i]

	nomials.append(powers)

formattedTerms = []

for nomial in nomials:
	coefficient = multinomialCoefficient(n, *nomial.values())
	term = ''

	if coefficient == 0:
		continue
	elif coefficient != 1:
		term += str(coefficient)

	for letter in nomial:
		power = nomial[letter]

		if power == 1:
			term += letter
		elif power > 0:
			powerString = ''

			for digit in str(power):
				powerString += superscript[int(digit)]

			term += '%s%s' % (letter, powerString)

	formattedTerms.append(term)

print(' + '.join(formattedTerms))


from common.python.utils import log_utils
from kernel.components.featurecalculation.base.calculation_properties import CalculationProperties
from kernel.transfer.variables.transfer_class.vert_feature_calculation_transfer_variable import \
    VertFeatureCalculationTransferVariable
from kernel.utils import consts

LOGGER = log_utils.get_logger()

class Promoter(object):
    # noinspection PyAttributeOutsideInit
    def register_calculation_trans_vars(self, transfer_variable):
        self._provider_calculate_cols_transfer = transfer_variable.provider_calculate_cols
        self._result_left_cols_transfer = transfer_variable.result_left_cols

    def sync_calculate_cols(self, suffix=tuple()):
        provider_calculate_col_names = self._provider_calculate_cols_transfer.get(idx=-1, suffix=suffix)
        provider_calculation_params = []
        for provider_id, calculate_names in enumerate(provider_calculate_col_names):
            provider_calculation_properties = CalculationProperties()
            provider_calculation_properties.set_header(calculate_names)
            provider_calculation_properties.set_last_left_col_indexes([x for x in range(len(calculate_names))])
            provider_calculation_properties.add_calculate_col_names(calculate_names)
            provider_calculation_params.append(provider_calculation_properties)
        return provider_calculation_params

    def sync_calculate_results(self, provider_calculation_inner_params, suffix=tuple()):
        for provider_id, provider_calculate_results in enumerate(provider_calculation_inner_params):
            LOGGER.debug(
                "Send provider calculated result, left_col_names: {}".format(provider_calculate_results.left_col_names))
            self._result_left_cols_transfer.remote(provider_calculate_results.left_col_names,
                                                   role=consts.PROVIDER,
                                                   idx=provider_id,
                                                   suffix=suffix)

class Provider(object):
    # noinspection PyAttributeOutsideInit
    def register_calculation_trans_vars(self, transfer_variable: VertFeatureCalculationTransferVariable):
        self._provider_calculate_cols_transfer = transfer_variable.provider_calculate_cols
        self._result_left_cols_transfer = transfer_variable.result_left_cols

    def sync_calculate_cols(self, encoded_names, suffix=tuple()):
        self._provider_calculate_cols_transfer.remote(encoded_names,
                                                      role=consts.PROMOTER,
                                                      idx=0,
                                                      suffix=suffix)

    def sync_calculate_results(self, calculation_param, decode_func=None, suffix=tuple()):
        left_cols_names = self._result_left_cols_transfer.get(idx=0, suffix=suffix)
        for col_name in left_cols_names:
            if decode_func is not None:
                col_name = decode_func(col_name)
            calculation_param.add_left_col_name(col_name)
        LOGGER.debug("Received provider calculated result, original left_cols: {},"
                     " left_col_names: {}".format(left_cols_names, calculation_param.left_col_names))


import numpy as np
from numpy.random import binomial
import matplotlib.pyplot as plt
import matplotlib
import pyDIFRATE as DR
ef=DR.frames
vft=ef.vft

#%% List of examples
"""
1) Correlation due to poorly defined frame
2) With and without timescale separation
3) Uncorrelated and correlated
4) Correlation due to geometry
"""

#%% Some useful functions

"""
calc_ct calculates the directly calculated correlation function and the product
of correlation functions
"""
def calc_ct(v,vXZ,vF,vFXZ=None):
    Ct=ef.Ct_D2inf(v,cmpt='00',mode='ct')

    Ct0pf,Af=ef.Ct_D2inf(v,vXZ,nuZ_F=vF,nuXZ_F=vFXZ,cmpt='0p')
    Ctf=Ct0pf[2].real

    Ctp0F=ef.Ct_D2inf(v,vXZ,nuZ_f=vF,nuXZ_f=vFXZ,cmpt='p0',mode='ct')
    CtF=np.sum(Af*Ctp0F.T,1).T.real/Af[2].real

    Ctp=Ctf*CtF
    return Ct.real,Ctp

#xl is sort of like a formatting string, inserting prefixes and units
xl=DR.tools.nice_str('{:q1}')
xl.unit='s'

#Set the default font size in matplotlib
matplotlib.rcParams['font.size']=8

"""
plot_ct plots the directly calculated correlation function and the product of
two correlation functions separated by a frame into a given axis
"""
def plot_ct(ax,v,vXZ,vF,vFXZ=None,dt=.005):
    t=np.arange(v.shape[1])*dt
    Ct,Ctp=calc_ct(v,vXZ,vF,vFXZ)
    ax.cla()
    ax.semilogx(t[1:],Ct[1:],color='red')
    ax.semilogx(t[1:],Ctp[1:],color='black',linestyle=':')
    ax.set_ylim([0,1])
    ax.set_xticks(np.logspace(-2,2,5))
    ax.set_xlim([t[1],250])
    s=ax.get_subplotspec()
    if s.is_first_col():
        ax.set_ylabel(r'$C(t)$')
    else:
        ax.set_yticklabels([])
    if s.is_last_row():
        ax.set_xlabel(r'$t$/ns')
        ax.set_xticklabels([xl.format(t*1e-9) if np.mod(k,2)==0 else '' for k,t in enumerate(ax.get_xticks())])
#        ax.set_xticklabels([xl.format(t*1e-9) for k,t in enumerate(ax.get_xticks())])
    else:
        ax.set_xticklabels([])
    if s.is_first_col() and s.is_first_row():
        ax.legend(['direct','product'],loc='upper right')

"""
sym_hop generates a trajectory with hopping between nsites (default 3), where
all sites are populated equally
"""
def sym_hop(tau,theta=np.pi/6,n=1e5,dt=.005,nsites=3):
    n=int(n)
    p=dt/tau
    state=np.mod((binomial(1,p,n)*(1-2*binomial(1,.5,n))).cumsum(),3).astype(int)
    v0=np.array([[np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi),np.cos(theta)] \
         for phi in np.linspace(0,2*np.pi,nsites,endpoint=False)])
    v=v0.T[:,state]
    vXZ=v0.T[:,state]
    return v,vXZ

"""
two_site_hop generates a trajectory with hops  between two sites
"""
def two_site_hop(tau,theta=np.pi/4,phi=0,n=1e5,dt=.005):
    n=int(n)
    p=dt/tau
    state=np.mod(binomial(1,p,n).cumsum(),2).astype(int)
    v0=np.array([[0,0,1],[np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi),np.cos(theta)]])
    v=v0.T[:,state]
    return v,np.repeat(np.atleast_2d([np.cos(phi),np.sin(phi),0]).T,n,axis=1)

"""
corr_met_2site generates two trajectories resulting from both a three-site hopping
and a two-site hopping, where the two-site hop only occurs for a particular
orientaion of the three site hoping (correlated motion)
"""
def corr_met_2site(tau_m,tau_h,theta_m=np.pi/6,theta_h=np.pi/4,n=1e5,dt=.005):
    n=int(n)
    p=dt/tau_m
    state=np.mod((binomial(1,p,n)*(1-2*binomial(1,.5,n))).cumsum(),3).astype(int)
    v0=np.array([[np.sin(theta_m)*np.cos(phi),np.sin(theta_m)*np.sin(phi),np.cos(theta_m)] \
         for phi in np.linspace(0,2*np.pi,3,endpoint=False)])
    vm=v0.T[:,state]
    vXZm=v0.T[:,state]

    p=3*dt/tau_h
    hop=binomial(1,p,n)
    hop[state!=0]=0
    state=np.mod(hop.cumsum(),2).astype(int)
    phi=0
    v0=np.array([[0,0,1],[np.sin(theta_h)*np.cos(phi),np.sin(theta_h)*np.sin(phi),np.cos(theta_h)]])
    vh=v0.T[:,state]

    return vm,vXZm,vh,np.repeat(np.atleast_2d([np.cos(phi),np.sin(phi),0]).T,n,axis=1)

"""
corr_met_2site2 generates two trajectories resulting from both a three-site hopping
and a two-site hopping, where the three-site hopping only occurs for one of the
two two-site hops
"""
def corr_met_2site2(tau_m,tau_h,theta_m=np.pi/6,theta_h=np.pi/4,n=1e5,dt=.005):
    n=int(n)

    p=dt/tau_h
    hop=binomial(1,p,n)
    state=np.mod(hop.cumsum(),2).astype(int)
    phi=0
    v0=np.array([[0,0,1],[np.sin(theta_h)*np.cos(phi),np.sin(theta_h)*np.sin(phi),np.cos(theta_h)]])
    vh=v0.T[:,state]

    p=2*dt/tau_m
    hop=binomial(1,p,n)*(1-2*binomial(1,.5,n))
    hop[state!=0]=0
    state=np.mod(hop.cumsum(),3).astype(int)
    v0=np.array([[np.sin(theta_m)*np.cos(phi),np.sin(theta_m)*np.sin(phi),np.cos(theta_m)] \
         for phi in np.linspace(0,2*np.pi,3,endpoint=False)])
    vm=v0.T[:,state]
    vXZm=v0.T[:,state]

    return vm,vXZm,vh,np.repeat(np.atleast_2d([np.cos(phi),np.sin(phi),0]).T,n,axis=1)

"""
Takes two trajectories resulting from individual motions and generates the motion
resulting from both motions acting together on an NMR interaction
"""
def v_overall(v1,vXZ1,v2,v2XZ=None):
    sc2=vft.getFrame(v2,v2XZ)
    return vft.R(v1,*sc2),vft.R(vXZ1,*sc2)

#%% Set up plots
fig=plt.figure('Correlation Functions')
fig.clear()
ax=[fig.add_subplot(2,5,k+1) for k in [0,5,1,6,2,7,3,8,4,9]]
fig.set_size_inches([180/25.4,100/25.4])

#%% Some default values
tau_m=.05
tau_h=5
dt=.005
n=4e5

"Example 1: Badly defined frame (frame uncorrelated with motion)"
vm,vmXZ=sym_hop(tau=tau_m,n=n)
vh,vhXZ=two_site_hop(tau=tau_h,n=n)

v,vXZ=v_overall(vm,vmXZ,vh,vhXZ)
plot_ct(ax[0],v,vXZ,vh,vhXZ)

vh,vhXZ=two_site_hop(tau=tau_h,n=n)  #Here we generate an uncorrelated motion
plot_ct(ax[1],v,vXZ,vh,vhXZ)

"Example 2: With and without timescale separation"
vm,vmXZ=sym_hop(tau=tau_m,n=n)
vh,vhXZ=two_site_hop(tau=tau_h,n=n)

v,vXZ=v_overall(vm,vmXZ,vh,vhXZ)
plot_ct(ax[2],v,vXZ,vh,vhXZ)

vm,vmXZ=sym_hop(tau=5,n=n)
vh,vhXZ=two_site_hop(tau=.05,n=n)

v,vXZ=v_overall(vm,vmXZ,vh,vhXZ)
plot_ct(ax[3],v,vXZ,vh,vhXZ)

"Example 3: Uncorrelated vs. correlated"
vm,vmXZ=sym_hop(tau=tau_m,n=n)
vh,vhXZ=two_site_hop(tau=tau_h,n=n)

v,vXZ=v_overall(vm,vmXZ,vh,vhXZ)
plot_ct(ax[4],v,vXZ,vh,vhXZ)

vm,vmXZ,vh,vhXZ=corr_met_2site(tau_m=tau_m,tau_h=tau_h,n=n)

v,vXZ=v_overall(vm,vmXZ,vh,vhXZ)
plot_ct(ax[5],v,vXZ,vh,vhXZ)

"Example 4: Uncorrelated vs. correlated (version 2)"
vm,vmXZ=sym_hop(tau=tau_m,n=n)
vh,vhXZ=two_site_hop(tau=tau_h,n=n)

v,vXZ=v_overall(vm,vmXZ,vh,vhXZ)
plot_ct(ax[6],v,vXZ,vh,vhXZ)

vm,vmXZ,vh,vhXZ=corr_met_2site2(tau_m=tau_m,tau_h=tau_h,n=n)

v,vXZ=v_overall(vm,vmXZ,vh,vhXZ)
plot_ct(ax[7],v,vXZ,vh,vhXZ)

"Example 5: Correlation due to geometry"
v1,v1XZ=two_site_hop(tau=tau_m,n=n)
v2,v2XZ=two_site_hop(tau=tau_h,n=n)
v,vXZ=v_overall(v1,v1XZ,v2,v2XZ)
plot_ct(ax[8],v,vXZ,v2,v2XZ)

v1,v1XZ=two_site_hop(tau=tau_m,phi=np.pi/2,n=n)
v2,v2XZ=two_site_hop(tau=tau_h,n=n)
v,vXZ=v_overall(v1,v1XZ,v2,v2XZ)
plot_ct(ax[9],v,vXZ,v2,v2XZ)

fig.tight_layout()

plt.show()


"""
# Slack Block Message Builder

TODO:
    - track number of characters, raise error after 4k
    - attach text, fields

This class is intended to be used with a channel-specific slack webhook.
More information can be found here: https://app.slack.com/block-kit-builder.

## Messages are not configured to send in development

Messages or alerts sent using `send_message` or `on_failure_callback` will only
send if a Slack connection is defined and we are running in production. You can
manually override this for testing purposes by setting the `SLACK_MESSAGE_OVERRIDE`
variable to `true` in the Airflow UI.

## Send multiple messages - payload is reset after sending

>>> slack = SlackMessage(username="Multi-message Test")

>>> slack.add_text("message 1")
>>> slack.send()

>>> slack.add_text("message 2")
>>> slack.send()

## Embed images, plus context

>>> slack = SlackMessage(username="Blocks - Referenced Images")

>>> slack.add_context(":pika-love: context stuff *here*")

>>> msg = "Example message with new method of embedding images and divider below."

>>> slack.add_text(msg)
>>> slack.add_divider()
>>> slack.add_image(url1, title=img1_title, alt_text="img #1")
>>> slack.add_image(url2, title=img2_title, alt_text="img #2")
>>> slack.send()

## Dev Tools
>>> # prints current payload
>>> slack.display()

>>> # get payload dict
>>> payload = slack.payload

"""

import json
import logging
import re
from collections.abc import Callable
from os.path import basename
from typing import Any

from airflow.exceptions import AirflowNotFoundException
from airflow.models import Variable
from airflow.providers.http.hooks.http import HttpHook
from requests import Response
from typing_extensions import NotRequired, TypedDict

SLACK_NOTIFICATIONS_CONN_ID = "slack_notifications"
SLACK_ALERTS_CONN_ID = "slack_alerts"
JsonDict = dict[str, Any]
log = logging.getLogger(__name__)

class SilencedSlackNotification(TypedDict):
    """
    Configuration for a silenced Slack notification.

    issue: A link to a GitHub issue which describes why the notification
           is silenced and tracks resolving the problem.
    predicate: Slack notifications whose text or username contain the
               predicate will be silenced. Matching is case-insensitive.
    task_id_pattern: A regex pattern that matches the task_id of the task
                     that triggered the notification. (Optional)
    """

    issue: str
    predicate: str
    task_id_pattern: NotRequired[str | None]

class SlackMessage:
    """Slack Block Message Builder"""

    def __init__(
        self,
        username: str = "Airflow",
        icon_emoji: str = ":airflow:",
        unfurl_links: bool = True,
        unfurl_media: bool = True,
        http_conn_id: str = SLACK_NOTIFICATIONS_CONN_ID,
    ):
        self.http = HttpHook(method="POST", http_conn_id=http_conn_id)
        self.blocks = []
        self._context = {}
        self._payload: dict[str, Any] = {
            "username": username,
            "unfurl_links": unfurl_links,
            "unfurl_media": unfurl_media,
        }

        if icon_emoji:
            self._payload["icon_emoji"] = icon_emoji

        self._base_payload = self._payload.copy()

    @staticmethod
    def _text_block(message: str, plain_text: bool) -> JsonDict:
        text_type = "plain_text" if plain_text else "mrkdwn"
        return {"type": text_type, "text": message}

    @staticmethod
    def _image_block(
        url: str, title: str | None = None, alt_text: str | None = None
    ) -> JsonDict:
        img = {"type": "image", "image_url": url}
        if title:
            img.update({"title": {"type": "plain_text", "text": title}})
        if alt_text:
            img["alt_text"] = alt_text
        else:
            img["alt_text"] = basename(url)
        return img

    def clear(self) -> None:
        """Clear all stored data to prime the instance for a new message."""
        self.blocks = []
        self._context = {}
        self._payload = self._base_payload.copy()

    def display(self) -> None:
        """Print current payload, intended for local development only."""
        if self._context:
            self._append_context()
        self._payload.update({"blocks": self.blocks})
        print(json.dumps(self._payload, indent=4))

    @property
    def payload(self) -> JsonDict:
        payload = self._payload.copy()
        payload.update({"blocks": self.blocks})
        return payload

    ####################################################################################
    # Context
    ####################################################################################

    def _append_context(self) -> None:
        self.blocks.append(self._context.copy())
        self._context = {}

    def _add_context(
        self, body_generator: Callable, main_text: str, **options: Any
    ) -> None:
        if not self._context:
            self._context = {"type": "context", "elements": []}
        body = body_generator(main_text, **options)
        if len(self._context["elements"]) < 10:
            self._context["elements"].append(body)
        else:
            raise ValueError("Unable to include more than 10 context elements")

    def add_context(self, message: str, plain_text: bool = False) -> None:
        """Display context above or below a text block."""
        self._add_context(
            self._text_block,
            message,
            plain_text=plain_text,
        )

    def add_context_image(self, url: str, alt_text: str | None = None) -> None:
        """Display context image inline within a text block."""
        self._add_context(self._image_block, url, alt_text=alt_text)

    ####################################################################################
    # Blocks
    ####################################################################################

    def _add_block(self, block: JsonDict) -> None:
        if self._context:
            self._append_context()
        self.blocks.append(block)

    def add_divider(self) -> None:
        """Add a divider between blocks."""
        self._add_block({"type": "divider"})

    def add_text(self, message: str, plain_text: bool = False) -> None:
        """Add a text block, using markdown or plain text."""
        text = self._text_block(message, plain_text)
        self._add_block({"type": "section", "text": text})

    def add_image(
        self, url, title: str | None = None, alt_text: str | None = None
    ) -> None:
        """Add an image block, with optional title and alt text."""
        self._add_block(self._image_block(url, title, alt_text))

    ####################################################################################
    # Send
    ####################################################################################

    def send(self, notification_text: str = "Airflow notification") -> Response:
        """
        Send message payload to the channel configured by the webhook.

        Any notification text provided will only show up as the content within
        the notification pushed to various devices.
        """
        if not self._context and not self.blocks:
            raise ValueError("Nothing to send!")

        if self._context:
            self._append_context()
        self._payload.update({"blocks": self.blocks})
        self._payload["text"] = notification_text

        response = self.http.run(
            endpoint=None,
            data=json.dumps(self._payload),
            headers={"Content-type": "application/json"},
            extra_options={"verify": True},
        )

        self.clear()
        response.raise_for_status()
        return response

def should_silence_message(
    text: str,
    username: str,
    dag_id: str,
    task_id: str | None = None,
):
    """
    Determine if a Slack message should be silenced.

    Checks the `SILENCED_SLACK_NOTIFICATIONS` Airflow variable to see if the message
    should be silenced for this DAG.
    """
    # Match on message text and username
    message = username + text

    # Get the configuration for silenced messages for this DAG
    silenced_notifications: list[SilencedSlackNotification] = Variable.get(
        "SILENCED_SLACK_NOTIFICATIONS", default_var={}, deserialize_json=True
    ).get(dag_id, [])

    if not bool(silenced_notifications):
        # No silenced notifications for this DAG, exit early
        return False
    matches = []
    for notification in silenced_notifications:
        # Check that the predicate matches whatever message was raised
        predicate_matches = notification["predicate"].lower() in message.lower()
        # Check that the task ID matches the predicate _if both were supplied_,
        # not all messages supply a task ID but all exception-based alerts do.
        pattern = notification.get("task_id_pattern")
        task_id_matches = (task_id is None or pattern is None) or (
            task_id and pattern and re.search(pattern, task_id)
        )
        matches.append(predicate_matches and task_id_matches)
    return any(matches)

def should_send_message(
    text: str,
    username: str,
    dag_id: str,
    http_conn_id: str = SLACK_NOTIFICATIONS_CONN_ID,
    task_id: str | None = None,
):
    """
    Determine if a Slack message should actually be sent.

    Returns True if:
      * A Slack connection is defined
      * The DAG is not configured to silence messages of this type
      * We are in the prod env OR the message override is set.
    """
    # Exit early if no slack connection exists
    hook = HttpHook(http_conn_id=http_conn_id)
    try:
        hook.get_conn()
    except AirflowNotFoundException:
        return False

    # Exit early if this DAG is configured to skip Slack messaging
    if should_silence_message(text, username, dag_id, task_id):
        log.info(f"Skipping Slack notification for {dag_id}::{task_id}.")
        return False

    # Exit early if we aren't on production or if force alert is not set
    environment = Variable.get("ENVIRONMENT", default_var="dev")
    force_message = Variable.get(
        "SLACK_MESSAGE_OVERRIDE", default_var=False, deserialize_json=True
    )
    return environment == "prod" or force_message

def send_message(
    text: str,
    dag_id: str,
    username: str = "Airflow",
    icon_emoji: str = ":airflow:",
    markdown: bool = True,
    unfurl_links: bool = False,
    unfurl_media: bool = False,
    http_conn_id: str = SLACK_NOTIFICATIONS_CONN_ID,
    task_id: str | None = None,
) -> None:
    """Send a simple slack message, convenience message for short/simple messages."""
    log.info(text)
    if not should_send_message(
        text, username, dag_id, http_conn_id=http_conn_id, task_id=task_id
    ):
        return

    environment = Variable.get("ENVIRONMENT", default_var="dev")
    s = SlackMessage(
        f"{username} | {environment}",
        icon_emoji,
        unfurl_links,
        unfurl_media,
        http_conn_id=http_conn_id,
    )
    s.add_text(text, plain_text=not markdown)
    s.send(text)

def send_alert(
    text: str,
    dag_id: str,
    username: str = "Airflow Alert",
    icon_emoji: str = ":airflow:",
    markdown: bool = True,
    unfurl_links: bool = False,
    unfurl_media: bool = False,
    task_id: str | None = None,
):
    """
    Send a slack alert.

    Wrapper for send_message that allows sending a message to the configured alerts
    channel instead of the default notification channel.
    """
    send_message(
        text,
        dag_id,
        username,
        icon_emoji,
        markdown,
        unfurl_links,
        unfurl_media,
        http_conn_id=SLACK_ALERTS_CONN_ID,
        task_id=task_id,
    )

def on_failure_callback(context: dict) -> None:
    """
    Send an alert out regarding a failure to Slack.

    Errors are only sent out in production and if a Slack connection is defined.
    """
    # Get relevant info
    ti = context["task_instance"]
    dag_id = ti.dag_id
    task_id = ti.task_id
    logical_date = context["logical_date"]
    exception: Exception | None = context.get("exception")
    exception_message = ""

    if exception:
        # Forgo the alert on upstream failures
        if (
            isinstance(exception, Exception)
            and "Upstream task(s) failed" in exception.args
        ):
            log.info("Forgoing Slack alert due to upstream failures")
            return
        exception_message = f"""
*Exception*: {exception}
*Exception Type*: `{exception.__class__.__module__}.{exception.__class__.__name__}`
"""

    message = f"""
*DAG*: `{dag_id}`
*Task*: `{task_id}`
*Logical Date*: {logical_date.strftime('%Y-%m-%dT%H:%M:%SZ')}
*Log*: {ti.log_url}
{exception_message}
"""
    send_alert(
        message,
        dag_id=dag_id,
        task_id=task_id,
        username="Airflow DAG Failure",
    )


import cv2
import cv2.aruco as aruco

img1 = cv2.imread("D:\RONY\IIT Dhanbad\Atulya\My Project\Ha.jpg")
img2= cv2.imread("D:\RONY\IIT Dhanbad\Atulya\My Project\HaHa.jpg")
img3 = cv2.imread("D:\RONY\IIT Dhanbad\Atulya\My Project\LMAO.jpg")
img4 = cv2.imread("D:\RONY\IIT Dhanbad\Atulya\My Project\XD.jpg")

def findAruco(img):
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    key=getattr(aruco,f'DICT_5X5_250')
    arucoDict = aruco.Dictionary_get(key)
    arucoParam = aruco.DetectorParameters_create()

    (corners,ids,rejected) =  cv2.aruco.detectMarkers(img,arucoDict,parameters=arucoParam)

    if len(corners) > 0 :
       ids= ids.flatten()

       for(markerCorner,markerId) in zip(corners,ids):
           corners = markerCorner.reshape((4,2))
           (topLeft,topRight,bottomRight,bottomLeft) = corners

           topRight= (int(topRight[0]),int(topRight[1]))
           topLeft= (int(topLeft[0]),int(topLeft[1]))
           bottomLeft= (int(bottomLeft[0]),int(bottomLeft[1]))
           bottomRight= (int(bottomRight[0]),int(bottomRight[1]))

           cx=int((topLeft[0]+bottomRight[0])/2.0)
           cy=int((topLeft[1]+bottomRight[1])/2.0)

           cv2.circle(img,(cx,cy),5,(255,0,0),-1)
           cv2.putText(img,str(markerId),(cx,cy-10),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2,cv2.LINE_AA)
           return (markerId)

a=findAruco(img4)
print(a)
cv2.imshow("output",img4)
print(img4.shape)
cv2.waitKey(0)
cv2.destroyAllWindows()


import setuptools

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

setuptools.setup(
    name="keras-yolo3",
    version="1.0",
    author="qqwweee",
    description="A Keras implementation of YOLOv3 (Tensorflow backend) inspired by allanzelener/YAD2K",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/qqwweee/keras-yolo3",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.5',
)


# coding: utf-8
import os
import cv2
import requests
import json
import base64
import numpy as np
import time
import threading
import re

#分割服务的地址
IMAGE_SEG_URL = 'http://xxx.xxx.xxx.xxx:8010/ImageSegService/inference'

class ClientThread(threading.Thread):
    def __init__(self, thread_id, image_data_repo):
        threading.Thread.__init__(self)
        self.__thread_id = thread_id
        self.__image_data_repo = image_data_repo

    def run(self):
        self.__request_image_seg_service()

    def __request_image_seg_service(self):
        # 持续发送150个请求
        for i in range(1, 151):
            print("Epoch %d, thread %d" % (i, self.__thread_id))
            self.__benchmark_test()

    # benchmark test
    def __benchmark_test(self):
        start = time.time()
        for image_filename in self.__image_data_repo:
            mask_mat_list = self.__request_predictor_server(image_filename)
            input_img = self.__image_data_repo.get_image_matrix(image_filename)
            # 将获得的mask matrix转换成可视化图像，并在当前目录下保存为图像文件
            # 如果进行压测，可以把这句话注释掉
            for j in range(len(mask_mat_list)):
                self.__visualization(mask_mat_list[j], image_filename, 2, input_img)
        latency = time.time() - start
        print("total latency = %f s" % (latency))

    # 对预测结果进行可视化
    # input_raw_mask 是server返回的预测结果
    # output_img 是可视化结果存储路径
    def __visualization(self, mask_mat, output_img, num_cls, input_img):
        # ColorMap for visualization more clearly
        n = num_cls
        color_map = []
        for j in range(n):
            lab = j
            a = b = c = 0
            color_map.append([a, b, c])
            i = 0
            while lab:
                color_map[j][0] |= (((lab >> 0) & 1) << (7 - i))
                color_map[j][1] |= (((lab >> 1) & 1) << (7 - i))
                color_map[j][2] |= (((lab >> 2) & 1) << (7 - i))
                i += 1
                lab >>= 3
        im = cv2.imdecode(mask_mat, 1)
        w, h, c = im.shape
        im2 = cv2.resize(im, (w, h))
        im = im2
        # I = aF + (1-a)B
        a = im / 255.0
        im = a * input_img + (1 - a) * [255, 255, 255]
        cv2.imwrite(output_img, im)

    def __request_predictor_server(self, input_img):
        data = {"instances": [self.__get_item_json(input_img)]}
        response = requests.post(IMAGE_SEG_URL, data=json.dumps(data))
        try:
            response = json.loads(response.text)
            prediction_list = response["prediction"]
            mask_response_list = [mask_response["info"] for mask_response in prediction_list]
            mask_raw_list = [json.loads(mask_response)["mask"] for mask_response in mask_response_list]
        except Exception as err:
            print("Exception[%s], server_message[%s]" % (str(err), response.text))
            return None
        # 使用 json 协议回复的包也是 base64 编码过的
        mask_binary_list = [base64.b64decode(mask_raw) for mask_raw in mask_raw_list]
        m = [np.fromstring(mask_binary, np.uint8) for mask_binary in mask_binary_list]
        return m

    # 请求预测服务
    # input_img 要预测的图片列表
    def __get_item_json(self, input_img):
        # 使用 http 协议请求服务时, 请使用 base64 编码发送图片
        item_binary_b64 = str(base64.b64encode(self.__image_data_repo.get_image_binary(input_img)), 'utf-8')
        item_size = len(item_binary_b64)
        item_json = {
            "image_length": item_size,
            "image_binary": item_binary_b64
        }
        return item_json

def create_thread_pool(thread_num, image_data_repo):
    return [ClientThread(i + 1, image_data_repo) for i in range(thread_num)]

def run_threads(thread_pool):
    for thread in thread_pool:
        thread.start()

    for thread in thread_pool:
        thread.join()

class ImageDataRepo:
    def __init__(self, dir_name):
        print("Loading images data...")
        self.__data = {}
        pattern = re.compile(".+\.(jpg|jpeg)", re.I)
        if os.path.isdir(dir_name):
            for image_filename in os.listdir(dir_name):
                if pattern.match(image_filename):
                    full_path = os.path.join(dir_name, image_filename)
                    fp = open(full_path, mode="rb")
                    image_binary_data = fp.read()
                    image_mat_data = cv2.imread(full_path)
                    self.__data[image_filename] = (image_binary_data, image_mat_data)
        else:
            raise Exception("Please use directory to initialize");
        print("Finish loading.")
    def __iter__(self):
        for filename in self.__data:
            yield filename

    def get_image_binary(self, image_name):
        return self.__data[image_name][0]

    def get_image_matrix(self, image_name):
        return self.__data[image_name][1]

if __name__ == "__main__":
    #preprocess
    IDR = ImageDataRepo("images")
    thread_pool = create_thread_pool(thread_num=1, image_data_repo=IDR)
    run_threads(thread_pool)


from todoist_api_python.models import Task, Due
from typing import Union, Dict
from datetime import datetime, date

from src.functions import convert_dt
import config

class ExtendedTask(Task):

    def __init__(self,
                 comment_count,
                 is_completed,
                 content,
                 created_at,
                 creator_id,
                 description,
                 id,
                 priority,
                 project_id,
                 section_id,
                 url,
                 assignee_id=None,
                 assigner_id=None,
                 due=None,
                 labels=None,
                 order=None,
                 parent_id=None,
                 is_deleted=None,
                 # Do NOT delete kwargs!
                 **kwargs):
        if due is not None:
            due = Due.from_dict(due)

        super().__init__(comment_count=comment_count,
                         is_completed=is_completed,
                         content=content,
                         created_at=created_at,
                         creator_id=creator_id,
                         description=description,
                         id=id,
                         priority=priority,
                         project_id=project_id,
                         section_id=section_id,
                         url=url,
                         assignee_id=assignee_id,
                         assigner_id=assigner_id,
                         due=due,
                         labels=labels,
                         order=order,
                         parent_id=parent_id)

        self.is_deleted = is_deleted

    @classmethod
    def extend(cls, task: Task):
        extended = cls(**task.to_dict())

        extended.is_deleted = False

        return extended

    @property
    def is_goal(self):
        return config.SPECIAL_LABELS['GOAL'] in self.labels

    @property
    def is_active(self):
        return bool(not self.is_completed and (self.is_active_with_due or
                                               self.is_active_no_due or
                                               self.is_active_goal))

    @property
    def is_active_goal(self):
        return bool(not self.is_completed and self.is_goal and self.priority in (3, 4))

    @property
    def is_active_with_due(self):
        return bool(not self.is_completed and self.priority in (3, 4) and self.due)

    @property
    def is_active_no_due(self):
        return bool(not self.is_completed and self.priority in (2, 4) and not self.due)

    @property
    def is_in_focus(self):
        if self.is_completed or self.is_goal:
            return False

        if self.is_active_no_due:
            return True

        if self.is_active_with_due:
            return datetime.strptime(self.due.date, config.TODOIST_DATE_FORMAT).date() <= datetime.now().date()

        return False

    @classmethod
    def from_dict(cls, obj):
        due: Union[Dict, None] = None

        due_dict = {k.split('.')[1]: v for k, v in obj.items() if k.startswith('due.')}

        if any(due_dict.values()):
            # in order to store dates consistently with original objects
            if due_dict['date'] is not None and isinstance(due_dict['date'], date):
                due_dict['date'] = due_dict['date'].strftime(config.TODOIST_DATE_FORMAT)
            if due_dict['datetime'] is not None and isinstance(due_dict['datetime'], datetime):
                due_dict['datetime'] = convert_dt(due_dict['datetime'])
            due = due_dict

        return cls(
            assignee_id=obj.get("assignee_id"),
            assigner_id=obj.get("assigner_id"),
            comment_count=obj["comment_count"],
            is_completed=obj["is_completed"],
            content=obj["content"],
            created_at=obj["created_at"],
            creator_id=obj["creator_id"],
            description=obj["description"],
            due=due,
            id=obj["id"],
            labels=obj.get("labels"),
            order=obj.get("order"),
            parent_id=obj.get("parent_id"),
            priority=obj["priority"],
            project_id=obj["project_id"],
            section_id=obj["section_id"],
            url=obj["url"],
            is_deleted=obj.get("is_deleted")
        )

    def to_dict(self):
        due: Union[dict, None] = None

        if self.due:
            due = self.due.to_dict()

        return {
            "assignee_id": self.assignee_id,
            "assigner_id": self.assigner_id,
            "comment_count": self.comment_count,
            "is_completed": self.is_completed,
            "content": self.content,
            "created_at": self.created_at,
            "creator_id": self.creator_id,
            "description": self.description,
            "due": due,
            "id": self.id,
            "labels": self.labels,
            "order": self.order,
            "parent_id": self.parent_id,
            "priority": self.priority,
            "project_id": self.project_id,
            "section_id": self.section_id,
            "sync_id": self.sync_id,
            "url": self.url,
            'is_deleted': self.is_deleted,
            'is_goal': self.is_goal,
            'is_active_goal': self.is_active_goal,
            'is_active_with_due': self.is_active_with_due,
            'is_active_no_due': self.is_active_no_due,
            'is_active': self.is_active,
            'is_in_focus': self.is_in_focus
        }


import os
import time
import sys

from unittest import skip

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException

from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core import mail
from django.conf import settings

from .server_tools import reset_database
from .server_tools import create_session_on_server
from .management.commands.create_session import create_pre_authenticated_session

BASE_DIR   = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.dirname(os.path.dirname(BASE_DIR))

GECKODRIVER_BIN = os.path.join( PARENT_DIR, 'bin' )
os.environ["PATH"]+=":"+GECKODRIVER_BIN

class Browser(webdriver.Firefox):
    firefox_path = "/usr/local/firefox/firefox"

    def __init__(self,wait_time=1):
        webdriver.Firefox.__init__(self,firefox_binary=FirefoxBinary(firefox_path=self.firefox_path))
        self.wait_time=1

    def wait_page(self):
        time.sleep(self.wait_time)

    def add_session(self,email,session_key,final_url):
        ## to set a cookie we need to first visit the domain.
        ## 404 pages load the quickest!
        self.get(final_url+"/404-not-found")
        self.wait_page()
        self.add_cookie(dict(
            name=settings.SESSION_COOKIE_NAME,
            value=session_key,
            path='/',
        ))
        self.get(final_url)
        self.wait_page()

class FunctionalTest(StaticLiveServerTestCase):
    wait_time=1

    def build_browser(self):
        browser = Browser(wait_time=self.wait_time)
        return browser

    def restart_browser(self):
        self.browser.quit()
        self.browser = Browser(wait_time=self.wait_time)

    @classmethod
    def setUpClass(cls):
        cls.emaildir=None
        cls.liveserver=False
        for arg in sys.argv:
            if 'liveserver' in arg:
                cls.server_host = arg.split('=')[1]
                cls.server_url = 'http://' + cls.server_host
                cls.liveserver=True
                cls.emaildir = "/srv/test.costruttoridimondi.org/var/mail"
        if cls.liveserver:
            return
        super().setUpClass()
        cls.server_url = cls.live_server_url
        cls.liveserver=False
        cls.emaildir=None

    @classmethod
    def tearDownClass(cls):
        if cls.liveserver: return
        #print(type(cls.live_server_url))
        # if cls.server_url == cls.live_server_url:
        super().tearDownClass()

    def setUp(self):
        if self.liveserver:
            reset_database(self.server_host)
        self.browser = Browser(wait_time=self.wait_time)

    def tearDown(self):
        self.browser.quit()

    def wait_for(self, function_with_assertion, timeout=-1):
        if timeout<=0: timeout=self.wait_time
        start_time = time.time()
        while time.time() - start_time < timeout:
            try:
                return function_with_assertion()
            except (AssertionError, WebDriverException):
                time.sleep(0.1)
        # one more try, which will raise any errors if they are outstanding
        return function_with_assertion()

    def wait_browser(self):
        time.sleep(self.wait_time)

    def wait_for_email(self, test_email, subject):
        if not self.liveserver:
            email = mail.outbox[0]
            self.assertIn(test_email, email.to)
            self.assertEqual(email.subject, subject)
            return email.body
        if self.emaildir:
            return self.wait_for_email_onfile(test_email,subject)
        return self.wait_for_email_pop3(test_email,subject)

    def wait_for_email_onfile(self, test_email, subject):
        subject_line = 'Subject: {}'.format(subject)
        email_list=os.listdir(self.emaildir)
        email_list.sort()
        if not email_list: return None
        email_file=os.path.join(self.emaildir,email_list[-1])
        fd=open(email_file,"r")
        body=fd.read()
        fd.close()
        return body

    def wait_for_email_pop3(self, test_email, subject):
        subject_line = 'Subject: {}'.format(subject)
        email_id = None
        start = time.time()
        inbox = poplib.POP3_SSL('pop.mail.yahoo.com')
        try:
            inbox.user(test_email)
            inbox.pass_(os.environ['YAHOO_PASSWORD'])
            while time.time() - start < 60:
                count, _ = inbox.stat()
                for i in reversed(range(max(1, count - 10), count + 1)):
                    print('getting msg', i)
                    _, lines, __ = inbox.retr(i)
                    lines = [l.decode('utf8') for l in lines]
                    print(lines)
                    if subject_line in lines:
                        email_id = i
                        body = '\n'.join(lines)
                        return body
                time.sleep(5)
        finally:
            if email_id:
                inbox.dele(email_id)
            inbox.quit()

    def get_session_key(self,email):
        if self.liveserver:
            session_key = create_session_on_server(self.server_host, email)
        else:
            session_key = create_pre_authenticated_session(email)
        return session_key

    def create_session(self,email):
        session_key=self.get_session_key(email)
        self.browser.add_session(email,session_key,self.server_url)

    def create_pre_authenticated_session(self, browser, email, final_url=None):
        if final_url==None: final_url=self.server_url
        session_key=self.get_session_key(email)
        browser.add_session(email,session_key,final_url)

class MultiuserFunctionalTest(FunctionalTest):
    def create_user_browser_with_session(self,email,size=None,position=None):
        user_browser = Browser(wait_time=self.wait_time)
        if email in self.browsers.keys():
            self.browsers[email].quit()
        if size:
            w,h=size
            user_browser.set_window_size(w,h)
        if position:
            x,y=position
            user_browser.set_window_position(x,y)
        session_key=self.get_session_key(email)
        user_browser.add_session(email,session_key,self.server_url)
        self.browsers[email]=user_browser
        return user_browser

    def set_browser(self,email,size=None,position=None):
        if email in self.browsers.keys():
            self.browser=self.browsers[email]
            if size:
                w,h=size
                self.browser.set_window_size(w,h)
            if position:
                x,y=position
                self.browser.set_window_position(x,y)
            return
        kwargs={}
        if size: kwargs["size"]=size
        if position: kwargs["position"]=position
        self.browser=self.create_user_browser_with_session(email,**kwargs)

    def setUp(self):
        if self.liveserver:
            reset_database(self.server_host)
        self.browsers = {}
        self.browser = None

    def tearDown(self):
        for browser in self.browsers.values():
            try:
                browser.quit()
            except:
                pass


import pytest

from snapcraft_legacy.storeapi import channels

class TestChannel:
    scenarios = (
        (
            "risk",
            dict(
                channel="edge",
                expected_track="latest",
                expected_risk="edge",
                expected_branch=None,
                expected_channel="edge",
            ),
        ),
        (
            "track/risk",
            dict(
                channel="11/candidate",
                expected_track="11",
                expected_risk="candidate",
                expected_branch=None,
                expected_channel="11/candidate",
            ),
        ),
        (
            "track/risk/branch",
            dict(
                channel="11/edge/patch-1",
                expected_track="11",
                expected_risk="edge",
                expected_branch="patch-1",
                expected_channel="11/edge/patch-1",
            ),
        ),
        (
            "risk/branch",
            dict(
                channel="edge/patch-2",
                expected_track="latest",
                expected_risk="edge",
                expected_branch="patch-2",
                expected_channel="edge/patch-2",
            ),
        ),
    )

    def test_channel(
        self, channel, expected_track, expected_risk, expected_branch, expected_channel
    ):
        c = channels.Channel(channel)

        assert c.track == expected_track
        assert c.risk == expected_risk
        assert c.branch == expected_branch
        assert str(c) == expected_channel
        assert repr(c), "'{}'".format(expected_channel)

class TestChannelTuple:
    scenarios = (
        (
            "risk",
            dict(
                track=None,
                risk="edge",
                branch=None,
                expected_track="latest",
                expected_channel="edge",
            ),
        ),
        (
            "track/risk",
            dict(
                track="11",
                risk="candidate",
                branch=None,
                expected_track="11",
                expected_channel="11/candidate",
            ),
        ),
        (
            "track/risk/branch",
            dict(
                track="11",
                risk="edge",
                branch="patch-1",
                expected_track="11",
                expected_channel="11/edge/patch-1",
            ),
        ),
        (
            "risk/branch",
            dict(
                track="latest",
                risk="edge",
                branch="patch-2",
                expected_track="latest",
                expected_channel="latest/edge/patch-2",
            ),
        ),
    )

    def test_channel(self, track, risk, branch, expected_track, expected_channel):
        c = channels.Channel.from_channel_tuple(track=track, risk=risk, branch=branch)
        assert c.track == expected_track
        assert c.risk == risk
        assert c.branch == branch
        assert str(c) == expected_channel
        assert repr(c), "'{}'".format(expected_channel)

class TestInvalidChannel:
    scenarios = (
        ("invalid risk", dict(channel="invalid-edge")),
        ("invalid track/risk", dict(channel="track/invalid-edge")),
        ("invalid track/risk/branch", dict(channel="track/invalid-edge/branch")),
        ("invalid tuple", dict(channel="start/track/invalid-edge/branch/end")),
    )

    def test_invalid(self, channel):
        with pytest.raises(RuntimeError):
            channels.Channel(channel)


# coding=utf-8
import functools
import random
import os
import json
import logging
import time
import pickle
import numpy as np
import torch

def timer(func):
    """
    function timer
    :param func:
    :return:
    """

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        end = time.time()
        print("{}total time{:.4f} second".format(func.__name__, end - start))
        return res

    return wrapper

def set_seed(seed=123):
    """
    Set random number seeds to ensure reproducible experiments
    :param seed:
    :return:
    """
    random.seed(seed)
    torch.manual_seed(seed)
    np.random.seed(seed)
    torch.cuda.manual_seed_all(seed)

def set_logger(log_path):
    """
    configure log
    :param log_path:s
    :return:
    """
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    if not any(handler.__class__ == logging.FileHandler for handler in logger.handlers):
        file_handler = logging.FileHandler(log_path)
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)d - %(message)s')
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    if not any(handler.__class__ == logging.StreamHandler for handler in logger.handlers):
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(logging.Formatter('%(message)s'))
        logger.addHandler(stream_handler)

def save_json(data_dir, data, desc):
    """save as json"""
    with open(os.path.join(data_dir, '{}.json'.format(desc)), 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def read_json(data_dir, desc):
    """read as json"""
    with open(os.path.join(data_dir, '{}.json'.format(desc)), 'r', encoding='utf-8') as f:
        data = json.load(f)
    return data

def save_pkl(data_dir, data, desc):
    """save .pkl"""
    with open(os.path.join(data_dir, '{}.pkl'.format(desc)), 'wb') as f:
        pickle.dump(data, f)

def read_pkl(data_dir, desc):
    """read .pkl"""
    with open(os.path.join(data_dir, '{}.pkl'.format(desc)), 'rb') as f:
        data = pickle.load(f)
    return data

def fine_grade_tokenize(raw_text, tokenizer):
    """
    The sequence tagging task BERT tokenizer may lead to tag offset,
    tokenize with char-level
    """
    tokens = []

    for _ch in raw_text:
        if _ch in [' ', '\t', '\n']:
            tokens.append('[BLANK]')
        else:
            if not len(tokenizer.tokenize(_ch)):
                tokens.append('[INV]')
            else:
                tokens.append(_ch)

    return tokens


import argparse
import os
import json
import torch
from load_data import Data
import pandas as pd
import numpy as np
from tqdm import tqdm
from model import DistMult, ComplEx, ConvE, TuckER

parser = argparse.ArgumentParser(
    description="Running Machine"
)
parser.add_argument('--model', default='tucker', help='Please provide a model to run')
parser.add_argument('--dataset', default='fb15k237', help='Please provide a dataset path')
parser.add_argument('--gpu', default='0', help='Please provide a gpu to assign the task')
parser.add_argument('--input', default='numeric', help='Please provide an input path')

def populate_estimate(model, test, suffix):
    ent, rel = [], []
    for i, row in test.iterrows():
        ent.append(ent2idx[row[0]])
        rel.append(rel2idx["Interval-" + row[1] + suffix])
    res = model(torch.LongTensor(ent), torch.LongTensor(rel))

    ind = test.columns.tolist().index(suffix)
    skips = 0
    for i, row in tqdm(test.iterrows()):
        try:
            candidates = list(filter(
                lambda x: row[1] in x,
                list(map(lambda x: idx2ent[x], [x.item() for x in torch.argsort(res[i], descending=True)[:50]]))
            ))
            test.iloc[i, ind] = medians[candidates[0]]
        except IndexError:
            skips += 1
            test.iloc[i, ind] = medians[row[1]]
    print('Skipped', skips)

def compute_result(test):
    res = []
    test['MAE'] = abs(test['estimate'] - test['value'])
    for p in test['label'].unique():
        sli = test[test['label'] == p]
        res.append({
            "Property": p,
            "MAE": round(sli['MAE'].mean(), 3 if 'height' in p else 1)
        })
    print(pd.DataFrame(res))

if __name__ == "__main__":

    torch.backends.cudnn.deterministic = True
    device = "cuda" if torch.cuda.is_available() else "cpu"

    args = parser.parse_args()
    os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)
    target = f'{args.input}/{args.dataset}'

    with open(f'{target}/{args.model}_entities.dict') as fd:
        ent2idx = json.load(fd)
    with open(f'{target}/{args.model}_relations.dict') as fd:
        rel2idx = json.load(fd)
    idx2ent = {v: k for k, v in ent2idx.items()}
    with open(f'{target}/medians.dict') as fd:
        medians = json.load(fd)

    d = Data(data_dir=f"{target}/", reverse=True)
    if args.model == "distmult":
        model = DistMult(d, 200, 200, **{"input_dropout": 0.2})
    elif args.model == "complex":
        model = ComplEx(d, 400, 400, **{"input_dropout": 0.2})
    elif args.model == "conve":
        model = ConvE(d, 200, 200, **{"input_dropout": 0.2,
                                      "hidden_dropout1": 0.3,
                                      "feature_map_dropout": 0.2,
                                      "use_bias": True,
                                      "hidden_size": 9728,
                                      "embedding_shape1": 20})
    elif args.model == "tucker":
        if "fb15k237" in args.dataset:
            model = TuckER(d, 200, 200, **{"input_dropout": 0.2,
                                           "hidden_dropout1": 0.4,
                                           "hidden_dropout2": 0.5,
                                           "device": device})
        else:
            model = TuckER(d, 200, 200, **{"input_dropout": 0.2,
                                           "hidden_dropout1": 0.2,
                                           "hidden_dropout2": 0.3,
                                           "device": device})
    else:
        print("Unsupported Model", args.model)
        exit()

    if torch.cuda.is_available():
        model.load_state_dict(torch.load(f"{target}/{args.model}.model"))
    else:
        model.load_state_dict(torch.load(f"{target}/{args.model}.model", map_location='cpu'))

    model.eval()

    if 'QOC' in args.dataset or 'FOC' in args.dataset:
        runs = ["_left", "_right"]
    else:
        exit()

    test = pd.read_csv(f'{target}/test_raw.txt', sep='\t', header=None)
    test.columns = ["node", "label", "value"]
    for suffix in runs:
        test[suffix] = np.nan
        populate_estimate(model, test, suffix)

    test["estimate"] = 0
    for suffix in runs:
        test["estimate"] += test[suffix]
    test["estimate"] /= len(runs)

    compute_result(test)


import pandas as pd

import re
import sys
from nltk.stem.porter import PorterStemmer

from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline

model = AutoModelForSequenceClassification.from_pretrained("savasy/bert-base-turkish-sentiment-cased")
tokenizer = AutoTokenizer.from_pretrained("savasy/bert-base-turkish-sentiment-cased")

sa = pipeline("sentiment-analysis", tokenizer=tokenizer, model=model)

def preprocess_word(word):
    # Remove punctuation
    word = word.strip('\'"?!,.():;')
    # Convert more than 2 letter repetitions to 2 letter
    # funnnnny --> funny
    word = re.sub(r'(.)\1+', r'\1\1', word)
    return word

def preprocess_text(text):
    processed_text = []

    text = text.lower()

    # Replace 2+ or more dots with space
    text = re.sub(r'\.{2,}', ' ', text)

    # Strip space, " and '
    text = text.strip(' "\'')

    text = re.sub(r'\s+', ' ', text)
    words = text.split()

    for word in words:
      word = preprocess_word(word)
      processed_text.append(word)

    return ' '.join(processed_text)

def sentiment_analysis(text):
    "True if positive"
    p = sa(str(text))
    return pd.Series([p[0]["label"], round(p[0]["score"],2)])


import pygame
from EmptyScreen import Empty
from MainGameScreen import MainGameScreen
from DefenderGameScreen import DefenderGameScreen
from MenuScreen import Menu

class Game():
    def __init__(self):
        pygame.mixer.pre_init(44100, 16, 2, 4096)
        pygame.font.init()
        pygame.init()
        diameter = 480
        self.pygameScreen = pygame.display.set_mode((diameter, diameter), pygame.FULLSCREEN)
        pygame.display.set_caption('Hyperpixel Game')#
        self.running = True
        self.mousePosition = (0, 0)
        self.mousePressed = False
        self.lastPressed = False
        self.screens = []
        self.currentScreen = 0
        self.pygame = pygame

    def setup(self):
        self.screens.append(Menu(self))
        self.screens.append(MainGameScreen(self))
        self.screens.append(DefenderGameScreen(self))

        self.getCurrentScreen().start()

    def run(self):
        while self.running:
            self.handleEvents()
            self.update()
            self.updateScreen()

    def handleEvents(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()

    def update(self):
        #self.mousePosition = pygame.mouse.get_pos()
        #self.mousePressed = pygame.mouse.get_pressed()[0]

        if not self.mousePressed is self.lastPressed:
            if self.mousePressed:
                self.getCurrentScreen().onClick(self.mousePosition[0], self.mousePosition[1])
            else:
                self.getCurrentScreen().onRelease(self.mousePosition[0], self.mousePosition[1])
        self.lastPressed = self.mousePressed

        self.getCurrentScreen().onUpdate()

    def updateScreen(self):
        self.pygameScreen.fill((0, 0, 0))

        # Draw the screen
        self.getCurrentScreen().onUpdateScreen()

        pygame.display.flip()

    def onHyperpixelTouch(self, touch_id, x, y, state):
        self.mousePosition = (x, y)
        self.mousePressed = state

    def getCurrentScreen(self):
        return self.screens[self.currentScreen]

    def loadScreen(self, screenIndex):
        self.getCurrentScreen().stop()
        self.currentScreen = screenIndex
        self.getCurrentScreen().start()

    def end(self):
        self.running = False


import fastapi
from pydantic.networks import EmailStr

from src.users import domain, models
from utils.providers import database

router = fastapi.APIRouter()

@router.get('/{email}', response_model=models.ReadUser)
async def get_user(
    email: EmailStr = fastapi.Path(...),
    database_provider: database.DatabaseProvider = fastapi.Depends(
        database.get_database_provider
    ),
):
    return await domain.RetrieveUserByEmailUseCase(
        database_provider, email
    ).execute()

@router.post('/', response_model=models.ReadUser)
async def create_user(
    payload: models.CreateUser = fastapi.Body(...),
    database_provider: database.DatabaseProvider = fastapi.Depends(
        database.get_database_provider
    ),
):
    return await domain.CreateUserUseCase(database_provider, payload).execute()

@router.patch('/{email}', response_model=models.ReadUser)
async def update_user(
    email: EmailStr = fastapi.Path(...),
    payload: models.EditUser = fastapi.Body(...),
    database_provider: database.DatabaseProvider = fastapi.Depends(
        database.get_database_provider
    ),
):
    return await domain.EditUserByEmailUseCase(
        database_provider, email, payload
    ).execute()