"""Info control for host."""
from __future__ import annotations

import asyncio
from contextlib import suppress
from ipaddress import IPv4Address, IPv4Interface, IPv6Address, IPv6Interface
import logging
from typing import Any

import attr

from ..const import ATTR_HOST_INTERNET
from ..coresys import CoreSys, CoreSysAttributes
from ..dbus.const import (
    DBUS_ATTR_CONNECTION_ENABLED,
    DBUS_ATTR_CONNECTIVITY,
    DBUS_IFACE_NM,
    DBUS_SIGNAL_NM_CONNECTION_ACTIVE_CHANGED,
    ConnectionStateFlags,
    ConnectionStateType,
    ConnectivityState,
    DeviceType,
    InterfaceMethod as NMInterfaceMethod,
    WirelessMethodType,
)
from ..dbus.network.connection import NetworkConnection
from ..dbus.network.interface import NetworkInterface
from ..dbus.network.setting.generate import get_connection_from_interface
from ..exceptions import (
    DBusError,
    DBusNotConnectedError,
    HostNetworkError,
    HostNetworkNotFound,
    HostNotSupportedError,
)
from ..jobs.const import JobCondition
from ..jobs.decorator import Job
from ..resolution.checks.network_interface_ipv4 import CheckNetworkInterfaceIPV4
from .const import AuthMethod, InterfaceMethod, InterfaceType, WifiMode

_LOGGER: logging.Logger = logging.getLogger(__name__)

class NetworkManager(CoreSysAttributes):
    """Handle local network setup."""

    def __init__(self, coresys: CoreSys):
        """Initialize system center handling."""
        self.coresys: CoreSys = coresys
        self._connectivity: bool | None = None

    @property
    def connectivity(self) -> bool | None:
        """Return true current connectivity state."""
        return self._connectivity

    @connectivity.setter
    def connectivity(self, state: bool | None) -> None:
        """Set host connectivity state."""
        if self._connectivity == state:
            return

        if state is None or self._connectivity is None:
            self.sys_create_task(
                self.sys_resolution.evaluate.get("connectivity_check")()
            )

        self._connectivity = state
        self.sys_homeassistant.websocket.supervisor_update_event(
            "network", {ATTR_HOST_INTERNET: state}
        )

    @property
    def interfaces(self) -> list[Interface]:
        """Return a dictionary of active interfaces."""
        interfaces: list[Interface] = []
        for inet in self.sys_dbus.network.interfaces.values():
            interfaces.append(Interface.from_dbus_interface(inet))

        return interfaces

    @property
    def dns_servers(self) -> list[str]:
        """Return a list of local DNS servers."""
        # Read all local dns servers
        servers: list[str] = []
        for config in self.sys_dbus.network.dns.configuration:
            if config.vpn or not config.nameservers:
                continue
            servers.extend(config.nameservers)

        return list(dict.fromkeys(servers))

    async def check_connectivity(self, *, force: bool = False):
        """Check the internet connection."""
        if not self.sys_dbus.network.connectivity_enabled:
            self.connectivity = None
            return

        # Check connectivity
        try:
            state = await self.sys_dbus.network.check_connectivity(force=force)
            self.connectivity = state == ConnectivityState.CONNECTIVITY_FULL
        except DBusError as err:
            _LOGGER.warning("Can't update connectivity information: %s", err)
            self.connectivity = False

    def get(self, inet_name: str) -> Interface:
        """Return interface from interface name."""
        if inet_name not in self.sys_dbus.network.interfaces:
            raise HostNetworkNotFound()

        return Interface.from_dbus_interface(
            self.sys_dbus.network.interfaces[inet_name]
        )

    @Job(conditions=[JobCondition.HOST_NETWORK])
    async def load(self):
        """Load network information and reapply defaults over dbus."""
        # Apply current settings on each interface so OS can update any out of date defaults
        interfaces = [
            Interface.from_dbus_interface(interface)
            for interface in self.sys_dbus.network.interfaces.values()
            if not CheckNetworkInterfaceIPV4.check_interface(interface)
        ]
        with suppress(HostNetworkNotFound):
            await asyncio.gather(
                *[
                    self.apply_changes(interface, update_only=True)
                    for interface in interfaces
                    if interface.enabled
                    and (
                        interface.ipv4.method != InterfaceMethod.DISABLED
                        or interface.ipv6.method != InterfaceMethod.DISABLED
                    )
                ]
            )

        self.sys_dbus.network.dbus.properties.on_properties_changed(
            self._check_connectivity_changed
        )

    async def _check_connectivity_changed(
        self, interface: str, changed: dict[str, Any], invalidated: list[str]
    ):
        """Check if connectivity property has changed."""
        if interface != DBUS_IFACE_NM:
            return

        connectivity_check: bool | None = changed.get(DBUS_ATTR_CONNECTION_ENABLED)
        connectivity: bool | None = changed.get(DBUS_ATTR_CONNECTIVITY)

        if (
            connectivity_check is True
            or DBUS_ATTR_CONNECTION_ENABLED in invalidated
            or DBUS_ATTR_CONNECTIVITY in invalidated
        ):
            self.sys_create_task(self.check_connectivity())

        elif connectivity_check is False:
            self.connectivity = None

        elif connectivity is not None:
            self.connectivity = connectivity == ConnectivityState.CONNECTIVITY_FULL

    async def update(self, *, force_connectivity_check: bool = False):
        """Update properties over dbus."""
        _LOGGER.info("Updating local network information")
        try:
            await self.sys_dbus.network.update()
        except DBusError:
            _LOGGER.warning("Can't update network information!")
        except DBusNotConnectedError as err:
            raise HostNotSupportedError(
                "No network D-Bus connection available", _LOGGER.error
            ) from err

        await self.check_connectivity(force=force_connectivity_check)

    async def apply_changes(
        self, interface: Interface, *, update_only: bool = False
    ) -> None:
        """Apply Interface changes to host."""
        inet = self.sys_dbus.network.interfaces.get(interface.name)
        con: NetworkConnection = None

        # Update exist configuration
        if (
            inet
            and inet.settings
            and inet.settings.connection.interface_name == interface.name
            and interface.enabled
        ):
            _LOGGER.debug("Updating existing configuration for %s", interface.name)
            settings = get_connection_from_interface(
                interface,
                name=inet.settings.connection.id,
                uuid=inet.settings.connection.uuid,
            )

            try:
                await inet.settings.update(settings)
                con = await self.sys_dbus.network.activate_connection(
                    inet.settings.object_path, inet.object_path
                )
                _LOGGER.debug(
                    "activate_connection returns %s",
                    con.object_path,
                )
            except DBusError as err:
                raise HostNetworkError(
                    f"Can't update config on {interface.name}: {err}", _LOGGER.error
                ) from err

        # Stop if only updates are allowed as other paths create/delete interfaces
        elif update_only:
            raise HostNetworkNotFound(
                f"Requested to update interface {interface.name} which does not exist or is disabled.",
                _LOGGER.warning,
            )

        # Create new configuration and activate interface
        elif inet and interface.enabled:
            _LOGGER.debug("Create new configuration for %s", interface.name)
            settings = get_connection_from_interface(interface)

            try:
                settings, con = await self.sys_dbus.network.add_and_activate_connection(
                    settings, inet.object_path
                )
                _LOGGER.debug(
                    "add_and_activate_connection returns %s",
                    con.object_path,
                )
            except DBusError as err:
                raise HostNetworkError(
                    f"Can't create config and activate {interface.name}: {err}",
                    _LOGGER.error,
                ) from err

        # Remove config from interface
        elif inet and inet.settings and not interface.enabled:
            try:
                await inet.settings.delete()
            except DBusError as err:
                raise HostNetworkError(
                    f"Can't disable interface {interface.name}: {err}", _LOGGER.error
                ) from err

        # Create new interface (like vlan)
        elif not inet:
            settings = get_connection_from_interface(interface)

            try:
                await self.sys_dbus.network.settings.add_connection(settings)
            except DBusError as err:
                raise HostNetworkError(
                    f"Can't create new interface: {err}", _LOGGER.error
                ) from err
        else:
            raise HostNetworkError(
                "Requested Network interface update is not possible", _LOGGER.warning
            )

        if con:
            async with con.dbus.signal(
                DBUS_SIGNAL_NM_CONNECTION_ACTIVE_CHANGED
            ) as signal:
                # From this point we monitor signals. However, it might be that
                # the state change before this point. Get the state currently to
                # avoid any race condition.
                await con.update()
                state: ConnectionStateType = con.state

                while state != ConnectionStateType.ACTIVATED:
                    if state == ConnectionStateType.DEACTIVATED:
                        raise HostNetworkError(
                            "Activating connection failed, check connection settings."
                        )

                    msg = await signal.wait_for_signal()
                    state = msg[0]
                    _LOGGER.debug("Active connection state changed to %s", state)

        # update_only means not done by user so don't force a check afterwards
        await self.update(force_connectivity_check=not update_only)

    async def scan_wifi(self, interface: Interface) -> list[AccessPoint]:
        """Scan on Interface for AccessPoint."""
        inet = self.sys_dbus.network.interfaces.get(interface.name)

        if inet.type != DeviceType.WIRELESS:
            raise HostNotSupportedError(
                f"Can only scan with wireless card - {interface.name}", _LOGGER.error
            )

        # Request Scan
        try:
            await inet.wireless.request_scan()
        except DBusError as err:
            _LOGGER.warning("Can't request a new scan: %s", err)
            raise HostNetworkError() from err

        await asyncio.sleep(5)

        # Process AP
        return [
            AccessPoint(
                WifiMode[WirelessMethodType(accesspoint.mode).name],
                accesspoint.ssid,
                accesspoint.mac,
                accesspoint.frequency,
                accesspoint.strength,
            )
            for accesspoint in await inet.wireless.get_all_accesspoints()
            if accesspoint.dbus
        ]

@attr.s(slots=True)
class AccessPoint:
    """Represent a wifi configuration."""

    mode: WifiMode = attr.ib()
    ssid: str = attr.ib()
    mac: str = attr.ib()
    frequency: int = attr.ib()
    signal: int = attr.ib()

@attr.s(slots=True)
class IpConfig:
    """Represent a IP configuration."""

    method: InterfaceMethod = attr.ib()
    address: list[IPv4Interface | IPv6Interface] = attr.ib()
    gateway: IPv4Address | IPv6Address | None = attr.ib()
    nameservers: list[IPv4Address | IPv6Address] = attr.ib()
    ready: bool | None = attr.ib()

@attr.s(slots=True)
class WifiConfig:
    """Represent a wifi configuration."""

    mode: WifiMode = attr.ib()
    ssid: str = attr.ib()
    auth: AuthMethod = attr.ib()
    psk: str | None = attr.ib()
    signal: int | None = attr.ib()

@attr.s(slots=True)
class VlanConfig:
    """Represent a vlan configuration."""

    id: int = attr.ib()
    interface: str = attr.ib()

