import pandas as pd
import numpy as np
import seaborn as sb

numerical = ['year', 'achievements', 'price', 'est_owners', # general information
            'num_categories', 'num_genres',  # imputed information
            'positive_ratings', 'negative_ratings', 'ratings_ratio', # dependent information
            'median_playtime']

categorical = ['mac', 'linux', 'Multi-player', 'Steam Achievements', 'Steam Trading Cards',
               'Indie', 'Action', 'Casual', 'Strategy', 'Simulation', 'Free to Play', 'kid_friendly', 'mature']

columns = categorical + numerical

def catplot_ylabel(g: sb.axisgrid.FacetGrid, fmt='{0:.0f}') -> sb.axisgrid.FacetGrid:
    # extract the matplotlib axes_subplot objects from the FacetGrid
    ax = g.axes.flat[0]

    # iterate through the axes containers
    for c in ax.containers:
        labels = [fmt.format(v.get_width()) for v in c]
        ax.bar_label(c, labels=labels, label_type='edge', padding=3)

    return g

def catplot_xlabel(g: sb.axisgrid.FacetGrid, fmt='{0:.0f}') -> sb.axisgrid.FacetGrid:
    # extract the matplotlib axes_subplot objects from the FacetGrid
    ax = g.axes.flat[0]

    # iterate through the axes containers
    for c in ax.containers:
        labels = [fmt.format(v.get_height()) for v in c]
        ax.bar_label(c, labels=labels, label_type='edge', padding=3)

    return g

def catplot_xpercent(data: pd.DataFrame, var: str, fmt='{0:.1%}') -> sb.axisgrid.FacetGrid:
    d = data[var].value_counts() / len(data)
    return catplot_xpercent_raw(d, var, fmt)

def catplot_xpercent_raw(data: pd.Series, var: str, fmt='{0:.1%}') -> sb.axisgrid.FacetGrid:
    g = sb.catplot(data=data.to_frame('percentage').reset_index(names=var), x=var, y='percentage', kind='bar')
    return catplot_xlabel(g, fmt=fmt)

def catplot_ypercent(data: pd.DataFrame, var: str, fmt='{0:.1%}') -> sb.axisgrid.FacetGrid:
    d = data[var].value_counts() / len(data)
    return catplot_ypercent_raw(d, var, fmt)

def catplot_ypercent_raw(data: pd.Series, var: str, fmt='{0:.1%}') -> sb.axisgrid.FacetGrid:
    g = sb.catplot(data=data.to_frame('percentage').reset_index(names=var), y=var, x='percentage', kind='bar')
    return catplot_ylabel(g, fmt=fmt)

def significant_digits(df: "Union[pd.DataFrame, pd.Series]",
                       significance: int,
                       inplace: bool = False
                       ) -> "Union[pd.DataFrame, pd.Series, None]":

    # Create a positive data vector with a place holder for NaN / inf data
    data = df.values
    data_positive = np.where(np.isfinite(data) & (data != 0),
                             np.abs(data),
                             10**(significance-1))

    # Align data by magnitude, round, and scale back to original
    magnitude = 10 ** (significance - 1 - np.floor(np.log10(data_positive)))
    data_rounded = np.round(data * magnitude) / magnitude

    # Place back into Series or DataFrame
    if inplace:
        df.loc[:] = data_rounded
    else:
        if isinstance(df, pd.DataFrame):
            return pd.DataFrame(data=data_rounded,
                                index=df.index,
                                columns=df.columns)
        else:
            return pd.Series(data=data_rounded, index=df.index)

def shorten(number):
    if number >= 1_000_000:
        return f'{number / 1_000_000:.0f}M'
    elif number >= 1_000:
        return f'{number / 1_000:.0f}K'
    elif number == 0:
        return '0'
    else:
        return f'{number / 1_000:.2f}K'


def main():
    n = int(input())
    while True:
        n = sum(map(lambda e: int(e)**2, list(str(n))))
        if n == 4:
            print("UNHAPPY")
            break
        elif n == 1:
            print("HAPPY")
            break

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
import os
import tensorflow as tf
import numpy as np
from non_local_tf import non_local_block
tf.enable_eager_execution()

n_class = 100

layers = tf.keras.layers
class CNN(tf.keras.Model):
    def __init__(self, non_local=True):
        super(CNN, self).__init__()
        self.non_local = non_local
        self.conv1 = layers.Conv2D(16, (3,3), padding='same')
        self.pool1 = layers.MaxPool2D(2)
        self.conv2 = layers.Conv2D(32, (3,3), padding='same')
        self.pool2 = layers.MaxPool2D(2)
        self.conv3 = layers.Conv2D(64, (3,3), padding='same')
        self.pool3 = layers.MaxPool2D(2)
        self.conv4 = layers.Conv2D(128, (3,3), padding='same')
        self.conv5 = layers.Conv2D(128, (3,3), padding='same')
        self.avgPool = layers.AveragePooling2D((4,4))
        self.dense = layers.Dense(n_class)

        # non-local
        if non_local == True:
            self.atten1 = non_local_block(input_channel=128, input_shape=4, mode='embedded')
            self.atten2 = non_local_block(input_channel=128, input_shape=4, mode='embedded')

    def predict(self, x):
        x = self.conv1(x)  # (batchsize, 32, 32, 16)
        x = tf.nn.relu(x)
        x = self.pool1(x)

        x = self.conv2(x)  # (batchsize, 16, 16, 32)
        x = tf.nn.relu(x)
        x = self.pool2(x)

        x = self.conv3(x)   # (batchsize, 8, 8, 64)
        x = tf.nn.relu(x)
        x = self.pool3(x)

        x = self.conv4(x)    # (batchsize, 4, 4, 128)
        x = tf.nn.relu(x)
        [x, w1] = self.atten1(x) if self.non_local else [x, None]
        x = self.conv5(x)    # (batchsize, 4, 4, 128)
        x = tf.nn.relu(x)
        [x, w2] = self.atten2(x) if self.non_local else [x, None]
        x = self.avgPool(x)  # (batchsize, 1, 1, 128)
        x = tf.squeeze(x)    # (batchsize, 128)

        logits = self.dense(x)   # (batchsize, 100)
        return logits, [w1,w2]

    def loss_fn(self, X, y):
        preds, _ = self.predict(X)
        loss = tf.losses.sparse_softmax_cross_entropy(labels=y, logits=preds)
        return loss

    def acc_fn(self, X, y):
        preds = self.predict(X)[0].numpy()
        acc = np.sum(np.argmax(preds, axis=1) == y.numpy(), dtype=np.float32) / X.numpy().shape[0]
        return acc

def train(model, dataset, test_data, test_labels, optimizer, epoches, logdir):
    train_losses, val_losses, val_accs = [], [], []
    test_data, test_labels = tf.convert_to_tensor(test_data), tf.convert_to_tensor(test_labels)
    best_acc = 0.
    # train
    for epoch in range(epoches):
        losses = []
        for (batch, (inp, targ)) in enumerate(dataset):
            with tf.GradientTape() as tape:
                loss = model.loss_fn(inp, targ)
            gradients = tape.gradient(loss, model.trainable_variables)
            # print("loss: ", loss.numpy(), ",\tacc: ", model.acc_fn(inp, targ)*100, "%")
            optimizer.apply_gradients(zip(gradients, model.variables))
            losses.append(loss)

        print("Epoch :", epoch, ", train loss :", np.mean(losses))
        val_loss = model.loss_fn(test_data, test_labels)
        val_acc = model.acc_fn(test_data, test_labels)
        print("Epoch :", epoch, ", val loss", val_loss.numpy(),", valid acc:", val_acc*100, "%")
        train_losses.append(np.mean(losses))
        val_losses.append(val_loss)
        val_accs.append(val_acc)
        if val_acc > best_acc:
            # model.save_weights(os.path.join(logdir, "model_best_"+str(val_acc)+".h5"))
            model.save_weights(os.path.join(logdir, "model_best.h5"))
            best_acc = val_acc
    return np.array(train_losses), np.array(val_losses), np.array(val_accs)

if __name__ == '__main__':
    # dataset
    (X_train, y_train), (X_test, y_test) = tf.keras.datasets.cifar100.load_data()
    X_train = X_train.astype(np.float32) / 255.
    X_test = X_test.astype(np.float32) / 255.
    y_train = y_train.reshape(y_train.shape[0]).astype(np.int)
    y_test = y_test.reshape(y_test.shape[0]).astype(np.int)

    dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(50000)
    dataset = dataset.batch(64, drop_remainder=True)

    # model
    non_local = True
    learning_rate = tf.Variable(1e-3, name="learning_rate")
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
    model = CNN(non_local=non_local)

    # dir
    logdir = "log-non-local" if non_local else "log"
    if not os.path.exists(logdir):
        os.makedirs(logdir)

    # train
    loss1, loss2, accs = train(model, dataset, X_test, y_test, optimizer, epoches=30, logdir=logdir)

    # plot
    import matplotlib.pyplot as plt
    plt.figure(figsize=(8, 8))
    plt.plot(np.arange(loss1.shape[0]), loss1)
    plt.plot(np.arange(loss2.shape[0]), loss2)
    plt.legend(["train loss", "val loss"])
    plt.grid()
    plt.savefig(os.path.join(logdir, "loss.png"))
    plt.close()

    plt.figure(figsize=(8, 8))
    plt.plot(np.arange(accs.shape[0]), accs)
    plt.legend(["val acc"])
    plt.grid()
    plt.savefig(os.path.join(logdir, "acc.png"))
    plt.close()


"""Admin routes for presentations."""

import json

from uuid import uuid4

from aiohttp import web
from aiohttp_apispec import docs, request_schema, response_schema
from marshmallow import fields, Schema

from ....holder.base import BaseHolder
from ....storage.error import StorageNotFoundError

from ...connections.models.connection_record import ConnectionRecord
from ...decorators.attach_decorator import AttachDecorator
from ...valid import (
    INDY_CRED_DEF_ID,
    INDY_DID,
    INDY_PREDICATE,
    INDY_SCHEMA_ID,
    INDY_VERSION,
    INT_EPOCH,
    UUIDFour,
)

from .manager import PresentationManager
from .messages.inner.presentation_preview import (
    PresentationPreview,
    PresentationPreviewSchema
)
from .messages.presentation_proposal import PresentationProposal
from .messages.presentation_request import PresentationRequest
from .models.presentation_exchange import (
    V10PresentationExchange,
    V10PresentationExchangeSchema,
)

class V10PresentationExchangeListSchema(Schema):
    """Result schema for an Aries#0037 v1.0 presentation exchange query."""

    results = fields.List(
        fields.Nested(V10PresentationExchangeSchema()),
        description="Aries#0037 v1.0 presentation exchange records"
    )

class V10PresentationProposalRequestSchema(Schema):
    """Request schema for sending a presentation proposal admin message."""

    connection_id = fields.UUID(
        description="Connection identifier",
        required=True,
        example=UUIDFour.EXAMPLE,
    )
    comment = fields.Str(
        description="Human-readable comment",
        required=False,
        default="")
    presentation_proposal = fields.Nested(PresentationPreviewSchema(), required=True)
    auto_present = fields.Boolean(
        description=(
            "Whether to respond automatically to presentation requests, building "
            "and presenting requested proof"
        ),
        required=False,
        default=False
    )

class IndyProofReqSpecRestrictionsSchema(Schema):
    """Schema for restrictions in attr or pred specifier indy proof request."""

    credential_definition_id = fields.Str(
        description="Credential definition identifier",
        required=True,
        **INDY_CRED_DEF_ID
    )
    schema_id = fields.String(
        description="Schema identifier",
        required=False,
        **INDY_SCHEMA_ID
    )
    schema_issuer_did = fields.String(
        description="Schema issuer (origin) DID",
        required=False,
        **INDY_DID
    )
    schema_name = fields.String(
        example="transcript",
        description="Schema name",
        required=False
    )
    schema_version = fields.String(
        description="Schema version",
        required=False,
        **INDY_VERSION
    )
    issuer_did = fields.String(
        description="Credential issuer DID",
        required=False,
        **INDY_DID
    )
    cred_def_id = fields.String(
        description="Credential definition identifier",
        required=False,
        **INDY_CRED_DEF_ID
    )

