import validators
from pydantic import BaseModel
from homepage2vec.model import WebsiteClassifier, Webpage
from fastapi import FastAPI, Depends, HTTPException, status
import os
import logging

logging.basicConfig(level=logging.DEBUG)

model = WebsiteClassifier()

WARMUP_MODEL = os.getenv("WARMUP_MODEL", 'False').lower() in ('true', '1', 't')
if WARMUP_MODEL:
    logging.info("Warming up model")
    website = Webpage("https://example.com")
    website.html = "Example"
    scores, embeddings = model.predict(website)
    logging.info("Model warmed up")

logging.info("FastAPI starting")
app = FastAPI()

class ClassifyRequest(BaseModel):
    url: str
    html: str = None

@app.get("/")
def read_root():
    return {"POST with [url] or [url, html] to / with a bearer token"}

@app.post("/")
def classify(classify_request: ClassifyRequest):
    if (not validators.url(classify_request.url)):
      raise HTTPException(status_code=403, detail="Invalid URL")

    if (not classify_request.html):
      raise HTTPException(status_code=403, detail="Must pass html")

    website = Webpage(classify_request.url)
    website.html = classify_request.html

    scores, embeddings = model.predict(website)
    return {"scores": scores, "embeddings": embeddings, "url": classify_request.url}


from net_compiler import *
from caffe_compiler import *

if __name__ == "__main__":
    if len(sys.argv) != 3:
        python_str = "python"
        this_pyfile_path = sys.argv[0]
        print("Usage: %s %s CAFFE_PROTOTXT CAFFE_CAFFEMODEL\n" % (python_str, this_pyfile_path))
        exit(-1)
    else:
        # net_compiler
        prototxt_file = sys.argv[1]
        net = Net(prototxt_file)
        name_pattern = "(.*).prototxt"
        name = re.findall(name_pattern, prototxt_file)[0]
        print("[INFO] Successful conversion from {}.prototxt to {}.c and {}.h" \
              .format(name, name, name))

        # caffe_compiler
        print("[INFO] Start to convert weight file ......")
        caffe_model_path = sys.argv[2]
        main(caffe_model_path)
        print("[INFO] Successful conversion from {}.caffemodel to {}.dat" \
              .format(name, name))


import tkinter as tk
from tkinter import ttk
from tkinter import *
import tkinter.font as font
from PIL import Image, ImageTk
import Texthide
import Decryption

def main1():
    root = Tk()

    # This is the section of code which creates the main window
    root.geometry('800x650')
    root.configure(background='#001533')
    root.title('Encryptor')

    # function for Text Encryption
    def btnTxtDecry():
        text = multext.get("1.0",'end-1c')
        text = Texthide.Text_recover(text)
        text = Decryption.main(text)
        tOutput.insert(0, text)

    # Name of the Program
    #Label(root, text='Morse Code Encryptor', bg='#436EEE', font=('verdana', 18, 'bold')).place(x=239, y=24)

    # gratitude
    #Label(root, text='Thanks for using the Machine', bg='#436EEE', font=('helvetica', 16, 'bold')).place(x=231,y=67)

    # Name of the Option selected
    Label(root, text='Data Extraction from Text',fg="#F01154", bg='#001533', font=('fixedsys', 28, 'normal')).place(x=140, y=30)

    # Enter the text prompt
    Label(root, text='Enter your Encrypted Text',fg="#04f8f8", bg='#001533', font=('verdana', 16, 'normal')).place(x=51, y=200)

    # textbox for the input
    # tInput = Entry(root, font="Calibri 16")
    # tInput.place(x=240, y=202)

    # Text Widget
    # multext = tk.Text(root, width=27, height=4)
    # multext.place(x=240, y=202)
    multext = tk.Text(root, height=6, width=40)
    scroll = tk.Scrollbar(root)
    multext.configure(yscrollcommand=scroll.set)
    multext.place(x=340, y=202)

    scroll.config(command=multext.yview)
    scroll.pack(side=tk.RIGHT, fill=tk.Y)

    # prompt for the showing encrypted text
    Label(root, text='Extracted Message',fg="#04f8f8", bg='#001533', font=('verdana', 16, 'normal')).place(x=52, y=390)

    # Output textbox
    tOutput = Entry(root, font="Calibri 16")
    tOutput.place(x=340, y=390)

    # Button for sending/saving the data
    Button(root, text='Decrypt it',
           fg="#001533",
           activeforeground='#04f8f8',
           activebackground='#001533',
           borderwidth=0,
           bg='#04f8f8',
           font=('verdana', 16, 'normal'),
           command=btnTxtDecry).place(
        x=340, y=320)

    # Text Widget
    # multext = tk.Text(root, width=27, height=4)
    # multext.place(x=240, y=202)
    #multext = tk.Text(root, height=6, width=40)
    #scroll = tk.Scrollbar(root)
    #multext.configure(yscrollcommand=scroll.set)
    #multext.place(x=340, y=390)

    #scroll.config(command=multext.yview)
    #scroll.pack(side=tk.RIGHT, fill=tk.Y)

    # exit button
    exit_button = Button(root, text="<<",fg="#001533",
                         activeforeground='#04f8f8',
                         activebackground='#001533',
                         borderwidth=0,
                         bg='#04f8f8', font=('verdana', 16, 'normal'),
                         command=root.destroy)
    exit_button.place(x=680,y=30)

    root.mainloop()


from urllib.parse import urlsplit, urljoin
from datetime import timedelta
from werkzeug.routing import RequestRedirect
from werkzeug.exceptions import NotFound, MethodNotAllowed
from flask import current_app, redirect, url_for, request, g
from flask.views import MethodView
from flask_smorest import abort
from swpt_pythonlib.utils import i64_to_u64, u64_to_i64
from swpt_pythonlib.swpt_uris import (
    parse_debtor_uri,
    parse_account_uri,
    make_debtor_uri,
)
from swpt_creditors.schemas import (
    examples,
    DebtorIdentitySchema,
    AccountIdentitySchema,
    AccountSchema,
    AccountConfigSchema,
    AccountDisplaySchema,
    AccountExchangeSchema,
    AccountKnowledgeSchema,
    AccountInfoSchema,
    AccountLedgerSchema,
    ObjectReferencesPageSchema,
    AccountsPaginationParamsSchema,
    LedgerEntriesPaginationParamsSchema,
    LedgerEntriesPageSchema,
)
from swpt_creditors import procedures
from swpt_creditors import inspect_ops
from .common import context, ensure_creditor_permissions, Blueprint
from .specs import DID, CID
from . import specs

def _parse_peg_account_uri(creditor_id: int, base_url: str, uri: str) -> int:
    Error = procedures.PegDoesNotExist

    try:
        scheme, netloc, path, *rest = urlsplit(urljoin(base_url, uri))
    except ValueError:
        raise Error()

    base_url_scheme, base_url_netloc, *_ = urlsplit(request.base_url)
    if (
        any(rest)
        or (scheme and scheme != base_url_scheme)
        or (netloc and netloc != base_url_netloc)
    ):
        raise Error()

    try:
        endpoint, params = current_app.url_map.bind("localhost").match(path)
    except (NotFound, RequestRedirect, MethodNotAllowed):
        raise Error()

    if (
        endpoint != "accounts.AccountEndpoint"
        or params["creditorId"] != creditor_id
    ):
        raise Error()

    return params["debtorId"]

accounts_api = Blueprint(
    "accounts",
    __name__,
    url_prefix="/creditors",
    description="""**Create, view, update, and delete accounts. View accounts'
    ledgers.** Every account record consists of a "master" account
    object, which contains references to several account sub-objects
    (account configuration, account status, account ledger etc). Each
    of these sub-objects contain different kind of information about
    the account, and each sub-object can be updated separately.""",
)
accounts_api.before_request(ensure_creditor_permissions)