@attr.s(slots=True)
class Interface:
    """Represent a host network interface."""

    name: str = attr.ib()
    enabled: bool = attr.ib()
    connected: bool = attr.ib()
    primary: bool = attr.ib()
    type: InterfaceType = attr.ib()
    ipv4: IpConfig | None = attr.ib()
    ipv6: IpConfig | None = attr.ib()
    wifi: WifiConfig | None = attr.ib()
    vlan: VlanConfig | None = attr.ib()

    @staticmethod
    def from_dbus_interface(inet: NetworkInterface) -> Interface:
        """Concert a dbus interface into normal Interface."""
        ipv4_method = (
            Interface._map_nm_method(inet.settings.ipv4.method)
            if inet.settings and inet.settings.ipv4
            else InterfaceMethod.DISABLED
        )
        ipv6_method = (
            Interface._map_nm_method(inet.settings.ipv6.method)
            if inet.settings and inet.settings.ipv6
            else InterfaceMethod.DISABLED
        )
        ipv4_ready = (
            bool(inet.connection)
            and ConnectionStateFlags.IP4_READY in inet.connection.state_flags
        )
        ipv6_ready = (
            bool(inet.connection)
            and ConnectionStateFlags.IP6_READY in inet.connection.state_flags
        )
        return Interface(
            inet.name,
            inet.settings is not None,
            Interface._map_nm_connected(inet.connection),
            inet.primary,
            Interface._map_nm_type(inet.type),
            IpConfig(
                ipv4_method,
                inet.connection.ipv4.address if inet.connection.ipv4.address else [],
                inet.connection.ipv4.gateway,
                inet.connection.ipv4.nameservers
                if inet.connection.ipv4.nameservers
                else [],
                ipv4_ready,
            )
            if inet.connection and inet.connection.ipv4
            else IpConfig(ipv4_method, [], None, [], ipv4_ready),
            IpConfig(
                ipv6_method,
                inet.connection.ipv6.address if inet.connection.ipv6.address else [],
                inet.connection.ipv6.gateway,
                inet.connection.ipv6.nameservers
                if inet.connection.ipv6.nameservers
                else [],
                ipv6_ready,
            )
            if inet.connection and inet.connection.ipv6
            else IpConfig(ipv6_method, [], None, [], ipv6_ready),
            Interface._map_nm_wifi(inet),
            Interface._map_nm_vlan(inet),
        )

    @staticmethod
    def _map_nm_method(method: str) -> InterfaceMethod:
        """Map IP interface method."""
        mapping = {
            NMInterfaceMethod.AUTO: InterfaceMethod.AUTO,
            NMInterfaceMethod.DISABLED: InterfaceMethod.DISABLED,
            NMInterfaceMethod.MANUAL: InterfaceMethod.STATIC,
            NMInterfaceMethod.LINK_LOCAL: InterfaceMethod.DISABLED,
        }

        return mapping.get(method, InterfaceMethod.DISABLED)

    @staticmethod
    def _map_nm_connected(connection: NetworkConnection | None) -> bool:
        """Map connectivity state."""
        if not connection:
            return False

        return connection.state in (
            ConnectionStateType.ACTIVATED,
            ConnectionStateType.ACTIVATING,
        )

    @staticmethod
    def _map_nm_type(device_type: int) -> InterfaceType:
        mapping = {
            DeviceType.ETHERNET: InterfaceType.ETHERNET,
            DeviceType.WIRELESS: InterfaceType.WIRELESS,
            DeviceType.VLAN: InterfaceType.VLAN,
        }
        return mapping[device_type]

    @staticmethod
    def _map_nm_wifi(inet: NetworkInterface) -> WifiConfig | None:
        """Create mapping to nm wifi property."""
        if inet.type != DeviceType.WIRELESS or not inet.settings:
            return None

        # Authentication and PSK
        auth = None
        psk = None
        if not inet.settings.wireless_security:
            auth = AuthMethod.OPEN
        elif inet.settings.wireless_security.key_mgmt == "none":
            auth = AuthMethod.WEP
        elif inet.settings.wireless_security.key_mgmt == "wpa-psk":
            auth = AuthMethod.WPA_PSK
            psk = inet.settings.wireless_security.psk

        # WifiMode
        mode = WifiMode.INFRASTRUCTURE
        if inet.settings.wireless.mode:
            mode = WifiMode(inet.settings.wireless.mode)

        # Signal
        if inet.wireless:
            signal = inet.wireless.active.strength
        else:
            signal = None

        return WifiConfig(
            mode,
            inet.settings.wireless.ssid,
            auth,
            psk,
            signal,
        )

    @staticmethod
    def _map_nm_vlan(inet: NetworkInterface) -> WifiConfig | None:
        """Create mapping to nm vlan property."""
        if inet.type != DeviceType.VLAN or not inet.settings:
            return None

        return VlanConfig(inet.settings.vlan.id, inet.settings.vlan.parent)


import io
import mock
import unittest
import zipfile

from cumulusci.core.config import OrgConfig
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.salesforce import UpdateDependencies
from cumulusci.tests.util import create_project_config
from .util import create_task

class TestUpdateDependencies(unittest.TestCase):
    maxDiff = None

    @mock.patch(
        "cumulusci.salesforce_api.metadata.ApiRetrieveInstalledPackages.__call__"
    )
    def test_run_task(self, ApiRetrieveInstalledPackages):
        project_config = create_project_config()
        repo = mock.Mock()
        project_config.config["project"]["dependencies"] = [
            {
                "zip_url": "http://zipurl",
                "subfolder": "src",
                "namespace_tokenize": "ns",
                "namespace_inject": "ns",
                "namespace_strip": "ns",
                "dependencies": [
                    {"namespace": "upgradeddep", "version": "1.1"},
                    {"namespace": "samedep", "version": "1.0"},
                    {"namespace": "downgradeddep", "version": "1.0"},
                    {"namespace": "newdep", "version": "1.0"},
                    {"repo": repo, "subfolder": "subfolder", "ref": "ref"},
                ],
            },
            {
                "namespace": "dependsonupgradedbeta",
                "version": "1.0",
                "dependencies": [
                    {"namespace": "upgradedbeta", "version": "1.0 (Beta 2)"}
                ],
            },
        ]
        task = create_task(UpdateDependencies, project_config=project_config)
        ApiRetrieveInstalledPackages.return_value = {
            "upgradeddep": "1.0",
            "samedep": "1.0",
            "downgradeddep": "1.1",
            "removeddep": "1.0",
            "upgradedbeta": "1.0 (Beta 1)",
            "dependsonupgradedbeta": "1.0",
        }
        task.api_class = mock.Mock()
        zf = zipfile.ZipFile(io.BytesIO(), "w")
        try:
            UD_globals = UpdateDependencies._install_dependency.__globals__
        except AttributeError:  # Python 2
            UD_globals = UpdateDependencies._install_dependency.__func__.__globals__
        download_extract_zip = UD_globals["download_extract_zip"]
        download_extract_github = UD_globals["download_extract_github"]
        UD_globals["download_extract_zip"] = mock.Mock(return_value=zf)
        UD_globals["download_extract_github"] = mock.Mock(return_value=zf)
        try:
            task()
        finally:
            UD_globals["download_extract_zip"] = download_extract_zip
            UD_globals["download_extract_github"] = download_extract_github
        self.assertEqual(
            [
                {"version": "1.1", "namespace": "upgradeddep"},
                {"version": "1.0", "namespace": "downgradeddep"},
                {"version": "1.0", "namespace": "newdep"},
                {"repo": repo, "subfolder": "subfolder", "ref": "ref"},
                {
                    "dependencies": [
                        {"version": "1.1", "namespace": "upgradeddep"},
                        {"version": "1.0", "namespace": "samedep"},
                        {"version": "1.0", "namespace": "downgradeddep"},
                        {"version": "1.0", "namespace": "newdep"},
                        {"repo": repo, "subfolder": "subfolder", "ref": "ref"},
                    ],
                    "zip_url": "http://zipurl",
                    "subfolder": "src",
                    "namespace_tokenize": "ns",
                    "namespace_inject": "ns",
                    "namespace_strip": "ns",
                },
                {"version": "1.0 (Beta 2)", "namespace": "upgradedbeta"},
                {
                    "version": "1.0",
                    "namespace": "dependsonupgradedbeta",
                    "dependencies": [
                        {"version": "1.0 (Beta 2)", "namespace": "upgradedbeta"}
                    ],
                },
            ],
            task.install_queue,
        )
        self.assertEqual(
            [
                {
                    "version": "1.0",
                    "namespace": "dependsonupgradedbeta",
                    "dependencies": [
                        {"version": "1.0 (Beta 2)", "namespace": "upgradedbeta"}
                    ],
                },
                {"version": "1.0 (Beta 2)", "namespace": "upgradedbeta"},
                {"version": "1.0", "namespace": "downgradeddep"},
            ],
            task.uninstall_queue,
        )
        self.assertEqual(10, task.api_class.call_count)

    def test_run_task__no_dependencies(self):
        task = create_task(UpdateDependencies)
        api = mock.Mock()
        task.api_class = mock.Mock(return_value=api)
        task()
        api.assert_not_called()

    def test_update_dependency_latest_option_err(self):
        project_config = create_project_config()
        project_config.config["project"]["dependencies"] = [{"namespace": "foo"}]
        task = create_task(UpdateDependencies, project_config=project_config)
        task.options["include_beta"] = True
        task.org_config = OrgConfig(None, None)

        with self.assertRaises(TaskOptionsError):
            task()


# from pathlib import Path
from pathlib import PurePath

from htmltools import HTMLDependency, Tag

from shiny.module import resolve_id
from shiny.render.transformer import (
    TransformerMetadata,
    ValueFn,
    output_transformer,
    resolve_value_fn,
)

# This object is used to let Shiny know where the dependencies needed to run
# our component all live. In this case, we're just using a single javascript
# file but we could also include CSS.
custom_component_deps = HTMLDependency(
    "custom-component",
    "1.0.0",
    source={
        "package": "custom_component",
        "subdir": str(PurePath(__file__).parent / "distjs"),
    },
    script={"src": "index.js", "type": "module"},
)

@output_transformer()
async def render_custom_component(
    _meta: TransformerMetadata,
    _fn: ValueFn[int | None],
):
    res = await resolve_value_fn(_fn)
    if res is None:
        return None

    if not isinstance(res, int):
        # Throw an error if the value is not an integer.
        raise TypeError(f"Expected a integer, got {type(res)}. ")

    # Send the results to the client. Make sure that this is a serializable
    # object and matches what is expected in the javascript code.
    return {"value": res}

def custom_component(id: str, height: str = "200px"):
    """
    A shiny output. To be paired with
    `render_custom_component` decorator.
    """
    return Tag(
        "custom-component",
        custom_component_deps,
        # Use resolve_id so that our component will work in a module
        id=resolve_id(id),
    )


class Solution:
    def maxSubArray(self, nums: List[int]) -> int: # had to look up the solutions for this
        maximum = nums[0]
        curr_subarray = nums[0]

        for num in nums[1:]:
            curr_subarray = max(num, curr_subarray + num)
            # at each iteration we check whether the old part of the subarray is actually helpful and wotth keeping
            # If it's not, we'll dump it, as it won't be helpful for any other subarray
            if curr_subarray > maximum: maximum = curr_subarray
            # We could store a i index if the question asked for it
        return maximum
        # TIME complexity: O(N)
        # SPACE complexity: O(1)


# -*- coding:utf-8-*-

import sqlite3

#连接数据库
conn = sqlite3.connect('first.db')

#获取游标
c = conn.cursor()

#调用executescript()方法执行一段sql脚本

c.executescript('''
    insert into user_tb values(null,'武松','3444','male')
    insert into user_tb values (null,'林冲','44444','male')
    create table item_tb(_id integer primary key autoincrement,name,price)
''')

conn.commit()

c.close()
conn.close()


#!/usr/bin/python3

from pyrob.api import *
from practise2.actions import *

@task(delay=0.02)
def task_2_4():

    def fill_star():

        def fill_current_cell():
            fill_cell()
            return False

        for direction in range(1,5):
            move(direction,1,fill_current_cell)
            move(get_reverse_direction(direction),1,fill_current_cell)

    move(4,1)
    move(3,1)

    for j in range(2,7):

        for i in range(10):
            fill_star()
            if i != 9:
                move(1 if j % 2 else 3, 4)

        move(4,4)

    move(1)
    move(2,2)

if __name__ == '__main__':
    run_tasks()


# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring,too-few-public-methods,invalid-name

""" Test cases for documents in ddionrails.data app """

from unittest import TestCase

import pytest
from django.forms.models import model_to_dict

from ddionrails.data.documents import VariableDocument

pytestmark = [pytest.mark.search]

TEST_CASE = TestCase()

