from flask import render_template, request, session
from flask import Blueprint
import flask
import flask_login
import time
import datetime
import sys
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# sys.path.append('../')

# Basic function
from ..app import db
from ..mail import sendEmail
# register blueprint
bp = flask.Blueprint('task', __name__)

# table record all the task and its property
class c_task_list(db.Model):
    __tablename__ = 'tb_task_list'
    id = db.Column(db.Integer, primary_key=True,
                   unique=True, autoincrement=True)
    task_id = db.Column(db.String(10))
    task_name = db.Column(db.String(200))
    pj_dpt = db.Column(db.String(20))
    task_type = db.Column(db.String(20))
    priority = db.Column(db.String(20))
    owner = db.Column(db.String(20))
    description = db.Column(db.String(1000))
    task_status = db.Column(db.String(20))
    log_by = db.Column(db.String(20))
    log_time = db.Column(db.String(20))
    update_time = db.Column(db.String(20))

# table record the update of the task
class c_task_content(db.Model):
    __tablename__ = 'tb_task_content'
    id = db.Column(db.Integer, primary_key=True,
                   unique=True, autoincrement=True)
    task_id = db.Column(db.String(10))
    task_seq = db.Column(db.Integer)
    update_name = db.Column(db.String(20))
    update_time = db.Column(db.String(20))
    time_consume = db.Column(db.Float)
    content = db.Column(db.String(2000))
    task_status = db.Column(db.String(20))
    file_qty = db.Column(db.Integer)

# table record the task property change for history tracking
class c_task_log(db.Model):
    __tablename__ = 'tb_task_log'
    id = db.Column(db.Integer, primary_key=True,
                   unique=True, autoincrement=True)
    task_id = db.Column(db.String(10))
    property = db.Column(db.String(20))
    name = db.Column(db.String(20))
    change_time = db.Column(db.String(20))
    old = db.Column(db.String(500))
    new = db.Column(db.String(500))

# table record the setting of the system
class c_task_config(db.Model):
    __tablename__ = 'tb_task_config'
    id = db.Column(db.Integer, primary_key=True,
                   unique=True, autoincrement=True)
    property = db.Column(db.String(20))
    setting = db.Column(db.String(20))

# table record the user access right
class c_task_role(db.Model):
    __tablename__ = 'tb_task_role'
    id = db.Column(db.Integer, primary_key=True,
                   unique=True, autoincrement=True)
    user_name = db.Column(db.String(20))
    property = db.Column(db.String(20))
    value = db.Column(db.String(20))

# table record the user's email
class c_task_user(db.Model):
    __tablename__ = 'tb_task_user'
    id = db.Column(db.Integer, primary_key=True,
                   unique=True, autoincrement=True)
    user_name = db.Column(db.String(20))
    email = db.Column(db.String(30))

def is_access(user_name, property1, val):
    result = 0
    if user_name:
        if val:
            filters = {
                c_task_role.user_name == user_name,
                c_task_role.property == property1,
                c_task_role.value == val
            }
            all_results = c_task_role.query.filter(*filters).all()
            if all_results:  # the resource's property user access match to the settinig
                result = 1
    return result

def send_email(title, task_id, content):
    try:
        all_results = c_task_list.query.filter(
            c_task_list.task_id == task_id).first()
        if all_results:
            to_addr = []
            user = c_task_user.query.filter(
                c_task_user.user_name == all_results.owner).first()
            if user:
                to_addr.append(user.email)
            user = c_task_user.query.filter(
                c_task_user.user_name == all_results.log_by).first()
            if user:
                to_addr.append(user.email)

            sendEmail(receivers=to_addr, subject=title,
                      content=content, sender='task@leadrive.com')

        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")

@bp.route('/')
@flask_login.login_required
def defaultPage():
    display_name = flask_login.current_user.displayName
    return render_template('/task/task_search.html', display_name=display_name)

@bp.route("/search")
@flask_login.login_required
def task_search():
    display_name = flask_login.current_user.displayName
    return render_template('/task/task_search.html', display_name=display_name)

@bp.route("/create")
@flask_login.login_required
def task_create():
    display_name = flask_login.current_user.displayName
    return render_template('/task/task_new.html', display_name=display_name)

@bp.route("/<task_id>")
@flask_login.login_required
def task_view(task_id):
    display_name = flask_login.current_user.displayName
    id1 = task_id.upper()
    return render_template('/task/task_view.html', task_id=id1, display_name=display_name)

# return the project & department the user can access

@bp.route("/role/get", methods=['POST'])
@flask_login.login_required
def task_role_get():

    property1 = request.form.get('property')
    user_name = flask_login.current_user.displayName
    all_results = c_task_role.query.filter(c_task_role.user_name == user_name, c_task_role.property == property1)\
        .all()

    if all_results:
        result_json = '['
        for i in all_results:
            result_json = result_json + '{' + '"setting":"' + i.value + '"},'
        status = '200'
        value_msg = 'get successfully!'
        result_json = result_json[0:len(result_json) - 1]
        result_json = result_json + ']'
    else:
        status = '401'
        value_msg = 'No Result Found!'
        result_json = '"No Data!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result

# return the config
# now only return the task_type of each project & department
@bp.route("/config/get", methods=['POST'])
def task_config_get():
    property1 = request.form.get('property')
    all_results = c_task_config.query.filter(
        c_task_config.property == property1).all()

    if all_results:
        result_json = '['
        for i in all_results:
            result_json = result_json + '{' + '"setting":"' + i.setting + '"},'
        status = '200'
        value_msg = 'get successfully!'
        result_json = result_json[0:len(result_json) - 1]
        result_json = result_json + ']'
    else:
        status = '401'
        value_msg = 'No Result Found!'
        result_json = '"No Data!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result

# create the new task
@bp.route("/list/new", methods=['POST'])
def task_list_new():
    if flask_login.current_user.displayName:  # if log in
        task_name = request.form.get('task_name')
        pj_dpt = request.form.get('pj_dpt')
        task_type = request.form.get('task_type')
        priority = request.form.get('priority')
        owner = request.form.get('owner')
        description = request.form.get('description')
        task_status = '1-新建'

        user_name = flask_login.current_user.displayName
        # check if can access the resource
        valid = is_access(user_name, 'pj_dpt', pj_dpt)
        if valid == 1:
            log_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            update_time = ''
            task_id = 'TK' + time.strftime("%y", time.localtime())
            return_id = c_task_list.query.filter(c_task_list.task_id.like(task_id + '%'))\
                .order_by(c_task_list.task_id.desc()).first()
            if return_id:
                print(return_id.task_id)
                last_id = return_id.task_id
                last_id = last_id[2:8]
                task_id = 'TK' + str(int(last_id) + 1)
            else:
                task_id = task_id + '0001'

            record = c_task_list(task_id=task_id, task_name=task_name, pj_dpt=pj_dpt, task_type=task_type,
                                 priority=priority, owner=owner, description=description, task_status=task_status,
                                 log_by=user_name, log_time=log_time, update_time=update_time)
            db.session.add(record)
            db.session.commit()

            # email to inform the related people
            email_title = '新建任务---' + task_id + ': ' + task_name
            email_content = '

' \
                '属性	内容
' \
                '
任务号	' + task_id + '
' \
                '
任务名	' + task_name + '
' \
                '
任务描述	' + description + '
' \
                '
项目或部门	' + pj_dpt + '
' \
                '
任务类型	' + task_type + '
' \
                '
优先级	' + priority + '
' \
                '
负责人	' + owner + '
' \
                '
创建人	' + user_name + '
' \
                '
任务状态	' + task_status + '

'
            send_email(email_title, task_id, email_content)

            status = '200'
            value_msg = 'Create successfully!'
            result_json = '[{"task_id":"' + task_id + '", "task_name":"' + task_name + '", "task_type":"' + task_type \
                          + '", "description":"' + description + '", "pj_dpt":"' + pj_dpt \
                          + '", "priority":"' + priority + '", "owner":"' + owner \
                          + '", "task_status":"' + task_status + '", "log_time":"' + str(log_time) \
                          + '", "log_by":"' + user_name + '", "update_time":"' + update_time + '"}]'
        else:
            status = '403'
            value_msg = 'Access Deny!'
            result_json = '"Access Deny"'
    else:
        status = '401'
        value_msg = 'Please log in first!'
        result_json = '"Please log in first!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result

# return the task list front end search

