from auth.constants import FAILED, PROCESSING, SUCCEEDED
from auth.core.ticket import TicketFactory
from auth.core.ticket_notification import TicketNotice
from auth.core.ticket_objects import BaseTicketSerializer
from auth.core.ticket_serializer import TicketStateSerializer
from auth.models import Ticket
from auth.models.ticket_models import TicketState
from auth.utils.serializer import DataPageNumberPagination
from auth.views.ticket_serializer import (
    CommonTicketCreateSerializer,
    TicketQuerySerializer,
    TicketStateApproveSerializer,
    TicketStateQuerySerializer,
    TicketStateRetrieveSerializer,
    TicketWithdrawSerializer,
    WXRecallTicketStateApproveSerializer,
)
from common.decorators import detail_route, list_route, params_valid
from common.views import APIModelViewSet
from django.db.models import F
from rest_framework.response import Response

from common import local

class TicketViewSet(APIModelViewSet):
    queryset = Ticket.objects.none()
    serializer_class = BaseTicketSerializer
    pagination_class = DataPageNumberPagination

    # 单据内容暂时不需要加上权限控制
    def get_queryset(self):
        return Ticket.objects.all()

    def serialize_queryset(self, query_params):
        """
        序列化query_set
        @param query_params:
        @return:
        """
        queryset = self.get_queryset().filter(**query_params).all()

        page = self.paginate_queryset(queryset)
        if page is not None:
            data = TicketFactory.serialize_ticket_queryset(page, many=True)
            return self.get_paginated_response(data)

        data = TicketFactory.serialize_ticket_queryset(queryset, many=True)
        return Response(data)

    @params_valid(TicketQuerySerializer, add_params=False)
    def list(self, request, *args, **kwargs):
        """
        @api {get} /v3/auth/tickets/ 获取单据列表
        @apiName ticket_list
        @apiGroup Ticket
        @apiParam {boolean} [is_creator] 是否为创建人
        @apiParam {boolean} [is_processor] 是否为处理候选人
        @apiParam {boolean} [is_processed_by] 是否为处理人
        @apiParam {string} [process_id] 流程ID，仅对通用单据生效，比如 verify_tdm_data、batch_recalc
        @apiSuccessExample {Json} 成功返回
        [
            {
                "id": 41,
                "process_length": 1,
                "ticket_type": "project_biz",
                "created_by": "admin1234",
                "created_at": "2018-12-18 11:59:22",
                "reason": "hello world",
                "status": "succeeded",
                "end_time": "2018-12-18 12:06:25",
                "extra": "{}",
                "process_step": 1,
                "permissions": [
                    {
                        "id": 54,
                        "ticket": "Ticket object",
                        "key": "result_table_id",
                        "value": "591_test_rt",
                        "scope": {
                            "result_table_name": "test_rt",
                            "result_table_info": {
                                "id": "591_test_rt",
                                "name": "test_rt"
                            },
                            "result_table_id": "591_test_rt"
                        },
                        "subject_id": "1",
                        "subject_name": "数据平台对内版",
                        "subject_class": "project",
                        "action": "result_table.query_data",
                        "object_class": "result_table"
                    }
                ],
                "ticket_type_display": "项目申请业务数据",
                "status_display": "成功"
            }
        ]
        """
        username = local.get_request_username()
        status = request.cleaned_params.get("status")
        ticket_type = request.cleaned_params.get("ticket_type")
        process_id = request.query_params.get("process_id")

        query_params = {}
        if request.cleaned_params.get("is_creator"):
            query_params["created_by"] = username
        if request.query_params.get("is_processor"):
            query_params["states__processors__contains"] = Ticket.generate_sub_member(username)
        if request.query_params.get("is_processed_by"):
            query_params["states__processed_by"] = username
        if request.query_params.get("present"):
            query_params["states__process_step__lte"] = F("process_step")
        if status:
            query_params["status"] = status
        if ticket_type:
            query_params["ticket_type"] = ticket_type
        if process_id:
            query_params["process_id"] = process_id

        return self.serialize_queryset(query_params)

    def create(self, request, *args, **kwargs):
        """
        @api {post} /v3/auth/tickets/ 创建单据
        @apiName create_ticket
        @apiGroup Ticket
        @apiParam {String} reason 创建原因
        @apiParam {String} ticket_type 单据类型
        @apiParam {Json} permissions 申请的权限列表
        @apiParamExample {Json} 项目申请结果数据样例
            {
                "reason": "hello world",
                "ticket_type": "project_biz",
                "permissions": [
                    {
                        "subject_id": "1",
                        "subject_class": "project",
                        "action": "result_table.query_data",
                        "object_class": "result_table",
                        "scope": {
                            "result_table_id": "591_test_rt"
                        }
                    }
                ]
            }
        @apiParamExample {Json} 项目申请资源组样例
            {
                "reason": "hello world",
                "ticket_type": "use_resource_group",
                "permissions": [
                    {
                        "subject_id": "1",
                        "subject_class": "project_info",
                        "action": "resource_group.use",
                        "object_class": "resource_group",
                        "scope": {
                            "resource_group_id": "tgqa"
                        }
                    }
                ]
            }
        @apiSuccessExample {Json} 项目申请结果数据返回样例结果
            {
                "id": 45,
                "process_length": 1,
                "ticket_type": "project_biz",
                "created_by": "admin1234",
                "created_at": "2018-12-21 11:55:39",
                "reason": "hello world",
                "status": "processing",
                "end_time": null,
                "extra": null,
                "process_step": 0,
                "permissions": [
                    {
                        "id": 58,
                        "ticket": "Ticket object",
                        "key": "result_table_id",
                        "value": "591_test_rt",
                        "scope": {
                            "result_table_name": "test_rt",
                            "result_table_info": {
                                "id": "591_test_rt",
                                "name": "test_rt"
                            },
                            "result_table_id": "591_test_rt"
                        },
                        "subject_id": "1",
                        "subject_name": "数据平台对内版",
                        "subject_class": "project",
                        "action": "result_table.query_data",
                        "object_class": "result_table"
                    }
                ],
                "ticket_type_display": "项目申请业务数据",
                "status_display": "处理中"
            }
        """
        data = request.data.copy()
        data["created_by"] = local.get_request_username()
        return Response(TicketFactory(data["ticket_type"]).generate_ticket_data(data))

    def retrieve(self, request, *args, **kwargs):
        """
        @api {get} /v3/auth/tickets/:ticket_id/ 查询单据
        @apiName ticket_query
        @apiGroup Ticket
        @apiSuccessExample {Json} 成功返回 Response.data
            {
                "id": 45,
                "process_length": 1,
                "ticket_type": "project_biz",
                "created_by": "admin1234",
                "created_at": "2018-12-21 11:55:39",
                "reason": "hello world",
                "status": "processing",
                "end_time": null,
                "extra": "{}",
                "process_step": 0,
                "permissions": [
                    {
                        "id": 58,
                        "ticket": "Ticket object",
                        "key": "result_table_id",
                        "value": "591_test_rt",
                        "scope": {
                            "result_table_name": "test_rt",
                            "result_table_info": {
                                "id": "591_test_rt",
                                "name": "test_rt"
                            },
                            "result_table_id": "591_test_rt"
                        },
                        "subject_id": "1",
                        "subject_name": "数据平台对内版",
                        "subject_class": "project",
                        "action": "result_table.query_data",
                        "object_class": "result_table"
                    }
                ],
                "ticket_type_display": "项目申请业务数据",
                "status_display": "处理中"
            }
        """
        ticket = self.get_object()
        data = TicketFactory.serialize_ticket_queryset(ticket)
        return Response(data)

    @list_route(methods=["get"])
    def ticket_types(self, request):
        """
        @api {get} /v3/auth/tickets/ticket_types/ 获取单据类型
        @apiName ticket_types
        @apiGroup Ticket
        @apiSuccessExample {Json} 成功返回
        [
            {id: 'APP', name: '业务数据'},
        ]
        """
        return Response(TicketFactory.list_ticket_types())

    @list_route(methods=["get"])
    def ticket_status(self, request):
        """
        @api {get} /v3/auth/tickets/ticket_status/ 获取单据状态列表
        @apiName ticket_types
        @apiGroup Ticket
        @apiSuccessExample {Json} 成功返回
        [
            {id: 'processing', name: '处理中'},
        ]
        """
        return Response(TicketFactory.list_ticket_status())

    @list_route(methods=["post"])
    @params_valid(CommonTicketCreateSerializer, add_params=False)
    def create_common(self, request):
        """
        @api {post} /v3/auth/tickets/create_common/ 创建单据
        @apiName create_common_ticket
        @apiGroup Ticket
        @apiParam {String} reason 创建原因
        @apiParam {String} ticket_type 单据类型
        @apiParam {String} process_id 任务ID
        @apiParam {String} content 任务描述
        @apiParam {String} callback_url 回调 URL，审批结果会通过 callback_url 进行回调
        @apiParam {Dict} [ticket_step_params] 单据步骤参数
        @apiParam {String} [auto_approve] 是否自动审批
        @apiParamExample {Json} verify_tdm_data 请求示例
            {
                "reason": "hello world",
                "ticket_type": "verify_tdm_data",
                "process_id": "111",
                "content": "用户要接入 TDM XX 表数据，是否允许",
                "callback_url": "http://xxx.com/xxx"
            }
        @apiParamExample {Json} create_resource_group 请求示例
            {
                "reason": "hello world",
                "ticket_type": "create_resource_group",
                "ticket_step_params": {
                    "0&process_scope_id": "591"   # 表示第一步的 process_scope_id 参数赋值为 591
                },
                "process_id": "111",
                "content": "现在要创建 XXX 资源组",
                "callback_url": "http://xxx.com/xxx"
            }
        @apiSuccessExample {Json} 成功返回
            {
                "id": 420,
                "ticket_type_display": "TDM原始数据接入申请",
                "status_display": "处理中",
                "process_length": 1,
                "ticket_type": "verify_tdw_data",
                "created_by": "request_user",
                "created_at": "2019-06-24 15:57:42",
                "reason": "test",
                "status": "processing",
                "end_time": null,
                "process_step": 0,
                "processors": ["admin"],
                "state_id": 358,
                "extra_info": {
                    "content": "用户要接入 TDM XX 表数据，是否允许",
                    "process_id": "111",
                    "callback_url": "http://xxx.com/xxx"
                },
                "permission": []
            }
        @apiSuccessExample {Json} 回调示例
            curl -XPOST http://xxx.com/xxx -d
            {
                "operator": "user01",
                "message": "ok",
                "process_id": "111",
                "status": "succeeded"  # succeeded=通过 | failed=拒绝 | stopped=中止
            }
        """
        data = request.cleaned_params
        data_restr = {}
        data_restr["created_by"] = local.get_request_username()
        data_restr["ticket_type"] = data["ticket_type"]
        data_restr["reason"] = data["reason"]
        data_restr["ticket_step_params"] = data.get("ticket_step_params", {})
        data_restr["auto_approve"] = data.get("auto_approve", True)
        extra_info = {
            "process_id": data["process_id"],
            "ticket_step_params": data_restr["ticket_step_params"],
            "content": data["content"],
            "callback_url": data.get("callback_url"),
        }
        data_restr["extra"] = extra_info
        data_restr["permission"] = []
        res = TicketFactory(data_restr["ticket_type"]).generate_ticket_data(data_restr)[0]
        return Response(res)

    @detail_route(methods=["post"], url_path="withdraw")
    @params_valid(TicketWithdrawSerializer, add_params=False)
    def withdraw(self, request, pk):
        """
        @api {post} /v3/auth/tickets/:id/withdraw/ 撤销单据
        @apiName withdraw_ticket
        @apiGroup Ticket
        @apiParam {String} process_message 处理信息
        @apiSuccessExample {json}
        {
            "id": 74,
            "extra": {
                "content": "对《项目1》->《任务1》的离线结果表 1_xx, 2_xx 进行重算",
                "process_id": "111_xx"
            },
            "ticket_type_display": "离线补录申请",
            "status_display": "已终止",
            "process_length": 1,
            "ticket_type": "batch_recalc",
            "created_by": "request_user",
            "created_at": "2019-06-28 18:10:50",
            "reason": "test",
            "status": "stopped",
            "end_time": "2019-06-28 18:10:50",
            "process_step": 0,
            "processors": ["admin"],
            "state_id": 74,
            "extra_info": {
                "content": "对《项目1》->《任务1》的离线结果表 1_xx, 2_xx 进行重算",
                "process_id": "111_xx"
            }
        }
        """
        ticket = self.get_object()
        username = local.get_request_username()
        result = TicketFactory.withdraw(
            ticket,
            request.cleaned_params["process_message"],
            username,
        )
        return Response(result)