@pytest.mark.usefixtures("variables_index")
def test_variable_search_document_fields(variable):
    search = VariableDocument.search().query("match_all")

    expected = 1
    TEST_CASE.assertEqual(expected, search.count())
    response = search.execute()
    document = response.hits[0]

    # test meta
    TEST_CASE.assertEqual(str(variable.id), document.meta.id)
    TEST_CASE.assertEqual("testing_variables", document.meta.index)

    # generate expected dictionary with attributes from model instance
    expected = model_to_dict(
        variable,
        fields=(
            "name",
            "label",
            "label_de",
            "description",
            "description_de",
        ),
    )
    expected["categories"] = {"labels": ["[1] Yes"], "labels_de": ["[1] Ja"]}
    # add facets to expected dictionary
    expected["analysis_unit"] = {"label": "", "label_de": ""}
    expected["conceptual_dataset"] = {"label": "", "label_de": ""}
    expected["period"] = {"label": "", "label_de": ""}
    expected["id"] = str(variable.id)
    expected["study_name"] = variable.dataset.study.title()
    expected["study"] = {
        "name": variable.dataset.study.name,
        "label": variable.dataset.study.label,
    }

    # add relations to expected dictionary
    expected["dataset"] = {"name": variable.dataset.name, "label": variable.dataset.label}
    # generate result dictionary from search document
    result = document.to_dict()
    TEST_CASE.assertEqual(expected, result)

@pytest.mark.usefixtures("variables_index")
def test_variable_search_document_fields_missing_related_objects(variable):
    variable.dataset.analysis_unit = None
    variable.dataset.conceptual_dataset = None
    variable.dataset.period = None
    variable.dataset.save()
    variable.save()

    search = VariableDocument.search().query("match_all")
    response = search.execute()
    document = response.hits[0]

    expected = "Not Categorized"
    TEST_CASE.assertEqual(expected, document.analysis_unit.label)
    TEST_CASE.assertEqual(expected, document.conceptual_dataset.label)
    TEST_CASE.assertEqual(expected, document.period.label)

@pytest.mark.usefixtures("variables_index")
def test_variable_search_document_fields_string_representing_missing(
    variable, conceptual_dataset, analysis_unit, period
):
    analysis_unit.label = "Unspecified"
    analysis_unit.save()
    conceptual_dataset.label = "none"
    conceptual_dataset.save()
    period.label = "unspecified"
    period.save()

    variable.dataset.analysis_unit = analysis_unit
    variable.dataset.conceptual_dataset = conceptual_dataset
    variable.dataset.period = period
    variable.dataset.save()
    variable.save()

    search = VariableDocument.search().query("match_all")
    response = search.execute()
    document = response.hits[0]

    excepted = "Not Categorized"
    TEST_CASE.assertEqual(excepted, document.analysis_unit.label)
    TEST_CASE.assertEqual(excepted, document.conceptual_dataset.label)
    TEST_CASE.assertEqual(excepted, document.period.label)


from tkinter import *
import random
import numpy

global tot
global val
tot=0

def interface():
    global val
    val=dict()# For Mapping of the Grid System
    tk=Tk()
    tk.config(bg="yellow")
    tk.title("MineSweeper-DPS")
    tk.resizable(0,0)
    #Creating the Buttons
    #As this is a 6x6 Minesweeper Interface
    b11=Button(tk,height=1,width=2,command=lambda:game(b11,tk)) #Button at Grid[1,1]
    b12=Button(tk,height=1,width=2,command=lambda:game(b12,tk)) #Button at Grid[1,2]
    b13=Button(tk,height=1,width=2,command=lambda:game(b13,tk)) #...
    b14=Button(tk,height=1,width=2,command=lambda:game(b14,tk)) #...
    b15=Button(tk,height=1,width=2,command=lambda:game(b15,tk)) #...
    b16=Button(tk,height=1,width=2,command=lambda:game(b16,tk)) #...
    b21=Button(tk,height=1,width=2,command=lambda:game(b21,tk)) #...
    b22=Button(tk,height=1,width=2,command=lambda:game(b22,tk)) #...
    b23=Button(tk,height=1,width=2,command=lambda:game(b23,tk)) #...
    b24=Button(tk,height=1,width=2,command=lambda:game(b24,tk)) #...
    b25=Button(tk,height=1,width=2,command=lambda:game(b25,tk)) #...
    b26=Button(tk,height=1,width=2,command=lambda:game(b26,tk)) #...
    b31=Button(tk,height=1,width=2,command=lambda:game(b31,tk)) #...
    b32=Button(tk,height=1,width=2,command=lambda:game(b32,tk)) #...
    b33=Button(tk,height=1,width=2,command=lambda:game(b33,tk)) #...
    b34=Button(tk,height=1,width=2,command=lambda:game(b34,tk)) #...
    b35=Button(tk,height=1,width=2,command=lambda:game(b35,tk)) #...
    b36=Button(tk,height=1,width=2,command=lambda:game(b36,tk)) #...
    b41=Button(tk,height=1,width=2,command=lambda:game(b41,tk)) #...
    b42=Button(tk,height=1,width=2,command=lambda:game(b42,tk)) #...
    b43=Button(tk,height=1,width=2,command=lambda:game(b43,tk)) #...
    b44=Button(tk,height=1,width=2,command=lambda:game(b44,tk)) #...
    b45=Button(tk,height=1,width=2,command=lambda:game(b45,tk)) #...
    b46=Button(tk,height=1,width=2,command=lambda:game(b46,tk)) #...
    b51=Button(tk,height=1,width=2,command=lambda:game(b51,tk)) #...
    b52=Button(tk,height=1,width=2,command=lambda:game(b52,tk)) #...
    b53=Button(tk,height=1,width=2,command=lambda:game(b53,tk)) #...
    b54=Button(tk,height=1,width=2,command=lambda:game(b54,tk)) #...
    b55=Button(tk,height=1,width=2,command=lambda:game(b55,tk)) #...
    b56=Button(tk,height=1,width=2,command=lambda:game(b56,tk)) #...
    b61=Button(tk,height=1,width=2,command=lambda:game(b61,tk)) #...
    b62=Button(tk,height=1,width=2,command=lambda:game(b62,tk)) #...
    b63=Button(tk,height=1,width=2,command=lambda:game(b63,tk)) #...
    b64=Button(tk,height=1,width=2,command=lambda:game(b64,tk)) #...
    b65=Button(tk,height=1,width=2,command=lambda:game(b65,tk)) #...
    b66=Button(tk,height=1,width=2,command=lambda:game(b66,tk)) #...
    #Create the Grid/ Position of the Buttons on the Interface
    # i.e. Assign the Positions to the button on the Interface
    b11.grid(row=1,column=1)
    b12.grid(row=1,column=2)
    b13.grid(row=1,column=3)
    b14.grid(row=1,column=4)
    b15.grid(row=1,column=5)
    b16.grid(row=1,column=6)
    b21.grid(row=2,column=1)
    b22.grid(row=2,column=2)
    b23.grid(row=2,column=3)
    b24.grid(row=2,column=4)
    b25.grid(row=2,column=5)
    b26.grid(row=2,column=6)
    b31.grid(row=3,column=1)
    b32.grid(row=3,column=2)
    b33.grid(row=3,column=3)
    b34.grid(row=3,column=4)
    b35.grid(row=3,column=5)
    b36.grid(row=3,column=6)
    b41.grid(row=4,column=1)
    b42.grid(row=4,column=2)
    b43.grid(row=4,column=3)
    b44.grid(row=4,column=4)
    b45.grid(row=4,column=5)
    b46.grid(row=4,column=6)
    b51.grid(row=5,column=1)
    b52.grid(row=5,column=2)
    b53.grid(row=5,column=3)
    b54.grid(row=5,column=4)
    b55.grid(row=5,column=5)
    b56.grid(row=5,column=6)
    b61.grid(row=6,column=1)
    b62.grid(row=6,column=2)
    b63.grid(row=6,column=3)
    b64.grid(row=6,column=4)
    b65.grid(row=6,column=5)
    b66.grid(row=6,column=6)
    ### Putting the Game Algorithm
    button_list=[b11,b12,b13,b14,b15,b16,b21,b22,b23,b24,b25,b26,b31,b32,b33,b34,b35,b36,b41,b42,b43,b44,b45,b46,b51,b52,b53,b54,b55,b56,b61,b62,b63,b64,b65,b66]
    val1=['1']*(6)
    val2=['2']*(6)
    val3=['3']*(6)
    val4=['4']*(6)
    val5=['5']*(6)
    val_bomb=['bomb']*(6)
    net_val=val1+val2+val3+val4+val5+val_bomb
    random.shuffle(net_val)
    #print(net_val)
    for i in range(0,len(net_val)):
        val[button_list[i]]=net_val[i]

def game(button,tk):
    global val,tot
    if(val[button]=='bomb'):
        tk.destroy()
        tk_end=Tk()
        tk_end.config(bg="yellow")
        tk_end.title("Mine-Sweeper-DPS")
        tk_end.resizable(0,0)
        label=Label(tk_end,text=str(tot))
        label.grid(row=1,column=1)
        label2=Label(tk_end,text="GameOver!")
        label2.grid(row=2,column=1)
    else:
        if(val[button] != '-1'):
            button['text']=val[button]
            tot=tot+int(val[button])
            val[button]='-1'
            if(tot==90):
                tk.destroy()
                tk_end=Tk()
                tk_end.config(bg="yellow")
                tk_end.title("MineSweeper-DPS")
                tk_end.resizable(0,0)
                label1=Label(tk_end,text="You Won!!")
                label1.grid(row=1,column=1)
                label2=Label(tk_end,text="Net Score = 90")
                label2.grid(row=2,column=1)

if __name__=="__main__":
    interface()


# 带冲量的随机梯度下降SGD
from AQI_DataSet import *

# 多元数据
def SGD_Momentum():
    # 训练集，每个样本有三个分量
    X_train, X_test, Y_train, Y_test = DataSet_Random(3)  # 获取随机拆分后的数据
    x, y = normalized(X_train, Y_train)  # 归一化

    # 初始化
    m, dim = x.shape
    theta = np.zeros(dim)  # 参数
    alpha = 0.01  # 学习率
    momentum = 0.1  # 冲量
    threshold = 0.0001  # 停止迭代的阈值
    iterations = 5000  # 迭代次数
    error = 0  # 初始错误为0
    gradient = 0  # 初始梯度为0
    i = 0
    # 迭代开始
    for i in range(iterations):
        j = i % m
        error = 1 / (2 * m) * np.dot((np.dot(x, theta) - y).T,
                                     (np.dot(x, theta) - y))
        # 迭代停止
        if abs(error) <= threshold:
            break

        gradient = momentum * gradient - alpha * (x[j] *
                                                  (np.dot(x[j], theta) - y[j]))
        theta += gradient

    print('SGD_Momentum:迭代次数：%d' % (i + 1), 'theta：', theta, 'error：%f' % error)

if __name__ == '__main__':
    SGD_Momentum()


import streamlit as st
from datetime import datetime, timedelta
import util, plot
from numerize import numerize
import pandas as pd
import numpy as np