class IndyProofReqNonRevoked(Schema):
    """Non-revocation times specification in indy proof request."""

    from_epoch = fields.Int(
        description="Earliest epoch of interest for non-revocation proof",
        required=True,
        **INT_EPOCH
    )
    to_epoch = fields.Int(
        description="Latest epoch of interest for non-revocation proof",
        required=True,
        **INT_EPOCH
    )

class IndyProofReqAttrSpecSchema(Schema):
    """Schema for attribute specification in indy proof request."""

    name = fields.String(
        example="favouriteDrink",
        description="Attribute name",
        required=True)
    restrictions = fields.List(
        fields.Nested(IndyProofReqSpecRestrictionsSchema()),
        description="If present, credential must satisfy one of given restrictions",
        required=False
    )
    non_revoked = fields.Nested(
        IndyProofReqNonRevoked(),
        required=False
    )

class IndyProofReqPredSpecSchema(Schema):
    """Schema for predicate specification in indy proof request."""

    name = fields.String(
        example="index",
        description="Attribute name",
        required=True)
    p_type: fields.String(
        description="Predicate type (indy currently supports only '>=')",
        required=True,
        **INDY_PREDICATE
    )
    p_value: fields.Integer(
        description="Threshold value",
        required=True,
    )
    restrictions = fields.List(
        fields.Nested(IndyProofReqSpecRestrictionsSchema()),
        description="If present, credential must satisfy one of given restrictions",
        required=False
    )
    non_revoked = fields.Nested(
        IndyProofReqNonRevoked(),
        required=False
    )

class IndyProofRequestSchema(Schema):
    """Schema for indy proof request."""

    nonce = fields.String(
        description="Nonce",
        required=False,
        example="1234567890"
    )
    name = fields.String(
        description="Proof request name",
        required=False,
        example="Proof request",
        default="Proof request"
    )
    version = fields.String(
        description="Proof request version",
        required=False,
        default="1.0",
        **INDY_VERSION
    )
    requested_attributes = fields.Dict(
        description=("Requested attribute specifications of proof request"),
        required=True,
        keys=fields.Str(example="0_attr_uuid"),  # marshmallow/apispec v3.0 ignores
        values=fields.Nested(IndyProofReqAttrSpecSchema())
    )
    requested_predicates = fields.Dict(
        description=("Requested predicate specifications of proof request"),
        required=True,
        keys=fields.Str(example="0_age_GE_uuid"),  # marshmallow/apispec v3.0 ignores
        values=fields.Nested(IndyProofReqPredSpecSchema())
    )

class V10PresentationRequestRequestSchema(Schema):
    """Request schema for sending a proof request."""

    connection_id = fields.UUID(
        description="Connection identifier",
        required=True,
        example=UUIDFour.EXAMPLE,
    )
    proof_request = fields.Nested(IndyProofRequestSchema(), required=True)

class IndyRequestedCredsRequestedAttrSchema(Schema):
    """Schema for requested attributes within indy requested credentials structure."""

    cred_id = fields.Str(
        example="3fa85f64-5717-4562-b3fc-2c963f66afa6",
        description=(
            "Wallet credential identifier (typically but not necessarily a UUID)"
        )
    )
    revealed = fields.Bool(
        description="Whether to reveal attribute in proof",
        default=True
    )

class IndyRequestedCredsRequestedPredSchema(Schema):
    """Schema for requested predicates within indy requested credentials structure."""

    cred_id = fields.Str(
        example="3fa85f64-5717-4562-b3fc-2c963f66afa6",
        description=(
            "Wallet credential identifier (typically but not necessarily a UUID)"
        )
    )

class V10PresentationRequestSchema(Schema):
    """Request schema for sending a presentation."""

    self_attested_attributes = fields.Dict(
        description=("Self-attested attributes to build into proof"),
        required=True,
        keys=fields.Str(example="attr_name"),  # marshmallow/apispec v3.0 ignores
        values=fields.Str(
            example="self_attested_value",
            description=(
                "Self-attested attribute values to use in requested-credentials "
                "structure for proof construction"
            )
        )
    )
    requested_attributes = fields.Dict(
        description=(
            "Nested object mapping proof request attribute referents to "
            "requested-attribute specifiers"
        ),
        required=True,
        keys=fields.Str(example="attr_referent"),  # marshmallow/apispec v3.0 ignores
        values=fields.Nested(IndyRequestedCredsRequestedAttrSchema())
    )
    requested_predicates = fields.Dict(
        description=(
            "Nested object mapping proof request predicate referents to "
            "requested-predicate specifiers"
        ),
        required=True,
        keys=fields.Str(example="pred_referent"),  # marshmallow/apispec v3.0 ignores
        values=fields.Nested(IndyRequestedCredsRequestedPredSchema())
    )

@docs(
    tags=["present-proof"],
    summary="Fetch all present-proof exchange records"
)
@response_schema(V10PresentationExchangeListSchema(), 200)
async def presentation_exchange_list(request: web.BaseRequest):
    """
    Request handler for searching presentation exchange records.

    Args:
        request: aiohttp request object

    Returns:
        The presentation exchange list response

    """
    context = request.app["request_context"]
    tag_filter = {}
    for param_name in (
        "connection_id",
        "thread_id",
        "initiator",
        "state",
        "verified"
    ):
        if param_name in request.query and request.query[param_name] != "":
            tag_filter[param_name] = request.query[param_name]
    records = await V10PresentationExchange.query(context, tag_filter)
    return web.json_response({"results": [record.serialize() for record in records]})

@docs(
    tags=["present-proof"],
    summary="Fetch a single presentation exchange record"
)
@response_schema(V10PresentationExchangeSchema(), 200)
async def presentation_exchange_retrieve(request: web.BaseRequest):
    """
    Request handler for fetching a single presentation exchange record.

    Args:
        request: aiohttp request object

    Returns:
        The presentation exchange record response

    """
    context = request.app["request_context"]
    presentation_exchange_id = request.match_info["pres_ex_id"]
    try:
        record = await V10PresentationExchange.retrieve_by_id(
            context,
            presentation_exchange_id
        )
    except StorageNotFoundError:
        raise web.HTTPNotFound()
    return web.json_response(record.serialize())

@docs(
    tags=["present-proof"],
    summary="Fetch credentials for a presentation request from wallet",
    parameters=[
        {
            "name": "start",
            "in": "query",
            "schema": {"type": "string"},
            "required": False,
        },
        {
            "name": "count",
            "in": "query",
            "schema": {"type": "string"},
            "required": False,
        },
        {
            "name": "extra_query",
            "in": "query",
            "schema": {"type": "string"},
            "required": False,
        },
    ]
)
async def presentation_exchange_credentials_list(request: web.BaseRequest):
    """
    Request handler for searching applicable credential records.

    Args:
        request: aiohttp request object

    Returns:
        The credential list response

    """
    context = request.app["request_context"]

    presentation_exchange_id = request.match_info["pres_ex_id"]
    presentation_referent = request.match_info.get("referent")

    try:
        presentation_exchange_record = await V10PresentationExchange.retrieve_by_id(
            context,
            presentation_exchange_id
        )
    except StorageNotFoundError:
        raise web.HTTPNotFound()

    start = request.query.get("start")
    count = request.query.get("count")

    # url encoded json extra_query
    encoded_extra_query = request.query.get("extra_query") or "{}"
    extra_query = json.loads(encoded_extra_query)

    # defaults
    start = int(start) if isinstance(start, str) else 0
    count = int(count) if isinstance(count, str) else 10

    holder: BaseHolder = await context.inject(BaseHolder)
    credentials = await holder.get_credentials_for_presentation_request_by_referent(
        presentation_exchange_record.presentation_request,
        (presentation_referent,) if presentation_referent else (),
        start,
        count,
        extra_query
    )

    presentation_exchange_record.log_state(
        context,
        "Retrieved presentation credentials",
        {
            "presentation_exchange_id": presentation_exchange_id,
            "referent": presentation_referent,
            "extra_query": extra_query,
            "credentials": credentials
        }
    )
    return web.json_response(credentials)

@docs(
    tags=["present-proof"],
    summary="Sends a presentation proposal"
)
@request_schema(V10PresentationProposalRequestSchema())
@response_schema(V10PresentationExchangeSchema(), 200)
async def presentation_exchange_send_proposal(request: web.BaseRequest):
    """
    Request handler for sending a presentation proposal.

    Args:
        request: aiohttp request object

    Returns:
        The presentation exchange details

    """
    context = request.app["request_context"]
    outbound_handler = request.app["outbound_message_router"]

    body = await request.json()

    connection_id = body.get("connection_id")
    try:
        connection_record = await ConnectionRecord.retrieve_by_id(
            context,
            connection_id
        )
    except StorageNotFoundError:
        raise web.HTTPBadRequest()

    if not connection_record.is_ready:
        raise web.HTTPForbidden()

    comment = body.get("comment")
    # Aries#0037 calls it a proposal in the proposal struct but it's of type preview
    presentation_preview = body.get("presentation_proposal")
    presentation_proposal_message = PresentationProposal(
        comment=comment,
        presentation_proposal=PresentationPreview.deserialize(presentation_preview)
    )
    auto_present = body.get(
        "auto_present",
        context.settings.get("debug.auto_respond_presentation_request")
    )

    presentation_manager = PresentationManager(context)

    presentation_exchange_record = (
        await presentation_manager.create_exchange_for_proposal(
            connection_id=connection_id,
            presentation_proposal_message=presentation_proposal_message,
            auto_present=auto_present
        )
    )
    await outbound_handler(presentation_proposal_message, connection_id=connection_id)

    return web.json_response(presentation_exchange_record.serialize())

@docs(
    tags=["present-proof"],
    summary="Sends a free presentation request not bound to any proposal"
)
@request_schema(V10PresentationRequestRequestSchema())
@response_schema(V10PresentationExchangeSchema(), 200)
async def presentation_exchange_send_free_request(request: web.BaseRequest):
    """
    Request handler for sending a presentation request free from any proposal.

    Args:
        request: aiohttp request object

    Returns:
        The presentation exchange details

    """
    context = request.app["request_context"]
    outbound_handler = request.app["outbound_message_router"]

    body = await request.json()

    connection_id = body.get("connection_id")
    try:
        connection_record = await ConnectionRecord.retrieve_by_id(
            context,
            connection_id
        )
    except StorageNotFoundError:
        raise web.HTTPBadRequest()

    if not connection_record.is_ready:
        raise web.HTTPForbidden()

    comment = body.get("comment")
    indy_proof_request = body.get("proof_request")
    if not indy_proof_request.get("nonce"):
        indy_proof_request["nonce"] = str(uuid4().int)

    presentation_request_message = PresentationRequest(
        comment=comment,
        request_presentations_attach=[
            AttachDecorator.from_indy_dict(indy_proof_request)
        ]
    )

    presentation_manager = PresentationManager(context)

    presentation_exchange_record = (
        await presentation_manager.create_exchange_for_request(
            connection_id=connection_id,
            presentation_request_message=presentation_request_message
        )
    )

    await outbound_handler(presentation_request_message, connection_id=connection_id)

    return web.json_response(presentation_exchange_record.serialize())

@docs(
    tags=["present-proof"],
    summary="Sends a presentation request in reference to a proposal"
)
@request_schema(V10PresentationRequestRequestSchema())
@response_schema(V10PresentationExchangeSchema(), 200)
async def presentation_exchange_send_bound_request(request: web.BaseRequest):
    """
    Request handler for sending a presentation request free from any proposal.

    Args:
        request: aiohttp request object

    Returns:
        The presentation exchange details

    """
    context = request.app["request_context"]
    outbound_handler = request.app["outbound_message_router"]

    presentation_exchange_id = request.match_info["pres_ex_id"]
    presentation_exchange_record = await V10PresentationExchange.retrieve_by_id(
        context,
        presentation_exchange_id
    )
    assert presentation_exchange_record.state == (
        V10PresentationExchange.STATE_PROPOSAL_RECEIVED
    )
    body = await request.json()

    connection_id = body.get("connection_id")
    try:
        connection_record = await ConnectionRecord.retrieve_by_id(
            context,
            connection_id
        )
    except StorageNotFoundError:
        raise web.HTTPBadRequest()

    if not connection_record.is_ready:
        raise web.HTTPForbidden()

    presentation_manager = PresentationManager(context)

    (
        presentation_exchange_record,
        presentation_request_message
    ) = await presentation_manager.create_bound_request(
        presentation_exchange_record
    )

    await outbound_handler(presentation_request_message, connection_id=connection_id)

    return web.json_response(presentation_exchange_record.serialize())