class TicketStateViewSet(APIModelViewSet):
    queryset = TicketState.objects.none()
    serializer_class = TicketStateSerializer
    pagination_class = DataPageNumberPagination

    # 单据内容暂时不需要做权限控制
    def get_queryset(self):
        """
        返回所有审批步骤，需要考虑下是否加上用户过滤环节
        """
        return TicketState.objects.all()

    def serialize_queryset(self, query_params, show_display=False):
        """
        序列化query_set
        @param query_params: 查询参数
        @param show_display: 是否返回显示字段
        @return:
        """
        queryset = self.get_queryset().filter(**query_params).all()

        paged_queryset = self.paginate_queryset(queryset)
        if paged_queryset is not None:
            data = TicketFactory.serialize_state_queryset(paged_queryset, many=True, show_display=show_display)
            return self.get_paginated_response(data)

        data = TicketFactory.serialize_state_queryset(queryset, many=True, show_display=show_display)
        return Response(data)

    @params_valid(TicketStateQuerySerializer, add_params=False)
    def list(self, request, *args, **kwargs):
        """
        @api {get} /v3/auth/ticket_states/ 获取单据列表
        @apiName ticket_state_list
        @apiGroup TicketState
        @apiParam {int} ticket_id 单据标识
        @apiParam {boolean} is_processor 是否为处理候选人
        @apiParam {boolean} is_processed_by 是否为处理人
        @apiSuccessExample {json} 查询结果样例
        [
            {
                "id": 1,
                "processed_at": "2018-12-18 12:06:26",
                "processors": [
                    "processor666"
                ],
                "processed_by": "processor666",
                "process_step": 0,
                "process_message": "hello you are succeeded",
                "status": "succeeded",
                "ticket": {
                    "id": 41,
                    "process_length": 1,
                    "ticket_type": "project_biz",
                    "created_by": "admin1234",
                    "created_at": "2018-12-18 11:59:22",
                    "reason": "hello world",
                    "status": "succeeded",
                    "end_time": "2018-12-18 12:06:25",
                    "extra": "{}",
                    "process_step": 1,
                    "permissions": [
                        {
                            "id": 54,
                            "ticket": "Ticket object",
                            "key": "result_table_id",
                            "value": "591_test_rt",
                            "scope": {
                                "result_table_name": "test_rt",
                                "result_table_info": {
                                    "id": "591_test_rt",
                                    "name": "test_rt"
                                },
                                "result_table_id": "591_test_rt"
                            },
                            "subject_id": "1",
                            "subject_name": "数据平台对内版",
                            "subject_class": "project",
                            "action": "result_table.query_data",
                            "object_class": "result_table"
                        }
                    ],
                    "ticket_type_display": "项目申请业务数据",
                    "status_display": "成功"
                },
                "status_display": "成功"
            }
        ]
        """
        query_params = {}
        username = local.get_request_username()
        status = request.cleaned_params.get("status")
        ticket__ticket_type = request.cleaned_params.get("ticket__ticket_type")
        is_processor = request.cleaned_params.get("is_processor")
        is_processed_by = request.cleaned_params.get("is_processed_by")
        ticket_id = request.cleaned_params.get("ticket_id")
        if ticket_id:
            query_params["ticket_id"] = ticket_id
        if is_processor:
            query_params["processors__contains"] = Ticket.generate_sub_member(username)
            query_params["status__in"] = [PROCESSING, SUCCEEDED, FAILED]
        if status:
            query_params["status"] = status
        if ticket__ticket_type:
            query_params["ticket__ticket_type"] = ticket__ticket_type
        if is_processed_by:
            query_params["processed_by"] = username

        return self.serialize_queryset(query_params)

    @params_valid(TicketStateRetrieveSerializer, add_params=False)
    def retrieve(self, request, pk):
        """
        @api {get} /v3/auth/ticket_states/:ticket_state_id/ 查询单据及关联状态
        @apiName approve_state
        @apiGroup TicketState
        @apiParam {String} status 审批状态
        @apiParam {String} process_message 处理信息
        @apiSuccessExample {json} 审批结果样例
        {
            states: [
                {
                    id: 1702,
                    status_display: "已同意",
                    processed_at: "2019-09-17 15:19:35",
                    processors: [
                        "user01"
                    ],
                    processed_by: "user01",
                    process_step: 1,
                    process_message: "同意",
                    status: "succeeded"
                }
            ],
            "ticket": {
                "id": 42,
                "process_length": 1,
                "ticket_type": "project_biz",
                "created_by": "admin1234",
                "created_at": "2018-12-18 19:47:00",
                "reason": "adf",
                "status": "processing",
                "end_time": null,
                "extra": "{}",
                "process_step": 0,
                "permissions": [
                    {
                        "id": 55,
                        "ticket": "Ticket object",
                        "key": "bk_biz_id",
                        "value": "591",
                        "scope": {
                            "bk_biz_id": "591",
                            "bk_biz_info": {
                                "id": "591",
                                "name": "unknown biz"
                            },
                            "bk_biz_name": "unknown biz"
                        },
                        "subject_id": "sdf",
                        "subject_name": "",
                        "subject_class": "project",
                        "action": "result_table.query_data",
                        "object_class": "biz"
                    }
                ],
                "ticket_type_display": "项目申请业务数据",
                "status_display": "处理中"
            },
            "status_display": "处理中"
        }
        """
        instance = self.get_object()
        instance_data = TicketFactory.serialize_state_queryset(
            instance, ticket_type=instance.ticket.ticket_type, many=False
        )
        data = self.serialize_queryset({"ticket_id": instance_data["ticket"]["id"]}, show_display=True).data
        ticket = {}
        for _data in data:
            ticket = _data.pop("ticket")
        return Response({"ticket": ticket, "states": data})

    @detail_route(methods=["post"], url_path="approve")
    @params_valid(TicketStateApproveSerializer, add_params=False)
    def approve(self, request, pk):
        """
        @api {post} /v3/auth/ticket_states/:id/approve/ 审批单据
        @apiName approve_state
        @apiGroup TicketState
        @apiParam {String} status 审批状态
        @apiParam {String} process_message 处理信息
        @apiSuccessExample {json} 审批结果样例
        {
            "id": 3,
            "processed_at": "2018-12-21 12:10:02",
            "processors": [
                "processor666"
            ],
            "processed_by": "processor666",
            "process_step": 0,
            "process_message": "hello you are succeeded",
            "status": "succeeded",
            "ticket": {
                "id": 43,
                "process_length": 1,
                "ticket_type": "project_biz",
                "created_by": "admin1234",
                "created_at": "2018-12-18 20:02:52",
                "reason": "asdf",
                "status": "succeeded",
                "end_time": "2018-12-21 12:10:02",
                "extra": "{}",
                "process_step": 1,
                "permissions": [
                    {
                        "id": 56,
                        "ticket": "Ticket object",
                        "key": "bk_biz_id",
                        "value": "591",
                        "scope": {
                            "bk_biz_id": "591",
                            "bk_biz_info": {
                                "id": "591",
                                "name": "unknown biz"
                            },
                            "bk_biz_name": "unknown biz"
                        },
                        "subject_id": "213",
                        "subject_name": "goodjob",
                        "subject_class": "project",
                        "action": "result_table.query_data",
                        "object_class": "biz"
                    }
                ],
                "ticket_type_display": "项目申请业务数据",
                "status_display": "成功"
            },
            "status_display": "成功"
        }
        """
        instance = self.get_object()
        username = local.get_request_username()
        result = TicketFactory.approve(
            instance,
            request.cleaned_params["status"],
            request.cleaned_params["process_message"],
            username,
            add_biz_list=True,
        )
        return Response(result)

    @list_route(methods=["post"])
    @params_valid(WXRecallTicketStateApproveSerializer, add_params=False)
    def wx_recall(self, request):
        """
        @api {post} /v3/auth/ticket_states/wx_recall/ 审批单据
        @apiName approve_state
        @apiGroup TicketState
        @apiParam {String} status 审批状态
        @apiParam {String} taskid bkdata:ticket_id:md5(ticket_id+APP_TOKEN)
        @apiSuccessExample {json} 审批结果样例
        {
            "id": 3,
            "processed_at": "2018-12-21 12:10:02",
            "processors": [
                "processor666"
            ],
            "processed_by": "processor666",
            "process_step": 0,
            "process_message": "hello you are succeeded",
            "status": "succeeded",
            "ticket": {
                "id": 43,
                "process_length": 1,
                "ticket_type": "project_biz",
                "created_by": "admin1234",
                "created_at": "2018-12-18 20:02:52",
                "reason": "asdf",
                "status": "succeeded",
                "end_time": "2018-12-21 12:10:02",
                "extra": "{}",
                "process_step": 1,
                "permissions": [
                    {
                        "id": 56,
                        "ticket": "Ticket object",
                        "key": "bk_biz_id",
                        "value": "591",
                        "scope": {
                            "bk_biz_id": "591",
                            "bk_biz_info": {
                                "id": "591",
                                "name": "unknown biz"
                            },
                            "bk_biz_name": "unknown biz"
                        },
                        "subject_id": "213",
                        "subject_name": "goodjob",
                        "subject_class": "project",
                        "action": "result_table.query_data",
                        "object_class": "biz"
                    }
                ],
                "ticket_type_display": "项目申请业务数据",
                "status_display": "成功"
            },
            "status_display": "成功"
        }
        """
        taskid = request.cleaned_params["taskid"]
        ticket_id = int(taskid.split(":")[1])
        TicketNotice().check_taskid(ticket_id, taskid)
        instance = TicketState.objects.filter(ticket=ticket_id, status=PROCESSING).first()
        username = request.cleaned_params["verifier"]
        status = request.cleaned_params["result"]
        result_status = FAILED
        if status == "1":
            result_status = SUCCEEDED
        result = TicketFactory.approve(
            instance, result_status, request.cleaned_params["message"], username, add_biz_list=True
        )
        return Response(result)

    @list_route(methods=["get"])
    def todo_count(self, request):
        return Response(TicketState.todo_count(local.get_request_username()))