def show_national_cases(national_data, start_date, stop_date, last_date):

    st.subheader('Situazione a livello nazionale')

    national_data_df = national_data.loc[start_date:stop_date]
    days = national_data_df.index.values
    cases = national_data_df["Casi"].values
    tamponi = national_data_df["Tamponi"].values
    hospital = national_data_df["Ospedalizzati"].values
    icu = national_data_df["TI"].values
    deaths = national_data_df["Deceduti"].values

    # Compute increments of interest
    delta_cases = util.get_delta(cases)
    delta_tamponi = util.get_delta(tamponi)
    ratio = (delta_cases/delta_tamponi)*100.

    delta_icu = util.get_delta(icu)
    delta_hospital = util.get_delta(hospital)

    perc_delta_icu = 100*delta_icu/icu[1:]
    perc_delta_hospital = 100*delta_hospital/hospital[1:]

    delta_deaths = util.get_delta(deaths)

    # Compute the rolling means at 7 days
    average = util.compute_rollingmean(ratio)
    average_hosp = util.compute_rollingmean(delta_hospital)
    average_icu = util.compute_rollingmean(delta_icu)
    average_deaths = util.compute_rollingmean(delta_deaths)

    # Show the metrics of the last day, only if last day is today
    if stop_date == last_date:
        last_day = days[-1]
        st.markdown(f'Dati più recenti, relativi al '+last_day)
        #col1, col2, col3, col4 = st.columns(4)

        st.metric("Casi", numerize.numerize(int(cases[-1]), 2), util.mysign(delta_cases[-1])+str(delta_cases[-1])+' ('+str(round(ratio[-1],1))+'%)', delta_color="inverse")
        if delta_hospital[-1] != 0:
            st.metric("Ospedalizzati", str(hospital[-1]), util.mysign(delta_hospital[-1])+str(delta_hospital[-1])+' ('+str(round(perc_delta_hospital[-1],1))+'%)', delta_color="inverse")
        else:
            st.metric("Ospedalizzati", str(hospital[-1]), delta=None, delta_color="off")
        if delta_icu[-1] != 0:
            st.metric("Terapie Intensive", str(icu[-1]), util.mysign(delta_icu[-1])+str(delta_icu[-1])+' ('+str(round(perc_delta_icu[-1],1))+'%)', delta_color="inverse")
        else:
            st.metric("Terapie Intensive", str(icu[-1]), delta=None, delta_color="off")
        st.metric("Deceduti", str(deaths[-1]), util.mysign(delta_deaths[-1])+str(delta_deaths[-1]), delta_color="inverse")

    giorni0 = [datetime.strptime(giorno, "%d/%m/%Y").date() for giorno in days]

    # Plot the national cases
    fig = plot.get_national_cases_fig(giorni0, ratio, average, delta_hospital, average_hosp, delta_icu, average_icu, delta_deaths, average_deaths)
    st.plotly_chart(fig, use_container_width=True)

def show_local_cases(local_data, start_date, stop_date, last_date):

    st.subheader('Situazione a livello provinciale')

    # Get the location for regional sub-area
    provinces_sorted = util.provinces.copy()
    provinces_sorted.sort()
    provinces_sorted.insert(0, '')
    # Get population automatically
    pop = util.get_pop()
    pop_df = pd.DataFrame({'Provincia': provinces_sorted, 'Pop': pop})
    province_to_visualize = st.selectbox('Provincia da visualizzare (default: Varese)', provinces_sorted, index=100,
                                         format_func=lambda x: 'Seleziona provincia' if x == '' else x)
    province_to_compare = st.selectbox('Compara con altra provincia?', provinces_sorted,
                                       format_func=lambda x: 'Seleziona provincia' if x == '' else x)

    local_data_df = local_data.loc[start_date:stop_date][province_to_visualize]
    days = local_data_df.index.values
    cases = local_data_df.values
    pop1 = pop_df[pop_df['Provincia'] == province_to_visualize]['Pop'].values

    # Compute increments of interest
    delta_cases = util.get_delta(cases)
    delta_casi_pertho = 1e5 * delta_cases / pop1

    # Compute the rolling mean at 7 days
    average = util.compute_rollingmean(delta_casi_pertho)

    # Show the metrics of the last day, only if last day is today
    if stop_date == last_date:
        last_day = days[-1]
        st.markdown(f'Dati più recenti, relativi al ' + last_day)
        st.metric("Casi a "+province_to_visualize, numerize.numerize(int(cases[-1]), 1), util.mysign(delta_cases[-1]) + str(delta_cases[-1]),
                  delta_color="inverse")

    if province_to_compare:
        df2 = local_data.loc[start_date:stop_date][province_to_compare]
        casi2 = df2.values
        delta_cases2 = util.get_delta(casi2)

        st.metric("Casi a "+province_to_compare, numerize.numerize(int(casi2[-1]), 1), util.mysign(delta_cases2[-1]) + str(delta_cases2[-1]),
                  delta_color="inverse")

    giorni0 = [datetime.strptime(giorno, "%d/%m/%Y").date() for giorno in days]

    # Plot the local cases
    fig = plot.get_local_cases_fig(giorni0, province_to_visualize, average, local_data, start_date, stop_date, pop_df,
                                   delta_casi_pertho, province_to_compare)
    st.plotly_chart(fig, use_container_width=True)


from os import name
from django.urls import path
from . import views

urlpatterns = [
	path('product-list/', views.ProductListView.as_view(), name="product-list_mobile"),
	path('category-list/', views.categoryList, name="category-list_mobile"),
	path('category/<int:pk>/', views.CategoryProductsView.as_view(), name="category-detail_mobile"),
	path('product-detail/<int:pk>/', views.ProductDetailView.as_view(), name="product-detail_mobile"),
	path('product-get-like/', views.likeGetProduct, name="product-get-like_mobile"),
	path('product-like/', views.likeProduct, name="product-like_mobile"),
	path('product-like-delete/<int:pk>/', views.LikeProductDelete.as_view(), name="product-like-delete_mobile"),
]


import pygame, sys
from button import Button
import datetime
import time
import random
from taunts import taunts_list

# Initialize pygame
pygame.mixer.init()
pygame.init()

screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption("Main Menu")

# Double the size of the background image
BG = pygame.image.load("assets/Title screen background.png")
BG = pygame.transform.scale(BG, (1280, 720))

# Set icon
icon = pygame.image.load("assets/App Icon.png")
pygame.display.set_icon(icon)

# Get Font
def get_font(size):
	return pygame.font.Font("assets/8bit.ttf", size)

# Game Variables
current_time = datetime.datetime.now()
current_time = current_time.strftime("%H:%M")
# Set alarm time to today's date and current time
alarm_time = datetime.datetime.now()
volume = 0.5
music = True
taunt = random.choice(taunts_list)

# Victory Loop
def victory():
	pygame.display.set_caption("Victory")

	# Stop playing alarm
	pygame.mixer.music.stop()
	# Start playing victory music
	pygame.mixer.music.load("assets/sounds/Victory Trumpets.mp3")
	pygame.mixer.music.set_volume(volume)
	pygame.mixer.music.play(1)

	while True:
		screen.fill("#999797")

		# Set background image
		screen.blit(BG, (0, 0))

		victory_mouse_pos = pygame.mouse.get_pos()

		# Render victory banner
		victory_banner = pygame.image.load("assets/victory Banner 2.png")
		victory_banner_rect = victory_banner.get_rect(center=(640, 325))
		screen.blit(victory_banner, victory_banner_rect)

		# Quit button
		quit_button = Button(image=None, pos=(640, 660), text_input="Quit", font=get_font(75), base_color="White",
		                     hovering_color="Green")

		quit_button.changeColor(victory_mouse_pos)
		quit_button.update(screen)

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				# stop music
				pygame.mixer.music.stop()
				pygame.quit()
				sys.exit()
			if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
				if quit_button.checkForInput(victory_mouse_pos):
					pygame.quit()
					sys.exit()

		pygame.display.update()