@accounts_api.route("/<i64:creditorId>/account-lookup", parameters=[CID])
class AccountLookupEndpoint(MethodView):
    @accounts_api.arguments(
        AccountIdentitySchema, example=examples.ACCOUNT_IDENTITY_EXAMPLE
    )
    @accounts_api.response(200, DebtorIdentitySchema)
    @accounts_api.doc(
        operationId="accountLookup", security=specs.SCOPE_ACCESS_MODIFY
    )
    def post(self, account_identity, creditorId):
        """Given an account identity, find the debtor's identity.

        This can be useful, for example, when the creditor wants to
        send money to some other creditor's account, but he does not
        know if he already has an account with the same debtor (that
        is: the debtor of the other creditor's account).

        """

        try:
            debtorId, _ = parse_account_uri(account_identity["uri"])
        except ValueError:
            abort(
                422,
                errors={"json": {"uri": ["The URI can not be recognized."]}},
            )

        return {"uri": make_debtor_uri(debtorId)}

@accounts_api.route("/<i64:creditorId>/debtor-lookup", parameters=[CID])
class DebtorLookupEndpoint(MethodView):
    @accounts_api.arguments(
        DebtorIdentitySchema, example=examples.DEBTOR_IDENTITY_EXAMPLE
    )
    @accounts_api.response(204)
    @accounts_api.doc(
        operationId="debtorLookup",
        security=specs.SCOPE_ACCESS_MODIFY,
        responses={
            204: specs.NO_ACCOUNT_WITH_THIS_DEBTOR,
            303: specs.ACCOUNT_EXISTS,
        },
    )
    def post(self, debtor_identity, creditorId):
        """Try to find an existing account with a given debtor.

        This is useful when the creditor wants not know if he already
        has an account with a given debtor.

        **Note:** A 422 error will be returned when the debtor's
        identity can not be recognized.

        """

        try:
            debtorId = parse_debtor_uri(debtor_identity["uri"])
        except ValueError:
            abort(
                422,
                errors={"json": {"uri": ["The URI can not be recognized."]}},
            )

        if procedures.has_account(creditorId, debtorId):
            location = url_for(
                "accounts.AccountEndpoint",
                _external=True,
                creditorId=creditorId,
                debtorId=debtorId,
            )
            return redirect(location, code=303)