import pandas as pd
import numpy as np

def readexcel(fileName):
    fileName=r"C:\Users\zlh\Desktop\数据分析方法实验\实验三、四\play.xlsx"
    data = pd.read_excel(fileName)
    # print(type(data))
    train_data = np.array(data)  # np.ndarray()
    excel_list = train_data.tolist()  # list
    print(excel_list)

    return excel_list

if __name__=="__main__":
    fileName=r"C:\Users\zlh\Desktop\数据分析方法实验\实验三、四\play.xlsx"
    readexcel(fileName)

数据分析方法实验/test.py


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy.polynomial import Polynomial

# Define a polynomial named 'f'
f = Polynomial([2.0, 1.0, -6.0, -2.0, 2.5, 1.0])

# Define the first derivative of polynomial 'f' named 'f_prime'
f_prime = f.deriv(1)

# Draw the X-axis
plt.axhline(y=0, color='k')

# Generate 100 values of x.
x = np.linspace(-2.5, 1.6, 100)

# Calculate y-values of corresponding x-values of f(x).
y = f(x)

# Plot the graph of f(x) using x-values and y-values
plt.plot(x, y)

# Plot the roots of the graph
plt.plot(f.roots(), f(f.roots()), 'ro')

# Print the roots of the function f(x)
print(f.roots())

# Calcuate y-values for corresponding x-values of f'(x).
y = f_prime(x)

# Plot the graph of f'(x)
plt.plot(x, y)

# Plot the roots of f'(x). Notice that, where f'(x) is zero the slop of f(x) is zero.
plt.plot(f_prime.roots(), f_prime(f_prime.roots()), 'bo')

# Print the roots of f'(x).
print(f_prime.roots())

# Start with an initial value
# complete the line below
xk = 5

# Create a list for storing values of x's after each iteration
list_x = [xk, ]

# Create a list for storing values of f(x)'s after each iteration
list_f = [f(xk), ]

while True:
        #+--------------------+
    #| Start of your code |
    #+--------------------+

    # Calculate newer values of xk
    k=xk-f(xk)/f_prime(xk);
    xk=k;
    list_x.append(xk);
    list_f.append(f(xk));
    er=abs(list_x[-1]-list_x[-2])/list_x[-1] ;
    if er<1e-6:
        break;

    # append xk into list_x

    # append f(xk) into list_f

    # Write the breaking condition; answer should be accurate to 6 decimal places

    #+------------------+
    #| End of your code |
    #+------------------+

df = pd.DataFrame({"x": list_x, "f(x)": list_f})

print(df)
plt.show();


import tkinter as artn

value_1=0
value_2=0
value_0=0

def calculation():
##    global value_0
    try:
        value_1 = int(btny_3.get())
        value_2 = int(btny_4.get())
        value_0 = value_1 * value_2
        if (value_0<=0):
            btny_3.delete(0, 'end')
            btny_4.delete(0, 'end')
            btny_7['text'] = "Пожалуйста, введите \nдругое значение"
        else:
            btny_7['text'] = f"Размер оплаты \n равен {value_0} руб."
            btny_3['state'] = "readonly"
            btny_4['state'] = "readonly"
    except:
        btny_3.delete(0, 'end')
        btny_4.delete(0, 'end')
        btny_7['text'] = "Ошибка символа, \nвведите число!"

def cancellation():
    value_0=0
    btny_7['text'] = f"Размер оплаты \n равен {value_0} руб."
    btny_3['state'] = "normal"
    btny_4['state'] = "normal"
    btny_3.delete(0, 'end')
    btny_4.delete(0, 'end')

win = artn.Tk()
win.title('Задание_1')
win.resizable(False, False)

btny_1 = artn.Label(win, text = "Расход электроэнергии: ")
btny_1.grid(row=0, column=0, pady=5, padx=5)

btny_2 = artn.Label(win, text = "Тариф за 1 КВт/ч: ")
btny_2.grid(row=1, column=0, pady=5, padx=5)

btny_3 = artn.Entry(win, state = "normal")
btny_3.grid(row=0, column=1, pady=5, padx=5)

btny_4 = artn.Entry(win, state = "normal")
btny_4.grid(row=1, column=1, pady=5, padx=5)

btny_5 = artn.Button(win, text = "Расчитать", command = calculation)
btny_5.grid(row=2, column=0, sticky="we", pady=5, padx=5)

btny_6 = artn.Button(win, text = "Отмена", command = cancellation)
btny_6.grid(row=3, column=0, sticky="we", pady=5, padx=5)

btny_7 = artn.Label(win, text = "Нажмите (расчитать)\nдля расчета" )
btny_7.grid(row=2, column=1, rowspan=2, pady=5, padx=5)

win.mainloop()


import os
import multiprocessing

input_data_path = "/data/disk2/private/zhx/scm/data/pretrain"
output_data_path = "/data/disk2/private/zhx/scm/data/pretrain_bin"
os.makedirs(output_data_path,exist_ok=True)

num_files = 100
num_process = 5

q = multiprocessing.Queue()
bq = multiprocessing.Queue()

for a in range(1, num_files + 1):
    q.put(a)

def work():
    while True:
        a = q.get(timeout=5)

        os.system("""
        python3 create_instances_fast.py --input_file_prefix %s/%d --output_file %s/%d --vocab_file ../utils/word2id.txt --dupe_factor 1 --max_seq_length 512 --max_predictions_per_seq 80 --random_seed 0
""" % (input_data_path, a, output_data_path, a))

        bq.put(1)

if __name__ == "__main__":
    process_list = []
    for a in range(0, num_process):
        process = multiprocessing.Process(target=work)
        process_list.append(process)
        process_list[-1].start()

    done = 0

    while done < num_files:
        _ = bq.get()

        done += _

        print("%d/%d\r" % (done, num_files), end="")


'''This script demonstrates using dropout in a single-layer auto-encoder for
MNIST data

'''

import os
import matplotlib.pylab as plt

from pydeep.neural import *
import pydeep.utils.utils

mnist_path = os.path.join(os.environ['PYDEEP_HOME'], 'demo',  'mnist', 'train-images-idx3-ubyte.npy')
data = np.load(mnist_path).astype('float') / 255
train = data
tp = NetTrainParams()
tp.maxepoch=200
tp.batchsize=100
tp.eta = scalar_schedule.ConstantSchedule(0.01)
tp.mu  = scalar_schedule.ConstantSchedule(0.5)
arch = [784, 100, 784]
lts=['Logistic', 'Linear']
regs = [NetReg() for lt in lts]
for reg in regs:
    reg.dropout=True
    reg.drop_rate = 0.5
    reg.max_constraint = True
    reg.max_unit_weight = 10
regs[0].drop_rate = 0.2
net = Net(arch, lts, regs)
train_sgd(net, train, train, tp)

Wimg = pydeep.utils.utils.tile_raster_images(net.layers[0].W.transpose(), (28,28), (10,10))

plt.figure(1)
plt.imshow(Wimg)
plt.set_cmap('gray')
plt.axis('off')
plt.show()


from host import *
import argparse
from time import sleep

parser = argparse.ArgumentParser()

parser.add_argument('--start',
                    dest='start',
                    action="store_true",
                    default=False)

parser.add_argument('--stop',
                    dest="stop",
                    action="store_true",
                    default=True)

parser.add_argument('-P',
                    dest="P",
                    default=4)

parser.add_argument('--cpu',
                    dest="cpu",
                    default=None)

args = parser.parse_args()
if args.start:
    args.stop = False
if args.stop:
    args.start = False

hosts = []
hlist = HostList()

for h in host_ips:
    hst = Host(h)
    hosts.append(hst)
    hlist.append(hst)

def iperf_server():
    cmd = "iperf -s"
    if args.cpu:
        cmd = "taskset -c %s %s" % (args.cpu, cmd)
    return cmd

def iperf_client(dst,time='3600'):
    cmd = "iperf -c %s -P %s -t %s" % (dst.get_10g_ip(), args.P, time)
    if args.cpu:
        cmd = "taskset -c %s %s" % (args.cpu, cmd)
    return "(%s &)" % cmd

def start_mesh():
    for h in hosts:
        h.cmd_async(iperf_server())
        h.configure_rps()

    sleep(2)
    for i,hi in enumerate(hosts):
        hi.delay = True
        for j,hj in enumerate(hosts):
            if i == j:
                continue
            hi.cmd_async(iperf_client(hj))
        hi.delayed_async_cmds_execute()
    return