@docs(
    tags=["present-proof"],
    summary="Sends a proof presentation"
)
@request_schema(V10PresentationRequestSchema())
@response_schema(V10PresentationExchangeSchema())
async def presentation_exchange_send_presentation(request: web.BaseRequest):
    """
    Request handler for sending a presentation.

    Args:
        request: aiohttp request object

    Returns:
        The presentation exchange details

    """

    context = request.app["request_context"]
    outbound_handler = request.app["outbound_message_router"]
    presentation_exchange_id = request.match_info["pres_ex_id"]
    presentation_exchange_record = await V10PresentationExchange.retrieve_by_id(
        context, presentation_exchange_id
    )

    body = await request.json()

    connection_id = presentation_exchange_record.connection_id
    try:
        connection_record = await ConnectionRecord.retrieve_by_id(
            context,
            connection_id
        )
    except StorageNotFoundError:
        raise web.HTTPBadRequest()

    if not connection_record.is_ready:
        raise web.HTTPForbidden()

    assert (
        presentation_exchange_record.state
    ) == V10PresentationExchange.STATE_REQUEST_RECEIVED

    presentation_manager = PresentationManager(context)

    (
        presentation_exchange_record,
        presentation_message,
    ) = await presentation_manager.create_presentation(
        presentation_exchange_record,
        {
            "self_attested_attributes": body.get("self_attested_attributes"),
            "requested_attributes": body.get("requested_attributes"),
            "requested_predicates": body.get("requested_predicates")
        },
        comment=body.get("comment")
    )

    await outbound_handler(presentation_message, connection_id=connection_id)
    return web.json_response(presentation_exchange_record.serialize())

@docs(
    tags=["present-proof"],
    summary="Verify a received presentation"
)
@response_schema(V10PresentationExchangeSchema())
async def presentation_exchange_verify_presentation(
    request: web.BaseRequest
):
    """
    Request handler for verifying a presentation request.

    Args:
        request: aiohttp request object

    Returns:
        The presentation exchange details

    """
    context = request.app["request_context"]
    presentation_exchange_id = request.match_info["pres_ex_id"]

    presentation_exchange_record = await V10PresentationExchange.retrieve_by_id(
        context,
        presentation_exchange_id
    )
    connection_id = presentation_exchange_record.connection_id

    try:
        connection_record = await ConnectionRecord.retrieve_by_id(
            context,
            connection_id
        )
    except StorageNotFoundError:
        raise web.HTTPBadRequest()

    if not connection_record.is_ready:
        raise web.HTTPForbidden()

    assert (
        presentation_exchange_record.state
    ) == V10PresentationExchange.STATE_PRESENTATION_RECEIVED

    presentation_manager = PresentationManager(context)

    presentation_exchange_record = await presentation_manager.verify_presentation(
        presentation_exchange_record
    )

    return web.json_response(presentation_exchange_record.serialize())

@docs(
    tags=["present-proof"],
    summary="Remove an existing presentation exchange record",
)
async def presentation_exchange_remove(request: web.BaseRequest):
    """
    Request handler for removing a presentation exchange record.

    Args:
        request: aiohttp request object

    """
    context = request.app["request_context"]
    presentation_exchange_id = request.match_info["pres_ex_id"]
    try:
        presentation_exchange_record = await V10PresentationExchange.retrieve_by_id(
            context,
            presentation_exchange_id
        )
    except StorageNotFoundError:
        raise web.HTTPNotFound()

    await presentation_exchange_record.delete_record(context)
    return web.json_response({})

async def register(app: web.Application):
    """Register routes."""

    app.add_routes(
        [
            web.get(
                "/present-proof/records",
                presentation_exchange_list
            ),
            web.get(
                "/present-proof/records/{pres_ex_id}",
                presentation_exchange_retrieve
            ),
            web.get(
                "/present-proof/records/{pres_ex_id}/credentials",
                presentation_exchange_credentials_list,
            ),
            web.get(
                "/present-proof/records/{pres_ex_id}/credentials/{referent}",
                presentation_exchange_credentials_list,
            ),
            web.post(
                "/present-proof/send-proposal",
                presentation_exchange_send_proposal,
            ),
            web.post(
                "/present-proof/send-request",
                presentation_exchange_send_free_request,
            ),
            web.post(
                "/present-proof/records/{pres_ex_id}/send-request",
                presentation_exchange_send_bound_request,
            ),
            web.post(
                "/present-proof/records/{pres_ex_id}/send-presentation",
                presentation_exchange_send_presentation,
            ),
            web.post(
                "/present-proof/records/{pres_ex_id}/verify-presentation",
                presentation_exchange_verify_presentation,
            ),
            web.post(
                "/present-proof/records/{pres_ex_id}/remove",
                presentation_exchange_remove
            ),
        ]
    )


from django import forms
from django.contrib.admin.widgets import AdminDateWidget    #インポート
from .models import Tasks,Projects

class AddTaskForm(forms.ModelForm):
    """タスク追加フォーム"""
    class Meta:
        model = Tasks
        fields = ('project','taskName','status','createdDate','deadline','priority',)

        widgets = {
            'createdDate': AdminDateWidget(),    #インポートしたウィジェットを使う指示
            'deadline': AdminDateWidget(),
        }

class AddProjectForm(forms.ModelForm):
    """タスク追加フォーム"""
    class Meta:
        model = Projects
        fields = ('Name','color',)

        widgets = {

        }


from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
from keras.utils.vis_utils import plot_model
from matplotlib import pyplot as plt
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix
import random
from pickle import dump

n = 132395
n_train = 92677
n_val = 11915

dataSet = loadtxt('AppDDoS.csv', delimiter=',');
random.shuffle(dataSet)
X = dataSet[:, 0:39]
singleY = dataSet[:,43]

i = 0
listY = []
for val in singleY:
	listY.append([0])
	if (val > 0) :
		listY[i][0] = 1
	i += 1

Y = np.array(listY)

trainX, testX = X[:n_train], X[n_train:]
trainY, testY = Y[:n_train], Y[n_train:]

valX = testX[:n_val]
valY = testY[:n_val]
testX = testX[n_val:]
testY = testY[n_val:]

scaler = MinMaxScaler()
scaler.fit(X)

normalizedTrain = scaler.transform(trainX)
normalizedTest = scaler.transform(testX)
normalizedVal = scaler.transform(valX)