@accounts_api.route("/<i64:creditorId>/accounts/", parameters=[CID])
class AccountsEndpoint(MethodView):
    @accounts_api.arguments(AccountsPaginationParamsSchema, location="query")
    @accounts_api.response(200, ObjectReferencesPageSchema(context=context))
    @accounts_api.doc(
        operationId="getAccountsPage", security=specs.SCOPE_ACCESS_READONLY
    )
    def get(self, params, creditorId):
        """Return a collection of accounts belonging to a given creditor.

        The returned object will be a fragment (a page) of a paginated
        list. The paginated list contains references to all `Account`s
        belonging to a given creditor. The returned fragment will not
        be sorted in any particular order.

        """

        try:
            prev = (
                u64_to_i64(int(params["prev"])) if "prev" in params else None
            )
        except ValueError:
            abort(422, errors={"query": {"prev": ["Invalid value."]}})

        n = current_app.config["APP_ACCOUNTS_PER_PAGE"]
        debtor_ids = procedures.get_account_debtor_ids(
            creditorId, count=n, prev=prev
        )
        items = [
            {"uri": f"{i64_to_u64(debtor_id)}/"} for debtor_id in debtor_ids
        ]

        if len(debtor_ids) < n:
            # The last page does not have a 'next' link.
            return {
                "uri": request.full_path,
                "items": items,
            }

        return {
            "uri": request.full_path,
            "items": items,
            "next": f"?prev={i64_to_u64(debtor_ids[-1])}",
        }

    @accounts_api.arguments(
        DebtorIdentitySchema, example=examples.DEBTOR_IDENTITY_EXAMPLE
    )
    @accounts_api.response(
        201, AccountSchema(context=context), headers=specs.LOCATION_HEADER
    )
    @accounts_api.doc(
        operationId="createAccount",
        security=specs.SCOPE_ACCESS_MODIFY,
        responses={303: specs.ACCOUNT_EXISTS, 403: specs.FORBIDDEN_OPERATION},
    )
    def post(self, debtor_identity, creditorId):
        """Create account.

        **Note:** This is an idempotent operation.

        """

        try:
            debtorId = parse_debtor_uri(debtor_identity["uri"])
        except ValueError:
            abort(
                422,
                errors={"json": {"uri": ["The URI can not be recognized."]}},
            )

        location = url_for(
            "accounts.AccountEndpoint",
            _external=True,
            creditorId=creditorId,
            debtorId=debtorId,
        )
        try:
            inspect_ops.allow_account_creation(creditorId, debtorId)
            account = procedures.create_new_account(creditorId, debtorId)
        except inspect_ops.ForbiddenOperation:  # pragma: no cover
            abort(403)
        except procedures.CreditorDoesNotExist:
            abort(404)
        except procedures.AccountExists:
            return redirect(location, code=303)

        inspect_ops.register_account_creation(creditorId, debtorId)
        return account, {"Location": location}

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/", parameters=[CID, DID]
)
class AccountEndpoint(MethodView):
    @accounts_api.response(200, AccountSchema(context=context))
    @accounts_api.doc(
        operationId="getAccount",
        security=specs.SCOPE_ACCESS_READONLY,
    )
    def get(self, creditorId, debtorId):
        """Return account.

        The returned `Account` object encompasses all the avilable
        information for a particular account. This includes the
        follwing sub-objects:

        * `AccountConfig`
        * `AccountLedger`
        * `AccountInfo`
        * `AccountDisplay`
        * `AccountExchange`
        * `AccountKnowledge`

        Note that when one of those sub-objects gets changed, a
        `LogEntry` for the change in the particular sub-object will be
        added to the log, but a `LogEntry` for the change in the
        encompassing `Account` object *will not be added to the log*.

        """

        return procedures.get_account(creditorId, debtorId) or abort(404)

    @accounts_api.response(204)
    @accounts_api.doc(
        operationId="deleteAccount",
        security=specs.SCOPE_ACCESS_MODIFY,
        responses={403: specs.FORBIDDEN_ACCOUNT_DELETION},
    )
    def delete(self, creditorId, debtorId):
        """Delete account.

        This operation will succeed only if all of the following
        conditions are true:

        1. There are no other accounts pegged to this account.

        2. The account is marked as safe for deletion, or unsafe
           deletion is allowed for the account, or a `debtorName` has
           not been set for the account.

        """

        deleted = False
        inspect_ops.decrement_account_number(creditorId, debtorId)
        try:
            procedures.delete_account(creditorId, debtorId)
            deleted = True
        except procedures.UnsafeAccountDeletion:
            abort(403)
        except procedures.ForbiddenPegDeletion:
            abort(403)
        except (
            procedures.CreditorDoesNotExist,
            procedures.AccountDoesNotExist,
        ):
            return
        finally:
            # NOTE: We decremented the account number before trying to
            # delete the account. Now if the deletion has been
            # unsuccessful, we should increment the account number
            # again. This guarantees that in case of a crash, the
            # difference between the recorded number of accounts and
            # the real number of accounts will always be in users'
            # favor.
            deleted or inspect_ops.increment_account_number(
                creditorId, debtorId
            )

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/config", parameters=[CID, DID]
)
class AccountConfigEndpoint(MethodView):
    @accounts_api.response(200, AccountConfigSchema(context=context))
    @accounts_api.doc(
        operationId="getAccountConfig", security=specs.SCOPE_ACCESS_READONLY
    )
    def get(self, creditorId, debtorId):
        """Return account's configuration."""

        return procedures.get_account_config(creditorId, debtorId) or abort(
            404
        )

    @accounts_api.arguments(AccountConfigSchema)
    @accounts_api.response(200, AccountConfigSchema(context=context))
    @accounts_api.doc(
        operationId="updateAccountConfig",
        security=specs.SCOPE_ACCESS_MODIFY,
        responses={403: specs.FORBIDDEN_OPERATION, 409: specs.UPDATE_CONFLICT},
    )
    def patch(self, account_config, creditorId, debtorId):
        """Update account's configuration.

        **Note:** This is a potentially dangerous operation which may
        require a PIN. Also, normally this is an idempotent operation,
        but when an incorrect PIN is supplied, repeating the operation
        may result in the creditor's PIN being blocked.

        """

        try:
            inspect_ops.allow_account_reconfig(creditorId, debtorId)
            if not g.pin_reset_mode:
                procedures.verify_pin_value(
                    creditor_id=creditorId,
                    secret=current_app.config["PIN_PROTECTION_SECRET"],
                    pin_value=account_config.get("optional_pin"),
                    pin_failures_reset_interval=timedelta(
                        days=current_app.config["APP_PIN_FAILURES_RESET_DAYS"]
                    ),
                )
            config = procedures.update_account_config(
                creditor_id=creditorId,
                debtor_id=debtorId,
                is_scheduled_for_deletion=account_config[
                    "is_scheduled_for_deletion"
                ],
                negligible_amount=account_config["negligible_amount"],
                allow_unsafe_deletion=account_config["allow_unsafe_deletion"],
                config_data=account_config["config_data"],
                latest_update_id=account_config["latest_update_id"],
            )
        except (inspect_ops.ForbiddenOperation, procedures.WrongPinValue):
            abort(403)
        except (
            procedures.CreditorDoesNotExist,
            procedures.AccountDoesNotExist,
        ):
            abort(404)
        except procedures.UpdateConflict:
            abort(
                409, errors={"json": {"latestUpdateId": ["Incorrect value."]}}
            )

        inspect_ops.register_account_reconfig(creditorId, debtorId)
        return config

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/display", parameters=[CID, DID]
)
class AccountDisplayEndpoint(MethodView):
    @accounts_api.response(200, AccountDisplaySchema(context=context))
    @accounts_api.doc(
        operationId="getAccountDisplay", security=specs.SCOPE_ACCESS_READONLY
    )
    def get(self, creditorId, debtorId):
        """Return account's display settings."""

        return procedures.get_account_display(creditorId, debtorId) or abort(
            404
        )

    @accounts_api.arguments(AccountDisplaySchema)
    @accounts_api.response(200, AccountDisplaySchema(context=context))
    @accounts_api.doc(
        operationId="updateAccountDisplay",
        security=specs.SCOPE_ACCESS_MODIFY,
        responses={403: specs.FORBIDDEN_OPERATION, 409: specs.UPDATE_CONFLICT},
    )
    def patch(self, account_display, creditorId, debtorId):
        """Update account's display settings.

        A 422 error will be returned if there is another account with
        the same `debtorName`.

        **Note:** This is a potentially dangerous operation which may
        require a PIN. Also, normally this is an idempotent operation,
        but when an incorrect PIN is supplied, repeating the operation
        may result in the creditor's PIN being blocked.

        """

        try:
            if not g.pin_reset_mode:
                procedures.verify_pin_value(
                    creditor_id=creditorId,
                    secret=current_app.config["PIN_PROTECTION_SECRET"],
                    pin_value=account_display.get("optional_pin"),
                    pin_failures_reset_interval=timedelta(
                        days=current_app.config["APP_PIN_FAILURES_RESET_DAYS"]
                    ),
                )
            display = procedures.update_account_display(
                creditor_id=creditorId,
                debtor_id=debtorId,
                debtor_name=account_display.get("optional_debtor_name"),
                amount_divisor=account_display["amount_divisor"],
                decimal_places=account_display["decimal_places"],
                unit=account_display.get("optional_unit"),
                known_debtor=account_display["known_debtor"],
                latest_update_id=account_display["latest_update_id"],
            )
        except procedures.WrongPinValue:
            abort(403)
        except (
            procedures.CreditorDoesNotExist,
            procedures.AccountDoesNotExist,
        ):
            abort(404)
        except procedures.UpdateConflict:
            abort(
                409, errors={"json": {"latestUpdateId": ["Incorrect value."]}}
            )
        except procedures.DebtorNameConflict:
            abort(
                422,
                errors={
                    "json": {
                        "debtorName": [
                            "Another account with the same debtorName already"
                            " exist."
                        ]
                    }
                },
            )

        return display

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/exchange", parameters=[CID, DID]
)
class AccountExchangeEndpoint(MethodView):
    @accounts_api.response(200, AccountExchangeSchema(context=context))
    @accounts_api.doc(
        operationId="getAccountExchange", security=specs.SCOPE_ACCESS_READONLY
    )
    def get(self, creditorId, debtorId):
        """Return account's exchange settings."""

        return procedures.get_account_exchange(creditorId, debtorId) or abort(
            404
        )

    @accounts_api.arguments(AccountExchangeSchema)
    @accounts_api.response(200, AccountExchangeSchema(context=context))
    @accounts_api.doc(
        operationId="updateAccountExchange",
        security=specs.SCOPE_ACCESS_MODIFY,
        responses={403: specs.FORBIDDEN_OPERATION, 409: specs.UPDATE_CONFLICT},
    )
    def patch(self, account_exchange, creditorId, debtorId):
        """Update account's exchange settings.

        **Note:** This is a potentially dangerous operation which may
        require a PIN. Also, normally this is an idempotent operation,
        but when an incorrect PIN is supplied, repeating the operation
        may result in the creditor's PIN being blocked.

        """

        optional_peg = account_exchange.get("optional_peg")
        try:
            if not g.pin_reset_mode:
                procedures.verify_pin_value(
                    creditor_id=creditorId,
                    secret=current_app.config["PIN_PROTECTION_SECRET"],
                    pin_value=account_exchange.get("optional_pin"),
                    pin_failures_reset_interval=timedelta(
                        days=current_app.config["APP_PIN_FAILURES_RESET_DAYS"]
                    ),
                )
            exchange = procedures.update_account_exchange(
                creditor_id=creditorId,
                debtor_id=debtorId,
                policy=account_exchange.get("optional_policy"),
                min_principal=account_exchange["min_principal"],
                max_principal=account_exchange["max_principal"],
                peg_exchange_rate=optional_peg
                and optional_peg["exchange_rate"],
                peg_debtor_id=optional_peg
                and _parse_peg_account_uri(
                    creditor_id=creditorId,
                    base_url=request.full_path,
                    uri=optional_peg["account"]["uri"],
                ),
                latest_update_id=account_exchange["latest_update_id"],
            )
        except procedures.WrongPinValue:
            abort(403)
        except (
            procedures.CreditorDoesNotExist,
            procedures.AccountDoesNotExist,
        ):
            abort(404)
        except procedures.UpdateConflict:
            abort(
                409, errors={"json": {"latestUpdateId": ["Incorrect value."]}}
            )
        except procedures.InvalidPolicyName:  # pragma: nocover
            abort(422, errors={"json": {"policy": ["Invalid policy name."]}})
        except procedures.PegDoesNotExist:
            abort(
                422,
                errors={
                    "json": {
                        "peg": {
                            "account": {"uri": ["Account does not exist."]}
                        }
                    }
                },
            )

        return exchange

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/knowledge",
    parameters=[CID, DID],
)
class AccountKnowledgeEndpoint(MethodView):
    @accounts_api.response(200, AccountKnowledgeSchema(context=context))
    @accounts_api.doc(
        operationId="getAccountKnowledge",
        security=specs.SCOPE_ACCESS_READONLY,
        responses={409: specs.UPDATE_CONFLICT},
    )
    def get(self, creditorId, debtorId):
        """Return account's stored knowledge.

        The returned object contains previously stored knowledge about
        the account.

        """

        return procedures.get_account_knowledge(creditorId, debtorId) or abort(
            404
        )

    @accounts_api.arguments(AccountKnowledgeSchema)
    @accounts_api.response(200, AccountKnowledgeSchema(context=context))
    @accounts_api.doc(
        operationId="updateAccountKnowledge",
        security=specs.SCOPE_ACCESS_MODIFY,
        responses={409: specs.UPDATE_CONFLICT},
    )
    def patch(self, account_knowledge, creditorId, debtorId):
        """Update account's stored knowledge.

        This operation should be performed when an important knowledge
        about the account needs to be stored. In addition to the
        properties defined in the `AccountKnowledge` schema, the
        passed object may contain any other properties, which will be
        stored as well. The total length of the stored data can not
        exceed 8000 bytes (JSON, UTF-8 encoded, excluding `type` and
        `latestUpdateId` properties).

        **Example:** To be able to detect a change in the interest
        rate on the account, the client application can use this
        endpoint to store the interest rate acknowledged by the user,
        and later, compare the stored value with the current interest
        rate on the account. This way, the change in the interest rate
        will be correctly detected, even if the user uses several
        different client devices (or applications).

        """

        try:
            knowledge = procedures.update_account_knowledge(
                creditorId,
                debtorId,
                latest_update_id=account_knowledge["latest_update_id"],
                data=account_knowledge["data"],
            )
        except procedures.AccountDoesNotExist:
            abort(404)
        except procedures.UpdateConflict:
            abort(
                409, errors={"json": {"latestUpdateId": ["Incorrect value."]}}
            )

        return knowledge

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/info", parameters=[CID, DID]
)
class AccountInfoEndpoint(MethodView):
    @accounts_api.response(200, AccountInfoSchema(context=context))
    @accounts_api.doc(
        operationId="getAccountInfo", security=specs.SCOPE_ACCESS_READONLY
    )
    def get(self, creditorId, debtorId):
        """Return account's status information."""

        return procedures.get_account_info(creditorId, debtorId) or abort(404)

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/ledger", parameters=[CID, DID]
)
class AccountLedgerEndpoint(MethodView):
    @accounts_api.response(200, AccountLedgerSchema(context=context))
    @accounts_api.doc(
        operationId="getAccountLedger", security=specs.SCOPE_ACCESS_READONLY
    )
    def get(self, creditorId, debtorId):
        """Return account's ledger."""

        return procedures.get_account_ledger(creditorId, debtorId) or abort(
            404
        )