@bp.route("/list/search", methods=['POST'])
def task_list_search():
    task_start_id = request.form.get('start_id')
    task_end_id = request.form.get('end_id')
    pj_dpt = request.form.get('pj_dpt')
    task_type = request.form.get('task_type')
    priority = request.form.get('priority')
    owner = request.form.get('owner')
    task_status = request.form.get('task_status')

    user_name = flask_login.current_user.displayName
    # check if can access the resource
    valid = is_access(user_name, 'pj_dpt', pj_dpt)
    if valid == 1:
        filters = {
            c_task_list.task_id.between(task_start_id, task_end_id),
            c_task_list.pj_dpt == pj_dpt
        }

        if task_type != '不限':
            filters.add(c_task_list.task_type == task_type)

        if priority != '不限':
            filters.add(c_task_list.priority == priority)

        if owner != '不限':
            filters.add(c_task_list.owner == owner)

        if task_status != '不限':
            filters.add(c_task_list.task_status == task_status)

        all_results = c_task_list.query.filter(*filters).all()

        if all_results:
            result_json = '['
            for i in all_results:
                last_update = '无更新记录！'
                aaa = c_task_content.query.filter(
                    c_task_content.task_id == i.task_id).all()
                if aaa:
                    last_update = aaa[-1].content
                result_json = result_json + '{' + '"task_id":"' + i.task_id\
                                                + '","task_name":"' + i.task_name\
                                                + '","pj_dpt":"' + i.pj_dpt\
                                                + '","task_type":"' + i.task_type\
                                                + '", "priority":"' + i.priority\
                                                + '", "owner":"' + i.owner\
                                                + '", "task_status":"' + i.task_status\
                                                + '", "last_update":"' + last_update\
                                                + '", "update_time":"' + i.update_time\
                                                + '", "log_by":"' + i.log_by\
                                                + '", "log_time":"' + i.log_time + '"},'
            status = '200'
            value_msg = 'Search successfully!'
            result_json = result_json[0:len(result_json) - 1]
            result_json = result_json + ']'
        else:
            status = '404'
            value_msg = 'No Result Found!'
            result_json = '"No Data!"'
    else:
        status = '403'
        value_msg = 'Access deny!'
        result_json = '"Access Deny!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result

# return the detailed task info of the task
#   1) task property such as task name, description, priority, owner
#   2) task updates
#   3) task property change history

@bp.route("/info/get", methods=['POST'])
def task_info_get():
    task_id = request.form.get('task_id')
    all_results = c_task_list.query.filter(
        c_task_list.task_id == task_id).first()

    if all_results:
        i = all_results
        user_name = flask_login.current_user.displayName
        valid = is_access(user_name, 'pj_dpt', i.pj_dpt)  # check if can access
        if valid == 1:
            #   1) task property such as task name, description, priority, owner
            result_json = '{' + '"task_id":"' + i.task_id\
                + '","task_name":"' + i.task_name\
                + '","pj_dpt":"' + i.pj_dpt\
                + '","task_type":"' + i.task_type\
                + '", "priority":"' + i.priority\
                + '", "owner":"' + i.owner \
                + '", "description":"' + i.description \
                + '", "task_status":"' + i.task_status\
                + '", "update_time":"' + i.update_time\
                + '", "log_by":"' + i.log_by\
                + '", "log_time":"' + i.log_time + '",'

            # 2) task updates
            all_results = c_task_content.query.filter(
                c_task_content.task_id == task_id).all()
            if all_results:
                result_json = result_json + '"content_valid":"True",'
                result_json = result_json + '"content":['
                for i in all_results:
                    time_consume = str(round(i.time_consume, 1))
                    result_json = result_json + '{' + '"task_id":"' + i.task_id \
                        + '","task_seq":' + str(i.task_seq) \
                        + ' ,"update_name":"' + i.update_name \
                        + '","update_time":"' + i.update_time \
                        + '", "time_consume":' + time_consume \
                        + ' , "task_status":"' + i.task_status \
                        + '", "content":"' + i.content \
                        + '", "file_qty":' + str(i.file_qty) + '},'

                result_json = result_json[0:len(result_json) - 1]
                result_json = result_json + '],'
            else:
                result_json = result_json + '"content_valid":"False",'

            #   3) task property change history
            all_results = c_task_log.query.filter(
                c_task_log.task_id == task_id).all()
            if all_results:
                result_json = result_json + '"log_valid":"True",'
                result_json = result_json + '"log":['
                for i in all_results:
                    result_json = result_json + '{' + '"task_id":"' + i.task_id \
                        + '","property":"' + i.property \
                        + '","old_p":"' + i.old \
                        + '","new_p":"' + i.new \
                        + '", "name":"' + i.name \
                        + '", "change_time":"' + i.change_time + '"},'
                result_json = result_json[0:len(result_json) - 1]
                result_json = result_json + ']'
                result_json = result_json + '}'
            else:
                result_json = result_json + '"log_valid":"False"}'

            status = '200'
            value_msg = 'Get successfully!'

        else:
            status = '403'
            value_msg = 'Access Deny!'
            result_json = '"Access Deny!"'
    else:
        status = '404'
        value_msg = 'No Result Found!'
        result_json = '"No Data!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result

# update the task property to the database
# such as description, project & department, prioroty, owner

@bp.route("/info/update", methods=['POST'])
def task_info_update():
    task_id = request.form.get('task_id')
    description = request.form.get('description')
    pj_dpt = request.form.get('pj_dpt')
    task_type = request.form.get('task_type')
    priority = request.form.get('priority')
    owner = request.form.get('owner')

    all_results = c_task_list.query.filter(
        c_task_list.task_id == task_id).first()

    user_name = flask_login.current_user.displayName
    valid = is_access(user_name, 'pj_dpt', pj_dpt)  # check if can access
    if valid == 1:
        change_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        count = 0
        if all_results:
            old_pj_dpt = all_results.pj_dpt
            old_type = all_results.task_type
            old_priority = all_results.priority
            old_owner = all_results.owner

            if all_results.description != description:
                all_results.description = description
                count = 1

            if old_pj_dpt != pj_dpt:
                all_results.pj_dpt = pj_dpt
                count = 1

            if old_type != task_type:
                all_results.task_type = task_type
                count = 1

            if old_priority != priority:
                all_results.priority = priority
                count = 1

            if old_owner != owner:
                all_results.owner = owner
                count = 1

            if count == 1:
                db.session.commit()
                status = '200'
                value_msg = 'Change successfully!'
                result_json = '"Change successfully!"'
            else:
                status = '410'
                value_msg = 'No need to update!'
                result_json = '"No need to update!"'

            if old_pj_dpt != pj_dpt:
                record = c_task_log(task_id=task_id, property='项目或部门', old=old_pj_dpt, new=pj_dpt,
                                    name=user_name, change_time=change_time)
                db.session.add(record)
                db.session.commit()

            if old_type != task_type:
                record = c_task_log(task_id=task_id, property='任务类型', old=old_type, new=task_type,
                                    name=user_name, change_time=change_time)
                db.session.add(record)
                db.session.commit()

            if old_priority != priority:
                record = c_task_log(task_id=task_id, property='优先级', old=old_priority, new=priority,
                                    name=user_name, change_time=change_time)
                db.session.add(record)
                db.session.commit()

            if old_owner != owner:
                record = c_task_log(task_id=task_id, property='负责人', old=old_owner, new=owner,
                                    name=user_name, change_time=change_time)
                db.session.add(record)
                db.session.commit()

                email_title = '任务负责人变更---' + task_id + ': ' + all_results.task_name
                email_content = '

' \
                    '属性	内容
' \
                    '
任务号	' + task_id + '
' \
                    '
任务名	' + all_results.task_name + '
' \
                    '
任务描述	' + all_results.description + '
' \
                    '
项目或部门	' + all_results.pj_dpt + '
' \
                    '
任务类型	' + all_results.task_type + '
' \
                    '
优先级	' + all_results.priority + '
' \
                    '
任务状态	' + all_results.task_status + '
' \
                    '
新负责人	' + owner + '

'
                send_email(email_title, task_id, email_content)
        else:
            status = '404'
            value_msg = 'No Result Found!'
            result_json = '"No Data!"'
    else:
        status = '403'
        value_msg = 'Access Deny!'
        result_json = '"Access Deny!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result

# update the task status
# total had 6 status: 1-新建，2-进行中，3-待评审，4-暂停，5-关闭，6-完成

@bp.route("/status/change", methods=['POST'])
def task_status_change():
    task_id = request.form.get('task_id')
    new_status = request.form.get('task_status')

    all_results = c_task_list.query.filter(
        c_task_list.task_id == task_id).first()

    user_name = flask_login.current_user.displayName
    # check if can access
    valid = is_access(user_name, 'pj_dpt', all_results.pj_dpt)
    if valid == 1:
        count = 0
        email = 0
        task_name = all_results.task_name
        if all_results:
            old_status = all_results.task_status

            if old_status != '2-进行中' and new_status == '2-进行中':
                count = 1
            if old_status == '2-进行中' and (new_status == '3-待评审' or new_status == '4-暂停'):
                count = 1
                email = 1
            if old_status == '3-待评审' and (new_status == '4-暂停' or new_status == '6-完成'):
                count = 1
                email = 1
            if old_status == '4-暂停' and new_status == '5-终止':
                count = 1
                email = 1

            if count == 1:
                all_results.task_status = new_status
                db.session.commit()

                change_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                record = c_task_log(task_id=task_id, property='任务状态', old=old_status, new=new_status,
                                    name=user_name, change_time=change_time)
                db.session.add(record)
                db.session.commit()
                status = '200'
                value_msg = 'Change successfully!'
                result_json = '{"task_id":"' + task_id + \
                    '","task_status":"' + new_status + '"}'
            else:
                status = '404'
                value_msg = 'No need to update!'
                result_json = '"No need to update!"'

            if email == 1:
                email_title = '任务状态变化---' + task_id + ': ' + task_name
                email_content = '