def stop_mesh():
    hlist.cmd("killall -9 iperf")

if args.start:
    start_mesh()
if args.stop:
    stop_mesh()


import numpy as np
import os
from keras.preprocessing.image import image

def preprocessing(path, X, y):
    img_list = os.listdir(path)
    for img_name in img_list:
        img_path = path + '/' + img_name
        img = image.load_img(img_path, color_mode="grayscale", target_size=(150, 150))
        img_tensor = image.img_to_array(img)
        X.append(img_tensor)
        if path.split("/")[-1] == "NORMAL":
            y.append([0])
        else:
            y.append([1])

def save_data(X_train, X_val, X_test, y_train, y_val, y_test):
    np.save("D:/dataset/train/X_train.npy", X_train)
    np.save("D:/dataset/val/X_val.npy", X_val)
    np.save("D:/dataset/test/X_test.npy", X_test)
    np.save("D:/dataset/train/y_train.npy", y_train)
    np.save("D:/dataset/val/y_val.npy", y_val)
    np.save("D:/dataset/test/y_test.npy", y_test)

train_normal_path = "D:/X-Ray image/train/NORMAL"
train_pneumonia_path = "D:/X-Ray image/train/PNEUMONIA"
val_normal_path = "D:/X-Ray image/val/NORMAL"
val_pneumonia_path = "D:/X-Ray image/val/PNEUMONIA"
test_normal_path = "D:/X-Ray image/test/NORMAL"
test_pneumonia_path = "D:/X-Ray image/test/PNEUMONIA"

X_train, y_train = [], []
X_val, y_val = [], []
X_test, y_test = [], []

preprocessing(train_normal_path, X_train, y_train)
preprocessing(train_pneumonia_path, X_train, y_train)
X_train = np.array(X_train)
y_train = np.array(y_train)

preprocessing(val_normal_path, X_val, y_val)
preprocessing(val_pneumonia_path, X_val, y_val)
X_val = np.array(X_val)
y_val = np.array(y_val)

preprocessing(test_normal_path, X_test, y_test)
preprocessing(test_pneumonia_path, X_test, y_test)
X_test = np.array(X_test)
y_test = np.array(y_test)

X_train_mean = np.mean(X_train)
X_train_std = np.std(X_train)
X_train = (X_train - X_train_mean) / X_train_std
X_val = (X_val - X_train_mean) / X_train_std
X_test = (X_test - X_train_mean) / X_train_std

save_data(X_train, X_val, X_test, y_train, y_val, y_test)


import PyPDF2
import sys
import os

# run this program from the command line with one argument after the .py file: the name of the combined pdf to be
# created. The program loops through each item in the the present working directory and merges all pdf files into one

new_pdf_name = sys.argv[1]
source_dir = os.getcwd()

# create merger object
merger = PyPDF2.PdfFileMerger()

# loop through all files in directory
for file in os.listdir(source_dir):
    if file.endswith('pdf'):
        merger.append(file)
merger.write(new_pdf_name)


import pygame as pg
import pygame.mouse as mouse
import constants
import os
from pygame.locals import *
from player import Player
from obstacles import ObstacleSet
from player import Player
from map import Map
from tokens import TokenSet
from background import StarSet, CloudSet

pg.init()
font = pg.font.Font("assets/slkscre.ttf", 32)
screen = pg.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT])

def main():
    plr = Player()
    plr.rect.centerx = 2 * constants.SCREEN_WIDTH / 3
    plr.rect.centery = constants.SCREEN_HEIGHT / 2

    running = True
    clock = pg.time.Clock()
    map: Map = Map(ObstacleSet(), TokenSet(), StarSet(), CloudSet())
    score: int = 0
    while running:
        clock.tick(constants.FPS)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
        # Update map
        map.update()

        # Check if mouse down, update size of player sprite
        plr.update(mouse.get_pressed()[0], constants.SCREEN_HEIGHT - 10)

        # Check for collisions here
        if map.check_for_collision(plr):
            break

        score += map.check_for_token_eat(plr)

        # Draw the actual content
        screen.fill(constants.BGCOLOR)
        for star in map.star_set.stars:
            screen.blit(star.surface, star.rect)
        for cloud in map.cloud_set.clouds:
            screen.blit(cloud.surface, cloud.rect)
        for obstacle in map.obstacle_set.obstacles:
            for block in obstacle.blocks:
                screen.blit(block.surface, block.rect)
        for token in map.token_set.get_tokens():
            screen.blit(token.surface, token.rect)

        facePosition = (plr.surf.get_width() - constants.PLAYER_WIDTH, plr.surf.get_height()/2 - constants.PLAYER_WIDTH/2)
        faceSize = (constants.PLAYER_WIDTH, constants.PLAYER_WIDTH)
        plr.surf.fill(constants.PLAYER_COLOR)
        plr.surf.blit(pg.transform.scale(pg.image.load(os.path.join("assets", "face.png")), faceSize), facePosition)
        screen.blit(plr.surf, plr.rect)
        pg.display.flip()

    game_over_running = True
    while game_over_running:
        clock.tick(constants.FPS)
        pg.display.flip()
        for event in pg.event.get():
            if event.type == pg.QUIT:
                game_over_running = False
        screen.fill(constants.GAME_OVER_COLOR)
        img = pg.image.load("assets/game_over.png")
        text = font.render('Score: ' + str(score), True, (0, 0, 0))
        screen.blit(text, (constants.SCREEN_WIDTH / 2 - text.get_width() / 2, constants.SCREEN_HEIGHT / 2 + (img.get_height() / 2) + 20))
        screen.blit(img, (constants.SCREEN_WIDTH / 2 - (img.get_width() / 2), constants.SCREEN_HEIGHT / 2 - (img.get_height() / 2)))
    print(score)

if __name__ == "__main__":
    main()


# Problem M 22
# Solution

# Time O(n) | Space O(n)
def BalancedBrackets(parens):

    # if is not completely divisible by 0, its not palindrome
    if len(parens) % 2 != 0:
        return False

    # stack to keep track of the opening parens
    stack = []

    # sets to compare the parens with
    openingParens = set('({[')
    completeParens = set([('(', ')'), ('{', '}'), ('[', ']')])

    # iterate over the parens
    for paren in parens:

        # if the current paren is in the opening parens, append to stack
        if paren in openingParens:
            stack.append(paren)

        else:
            # without a opening paren, it can't be a palindrome
            if len(stack) == 0:
                return False

            # pop the last open paren
            lastOpen = stack.pop()

            # set lastOpen and current paren to compare against the complete set
            # if not in complete set, return false
            if(lastOpen, paren) not in completeParens:
                return False

    # return true if len of stack is 0. It will be 0 if there are no more parens left and its balanced
    return len(stack) == 0

print(BalancedBrackets("([]]{)"))


from sensor_measurement_parser import BluetoothParser

def main():
    parser = BluetoothParser()
    responses = []
    for c in "LOCALIZE,1\n":
        r = parser.add_data(c)
        responses.append(r)
    for c in "1,2,3,4\n":
        r = parser.add_data(c)
        responses.append(r)
    assert responses == [None] * 11 + [None] * 7 + [("LOCALIZE", 1, 1, 2, 3, 4)]

if __name__ == "__main__":
    main()


from bs4 import BeautifulSoup
import requests

# Set the base URL for the website
base_url = "https://ec.europa.eu"

# Set the initial URL
url = "https://ec.europa.eu/clima/ets/transaction.do?languageCode=fr&startDate=&endDate=&transactionStatus=4&fromCompletionDate=&toCompletionDate=&transactionID=&transactionType=-1&suppTransactionType=-1&originatingRegistry=-1&destinationRegistry=-1&originatingAccountType=-1&destinationAccountType=-1&originatingAccountIdentifier=&destinationAccountIdentifier=&originatingAccountHolder=&destinationAccountHolder=&search=Search&currentSortSettings="

# Set a flag to control the loop
done = False

# Loop until the flag is set to True
while not done:
    # Make a request to the website
    response = requests.get(url)

    # Parse the HTML content
    soup = BeautifulSoup(response.content, "html.parser")

    # Find all tables on the page
    tables = soup.find_all("table")

    # Iterate through the tables and print their data
    for table in tables:
        rows = table.find_all("tr")
        for row in rows:
            cells = row.find_all("td")
            for cell in cells:
                print(cell.text)

    # Find the "nextList" button
    next_button = soup.find("a", {"title": "Go to the next page"})
    if next_button:
        # If the "nextList" button is found, get its href attribute
        next_url = next_button["href"]
        # Concatenate the base URL and the href attribute to get the full URL
        url = base_url + next_url
    else:
        # If the "nextList" button is not found, set the flag to True to exit the loop
        done = True


import argparse
import contextlib
import json
import os
import shutil
import subprocess
import sys
import tempfile

import tensorflow as tf
from tensorflow.python.platform import resource_loader

parser = argparse.ArgumentParser(
    description="Script to move TFLite models from pre-release schema to "
    "new schema.")
parser.add_argument(
    "input",
    type=str,
    help="Input TensorFlow lite file in `.json`, `.bin` or `.tflite` format.")
parser.add_argument(
    "output",
    type=str,
    help="Output json or bin TensorFlow lite model compliant with "
    "the new schema. Extension must be `.json`, `.bin` or `.tflite`.")

# RAII Temporary Directory, because flatc doesn't allow direct use of tempfiles.
@contextlib.contextmanager
def TemporaryDirectoryResource():
  temporary = tempfile.mkdtemp()
  try:
    yield temporary
  finally:
    shutil.rmtree(temporary)