@accounts_api.route(
    "/<i64:creditorId>/accounts/<i64:debtorId>/entries", parameters=[CID, DID]
)
class AccountLedgerEntriesEndpoint(MethodView):
    @accounts_api.arguments(
        LedgerEntriesPaginationParamsSchema, location="query"
    )
    @accounts_api.response(
        200,
        LedgerEntriesPageSchema(context=context),
        example=examples.ACCOUNT_LEDGER_ENTRIES_EXAMPLE,
    )
    @accounts_api.doc(
        operationId="getAccountLedgerEntriesPage",
        security=specs.SCOPE_ACCESS_READONLY,
    )
    def get(self, params, creditorId, debtorId):
        """Return a collection of ledger entries for a given account.

        The returned object will be a fragment (a page) of a paginated
        list. The paginated list contains ledger entries for a given
        account. The returned fragment, and all the subsequent
        fragments, will be sorted in reverse-chronological order
        (bigger `entryId`s go first).

        """

        n = current_app.config["APP_LEDGER_ENTRIES_PER_PAGE"]
        prev = params["prev"]
        stop = params["stop"]
        try:
            ledger_entries = procedures.get_account_ledger_entries(
                creditorId, debtorId, count=n, prev=prev, stop=stop
            )
        except procedures.AccountDoesNotExist:  # pragma: no cover
            abort(404)

        if len(ledger_entries) < n:
            # The last page does not have a 'next' link.
            return {
                "uri": request.full_path,
                "items": ledger_entries,
            }

        return {
            "uri": request.full_path,
            "items": ledger_entries,
            "next": f"?prev={ledger_entries[-1].entry_id}&stop={stop}",
        }


#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Created on 13/02/2015