' \
                                '属性	内容
' \
                                '
任务号	' + task_id + '
' \
                                '
任务名	' + task_name + '
' \
                                '
任务描述	' + all_results.description + '
' \
                                '
负责人	' + all_results.owner + '
' \
                                '
更新人	' + user_name + '
' \
                                '
新任务状态	' + new_status + '

'
                send_email(email_title, task_id, email_content)

        else:
            status = '404'
            value_msg = 'No Result Found!'
            result_json = '"No Data!"'
    else:
        status = '403'
        value_msg = 'Access Deny!'
        result_json = '"Access Deny!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result

# record the task content update

@bp.route("/content/update", methods=['POST'])
def task_content_update():
    task_id = request.form.get('task_id')
    time_consume = request.form.get('task_time')
    input_content = request.form.get('input_content')
    change_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    all_results = c_task_list.query.filter(
        c_task_list.task_id == task_id).first()

    user_name = flask_login.current_user.displayName
    # check if can access
    valid = is_access(user_name, 'pj_dpt', all_results.pj_dpt)
    if valid == 1:
        if all_results:
            task_status = all_results.task_status
            task_name = all_results.task_name
            description = all_results.description
            owner = all_results.owner

            all_results.update_time = change_time
            db.session.commit()

            all_results = c_task_content.query.filter(c_task_content.task_id == task_id)\
                .order_by(c_task_content.task_seq.desc()).all()
            if all_results:
                task_seq = all_results[0].task_seq + 1
            else:
                task_seq = 1

            record = c_task_content(task_id=task_id, task_seq=task_seq, time_consume=time_consume,
                                    content=input_content, task_status=task_status, file_qty=0,
                                    update_name=user_name, update_time=change_time)
            db.session.add(record)
            db.session.commit()

            email_title = '任务更新---' + task_id + ': ' + task_name
            email_content = '

' \
                            '属性	内容
' \
                            '
任务号	' + task_id + '
' \
                            '
任务名	' + task_name + '
' \
                            '
任务描述	' + description + '
' \
                            '
负责人	' + owner + '
' \
                            '
更新人	' + user_name + '
' \
                            '
更新内容	' + input_content + '

'
            send_email(email_title, task_id, email_content)

            status = '200'
            value_msg = 'Change successfully!'
            result_json = '{"task_id":"' + task_id + '","task_seq":' + str(task_seq) + ' ,"task_time":' \
                          + str(time_consume) + ',"name":"' + user_name + '","update_time":"' \
                          + change_time + '","content":"' + input_content + '"}'
        else:
            status = '404'
            value_msg = 'Task ID is wrong!'
            result_json = '"No Task Record!"'
    else:
        status = '403'
        value_msg = 'Access Deny!'
        result_json = '"Access Deny!"'

    result = '{"status":' + status + ',"msg":"' + \
        value_msg + '","result":' + result_json + '}'
    print(result)
    return result


from cntk import ops, cpu, parameter, NDArrayView, input
import numpy as np
import cntk as C
import os
import sys
import pytest

abs_path = os.path.dirname(os.path.abspath(__file__))
custom_convolution_ops_dir = os.path.join(abs_path, "..", "..", "..", "..", "Examples", "Extensibility", "BinaryConvolution")
sys.path.append(custom_convolution_ops_dir)

from custom_convolution_ops import *
import cntk.contrib.netopt as nopt

# checks the functionality of the binary convolution custom function
def test_native_binary_function():
    # user functions need to be registered before being callable by python
    if not nopt.native_convolve_function_registered:
      pytest.skip("Could not find {0} library. "
        "Please check if HALIDE_PATH is configured properly "
        "and try building {1} again"
        .format('Cntk.BinaryConvolution-' + C.__version__.rstrip('+'),
        'Extnsibiliy\\BinaryConvolution'))

    # be sure to only run on CPU, binary convolution does not have GPU support for now
    dev = C.cpu()
    # create an arbitrary input mimicking a realistic cifar input
    x = input((64, 28, 28))
    # random filter weights for testing
    w = parameter((64, 64, 3, 3), init=np.reshape(2*(np.random.rand(64*64*3*3)-.5), (64, 64, 3, 3)), dtype=np.float32, device=dev)

    # set the convolution parameters by passing in an attribute dictionary
    #attributes = {'stride' : 1, 'padding' : False, 'size' : 3}

    attributes = {'stride' : 1,
                  'padding' : False,
                  'size' : 3,
                  'h' : 28,
                  'w' : 28,
                  'channels' : 64,
                  'filters' : 64 }

    # define the binary convolution op
    op = ops.native_user_function('NativeBinaryConvolveFunction', [w, x], attributes, 'native_binary_convolve')

    # also define an op using python custom functions that should have the same output
    op2 = C.convolution(CustomMultibitKernel(w, 1), CustomSign(x), auto_padding = [False])
    # create random input data
    x_data = NDArrayView.from_dense(np.asarray(np.reshape(2*(np.random.rand(64*28*28)-.5), (64, 28, 28)),dtype=np.float32), device=dev)
    # evaluate the CPP binary convolve
    result = op.eval({x : x_data}, device=dev)

    # evaluate the python emulator
    result2 = op2.eval({x : x_data}, device=dev)
    native_times_primitive = op.find_by_name('native_binary_convolve')
    # assert that both have the same result
    '''
    Disable this tempororily. Needs to investigate and fix the halide
    code to match the previous test behavior.
    '''
    #assert np.allclose(result, result2, atol=0.001)


"""Pullers Collection"""
# -*- coding: utf-8 -*-
from __future__ import annotations
import os
import asyncio
from asyncio import Future
from typing import Iterable, Mapping, Any, Callable, Awaitable, Sequence, TypeVar
from abc import abstractmethod
from httpx import Request, Response, Timeout
from ..misc import DummyAioFileStream as Dummyf
from ...io import aio
from ...collections import StrChain
from ...react import ActionChain, EventHook, EventHint as Hint
from httpx._types import HeaderTypes, ProxiesTypes, CookieTypes, QueryParamTypes
import httpx

__all__ = (
    "MaxRetryReached",
    "BasePuller",
    "BaseWorker",
    "BaseMaster",
    "AsyncPuller",
    "AsyncWorker",
    "AsyncMaster",
)

class MaxRetryReached(Exception):
    """Raised when the maximum number of retries is reached."""

class BasePuller:
    """Base class for pullers."""
    @property
    def event_hooks(self) -> EventHook:
        """Event hook for this puller."""
        raise NotImplementedError()

    @abstractmethod
    def pull(self, url: str, path: str) -> Any:
        """Pull the file from the url to the path."""

class BaseWorker:
    """Base class for workers."""

class BaseMaster:
    """Base class for masters."""

HttpActionType = Callable[[Request | Response], Awaitable]
ActionVar = TypeVar('ActionVar', bound=Callable)

class AsyncHttpActionChain(ActionChain[HttpActionType]):
    """Async Http Action Chain"""

    def __init__(self, actions: Iterable[HttpActionType] = None) -> None:
        super().__init__(actions=actions)

class AsyncPullerEventHook(EventHook):
    """Async Puller Event Hook"""

    def __init__(self, chain: Mapping[str, Iterable[Callable[..., Any]]] | None = None):
        self.hook("request", AsyncHttpActionChain())
        self.hook("response", AsyncHttpActionChain())
        self.hook("worker.spawn", ActionChain())
        self.hook("worker.destroy", ActionChain())
        self.hook("worker.start", ActionChain())
        self.hook("worker.response_get", ActionChain())
        self.hook("worker.bytes_get", ActionChain())
        self.hook("worker.retry", ActionChain())
        self.hook("worker.success", ActionChain())
        self.hook("worker.fail", ActionChain())
        self.hook("puller.spawn", ActionChain())
        self.hook("puller.destroy", ActionChain())
        self.hook("puller.join", ActionChain())
        EventHook.__init__(self, chain=chain)