def card_game():
	pygame.display.set_caption("Card Game")

	# Start playing alarm
	pygame.mixer.music.load("assets/sounds/default alarm.wav")

	pygame.mixer.music.set_volume(volume)
	pygame.mixer.music.play(-1)
	time.sleep(5)
	if music:
		pygame.mixer.music.load("assets/sounds/Boss fight music.mp3")
		pygame.mixer.music.set_volume(volume)
		pygame.mixer.music.play(-1)

	# Variables
	health = 6  # Start with full health

	# Constants
	CARD_WIDTH, CARD_HEIGHT = 100, 150
	FPS = 60

	# Load face-down images
	card_images_face_down = [pygame.image.load("assets/CardBackside.png") for i in range(12)]

	# Game variables
	cards = [i // 2 for i in range(12)]
	random.shuffle(cards)
	flipped_cards = []
	completed_cards = []

	# Load a single set of face-up images for all cards
	card_images_face_up = [pygame.image.load(f"assets/{name}") for name in
	                       ["ArrowClusterCard.png", "AxeCard.png", "IceShrinkCard.png", "SpearCard.png",
	                        "SwordCard.png", "SwordClusterCard.png"]]

	# Pygame setup
	clock = pygame.time.Clock()

	def calculate_board_position():
		return 700, 75

	def draw_card(x, y, index, flipped, completed):
		if flipped:
			if 0 <= cards[index] < len(card_images_face_up):
				screen.blit(card_images_face_up[cards[index]], (x, y))
		elif completed:
			pass
		else:
			if 0 <= index < len(card_images_face_down):
				screen.blit(card_images_face_down[index], (x, y))

	def draw_board():
		board_x, board_y = calculate_board_position()

		for i in range(4):
			for j in range(4):
				index = i * 4 + j
				x = board_x + j * (CARD_WIDTH + 10)
				y = board_y + i * (CARD_HEIGHT + 10)
				draw_card(x, y, index, index in flipped_cards, index in completed_cards)

	match_event = pygame.USEREVENT + 1
	match_fail_event = pygame.USEREVENT + 2
	def check_match():
		if len(flipped_cards) == 2:
			if cards[flipped_cards[0]] == cards[flipped_cards[1]]:
				matched_indices = list(set(flipped_cards))
				for index in matched_indices:
					cards[index] = -1
					completed_cards.append(index)

				# Trigger match event
				pygame.event.post(pygame.event.Event(match_event))

				if all(card == -1 for card in cards):
					flipped_cards.clear()
					completed_cards.clear()

			else:
				pygame.time.set_timer(match_fail_event, 2000)

	board_x, board_y = calculate_board_position()
	while True:
		screen.fill("#dbd6d4")

		card_game_mouse_pos = pygame.mouse.get_pos()

		# Render Boss
		boss = pygame.image.load("assets/demon no background.png")
		boss = pygame.transform.scale(boss, (500, 500))
		boss_rect = boss.get_rect(center=(300, 310))
		screen.blit(boss, boss_rect)

		# Display taunt
		global taunt
		taunt_text = get_font(30).render(taunt, True, "#b68f40")
		taunt_rect = taunt_text.get_rect(center=(300, 70))
		screen.blit(taunt_text, taunt_rect)

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				# stop music
				pygame.mixer.music.stop()

				pygame.quit()
				sys.exit()

			elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
				x, y = event.pos
				# check if the click is within the board
				if board_x <= x <= board_x + 4 * (CARD_WIDTH + 10) and board_y <= y <= board_y + 4 * (
					CARD_HEIGHT + 10):
					row = (y - board_y) // (CARD_HEIGHT + 10)
					col = (x - board_x) // (CARD_WIDTH + 10)
					index = row * 4 + col

					if index not in flipped_cards and len(flipped_cards) < 2:
						# Play card flip sound effect
						card_flip_sound = pygame.mixer.Sound("assets/sounds/Flip card.mp3")
						card_flip_sound.set_volume(volume)
						card_flip_sound.play()
						flipped_cards.append(index)
						if len(flipped_cards) == 2:
							check_match()

			elif event.type == match_fail_event:
				flipped_cards.clear()
				# Change taunt
				taunt = random.choice(taunts_list)

			# Decrease health when mouse is clicked
			elif event.type == match_event:
				health -= 1
				# Play damage sound effect
				damage_sound = pygame.mixer.Sound("assets/sounds/damagesfx.mp3")
				damage_sound.set_volume(volume)
				damage_sound.play()

				# Play damage animation
				boss = pygame.image.load("assets/Demon taking damage.png")
				boss = pygame.transform.scale(boss, (500, 500))
				boss_rect = boss.get_rect(center=(300, 310))
				screen.blit(boss, boss_rect)
				# Render health bar above boss
				health_bar = pygame.image.load(f"assets/health bar/{health}_6 health bar.png")
				health_bar_rect = health_bar.get_rect(center=(300, 590))
				screen.blit(health_bar, health_bar_rect)
				pygame.display.update()
				time.sleep(0.5)

		# Render health bar above boss
		health_bar = pygame.image.load(f"assets/health bar/{health}_6 health bar.png")
		health_bar_rect = health_bar.get_rect(center=(300, 590))
		screen.blit(health_bar, health_bar_rect)

		draw_board()

		pygame.display.flip()
		clock.tick(FPS)

		# If health is 0, go to the victory screen
		if health == 0:
			time.sleep(1)
			victory()

# Countdown Loop
def countdown():
	pygame.display.set_caption("Countdown")

	while True:

		countdown_mouse_pos = pygame.mouse.get_pos()

		screen.fill("#dbd6d4")

		# Alarm Title
		alarm_title = get_font(120).render("Alarm Time", True, "#b68f40")
		alarm_title_rect = alarm_title.get_rect(center=(940, 240))
		screen.blit(alarm_title, alarm_title_rect)

		# Display alarm time in center right
		alarm_time_text = get_font(120).render(alarm_time.strftime("%H:%M"), True, "#b68f40")
		alarm_time_rect = alarm_time_text.get_rect(center=(940, 320))
		screen.blit(alarm_time_text, alarm_time_rect)

		# Display countdown to alarm time below
		time_until_alarm = alarm_time - datetime.datetime.now()
		countdown_text = get_font(60).render(str(time_until_alarm), True, "#b68f40")
		countdown_rect = countdown_text.get_rect(center=(940, 400))
		screen.blit(countdown_text, countdown_rect)

		# Render Boss
		boss = pygame.image.load("assets/demon dormant.png")
		boss = pygame.transform.scale(boss, (500, 500))
		boss_rect = boss.get_rect(center=(340, 350))
		screen.blit(boss, boss_rect)

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()

		# Go to the cardgame screen when time is up
		if time_until_alarm <= datetime.timedelta(seconds=0):
			# Render flames and play flame whoosh
			flames = pygame.image.load("assets/Flames.png")
			flames_rect = flames.get_rect(center=(640, 350))
			screen.blit(flames, flames_rect)
			flame_whoosh = pygame.mixer.Sound("assets/sounds/flame whoosh.mp3")
			flame_whoosh.set_volume(volume)
			flame_whoosh.play()
			pygame.display.update()
			card_game()

		pygame.display.update()

# Play Loop
def play():
	pygame.display.set_caption("Play")

	music_button_colour = "White"
	music_button_text = "On"

	while True:

		play_mouse_pos = pygame.mouse.get_pos()

		screen.fill("black")

		# Alarm time input display
		global alarm_time
		display_pos = (640, 260)
		alarm_time_input_text = get_font(45).render(alarm_time.strftime("%H:%M"), True, "#b68f40")
		alarm_time_input_text_rect = alarm_time_input_text.get_rect(center=display_pos)
		screen.blit(alarm_time_input_text, alarm_time_input_text_rect)

		# Alarm Title
		alarm_text = get_font(120).render("Set Alarm Time", True, "#b68f40")
		alarm_rect = alarm_text.get_rect(center=(640, display_pos[1] - 110))
		screen.blit(alarm_text, alarm_rect)

		# Volume Title and input display
		volume_text = get_font(65).render("Volume", True, "#b68f40")
		volume_rect = volume_text.get_rect(center=(640, 400))
		screen.blit(volume_text, volume_rect)
		global volume
		volume_input_text = get_font(45).render(str(round(volume*100)), True, "#b68f40")
		volume_input_text_rect = volume_input_text.get_rect(center=(640, 470))
		screen.blit(volume_input_text, volume_input_text_rect)

		# Button images
		up_arrow = pygame.image.load("assets/uparrow.png")
		up_arrow = pygame.transform.scale(up_arrow, (20, 20))

		down_arrow = pygame.image.load("assets/downarrow.png")
		down_arrow = pygame.transform.scale(down_arrow, (20, 20))

		# Button classes to change alarm time
		class UpArrow(Button):
			def __init__(self, pos):
				super().__init__(image=up_arrow, pos=pos, text_input="", font=pygame.font.SysFont("Arial", 20), base_color="White",
				                 hovering_color="Green")

		class DownArrow(Button):
			def __init__(self, pos):
				super().__init__(image=down_arrow, pos=pos, text_input="", font=pygame.font.SysFont("Arial", 20), base_color="White",
				                 hovering_color="Green")

		# Back button
		play_back = Button(image=None, pos=(640, 660), text_input="Back", font=get_font(75), base_color="White",
		                   hovering_color="Green")

		# Confirm alarm button
		confirm_alarm = Button(image=None, pos=(640, 330), text_input="Start!", font=get_font(75),
		                       base_color="White", hovering_color="Green")

		plus_one_min = UpArrow(pos=(display_pos[0] + 35, display_pos[1] - 25))
		minus_one_min = DownArrow(pos=(display_pos[0] + 35, display_pos[1] + 25))
		plus_ten_min = UpArrow(pos=(display_pos[0] + 15, display_pos[1] - 25))
		minus_ten_min = DownArrow(pos=(display_pos[0] + 15, display_pos[1] + 25))
		plus_one_hour = UpArrow(pos=(display_pos[0] - 15, display_pos[1] - 25))
		minus_one_hour = DownArrow(pos=(display_pos[0] - 15, display_pos[1] + 25))
		plus_ten_hours = UpArrow(pos=(display_pos[0] - 35, display_pos[1] - 25))
		minus_ten_hours = DownArrow(pos=(display_pos[0] - 35, display_pos[1] + 25))

		plus_volume = UpArrow(pos=(640, 470-25))
		minus_volume = DownArrow(pos=(640, 470+25))

		toggle_music = Button(image=None, pos=(640, 550), text_input=f"Music: {music_button_text}",
		                      font=get_font(75), base_color=music_button_colour, hovering_color="Green")

		buttons = [plus_one_min,
		           minus_one_min,
		           plus_ten_min,
		           minus_ten_min,
		           plus_one_hour,
		           minus_one_hour,
		           plus_ten_hours,
		           minus_ten_hours,
		           play_back,
		           confirm_alarm,
		           plus_volume,
		           minus_volume,
		           toggle_music,

		           ]

		# Update buttons
		for button in buttons:
			button.changeColor(play_mouse_pos)
			button.update(screen)

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
				if play_back.checkForInput(play_mouse_pos):
					main_menu()
				if confirm_alarm.checkForInput(play_mouse_pos):
					countdown()

				# Change alarm time
				if plus_one_min.checkForInput(play_mouse_pos):
					# Add 1 minute to alarm time
					alarm_time = alarm_time + datetime.timedelta(minutes=1)
				if minus_one_min.checkForInput(play_mouse_pos):
					# Subtract 1 minute from alarm time
					alarm_time = alarm_time - datetime.timedelta(minutes=1)
				if plus_ten_min.checkForInput(play_mouse_pos):
					# Add 10 minutes to alarm time
					alarm_time = alarm_time + datetime.timedelta(minutes=10)
				if minus_ten_min.checkForInput(play_mouse_pos):
					# Subtract 10 minutes from alarm time
					alarm_time = alarm_time - datetime.timedelta(minutes=10)
				if plus_one_hour.checkForInput(play_mouse_pos):
					# Add 1 hour to alarm time
					alarm_time = alarm_time + datetime.timedelta(hours=1)
				if minus_one_hour.checkForInput(play_mouse_pos):
					# Subtract 1 hour from alarm time
					alarm_time = alarm_time - datetime.timedelta(hours=1)
				if plus_ten_hours.checkForInput(play_mouse_pos):
					# Add 10 hours to alarm time
					alarm_time = alarm_time + datetime.timedelta(hours=10)
				if minus_ten_hours.checkForInput(play_mouse_pos):
					# Subtract 10 hours from alarm time
					alarm_time = alarm_time - datetime.timedelta(hours=10)

				# Change volume
				if plus_volume.checkForInput(play_mouse_pos):
					# Add 0.1 to volume
					if volume <= 0.9:
						volume += 0.1
				if minus_volume.checkForInput(play_mouse_pos):
					# Subtract 0.1 from volume
					if volume >= 0.1:
						volume -= 0.1

				# Toggle music
				if toggle_music.checkForInput(play_mouse_pos):
					global music
					music = not music
					if music:
						music_button_colour = "White"
						music_button_text = "On"
						toggle_music.update(screen)
					else:
						music_button_colour = "Red"
						music_button_text = "Off"
						toggle_music.update(screen)

		pygame.display.update()

# Main Menu Loop
def main_menu():
	pygame.display.set_caption("Main Menu")

	while True:
		screen.blit(BG, (0, 0))

		menu_mouse_pos = pygame.mouse.get_pos()

		menu_title = pygame.image.load("assets/title text.png")
		menu_rect = menu_title.get_rect(center=(640, 300))

		play_button = Button(image=pygame.image.load("assets/set alarm button _UPDATED_.png"), pos=(640, 480),
							text_input="", font=get_font(75), base_color="#d7fcd4", hovering_color="White")
		quit_button = Button(image=pygame.image.load("assets/quit button.png"), pos=(640, 595),
		                     text_input="", font=get_font(75), base_color="#d7fcd4", hovering_color="White")

		screen.blit(menu_title, menu_rect)

		for button in [play_button, quit_button]:
			button.changeColor(menu_mouse_pos)
			button.update(screen)

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
				if play_button.checkForInput(menu_mouse_pos):
					play()
				elif quit_button.checkForInput(menu_mouse_pos):
					pygame.quit()
					sys.exit()

		pygame.display.update()

if __name__ == "__main__":
	main_menu()


from huggingface_hub import from_pretrained_keras
from tensorflow import keras
from PIL import Image
import numpy as np
import io
import os

def create_model() -> keras.Model:
    return from_pretrained_keras("keras-io/lowlight-enhance-mirnet")

def run_model(image_bytes: io.BytesIO, model: keras.Model) -> Image.Image:
    image = Image.open(image_bytes)
    width, height = image.size
    image = image.resize((960, 640))
    image_array = np.expand_dims(keras.utils.img_to_array(image).astype("float32") / 255.0, axis=0)
    output = model.predict(image_array)
    output_image_array = (output[0] * 255.0).clip(0, 255)
    output_image_array = output_image_array.reshape(
        (np.shape(output_image_array)[0], np.shape(output_image_array)[1], 3)
    ).astype(np.uint8)
    output_image = Image.fromarray(output_image_array).resize((width, height))

    if not os.path.exists("user_data"):
        os.makedirs("user_data")
    output_image.save("user_data/output.jpg")

    return output_image


"""
XML utilities.
"""

import os

from lxml import etree

from alto2txt import xslts

METS_18_XSLT = "extract_text_mets18.xslt"
""" METS 1.8 XSLT """
METS_13_XSLT = "extract_text_mets13.xslt"
""" METS 1.3 XSLT """
BLN_XSLT = "extract_text_bln.xslt"
""" BLN XSLT """
UKP_XSLT = "extract_text_ukp.xslt"
""" UKP XSLT """

XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
""" XML Schema Instance namespace """
SCHEMA_LOCATION = etree.QName(XSI_NS, "schemaLocation")
""" schemaLocation element """
NO_NS_SCHEMA_LOCATION = etree.QName(XSI_NS, "noNamespaceSchemaLocation")
""" noNamespaceSchemaLocation element """

METS_NS = "http://www.loc.gov/METS/"
""" METS namespace """
METS_18_URI = "http://www.loc.gov/standards/mets/version18/mets.xsd"
""" METS 1.8 schemaLocation """
METS_13_URI = "http://schema.ccs-gmbh.com/docworks/mets-metae.xsd"
""" METS 1.3 schemaLocation """
METS_ROOT = etree.QName(METS_NS, "mets")
""" METS root element """
ALTO_ROOT = "alto"
""" ALTO root element """
BLN_ROOT = "BL_newspaper"
""" BLN root element """
BLN_PAGE_XPATH = "/BL_newspaper/BL_page"
""" XPath for BLN BL_page element """
UKP_NS = "http://tempuri.org/ncbpissue"
""" UKP namespace """
UKP_ROOT = etree.QName(UKP_NS, "UKP")
""" UKP root element """

LWM_NS = {"ukp": UKP_NS, "mets": METS_NS}
""" Namespaces of documents within Living with Machines datasets. """

XML_ROOT = "root"
""" XML metadata key. """
XML_DOCTYPE = "doctype"
""" XML metadata key. """
XML_NS = "namespaces"
""" XML metadata key. """
XML_NO_NS_SCHEMA_LOCATION = "no_ns_schema_location"
""" XML metadata key. """
XML_SCHEMA_LOCATIONS = "schema_locations"
""" XML metadata key. """

RE_METS = "(.*)[-|_](mets|METS).xml$"
""" Regular expression for METS file """

def get_path(module, *name):
    """
    Gets path to file in module, given module and relative path.

    :param module: module
    :type module: module
    :param *name: file name components
    :type *name: str
    :return: path to file
    :rtype: str
    """
    return os.path.join(os.path.dirname(module.__file__), *name)

def load_xslts():
    """
    Loads XSLTs and returns in a dictionary.

    The following XSLT files need to be in an extract_text.xslts
    module:

    * extract_text_mets18.xslt: METS 1.8 XSL file.
    * extract_text_mets13.xslt: METS 1.3 XSL file.
    * extract_text_bln.xslt: BLN XSL file.
    * extract_text_ukp.xslt: BLN UKP file.

    :return: XSLTs
    :rtype: dict(str: lxml.etree.XSLT)
    """
    xsl_transforms = {}
    for xslt_name in [METS_18_XSLT, METS_13_XSLT, BLN_XSLT, UKP_XSLT]:
        xslt_file = get_path(xslts, xslt_name)
        xsl_transforms[xslt_name] = etree.XSLT(etree.parse(xslt_file))
    return xsl_transforms

def get_xml(filename):
    """
    Gets XML document tree from file.

    :param filename: XML filename
    :type filename: str
    :return: Document tree
    :rtype: lxml.etree._ElementTree
    """
    with open(filename, "r") as f:
        document_tree = None
        parser = etree.XMLParser()
        document_tree = etree.parse(f, parser)
    return document_tree

def get_xml_metadata(document_tree):
    """
    Extracts information (root element, namespaces, schema locations,
    default schema location) from XML document tree. Returns dict of
    form:

        {
            doctype: <DOCTYPE>,
            namespaces: {<TAG>: <URL>, <TAG>: <URL>, ...},
            no_ns_schema_location: <URL> | None,
            root: <ROOT_ELEMENT>,
            schema_locations: {<URL>: <URL>, ...}
        }

    :param document_tree: Document tree
    :type document_tree: lxml.etree._ElementTree
    :return: metadata
    :rtype: dict
    """
    root_element = document_tree.getroot()
    root_element_tag = str(root_element.tag)
    doctype = str(document_tree.docinfo.doctype)
    namespaces = root_element.nsmap
    no_ns_schema_location = root_element.get(NO_NS_SCHEMA_LOCATION.text)
    schema_locations = root_element.get(SCHEMA_LOCATION.text)

    if schema_locations is not None:
        # Convert schema_locations from "namespaceURI schemaURI ..."
        # to dictionary with namespaceURI:schemaURI
        uris = schema_locations.split(" ")
        schema_locations = {uris[i]: uris[i + 1] for i in range(0, len(uris), 2)}
    else:
        schema_locations = {}
    metadata = {}
    metadata[XML_ROOT] = root_element_tag
    metadata[XML_DOCTYPE] = doctype
    metadata[XML_NS] = namespaces
    metadata[XML_NO_NS_SCHEMA_LOCATION] = no_ns_schema_location
    metadata[XML_SCHEMA_LOCATIONS] = schema_locations
    return metadata

def query_xml(document_tree, query):
    """
    Runs XPath query and returns results.

    Query string can use namespace prefixes of "ukp" and "mets"
    (as defined in LWM_NS).

    :param document_tree: Document tree
    :type document_tree: lxml.etree._ElementTree
    :param query: XPath query
    :type query: str
    :return: Query results
    :rtype: Query-specific
    """
    root_element = document_tree.getroot()
    result = root_element.xpath(query, namespaces=LWM_NS)
    return result


#Working withe text files

'''
fo=open('newdemo.txt','w')
#print(fo.mode)
#print(fo.readable())
#print(fo.writable())
fo.close()
'''
'''
my_content=["This is data -1\n","This is data -2\n","This is data-3"]
fo=open('newdemo.txt','a')
fo.write("I am adding the new data\n")
fo.write("I am adding the first data\n")
#fo.writelines(my_content)
fo.close()
'''
'''
my_content=["This is data -1\n","This is data -2\n","This is data-3"]
fo=open('newdemo.txt','w')
for each_lines in my_content:
    fo.write(each_lines+"\n")
fo.close()
'''
'''
fo=open('newdemo.txt','r')
data=fo.read()
fo.close()
print(data)
'''
'''
fo=open('newdemo.txt','r')
print(fo.readline())
print(fo.readline())
print(fo.readline())
fo.close()
'''
'''
fo=open('newdemo.txt','r')
data=fo.readlines()
fo.close()
print(data[-1])

'''
'''
fo=open('newdemo.txt','r')
data=fo.readlines()
for eachlines in range(3):
    print(data[eachlines])
fo.close()
'''

#sfile="newdemo.txt"
#dfile="random.txt"
sfile=input("Enter sfile:")
dfile=input("Enter dfile:")
sfo=open(sfile,'r')
content=sfo.read()
sfo.close()
dfo=open(dfile,'w')
dfo.write(content)
dfo.close()


import sqlite3

def singleton(cls):
    instances = {}

    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]

    return getinstance