@author: jorgesaw
'''

from __future__ import absolute_import, print_function, unicode_literals

from mate.core.gui.Actions import addActions, createAction
from mate.vista import factoria

BCK_IMAGE = ':/fondo_abstracto.png'

MENUS = [u"&Archivo", u"&Productos", u"&Rubros", "&Informes", "&Ventas", "P&unto de venta"]

actSalir = ["&Salir", "Alt+F4", "quit.png", u"Salir de la aplicación", "triggered()"]

MATRIZ_ACTIONS_POR_MENU = [
            [
                ["&Exit", "Alt+F4", "quit.png", u"Exit the app", "triggered()"],

            ],
            [
                ["&Nuevo...", "", "article.png", u"Nuevo producto", "triggered()"],
                ["&Mostrar", "", "", u"Mostrar productos", "triggered()"],
                #["&Limits", "", "", u"Limits", "triggered()"]
            ],
            [
                ["&Nuevo...", "", "article.png", u"Nuevo rubro", "triggered()"],
                ["&Mostrar", "", "", u"Mostrar rubros", "triggered()"]
            ],
            [
                ["&Control de stock", "", "", u"Control de stock", "triggered()"],

            ],
            [
                ["&Informe de Ventas", "", "", u"Informe de Ventas", "triggered()"],

            ],
            [
                ["&Mostrar...", "", "", u"Mostrar TPV", "triggered()"],

            ],
        ]

def getActions(window, lst_var_actions, lstSlot, matriz=MATRIZ_ACTIONS_POR_MENU):
    #uAgrega las acciones definidas en factoria.
    matriz_actions = []
    i = factoria.APP_EXIT # Inicia con 0

    for menu in matriz:
        lstActions = []

        #print('LST_ACTIONS:', len(lstSlot))

        for action in menu:
            #print('I:', i)
            lst_var_actions[i] = createAction (window, window.tr(action[0]),
                                    slot=lstSlot[i],
                                    shortcut=action[1], icon=action[2],
                                    tip=window.tr(action[3]),
                                    signal=action[4]
                                    )
            lst_var_actions[i].setData(i)

            lstActions.append(lst_var_actions[i])
            i +=1

        matriz_actions.append(lstActions)

    return matriz_actions

def getMenus(window, lstMenus, matrizActions, menus=MENUS):
    for menu_string, menu_var, lstActions in zip(menus, lstMenus, matrizActions):
        menu_var = window.menuBar().addMenu(window.tr(menu_string))

        addActions(window, menu_var, lstActions)


for j in range (2,21) :
    f = open(f"MultiplicationTable of {j}.txt","w")
    for k in range(1,21) :
        mul = (j)*(k)
        if(k==20) :
            f.write(f"{j} X {k} = {mul}")

        else :
            f.write(f"{j} X {k} = {mul}\n")

        # break -> this is used to check the pgm running or not

    f.close()

print("Done!!")

PYTHON PART - 1/CHAPTER 9 - PART-1/13_fileMultiplication.py


from enum import Enum

class TemplateColor(Enum):
    NAME = (1, "赤" ,[255, 0, 0])
    ADRESS = (2 , "緑", [0, 255, 0])
    TEL = (3 , "青", [0, 0, 255])

    def __init__(self, id, color_name, rgb) -> None:
        super().__init__()
        self.id = id
        self.color_name = color_name
        self.rgb = rgb

print("zzz")
print(TemplateColor.NAME.rgb)

print(TemplateColor)
for area in TemplateColor:
    area_name = area.name  # NAME , ADDRESS , TEL
    aera_rgb = area.rgb
    print(area) # rgb値を与えたら値が返ってくる素晴らしい処理

# # 関数の処理時間を計測
# from functools import wraps
# import time

# # 関数を受け取る関数を定義
# # 内部の関数を返却する
# def time_measurement(func):
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         start = time.time()
#         exe = func(*args, **kwargs)
#         end = time.time()
#         print(f"time_measurement: {end - start}")
#         return exe
#     return wrapper

# # @をつけて呼び出す（デコレータ）と、呼び出し先の関数の引数に入る
# @time_measurement
# def func(num):
#     res = 0
#     for n in range(num):
#         res += n
#     return res

# func(10000000) # time_measurement: 0.48942112922668457

雑記/Enumに複数要素を定義.py

Enumに複数要素を定義.py


import sys
import pygame
from Game import *
from Game import WIDTH

def switch_start(screen,choice_logo):
    screen.fill(0)
    background_img = pygame.image.load('./resources/images/background.png')
    color_white = (255, 255, 255)
    color_gray = (192, 192, 192)
    font = pygame.font.Font('./resources/fonts/font.TTF',30)
    logo_img = pygame.image.load('./resources/images/logo.png')
    logo_img = pygame.transform.scale(logo_img, (450, 100))
    bird_img = pygame.image.load('./resources/images/bird.png')
    bird_rect = bird_img.get_rect()
    logo_rect = logo_img.get_rect()
    logo_rect.centerx,logo_rect.centery = 350,150
    jindu_img = pygame.image.load('./resources/images/gamebar.png')
    # 游戏加载提示
    font_render = font.render('Londing game data,You will enter Level_%s' %choice_logo,True,color_white)
    font_rect = font_render.get_rect()
    font_rect.centerx, font_rect.centery = 330,220
    # 游戏加载进度条进度
    # jindu_img.rect = jindu_img.get_rect()
    jindu_rect = jindu_img.get_rect()
    jindu_rect.centerx, jindu_rect.centery = 330,340
    bird_rect.left = jindu_rect.left
    bird_rect.centery = jindu_rect.centery
    # 加载所需时间
    load_time_left = jindu_rect.right - bird_rect.right + 8
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        if load_time_left <= 0:
            return
        for x in range(WIDTH // background_img.get_width() + 1):
            for y in range(HEIGHT // background_img.get_height() + 1):
                screen.blit(background_img, (x * 100, y * 100))
        screen.blit(logo_img,logo_rect)
        screen.blit(font_render,font_rect)
        screen.blit(jindu_img, jindu_rect)
        screen.blit(bird_img,bird_rect)
        pygame.draw.rect(screen,color_gray,(jindu_rect.left+6,jindu_rect.top+5,bird_rect.left-jindu_rect.left-8,bird_rect.bottom-jindu_rect.top-13))
        bird_rect.left += 1
        load_time_left -= 1
        pygame.display.update()
        clock.tick(60)


import click
from repoinsights.pr import fetch_pull_requests, PullRequest
from repoinsights.release import Release, fetch_releases
from datetime import datetime, timedelta
from io import StringIO
import csv

ONE_MONTH_BEFORE = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")

def to_csv(headers, rows, delimiter):
    delimiter = delimiter.replace("\\t", "\t").replace("\\n", "\n")
    with StringIO() as string_io:
        writer = csv.writer(string_io, delimiter=delimiter)
        writer.writerow(headers)
        writer.writerows(rows)
        return string_io.getvalue()

@click.group()
def cli():
    pass

@cli.command()
@click.argument("repository_name")
@click.argument("personal_token")
@click.option(
    "--first-created-date",
    "-f",
    default=ONE_MONTH_BEFORE,
    show_default=True,
    help="first created date to filter PRs (format: yyyy-mm-dd)",
)
@click.option("--base", "-b", default=None, help="a base branch to filter PR")
@click.option("--label", "-l", help="a label name to filter PR")
@click.option("--delimiter", "-d", default=",", show_default=True, help="a delimiter character to separate fields of a result")
def pr(repository_name, personal_token, first_created_date, base, label, delimiter):
    """
    This command allows you to get activity data of a GitHub Pull Reuqst.
    Time taken to merge field of a result is calculated by (merged datetime - created datetime of the PR).
    A result is output in CSV format.

    Usage: repo-insights pr "yuizho/repo-insights" "<your personal token of GitHub>"
    """
    records = fetch_pull_requests(
        repository_name,
        personal_token,
        first_created_date,
        base
    )

    filtered_records = records if label is None else [
        r for r in records if label in r.labels]

    print(
        to_csv(
            PullRequest.get_fields_name(),
            [r.get_fields()
             for r in sorted(filtered_records, key=lambda r: r.created_at)],
            delimiter
        )
    )

@cli.command()
@click.argument("repository_name")
@click.argument("personal_token")
@click.option(
    "--first-date",
    "-f",
    default=ONE_MONTH_BEFORE,
    show_default=True,
    help="first date to filter Releases",
)
@click.option("--delimiter", "-d", default=",", show_default=True, help="a delimiter character to separate fields of a result")
def release(repository_name, personal_token, first_date, delimiter):
    """
    This command allows you to get activity data of a GitHub Release.
    A result is output in CSV format.

    Usage: repo-insights release "yuizho/repo-insights" "<your personal token of GitHub>"
    """
    releases = fetch_releases(
        repository_name,
        personal_token,
        first_date
    )

    print(
        to_csv(
            Release.get_fields_name(),
            [r.get_fields() for r in sorted(releases, key=lambda r: r.published_at)],
            delimiter
        )
    )

def main():
    cli()

if __name__ == "__main__":
    main()


import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm

from modelscope.metainfo import Trainers
from modelscope.models.base import Model, TorchModel
from modelscope.models.nlp import BertForTextRanking
from modelscope.msdatasets.ms_dataset import MsDataset
from modelscope.preprocessors.base import Preprocessor
from modelscope.trainers.builder import TRAINERS
from modelscope.trainers.nlp_trainer import NlpEpochBasedTrainer
from modelscope.utils.constant import DEFAULT_MODEL_REVISION
from modelscope.utils.logger import get_logger

logger = get_logger()

@dataclass
class GroupCollator():
    """
    Wrapper that does conversion from List[Tuple[encode_qry, encode_psg]] to
    List[qry], List[psg] and pass batch separately to the actual collator.
    Abstract out data detail for the model.
    """

    def get_gis(self, gis, inps):
        gis_input_ids, gis_token_type_ids, gis_rel_type_ids = ([], [], [])
        gis_absolute_position_ids, gis_relative_position_ids = ([], [])
        gis_prov_ids, gis_city_ids, gis_dist_ids = ([], [], [])
        china_version = False
        for doc in inps:
            if len(doc) == 0:
                continue
            if len(doc[0]) == 6:
                for geom_id, geom_type, rel_type, absolute_position, relative_position, lxly in doc:
                    gis_input_ids.append(geom_id)
                    gis_token_type_ids.append(geom_type)
                    gis_rel_type_ids.append(rel_type)
                    gis_absolute_position_ids.append(absolute_position)
                    gis_relative_position_ids.append(relative_position)
            elif len(doc[0]) == 9:
                china_version = True
                for geom_id, geom_type, rel_type, absolute_position, relative_position, \
                        prov_id, city_id, dist_id, lxly in doc:
                    gis_input_ids.append(geom_id)
                    gis_token_type_ids.append(geom_type)
                    gis_rel_type_ids.append(rel_type)
                    gis_absolute_position_ids.append(absolute_position)
                    gis_relative_position_ids.append(relative_position)
                    gis_prov_ids.append(prov_id)
                    gis_city_ids.append(city_id)
                    gis_dist_ids.append(dist_id)

        gis.update(gis_input_ids, gis_token_type_ids, gis_rel_type_ids,
                   gis_absolute_position_ids, gis_relative_position_ids,
                   gis_prov_ids, gis_city_ids, gis_dist_ids, china_version)
        return gis

    def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
        if isinstance(features[0], list):
            features = sum(features, [])
        keys = features[0].keys()
        batch = {k: list() for k in keys}
        for ele in features:
            for k, v in ele.items():
                batch[k].append(v)
        merged_batch = {}
        gis_list = []
        gis_tp = []
        for k in batch:
            if 'sentence1_gis' == k:
                gis = batch['gis1'][0]
                gis = self.get_gis(gis, batch['sentence1_gis'])
                if gis.prov_ids is not None:
                    gis_list.append({
                        'input_ids': gis.input_ids,
                        'attention_mask': gis.attention_mask,
                        'token_type_ids': gis.token_type_ids,
                        'rel_type_ids': gis.rel_type_ids,
                        'absolute_position_ids': gis.absolute_position_ids,
                        'relative_position_ids': gis.relative_position_ids,
                        'prov_ids': gis.prov_ids,
                        'city_ids': gis.city_ids,
                        'dist_ids': gis.dist_ids
                    })
                else:
                    gis_list.append({
                        'input_ids':
                        gis.input_ids,
                        'attention_mask':
                        gis.attention_mask,
                        'token_type_ids':
                        gis.token_type_ids,
                        'rel_type_ids':
                        gis.rel_type_ids,
                        'absolute_position_ids':
                        gis.absolute_position_ids,
                        'relative_position_ids':
                        gis.relative_position_ids
                    })
                gis_tp.append(torch.LongTensor([1]).to(gis.input_ids.device))
            elif 'sentence2_gis' == k:
                gis = batch['gis2'][0]
                gis = self.get_gis(gis, batch['sentence2_gis'])
                if gis.prov_ids is not None:
                    gis_list.append({
                        'input_ids': gis.input_ids,
                        'attention_mask': gis.attention_mask,
                        'token_type_ids': gis.token_type_ids,
                        'rel_type_ids': gis.rel_type_ids,
                        'absolute_position_ids': gis.absolute_position_ids,
                        'relative_position_ids': gis.relative_position_ids,
                        'prov_ids': gis.prov_ids,
                        'city_ids': gis.city_ids,
                        'dist_ids': gis.dist_ids
                    })
                else:
                    gis_list.append({
                        'input_ids':
                        gis.input_ids,
                        'attention_mask':
                        gis.attention_mask,
                        'token_type_ids':
                        gis.token_type_ids,
                        'rel_type_ids':
                        gis.rel_type_ids,
                        'absolute_position_ids':
                        gis.absolute_position_ids,
                        'relative_position_ids':
                        gis.relative_position_ids
                    })
                gis_tp.append(torch.LongTensor([0]).to(gis.input_ids.device))
            elif 'qid' in k or 'labels' in k:
                merged_batch[k] = torch.cat(batch[k], dim=0)
            elif not k.startswith('gis'):
                k_t = [it.t() for it in batch[k]]
                pad = torch.nn.utils.rnn.pad_sequence(k_t)
                if len(pad.size()) <= 2:
                    merged_batch[k] = pad.t()
                else:
                    l, b1, b2 = pad.size()
                    merged_batch[k] = pad.view(l, b1 * b2).t()
        if len(gis_list) > 0:
            merged_batch['gis_list'] = gis_list
        if len(gis_tp) > 0:
            merged_batch['gis_tp'] = gis_tp
        return merged_batch

@TRAINERS.register_module(module_name=Trainers.mgeo_ranking_trainer)
class MGeoRankingTrainer(NlpEpochBasedTrainer):

    def __init__(
            self,
            model: Optional[Union[TorchModel, nn.Module, str]] = None,
            cfg_file: Optional[str] = None,
            cfg_modify_fn: Optional[Callable] = None,
            arg_parse_fn: Optional[Callable] = None,
            data_collator: Optional[Callable] = None,
            train_dataset: Optional[Union[MsDataset, Dataset]] = None,
            eval_dataset: Optional[Union[MsDataset, Dataset]] = None,
            preprocessor: Optional[Preprocessor] = None,
            optimizers: Tuple[torch.optim.Optimizer,
                              torch.optim.lr_scheduler._LRScheduler] = (None,
                                                                        None),
            model_revision: Optional[str] = DEFAULT_MODEL_REVISION,
            **kwargs):

        if data_collator is None:
            data_collator = GroupCollator()

        super().__init__(
            model=model,
            cfg_file=cfg_file,
            cfg_modify_fn=cfg_modify_fn,
            arg_parse_fn=arg_parse_fn,
            data_collator=data_collator,
            preprocessor=preprocessor,
            optimizers=optimizers,
            train_dataset=train_dataset,
            eval_dataset=eval_dataset,
            model_revision=model_revision,
            **kwargs)

    def compute_mrr(self, result, k=10):
        mrr = 0
        for res in result.values():
            sorted_res = sorted(res, key=lambda x: x[0], reverse=True)
            ar = 0
            for index, ele in enumerate(sorted_res[:k]):
                if str(ele[1]) == '1':
                    ar = 1.0 / (index + 1)
                    break
            mrr += ar
        return mrr / len(result)

    def compute_ndcg(self, result, k=10):
        ndcg = 0
        from sklearn import ndcg_score
        for res in result.values():
            sorted_res = sorted(res, key=lambda x: [0], reverse=True)
            labels = np.array([[ele[1] for ele in sorted_res]])
            scores = np.array([[ele[0] for ele in sorted_res]])
            ndcg += float(ndcg_score(labels, scores, k=k))
        ndcg = ndcg / len(result)
        return ndcg

    def to_device(self, val, device):
        if isinstance(val, torch.Tensor):
            return val.to(device)
        elif isinstance(val, list):
            return [self.to_device(item, device) for item in val]
        elif isinstance(val, dict):
            new_val = {}
            for key in val:
                new_val[key] = self.to_device(val[key], device)
            return new_val
        print('can not convert to device')
        raise Exception('can not convert to device')

    def evaluate(self,
                 checkpoint_path: Optional[str] = None,
                 *args,
                 **kwargs) -> Dict[str, float]:
        """evaluate a dataset

        evaluate a dataset via a specific model from the `checkpoint_path` path,
        if the `checkpoint_path` does not exist, read from the config file.

        Args:
            checkpoint_path (Optional[str], optional): the model path. Defaults
            to None.

        Returns:
            Dict[str, float]: the results about the evaluation Example:
            {"accuracy": 0.5091743119266054, "f1": 0.673780487804878}
        """
        # get the raw online dataset
        self.eval_dataloader = self._build_dataloader_with_dataset(
            self.eval_dataset,
            **self.cfg.evaluation.get('dataloader', {}),
            collate_fn=self.eval_data_collator)
        # generate a standard dataloader
        # generate a model
        if checkpoint_path is not None:
            model = BertForTextRanking.from_pretrained(checkpoint_path)
        else:
            model = self.model

        # copy from easynlp (start)
        model.eval()
        total_samples = 0

        logits_list = list()
        label_list = list()
        qid_list = list()

        total_spent_time = 0.0
        device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
        model.to(device)
        for _step, batch in enumerate(tqdm(self.eval_dataloader)):
            try:
                batch = self.to_device(batch, device)
            except RuntimeError:
                batch = {key: val for key, val in batch.items()}

            infer_start_time = time.time()
            with torch.no_grad():
                label_ids = batch.pop('labels').detach().cpu().numpy()
                qids = batch.pop('qid').detach().cpu().numpy()
                outputs = model(**batch)
            infer_end_time = time.time()
            total_spent_time += infer_end_time - infer_start_time
            total_samples += self.eval_dataloader.batch_size

            def sigmoid(logits):
                return np.exp(logits) / (1 + np.exp(logits))

            logits = outputs['logits'].squeeze(-1).detach().cpu().numpy()
            logits = sigmoid(logits).tolist()

            label_list.extend(label_ids)
            logits_list.extend(logits)
            qid_list.extend(qids)

        logger.info('Inference time = {:.2f}s, [{:.4f} ms / sample] '.format(
            total_spent_time, total_spent_time * 1000 / total_samples))

        rank_result = {}
        for qid, score, label in zip(qid_list, logits_list, label_list):
            if qid not in rank_result:
                rank_result[qid] = []
            rank_result[qid].append((score, label))

        for qid in rank_result:
            rank_result[qid] = sorted(rank_result[qid], key=lambda x: x[0])

        eval_outputs = list()
        for metric in self.metrics:
            if metric.startswith('mrr'):
                k = metric.split('@')[-1]
                k = int(k)
                mrr = self.compute_mrr(rank_result, k=k)
                logger.info('{}: {}'.format(metric, mrr))
                eval_outputs.append((metric, mrr))
            elif metric.startswith('ndcg'):
                k = metric.split('@')[-1]
                k = int(k)
                ndcg = self.compute_ndcg(rank_result, k=k)
                logger.info('{}: {}'.format(metric, ndcg))
                eval_outputs.append(('ndcg', ndcg))
            else:
                raise NotImplementedError('Metric %s not implemented' % metric)

        return dict(eval_outputs)


import argparse
import os
import socket
import threading
from builtins import Exception
from time import sleep

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash
from cryptography.hazmat.primitives.ciphers.aead import AESCCM

seperator = b'+'

def key_generator(key):
    print(type(key), len(key))
    # Using PRF to generate IV
    aesccm = AESCCM(key)
    ckdf = ConcatKDFHash(algorithm=hashes.SHA256(), length=13, otherinfo=None)
    iv = ckdf.derive(key)

    return aesccm, iv

def client_receive(client, sk, aesccm, iv):
    while True:

        ct = client.recv(1024)
        aesccm, iv =key_generator(sk)
        message = ct.split(seperator)
        print(sk)
        print('Received:', message)
        # print(sk)
        # print( args.n.encode(), message[1])
        try:

            if args.n.encode() == message[1] and b'102' == message[0]:
                # print(f"\nmessage encrypted content:\n {ct}")
                message = aesccm.decrypt(iv, message[2], None)
                print(f"\nmessage decrypted content...\n")
                print(message)
                with open(f'{args.n}_received.txt', 'wb') as f:
                    f.write(message)
            elif args.n.encode() == message[1] and b'103' == message[0]:
                print("File not found...")

            else:
                print(f"message discarded...\n")
        except:
            # print(Exception)
            print(f'Error Occured try again....')
            # client.close()
            # exit()
            break

def client_send(client, sk, aesccm, iv):
    while True:
        file = input("Enter file name: \n").encode()
        message = b'101' + seperator + args.n.encode() + seperator + file
        ct = aesccm.encrypt(iv, message, None)
        client.send(ct)
        sleep(1)

def active(client, sk, aesccm, iv):
    receive_thread = threading.Thread(target=client_receive, args=(client, sk, aesccm, iv))
    receive_thread.start()

    send_thread = threading.Thread(target=client_send, args=(client, sk, aesccm, iv))
    send_thread.start()

def authenticate_token(client):
    try:
        f = open(f"{args.n}_token.txt", 'rb')
        sk_token = f.read()
        f.close()
    except:
        authenticate_credentials(client)
        return

    # print(sk_token)
    sk_token = sk_token.split(seperator)
    sk = sk_token[0]
    token = sk_token[1]
    print(f"{args.n} Authenticating with the token...")
    message = b'701' + seperator + args.n.encode() + seperator + token
    client.send(message)
    ct = client.recv(1024)
    # print(ct)
    aesccm, iv = key_generator(sk)
    # message = aesccm.decrypt(iv, ct, None)

    message = ct.split(seperator)

    if message[0] == b'802':
        print(f"{args.n}'s Token Authentication Successful...")
        active(client, sk, aesccm, iv)

    elif message[0] == b'803':
        print(f"Token Authentication failed...")
        # print(f"{args.n} Token Authentication failed...")
        authenticate_credentials(client)

def authenticate_credentials(client):
    print(f"Authenticate using password file...")
    # print(f"{args.n} Authenticate using password file...")

    key_file = input("Enter your password file name...\n")
    with open(key_file, 'rb') as kf:
        psk_key = kf.read()
    # print("Working Good...1")
    aesccm, iv = key_generator(psk_key)

    nonce = os.urandom(6)

    message = args.n.encode() + seperator + nonce + seperator + args.m.encode() + seperator + str(args.v).encode()
    ct = aesccm.encrypt(iv, message, None)
    message = b'700' + seperator + args.n.encode() + seperator + ct
    client.send(message)
    # print(message)
    message = client.recv(1024)

    message = message.split(seperator)

    if message[0] == b'800':
        print(f"Authentication Successful...")
        # print(f"{args.n}'s Authentication Successful...")
        with open(f'{args.n}.txt', 'wb') as f:
            f.write(message[4])

        id = message[2]
        # ct = message[2]
        # print(message)
        # message = aesccm.encrypt(iv, ct, None).split(seperator)
        if id != args.n.encode():
            print('Error Occurred...')

            exit()
        sk = message[1]
        token = message[4]
        with open(f'{id.decode()}_token.txt', 'wb') as kf:
            kf.write(sk+seperator+token)

        aesccm, iv = key_generator(sk)
        active(client, sk, aesccm, iv)

    elif message[0] == b'801':
        # raise Exception(f"{args.n}  Authentication failed...")
        print(f"Authentication failed...")

def search_AP(AP):
    f = open("AP.txt", 'r')
    AP_details = f.read().split('\n')
    f.close()
    AP_select = ''
    found = False

    for i in AP_details:
        if AP in i:
            AP_select = i
            found = True
            break

    if found == False:
        print(f"AP {AP} is not Available...")
        exit()
    else:
        print(f"connecting to  {AP}...")

    port = int(AP_select.split(':')[1])

    # Create a socket object
    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # connect to the AP
    clientSocket.connect(("127.0.0.1", port))

    return clientSocket

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-n', type=str)  # id of device
    parser.add_argument('-a', type=str)  # AP name
    parser.add_argument('-m', type=str, default='h')  # Mode Hours or days
    parser.add_argument('-v', type=int, default=1)  # Token Validity

    args = parser.parse_args()
    # Search & Connect AP
    client = search_AP(args.a)

# try:
    authenticate_token(client)
# except:

    # try:
    #     authenticate_credentials(client)
    # except:
    #     print("Authentication Failed")
    #     client.close()
    #     raise Exception
    #     exit()


#
# @lc app=leetcode.cn id=13 lang=python3
#
# [13] 罗马数字转整数
#

# @lc code=start
class Solution:
    SYMBOL_VALUES = [
        ("M", 1000),
        ("CM", 900),
        ("D", 500),
        ("CD", 400),
        ("C", 100),
        ("XC", 90),
        ("L", 50),
        ("XL", 40),
        ("X", 10),
        ("IX", 9),
        ("V", 5),
        ("IV", 4),
        ("I", 1),
    ]

    def romanToInt(self,s: str) -> int:
        ans = 0
        while s:
            for symbol, value in Solution.SYMBOL_VALUES:
                # print(s)
                # print(symbol)
                if s.startswith(symbol):
                    # print(value)
                    # print(ans)
                    ans += value
                    s = s[len(symbol):]
        return ans
# @lc code=end


import os

BASE_URL = 'https://api-testing.mozio.com'
LANGUAGE = 'en-US'
API_KEY = os.environ.get('MOZIO_API_KEY')
HEADERS = {
    'Content-Type': 'application/json',
    'API-KEY': API_KEY,
    'LANG': LANGUAGE
}
indent = 4


# -*- coding: utf-8 -*-
# __author__ = 'qingchen.zhang'

from biocluster.api.database.base import Base, report_check
import re
import json
import datetime
from bson.objectid import ObjectId
from types import StringTypes

class Circos(Base):

    def __init__(self, bind_object):
        super(Circos, self).__init__(bind_object)
        self._project_type = 'metaasv'
        self.task_id = ""
        self.name_id = dict()

    @report_check
    def add_barpie(self, params, from_otu_table, name=None, newick_id=None):
        if from_otu_table != 0 and not isinstance(from_otu_table, ObjectId):
            if isinstance(from_otu_table, StringTypes):
                from_otu_table = ObjectId(from_otu_table)
            else:
                self.bind_object.set_error("from_otu_table必须为ObjectId对象或其对应的字符串!")
        collection = self.db["asv"]
        result = collection.find_one({"_id": from_otu_table})
        if not result:
            self.bind_object.logger.error("无法根据传入的_id:{}circos在表里找到相应的记录".format(str(from_otu_table)))
            self.bind_object.set_error("在sg_otu表中找不到相应记录")
        project_sn = result['project_sn']
        self.task_id = result['task_id']
        if not name:
            name = "circos_" + datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        insert_data = {
            "project_sn": project_sn,
            'task_id': self.task_id,
            'asv_id': str(from_otu_table),
            'name': self.bind_object.sheet.main_table_name if self.bind_object.sheet.main_table_name else name,
            "params": params,
            'status': 'end',
            'desc': 'Circos主表',
            'created_ts': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        }
        collection = self.db["circos"]
        inserted_id = collection.insert_one(insert_data).inserted_id
        return inserted_id

    @report_check
    def add_sg_otu_detail(self, file_path, main_id):
        self.bind_object.logger.info("开始导入circos_detail表")
        find_otu = self.db['circos'].find_one({"_id": ObjectId(main_id)})
        if find_otu:
            self.task_id = find_otu['task_id']
        else:
            self.bind_object.set_error("没有找到相关的主表信息")
        species_sort = []
        with open(file_path, 'rb') as r:
            lines = r.readlines()
            head = lines[0].strip('\r\n')
            head = re.split('\t', head)
            sample_list = head[1:]
            data_list = []
            for line in lines[1:]:
                line = line.strip().split('\t')
                sample_num = [float(x) for x in line[1:]]
                if line[0] not in species_sort:
                    species_sort.append(line[0].strip().split("; ")[-1].strip())
                otu_detail = {
                    "circos_id": ObjectId(main_id),
                    "species_name": line[0].strip().split("; ")[-1].strip()
                }
                values_dict = dict(zip(sample_list, sample_num))
                data_list.append(dict(otu_detail, **values_dict))
        try:
            collection = self.db['circos_detail']
            collection.insert_many(data_list)
        except Exception as e:
            self.bind_object.logger.error("导入circos_detail表格信息出错:{}".format(e))
        else:
            self.bind_object.logger.info("导入circos_detail表格成功")
        try:
            main_collection = self.db['circos']
            settled_params = {'software': "python-2.7"}
            settled_params_json = json.dumps(settled_params, sort_keys=True, separators=(',', ':'))
            specimen_sort = sample_list
            main_collection.update({"_id":ObjectId(main_id)},{"$set":{"settled_params":settled_params_json,
                                                                      "specimen_sort":specimen_sort,
                                                                      "main_id": ObjectId(main_id),
                                                                      "species_sort":species_sort,
                                                                      }})
        except Exception as e:
            self.bind_object.logger.error("更新circos表格信息出错:{}".format(e))
        else:
            self.bind_object.logger.info("更新circos表格成功")


# -*- coding: UTF-8 -*-
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from config import setting
from logger import Logger

logger = Logger('send_email').getLog()

def SendMail(file_name):
    '''
    邮件发送
    :param file_name:
    :return:
    '''

    filename = os.path.join(setting.REPORT_PATH,'%s' % file_name)
    with open(filename,'rb+') as f:
        report = f.read()

    # 邮件首部
    message = MIMEMultipart()
    message['From'] = setting.FROM_ADDR
    message['To'] = setting.TO_ADDR
    subject = '自动化测试报告'
    message['Subject'] = Header(subject,'utf-8')

    #正文内容
    message.attach(MIMEText('自动化测试报告在附件，请查收','plain','utf-8'))

    #添加附件
    att = MIMEText(report,'plain','utf-8')
    att["Content-Type"] = 'application/octet-stream'
    # 邮件附件的名字
    att["Content-Disposition"] = 'attachment; filename=%s' % filename
    message.attach(att)

    try:
        smtp_obj = smtplib.SMTP()
        smtp_obj.connect("smtp.163.com", "25")
        state = smtp_obj.login(setting.FROM_ADDR, setting.PASSWORD)
        if state[0] == 235:
            smtp_obj.sendmail(setting.FROM_ADDR, setting.TO_ADDR, message.as_string())
            logger.info("Sent mail successfully!")
        smtp_obj.quit()
    except smtplib.SMTPException as e:
        logger.error(str(e))

if __name__ == '__main__':
    SendMail('report')


# -*- coding: utf-8 -*-
class Train:
    learning_rate = 0.0001
    optimizer = 'adam'
    var_filter = ''
    grads_clip = 5
    loss_ce = 1.0
    loss_mwer = 0.5
    num_batch = 5614
    is_scheduled = False

class Test:
    beam_size = 10
    max_target_length = 34
    lp_alpha = 0.6

class Hyperparams:
    '''Hyperparameters'''
    # training
    batch_size = 8  # alias = N
    lr = 0.0001  # learning rate. In paper, learning rate is adjusted to the global step.
    logdir = 'logdir'  # log directory

    # model
    maxlen = 34  # Maximum number of words in a sentence. alias = T.
    hidden_units = 512  # alias = C
    num_blocks = 6  # number of encoder/decoder blocks
    num_epochs = 10
    num_heads = 8
    dropout_rate = 0.1
    sinusoid = False  # If True, use sinusoid. If false, positional embedding.
    sample_rate = 16000
    audio_length = 532
    audio_feature_length = 320
    audio_signal_length = 16 * sample_rate
    log_mel_length = 1598

    save_epochs = 3
    beam_size = 10
    end_id = 3
    filter_size = 5
    num_filters_1 = 64
    num_filters_2 = 128
    filter_sizes = [1, 3, 5, 7]
    bn_decay = 0.9997
    bn_epsilon = 0.001

    train = Train
    test = Test

    loss_type = ['ce', 'l2', 'mwer']


class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        # print(Counter(word1).values(),Counter(word2).values())
        a = Counter(word1)
        b = Counter(word2)
        arr1 = []
        arr2 = []
        for i in a:
            arr1.append([
                i,a[i]
            ])
        for i in b:
            arr2.append([
                i,b[i]
            ])
        arr1.sort(key = lambda x : x[1])
        arr2.sort(key = lambda x : x[1])
        # print(arr1)
        # print(arr2)
        d = dict()
        for i in range(len(arr1)):
            d[arr1[i][0]] = i
            if arr1[i][1]!=arr2[i][1]:
                return False

        for i in range(len(arr1)):
            c1 = arr1[i][0]
            c2 = arr2[i][0]
            if c1!=c2 and c2 not in a:
                return False
            elif c1!=c2 and c2 in a:
                thatIndex = d[c2]
                arr1[thatIndex][0] = c1

        return True