class AsyncWorker(BaseWorker):
    def __init__(
        self,
        puller: AsyncPuller,
        url: str,
        path: str | None,
        retry: int,
        overwrite: bool,
        *,
        future: Future = None,
        timeout: Timeout | float | None,
        extra_headers: HeaderTypes | None,
        extra_params: QueryParamTypes | None,
        extra_cookies: CookieTypes | None,
        **kw
    ):
        self.puller = puller
        self.url = url
        self.path = path
        self.future: Future = future  # type: ignore[assignment]
        self.timeout = timeout
        self.max_retry = retry
        self.overwrite = overwrite
        self.extra_headers = extra_headers
        self.extra_params = extra_params
        self.extra_cookies = extra_cookies
        self.kw = kw
        self.event_hooks = AsyncPullerEventHook(
            self.puller.event_hooks)  # snapshot

    async def run(self):
        """Run the worker."""
        event_hooks = self.event_hooks
        try:
            await event_hooks.aemit("worker.start", self)
            if self.path and os.path.exists(self.path) and not self.overwrite:
                raise FileExistsError(f"{self.path} already exists")
            client = self.puller.client
            retry = 0
            while True:
                try:
                    # Open file in async mode, if path is None, write to void
                    async with aio.open(self.path, "wb") \
                            if self.path else Dummyf() as f:  # type: ignore
                        # Establish connection
                        async with client.stream(
                            method=self.kw.pop("method", "GET"),
                            url=self.url,
                            params=self.extra_params,
                            headers=self.extra_headers,
                            cookies=self.extra_cookies,
                            timeout=self.timeout or self.puller.client.timeout,
                            **self.kw
                        ) as r:
                            await event_hooks.aemit("worker.response_get", self, r)
                            # Iterate over response chunks
                            # 256KB
                            async for chunk in r.aiter_bytes(chunk_size=2**18):
                                await event_hooks.aemit(
                                    "worker.bytes_get", self, r, chunk)
                                await f.write(chunk)
                            await f.flush()
                            await event_hooks.aemit("worker.success", self, r)
                    # set result for placeholder
                    self.future.set_result(self.path)
                    self.puller._ft_map.pop(id(self.future))  # type: ignore
                    break  # Quit successfully
                # Retry on network IO error
                except (httpx.HTTPError, httpx.StreamError) as e:
                    retry += 1
                    if retry > self.max_retry:
                        raise MaxRetryReached(
                            f"Max retry reached: {retry} times") from e
                    await event_hooks.aemit("worker.retry", self, e, retry)
                    await asyncio.sleep(min(30, 1.7 ** retry))
        # Fatal Errors
        except (Exception, asyncio.CancelledError) as e:
            handled = await event_hooks.aemit("worker.fail", self, e)
            if True not in handled:
                self.future.set_exception(e)
                raise e
            self.puller._ft_map.pop(id(self.future))  # type: ignore
        finally:
            await event_hooks.aemit("worker.destroy", self)
            self.puller._workers.get_nowait()
            self.puller._workers.task_done()  # workers count - 1

    def __repr__(self) -> str:
        return f"AsynWorker({self.url}, {self.path})"

class AsyncMaster(BaseMaster):
    def __init__(self, puller: AsyncPuller):
        self.puller = puller

    async def run(self):
        """Run the master."""
        try:
            buffer = self.puller._buffer
            workers = self.puller._workers
            while True:
                worker = await buffer.get()
                if worker is None:  # Kill signal
                    buffer.task_done()
                    break
                await workers.put(worker)  # blocks when max_workers reached
                self.puller.loop.create_task(worker.run())
                buffer.task_done()
                await asyncio.sleep(self.puller.interval)  # sleep a while
        finally:
            self.puller._master = None  # Reset master

class AsyncPuller(BasePuller):
    """### Async Puller"""

    def __init__(
        self,
        *,
        headers: HeaderTypes = None,
        params: QueryParamTypes = None,
        proxies: ProxiesTypes = None,
        cookies: CookieTypes = None,
        event_hooks: Mapping[str, Sequence[Callable]] = None,
        interval: float = 0.0,
        max_workers: int = 8,
        timeout: Timeout | float | None = 10,
        retry: int = 3,
        overwrite: bool = False,
        loop: asyncio.AbstractEventLoop = None,
        **kw
    ):
        """### Init Puller
        * `headers`: Default headers for all requests
        * `params`: Default query params for all requests
        * `proxies`: Default proxies for all requests
        * `cookies`: Default cookies for all requests
        * `event_hooks`: dict[str, Iterable[Callable]]
        * `interval`: Interval between each request
        * `max_workers`: Max downloading threads count
        * `timeout`: Timeout for each request
        * `retry`: Max retry times for each request
        * `overwrite`: Overwrite existing files
        * `loop`: Event loop
        * `**kw`: Other keyword arguments for httpx.Client
        """
        self._loop = loop
        self.interval = interval
        self.max_retry = max(retry, 0)
        self.overwrite = overwrite

        self._proxies = proxies
        self._master: AsyncMaster | None = None
        self._buffer: asyncio.Queue = asyncio.Queue()  # Pending workers
        self._workers: asyncio.Queue = asyncio.Queue(
            maxsize=max_workers)  # Running workers
        self._ft_map: dict[int, Future] = {}

        limits = httpx.Limits(
            max_connections=None,
            max_keepalive_connections=None,
            keepalive_expiry=10)

        self._client = httpx.AsyncClient(
            headers=headers,
            params=params,
            proxies=proxies,
            cookies=cookies,
            timeout=timeout,
            limits=limits,
            follow_redirects=True,
            http2=True,
            **kw
        )
        self.event_hooks = event_hooks or AsyncPullerEventHook()

        # Set up event hook
        def subscribe(event: StrChain, action: ActionVar) -> ActionVar:
            ev = str(event)
            self._event_hooks[ev].append(action)
            if ev in ["request", "response"]:
                self._client.event_hooks = self._event_hooks  # type: ignore[assignment]
            return action

        self._on = PullerEventHint(
            strchain=StrChain(joint='.', callback=subscribe))

    @property
    def client(self):
        return self._client

    @property
    def loop(self):
        if self._loop is None:
            self._loop = asyncio.get_running_loop()
        return self._loop

    @property
    def headers(self):
        """Get headers."""
        return self._client.headers

    @headers.setter
    def headers(self, value: HeaderTypes):
        """Set headers for all requests."""
        self._client.headers = value  # type: ignore[assignment]

    @property
    def cookies(self):
        return self._client.cookies

    @cookies.setter
    def cookies(self, value: CookieTypes):
        """Set cookies for all requests."""
        self._client.cookies = value  # type: ignore[assignment]

    @property
    def params(self):
        return self._client.params

    @params.setter
    def params(self, value: QueryParamTypes):
        """Set params for all requests."""
        self._client.params = value  # type: ignore[assignment]

    @property
    def event_hooks(self):
        return self._event_hooks

    @event_hooks.setter
    def event_hooks(self, hooks: Mapping[str, Sequence[Callable]]):
        """Set event hooks for all requests."""
        self._event_hooks = AsyncPullerEventHook(hooks)  # deepcopy
        self._client.event_hooks = self._event_hooks  # type: ignore[assignment]

    @property
    def on(self):
        """Shortcut for `Puller.event_hooks.on`"""
        return self._on

    @property
    def proxies(self):
        return self._proxies

    async def pull(
        self,
        url: str,
        path: str | None,
        *,
        extra_headers: HeaderTypes | None = None,
        extra_params: QueryParamTypes | None = None,
        extra_cookies: CookieTypes | None = None,
        timeout: Timeout | float | None = 0,
        retry: int | None = None,
        overwrite: bool | None = None,
        **kw
    ) -> Future:
        """
        ### Asynchronously pull a file from a url.
        File will be decompressed and saved in binary mode.

        Returns a `Future` instance refer to the path of the downloaded file.
        * `url`: url to pull from
        * `path`: path to save to, set to `None` or `""` will not save file

        Optional Parameters:
        * `extra_headers`: extra headers to add to request
        * `extra_params`: extra params to add to request
        * `extra_cookies`: extra cookies to add to request
        * `timeout`: timeout for this request, set to None will be no limit, 0 for default
        * `retry`: retry times for this request, set to None will use default
        * `overwrite`: overwrite file if exists, set to None will use default
        * `**kw`: extra keyword arguments for httpx.stream
        """
        timeout = self.client.timeout if timeout == 0 else timeout
        self._loop = self.loop or asyncio.get_running_loop()
        if self._master is None:
            self._master = AsyncMaster(self)
            self._loop.create_task(self._master.run())
        future: Future = Future()  # A placeholder for the worker.run() task
        self._ft_map[id(future)] = future
        worker = AsyncWorker(
            self,
            url=url,
            path=path,
            extra_headers=extra_headers,
            extra_params=extra_params,
            extra_cookies=extra_cookies,
            future=future,
            timeout=timeout,
            retry=self.max_retry if retry is None else retry,
            overwrite=overwrite or self.overwrite,
            **kw
        )
        await self._event_hooks.aemit("worker.spawn", worker)
        await self._buffer.put(worker)
        return future

    async def join(self) -> None:
        """### Wait for all workers to finish."""
        await self._event_hooks.aemit("puller.join", self)
        await self._buffer.join()  # Make sure no pending tasks
        await self._workers.join()  # Make sure all workers finished
        jobs = list(self._ft_map.values())
        self._ft_map.clear()
        await asyncio.gather(*jobs)  # Make sure all tasks are done

    async def aclose(self):
        await self.join()  # Make sure all tasks are done
        await self._buffer.put(None)  # Kill master
        await self._event_hooks.aemit("puller.destroy", self)
        await self._client.aclose()

    async def __aenter__(self) -> AsyncPuller:
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb) -> bool:
        await self.aclose()
        return False

    def __repr__(self):
        return f"{self.__class__.__name__}:\n" +\
            f"  max_retry: {self.max_retry}\n" +\
            f"  overwrite: {self.overwrite}\n" +\
            f"  headers: {self.headers}\n" +\
            f"  params: {self.params}\n" +\
            f"  cookies: {self.cookies}\n" +\
            f"  proxies: {self.proxies}\n" +\
            f"  event_hooks: {self.event_hooks}\n"