class Converter:
  """Converts TensorFlow flatbuffer models from old to new version of schema.

  This can convert between any version to the latest version. It uses
  an incremental upgrade strategy to go from version to version.

  Usage:
    converter = Converter()
    converter.Convert("a.tflite", "a.json")
    converter.Convert("b.json", "b.tflite")
  """

  def __init__(self):
    # TODO(aselle): make this work in the open source version with better
    # path.
    paths_to_try = [
        "../../../../flatbuffers/flatc",  # not bazel
        "../../../../external/flatbuffers/flatc"  # bazel
    ]
    for p in paths_to_try:
      self._flatc_path = resource_loader.get_path_to_datafile(p)
      if os.path.exists(self._flatc_path): break

    def FindSchema(base_name):
      return resource_loader.get_path_to_datafile("%s" % base_name)

    # Supported schemas for upgrade.
    self._schemas = [
        (0, FindSchema("schema_v0.fbs"), True, self._Upgrade0To1),
        (1, FindSchema("schema_v1.fbs"), True, self._Upgrade1To2),
        (2, FindSchema("schema_v2.fbs"), True, self._Upgrade2To3),
        (3, FindSchema("schema_v3.fbs"), False, None)  # Non-callable by design.
    ]
    # Ensure schemas are sorted, and extract latest version and upgrade
    # dispatch function table.
    self._schemas.sort()
    self._new_version, self._new_schema = self._schemas[-1][:2]
    self._upgrade_dispatch = {
        version: dispatch
        for version, unused1, unused2, dispatch in self._schemas}

  def _Read(self, input_file, schema, raw_binary=False):
    """Read a tflite model assuming the given flatbuffer schema.

    If `input_file` is in bin, then we must use flatc to convert the schema
    from binary to json.

    Args:
      input_file: a binary (flatbuffer) or json file to read from. Extension
        must  be `.tflite`, `.bin`, or `.json` for FlatBuffer Binary or
        FlatBuffer JSON.
      schema: which schema to use for reading
      raw_binary: whether to assume raw_binary (versions previous to v3)
        that lacked file_identifier require this.

    Raises:
      RuntimeError: 1. When flatc cannot be invoked.
                    2. When json file does not exists.
      ValueError: When the extension is not json or bin.

    Returns:
      A dictionary representing the read tflite model.
    """
    raw_binary = ["--raw-binary"] if raw_binary else []
    with TemporaryDirectoryResource() as tempdir:
      basename = os.path.basename(input_file)
      basename_no_extension, extension = os.path.splitext(basename)
      if extension in [".bin", ".tflite"]:
        # Convert to json using flatc
        returncode = subprocess.call([
            self._flatc_path,
            "-t",
            "--strict-json",
            "--defaults-json",
        ] + raw_binary + ["-o", tempdir, schema, "--", input_file])
        if returncode != 0:
          raise RuntimeError("flatc failed to convert from binary to json.")
        json_file = os.path.join(tempdir, basename_no_extension + ".json")
        if not os.path.exists(json_file):
          raise RuntimeError("Could not find %r" % json_file)
      elif extension == ".json":
        json_file = input_file
      else:
        raise ValueError("Invalid extension on input file %r" % input_file)
      return json.load(open(json_file))

  def _Write(self, data, output_file):
    """Output a json or bin version of the flatbuffer model.

    Args:
      data: Dict representing the TensorFlow Lite model to write.
      output_file: filename to write the converted flatbuffer to. (json,
        tflite, or bin extension is required).
    Raises:
      ValueError: When the extension is not json or bin
      RuntimeError: When flatc fails to convert json data to binary.
    """
    _, extension = os.path.splitext(output_file)
    with TemporaryDirectoryResource() as tempdir:
      if extension == ".json":
        json.dump(data, open(output_file, "w"), sort_keys=True, indent=2)
      elif extension in [".tflite", ".bin"]:
        input_json = os.path.join(tempdir, "temp.json")
        with open(input_json, "w") as fp:
          json.dump(data, fp, sort_keys=True, indent=2)
        returncode = subprocess.call([
            self._flatc_path, "-b", "--defaults-json", "--strict-json", "-o",
            tempdir, self._new_schema, input_json
        ])
        if returncode != 0:
          raise RuntimeError("flatc failed to convert upgraded json to binary.")

        shutil.copy(os.path.join(tempdir, "temp.tflite"), output_file)
      else:
        raise ValueError("Invalid extension on output file %r" % output_file)

  def _Upgrade0To1(self, data):
    """Upgrade data from Version 0 to Version 1.

    Changes: Added subgraphs (which contains a subset of formally global
    entries).

    Args:
      data: Dictionary representing the TensorFlow lite data to be upgraded.
        This will be modified in-place to be an upgraded version.
    """
    subgraph = {}
    for key_to_promote in ["tensors", "operators", "inputs", "outputs"]:
      subgraph[key_to_promote] = data[key_to_promote]
      del data[key_to_promote]
    data["subgraphs"] = [subgraph]

  def _Upgrade1To2(self, data):
    """Upgrade data from Version 1 to Version 2.

    Changes: Rename operators to Conform to NN API.

    Args:
      data: Dictionary representing the TensorFlow lite data to be upgraded.
        This will be modified in-place to be an upgraded version.
    Raises:
      ValueError: Throws when model builtins are numeric rather than symbols.
    """

    def RemapOperator(opcode_name):
      """Go from old schema op name to new schema op name.

      Args:
        opcode_name: String representing the ops (see :schema.fbs).
      Returns:
        Converted opcode_name from V1 to V2.
      """
      old_name_to_new_name = {
          "CONVOLUTION": "CONV_2D",
          "DEPTHWISE_CONVOLUTION": "DEPTHWISE_CONV_2D",
          "AVERAGE_POOL": "AVERAGE_POOL_2D",
          "MAX_POOL": "MAX_POOL_2D",
          "L2_POOL": "L2_POOL_2D",
          "SIGMOID": "LOGISTIC",
          "L2NORM": "L2_NORMALIZATION",
          "LOCAL_RESPONSE_NORM": "LOCAL_RESPONSE_NORMALIZATION",
          "Basic_RNN": "RNN",
      }

      return (old_name_to_new_name[opcode_name]
              if opcode_name in old_name_to_new_name else opcode_name)

    def RemapOperatorType(operator_type):
      """Remap operator structs from old names to new names.

      Args:
        operator_type: String representing the builtin operator data type
          string. (see :schema.fbs).
      Raises:
        ValueError: When the model has consistency problems.
      Returns:
        Upgraded builtin operator data type as a string.
      """
      old_to_new = {
          "PoolOptions": "Pool2DOptions",
          "DepthwiseConvolutionOptions": "DepthwiseConv2DOptions",
          "ConvolutionOptions": "Conv2DOptions",
          "LocalResponseNormOptions": "LocalResponseNormalizationOptions",
          "BasicRNNOptions": "RNNOptions",
      }
      return (old_to_new[operator_type]
              if operator_type in old_to_new else operator_type)

    for subgraph in data["subgraphs"]:
      for ops in subgraph["operators"]:
        ops["builtin_options_type"] = RemapOperatorType(
            ops["builtin_options_type"])

    # Upgrade the operator codes
    for operator_code in data["operator_codes"]:
      # Check if builtin_code is the appropriate string type
      # use type("") instead of str or unicode. for py2and3
      if not isinstance(operator_code["builtin_code"], type(u"")):
        raise ValueError("builtin_code %r is non-string. this usually means "
                         "your model has consistency problems." %
                         (operator_code["builtin_code"]))
      operator_code["builtin_code"] = (RemapOperator(
          operator_code["builtin_code"]))

  def _Upgrade2To3(self, data):
    """Upgrade data from Version 2 to Version 3.

    Changed actual read-only tensor data to be in a buffers table instead
    of inline with the tensor.

    Args:
      data: Dictionary representing the TensorFlow lite data to be upgraded.
        This will be modified in-place to be an upgraded version.
    """
    buffers = [{"data": []}]  # Start with 1 empty buffer
    for subgraph in data["subgraphs"]:
      if "tensors" not in subgraph:
        continue
      for tensor in subgraph["tensors"]:
        if "data_buffer" not in tensor:
          tensor["buffer"] = 0
        else:
          if tensor["data_buffer"]:
            tensor[u"buffer"] = len(buffers)
            buffers.append({"data": tensor["data_buffer"]})
          else:
            tensor["buffer"] = 0
          del tensor["data_buffer"]
    data["buffers"] = buffers

  def _PerformUpgrade(self, data):
    """Manipulate the `data` (parsed JSON) based on changes in format.

    This incrementally will upgrade from version to version within data.

    Args:
      data: Dictionary representing the TensorFlow data. This will be upgraded
        in place.
    """
    while data["version"] < self._new_version:
      self._upgrade_dispatch[data["version"]](data)
      data["version"] += 1

  def Convert(self, input_file, output_file):
    """Perform schema conversion from input_file to output_file.

    Args:
      input_file: Filename of TensorFlow Lite data to convert from. Must
        be `.json` or `.bin` extension files for JSON or Binary forms of
        the TensorFlow FlatBuffer schema.
      output_file: Filename to write to. Extension also must be `.json`
        or `.bin`.

    Raises:
      RuntimeError: Generated when none of the upgrader supported schemas
        matche the `input_file` data.
    """
    # Read data in each schema (since they are incompatible). Version is
    # always present. Use the read data that matches the version of the
    # schema.
    for version, schema, raw_binary, _ in self._schemas:
      try:
        data_candidate = self._Read(input_file, schema, raw_binary)
      except RuntimeError:
        continue  # Skip and hope another schema works
      if "version" not in data_candidate:  # Assume version 1 if not present.
        data_candidate["version"] = 1
      elif data_candidate["version"] == 0:  # Version 0 doesn't exist in wild.
        data_candidate["version"] = 1

      if data_candidate["version"] == version:
        self._PerformUpgrade(data_candidate)
        self._Write(data_candidate, output_file)
        return
    raise RuntimeError("No schema that the converter understands worked with "
                       "the data file you provided.")

def main(argv):
  del argv
  Converter().Convert(FLAGS.input, FLAGS.output)

if __name__ == "__main__":
  FLAGS, unparsed = parser.parse_known_args()
  tf.compat.v1.app.run(main=main, argv=[sys.argv[0]] + unparsed)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 13:32:40 2019