class DatabaseDriver(object):
    """
    Database driver for our app.
    Handles with reading and writing data with the database.
    """

    def __init__(self):
        """
        Secures a connection with the database and stores it into the
        instance variable `conn`
        """
        self.conn = sqlite3.connect("todo.db", check_same_thread=False)
        self.create_location_table()
        self.create_restaurant_table()
        self.create_review_table()

    # -- TASKS -----------------------------------------------------------

    def create_location_table(self):
        """
        Create a table to general locations (e.g. North, South, CTown) and prepopulate table with some locations
        """
        try:
            self.conn.execute("""DROP TABLE IF EXISTS location; """)
            self.conn.execute(
                """
                CREATE TABLE IF NOT EXISTS location(
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL
                );
                """
            )
            self.conn.execute("INSERT INTO location (name) VALUES ('North Campus'); ")
            self.conn.execute("INSERT INTO location (name) VALUES ('West Campus');")
            self.conn.execute("INSERT INTO location (name) VALUES ('Central Campus'); ")
            self.conn.execute(
                " INSERT INTO location (name) VALUES ('Collegetown'); "
            )
            self.conn.execute("INSERT INTO location (name) VALUES ('Downtown'); ")
            self.conn.execute("INSERT INTO location (name) VALUES ('Other'); ")
            self.conn.commit()
        except Exception as e:
            print("error creating location table " + str(e))

    def create_restaurant_table(self):
        """
        Create a table to store dining halls / restaurants
        """
        try:
            self.conn.execute("""DROP TABLE IF EXISTS restaurant; """)
            self.conn.execute(
                """
                CREATE TABLE IF NOT EXISTS restaurant(
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    description TEXT NOT NULL,
                    cuisine TEXT,
                    address TEXT NOT NULL,
                    image TEXT,
                    rating REAL NOT NULL,
                    location_id INTEGER NOT NULL,
                    FOREIGN KEY(location_id) REFERENCES location(id) ON DELETE CASCADE
                );
                """
            )
            self.conn.commit()
        except Exception as e:
            print("error creating restaurant table " + str(e))

    def create_review_table(self):
        """
        Create a table to store restaurant reviews
        """
        try:
            self.conn.execute("""DROP TABLE IF EXISTS review; """)
            self.conn.execute(
                """
                CREATE TABLE IF NOT EXISTS review(
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    date_created DATE NOT NULL,
                    service INTEGER NOT NULL,
                    decor INTEGER NOT NULL,
                    food INTEGER NOT NULL,
                    description TEXT NOT NULL,
                    restaurant_id INTEGER NOT NULL,
                    FOREIGN KEY(restaurant_id) REFERENCES restaurant(id) ON DELETE CASCADE
                );
                """
            )
        except Exception as e:
            print("error creating review table " + str(e))

    def get_locations(self):
        """
        Return a list of all available locations, each as a dictionary of form {"id":id,"name":name}.
        """
        cursor = self.conn.execute(
            """
            SELECT *
            FROM location;
        """
        )
        return [{"id": row[0], "name": row[1]} for row in cursor]

    def get_location(self, location_id):
        """
        Return the location that has id location_id if the corresponding location exists, and return None otherwise.
        """
        row = self.conn.execute(
            """
            SELECT *
            FROM location
            WHERE id = ?;
            """,
            (location_id,),
        ).fetchone()
        if row is None:
            return None
        return {"id": row[0], "name": row[1]}

    def get_restaurant(self, restaurant_id):
        """
        Return the restaurant that has id restaurant_id if the corresponding location exists, and return None
        otherwise. The returned restaurant will be a dictionary of form
        {"id":id,"description":description",
        "cuisine":cuisine,"address":address,"image":image, "rating":rating,"location_id":location_id}
        """
        row = self.conn.execute(
            """
            SELECT *
            FROM restaurant
            WHERE id = ?;
            """,
            (restaurant_id,),
        ).fetchone()
        if row is None:
            return None
        restaurant = {"id": row[0], "name":row[1], "description": row[2], "cuisine": row[3], "address": row[4], "image": row[5],
                      "rating": row[6], "location_id": row[7]}
        cursor = self.conn.execute(
            """
            SELECT *
            FROM review
            WHERE restaurant_id=?;
            """,
            (restaurant["id"],),
        )
        restaurant["reviews"] = [
            {
                "date_created": row[0],
                "service": row[1],
                "decor": row[2],
                "food": row[3],
                "description": row[4],
            }
            for row in cursor
        ]
        return restaurant

    def get_restaurants_of_location(self, location_id):
        """
        Return a list of all restaurants in the location with id location_id, each as a dictionary of form
        {"id":id,"description":description",
        "cuisine":cuisine,"address":address,"image":image, "rating":rating,"location_id":location_id}
        Requires that location_id must correspond to a valid location.
        """
        cursor = self.conn.execute(
            """
            SELECT id
            FROM restaurant
            WHERE location_id=?;""",
            (location_id,),
        )
        return [self.get_restaurant(row[0]) for row in cursor]

    def create_restaurant(self, name, description, location_id, address, cuisine, image, rating):
        """
        Creates a new restaurant in the restaurant table.
        """
        cursor = self.conn.execute(
            """
            INSERT INTO restaurant (name, description, cuisine, address, image, rating, location_id)
            VALUES (?, ?, ?, ?, ?, ?, ?)""",
            (name, description, cuisine, address, image, rating, location_id)
        )
        self.conn.commit()
        return self.get_restaurant(cursor.lastrowid)

    def delete_review(self, restaurant_id):
        """
        Deletes a restaurant associated with id restaurant_id and returns the restaurant
        """
        self.conn.execute(
            """
            DELETE
            FROM restaurant
            WHERE id=?;
            """,
            (restaurant_id,),
        )
        self.conn.commit()

# Only <=1 instance of the database driver
# exists within the app at all times
DatabaseDriver = singleton(DatabaseDriver)


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

import os
import glob
import sys
import setuptools

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext

PYNUCLEUS_VERSION = '0.65'
PYNUCLEUS_REPOSITORY_URL = 'https://bitbucket.org/vusec/nucleus'

# Description
PYNUCLEUS_DESCRIPTION = """PyNucleus
=========

.. image:: https://img.shields.io/pypi/v/pynucleus.svg
    :target: https://pypi.python.org/pypi/pynucleus

Nucleus function detector bindings for Python 2.x and 3.x.
More information at: https://bitbucket.org/vusec/nucleus
"""

__version__ = PYNUCLEUS_VERSION

class get_pybind_include(object):
    """
    Helper class to determine the pybind11 include path

    The purpose of this class is to postpone importing pybind11
    until it is actually installed, so that the ``get_include()``
    method can be invoked.
    """
    def __init__(self, user=False):
        self.user = user

    def __str__(self):
        import pybind11
        return pybind11.get_include(self.user)