#### Start Hinting: Add hints for event names ####

class on_puller_hint(Hint):  # pragma: no cover
    @property
    def spawn(self):
        """Callback Type: (event_name: str, AsyncPuller) -> None"""
        return self._chain.spawn

    @property
    def destroy(self):
        """Callback Type: (event_name: str, AsyncPuller) -> None"""
        return self._chain.destroy

    @property
    def join(self):
        """Callback Type: (event_name: str, AsyncPuller) -> None"""
        return self._chain.join

class on_worker_hint(Hint):  # pragma: no cover
    @property
    def spawn(self):
        """Callback Type: (event_name: str, AsyncWorker) -> None"""
    @property
    def destroy(self):
        """Callback Type: (event_name: str, AsyncWorker) -> None"""
    @property
    def start(self):
        """Callback Type: (event_name: str, AsyncWorker) -> None"""
    @property
    def response_get(self):
        """Callback Type: (event_name: str, AsyncWorker, Response) -> None"""
    @property
    def bytes_get(self):
        """Callback Type: (event_name: str, AsyncWorker, Response, bytes) -> None"""
    @property
    def retry(self):
        """Callback Type: (event_name: str, AsyncWorker, Exception, retry: int) -> None"""
    @property
    def success(self):
        """Callback Type: (event_name: str, AsyncWorker) -> None"""
    @property
    def fail(self):
        """Callback Type: (event_name: str, AsyncWorker, Exception) -> bool:
        whether to ignore the exception"""

class PullerEventHint(Hint):  # pragma: no cover
    """Puller Event Hint."""
    @property
    def puller(self) -> on_puller_hint:
        return self._chain.puller  # type: ignore

    @property
    def worker(self) -> on_worker_hint:
        return self._chain.worker  # type: ignore

    @property
    def request(self):
        """Callback Type: (Request) -> None"""
        return self._chain.request

    @property
    def response(self):
        """Callback Type: (Response) -> None"""
        return self._chain.response

### End Hinting ###


import socket
import threading
import time
import datetime
from ..sdn_message_reader import SDNMessageReader
from ryu.ofproto.ofproto_v1_0 import OFPT_BARRIER_REQUEST, OFPT_FLOW_MOD

class TimedReverseFlowmodsMessageManager(object):
    '''
    When receive flow mod sdn messages on incoming queue, delay until:

      1) Receive a barrier or
      2) A user-specified period of time has expired since received
         last flow mod.

    If either of these happen, send out buffered flow mods in reverse
    order of when they were accepted.
    '''

    def __init__(self,timeout_seconds,receiver_socket,sender_socket):
        '''
        @param {float} timeout_seconds --- If we have not received a
        flow mod in this many seconds, then send all buffered flow
        mods in reverse order.

        @param {SDNSocket} receiver_socket --- Reads messages on this
        socket and instantly forwards them on sender_socket.

        @param {SDNSocket} sender_socket --- Forwards openflow
        messages out of this socket.
        '''
        self.timeout_seconds = timeout_seconds

        self.sdn_message_reader = SDNMessageReader(receiver_socket)
        self.sender_socket = sender_socket
        # Elements are byte arrays/strings for openflow messages since
        # last barrier message.
        self.received_flowmods_list = []
        self.last_received_time = None
        self._received_flow_mods_lock = threading.RLock()

    def check_time_expired_thread(self):
        '''
        Runs, periodically checking whether it's been
        self.timeout_seconds since the last flow mod has been
        received, and send buffered flow mods if it has been.
        '''
        sleep_time = .5
        while True:
            time.sleep(sleep_time)
            with self._received_flow_mods_lock:
                # empty flowmods list.
                if self.last_received_time is None:
                    sleep_time = .5
                    continue

                # check when the last sent flowmod was received.
                current_time = datetime.datetime.now()
                diff = current_time - self.last_received_time
                seconds_since_last_flowmod = diff.total_seconds()
                if seconds_since_last_flowmod >= self.timeout_seconds:
                    self._send_outstanding()
                    sleep_time = .5
                else:
                    sleep_time =  (
                        self.timeout_seconds - seconds_since_last_flowmod + .01)

    def start_service(self):
        '''
        Actually start listening for openflow messages and forwarding
        them.
        '''
        t = threading.Thread(target=self._start_forwarding)
        t.setDaemon(True)
        t.start()
        t_watchdog = threading.Thread(target=self.check_time_expired_thread)
        t_watchdog.setDaemon(True)
        t_watchdog.start()

    def _send_outstanding(self,barrier_message_buf=None):
        '''
        @param {bytearray} barrier_message_buf --- None if we aren't
        supposed to send a barrier message.
        '''
        with self._received_flow_mods_lock:
            # by default, we forward flowmods in reverse order.
            for msg_buf_to_write in reversed(self.received_flowmods_list):
                self.sender_socket.write(msg_buf_to_write)

            self.received_flowmods_list = []

            if barrier_message_buf is not None:
                self.sender_socket.write(barrier_message_buf)

            # reset receipt timer because sent out last outstanding
            # message.
            self.last_received_time = None

    def _start_forwarding(self):
        while True:
            # msg will either be a ryu message or an unparsed message.
            # in either case, should support serialize + buf calls.
            msg = self.sdn_message_reader.blocking_read_sdn_message()
            msg.serialize()

            with self._received_flow_mods_lock:
                try:
                    if msg.msg_type == OFPT_BARRIER_REQUEST:
                        self._send_outstanding(msg.original_buffer)
                    elif msg.msg_type == OFPT_FLOW_MOD:
                        self.last_received_time = datetime.datetime.now()
                        self.received_flowmods_list.append(msg.original_buffer)
                    else:
                        # just forward the message along: it's non-barrier
                        # and non-flow mod
                        self.sender_socket.write(msg.original_buffer)
                except socket.error:
                    break


from flask import Flask, render_template,request,flash,redirect

import tensorflow as tf
from colabcode import ColabCode
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from keras.preprocessing.image import ImageDataGenerator
import uvicorn
import numpy as np

import keras.utils as image

class Image(BaseModel):
    imageName : str

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)
training_set = train_datagen.flow_from_directory('training_set',
                                                 target_size = (128, 128),
                                                 batch_size = 128,
                                                 class_mode = 'categorical',
                                                 shuffle=True)
#model loading
cnn=tf.keras.models.load_model("./myModel_v1")

app = FastAPI()

origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app=Flask(__name__)

#-------------------------------------------------------------------------------------------------------#
# page d'accueil #
@app.route('/')
def accueil ():
    return render_template('index.html')
###########

# test #
@app.route('/test')
def get_image_category():
    return render_template('test.html')

from werkzeug.utils import secure_filename

import PIL.Image
import cv2

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file'].read()
      npimg = np.fromstring(f,np.uint8)
      img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)
      print(img)
      test_image = image.img_to_array(img)
      test_image = np.expand_dims(test_image, axis = 0)
      print(test_image)
      result = cnn.predict(test_image)
      training_set.class_indices
      print(result)
      if result[0][0] == 0:
        prediction = 'Cancer'
      else:
        prediction = 'NORMAL'
      return {'classificaton_result': prediction}

#main#
if __name__=="__main__":
    app.run(debug=True)
#------------------------#


seq = eval(input())
seq = sorted(seq)
length = len(seq)
if length == 0:
    exit()
i = 1
ans = []
while i < length:
    if seq[i - 1][1] < seq[i][0]:
        i = i + 1
    else:
        tmp = ([seq[i - 1][0], seq[i][1]])
        seq = seq[2:]
        seq.insert(0, tmp)
        length = length - 1
print(seq)


str1=input()
str1=str1.replace('[','')
str1=str1.replace(']','')
list1=str1.split(',')
nums1=[]
for i in range(len(list1)):
    nums1.append(int(list1[i]))
str2=input()
str2=str2.replace('[','')
str2=str2.replace(']','')
list2=str2.split(',')
nums2=[]
for i in range(len(list2)):
    nums2.append(int(list2[i]))
nums1.extend(nums2)
nums1.sort()
length=len(nums1)
ans=0
if length%2==1:
    ans=nums1[length//2]
else:
    ans=(nums1[length//2]+nums1[length//2-1])/2.0
a_s=str(ans)
list3=a_s.split('.')
while len(list3[1])<5:
    list3[1]=list3[1]+'0'
ass=list3[0]+'.'+list3[1]
print(ass)


import tensorflow as tf

import os, argparse

dir = os.path.dirname(os.path.realpath(__file__))

def freeze_graph(model_dir, output_node_names):
  """Extract the sub graph defined by the output nodes and convert
    all its variables into constant
    Args:
        model_dir: the root folder containing the checkpoint state file
        output_node_names: a string, containing all the output node's names,
                            comma separated
  """

  if not tf.gfile.Exists(model_dir):
    raise AssertionError(
      "Export directory doesn't exists. Please specify an export "
      "directory: %s" % model_dir)

  if not output_node_names:
    print("You need to supply the name of a node to --output_node_names.")
    return -1

  checkpoint = tf.train.get_checkpoint_state(model_dir)
  input_checkpoint = checkpoint.model_checkpoint_path
  print(input_checkpoint)

  absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])
  output_graph = os.path.join(absolute_model_dir,'freeze_model.pb')

  clear_devices =True

  with tf.Session(graph=tf.Graph()) as sess:
    saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)

    saver.restore(sess, input_checkpoint)

    print([n.name for n in tf.get_default_graph().as_graph_def().node])

    output_graph_def = tf.graph_util.convert_variables_to_constants(
      sess,
      tf.get_default_graph().as_graph_def(),
      output_node_names.split(',')

      )

    with tf.gfile.GFile(output_graph, 'wb') as f:
      f.write(output_graph_def.SerializeToString())
    print("%d ops in the final graph." % len(output_graph_def.node))

  return output_graph_def

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument("--model_dir", type=str, default="", help="Model folder to export")
  parser.add_argument("--output_node_names", type=str, default="", help="The name of the output nodes, comma separated.")
  args = parser.parse_args()
  freeze_graph(args.model_dir, args.output_node_names)