@author: Khanax
"""
import math
import time
import statistics as stats

import numpy as np
import pandas as pd
import tensorflow as tf

from ..utils import EPS,windowUnits
import include.network.net_constants as netco

def labelMaker(data, nb_classes):
    """Convert an iterable of indices to one-hot encoded labels."""
    targets = np.array(data).reshape(-1)
    return np.eye(nb_classes)[targets]

# n_x = num__input_features
# n_y = expected output (num classes)
def create_placeholders(n_x=None, n_y=None):
    X1 = tf.compat.v1.placeholder(tf.float32, [n_x, None], name="X")
    Y1 = tf.compat.v1.placeholder(tf.float32, [n_y, None], name="Y")
    return X1, Y1

def network_cost_function(final_layer, Y, loss):
    """
    Computes the cost in softmax cross entropy or RMSE or MSE fashion

    Arguments:
    final_layer -- output of forward propagation (output of the last LINEAR unit)
    Y -- "true" labels vector placeholder, same shape as final_layer

    Returns:
    cost - Tensor of the cost function
    """
    if loss == netco.SOFTMAX_CROSS_ENTROPY or loss=='SCE':
        logits = tf.transpose(final_layer)
        labels = tf.transpose(Y)
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=labels))
    elif loss == netco.REDUCED_MEAN_SQR_ERROR or loss=='RMSE':
        cost = tf.reduce_mean(tf.square(final_layer - Y))
    elif loss == netco.MEAN_SQR_ERROR or loss=='MSE':
        cost = tf.losses.mean_squared_error(Y,final_layer)

    return cost

def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
    """
    Creates a list of random minibatches from (X, Y)

    Arguments:
    X -- input data, of shape (input size, number of examples)
    Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
    mini_batch_size - size of the mini-batches, integer
    seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.

    Returns:
    mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
    """

    m = X.shape[1]# number of training examples
    mini_batches = []
    np.random.seed(seed)

    # Step 1: Shuffle (X, Y)
    permutation = list(np.random.permutation(m))
    shuffled_X = X[:, permutation]
    shuffled_Y = Y[:, permutation].reshape((Y.shape[0],m))

    # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
    num_complete_minibatches = math.floor(m/mini_batch_size)# number of mini batches of size mini_batch_size in your partitionning
    for k in range(0, num_complete_minibatches):
        mini_batch_X = shuffled_X[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size]
        mini_batch_Y = shuffled_Y[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size]
        mini_batch = (mini_batch_X, mini_batch_Y)
        mini_batches.append(mini_batch)

    # Handling the end case (last mini-batch < mini_batch_size)
    if m % mini_batch_size != 0:
        mini_batch_X = shuffled_X[:, num_complete_minibatches * mini_batch_size : m]
        mini_batch_Y = shuffled_Y[:, num_complete_minibatches * mini_batch_size : m]
        mini_batch = (mini_batch_X, mini_batch_Y)
        mini_batches.append(mini_batch)

    return mini_batches


import math
import os.path
from os.path import join

import torch
from torch.utils.data import DataLoader, Dataset
from typing import Dict, AnyStr, Any
from .image_folder import is_image_file, make_dataset
from PIL import Image
import numpy as np

from .transforms import to_tensor

def linear_transform(x, alpha: float = (math.e - 1), beta: float = 1):
    """
    Mapping x to alpha * x + beta, which transforms [l,r] to [alpha * l + beta, alpha * r + beta]
    """
    return alpha * x + beta

class IntrinsicDataset(Dataset):
    def __init__(self):
        super(IntrinsicDataset, self).__init__()

    @staticmethod
    def __get_transform__(data: dict):
        for key in data.keys():
            data[key] = linear_transform(data[key])
        return data

class MITIntrinsicDataset(IntrinsicDataset):
    """
        Dataset origin: https://www.cs.toronto.edu/~rgrosse/intrinsic/

        Following the train-test split strategy and dataset pre-processing script in
        "Direct intrinsics: Learning albedo-shading decomposition by convolutional regression." CVPR 2015.
        The dataset pre-processing script can be found in
        https://github.com/tnarihi/direct-intrinsics/tree/master/data/mit.

    """
    objects = {
        "train": ['apple', 'box', 'cup1', 'dinosaur', 'frog1', 'panther', 'paper1', 'phone', 'squirrel', 'teabag2'],
        "test": ['cup2', 'deer', 'frog2', 'paper2', 'pear', 'potato', 'raccoon', 'sun', 'teabag1', 'turtle']}

    @staticmethod
    def no_transform(item):
        return item

    def __init__(
            self,
            root: str,
            size: int = None,
            transforms: str = None,
            train: bool = True
    ) -> None:
        super(MITIntrinsicDataset, self).__init__()
        self.size = size
        self.root = root.rstrip('/').rstrip('\\')
        self.train = "train" if train else "test"
        self.transforms = transforms
        self.objs = self.objects[self.train]
        self.dirs = {k: dict() for k in self.objs}
        for key in self.dirs.keys():
            self.dirs[key]["mask"] = self.root + '/' + key + '/' + 'mask.png'
            self.dirs[key]["albedo"] = self.root + '/' + key + '/' + 'reflectance.png'
            self.dirs[key]["shading"] = [self.root + '/' + key + '/' + ('gray_shading%02d.png' % idx) for idx in
                                         range(1, 11)]
            self.dirs[key]["shading"].append(self.root + '/' + key + '/' + 'gray_shading.png')

            self.dirs[key]["input"] = [self.root + '/' + key + '/' + ('light%02d.png' % idx) for idx in range(1, 11)]
            self.dirs[key]["input"].append(self.root + '/' + key + '/' + "diffuse.png")
        # check whether images exists or not
        if self.size is None:
            self.size = 110
        for k, v in self.dirs.items():
            for ptp, pth in v.items():
                if type(pth) == list:
                    for inner_pth in pth:
                        if not os.path.isfile(inner_pth):
                            raise FileNotFoundError(inner_pth)
                else:
                    if not os.path.isfile(pth):
                        raise FileNotFoundError(pth)

    def __getpath__(self,
                    index: int
                    ) -> Dict[AnyStr, Any]:

        if index > self.size:
            raise IndexError("out of the range")

        selected_obj = self.objs[index // 11]

        return {"mask": self.dirs[selected_obj]["mask"],
                "albedo": self.dirs[selected_obj]["albedo"],
                "shading": self.dirs[selected_obj]["shading"][index % 11],
                "input": self.dirs[selected_obj]["input"][index % 11]}

    def __getitem__(
            self,
            index: int
    ) -> Dict[AnyStr, Any]:
        paths = self.__getpath__(index)
        ret = dict()
        img_mask = Image.open(paths["mask"]).convert('L')
        img_albedo = Image.open(paths["albedo"]).convert("RGB")
        img_shading = Image.open(paths["shading"]).convert("RGB")
        img_original_shading = Image.open(paths["shading"]).convert("L")
        img_input = Image.open(paths["input"]).convert("RGB")

        ret["mask"] = to_tensor(img_mask)
        ret["mask"][ret["mask"] < 0.5] = 0
        ret["mask"][ret["mask"] > 0.5] = 1
        ret["albedo"] = to_tensor(img_albedo) * ret["mask"]
        ret["shading"] = to_tensor(img_shading) * ret["mask"]

        ret["input"] = linear_transform(to_tensor(img_input) * ret["mask"])
        ret["org_input"] = to_tensor(img_input) * ret["mask"]
        ret["org_shading"] = to_tensor(img_original_shading) * ret["mask"]
        ret["fn"] = "".join((paths["input"]).strip("/").split("/")[-2:])
        # print(ret["fn"])
        return ret
        # return self.__get_transform__(ret)

    def __len__(self):
        return self.size

class BatchInferenceDataset(IntrinsicDataset):
    """
    This inference-only dataset class loads images from the given path.
    """

    def __init__(
            self,
            root: str,
            size: int = None,
            transforms: str = None,
    ) -> None:

        super(BatchInferenceDataset, self).__init__()
        self.size = size
        self.root = root.rstrip('/').rstrip('\\')
        self.transforms = transforms
        self.images = make_dataset(root)
        print(self.images)
        # check whether images exists or not
        if self.size is None:
            self.size = len(self.images)

    def __getitem__(
            self,
            index: int
    ) -> Dict[AnyStr, Any]:
        if index > self.size:
            raise IndexError("out of the range")
        ret = dict()
        ret["fn"] = "%d" % index
        path = self.images[index]
        img = Image.open(path)
        ret["org_input"] = to_tensor(img)
        ret["mask"] = torch.ones(ret["org_input"].shape).type(torch.FloatTensor)
        ret["input"] = linear_transform(ret["org_input"])
        print(ret)
        return ret

    def __len__(self):
        return self.size


from flask import Flask, render_template, request
import openai
import os
from dotenv import load_dotenv
load_dotenv()
import regex as re

app = Flask(__name__)

# Set up OpenAI API credentials
openai.api_key = os.environ["OPENAI_API_KEY"]

# Initialize conversation list
conversation = [{'role':'system', 'content':"""
You are a Language tutor for teaching human speaking languages.
Your first task is to greet and ask the my name.
You ask which language do I want to learn.

Give me options like [Spanish , French , German , Russian  or ask their personal choises of languages]

...wait for my response
You then ask my proficiecy level.

... wait for my response
Based on my language prefernce prepare a course for that language

start the course by describing how you are going to teach

Strictly follow the below steps
give examples at every step and then provide few exercise for practise in each conversation
give two line space before staring the exercise for clearner paragraph
Generate google translate link for the words used for prefered language by me
strictly print those links in form of JSON format at the last of every conversation