# As of Python 3.6, CCompiler has a `has_flag` method.
# cf http://bugs.python.org/issue26689
def has_flag(compiler, flagname):
    """
    Return a boolean indicating whether a flag name is supported on
    the specified compiler.
    """
    import tempfile
    with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:
        f.write('int main (int argc, char **argv) { return 0; }')
        try:
            compiler.compile([f.name], extra_postargs=[flagname])
        except setuptools.distutils.errors.CompileError:
            return False
    return True

def cpp_flag(compiler):
    """
    Return the -std=c++[11/14] compiler flag.
    The c++14 is prefered over c++11 (when it is available).
    """
    if has_flag(compiler, '-std=c++14'):
        return '-std=c++14'
    elif has_flag(compiler, '-std=c++11'):
        return '-std=c++11'
    else:
        raise RuntimeError(
            'Unsupported compiler -- at least C++11 support is needed!')

class BuildExt(build_ext):
    """
    A custom build extension for adding compiler-specific options.
    """
    c_opts = {
        'msvc': ['/EHsc'],
        'unix': [],
    }
    if sys.platform == 'darwin':
        c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7']

    def build_extensions(self):
        ct = self.compiler.compiler_type
        opts = self.c_opts.get(ct, [])
        if ct == 'unix':
            opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version())
            opts.append(cpp_flag(self.compiler))
            if has_flag(self.compiler, '-fvisibility=hidden'):
                opts.append('-fvisibility=hidden')
        elif ct == 'msvc':
            opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version())
        for ext in self.extensions:
            ext.extra_compile_args = opts
        build_ext.build_extensions(self)

# Sources
sources = ['bindings.cc']
for name in glob.glob('../../*.cc'):
    sources.append(name)

# Modules
ext_modules = [
    Extension(
        'nucleus',
        sources,
        include_dirs=[
            # Path to pybind11 headers
            get_pybind_include(),
            get_pybind_include(user=True)
        ],
        libraries=[
            'capstone',
            'bfd-multiarch'
        ],
        language='c++'
    ),
]

setup(
    name='pynucleus',
    version=PYNUCLEUS_VERSION,
    description='Bindings for the Nucleus function detector',
    long_description=PYNUCLEUS_DESCRIPTION,
    license='BSD (3-clause)',
    author='Dennis Andriesse',
    maintainer='Alexandro Sanchez Bach',
    maintainer_email='alexandro@phi.nz',
    url=PYNUCLEUS_REPOSITORY_URL,
    ext_modules=ext_modules,
    install_requires=['pybind11>=2.2'],
    cmdclass={'build_ext': BuildExt},
    zip_safe=False,
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Natural Language :: English',
    ],
)


from bs4 import BeautifulSoup as bs
import requests
from selenium import webdriver
from directoryassistor import DirectoryAssistor
import time
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import textract
import pandas as pd
from nltk.corpus import stopwords
from sifter import ContractSifter
from pipeline import ContractPipeline
import pandas as pd
import scipy.stats as stats
import matplotlib
from sklearn.preprocessing import normalize

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 12}

matplotlib.rc('font', **font)

plt.style.use('tableau-colorblind10')

def make_sns_bar_plot(ax, cols, labels, title, color='blue', label=None):
    """
    Creates a seaborn bar plot

    Parameters:
    ax = axes for the plot
    df = dataframe for the data
    col_name = str name of the dataframe column for the heights
    labels = str name of the dataframe column for the x axis labels
    color = color for the bars in the graph
    label = label the graph

    Returns:
    Bar plot
    """
    tick_loc = np.arange(len(labels))
    xlabel = labels
    sns.barplot(tick_loc, cols, color=color, ax=ax, label=label)
    ax.set_xticks(ticks=tick_loc)
    ax.set_xticklabels([str(x) for x in xlabel], rotation= 45, fontsize=14,
                        horizontalalignment='right')
    ax.set_title(title, fontsize=20)

def make_bar_plot(ax, cols, labels, title, color='blue', label=None):
    """
    Creates a matplotlib bar plot

    Parameters:
    ax = axes for the plot
    df = dataframe for the data
    col_name = str name of the dataframe column for the heights
    labels = str name of the dataframe column for the x axis labels
    color = color for the bars in the graph
    label = label the graph

    Returns:
    Bar plot
    """
    tick_loc = np.arange(len(labels))
    xlabel = labels
    ax.bar(tick_loc, cols, color=color, label=label)
    ax.set_xticks(ticks=tick_loc)
    ax.set_xticklabels([str(x) for x in xlabel], rotation= 45, fontsize=14)
    ax.set_title(title, fontsize=20)

def pad_dic_list(dic, pad):
    """
    Pads dictionary so that all columns have the same number of rows

    Params
    dic: dictionary to be padded
    pad: value to pad with

    Returns
    The padded dictionary
    """
    lmax = 0
    for lname in dic.keys():
        lmax = max(lmax, len(dic[lname]))
    for lname in dic.keys():
        ll = len(dic[lname])
        if ll < lmax:
            dic[lname] += [pad] * (lmax - ll)
    return dic

def create_contract_graph(directory, title):
    """
    Generates a bar graph with the labels as the folders in the directory and the
    bar heights as the number of documents in each folder

    Params
    directory: str where the folders are located
    title: str title for bar graph
    """
    ds = DirectoryAssistor()
    folder_lst = ds.create_content_list(directory)
    folder_dic = {}
    for folder in folder_lst:
        folder_dic[folder] = len(ds.create_content_list(directory+folder))
    sort_folder_dic= sorted(folder_dic.items(), key=lambda x: x[1], reverse=True)
    cols = []
    labels = []
    for i in sort_folder_dic:
        labels.append(i[0])
        cols.append(i[1])
    fig, ax = plt.subplots(figsize=(10,10))
    # cols = list(new_dic.values())
    # labels = list(new_dic.keys())
    make_sns_bar_plot(ax, cols, labels, title=title)

def word_counts(individual_bag):
    """
    Returns the mean, avg, max, and min of the unique word count for all of
    the contract classes

    Params
    individual_bag: dictionary with the keys as the contract type and the values
    are a bag of words for all the contracts for that type
    """
    contract_dic = {}
    for key, val in individual_bag.items():
        contract_dic[key] = len(val)
    unique_word_lst = list(contract_dic.values())
    word_mean = np.mean(unique_word_lst)
    word_std = np.std(unique_word_lst)
    max_words = np.max(unique_word_lst)
    min_words = np.min(unique_word_lst)

    return word_mean, word_std, max_words, min_words

def graph_word_dist(individual_bag):
    """
    Returns a distribution graph of the unique words for each of the classes

    Params
    individual_bag: dictionary with the keys as the contract type and the values
    are a bag of words for all the contracts for that type
    """

    mu, sig, max_words, min_words = word_counts(individual_bag)
    print(f'The average number of unique words per contract type is {mu} with a \
standard devaition of {sig}.  The max and min number of unique words were {max_words},\
and {min_words}')
    x_axis = np.linspace(-3*sig, 6*sig, 100)
    norm = stats.norm(mu, sig)

    fig, ax = plt.subplots()
    ax.plot(x_axis, norm.pdf(x_axis))
    ax.set_title('Distribution of Unique Words', fontsize=16)
    plt.tight_layout()
    plt.show()

def true_pos(row, col1, col2):
    if row[col1] == row[col2]:
        return 1
    else:
        return 0

def true_neg(row, col1, col2):
    if row[col1] != row[col2]:
        return 1
    else:
        return 0

execute = True
if __name__ == "__main__" and execute:

   df = pd.read_csv('../data/optimized_predictions.csv')
   df.drop(columns='Unnamed: 0', inplace=True)
   df['Correct'] = df.apply(lambda row: true_pos(row, 'True Label', 'Predicted Label'), axis=1)
   df['Incorrect'] = df.apply(lambda row: true_neg(row, 'True Label', 'Predicted Label'), axis=1)
   contract_group = df.groupby('True Label').sum().sort_values('Correct', ascending=True)

   contract_group.plot(kind='barh', stacked=True, figsize=(10,6), linewidth=1,
                       align='center', width=.5, alpha=.7)

   plt.legend(bbox_to_anchor=(.8,1.01), fontsize=25)
   plt.tight_layout()
   plt.xlabel('Predicted Count', fontsize=30, weight='bold')
#    plt.ylabel('Contract Class',fontsize=30, weight='bold')
   ax1 = plt.axes()
   y_axis = ax1.yaxis
   y_axis.label.set_visible(False)
#    y_axis = plt.axes.get_yaxis()
#    y_label = y_axis.get_label()
   plt.xticks(fontsize=30, weight="bold")
   plt.yticks(fontsize=30, weight="bold")
   plt.title('Predictions', fontsize=40, weight='bold')
   plt.show()

    # x = np.arange(1,8, step=1)
    # y = [0.862,0.894,0.894,0.901,0.901,.9,.898]

    # fig, ax = plt.subplots(figsize=(8,8))
    # ax.plot(x,y)
    # ax.set_title('Optimization Plot', fontsize=40, weight='bold')
    # plt.xlabel('# of Words', fontsize=30, weight='bold')
    # plt.ylabel('Accuracy',fontsize=30, weight='bold')
    # plt.xticks(fontsize=16)
    # plt.yticks(fontsize=20)
    # plt.tight_layout()
    # plt.show()


# Function to find the length of the longest substring without repeating characters.
def longestUniqueSubstr(str):
    n = len(str)
    max_length = 0
    max_start = 0
    start = 0
    char_index = {}

    for i in range(n):
        if str[i] in char_index and char_index[str[i]] >= start:
            start = char_index[str[i]] + 1

        char_index[str[i]] = i

        if i - start + 1 > max_length:
            max_length = i - start + 1
            max_start = start

    return str[max_start:max_start+max_length]

# Main function to read input from the command line
if __name__ == '__main__':
    input_str = input("input: ")
    output_str = longestUniqueSubstr(input_str)
    print("output:", output_str, "length:", len(output_str))


from tkinter import *
import os
import sys
import threading

class TK(object):
    def __init__(self):
        self.root = Tk()

        # 创建菜单条
        menubar = Menu(self.root)
        # 创建绑定变量
        self.menu = StringVar()
        filemenu = Menu(menubar, tearoff=0)
        for item in ['文件', '打开1', '打开2']:
            filemenu.add_radiobutton(label=item, variable=self.menu, command=self.OpenFile)
        menubar.add_cascade(label='File', menu=filemenu)

        func = Menu(menubar, tearoff=0)
        for item01 in ['同步', '导出', '导入']:
            func.add_radiobutton(label=item01, variable=self.menu, command=self.OpenFile)
        menubar.add_cascade(label='Func', menu=func)
        self.root['menu'] = menubar

        self.root.mainloop()
    def OpenFile(self):
        print(self.menu.get())

def main():

    tk = TK()
    # t = threading.Thread(target=tk.OpenFile)
    # t.start()
    # t.join()

if __name__ == '__main__':
    main()


import requests, json, re
from datetime import date

re_name = r'(?<=title=")(.*?)(?=")'
re_country = r'(?<=\n)[\w ]+(?=.*	)'
re_last = r'[\d.,]+(?=
)'
re_change = r'(?<=>)[\d.-]+(?=
)'
re_percent = r'(?<=>)[\d.-]+%(?=)'

queries = [re_name,re_country,re_last,re_change,re_percent]

stock_url = "https://markets.businessinsider.com/indices"
stock_file = "stocks.json"
key_file = "stock_countries.json"

def crawl():
    today = date.today().strftime("%Y-%m-%d")

    stockPage = requests.get(stock_url)
    substr = r'' in entry]
    results = []

    for entry in entries:
        results.append([re.search(query,entry).group(0) for query in queries]+[today])

    countries = {}
    for result in results:
        if result[1] in countries:
            countries[result[1]].append(result[0])
        else:
            countries[result[1]] = [result[0]]

    with open(key_file, "w") as f: json.dump(countries, f)
    with open(stock_file, "w") as f: json.dump([["Name","Country","Last","+/-",'%',"Date"]]+results,f)