import cv2

image = cv2.imread("Tank64229left.png")
#image = cv2.imread("Test1.png")

# grayscale the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#cv2.imwrite("gray_tank64229.png",gray)
# apply a Gaussian blur
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# threshold the image
(t, binary) = cv2.threshold(blur, 100, 255, cv2.THRESH_BINARY)
# find contours
(_, contours, _) = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
image_cropped_contoured_drawn = cv2.drawContours(image.copy(), contours, -1, (0, 255, 0), 3)
cv2.imwrite("exploration.jpg", image_cropped_contoured_drawn)

f = open('co_ordinates.txt', 'w+')
for c in range(len(contours)):
    n_contour = contours[c]
    for d in range(len(n_contour)):
        XY_Coordinates = n_contour[d]
        print(XY_Coordinates)
        f.write("%s\n" % (XY_Coordinates))


def solve():
    q = [b]
    for i in range(k):
        x = len(q)
        for j in range(x):
            if 0 <= q[0] - c[i] <= l:
                q.append(q[0] - c[i])
            if 0 <= q[0] + c[i] <= l:
                q.append(q[0] + c[i])
            q.pop(0)
    ans = len(set(q))
    if ans:
        print(ans)
    else:
        print(-1)

l, k = map(int, input().split())
b = int(input())
c = list(map(int, input().split()))

solve()


"""
Created on Wed Dec 14 22:11:37 2022

@author: alexandre
"""

import epics
import matplotlib.pyplot as plt
from time import sleep

"""
           PV Information

Object: Text Monitor
Thu Dec 15 06:49:54 CST 2022

alexandre:PM1:X:positionM
======================================
DESC: PM1:X
RTYP: calc
TYPE: DBF_DOUBLE
COUNT: 1
ACCESS: RW
IOC: localhost:5064
VALUE: -0.06
STAMP: Thu Dec 15, 2022 06:49:54.777
ALARM: NO

PRECISION: 2
HOPR: 5  LOPR: -5
"""

"""
           PV Information

Object: Slider
Thu Dec 15 11:37:31 CST 2022

alexandre:H1:setCurrentC
======================================
DESC: H1 current setpoint
RTYP: ao
TYPE: DBF_DOUBLE
COUNT: 1
ACCESS: RW
IOC: localhost:5064
VALUE: -1.28
STAMP: Thu Dec 15, 2022 08:34:18.962
ALARM: NO

PRECISION: 2
HOPR: 5  LOPR: -5
"""

#%% channels
PM1_X = epics.PV("alexandre:PM1:X:positionM")
PM1_X_current = epics.PV("alexandre:H1:setCurrentC")

#%% control parameters
PM1_X_set_point = 0.0
PM1_X_error     = 0.001

PM1_X_current_step = .1

#%% control loop
PM1_Xvalues =[]
PM1_X_currentvalues =[]

PM1_X_current.put(6)
sleep(.2)

for n in range(100):
    PM1_Xvalues.append(PM1_X.get())
    PM1_X_currentvalues.append(PM1_X_current.get())
    if   abs(PM1_Xvalues[-1] - PM1_X_set_point) <= PM1_X_error: break
    if   PM1_Xvalues[-1] > PM1_X_set_point                    : PM1_X_current.put(PM1_X_currentvalues[-1] - PM1_X_current_step)
    elif PM1_Xvalues[-1] < PM1_X_set_point                    : PM1_X_current.put(PM1_X_currentvalues[-1] + PM1_X_current_step)

    sleep(.2)

#%%
plt.close("all")
fig , (ax1, ax2) = plt.subplots(2,1)
ax1.plot(PM1_Xvalues)
ax1.set_ylabel("X tranverse position, $X_1$ [$\mu m$]")
ax1.grid(True)

ax2.plot(PM1_X_currentvalues)
ax2.set_ylabel("Horizontal Magnet Current, $I_1$ [A]")
ax2.set_xlabel("time, t [s]")
ax2.grid(True)


import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy

from flaskr import create_app
from models import setup_db, Question, Category

class TriviaTestCase(unittest.TestCase):
    """This class represents the trivia test case"""

    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "trivia_test"
        self.database_path = "postgresql://{}:{}@{}/{}".format('postgres', 'admin', 'localhost:5432', self.database_name)
        setup_db(self.app, self.database_path)
        self.new_object = {
            'question': 'who is the best player in the world?',
            'answer': 'mputu',
            'difficulty': 5,
            'category': 2
        }

        self.erreur_question = {
            'question': 'What is your name?',
        }

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()

    def tearDown(self):
        """Executed after reach test"""
        pass

    """
    TODO
    Write at least one test for each test for successful operation and for expected errors.
    """

    def test_trouver_categories(self):
        res = self.client().get('/categories')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(len(data['categories']))

    def test_recuperer_questions(self):
        res = self.client().get('/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(len(data['questions']))
        self.assertTrue(len(data['categories']))

    def test_erreur_pour_trouver_une_question(self):

        res = self.client().post('/questions/chercher', json={'terme': 'mbula'})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)

    def test_404_trouver_questions(self):
        res = self.client().get('/questions?page=5000')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'resource not found')

    def test_questions_par_categorie(self):
        res = self.client().get('/categories/2/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertIsNotNone((data['questions']))
        self.assertTrue((data['total_de_questions'] > 0 , True))
        self.assertTrue((data['categorie_courante'] == 2,True))

    def test_404_questions_par_categorie(self):
        res = self.client().get('/categories/c/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)

    def test_poster_question(self):
        res = self.client().post('/questions', json=self.new_object)
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['total_questions'] > 0,True)

    def test_poster_question(self):
        res = self.client().post('/questions', json=self.erreur_question)
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)

    def test_quiziew(self):
        new_quiz = {'quiz_category': {'type': 'Entertainment', 'id': 9},'last_questions': []}

        res = self.client().post('/quizzes', json=new_quiz)
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)

    def test_404_if_book_does_not_exist(self):
        res = self.client().delete('/questions/5000')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'non traetable')

    def test_supprimer_question(self):
        NQuestion = Question(question='what is your name', answer='Abdullah Alessa',difficulty=5 , category=6)
        NQuestion.insert()
        res = self.client().delete(f'/questions/{NQuestion.id}')
        data = json.loads(res.data)

        question = Question.query.filter(Question.id == NQuestion.id).one_or_none()

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['deleted'], (NQuestion.id))

# Make the tests conveniently executable
if __name__ == "__main__":
    unittest.main()


import pygame
from ray import Ray
from wall import Wall
import numpy as np

def dist(x1, y1, x2, y2):
	return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)

class Point:
	def __init__(self, pos, n):
		self.x, self.y = pos
		self.rays = []

		for i in range(n):
			self.rays.append(Ray(self.x, self.y, i * 2 * np.pi / n))

	def update(self, pos):
		self.x, self.y = pos
		for ray in self.rays:
			ray.x = self.x
			ray.y = self.y

	def look(self, walls, screen):
		for i in range(len(self.rays)):
			ray = self.rays[i]
			clostest = None
			record = np.Inf

			for wall in walls:
				x1, y1 = ray.cast(wall)
				if x1 == -100 and y1 == -100:
					continue
				d = dist(x1, y1, self.x, self.y)

				if d < record:
					clostest = (x1, y1)
					record = d
			if clostest != None:
				pygame.draw.line(screen, pygame.Color(255, 255, 255), (ray.x, ray.y), clostest)

	def draw(self, screen):
		pygame.draw.circle(screen, pygame.Color(255, 255, 255), (self.x, self.y), 3)


import os

class FileListItem(object):
    def __init__(self, index, is_dir, dir_path, name):
        self.index = index
        self.is_dir = is_dir
        self.dir_path = dir_path
        self.name = name
        self.full_path = os.path.join(dir_path, name)