"""}]

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get_response', methods=['POST'])
def get_response():
    # Get user input from the form
    user_input = request.form['user_input']

    # Append user input to conversation
    conversation.append({'role':'user', 'content':f"{user_input}"})

    # Get response from OpenAI API
    response = openai.ChatCompletion.create(
        model = 'gpt-3.5-turbo',
        temperature=0.0,
        messages = conversation,
    )

    # Append OpenAI's response to conversation
    assistant_response = response.choices[0].message["content"]

    #extracting link using regex
    deli = str(assistant_response)
    print(deli)
    stri = re.findall('\{.*\}' , deli)
    print(stri)
    if len(stri) == 0:
        print("None")
    else:
        pattern = r'"([^"]*)"'
        links = re.findall(pattern, stri[0])
        print(links)

    # senti = openai.ChatCompletion.create(
    #     model = 'gpt-3.5-turbo',
    #     temperature=0.0,
    #     messages = [{'role':'system', 'content':f"""If the paragraph given in triple quotes '''{assistant_response}''' is of type that it has no acces to the data then give output "NO" """}],
    # )
    # sentiment = senti.choices[0].message["content"]
    # print(sentiment)

    if len(conversation) == 7:
        conversation.pop(1)
        conversation.pop(2)

    conversation.append({'role':'assistant', 'content':f"{assistant_response}"})

    return {'response': assistant_response}

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


from Crypto.Util import number
import gmpy2
import random

class Signature:
    def __init__(self, security_parameter):
        self.security_parameter = security_parameter
        ((n,e),(p,q,d)) = self.generateKeyPair()
        self.pubKey = {"n": n, "e": e}
        self.privKey = {"p": p, "q": q, "d": d}

    def gcd(a, b):
        while b != 0:
            (a, b) = (b, a%b)
        return a

    def generateKeyPair(self):
        p = number.getPrime(self.security_parameter)
        q = number.getPrime(self.security_parameter)

        while p == q:
            q = number.getPrime(self.security_parameter)

        n = p * q

        phi_n = (p-1) * (q-1)

        e = random.randint(2, phi_n-1)

        while Signature.gcd(e, phi_n) != 1:
            e = random.randint(2, phi_n-1)

        d = gmpy2.invert(e, phi_n)

        return ((n,e),(p,q,d))

    def signMessage(self, m):
        if type(m) != int:
            raise ValueError("[ERROR] Message to be signed must be an integer type!")

        signature = pow(m, self.privKey["d"], self.privKey["p"] * self.privKey["q"])
        return signature

    def validateSignature(self, m, sign):
        if type(m) != int :
            raise ValueError("[ERROR] Message to be signed must be an integer type!")

        if type(sign) != int:
            raise ValueError("[ERROR] Signature to be verified must be an integer type!")

        m_prime = pow(sign, self.pubKey["e"], self.pubKey["n"])
        return m == m_prime

    def getMessage(self, sign):
        m = pow(sign, self.pubKey["e"], self.pubKey["n"])
        return m

class Predicate_R:
    def __init__(self):
        self.dump = []

    def setRedundancy(self, x):
        self.dump.append(x)

    def checkRedundancy(self, x):
        return x in self.dump


import os, sys
import pytest
import re

# Set up script
app_path = os.path.abspath(os.pardir)
print(app_path)
sys.path.append(app_path)

# import the tested and the errors
from ex03.financial import main, TickerNotFound

# Test cases
ARGS_OK = ["", 'msft', 'Total Revenue']
ARGS_BAD_TICKER = ["", 'asldfjhals', "Total Revenue"]

# Test functions
def test_total_revenue():
    assert main(ARGS_OK)[0].lower() == 'Total Revenue'.lower()

def test_is_tuple():
    assert isinstance(main(ARGS_OK), tuple)

def test_invalid_ticker_error():
    # connection error check failed; url comparison ok
    with pytest.raises(TickerNotFound, match='TICKER NOT FOUND', ):
        main(ARGS_BAD_TICKER)

"""
•   If I ask for Total Revenue, do I get the total revenue for the given ticker?
•   Is the type of the return a tuple?
•   If I give an invalid ticker name, do I get an exception?
"""


#!/usr/bin/python

""" Transaction Fraud Detection Using Social-network Information
Author: Shifan Mao
Date: 11-06-16 """

import sys
import networkx as nx
import numpy as np
# from graph import Graph

"""
example of executing this script
python ./src/antifraud.py ./paymo_input/batch_payment.txt ./paymo_input/stream_payment.txt ./paymo_output/output1.txt ./paymo_output/output2.txt ./paymo_output/output3.txt
"""

def train(input_batch, feat=None):
    """ Make Network of Users based on Transaction History """
    G = nx.Graph()

    with open(input_batch) as f:
        next(f)  # skip header
        for i, l in enumerate(f):
            row = l.split(',')
            id1,id2 = row[1:3]
            G.add_edge(id1,id2)

            if (feat==4):
                pass # new feature, to be implemented
    return G

def test(input_stream,output_out,G,feat=1):
    """
    Feature 1. Display Warning if Not Friends (degree 1 connection)
    Feature 2. Display Warning if Not Friends of Friends (degree 2 connection)
    Feature 3. Display Warning if Outside of Fourth-degree Friends (degree> 4 connection)
    """
    if (feat not in [1,2,3]):
        raise ValueError('Feature not specified, need to choose feature no. from 1, 2, 3, or 4')

    fout = open(output_out, 'w')
    with open(input_stream) as f:
        next(f)  #skip header
        for i, l in enumerate(f):
            row = l.split(',')
            id1,id2 = row[1:3]

            result = 'unverified\n'
            if (feat==1):
                if G.has_edge(id1,id2):
                    result = 'trusted\n'
            else:
                has_nodes = ((id1 in G) and (id2 in G))
                if (has_nodes):
                    has_path = nx.has_path(G,id1,id2)
                    if (has_path):
                        path_length = nx.shortest_path_length(G,source=id1,target=id2)

                        if (feat==2):
                            if (path_length<=2):
                                result = 'trusted\n'
                        elif (feat==3):
                            if (path_length<=4):
                                result = 'trusted\n'
            fout.write(result)
    fout.close()

def main(input_batch, input_stream, output_out1, output_out2, output_out3):
    """ specify train and test files
    training data comes from transaction history and
    test data are new transactions, which need classification trusted/untrusted """

    outputs = [output_out1,output_out2,output_out3]
    for feature in [1,2,3]:
        output = outputs[feature-1]

        """ load transaction history """
        G = train(input_batch, feat=feature)

        """ test with new transactions """
        test(input_stream,output,G,feat=feature)

if __name__ == "__main__":
    try:
        input_batch, input_stream, output_out1, output_out2, output_out3 = sys.argv[1:]
    except:
        input_batch = '../paymo_input/batch_payment.txt'
        input_stream = '../paymo_input/stream_payment.txt'

        output_out1 = '../paymo_output/output1.txt'
        output_out2 = '../paymo_output/output2.txt'
        output_out3 = '../paymo_output/output3.txt'
    main(input_batch, input_stream, \
         output_out1, output_out2, output_out3)


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

app = Flask(__name__)

# Aluno ----------------------------------------------------------------------------------------------------------------
@app.route('/')
def index():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Consultando os alunos do banco de dados
    cursor.execute("SELECT * FROM aluno")
    alunos = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    return render_template('index.html', alunos=alunos)

@app.route('/inserir', methods=['POST'])
def inserir():
    # Recuperando os dados do formulário
    nome = request.form['nome']
    email = request.form['email']
    curso = request.form['curso']
    data_nascimento = request.form['data_nascimento']
    endereco = request.form['endereco']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Inserindo um novo aluno na tabela
    cursor.execute("INSERT INTO aluno (nome, email, curso, data_nascimento, endereco) VALUES (?, ?, ?, ?, ?)",
                   (nome, email, curso, data_nascimento, endereco))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/')

@app.route('/remover/<int:aluno_id>')
def remover(aluno_id):
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Removendo o aluno da tabela
    cursor.execute("DELETE FROM aluno WHERE id=?", (aluno_id,))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/')

@app.route('/atualizar/<int:aluno_id>', methods=['POST'])
def atualizar(aluno_id):
    # Recuperando os dados do formulário
    nome = request.form['nome']
    email = request.form['email']
    curso = request.form['curso']
    data_nascimento = request.form['data_nascimento']
    endereco = request.form['endereco']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Atualizando os dados do aluno na tabela
    cursor.execute("UPDATE aluno SET nome=?, email=?, curso=?, data_nascimento=?, endereco=? WHERE id=?",
                   (nome, email, curso, data_nascimento, endereco, aluno_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/')
# ----------------------------------------------------------------------------------------------------------------------

# Professor ------------------------------------------------------------------------------------------------------------
@app.route('/professores')
def listar_professores():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Consultando os professores do banco de dados
    cursor.execute("SELECT * FROM professor")
    professores = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    return render_template('professores.html', professores=professores)
@app.route('/inserir_professor', methods=['POST'])
def inserir_professor():
    # Recuperando os dados do formulário
    nome = request.form['nome']
    email = request.form['email']
    curso = request.form['curso']
    data_nascimento = request.form['data_nascimento']
    endereco = request.form['endereco']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Inserindo um novo professor na tabela
    cursor.execute("INSERT INTO professor (nome, email, curso, data_nascimento, endereco) VALUES (?, ?, ?, ?, ?)",
                   (nome, email, curso, data_nascimento, endereco))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página de professores
    return redirect('/professores')

@app.route('/remover_professor/<int:professor_id>')
def remover_professor(professor_id):
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Removendo o professor da tabela
    cursor.execute("DELETE FROM professor WHERE id=?", (professor_id,))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página de professores
    return redirect('/professores')

@app.route('/atualizar_professor/<int:professor_id>', methods=['POST'])
def atualizar_professor(professor_id):
    # Recuperando os dados do formulário
    nome = request.form['nome']
    email = request.form['email']
    curso = request.form['curso']
    data_nascimento = request.form['data_nascimento']
    endereco = request.form['endereco']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Atualizando os dados do professor na tabela
    cursor.execute("UPDATE professor SET nome=?, email=?, curso=?, data_nascimento=?, endereco=? WHERE id=?",
                   (nome, email, curso, data_nascimento, endereco, professor_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página de professores
    return redirect('/professores')
# ----------------------------------------------------------------------------------------------------------------------

# Disciplina------------------------------------------------------------------------------------------------------------
@app.route('/disciplinas')
def disciplinas():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Obtendo todas as disciplinas da tabela
    cursor.execute("SELECT * FROM disciplina")
    disciplinas = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    # Renderizando o template disciplina.html e passando as disciplinas como argumento
    return render_template('disciplina.html', disciplinas=disciplinas)

@app.route('/inserir_disciplina', methods=['POST'])
def inserir_disciplina():
    # Recuperando os dados do formulário
    nome = request.form['nome']
    carga_horaria = request.form['carga_horaria']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Inserindo uma nova disciplina na tabela
    cursor.execute("INSERT INTO disciplina (nome, carga_horaria) VALUES (?, ?)",
                   (nome, carga_horaria))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/disciplinas')

@app.route('/remover_disciplina/<int:disciplina_id>')
def remover_disciplina(disciplina_id):
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Removendo a disciplina da tabela
    cursor.execute("DELETE FROM disciplina WHERE id=?", (disciplina_id,))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/disciplinas')

@app.route('/atualizar_disciplina/<int:disciplina_id>', methods=['POST'])
def atualizar_disciplina(disciplina_id):
    # Recuperando os dados do formulário
    nome = request.form['nome']
    carga_horaria = request.form['carga_horaria']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Atualizando os dados da disciplina na tabela
    cursor.execute("UPDATE disciplina SET nome=?, carga_horaria=? WHERE id=?",
                   (nome, carga_horaria, disciplina_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/disciplinas')

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

# Turmas ---------------------------------------------------------------------------------------------------------------
@app.route('/turmas')
def turmas():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Obtendo todas as turmas da tabela
    cursor.execute("SELECT * FROM turma")
    turmas = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    # Renderizando o template turma.html e passando as turmas como argumento
    return render_template('turma.html', turmas=turmas)

@app.route('/inserir_turma', methods=['POST'])
def inserir_turma():
    # Recuperando os dados do formulário
    sala = request.form['sala']
    horario = request.form['horario']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Inserindo uma nova turma na tabela
    cursor.execute("INSERT INTO turma (sala, horario) VALUES (?, ?)",
                   (sala, horario))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/turmas')

@app.route('/remover_turma/<int:turma_id>')
def remover_turma(turma_id):
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Removendo a turma da tabela
    cursor.execute("DELETE FROM turma WHERE id=?", (turma_id,))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/turmas')

@app.route('/atualizar_turma/<int:turma_id>', methods=['POST'])
def atualizar_turma(turma_id):
    # Recuperando os dados do formulário
    sala = request.form['sala']
    horario = request.form['horario']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Atualizando os dados da turma na tabela
    cursor.execute("UPDATE turma SET sala=?, horario=? WHERE id=?",
                   (sala, horario, turma_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/turmas')

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

# Matrícula ------------------------------------------------------------------------------------------------------------
@app.route('/matriculas')
def matriculas():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Obtendo todas as matrículas da tabela
    cursor.execute("SELECT * FROM matricula")
    matriculas = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    # Renderizando o template matricula.html e passando as matrículas como argumento
    return render_template('matricula.html', matriculas=matriculas)

@app.route('/inserir_matricula', methods=['POST'])
def inserir_matricula():
    # Recuperando os dados do formulário
    aluno_id = request.form['aluno_id']
    disciplina_id = request.form['disciplina_id']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Inserindo uma nova matrícula na tabela
    cursor.execute("INSERT INTO matricula (aluno_id, disciplina_id) VALUES (?, ?)",
                   (aluno_id, disciplina_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/matriculas')

@app.route('/remover_matricula/<int:aluno_id>/<int:disciplina_id>')
def remover_matricula(aluno_id, disciplina_id):
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Removendo a matrícula da tabela
    cursor.execute("DELETE FROM matricula WHERE aluno_id=? AND disciplina_id=?",
                   (aluno_id, disciplina_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/matriculas')

@app.route('/atualizar_matricula/<int:aluno_id>/<int:disciplina_id>', methods=['POST'])
def atualizar_matricula(aluno_id, disciplina_id):
    # Recuperando os dados do formulário
    novo_aluno_id = request.form['aluno_id']
    nova_disciplina_id = request.form['disciplina_id']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Atualizando os dados da matrícula na tabela
    cursor.execute("UPDATE matricula SET aluno_id=?, disciplina_id=? WHERE aluno_id=? AND disciplina_id=?",
                   (novo_aluno_id, nova_disciplina_id, aluno_id, disciplina_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/matriculas')

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

# Leciona --------------------------------------------------------------------------------------------------------------
@app.route('/leciona')
def lecionas():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Obtendo todas as relações "leciona" da tabela
    cursor.execute("SELECT * FROM leciona")
    lecionas = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    # Renderizando o template leciona.html e passando as relações "leciona" como argumento
    return render_template('leciona.html', lecionas=lecionas)

@app.route('/inserir_leciona', methods=['POST'])
def inserir_leciona():
    # Recuperando os dados do formulário
    professor_id = request.form['professor_id']
    disciplina_id = request.form['disciplina_id']
    turma_id = request.form['turma_id']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Inserindo uma nova relação "leciona" na tabela
    cursor.execute("INSERT INTO leciona (professor_id, disciplina_id, turma_id) VALUES (?, ?, ?)",
                   (professor_id, disciplina_id, turma_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/leciona')

@app.route('/remover_leciona/<int:professor_id>/<int:disciplina_id>/<int:turma_id>')
def remover_leciona(professor_id, disciplina_id, turma_id):
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Removendo a relação "leciona" da tabela
    cursor.execute("DELETE FROM leciona WHERE professor_id=? AND disciplina_id=? AND turma_id=?",
                   (professor_id, disciplina_id, turma_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/leciona')

@app.route('/atualizar_leciona/<int:professor_id>/<int:disciplina_id>/<int:turma_id>', methods=['POST'])
def atualizar_leciona(professor_id, disciplina_id, turma_id):
    # Recuperando os dados do formulário
    novo_professor_id = request.form['professor_id']
    nova_disciplina_id = request.form['disciplina_id']
    nova_turma_id = request.form['turma_id']

    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Atualizando os dados da relação "leciona" na tabela
    cursor.execute("UPDATE leciona SET professor_id=?, disciplina_id=?, turma_id=? WHERE professor_id=? AND disciplina_id=? AND turma_id=?",
                   (novo_professor_id, nova_disciplina_id, nova_turma_id, professor_id, disciplina_id, turma_id))

    # Salvando as alterações e fechando a conexão com o banco de dados
    conn.commit()
    conn.close()

    # Redirecionando de volta para a página inicial
    return redirect('/leciona')
# ----------------------------------------------------------------------------------------------------------------------

# Junção Interna--------------------------------------------------------------------------------------------------------
@app.route('/juncao_interna')
def juncao():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Executando a consulta de junção interna
    cursor.execute("SELECT aluno.nome, aluno.email, disciplina.nome FROM aluno "
                   "INNER JOIN matricula ON aluno.id = matricula.aluno_id "
                   "INNER JOIN disciplina ON matricula.disciplina_id = disciplina.id")

    # Obtendo os resultados da consulta
    resultados = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    # Renderizando o template juncao.html e passando os resultados da junção como argumento
    return render_template('juncao_interna.html', resultados=resultados)

# Junção Externa--------------------------------------------------------------------------------------------------------
@app.route('/juncao_externa')
def juncao_externa():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Executando a consulta de junção externa
    cursor.execute("SELECT professor.nome, disciplina.nome, leciona.turma_id FROM professor "
                   "LEFT JOIN leciona ON professor.id = leciona.professor_id "
                   "LEFT JOIN disciplina ON leciona.disciplina_id = disciplina.id")

    # Obtendo os resultados da consulta
    resultados = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    # Renderizando o template juncao_externa.html e passando os resultados da junção como argumento
    return render_template('juncao_externa.html', resultados=resultados)

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

# Sentença de grupo envolvendo as junções dos anteriores ---------------------------------------------------------------
# Página mostrando quantas disciplinas cada aluno faz
@app.route('/disciplinas_por_aluno')
def disciplinas_por_aluno():
    # Conectando ao banco de dados
    conn = sqlite3.connect('sistema_de_matriculas.db')
    cursor = conn.cursor()

    # Executando a consulta para contar as disciplinas por aluno
    cursor.execute("SELECT aluno.nome, COUNT(matricula.disciplina_id) FROM aluno "
                   "LEFT JOIN matricula ON aluno.id = matricula.aluno_id GROUP BY aluno.nome")

    # Obtendo os resultados da consulta
    resultados = cursor.fetchall()

    # Fechando a conexão com o banco de dados
    conn.close()

    # Renderizando o template disciplinas_por_aluno.html e passando os resultados como argumento
    return render_template('disciplinas_por_aluno.html', resultados=resultados)

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

# Sentença com a cláusula HAVING ---------------------------------------------------------------------------------------
@app.route('/filtrar_disciplinas', methods=['GET', 'POST'])
def filtrar_disciplinas():
    if request.method == 'POST':
        # Obter o valor mínimo fornecido pelo usuário no formulário
        valor_minimo = int(request.form['valor_minimo'])

        # Conectar ao banco de dados
        conn = sqlite3.connect('sistema_de_matriculas.db')
        cursor = conn.cursor()

        # Executar a consulta filtrando as disciplinas pelo número mínimo de alunos matriculados
        cursor.execute("SELECT disciplina.nome, COUNT(matricula.aluno_id) FROM disciplina "
                       "LEFT JOIN matricula ON disciplina.id = matricula.disciplina_id "
                       "GROUP BY disciplina.nome "
                       "HAVING COUNT(matricula.aluno_id) >= ?", (valor_minimo,))

        # Obter os resultados da consulta
        resultados = cursor.fetchall()

        # Fechar a conexão com o banco de dados
        conn.close()

        # Renderizar o template disciplinas_filtradas.html e passar os resultados e o valor mínimo como argumentos
        return render_template('disciplinas_filtradas.html', resultados=resultados, valor_minimo=valor_minimo)

    # Renderizar o template de formulário de filtragem
    return render_template('filtrar_disciplinas.html')
# ----------------------------------------------------------------------------------------------------------------------

# Consulta com subconsulta ---------------------------------------------------------------------------------------------
@app.route('/alunos_por_professor', methods=['GET', 'POST'])
def alunos_por_professor():
    if request.method == 'POST':
        # Obter o ID do professor fornecido pelo usuário no formulário
        professor_id = int(request.form['professor_id'])

        # Conectar ao banco de dados
        conn = sqlite3.connect('sistema_de_matriculas.db')
        cursor = conn.cursor()

        # Executar a consulta usando uma subconsulta para obter os nomes dos alunos
        cursor.execute("SELECT aluno.nome FROM aluno WHERE aluno.id IN "
                       "(SELECT matricula.aluno_id FROM matricula "
                       "LEFT JOIN leciona ON matricula.disciplina_id = leciona.disciplina_id "
                       "WHERE leciona.professor_id = ?)", (professor_id,))

        # Obter os resultados da consulta
        resultados = cursor.fetchall()

        # Fechar a conexão com o banco de dados
        conn.close()

        # Renderizar o template alunos_por_professor.html e passar os resultados e o ID do professor como argumentos
        return render_template('alunos_por_professor.html', resultados=resultados, professor_id=professor_id)

    # Renderizar o template de formulário para inserir o ID do professor
    return render_template('informar_professor.html')

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

if __name__ == '__main__':
    app.run()


# -*- coding: utf-8 -*-
"""
Created on Fri Apr  3 11:30:44 2020

@author: Maldonado
"""

from tkinter import *
from tkinter import messagebox as MB
from tkinter import colorchooser as CC
from tkinter import filedialog as FD

root = Tk()

def test():

    color = CC.askcolor(title="Elige un color")
    print(color)

    ficheror = FD.askopenfilename(title="Abrir archivo", initialdir="C:",
                                  filetypes=(("Fichero de texto","*.txt"), ("Fichero python","*.py"), ("Todos los ficheros","*.*")))
    print(ficheror)

    ruta = FD.asksaveasfile(title="Guardar archivo")
    print(ruta)

Button(root, text="click", command=test).pack()

root.mainloop()