model = Sequential()
model.add(Dense(32, input_dim=trainX.shape[1], activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(8, activation='relu'))
#model.add(Dense(8, activation='relu'))
#model.add(Dense(10, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

history = model.fit(
	normalizedTrain,
	trainY,
	epochs=100,
	 batch_size=32,
	 validation_data=(normalizedVal, valY))

#print(model.summary())
#plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
print(history.history.keys())
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

_, accuracy = model.evaluate(normalizedTest, testY)
predictions = model.predict(normalizedTest)

print(predictions[0])

y_pred = predictions > 0.5

#matrix = confusion_matrix(testY.argmax(axis=1), y_pred.argmax(axis=1))
matrix = confusion_matrix(testY, y_pred)

print(matrix)
print('Accuracy: %.2f' % (accuracy*100))

model.save('model.h5')
dump(scaler, open('scaler.pkl', 'wb'))


def is_anagram(s1, s2):
    s1 = sorted(s1)
    s2 = sorted(s2)
    for i in range(len(s1)):
        if s1[i] != s2[i]:
            return False
    return True

def is_anagram_hash(s1 ,s2, ):
    h = dict()
    for s in s1:
        if s in h:
            h[s] += 1
        else:
            h[s] = 1
    for s in s2:
        if s in h:
            h[s] -= 1
            if h[s] < 0:
                return False
        else:
            return False
    for _, value in h.items():
        if value != 0:
            return False
    return True

def is_anagram_26(s1 ,s2, numbers):
    for i in range(len(s1)):
        numbers[ord(s1[i]) - 97] += 1
        numbers[ord(s2[i]) - 97] -= 1
    for i in range(26):
        if numbers[i] != 0:
            return False
    return True

def sherlockAndAnagrams(s):
    n = len(s)
    anagrams = []
    numbers = [0]*26
    for w in range(1, n):
        for i in range(0, n-w+1):
            for j in range(i+1, n-w+1):
                if is_anagram_26(s[i:(i+w)], s[j:(j+w)], numbers):
                    anagrams.append((s[i:(i+w)], s[j:(j+w)]) )
                else:
                    for k in range(26):
                        numbers[k] = 0
    return anagrams

if __name__ == "__main__":
    s = 'abba'
    s = 'kkkk'
    s = 'ifailuhkqq'

    anangrams = sherlockAndAnagrams(s)
    print(' number of anagram: {}'.format(len(anangrams)))
    for anagram in anangrams:
        print(anagram)


from django.urls import path
from . import views as blog_views
app_name = 'blog'
urlpatterns = [
    path('', blog_views.IndexView.as_view(), name='index'),
    path(
        'p/<int:article_id>',
        blog_views.ArticleDetailView.as_view(),
        name='detail'),
]


import socket

def main():
    # 1 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 2 绑定本地信息
    tcp_server_socket.bind(('', 7788))

    # 3 让默认的套接字由主动变为被动 listen
    tcp_server_socket.listen(128)

    while True:
        # 4 等待客户端的连接 accept
        print('等待新的客户端连接...')
        client_socket, client_ip = tcp_server_socket.accept()
        print('客户端的ip:', client_ip)

        while True:
            # 接收客户端发送过来的请求
            receice_content = client_socket.recv(1024)
            print(receice_content.decode('gbk'))

            # 回复客户端
            # 如果recv解堵塞有2种情况
            # 1 客户端发送数据过来
            # 2 客户端调用close导致关闭
            if receice_content:
                client_socket.send('已收到消息'.encode('utf-8'))
            else:
                client_socket.send('断开连接'.encode('utf-8'))
                break

        # 关闭套接字
        client_socket.close()

    tcp_server_socket.close()

if __name__ == '__main__':
    main()


import warnings
import os
from .config import BasicConfig
class DefaultConfig(BasicConfig):
    model_root = '/data/fyl/models_pytorch'
    model = 'EnsembleNet_Paramwise'
    model_setup = {'pretrained': True}
    connection_mode = 'singleline'
    env = model + '_oa_lidc3s_classification_pretrained_adam_rfold1|10'
    Devices_ID = '6'

    dataset = 'Pathology_Slicewise_Dataset'
    label_mode = 'binclass'
    patch_mode = 'oa'
    root_dir = '/data/fyl/data_samples/lidc_3slices'
    #root_dir = model_root + "/BasicNet_lidc_classification_9/filelist_train_fold[0, 1, 2, 3, 4].log"
    patientlist = '/data/fyl/models_pytorch/BaseweightSharedBNNet_classification_pretrained_adam_rfold8|10/patientlist.log'
    filelist_shuffle = False
    num_cross_folds = 10
    val_fold = 1
    test_fold = -1
    remove_uncertain = True
    filelists = dict(
        #train = model_root + '/BasicNet_classification_lidc_test_rfold1/filelist_train_fold[1, 2, 3, 4].log',
        #val = model_root + '/BasicNet_classification_lidc_test_rfold1/filelist_val_fold0.log',
        test = model_root + '/EnsembleNet_Paramwise_oa_lidc3s_classification_pretrained_adam_rfold1|10/filelist_val_fold0.log'
    )

    #load_model_path = None
    #load_model_path = model_root + "/ParamResNet50_lidc_classification_pretrained_rfold1|10/ParamResNet50_lidc_classification_pretrained_rfold1|10_epoch22"
    #load_model_path = model_root + '/BasicNet_lidc_classification_9/BasicNet_lidc_classification_9_epoch500'
    #load_model_path = model_root + '/BasicNet_classification_lidc_transfer_rfold5/BasicNet_classification_lidc_transfer_rfold5_epoch1330'
    #load_model_path = model_root + '/EnsembleNet_Paramwise_lidc_classification_adam_rfold1|10/EnsembleNet_Paramwise_lidc_classification_adam_rfold1|10_epoch10'
    #load_model_path = model_root + "/DenseNet_Iterative_trand_fold1/DenseNet_Iterative_trand_fold1_epoch101"
    #load_model_path = model_root + "/ParamDenseCropNet_classification_fold4|5/ParamDenseCropNet_classification_fold4|5_epoch146"
    inference_setup = {'model_name': 'EnsembleNet_Paramwise_oa_lidc3s_classification_pretrained_adam_rfold1|10', 'epochs': [2, 3, 18, 19, 27, 35, 46]}
    use_gpu = True

    input_size = 200
    batch_size = 10
    print_freq = 50
    save_freq = 1

    data_preprocess = dict(
        translation_num = 1,
        translation_range = (-10, 10),
        rotation_num = 3,
        flip_num = 2,
	shear_num = 0,
        noise_range = (0, 0)
    )

    #drop_rate = 0
    weight_decay = 0
    loss_exp = 0
    balancing = (0.5, 0.5)

    max_epoch = 50
    lr = 5e-6

'''
further improvements:
1) randomly augment differently among 3 input channels;
2) add drop out, weight decay, or balancing factor;
3) further read implementation details from the original paper.
'''


from dataoutput.write_timetables import writingTimetables
from .schulmodell import createModel
from loguru import logger as loguru_logger

# from .schulmodell import Datenbankzugriff
import pyomo.environ as pyo

# from pyomo.environ import
import os

# Aus schulmodell.py
from pyomo.environ import *
import cProfile
import time
import datetime

# import von Django Model Klassen
from datainput.models import (
    Raum,
    Lehrer,
    Schulklasse,
    Schulfach,
    Lehrfaecher,
    Unterrricht,
    Tag,
    Stunde,
    Slot,
    Partner,
    LehrerBelegt,
    RaumBelegt,
    VorgabeEinheit,
    Uebergreifung,
    LehrerBelegt,
    StundenzahlproTag,
)
from optimierung.models import Parameters

"""
Hier wird das Optimierungsmodell an den jeweils ausgewählten Solver weitergegeben.
"""
"""Aktuell wird nur künstlich ein Run kreiert und eine bereits vorbereitete Resultdatei ausgewertet.
Später muss das Ergebnis CSV Dateiblatt im Optimierung ordner gespeichert werden. Dann kann get getTimetableUnits seine Arbeit richtig machen
"""

def doeverything():

    """ Senden an den solver und festlegen des Ouputorts
    Supported Solvers: CBC, Gurobi, Cplex
    all solvers with pyomo help --solvers
    """

    # check if file exists, then delete it if so
    if os.path.exists("./X_res.csv"):
        os.remove("./X_res.csv")

    loguru_logger.info("START: create model")
    # import solver and solve model, wirte documentation and load results
    model = createModel()
    loguru_logger.info("END: create model")
    # model.pprint('model-debug.txt')
    # see https://github.com/PyUtilib/pyutilib/issues/31#issuecomment-382479024
    import pyutilib.subprocess.GlobalData

    pyutilib.subprocess.GlobalData.DEFINE_SIGNAL_HANDLERS_DEFAULT = False
    # opt = pyo.SolverFactory('glpk', executable='/usr/local/bin/glpsol')
    loguru_logger.info("initialize solver")
    opt = pyo.SolverFactory("gurobi")
    # instance = model.create_instance()
    loguru_logger.info("START: solve model")
    # solve the model with a mip gap of 2%
    results = opt.solve(model, options=dict(mipgap=0.07), tee=True)
    loguru_logger.info("END: solve model")
    results.write()
    loguru_logger.info(f"SOLVER STATUS: {str(results.solver.status)}")

    loguru_logger.info("Write model file")
    model.write("model.lp", io_options={"symbolic_solver_labels": True})

    print("optimierung done")

    if (results.solver.status == SolverStatus.ok) and (
        results.solver.termination_condition == TerminationCondition.optimal
    ):
        loguru_logger.info("write results file")
        #model.display("results.txt")
        loguru_logger.info("START: write x values")
        with open("./X_res.csv", "w") as file:
            file.write("Klasse, Lehrer, Fach, Slot, Var\n")
            for (k, l, f, s) in model.Variablenmenge:
                if pyo.value(model.x[k, l, f, s] > 0.1):
                    file.write(f"{k},{l},{f},{s},{pyo.value(model.x[k, l, f, s])}\n")
        loguru_logger.info("END: write x values")
        loguru_logger.info("Transfer solution to timetables")
        """Benutze kreiertes Ergebnis, um Lehreinheiten zu erstellen"""
        writingTimetables.getTimetableUnits()
    elif results.solver.termination_condition == TerminationCondition.infeasible:
        loguru_logger.warning("Solver status is infeasible!")
    else:
        loguru_logger.warning(
            "Solver status is not optimal and not infeasible (possibly unbounded)!"
        )


from flask import Flask, render_template, request, redirect, session, flash, url_for
# import the Connector function
from mysqlconnection import MySQLConnector
import re
# was unable to create a single regex expression for name.  Need to work more on regex
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$')

app = Flask(__name__)
app.secret_key = 'supersecret'
# connect and store the connection in "mysql" note that you pass the database name to the function
mysql = MySQLConnector(app, 'emaildb')
# an example of running a query

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

@app.route('/update', methods=['POST'])
def update():
    query = "SELECT email FROM emails"                           # define your query
    emails = mysql.query_db(query)
    errors = False
    if len(request.form['email']) < 1:
        errors = True
        flash("e-mail address is empty. Enter e-mail.")
    elif not EMAIL_REGEX.match(request.form['email']):
        errors = True
        flash("Invalid e-mail address. Enter e-mail.")
    elif {'email' : request.form['email']} in emails:
        errors = True
        flash("The e-mail address entered already exists in the database.")
    if errors:
        return redirect('/')
    else:
        session['insert'] = 1
        query = "INSERT INTO emails (email, created_at, updated_at) VALUES (:email, NOW(), NOW())"
        data = {'email': request.form['email']}
        mysql.query_db(query, data)
        return redirect('/success')

@app.route('/success')
def email_list():
    query = "SELECT * FROM emails"                           # define your query
    emails = mysql.query_db(query)                           # run query with query_db()
    return render_template('email_list.html', list_emails=emails, insert = session['insert']) # pass data to our template

@app.route('/remove', methods=['POST'])
def remove():
    session['insert'] = 0
    errors = False
    if len(request.form['email']) < 1:
        errors = True
        flash("e-mail address field is empty. Enter e-mail to remove and re-submit.")
    elif not EMAIL_REGEX.match(request.form['email']):
        errors = True
        flash("Invalid e-mail address. Enter e-mail.")
    else:
        query = "SELECT email FROM emails"                           # define your query
        emails = mysql.query_db(query)
        if not {'email' : request.form['email']} in emails:
            errors = True
            flash("The e-mail address entered was not found in the database.")
    if errors:
        return redirect('/success')
    else:
        query = "DELETE FROM emails WHERE email = :email"
        data = {'email': request.form['email']}
        mysql.query_db(query, data)
        return redirect('/success')

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


# -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 18:12:31 2015

@author: Robert
"""

"""
Ce code permet de calculer la correction à l'énergie d'un niveau électronique donné (pour un réseau 2D),
en écrivant les intégrales I_2D(l1,p1) en coordonnées sphériques et en tirant les variables radiales
selon des lois gaussiennes et les variables angulaires uniformément.
L'invariance par translation dans la somme a été prise en compte.
"""

get_ipython().magic(u'pylab inline')
import numpy
import scipy
import math
from math import *
import random
import time

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

e2=2.3*math.pow(10,-28)
N=30
E0=13
t0=0.5
t=2
a=math.pow(10,-10)

l2=0
p2=0

#d : inférieur ou égal à a/4. pour une gaussienne (ainsi 1 % de recouvrement des gaussiennes
# de 2 orbitales atomiques localisée voisines en a/2)
d=a/4.
#Tester d'autres d ??

#Nombre d'ELECTRONS mis dans le système
#On remplit les états de façon non magnétique : en partant de l'état fondamental ;
#2 électrons (spins up et down) par état

#Si le nombre d'électrons est impair, on a forcément un état d'énergie avec un électron
#uniquement et donc un seul spin représenté. La correction calculée sera polarisée en spin.

#Nombre de valeurs de k_x occupées
alpha1=5
#Nombre de valeurs de k_y occupées
alpha2=10

NB=alpha1*alpha2
#NB maximal : 2*(N^2)

#Demi-remplissage : NB=N
#(N niveaux en tout ; 2 électrons par niveaux : donc 2N électrons au total au maximum)

k_x=[(-(2*pi/(N*a))*floor(N/2.)+i*(2*pi/(N*a))) for i in range(0,N)]

k_y=[(-(2*pi/(N*a))*floor(N/2.)+i*(2*pi/(N*a))) for i in range(0,N)]

def distance_reseau_2D(x,y,z,x1,y1,z1):
    #§Minimum entre 4 éléments
    var1=sqrt((x-(x1-N*a))**2+(y-y1)**2+(z-z1)**2)
    var2=sqrt((x-x1)**2+(y-(y1-N*a))**2+(z-z1)**2)
    var3=sqrt((x-(x1-N*a))**2+(y-(y1-N*a))**2+(z-z1)**2)
    return min(var1,var2,var3,sqrt((x-x1)**2+(y-y1)**2+(z-z1)**2))

def terme_facteur_phase(n_x,n_y,l1,p1):
    res=0

    for j_x in range(alpha1):
        for j_y in range(alpha2):
            if ((N-alpha1)/2+j_x!=n_x) or ((N-alpha2)/2+j_y!=n_y):

                res+= -cos((k_x[n_x]-k_x[(N-alpha1)/2+j_x])*(l1-l2)*a+(k_y[n_y]-k_y[(N-alpha2)/2+j_y])*(p1-p2)*a)

    if (n_x >= (N-alpha1)/2) and (n_x < (N+alpha1)/2) and (n_y >= (N-alpha2)/2) and (n_y < (N+alpha2)/2):
        return NB-1+res
    else:
        #(k_n_x,k_n_y) n'est pas un état occupé
        return NB+res

    #return res
    #Effet du terme de Fock seul

def F(l1,p1,r1,r2,theta1,theta2,phi1,phi2):
    #return (pi**2)*(2*pi)**2*(pi*(d/a)**2/2)*r1**2*r2**2*sin(theta1)*sin(theta2)/sqrt(r1**2+r2**2-2*r1*r2*(sin(theta1)*sin(theta2)*cos(phi1-phi2)+cos(theta1)*cos(theta2))+2*l1*(r2*sin(theta2)*cos(phi2)-r1*cos(phi1)*sin(theta1))+l1**2+2*p1*(r1*sin(theta1)*sin(phi1)-r2*sin(theta2)*sin(phi2))+p1**2)
    return r1**2*r2**2*sin(theta1)*sin(theta2)/distance_reseau_2D(r1*sin(theta1)*cos(phi1)-l1,r1*sin(theta1)*sin(phi1)-p1,r1*cos(phi1),r2*sin(theta2)*cos(phi2),r2*sin(theta2)*sin(phi2),r2*cos(phi2))
#Facteur exp(-2*r1**2/(d/a)**2)*exp(-2*r1**2/(d/a)**2) dans l'intégrande : contenu dans
#le tirage de r1 et r2 selon des gaussiennes
#Premier facteur : facteur de renormalisation de la densité de la gaussienne

nb=1000.

"""
r1_0=0.
r2_0=0.
theta1_0=0.
theta2_0=0.
phi1_0=0.
phi2_0=0.
"""

def I_2D(l1,p1):

    Y=[0 for i in range(6)]
    res=0

    for i in range(999):
        #Tirage d'un (i+1)ème uplet de variables aléatoires

        Y[0]=numpy.random.normal(0,(d/a)/2.)
        Y[1]=numpy.random.normal(0,(d/a)/2.)
        Y[2]=random.uniform(0,pi)
        Y[3]=random.uniform(0,pi)
        Y[4]=random.uniform(0,2*pi)
        Y[5]=random.uniform(0,2*pi)

        res+= F(l1,p1,Y[0],Y[1],Y[2],Y[3],Y[4],Y[5])

    return (pi**2/d)*(a/d)**3*(res/nb)
#Facteur K**4 * a**5 (où K est la partie angulaire de l'orbitale atomique)

"""
n=N/2
tab=[0 for i in range(N)]
for m_1 in range(N):
    tab[m_1]=I_1D_Metropolis(m_1)*terme_facteur_phase(n,m_1)
    #print("I_1D({0}) : {1} ".format(m_1,I_1D_Metropolis(m_1)))
    #print("Delta({2},{0}) : {1} ".format(m_1,terme_facteur_phase(n,m_1),n))
    print("I_1D({0})*Delta({2},{0}) : {1} ".format(m_1,I_1D_Metropolis(m_1)*terme_facteur_phase(n,m_1),n))

M=[i for i in range(N)]
plot(M,tab)
"""

"""
#Avec cette méthode, on recalcule pour chaque m
#I_1D(m) avec nb tirages du 6-uplet (rho1,rho2,theta1,theta2,phi1,phi2)
def Delta_Hartree_Fock(n_x,n_y):
    res2=0
    tab_I_2D=[[0 for i in range(N)] for j in range(N)]

    for l1 in range(N):
        for p1 in range(N):
            tab_I_2D[l1][p1]=I_2D(l1,p1)*terme_facteur_phase(n_x,n_y,l1,p1)
            res2+= tab_I_2D[l1][p1]
        #Le calcul de I_1D(m) nécessite à chaque m nb tirages...

    #abscisses_m=[i for i in range(N)]
    #plot(abscisses_m,tab_I_1D)
    return (e2/N**2)*res2

#print(Delta_Hartree_Fock(2))

nb_tirages=10000.

#Avec cette méthode, on évalue pour chaque tirage la valeur de l'intégrande de I_1D
#pour chaque m.
#Rajouter variable de spin en argument ?
def Delta_Hartree_Fock_bis(n_x,n_y):
    res=[[0 for i in range(N)] for j in range(N)]

    Y=[0 for i in range(6)]

    for i in range(9999):
        #Tirage d'un (i+1)ème uplet de variables aléatoires
        Y[0]=numpy.random.normal(0,(d/a)/sqrt(2.))
        Y[1]=numpy.random.normal(0,(d/a)/sqrt(2.))
        Y[2]=random.uniform(0,pi)
        Y[3]=random.uniform(0,pi)
        Y[4]=random.uniform(-pi,pi)
        Y[5]=random.uniform(-pi,pi)

        #tab=[0 for i in range(N)]

        for l1 in range(N):
            for p1 in range(N):
                res[l1][p1] += F(l1,p1,Y[0],Y[1],Y[2],Y[3],Y[4],Y[5])
                #tab[m] = F(m,p1,Y[0],Y[1],Y[2],Y[3],Y[4],Y[5])

        #Vérification que à p1 fixé, pour un tirage des variables donné, l1 -> F(l1,p1,Y[0],Y[1],Y[2],Y[3],Y[4],Y[5]) évolue bien en 1/|l1|
        #abscisses_m=[i for i in range(10)]
        #print(Y)
        #print(F(1,1,Y[0],Y[1],Y[2],Y[3],Y[4],Y[5]))
        #plot(abscisses_m,tab[0:10])

    I_2D_estime=[[0 for i in range(N)] for j in range(N)]

    for l1 in range(N):
            for p1 in range(N):
                I_2D_estime[l1][p1]=res[l1][p1]/nb_tirages

    resultat_correction_energie=0
    for l_1 in range(N):
        for p_1 in range(N):
            resultat_correction_energie += I_2D_estime[l1][p1]*terme_facteur_phase(n_x,n_y,l_1,p_1)

    return (e2/N**2)*resultat_correction_energie
"""

"""
n=5

#Estimation de l'écart type pour un nombre de tirages donné

#Nombre de calculs de la correction (=nb de fois que l'on a simulé une chaîne de Markov)
p=10.

#Estimateur de la moyenne
mu=0.

#Somme des réalisations
sum=0.

#Estimteur de la moyenne du carré
m=0.

#Somme des carrés des réalisations
sum2=0.

#Estimateur de l'écart type
sigma=0.

for i in range(10):

    tps1=time.clock()
    var =Delta_Hartree_Fock_bis(n)
    tps2=time.clock()
    sum +=var
    sum2+=var**2
    print("Delta_Hartree_Fock_bis({0}) : {1}  Temps calcul : {2} ".format(n,var,tps2-tps1))

mu=sum/p
m=sum2/p
sigma=sqrt(m-mu**2)
print("Ecart-type : {0}  Moyenne : {1}".format(sigma,mu))
print("Pourcentage : {0} %".format(100*sigma/mu))
"""

"""
tab=[[0 for i in range(N)] for j in range(N)]
for m in range(N):
    for q in range(N):
        tab[m][q]=Delta_Hartree_Fock_bis(m,q)
        print("Delta_Fock_w_s_i_(k_x[{0}]={1},k_y[{2}]={3}) : {4} ".format(m,k_x[m],q,k_y[q],tab[m][q]))
"""

#numpy.savetxt('Correction_energie_2D_bis.txt',tab,newline='\n')

valeurs_I_2D=[[0 for i in range(N)] for j in range(N)]
#On calcule les valeurs de I_1D une fois pour toutes (en faisant beaucoup de tirages pour un m donné et ainsi avoir peu d'incertitudes)
#(elles sont indépendantes de n ; n n'intervient que dans le facteur de phase)
for l1 in range(N):
    for p1 in range(N):
        valeurs_I_2D[l1][p1]=I_2D(l1,p1)

#print(valeurs_I_2D)

null=linspace(0.,0.,N)
correction_energie=np.outer(null,np.ones(np.size(null)))

for n_x in range(N):
    for n_y in range(N):
        #tps1=time.clock()

        res=0
        for l1 in range(N):
            for p1 in range(N):
                #print("terme_facteur_phase({0},{1}) = {2}".format(v,u,terme_facteur_phase(v,u)))
                res+= valeurs_I_2D[l1][p1]*terme_facteur_phase(n_x,n_y,l1,p1)

        correction_energie[n_x][n_y]=(1/(1.6*math.pow(10,-19)))*(e2/N**2)*res

        #tps2=time.clock()
        #print("Delta_Hartree_Fock({0},{1})= {2}  Temps calcul : {3}".format(n_x,n_y,correction_energie[n_x][n_y],tps2-tps1))

#Graphe en 3D de la correction de l'énergie par le terme de Hartree Fock
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') #Créaton d'axes 3D

#plt.show()

k_x_1=np.outer(k_x,np.ones(np.size(k_x)))

k_y_1=np.outer(np.ones(np.size(k_y)),k_y)

energie_2D_corrigee=[[(E0-t0-2*t*(cos(k_x[i]*a)+cos(k_y[j]*a))+correction_energie[i][j]) for i in range(N)] for j in range(N)]
#energie_corrigee=[[(energie_2D[i][j],correction_energie[i][j]) for i in range(N)] for j in range(N)]
#energie_corrigee=[[(energie_2D[i][j]+correction_energie[i][j]) for i in range(N)] for j in range(N)]

ax.plot_surface(k_x_1, k_y_1,correction_energie,rstride=1, cstride=1, cmap=plt.cm.coolwarm, linewidth=0.05, antialiased=True,alpha=1)
#ax.view_init(elev=10,azim=0)
#La fonction plot_surface trace à partir de 3 matrices A, B et C, l'ensemble des points
#de coordonnées (A[i][j], B[i][j], C[i][j]) et les relie pour former une surface.
plt.title("Correction given by the Hartree-Fock term for the 2D lattice,  in eV", fontsize=10)
ylabel("kx (m^(-1))")
xlabel("ky (m^(-1))")
plt.show()
plt.hold()
#ax.contour(k_x_1, k_y_1, energie_corrigee,zdir='z')

#ax.set_zlim(E0-t0-4*t, E0-t0+4*t)

ax.zaxis.set_major_locator(plt.LinearLocator(10))
ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.02f'))

X,Y= meshgrid(k_x,k_y)
pcolor(X,Y,correction_energie)
xlabel("kx (m^(-1))")
ylabel("ky (m^(-1))")
show()

#fig.colorbar(surf, shrink=0.5, aspect=10)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') #Créaton d'axes 3D

ax.plot_surface(k_x_1, k_y_1,energie_2D_corrigee,rstride=1, cstride=1, cmap=plt.cm.coolwarm, linewidth=0.05, antialiased=True,alpha=1)
plt.title("Energy corrected by the Hartree-Fock term for the 2D lattice (eV)", fontsize=10)
xlabel("kx (m^(-1))")
ylabel("ky (m^(-1))")
#ax.view_init(elev=10,azim=40)

plt.show()
plt.hold()

"""
X,Y= meshgrid(k_x,k_y)
pcolor(X,Y,energie_2D)
show()
"""


import time
import xbmc
import json
import xbmcgui
import xbmcaddon

import struct
import select
import os

def log(txt):
    message = '%s: %s' % ("service.rotdev", txt.encode('ascii', 'ignore'))
    xbmc.log(msg=message, level=xbmc.LOGINFO)

def getVolume():
    curVol = -1
    resp = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Application.GetProperties", "params": { "properties": [ "volume"] }, "id": 1}')
    dct = json.loads(resp)
    if ("result" in dct and "volume" in dct["result"]):
        curVol = dct["result"]["volume"]
    return curVol

def getInputDevice():
    dev = -1
    for fn in os.listdir('/sys/class/input/'):
        if fn.startswith('event'):
            with open('/sys/class/input/' + fn + '/device/name') as f:
                if f.readline(8).startswith('rotary'):
                    dev = int(fn[5:])
                    break
    return dev

class Rotary:
    def __init__(self):
        self._vol = None
        self._device = None

    def __rotate(self, direction):
        vol = getVolume()
        if(direction == -1 and vol > 0):
            xbmc.executebuiltin("SetVolume({}, showVolumeBar)".format(vol-self._vol))
        elif(direction == 1 and vol < 100):
            xbmc.executebuiltin("SetVolume({}, showVolumeBar)".format(vol+self._vol))

    def setup(self):
        log("setup")
        self.stop()

        dev = getInputDevice()
        if dev == -1:
            log("No rotary device found")
            return

        _evdev = "/dev/input/event" + str(dev)

        _this = xbmcaddon.Addon()
        self._vol = int(_this.getSetting("vol_step"))

        log("config: %s %i" % (_evdev, self._vol))
        self._device = open(_evdev, "rb")

    def stop(self):
        log("stop")
        if self._device:
            self._device.close()
            self._device = None

    def read(self):
        if self._device:
            rrdy, wrdy, xrdy = select.select([self._device], [], [], 5);
            if rrdy:
                data = self._device.read(16)
                tmp = struct.unpack('2IHHi',data)
                if tmp[2] == 2:
                    self.__rotate(tmp[4])

class MyMonitor(xbmc.Monitor):
    def __init__(self, rotary):
        xbmc.Monitor.__init__(self)
        self.rotary = rotary

    def onSettingsChanged(self):
        log("onSettingsChanged")
        self.rotary.stop()
        self.rotary.setup()

if __name__ == '__main__':
    rot = Rotary()
    monitor = MyMonitor(rot)
    rot.setup()

    while not monitor.abortRequested():
        rot.read()

    rot.stop()


from flask import request, make_response, jsonify
from werkzeug.exceptions import NotFound

from datetime import datetime
from ....data import Data

class ProductModel():
    """This class encapsulates the functions of the product model"""

    def __init__(self, name, stock, min_q, category, product_id=0):
        """initialize the question model"""
        self.name = name
        self.stock = stock
        self.min_q = min_q
        self.date_created = datetime.now()
        self.category = category
        self.product_id = product_id

    def save_product(self):
        product_id = len(Data.products) + 1
        product = {
            "product_id": product_id,
            "name": self.name,
            "min_q": self.min_q,
            "category": self.category,
            "stock": self.stock,
            "date_created": self.date_created

        }
        #save the product to the products list
        Data.products.append(product)

    @staticmethod
    def edit_product(product_id, name, stock, category, min_q):
        """method to Edit Product details"""

        update_prd = [
            prod for prod in Data.products if prod['product_id'] == product_id]

        if update_prd:
            print(update_prd)
            update_prd[0]['name'] = name
            update_prd[0]['stock'] = stock
            update_prd[0]['category'] = category
            update_prd[0]['min_q'] = min_q
            return update_prd
        raise NotFound('Product Not Found')

    @staticmethod
    def delete_product(product_id):
        """Class method to delete products from inventory"""

        deleted_prd = [
            prod for prod in Data.products if prod['product_id'] == product_id]
        if deleted_prd:
            Data.products.remove(deleted_prd[0])
            return deleted_prd
        raise NotFound('Product Not Found')


from typing import TYPE_CHECKING, cast, Optional
from inspect import isclass

from ..config import config
from .stub import BaseStub, ArgsStub, SubcommandStub, OptionStub, Subcommand, Option

if TYPE_CHECKING:
    from ..core import Alconna
    from ..arpamar import Arpamar

class Duplication:
    """
    用以更方便的检查、调用解析结果的类。
    """
    __target: 'Arpamar'

    @property
    def origin(self) -> "Arpamar":
        return self.__target

    @property
    def header(self):
        return self.__target.header

    def set_target(self, target: 'Arpamar'):
        self.__target = target
        if self.__stubs__.get("main_args"):
            getattr(self, self.__stubs__["main_args"]).set_result(target.main_args)  # type: ignore
        for key in self.__stubs__["options"]:
            if key in target.options:
                getattr(self, key).set_result(target._options[key])  # noqa
        for key in self.__stubs__["subcommands"]:
            if key in target.subcommands:
                getattr(self, key).set_result(target._subcommands[key])  # noqa
        for key in target.all_matched_args:
            if key in self.__stubs__['other_args']:
                setattr(self, key, target.all_matched_args[key])
        if isinstance(target.header, dict):
            for key in target.header:
                if key in self.__stubs__['other_args']:
                    setattr(self, key, target.header[key])
        return self

    def __init__(self, alconna: 'Alconna'):
        self.__stubs__ = {"options": [], "subcommands": [], "other_args": []}
        for key, value in self.__annotations__.items():
            if isclass(value) and issubclass(value, BaseStub):
                if value == ArgsStub:
                    setattr(self, key, ArgsStub(alconna.args))
                    self.__stubs__["main_args"] = key  # type: ignore
                elif value == SubcommandStub:
                    for subcommand in filter(lambda x: isinstance(x, Subcommand), alconna.options):
                        if subcommand.dest == key:
                            setattr(self, key, SubcommandStub(subcommand))  # type: ignore
                            self.__stubs__["subcommands"].append(key)
                elif value == OptionStub:
                    for option in filter(lambda x: isinstance(x, Option), alconna.options):
                        if option.dest == key:
                            setattr(self, key, OptionStub(option))  # type: ignore
                            self.__stubs__["options"].append(key)
                else:
                    raise TypeError(config.lang.duplication_stub_type_error.format(target=value))
            elif key not in '__target':
                self.__stubs__['other_args'].append(key)

    def __repr__(self):
        return f'<{self.__class__.__name__} with {self.__stubs__}>'

    def option(self, name: str) -> Optional[OptionStub]:
        return cast(OptionStub, getattr(self, name, None))

    def subcommand(self, name: str) -> Optional[SubcommandStub]:
        return cast(SubcommandStub, getattr(self, name, None))

def generate_duplication(command: "Alconna") -> Duplication:
    """
    依据给定的命令生成一个解析结果的检查类。
    """
    options = filter(lambda x: isinstance(x, Option), command.options)
    subcommands = filter(lambda x: isinstance(x, Subcommand), command.options)
    return cast(Duplication, type(
        command.name.strip("/\\.-:") + 'Interface',
        (Duplication,), {
            "__annotations__": {
                **{"args": ArgsStub},
                **{opt.dest: OptionStub for opt in options if opt.name.lstrip('-') not in ("help", "shortcut", "comp")},
                **{sub.dest: SubcommandStub for sub in subcommands},
            }
        }
    )(command))


#!/usr/bin/env python
#
# Quick button test.
# Works with these Launchpads: Mk1, Mk2, Mini Mk3, S/Mini, Pro, Pro Mk3
# And these:                   Midi Figther 64
#
#
# FMMT666(ASkr) 7/2013..8/2020
# www.askrprojects.net
#

import sys
import time

try:
	import launchpad_py as launchpad
except ImportError:
	try:
		import launchpad
	except ImportError:
		sys.exit("error loading launchpad.py")

def main():

	mode = None

	if launchpad.LaunchpadPro().Check( 0 ):
		lp = launchpad.LaunchpadPro()
		if lp.Open( 0 ):
			print("Launchpad Pro")
			mode = "Pro"

	elif launchpad.LaunchpadProMk3().Check( 0 ):
		lp = launchpad.LaunchpadProMk3()
		if lp.Open( 0 ):
			print("Launchpad Pro Mk3")
			mode = "ProMk3"

	elif launchpad.LaunchpadMiniMk3().Check( 1 ):
		lp = launchpad.LaunchpadMiniMk3()
		if lp.Open( 1 ):
			print("Launchpad Mini Mk3")
			mode = "MiniMk3"

	elif launchpad.LaunchpadLPX().Check( 1 ):
		lp = launchpad.LaunchpadLPX()
		if lp.Open( 1 ):
			print("Launchpad X")
			mode = "LPX"

	elif launchpad.LaunchpadMk2().Check( 0 ):
		lp = launchpad.LaunchpadMk2()
		if lp.Open( 0 ):
			print("Launchpad Mk2")
			mode = "Mk2"

	# elif launchpad.LaunchControlXL().Check( 0 ):
	# 	lp = launchpad.LaunchControlXL()
	# 	if lp.Open( 0 ):
	# 		print("Launch Control XL")
	# 		mode = "XL"

	# elif launchpad.LaunchKeyMini().Check( 0 ):
	# 	lp = launchpad.LaunchKeyMini()
	# 	if lp.Open( 0 ):
	# 		print("LaunchKey (Mini)")
	# 		mode = "LKM"

	elif launchpad.Dicer().Check( 0 ):
		lp = launchpad.Dicer()
		if lp.Open( 0 ):
			print("Dicer")
			mode = "Dcr"

	elif launchpad.MidiFighter64().Check( 0 ):
		lp = launchpad.MidiFighter64()
		if lp.Open( 0 ):
			print("Midi Fighter 64")
			mode = "F64"

	elif launchpad.Launchpad().Check( 0 ):
		lp = launchpad.Launchpad()
		if lp.Open( 0 ):
			print("Launchpad Mk1/S/Mini")
			mode = "Mk1"

	if mode is None:
		print("Did not find any Launchpads, meh...")
		return

	print("QUIT: Push a single button for longer than 3s and release it.")

	lastBut = (-99,-99)
	tStart = time.time()
	while True:
		if mode == 'Pro' or mode == 'ProMk3':
			buts = lp.ButtonStateXY( mode = 'pro')
		else:
			buts = lp.ButtonStateXY()

		if buts != []:
			print( buts[0], buts[1], buts[2] )

			# quit?
			if buts[2] > 0:
				lastBut = ( buts[0], buts[1] )
				tStart = time.time()
			else:
				if lastBut == ( buts[0], buts[1] ) and (time.time() - tStart) > 2:
					break

	print("bye ...")

	lp.Reset() # turn all LEDs off
	lp.Close() # close the Launchpad (will quit with an error due to a PyGame bug)

if __name__ == '__main__':
	main()


# 方法1:从后往前遍历，遇相同删除当前项
def removeDuplicates(nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    for num in range(len(nums)-1, 0, -1):
        if nums[num] == nums[num-1]:
            nums.pop(num)
    return len(nums)

# 方法2:只是为了计数，不删除
def removeDuplicates2(nums):
    index = 1
    for i in range(len(nums)-1):
        if(nums[i] != nums[i+1]):
            nums[index] = nums[i+1]
            index += 1
    return(index)

# 方法3:双指针
def removeDuplicates3(self, nums):
    if not nums:
        return 0
    slow = fast = 0
    while fast <= len(nums) - 1:
        if nums[fast] != nums[slow]:
            nums[slow+1] = nums[fast]
            slow += 1
        fast += 1
    return slow + 1


from bs4 import BeautifulSoup
import requests

def downloadDoi(url, filePath):
    '''
        Download a pdf file, corresponding to the paper from the doi link to filePath using sci-hub.
        Attributes:
            sci_hub_url: Base url of hte sci-hub site.
            headers: Headers for the request.
            r: Request of this sci-hub site to retrieve the paper link from and the pdf file.
            soup: BeautifulSoup object of the sci-hub page.
            embed: Find the element with the id of pdf from the page.
            link: Link if there is a pdf on the page.
            fd: File to write the pdf file to.
            chunk: Chunk of the pdf file to be saved to the disk.
        Arguments:
            url: Url of the doi of which we need to download the paper.
            filePath: Path we need to save the pdf to.
        Returns:
            True if a pdf file has been downloaded and saved to filePath, else False.
    '''
    sci_hub_url = 'https://sci-hub.se/'
    # Use headers, so act like we are a firefox browser:
    headers = {
        'User-Agent': 'Mozilla/5.0',
    }
    # Get the url, which consists of the sci_hub_url and then the doi url:
    url = sci_hub_url + url
    # Fetch this page and create a BeautifulSoup object:
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.content, 'html.parser')
    # Get the pdf embed elementL
    embed = soup.find(id='pdf')
    if embed:
        # If it exists, get the link:
        link = embed.get('src')
        if link:
            link = sci_hub_url + link
            # Retrieve this pdf file:
            r = requests.get(link, headers=headers)
            if r.status_code == 200:
                # If we have retrieved a pdf, save this to the filePath location:
                with open(filePath, 'wb') as fd:
                    for chunk in r.iter_content(chunk_size=128):
                        fd.write(chunk)
                # Return true, since we have written a file to the correct location:
                return True
    # Return false if we have not saved a file to the correct location:
    return False

def scrapePage(url):
    '''
        Scrape the page corresponding to the url and return the text.
        Attributes:
            headers: Headers for the request.
            r: Request of this sci-hub site to retrieve the paper link from and the pdf file.
            soup: BeautifulSoup object of the sci-hub page.
            text: Html text form this webpage.
            blacklist: Elements from the html page we do not want in the output.
            t: Elements from the html text we might remove or we add to the output.
        Arguments:
            url: Url we scrape the page from.
        Returns:
            True, if the page has successfully been scraped,
            together with output: Output of the text on the site corresponding to url.
            False, if the page could not be scraped, together with an error message.
    '''
    # Try to scrape the page:
    try:
        # Create the headers, which correspond to a firefox browser:
        headers = {
            'User-Agent': 'Mozilla/5.0',
        }
        # Retrieve the page corresponding to url:
        r = requests.get(url, headers=headers)
        # Create the BeautifulSoup object:
        soup = BeautifulSoup(r.content, 'html.parser')
        # Retrieve all text from this object:
        text = soup.find_all(string=True)
        # Create a output element:
        output = ''
        # Blacklist of HTML elements we do not want the text from:
        blacklist = [
            '[document]',
            'noscript',
            'style',
            'header',
            'html',
            'meta',
            'head',
            'input',
            'script',
            'link',
            'button',
            'form',
            'label',
            'amp-state',
            'footer',
            # there may be more elements you don't want, such as "style", etc.
        ]

        # For all object in the HTML source:
        for t in text:
            # If this element is not in the blacklist, add the text from this element to output:
            if t.parent.name not in blacklist:
                output += '{} '.format(t)
    # If this is unsuccessful, return the error message:
    except Exception as e:
        return False, str(e)
    # Else, return the output:
    return True, output


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
        start = list1
        for i in range(a-1):
            start = start.next
        print(start.val)
        end = start
        for i in range(b-a+2):
            end = end.next
        print(end.val)
        start.next = list2
        while list2.next:
            list2 = list2.next
        list2.next = end
        return list1

Contests/Biweekly Contest/Contest 40/1669. Merge In Between Linked Lists.py


"""
Python
    Memory - 31 MB
    Time - 0.168 s
"""

import sys
import heapq
sys.stdin = open('4485_input.txt')

def dijkstra():                     # 다익스트라
    heap = [(cave[0][0], 0, 0)]     # 현재 위치의 잃는 금액 / 현재 위치

    while heap:
        node = heapq.heappop(heap)
        distance[node[1]][node[2]] = node[0]        # 현재 위치까지 오는데 잃는 최소 비용

        for k in range(4):          # 상하좌우
            r = node[1] + dr[k]     # 새로운 좌표
            c = node[2] + dc[k]

            if 0 <= r < N and 0 <= c < N and not visited[r][c]:     # 범위내이고 아직 방문하지 않았으면
                weight = cave[r][c] + distance[node[1]][node[2]]    # 현재 위치에서 다음칸으로 이동했을때 잃는 금액
                visited[r][c] = 1                                   # 방문처리
                heapq.heappush(heap, (weight, r, c))                # 최소힙에 추가
    return

dr = [-1, 0, 1, 0]
dc = [0, 1, 0, -1]

case = 0                                # 테스트 케이스
while True:                             # 테스트 케이스 종료될때까지 반복
    N = int(sys.stdin.readline())       # 동굴의 크기
    if not N:                           # 테스트 케이스 종료인 경우
        break

    cave = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]     # 동굴 정보
    distance = [[0]*N for _ in range(N)]                                        # 동굴의 각 위치별 소요되는 비용
    visited = [[0]*N for _ in range(N)]                                         # 동굴의 각 위치 방문 여부
    case += 1                                                                   # 케이스 번호 증가

    dijkstra()      # 다익스트라

    print(f'Problem {case}: {distance[N-1][N-1]}')      # 출력


import threading
import time

def sing():
    """唱歌5s"""
    for i in range(5):
        print("----------正在唱歌----------")
        time.sleep(1)

def dance():
    """跳舞5s"""
    for i in range(5):
        print("----------正在跳舞----------")
        time.sleep(1)

def main():
    t1=threading.Thread(target=sing)
    t2=threading.Thread(target=dance)
    t1.start()
    t2.start()

if __name__  ==  "__main__":
    main()


import numpy as np
from classes import ClassPkSpectrum

ks = 10**np.linspace(1.0, 8.0, 100, True)

# Set Gaussian Pk
m="gaussian"
CPk = ClassPkSpectrum(pkmodel=m)
Pks = CPk.Pk(ks)

print("Gaussian Pks : " , Pks)

# Import ks and Pks
m="user_import"
CPk = ClassPkSpectrum(pkmodel=m, user_k=ks, user_Pk=Pks)
Pks_UI = CPk.Pk(ks)

print("User imported Pks : " , Pks_UI)
print("Are the same:", np.all(Pks == Pks_UI)  )

# Set own funtion
def MyPkFunction(kk): return np.ones_like(kk)*0.1
CPk.set_Pk_function(MyPkFunction)
Pks_UI = CPk.Pk(ks)

print("User imported Pks : " , Pks_UI)
print("Are the same:", np.all(Pks == Pks_UI)  )


#!/usr/bin/python3
"""
child class of BaseGeometry
"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry

class Rectangle(BaseGeometry):
    """
    child class of BaseGeometry
    Args:
        width (int): The width of the new Rectangle.
        height (int): The height of the new Rectangle.
    """
    def __init__(self, width, height):
        self.integer_validator("width", width)
        self.__width = width
        self.integer_validator("height", height)
        self.__height = height


def triangle_to_svg(triangle):
    a, b, c = triangle.get_vertices()
    ax = str(a.get_x())
    ay = str(a.get_y())
    bx = str(b.get_x())
    by = str(b.get_y())
    cx = str(c.get_x())
    cy = str(c.get_y())
    with open("sierpinksi_triangle.svg", "a") as f:
        f.write(
            "<polygon points=\"" + ax + "," + ay + " " + bx + "," + by + " " + cx + "," + cy +
            "\" style=\"fill:white;stroke:black;stroke-width:1\" />\n")

class Vertex:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        return self.x

    def get_y(self):
        return self.y

    def create_middle(self, other_vertex):
        x = (self.get_x() + other_vertex.get_x()) / 2
        y = (self.get_y() + other_vertex.get_y()) / 2
        return Vertex(x, y)

class Triangle:

    def __init__(self, a, b, c, depth="No argument"):
        self.vertices = [a, b, c]
        triangle_to_svg(self)
        self.smaller_triangles = [None, None, None]
        if depth != "No argument":
            self.divide(depth)

    def divide(self, depth="No argument"):
        if depth == "No argument":
            for i in range(3):
                a = self.vertices[i]
                b = self.vertices[i].create_middle(self.vertices[(i + 1) % 3])
                c = self.vertices[i].create_middle(self.vertices[(i + 2) % 3])
                self.smaller_triangles[i] = Triangle(a, b, c)
            return True
        if depth < 1:
            return False
        self.divide()
        for i in range(3):
            self.smaller_triangles[i].divide(depth - 1)
        return True

    def get_vertices(self):
        return self.vertices

with open("sierpinksi_triangle.svg", "w") as f:
    f.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
    f.write("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n")

a = Vertex(0, 86.6)
b = Vertex(100, 86.6)
c = Vertex(50, 0)
t = Triangle(a, b, c, 5)

with open("sierpinksi_triangle.svg", "a") as f:
    f.write("</svg>\n")


import operator
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, load_model
import tensorflow as tf
import dbmanagement

dbhandler = dbmanagement.SQLController()
config = tf.ConfigProto()

config.gpu_options.allow_growth = True

sess = tf.Session(config=config)

class_pattern = {
    0: 'Checked',
    1: 'Floral',
    2: 'Graphic',
    3: 'Plain',
    4: 'Striped'}
class_fabric = {
    0: 'Chiffon',
    1: 'Cotton',
    2: 'Crochet',
    3: 'Denim',
    4: 'Wool'}
class_color = {
    0: 'Black',
    1: 'Blue',
    2: 'Green',
    3: 'Red',
    4: 'White'}
class_style = {
    0: 'Casual',
    1: 'Formal',
    2: 'Party',
    3: 'Sports',
    4: 'Vacance'}

if __name__ == "__main__":

    img_width, img_height = 150, 150

    imagelist = []
    # top_model_weights_path = 'bottleneck_fc_model.h5'
    image_data_dir = 'Classification/fabric/test'
    #chosenOnes = sorted(os.listdir(train_data_dir))
    count = 0

    test_datagen = ImageDataGenerator(rescale=1./255)

    data1_generator = test_datagen.flow_from_directory(
            image_data_dir,
            target_size=(150, 150),
            batch_size=1,
            class_mode=None,
            shuffle = False)

    # Reshaping the images array
    nb_data_samples = 1293
    c=0
    images_valid=[]
    for X_batch in data1_generator:
        c+=1
        if (c>nb_data_samples):
            break
        images_valid.append(X_batch[0,:,:,:])

    data_images=np.asarray(images_valid)
    print (data_images.shape)

    image_input_dir = 'find_identical_output/'
    test_datagen = ImageDataGenerator(rescale=1./255)
    inpdata_generator = test_datagen.flow_from_directory(
            image_input_dir,
            target_size=(150, 150),
            batch_size=1,
            class_mode=None,
            shuffle = False)

    nb_input_samples = 1
    c=0
    images_input=[]
    for X_batch in inpdata_generator:
        c+=1
        if (c>nb_input_samples):
            break
        images_input.append(X_batch[0,:,:,:])

    data_images_inp=np.asarray(images_input)

    pattern_model = load_model('./models/vgg_weights_best_pattern.hdf5')
    fabric_model = load_model('./models/vgg_weights_best_fabric.hdf5')
    color_model = load_model('./models/vgg_weights_best_color.hdf5')
    style_model = load_model('./models/vgg_weights_best_style.hdf5')
    # part_model = load_model('./models/vgg_weights_best_part.hdf5')

    inp_pattern=pattern_model.predict(data_images_inp)
    inp_fabric=fabric_model.predict(data_images_inp)
    inp_color=color_model.predict(data_images_inp)
    inp_style=style_model.predict(data_images_inp)
    # part=part_model.predict(data_images_inp)

    inp_feature_list=[]
    for i in range(len(data_images_inp)):
        vals=np.zeros(4)
        vals[0] = np.argmax(inp_pattern[i])
        vals[1] = np.argmax(inp_fabric[i])
        vals[2] = np.argmax(inp_color[i])
        vals[3] = np.argmax(inp_style[i])
    #     vals[4] = np.argmax(inp_part[i])
        inp_feature_list.append(vals)

    inp_feature_data = np.asarray(inp_feature_list)

    def similarity(feature_data,inp_feature_data):
        num_samp=inp_feature_data.size
    #     print (num_samp)
        sim_score={}
        for i in range(len(feature_data)):
            score=0
    #         show_sample(data_images[i])
    #         print(feature_data[i])
            score_m= inp_feature_data - feature_data[i]
    #         print (score_m)
            score = num_samp-np.count_nonzero(score_m)
            sim_score[i]=score
    #         print (score)

        return sim_score

    feature_data=np.load('db_features.npy')
    similarities=similarity(feature_data,inp_feature_data)
    sorted_similarities = sorted(similarities.items(), key=operator.itemgetter(1),reverse=True)
    # print (sorted_similarities)
    num_reco=10
    num_data=feature_data.size
    user_ID=1
    for i in range(num_reco):
    	print("\nIndex : ", sorted_similarities[i][0])
    	clothename, style, store_url, gotostore_url = dbhandler.get_clothes_info(sorted_similarities[i][0])
    	print("Name: "+clothename+"\nStyle: "+style+"\nPic_Url: "+store_url+"\nURL: "+gotostore_url)
    	dbhandler.save_index(user_ID, sorted_similarities[i][0],clothename, style, store_url, gotostore_url)


import torch
import torch.nn as nn
import MiniBert
from MiniBert import MiniBertEncoder, MiniBertConfig

class RNNEncoder(nn.Module):
    def __init__(self, model_size, cell='gru', bidirectional=False):
        super(RNNEncoder, self).__init__()
        self.size = model_size
        self.embed = nn.Linear(16, self.size)
        self.num_direction = 2 if bidirectional else 1
        self.cellname = cell
        assert cell in ['gru', 'lstm', 'rnn']
        if cell == 'lstm':
            self.cell = nn.LSTM(self.size, self.size, 2,
                           dropout=0.3, bidirectional=bidirectional)
        elif cell == 'gru':
            self.cell = nn.GRU(self.size, self.size, 2,
                           dropout=0.3, bidirectional=bidirectional)
        else:
            self.cell = nn.RNN(self.size, self.size, 2,
                           dropout=0.3, bidirectional=bidirectional)

    def forward(self, input):
        outputs = self.embed(input.view(-1,16))
        outputs, state = self.cell(outputs.view(input.size(0), -1, self.size))
        return outputs, state


#!/usr/bin/env python

'''
    This module has code for the state estimator algorithms
'''

#------------------------------------------
# Library imports
import numpy as np
import math
#------------------------------------------
# Import created scripts
import helper_functions as helper
#------------------------------------------

class EKF:
    '''
    Class setup for extended kalman filter
    '''
    def __init__(self, T, v_var, w_var, r_var, b_var):

        self.T = T # Time-step, delta(t)
        self.v_var = v_var # Variance of noise model added to linear velocity measurements
        self.w_var = w_var # Variance of noise model added to angular velocity measurements
        self.r_var = r_var # Variance of noise model added to sensor range measurements
        self.b_var = b_var # Variance of noise model added to sensor bearing measurements

    def motion_model(self, x_k_1, y_k_1, theta_k_1, v_k, w_k):
        '''
        Motion model for robot
        INPUTS:
            x_k_1 - Estimate of x-pose of robot at previous time-step; datatype: float
            y_k_1 - Estimate of y-pose of robot at previous time-step; datatype: float
            theta_k_1 - Estimate of yaw-pose of robot at previous time-step; datatype: float
            v_k - Linear velocity input at current time-step; datatype: float
            w_k - Angular velocity input at current time-step; datatype: float
        OUTPUTS:
            X_k_check - Prior estimate of robot pose using motion model; datatype: np.array [3, 1]
        '''
        X_k_1_hat = np.zeros((3,1))
        X_k_1_hat[0,0] = x_k_1
        X_k_1_hat[1,0] = y_k_1
        X_k_1_hat[2,0] = helper.wraptopi(theta_k_1)
        X_k_check = X_k_1_hat + np.matmul(self.T*np.array([[math.cos(theta_k_1), 0], [math.sin(theta_k_1), 0], [0, 1]]), np.array([[v_k], [w_k]]))
        X_k_check[2] = helper.wraptopi(X_k_check[2])

        return X_k_check

    def observation_model(self, x_k_check, y_k_check, theta_k_check, l, valid_index):
        '''
        Observation model for robot
        INPUTS:
            x_k_check - Prior estimate of x-pose of robot; datatype: float
            y_k_check - Prior estimate of y-pose of robot; datatype: float
            theta_k_check - Prior estimate of yaw-pose of robot; datatype: float
            l - x and y position of landmarks in the environement; datatype: np.array[num_landmarks, 2]
            valid_index - Index of landmarks that are detected by robot; datatype: list
        OUTPUTS:
            X_k_check - Prior estimate of robot pose using motion model; datatype: np.array [3, 1]
        '''
        num_l = len(valid_index)
        Y_k_check = np.zeros((2*num_l,1))
        for i in range(num_l):
            a_l = l[valid_index[i],0] - x_k_check
            b_l = l[valid_index[i],1] - y_k_check
            r_k_l = math.sqrt(pow(a_l,2) + pow(b_l,2))
            b_k_l = math.atan2(b_l,a_l) - theta_k_check
            Y_k_check[2*i,0] = r_k_l
            Y_k_check[2*i+1,0] = helper.wraptopi(b_k_l)

        return Y_k_check

    def calc_Q_k(self): # Motion covariance matrix
        '''
        Calculate motion covariance matrix
        INPUTS:
            None
        OUTPUTS:
            Q_k - Motion covariance at current time-step; datatype: np.array [2,2]
        '''
        Q_k = np.zeros((2,2))
        Q_k[0,0] = self.v_var
        Q_k[1,1] = self.w_var

        return Q_k

    def calc_F_k_1(self, X_k_1, v_k): # Motion Jacobian
        '''
        Calculate motion jacobian
        INPUTS:
            X_k_1 - Estimate of robot pose at previous time-step; datatype: np.array [3, 1]
            v_k - Linear velocity input at current time-step; datatype: float
        OUTPUTS:
            F_k_1 - Motion jacobian; datatype: np.array [3, 3]
        '''
        F_k_1 = np.zeros((3,3))
        F_k_1[0,0] = 1
        F_k_1[1,1] = 1
        F_k_1[2,2] = 1
        F_k_1[0,2] = (-self.T)*math.sin(X_k_1[2])*v_k
        F_k_1[1,2] = self.T*math.cos(X_k_1[2])*v_k

        return F_k_1

    def calc_df_dW(self, X_k_1):
        '''
        INPUTS:
            X_k_1 - Estimate of robot pose at previous time-step; datatype: np.array [3, 1]
        OUTPUTS:
            df_dW - datatype: np.array [3, 2]
        '''
        df_dW = np.zeros((3,2))
        df_dW[0,0] = self.T*math.cos(X_k_1[2])
        df_dW[1,0] = self.T*math.sin(X_k_1[2])
        df_dW[2,1] = self.T

        return df_dW

    def calc_Q_k_prime(self, df_dW, Q_k):
        '''
        Calculate motion covariance matrix for EKF use
        INPUTS:
            None
        OUTPUTS:
            Q_k_prime - Motion covariance at current time-step; datatype: np.array [2,2]
        '''
        Q_k_prime = np.matmul(np.matmul(df_dW, Q_k), np.transpose(df_dW))

        return Q_k_prime

    def calc_R_k_l(self, num_landmarks):
        '''
        Calculate observation covariance
        INPUTS:
            num_landmarks - Number of landmarks observable at current time-step; datatype: int
        OUTPUTS:
            R_k_l - Observation covariance; datatype: np.array [2*num_landmarks, 2*num_landmarks]
        '''
        R_k_l = np.zeros((2*num_landmarks,2*num_landmarks))
        for i in range(0, num_landmarks, 2):
            R_k_l[i,i] = self.r_var
        for i in range(1, num_landmarks, 2):
            R_k_l[i,i] = self.b_var

        return R_k_l

    def calc_G_k_l(self, x_k_check, y_k_check, theta_k_check, l, valid_index):
        '''
        Calculate observation jacobian
        INPUTS:
            x_k_check - Prior estimate of x-pose of robot; datatype: float
            y_k_check - Prior estimate of y-pose of robot; datatype: float
            theta_k_check - Prior estimate of yaw-pose of robot; datatype: float
            l - x and y position of landmarks in the environement; datatype: np.array[num_landmarks, 2]
            valid_index - Index of landmarks that are detected by robot; datatype: list
        OUTPUTS:
            G_k_l - Motion jacobian; datatype: np.array [2*num_l, 3]
        '''
        num_l = len(valid_index)
        G_k_l = np.zeros((2*num_l,3))
        for i in range(num_l):
            temp = np.zeros((2,3))
            a_l = l[valid_index[i],0] - x_k_check
            b_l = l[valid_index[i],1] - y_k_check
            temp[0,0] = (-a_l)/(math.sqrt(pow(a_l,2) + pow(b_l,2)))
            temp[1,0] = b_l/(pow(a_l,2) + pow(b_l,2))
            temp[0,1] = (-b_l)/(math.sqrt(pow(a_l,2) + pow(b_l,2)))
            temp[1,1] = (-a_l)/(pow(a_l,2) + pow(b_l,2))
            temp[1,2] = -1
            G_k_l[2*i:2*i+2,:] = temp

        return G_k_l

    def calc_dg_dN(self, num_l):
        '''
        INPUTS:
            num_l - Number of landmarks observable at current time-step; datatype: int
        OUTPUTS:
            dg_dN - datatype: np.array [2*num_l, 2*num_l]
        '''
        return np.identity(2*num_l)

    def calc_R_k_l_prime(self, dg_dN, R_k_l):
        '''
        Calculate observation covariance matrix for EKF use
        INPUTS:
            dg_dN
            R_k_l
        OUTPUTS:
        '''
        return np.matmul(np.matmul(dg_dN, R_k_l), np.transpose(dg_dN))

    def calc_Y_k(self, valid_index, r_k, b_k):
        '''
        Setup range and bearing measurements to landmarks in a 1D array for EKF calculations
        INPUTS:
            valid_index - Index of landmarks that are detected by robot; datatype: list
            r_k - Range to landmarks; datatype: np.array [totoal_num_landmarks, 1]
            b_k - Bearing to landmarks; datatype: np.array [totoal_num_landmarks, 1]
        OUTPUTS:
            Y_k - Stack of r_k and b_k; datatype: np.array [2*num_l, 1]
        '''
        num_l = len(valid_index)
        Y_k = np.zeros((2*num_l, 1))
        for i in range(num_l):
            Y_k[2*i,0] = r_k[valid_index[i]]
            Y_k[2*i+1,0] = helper.wraptopi(b_k[valid_index[i]])

        return Y_k

    def predict(self, X_k_1, P_k_1, v_k, w_k):
        '''
        Prediction module of EKF
        '''
        Q_k = self.calc_Q_k()
        df_dW = self.calc_df_dW(X_k_1)
        Q_k_prime = self.calc_Q_k_prime(df_dW, Q_k)
        F_k_1 = self.calc_F_k_1(X_k_1, v_k)
        P_k_check = np.matmul(np.matmul(F_k_1, P_k_1), np.transpose(F_k_1)) + Q_k_prime
        X_k_check = self.motion_model(X_k_1[0], X_k_1[1], X_k_1[2], v_k, w_k)
        X_k_check[2] = helper.wraptopi(X_k_check[2])

        return X_k_check.reshape((3)), P_k_check

    def update(self, X_k_check, P_k_check, l, valid_index, r_k, b_k):
        '''
        Correction module of EKF
        '''
        num_l = len(valid_index)
        R_k_l = self.calc_R_k_l(num_l)
        dg_dN = self.calc_dg_dN(num_l)
        R_k_l_prime = self.calc_R_k_l_prime(dg_dN, R_k_l)
        G_k_l = self.calc_G_k_l(X_k_check[0], X_k_check[1], X_k_check[2], l, valid_index)
        Y_k = self.calc_Y_k(valid_index, r_k, b_k)
        Y_k_check = self.observation_model(X_k_check[0], X_k_check[1], X_k_check[2], l, valid_index)
        K_k = np.matmul(np.matmul(P_k_check, np.transpose(G_k_l)), np.linalg.pinv(np.matmul(np.matmul(G_k_l, P_k_check), np.transpose(G_k_l)) + R_k_l_prime))
        dim_identity_matrix = len(np.matmul(K_k, G_k_l))
        P_k_hat = np.matmul(np.identity(dim_identity_matrix) - np.matmul(K_k, G_k_l), P_k_check)
        X_k_hat = X_k_check + np.matmul(K_k, Y_k - Y_k_check)
        X_k_hat[2] = helper.wraptopi(X_k_hat[2])

        return X_k_hat.reshape((3)), P_k_hat


import os
import numpy as np

def part1(line):
    list = np.array(line.split("\t"), dtype=np.int32)

    def redist(list, i):
        cnt = list[i]

        for j in np.ones(cnt, dtype=np.int32):
            i += j
            i = i % cnt
            list[i] = list[i] + 1

    redist(list, 2)

    i = 0
    cnt = 0
    return cnt

def part2(line):
    pass

if __name__ == "__main__":
    with open("input/input_"+os.path.basename(__file__)+".txt") as f:
        val = f.readline()

        print(part1("0\t2\t7\t0"))
        # assert part1(val) == 358309

        print(part2(val))
        # assert part2(val) == 251


from math import hypot
import numpy as np

def fuzzy_kmeans(data, groups_count, iterations=100, fcm_m=2, progress=None):
  attributes = 2
  U = np.empty((groups_count, len(data)))      # Samples participation in groups
  D = np.empty((groups_count, len(data)))      # Sample - group distances
  V = np.random.rand(groups_count, attributes) # Groups centers

  power = 1 / (1 - fcm_m)
  data_np = np.array(data)
  for _ in range(iterations):
    for j in range(groups_count):
      for s in range(len(data)):
        sample = data[s]
        D[j,s] = max(hypot(V[j,0] - sample[0], V[j,1] - sample[1]), 1e-10)

    for j in range(groups_count):
      for s in range(len(data)):
        U[j,s] = (D[j,s] ** power) / np.sum(D[:,s] ** power)

    if not progress is None:
      progress.append({ 'groups': np.array(U), 'centers': np.array(V) })

    for j in range(groups_count):
      for i in range(attributes):
        u_adjusted = U[j,:] ** fcm_m
        V[j,i] = np.sum(np.multiply(u_adjusted, data_np[:,i])) / np.sum(u_adjusted)

  return U, V