class FileList(object):
    (SORT_BY_FILE_NAME,
     SORT_BY_MOD_DATE,
     SORT_BY_FILE_EXT,
     SORT_BY_FILE_SIZE,
     SORT_BY_IS_DIR) = range(5)

    @classmethod
    def build_key_generator(cls, sort_types, case_sensitive=False):
        adj = ((lambda x: x) if case_sensitive else (lambda x: x.lower()))

        gns = []
        for sort_type in sort_types:
            if sort_type == cls.SORT_BY_FILE_NAME:
                gn = lambda is_dir, fn: adj(os.path.split(fn)[-1])
            elif sort_type == cls.SORT_BY_FILE_EXT:
                gn = lambda is_dir, fn: adj(os.path.splitext(fn)[-1])
            elif sort_type == cls.SORT_BY_MOD_DATE:
                gn = lambda is_dir, fn: os.path.getmtime(fn)
            elif sort_type == cls.SORT_BY_FILE_SIZE:
                gn = lambda is_dir, fn: os.path.getsize(fn)
            elif sort_type == cls.SORT_BY_IS_DIR:
                gn = lambda is_dir, fn: (0 if is_dir else 1)
            else:
                continue
            gns.append(gn)

        def key_generator(item):
            return tuple(gn(*item) for gn in gns)
        return key_generator

    def __init__(self, dir_path, **kwargs):
        self.callbacks = []
        self.full_path = dir_path = os.path.realpath(dir_path)
        self.file_items = items = []
        for i, args in enumerate(get_files_in_dir(dir_path, **kwargs)):
            is_dir, name = args
            items.append(FileListItem(i, is_dir, dir_path, name))

    def __iter__(self):
        return iter(self.file_items)

    def __len__(self):
        return len(self.file_items)

    def __getitem__(self, idx):
        return self.file_items[idx]

    def register_callback(self, update_callback):
        self.callbacks.append(update_callback)

image_file_extensions = ('.jpeg', '.jpg', '.png', '.tif', '.xpm', '.bmp')

def list_dir(directory_path):
    '''Return the files in the directory or an empty list if the directory
    access fails.'''

    assert isinstance(directory_path, str)
    try:
        entries = os.listdir(directory_path)
    except Exception as x:
        return []
    return [os.path.join(directory_path, entry) for entry in entries]

def get_files_in_dir(directory_path, **kwargs):
    '''Return tuples (isdir, full_path) where isdir is a boolean indicating
    whether the item is a directory and full_path is the path to it.
    The following keyword arguments can be used:

    `file_extensions`: list of extensions of files to consider. Files with
      different extension are ignored.

    `sort_type`: how the files are sorted. Can be FileList.SORT_BY_FILE_NAME
      or another value of the same enumeration.

    `reversed_sort`: whether the sort order should be reversed. Default order
      is from smaller to bigger.
    '''
    return categorize_files(list_dir(directory_path), **kwargs)

def is_hidden(full_path):
    '''Whether the given file is hidden.'''
    return os.path.split(full_path)[-1].startswith('.')

def categorize_files(file_list, file_extensions=None, sort_type=None,
                     reversed_sort=False, show_hidden_files=True):
    '''Similar to get_files_in_dir, but uses the files in the list given as
    first argument, rather than obtaining the file list from a directory path.
    '''

    exts = file_extensions or image_file_extensions
    isdir_file_tuples = []
    for full_path in file_list:
        if not show_hidden_files and is_hidden(full_path):
            continue

        if not os.path.exists(full_path):
            continue

        isdir = os.path.isdir(full_path)
        if not isdir:
            ext = os.path.splitext(full_path)[1]
            if ext.lower() not in exts:
                continue
        isdir_file_tuples.append((isdir, full_path))

    # For now we only provide one sort type. Later we may want to provide a
    # tuple of sort types from the one which has the higher precedence to the
    # one which has the lowest precedence. Infrastructure for this is already
    # in place. Here we map the single sort order to a tuple which makes sense.
    if sort_type is not None:
        if sort_type == FileList.SORT_BY_FILE_NAME:
            sort_types = (sort_type,)
        else:
            sort_types = (sort_type, FileList.SORT_BY_FILE_NAME)

        key = FileList.build_key_generator(sort_types)
        isdir_file_tuples.sort(key=key, reverse=reversed_sort)
    return isdir_file_tuples

def pick_file_from_dir(directory_path, out_list, file_extensions=None,
                       **kwargs):
    '''Pick the first file in the given directory with the required extension.
    If a file is found, it is appended to out_list and True is returned.
    Otherwise False is returned.'''

    exts = file_extensions or image_file_extensions
    entries = get_files_in_dir(directory_path, **kwargs)
    for is_dir, entry_name in entries:
        if not is_dir:
            out_list.append(entry_name)
            return True
    for is_dir, entry_name in entries:
        assert is_dir
        if pick_file_from_dir(entry_name, out_list, **kwargs):
            return True
    return False