if __name__ == '__main__':
    crawl()


import os
import math

import torch
import torch.nn as nn

class MultiHeadedAttentionSANM(nn.Module):
    def __init__(self, model):
        super().__init__()
        self.d_k = model.d_k
        self.h = model.h
        self.linear_out = model.linear_out
        self.linear_q_k_v = model.linear_q_k_v
        self.fsmn_block = model.fsmn_block
        self.pad_fn = model.pad_fn

        self.attn = None
        self.all_head_size = self.h * self.d_k

    def forward(self, x, mask):
        mask_3d_btd, mask_4d_bhlt = mask
        q_h, k_h, v_h, v = self.forward_qkv(x)
        fsmn_memory = self.forward_fsmn(v, mask_3d_btd)
        q_h = q_h * self.d_k**(-0.5)
        scores = torch.matmul(q_h, k_h.transpose(-2, -1))
        att_outs = self.forward_attention(v_h, scores, mask_4d_bhlt)
        return att_outs + fsmn_memory

    def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
        new_x_shape = x.size()[:-1] + (self.h, self.d_k)
        x = x.view(new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward_qkv(self, x):
        q_k_v = self.linear_q_k_v(x)
        q, k, v = torch.split(q_k_v, int(self.h * self.d_k), dim=-1)
        q_h = self.transpose_for_scores(q)
        k_h = self.transpose_for_scores(k)
        v_h = self.transpose_for_scores(v)
        return q_h, k_h, v_h, v

    def forward_fsmn(self, inputs, mask):
        # b, t, d = inputs.size()
        # mask = torch.reshape(mask, (b, -1, 1))
        inputs = inputs * mask
        x = inputs.transpose(1, 2)
        x = self.pad_fn(x)
        x = self.fsmn_block(x)
        x = x.transpose(1, 2)
        x = x + inputs
        x = x * mask
        return x

    def forward_attention(self, value, scores, mask):
        scores = scores + mask

        self.attn = torch.softmax(scores, dim=-1)
        context_layer = torch.matmul(self.attn, value)  # (batch, head, time1, d_k)

        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(new_context_layer_shape)
        return self.linear_out(context_layer)  # (batch, time1, d_model)

def preprocess_for_attn(x, mask, cache, pad_fn, kernel_size):
    x = x * mask
    x = x.transpose(1, 2)
    if cache is None:
        x = pad_fn(x)
    else:
        x = torch.cat((cache, x), dim=2)
        cache = x[:, :, -(kernel_size-1):]
    return x, cache

torch_version = tuple([int(i) for i in torch.__version__.split(".")[:2]])
if torch_version >= (1, 8):
    import torch.fx
    torch.fx.wrap('preprocess_for_attn')

class MultiHeadedAttentionSANMDecoder(nn.Module):
    def __init__(self, model):
        super().__init__()
        self.fsmn_block = model.fsmn_block
        self.pad_fn = model.pad_fn
        self.kernel_size = model.kernel_size
        self.attn = None

    def forward(self, inputs, mask, cache=None):
        x, cache = preprocess_for_attn(inputs, mask, cache, self.pad_fn, self.kernel_size)
        x = self.fsmn_block(x)
        x = x.transpose(1, 2)

        x = x + inputs
        x = x * mask
        return x, cache

class MultiHeadedAttentionCrossAtt(nn.Module):
    def __init__(self, model):
        super().__init__()
        self.d_k = model.d_k
        self.h = model.h
        self.linear_q = model.linear_q
        self.linear_k_v = model.linear_k_v
        self.linear_out = model.linear_out
        self.attn = None
        self.all_head_size = self.h * self.d_k

    def forward(self, x, memory, memory_mask):
        q, k, v = self.forward_qkv(x, memory)
        scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
        return self.forward_attention(v, scores, memory_mask)

    def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
        new_x_shape = x.size()[:-1] + (self.h, self.d_k)
        x = x.view(new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward_qkv(self, x, memory):
        q = self.linear_q(x)

        k_v = self.linear_k_v(memory)
        k, v = torch.split(k_v, int(self.h * self.d_k), dim=-1)
        q = self.transpose_for_scores(q)
        k = self.transpose_for_scores(k)
        v = self.transpose_for_scores(v)
        return q, k, v

    def forward_attention(self, value, scores, mask):
        scores = scores + mask

        self.attn = torch.softmax(scores, dim=-1)
        context_layer = torch.matmul(self.attn, value)  # (batch, head, time1, d_k)

        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(new_context_layer_shape)
        return self.linear_out(context_layer)  # (batch, time1, d_model)

class OnnxMultiHeadedAttention(nn.Module):
    def __init__(self, model):
        super().__init__()
        self.d_k = model.d_k
        self.h = model.h
        self.linear_q = model.linear_q
        self.linear_k = model.linear_k
        self.linear_v = model.linear_v
        self.linear_out = model.linear_out
        self.attn = None
        self.all_head_size = self.h * self.d_k

    def forward(self, query, key, value, mask):
        q, k, v = self.forward_qkv(query, key, value)
        scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
        return self.forward_attention(v, scores, mask)

    def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
        new_x_shape = x.size()[:-1] + (self.h, self.d_k)
        x = x.view(new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward_qkv(self, query, key, value):
        q = self.linear_q(query)
        k = self.linear_k(key)
        v = self.linear_v(value)
        q = self.transpose_for_scores(q)
        k = self.transpose_for_scores(k)
        v = self.transpose_for_scores(v)
        return q, k, v

    def forward_attention(self, value, scores, mask):
        scores = scores + mask

        self.attn = torch.softmax(scores, dim=-1)
        context_layer = torch.matmul(self.attn, value)  # (batch, head, time1, d_k)

        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(new_context_layer_shape)
        return self.linear_out(context_layer)  # (batch, time1, d_model)

class OnnxRelPosMultiHeadedAttention(OnnxMultiHeadedAttention):
    def __init__(self, model):
        super().__init__(model)
        self.linear_pos = model.linear_pos
        self.pos_bias_u = model.pos_bias_u
        self.pos_bias_v = model.pos_bias_v

    def forward(self, query, key, value, pos_emb, mask):
        q, k, v = self.forward_qkv(query, key, value)
        q = q.transpose(1, 2)  # (batch, time1, head, d_k)

        p = self.transpose_for_scores(self.linear_pos(pos_emb)) # (batch, head, time1, d_k)

        # (batch, head, time1, d_k)
        q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)
        # (batch, head, time1, d_k)
        q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)

        # compute attention score
        # first compute matrix a and matrix c
        # as described in https://arxiv.org/abs/1901.02860 Section 3.3
        # (batch, head, time1, time2)
        matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))

        # compute matrix b and matrix d
        # (batch, head, time1, time1)
        matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
        matrix_bd = self.rel_shift(matrix_bd)

        scores = (matrix_ac + matrix_bd) / math.sqrt(
            self.d_k
        )  # (batch, head, time1, time2)

        return self.forward_attention(v, scores, mask)

    def rel_shift(self, x):
        zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype)
        x_padded = torch.cat([zero_pad, x], dim=-1)

        x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2))
        x = x_padded[:, :, 1:].view_as(x)[
            :, :, :, : x.size(-1) // 2 + 1
        ]  # only keep the positions from 0 to time2
        return x

    def forward_attention(self, value, scores, mask):
        scores = scores + mask

        self.attn = torch.softmax(scores, dim=-1)
        context_layer = torch.matmul(self.attn, value)  # (batch, head, time1, d_k)

        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(new_context_layer_shape)
        return self.linear_out(context_layer)  # (batch, time1, d_model)


"""
https://www.acmicpc.net/problem/14267
"""
import sys
sys.setrecursionlimit(10**5)

def dfs_with_weigth_accumulation(T, D, P, i=1, a_w=0):
    new_weight = P[i] if i in P else 0
    D[i] = a_w + new_weight
    # print('In dfs_with_weigth_accumulation, D : {}'.format(D))
    for child in T[i]:
        dfs_with_weigth_accumulation(T, D, P, child, a_w+new_weight)

if __name__ == '__main__':
    N, M = map(int, input().split())
    tree_list = [[] for _ in range(N+1)]
    dp = [0] * (N+1)
    employee_num = 1
    for boss in map(int, input().split()):
        # print('boss : {}, employee_num : {}'.format(boss, employee_num))
        if employee_num > 1:
            tree_list[boss].append(employee_num)
        employee_num += 1
    # print('tree_list : {}'.format(tree_list))

    praise_record = {}
    for _ in range(M):
        praised, weight = map(int, input().split())
        if praised not in praise_record:
            praise_record[praised] = weight
        else:
            praise_record[praised] += weight

    dfs_with_weigth_accumulation(tree_list, dp, praise_record)
    # dp.pop(0)
    # print(*dp, sep=" ")
    for i in range(N):
        print(dp[i+1], end=" ")


from pathlib import Path

import pandas as pd
from google.cloud import bigquery
from prefect import flow, task
from prefect.blocks.system import JSON
from prefect.tasks import exponential_backoff
from prefect_gcp import GcpCredentials
from prefect_gcp.cloud_storage import GcsBucket

@flow(log_prints=True)
def load_bigquery(gcs_file_paths):
    path_list = extract_from_gcs(gcs_file_paths=gcs_file_paths)
    gcs_data_all = transform(path_list)
    upload_gbq(gcs_data_all)

@task(
    retries=3,
    retry_delay_seconds=exponential_backoff(backoff_factor=10),
    retry_jitter_factor=0.5,
)
def extract_from_gcs(gcs_file_paths: Path):
    """Download data from gcs"""
    gcs_block = GcsBucket.load("gcp-bucket-block")
    path_list = []

    for gcs_path in gcs_file_paths:
        gcs_block.get_directory(from_path=gcs_path, local_path=f"data-gcs/")
        path_list.append(Path(f"data-gcs/{gcs_path}"))
    return path_list

@task()
def transform(path_list):
    li = []
    for path in path_list:
        df = pd.read_csv(path, index_col=None, header=0)
        li.append(df)
    frame = pd.concat(li, axis=0, ignore_index=True)
    frame.to_csv("data-gcs/data-all.csv", index=False)
    # row.to_frame().T.to_csv(file_path, mode="a", header=not file_path.exists(), index=False)
    return Path("data-gcs/data-all.csv")

@task()
def upload_gbq(gcs_data_all):
    # Getting required config from json block
    json_block = JSON.load("json-config")
    dataset_id = json_block.value["dataset_id"]
    table_id = json_block.value["table_id"]

    gcp_credentials_block = GcpCredentials.load("gcp-credential-block")
    credentials = gcp_credentials_block.get_credentials_from_service_account()

    # setting google client
    client = bigquery.Client(credentials=credentials, project=credentials.project_id)
    dataset = client.dataset(dataset_id)
    table = dataset.table(table_id)

    job_config = bigquery.LoadJobConfig(
        source_format=bigquery.SourceFormat.CSV,
        autodetect=True,
    )

    with open(gcs_data_all.resolve(), "rb") as file:
        load_job = client.load_table_from_file(
            file,
            table,
            job_config=job_config,  # omit schema parameter
        )
    load_job.result()


import cv2 as cv
capture = cv.VideoCapture(0)

while True:
    isTrue, img = capture.read()
    cv.imshow("video", img)
    if cv.waitKey(20) & 0xFF == ord('d'):
        break

cv.imwrite("rayon.png", img)
capture.release
cv.destroyAllWindows()


# keywords are words where the Pc understands or something
name = input("what is your name: ")
print(f"hello {name}")
age = int(input("what is your age: "))  # casting to make input into an int
anotherage = 20
if age >= 18:  # if else computation

    print("please wait a moment while we create your ID")
else:
    # dif = 18 - age
    print(f"you are not old enough comeback in {18 - age} years")
    # pass #simply leaves the condtion