def choose_representatives(directory_path, num=4, **kwargs):
    if num < 1:
        return []

    file_list = list_dir(directory_path)
    all_entries = categorize_files(file_list, **kwargs)
    all_dirs = [entry for is_dir, entry in all_entries if is_dir]
    all_images = [entry for is_dir, entry in all_entries if not is_dir]

    # First, we want to determine whether this is a folder mostly containing
    # images or whether this folder contains all sorts of files. We want to
    # avoid scanning huge directories looking for images that they don't
    # contain. For example, if `directory_path` is the home folder, then we
    # want to avoid scanning any of its subfolders.
    n = len(file_list) - len(all_dirs)  # Num of non-image files.
    tol = 2                             # Num of non-image files we tolerate.
    image_content_ratio = ((len(all_images) + tol) * 100) // (n + tol)
    is_image_folder = (image_content_ratio > 60)

    # Pick at least one image from this directory.
    out = []
    if len(all_images) > 0:
        out.append(all_images.pop(0))
        if num == 1:
            return out

    if is_image_folder:
        # If available, pick all the other images from separate directories.
        step = max(1, len(all_dirs) // (num - len(out)))
        index = 0
        while len(all_dirs) > 0:
            index = index % len(all_dirs)
            candidate_dir = all_dirs.pop(index)
            index += step
            if (pick_file_from_dir(candidate_dir, out, **kwargs) and
                len(out) >= num):
                return out

    # Not enough directories, then pick the other images from this dir.
    assert num >= 1 and len(out) < num
    step = max(1, len(all_images) // (num - len(out)))
    index = step
    while len(all_images) > 0 and len(out) < num:
        index = index % len(all_images)
        out.append(all_images.pop(index))
        index += step
    return out


import logging

from pecan import expose, response, conf, render
from stevedore import driver

from cauth.auth import base
from cauth.model import db
from cauth.utils import common
from cauth.utils import transaction

OAUTH_PROVIDERS_PLUGINS = ['Github',
                           'Google',
                           'BitBucket', ]

class OAuth2Controller(transaction.TransactionLogger):
    log = logging.getLogger("cauth.Oauth2Controller")

    def __init__(self):
        self.auth_plugins = {}
        for p in OAUTH_PROVIDERS_PLUGINS:
            try:
                self.auth_plugins[p] = driver.DriverManager(
                    namespace='cauth.authentication',
                    name=p,
                    invoke_on_load=True,
                    invoke_args=(conf,)).driver
                self.log.debug('Loaded OAuth2 plugin %s' % p)
            except Exception:
                pass
        if not self.auth_plugins:
            msg = ('no valid configuration found for any of the '
                   'supported OAuth '
                   'providers (%s)' % ', '.join(OAUTH_PROVIDERS_PLUGINS))
            raise base.AuthProtocolNotAvailableError(msg)

    @expose()
    def callback(self, **kwargs):
        auth_context = kwargs
        auth_context['response'] = kwargs
        auth_context['calling_back'] = True
        transactionID = transaction.ensure_tid(auth_context)
        try:
            # Verify the state previously put in the db
            state = auth_context.get('state', None)
            back, provider = db.get_url(state)
            if not back:
                err = 'OAuth callback with forged state, discarding'
                self.tdebug(err, transactionID)
                raise base.UnauthenticatedError(err)
            auth_plugin = self.auth_plugins.get(provider)
            if not auth_plugin:
                msg = 'Unknown OAuth provider: %s' % provider
                self.terror(msg, transactionID)
                raise base.UnauthenticatedError(msg)
            self.tdebug('Callback called by OAuth provider %s',
                        transactionID, provider)
            auth_context['back'] = back
            valid_user = auth_plugin.authenticate(**auth_context)
        except base.UnauthenticatedError as e:
            response.status = 401
            auth_methods = [k for k, v in conf.get('auth', {})]
            return render('login.html',
                          dict(back=back,
                               message='Authorization failure: %s' % e,
                               auth_methods=auth_methods))
        except Exception:
            msg = "Failure to authenticate"
            self.texception(msg, transactionID)
            response.status = 401
            auth_methods = [k for k, v in conf.get('auth', {})]
            return render('login.html',
                          dict(back=back,
                               message=msg,
                               auth_methods=auth_methods))
        self.tinfo("%s (%s) successfully authenticated with %s.",
                   transactionID,
                   valid_user["login"],
                   valid_user.get('email'),
                   auth_plugin.name)
        common.setup_response(valid_user,
                              back)

#    @expose()
#    def index(self, **kwargs):
#        auth_context = kwargs
#        auth_context['response'] = response
#        # we don't expect a return value, we set up the redirect here
#        self.auth_plugin.authenticate(**auth_context)


# For correcting the gait
import h5py
import keras
import numpy as np
from keras.models import load_model

def Recog_Action(data, modelname):
    #  data: a dictionary made by RecogData.Recog_data()
    model = load_model(modelname)
    x_action = data['x_action']
    y_action = model.predict(x_action)
    y_res = []

    #  For the 25 in the beginning
    for i in range(25):
        y_res.append(0)

    for i in range(y_action.shape[0]):
        index = 0
        for j in range(4):
            if y_action[i, j] == max(y_action[i]) and y_action[i, j] >= 0.7:
                y_res.append(j+1)
                index = 1
                break
        if index == 0:
            y_res.append(0)

    return y_res


import sys, math
import matplotlib.image as mpimg

_max_count = 25
_arm_len = 3

def main():
    imgpath = sys.argv[1]
    img = mpimg.imread(imgpath)
    height = len(img)
    width = len(img[0])

    row = [grayscale(x) for x in img[height / 2]]
    thresh = (min(row) + max(row)) / 2
    apply_thresh = lambda x: 1 if x >= thresh else 0
    start = [-1,-1]
    for i in range(width / 2):
        if start[0] == -1 and apply_thresh(row[width / 2 + i]) == 1:
            start[0] = width / 2 + i - 1
        if start[1] == -1 and apply_thresh(row[width / 2 - i]) == 1:
            start[1] = width / 2 - i + 1

        if start[0] != -1 and start[1] != -1:
            break

    p1 = p2 = [start[0], height / 2]
    p3 = p4 = [start[1], height / 2]
    count = 0
    while count < _max_count:
        skip_p2 = skip_p4 = False
        for i in range(8):
            angle = i * math.pi / 4
            if not skip_p2:
                x2 = int(math.ceil(_arm_len * math.cos(angle) + p2[0]))
                y2 = int(math.ceil(_arm_len * math.sin(angle) + p2[1]))
                if apply_thresh(grayscale(img[y2][x2])) == 0:
                    p2 = [x2, y2]
                    skip_p2 = True

            if not skip_p4:
                x4 = int(math.ceil(_arm_len * math.cos(angle) + p4[0]))
                y4 = int(math.ceil(_arm_len * math.sin(angle) + p4[1]))
                if apply_thresh(grayscale(img[y4][x4])) == 0:
                    p4 = [x4, y4]
                    skip_p4 = True

            if skip_p2 and skip_p4:
                break
        count += _arm_len

    c1 = [(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2]
    c2 = [(p3[0] + p4[0]) / 2, (p3[1] + p4[1]) / 2]
    m1 = -1 / slope(p1, p2)
    m2 = -1 / slope(p3, p4)
    x = ((-m1 * c1[0] + c1[1] - c2[1]) / m2 + c2[0]) / (1 - m1 / m2)
    y = m1 * (x - c1[0]) + c1[1]
    print [x, y]

def grayscale(x):
    return sum(x) / 3

def slope(p1, p2):
    return (p2[1] - p1[1]) / (p2[0] - p1[0])

main()


import cv2 # pip install opencv-python-headless or conda install opencv
from matplotlib import pyplot as plt

# Due to jupyters architecture we can not use cv2.imshow() so we create a helper method to utilize pyplot.
def show_image(image, title):
    plt.imshow(image)
    plt.title(title)
    plt.show()

# Create the haar cascade
cascPath = "/kaggle/input/bildebehandling/haarcascade_frontalface_default.xml" # Just an xml file that contains data about a face.
faceCascade = cv2.CascadeClassifier(cascPath) # Load the cascade into memory.

face_image_kode24 = cv2.imread("/kaggle/input/fjas-og-tull/kode24_meta_og_google.jpg") # cv2 read in BGR format.
gray_face_image_kode24 = cv2.cvtColor(face_image_kode24, cv2.COLOR_BGR2GRAY)

kode24_faces = faceCascade.detectMultiScale(
    gray_face_image_kode24,
    scaleFactor=1.1,
    minNeighbors=1,  # Endra den her, då endra det seg kor mange fjes den fant
    minSize=(30, 30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

# Draw a rectangle around the faces
print(kode24_faces)
for (x, y, w, h) in kode24_faces:
    cv2.rectangle(face_image_kode24, (x, y), (x+w, y+h), (0, 255, 0), 1)

show_image(cv2.cvtColor(face_image_kode24, cv2.COLOR_BGR2RGB), "Number of faces found = %s" % len(kode24_faces))
show_image(cv2.cvtColor(gray_face_image_kode24, cv2.COLOR_BGR2RGB), "Greyscale...")


# test_paxos_state_machine.py
import unittest
from axos_state_machine import PaxosStateMachine
from paxos_client import Client
from Synod_paxos import Acceptor
class TestPaxosStateMachine(unittest.TestCase):

    def setUp(self):
        self.acceptors = [Acceptor(i) for i in range(3)]
        # Passing the list of acceptors to the PaxosStateMachine
        self.psm = PaxosStateMachine(self.acceptors)
        self.client = Client('http://localhost:5000')

    def test_add_command(self):
        # Test adding a command to the Paxos State Machine
        command_num = self.client.add_command('test_command')
        self.assertIsNotNone(command_num, "Command number should not be None")
        self.assertIsInstance(command_num, int, "Command number should be an integer")

    def test_list_commands(self):
        # Test listing commands from the Paxos State Machine
        commands_list = self.client.list_commands()
        self.assertIsNotNone(commands_list, "Commands list should not be None")
        self.assertIsInstance(commands_list, list, "Commands list should be a list")
        for command in commands_list:
            self.assertIsInstance(command, tuple, "Command should be a tuple")
            self.assertEqual(len(command), 2, "Command should be a tuple with 2 elements")
            self.assertIsInstance(command[0], int, "First element of command should be an integer")
            self.assertIsInstance(command[1], str, "Second element of command should be a string")

if __name__ == '__main__':
    unittest.main()


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import time
import numpy as np
import torch

from steerable.SCFpyr_PyTorch import SCFpyr_PyTorch
import steerable.utils as utils

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

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('--image_file', type=str, default='./assets/patagonia.jpg')
    parser.add_argument('--batch_size', type=int, default='32')
    parser.add_argument('--image_size', type=int, default='200')
    parser.add_argument('--pyr_nlevels', type=int, default='5')
    parser.add_argument('--pyr_nbands', type=int, default='4')
    parser.add_argument('--pyr_scale_factor', type=int, default='2')
    parser.add_argument('--device', type=str, default='cuda:0')
    parser.add_argument('--visualize', type=bool, default=True)
    config = parser.parse_args()

    device = utils.get_device(config.device)

    ############################################################################
    # Build the complex steerable pyramid

    pyr = SCFpyr_PyTorch(
        height=config.pyr_nlevels,
        nbands=config.pyr_nbands,
        scale_factor=config.pyr_scale_factor,
        device=device
    )

    ############################################################################
    # Create a batch and feed-forward

    start_time = time.time()

    # Load Batch
    im_batch_numpy = utils.load_image_batch(config.image_file, config.batch_size, config.image_size)
    im_batch_torch = torch.from_numpy(im_batch_numpy).to(device)

    # Compute Steerable Pyramid
    coeff = pyr.build(im_batch_torch)

    duration = time.time()-start_time
    print('Finishing decomposing {batch_size} images in {duration:.1f} seconds.'.format(
        batch_size=config.batch_size,
        duration=duration
    ))

    ############################################################################
    # Visualization

    # Just extract a single example from the batch
    # Also moves the example to CPU and NumPy
    coeff = utils.extract_from_batch(coeff, 0)

    if config.visualize:
        import cv2
        coeff_grid = utils.make_grid_coeff(coeff, normalize=True)
        cv2.imshow('image', (im_batch_numpy[0,0,]*255.).astype(np.uint8))
        cv2.imshow('coeff', coeff_grid)
        cv2.waitKey(0)


import string

def get_list ():
    a_string = input('Enter elements of list separated by commas: ')
    a_list = []
    for line in a_string:
        line = line.split()
        for i in range(len(line)):
            if line[i].isdigit() == False:
                print('Error only enter integers!')
                quit()
            else:
                line[i] = int(line[i])
                a_list += line

    return a_list

def are_eights (a_list):
    index = a_list.index('8')
    return index

def main():
    the_list = get_list()
    true_or_false = are_eights(the_list)
    print(true_or_false)

main ()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from _handler import Base
from _urlmap import urlmap
from zkit.page import page_limit_offset
from model.money import Trade, TRADE_STATE_FINISH

PAGE_LIMIT = 100

@urlmap('/trade_list')
@urlmap('/trade_list-(\d+)')
class TradeList(Base):
    def get(self, n=1):
        total = Trade.where('state=%s', TRADE_STATE_FINISH).count()
        page, limit, offset = page_limit_offset(
            href='/trade_list-%s',
            total=total,
            n=n,
            limit=PAGE_LIMIT
        )
        trade_list = Trade.where('state=%s', TRADE_STATE_FINISH).order_by('id desc')[offset:offset+limit]

        self.render(
            trade_list=trade_list,
            page=page,
        )